git-svn: fix delete+add branch tracking with empty files
[git/mingw/j6t.git] / git-svn.perl
blobbce24a80c45e67663cebf43e3617e9c6aa7f8def
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 %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 Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
43 use IPC::Open3;
44 use Git;
46 BEGIN {
47 # import functions from Git into our packages, en masse
48 no strict 'refs';
49 foreach (qw/command command_oneline command_noisy command_output_pipe
50 command_input_pipe command_close_pipe/) {
51 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
52 Git::SVN::Migration Git::SVN::Log Git::SVN),
53 __PACKAGE__) {
54 *{"${package}::$_"} = \&{"Git::$_"};
59 my ($SVN);
61 $sha1 = qr/[a-f\d]{40}/;
62 $sha1_short = qr/[a-f\d]{4,40}/;
63 my ($_stdin, $_help, $_edit,
64 $_message, $_file,
65 $_template, $_shared,
66 $_version, $_fetch_all, $_no_rebase,
67 $_merge, $_strategy, $_dry_run, $_local,
68 $_prefix, $_no_checkout, $_url, $_verbose,
69 $_git_format, $_commit_url, $_tag);
70 $Git::SVN::_follow_parent = 1;
71 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
72 'config-dir=s' => \$Git::SVN::Ra::config_dir,
73 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
74 'ignore-paths=s' => \$SVN::Git::Fetcher::_ignore_regex );
75 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
76 'authors-file|A=s' => \$_authors,
77 'repack:i' => \$Git::SVN::_repack,
78 'noMetadata' => \$Git::SVN::_no_metadata,
79 'useSvmProps' => \$Git::SVN::_use_svm_props,
80 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
81 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
82 'no-checkout' => \$_no_checkout,
83 'quiet|q' => \$_q,
84 'repack-flags|repack-args|repack-opts=s' =>
85 \$Git::SVN::_repack_flags,
86 'use-log-author' => \$Git::SVN::_use_log_author,
87 'add-author-from' => \$Git::SVN::_add_author_from,
88 'localtime' => \$Git::SVN::_localtime,
89 %remote_opts );
91 my ($_trunk, $_tags, $_branches, $_stdlayout);
92 my %icv;
93 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
94 'trunk|T=s' => \$_trunk, 'tags|t=s' => \$_tags,
95 'branches|b=s' => \$_branches, 'prefix=s' => \$_prefix,
96 'stdlayout|s' => \$_stdlayout,
97 'minimize-url|m' => \$Git::SVN::_minimize_url,
98 'no-metadata' => sub { $icv{noMetadata} = 1 },
99 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
100 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
101 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
102 %remote_opts );
103 my %cmt_opts = ( 'edit|e' => \$_edit,
104 'rmdir' => \$SVN::Git::Editor::_rmdir,
105 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
106 'l=i' => \$SVN::Git::Editor::_rename_limit,
107 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
110 my %cmd = (
111 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
112 { 'revision|r=s' => \$_revision,
113 'fetch-all|all' => \$_fetch_all,
114 %fc_opts } ],
115 clone => [ \&cmd_clone, "Initialize and fetch revisions",
116 { 'revision|r=s' => \$_revision,
117 %fc_opts, %init_opts } ],
118 init => [ \&cmd_init, "Initialize a repo for tracking" .
119 " (requires URL argument)",
120 \%init_opts ],
121 'multi-init' => [ \&cmd_multi_init,
122 "Deprecated alias for ".
123 "'$0 init -T<trunk> -b<branches> -t<tags>'",
124 \%init_opts ],
125 dcommit => [ \&cmd_dcommit,
126 'Commit several diffs to merge with upstream',
127 { 'merge|m|M' => \$_merge,
128 'strategy|s=s' => \$_strategy,
129 'verbose|v' => \$_verbose,
130 'dry-run|n' => \$_dry_run,
131 'fetch-all|all' => \$_fetch_all,
132 'commit-url=s' => \$_commit_url,
133 'revision|r=i' => \$_revision,
134 'no-rebase' => \$_no_rebase,
135 %cmt_opts, %fc_opts } ],
136 branch => [ \&cmd_branch,
137 'Create a branch in the SVN repository',
138 { 'message|m=s' => \$_message,
139 'dry-run|n' => \$_dry_run,
140 'tag|t' => \$_tag } ],
141 tag => [ sub { $_tag = 1; cmd_branch(@_) },
142 'Create a tag in the SVN repository',
143 { 'message|m=s' => \$_message,
144 'dry-run|n' => \$_dry_run } ],
145 'set-tree' => [ \&cmd_set_tree,
146 "Set an SVN repository to a git tree-ish",
147 { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
148 'create-ignore' => [ \&cmd_create_ignore,
149 'Create a .gitignore per svn:ignore',
150 { 'revision|r=i' => \$_revision
151 } ],
152 'propget' => [ \&cmd_propget,
153 'Print the value of a property on a file or directory',
154 { 'revision|r=i' => \$_revision } ],
155 'proplist' => [ \&cmd_proplist,
156 'List all properties of a file or directory',
157 { 'revision|r=i' => \$_revision } ],
158 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
159 { 'revision|r=i' => \$_revision
160 } ],
161 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
162 { 'revision|r=i' => \$_revision
163 } ],
164 'multi-fetch' => [ \&cmd_multi_fetch,
165 "Deprecated alias for $0 fetch --all",
166 { 'revision|r=s' => \$_revision, %fc_opts } ],
167 'migrate' => [ sub { },
168 # no-op, we automatically run this anyways,
169 'Migrate configuration/metadata/layout from
170 previous versions of git-svn',
171 { 'minimize' => \$Git::SVN::Migration::_minimize,
172 %remote_opts } ],
173 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
174 { 'limit=i' => \$Git::SVN::Log::limit,
175 'revision|r=s' => \$_revision,
176 'verbose|v' => \$Git::SVN::Log::verbose,
177 'incremental' => \$Git::SVN::Log::incremental,
178 'oneline' => \$Git::SVN::Log::oneline,
179 'show-commit' => \$Git::SVN::Log::show_commit,
180 'non-recursive' => \$Git::SVN::Log::non_recursive,
181 'authors-file|A=s' => \$_authors,
182 'color' => \$Git::SVN::Log::color,
183 'pager=s' => \$Git::SVN::Log::pager
184 } ],
185 'find-rev' => [ \&cmd_find_rev,
186 "Translate between SVN revision numbers and tree-ish",
187 {} ],
188 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
189 { 'merge|m|M' => \$_merge,
190 'verbose|v' => \$_verbose,
191 'strategy|s=s' => \$_strategy,
192 'local|l' => \$_local,
193 'fetch-all|all' => \$_fetch_all,
194 'dry-run|n' => \$_dry_run,
195 %fc_opts } ],
196 'commit-diff' => [ \&cmd_commit_diff,
197 'Commit a diff between two trees',
198 { 'message|m=s' => \$_message,
199 'file|F=s' => \$_file,
200 'revision|r=s' => \$_revision,
201 %cmt_opts } ],
202 'info' => [ \&cmd_info,
203 "Show info about the latest SVN revision
204 on the current branch",
205 { 'url' => \$_url, } ],
206 'blame' => [ \&Git::SVN::Log::cmd_blame,
207 "Show what revision and author last modified each line of a file",
208 { 'git-format' => \$_git_format } ],
211 my $cmd;
212 for (my $i = 0; $i < @ARGV; $i++) {
213 if (defined $cmd{$ARGV[$i]}) {
214 $cmd = $ARGV[$i];
215 splice @ARGV, $i, 1;
216 last;
220 # make sure we're always running at the top-level working directory
221 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
222 unless (-d $ENV{GIT_DIR}) {
223 if ($git_dir_user_set) {
224 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
225 "but it is not a directory\n";
227 my $git_dir = delete $ENV{GIT_DIR};
228 my $cdup = undef;
229 git_cmd_try {
230 $cdup = command_oneline(qw/rev-parse --show-cdup/);
231 $git_dir = '.' unless ($cdup);
232 chomp $cdup if ($cdup);
233 $cdup = "." unless ($cdup && length $cdup);
234 } "Already at toplevel, but $git_dir not found\n";
235 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
236 unless (-d $git_dir) {
237 die "$git_dir still not found after going to ",
238 "'$cdup'\n";
240 $ENV{GIT_DIR} = $git_dir;
242 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
245 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
247 read_repo_config(\%opts);
248 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
249 Getopt::Long::Configure('pass_through');
251 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
252 'minimize-connections' => \$Git::SVN::Migration::_minimize,
253 'id|i=s' => \$Git::SVN::default_ref_id,
254 'svn-remote|remote|R=s' => sub {
255 $Git::SVN::no_reuse_existing = 1;
256 $Git::SVN::default_repo_id = $_[1] });
257 exit 1 if (!$rv && $cmd && $cmd ne 'log');
259 usage(0) if $_help;
260 version() if $_version;
261 usage(1) unless defined $cmd;
262 load_authors() if $_authors;
264 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
265 Git::SVN::Migration::migration_check();
267 Git::SVN::init_vars();
268 eval {
269 Git::SVN::verify_remotes_sanity();
270 $cmd{$cmd}->[0]->(@ARGV);
272 fatal $@ if $@;
273 post_fetch_checkout();
274 exit 0;
276 ####################### primary functions ######################
277 sub usage {
278 my $exit = shift || 0;
279 my $fd = $exit ? \*STDERR : \*STDOUT;
280 print $fd <<"";
281 git-svn - bidirectional operations between a single Subversion tree and git
282 Usage: git svn <command> [options] [arguments]\n
284 print $fd "Available commands:\n" unless $cmd;
286 foreach (sort keys %cmd) {
287 next if $cmd && $cmd ne $_;
288 next if /^multi-/; # don't show deprecated commands
289 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
290 foreach (sort keys %{$cmd{$_}->[2]}) {
291 # mixed-case options are for .git/config only
292 next if /[A-Z]/ && /^[a-z]+$/i;
293 # prints out arguments as they should be passed:
294 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
295 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
296 "--$_" : "-$_" }
297 split /\|/,$_)," $x\n";
300 print $fd <<"";
301 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
302 arbitrary identifier if you're tracking multiple SVN branches/repositories in
303 one git repository and want to keep them separate. See git-svn(1) for more
304 information.
306 exit $exit;
309 sub version {
310 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
311 exit 0;
314 sub do_git_init_db {
315 unless (-d $ENV{GIT_DIR}) {
316 my @init_db = ('init');
317 push @init_db, "--template=$_template" if defined $_template;
318 if (defined $_shared) {
319 if ($_shared =~ /[a-z]/) {
320 push @init_db, "--shared=$_shared";
321 } else {
322 push @init_db, "--shared";
325 command_noisy(@init_db);
326 $_repository = Git->repository(Repository => ".git");
328 my $set;
329 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
330 foreach my $i (keys %icv) {
331 die "'$set' and '$i' cannot both be set\n" if $set;
332 next unless defined $icv{$i};
333 command_noisy('config', "$pfx.$i", $icv{$i});
334 $set = $i;
338 sub init_subdir {
339 my $repo_path = shift or return;
340 mkpath([$repo_path]) unless -d $repo_path;
341 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
342 $ENV{GIT_DIR} = '.git';
343 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
346 sub cmd_clone {
347 my ($url, $path) = @_;
348 if (!defined $path &&
349 (defined $_trunk || defined $_branches || defined $_tags ||
350 defined $_stdlayout) &&
351 $url !~ m#^[a-z\+]+://#) {
352 $path = $url;
354 $path = basename($url) if !defined $path || !length $path;
355 cmd_init($url, $path);
356 Git::SVN::fetch_all($Git::SVN::default_repo_id);
359 sub cmd_init {
360 if (defined $_stdlayout) {
361 $_trunk = 'trunk' if (!defined $_trunk);
362 $_tags = 'tags' if (!defined $_tags);
363 $_branches = 'branches' if (!defined $_branches);
365 if (defined $_trunk || defined $_branches || defined $_tags) {
366 return cmd_multi_init(@_);
368 my $url = shift or die "SVN repository location required ",
369 "as a command-line argument\n";
370 init_subdir(@_);
371 do_git_init_db();
373 Git::SVN->init($url);
376 sub cmd_fetch {
377 if (grep /^\d+=./, @_) {
378 die "'<rev>=<commit>' fetch arguments are ",
379 "no longer supported.\n";
381 my ($remote) = @_;
382 if (@_ > 1) {
383 die "Usage: $0 fetch [--all] [svn-remote]\n";
385 $remote ||= $Git::SVN::default_repo_id;
386 if ($_fetch_all) {
387 cmd_multi_fetch();
388 } else {
389 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
393 sub cmd_set_tree {
394 my (@commits) = @_;
395 if ($_stdin || !@commits) {
396 print "Reading from stdin...\n";
397 @commits = ();
398 while (<STDIN>) {
399 if (/\b($sha1_short)\b/o) {
400 unshift @commits, $1;
404 my @revs;
405 foreach my $c (@commits) {
406 my @tmp = command('rev-parse',$c);
407 if (scalar @tmp == 1) {
408 push @revs, $tmp[0];
409 } elsif (scalar @tmp > 1) {
410 push @revs, reverse(command('rev-list',@tmp));
411 } else {
412 fatal "Failed to rev-parse $c";
415 my $gs = Git::SVN->new;
416 my ($r_last, $cmt_last) = $gs->last_rev_commit;
417 $gs->fetch;
418 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
419 fatal "There are new revisions that were fetched ",
420 "and need to be merged (or acknowledged) ",
421 "before committing.\nlast rev: $r_last\n",
422 " current: $gs->{last_rev}";
424 $gs->set_tree($_) foreach @revs;
425 print "Done committing ",scalar @revs," revisions to SVN\n";
426 unlink $gs->{index};
429 sub cmd_dcommit {
430 my $head = shift;
431 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
432 'Cannot dcommit with a dirty index. Commit your changes first, '
433 . "or stash them with `git stash'.\n";
434 $head ||= 'HEAD';
435 my @refs;
436 my ($url, $rev, $uuid, $gs) = working_head_info($head, \@refs);
437 unless ($gs) {
438 die "Unable to determine upstream SVN information from ",
439 "$head history.\nPerhaps the repository is empty.";
441 $url = defined $_commit_url ? $_commit_url : $gs->full_url;
442 my $last_rev = $_revision if defined $_revision;
443 if ($url) {
444 print "Committing to $url ...\n";
446 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
447 if ($_no_rebase && scalar(@$linear_refs) > 1) {
448 warn "Attempting to commit more than one change while ",
449 "--no-rebase is enabled.\n",
450 "If these changes depend on each other, re-running ",
451 "without --no-rebase may be required."
453 my $expect_url = $url;
454 Git::SVN::remove_username($expect_url);
455 while (1) {
456 my $d = shift @$linear_refs or last;
457 unless (defined $last_rev) {
458 (undef, $last_rev, undef) = cmt_metadata("$d~1");
459 unless (defined $last_rev) {
460 fatal "Unable to extract revision information ",
461 "from commit $d~1";
464 if ($_dry_run) {
465 print "diff-tree $d~1 $d\n";
466 } else {
467 my $cmt_rev;
468 my %ed_opts = ( r => $last_rev,
469 log => get_commit_entry($d)->{log},
470 ra => Git::SVN::Ra->new($url),
471 config => SVN::Core::config_get_config(
472 $Git::SVN::Ra::config_dir
474 tree_a => "$d~1",
475 tree_b => $d,
476 editor_cb => sub {
477 print "Committed r$_[0]\n";
478 $cmt_rev = $_[0];
480 svn_path => '');
481 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
482 print "No changes\n$d~1 == $d\n";
483 } elsif ($parents->{$d} && @{$parents->{$d}}) {
484 $gs->{inject_parents_dcommit}->{$cmt_rev} =
485 $parents->{$d};
487 $_fetch_all ? $gs->fetch_all : $gs->fetch;
488 $last_rev = $cmt_rev;
489 next if $_no_rebase;
491 # we always want to rebase against the current HEAD,
492 # not any head that was passed to us
493 my @diff = command('diff-tree', $d,
494 $gs->refname, '--');
495 my @finish;
496 if (@diff) {
497 @finish = rebase_cmd();
498 print STDERR "W: $d and ", $gs->refname,
499 " differ, using @finish:\n",
500 join("\n", @diff), "\n";
501 } else {
502 print "No changes between current HEAD and ",
503 $gs->refname,
504 "\nResetting to the latest ",
505 $gs->refname, "\n";
506 @finish = qw/reset --mixed/;
508 command_noisy(@finish, $gs->refname);
509 if (@diff) {
510 @refs = ();
511 my ($url_, $rev_, $uuid_, $gs_) =
512 working_head_info($head, \@refs);
513 my ($linear_refs_, $parents_) =
514 linearize_history($gs_, \@refs);
515 if (scalar(@$linear_refs) !=
516 scalar(@$linear_refs_)) {
517 fatal "# of revisions changed ",
518 "\nbefore:\n",
519 join("\n", @$linear_refs),
520 "\n\nafter:\n",
521 join("\n", @$linear_refs_), "\n",
522 'If you are attempting to commit ',
523 "merges, try running:\n\t",
524 'git rebase --interactive',
525 '--preserve-merges ',
526 $gs->refname,
527 "\nBefore dcommitting";
529 if ($url_ ne $expect_url) {
530 fatal "URL mismatch after rebase: ",
531 "$url_ != $expect_url";
533 if ($uuid_ ne $uuid) {
534 fatal "uuid mismatch after rebase: ",
535 "$uuid_ != $uuid";
537 # remap parents
538 my (%p, @l, $i);
539 for ($i = 0; $i < scalar @$linear_refs; $i++) {
540 my $new = $linear_refs_->[$i] or next;
541 $p{$new} =
542 $parents->{$linear_refs->[$i]};
543 push @l, $new;
545 $parents = \%p;
546 $linear_refs = \@l;
550 unlink $gs->{index};
553 sub cmd_branch {
554 my ($branch_name, $head) = @_;
556 unless (defined $branch_name && length $branch_name) {
557 die(($_tag ? "tag" : "branch") . " name required\n");
559 $head ||= 'HEAD';
561 my ($src, $rev, undef, $gs) = working_head_info($head);
563 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
564 my $glob = $remote->{ $_tag ? 'tags' : 'branches' };
565 my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
566 my $dst = join '/', $remote->{url}, $lft, $branch_name, ($rgt || ());
568 my $ctx = SVN::Client->new(
569 auth => Git::SVN::Ra::_auth_providers(),
570 log_msg => sub {
571 ${ $_[0] } = defined $_message
572 ? $_message
573 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
574 . $branch_name;
578 eval {
579 $ctx->ls($dst, 'HEAD', 0);
580 } and die "branch ${branch_name} already exists\n";
582 print "Copying ${src} at r${rev} to ${dst}...\n";
583 $ctx->copy($src, $rev, $dst)
584 unless $_dry_run;
586 $gs->fetch_all;
589 sub cmd_find_rev {
590 my $revision_or_hash = shift or die "SVN or git revision required ",
591 "as a command-line argument\n";
592 my $result;
593 if ($revision_or_hash =~ /^r\d+$/) {
594 my $head = shift;
595 $head ||= 'HEAD';
596 my @refs;
597 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
598 unless ($gs) {
599 die "Unable to determine upstream SVN information from ",
600 "$head history\n";
602 my $desired_revision = substr($revision_or_hash, 1);
603 $result = $gs->rev_map_get($desired_revision, $uuid);
604 } else {
605 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
606 $result = $rev;
608 print "$result\n" if $result;
611 sub cmd_rebase {
612 command_noisy(qw/update-index --refresh/);
613 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
614 unless ($gs) {
615 die "Unable to determine upstream SVN information from ",
616 "working tree history\n";
618 if ($_dry_run) {
619 print "Remote Branch: " . $gs->refname . "\n";
620 print "SVN URL: " . $url . "\n";
621 return;
623 if (command(qw/diff-index HEAD --/)) {
624 print STDERR "Cannot rebase with uncommited changes:\n";
625 command_noisy('status');
626 exit 1;
628 unless ($_local) {
629 # rebase will checkout for us, so no need to do it explicitly
630 $_no_checkout = 'true';
631 $_fetch_all ? $gs->fetch_all : $gs->fetch;
633 command_noisy(rebase_cmd(), $gs->refname);
636 sub cmd_show_ignore {
637 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
638 $gs ||= Git::SVN->new;
639 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
640 $gs->prop_walk($gs->{path}, $r, sub {
641 my ($gs, $path, $props) = @_;
642 print STDOUT "\n# $path\n";
643 my $s = $props->{'svn:ignore'} or return;
644 $s =~ s/[\r\n]+/\n/g;
645 chomp $s;
646 $s =~ s#^#$path#gm;
647 print STDOUT "$s\n";
651 sub cmd_show_externals {
652 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
653 $gs ||= Git::SVN->new;
654 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
655 $gs->prop_walk($gs->{path}, $r, sub {
656 my ($gs, $path, $props) = @_;
657 print STDOUT "\n# $path\n";
658 my $s = $props->{'svn:externals'} or return;
659 $s =~ s/[\r\n]+/\n/g;
660 chomp $s;
661 $s =~ s#^#$path#gm;
662 print STDOUT "$s\n";
666 sub cmd_create_ignore {
667 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
668 $gs ||= Git::SVN->new;
669 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
670 $gs->prop_walk($gs->{path}, $r, sub {
671 my ($gs, $path, $props) = @_;
672 # $path is of the form /path/to/dir/
673 $path = '.' . $path;
674 # SVN can have attributes on empty directories,
675 # which git won't track
676 mkpath([$path]) unless -d $path;
677 my $ignore = $path . '.gitignore';
678 my $s = $props->{'svn:ignore'} or return;
679 open(GITIGNORE, '>', $ignore)
680 or fatal("Failed to open `$ignore' for writing: $!");
681 $s =~ s/[\r\n]+/\n/g;
682 chomp $s;
683 # Prefix all patterns so that the ignore doesn't apply
684 # to sub-directories.
685 $s =~ s#^#/#gm;
686 print GITIGNORE "$s\n";
687 close(GITIGNORE)
688 or fatal("Failed to close `$ignore': $!");
689 command_noisy('add', '-f', $ignore);
693 sub canonicalize_path {
694 my ($path) = @_;
695 my $dot_slash_added = 0;
696 if (substr($path, 0, 1) ne "/") {
697 $path = "./" . $path;
698 $dot_slash_added = 1;
700 # File::Spec->canonpath doesn't collapse x/../y into y (for a
701 # good reason), so let's do this manually.
702 $path =~ s#/+#/#g;
703 $path =~ s#/\.(?:/|$)#/#g;
704 $path =~ s#/[^/]+/\.\.##g;
705 $path =~ s#/$##g;
706 $path =~ s#^\./## if $dot_slash_added;
707 $path =~ s#^/##;
708 $path =~ s#^\.$##;
709 return $path;
712 # get_svnprops(PATH)
713 # ------------------
714 # Helper for cmd_propget and cmd_proplist below.
715 sub get_svnprops {
716 my $path = shift;
717 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
718 $gs ||= Git::SVN->new;
720 # prefix THE PATH by the sub-directory from which the user
721 # invoked us.
722 $path = $cmd_dir_prefix . $path;
723 fatal("No such file or directory: $path") unless -e $path;
724 my $is_dir = -d $path ? 1 : 0;
725 $path = $gs->{path} . '/' . $path;
727 # canonicalize the path (otherwise libsvn will abort or fail to
728 # find the file)
729 $path = canonicalize_path($path);
731 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
732 my $props;
733 if ($is_dir) {
734 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
736 else {
737 (undef, $props) = $gs->ra->get_file($path, $r, undef);
739 return $props;
742 # cmd_propget (PROP, PATH)
743 # ------------------------
744 # Print the SVN property PROP for PATH.
745 sub cmd_propget {
746 my ($prop, $path) = @_;
747 $path = '.' if not defined $path;
748 usage(1) if not defined $prop;
749 my $props = get_svnprops($path);
750 if (not defined $props->{$prop}) {
751 fatal("`$path' does not have a `$prop' SVN property.");
753 print $props->{$prop} . "\n";
756 # cmd_proplist (PATH)
757 # -------------------
758 # Print the list of SVN properties for PATH.
759 sub cmd_proplist {
760 my $path = shift;
761 $path = '.' if not defined $path;
762 my $props = get_svnprops($path);
763 print "Properties on '$path':\n";
764 foreach (sort keys %{$props}) {
765 print " $_\n";
769 sub cmd_multi_init {
770 my $url = shift;
771 unless (defined $_trunk || defined $_branches || defined $_tags) {
772 usage(1);
775 # there are currently some bugs that prevent multi-init/multi-fetch
776 # setups from working well without this.
777 $Git::SVN::_minimize_url = 1;
779 $_prefix = '' unless defined $_prefix;
780 if (defined $url) {
781 $url =~ s#/+$##;
782 init_subdir(@_);
784 do_git_init_db();
785 if (defined $_trunk) {
786 my $trunk_ref = $_prefix . 'trunk';
787 # try both old-style and new-style lookups:
788 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
789 unless ($gs_trunk) {
790 my ($trunk_url, $trunk_path) =
791 complete_svn_url($url, $_trunk);
792 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
793 undef, $trunk_ref);
796 return unless defined $_branches || defined $_tags;
797 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
798 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
799 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
802 sub cmd_multi_fetch {
803 my $remotes = Git::SVN::read_all_remotes();
804 foreach my $repo_id (sort keys %$remotes) {
805 if ($remotes->{$repo_id}->{url}) {
806 Git::SVN::fetch_all($repo_id, $remotes);
811 # this command is special because it requires no metadata
812 sub cmd_commit_diff {
813 my ($ta, $tb, $url) = @_;
814 my $usage = "Usage: $0 commit-diff -r<revision> ".
815 "<tree-ish> <tree-ish> [<URL>]";
816 fatal($usage) if (!defined $ta || !defined $tb);
817 my $svn_path = '';
818 if (!defined $url) {
819 my $gs = eval { Git::SVN->new };
820 if (!$gs) {
821 fatal("Needed URL or usable git-svn --id in ",
822 "the command-line\n", $usage);
824 $url = $gs->{url};
825 $svn_path = $gs->{path};
827 unless (defined $_revision) {
828 fatal("-r|--revision is a required argument\n", $usage);
830 if (defined $_message && defined $_file) {
831 fatal("Both --message/-m and --file/-F specified ",
832 "for the commit message.\n",
833 "I have no idea what you mean");
835 if (defined $_file) {
836 $_message = file_to_s($_file);
837 } else {
838 $_message ||= get_commit_entry($tb)->{log};
840 my $ra ||= Git::SVN::Ra->new($url);
841 my $r = $_revision;
842 if ($r eq 'HEAD') {
843 $r = $ra->get_latest_revnum;
844 } elsif ($r !~ /^\d+$/) {
845 die "revision argument: $r not understood by git-svn\n";
847 my %ed_opts = ( r => $r,
848 log => $_message,
849 ra => $ra,
850 tree_a => $ta,
851 tree_b => $tb,
852 editor_cb => sub { print "Committed r$_[0]\n" },
853 svn_path => $svn_path );
854 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
855 print "No changes\n$ta == $tb\n";
859 sub escape_uri_only {
860 my ($uri) = @_;
861 my @tmp;
862 foreach (split m{/}, $uri) {
863 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
864 push @tmp, $_;
866 join('/', @tmp);
869 sub escape_url {
870 my ($url) = @_;
871 if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
872 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
873 $url = "$scheme://$domain$uri";
875 $url;
878 sub cmd_info {
879 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
880 my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
881 if (exists $_[1]) {
882 die "Too many arguments specified\n";
885 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
887 if (!$file_type && !$diff_status) {
888 print STDERR "svn: '$path' is not under version control\n";
889 exit 1;
892 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
893 unless ($gs) {
894 die "Unable to determine upstream SVN information from ",
895 "working tree history\n";
898 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
899 $path = "." if $path eq "";
901 my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
903 if ($_url) {
904 print escape_url($full_url), "\n";
905 return;
908 my $result = "Path: $path\n";
909 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
910 $result .= "URL: " . escape_url($full_url) . "\n";
912 eval {
913 my $repos_root = $gs->repos_root;
914 Git::SVN::remove_username($repos_root);
915 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
917 if ($@) {
918 $result .= "Repository Root: (offline)\n";
920 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
921 ($SVN::Core::VERSION le '1.5.4' || $file_type ne "dir");
922 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
924 $result .= "Node Kind: " .
925 ($file_type eq "dir" ? "directory" : "file") . "\n";
927 my $schedule = $diff_status eq "A"
928 ? "add"
929 : ($diff_status eq "D" ? "delete" : "normal");
930 $result .= "Schedule: $schedule\n";
932 if ($diff_status eq "A") {
933 print $result, "\n";
934 return;
937 my ($lc_author, $lc_rev, $lc_date_utc);
938 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
939 my $log = command_output_pipe(@args);
940 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
941 while (<$log>) {
942 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
943 $lc_author = $1;
944 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
945 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
946 (undef, $lc_rev, undef) = ::extract_metadata($1);
949 close $log;
951 Git::SVN::Log::set_local_timezone();
953 $result .= "Last Changed Author: $lc_author\n";
954 $result .= "Last Changed Rev: $lc_rev\n";
955 $result .= "Last Changed Date: " .
956 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
958 if ($file_type ne "dir") {
959 my $text_last_updated_date =
960 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
961 $result .=
962 "Text Last Updated: " .
963 Git::SVN::Log::format_svn_date($text_last_updated_date) .
964 "\n";
965 my $checksum;
966 if ($diff_status eq "D") {
967 my ($fh, $ctx) =
968 command_output_pipe(qw(cat-file blob), "HEAD:$path");
969 if ($file_type eq "link") {
970 my $file_name = <$fh>;
971 $checksum = md5sum("link $file_name");
972 } else {
973 $checksum = md5sum($fh);
975 command_close_pipe($fh, $ctx);
976 } elsif ($file_type eq "link") {
977 my $file_name =
978 command(qw(cat-file blob), "HEAD:$path");
979 $checksum =
980 md5sum("link " . $file_name);
981 } else {
982 open FILE, "<", $path or die $!;
983 $checksum = md5sum(\*FILE);
984 close FILE or die $!;
986 $result .= "Checksum: " . $checksum . "\n";
989 print $result, "\n";
992 ########################### utility functions #########################
994 sub rebase_cmd {
995 my @cmd = qw/rebase/;
996 push @cmd, '-v' if $_verbose;
997 push @cmd, qw/--merge/ if $_merge;
998 push @cmd, "--strategy=$_strategy" if $_strategy;
999 @cmd;
1002 sub post_fetch_checkout {
1003 return if $_no_checkout;
1004 my $gs = $Git::SVN::_head or return;
1005 return if verify_ref('refs/heads/master^0');
1007 my $valid_head = verify_ref('HEAD^0');
1008 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1009 return if ($valid_head || !verify_ref('HEAD^0'));
1011 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1012 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1013 return if -f $index;
1015 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1016 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1017 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1018 print STDERR "Checked out HEAD:\n ",
1019 $gs->full_url, " r", $gs->last_rev, "\n";
1022 sub complete_svn_url {
1023 my ($url, $path) = @_;
1024 $path =~ s#/+$##;
1025 if ($path !~ m#^[a-z\+]+://#) {
1026 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1027 fatal("E: '$path' is not a complete URL ",
1028 "and a separate URL is not specified");
1030 return ($url, $path);
1032 return ($path, '');
1035 sub complete_url_ls_init {
1036 my ($ra, $repo_path, $switch, $pfx) = @_;
1037 unless ($repo_path) {
1038 print STDERR "W: $switch not specified\n";
1039 return;
1041 $repo_path =~ s#/+$##;
1042 if ($repo_path =~ m#^[a-z\+]+://#) {
1043 $ra = Git::SVN::Ra->new($repo_path);
1044 $repo_path = '';
1045 } else {
1046 $repo_path =~ s#^/+##;
1047 unless ($ra) {
1048 fatal("E: '$repo_path' is not a complete URL ",
1049 "and a separate URL is not specified");
1052 my $url = $ra->{url};
1053 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1054 my $k = "svn-remote.$gs->{repo_id}.url";
1055 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1056 if ($orig_url && ($orig_url ne $gs->{url})) {
1057 die "$k already set: $orig_url\n",
1058 "wanted to set to: $gs->{url}\n";
1060 command_oneline('config', $k, $gs->{url}) unless $orig_url;
1061 my $remote_path = "$ra->{svn_path}/$repo_path";
1062 $remote_path =~ s#/+#/#g;
1063 $remote_path =~ s#^/##g;
1064 $remote_path .= "/*" if $remote_path !~ /\*/;
1065 my ($n) = ($switch =~ /^--(\w+)/);
1066 if (length $pfx && $pfx !~ m#/$#) {
1067 die "--prefix='$pfx' must have a trailing slash '/'\n";
1069 command_noisy('config',
1070 "svn-remote.$gs->{repo_id}.$n",
1071 "$remote_path:refs/remotes/$pfx*" .
1072 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1075 sub verify_ref {
1076 my ($ref) = @_;
1077 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1078 { STDERR => 0 }); };
1081 sub get_tree_from_treeish {
1082 my ($treeish) = @_;
1083 # $treeish can be a symbolic ref, too:
1084 my $type = command_oneline(qw/cat-file -t/, $treeish);
1085 my $expected;
1086 while ($type eq 'tag') {
1087 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1089 if ($type eq 'commit') {
1090 $expected = (grep /^tree /, command(qw/cat-file commit/,
1091 $treeish))[0];
1092 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1093 die "Unable to get tree from $treeish\n" unless $expected;
1094 } elsif ($type eq 'tree') {
1095 $expected = $treeish;
1096 } else {
1097 die "$treeish is a $type, expected tree, tag or commit\n";
1099 return $expected;
1102 sub get_commit_entry {
1103 my ($treeish) = shift;
1104 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1105 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1106 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1107 open my $log_fh, '>', $commit_editmsg or croak $!;
1109 my $type = command_oneline(qw/cat-file -t/, $treeish);
1110 if ($type eq 'commit' || $type eq 'tag') {
1111 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1112 $type, $treeish);
1113 my $in_msg = 0;
1114 my $author;
1115 my $saw_from = 0;
1116 my $msgbuf = "";
1117 while (<$msg_fh>) {
1118 if (!$in_msg) {
1119 $in_msg = 1 if (/^\s*$/);
1120 $author = $1 if (/^author (.*>)/);
1121 } elsif (/^git-svn-id: /) {
1122 # skip this for now, we regenerate the
1123 # correct one on re-fetch anyways
1124 # TODO: set *:merge properties or like...
1125 } else {
1126 if (/^From:/ || /^Signed-off-by:/) {
1127 $saw_from = 1;
1129 $msgbuf .= $_;
1132 $msgbuf =~ s/\s+$//s;
1133 if ($Git::SVN::_add_author_from && defined($author)
1134 && !$saw_from) {
1135 $msgbuf .= "\n\nFrom: $author";
1137 print $log_fh $msgbuf or croak $!;
1138 command_close_pipe($msg_fh, $ctx);
1140 close $log_fh or croak $!;
1142 if ($_edit || ($type eq 'tree')) {
1143 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1144 # TODO: strip out spaces, comments, like git-commit.sh
1145 system($editor, $commit_editmsg);
1147 rename $commit_editmsg, $commit_msg or croak $!;
1149 # SVN requires messages to be UTF-8 when entering the repo
1150 local $/;
1151 open $log_fh, '<', $commit_msg or croak $!;
1152 binmode $log_fh;
1153 chomp($log_entry{log} = <$log_fh>);
1155 if (my $enc = Git::config('i18n.commitencoding')) {
1156 require Encode;
1157 Encode::from_to($log_entry{log}, $enc, 'UTF-8');
1159 close $log_fh or croak $!;
1161 unlink $commit_msg;
1162 \%log_entry;
1165 sub s_to_file {
1166 my ($str, $file, $mode) = @_;
1167 open my $fd,'>',$file or croak $!;
1168 print $fd $str,"\n" or croak $!;
1169 close $fd or croak $!;
1170 chmod ($mode &~ umask, $file) if (defined $mode);
1173 sub file_to_s {
1174 my $file = shift;
1175 open my $fd,'<',$file or croak "$!: file: $file\n";
1176 local $/;
1177 my $ret = <$fd>;
1178 close $fd or croak $!;
1179 $ret =~ s/\s*$//s;
1180 return $ret;
1183 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1184 sub load_authors {
1185 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1186 my $log = $cmd eq 'log';
1187 while (<$authors>) {
1188 chomp;
1189 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1190 my ($user, $name, $email) = ($1, $2, $3);
1191 if ($log) {
1192 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1193 } else {
1194 $users{$user} = [$name, $email];
1197 close $authors or croak $!;
1200 # convert GetOpt::Long specs for use by git-config
1201 sub read_repo_config {
1202 return unless -d $ENV{GIT_DIR};
1203 my $opts = shift;
1204 my @config_only;
1205 foreach my $o (keys %$opts) {
1206 # if we have mixedCase and a long option-only, then
1207 # it's a config-only variable that we don't need for
1208 # the command-line.
1209 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1210 my $v = $opts->{$o};
1211 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1212 $key =~ s/-//g;
1213 my $arg = 'git config';
1214 $arg .= ' --int' if ($o =~ /[:=]i$/);
1215 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1216 if (ref $v eq 'ARRAY') {
1217 chomp(my @tmp = `$arg --get-all svn.$key`);
1218 @$v = @tmp if @tmp;
1219 } else {
1220 chomp(my $tmp = `$arg --get svn.$key`);
1221 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1222 $$v = $tmp;
1226 delete @$opts{@config_only} if @config_only;
1229 sub extract_metadata {
1230 my $id = shift or return (undef, undef, undef);
1231 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1232 \s([a-f\d\-]+)$/x);
1233 if (!defined $rev || !$uuid || !$url) {
1234 # some of the original repositories I made had
1235 # identifiers like this:
1236 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
1238 return ($url, $rev, $uuid);
1241 sub cmt_metadata {
1242 return extract_metadata((grep(/^git-svn-id: /,
1243 command(qw/cat-file commit/, shift)))[-1]);
1246 sub working_head_info {
1247 my ($head, $refs) = @_;
1248 my @args = ('log', '--no-color', '--first-parent', '--pretty=medium');
1249 my ($fh, $ctx) = command_output_pipe(@args, $head);
1250 my $hash;
1251 my %max;
1252 while (<$fh>) {
1253 if ( m{^commit ($::sha1)$} ) {
1254 unshift @$refs, $hash if $hash and $refs;
1255 $hash = $1;
1256 next;
1258 next unless s{^\s*(git-svn-id:)}{$1};
1259 my ($url, $rev, $uuid) = extract_metadata($_);
1260 if (defined $url && defined $rev) {
1261 next if $max{$url} and $max{$url} < $rev;
1262 if (my $gs = Git::SVN->find_by_url($url)) {
1263 my $c = $gs->rev_map_get($rev, $uuid);
1264 if ($c && $c eq $hash) {
1265 close $fh; # break the pipe
1266 return ($url, $rev, $uuid, $gs);
1267 } else {
1268 $max{$url} ||= $gs->rev_map_max;
1273 command_close_pipe($fh, $ctx);
1274 (undef, undef, undef, undef);
1277 sub read_commit_parents {
1278 my ($parents, $c) = @_;
1279 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1280 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1281 @{$parents->{$c}} = split(/ /, $p);
1284 sub linearize_history {
1285 my ($gs, $refs) = @_;
1286 my %parents;
1287 foreach my $c (@$refs) {
1288 read_commit_parents(\%parents, $c);
1291 my @linear_refs;
1292 my %skip = ();
1293 my $last_svn_commit = $gs->last_commit;
1294 foreach my $c (reverse @$refs) {
1295 next if $c eq $last_svn_commit;
1296 last if $skip{$c};
1298 unshift @linear_refs, $c;
1299 $skip{$c} = 1;
1301 # we only want the first parent to diff against for linear
1302 # history, we save the rest to inject when we finalize the
1303 # svn commit
1304 my $fp_a = verify_ref("$c~1");
1305 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1306 if (!$fp_a || !$fp_b) {
1307 die "Commit $c\n",
1308 "has no parent commit, and therefore ",
1309 "nothing to diff against.\n",
1310 "You should be working from a repository ",
1311 "originally created by git-svn\n";
1313 if ($fp_a ne $fp_b) {
1314 die "$c~1 = $fp_a, however parsing commit $c ",
1315 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1318 foreach my $p (@{$parents{$c}}) {
1319 $skip{$p} = 1;
1322 (\@linear_refs, \%parents);
1325 sub find_file_type_and_diff_status {
1326 my ($path) = @_;
1327 return ('dir', '') if $path eq '';
1329 my $diff_output =
1330 command_oneline(qw(diff --cached --name-status --), $path) || "";
1331 my $diff_status = (split(' ', $diff_output))[0] || "";
1333 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1335 return (undef, undef) if !$diff_status && !$ls_tree;
1337 if ($diff_status eq "A") {
1338 return ("link", $diff_status) if -l $path;
1339 return ("dir", $diff_status) if -d $path;
1340 return ("file", $diff_status);
1343 my $mode = (split(' ', $ls_tree))[0] || "";
1345 return ("link", $diff_status) if $mode eq "120000";
1346 return ("dir", $diff_status) if $mode eq "040000";
1347 return ("file", $diff_status);
1350 sub md5sum {
1351 my $arg = shift;
1352 my $ref = ref $arg;
1353 my $md5 = Digest::MD5->new();
1354 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
1355 $md5->addfile($arg) or croak $!;
1356 } elsif ($ref eq 'SCALAR') {
1357 $md5->add($$arg) or croak $!;
1358 } elsif (!$ref) {
1359 $md5->add($arg) or croak $!;
1360 } else {
1361 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1363 return $md5->hexdigest();
1366 package Git::SVN;
1367 use strict;
1368 use warnings;
1369 use Fcntl qw/:DEFAULT :seek/;
1370 use constant rev_map_fmt => 'NH40';
1371 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1372 $_repack $_repack_flags $_use_svm_props $_head
1373 $_use_svnsync_props $no_reuse_existing $_minimize_url
1374 $_use_log_author $_add_author_from $_localtime/;
1375 use Carp qw/croak/;
1376 use File::Path qw/mkpath/;
1377 use File::Copy qw/copy/;
1378 use IPC::Open3;
1380 my ($_gc_nr, $_gc_period);
1382 # properties that we do not log:
1383 my %SKIP_PROP;
1384 BEGIN {
1385 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1386 svn:special svn:executable
1387 svn:entry:committed-rev
1388 svn:entry:last-author
1389 svn:entry:uuid
1390 svn:entry:committed-date/;
1392 # some options are read globally, but can be overridden locally
1393 # per [svn-remote "..."] section. Command-line options will *NOT*
1394 # override options set in an [svn-remote "..."] section
1395 no strict 'refs';
1396 for my $option (qw/follow_parent no_metadata use_svm_props
1397 use_svnsync_props/) {
1398 my $key = $option;
1399 $key =~ tr/_//d;
1400 my $prop = "-$option";
1401 *$option = sub {
1402 my ($self) = @_;
1403 return $self->{$prop} if exists $self->{$prop};
1404 my $k = "svn-remote.$self->{repo_id}.$key";
1405 eval { command_oneline(qw/config --get/, $k) };
1406 if ($@) {
1407 $self->{$prop} = ${"Git::SVN::_$option"};
1408 } else {
1409 my $v = command_oneline(qw/config --bool/,$k);
1410 $self->{$prop} = $v eq 'false' ? 0 : 1;
1412 return $self->{$prop};
1418 my (%LOCKFILES, %INDEX_FILES);
1419 END {
1420 unlink keys %LOCKFILES if %LOCKFILES;
1421 unlink keys %INDEX_FILES if %INDEX_FILES;
1424 sub resolve_local_globs {
1425 my ($url, $fetch, $glob_spec) = @_;
1426 return unless defined $glob_spec;
1427 my $ref = $glob_spec->{ref};
1428 my $path = $glob_spec->{path};
1429 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
1430 next unless m#^refs/remotes/$ref->{regex}$#;
1431 my $p = $1;
1432 my $pathname = desanitize_refname($path->full_path($p));
1433 my $refname = desanitize_refname($ref->full_path($p));
1434 if (my $existing = $fetch->{$pathname}) {
1435 if ($existing ne $refname) {
1436 die "Refspec conflict:\n",
1437 "existing: refs/remotes/$existing\n",
1438 " globbed: refs/remotes/$refname\n";
1440 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
1441 $u =~ s!^\Q$url\E(/|$)!! or die
1442 "refs/remotes/$refname: '$url' not found in '$u'\n";
1443 if ($pathname ne $u) {
1444 warn "W: Refspec glob conflict ",
1445 "(ref: refs/remotes/$refname):\n",
1446 "expected path: $pathname\n",
1447 " real path: $u\n",
1448 "Continuing ahead with $u\n";
1449 next;
1451 } else {
1452 $fetch->{$pathname} = $refname;
1457 sub parse_revision_argument {
1458 my ($base, $head) = @_;
1459 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1460 return ($base, $head);
1462 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1463 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1464 return ($head, $head) if ($::_revision eq 'HEAD');
1465 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1466 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1467 die "revision argument: $::_revision not understood by git-svn\n";
1470 sub fetch_all {
1471 my ($repo_id, $remotes) = @_;
1472 if (ref $repo_id) {
1473 my $gs = $repo_id;
1474 $repo_id = undef;
1475 $repo_id = $gs->{repo_id};
1477 $remotes ||= read_all_remotes();
1478 my $remote = $remotes->{$repo_id} or
1479 die "[svn-remote \"$repo_id\"] unknown\n";
1480 my $fetch = $remote->{fetch};
1481 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1482 my (@gs, @globs);
1483 my $ra = Git::SVN::Ra->new($url);
1484 my $uuid = $ra->get_uuid;
1485 my $head = $ra->get_latest_revnum;
1486 my $base = defined $fetch ? $head : 0;
1488 # read the max revs for wildcard expansion (branches/*, tags/*)
1489 foreach my $t (qw/branches tags/) {
1490 defined $remote->{$t} or next;
1491 push @globs, $remote->{$t};
1492 my $max_rev = eval { tmp_config(qw/--int --get/,
1493 "svn-remote.$repo_id.${t}-maxRev") };
1494 if (defined $max_rev && ($max_rev < $base)) {
1495 $base = $max_rev;
1496 } elsif (!defined $max_rev) {
1497 $base = 0;
1501 if ($fetch) {
1502 foreach my $p (sort keys %$fetch) {
1503 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1504 my $lr = $gs->rev_map_max;
1505 if (defined $lr) {
1506 $base = $lr if ($lr < $base);
1508 push @gs, $gs;
1512 ($base, $head) = parse_revision_argument($base, $head);
1513 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1516 sub read_all_remotes {
1517 my $r = {};
1518 my $use_svm_props = eval { command_oneline(qw/config --bool
1519 svn.useSvmProps/) };
1520 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
1521 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1522 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*(.+)\s*$!) {
1523 my ($remote, $local_ref, $_remote_ref) = ($1, $2, $3);
1524 die("svn-remote.$remote: remote ref '$_remote_ref' "
1525 . "must start with 'refs/remotes/'\n")
1526 unless $_remote_ref =~ m{^refs/remotes/(.+)};
1527 my $remote_ref = $1;
1528 $local_ref =~ s{^/}{};
1529 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1530 $r->{$remote}->{svm} = {} if $use_svm_props;
1531 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
1532 $r->{$1}->{svm} = {};
1533 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1534 $r->{$1}->{url} = $2;
1535 } elsif (m!^(.+)\.(branches|tags)=
1536 (.*):refs/remotes/(.+)\s*$/!x) {
1537 my ($p, $g) = ($3, $4);
1538 my $rs = $r->{$1}->{$2} = {
1539 t => $2,
1540 remote => $1,
1541 path => Git::SVN::GlobSpec->new($p),
1542 ref => Git::SVN::GlobSpec->new($g) };
1543 if (length($rs->{ref}->{right}) != 0) {
1544 die "The '*' glob character must be the last ",
1545 "character of '$g'\n";
1550 map {
1551 if (defined $r->{$_}->{svm}) {
1552 my $svm;
1553 eval {
1554 my $section = "svn-remote.$_";
1555 $svm = {
1556 source => tmp_config('--get',
1557 "$section.svm-source"),
1558 replace => tmp_config('--get',
1559 "$section.svm-replace"),
1562 $r->{$_}->{svm} = $svm;
1564 } keys %$r;
1569 sub init_vars {
1570 $_gc_nr = $_gc_period = 1000;
1571 if (defined $_repack || defined $_repack_flags) {
1572 warn "Repack options are obsolete; they have no effect.\n";
1576 sub verify_remotes_sanity {
1577 return unless -d $ENV{GIT_DIR};
1578 my %seen;
1579 foreach (command(qw/config -l/)) {
1580 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1581 if ($seen{$1}) {
1582 die "Remote ref refs/remote/$1 is tracked by",
1583 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1584 "Please resolve this ambiguity in ",
1585 "your git configuration file before ",
1586 "continuing\n";
1588 $seen{$1} = $_;
1593 sub find_existing_remote {
1594 my ($url, $remotes) = @_;
1595 return undef if $no_reuse_existing;
1596 my $existing;
1597 foreach my $repo_id (keys %$remotes) {
1598 my $u = $remotes->{$repo_id}->{url} or next;
1599 next if $u ne $url;
1600 $existing = $repo_id;
1601 last;
1603 $existing;
1606 sub init_remote_config {
1607 my ($self, $url, $no_write) = @_;
1608 $url =~ s!/+$!!; # strip trailing slash
1609 my $r = read_all_remotes();
1610 my $existing = find_existing_remote($url, $r);
1611 if ($existing) {
1612 unless ($no_write) {
1613 print STDERR "Using existing ",
1614 "[svn-remote \"$existing\"]\n";
1616 $self->{repo_id} = $existing;
1617 } elsif ($_minimize_url) {
1618 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1619 $existing = find_existing_remote($min_url, $r);
1620 if ($existing) {
1621 unless ($no_write) {
1622 print STDERR "Using existing ",
1623 "[svn-remote \"$existing\"]\n";
1625 $self->{repo_id} = $existing;
1627 if ($min_url ne $url) {
1628 unless ($no_write) {
1629 print STDERR "Using higher level of URL: ",
1630 "$url => $min_url\n";
1632 my $old_path = $self->{path};
1633 $self->{path} = $url;
1634 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1635 if (length $old_path) {
1636 $self->{path} .= "/$old_path";
1638 $url = $min_url;
1641 my $orig_url;
1642 if (!$existing) {
1643 # verify that we aren't overwriting anything:
1644 $orig_url = eval {
1645 command_oneline('config', '--get',
1646 "svn-remote.$self->{repo_id}.url")
1648 if ($orig_url && ($orig_url ne $url)) {
1649 die "svn-remote.$self->{repo_id}.url already set: ",
1650 "$orig_url\nwanted to set to: $url\n";
1653 my ($xrepo_id, $xpath) = find_ref($self->refname);
1654 if (defined $xpath) {
1655 die "svn-remote.$xrepo_id.fetch already set to track ",
1656 "$xpath:refs/remotes/", $self->refname, "\n";
1658 unless ($no_write) {
1659 command_noisy('config',
1660 "svn-remote.$self->{repo_id}.url", $url);
1661 $self->{path} =~ s{^/}{};
1662 command_noisy('config', '--add',
1663 "svn-remote.$self->{repo_id}.fetch",
1664 "$self->{path}:".$self->refname);
1666 $self->{url} = $url;
1669 sub find_by_url { # repos_root and, path are optional
1670 my ($class, $full_url, $repos_root, $path) = @_;
1672 return undef unless defined $full_url;
1673 remove_username($full_url);
1674 remove_username($repos_root) if defined $repos_root;
1675 my $remotes = read_all_remotes();
1676 if (defined $full_url && defined $repos_root && !defined $path) {
1677 $path = $full_url;
1678 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1680 foreach my $repo_id (keys %$remotes) {
1681 my $u = $remotes->{$repo_id}->{url} or next;
1682 remove_username($u);
1683 next if defined $repos_root && $repos_root ne $u;
1685 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1686 foreach (qw/branches tags/) {
1687 resolve_local_globs($u, $fetch,
1688 $remotes->{$repo_id}->{$_});
1690 my $p = $path;
1691 my $rwr = rewrite_root({repo_id => $repo_id});
1692 my $svm = $remotes->{$repo_id}->{svm}
1693 if defined $remotes->{$repo_id}->{svm};
1694 unless (defined $p) {
1695 $p = $full_url;
1696 my $z = $u;
1697 my $prefix = '';
1698 if ($rwr) {
1699 $z = $rwr;
1700 remove_username($z);
1701 } elsif (defined $svm) {
1702 $z = $svm->{source};
1703 $prefix = $svm->{replace};
1704 $prefix =~ s#^\Q$u\E(?:/|$)##;
1705 $prefix =~ s#/$##;
1707 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
1709 foreach my $f (keys %$fetch) {
1710 next if $f ne $p;
1711 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1714 undef;
1717 sub init {
1718 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1719 my $self = _new($class, $repo_id, $ref_id, $path);
1720 if (defined $url) {
1721 $self->init_remote_config($url, $no_write);
1723 $self;
1726 sub find_ref {
1727 my ($ref_id) = @_;
1728 foreach (command(qw/config -l/)) {
1729 next unless m!^svn-remote\.(.+)\.fetch=
1730 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1731 my ($repo_id, $path, $ref) = ($1, $2, $3);
1732 if ($ref eq $ref_id) {
1733 $path = '' if ($path =~ m#^\./?#);
1734 return ($repo_id, $path);
1737 (undef, undef, undef);
1740 sub new {
1741 my ($class, $ref_id, $repo_id, $path) = @_;
1742 if (defined $ref_id && !defined $repo_id && !defined $path) {
1743 ($repo_id, $path) = find_ref($ref_id);
1744 if (!defined $repo_id) {
1745 die "Could not find a \"svn-remote.*.fetch\" key ",
1746 "in the repository configuration matching: ",
1747 "refs/remotes/$ref_id\n";
1750 my $self = _new($class, $repo_id, $ref_id, $path);
1751 if (!defined $self->{path} || !length $self->{path}) {
1752 my $fetch = command_oneline('config', '--get',
1753 "svn-remote.$repo_id.fetch",
1754 ":refs/remotes/$ref_id\$") or
1755 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1756 "\":refs/remotes/$ref_id\$\" in config\n";
1757 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1759 $self->{url} = command_oneline('config', '--get',
1760 "svn-remote.$repo_id.url") or
1761 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1762 $self->rebuild;
1763 $self;
1766 sub refname {
1767 my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1769 # It cannot end with a slash /, we'll throw up on this because
1770 # SVN can't have directories with a slash in their name, either:
1771 if ($refname =~ m{/$}) {
1772 die "ref: '$refname' ends with a trailing slash, this is ",
1773 "not permitted by git nor Subversion\n";
1776 # It cannot have ASCII control character space, tilde ~, caret ^,
1777 # colon :, question-mark ?, asterisk *, space, or open bracket [
1778 # anywhere.
1780 # Additionally, % must be escaped because it is used for escaping
1781 # and we want our escaped refname to be reversible
1782 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1784 # no slash-separated component can begin with a dot .
1785 # /.* becomes /%2E*
1786 $refname =~ s{/\.}{/%2E}g;
1788 # It cannot have two consecutive dots .. anywhere
1789 # .. becomes %2E%2E
1790 $refname =~ s{\.\.}{%2E%2E}g;
1792 return $refname;
1795 sub desanitize_refname {
1796 my ($refname) = @_;
1797 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1798 return $refname;
1801 sub svm_uuid {
1802 my ($self) = @_;
1803 return $self->{svm}->{uuid} if $self->svm;
1804 $self->ra;
1805 unless ($self->{svm}) {
1806 die "SVM UUID not cached, and reading remotely failed\n";
1808 $self->{svm}->{uuid};
1811 sub svm {
1812 my ($self) = @_;
1813 return $self->{svm} if $self->{svm};
1814 my $svm;
1815 # see if we have it in our config, first:
1816 eval {
1817 my $section = "svn-remote.$self->{repo_id}";
1818 $svm = {
1819 source => tmp_config('--get', "$section.svm-source"),
1820 uuid => tmp_config('--get', "$section.svm-uuid"),
1821 replace => tmp_config('--get', "$section.svm-replace"),
1824 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1825 $self->{svm} = $svm;
1827 $self->{svm};
1830 sub _set_svm_vars {
1831 my ($self, $ra) = @_;
1832 return $ra if $self->svm;
1834 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1835 "(svm:source, svm:uuid) ",
1836 "from the following URLs:\n" );
1837 sub read_svm_props {
1838 my ($self, $ra, $path, $r) = @_;
1839 my $props = ($ra->get_dir($path, $r))[2];
1840 my $src = $props->{'svm:source'};
1841 my $uuid = $props->{'svm:uuid'};
1842 return undef if (!$src || !$uuid);
1844 chomp($src, $uuid);
1846 $uuid =~ m{^[0-9a-f\-]{30,}$}
1847 or die "doesn't look right - svm:uuid is '$uuid'\n";
1849 # the '!' is used to mark the repos_root!/relative/path
1850 $src =~ s{/?!/?}{/};
1851 $src =~ s{/+$}{}; # no trailing slashes please
1852 # username is of no interest
1853 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1855 my $replace = $ra->{url};
1856 $replace .= "/$path" if length $path;
1858 my $section = "svn-remote.$self->{repo_id}";
1859 tmp_config("$section.svm-source", $src);
1860 tmp_config("$section.svm-replace", $replace);
1861 tmp_config("$section.svm-uuid", $uuid);
1862 $self->{svm} = {
1863 source => $src,
1864 uuid => $uuid,
1865 replace => $replace
1869 my $r = $ra->get_latest_revnum;
1870 my $path = $self->{path};
1871 my %tried;
1872 while (length $path) {
1873 unless ($tried{"$self->{url}/$path"}) {
1874 return $ra if $self->read_svm_props($ra, $path, $r);
1875 $tried{"$self->{url}/$path"} = 1;
1877 $path =~ s#/?[^/]+$##;
1879 die "Path: '$path' should be ''\n" if $path ne '';
1880 return $ra if $self->read_svm_props($ra, $path, $r);
1881 $tried{"$self->{url}/$path"} = 1;
1883 if ($ra->{repos_root} eq $self->{url}) {
1884 die @err, (map { " $_\n" } keys %tried), "\n";
1887 # nope, make sure we're connected to the repository root:
1888 my $ok;
1889 my @tried_b;
1890 $path = $ra->{svn_path};
1891 $ra = Git::SVN::Ra->new($ra->{repos_root});
1892 while (length $path) {
1893 unless ($tried{"$ra->{url}/$path"}) {
1894 $ok = $self->read_svm_props($ra, $path, $r);
1895 last if $ok;
1896 $tried{"$ra->{url}/$path"} = 1;
1898 $path =~ s#/?[^/]+$##;
1900 die "Path: '$path' should be ''\n" if $path ne '';
1901 $ok ||= $self->read_svm_props($ra, $path, $r);
1902 $tried{"$ra->{url}/$path"} = 1;
1903 if (!$ok) {
1904 die @err, (map { " $_\n" } keys %tried), "\n";
1906 Git::SVN::Ra->new($self->{url});
1909 sub svnsync {
1910 my ($self) = @_;
1911 return $self->{svnsync} if $self->{svnsync};
1913 if ($self->no_metadata) {
1914 die "Can't have both 'noMetadata' and ",
1915 "'useSvnsyncProps' options set!\n";
1917 if ($self->rewrite_root) {
1918 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1919 "options set!\n";
1922 my $svnsync;
1923 # see if we have it in our config, first:
1924 eval {
1925 my $section = "svn-remote.$self->{repo_id}";
1927 my $url = tmp_config('--get', "$section.svnsync-url");
1928 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
1929 die "doesn't look right - svn:sync-from-url is '$url'\n";
1931 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
1932 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
1933 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1935 $svnsync = { url => $url, uuid => $uuid }
1937 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1938 return $self->{svnsync} = $svnsync;
1941 my $err = "useSvnsyncProps set, but failed to read " .
1942 "svnsync property: svn:sync-from-";
1943 my $rp = $self->ra->rev_proplist(0);
1945 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
1946 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
1947 die "doesn't look right - svn:sync-from-url is '$url'\n";
1949 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
1950 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
1951 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1953 my $section = "svn-remote.$self->{repo_id}";
1954 tmp_config('--add', "$section.svnsync-uuid", $uuid);
1955 tmp_config('--add', "$section.svnsync-url", $url);
1956 return $self->{svnsync} = { url => $url, uuid => $uuid };
1959 # this allows us to memoize our SVN::Ra UUID locally and avoid a
1960 # remote lookup (useful for 'git svn log').
1961 sub ra_uuid {
1962 my ($self) = @_;
1963 unless ($self->{ra_uuid}) {
1964 my $key = "svn-remote.$self->{repo_id}.uuid";
1965 my $uuid = eval { tmp_config('--get', $key) };
1966 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1967 $self->{ra_uuid} = $uuid;
1968 } else {
1969 die "ra_uuid called without URL\n" unless $self->{url};
1970 $self->{ra_uuid} = $self->ra->get_uuid;
1971 tmp_config('--add', $key, $self->{ra_uuid});
1974 $self->{ra_uuid};
1977 sub _set_repos_root {
1978 my ($self, $repos_root) = @_;
1979 my $k = "svn-remote.$self->{repo_id}.reposRoot";
1980 $repos_root ||= $self->ra->{repos_root};
1981 tmp_config($k, $repos_root);
1982 $repos_root;
1985 sub repos_root {
1986 my ($self) = @_;
1987 my $k = "svn-remote.$self->{repo_id}.reposRoot";
1988 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
1991 sub ra {
1992 my ($self) = shift;
1993 my $ra = Git::SVN::Ra->new($self->{url});
1994 $self->_set_repos_root($ra->{repos_root});
1995 if ($self->use_svm_props && !$self->{svm}) {
1996 if ($self->no_metadata) {
1997 die "Can't have both 'noMetadata' and ",
1998 "'useSvmProps' options set!\n";
1999 } elsif ($self->use_svnsync_props) {
2000 die "Can't have both 'useSvnsyncProps' and ",
2001 "'useSvmProps' options set!\n";
2003 $ra = $self->_set_svm_vars($ra);
2004 $self->{-want_revprops} = 1;
2006 $ra;
2009 sub rel_path {
2010 my ($self) = @_;
2011 my $repos_root = $self->ra->{repos_root};
2012 return $self->{path} if ($self->{url} eq $repos_root);
2013 my $url = $self->{url} .
2014 (length $self->{path} ? "/$self->{path}" : $self->{path});
2015 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
2016 $url;
2019 # prop_walk(PATH, REV, SUB)
2020 # -------------------------
2021 # Recursively traverse PATH at revision REV and invoke SUB for each
2022 # directory that contains a SVN property. SUB will be invoked as
2023 # follows: &SUB(gs, path, props); where `gs' is this instance of
2024 # Git::SVN, `path' the path to the directory where the properties
2025 # `props' were found. The `path' will be relative to point of checkout,
2026 # that is, if url://repo/trunk is the current Git branch, and that
2027 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
2028 # as `path' (note the trailing `/').
2029 sub prop_walk {
2030 my ($self, $path, $rev, $sub) = @_;
2032 $path =~ s#^/##;
2033 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2034 $path =~ s#^/*#/#g;
2035 my $p = $path;
2036 # Strip the irrelevant part of the path.
2037 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2038 # Ensure the path is terminated by a `/'.
2039 $p =~ s#/*$#/#;
2041 # The properties contain all the internal SVN stuff nobody
2042 # (usually) cares about.
2043 my $interesting_props = 0;
2044 foreach (keys %{$props}) {
2045 # If it doesn't start with `svn:', it must be a
2046 # user-defined property.
2047 ++$interesting_props and next if $_ !~ /^svn:/;
2048 # FIXME: Fragile, if SVN adds new public properties,
2049 # this needs to be updated.
2050 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2051 |eol-style|mime-type
2052 |externals|needs-lock)$/x;
2054 &$sub($self, $p, $props) if $interesting_props;
2056 foreach (sort keys %$dirent) {
2057 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
2058 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
2062 sub last_rev { ($_[0]->last_rev_commit)[0] }
2063 sub last_commit { ($_[0]->last_rev_commit)[1] }
2065 # returns the newest SVN revision number and newest commit SHA1
2066 sub last_rev_commit {
2067 my ($self) = @_;
2068 if (defined $self->{last_rev} && defined $self->{last_commit}) {
2069 return ($self->{last_rev}, $self->{last_commit});
2071 my $c = ::verify_ref($self->refname.'^0');
2072 if ($c && !$self->use_svm_props && !$self->no_metadata) {
2073 my $rev = (::cmt_metadata($c))[1];
2074 if (defined $rev) {
2075 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2076 return ($rev, $c);
2079 my $map_path = $self->map_path;
2080 unless (-e $map_path) {
2081 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2082 return (undef, undef);
2084 my ($rev, $commit) = $self->rev_map_max(1);
2085 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2086 return ($rev, $commit);
2089 sub get_fetch_range {
2090 my ($self, $min, $max) = @_;
2091 $max ||= $self->ra->get_latest_revnum;
2092 $min ||= $self->rev_map_max;
2093 (++$min, $max);
2096 sub tmp_config {
2097 my (@args) = @_;
2098 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2099 my $config = "$ENV{GIT_DIR}/svn/.metadata";
2100 if (! -f $config && -f $old_def_config) {
2101 rename $old_def_config, $config or
2102 die "Failed rename $old_def_config => $config: $!\n";
2104 my $old_config = $ENV{GIT_CONFIG};
2105 $ENV{GIT_CONFIG} = $config;
2106 $@ = undef;
2107 my @ret = eval {
2108 unless (-f $config) {
2109 mkfile($config);
2110 open my $fh, '>', $config or
2111 die "Can't open $config: $!\n";
2112 print $fh "; This file is used internally by ",
2113 "git-svn\n" or die
2114 "Couldn't write to $config: $!\n";
2115 print $fh "; You should not have to edit it\n" or
2116 die "Couldn't write to $config: $!\n";
2117 close $fh or die "Couldn't close $config: $!\n";
2119 command('config', @args);
2121 my $err = $@;
2122 if (defined $old_config) {
2123 $ENV{GIT_CONFIG} = $old_config;
2124 } else {
2125 delete $ENV{GIT_CONFIG};
2127 die $err if $err;
2128 wantarray ? @ret : $ret[0];
2131 sub tmp_index_do {
2132 my ($self, $sub) = @_;
2133 my $old_index = $ENV{GIT_INDEX_FILE};
2134 $ENV{GIT_INDEX_FILE} = $self->{index};
2135 $@ = undef;
2136 my @ret = eval {
2137 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2138 mkpath([$dir]) unless -d $dir;
2139 &$sub;
2141 my $err = $@;
2142 if (defined $old_index) {
2143 $ENV{GIT_INDEX_FILE} = $old_index;
2144 } else {
2145 delete $ENV{GIT_INDEX_FILE};
2147 die $err if $err;
2148 wantarray ? @ret : $ret[0];
2151 sub assert_index_clean {
2152 my ($self, $treeish) = @_;
2154 $self->tmp_index_do(sub {
2155 command_noisy('read-tree', $treeish) unless -e $self->{index};
2156 my $x = command_oneline('write-tree');
2157 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2158 /^tree ($::sha1)/mo);
2159 return if $y eq $x;
2161 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2162 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2163 command_noisy('read-tree', $treeish);
2164 $x = command_oneline('write-tree');
2165 if ($y ne $x) {
2166 ::fatal "trees ($treeish) $y != $x\n",
2167 "Something is seriously wrong...";
2172 sub get_commit_parents {
2173 my ($self, $log_entry) = @_;
2174 my (%seen, @ret, @tmp);
2175 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2176 if (my $ip = $self->{inject_parents}) {
2177 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2178 push @tmp, $commit;
2181 if (my $cur = ::verify_ref($self->refname.'^0')) {
2182 push @tmp, $cur;
2184 if (my $ipd = $self->{inject_parents_dcommit}) {
2185 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2186 push @tmp, @$commit;
2189 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2190 while (my $p = shift @tmp) {
2191 next if $seen{$p};
2192 $seen{$p} = 1;
2193 push @ret, $p;
2194 # MAXPARENT is defined to 16 in commit-tree.c:
2195 last if @ret >= 16;
2197 if (@tmp) {
2198 die "r$log_entry->{revision}: No room for parents:\n\t",
2199 join("\n\t", @tmp), "\n";
2201 @ret;
2204 sub rewrite_root {
2205 my ($self) = @_;
2206 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2207 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2208 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2209 if ($rwr) {
2210 $rwr =~ s#/+$##;
2211 if ($rwr !~ m#^[a-z\+]+://#) {
2212 die "$rwr is not a valid URL (key: $k)\n";
2215 $self->{-rewrite_root} = $rwr;
2218 sub metadata_url {
2219 my ($self) = @_;
2220 ($self->rewrite_root || $self->{url}) .
2221 (length $self->{path} ? '/' . $self->{path} : '');
2224 sub full_url {
2225 my ($self) = @_;
2226 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2230 sub set_commit_header_env {
2231 my ($log_entry) = @_;
2232 my %env;
2233 foreach my $ned (qw/NAME EMAIL DATE/) {
2234 foreach my $ac (qw/AUTHOR COMMITTER/) {
2235 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2239 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2240 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2241 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2243 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2244 ? $log_entry->{commit_name}
2245 : $log_entry->{name};
2246 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2247 ? $log_entry->{commit_email}
2248 : $log_entry->{email};
2249 \%env;
2252 sub restore_commit_header_env {
2253 my ($env) = @_;
2254 foreach my $ned (qw/NAME EMAIL DATE/) {
2255 foreach my $ac (qw/AUTHOR COMMITTER/) {
2256 my $k = "GIT_${ac}_${ned}";
2257 if (defined $env->{$k}) {
2258 $ENV{$k} = $env->{$k};
2259 } else {
2260 delete $ENV{$k};
2266 sub gc {
2267 command_noisy('gc', '--auto');
2270 sub do_git_commit {
2271 my ($self, $log_entry) = @_;
2272 my $lr = $self->last_rev;
2273 if (defined $lr && $lr >= $log_entry->{revision}) {
2274 die "Last fetched revision of ", $self->refname,
2275 " was r$lr, but we are about to fetch: ",
2276 "r$log_entry->{revision}!\n";
2278 if (my $c = $self->rev_map_get($log_entry->{revision})) {
2279 croak "$log_entry->{revision} = $c already exists! ",
2280 "Why are we refetching it?\n";
2282 my $old_env = set_commit_header_env($log_entry);
2283 my $tree = $log_entry->{tree};
2284 if (!defined $tree) {
2285 $tree = $self->tmp_index_do(sub {
2286 command_oneline('write-tree') });
2288 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2290 my @exec = ('git', 'commit-tree', $tree);
2291 foreach ($self->get_commit_parents($log_entry)) {
2292 push @exec, '-p', $_;
2294 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2295 or croak $!;
2296 binmode $msg_fh;
2298 # we always get UTF-8 from SVN, but we may want our commits in
2299 # a different encoding.
2300 if (my $enc = Git::config('i18n.commitencoding')) {
2301 require Encode;
2302 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
2304 print $msg_fh $log_entry->{log} or croak $!;
2305 restore_commit_header_env($old_env);
2306 unless ($self->no_metadata) {
2307 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2308 or croak $!;
2310 $msg_fh->flush == 0 or croak $!;
2311 close $msg_fh or croak $!;
2312 chomp(my $commit = do { local $/; <$out_fh> });
2313 close $out_fh or croak $!;
2314 waitpid $pid, 0;
2315 croak $? if $?;
2316 if ($commit !~ /^$::sha1$/o) {
2317 die "Failed to commit, invalid sha1: $commit\n";
2320 $self->rev_map_set($log_entry->{revision}, $commit, 1);
2322 $self->{last_rev} = $log_entry->{revision};
2323 $self->{last_commit} = $commit;
2324 print "r$log_entry->{revision}";
2325 if (defined $log_entry->{svm_revision}) {
2326 print " (\@$log_entry->{svm_revision})";
2327 $self->rev_map_set($log_entry->{svm_revision}, $commit,
2328 0, $self->svm_uuid);
2330 print " = $commit ($self->{ref_id})\n";
2331 if (--$_gc_nr == 0) {
2332 $_gc_nr = $_gc_period;
2333 gc();
2335 return $commit;
2338 sub match_paths {
2339 my ($self, $paths, $r) = @_;
2340 return 1 if $self->{path} eq '';
2341 if (my $path = $paths->{"/$self->{path}"}) {
2342 return ($path->{action} eq 'D') ? 0 : 1;
2344 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
2345 if (grep /$self->{path_regex}/, keys %$paths) {
2346 return 1;
2348 my $c = '';
2349 foreach (split m#/#, $self->{path}) {
2350 $c .= "/$_";
2351 next unless ($paths->{$c} &&
2352 ($paths->{$c}->{action} =~ /^[AR]$/));
2353 if ($self->ra->check_path($self->{path}, $r) ==
2354 $SVN::Node::dir) {
2355 return 1;
2358 return 0;
2361 sub find_parent_branch {
2362 my ($self, $paths, $rev) = @_;
2363 return undef unless $self->follow_parent;
2364 unless (defined $paths) {
2365 my $err_handler = $SVN::Error::handler;
2366 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2367 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
2368 $paths =
2369 Git::SVN::Ra::dup_changed_paths($_[0]) });
2370 $SVN::Error::handler = $err_handler;
2372 return undef unless defined $paths;
2374 # look for a parent from another branch:
2375 my @b_path_components = split m#/#, $self->rel_path;
2376 my @a_path_components;
2377 my $i;
2378 while (@b_path_components) {
2379 $i = $paths->{'/'.join('/', @b_path_components)};
2380 last if $i && defined $i->{copyfrom_path};
2381 unshift(@a_path_components, pop(@b_path_components));
2383 return undef unless defined $i && defined $i->{copyfrom_path};
2384 my $branch_from = $i->{copyfrom_path};
2385 if (@a_path_components) {
2386 print STDERR "branch_from: $branch_from => ";
2387 $branch_from .= '/'.join('/', @a_path_components);
2388 print STDERR $branch_from, "\n";
2390 my $r = $i->{copyfrom_rev};
2391 my $repos_root = $self->ra->{repos_root};
2392 my $url = $self->ra->{url};
2393 my $new_url = $repos_root . $branch_from;
2394 print STDERR "Found possible branch point: ",
2395 "$new_url => ", $self->full_url, ", $r\n";
2396 $branch_from =~ s#^/##;
2397 my $gs = $self->other_gs($new_url, $url, $repos_root,
2398 $branch_from, $r, $self->{ref_id});
2399 my ($r0, $parent) = $gs->find_rev_before($r, 1);
2401 my ($base, $head);
2402 if (!defined $r0 || !defined $parent) {
2403 ($base, $head) = parse_revision_argument(0, $r);
2404 } else {
2405 if ($r0 < $r) {
2406 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
2407 0, 1, sub { $base = $_[1] - 1 });
2410 if (defined $base && $base <= $r) {
2411 $gs->fetch($base, $r);
2413 ($r0, $parent) = $gs->find_rev_before($r, 1);
2415 if (defined $r0 && defined $parent) {
2416 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
2417 my $ed;
2418 if ($self->ra->can_do_switch) {
2419 $self->assert_index_clean($parent);
2420 print STDERR "Following parent with do_switch\n";
2421 # do_switch works with svn/trunk >= r22312, but that
2422 # is not included with SVN 1.4.3 (the latest version
2423 # at the moment), so we can't rely on it
2424 $self->{last_rev} = $r0;
2425 $self->{last_commit} = $parent;
2426 $ed = SVN::Git::Fetcher->new($self, $gs->{path});
2427 $gs->ra->gs_do_switch($r0, $rev, $gs,
2428 $self->full_url, $ed)
2429 or die "SVN connection failed somewhere...\n";
2430 } elsif ($self->ra->trees_match($new_url, $r0,
2431 $self->full_url, $rev)) {
2432 print STDERR "Trees match:\n",
2433 " $new_url\@$r0\n",
2434 " ${\$self->full_url}\@$rev\n",
2435 "Following parent with no changes\n";
2436 $self->tmp_index_do(sub {
2437 command_noisy('read-tree', $parent);
2439 $self->{last_commit} = $parent;
2440 } else {
2441 print STDERR "Following parent with do_update\n";
2442 $ed = SVN::Git::Fetcher->new($self);
2443 $self->ra->gs_do_update($rev, $rev, $self, $ed)
2444 or die "SVN connection failed somewhere...\n";
2446 print STDERR "Successfully followed parent\n";
2447 return $self->make_log_entry($rev, [$parent], $ed);
2449 return undef;
2452 sub do_fetch {
2453 my ($self, $paths, $rev) = @_;
2454 my $ed;
2455 my ($last_rev, @parents);
2456 if (my $lc = $self->last_commit) {
2457 # we can have a branch that was deleted, then re-added
2458 # under the same name but copied from another path, in
2459 # which case we'll have multiple parents (we don't
2460 # want to break the original ref, nor lose copypath info):
2461 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2462 push @{$log_entry->{parents}}, $lc;
2463 return $log_entry;
2465 $ed = SVN::Git::Fetcher->new($self);
2466 $last_rev = $self->{last_rev};
2467 $ed->{c} = $lc;
2468 @parents = ($lc);
2469 } else {
2470 $last_rev = $rev;
2471 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2472 return $log_entry;
2474 $ed = SVN::Git::Fetcher->new($self);
2476 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2477 die "SVN connection failed somewhere...\n";
2479 $self->make_log_entry($rev, \@parents, $ed);
2482 sub get_untracked {
2483 my ($self, $ed) = @_;
2484 my @out;
2485 my $h = $ed->{empty};
2486 foreach (sort keys %$h) {
2487 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2488 push @out, " $act: " . uri_encode($_);
2489 warn "W: $act: $_\n";
2491 foreach my $t (qw/dir_prop file_prop/) {
2492 $h = $ed->{$t} or next;
2493 foreach my $path (sort keys %$h) {
2494 my $ppath = $path eq '' ? '.' : $path;
2495 foreach my $prop (sort keys %{$h->{$path}}) {
2496 next if $SKIP_PROP{$prop};
2497 my $v = $h->{$path}->{$prop};
2498 my $t_ppath_prop = "$t: " .
2499 uri_encode($ppath) . ' ' .
2500 uri_encode($prop);
2501 if (defined $v) {
2502 push @out, " +$t_ppath_prop " .
2503 uri_encode($v);
2504 } else {
2505 push @out, " -$t_ppath_prop";
2510 foreach my $t (qw/absent_file absent_directory/) {
2511 $h = $ed->{$t} or next;
2512 foreach my $parent (sort keys %$h) {
2513 foreach my $path (sort @{$h->{$parent}}) {
2514 push @out, " $t: " .
2515 uri_encode("$parent/$path");
2516 warn "W: $t: $parent/$path ",
2517 "Insufficient permissions?\n";
2521 \@out;
2524 # parse_svn_date(DATE)
2525 # --------------------
2526 # Given a date (in UTC) from Subversion, return a string in the format
2527 # "<TZ Offset> <local date/time>" that Git will use.
2529 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
2530 # is true we'll convert it to the local timezone instead.
2531 sub parse_svn_date {
2532 my $date = shift || return '+0000 1970-01-01 00:00:00';
2533 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2534 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
2535 croak "Unable to parse date: $date\n";
2536 my $parsed_date; # Set next.
2538 if ($Git::SVN::_localtime) {
2539 # Translate the Subversion datetime to an epoch time.
2540 # Begin by switching ourselves to $date's timezone, UTC.
2541 my $old_env_TZ = $ENV{TZ};
2542 $ENV{TZ} = 'UTC';
2544 my $epoch_in_UTC =
2545 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
2547 # Determine our local timezone (including DST) at the
2548 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
2549 # value of TZ, if any, at the time we were run.
2550 if (defined $Git::SVN::Log::TZ) {
2551 $ENV{TZ} = $Git::SVN::Log::TZ;
2552 } else {
2553 delete $ENV{TZ};
2556 my $our_TZ =
2557 POSIX::strftime('%Z', $S, $M, $H, $d, $m - 1, $Y - 1900);
2559 # This converts $epoch_in_UTC into our local timezone.
2560 my ($sec, $min, $hour, $mday, $mon, $year,
2561 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
2563 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
2564 $our_TZ, $year + 1900, $mon + 1,
2565 $mday, $hour, $min, $sec);
2567 # Reset us to the timezone in effect when we entered
2568 # this routine.
2569 if (defined $old_env_TZ) {
2570 $ENV{TZ} = $old_env_TZ;
2571 } else {
2572 delete $ENV{TZ};
2574 } else {
2575 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
2578 return $parsed_date;
2581 sub other_gs {
2582 my ($self, $new_url, $url, $repos_root,
2583 $branch_from, $r, $old_ref_id) = @_;
2584 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
2585 unless ($gs) {
2586 my $ref_id = $old_ref_id;
2587 $ref_id =~ s/\@\d+$//;
2588 $ref_id .= "\@$r";
2589 # just grow a tail if we're not unique enough :x
2590 $ref_id .= '-' while find_ref($ref_id);
2591 print STDERR "Initializing parent: $ref_id\n";
2592 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
2593 if ($u =~ s#^\Q$url\E(/|$)##) {
2594 $p = $u;
2595 $u = $url;
2596 $repo_id = $self->{repo_id};
2598 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
2603 sub check_author {
2604 my ($author) = @_;
2605 if (!defined $author || length $author == 0) {
2606 $author = '(no author)';
2607 } elsif (defined $::_authors && ! defined $::users{$author}) {
2608 die "Author: $author not defined in $::_authors file\n";
2610 $author;
2613 sub make_log_entry {
2614 my ($self, $rev, $parents, $ed) = @_;
2615 my $untracked = $self->get_untracked($ed);
2617 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
2618 print $un "r$rev\n" or croak $!;
2619 print $un $_, "\n" foreach @$untracked;
2620 my %log_entry = ( parents => $parents || [], revision => $rev,
2621 log => '');
2623 my $headrev;
2624 my $logged = delete $self->{logged_rev_props};
2625 if (!$logged || $self->{-want_revprops}) {
2626 my $rp = $self->ra->rev_proplist($rev);
2627 foreach (sort keys %$rp) {
2628 my $v = $rp->{$_};
2629 if (/^svn:(author|date|log)$/) {
2630 $log_entry{$1} = $v;
2631 } elsif ($_ eq 'svm:headrev') {
2632 $headrev = $v;
2633 } else {
2634 print $un " rev_prop: ", uri_encode($_), ' ',
2635 uri_encode($v), "\n";
2638 } else {
2639 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
2641 close $un or croak $!;
2643 $log_entry{date} = parse_svn_date($log_entry{date});
2644 $log_entry{log} .= "\n";
2645 my $author = $log_entry{author} = check_author($log_entry{author});
2646 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
2647 : ($author, undef);
2649 my ($commit_name, $commit_email) = ($name, $email);
2650 if ($_use_log_author) {
2651 my $name_field;
2652 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
2653 $name_field = $1;
2654 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
2655 $name_field = $1;
2657 if (!defined $name_field) {
2658 if (!defined $email) {
2659 $email = $name;
2661 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
2662 ($name, $email) = ($1, $2);
2663 } elsif ($name_field =~ /(.*)@/) {
2664 ($name, $email) = ($1, $name_field);
2665 } else {
2666 ($name, $email) = ($name_field, $name_field);
2669 if (defined $headrev && $self->use_svm_props) {
2670 if ($self->rewrite_root) {
2671 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2672 "options set!\n";
2674 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
2675 # we don't want "SVM: initializing mirror for junk" ...
2676 return undef if $r == 0;
2677 my $svm = $self->svm;
2678 if ($uuid ne $svm->{uuid}) {
2679 die "UUID mismatch on SVM path:\n",
2680 "expected: $svm->{uuid}\n",
2681 " got: $uuid\n";
2683 my $full_url = $self->full_url;
2684 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2685 die "Failed to replace '$svm->{replace}' with ",
2686 "'$svm->{source}' in $full_url\n";
2687 # throw away username for storing in records
2688 remove_username($full_url);
2689 $log_entry{metadata} = "$full_url\@$r $uuid";
2690 $log_entry{svm_revision} = $r;
2691 $email ||= "$author\@$uuid";
2692 $commit_email ||= "$author\@$uuid";
2693 } elsif ($self->use_svnsync_props) {
2694 my $full_url = $self->svnsync->{url};
2695 $full_url .= "/$self->{path}" if length $self->{path};
2696 remove_username($full_url);
2697 my $uuid = $self->svnsync->{uuid};
2698 $log_entry{metadata} = "$full_url\@$rev $uuid";
2699 $email ||= "$author\@$uuid";
2700 $commit_email ||= "$author\@$uuid";
2701 } else {
2702 my $url = $self->metadata_url;
2703 remove_username($url);
2704 $log_entry{metadata} = "$url\@$rev " .
2705 $self->ra->get_uuid;
2706 $email ||= "$author\@" . $self->ra->get_uuid;
2707 $commit_email ||= "$author\@" . $self->ra->get_uuid;
2709 $log_entry{name} = $name;
2710 $log_entry{email} = $email;
2711 $log_entry{commit_name} = $commit_name;
2712 $log_entry{commit_email} = $commit_email;
2713 \%log_entry;
2716 sub fetch {
2717 my ($self, $min_rev, $max_rev, @parents) = @_;
2718 my ($last_rev, $last_commit) = $self->last_rev_commit;
2719 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2720 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2723 sub set_tree_cb {
2724 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2725 $self->{inject_parents} = { $rev => $tree };
2726 $self->fetch(undef, undef);
2729 sub set_tree {
2730 my ($self, $tree) = (shift, shift);
2731 my $log_entry = ::get_commit_entry($tree);
2732 unless ($self->{last_rev}) {
2733 ::fatal("Must have an existing revision to commit");
2735 my %ed_opts = ( r => $self->{last_rev},
2736 log => $log_entry->{log},
2737 ra => $self->ra,
2738 tree_a => $self->{last_commit},
2739 tree_b => $tree,
2740 editor_cb => sub {
2741 $self->set_tree_cb($log_entry, $tree, @_) },
2742 svn_path => $self->{path} );
2743 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2744 print "No changes\nr$self->{last_rev} = $tree\n";
2748 sub rebuild_from_rev_db {
2749 my ($self, $path) = @_;
2750 my $r = -1;
2751 open my $fh, '<', $path or croak "open: $!";
2752 binmode $fh or croak "binmode: $!";
2753 while (<$fh>) {
2754 length($_) == 41 or croak "inconsistent size in ($_) != 41";
2755 chomp($_);
2756 ++$r;
2757 next if $_ eq ('0' x 40);
2758 $self->rev_map_set($r, $_);
2759 print "r$r = $_\n";
2761 close $fh or croak "close: $!";
2762 unlink $path or croak "unlink: $!";
2765 sub rebuild {
2766 my ($self) = @_;
2767 my $map_path = $self->map_path;
2768 my $partial = (-e $map_path && ! -z $map_path);
2769 return unless ::verify_ref($self->refname.'^0');
2770 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
2771 my $rev_db = $self->rev_db_path;
2772 $self->rebuild_from_rev_db($rev_db);
2773 if ($self->use_svm_props) {
2774 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
2775 $self->rebuild_from_rev_db($svm_rev_db);
2777 $self->unlink_rev_db_symlink;
2778 return;
2780 print "Rebuilding $map_path ...\n" if (!$partial);
2781 my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
2782 (undef, undef));
2783 my ($log, $ctx) =
2784 command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
2785 ($head ? "$head.." : "") . $self->refname,
2786 '--');
2787 my $metadata_url = $self->metadata_url;
2788 remove_username($metadata_url);
2789 my $svn_uuid = $self->ra_uuid;
2790 my $c;
2791 while (<$log>) {
2792 if ( m{^commit ($::sha1)$} ) {
2793 $c = $1;
2794 next;
2796 next unless s{^\s*(git-svn-id:)}{$1};
2797 my ($url, $rev, $uuid) = ::extract_metadata($_);
2798 remove_username($url);
2800 # ignore merges (from set-tree)
2801 next if (!defined $rev || !$uuid);
2803 # if we merged or otherwise started elsewhere, this is
2804 # how we break out of it
2805 if (($uuid ne $svn_uuid) ||
2806 ($metadata_url && $url && ($url ne $metadata_url))) {
2807 next;
2809 if ($partial && $head) {
2810 print "Partial-rebuilding $map_path ...\n";
2811 print "Currently at $base_rev = $head\n";
2812 $head = undef;
2815 $self->rev_map_set($rev, $c);
2816 print "r$rev = $c\n";
2818 command_close_pipe($log, $ctx);
2819 print "Done rebuilding $map_path\n" if (!$partial || !$head);
2820 my $rev_db_path = $self->rev_db_path;
2821 if (-f $self->rev_db_path) {
2822 unlink $self->rev_db_path or croak "unlink: $!";
2824 $self->unlink_rev_db_symlink;
2827 # rev_map:
2828 # Tie::File seems to be prone to offset errors if revisions get sparse,
2829 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2830 # one of my favorite modules is out :< Next up would be one of the DBM
2831 # modules, but I'm not sure which is most portable...
2833 # This is the replacement for the rev_db format, which was too big
2834 # and inefficient for large repositories with a lot of sparse history
2835 # (mainly tags)
2837 # The format is this:
2838 # - 24 bytes for every record,
2839 # * 4 bytes for the integer representing an SVN revision number
2840 # * 20 bytes representing the sha1 of a git commit
2841 # - No empty padding records like the old format
2842 # (except the last record, which can be overwritten)
2843 # - new records are written append-only since SVN revision numbers
2844 # increase monotonically
2845 # - lookups on SVN revision number are done via a binary search
2846 # - Piping the file to xxd -c24 is a good way of dumping it for
2847 # viewing or editing (piped back through xxd -r), should the need
2848 # ever arise.
2849 # - The last record can be padding revision with an all-zero sha1
2850 # This is used to optimize fetch performance when using multiple
2851 # "fetch" directives in .git/config
2853 # These files are disposable unless noMetadata or useSvmProps is set
2855 sub _rev_map_set {
2856 my ($fh, $rev, $commit) = @_;
2858 binmode $fh or croak "binmode: $!";
2859 my $size = (stat($fh))[7];
2860 ($size % 24) == 0 or croak "inconsistent size: $size";
2862 my $wr_offset = 0;
2863 if ($size > 0) {
2864 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2865 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
2866 $read == 24 or croak "read only $read bytes (!= 24)";
2867 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
2868 if ($last_commit eq ('0' x40)) {
2869 if ($size >= 48) {
2870 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2871 $read = sysread($fh, $buf, 24) or
2872 croak "read: $!";
2873 $read == 24 or
2874 croak "read only $read bytes (!= 24)";
2875 ($last_rev, $last_commit) =
2876 unpack(rev_map_fmt, $buf);
2877 if ($last_commit eq ('0' x40)) {
2878 croak "inconsistent .rev_map\n";
2881 if ($last_rev >= $rev) {
2882 croak "last_rev is higher!: $last_rev >= $rev";
2884 $wr_offset = -24;
2887 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
2888 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
2889 croak "write: $!";
2892 sub mkfile {
2893 my ($path) = @_;
2894 unless (-e $path) {
2895 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2896 mkpath([$dir]) unless -d $dir;
2897 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2898 close $fh or die "Couldn't close (create) $path: $!\n";
2902 sub rev_map_set {
2903 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2904 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2905 my $db = $self->map_path($uuid);
2906 my $db_lock = "$db.lock";
2907 my $sig;
2908 if ($update_ref) {
2909 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2910 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2912 mkfile($db);
2914 $LOCKFILES{$db_lock} = 1;
2915 my $sync;
2916 # both of these options make our .rev_db file very, very important
2917 # and we can't afford to lose it because rebuild() won't work
2918 if ($self->use_svm_props || $self->no_metadata) {
2919 $sync = 1;
2920 copy($db, $db_lock) or die "rev_map_set(@_): ",
2921 "Failed to copy: ",
2922 "$db => $db_lock ($!)\n";
2923 } else {
2924 rename $db, $db_lock or die "rev_map_set(@_): ",
2925 "Failed to rename: ",
2926 "$db => $db_lock ($!)\n";
2929 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
2930 or croak "Couldn't open $db_lock: $!\n";
2931 _rev_map_set($fh, $rev, $commit);
2932 if ($sync) {
2933 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2934 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2936 close $fh or croak $!;
2937 if ($update_ref) {
2938 $_head = $self;
2939 command_noisy('update-ref', '-m', "r$rev",
2940 $self->refname, $commit);
2942 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
2943 "$db_lock => $db ($!)\n";
2944 delete $LOCKFILES{$db_lock};
2945 if ($update_ref) {
2946 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2947 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
2948 kill $sig, $$ if defined $sig;
2952 # If want_commit, this will return an array of (rev, commit) where
2953 # commit _must_ be a valid commit in the archive.
2954 # Otherwise, it'll return the max revision (whether or not the
2955 # commit is valid or just a 0x40 placeholder).
2956 sub rev_map_max {
2957 my ($self, $want_commit) = @_;
2958 $self->rebuild;
2959 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
2960 $want_commit ? ($r, $c) : $r;
2963 sub rev_map_max_norebuild {
2964 my ($self, $want_commit) = @_;
2965 my $map_path = $self->map_path;
2966 stat $map_path or return $want_commit ? (0, undef) : 0;
2967 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
2968 binmode $fh or croak "binmode: $!";
2969 my $size = (stat($fh))[7];
2970 ($size % 24) == 0 or croak "inconsistent size: $size";
2972 if ($size == 0) {
2973 close $fh or croak "close: $!";
2974 return $want_commit ? (0, undef) : 0;
2977 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2978 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
2979 my ($r, $c) = unpack(rev_map_fmt, $buf);
2980 if ($want_commit && $c eq ('0' x40)) {
2981 if ($size < 48) {
2982 return $want_commit ? (0, undef) : 0;
2984 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2985 sysread($fh, $buf, 24) == 24 or croak "read: $!";
2986 ($r, $c) = unpack(rev_map_fmt, $buf);
2987 if ($c eq ('0'x40)) {
2988 croak "Penultimate record is all-zeroes in $map_path";
2991 close $fh or croak "close: $!";
2992 $want_commit ? ($r, $c) : $r;
2995 sub rev_map_get {
2996 my ($self, $rev, $uuid) = @_;
2997 my $map_path = $self->map_path($uuid);
2998 return undef unless -e $map_path;
3000 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3001 binmode $fh or croak "binmode: $!";
3002 my $size = (stat($fh))[7];
3003 ($size % 24) == 0 or croak "inconsistent size: $size";
3005 if ($size == 0) {
3006 close $fh or croak "close: $fh";
3007 return undef;
3010 my ($l, $u) = (0, $size - 24);
3011 my ($r, $c, $buf);
3013 while ($l <= $u) {
3014 my $i = int(($l/24 + $u/24) / 2) * 24;
3015 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
3016 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3017 my ($r, $c) = unpack('NH40', $buf);
3019 if ($r < $rev) {
3020 $l = $i + 24;
3021 } elsif ($r > $rev) {
3022 $u = $i - 24;
3023 } else { # $r == $rev
3024 close($fh) or croak "close: $!";
3025 return $c eq ('0' x 40) ? undef : $c;
3028 close($fh) or croak "close: $!";
3029 undef;
3032 # Finds the first svn revision that exists on (if $eq_ok is true) or
3033 # before $rev for the current branch. It will not search any lower
3034 # than $min_rev. Returns the git commit hash and svn revision number
3035 # if found, else (undef, undef).
3036 sub find_rev_before {
3037 my ($self, $rev, $eq_ok, $min_rev) = @_;
3038 --$rev unless $eq_ok;
3039 $min_rev ||= 1;
3040 while ($rev >= $min_rev) {
3041 if (my $c = $self->rev_map_get($rev)) {
3042 return ($rev, $c);
3044 --$rev;
3046 return (undef, undef);
3049 # Finds the first svn revision that exists on (if $eq_ok is true) or
3050 # after $rev for the current branch. It will not search any higher
3051 # than $max_rev. Returns the git commit hash and svn revision number
3052 # if found, else (undef, undef).
3053 sub find_rev_after {
3054 my ($self, $rev, $eq_ok, $max_rev) = @_;
3055 ++$rev unless $eq_ok;
3056 $max_rev ||= $self->rev_map_max;
3057 while ($rev <= $max_rev) {
3058 if (my $c = $self->rev_map_get($rev)) {
3059 return ($rev, $c);
3061 ++$rev;
3063 return (undef, undef);
3066 sub _new {
3067 my ($class, $repo_id, $ref_id, $path) = @_;
3068 unless (defined $repo_id && length $repo_id) {
3069 $repo_id = $Git::SVN::default_repo_id;
3071 unless (defined $ref_id && length $ref_id) {
3072 $_[2] = $ref_id = $Git::SVN::default_ref_id;
3074 $_[1] = $repo_id;
3075 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
3076 $_[3] = $path = '' unless (defined $path);
3077 mkpath(["$ENV{GIT_DIR}/svn"]);
3078 bless {
3079 ref_id => $ref_id, dir => $dir, index => "$dir/index",
3080 path => $path, config => "$ENV{GIT_DIR}/svn/config",
3081 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
3084 # for read-only access of old .rev_db formats
3085 sub unlink_rev_db_symlink {
3086 my ($self) = @_;
3087 my $link = $self->rev_db_path;
3088 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
3089 if (-l $link) {
3090 unlink $link or croak "unlink: $link failed!";
3094 sub rev_db_path {
3095 my ($self, $uuid) = @_;
3096 my $db_path = $self->map_path($uuid);
3097 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
3098 or croak "map_path: $db_path does not contain '/.rev_map.' !";
3099 $db_path;
3102 # the new replacement for .rev_db
3103 sub map_path {
3104 my ($self, $uuid) = @_;
3105 $uuid ||= $self->ra_uuid;
3106 "$self->{map_root}.$uuid";
3109 sub uri_encode {
3110 my ($f) = @_;
3111 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
3115 sub remove_username {
3116 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
3119 package Git::SVN::Prompt;
3120 use strict;
3121 use warnings;
3122 require SVN::Core;
3123 use vars qw/$_no_auth_cache $_username/;
3125 sub simple {
3126 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
3127 $may_save = undef if $_no_auth_cache;
3128 $default_username = $_username if defined $_username;
3129 if (defined $default_username && length $default_username) {
3130 if (defined $realm && length $realm) {
3131 print STDERR "Authentication realm: $realm\n";
3132 STDERR->flush;
3134 $cred->username($default_username);
3135 } else {
3136 username($cred, $realm, $may_save, $pool);
3138 $cred->password(_read_password("Password for '" .
3139 $cred->username . "': ", $realm));
3140 $cred->may_save($may_save);
3141 $SVN::_Core::SVN_NO_ERROR;
3144 sub ssl_server_trust {
3145 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
3146 $may_save = undef if $_no_auth_cache;
3147 print STDERR "Error validating server certificate for '$realm':\n";
3149 no warnings 'once';
3150 # All variables SVN::Auth::SSL::* are used only once,
3151 # so we're shutting up Perl warnings about this.
3152 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
3153 print STDERR " - The certificate is not issued ",
3154 "by a trusted authority. Use the\n",
3155 " fingerprint to validate ",
3156 "the certificate manually!\n";
3158 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
3159 print STDERR " - The certificate hostname ",
3160 "does not match.\n";
3162 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
3163 print STDERR " - The certificate is not yet valid.\n";
3165 if ($failures & $SVN::Auth::SSL::EXPIRED) {
3166 print STDERR " - The certificate has expired.\n";
3168 if ($failures & $SVN::Auth::SSL::OTHER) {
3169 print STDERR " - The certificate has ",
3170 "an unknown error.\n";
3172 } # no warnings 'once'
3173 printf STDERR
3174 "Certificate information:\n".
3175 " - Hostname: %s\n".
3176 " - Valid: from %s until %s\n".
3177 " - Issuer: %s\n".
3178 " - Fingerprint: %s\n",
3179 map $cert_info->$_, qw(hostname valid_from valid_until
3180 issuer_dname fingerprint);
3181 my $choice;
3182 prompt:
3183 print STDERR $may_save ?
3184 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
3185 "(R)eject or accept (t)emporarily? ";
3186 STDERR->flush;
3187 $choice = lc(substr(<STDIN> || 'R', 0, 1));
3188 if ($choice =~ /^t$/i) {
3189 $cred->may_save(undef);
3190 } elsif ($choice =~ /^r$/i) {
3191 return -1;
3192 } elsif ($may_save && $choice =~ /^p$/i) {
3193 $cred->may_save($may_save);
3194 } else {
3195 goto prompt;
3197 $cred->accepted_failures($failures);
3198 $SVN::_Core::SVN_NO_ERROR;
3201 sub ssl_client_cert {
3202 my ($cred, $realm, $may_save, $pool) = @_;
3203 $may_save = undef if $_no_auth_cache;
3204 print STDERR "Client certificate filename: ";
3205 STDERR->flush;
3206 chomp(my $filename = <STDIN>);
3207 $cred->cert_file($filename);
3208 $cred->may_save($may_save);
3209 $SVN::_Core::SVN_NO_ERROR;
3212 sub ssl_client_cert_pw {
3213 my ($cred, $realm, $may_save, $pool) = @_;
3214 $may_save = undef if $_no_auth_cache;
3215 $cred->password(_read_password("Password: ", $realm));
3216 $cred->may_save($may_save);
3217 $SVN::_Core::SVN_NO_ERROR;
3220 sub username {
3221 my ($cred, $realm, $may_save, $pool) = @_;
3222 $may_save = undef if $_no_auth_cache;
3223 if (defined $realm && length $realm) {
3224 print STDERR "Authentication realm: $realm\n";
3226 my $username;
3227 if (defined $_username) {
3228 $username = $_username;
3229 } else {
3230 print STDERR "Username: ";
3231 STDERR->flush;
3232 chomp($username = <STDIN>);
3234 $cred->username($username);
3235 $cred->may_save($may_save);
3236 $SVN::_Core::SVN_NO_ERROR;
3239 sub _read_password {
3240 my ($prompt, $realm) = @_;
3241 print STDERR $prompt;
3242 STDERR->flush;
3243 require Term::ReadKey;
3244 Term::ReadKey::ReadMode('noecho');
3245 my $password = '';
3246 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
3247 last if $key =~ /[\012\015]/; # \n\r
3248 $password .= $key;
3250 Term::ReadKey::ReadMode('restore');
3251 print STDERR "\n";
3252 STDERR->flush;
3253 $password;
3256 package SVN::Git::Fetcher;
3257 use vars qw/@ISA/;
3258 use strict;
3259 use warnings;
3260 use Carp qw/croak/;
3261 use File::Temp qw/tempfile/;
3262 use IO::File qw//;
3263 use vars qw/$_ignore_regex/;
3265 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
3266 sub new {
3267 my ($class, $git_svn, $switch_path) = @_;
3268 my $self = SVN::Delta::Editor->new;
3269 bless $self, $class;
3270 if (exists $git_svn->{last_commit}) {
3271 $self->{c} = $git_svn->{last_commit};
3272 $self->{empty_symlinks} =
3273 _mark_empty_symlinks($git_svn, $switch_path);
3275 $self->{empty} = {};
3276 $self->{dir_prop} = {};
3277 $self->{file_prop} = {};
3278 $self->{absent_dir} = {};
3279 $self->{absent_file} = {};
3280 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
3281 $self;
3284 # this uses the Ra object, so it must be called before do_{switch,update},
3285 # not inside them (when the Git::SVN::Fetcher object is passed) to
3286 # do_{switch,update}
3287 sub _mark_empty_symlinks {
3288 my ($git_svn, $switch_path) = @_;
3289 my $bool = Git::config_bool('svn.brokenSymlinkWorkaround');
3290 return {} if (defined($bool) && ! $bool);
3292 my %ret;
3293 my ($rev, $cmt) = $git_svn->last_rev_commit;
3294 return {} unless ($rev && $cmt);
3296 # allow the warning to be printed for each revision we fetch to
3297 # ensure the user sees it. The user can also disable the workaround
3298 # on the repository even while git svn is running and the next
3299 # revision fetched will skip this expensive function.
3300 my $printed_warning;
3301 chomp(my $empty_blob = `git hash-object -t blob --stdin < /dev/null`);
3302 my ($ls, $ctx) = command_output_pipe(qw/ls-tree -r -z/, $cmt);
3303 local $/ = "\0";
3304 my $pfx = defined($switch_path) ? $switch_path : $git_svn->{path};
3305 $pfx .= '/' if length($pfx);
3306 while (<$ls>) {
3307 chomp;
3308 s/\A100644 blob $empty_blob\t//o or next;
3309 unless ($printed_warning) {
3310 print STDERR "Scanning for empty symlinks, ",
3311 "this may take a while if you have ",
3312 "many empty files\n",
3313 "You may disable this with `",
3314 "git config svn.brokenSymlinkWorkaround ",
3315 "false'.\n",
3316 "This may be done in a different ",
3317 "terminal without restarting ",
3318 "git svn\n";
3319 $printed_warning = 1;
3321 my $path = $_;
3322 my (undef, $props) =
3323 $git_svn->ra->get_file($pfx.$path, $rev, undef);
3324 if ($props->{'svn:special'}) {
3325 $ret{$path} = 1;
3328 command_close_pipe($ls, $ctx);
3329 \%ret;
3332 # returns true if a given path is inside a ".git" directory
3333 sub in_dot_git {
3334 $_[0] =~ m{(?:^|/)\.git(?:/|$)};
3337 # return value: 0 -- don't ignore, 1 -- ignore
3338 sub is_path_ignored {
3339 my ($path) = @_;
3340 return 1 if in_dot_git($path);
3341 return 0 unless defined($_ignore_regex);
3342 return 1 if $path =~ m!$_ignore_regex!o;
3343 return 0;
3346 sub set_path_strip {
3347 my ($self, $path) = @_;
3348 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
3351 sub open_root {
3352 { path => '' };
3355 sub open_directory {
3356 my ($self, $path, $pb, $rev) = @_;
3357 { path => $path };
3360 sub git_path {
3361 my ($self, $path) = @_;
3362 if ($self->{path_strip}) {
3363 $path =~ s!$self->{path_strip}!! or
3364 die "Failed to strip path '$path' ($self->{path_strip})\n";
3366 $path;
3369 sub delete_entry {
3370 my ($self, $path, $rev, $pb) = @_;
3371 return undef if is_path_ignored($path);
3373 my $gpath = $self->git_path($path);
3374 return undef if ($gpath eq '');
3376 # remove entire directories.
3377 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
3378 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3379 -r --name-only -z/,
3380 $self->{c}, '--', $gpath);
3381 local $/ = "\0";
3382 while (<$ls>) {
3383 chomp;
3384 $self->{gii}->remove($_);
3385 print "\tD\t$_\n" unless $::_q;
3387 print "\tD\t$gpath/\n" unless $::_q;
3388 command_close_pipe($ls, $ctx);
3389 $self->{empty}->{$path} = 0
3390 } else {
3391 $self->{gii}->remove($gpath);
3392 print "\tD\t$gpath\n" unless $::_q;
3394 undef;
3397 sub open_file {
3398 my ($self, $path, $pb, $rev) = @_;
3399 my ($mode, $blob);
3401 goto out if is_path_ignored($path);
3403 my $gpath = $self->git_path($path);
3404 ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
3405 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
3406 unless (defined $mode && defined $blob) {
3407 die "$path was not found in commit $self->{c} (r$rev)\n";
3409 if ($mode eq '100644' && $self->{empty_symlinks}->{$path}) {
3410 $mode = '120000';
3412 out:
3413 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
3414 pool => SVN::Pool->new, action => 'M' };
3417 sub add_file {
3418 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
3419 my $mode;
3421 if (!is_path_ignored($path)) {
3422 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3423 delete $self->{empty}->{$dir};
3424 $mode = '100644';
3426 { path => $path, mode_a => $mode, mode_b => $mode,
3427 pool => SVN::Pool->new, action => 'A' };
3430 sub add_directory {
3431 my ($self, $path, $cp_path, $cp_rev) = @_;
3432 goto out if is_path_ignored($path);
3433 my $gpath = $self->git_path($path);
3434 if ($gpath eq '') {
3435 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3436 -r --name-only -z/,
3437 $self->{c});
3438 local $/ = "\0";
3439 while (<$ls>) {
3440 chomp;
3441 $self->{gii}->remove($_);
3442 print "\tD\t$_\n" unless $::_q;
3444 command_close_pipe($ls, $ctx);
3445 $self->{empty}->{$path} = 0;
3447 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3448 delete $self->{empty}->{$dir};
3449 $self->{empty}->{$path} = 1;
3450 out:
3451 { path => $path };
3454 sub change_dir_prop {
3455 my ($self, $db, $prop, $value) = @_;
3456 return undef if is_path_ignored($db->{path});
3457 $self->{dir_prop}->{$db->{path}} ||= {};
3458 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
3459 undef;
3462 sub absent_directory {
3463 my ($self, $path, $pb) = @_;
3464 return undef if is_path_ignored($path);
3465 $self->{absent_dir}->{$pb->{path}} ||= [];
3466 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
3467 undef;
3470 sub absent_file {
3471 my ($self, $path, $pb) = @_;
3472 return undef if is_path_ignored($path);
3473 $self->{absent_file}->{$pb->{path}} ||= [];
3474 push @{$self->{absent_file}->{$pb->{path}}}, $path;
3475 undef;
3478 sub change_file_prop {
3479 my ($self, $fb, $prop, $value) = @_;
3480 return undef if is_path_ignored($fb->{path});
3481 if ($prop eq 'svn:executable') {
3482 if ($fb->{mode_b} != 120000) {
3483 $fb->{mode_b} = defined $value ? 100755 : 100644;
3485 } elsif ($prop eq 'svn:special') {
3486 $fb->{mode_b} = defined $value ? 120000 : 100644;
3487 } else {
3488 $self->{file_prop}->{$fb->{path}} ||= {};
3489 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
3491 undef;
3494 sub apply_textdelta {
3495 my ($self, $fb, $exp) = @_;
3496 return undef if is_path_ignored($fb->{path});
3497 my $fh = $::_repository->temp_acquire('svn_delta');
3498 # $fh gets auto-closed() by SVN::TxDelta::apply(),
3499 # (but $base does not,) so dup() it for reading in close_file
3500 open my $dup, '<&', $fh or croak $!;
3501 my $base = $::_repository->temp_acquire('git_blob');
3503 if ($fb->{blob}) {
3504 my ($base_is_link, $size);
3506 if ($fb->{mode_a} eq '120000' &&
3507 ! $self->{empty_symlinks}->{$fb->{path}}) {
3508 print $base 'link ' or die "print $!\n";
3509 $base_is_link = 1;
3511 retry:
3512 $size = $::_repository->cat_blob($fb->{blob}, $base);
3513 die "Failed to read object $fb->{blob}" if ($size < 0);
3515 if (defined $exp) {
3516 seek $base, 0, 0 or croak $!;
3517 my $got = ::md5sum($base);
3518 if ($got ne $exp) {
3519 my $err = "Checksum mismatch: ".
3520 "$fb->{path} $fb->{blob}\n" .
3521 "expected: $exp\n" .
3522 " got: $got\n";
3523 if ($base_is_link) {
3524 warn $err,
3525 "Retrying... (possibly ",
3526 "a bad symlink from SVN)\n";
3527 $::_repository->temp_reset($base);
3528 $base_is_link = 0;
3529 goto retry;
3531 die $err;
3535 seek $base, 0, 0 or croak $!;
3536 $fb->{fh} = $fh;
3537 $fb->{base} = $base;
3538 [ SVN::TxDelta::apply($base, $dup, undef, $fb->{path}, $fb->{pool}) ];
3541 sub close_file {
3542 my ($self, $fb, $exp) = @_;
3543 return undef if is_path_ignored($fb->{path});
3545 my $hash;
3546 my $path = $self->git_path($fb->{path});
3547 if (my $fh = $fb->{fh}) {
3548 if (defined $exp) {
3549 seek($fh, 0, 0) or croak $!;
3550 my $got = ::md5sum($fh);
3551 if ($got ne $exp) {
3552 die "Checksum mismatch: $path\n",
3553 "expected: $exp\n got: $got\n";
3556 if ($fb->{mode_b} == 120000) {
3557 sysseek($fh, 0, 0) or croak $!;
3558 my $rd = sysread($fh, my $buf, 5);
3560 if (!defined $rd) {
3561 croak "sysread: $!\n";
3562 } elsif ($rd == 0) {
3563 warn "$path has mode 120000",
3564 " but it points to nothing\n",
3565 "converting to an empty file with mode",
3566 " 100644\n";
3567 $fb->{mode_b} = '100644';
3568 } elsif ($buf ne 'link ') {
3569 warn "$path has mode 120000",
3570 " but is not a link\n";
3571 } else {
3572 my $tmp_fh = $::_repository->temp_acquire(
3573 'svn_hash');
3574 my $res;
3575 while ($res = sysread($fh, my $str, 1024)) {
3576 my $out = syswrite($tmp_fh, $str, $res);
3577 defined($out) && $out == $res
3578 or croak("write ",
3579 Git::temp_path($tmp_fh),
3580 ": $!\n");
3582 defined $res or croak $!;
3584 ($fh, $tmp_fh) = ($tmp_fh, $fh);
3585 Git::temp_release($tmp_fh, 1);
3589 $hash = $::_repository->hash_and_insert_object(
3590 Git::temp_path($fh));
3591 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
3593 Git::temp_release($fb->{base}, 1);
3594 Git::temp_release($fh, 1);
3595 } else {
3596 $hash = $fb->{blob} or die "no blob information\n";
3598 $fb->{pool}->clear;
3599 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
3600 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
3601 undef;
3604 sub abort_edit {
3605 my $self = shift;
3606 $self->{nr} = $self->{gii}->{nr};
3607 delete $self->{gii};
3608 $self->SUPER::abort_edit(@_);
3611 sub close_edit {
3612 my $self = shift;
3613 $self->{git_commit_ok} = 1;
3614 $self->{nr} = $self->{gii}->{nr};
3615 delete $self->{gii};
3616 $self->SUPER::close_edit(@_);
3619 package SVN::Git::Editor;
3620 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
3621 use strict;
3622 use warnings;
3623 use Carp qw/croak/;
3624 use IO::File;
3626 sub new {
3627 my ($class, $opts) = @_;
3628 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
3629 die "$_ required!\n" unless (defined $opts->{$_});
3632 my $pool = SVN::Pool->new;
3633 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
3634 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
3635 $opts->{r}, $mods);
3637 # $opts->{ra} functions should not be used after this:
3638 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
3639 $opts->{editor_cb}, $pool);
3640 my $self = SVN::Delta::Editor->new(@ce, $pool);
3641 bless $self, $class;
3642 foreach (qw/svn_path r tree_a tree_b/) {
3643 $self->{$_} = $opts->{$_};
3645 $self->{url} = $opts->{ra}->{url};
3646 $self->{mods} = $mods;
3647 $self->{types} = $types;
3648 $self->{pool} = $pool;
3649 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
3650 $self->{rm} = { };
3651 $self->{path_prefix} = length $self->{svn_path} ?
3652 "$self->{svn_path}/" : '';
3653 $self->{config} = $opts->{config};
3654 return $self;
3657 sub generate_diff {
3658 my ($tree_a, $tree_b) = @_;
3659 my @diff_tree = qw(diff-tree -z -r);
3660 if ($_cp_similarity) {
3661 push @diff_tree, "-C$_cp_similarity";
3662 } else {
3663 push @diff_tree, '-C';
3665 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
3666 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
3667 push @diff_tree, $tree_a, $tree_b;
3668 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
3669 local $/ = "\0";
3670 my $state = 'meta';
3671 my @mods;
3672 while (<$diff_fh>) {
3673 chomp $_; # this gets rid of the trailing "\0"
3674 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
3675 ($::sha1)\s($::sha1)\s
3676 ([MTCRAD])\d*$/xo) {
3677 push @mods, { mode_a => $1, mode_b => $2,
3678 sha1_a => $3, sha1_b => $4,
3679 chg => $5 };
3680 if ($5 =~ /^(?:C|R)$/) {
3681 $state = 'file_a';
3682 } else {
3683 $state = 'file_b';
3685 } elsif ($state eq 'file_a') {
3686 my $x = $mods[$#mods] or croak "Empty array\n";
3687 if ($x->{chg} !~ /^(?:C|R)$/) {
3688 croak "Error parsing $_, $x->{chg}\n";
3690 $x->{file_a} = $_;
3691 $state = 'file_b';
3692 } elsif ($state eq 'file_b') {
3693 my $x = $mods[$#mods] or croak "Empty array\n";
3694 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
3695 croak "Error parsing $_, $x->{chg}\n";
3697 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
3698 croak "Error parsing $_, $x->{chg}\n";
3700 $x->{file_b} = $_;
3701 $state = 'meta';
3702 } else {
3703 croak "Error parsing $_\n";
3706 command_close_pipe($diff_fh, $ctx);
3707 \@mods;
3710 sub check_diff_paths {
3711 my ($ra, $pfx, $rev, $mods) = @_;
3712 my %types;
3713 $pfx .= '/' if length $pfx;
3715 sub type_diff_paths {
3716 my ($ra, $types, $path, $rev) = @_;
3717 my @p = split m#/+#, $path;
3718 my $c = shift @p;
3719 unless (defined $types->{$c}) {
3720 $types->{$c} = $ra->check_path($c, $rev);
3722 while (@p) {
3723 $c .= '/' . shift @p;
3724 next if defined $types->{$c};
3725 $types->{$c} = $ra->check_path($c, $rev);
3729 foreach my $m (@$mods) {
3730 foreach my $f (qw/file_a file_b/) {
3731 next unless defined $m->{$f};
3732 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
3733 if (length $pfx.$dir && ! defined $types{$dir}) {
3734 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
3738 \%types;
3741 sub split_path {
3742 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
3745 sub repo_path {
3746 my ($self, $path) = @_;
3747 $self->{path_prefix}.(defined $path ? $path : '');
3750 sub url_path {
3751 my ($self, $path) = @_;
3752 if ($self->{url} =~ m#^https?://#) {
3753 $path =~ s/([^~a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
3755 $self->{url} . '/' . $self->repo_path($path);
3758 sub rmdirs {
3759 my ($self) = @_;
3760 my $rm = $self->{rm};
3761 delete $rm->{''}; # we never delete the url we're tracking
3762 return unless %$rm;
3764 foreach (keys %$rm) {
3765 my @d = split m#/#, $_;
3766 my $c = shift @d;
3767 $rm->{$c} = 1;
3768 while (@d) {
3769 $c .= '/' . shift @d;
3770 $rm->{$c} = 1;
3773 delete $rm->{$self->{svn_path}};
3774 delete $rm->{''}; # we never delete the url we're tracking
3775 return unless %$rm;
3777 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
3778 $self->{tree_b});
3779 local $/ = "\0";
3780 while (<$fh>) {
3781 chomp;
3782 my @dn = split m#/#, $_;
3783 while (pop @dn) {
3784 delete $rm->{join '/', @dn};
3786 unless (%$rm) {
3787 close $fh;
3788 return;
3791 command_close_pipe($fh, $ctx);
3793 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
3794 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
3795 $self->close_directory($bat->{$d}, $p);
3796 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
3797 print "\tD+\t$d/\n" unless $::_q;
3798 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
3799 delete $bat->{$d};
3803 sub open_or_add_dir {
3804 my ($self, $full_path, $baton) = @_;
3805 my $t = $self->{types}->{$full_path};
3806 if (!defined $t) {
3807 die "$full_path not known in r$self->{r} or we have a bug!\n";
3810 no warnings 'once';
3811 # SVN::Node::none and SVN::Node::file are used only once,
3812 # so we're shutting up Perl's warnings about them.
3813 if ($t == $SVN::Node::none) {
3814 return $self->add_directory($full_path, $baton,
3815 undef, -1, $self->{pool});
3816 } elsif ($t == $SVN::Node::dir) {
3817 return $self->open_directory($full_path, $baton,
3818 $self->{r}, $self->{pool});
3819 } # no warnings 'once'
3820 print STDERR "$full_path already exists in repository at ",
3821 "r$self->{r} and it is not a directory (",
3822 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
3823 } # no warnings 'once'
3824 exit 1;
3827 sub ensure_path {
3828 my ($self, $path) = @_;
3829 my $bat = $self->{bat};
3830 my $repo_path = $self->repo_path($path);
3831 return $bat->{''} unless (length $repo_path);
3832 my @p = split m#/+#, $repo_path;
3833 my $c = shift @p;
3834 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
3835 while (@p) {
3836 my $c0 = $c;
3837 $c .= '/' . shift @p;
3838 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
3840 return $bat->{$c};
3843 # Subroutine to convert a globbing pattern to a regular expression.
3844 # From perl cookbook.
3845 sub glob2pat {
3846 my $globstr = shift;
3847 my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
3848 $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
3849 return '^' . $globstr . '$';
3852 sub check_autoprop {
3853 my ($self, $pattern, $properties, $file, $fbat) = @_;
3854 # Convert the globbing pattern to a regular expression.
3855 my $regex = glob2pat($pattern);
3856 # Check if the pattern matches the file name.
3857 if($file =~ m/($regex)/) {
3858 # Parse the list of properties to set.
3859 my @props = split(/;/, $properties);
3860 foreach my $prop (@props) {
3861 # Parse 'name=value' syntax and set the property.
3862 if ($prop =~ /([^=]+)=(.*)/) {
3863 my ($n,$v) = ($1,$2);
3864 for ($n, $v) {
3865 s/^\s+//; s/\s+$//;
3867 $self->change_file_prop($fbat, $n, $v);
3873 sub apply_autoprops {
3874 my ($self, $file, $fbat) = @_;
3875 my $conf_t = ${$self->{config}}{'config'};
3876 no warnings 'once';
3877 # Check [miscellany]/enable-auto-props in svn configuration.
3878 if (SVN::_Core::svn_config_get_bool(
3879 $conf_t,
3880 $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
3881 $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
3882 0)) {
3883 # Auto-props are enabled. Enumerate them to look for matches.
3884 my $callback = sub {
3885 $self->check_autoprop($_[0], $_[1], $file, $fbat);
3887 SVN::_Core::svn_config_enumerate(
3888 $conf_t,
3889 $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
3890 $callback);
3894 sub A {
3895 my ($self, $m) = @_;
3896 my ($dir, $file) = split_path($m->{file_b});
3897 my $pbat = $self->ensure_path($dir);
3898 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3899 undef, -1);
3900 print "\tA\t$m->{file_b}\n" unless $::_q;
3901 $self->apply_autoprops($file, $fbat);
3902 $self->chg_file($fbat, $m);
3903 $self->close_file($fbat,undef,$self->{pool});
3906 sub C {
3907 my ($self, $m) = @_;
3908 my ($dir, $file) = split_path($m->{file_b});
3909 my $pbat = $self->ensure_path($dir);
3910 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3911 $self->url_path($m->{file_a}), $self->{r});
3912 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3913 $self->chg_file($fbat, $m);
3914 $self->close_file($fbat,undef,$self->{pool});
3917 sub delete_entry {
3918 my ($self, $path, $pbat) = @_;
3919 my $rpath = $self->repo_path($path);
3920 my ($dir, $file) = split_path($rpath);
3921 $self->{rm}->{$dir} = 1;
3922 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
3925 sub R {
3926 my ($self, $m) = @_;
3927 my ($dir, $file) = split_path($m->{file_b});
3928 my $pbat = $self->ensure_path($dir);
3929 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3930 $self->url_path($m->{file_a}), $self->{r});
3931 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3932 $self->apply_autoprops($file, $fbat);
3933 $self->chg_file($fbat, $m);
3934 $self->close_file($fbat,undef,$self->{pool});
3936 ($dir, $file) = split_path($m->{file_a});
3937 $pbat = $self->ensure_path($dir);
3938 $self->delete_entry($m->{file_a}, $pbat);
3941 sub M {
3942 my ($self, $m) = @_;
3943 my ($dir, $file) = split_path($m->{file_b});
3944 my $pbat = $self->ensure_path($dir);
3945 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
3946 $pbat,$self->{r},$self->{pool});
3947 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
3948 $self->chg_file($fbat, $m);
3949 $self->close_file($fbat,undef,$self->{pool});
3952 sub T { shift->M(@_) }
3954 sub change_file_prop {
3955 my ($self, $fbat, $pname, $pval) = @_;
3956 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
3959 sub _chg_file_get_blob ($$$$) {
3960 my ($self, $fbat, $m, $which) = @_;
3961 my $fh = $::_repository->temp_acquire("git_blob_$which");
3962 if ($m->{"mode_$which"} =~ /^120/) {
3963 print $fh 'link ' or croak $!;
3964 $self->change_file_prop($fbat,'svn:special','*');
3965 } elsif ($m->{mode_a} =~ /^120/ && $m->{"mode_$which"} !~ /^120/) {
3966 $self->change_file_prop($fbat,'svn:special',undef);
3968 my $blob = $m->{"sha1_$which"};
3969 return ($fh,) if ($blob =~ /^0{40}$/);
3970 my $size = $::_repository->cat_blob($blob, $fh);
3971 croak "Failed to read object $blob" if ($size < 0);
3972 $fh->flush == 0 or croak $!;
3973 seek $fh, 0, 0 or croak $!;
3975 my $exp = ::md5sum($fh);
3976 seek $fh, 0, 0 or croak $!;
3977 return ($fh, $exp);
3980 sub chg_file {
3981 my ($self, $fbat, $m) = @_;
3982 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
3983 $self->change_file_prop($fbat,'svn:executable','*');
3984 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
3985 $self->change_file_prop($fbat,'svn:executable',undef);
3987 my ($fh_a, $exp_a) = _chg_file_get_blob $self, $fbat, $m, 'a';
3988 my ($fh_b, $exp_b) = _chg_file_get_blob $self, $fbat, $m, 'b';
3989 my $pool = SVN::Pool->new;
3990 my $atd = $self->apply_textdelta($fbat, $exp_a, $pool);
3991 if (-s $fh_a) {
3992 my $txstream = SVN::TxDelta::new ($fh_a, $fh_b, $pool);
3993 my $res = SVN::TxDelta::send_txstream($txstream, @$atd, $pool);
3994 if (defined $res) {
3995 die "Unexpected result from send_txstream: $res\n",
3996 "(SVN::Core::VERSION: $SVN::Core::VERSION)\n";
3998 } else {
3999 my $got = SVN::TxDelta::send_stream($fh_b, @$atd, $pool);
4000 die "Checksum mismatch\nexpected: $exp_b\ngot: $got\n"
4001 if ($got ne $exp_b);
4003 Git::temp_release($fh_b, 1);
4004 Git::temp_release($fh_a, 1);
4005 $pool->clear;
4008 sub D {
4009 my ($self, $m) = @_;
4010 my ($dir, $file) = split_path($m->{file_b});
4011 my $pbat = $self->ensure_path($dir);
4012 print "\tD\t$m->{file_b}\n" unless $::_q;
4013 $self->delete_entry($m->{file_b}, $pbat);
4016 sub close_edit {
4017 my ($self) = @_;
4018 my ($p,$bat) = ($self->{pool}, $self->{bat});
4019 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
4020 next if $_ eq '';
4021 $self->close_directory($bat->{$_}, $p);
4023 $self->close_directory($bat->{''}, $p);
4024 $self->SUPER::close_edit($p);
4025 $p->clear;
4028 sub abort_edit {
4029 my ($self) = @_;
4030 $self->SUPER::abort_edit($self->{pool});
4033 sub DESTROY {
4034 my $self = shift;
4035 $self->SUPER::DESTROY(@_);
4036 $self->{pool}->clear;
4039 # this drives the editor
4040 sub apply_diff {
4041 my ($self) = @_;
4042 my $mods = $self->{mods};
4043 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
4044 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
4045 my $f = $m->{chg};
4046 if (defined $o{$f}) {
4047 $self->$f($m);
4048 } else {
4049 fatal("Invalid change type: $f");
4052 $self->rmdirs if $_rmdir;
4053 if (@$mods == 0) {
4054 $self->abort_edit;
4055 } else {
4056 $self->close_edit;
4058 return scalar @$mods;
4061 package Git::SVN::Ra;
4062 use vars qw/@ISA $config_dir $_log_window_size/;
4063 use strict;
4064 use warnings;
4065 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
4067 BEGIN {
4068 # enforce temporary pool usage for some simple functions
4069 no strict 'refs';
4070 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root
4071 get_file/) {
4072 my $SUPER = "SUPER::$f";
4073 *$f = sub {
4074 my $self = shift;
4075 my $pool = SVN::Pool->new;
4076 my @ret = $self->$SUPER(@_,$pool);
4077 $pool->clear;
4078 wantarray ? @ret : $ret[0];
4083 sub _auth_providers () {
4085 SVN::Client::get_simple_provider(),
4086 SVN::Client::get_ssl_server_trust_file_provider(),
4087 SVN::Client::get_simple_prompt_provider(
4088 \&Git::SVN::Prompt::simple, 2),
4089 SVN::Client::get_ssl_client_cert_file_provider(),
4090 SVN::Client::get_ssl_client_cert_prompt_provider(
4091 \&Git::SVN::Prompt::ssl_client_cert, 2),
4092 SVN::Client::get_ssl_client_cert_pw_file_provider(),
4093 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
4094 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
4095 SVN::Client::get_username_provider(),
4096 SVN::Client::get_ssl_server_trust_prompt_provider(
4097 \&Git::SVN::Prompt::ssl_server_trust),
4098 SVN::Client::get_username_prompt_provider(
4099 \&Git::SVN::Prompt::username, 2)
4103 sub escape_uri_only {
4104 my ($uri) = @_;
4105 my @tmp;
4106 foreach (split m{/}, $uri) {
4107 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
4108 push @tmp, $_;
4110 join('/', @tmp);
4113 sub escape_url {
4114 my ($url) = @_;
4115 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
4116 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
4117 $url = "$scheme://$domain$uri";
4119 $url;
4122 sub new {
4123 my ($class, $url) = @_;
4124 $url =~ s!/+$!!;
4125 return $RA if ($RA && $RA->{url} eq $url);
4127 SVN::_Core::svn_config_ensure($config_dir, undef);
4128 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
4129 my $config = SVN::Core::config_get_config($config_dir);
4130 $RA = undef;
4131 my $dont_store_passwords = 1;
4132 my $conf_t = ${$config}{'config'};
4134 no warnings 'once';
4135 # The usage of $SVN::_Core::SVN_CONFIG_* variables
4136 # produces warnings that variables are used only once.
4137 # I had not found the better way to shut them up, so
4138 # the warnings of type 'once' are disabled in this block.
4139 if (SVN::_Core::svn_config_get_bool($conf_t,
4140 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4141 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
4142 1) == 0) {
4143 SVN::_Core::svn_auth_set_parameter($baton,
4144 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
4145 bless (\$dont_store_passwords, "_p_void"));
4147 if (SVN::_Core::svn_config_get_bool($conf_t,
4148 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4149 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
4150 1) == 0) {
4151 $Git::SVN::Prompt::_no_auth_cache = 1;
4153 } # no warnings 'once'
4154 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
4155 config => $config,
4156 pool => SVN::Pool->new,
4157 auth_provider_callbacks => $callbacks);
4158 $self->{url} = $url;
4159 $self->{svn_path} = $url;
4160 $self->{repos_root} = $self->get_repos_root;
4161 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
4162 $self->{cache} = { check_path => { r => 0, data => {} },
4163 get_dir => { r => 0, data => {} } };
4164 $RA = bless $self, $class;
4167 sub check_path {
4168 my ($self, $path, $r) = @_;
4169 my $cache = $self->{cache}->{check_path};
4170 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
4171 return $cache->{data}->{$path};
4173 my $pool = SVN::Pool->new;
4174 my $t = $self->SUPER::check_path($path, $r, $pool);
4175 $pool->clear;
4176 if ($r != $cache->{r}) {
4177 %{$cache->{data}} = ();
4178 $cache->{r} = $r;
4180 $cache->{data}->{$path} = $t;
4183 sub get_dir {
4184 my ($self, $dir, $r) = @_;
4185 my $cache = $self->{cache}->{get_dir};
4186 if ($r == $cache->{r}) {
4187 if (my $x = $cache->{data}->{$dir}) {
4188 return wantarray ? @$x : $x->[0];
4191 my $pool = SVN::Pool->new;
4192 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
4193 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
4194 $pool->clear;
4195 if ($r != $cache->{r}) {
4196 %{$cache->{data}} = ();
4197 $cache->{r} = $r;
4199 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
4200 wantarray ? (\%dirents, $r, $props) : \%dirents;
4203 sub DESTROY {
4204 # do not call the real DESTROY since we store ourselves in $RA
4207 # get_log(paths, start, end, limit,
4208 # discover_changed_paths, strict_node_history, receiver)
4209 sub get_log {
4210 my ($self, @args) = @_;
4211 my $pool = SVN::Pool->new;
4213 # the limit parameter was not supported in SVN 1.1.x, so we
4214 # drop it. Therefore, the receiver callback passed to it
4215 # is made aware of this limitation by being wrapped if
4216 # the limit passed to is being wrapped.
4217 if ($SVN::Core::VERSION le '1.2.0') {
4218 my $limit = splice(@args, 3, 1);
4219 if ($limit > 0) {
4220 my $receiver = pop @args;
4221 push(@args, sub { &$receiver(@_) if (--$limit >= 0) });
4224 my $ret = $self->SUPER::get_log(@args, $pool);
4225 $pool->clear;
4226 $ret;
4229 sub trees_match {
4230 my ($self, $url1, $rev1, $url2, $rev2) = @_;
4231 my $ctx = SVN::Client->new(auth => _auth_providers);
4232 my $out = IO::File->new_tmpfile;
4234 # older SVN (1.1.x) doesn't take $pool as the last parameter for
4235 # $ctx->diff(), so we'll create a default one
4236 my $pool = SVN::Pool->new_default_sub;
4238 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
4239 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
4240 $out->flush;
4241 my $ret = (($out->stat)[7] == 0);
4242 close $out or croak $!;
4244 $ret;
4247 sub get_commit_editor {
4248 my ($self, $log, $cb, $pool) = @_;
4249 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
4250 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
4253 sub gs_do_update {
4254 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
4255 my $new = ($rev_a == $rev_b);
4256 my $path = $gs->{path};
4258 if ($new && -e $gs->{index}) {
4259 unlink $gs->{index} or die
4260 "Couldn't unlink index: $gs->{index}: $!\n";
4262 my $pool = SVN::Pool->new;
4263 $editor->set_path_strip($path);
4264 my (@pc) = split m#/#, $path;
4265 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
4266 1, $editor, $pool);
4267 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4269 # Since we can't rely on svn_ra_reparent being available, we'll
4270 # just have to do some magic with set_path to make it so
4271 # we only want a partial path.
4272 my $sp = '';
4273 my $final = join('/', @pc);
4274 while (@pc) {
4275 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
4276 $sp .= '/' if length $sp;
4277 $sp .= shift @pc;
4279 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
4281 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
4283 $reporter->finish_report($pool);
4284 $pool->clear;
4285 $editor->{git_commit_ok};
4288 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
4289 # svn_ra_reparent didn't work before 1.4)
4290 sub gs_do_switch {
4291 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
4292 my $path = $gs->{path};
4293 my $pool = SVN::Pool->new;
4295 my $full_url = $self->{url};
4296 my $old_url = $full_url;
4297 $full_url .= '/' . escape_uri_only($path) if length $path;
4298 my ($ra, $reparented);
4300 if ($old_url =~ m#^svn(\+ssh)?://#) {
4301 $_[0] = undef;
4302 $self = undef;
4303 $RA = undef;
4304 $ra = Git::SVN::Ra->new($full_url);
4305 $ra_invalid = 1;
4306 } elsif ($old_url ne $full_url) {
4307 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url, $pool);
4308 $self->{url} = $full_url;
4309 $reparented = 1;
4312 $ra ||= $self;
4313 $url_b = escape_url($url_b);
4314 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
4315 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4316 $reporter->set_path('', $rev_a, 0, @lock, $pool);
4317 $reporter->finish_report($pool);
4319 if ($reparented) {
4320 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
4321 $self->{url} = $old_url;
4324 $pool->clear;
4325 $editor->{git_commit_ok};
4328 sub longest_common_path {
4329 my ($gsv, $globs) = @_;
4330 my %common;
4331 my $common_max = scalar @$gsv;
4333 foreach my $gs (@$gsv) {
4334 my @tmp = split m#/#, $gs->{path};
4335 my $p = '';
4336 foreach (@tmp) {
4337 $p .= length($p) ? "/$_" : $_;
4338 $common{$p} ||= 0;
4339 $common{$p}++;
4342 $globs ||= [];
4343 $common_max += scalar @$globs;
4344 foreach my $glob (@$globs) {
4345 my @tmp = split m#/#, $glob->{path}->{left};
4346 my $p = '';
4347 foreach (@tmp) {
4348 $p .= length($p) ? "/$_" : $_;
4349 $common{$p} ||= 0;
4350 $common{$p}++;
4354 my $longest_path = '';
4355 foreach (sort {length $b <=> length $a} keys %common) {
4356 if ($common{$_} == $common_max) {
4357 $longest_path = $_;
4358 last;
4361 $longest_path;
4364 sub gs_fetch_loop_common {
4365 my ($self, $base, $head, $gsv, $globs) = @_;
4366 return if ($base > $head);
4367 my $inc = $_log_window_size;
4368 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
4369 my $longest_path = longest_common_path($gsv, $globs);
4370 my $ra_url = $self->{url};
4371 while (1) {
4372 my %revs;
4373 my $err;
4374 my $err_handler = $SVN::Error::handler;
4375 $SVN::Error::handler = sub {
4376 ($err) = @_;
4377 skip_unknown_revs($err);
4379 sub _cb {
4380 my ($paths, $r, $author, $date, $log) = @_;
4381 [ dup_changed_paths($paths),
4382 { author => $author, date => $date, log => $log } ];
4384 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
4385 sub { $revs{$_[1]} = _cb(@_) });
4386 if ($err) {
4387 print "Checked through r$max\r";
4389 if ($err && $max >= $head) {
4390 print STDERR "Path '$longest_path' ",
4391 "was probably deleted:\n",
4392 $err->expanded_message,
4393 "\nWill attempt to follow ",
4394 "revisions r$min .. r$max ",
4395 "committed before the deletion\n";
4396 my $hi = $max;
4397 while (--$hi >= $min) {
4398 my $ok;
4399 $self->get_log([$longest_path], $min, $hi,
4400 0, 1, 1, sub {
4401 $ok ||= $_[1];
4402 $revs{$_[1]} = _cb(@_) });
4403 if ($ok) {
4404 print STDERR "r$min .. r$ok OK\n";
4405 last;
4409 $SVN::Error::handler = $err_handler;
4411 my %exists = map { $_->{path} => $_ } @$gsv;
4412 foreach my $r (sort {$a <=> $b} keys %revs) {
4413 my ($paths, $logged) = @{$revs{$r}};
4415 foreach my $gs ($self->match_globs(\%exists, $paths,
4416 $globs, $r)) {
4417 if ($gs->rev_map_max >= $r) {
4418 next;
4420 next unless $gs->match_paths($paths, $r);
4421 $gs->{logged_rev_props} = $logged;
4422 if (my $last_commit = $gs->last_commit) {
4423 $gs->assert_index_clean($last_commit);
4425 my $log_entry = $gs->do_fetch($paths, $r);
4426 if ($log_entry) {
4427 $gs->do_git_commit($log_entry);
4429 $INDEX_FILES{$gs->{index}} = 1;
4431 foreach my $g (@$globs) {
4432 my $k = "svn-remote.$g->{remote}." .
4433 "$g->{t}-maxRev";
4434 Git::SVN::tmp_config($k, $r);
4436 if ($ra_invalid) {
4437 $_[0] = undef;
4438 $self = undef;
4439 $RA = undef;
4440 $self = Git::SVN::Ra->new($ra_url);
4441 $ra_invalid = undef;
4444 # pre-fill the .rev_db since it'll eventually get filled in
4445 # with '0' x40 if something new gets committed
4446 foreach my $gs (@$gsv) {
4447 next if $gs->rev_map_max >= $max;
4448 next if defined $gs->rev_map_get($max);
4449 $gs->rev_map_set($max, 0 x40);
4451 foreach my $g (@$globs) {
4452 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
4453 Git::SVN::tmp_config($k, $max);
4455 last if $max >= $head;
4456 $min = $max + 1;
4457 $max += $inc;
4458 $max = $head if ($max > $head);
4460 Git::SVN::gc();
4463 sub get_dir_globbed {
4464 my ($self, $left, $depth, $r) = @_;
4466 my @x = eval { $self->get_dir($left, $r) };
4467 return unless scalar @x == 3;
4468 my $dirents = $x[0];
4469 my @finalents;
4470 foreach my $de (keys %$dirents) {
4471 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
4472 if ($depth > 1) {
4473 my @args = ("$left/$de", $depth - 1, $r);
4474 foreach my $dir ($self->get_dir_globbed(@args)) {
4475 push @finalents, "$de/$dir";
4477 } else {
4478 push @finalents, $de;
4481 @finalents;
4484 sub match_globs {
4485 my ($self, $exists, $paths, $globs, $r) = @_;
4487 sub get_dir_check {
4488 my ($self, $exists, $g, $r) = @_;
4490 my @dirs = $self->get_dir_globbed($g->{path}->{left},
4491 $g->{path}->{depth},
4492 $r);
4494 foreach my $de (@dirs) {
4495 my $p = $g->{path}->full_path($de);
4496 next if $exists->{$p};
4497 next if (length $g->{path}->{right} &&
4498 ($self->check_path($p, $r) !=
4499 $SVN::Node::dir));
4500 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
4501 $g->{ref}->full_path($de), 1);
4504 foreach my $g (@$globs) {
4505 if (my $path = $paths->{"/$g->{path}->{left}"}) {
4506 if ($path->{action} =~ /^[AR]$/) {
4507 get_dir_check($self, $exists, $g, $r);
4510 foreach (keys %$paths) {
4511 if (/$g->{path}->{left_regex}/ &&
4512 !/$g->{path}->{regex}/) {
4513 next if $paths->{$_}->{action} !~ /^[AR]$/;
4514 get_dir_check($self, $exists, $g, $r);
4516 next unless /$g->{path}->{regex}/;
4517 my $p = $1;
4518 my $pathname = $g->{path}->full_path($p);
4519 next if $exists->{$pathname};
4520 next if ($self->check_path($pathname, $r) !=
4521 $SVN::Node::dir);
4522 $exists->{$pathname} = Git::SVN->init(
4523 $self->{url}, $pathname, undef,
4524 $g->{ref}->full_path($p), 1);
4526 my $c = '';
4527 foreach (split m#/#, $g->{path}->{left}) {
4528 $c .= "/$_";
4529 next unless ($paths->{$c} &&
4530 ($paths->{$c}->{action} =~ /^[AR]$/));
4531 get_dir_check($self, $exists, $g, $r);
4534 values %$exists;
4537 sub minimize_url {
4538 my ($self) = @_;
4539 return $self->{url} if ($self->{url} eq $self->{repos_root});
4540 my $url = $self->{repos_root};
4541 my @components = split(m!/!, $self->{svn_path});
4542 my $c = '';
4543 do {
4544 $url .= "/$c" if length $c;
4545 eval { (ref $self)->new($url)->get_latest_revnum };
4546 } while ($@ && ($c = shift @components));
4547 $url;
4550 sub can_do_switch {
4551 my $self = shift;
4552 unless (defined $can_do_switch) {
4553 my $pool = SVN::Pool->new;
4554 my $rep = eval {
4555 $self->do_switch(1, '', 0, $self->{url},
4556 SVN::Delta::Editor->new, $pool);
4558 if ($@) {
4559 $can_do_switch = 0;
4560 } else {
4561 $rep->abort_report($pool);
4562 $can_do_switch = 1;
4564 $pool->clear;
4566 $can_do_switch;
4569 sub skip_unknown_revs {
4570 my ($err) = @_;
4571 my $errno = $err->apr_err();
4572 # Maybe the branch we're tracking didn't
4573 # exist when the repo started, so it's
4574 # not an error if it doesn't, just continue
4576 # Wonderfully consistent library, eh?
4577 # 160013 - svn:// and file://
4578 # 175002 - http(s)://
4579 # 175007 - http(s):// (this repo required authorization, too...)
4580 # More codes may be discovered later...
4581 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
4582 my $err_key = $err->expanded_message;
4583 # revision numbers change every time, filter them out
4584 $err_key =~ s/\d+/\0/g;
4585 $err_key = "$errno\0$err_key";
4586 unless ($ignored_err{$err_key}) {
4587 warn "W: Ignoring error from SVN, path probably ",
4588 "does not exist: ($errno): ",
4589 $err->expanded_message,"\n";
4590 warn "W: Do not be alarmed at the above message ",
4591 "git-svn is just searching aggressively for ",
4592 "old history.\n",
4593 "This may take a while on large repositories\n";
4594 $ignored_err{$err_key} = 1;
4596 return;
4598 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
4601 # svn_log_changed_path_t objects passed to get_log are likely to be
4602 # overwritten even if only the refs are copied to an external variable,
4603 # so we should dup the structures in their entirety. Using an externally
4604 # passed pool (instead of our temporary and quickly cleared pool in
4605 # Git::SVN::Ra) does not help matters at all...
4606 sub dup_changed_paths {
4607 my ($paths) = @_;
4608 return undef unless $paths;
4609 my %ret;
4610 foreach my $p (keys %$paths) {
4611 my $i = $paths->{$p};
4612 my %s = map { $_ => $i->$_ }
4613 qw/copyfrom_path copyfrom_rev action/;
4614 $ret{$p} = \%s;
4616 \%ret;
4619 package Git::SVN::Log;
4620 use strict;
4621 use warnings;
4622 use POSIX qw/strftime/;
4623 use constant commit_log_separator => ('-' x 72) . "\n";
4624 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
4625 %rusers $show_commit $incremental/;
4626 my $l_fmt;
4628 sub cmt_showable {
4629 my ($c) = @_;
4630 return 1 if defined $c->{r};
4632 # big commit message got truncated by the 16k pretty buffer in rev-list
4633 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
4634 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
4635 @{$c->{l}} = ();
4636 my @log = command(qw/cat-file commit/, $c->{c});
4638 # shift off the headers
4639 shift @log while ($log[0] ne '');
4640 shift @log;
4642 # TODO: make $c->{l} not have a trailing newline in the future
4643 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
4645 (undef, $c->{r}, undef) = ::extract_metadata(
4646 (grep(/^git-svn-id: /, @log))[-1]);
4648 return defined $c->{r};
4651 sub log_use_color {
4652 return $color || Git->repository->get_colorbool('color.diff');
4655 sub git_svn_log_cmd {
4656 my ($r_min, $r_max, @args) = @_;
4657 my $head = 'HEAD';
4658 my (@files, @log_opts);
4659 foreach my $x (@args) {
4660 if ($x eq '--' || @files) {
4661 push @files, $x;
4662 } else {
4663 if (::verify_ref("$x^0")) {
4664 $head = $x;
4665 } else {
4666 push @log_opts, $x;
4671 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
4672 $gs ||= Git::SVN->_new;
4673 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
4674 $gs->refname);
4675 push @cmd, '-r' unless $non_recursive;
4676 push @cmd, qw/--raw --name-status/ if $verbose;
4677 push @cmd, '--color' if log_use_color();
4678 push @cmd, @log_opts;
4679 if (defined $r_max && $r_max == $r_min) {
4680 push @cmd, '--max-count=1';
4681 if (my $c = $gs->rev_map_get($r_max)) {
4682 push @cmd, $c;
4684 } elsif (defined $r_max) {
4685 if ($r_max < $r_min) {
4686 ($r_min, $r_max) = ($r_max, $r_min);
4688 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
4689 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
4690 # If there are no commits in the range, both $c_max and $c_min
4691 # will be undefined. If there is at least 1 commit in the
4692 # range, both will be defined.
4693 return () if !defined $c_min || !defined $c_max;
4694 if ($c_min eq $c_max) {
4695 push @cmd, '--max-count=1', $c_min;
4696 } else {
4697 push @cmd, '--boundary', "$c_min..$c_max";
4700 return (@cmd, @files);
4703 # adapted from pager.c
4704 sub config_pager {
4705 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
4706 if (!defined $pager) {
4707 $pager = 'less';
4708 } elsif (length $pager == 0 || $pager eq 'cat') {
4709 $pager = undef;
4711 $ENV{GIT_PAGER_IN_USE} = defined($pager);
4714 sub run_pager {
4715 return unless -t *STDOUT && defined $pager;
4716 pipe my ($rfd, $wfd) or return;
4717 defined(my $pid = fork) or ::fatal "Can't fork: $!";
4718 if (!$pid) {
4719 open STDOUT, '>&', $wfd or
4720 ::fatal "Can't redirect to stdout: $!";
4721 return;
4723 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
4724 $ENV{LESS} ||= 'FRSX';
4725 exec $pager or ::fatal "Can't run pager: $! ($pager)";
4728 sub format_svn_date {
4729 return strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)", localtime(shift));
4732 sub parse_git_date {
4733 my ($t, $tz) = @_;
4734 # Date::Parse isn't in the standard Perl distro :(
4735 if ($tz =~ s/^\+//) {
4736 $t += tz_to_s_offset($tz);
4737 } elsif ($tz =~ s/^\-//) {
4738 $t -= tz_to_s_offset($tz);
4740 return $t;
4743 sub set_local_timezone {
4744 if (defined $TZ) {
4745 $ENV{TZ} = $TZ;
4746 } else {
4747 delete $ENV{TZ};
4751 sub tz_to_s_offset {
4752 my ($tz) = @_;
4753 $tz =~ s/(\d\d)$//;
4754 return ($1 * 60) + ($tz * 3600);
4757 sub get_author_info {
4758 my ($dest, $author, $t, $tz) = @_;
4759 $author =~ s/(?:^\s*|\s*$)//g;
4760 $dest->{a_raw} = $author;
4761 my $au;
4762 if ($::_authors) {
4763 $au = $rusers{$author} || undef;
4765 if (!$au) {
4766 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
4768 $dest->{t} = $t;
4769 $dest->{tz} = $tz;
4770 $dest->{a} = $au;
4771 $dest->{t_utc} = parse_git_date($t, $tz);
4774 sub process_commit {
4775 my ($c, $r_min, $r_max, $defer) = @_;
4776 if (defined $r_min && defined $r_max) {
4777 if ($r_min == $c->{r} && $r_min == $r_max) {
4778 show_commit($c);
4779 return 0;
4781 return 1 if $r_min == $r_max;
4782 if ($r_min < $r_max) {
4783 # we need to reverse the print order
4784 return 0 if (defined $limit && --$limit < 0);
4785 push @$defer, $c;
4786 return 1;
4788 if ($r_min != $r_max) {
4789 return 1 if ($r_min < $c->{r});
4790 return 1 if ($r_max > $c->{r});
4793 return 0 if (defined $limit && --$limit < 0);
4794 show_commit($c);
4795 return 1;
4798 sub show_commit {
4799 my $c = shift;
4800 if ($oneline) {
4801 my $x = "\n";
4802 if (my $l = $c->{l}) {
4803 while ($l->[0] =~ /^\s*$/) { shift @$l }
4804 $x = $l->[0];
4806 $l_fmt ||= 'A' . length($c->{r});
4807 print 'r',pack($l_fmt, $c->{r}),' | ';
4808 print "$c->{c} | " if $show_commit;
4809 print $x;
4810 } else {
4811 show_commit_normal($c);
4815 sub show_commit_changed_paths {
4816 my ($c) = @_;
4817 return unless $c->{changed};
4818 print "Changed paths:\n", @{$c->{changed}};
4821 sub show_commit_normal {
4822 my ($c) = @_;
4823 print commit_log_separator, "r$c->{r} | ";
4824 print "$c->{c} | " if $show_commit;
4825 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
4826 my $nr_line = 0;
4828 if (my $l = $c->{l}) {
4829 while ($l->[$#$l] eq "\n" && $#$l > 0
4830 && $l->[($#$l - 1)] eq "\n") {
4831 pop @$l;
4833 $nr_line = scalar @$l;
4834 if (!$nr_line) {
4835 print "1 line\n\n\n";
4836 } else {
4837 if ($nr_line == 1) {
4838 $nr_line = '1 line';
4839 } else {
4840 $nr_line .= ' lines';
4842 print $nr_line, "\n";
4843 show_commit_changed_paths($c);
4844 print "\n";
4845 print $_ foreach @$l;
4847 } else {
4848 print "1 line\n";
4849 show_commit_changed_paths($c);
4850 print "\n";
4853 foreach my $x (qw/raw stat diff/) {
4854 if ($c->{$x}) {
4855 print "\n";
4856 print $_ foreach @{$c->{$x}}
4861 sub cmd_show_log {
4862 my (@args) = @_;
4863 my ($r_min, $r_max);
4864 my $r_last = -1; # prevent dupes
4865 set_local_timezone();
4866 if (defined $::_revision) {
4867 if ($::_revision =~ /^(\d+):(\d+)$/) {
4868 ($r_min, $r_max) = ($1, $2);
4869 } elsif ($::_revision =~ /^\d+$/) {
4870 $r_min = $r_max = $::_revision;
4871 } else {
4872 ::fatal "-r$::_revision is not supported, use ",
4873 "standard 'git log' arguments instead";
4877 config_pager();
4878 @args = git_svn_log_cmd($r_min, $r_max, @args);
4879 if (!@args) {
4880 print commit_log_separator unless $incremental || $oneline;
4881 return;
4883 my $log = command_output_pipe(@args);
4884 run_pager();
4885 my (@k, $c, $d, $stat);
4886 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
4887 while (<$log>) {
4888 if (/^${esc_color}commit -?($::sha1_short)/o) {
4889 my $cmt = $1;
4890 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
4891 $r_last = $c->{r};
4892 process_commit($c, $r_min, $r_max, \@k) or
4893 goto out;
4895 $d = undef;
4896 $c = { c => $cmt };
4897 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
4898 get_author_info($c, $1, $2, $3);
4899 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
4900 # ignore
4901 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
4902 push @{$c->{raw}}, $_;
4903 } elsif (/^${esc_color}[ACRMDT]\t/) {
4904 # we could add $SVN->{svn_path} here, but that requires
4905 # remote access at the moment (repo_path_split)...
4906 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
4907 push @{$c->{changed}}, $_;
4908 } elsif (/^${esc_color}diff /o) {
4909 $d = 1;
4910 push @{$c->{diff}}, $_;
4911 } elsif ($d) {
4912 push @{$c->{diff}}, $_;
4913 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
4914 $esc_color*[\+\-]*$esc_color$/x) {
4915 $stat = 1;
4916 push @{$c->{stat}}, $_;
4917 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
4918 push @{$c->{stat}}, $_;
4919 $stat = undef;
4920 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
4921 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
4922 } elsif (s/^${esc_color} //o) {
4923 push @{$c->{l}}, $_;
4926 if ($c && defined $c->{r} && $c->{r} != $r_last) {
4927 $r_last = $c->{r};
4928 process_commit($c, $r_min, $r_max, \@k);
4930 if (@k) {
4931 ($r_min, $r_max) = ($r_max, $r_min);
4932 process_commit($_, $r_min, $r_max) foreach reverse @k;
4934 out:
4935 close $log;
4936 print commit_log_separator unless $incremental || $oneline;
4939 sub cmd_blame {
4940 my $path = pop;
4942 config_pager();
4943 run_pager();
4945 my ($fh, $ctx, $rev);
4947 if ($_git_format) {
4948 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
4949 while (my $line = <$fh>) {
4950 if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
4951 # Uncommitted edits show up as a rev ID of
4952 # all zeros, which we can't look up with
4953 # cmt_metadata
4954 if ($1 !~ /^0+$/) {
4955 (undef, $rev, undef) =
4956 ::cmt_metadata($1);
4957 $rev = '0' if (!$rev);
4958 } else {
4959 $rev = '0';
4961 $rev = sprintf('%-10s', $rev);
4962 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
4964 print $line;
4966 } else {
4967 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
4968 '--', $path);
4969 my ($sha1);
4970 my %authors;
4971 while (my $line = <$fh>) {
4972 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
4973 $sha1 = $1;
4974 (undef, $rev, undef) = ::cmt_metadata($1);
4975 $rev = '0' if (!$rev);
4977 elsif ($line =~ /^author (.*)/) {
4978 $authors{$rev} = $1;
4979 $authors{$rev} =~ s/\s/_/g;
4981 elsif ($line =~ /^\t(.*)$/) {
4982 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
4986 command_close_pipe($fh, $ctx);
4989 package Git::SVN::Migration;
4990 # these version numbers do NOT correspond to actual version numbers
4991 # of git nor git-svn. They are just relative.
4993 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
4995 # v1 layout: .git/$id/info/url, refs/remotes/$id
4997 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
4999 # v3 layout: .git/svn/$id, refs/remotes/$id
5000 # - info/url may remain for backwards compatibility
5001 # - this is what we migrate up to this layout automatically,
5002 # - this will be used by git svn init on single branches
5003 # v3.1 layout (auto migrated):
5004 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
5005 # for backwards compatibility
5007 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
5008 # - this is only created for newly multi-init-ed
5009 # repositories. Similar in spirit to the
5010 # --use-separate-remotes option in git-clone (now default)
5011 # - we do not automatically migrate to this (following
5012 # the example set by core git)
5014 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
5015 # - newer, more-efficient format that uses 24-bytes per record
5016 # with no filler space.
5017 # - use xxd -c24 < .rev_map.$UUID to view and debug
5018 # - This is a one-way migration, repositories updated to the
5019 # new format will not be able to use old git-svn without
5020 # rebuilding the .rev_db. Rebuilding the rev_db is not
5021 # possible if noMetadata or useSvmProps are set; but should
5022 # be no problem for users that use the (sensible) defaults.
5023 use strict;
5024 use warnings;
5025 use Carp qw/croak/;
5026 use File::Path qw/mkpath/;
5027 use File::Basename qw/dirname basename/;
5028 use vars qw/$_minimize/;
5030 sub migrate_from_v0 {
5031 my $git_dir = $ENV{GIT_DIR};
5032 return undef unless -d $git_dir;
5033 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5034 my $migrated = 0;
5035 while (<$fh>) {
5036 chomp;
5037 my ($id, $orig_ref) = ($_, $_);
5038 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
5039 next unless -f "$git_dir/$id/info/url";
5040 my $new_ref = "refs/remotes/$id";
5041 if (::verify_ref("$new_ref^0")) {
5042 print STDERR "W: $orig_ref is probably an old ",
5043 "branch used by an ancient version of ",
5044 "git-svn.\n",
5045 "However, $new_ref also exists.\n",
5046 "We will not be able ",
5047 "to use this branch until this ",
5048 "ambiguity is resolved.\n";
5049 next;
5051 print STDERR "Migrating from v0 layout...\n" if !$migrated;
5052 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
5053 command_noisy('update-ref', $new_ref, $orig_ref);
5054 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
5055 $migrated++;
5057 command_close_pipe($fh, $ctx);
5058 print STDERR "Done migrating from v0 layout...\n" if $migrated;
5059 $migrated;
5062 sub migrate_from_v1 {
5063 my $git_dir = $ENV{GIT_DIR};
5064 my $migrated = 0;
5065 return $migrated unless -d $git_dir;
5066 my $svn_dir = "$git_dir/svn";
5068 # just in case somebody used 'svn' as their $id at some point...
5069 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
5071 print STDERR "Migrating from a git-svn v1 layout...\n";
5072 mkpath([$svn_dir]);
5073 print STDERR "Data from a previous version of git-svn exists, but\n\t",
5074 "$svn_dir\n\t(required for this version ",
5075 "($::VERSION) of git-svn) does not exist.\n";
5076 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5077 while (<$fh>) {
5078 my $x = $_;
5079 next unless $x =~ s#^refs/remotes/##;
5080 chomp $x;
5081 next unless -f "$git_dir/$x/info/url";
5082 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
5083 next unless $u;
5084 my $dn = dirname("$git_dir/svn/$x");
5085 mkpath([$dn]) unless -d $dn;
5086 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
5087 mkpath(["$git_dir/svn/svn"]);
5088 print STDERR " - $git_dir/$x/info => ",
5089 "$git_dir/svn/$x/info\n";
5090 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
5091 croak "$!: $x";
5092 # don't worry too much about these, they probably
5093 # don't exist with repos this old (save for index,
5094 # and we can easily regenerate that)
5095 foreach my $f (qw/unhandled.log index .rev_db/) {
5096 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
5098 } else {
5099 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
5100 rename "$git_dir/$x", "$git_dir/svn/$x" or
5101 croak "$!: $x";
5103 $migrated++;
5105 command_close_pipe($fh, $ctx);
5106 print STDERR "Done migrating from a git-svn v1 layout\n";
5107 $migrated;
5110 sub read_old_urls {
5111 my ($l_map, $pfx, $path) = @_;
5112 my @dir;
5113 foreach (<$path/*>) {
5114 if (-r "$_/info/url") {
5115 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
5116 my $ref_id = $pfx . basename $_;
5117 my $url = ::file_to_s("$_/info/url");
5118 $l_map->{$ref_id} = $url;
5119 } elsif (-d $_) {
5120 push @dir, $_;
5123 foreach (@dir) {
5124 my $x = $_;
5125 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
5126 read_old_urls($l_map, $x, $_);
5130 sub migrate_from_v2 {
5131 my @cfg = command(qw/config -l/);
5132 return if grep /^svn-remote\..+\.url=/, @cfg;
5133 my %l_map;
5134 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
5135 my $migrated = 0;
5137 foreach my $ref_id (sort keys %l_map) {
5138 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
5139 if ($@) {
5140 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
5142 $migrated++;
5144 $migrated;
5147 sub minimize_connections {
5148 my $r = Git::SVN::read_all_remotes();
5149 my $new_urls = {};
5150 my $root_repos = {};
5151 foreach my $repo_id (keys %$r) {
5152 my $url = $r->{$repo_id}->{url} or next;
5153 my $fetch = $r->{$repo_id}->{fetch} or next;
5154 my $ra = Git::SVN::Ra->new($url);
5156 # skip existing cases where we already connect to the root
5157 if (($ra->{url} eq $ra->{repos_root}) ||
5158 ($ra->{repos_root} eq $repo_id)) {
5159 $root_repos->{$ra->{url}} = $repo_id;
5160 next;
5163 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
5164 my $root_path = $ra->{url};
5165 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
5166 foreach my $path (keys %$fetch) {
5167 my $ref_id = $fetch->{$path};
5168 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
5170 # make sure we can read when connecting to
5171 # a higher level of a repository
5172 my ($last_rev, undef) = $gs->last_rev_commit;
5173 if (!defined $last_rev) {
5174 $last_rev = eval {
5175 $root_ra->get_latest_revnum;
5177 next if $@;
5179 my $new = $root_path;
5180 $new .= length $path ? "/$path" : '';
5181 eval {
5182 $root_ra->get_log([$new], $last_rev, $last_rev,
5183 0, 0, 1, sub { });
5185 next if $@;
5186 $new_urls->{$ra->{repos_root}}->{$new} =
5187 { ref_id => $ref_id,
5188 old_repo_id => $repo_id,
5189 old_path => $path };
5193 my @emptied;
5194 foreach my $url (keys %$new_urls) {
5195 # see if we can re-use an existing [svn-remote "repo_id"]
5196 # instead of creating a(n ugly) new section:
5197 my $repo_id = $root_repos->{$url} || $url;
5199 my $fetch = $new_urls->{$url};
5200 foreach my $path (keys %$fetch) {
5201 my $x = $fetch->{$path};
5202 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
5203 my $pfx = "svn-remote.$x->{old_repo_id}";
5205 my $old_fetch = quotemeta("$x->{old_path}:".
5206 "refs/remotes/$x->{ref_id}");
5207 command_noisy(qw/config --unset/,
5208 "$pfx.fetch", '^'. $old_fetch . '$');
5209 delete $r->{$x->{old_repo_id}}->
5210 {fetch}->{$x->{old_path}};
5211 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
5212 command_noisy(qw/config --unset/,
5213 "$pfx.url");
5214 push @emptied, $x->{old_repo_id}
5218 if (@emptied) {
5219 my $file = $ENV{GIT_CONFIG} || "$ENV{GIT_DIR}/config";
5220 print STDERR <<EOF;
5221 The following [svn-remote] sections in your config file ($file) are empty
5222 and can be safely removed:
5224 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
5228 sub migration_check {
5229 migrate_from_v0();
5230 migrate_from_v1();
5231 migrate_from_v2();
5232 minimize_connections() if $_minimize;
5235 package Git::IndexInfo;
5236 use strict;
5237 use warnings;
5238 use Git qw/command_input_pipe command_close_pipe/;
5240 sub new {
5241 my ($class) = @_;
5242 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
5243 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
5246 sub remove {
5247 my ($self, $path) = @_;
5248 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
5249 return ++$self->{nr};
5251 undef;
5254 sub update {
5255 my ($self, $mode, $hash, $path) = @_;
5256 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
5257 return ++$self->{nr};
5259 undef;
5262 sub DESTROY {
5263 my ($self) = @_;
5264 command_close_pipe($self->{gui}, $self->{ctx});
5267 package Git::SVN::GlobSpec;
5268 use strict;
5269 use warnings;
5271 sub new {
5272 my ($class, $glob) = @_;
5273 my $re = $glob;
5274 $re =~ s!/+$!!g; # no need for trailing slashes
5275 $re =~ m!^([^*]*)(\*(?:/\*)*)([^*]*)$!;
5276 my $temp = $re;
5277 my ($left, $right) = ($1, $3);
5278 $re = $2;
5279 my $depth = $re =~ tr/*/*/;
5280 if ($depth != $temp =~ tr/*/*/) {
5281 die "Only one set of wildcard directories " .
5282 "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
5284 if ($depth == 0) {
5285 die "One '*' is needed for glob: '$glob'\n";
5287 $re =~ s!\*!\[^/\]*!g;
5288 $re = quotemeta($left) . "($re)" . quotemeta($right);
5289 if (length $left && !($left =~ s!/+$!!g)) {
5290 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
5292 if (length $right && !($right =~ s!^/+!!g)) {
5293 die "Missing leading '/' on right side of: '$glob' ($right)\n";
5295 my $left_re = qr/^\/\Q$left\E(\/|$)/;
5296 bless { left => $left, right => $right, left_regex => $left_re,
5297 regex => qr/$re/, glob => $glob, depth => $depth }, $class;
5300 sub full_path {
5301 my ($self, $path) = @_;
5302 return (length $self->{left} ? "$self->{left}/" : '') .
5303 $path . (length $self->{right} ? "/$self->{right}" : '');
5306 __END__
5308 Data structures:
5311 $remotes = { # returned by read_all_remotes()
5312 'svn' => {
5313 # svn-remote.svn.url=https://svn.musicpd.org
5314 url => 'https://svn.musicpd.org',
5315 # svn-remote.svn.fetch=mpd/trunk:trunk
5316 fetch => {
5317 'mpd/trunk' => 'trunk',
5319 # svn-remote.svn.tags=mpd/tags/*:tags/*
5320 tags => {
5321 path => {
5322 left => 'mpd/tags',
5323 right => '',
5324 regex => qr!mpd/tags/([^/]+)$!,
5325 glob => 'tags/*',
5327 ref => {
5328 left => 'tags',
5329 right => '',
5330 regex => qr!tags/([^/]+)$!,
5331 glob => 'tags/*',
5337 $log_entry hashref as returned by libsvn_log_entry()
5339 log => 'whitespace-formatted log entry
5340 ', # trailing newline is preserved
5341 revision => '8', # integer
5342 date => '2004-02-24T17:01:44.108345Z', # commit date
5343 author => 'committer name'
5347 # this is generated by generate_diff();
5348 @mods = array of diff-index line hashes, each element represents one line
5349 of diff-index output
5351 diff-index line ($m hash)
5353 mode_a => first column of diff-index output, no leading ':',
5354 mode_b => second column of diff-index output,
5355 sha1_b => sha1sum of the final blob,
5356 chg => change type [MCRADT],
5357 file_a => original file name of a file (iff chg is 'C' or 'R')
5358 file_b => new/current file name of a file (any chg)
5362 # retval of read_url_paths{,_all}();
5363 $l_map = {
5364 # repository root url
5365 'https://svn.musicpd.org' => {
5366 # repository path # GIT_SVN_ID
5367 'mpd/trunk' => 'trunk',
5368 'mpd/tags/0.11.5' => 'tags/0.11.5',
5372 Notes:
5373 I don't trust the each() function on unless I created %hash myself
5374 because the internal iterator may not have started at base.