imap-send: add support for IPv6
[git/mingw.git] / git-svn.perl
bloba70c7d7b2cc1e47d5293e1bd45e11d398e48c3f1
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';
457 my @refs;
458 my ($url, $rev, $uuid, $gs) = working_head_info($head, \@refs);
459 unless ($gs) {
460 die "Unable to determine upstream SVN information from ",
461 "$head history.\nPerhaps the repository is empty.";
464 if (defined $_commit_url) {
465 $url = $_commit_url;
466 } else {
467 $url = eval { command_oneline('config', '--get',
468 "svn-remote.$gs->{repo_id}.commiturl") };
469 if (!$url) {
470 $url = $gs->full_url
474 my $last_rev = $_revision if defined $_revision;
475 if ($url) {
476 print "Committing to $url ...\n";
478 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
479 if ($_no_rebase && scalar(@$linear_refs) > 1) {
480 warn "Attempting to commit more than one change while ",
481 "--no-rebase is enabled.\n",
482 "If these changes depend on each other, re-running ",
483 "without --no-rebase may be required."
485 my $expect_url = $url;
486 Git::SVN::remove_username($expect_url);
487 while (1) {
488 my $d = shift @$linear_refs or last;
489 unless (defined $last_rev) {
490 (undef, $last_rev, undef) = cmt_metadata("$d~1");
491 unless (defined $last_rev) {
492 fatal "Unable to extract revision information ",
493 "from commit $d~1";
496 if ($_dry_run) {
497 print "diff-tree $d~1 $d\n";
498 } else {
499 my $cmt_rev;
500 my %ed_opts = ( r => $last_rev,
501 log => get_commit_entry($d)->{log},
502 ra => Git::SVN::Ra->new($url),
503 config => SVN::Core::config_get_config(
504 $Git::SVN::Ra::config_dir
506 tree_a => "$d~1",
507 tree_b => $d,
508 editor_cb => sub {
509 print "Committed r$_[0]\n";
510 $cmt_rev = $_[0];
512 svn_path => '');
513 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
514 print "No changes\n$d~1 == $d\n";
515 } elsif ($parents->{$d} && @{$parents->{$d}}) {
516 $gs->{inject_parents_dcommit}->{$cmt_rev} =
517 $parents->{$d};
519 $_fetch_all ? $gs->fetch_all : $gs->fetch;
520 $last_rev = $cmt_rev;
521 next if $_no_rebase;
523 # we always want to rebase against the current HEAD,
524 # not any head that was passed to us
525 my @diff = command('diff-tree', $d,
526 $gs->refname, '--');
527 my @finish;
528 if (@diff) {
529 @finish = rebase_cmd();
530 print STDERR "W: $d and ", $gs->refname,
531 " differ, using @finish:\n",
532 join("\n", @diff), "\n";
533 } else {
534 print "No changes between current HEAD and ",
535 $gs->refname,
536 "\nResetting to the latest ",
537 $gs->refname, "\n";
538 @finish = qw/reset --mixed/;
540 command_noisy(@finish, $gs->refname);
541 if (@diff) {
542 @refs = ();
543 my ($url_, $rev_, $uuid_, $gs_) =
544 working_head_info($head, \@refs);
545 my ($linear_refs_, $parents_) =
546 linearize_history($gs_, \@refs);
547 if (scalar(@$linear_refs) !=
548 scalar(@$linear_refs_)) {
549 fatal "# of revisions changed ",
550 "\nbefore:\n",
551 join("\n", @$linear_refs),
552 "\n\nafter:\n",
553 join("\n", @$linear_refs_), "\n",
554 'If you are attempting to commit ',
555 "merges, try running:\n\t",
556 'git rebase --interactive',
557 '--preserve-merges ',
558 $gs->refname,
559 "\nBefore dcommitting";
561 if ($url_ ne $expect_url) {
562 fatal "URL mismatch after rebase: ",
563 "$url_ != $expect_url";
565 if ($uuid_ ne $uuid) {
566 fatal "uuid mismatch after rebase: ",
567 "$uuid_ != $uuid";
569 # remap parents
570 my (%p, @l, $i);
571 for ($i = 0; $i < scalar @$linear_refs; $i++) {
572 my $new = $linear_refs_->[$i] or next;
573 $p{$new} =
574 $parents->{$linear_refs->[$i]};
575 push @l, $new;
577 $parents = \%p;
578 $linear_refs = \@l;
582 unlink $gs->{index};
585 sub cmd_branch {
586 my ($branch_name, $head) = @_;
588 unless (defined $branch_name && length $branch_name) {
589 die(($_tag ? "tag" : "branch") . " name required\n");
591 $head ||= 'HEAD';
593 my ($src, $rev, undef, $gs) = working_head_info($head);
595 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
596 my $glob = $remote->{ $_tag ? 'tags' : 'branches' };
597 my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
598 my $dst = join '/', $remote->{url}, $lft, $branch_name, ($rgt || ());
600 my $ctx = SVN::Client->new(
601 auth => Git::SVN::Ra::_auth_providers(),
602 log_msg => sub {
603 ${ $_[0] } = defined $_message
604 ? $_message
605 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
606 . $branch_name;
610 eval {
611 $ctx->ls($dst, 'HEAD', 0);
612 } and die "branch ${branch_name} already exists\n";
614 print "Copying ${src} at r${rev} to ${dst}...\n";
615 $ctx->copy($src, $rev, $dst)
616 unless $_dry_run;
618 $gs->fetch_all;
621 sub cmd_find_rev {
622 my $revision_or_hash = shift or die "SVN or git revision required ",
623 "as a command-line argument\n";
624 my $result;
625 if ($revision_or_hash =~ /^r\d+$/) {
626 my $head = shift;
627 $head ||= 'HEAD';
628 my @refs;
629 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
630 unless ($gs) {
631 die "Unable to determine upstream SVN information from ",
632 "$head history\n";
634 my $desired_revision = substr($revision_or_hash, 1);
635 $result = $gs->rev_map_get($desired_revision, $uuid);
636 } else {
637 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
638 $result = $rev;
640 print "$result\n" if $result;
643 sub cmd_rebase {
644 command_noisy(qw/update-index --refresh/);
645 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
646 unless ($gs) {
647 die "Unable to determine upstream SVN information from ",
648 "working tree history\n";
650 if ($_dry_run) {
651 print "Remote Branch: " . $gs->refname . "\n";
652 print "SVN URL: " . $url . "\n";
653 return;
655 if (command(qw/diff-index HEAD --/)) {
656 print STDERR "Cannot rebase with uncommited changes:\n";
657 command_noisy('status');
658 exit 1;
660 unless ($_local) {
661 # rebase will checkout for us, so no need to do it explicitly
662 $_no_checkout = 'true';
663 $_fetch_all ? $gs->fetch_all : $gs->fetch;
665 command_noisy(rebase_cmd(), $gs->refname);
668 sub cmd_show_ignore {
669 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
670 $gs ||= Git::SVN->new;
671 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
672 $gs->prop_walk($gs->{path}, $r, sub {
673 my ($gs, $path, $props) = @_;
674 print STDOUT "\n# $path\n";
675 my $s = $props->{'svn:ignore'} or return;
676 $s =~ s/[\r\n]+/\n/g;
677 chomp $s;
678 $s =~ s#^#$path#gm;
679 print STDOUT "$s\n";
683 sub cmd_show_externals {
684 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
685 $gs ||= Git::SVN->new;
686 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
687 $gs->prop_walk($gs->{path}, $r, sub {
688 my ($gs, $path, $props) = @_;
689 print STDOUT "\n# $path\n";
690 my $s = $props->{'svn:externals'} or return;
691 $s =~ s/[\r\n]+/\n/g;
692 chomp $s;
693 $s =~ s#^#$path#gm;
694 print STDOUT "$s\n";
698 sub cmd_create_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 # $path is of the form /path/to/dir/
705 $path = '.' . $path;
706 # SVN can have attributes on empty directories,
707 # which git won't track
708 mkpath([$path]) unless -d $path;
709 my $ignore = $path . '.gitignore';
710 my $s = $props->{'svn:ignore'} or return;
711 open(GITIGNORE, '>', $ignore)
712 or fatal("Failed to open `$ignore' for writing: $!");
713 $s =~ s/[\r\n]+/\n/g;
714 chomp $s;
715 # Prefix all patterns so that the ignore doesn't apply
716 # to sub-directories.
717 $s =~ s#^#/#gm;
718 print GITIGNORE "$s\n";
719 close(GITIGNORE)
720 or fatal("Failed to close `$ignore': $!");
721 command_noisy('add', '-f', $ignore);
725 sub canonicalize_path {
726 my ($path) = @_;
727 my $dot_slash_added = 0;
728 if (substr($path, 0, 1) ne "/") {
729 $path = "./" . $path;
730 $dot_slash_added = 1;
732 # File::Spec->canonpath doesn't collapse x/../y into y (for a
733 # good reason), so let's do this manually.
734 $path =~ s#/+#/#g;
735 $path =~ s#/\.(?:/|$)#/#g;
736 $path =~ s#/[^/]+/\.\.##g;
737 $path =~ s#/$##g;
738 $path =~ s#^\./## if $dot_slash_added;
739 $path =~ s#^/##;
740 $path =~ s#^\.$##;
741 return $path;
744 # get_svnprops(PATH)
745 # ------------------
746 # Helper for cmd_propget and cmd_proplist below.
747 sub get_svnprops {
748 my $path = shift;
749 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
750 $gs ||= Git::SVN->new;
752 # prefix THE PATH by the sub-directory from which the user
753 # invoked us.
754 $path = $cmd_dir_prefix . $path;
755 fatal("No such file or directory: $path") unless -e $path;
756 my $is_dir = -d $path ? 1 : 0;
757 $path = $gs->{path} . '/' . $path;
759 # canonicalize the path (otherwise libsvn will abort or fail to
760 # find the file)
761 $path = canonicalize_path($path);
763 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
764 my $props;
765 if ($is_dir) {
766 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
768 else {
769 (undef, $props) = $gs->ra->get_file($path, $r, undef);
771 return $props;
774 # cmd_propget (PROP, PATH)
775 # ------------------------
776 # Print the SVN property PROP for PATH.
777 sub cmd_propget {
778 my ($prop, $path) = @_;
779 $path = '.' if not defined $path;
780 usage(1) if not defined $prop;
781 my $props = get_svnprops($path);
782 if (not defined $props->{$prop}) {
783 fatal("`$path' does not have a `$prop' SVN property.");
785 print $props->{$prop} . "\n";
788 # cmd_proplist (PATH)
789 # -------------------
790 # Print the list of SVN properties for PATH.
791 sub cmd_proplist {
792 my $path = shift;
793 $path = '.' if not defined $path;
794 my $props = get_svnprops($path);
795 print "Properties on '$path':\n";
796 foreach (sort keys %{$props}) {
797 print " $_\n";
801 sub cmd_multi_init {
802 my $url = shift;
803 unless (defined $_trunk || defined $_branches || defined $_tags) {
804 usage(1);
807 # there are currently some bugs that prevent multi-init/multi-fetch
808 # setups from working well without this.
809 $Git::SVN::_minimize_url = 1;
811 $_prefix = '' unless defined $_prefix;
812 if (defined $url) {
813 $url =~ s#/+$##;
814 init_subdir(@_);
816 do_git_init_db();
817 if (defined $_trunk) {
818 my $trunk_ref = $_prefix . 'trunk';
819 # try both old-style and new-style lookups:
820 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
821 unless ($gs_trunk) {
822 my ($trunk_url, $trunk_path) =
823 complete_svn_url($url, $_trunk);
824 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
825 undef, $trunk_ref);
828 return unless defined $_branches || defined $_tags;
829 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
830 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
831 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
834 sub cmd_multi_fetch {
835 my $remotes = Git::SVN::read_all_remotes();
836 foreach my $repo_id (sort keys %$remotes) {
837 if ($remotes->{$repo_id}->{url}) {
838 Git::SVN::fetch_all($repo_id, $remotes);
843 # this command is special because it requires no metadata
844 sub cmd_commit_diff {
845 my ($ta, $tb, $url) = @_;
846 my $usage = "Usage: $0 commit-diff -r<revision> ".
847 "<tree-ish> <tree-ish> [<URL>]";
848 fatal($usage) if (!defined $ta || !defined $tb);
849 my $svn_path = '';
850 if (!defined $url) {
851 my $gs = eval { Git::SVN->new };
852 if (!$gs) {
853 fatal("Needed URL or usable git-svn --id in ",
854 "the command-line\n", $usage);
856 $url = $gs->{url};
857 $svn_path = $gs->{path};
859 unless (defined $_revision) {
860 fatal("-r|--revision is a required argument\n", $usage);
862 if (defined $_message && defined $_file) {
863 fatal("Both --message/-m and --file/-F specified ",
864 "for the commit message.\n",
865 "I have no idea what you mean");
867 if (defined $_file) {
868 $_message = file_to_s($_file);
869 } else {
870 $_message ||= get_commit_entry($tb)->{log};
872 my $ra ||= Git::SVN::Ra->new($url);
873 my $r = $_revision;
874 if ($r eq 'HEAD') {
875 $r = $ra->get_latest_revnum;
876 } elsif ($r !~ /^\d+$/) {
877 die "revision argument: $r not understood by git-svn\n";
879 my %ed_opts = ( r => $r,
880 log => $_message,
881 ra => $ra,
882 tree_a => $ta,
883 tree_b => $tb,
884 editor_cb => sub { print "Committed r$_[0]\n" },
885 svn_path => $svn_path );
886 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
887 print "No changes\n$ta == $tb\n";
891 sub escape_uri_only {
892 my ($uri) = @_;
893 my @tmp;
894 foreach (split m{/}, $uri) {
895 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
896 push @tmp, $_;
898 join('/', @tmp);
901 sub escape_url {
902 my ($url) = @_;
903 if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
904 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
905 $url = "$scheme://$domain$uri";
907 $url;
910 sub cmd_info {
911 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
912 my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
913 if (exists $_[1]) {
914 die "Too many arguments specified\n";
917 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
919 if (!$file_type && !$diff_status) {
920 print STDERR "svn: '$path' is not under version control\n";
921 exit 1;
924 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
925 unless ($gs) {
926 die "Unable to determine upstream SVN information from ",
927 "working tree history\n";
930 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
931 $path = "." if $path eq "";
933 my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
935 if ($_url) {
936 print escape_url($full_url), "\n";
937 return;
940 my $result = "Path: $path\n";
941 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
942 $result .= "URL: " . escape_url($full_url) . "\n";
944 eval {
945 my $repos_root = $gs->repos_root;
946 Git::SVN::remove_username($repos_root);
947 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
949 if ($@) {
950 $result .= "Repository Root: (offline)\n";
952 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
953 ($SVN::Core::VERSION le '1.5.4' || $file_type ne "dir");
954 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
956 $result .= "Node Kind: " .
957 ($file_type eq "dir" ? "directory" : "file") . "\n";
959 my $schedule = $diff_status eq "A"
960 ? "add"
961 : ($diff_status eq "D" ? "delete" : "normal");
962 $result .= "Schedule: $schedule\n";
964 if ($diff_status eq "A") {
965 print $result, "\n";
966 return;
969 my ($lc_author, $lc_rev, $lc_date_utc);
970 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
971 my $log = command_output_pipe(@args);
972 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
973 while (<$log>) {
974 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
975 $lc_author = $1;
976 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
977 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
978 (undef, $lc_rev, undef) = ::extract_metadata($1);
981 close $log;
983 Git::SVN::Log::set_local_timezone();
985 $result .= "Last Changed Author: $lc_author\n";
986 $result .= "Last Changed Rev: $lc_rev\n";
987 $result .= "Last Changed Date: " .
988 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
990 if ($file_type ne "dir") {
991 my $text_last_updated_date =
992 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
993 $result .=
994 "Text Last Updated: " .
995 Git::SVN::Log::format_svn_date($text_last_updated_date) .
996 "\n";
997 my $checksum;
998 if ($diff_status eq "D") {
999 my ($fh, $ctx) =
1000 command_output_pipe(qw(cat-file blob), "HEAD:$path");
1001 if ($file_type eq "link") {
1002 my $file_name = <$fh>;
1003 $checksum = md5sum("link $file_name");
1004 } else {
1005 $checksum = md5sum($fh);
1007 command_close_pipe($fh, $ctx);
1008 } elsif ($file_type eq "link") {
1009 my $file_name =
1010 command(qw(cat-file blob), "HEAD:$path");
1011 $checksum =
1012 md5sum("link " . $file_name);
1013 } else {
1014 open FILE, "<", $path or die $!;
1015 $checksum = md5sum(\*FILE);
1016 close FILE or die $!;
1018 $result .= "Checksum: " . $checksum . "\n";
1021 print $result, "\n";
1024 ########################### utility functions #########################
1026 sub rebase_cmd {
1027 my @cmd = qw/rebase/;
1028 push @cmd, '-v' if $_verbose;
1029 push @cmd, qw/--merge/ if $_merge;
1030 push @cmd, "--strategy=$_strategy" if $_strategy;
1031 @cmd;
1034 sub post_fetch_checkout {
1035 return if $_no_checkout;
1036 my $gs = $Git::SVN::_head or return;
1037 return if verify_ref('refs/heads/master^0');
1039 my $valid_head = verify_ref('HEAD^0');
1040 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1041 return if ($valid_head || !verify_ref('HEAD^0'));
1043 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1044 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1045 return if -f $index;
1047 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1048 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1049 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1050 print STDERR "Checked out HEAD:\n ",
1051 $gs->full_url, " r", $gs->last_rev, "\n";
1054 sub complete_svn_url {
1055 my ($url, $path) = @_;
1056 $path =~ s#/+$##;
1057 if ($path !~ m#^[a-z\+]+://#) {
1058 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1059 fatal("E: '$path' is not a complete URL ",
1060 "and a separate URL is not specified");
1062 return ($url, $path);
1064 return ($path, '');
1067 sub complete_url_ls_init {
1068 my ($ra, $repo_path, $switch, $pfx) = @_;
1069 unless ($repo_path) {
1070 print STDERR "W: $switch not specified\n";
1071 return;
1073 $repo_path =~ s#/+$##;
1074 if ($repo_path =~ m#^[a-z\+]+://#) {
1075 $ra = Git::SVN::Ra->new($repo_path);
1076 $repo_path = '';
1077 } else {
1078 $repo_path =~ s#^/+##;
1079 unless ($ra) {
1080 fatal("E: '$repo_path' is not a complete URL ",
1081 "and a separate URL is not specified");
1084 my $url = $ra->{url};
1085 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1086 my $k = "svn-remote.$gs->{repo_id}.url";
1087 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1088 if ($orig_url && ($orig_url ne $gs->{url})) {
1089 die "$k already set: $orig_url\n",
1090 "wanted to set to: $gs->{url}\n";
1092 command_oneline('config', $k, $gs->{url}) unless $orig_url;
1093 my $remote_path = "$ra->{svn_path}/$repo_path";
1094 $remote_path =~ s#/+#/#g;
1095 $remote_path =~ s#^/##g;
1096 $remote_path .= "/*" if $remote_path !~ /\*/;
1097 my ($n) = ($switch =~ /^--(\w+)/);
1098 if (length $pfx && $pfx !~ m#/$#) {
1099 die "--prefix='$pfx' must have a trailing slash '/'\n";
1101 command_noisy('config',
1102 "svn-remote.$gs->{repo_id}.$n",
1103 "$remote_path:refs/remotes/$pfx*" .
1104 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1107 sub verify_ref {
1108 my ($ref) = @_;
1109 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1110 { STDERR => 0 }); };
1113 sub get_tree_from_treeish {
1114 my ($treeish) = @_;
1115 # $treeish can be a symbolic ref, too:
1116 my $type = command_oneline(qw/cat-file -t/, $treeish);
1117 my $expected;
1118 while ($type eq 'tag') {
1119 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1121 if ($type eq 'commit') {
1122 $expected = (grep /^tree /, command(qw/cat-file commit/,
1123 $treeish))[0];
1124 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1125 die "Unable to get tree from $treeish\n" unless $expected;
1126 } elsif ($type eq 'tree') {
1127 $expected = $treeish;
1128 } else {
1129 die "$treeish is a $type, expected tree, tag or commit\n";
1131 return $expected;
1134 sub get_commit_entry {
1135 my ($treeish) = shift;
1136 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1137 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1138 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1139 open my $log_fh, '>', $commit_editmsg or croak $!;
1141 my $type = command_oneline(qw/cat-file -t/, $treeish);
1142 if ($type eq 'commit' || $type eq 'tag') {
1143 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1144 $type, $treeish);
1145 my $in_msg = 0;
1146 my $author;
1147 my $saw_from = 0;
1148 my $msgbuf = "";
1149 while (<$msg_fh>) {
1150 if (!$in_msg) {
1151 $in_msg = 1 if (/^\s*$/);
1152 $author = $1 if (/^author (.*>)/);
1153 } elsif (/^git-svn-id: /) {
1154 # skip this for now, we regenerate the
1155 # correct one on re-fetch anyways
1156 # TODO: set *:merge properties or like...
1157 } else {
1158 if (/^From:/ || /^Signed-off-by:/) {
1159 $saw_from = 1;
1161 $msgbuf .= $_;
1164 $msgbuf =~ s/\s+$//s;
1165 if ($Git::SVN::_add_author_from && defined($author)
1166 && !$saw_from) {
1167 $msgbuf .= "\n\nFrom: $author";
1169 print $log_fh $msgbuf or croak $!;
1170 command_close_pipe($msg_fh, $ctx);
1172 close $log_fh or croak $!;
1174 if ($_edit || ($type eq 'tree')) {
1175 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1176 # TODO: strip out spaces, comments, like git-commit.sh
1177 system($editor, $commit_editmsg);
1179 rename $commit_editmsg, $commit_msg or croak $!;
1181 # SVN requires messages to be UTF-8 when entering the repo
1182 local $/;
1183 open $log_fh, '<', $commit_msg or croak $!;
1184 binmode $log_fh;
1185 chomp($log_entry{log} = <$log_fh>);
1187 if (my $enc = Git::config('i18n.commitencoding')) {
1188 require Encode;
1189 Encode::from_to($log_entry{log}, $enc, 'UTF-8');
1191 close $log_fh or croak $!;
1193 unlink $commit_msg;
1194 \%log_entry;
1197 sub s_to_file {
1198 my ($str, $file, $mode) = @_;
1199 open my $fd,'>',$file or croak $!;
1200 print $fd $str,"\n" or croak $!;
1201 close $fd or croak $!;
1202 chmod ($mode &~ umask, $file) if (defined $mode);
1205 sub file_to_s {
1206 my $file = shift;
1207 open my $fd,'<',$file or croak "$!: file: $file\n";
1208 local $/;
1209 my $ret = <$fd>;
1210 close $fd or croak $!;
1211 $ret =~ s/\s*$//s;
1212 return $ret;
1215 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1216 sub load_authors {
1217 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1218 my $log = $cmd eq 'log';
1219 while (<$authors>) {
1220 chomp;
1221 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1222 my ($user, $name, $email) = ($1, $2, $3);
1223 if ($log) {
1224 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1225 } else {
1226 $users{$user} = [$name, $email];
1229 close $authors or croak $!;
1232 # convert GetOpt::Long specs for use by git-config
1233 sub read_repo_config {
1234 return unless -d $ENV{GIT_DIR};
1235 my $opts = shift;
1236 my @config_only;
1237 foreach my $o (keys %$opts) {
1238 # if we have mixedCase and a long option-only, then
1239 # it's a config-only variable that we don't need for
1240 # the command-line.
1241 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1242 my $v = $opts->{$o};
1243 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1244 $key =~ s/-//g;
1245 my $arg = 'git config';
1246 $arg .= ' --int' if ($o =~ /[:=]i$/);
1247 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1248 if (ref $v eq 'ARRAY') {
1249 chomp(my @tmp = `$arg --get-all svn.$key`);
1250 @$v = @tmp if @tmp;
1251 } else {
1252 chomp(my $tmp = `$arg --get svn.$key`);
1253 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1254 $$v = $tmp;
1258 delete @$opts{@config_only} if @config_only;
1261 sub extract_metadata {
1262 my $id = shift or return (undef, undef, undef);
1263 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1264 \s([a-f\d\-]+)$/x);
1265 if (!defined $rev || !$uuid || !$url) {
1266 # some of the original repositories I made had
1267 # identifiers like this:
1268 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
1270 return ($url, $rev, $uuid);
1273 sub cmt_metadata {
1274 return extract_metadata((grep(/^git-svn-id: /,
1275 command(qw/cat-file commit/, shift)))[-1]);
1278 sub cmt_sha2rev_batch {
1279 my %s2r;
1280 my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1281 my $list = shift;
1283 foreach my $sha (@{$list}) {
1284 my $first = 1;
1285 my $size = 0;
1286 print $out $sha, "\n";
1288 while (my $line = <$in>) {
1289 if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1290 last;
1291 } elsif ($first &&
1292 $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1293 $first = 0;
1294 $size = $1;
1295 next;
1296 } elsif ($line =~ /^(git-svn-id: )/) {
1297 my (undef, $rev, undef) =
1298 extract_metadata($line);
1299 $s2r{$sha} = $rev;
1302 $size -= length($line);
1303 last if ($size == 0);
1307 command_close_bidi_pipe($pid, $in, $out, $ctx);
1309 return \%s2r;
1312 sub working_head_info {
1313 my ($head, $refs) = @_;
1314 my @args = ('log', '--no-color', '--first-parent', '--pretty=medium');
1315 my ($fh, $ctx) = command_output_pipe(@args, $head);
1316 my $hash;
1317 my %max;
1318 while (<$fh>) {
1319 if ( m{^commit ($::sha1)$} ) {
1320 unshift @$refs, $hash if $hash and $refs;
1321 $hash = $1;
1322 next;
1324 next unless s{^\s*(git-svn-id:)}{$1};
1325 my ($url, $rev, $uuid) = extract_metadata($_);
1326 if (defined $url && defined $rev) {
1327 next if $max{$url} and $max{$url} < $rev;
1328 if (my $gs = Git::SVN->find_by_url($url)) {
1329 my $c = $gs->rev_map_get($rev, $uuid);
1330 if ($c && $c eq $hash) {
1331 close $fh; # break the pipe
1332 return ($url, $rev, $uuid, $gs);
1333 } else {
1334 $max{$url} ||= $gs->rev_map_max;
1339 command_close_pipe($fh, $ctx);
1340 (undef, undef, undef, undef);
1343 sub read_commit_parents {
1344 my ($parents, $c) = @_;
1345 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1346 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1347 @{$parents->{$c}} = split(/ /, $p);
1350 sub linearize_history {
1351 my ($gs, $refs) = @_;
1352 my %parents;
1353 foreach my $c (@$refs) {
1354 read_commit_parents(\%parents, $c);
1357 my @linear_refs;
1358 my %skip = ();
1359 my $last_svn_commit = $gs->last_commit;
1360 foreach my $c (reverse @$refs) {
1361 next if $c eq $last_svn_commit;
1362 last if $skip{$c};
1364 unshift @linear_refs, $c;
1365 $skip{$c} = 1;
1367 # we only want the first parent to diff against for linear
1368 # history, we save the rest to inject when we finalize the
1369 # svn commit
1370 my $fp_a = verify_ref("$c~1");
1371 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1372 if (!$fp_a || !$fp_b) {
1373 die "Commit $c\n",
1374 "has no parent commit, and therefore ",
1375 "nothing to diff against.\n",
1376 "You should be working from a repository ",
1377 "originally created by git-svn\n";
1379 if ($fp_a ne $fp_b) {
1380 die "$c~1 = $fp_a, however parsing commit $c ",
1381 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1384 foreach my $p (@{$parents{$c}}) {
1385 $skip{$p} = 1;
1388 (\@linear_refs, \%parents);
1391 sub find_file_type_and_diff_status {
1392 my ($path) = @_;
1393 return ('dir', '') if $path eq '';
1395 my $diff_output =
1396 command_oneline(qw(diff --cached --name-status --), $path) || "";
1397 my $diff_status = (split(' ', $diff_output))[0] || "";
1399 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1401 return (undef, undef) if !$diff_status && !$ls_tree;
1403 if ($diff_status eq "A") {
1404 return ("link", $diff_status) if -l $path;
1405 return ("dir", $diff_status) if -d $path;
1406 return ("file", $diff_status);
1409 my $mode = (split(' ', $ls_tree))[0] || "";
1411 return ("link", $diff_status) if $mode eq "120000";
1412 return ("dir", $diff_status) if $mode eq "040000";
1413 return ("file", $diff_status);
1416 sub md5sum {
1417 my $arg = shift;
1418 my $ref = ref $arg;
1419 my $md5 = Digest::MD5->new();
1420 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
1421 $md5->addfile($arg) or croak $!;
1422 } elsif ($ref eq 'SCALAR') {
1423 $md5->add($$arg) or croak $!;
1424 } elsif (!$ref) {
1425 $md5->add($arg) or croak $!;
1426 } else {
1427 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1429 return $md5->hexdigest();
1432 package Git::SVN;
1433 use strict;
1434 use warnings;
1435 use Fcntl qw/:DEFAULT :seek/;
1436 use constant rev_map_fmt => 'NH40';
1437 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1438 $_repack $_repack_flags $_use_svm_props $_head
1439 $_use_svnsync_props $no_reuse_existing $_minimize_url
1440 $_use_log_author $_add_author_from $_localtime/;
1441 use Carp qw/croak/;
1442 use File::Path qw/mkpath/;
1443 use File::Copy qw/copy/;
1444 use IPC::Open3;
1446 my ($_gc_nr, $_gc_period);
1448 # properties that we do not log:
1449 my %SKIP_PROP;
1450 BEGIN {
1451 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1452 svn:special svn:executable
1453 svn:entry:committed-rev
1454 svn:entry:last-author
1455 svn:entry:uuid
1456 svn:entry:committed-date/;
1458 # some options are read globally, but can be overridden locally
1459 # per [svn-remote "..."] section. Command-line options will *NOT*
1460 # override options set in an [svn-remote "..."] section
1461 no strict 'refs';
1462 for my $option (qw/follow_parent no_metadata use_svm_props
1463 use_svnsync_props/) {
1464 my $key = $option;
1465 $key =~ tr/_//d;
1466 my $prop = "-$option";
1467 *$option = sub {
1468 my ($self) = @_;
1469 return $self->{$prop} if exists $self->{$prop};
1470 my $k = "svn-remote.$self->{repo_id}.$key";
1471 eval { command_oneline(qw/config --get/, $k) };
1472 if ($@) {
1473 $self->{$prop} = ${"Git::SVN::_$option"};
1474 } else {
1475 my $v = command_oneline(qw/config --bool/,$k);
1476 $self->{$prop} = $v eq 'false' ? 0 : 1;
1478 return $self->{$prop};
1484 my (%LOCKFILES, %INDEX_FILES);
1485 END {
1486 unlink keys %LOCKFILES if %LOCKFILES;
1487 unlink keys %INDEX_FILES if %INDEX_FILES;
1490 sub resolve_local_globs {
1491 my ($url, $fetch, $glob_spec) = @_;
1492 return unless defined $glob_spec;
1493 my $ref = $glob_spec->{ref};
1494 my $path = $glob_spec->{path};
1495 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
1496 next unless m#^refs/remotes/$ref->{regex}$#;
1497 my $p = $1;
1498 my $pathname = desanitize_refname($path->full_path($p));
1499 my $refname = desanitize_refname($ref->full_path($p));
1500 if (my $existing = $fetch->{$pathname}) {
1501 if ($existing ne $refname) {
1502 die "Refspec conflict:\n",
1503 "existing: refs/remotes/$existing\n",
1504 " globbed: refs/remotes/$refname\n";
1506 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
1507 $u =~ s!^\Q$url\E(/|$)!! or die
1508 "refs/remotes/$refname: '$url' not found in '$u'\n";
1509 if ($pathname ne $u) {
1510 warn "W: Refspec glob conflict ",
1511 "(ref: refs/remotes/$refname):\n",
1512 "expected path: $pathname\n",
1513 " real path: $u\n",
1514 "Continuing ahead with $u\n";
1515 next;
1517 } else {
1518 $fetch->{$pathname} = $refname;
1523 sub parse_revision_argument {
1524 my ($base, $head) = @_;
1525 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1526 return ($base, $head);
1528 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1529 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1530 return ($head, $head) if ($::_revision eq 'HEAD');
1531 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1532 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1533 die "revision argument: $::_revision not understood by git-svn\n";
1536 sub fetch_all {
1537 my ($repo_id, $remotes) = @_;
1538 if (ref $repo_id) {
1539 my $gs = $repo_id;
1540 $repo_id = undef;
1541 $repo_id = $gs->{repo_id};
1543 $remotes ||= read_all_remotes();
1544 my $remote = $remotes->{$repo_id} or
1545 die "[svn-remote \"$repo_id\"] unknown\n";
1546 my $fetch = $remote->{fetch};
1547 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1548 my (@gs, @globs);
1549 my $ra = Git::SVN::Ra->new($url);
1550 my $uuid = $ra->get_uuid;
1551 my $head = $ra->get_latest_revnum;
1552 my $base = defined $fetch ? $head : 0;
1554 # read the max revs for wildcard expansion (branches/*, tags/*)
1555 foreach my $t (qw/branches tags/) {
1556 defined $remote->{$t} or next;
1557 push @globs, $remote->{$t};
1558 my $max_rev = eval { tmp_config(qw/--int --get/,
1559 "svn-remote.$repo_id.${t}-maxRev") };
1560 if (defined $max_rev && ($max_rev < $base)) {
1561 $base = $max_rev;
1562 } elsif (!defined $max_rev) {
1563 $base = 0;
1567 if ($fetch) {
1568 foreach my $p (sort keys %$fetch) {
1569 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1570 my $lr = $gs->rev_map_max;
1571 if (defined $lr) {
1572 $base = $lr if ($lr < $base);
1574 push @gs, $gs;
1578 ($base, $head) = parse_revision_argument($base, $head);
1579 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1582 sub read_all_remotes {
1583 my $r = {};
1584 my $use_svm_props = eval { command_oneline(qw/config --bool
1585 svn.useSvmProps/) };
1586 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
1587 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1588 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*(.+)\s*$!) {
1589 my ($remote, $local_ref, $_remote_ref) = ($1, $2, $3);
1590 die("svn-remote.$remote: remote ref '$_remote_ref' "
1591 . "must start with 'refs/remotes/'\n")
1592 unless $_remote_ref =~ m{^refs/remotes/(.+)};
1593 my $remote_ref = $1;
1594 $local_ref =~ s{^/}{};
1595 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1596 $r->{$remote}->{svm} = {} if $use_svm_props;
1597 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
1598 $r->{$1}->{svm} = {};
1599 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1600 $r->{$1}->{url} = $2;
1601 } elsif (m!^(.+)\.(branches|tags)=
1602 (.*):refs/remotes/(.+)\s*$/!x) {
1603 my ($p, $g) = ($3, $4);
1604 my $rs = $r->{$1}->{$2} = {
1605 t => $2,
1606 remote => $1,
1607 path => Git::SVN::GlobSpec->new($p),
1608 ref => Git::SVN::GlobSpec->new($g) };
1609 if (length($rs->{ref}->{right}) != 0) {
1610 die "The '*' glob character must be the last ",
1611 "character of '$g'\n";
1616 map {
1617 if (defined $r->{$_}->{svm}) {
1618 my $svm;
1619 eval {
1620 my $section = "svn-remote.$_";
1621 $svm = {
1622 source => tmp_config('--get',
1623 "$section.svm-source"),
1624 replace => tmp_config('--get',
1625 "$section.svm-replace"),
1628 $r->{$_}->{svm} = $svm;
1630 } keys %$r;
1635 sub init_vars {
1636 $_gc_nr = $_gc_period = 1000;
1637 if (defined $_repack || defined $_repack_flags) {
1638 warn "Repack options are obsolete; they have no effect.\n";
1642 sub verify_remotes_sanity {
1643 return unless -d $ENV{GIT_DIR};
1644 my %seen;
1645 foreach (command(qw/config -l/)) {
1646 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1647 if ($seen{$1}) {
1648 die "Remote ref refs/remote/$1 is tracked by",
1649 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1650 "Please resolve this ambiguity in ",
1651 "your git configuration file before ",
1652 "continuing\n";
1654 $seen{$1} = $_;
1659 sub find_existing_remote {
1660 my ($url, $remotes) = @_;
1661 return undef if $no_reuse_existing;
1662 my $existing;
1663 foreach my $repo_id (keys %$remotes) {
1664 my $u = $remotes->{$repo_id}->{url} or next;
1665 next if $u ne $url;
1666 $existing = $repo_id;
1667 last;
1669 $existing;
1672 sub init_remote_config {
1673 my ($self, $url, $no_write) = @_;
1674 $url =~ s!/+$!!; # strip trailing slash
1675 my $r = read_all_remotes();
1676 my $existing = find_existing_remote($url, $r);
1677 if ($existing) {
1678 unless ($no_write) {
1679 print STDERR "Using existing ",
1680 "[svn-remote \"$existing\"]\n";
1682 $self->{repo_id} = $existing;
1683 } elsif ($_minimize_url) {
1684 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1685 $existing = find_existing_remote($min_url, $r);
1686 if ($existing) {
1687 unless ($no_write) {
1688 print STDERR "Using existing ",
1689 "[svn-remote \"$existing\"]\n";
1691 $self->{repo_id} = $existing;
1693 if ($min_url ne $url) {
1694 unless ($no_write) {
1695 print STDERR "Using higher level of URL: ",
1696 "$url => $min_url\n";
1698 my $old_path = $self->{path};
1699 $self->{path} = $url;
1700 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1701 if (length $old_path) {
1702 $self->{path} .= "/$old_path";
1704 $url = $min_url;
1707 my $orig_url;
1708 if (!$existing) {
1709 # verify that we aren't overwriting anything:
1710 $orig_url = eval {
1711 command_oneline('config', '--get',
1712 "svn-remote.$self->{repo_id}.url")
1714 if ($orig_url && ($orig_url ne $url)) {
1715 die "svn-remote.$self->{repo_id}.url already set: ",
1716 "$orig_url\nwanted to set to: $url\n";
1719 my ($xrepo_id, $xpath) = find_ref($self->refname);
1720 if (defined $xpath) {
1721 die "svn-remote.$xrepo_id.fetch already set to track ",
1722 "$xpath:refs/remotes/", $self->refname, "\n";
1724 unless ($no_write) {
1725 command_noisy('config',
1726 "svn-remote.$self->{repo_id}.url", $url);
1727 $self->{path} =~ s{^/}{};
1728 command_noisy('config', '--add',
1729 "svn-remote.$self->{repo_id}.fetch",
1730 "$self->{path}:".$self->refname);
1732 $self->{url} = $url;
1735 sub find_by_url { # repos_root and, path are optional
1736 my ($class, $full_url, $repos_root, $path) = @_;
1738 return undef unless defined $full_url;
1739 remove_username($full_url);
1740 remove_username($repos_root) if defined $repos_root;
1741 my $remotes = read_all_remotes();
1742 if (defined $full_url && defined $repos_root && !defined $path) {
1743 $path = $full_url;
1744 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1746 foreach my $repo_id (keys %$remotes) {
1747 my $u = $remotes->{$repo_id}->{url} or next;
1748 remove_username($u);
1749 next if defined $repos_root && $repos_root ne $u;
1751 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1752 foreach (qw/branches tags/) {
1753 resolve_local_globs($u, $fetch,
1754 $remotes->{$repo_id}->{$_});
1756 my $p = $path;
1757 my $rwr = rewrite_root({repo_id => $repo_id});
1758 my $svm = $remotes->{$repo_id}->{svm}
1759 if defined $remotes->{$repo_id}->{svm};
1760 unless (defined $p) {
1761 $p = $full_url;
1762 my $z = $u;
1763 my $prefix = '';
1764 if ($rwr) {
1765 $z = $rwr;
1766 remove_username($z);
1767 } elsif (defined $svm) {
1768 $z = $svm->{source};
1769 $prefix = $svm->{replace};
1770 $prefix =~ s#^\Q$u\E(?:/|$)##;
1771 $prefix =~ s#/$##;
1773 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
1775 foreach my $f (keys %$fetch) {
1776 next if $f ne $p;
1777 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1780 undef;
1783 sub init {
1784 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1785 my $self = _new($class, $repo_id, $ref_id, $path);
1786 if (defined $url) {
1787 $self->init_remote_config($url, $no_write);
1789 $self;
1792 sub find_ref {
1793 my ($ref_id) = @_;
1794 foreach (command(qw/config -l/)) {
1795 next unless m!^svn-remote\.(.+)\.fetch=
1796 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1797 my ($repo_id, $path, $ref) = ($1, $2, $3);
1798 if ($ref eq $ref_id) {
1799 $path = '' if ($path =~ m#^\./?#);
1800 return ($repo_id, $path);
1803 (undef, undef, undef);
1806 sub new {
1807 my ($class, $ref_id, $repo_id, $path) = @_;
1808 if (defined $ref_id && !defined $repo_id && !defined $path) {
1809 ($repo_id, $path) = find_ref($ref_id);
1810 if (!defined $repo_id) {
1811 die "Could not find a \"svn-remote.*.fetch\" key ",
1812 "in the repository configuration matching: ",
1813 "refs/remotes/$ref_id\n";
1816 my $self = _new($class, $repo_id, $ref_id, $path);
1817 if (!defined $self->{path} || !length $self->{path}) {
1818 my $fetch = command_oneline('config', '--get',
1819 "svn-remote.$repo_id.fetch",
1820 ":refs/remotes/$ref_id\$") or
1821 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1822 "\":refs/remotes/$ref_id\$\" in config\n";
1823 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1825 $self->{url} = command_oneline('config', '--get',
1826 "svn-remote.$repo_id.url") or
1827 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1828 $self->rebuild;
1829 $self;
1832 sub refname {
1833 my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1835 # It cannot end with a slash /, we'll throw up on this because
1836 # SVN can't have directories with a slash in their name, either:
1837 if ($refname =~ m{/$}) {
1838 die "ref: '$refname' ends with a trailing slash, this is ",
1839 "not permitted by git nor Subversion\n";
1842 # It cannot have ASCII control character space, tilde ~, caret ^,
1843 # colon :, question-mark ?, asterisk *, space, or open bracket [
1844 # anywhere.
1846 # Additionally, % must be escaped because it is used for escaping
1847 # and we want our escaped refname to be reversible
1848 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1850 # no slash-separated component can begin with a dot .
1851 # /.* becomes /%2E*
1852 $refname =~ s{/\.}{/%2E}g;
1854 # It cannot have two consecutive dots .. anywhere
1855 # .. becomes %2E%2E
1856 $refname =~ s{\.\.}{%2E%2E}g;
1858 return $refname;
1861 sub desanitize_refname {
1862 my ($refname) = @_;
1863 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1864 return $refname;
1867 sub svm_uuid {
1868 my ($self) = @_;
1869 return $self->{svm}->{uuid} if $self->svm;
1870 $self->ra;
1871 unless ($self->{svm}) {
1872 die "SVM UUID not cached, and reading remotely failed\n";
1874 $self->{svm}->{uuid};
1877 sub svm {
1878 my ($self) = @_;
1879 return $self->{svm} if $self->{svm};
1880 my $svm;
1881 # see if we have it in our config, first:
1882 eval {
1883 my $section = "svn-remote.$self->{repo_id}";
1884 $svm = {
1885 source => tmp_config('--get', "$section.svm-source"),
1886 uuid => tmp_config('--get', "$section.svm-uuid"),
1887 replace => tmp_config('--get', "$section.svm-replace"),
1890 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1891 $self->{svm} = $svm;
1893 $self->{svm};
1896 sub _set_svm_vars {
1897 my ($self, $ra) = @_;
1898 return $ra if $self->svm;
1900 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1901 "(svm:source, svm:uuid) ",
1902 "from the following URLs:\n" );
1903 sub read_svm_props {
1904 my ($self, $ra, $path, $r) = @_;
1905 my $props = ($ra->get_dir($path, $r))[2];
1906 my $src = $props->{'svm:source'};
1907 my $uuid = $props->{'svm:uuid'};
1908 return undef if (!$src || !$uuid);
1910 chomp($src, $uuid);
1912 $uuid =~ m{^[0-9a-f\-]{30,}$}
1913 or die "doesn't look right - svm:uuid is '$uuid'\n";
1915 # the '!' is used to mark the repos_root!/relative/path
1916 $src =~ s{/?!/?}{/};
1917 $src =~ s{/+$}{}; # no trailing slashes please
1918 # username is of no interest
1919 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1921 my $replace = $ra->{url};
1922 $replace .= "/$path" if length $path;
1924 my $section = "svn-remote.$self->{repo_id}";
1925 tmp_config("$section.svm-source", $src);
1926 tmp_config("$section.svm-replace", $replace);
1927 tmp_config("$section.svm-uuid", $uuid);
1928 $self->{svm} = {
1929 source => $src,
1930 uuid => $uuid,
1931 replace => $replace
1935 my $r = $ra->get_latest_revnum;
1936 my $path = $self->{path};
1937 my %tried;
1938 while (length $path) {
1939 unless ($tried{"$self->{url}/$path"}) {
1940 return $ra if $self->read_svm_props($ra, $path, $r);
1941 $tried{"$self->{url}/$path"} = 1;
1943 $path =~ s#/?[^/]+$##;
1945 die "Path: '$path' should be ''\n" if $path ne '';
1946 return $ra if $self->read_svm_props($ra, $path, $r);
1947 $tried{"$self->{url}/$path"} = 1;
1949 if ($ra->{repos_root} eq $self->{url}) {
1950 die @err, (map { " $_\n" } keys %tried), "\n";
1953 # nope, make sure we're connected to the repository root:
1954 my $ok;
1955 my @tried_b;
1956 $path = $ra->{svn_path};
1957 $ra = Git::SVN::Ra->new($ra->{repos_root});
1958 while (length $path) {
1959 unless ($tried{"$ra->{url}/$path"}) {
1960 $ok = $self->read_svm_props($ra, $path, $r);
1961 last if $ok;
1962 $tried{"$ra->{url}/$path"} = 1;
1964 $path =~ s#/?[^/]+$##;
1966 die "Path: '$path' should be ''\n" if $path ne '';
1967 $ok ||= $self->read_svm_props($ra, $path, $r);
1968 $tried{"$ra->{url}/$path"} = 1;
1969 if (!$ok) {
1970 die @err, (map { " $_\n" } keys %tried), "\n";
1972 Git::SVN::Ra->new($self->{url});
1975 sub svnsync {
1976 my ($self) = @_;
1977 return $self->{svnsync} if $self->{svnsync};
1979 if ($self->no_metadata) {
1980 die "Can't have both 'noMetadata' and ",
1981 "'useSvnsyncProps' options set!\n";
1983 if ($self->rewrite_root) {
1984 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1985 "options set!\n";
1988 my $svnsync;
1989 # see if we have it in our config, first:
1990 eval {
1991 my $section = "svn-remote.$self->{repo_id}";
1993 my $url = tmp_config('--get', "$section.svnsync-url");
1994 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
1995 die "doesn't look right - svn:sync-from-url is '$url'\n";
1997 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
1998 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
1999 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2001 $svnsync = { url => $url, uuid => $uuid }
2003 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
2004 return $self->{svnsync} = $svnsync;
2007 my $err = "useSvnsyncProps set, but failed to read " .
2008 "svnsync property: svn:sync-from-";
2009 my $rp = $self->ra->rev_proplist(0);
2011 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
2012 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2013 die "doesn't look right - svn:sync-from-url is '$url'\n";
2015 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
2016 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
2017 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2019 my $section = "svn-remote.$self->{repo_id}";
2020 tmp_config('--add', "$section.svnsync-uuid", $uuid);
2021 tmp_config('--add', "$section.svnsync-url", $url);
2022 return $self->{svnsync} = { url => $url, uuid => $uuid };
2025 # this allows us to memoize our SVN::Ra UUID locally and avoid a
2026 # remote lookup (useful for 'git svn log').
2027 sub ra_uuid {
2028 my ($self) = @_;
2029 unless ($self->{ra_uuid}) {
2030 my $key = "svn-remote.$self->{repo_id}.uuid";
2031 my $uuid = eval { tmp_config('--get', $key) };
2032 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
2033 $self->{ra_uuid} = $uuid;
2034 } else {
2035 die "ra_uuid called without URL\n" unless $self->{url};
2036 $self->{ra_uuid} = $self->ra->get_uuid;
2037 tmp_config('--add', $key, $self->{ra_uuid});
2040 $self->{ra_uuid};
2043 sub _set_repos_root {
2044 my ($self, $repos_root) = @_;
2045 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2046 $repos_root ||= $self->ra->{repos_root};
2047 tmp_config($k, $repos_root);
2048 $repos_root;
2051 sub repos_root {
2052 my ($self) = @_;
2053 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2054 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
2057 sub ra {
2058 my ($self) = shift;
2059 my $ra = Git::SVN::Ra->new($self->{url});
2060 $self->_set_repos_root($ra->{repos_root});
2061 if ($self->use_svm_props && !$self->{svm}) {
2062 if ($self->no_metadata) {
2063 die "Can't have both 'noMetadata' and ",
2064 "'useSvmProps' options set!\n";
2065 } elsif ($self->use_svnsync_props) {
2066 die "Can't have both 'useSvnsyncProps' and ",
2067 "'useSvmProps' options set!\n";
2069 $ra = $self->_set_svm_vars($ra);
2070 $self->{-want_revprops} = 1;
2072 $ra;
2075 sub rel_path {
2076 my ($self) = @_;
2077 my $repos_root = $self->ra->{repos_root};
2078 return $self->{path} if ($self->{url} eq $repos_root);
2079 my $url = $self->{url} .
2080 (length $self->{path} ? "/$self->{path}" : $self->{path});
2081 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
2082 $url;
2085 # prop_walk(PATH, REV, SUB)
2086 # -------------------------
2087 # Recursively traverse PATH at revision REV and invoke SUB for each
2088 # directory that contains a SVN property. SUB will be invoked as
2089 # follows: &SUB(gs, path, props); where `gs' is this instance of
2090 # Git::SVN, `path' the path to the directory where the properties
2091 # `props' were found. The `path' will be relative to point of checkout,
2092 # that is, if url://repo/trunk is the current Git branch, and that
2093 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
2094 # as `path' (note the trailing `/').
2095 sub prop_walk {
2096 my ($self, $path, $rev, $sub) = @_;
2098 $path =~ s#^/##;
2099 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2100 $path =~ s#^/*#/#g;
2101 my $p = $path;
2102 # Strip the irrelevant part of the path.
2103 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2104 # Ensure the path is terminated by a `/'.
2105 $p =~ s#/*$#/#;
2107 # The properties contain all the internal SVN stuff nobody
2108 # (usually) cares about.
2109 my $interesting_props = 0;
2110 foreach (keys %{$props}) {
2111 # If it doesn't start with `svn:', it must be a
2112 # user-defined property.
2113 ++$interesting_props and next if $_ !~ /^svn:/;
2114 # FIXME: Fragile, if SVN adds new public properties,
2115 # this needs to be updated.
2116 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2117 |eol-style|mime-type
2118 |externals|needs-lock)$/x;
2120 &$sub($self, $p, $props) if $interesting_props;
2122 foreach (sort keys %$dirent) {
2123 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
2124 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
2128 sub last_rev { ($_[0]->last_rev_commit)[0] }
2129 sub last_commit { ($_[0]->last_rev_commit)[1] }
2131 # returns the newest SVN revision number and newest commit SHA1
2132 sub last_rev_commit {
2133 my ($self) = @_;
2134 if (defined $self->{last_rev} && defined $self->{last_commit}) {
2135 return ($self->{last_rev}, $self->{last_commit});
2137 my $c = ::verify_ref($self->refname.'^0');
2138 if ($c && !$self->use_svm_props && !$self->no_metadata) {
2139 my $rev = (::cmt_metadata($c))[1];
2140 if (defined $rev) {
2141 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2142 return ($rev, $c);
2145 my $map_path = $self->map_path;
2146 unless (-e $map_path) {
2147 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2148 return (undef, undef);
2150 my ($rev, $commit) = $self->rev_map_max(1);
2151 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2152 return ($rev, $commit);
2155 sub get_fetch_range {
2156 my ($self, $min, $max) = @_;
2157 $max ||= $self->ra->get_latest_revnum;
2158 $min ||= $self->rev_map_max;
2159 (++$min, $max);
2162 sub tmp_config {
2163 my (@args) = @_;
2164 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2165 my $config = "$ENV{GIT_DIR}/svn/.metadata";
2166 if (! -f $config && -f $old_def_config) {
2167 rename $old_def_config, $config or
2168 die "Failed rename $old_def_config => $config: $!\n";
2170 my $old_config = $ENV{GIT_CONFIG};
2171 $ENV{GIT_CONFIG} = $config;
2172 $@ = undef;
2173 my @ret = eval {
2174 unless (-f $config) {
2175 mkfile($config);
2176 open my $fh, '>', $config or
2177 die "Can't open $config: $!\n";
2178 print $fh "; This file is used internally by ",
2179 "git-svn\n" or die
2180 "Couldn't write to $config: $!\n";
2181 print $fh "; You should not have to edit it\n" or
2182 die "Couldn't write to $config: $!\n";
2183 close $fh or die "Couldn't close $config: $!\n";
2185 command('config', @args);
2187 my $err = $@;
2188 if (defined $old_config) {
2189 $ENV{GIT_CONFIG} = $old_config;
2190 } else {
2191 delete $ENV{GIT_CONFIG};
2193 die $err if $err;
2194 wantarray ? @ret : $ret[0];
2197 sub tmp_index_do {
2198 my ($self, $sub) = @_;
2199 my $old_index = $ENV{GIT_INDEX_FILE};
2200 $ENV{GIT_INDEX_FILE} = $self->{index};
2201 $@ = undef;
2202 my @ret = eval {
2203 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2204 mkpath([$dir]) unless -d $dir;
2205 &$sub;
2207 my $err = $@;
2208 if (defined $old_index) {
2209 $ENV{GIT_INDEX_FILE} = $old_index;
2210 } else {
2211 delete $ENV{GIT_INDEX_FILE};
2213 die $err if $err;
2214 wantarray ? @ret : $ret[0];
2217 sub assert_index_clean {
2218 my ($self, $treeish) = @_;
2220 $self->tmp_index_do(sub {
2221 command_noisy('read-tree', $treeish) unless -e $self->{index};
2222 my $x = command_oneline('write-tree');
2223 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2224 /^tree ($::sha1)/mo);
2225 return if $y eq $x;
2227 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2228 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2229 command_noisy('read-tree', $treeish);
2230 $x = command_oneline('write-tree');
2231 if ($y ne $x) {
2232 ::fatal "trees ($treeish) $y != $x\n",
2233 "Something is seriously wrong...";
2238 sub get_commit_parents {
2239 my ($self, $log_entry) = @_;
2240 my (%seen, @ret, @tmp);
2241 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2242 if (my $ip = $self->{inject_parents}) {
2243 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2244 push @tmp, $commit;
2247 if (my $cur = ::verify_ref($self->refname.'^0')) {
2248 push @tmp, $cur;
2250 if (my $ipd = $self->{inject_parents_dcommit}) {
2251 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2252 push @tmp, @$commit;
2255 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2256 while (my $p = shift @tmp) {
2257 next if $seen{$p};
2258 $seen{$p} = 1;
2259 push @ret, $p;
2260 # MAXPARENT is defined to 16 in commit-tree.c:
2261 last if @ret >= 16;
2263 if (@tmp) {
2264 die "r$log_entry->{revision}: No room for parents:\n\t",
2265 join("\n\t", @tmp), "\n";
2267 @ret;
2270 sub rewrite_root {
2271 my ($self) = @_;
2272 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2273 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2274 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2275 if ($rwr) {
2276 $rwr =~ s#/+$##;
2277 if ($rwr !~ m#^[a-z\+]+://#) {
2278 die "$rwr is not a valid URL (key: $k)\n";
2281 $self->{-rewrite_root} = $rwr;
2284 sub metadata_url {
2285 my ($self) = @_;
2286 ($self->rewrite_root || $self->{url}) .
2287 (length $self->{path} ? '/' . $self->{path} : '');
2290 sub full_url {
2291 my ($self) = @_;
2292 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2296 sub set_commit_header_env {
2297 my ($log_entry) = @_;
2298 my %env;
2299 foreach my $ned (qw/NAME EMAIL DATE/) {
2300 foreach my $ac (qw/AUTHOR COMMITTER/) {
2301 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2305 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2306 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2307 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2309 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2310 ? $log_entry->{commit_name}
2311 : $log_entry->{name};
2312 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2313 ? $log_entry->{commit_email}
2314 : $log_entry->{email};
2315 \%env;
2318 sub restore_commit_header_env {
2319 my ($env) = @_;
2320 foreach my $ned (qw/NAME EMAIL DATE/) {
2321 foreach my $ac (qw/AUTHOR COMMITTER/) {
2322 my $k = "GIT_${ac}_${ned}";
2323 if (defined $env->{$k}) {
2324 $ENV{$k} = $env->{$k};
2325 } else {
2326 delete $ENV{$k};
2332 sub gc {
2333 command_noisy('gc', '--auto');
2336 sub do_git_commit {
2337 my ($self, $log_entry) = @_;
2338 my $lr = $self->last_rev;
2339 if (defined $lr && $lr >= $log_entry->{revision}) {
2340 die "Last fetched revision of ", $self->refname,
2341 " was r$lr, but we are about to fetch: ",
2342 "r$log_entry->{revision}!\n";
2344 if (my $c = $self->rev_map_get($log_entry->{revision})) {
2345 croak "$log_entry->{revision} = $c already exists! ",
2346 "Why are we refetching it?\n";
2348 my $old_env = set_commit_header_env($log_entry);
2349 my $tree = $log_entry->{tree};
2350 if (!defined $tree) {
2351 $tree = $self->tmp_index_do(sub {
2352 command_oneline('write-tree') });
2354 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2356 my @exec = ('git', 'commit-tree', $tree);
2357 foreach ($self->get_commit_parents($log_entry)) {
2358 push @exec, '-p', $_;
2360 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2361 or croak $!;
2362 binmode $msg_fh;
2364 # we always get UTF-8 from SVN, but we may want our commits in
2365 # a different encoding.
2366 if (my $enc = Git::config('i18n.commitencoding')) {
2367 require Encode;
2368 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
2370 print $msg_fh $log_entry->{log} or croak $!;
2371 restore_commit_header_env($old_env);
2372 unless ($self->no_metadata) {
2373 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2374 or croak $!;
2376 $msg_fh->flush == 0 or croak $!;
2377 close $msg_fh or croak $!;
2378 chomp(my $commit = do { local $/; <$out_fh> });
2379 close $out_fh or croak $!;
2380 waitpid $pid, 0;
2381 croak $? if $?;
2382 if ($commit !~ /^$::sha1$/o) {
2383 die "Failed to commit, invalid sha1: $commit\n";
2386 $self->rev_map_set($log_entry->{revision}, $commit, 1);
2388 $self->{last_rev} = $log_entry->{revision};
2389 $self->{last_commit} = $commit;
2390 print "r$log_entry->{revision}" unless $::_q > 1;
2391 if (defined $log_entry->{svm_revision}) {
2392 print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
2393 $self->rev_map_set($log_entry->{svm_revision}, $commit,
2394 0, $self->svm_uuid);
2396 print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
2397 if (--$_gc_nr == 0) {
2398 $_gc_nr = $_gc_period;
2399 gc();
2401 return $commit;
2404 sub match_paths {
2405 my ($self, $paths, $r) = @_;
2406 return 1 if $self->{path} eq '';
2407 if (my $path = $paths->{"/$self->{path}"}) {
2408 return ($path->{action} eq 'D') ? 0 : 1;
2410 my $repos_root = $self->ra->{repos_root};
2411 my $extended_path = $self->{url} . '/' . $self->{path};
2412 $extended_path =~ s#^\Q$repos_root\E(/|$)##;
2413 $self->{path_regex} ||= qr/^\/\Q$extended_path\E\//;
2414 if (grep /$self->{path_regex}/, keys %$paths) {
2415 return 1;
2417 my $c = '';
2418 foreach (split m#/#, $self->{path}) {
2419 $c .= "/$_";
2420 next unless ($paths->{$c} &&
2421 ($paths->{$c}->{action} =~ /^[AR]$/));
2422 if ($self->ra->check_path($self->{path}, $r) ==
2423 $SVN::Node::dir) {
2424 return 1;
2427 return 0;
2430 sub find_parent_branch {
2431 my ($self, $paths, $rev) = @_;
2432 return undef unless $self->follow_parent;
2433 unless (defined $paths) {
2434 my $err_handler = $SVN::Error::handler;
2435 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2436 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
2437 $paths =
2438 Git::SVN::Ra::dup_changed_paths($_[0]) });
2439 $SVN::Error::handler = $err_handler;
2441 return undef unless defined $paths;
2443 # look for a parent from another branch:
2444 my @b_path_components = split m#/#, $self->rel_path;
2445 my @a_path_components;
2446 my $i;
2447 while (@b_path_components) {
2448 $i = $paths->{'/'.join('/', @b_path_components)};
2449 last if $i && defined $i->{copyfrom_path};
2450 unshift(@a_path_components, pop(@b_path_components));
2452 return undef unless defined $i && defined $i->{copyfrom_path};
2453 my $branch_from = $i->{copyfrom_path};
2454 if (@a_path_components) {
2455 print STDERR "branch_from: $branch_from => ";
2456 $branch_from .= '/'.join('/', @a_path_components);
2457 print STDERR $branch_from, "\n";
2459 my $r = $i->{copyfrom_rev};
2460 my $repos_root = $self->ra->{repos_root};
2461 my $url = $self->ra->{url};
2462 my $new_url = $repos_root . $branch_from;
2463 print STDERR "Found possible branch point: ",
2464 "$new_url => ", $self->full_url, ", $r\n";
2465 $branch_from =~ s#^/##;
2466 my $gs = $self->other_gs($new_url, $url, $repos_root,
2467 $branch_from, $r, $self->{ref_id});
2468 my ($r0, $parent) = $gs->find_rev_before($r, 1);
2470 my ($base, $head);
2471 if (!defined $r0 || !defined $parent) {
2472 ($base, $head) = parse_revision_argument(0, $r);
2473 } else {
2474 if ($r0 < $r) {
2475 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
2476 0, 1, sub { $base = $_[1] - 1 });
2479 if (defined $base && $base <= $r) {
2480 $gs->fetch($base, $r);
2482 ($r0, $parent) = $gs->find_rev_before($r, 1);
2484 if (defined $r0 && defined $parent) {
2485 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
2486 my $ed;
2487 if ($self->ra->can_do_switch) {
2488 $self->assert_index_clean($parent);
2489 print STDERR "Following parent with do_switch\n";
2490 # do_switch works with svn/trunk >= r22312, but that
2491 # is not included with SVN 1.4.3 (the latest version
2492 # at the moment), so we can't rely on it
2493 $self->{last_rev} = $r0;
2494 $self->{last_commit} = $parent;
2495 $ed = SVN::Git::Fetcher->new($self, $gs->{path});
2496 $gs->ra->gs_do_switch($r0, $rev, $gs,
2497 $self->full_url, $ed)
2498 or die "SVN connection failed somewhere...\n";
2499 } elsif ($self->ra->trees_match($new_url, $r0,
2500 $self->full_url, $rev)) {
2501 print STDERR "Trees match:\n",
2502 " $new_url\@$r0\n",
2503 " ${\$self->full_url}\@$rev\n",
2504 "Following parent with no changes\n";
2505 $self->tmp_index_do(sub {
2506 command_noisy('read-tree', $parent);
2508 $self->{last_commit} = $parent;
2509 } else {
2510 print STDERR "Following parent with do_update\n";
2511 $ed = SVN::Git::Fetcher->new($self);
2512 $self->ra->gs_do_update($rev, $rev, $self, $ed)
2513 or die "SVN connection failed somewhere...\n";
2515 print STDERR "Successfully followed parent\n";
2516 return $self->make_log_entry($rev, [$parent], $ed);
2518 return undef;
2521 sub do_fetch {
2522 my ($self, $paths, $rev) = @_;
2523 my $ed;
2524 my ($last_rev, @parents);
2525 if (my $lc = $self->last_commit) {
2526 # we can have a branch that was deleted, then re-added
2527 # under the same name but copied from another path, in
2528 # which case we'll have multiple parents (we don't
2529 # want to break the original ref, nor lose copypath info):
2530 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2531 push @{$log_entry->{parents}}, $lc;
2532 return $log_entry;
2534 $ed = SVN::Git::Fetcher->new($self);
2535 $last_rev = $self->{last_rev};
2536 $ed->{c} = $lc;
2537 @parents = ($lc);
2538 } else {
2539 $last_rev = $rev;
2540 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2541 return $log_entry;
2543 $ed = SVN::Git::Fetcher->new($self);
2545 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2546 die "SVN connection failed somewhere...\n";
2548 $self->make_log_entry($rev, \@parents, $ed);
2551 sub get_untracked {
2552 my ($self, $ed) = @_;
2553 my @out;
2554 my $h = $ed->{empty};
2555 foreach (sort keys %$h) {
2556 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2557 push @out, " $act: " . uri_encode($_);
2558 warn "W: $act: $_\n";
2560 foreach my $t (qw/dir_prop file_prop/) {
2561 $h = $ed->{$t} or next;
2562 foreach my $path (sort keys %$h) {
2563 my $ppath = $path eq '' ? '.' : $path;
2564 foreach my $prop (sort keys %{$h->{$path}}) {
2565 next if $SKIP_PROP{$prop};
2566 my $v = $h->{$path}->{$prop};
2567 my $t_ppath_prop = "$t: " .
2568 uri_encode($ppath) . ' ' .
2569 uri_encode($prop);
2570 if (defined $v) {
2571 push @out, " +$t_ppath_prop " .
2572 uri_encode($v);
2573 } else {
2574 push @out, " -$t_ppath_prop";
2579 foreach my $t (qw/absent_file absent_directory/) {
2580 $h = $ed->{$t} or next;
2581 foreach my $parent (sort keys %$h) {
2582 foreach my $path (sort @{$h->{$parent}}) {
2583 push @out, " $t: " .
2584 uri_encode("$parent/$path");
2585 warn "W: $t: $parent/$path ",
2586 "Insufficient permissions?\n";
2590 \@out;
2593 # parse_svn_date(DATE)
2594 # --------------------
2595 # Given a date (in UTC) from Subversion, return a string in the format
2596 # "<TZ Offset> <local date/time>" that Git will use.
2598 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
2599 # is true we'll convert it to the local timezone instead.
2600 sub parse_svn_date {
2601 my $date = shift || return '+0000 1970-01-01 00:00:00';
2602 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2603 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
2604 croak "Unable to parse date: $date\n";
2605 my $parsed_date; # Set next.
2607 if ($Git::SVN::_localtime) {
2608 # Translate the Subversion datetime to an epoch time.
2609 # Begin by switching ourselves to $date's timezone, UTC.
2610 my $old_env_TZ = $ENV{TZ};
2611 $ENV{TZ} = 'UTC';
2613 my $epoch_in_UTC =
2614 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
2616 # Determine our local timezone (including DST) at the
2617 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
2618 # value of TZ, if any, at the time we were run.
2619 if (defined $Git::SVN::Log::TZ) {
2620 $ENV{TZ} = $Git::SVN::Log::TZ;
2621 } else {
2622 delete $ENV{TZ};
2625 my $our_TZ =
2626 POSIX::strftime('%Z', $S, $M, $H, $d, $m - 1, $Y - 1900);
2628 # This converts $epoch_in_UTC into our local timezone.
2629 my ($sec, $min, $hour, $mday, $mon, $year,
2630 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
2632 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
2633 $our_TZ, $year + 1900, $mon + 1,
2634 $mday, $hour, $min, $sec);
2636 # Reset us to the timezone in effect when we entered
2637 # this routine.
2638 if (defined $old_env_TZ) {
2639 $ENV{TZ} = $old_env_TZ;
2640 } else {
2641 delete $ENV{TZ};
2643 } else {
2644 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
2647 return $parsed_date;
2650 sub other_gs {
2651 my ($self, $new_url, $url, $repos_root,
2652 $branch_from, $r, $old_ref_id) = @_;
2653 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
2654 unless ($gs) {
2655 my $ref_id = $old_ref_id;
2656 $ref_id =~ s/\@\d+$//;
2657 $ref_id .= "\@$r";
2658 # just grow a tail if we're not unique enough :x
2659 $ref_id .= '-' while find_ref($ref_id);
2660 print STDERR "Initializing parent: $ref_id\n";
2661 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
2662 if ($u =~ s#^\Q$url\E(/|$)##) {
2663 $p = $u;
2664 $u = $url;
2665 $repo_id = $self->{repo_id};
2667 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
2672 sub call_authors_prog {
2673 my ($orig_author) = @_;
2674 my $author = `$::_authors_prog $orig_author`;
2675 if ($? != 0) {
2676 die "$::_authors_prog failed with exit code $?\n"
2678 if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
2679 my ($name, $email) = ($1, $2);
2680 $email = undef if length $2 == 0;
2681 return [$name, $email];
2682 } else {
2683 die "Author: $orig_author: $::_authors_prog returned "
2684 . "invalid author format: $author\n";
2688 sub check_author {
2689 my ($author) = @_;
2690 if (!defined $author || length $author == 0) {
2691 $author = '(no author)';
2693 if (!defined $::users{$author}) {
2694 if (defined $::_authors_prog) {
2695 $::users{$author} = call_authors_prog($author);
2696 } elsif (defined $::_authors) {
2697 die "Author: $author not defined in $::_authors file\n";
2700 $author;
2703 sub make_log_entry {
2704 my ($self, $rev, $parents, $ed) = @_;
2705 my $untracked = $self->get_untracked($ed);
2707 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
2708 print $un "r$rev\n" or croak $!;
2709 print $un $_, "\n" foreach @$untracked;
2710 my %log_entry = ( parents => $parents || [], revision => $rev,
2711 log => '');
2713 my $headrev;
2714 my $logged = delete $self->{logged_rev_props};
2715 if (!$logged || $self->{-want_revprops}) {
2716 my $rp = $self->ra->rev_proplist($rev);
2717 foreach (sort keys %$rp) {
2718 my $v = $rp->{$_};
2719 if (/^svn:(author|date|log)$/) {
2720 $log_entry{$1} = $v;
2721 } elsif ($_ eq 'svm:headrev') {
2722 $headrev = $v;
2723 } else {
2724 print $un " rev_prop: ", uri_encode($_), ' ',
2725 uri_encode($v), "\n";
2728 } else {
2729 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
2731 close $un or croak $!;
2733 $log_entry{date} = parse_svn_date($log_entry{date});
2734 $log_entry{log} .= "\n";
2735 my $author = $log_entry{author} = check_author($log_entry{author});
2736 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
2737 : ($author, undef);
2739 my ($commit_name, $commit_email) = ($name, $email);
2740 if ($_use_log_author) {
2741 my $name_field;
2742 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
2743 $name_field = $1;
2744 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
2745 $name_field = $1;
2747 if (!defined $name_field) {
2748 if (!defined $email) {
2749 $email = $name;
2751 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
2752 ($name, $email) = ($1, $2);
2753 } elsif ($name_field =~ /(.*)@/) {
2754 ($name, $email) = ($1, $name_field);
2755 } else {
2756 ($name, $email) = ($name_field, $name_field);
2759 if (defined $headrev && $self->use_svm_props) {
2760 if ($self->rewrite_root) {
2761 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2762 "options set!\n";
2764 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
2765 # we don't want "SVM: initializing mirror for junk" ...
2766 return undef if $r == 0;
2767 my $svm = $self->svm;
2768 if ($uuid ne $svm->{uuid}) {
2769 die "UUID mismatch on SVM path:\n",
2770 "expected: $svm->{uuid}\n",
2771 " got: $uuid\n";
2773 my $full_url = $self->full_url;
2774 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2775 die "Failed to replace '$svm->{replace}' with ",
2776 "'$svm->{source}' in $full_url\n";
2777 # throw away username for storing in records
2778 remove_username($full_url);
2779 $log_entry{metadata} = "$full_url\@$r $uuid";
2780 $log_entry{svm_revision} = $r;
2781 $email ||= "$author\@$uuid";
2782 $commit_email ||= "$author\@$uuid";
2783 } elsif ($self->use_svnsync_props) {
2784 my $full_url = $self->svnsync->{url};
2785 $full_url .= "/$self->{path}" if length $self->{path};
2786 remove_username($full_url);
2787 my $uuid = $self->svnsync->{uuid};
2788 $log_entry{metadata} = "$full_url\@$rev $uuid";
2789 $email ||= "$author\@$uuid";
2790 $commit_email ||= "$author\@$uuid";
2791 } else {
2792 my $url = $self->metadata_url;
2793 remove_username($url);
2794 $log_entry{metadata} = "$url\@$rev " .
2795 $self->ra->get_uuid;
2796 $email ||= "$author\@" . $self->ra->get_uuid;
2797 $commit_email ||= "$author\@" . $self->ra->get_uuid;
2799 $log_entry{name} = $name;
2800 $log_entry{email} = $email;
2801 $log_entry{commit_name} = $commit_name;
2802 $log_entry{commit_email} = $commit_email;
2803 \%log_entry;
2806 sub fetch {
2807 my ($self, $min_rev, $max_rev, @parents) = @_;
2808 my ($last_rev, $last_commit) = $self->last_rev_commit;
2809 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2810 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2813 sub set_tree_cb {
2814 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2815 $self->{inject_parents} = { $rev => $tree };
2816 $self->fetch(undef, undef);
2819 sub set_tree {
2820 my ($self, $tree) = (shift, shift);
2821 my $log_entry = ::get_commit_entry($tree);
2822 unless ($self->{last_rev}) {
2823 ::fatal("Must have an existing revision to commit");
2825 my %ed_opts = ( r => $self->{last_rev},
2826 log => $log_entry->{log},
2827 ra => $self->ra,
2828 tree_a => $self->{last_commit},
2829 tree_b => $tree,
2830 editor_cb => sub {
2831 $self->set_tree_cb($log_entry, $tree, @_) },
2832 svn_path => $self->{path} );
2833 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2834 print "No changes\nr$self->{last_rev} = $tree\n";
2838 sub rebuild_from_rev_db {
2839 my ($self, $path) = @_;
2840 my $r = -1;
2841 open my $fh, '<', $path or croak "open: $!";
2842 binmode $fh or croak "binmode: $!";
2843 while (<$fh>) {
2844 length($_) == 41 or croak "inconsistent size in ($_) != 41";
2845 chomp($_);
2846 ++$r;
2847 next if $_ eq ('0' x 40);
2848 $self->rev_map_set($r, $_);
2849 print "r$r = $_\n";
2851 close $fh or croak "close: $!";
2852 unlink $path or croak "unlink: $!";
2855 sub rebuild {
2856 my ($self) = @_;
2857 my $map_path = $self->map_path;
2858 my $partial = (-e $map_path && ! -z $map_path);
2859 return unless ::verify_ref($self->refname.'^0');
2860 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
2861 my $rev_db = $self->rev_db_path;
2862 $self->rebuild_from_rev_db($rev_db);
2863 if ($self->use_svm_props) {
2864 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
2865 $self->rebuild_from_rev_db($svm_rev_db);
2867 $self->unlink_rev_db_symlink;
2868 return;
2870 print "Rebuilding $map_path ...\n" if (!$partial);
2871 my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
2872 (undef, undef));
2873 my ($log, $ctx) =
2874 command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
2875 ($head ? "$head.." : "") . $self->refname,
2876 '--');
2877 my $metadata_url = $self->metadata_url;
2878 remove_username($metadata_url);
2879 my $svn_uuid = $self->ra_uuid;
2880 my $c;
2881 while (<$log>) {
2882 if ( m{^commit ($::sha1)$} ) {
2883 $c = $1;
2884 next;
2886 next unless s{^\s*(git-svn-id:)}{$1};
2887 my ($url, $rev, $uuid) = ::extract_metadata($_);
2888 remove_username($url);
2890 # ignore merges (from set-tree)
2891 next if (!defined $rev || !$uuid);
2893 # if we merged or otherwise started elsewhere, this is
2894 # how we break out of it
2895 if (($uuid ne $svn_uuid) ||
2896 ($metadata_url && $url && ($url ne $metadata_url))) {
2897 next;
2899 if ($partial && $head) {
2900 print "Partial-rebuilding $map_path ...\n";
2901 print "Currently at $base_rev = $head\n";
2902 $head = undef;
2905 $self->rev_map_set($rev, $c);
2906 print "r$rev = $c\n";
2908 command_close_pipe($log, $ctx);
2909 print "Done rebuilding $map_path\n" if (!$partial || !$head);
2910 my $rev_db_path = $self->rev_db_path;
2911 if (-f $self->rev_db_path) {
2912 unlink $self->rev_db_path or croak "unlink: $!";
2914 $self->unlink_rev_db_symlink;
2917 # rev_map:
2918 # Tie::File seems to be prone to offset errors if revisions get sparse,
2919 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2920 # one of my favorite modules is out :< Next up would be one of the DBM
2921 # modules, but I'm not sure which is most portable...
2923 # This is the replacement for the rev_db format, which was too big
2924 # and inefficient for large repositories with a lot of sparse history
2925 # (mainly tags)
2927 # The format is this:
2928 # - 24 bytes for every record,
2929 # * 4 bytes for the integer representing an SVN revision number
2930 # * 20 bytes representing the sha1 of a git commit
2931 # - No empty padding records like the old format
2932 # (except the last record, which can be overwritten)
2933 # - new records are written append-only since SVN revision numbers
2934 # increase monotonically
2935 # - lookups on SVN revision number are done via a binary search
2936 # - Piping the file to xxd -c24 is a good way of dumping it for
2937 # viewing or editing (piped back through xxd -r), should the need
2938 # ever arise.
2939 # - The last record can be padding revision with an all-zero sha1
2940 # This is used to optimize fetch performance when using multiple
2941 # "fetch" directives in .git/config
2943 # These files are disposable unless noMetadata or useSvmProps is set
2945 sub _rev_map_set {
2946 my ($fh, $rev, $commit) = @_;
2948 binmode $fh or croak "binmode: $!";
2949 my $size = (stat($fh))[7];
2950 ($size % 24) == 0 or croak "inconsistent size: $size";
2952 my $wr_offset = 0;
2953 if ($size > 0) {
2954 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2955 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
2956 $read == 24 or croak "read only $read bytes (!= 24)";
2957 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
2958 if ($last_commit eq ('0' x40)) {
2959 if ($size >= 48) {
2960 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2961 $read = sysread($fh, $buf, 24) or
2962 croak "read: $!";
2963 $read == 24 or
2964 croak "read only $read bytes (!= 24)";
2965 ($last_rev, $last_commit) =
2966 unpack(rev_map_fmt, $buf);
2967 if ($last_commit eq ('0' x40)) {
2968 croak "inconsistent .rev_map\n";
2971 if ($last_rev >= $rev) {
2972 croak "last_rev is higher!: $last_rev >= $rev";
2974 $wr_offset = -24;
2977 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
2978 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
2979 croak "write: $!";
2982 sub mkfile {
2983 my ($path) = @_;
2984 unless (-e $path) {
2985 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2986 mkpath([$dir]) unless -d $dir;
2987 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2988 close $fh or die "Couldn't close (create) $path: $!\n";
2992 sub rev_map_set {
2993 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2994 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2995 my $db = $self->map_path($uuid);
2996 my $db_lock = "$db.lock";
2997 my $sig;
2998 if ($update_ref) {
2999 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3000 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
3002 mkfile($db);
3004 $LOCKFILES{$db_lock} = 1;
3005 my $sync;
3006 # both of these options make our .rev_db file very, very important
3007 # and we can't afford to lose it because rebuild() won't work
3008 if ($self->use_svm_props || $self->no_metadata) {
3009 $sync = 1;
3010 copy($db, $db_lock) or die "rev_map_set(@_): ",
3011 "Failed to copy: ",
3012 "$db => $db_lock ($!)\n";
3013 } else {
3014 rename $db, $db_lock or die "rev_map_set(@_): ",
3015 "Failed to rename: ",
3016 "$db => $db_lock ($!)\n";
3019 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
3020 or croak "Couldn't open $db_lock: $!\n";
3021 _rev_map_set($fh, $rev, $commit);
3022 if ($sync) {
3023 $fh->flush or die "Couldn't flush $db_lock: $!\n";
3024 $fh->sync or die "Couldn't sync $db_lock: $!\n";
3026 close $fh or croak $!;
3027 if ($update_ref) {
3028 $_head = $self;
3029 command_noisy('update-ref', '-m', "r$rev",
3030 $self->refname, $commit);
3032 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
3033 "$db_lock => $db ($!)\n";
3034 delete $LOCKFILES{$db_lock};
3035 if ($update_ref) {
3036 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3037 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
3038 kill $sig, $$ if defined $sig;
3042 # If want_commit, this will return an array of (rev, commit) where
3043 # commit _must_ be a valid commit in the archive.
3044 # Otherwise, it'll return the max revision (whether or not the
3045 # commit is valid or just a 0x40 placeholder).
3046 sub rev_map_max {
3047 my ($self, $want_commit) = @_;
3048 $self->rebuild;
3049 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
3050 $want_commit ? ($r, $c) : $r;
3053 sub rev_map_max_norebuild {
3054 my ($self, $want_commit) = @_;
3055 my $map_path = $self->map_path;
3056 stat $map_path or return $want_commit ? (0, undef) : 0;
3057 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3058 binmode $fh or croak "binmode: $!";
3059 my $size = (stat($fh))[7];
3060 ($size % 24) == 0 or croak "inconsistent size: $size";
3062 if ($size == 0) {
3063 close $fh or croak "close: $!";
3064 return $want_commit ? (0, undef) : 0;
3067 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3068 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3069 my ($r, $c) = unpack(rev_map_fmt, $buf);
3070 if ($want_commit && $c eq ('0' x40)) {
3071 if ($size < 48) {
3072 return $want_commit ? (0, undef) : 0;
3074 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3075 sysread($fh, $buf, 24) == 24 or croak "read: $!";
3076 ($r, $c) = unpack(rev_map_fmt, $buf);
3077 if ($c eq ('0'x40)) {
3078 croak "Penultimate record is all-zeroes in $map_path";
3081 close $fh or croak "close: $!";
3082 $want_commit ? ($r, $c) : $r;
3085 sub rev_map_get {
3086 my ($self, $rev, $uuid) = @_;
3087 my $map_path = $self->map_path($uuid);
3088 return undef unless -e $map_path;
3090 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3091 binmode $fh or croak "binmode: $!";
3092 my $size = (stat($fh))[7];
3093 ($size % 24) == 0 or croak "inconsistent size: $size";
3095 if ($size == 0) {
3096 close $fh or croak "close: $fh";
3097 return undef;
3100 my ($l, $u) = (0, $size - 24);
3101 my ($r, $c, $buf);
3103 while ($l <= $u) {
3104 my $i = int(($l/24 + $u/24) / 2) * 24;
3105 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
3106 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3107 my ($r, $c) = unpack('NH40', $buf);
3109 if ($r < $rev) {
3110 $l = $i + 24;
3111 } elsif ($r > $rev) {
3112 $u = $i - 24;
3113 } else { # $r == $rev
3114 close($fh) or croak "close: $!";
3115 return $c eq ('0' x 40) ? undef : $c;
3118 close($fh) or croak "close: $!";
3119 undef;
3122 # Finds the first svn revision that exists on (if $eq_ok is true) or
3123 # before $rev for the current branch. It will not search any lower
3124 # than $min_rev. Returns the git commit hash and svn revision number
3125 # if found, else (undef, undef).
3126 sub find_rev_before {
3127 my ($self, $rev, $eq_ok, $min_rev) = @_;
3128 --$rev unless $eq_ok;
3129 $min_rev ||= 1;
3130 while ($rev >= $min_rev) {
3131 if (my $c = $self->rev_map_get($rev)) {
3132 return ($rev, $c);
3134 --$rev;
3136 return (undef, undef);
3139 # Finds the first svn revision that exists on (if $eq_ok is true) or
3140 # after $rev for the current branch. It will not search any higher
3141 # than $max_rev. Returns the git commit hash and svn revision number
3142 # if found, else (undef, undef).
3143 sub find_rev_after {
3144 my ($self, $rev, $eq_ok, $max_rev) = @_;
3145 ++$rev unless $eq_ok;
3146 $max_rev ||= $self->rev_map_max;
3147 while ($rev <= $max_rev) {
3148 if (my $c = $self->rev_map_get($rev)) {
3149 return ($rev, $c);
3151 ++$rev;
3153 return (undef, undef);
3156 sub _new {
3157 my ($class, $repo_id, $ref_id, $path) = @_;
3158 unless (defined $repo_id && length $repo_id) {
3159 $repo_id = $Git::SVN::default_repo_id;
3161 unless (defined $ref_id && length $ref_id) {
3162 $_[2] = $ref_id = $Git::SVN::default_ref_id;
3164 $_[1] = $repo_id;
3165 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
3166 $_[3] = $path = '' unless (defined $path);
3167 mkpath(["$ENV{GIT_DIR}/svn"]);
3168 bless {
3169 ref_id => $ref_id, dir => $dir, index => "$dir/index",
3170 path => $path, config => "$ENV{GIT_DIR}/svn/config",
3171 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
3174 # for read-only access of old .rev_db formats
3175 sub unlink_rev_db_symlink {
3176 my ($self) = @_;
3177 my $link = $self->rev_db_path;
3178 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
3179 if (-l $link) {
3180 unlink $link or croak "unlink: $link failed!";
3184 sub rev_db_path {
3185 my ($self, $uuid) = @_;
3186 my $db_path = $self->map_path($uuid);
3187 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
3188 or croak "map_path: $db_path does not contain '/.rev_map.' !";
3189 $db_path;
3192 # the new replacement for .rev_db
3193 sub map_path {
3194 my ($self, $uuid) = @_;
3195 $uuid ||= $self->ra_uuid;
3196 "$self->{map_root}.$uuid";
3199 sub uri_encode {
3200 my ($f) = @_;
3201 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
3205 sub remove_username {
3206 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
3209 package Git::SVN::Prompt;
3210 use strict;
3211 use warnings;
3212 require SVN::Core;
3213 use vars qw/$_no_auth_cache $_username/;
3215 sub simple {
3216 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
3217 $may_save = undef if $_no_auth_cache;
3218 $default_username = $_username if defined $_username;
3219 if (defined $default_username && length $default_username) {
3220 if (defined $realm && length $realm) {
3221 print STDERR "Authentication realm: $realm\n";
3222 STDERR->flush;
3224 $cred->username($default_username);
3225 } else {
3226 username($cred, $realm, $may_save, $pool);
3228 $cred->password(_read_password("Password for '" .
3229 $cred->username . "': ", $realm));
3230 $cred->may_save($may_save);
3231 $SVN::_Core::SVN_NO_ERROR;
3234 sub ssl_server_trust {
3235 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
3236 $may_save = undef if $_no_auth_cache;
3237 print STDERR "Error validating server certificate for '$realm':\n";
3239 no warnings 'once';
3240 # All variables SVN::Auth::SSL::* are used only once,
3241 # so we're shutting up Perl warnings about this.
3242 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
3243 print STDERR " - The certificate is not issued ",
3244 "by a trusted authority. Use the\n",
3245 " fingerprint to validate ",
3246 "the certificate manually!\n";
3248 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
3249 print STDERR " - The certificate hostname ",
3250 "does not match.\n";
3252 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
3253 print STDERR " - The certificate is not yet valid.\n";
3255 if ($failures & $SVN::Auth::SSL::EXPIRED) {
3256 print STDERR " - The certificate has expired.\n";
3258 if ($failures & $SVN::Auth::SSL::OTHER) {
3259 print STDERR " - The certificate has ",
3260 "an unknown error.\n";
3262 } # no warnings 'once'
3263 printf STDERR
3264 "Certificate information:\n".
3265 " - Hostname: %s\n".
3266 " - Valid: from %s until %s\n".
3267 " - Issuer: %s\n".
3268 " - Fingerprint: %s\n",
3269 map $cert_info->$_, qw(hostname valid_from valid_until
3270 issuer_dname fingerprint);
3271 my $choice;
3272 prompt:
3273 print STDERR $may_save ?
3274 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
3275 "(R)eject or accept (t)emporarily? ";
3276 STDERR->flush;
3277 $choice = lc(substr(<STDIN> || 'R', 0, 1));
3278 if ($choice =~ /^t$/i) {
3279 $cred->may_save(undef);
3280 } elsif ($choice =~ /^r$/i) {
3281 return -1;
3282 } elsif ($may_save && $choice =~ /^p$/i) {
3283 $cred->may_save($may_save);
3284 } else {
3285 goto prompt;
3287 $cred->accepted_failures($failures);
3288 $SVN::_Core::SVN_NO_ERROR;
3291 sub ssl_client_cert {
3292 my ($cred, $realm, $may_save, $pool) = @_;
3293 $may_save = undef if $_no_auth_cache;
3294 print STDERR "Client certificate filename: ";
3295 STDERR->flush;
3296 chomp(my $filename = <STDIN>);
3297 $cred->cert_file($filename);
3298 $cred->may_save($may_save);
3299 $SVN::_Core::SVN_NO_ERROR;
3302 sub ssl_client_cert_pw {
3303 my ($cred, $realm, $may_save, $pool) = @_;
3304 $may_save = undef if $_no_auth_cache;
3305 $cred->password(_read_password("Password: ", $realm));
3306 $cred->may_save($may_save);
3307 $SVN::_Core::SVN_NO_ERROR;
3310 sub username {
3311 my ($cred, $realm, $may_save, $pool) = @_;
3312 $may_save = undef if $_no_auth_cache;
3313 if (defined $realm && length $realm) {
3314 print STDERR "Authentication realm: $realm\n";
3316 my $username;
3317 if (defined $_username) {
3318 $username = $_username;
3319 } else {
3320 print STDERR "Username: ";
3321 STDERR->flush;
3322 chomp($username = <STDIN>);
3324 $cred->username($username);
3325 $cred->may_save($may_save);
3326 $SVN::_Core::SVN_NO_ERROR;
3329 sub _read_password {
3330 my ($prompt, $realm) = @_;
3331 print STDERR $prompt;
3332 STDERR->flush;
3333 require Term::ReadKey;
3334 Term::ReadKey::ReadMode('noecho');
3335 my $password = '';
3336 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
3337 last if $key =~ /[\012\015]/; # \n\r
3338 $password .= $key;
3340 Term::ReadKey::ReadMode('restore');
3341 print STDERR "\n";
3342 STDERR->flush;
3343 $password;
3346 package SVN::Git::Fetcher;
3347 use vars qw/@ISA/;
3348 use strict;
3349 use warnings;
3350 use Carp qw/croak/;
3351 use File::Temp qw/tempfile/;
3352 use IO::File qw//;
3353 use vars qw/$_ignore_regex/;
3355 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
3356 sub new {
3357 my ($class, $git_svn, $switch_path) = @_;
3358 my $self = SVN::Delta::Editor->new;
3359 bless $self, $class;
3360 if (exists $git_svn->{last_commit}) {
3361 $self->{c} = $git_svn->{last_commit};
3362 $self->{empty_symlinks} =
3363 _mark_empty_symlinks($git_svn, $switch_path);
3365 $self->{ignore_regex} = eval { command_oneline('config', '--get',
3366 "svn-remote.$git_svn->{repo_id}.ignore-paths") };
3367 $self->{empty} = {};
3368 $self->{dir_prop} = {};
3369 $self->{file_prop} = {};
3370 $self->{absent_dir} = {};
3371 $self->{absent_file} = {};
3372 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
3373 $self;
3376 # this uses the Ra object, so it must be called before do_{switch,update},
3377 # not inside them (when the Git::SVN::Fetcher object is passed) to
3378 # do_{switch,update}
3379 sub _mark_empty_symlinks {
3380 my ($git_svn, $switch_path) = @_;
3381 my $bool = Git::config_bool('svn.brokenSymlinkWorkaround');
3382 return {} if (!defined($bool)) || (defined($bool) && ! $bool);
3384 my %ret;
3385 my ($rev, $cmt) = $git_svn->last_rev_commit;
3386 return {} unless ($rev && $cmt);
3388 # allow the warning to be printed for each revision we fetch to
3389 # ensure the user sees it. The user can also disable the workaround
3390 # on the repository even while git svn is running and the next
3391 # revision fetched will skip this expensive function.
3392 my $printed_warning;
3393 chomp(my $empty_blob = `git hash-object -t blob --stdin < /dev/null`);
3394 my ($ls, $ctx) = command_output_pipe(qw/ls-tree -r -z/, $cmt);
3395 local $/ = "\0";
3396 my $pfx = defined($switch_path) ? $switch_path : $git_svn->{path};
3397 $pfx .= '/' if length($pfx);
3398 while (<$ls>) {
3399 chomp;
3400 s/\A100644 blob $empty_blob\t//o or next;
3401 unless ($printed_warning) {
3402 print STDERR "Scanning for empty symlinks, ",
3403 "this may take a while if you have ",
3404 "many empty files\n",
3405 "You may disable this with `",
3406 "git config svn.brokenSymlinkWorkaround ",
3407 "false'.\n",
3408 "This may be done in a different ",
3409 "terminal without restarting ",
3410 "git svn\n";
3411 $printed_warning = 1;
3413 my $path = $_;
3414 my (undef, $props) =
3415 $git_svn->ra->get_file($pfx.$path, $rev, undef);
3416 if ($props->{'svn:special'}) {
3417 $ret{$path} = 1;
3420 command_close_pipe($ls, $ctx);
3421 \%ret;
3424 # returns true if a given path is inside a ".git" directory
3425 sub in_dot_git {
3426 $_[0] =~ m{(?:^|/)\.git(?:/|$)};
3429 # return value: 0 -- don't ignore, 1 -- ignore
3430 sub is_path_ignored {
3431 my ($self, $path) = @_;
3432 return 1 if in_dot_git($path);
3433 return 1 if defined($self->{ignore_regex}) &&
3434 $path =~ m!$self->{ignore_regex}!;
3435 return 0 unless defined($_ignore_regex);
3436 return 1 if $path =~ m!$_ignore_regex!o;
3437 return 0;
3440 sub set_path_strip {
3441 my ($self, $path) = @_;
3442 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
3445 sub open_root {
3446 { path => '' };
3449 sub open_directory {
3450 my ($self, $path, $pb, $rev) = @_;
3451 { path => $path };
3454 sub git_path {
3455 my ($self, $path) = @_;
3456 if ($self->{path_strip}) {
3457 $path =~ s!$self->{path_strip}!! or
3458 die "Failed to strip path '$path' ($self->{path_strip})\n";
3460 $path;
3463 sub delete_entry {
3464 my ($self, $path, $rev, $pb) = @_;
3465 return undef if $self->is_path_ignored($path);
3467 my $gpath = $self->git_path($path);
3468 return undef if ($gpath eq '');
3470 # remove entire directories.
3471 my ($tree) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
3472 =~ /\A040000 tree ([a-f\d]{40})\t\Q$gpath\E\0/);
3473 if ($tree) {
3474 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3475 -r --name-only -z/,
3476 $tree);
3477 local $/ = "\0";
3478 while (<$ls>) {
3479 chomp;
3480 my $rmpath = "$gpath/$_";
3481 $self->{gii}->remove($rmpath);
3482 print "\tD\t$rmpath\n" unless $::_q;
3484 print "\tD\t$gpath/\n" unless $::_q;
3485 command_close_pipe($ls, $ctx);
3486 $self->{empty}->{$path} = 0
3487 } else {
3488 $self->{gii}->remove($gpath);
3489 print "\tD\t$gpath\n" unless $::_q;
3491 undef;
3494 sub open_file {
3495 my ($self, $path, $pb, $rev) = @_;
3496 my ($mode, $blob);
3498 goto out if $self->is_path_ignored($path);
3500 my $gpath = $self->git_path($path);
3501 ($mode, $blob) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
3502 =~ /\A(\d{6}) blob ([a-f\d]{40})\t\Q$gpath\E\0/);
3503 unless (defined $mode && defined $blob) {
3504 die "$path was not found in commit $self->{c} (r$rev)\n";
3506 if ($mode eq '100644' && $self->{empty_symlinks}->{$path}) {
3507 $mode = '120000';
3509 out:
3510 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
3511 pool => SVN::Pool->new, action => 'M' };
3514 sub add_file {
3515 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
3516 my $mode;
3518 if (!$self->is_path_ignored($path)) {
3519 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3520 delete $self->{empty}->{$dir};
3521 $mode = '100644';
3523 { path => $path, mode_a => $mode, mode_b => $mode,
3524 pool => SVN::Pool->new, action => 'A' };
3527 sub add_directory {
3528 my ($self, $path, $cp_path, $cp_rev) = @_;
3529 goto out if $self->is_path_ignored($path);
3530 my $gpath = $self->git_path($path);
3531 if ($gpath eq '') {
3532 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3533 -r --name-only -z/,
3534 $self->{c});
3535 local $/ = "\0";
3536 while (<$ls>) {
3537 chomp;
3538 $self->{gii}->remove($_);
3539 print "\tD\t$_\n" unless $::_q;
3541 command_close_pipe($ls, $ctx);
3542 $self->{empty}->{$path} = 0;
3544 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3545 delete $self->{empty}->{$dir};
3546 $self->{empty}->{$path} = 1;
3547 out:
3548 { path => $path };
3551 sub change_dir_prop {
3552 my ($self, $db, $prop, $value) = @_;
3553 return undef if $self->is_path_ignored($db->{path});
3554 $self->{dir_prop}->{$db->{path}} ||= {};
3555 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
3556 undef;
3559 sub absent_directory {
3560 my ($self, $path, $pb) = @_;
3561 return undef if $self->is_path_ignored($path);
3562 $self->{absent_dir}->{$pb->{path}} ||= [];
3563 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
3564 undef;
3567 sub absent_file {
3568 my ($self, $path, $pb) = @_;
3569 return undef if $self->is_path_ignored($path);
3570 $self->{absent_file}->{$pb->{path}} ||= [];
3571 push @{$self->{absent_file}->{$pb->{path}}}, $path;
3572 undef;
3575 sub change_file_prop {
3576 my ($self, $fb, $prop, $value) = @_;
3577 return undef if $self->is_path_ignored($fb->{path});
3578 if ($prop eq 'svn:executable') {
3579 if ($fb->{mode_b} != 120000) {
3580 $fb->{mode_b} = defined $value ? 100755 : 100644;
3582 } elsif ($prop eq 'svn:special') {
3583 $fb->{mode_b} = defined $value ? 120000 : 100644;
3584 } else {
3585 $self->{file_prop}->{$fb->{path}} ||= {};
3586 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
3588 undef;
3591 sub apply_textdelta {
3592 my ($self, $fb, $exp) = @_;
3593 return undef if $self->is_path_ignored($fb->{path});
3594 my $fh = $::_repository->temp_acquire('svn_delta');
3595 # $fh gets auto-closed() by SVN::TxDelta::apply(),
3596 # (but $base does not,) so dup() it for reading in close_file
3597 open my $dup, '<&', $fh or croak $!;
3598 my $base = $::_repository->temp_acquire('git_blob');
3600 if ($fb->{blob}) {
3601 my ($base_is_link, $size);
3603 if ($fb->{mode_a} eq '120000' &&
3604 ! $self->{empty_symlinks}->{$fb->{path}}) {
3605 print $base 'link ' or die "print $!\n";
3606 $base_is_link = 1;
3608 retry:
3609 $size = $::_repository->cat_blob($fb->{blob}, $base);
3610 die "Failed to read object $fb->{blob}" if ($size < 0);
3612 if (defined $exp) {
3613 seek $base, 0, 0 or croak $!;
3614 my $got = ::md5sum($base);
3615 if ($got ne $exp) {
3616 my $err = "Checksum mismatch: ".
3617 "$fb->{path} $fb->{blob}\n" .
3618 "expected: $exp\n" .
3619 " got: $got\n";
3620 if ($base_is_link) {
3621 warn $err,
3622 "Retrying... (possibly ",
3623 "a bad symlink from SVN)\n";
3624 $::_repository->temp_reset($base);
3625 $base_is_link = 0;
3626 goto retry;
3628 die $err;
3632 seek $base, 0, 0 or croak $!;
3633 $fb->{fh} = $fh;
3634 $fb->{base} = $base;
3635 [ SVN::TxDelta::apply($base, $dup, undef, $fb->{path}, $fb->{pool}) ];
3638 sub close_file {
3639 my ($self, $fb, $exp) = @_;
3640 return undef if $self->is_path_ignored($fb->{path});
3642 my $hash;
3643 my $path = $self->git_path($fb->{path});
3644 if (my $fh = $fb->{fh}) {
3645 if (defined $exp) {
3646 seek($fh, 0, 0) or croak $!;
3647 my $got = ::md5sum($fh);
3648 if ($got ne $exp) {
3649 die "Checksum mismatch: $path\n",
3650 "expected: $exp\n got: $got\n";
3653 if ($fb->{mode_b} == 120000) {
3654 sysseek($fh, 0, 0) or croak $!;
3655 my $rd = sysread($fh, my $buf, 5);
3657 if (!defined $rd) {
3658 croak "sysread: $!\n";
3659 } elsif ($rd == 0) {
3660 warn "$path has mode 120000",
3661 " but it points to nothing\n",
3662 "converting to an empty file with mode",
3663 " 100644\n";
3664 $fb->{mode_b} = '100644';
3665 } elsif ($buf ne 'link ') {
3666 warn "$path has mode 120000",
3667 " but is not a link\n";
3668 } else {
3669 my $tmp_fh = $::_repository->temp_acquire(
3670 'svn_hash');
3671 my $res;
3672 while ($res = sysread($fh, my $str, 1024)) {
3673 my $out = syswrite($tmp_fh, $str, $res);
3674 defined($out) && $out == $res
3675 or croak("write ",
3676 Git::temp_path($tmp_fh),
3677 ": $!\n");
3679 defined $res or croak $!;
3681 ($fh, $tmp_fh) = ($tmp_fh, $fh);
3682 Git::temp_release($tmp_fh, 1);
3686 $hash = $::_repository->hash_and_insert_object(
3687 Git::temp_path($fh));
3688 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
3690 Git::temp_release($fb->{base}, 1);
3691 Git::temp_release($fh, 1);
3692 } else {
3693 $hash = $fb->{blob} or die "no blob information\n";
3695 $fb->{pool}->clear;
3696 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
3697 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
3698 undef;
3701 sub abort_edit {
3702 my $self = shift;
3703 $self->{nr} = $self->{gii}->{nr};
3704 delete $self->{gii};
3705 $self->SUPER::abort_edit(@_);
3708 sub close_edit {
3709 my $self = shift;
3710 $self->{git_commit_ok} = 1;
3711 $self->{nr} = $self->{gii}->{nr};
3712 delete $self->{gii};
3713 $self->SUPER::close_edit(@_);
3716 package SVN::Git::Editor;
3717 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
3718 use strict;
3719 use warnings;
3720 use Carp qw/croak/;
3721 use IO::File;
3723 sub new {
3724 my ($class, $opts) = @_;
3725 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
3726 die "$_ required!\n" unless (defined $opts->{$_});
3729 my $pool = SVN::Pool->new;
3730 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
3731 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
3732 $opts->{r}, $mods);
3734 # $opts->{ra} functions should not be used after this:
3735 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
3736 $opts->{editor_cb}, $pool);
3737 my $self = SVN::Delta::Editor->new(@ce, $pool);
3738 bless $self, $class;
3739 foreach (qw/svn_path r tree_a tree_b/) {
3740 $self->{$_} = $opts->{$_};
3742 $self->{url} = $opts->{ra}->{url};
3743 $self->{mods} = $mods;
3744 $self->{types} = $types;
3745 $self->{pool} = $pool;
3746 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
3747 $self->{rm} = { };
3748 $self->{path_prefix} = length $self->{svn_path} ?
3749 "$self->{svn_path}/" : '';
3750 $self->{config} = $opts->{config};
3751 return $self;
3754 sub generate_diff {
3755 my ($tree_a, $tree_b) = @_;
3756 my @diff_tree = qw(diff-tree -z -r);
3757 if ($_cp_similarity) {
3758 push @diff_tree, "-C$_cp_similarity";
3759 } else {
3760 push @diff_tree, '-C';
3762 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
3763 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
3764 push @diff_tree, $tree_a, $tree_b;
3765 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
3766 local $/ = "\0";
3767 my $state = 'meta';
3768 my @mods;
3769 while (<$diff_fh>) {
3770 chomp $_; # this gets rid of the trailing "\0"
3771 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
3772 ($::sha1)\s($::sha1)\s
3773 ([MTCRAD])\d*$/xo) {
3774 push @mods, { mode_a => $1, mode_b => $2,
3775 sha1_a => $3, sha1_b => $4,
3776 chg => $5 };
3777 if ($5 =~ /^(?:C|R)$/) {
3778 $state = 'file_a';
3779 } else {
3780 $state = 'file_b';
3782 } elsif ($state eq 'file_a') {
3783 my $x = $mods[$#mods] or croak "Empty array\n";
3784 if ($x->{chg} !~ /^(?:C|R)$/) {
3785 croak "Error parsing $_, $x->{chg}\n";
3787 $x->{file_a} = $_;
3788 $state = 'file_b';
3789 } elsif ($state eq 'file_b') {
3790 my $x = $mods[$#mods] or croak "Empty array\n";
3791 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
3792 croak "Error parsing $_, $x->{chg}\n";
3794 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
3795 croak "Error parsing $_, $x->{chg}\n";
3797 $x->{file_b} = $_;
3798 $state = 'meta';
3799 } else {
3800 croak "Error parsing $_\n";
3803 command_close_pipe($diff_fh, $ctx);
3804 \@mods;
3807 sub check_diff_paths {
3808 my ($ra, $pfx, $rev, $mods) = @_;
3809 my %types;
3810 $pfx .= '/' if length $pfx;
3812 sub type_diff_paths {
3813 my ($ra, $types, $path, $rev) = @_;
3814 my @p = split m#/+#, $path;
3815 my $c = shift @p;
3816 unless (defined $types->{$c}) {
3817 $types->{$c} = $ra->check_path($c, $rev);
3819 while (@p) {
3820 $c .= '/' . shift @p;
3821 next if defined $types->{$c};
3822 $types->{$c} = $ra->check_path($c, $rev);
3826 foreach my $m (@$mods) {
3827 foreach my $f (qw/file_a file_b/) {
3828 next unless defined $m->{$f};
3829 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
3830 if (length $pfx.$dir && ! defined $types{$dir}) {
3831 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
3835 \%types;
3838 sub split_path {
3839 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
3842 sub repo_path {
3843 my ($self, $path) = @_;
3844 $self->{path_prefix}.(defined $path ? $path : '');
3847 sub url_path {
3848 my ($self, $path) = @_;
3849 if ($self->{url} =~ m#^https?://#) {
3850 $path =~ s/([^~a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
3852 $self->{url} . '/' . $self->repo_path($path);
3855 sub rmdirs {
3856 my ($self) = @_;
3857 my $rm = $self->{rm};
3858 delete $rm->{''}; # we never delete the url we're tracking
3859 return unless %$rm;
3861 foreach (keys %$rm) {
3862 my @d = split m#/#, $_;
3863 my $c = shift @d;
3864 $rm->{$c} = 1;
3865 while (@d) {
3866 $c .= '/' . shift @d;
3867 $rm->{$c} = 1;
3870 delete $rm->{$self->{svn_path}};
3871 delete $rm->{''}; # we never delete the url we're tracking
3872 return unless %$rm;
3874 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
3875 $self->{tree_b});
3876 local $/ = "\0";
3877 while (<$fh>) {
3878 chomp;
3879 my @dn = split m#/#, $_;
3880 while (pop @dn) {
3881 delete $rm->{join '/', @dn};
3883 unless (%$rm) {
3884 close $fh;
3885 return;
3888 command_close_pipe($fh, $ctx);
3890 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
3891 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
3892 $self->close_directory($bat->{$d}, $p);
3893 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
3894 print "\tD+\t$d/\n" unless $::_q;
3895 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
3896 delete $bat->{$d};
3900 sub open_or_add_dir {
3901 my ($self, $full_path, $baton) = @_;
3902 my $t = $self->{types}->{$full_path};
3903 if (!defined $t) {
3904 die "$full_path not known in r$self->{r} or we have a bug!\n";
3907 no warnings 'once';
3908 # SVN::Node::none and SVN::Node::file are used only once,
3909 # so we're shutting up Perl's warnings about them.
3910 if ($t == $SVN::Node::none) {
3911 return $self->add_directory($full_path, $baton,
3912 undef, -1, $self->{pool});
3913 } elsif ($t == $SVN::Node::dir) {
3914 return $self->open_directory($full_path, $baton,
3915 $self->{r}, $self->{pool});
3916 } # no warnings 'once'
3917 print STDERR "$full_path already exists in repository at ",
3918 "r$self->{r} and it is not a directory (",
3919 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
3920 } # no warnings 'once'
3921 exit 1;
3924 sub ensure_path {
3925 my ($self, $path) = @_;
3926 my $bat = $self->{bat};
3927 my $repo_path = $self->repo_path($path);
3928 return $bat->{''} unless (length $repo_path);
3929 my @p = split m#/+#, $repo_path;
3930 my $c = shift @p;
3931 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
3932 while (@p) {
3933 my $c0 = $c;
3934 $c .= '/' . shift @p;
3935 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
3937 return $bat->{$c};
3940 # Subroutine to convert a globbing pattern to a regular expression.
3941 # From perl cookbook.
3942 sub glob2pat {
3943 my $globstr = shift;
3944 my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
3945 $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
3946 return '^' . $globstr . '$';
3949 sub check_autoprop {
3950 my ($self, $pattern, $properties, $file, $fbat) = @_;
3951 # Convert the globbing pattern to a regular expression.
3952 my $regex = glob2pat($pattern);
3953 # Check if the pattern matches the file name.
3954 if($file =~ m/($regex)/) {
3955 # Parse the list of properties to set.
3956 my @props = split(/;/, $properties);
3957 foreach my $prop (@props) {
3958 # Parse 'name=value' syntax and set the property.
3959 if ($prop =~ /([^=]+)=(.*)/) {
3960 my ($n,$v) = ($1,$2);
3961 for ($n, $v) {
3962 s/^\s+//; s/\s+$//;
3964 $self->change_file_prop($fbat, $n, $v);
3970 sub apply_autoprops {
3971 my ($self, $file, $fbat) = @_;
3972 my $conf_t = ${$self->{config}}{'config'};
3973 no warnings 'once';
3974 # Check [miscellany]/enable-auto-props in svn configuration.
3975 if (SVN::_Core::svn_config_get_bool(
3976 $conf_t,
3977 $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
3978 $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
3979 0)) {
3980 # Auto-props are enabled. Enumerate them to look for matches.
3981 my $callback = sub {
3982 $self->check_autoprop($_[0], $_[1], $file, $fbat);
3984 SVN::_Core::svn_config_enumerate(
3985 $conf_t,
3986 $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
3987 $callback);
3991 sub A {
3992 my ($self, $m) = @_;
3993 my ($dir, $file) = split_path($m->{file_b});
3994 my $pbat = $self->ensure_path($dir);
3995 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3996 undef, -1);
3997 print "\tA\t$m->{file_b}\n" unless $::_q;
3998 $self->apply_autoprops($file, $fbat);
3999 $self->chg_file($fbat, $m);
4000 $self->close_file($fbat,undef,$self->{pool});
4003 sub C {
4004 my ($self, $m) = @_;
4005 my ($dir, $file) = split_path($m->{file_b});
4006 my $pbat = $self->ensure_path($dir);
4007 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4008 $self->url_path($m->{file_a}), $self->{r});
4009 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
4010 $self->chg_file($fbat, $m);
4011 $self->close_file($fbat,undef,$self->{pool});
4014 sub delete_entry {
4015 my ($self, $path, $pbat) = @_;
4016 my $rpath = $self->repo_path($path);
4017 my ($dir, $file) = split_path($rpath);
4018 $self->{rm}->{$dir} = 1;
4019 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
4022 sub R {
4023 my ($self, $m) = @_;
4024 my ($dir, $file) = split_path($m->{file_b});
4025 my $pbat = $self->ensure_path($dir);
4026 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4027 $self->url_path($m->{file_a}), $self->{r});
4028 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
4029 $self->apply_autoprops($file, $fbat);
4030 $self->chg_file($fbat, $m);
4031 $self->close_file($fbat,undef,$self->{pool});
4033 ($dir, $file) = split_path($m->{file_a});
4034 $pbat = $self->ensure_path($dir);
4035 $self->delete_entry($m->{file_a}, $pbat);
4038 sub M {
4039 my ($self, $m) = @_;
4040 my ($dir, $file) = split_path($m->{file_b});
4041 my $pbat = $self->ensure_path($dir);
4042 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
4043 $pbat,$self->{r},$self->{pool});
4044 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
4045 $self->chg_file($fbat, $m);
4046 $self->close_file($fbat,undef,$self->{pool});
4049 sub T { shift->M(@_) }
4051 sub change_file_prop {
4052 my ($self, $fbat, $pname, $pval) = @_;
4053 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
4056 sub _chg_file_get_blob ($$$$) {
4057 my ($self, $fbat, $m, $which) = @_;
4058 my $fh = $::_repository->temp_acquire("git_blob_$which");
4059 if ($m->{"mode_$which"} =~ /^120/) {
4060 print $fh 'link ' or croak $!;
4061 $self->change_file_prop($fbat,'svn:special','*');
4062 } elsif ($m->{mode_a} =~ /^120/ && $m->{"mode_$which"} !~ /^120/) {
4063 $self->change_file_prop($fbat,'svn:special',undef);
4065 my $blob = $m->{"sha1_$which"};
4066 return ($fh,) if ($blob =~ /^0{40}$/);
4067 my $size = $::_repository->cat_blob($blob, $fh);
4068 croak "Failed to read object $blob" if ($size < 0);
4069 $fh->flush == 0 or croak $!;
4070 seek $fh, 0, 0 or croak $!;
4072 my $exp = ::md5sum($fh);
4073 seek $fh, 0, 0 or croak $!;
4074 return ($fh, $exp);
4077 sub chg_file {
4078 my ($self, $fbat, $m) = @_;
4079 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
4080 $self->change_file_prop($fbat,'svn:executable','*');
4081 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
4082 $self->change_file_prop($fbat,'svn:executable',undef);
4084 my ($fh_a, $exp_a) = _chg_file_get_blob $self, $fbat, $m, 'a';
4085 my ($fh_b, $exp_b) = _chg_file_get_blob $self, $fbat, $m, 'b';
4086 my $pool = SVN::Pool->new;
4087 my $atd = $self->apply_textdelta($fbat, $exp_a, $pool);
4088 if (-s $fh_a) {
4089 my $txstream = SVN::TxDelta::new ($fh_a, $fh_b, $pool);
4090 my $res = SVN::TxDelta::send_txstream($txstream, @$atd, $pool);
4091 if (defined $res) {
4092 die "Unexpected result from send_txstream: $res\n",
4093 "(SVN::Core::VERSION: $SVN::Core::VERSION)\n";
4095 } else {
4096 my $got = SVN::TxDelta::send_stream($fh_b, @$atd, $pool);
4097 die "Checksum mismatch\nexpected: $exp_b\ngot: $got\n"
4098 if ($got ne $exp_b);
4100 Git::temp_release($fh_b, 1);
4101 Git::temp_release($fh_a, 1);
4102 $pool->clear;
4105 sub D {
4106 my ($self, $m) = @_;
4107 my ($dir, $file) = split_path($m->{file_b});
4108 my $pbat = $self->ensure_path($dir);
4109 print "\tD\t$m->{file_b}\n" unless $::_q;
4110 $self->delete_entry($m->{file_b}, $pbat);
4113 sub close_edit {
4114 my ($self) = @_;
4115 my ($p,$bat) = ($self->{pool}, $self->{bat});
4116 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
4117 next if $_ eq '';
4118 $self->close_directory($bat->{$_}, $p);
4120 $self->close_directory($bat->{''}, $p);
4121 $self->SUPER::close_edit($p);
4122 $p->clear;
4125 sub abort_edit {
4126 my ($self) = @_;
4127 $self->SUPER::abort_edit($self->{pool});
4130 sub DESTROY {
4131 my $self = shift;
4132 $self->SUPER::DESTROY(@_);
4133 $self->{pool}->clear;
4136 # this drives the editor
4137 sub apply_diff {
4138 my ($self) = @_;
4139 my $mods = $self->{mods};
4140 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
4141 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
4142 my $f = $m->{chg};
4143 if (defined $o{$f}) {
4144 $self->$f($m);
4145 } else {
4146 fatal("Invalid change type: $f");
4149 $self->rmdirs if $_rmdir;
4150 if (@$mods == 0) {
4151 $self->abort_edit;
4152 } else {
4153 $self->close_edit;
4155 return scalar @$mods;
4158 package Git::SVN::Ra;
4159 use vars qw/@ISA $config_dir $_log_window_size/;
4160 use strict;
4161 use warnings;
4162 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
4164 BEGIN {
4165 # enforce temporary pool usage for some simple functions
4166 no strict 'refs';
4167 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root
4168 get_file/) {
4169 my $SUPER = "SUPER::$f";
4170 *$f = sub {
4171 my $self = shift;
4172 my $pool = SVN::Pool->new;
4173 my @ret = $self->$SUPER(@_,$pool);
4174 $pool->clear;
4175 wantarray ? @ret : $ret[0];
4180 sub _auth_providers () {
4182 SVN::Client::get_simple_provider(),
4183 SVN::Client::get_ssl_server_trust_file_provider(),
4184 SVN::Client::get_simple_prompt_provider(
4185 \&Git::SVN::Prompt::simple, 2),
4186 SVN::Client::get_ssl_client_cert_file_provider(),
4187 SVN::Client::get_ssl_client_cert_prompt_provider(
4188 \&Git::SVN::Prompt::ssl_client_cert, 2),
4189 SVN::Client::get_ssl_client_cert_pw_file_provider(),
4190 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
4191 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
4192 SVN::Client::get_username_provider(),
4193 SVN::Client::get_ssl_server_trust_prompt_provider(
4194 \&Git::SVN::Prompt::ssl_server_trust),
4195 SVN::Client::get_username_prompt_provider(
4196 \&Git::SVN::Prompt::username, 2)
4200 sub escape_uri_only {
4201 my ($uri) = @_;
4202 my @tmp;
4203 foreach (split m{/}, $uri) {
4204 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
4205 push @tmp, $_;
4207 join('/', @tmp);
4210 sub escape_url {
4211 my ($url) = @_;
4212 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
4213 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
4214 $url = "$scheme://$domain$uri";
4216 $url;
4219 sub new {
4220 my ($class, $url) = @_;
4221 $url =~ s!/+$!!;
4222 return $RA if ($RA && $RA->{url} eq $url);
4224 SVN::_Core::svn_config_ensure($config_dir, undef);
4225 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
4226 my $config = SVN::Core::config_get_config($config_dir);
4227 $RA = undef;
4228 my $dont_store_passwords = 1;
4229 my $conf_t = ${$config}{'config'};
4231 no warnings 'once';
4232 # The usage of $SVN::_Core::SVN_CONFIG_* variables
4233 # produces warnings that variables are used only once.
4234 # I had not found the better way to shut them up, so
4235 # the warnings of type 'once' are disabled in this block.
4236 if (SVN::_Core::svn_config_get_bool($conf_t,
4237 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4238 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
4239 1) == 0) {
4240 SVN::_Core::svn_auth_set_parameter($baton,
4241 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
4242 bless (\$dont_store_passwords, "_p_void"));
4244 if (SVN::_Core::svn_config_get_bool($conf_t,
4245 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4246 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
4247 1) == 0) {
4248 $Git::SVN::Prompt::_no_auth_cache = 1;
4250 } # no warnings 'once'
4251 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
4252 config => $config,
4253 pool => SVN::Pool->new,
4254 auth_provider_callbacks => $callbacks);
4255 $self->{url} = $url;
4256 $self->{svn_path} = $url;
4257 $self->{repos_root} = $self->get_repos_root;
4258 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
4259 $self->{cache} = { check_path => { r => 0, data => {} },
4260 get_dir => { r => 0, data => {} } };
4261 $RA = bless $self, $class;
4264 sub check_path {
4265 my ($self, $path, $r) = @_;
4266 my $cache = $self->{cache}->{check_path};
4267 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
4268 return $cache->{data}->{$path};
4270 my $pool = SVN::Pool->new;
4271 my $t = $self->SUPER::check_path($path, $r, $pool);
4272 $pool->clear;
4273 if ($r != $cache->{r}) {
4274 %{$cache->{data}} = ();
4275 $cache->{r} = $r;
4277 $cache->{data}->{$path} = $t;
4280 sub get_dir {
4281 my ($self, $dir, $r) = @_;
4282 my $cache = $self->{cache}->{get_dir};
4283 if ($r == $cache->{r}) {
4284 if (my $x = $cache->{data}->{$dir}) {
4285 return wantarray ? @$x : $x->[0];
4288 my $pool = SVN::Pool->new;
4289 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
4290 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
4291 $pool->clear;
4292 if ($r != $cache->{r}) {
4293 %{$cache->{data}} = ();
4294 $cache->{r} = $r;
4296 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
4297 wantarray ? (\%dirents, $r, $props) : \%dirents;
4300 sub DESTROY {
4301 # do not call the real DESTROY since we store ourselves in $RA
4304 # get_log(paths, start, end, limit,
4305 # discover_changed_paths, strict_node_history, receiver)
4306 sub get_log {
4307 my ($self, @args) = @_;
4308 my $pool = SVN::Pool->new;
4310 # the limit parameter was not supported in SVN 1.1.x, so we
4311 # drop it. Therefore, the receiver callback passed to it
4312 # is made aware of this limitation by being wrapped if
4313 # the limit passed to is being wrapped.
4314 if ($SVN::Core::VERSION le '1.2.0') {
4315 my $limit = splice(@args, 3, 1);
4316 if ($limit > 0) {
4317 my $receiver = pop @args;
4318 push(@args, sub { &$receiver(@_) if (--$limit >= 0) });
4321 my $ret = $self->SUPER::get_log(@args, $pool);
4322 $pool->clear;
4323 $ret;
4326 sub trees_match {
4327 my ($self, $url1, $rev1, $url2, $rev2) = @_;
4328 my $ctx = SVN::Client->new(auth => _auth_providers);
4329 my $out = IO::File->new_tmpfile;
4331 # older SVN (1.1.x) doesn't take $pool as the last parameter for
4332 # $ctx->diff(), so we'll create a default one
4333 my $pool = SVN::Pool->new_default_sub;
4335 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
4336 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
4337 $out->flush;
4338 my $ret = (($out->stat)[7] == 0);
4339 close $out or croak $!;
4341 $ret;
4344 sub get_commit_editor {
4345 my ($self, $log, $cb, $pool) = @_;
4346 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
4347 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
4350 sub gs_do_update {
4351 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
4352 my $new = ($rev_a == $rev_b);
4353 my $path = $gs->{path};
4355 if ($new && -e $gs->{index}) {
4356 unlink $gs->{index} or die
4357 "Couldn't unlink index: $gs->{index}: $!\n";
4359 my $pool = SVN::Pool->new;
4360 $editor->set_path_strip($path);
4361 my (@pc) = split m#/#, $path;
4362 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
4363 1, $editor, $pool);
4364 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4366 # Since we can't rely on svn_ra_reparent being available, we'll
4367 # just have to do some magic with set_path to make it so
4368 # we only want a partial path.
4369 my $sp = '';
4370 my $final = join('/', @pc);
4371 while (@pc) {
4372 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
4373 $sp .= '/' if length $sp;
4374 $sp .= shift @pc;
4376 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
4378 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
4380 $reporter->finish_report($pool);
4381 $pool->clear;
4382 $editor->{git_commit_ok};
4385 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
4386 # svn_ra_reparent didn't work before 1.4)
4387 sub gs_do_switch {
4388 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
4389 my $path = $gs->{path};
4390 my $pool = SVN::Pool->new;
4392 my $full_url = $self->{url};
4393 my $old_url = $full_url;
4394 $full_url .= '/' . escape_uri_only($path) if length $path;
4395 my ($ra, $reparented);
4397 if ($old_url =~ m#^svn(\+ssh)?://#) {
4398 $_[0] = undef;
4399 $self = undef;
4400 $RA = undef;
4401 $ra = Git::SVN::Ra->new($full_url);
4402 $ra_invalid = 1;
4403 } elsif ($old_url ne $full_url) {
4404 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url, $pool);
4405 $self->{url} = $full_url;
4406 $reparented = 1;
4409 $ra ||= $self;
4410 $url_b = escape_url($url_b);
4411 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
4412 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4413 $reporter->set_path('', $rev_a, 0, @lock, $pool);
4414 $reporter->finish_report($pool);
4416 if ($reparented) {
4417 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
4418 $self->{url} = $old_url;
4421 $pool->clear;
4422 $editor->{git_commit_ok};
4425 sub longest_common_path {
4426 my ($gsv, $globs) = @_;
4427 my %common;
4428 my $common_max = scalar @$gsv;
4430 foreach my $gs (@$gsv) {
4431 my @tmp = split m#/#, $gs->{path};
4432 my $p = '';
4433 foreach (@tmp) {
4434 $p .= length($p) ? "/$_" : $_;
4435 $common{$p} ||= 0;
4436 $common{$p}++;
4439 $globs ||= [];
4440 $common_max += scalar @$globs;
4441 foreach my $glob (@$globs) {
4442 my @tmp = split m#/#, $glob->{path}->{left};
4443 my $p = '';
4444 foreach (@tmp) {
4445 $p .= length($p) ? "/$_" : $_;
4446 $common{$p} ||= 0;
4447 $common{$p}++;
4451 my $longest_path = '';
4452 foreach (sort {length $b <=> length $a} keys %common) {
4453 if ($common{$_} == $common_max) {
4454 $longest_path = $_;
4455 last;
4458 $longest_path;
4461 sub gs_fetch_loop_common {
4462 my ($self, $base, $head, $gsv, $globs) = @_;
4463 return if ($base > $head);
4464 my $inc = $_log_window_size;
4465 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
4466 my $longest_path = longest_common_path($gsv, $globs);
4467 my $ra_url = $self->{url};
4468 my $find_trailing_edge;
4469 while (1) {
4470 my %revs;
4471 my $err;
4472 my $err_handler = $SVN::Error::handler;
4473 $SVN::Error::handler = sub {
4474 ($err) = @_;
4475 skip_unknown_revs($err);
4477 sub _cb {
4478 my ($paths, $r, $author, $date, $log) = @_;
4479 [ dup_changed_paths($paths),
4480 { author => $author, date => $date, log => $log } ];
4482 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
4483 sub { $revs{$_[1]} = _cb(@_) });
4484 if ($err) {
4485 print "Checked through r$max\r";
4486 } else {
4487 $find_trailing_edge = 1;
4489 if ($err and $find_trailing_edge) {
4490 print STDERR "Path '$longest_path' ",
4491 "was probably deleted:\n",
4492 $err->expanded_message,
4493 "\nWill attempt to follow ",
4494 "revisions r$min .. r$max ",
4495 "committed before the deletion\n";
4496 my $hi = $max;
4497 while (--$hi >= $min) {
4498 my $ok;
4499 $self->get_log([$longest_path], $min, $hi,
4500 0, 1, 1, sub {
4501 $ok = $_[1];
4502 $revs{$_[1]} = _cb(@_) });
4503 if ($ok) {
4504 print STDERR "r$min .. r$ok OK\n";
4505 last;
4508 $find_trailing_edge = 0;
4510 $SVN::Error::handler = $err_handler;
4512 my %exists = map { $_->{path} => $_ } @$gsv;
4513 foreach my $r (sort {$a <=> $b} keys %revs) {
4514 my ($paths, $logged) = @{$revs{$r}};
4516 foreach my $gs ($self->match_globs(\%exists, $paths,
4517 $globs, $r)) {
4518 if ($gs->rev_map_max >= $r) {
4519 next;
4521 next unless $gs->match_paths($paths, $r);
4522 $gs->{logged_rev_props} = $logged;
4523 if (my $last_commit = $gs->last_commit) {
4524 $gs->assert_index_clean($last_commit);
4526 my $log_entry = $gs->do_fetch($paths, $r);
4527 if ($log_entry) {
4528 $gs->do_git_commit($log_entry);
4530 $INDEX_FILES{$gs->{index}} = 1;
4532 foreach my $g (@$globs) {
4533 my $k = "svn-remote.$g->{remote}." .
4534 "$g->{t}-maxRev";
4535 Git::SVN::tmp_config($k, $r);
4537 if ($ra_invalid) {
4538 $_[0] = undef;
4539 $self = undef;
4540 $RA = undef;
4541 $self = Git::SVN::Ra->new($ra_url);
4542 $ra_invalid = undef;
4545 # pre-fill the .rev_db since it'll eventually get filled in
4546 # with '0' x40 if something new gets committed
4547 foreach my $gs (@$gsv) {
4548 next if $gs->rev_map_max >= $max;
4549 next if defined $gs->rev_map_get($max);
4550 $gs->rev_map_set($max, 0 x40);
4552 foreach my $g (@$globs) {
4553 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
4554 Git::SVN::tmp_config($k, $max);
4556 last if $max >= $head;
4557 $min = $max + 1;
4558 $max += $inc;
4559 $max = $head if ($max > $head);
4561 Git::SVN::gc();
4564 sub get_dir_globbed {
4565 my ($self, $left, $depth, $r) = @_;
4567 my @x = eval { $self->get_dir($left, $r) };
4568 return unless scalar @x == 3;
4569 my $dirents = $x[0];
4570 my @finalents;
4571 foreach my $de (keys %$dirents) {
4572 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
4573 if ($depth > 1) {
4574 my @args = ("$left/$de", $depth - 1, $r);
4575 foreach my $dir ($self->get_dir_globbed(@args)) {
4576 push @finalents, "$de/$dir";
4578 } else {
4579 push @finalents, $de;
4582 @finalents;
4585 sub match_globs {
4586 my ($self, $exists, $paths, $globs, $r) = @_;
4588 sub get_dir_check {
4589 my ($self, $exists, $g, $r) = @_;
4591 my @dirs = $self->get_dir_globbed($g->{path}->{left},
4592 $g->{path}->{depth},
4593 $r);
4595 foreach my $de (@dirs) {
4596 my $p = $g->{path}->full_path($de);
4597 next if $exists->{$p};
4598 next if (length $g->{path}->{right} &&
4599 ($self->check_path($p, $r) !=
4600 $SVN::Node::dir));
4601 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
4602 $g->{ref}->full_path($de), 1);
4605 foreach my $g (@$globs) {
4606 if (my $path = $paths->{"/$g->{path}->{left}"}) {
4607 if ($path->{action} =~ /^[AR]$/) {
4608 get_dir_check($self, $exists, $g, $r);
4611 foreach (keys %$paths) {
4612 if (/$g->{path}->{left_regex}/ &&
4613 !/$g->{path}->{regex}/) {
4614 next if $paths->{$_}->{action} !~ /^[AR]$/;
4615 get_dir_check($self, $exists, $g, $r);
4617 next unless /$g->{path}->{regex}/;
4618 my $p = $1;
4619 my $pathname = $g->{path}->full_path($p);
4620 next if $exists->{$pathname};
4621 next if ($self->check_path($pathname, $r) !=
4622 $SVN::Node::dir);
4623 $exists->{$pathname} = Git::SVN->init(
4624 $self->{url}, $pathname, undef,
4625 $g->{ref}->full_path($p), 1);
4627 my $c = '';
4628 foreach (split m#/#, $g->{path}->{left}) {
4629 $c .= "/$_";
4630 next unless ($paths->{$c} &&
4631 ($paths->{$c}->{action} =~ /^[AR]$/));
4632 get_dir_check($self, $exists, $g, $r);
4635 values %$exists;
4638 sub minimize_url {
4639 my ($self) = @_;
4640 return $self->{url} if ($self->{url} eq $self->{repos_root});
4641 my $url = $self->{repos_root};
4642 my @components = split(m!/!, $self->{svn_path});
4643 my $c = '';
4644 do {
4645 $url .= "/$c" if length $c;
4646 eval { (ref $self)->new($url)->get_latest_revnum };
4647 } while ($@ && ($c = shift @components));
4648 $url;
4651 sub can_do_switch {
4652 my $self = shift;
4653 unless (defined $can_do_switch) {
4654 my $pool = SVN::Pool->new;
4655 my $rep = eval {
4656 $self->do_switch(1, '', 0, $self->{url},
4657 SVN::Delta::Editor->new, $pool);
4659 if ($@) {
4660 $can_do_switch = 0;
4661 } else {
4662 $rep->abort_report($pool);
4663 $can_do_switch = 1;
4665 $pool->clear;
4667 $can_do_switch;
4670 sub skip_unknown_revs {
4671 my ($err) = @_;
4672 my $errno = $err->apr_err();
4673 # Maybe the branch we're tracking didn't
4674 # exist when the repo started, so it's
4675 # not an error if it doesn't, just continue
4677 # Wonderfully consistent library, eh?
4678 # 160013 - svn:// and file://
4679 # 175002 - http(s)://
4680 # 175007 - http(s):// (this repo required authorization, too...)
4681 # More codes may be discovered later...
4682 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
4683 my $err_key = $err->expanded_message;
4684 # revision numbers change every time, filter them out
4685 $err_key =~ s/\d+/\0/g;
4686 $err_key = "$errno\0$err_key";
4687 unless ($ignored_err{$err_key}) {
4688 warn "W: Ignoring error from SVN, path probably ",
4689 "does not exist: ($errno): ",
4690 $err->expanded_message,"\n";
4691 warn "W: Do not be alarmed at the above message ",
4692 "git-svn is just searching aggressively for ",
4693 "old history.\n",
4694 "This may take a while on large repositories\n";
4695 $ignored_err{$err_key} = 1;
4697 return;
4699 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
4702 # svn_log_changed_path_t objects passed to get_log are likely to be
4703 # overwritten even if only the refs are copied to an external variable,
4704 # so we should dup the structures in their entirety. Using an externally
4705 # passed pool (instead of our temporary and quickly cleared pool in
4706 # Git::SVN::Ra) does not help matters at all...
4707 sub dup_changed_paths {
4708 my ($paths) = @_;
4709 return undef unless $paths;
4710 my %ret;
4711 foreach my $p (keys %$paths) {
4712 my $i = $paths->{$p};
4713 my %s = map { $_ => $i->$_ }
4714 qw/copyfrom_path copyfrom_rev action/;
4715 $ret{$p} = \%s;
4717 \%ret;
4720 package Git::SVN::Log;
4721 use strict;
4722 use warnings;
4723 use POSIX qw/strftime/;
4724 use Time::Local;
4725 use constant commit_log_separator => ('-' x 72) . "\n";
4726 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
4727 %rusers $show_commit $incremental/;
4728 my $l_fmt;
4730 sub cmt_showable {
4731 my ($c) = @_;
4732 return 1 if defined $c->{r};
4734 # big commit message got truncated by the 16k pretty buffer in rev-list
4735 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
4736 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
4737 @{$c->{l}} = ();
4738 my @log = command(qw/cat-file commit/, $c->{c});
4740 # shift off the headers
4741 shift @log while ($log[0] ne '');
4742 shift @log;
4744 # TODO: make $c->{l} not have a trailing newline in the future
4745 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
4747 (undef, $c->{r}, undef) = ::extract_metadata(
4748 (grep(/^git-svn-id: /, @log))[-1]);
4750 return defined $c->{r};
4753 sub log_use_color {
4754 return $color || Git->repository->get_colorbool('color.diff');
4757 sub git_svn_log_cmd {
4758 my ($r_min, $r_max, @args) = @_;
4759 my $head = 'HEAD';
4760 my (@files, @log_opts);
4761 foreach my $x (@args) {
4762 if ($x eq '--' || @files) {
4763 push @files, $x;
4764 } else {
4765 if (::verify_ref("$x^0")) {
4766 $head = $x;
4767 } else {
4768 push @log_opts, $x;
4773 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
4774 $gs ||= Git::SVN->_new;
4775 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
4776 $gs->refname);
4777 push @cmd, '-r' unless $non_recursive;
4778 push @cmd, qw/--raw --name-status/ if $verbose;
4779 push @cmd, '--color' if log_use_color();
4780 push @cmd, @log_opts;
4781 if (defined $r_max && $r_max == $r_min) {
4782 push @cmd, '--max-count=1';
4783 if (my $c = $gs->rev_map_get($r_max)) {
4784 push @cmd, $c;
4786 } elsif (defined $r_max) {
4787 if ($r_max < $r_min) {
4788 ($r_min, $r_max) = ($r_max, $r_min);
4790 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
4791 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
4792 # If there are no commits in the range, both $c_max and $c_min
4793 # will be undefined. If there is at least 1 commit in the
4794 # range, both will be defined.
4795 return () if !defined $c_min || !defined $c_max;
4796 if ($c_min eq $c_max) {
4797 push @cmd, '--max-count=1', $c_min;
4798 } else {
4799 push @cmd, '--boundary', "$c_min..$c_max";
4802 return (@cmd, @files);
4805 # adapted from pager.c
4806 sub config_pager {
4807 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
4808 if (!defined $pager) {
4809 $pager = 'less';
4810 } elsif (length $pager == 0 || $pager eq 'cat') {
4811 $pager = undef;
4813 $ENV{GIT_PAGER_IN_USE} = defined($pager);
4816 sub run_pager {
4817 return unless -t *STDOUT && defined $pager;
4818 pipe my ($rfd, $wfd) or return;
4819 defined(my $pid = fork) or ::fatal "Can't fork: $!";
4820 if (!$pid) {
4821 open STDOUT, '>&', $wfd or
4822 ::fatal "Can't redirect to stdout: $!";
4823 return;
4825 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
4826 $ENV{LESS} ||= 'FRSX';
4827 exec $pager or ::fatal "Can't run pager: $! ($pager)";
4830 sub format_svn_date {
4831 # some systmes don't handle or mishandle %z, so be creative.
4832 my $t = shift || time;
4833 my $gm = timelocal(gmtime($t));
4834 my $sign = qw( + + - )[ $t <=> $gm ];
4835 my $gmoff = sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
4836 return strftime("%Y-%m-%d %H:%M:%S $gmoff (%a, %d %b %Y)", localtime($t));
4839 sub parse_git_date {
4840 my ($t, $tz) = @_;
4841 # Date::Parse isn't in the standard Perl distro :(
4842 if ($tz =~ s/^\+//) {
4843 $t += tz_to_s_offset($tz);
4844 } elsif ($tz =~ s/^\-//) {
4845 $t -= tz_to_s_offset($tz);
4847 return $t;
4850 sub set_local_timezone {
4851 if (defined $TZ) {
4852 $ENV{TZ} = $TZ;
4853 } else {
4854 delete $ENV{TZ};
4858 sub tz_to_s_offset {
4859 my ($tz) = @_;
4860 $tz =~ s/(\d\d)$//;
4861 return ($1 * 60) + ($tz * 3600);
4864 sub get_author_info {
4865 my ($dest, $author, $t, $tz) = @_;
4866 $author =~ s/(?:^\s*|\s*$)//g;
4867 $dest->{a_raw} = $author;
4868 my $au;
4869 if ($::_authors) {
4870 $au = $rusers{$author} || undef;
4872 if (!$au) {
4873 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
4875 $dest->{t} = $t;
4876 $dest->{tz} = $tz;
4877 $dest->{a} = $au;
4878 $dest->{t_utc} = parse_git_date($t, $tz);
4881 sub process_commit {
4882 my ($c, $r_min, $r_max, $defer) = @_;
4883 if (defined $r_min && defined $r_max) {
4884 if ($r_min == $c->{r} && $r_min == $r_max) {
4885 show_commit($c);
4886 return 0;
4888 return 1 if $r_min == $r_max;
4889 if ($r_min < $r_max) {
4890 # we need to reverse the print order
4891 return 0 if (defined $limit && --$limit < 0);
4892 push @$defer, $c;
4893 return 1;
4895 if ($r_min != $r_max) {
4896 return 1 if ($r_min < $c->{r});
4897 return 1 if ($r_max > $c->{r});
4900 return 0 if (defined $limit && --$limit < 0);
4901 show_commit($c);
4902 return 1;
4905 sub show_commit {
4906 my $c = shift;
4907 if ($oneline) {
4908 my $x = "\n";
4909 if (my $l = $c->{l}) {
4910 while ($l->[0] =~ /^\s*$/) { shift @$l }
4911 $x = $l->[0];
4913 $l_fmt ||= 'A' . length($c->{r});
4914 print 'r',pack($l_fmt, $c->{r}),' | ';
4915 print "$c->{c} | " if $show_commit;
4916 print $x;
4917 } else {
4918 show_commit_normal($c);
4922 sub show_commit_changed_paths {
4923 my ($c) = @_;
4924 return unless $c->{changed};
4925 print "Changed paths:\n", @{$c->{changed}};
4928 sub show_commit_normal {
4929 my ($c) = @_;
4930 print commit_log_separator, "r$c->{r} | ";
4931 print "$c->{c} | " if $show_commit;
4932 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
4933 my $nr_line = 0;
4935 if (my $l = $c->{l}) {
4936 while ($l->[$#$l] eq "\n" && $#$l > 0
4937 && $l->[($#$l - 1)] eq "\n") {
4938 pop @$l;
4940 $nr_line = scalar @$l;
4941 if (!$nr_line) {
4942 print "1 line\n\n\n";
4943 } else {
4944 if ($nr_line == 1) {
4945 $nr_line = '1 line';
4946 } else {
4947 $nr_line .= ' lines';
4949 print $nr_line, "\n";
4950 show_commit_changed_paths($c);
4951 print "\n";
4952 print $_ foreach @$l;
4954 } else {
4955 print "1 line\n";
4956 show_commit_changed_paths($c);
4957 print "\n";
4960 foreach my $x (qw/raw stat diff/) {
4961 if ($c->{$x}) {
4962 print "\n";
4963 print $_ foreach @{$c->{$x}}
4968 sub cmd_show_log {
4969 my (@args) = @_;
4970 my ($r_min, $r_max);
4971 my $r_last = -1; # prevent dupes
4972 set_local_timezone();
4973 if (defined $::_revision) {
4974 if ($::_revision =~ /^(\d+):(\d+)$/) {
4975 ($r_min, $r_max) = ($1, $2);
4976 } elsif ($::_revision =~ /^\d+$/) {
4977 $r_min = $r_max = $::_revision;
4978 } else {
4979 ::fatal "-r$::_revision is not supported, use ",
4980 "standard 'git log' arguments instead";
4984 config_pager();
4985 @args = git_svn_log_cmd($r_min, $r_max, @args);
4986 if (!@args) {
4987 print commit_log_separator unless $incremental || $oneline;
4988 return;
4990 my $log = command_output_pipe(@args);
4991 run_pager();
4992 my (@k, $c, $d, $stat);
4993 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
4994 while (<$log>) {
4995 if (/^${esc_color}commit -?($::sha1_short)/o) {
4996 my $cmt = $1;
4997 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
4998 $r_last = $c->{r};
4999 process_commit($c, $r_min, $r_max, \@k) or
5000 goto out;
5002 $d = undef;
5003 $c = { c => $cmt };
5004 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
5005 get_author_info($c, $1, $2, $3);
5006 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
5007 # ignore
5008 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
5009 push @{$c->{raw}}, $_;
5010 } elsif (/^${esc_color}[ACRMDT]\t/) {
5011 # we could add $SVN->{svn_path} here, but that requires
5012 # remote access at the moment (repo_path_split)...
5013 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
5014 push @{$c->{changed}}, $_;
5015 } elsif (/^${esc_color}diff /o) {
5016 $d = 1;
5017 push @{$c->{diff}}, $_;
5018 } elsif ($d) {
5019 push @{$c->{diff}}, $_;
5020 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
5021 $esc_color*[\+\-]*$esc_color$/x) {
5022 $stat = 1;
5023 push @{$c->{stat}}, $_;
5024 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
5025 push @{$c->{stat}}, $_;
5026 $stat = undef;
5027 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
5028 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
5029 } elsif (s/^${esc_color} //o) {
5030 push @{$c->{l}}, $_;
5033 if ($c && defined $c->{r} && $c->{r} != $r_last) {
5034 $r_last = $c->{r};
5035 process_commit($c, $r_min, $r_max, \@k);
5037 if (@k) {
5038 ($r_min, $r_max) = ($r_max, $r_min);
5039 process_commit($_, $r_min, $r_max) foreach reverse @k;
5041 out:
5042 close $log;
5043 print commit_log_separator unless $incremental || $oneline;
5046 sub cmd_blame {
5047 my $path = pop;
5049 config_pager();
5050 run_pager();
5052 my ($fh, $ctx, $rev);
5054 if ($_git_format) {
5055 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
5056 while (my $line = <$fh>) {
5057 if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
5058 # Uncommitted edits show up as a rev ID of
5059 # all zeros, which we can't look up with
5060 # cmt_metadata
5061 if ($1 !~ /^0+$/) {
5062 (undef, $rev, undef) =
5063 ::cmt_metadata($1);
5064 $rev = '0' if (!$rev);
5065 } else {
5066 $rev = '0';
5068 $rev = sprintf('%-10s', $rev);
5069 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
5071 print $line;
5073 } else {
5074 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
5075 '--', $path);
5076 my ($sha1);
5077 my %authors;
5078 my @buffer;
5079 my %dsha; #distinct sha keys
5081 while (my $line = <$fh>) {
5082 push @buffer, $line;
5083 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5084 $dsha{$1} = 1;
5088 my $s2r = ::cmt_sha2rev_batch([keys %dsha]);
5090 foreach my $line (@buffer) {
5091 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5092 $rev = $s2r->{$1};
5093 $rev = '0' if (!$rev)
5095 elsif ($line =~ /^author (.*)/) {
5096 $authors{$rev} = $1;
5097 $authors{$rev} =~ s/\s/_/g;
5099 elsif ($line =~ /^\t(.*)$/) {
5100 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
5104 command_close_pipe($fh, $ctx);
5107 package Git::SVN::Migration;
5108 # these version numbers do NOT correspond to actual version numbers
5109 # of git nor git-svn. They are just relative.
5111 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
5113 # v1 layout: .git/$id/info/url, refs/remotes/$id
5115 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
5117 # v3 layout: .git/svn/$id, refs/remotes/$id
5118 # - info/url may remain for backwards compatibility
5119 # - this is what we migrate up to this layout automatically,
5120 # - this will be used by git svn init on single branches
5121 # v3.1 layout (auto migrated):
5122 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
5123 # for backwards compatibility
5125 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
5126 # - this is only created for newly multi-init-ed
5127 # repositories. Similar in spirit to the
5128 # --use-separate-remotes option in git-clone (now default)
5129 # - we do not automatically migrate to this (following
5130 # the example set by core git)
5132 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
5133 # - newer, more-efficient format that uses 24-bytes per record
5134 # with no filler space.
5135 # - use xxd -c24 < .rev_map.$UUID to view and debug
5136 # - This is a one-way migration, repositories updated to the
5137 # new format will not be able to use old git-svn without
5138 # rebuilding the .rev_db. Rebuilding the rev_db is not
5139 # possible if noMetadata or useSvmProps are set; but should
5140 # be no problem for users that use the (sensible) defaults.
5141 use strict;
5142 use warnings;
5143 use Carp qw/croak/;
5144 use File::Path qw/mkpath/;
5145 use File::Basename qw/dirname basename/;
5146 use vars qw/$_minimize/;
5148 sub migrate_from_v0 {
5149 my $git_dir = $ENV{GIT_DIR};
5150 return undef unless -d $git_dir;
5151 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5152 my $migrated = 0;
5153 while (<$fh>) {
5154 chomp;
5155 my ($id, $orig_ref) = ($_, $_);
5156 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
5157 next unless -f "$git_dir/$id/info/url";
5158 my $new_ref = "refs/remotes/$id";
5159 if (::verify_ref("$new_ref^0")) {
5160 print STDERR "W: $orig_ref is probably an old ",
5161 "branch used by an ancient version of ",
5162 "git-svn.\n",
5163 "However, $new_ref also exists.\n",
5164 "We will not be able ",
5165 "to use this branch until this ",
5166 "ambiguity is resolved.\n";
5167 next;
5169 print STDERR "Migrating from v0 layout...\n" if !$migrated;
5170 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
5171 command_noisy('update-ref', $new_ref, $orig_ref);
5172 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
5173 $migrated++;
5175 command_close_pipe($fh, $ctx);
5176 print STDERR "Done migrating from v0 layout...\n" if $migrated;
5177 $migrated;
5180 sub migrate_from_v1 {
5181 my $git_dir = $ENV{GIT_DIR};
5182 my $migrated = 0;
5183 return $migrated unless -d $git_dir;
5184 my $svn_dir = "$git_dir/svn";
5186 # just in case somebody used 'svn' as their $id at some point...
5187 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
5189 print STDERR "Migrating from a git-svn v1 layout...\n";
5190 mkpath([$svn_dir]);
5191 print STDERR "Data from a previous version of git-svn exists, but\n\t",
5192 "$svn_dir\n\t(required for this version ",
5193 "($::VERSION) of git-svn) does not exist.\n";
5194 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5195 while (<$fh>) {
5196 my $x = $_;
5197 next unless $x =~ s#^refs/remotes/##;
5198 chomp $x;
5199 next unless -f "$git_dir/$x/info/url";
5200 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
5201 next unless $u;
5202 my $dn = dirname("$git_dir/svn/$x");
5203 mkpath([$dn]) unless -d $dn;
5204 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
5205 mkpath(["$git_dir/svn/svn"]);
5206 print STDERR " - $git_dir/$x/info => ",
5207 "$git_dir/svn/$x/info\n";
5208 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
5209 croak "$!: $x";
5210 # don't worry too much about these, they probably
5211 # don't exist with repos this old (save for index,
5212 # and we can easily regenerate that)
5213 foreach my $f (qw/unhandled.log index .rev_db/) {
5214 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
5216 } else {
5217 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
5218 rename "$git_dir/$x", "$git_dir/svn/$x" or
5219 croak "$!: $x";
5221 $migrated++;
5223 command_close_pipe($fh, $ctx);
5224 print STDERR "Done migrating from a git-svn v1 layout\n";
5225 $migrated;
5228 sub read_old_urls {
5229 my ($l_map, $pfx, $path) = @_;
5230 my @dir;
5231 foreach (<$path/*>) {
5232 if (-r "$_/info/url") {
5233 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
5234 my $ref_id = $pfx . basename $_;
5235 my $url = ::file_to_s("$_/info/url");
5236 $l_map->{$ref_id} = $url;
5237 } elsif (-d $_) {
5238 push @dir, $_;
5241 foreach (@dir) {
5242 my $x = $_;
5243 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
5244 read_old_urls($l_map, $x, $_);
5248 sub migrate_from_v2 {
5249 my @cfg = command(qw/config -l/);
5250 return if grep /^svn-remote\..+\.url=/, @cfg;
5251 my %l_map;
5252 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
5253 my $migrated = 0;
5255 foreach my $ref_id (sort keys %l_map) {
5256 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
5257 if ($@) {
5258 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
5260 $migrated++;
5262 $migrated;
5265 sub minimize_connections {
5266 my $r = Git::SVN::read_all_remotes();
5267 my $new_urls = {};
5268 my $root_repos = {};
5269 foreach my $repo_id (keys %$r) {
5270 my $url = $r->{$repo_id}->{url} or next;
5271 my $fetch = $r->{$repo_id}->{fetch} or next;
5272 my $ra = Git::SVN::Ra->new($url);
5274 # skip existing cases where we already connect to the root
5275 if (($ra->{url} eq $ra->{repos_root}) ||
5276 ($ra->{repos_root} eq $repo_id)) {
5277 $root_repos->{$ra->{url}} = $repo_id;
5278 next;
5281 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
5282 my $root_path = $ra->{url};
5283 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
5284 foreach my $path (keys %$fetch) {
5285 my $ref_id = $fetch->{$path};
5286 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
5288 # make sure we can read when connecting to
5289 # a higher level of a repository
5290 my ($last_rev, undef) = $gs->last_rev_commit;
5291 if (!defined $last_rev) {
5292 $last_rev = eval {
5293 $root_ra->get_latest_revnum;
5295 next if $@;
5297 my $new = $root_path;
5298 $new .= length $path ? "/$path" : '';
5299 eval {
5300 $root_ra->get_log([$new], $last_rev, $last_rev,
5301 0, 0, 1, sub { });
5303 next if $@;
5304 $new_urls->{$ra->{repos_root}}->{$new} =
5305 { ref_id => $ref_id,
5306 old_repo_id => $repo_id,
5307 old_path => $path };
5311 my @emptied;
5312 foreach my $url (keys %$new_urls) {
5313 # see if we can re-use an existing [svn-remote "repo_id"]
5314 # instead of creating a(n ugly) new section:
5315 my $repo_id = $root_repos->{$url} || $url;
5317 my $fetch = $new_urls->{$url};
5318 foreach my $path (keys %$fetch) {
5319 my $x = $fetch->{$path};
5320 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
5321 my $pfx = "svn-remote.$x->{old_repo_id}";
5323 my $old_fetch = quotemeta("$x->{old_path}:".
5324 "refs/remotes/$x->{ref_id}");
5325 command_noisy(qw/config --unset/,
5326 "$pfx.fetch", '^'. $old_fetch . '$');
5327 delete $r->{$x->{old_repo_id}}->
5328 {fetch}->{$x->{old_path}};
5329 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
5330 command_noisy(qw/config --unset/,
5331 "$pfx.url");
5332 push @emptied, $x->{old_repo_id}
5336 if (@emptied) {
5337 my $file = $ENV{GIT_CONFIG} || "$ENV{GIT_DIR}/config";
5338 print STDERR <<EOF;
5339 The following [svn-remote] sections in your config file ($file) are empty
5340 and can be safely removed:
5342 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
5346 sub migration_check {
5347 migrate_from_v0();
5348 migrate_from_v1();
5349 migrate_from_v2();
5350 minimize_connections() if $_minimize;
5353 package Git::IndexInfo;
5354 use strict;
5355 use warnings;
5356 use Git qw/command_input_pipe command_close_pipe/;
5358 sub new {
5359 my ($class) = @_;
5360 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
5361 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
5364 sub remove {
5365 my ($self, $path) = @_;
5366 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
5367 return ++$self->{nr};
5369 undef;
5372 sub update {
5373 my ($self, $mode, $hash, $path) = @_;
5374 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
5375 return ++$self->{nr};
5377 undef;
5380 sub DESTROY {
5381 my ($self) = @_;
5382 command_close_pipe($self->{gui}, $self->{ctx});
5385 package Git::SVN::GlobSpec;
5386 use strict;
5387 use warnings;
5389 sub new {
5390 my ($class, $glob) = @_;
5391 my $re = $glob;
5392 $re =~ s!/+$!!g; # no need for trailing slashes
5393 $re =~ m!^([^*]*)(\*(?:/\*)*)([^*]*)$!;
5394 my $temp = $re;
5395 my ($left, $right) = ($1, $3);
5396 $re = $2;
5397 my $depth = $re =~ tr/*/*/;
5398 if ($depth != $temp =~ tr/*/*/) {
5399 die "Only one set of wildcard directories " .
5400 "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
5402 if ($depth == 0) {
5403 die "One '*' is needed for glob: '$glob'\n";
5405 $re =~ s!\*!\[^/\]*!g;
5406 $re = quotemeta($left) . "($re)" . quotemeta($right);
5407 if (length $left && !($left =~ s!/+$!!g)) {
5408 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
5410 if (length $right && !($right =~ s!^/+!!g)) {
5411 die "Missing leading '/' on right side of: '$glob' ($right)\n";
5413 my $left_re = qr/^\/\Q$left\E(\/|$)/;
5414 bless { left => $left, right => $right, left_regex => $left_re,
5415 regex => qr/$re/, glob => $glob, depth => $depth }, $class;
5418 sub full_path {
5419 my ($self, $path) = @_;
5420 return (length $self->{left} ? "$self->{left}/" : '') .
5421 $path . (length $self->{right} ? "/$self->{right}" : '');
5424 __END__
5426 Data structures:
5429 $remotes = { # returned by read_all_remotes()
5430 'svn' => {
5431 # svn-remote.svn.url=https://svn.musicpd.org
5432 url => 'https://svn.musicpd.org',
5433 # svn-remote.svn.fetch=mpd/trunk:trunk
5434 fetch => {
5435 'mpd/trunk' => 'trunk',
5437 # svn-remote.svn.tags=mpd/tags/*:tags/*
5438 tags => {
5439 path => {
5440 left => 'mpd/tags',
5441 right => '',
5442 regex => qr!mpd/tags/([^/]+)$!,
5443 glob => 'tags/*',
5445 ref => {
5446 left => 'tags',
5447 right => '',
5448 regex => qr!tags/([^/]+)$!,
5449 glob => 'tags/*',
5455 $log_entry hashref as returned by libsvn_log_entry()
5457 log => 'whitespace-formatted log entry
5458 ', # trailing newline is preserved
5459 revision => '8', # integer
5460 date => '2004-02-24T17:01:44.108345Z', # commit date
5461 author => 'committer name'
5465 # this is generated by generate_diff();
5466 @mods = array of diff-index line hashes, each element represents one line
5467 of diff-index output
5469 diff-index line ($m hash)
5471 mode_a => first column of diff-index output, no leading ':',
5472 mode_b => second column of diff-index output,
5473 sha1_b => sha1sum of the final blob,
5474 chg => change type [MCRADT],
5475 file_a => original file name of a file (iff chg is 'C' or 'R')
5476 file_b => new/current file name of a file (any chg)
5480 # retval of read_url_paths{,_all}();
5481 $l_map = {
5482 # repository root url
5483 'https://svn.musicpd.org' => {
5484 # repository path # GIT_SVN_ID
5485 'mpd/trunk' => 'trunk',
5486 'mpd/tags/0.11.5' => 'tags/0.11.5',
5490 Notes:
5491 I don't trust the each() function on unless I created %hash myself
5492 because the internal iterator may not have started at base.