Add 'git svn reset' to unwind 'git svn fetch'
[git.git] / git-svn.perl
blobb1245cbab2ec7303482d7405e594ba666dfc3f58
1 #!/usr/bin/env perl
2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
4 use warnings;
5 use strict;
6 use vars qw/ $AUTHOR $VERSION
7 $sha1 $sha1_short $_revision $_repository
8 $_q $_authors $_authors_prog %users/;
9 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
10 $VERSION = '@@GIT_VERSION@@';
12 # From which subdir have we been invoked?
13 my $cmd_dir_prefix = eval {
14 command_oneline([qw/rev-parse --show-prefix/], STDERR => 0)
15 } || '';
17 my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
18 $ENV{GIT_DIR} ||= '.git';
19 $Git::SVN::default_repo_id = 'svn';
20 $Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
21 $Git::SVN::Ra::_log_window_size = 100;
23 $Git::SVN::Log::TZ = $ENV{TZ};
24 $ENV{TZ} = 'UTC';
25 $| = 1; # unbuffer STDOUT
27 sub fatal (@) { print STDERR "@_\n"; exit 1 }
28 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
29 require SVN::Ra;
30 require SVN::Delta;
31 if ($SVN::Core::VERSION lt '1.1.0') {
32 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
34 push @Git::SVN::Ra::ISA, 'SVN::Ra';
35 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
36 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
37 use Carp qw/croak/;
38 use Digest::MD5;
39 use IO::File qw//;
40 use File::Basename qw/dirname basename/;
41 use File::Path qw/mkpath/;
42 use File::Spec;
43 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
44 use IPC::Open3;
45 use Git;
47 BEGIN {
48 # import functions from Git into our packages, en masse
49 no strict 'refs';
50 foreach (qw/command command_oneline command_noisy command_output_pipe
51 command_input_pipe command_close_pipe
52 command_bidi_pipe command_close_bidi_pipe/) {
53 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
54 Git::SVN::Migration Git::SVN::Log Git::SVN),
55 __PACKAGE__) {
56 *{"${package}::$_"} = \&{"Git::$_"};
61 my ($SVN);
63 $sha1 = qr/[a-f\d]{40}/;
64 $sha1_short = qr/[a-f\d]{4,40}/;
65 my ($_stdin, $_help, $_edit,
66 $_message, $_file,
67 $_template, $_shared,
68 $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
69 $_merge, $_strategy, $_dry_run, $_local,
70 $_prefix, $_no_checkout, $_url, $_verbose,
71 $_git_format, $_commit_url, $_tag);
72 $Git::SVN::_follow_parent = 1;
73 $_q ||= 0;
74 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
75 'config-dir=s' => \$Git::SVN::Ra::config_dir,
76 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
77 'ignore-paths=s' => \$SVN::Git::Fetcher::_ignore_regex );
78 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
79 'authors-file|A=s' => \$_authors,
80 'authors-prog=s' => \$_authors_prog,
81 'repack:i' => \$Git::SVN::_repack,
82 'noMetadata' => \$Git::SVN::_no_metadata,
83 'useSvmProps' => \$Git::SVN::_use_svm_props,
84 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
85 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
86 'no-checkout' => \$_no_checkout,
87 'quiet|q+' => \$_q,
88 'repack-flags|repack-args|repack-opts=s' =>
89 \$Git::SVN::_repack_flags,
90 'use-log-author' => \$Git::SVN::_use_log_author,
91 'add-author-from' => \$Git::SVN::_add_author_from,
92 'localtime' => \$Git::SVN::_localtime,
93 %remote_opts );
95 my ($_trunk, $_tags, $_branches, $_stdlayout);
96 my %icv;
97 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
98 'trunk|T=s' => \$_trunk, 'tags|t=s' => \$_tags,
99 'branches|b=s' => \$_branches, 'prefix=s' => \$_prefix,
100 'stdlayout|s' => \$_stdlayout,
101 'minimize-url|m' => \$Git::SVN::_minimize_url,
102 'no-metadata' => sub { $icv{noMetadata} = 1 },
103 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
104 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
105 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
106 %remote_opts );
107 my %cmt_opts = ( 'edit|e' => \$_edit,
108 'rmdir' => \$SVN::Git::Editor::_rmdir,
109 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
110 'l=i' => \$SVN::Git::Editor::_rename_limit,
111 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
114 my %cmd = (
115 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
116 { 'revision|r=s' => \$_revision,
117 'fetch-all|all' => \$_fetch_all,
118 'parent|p' => \$_fetch_parent,
119 %fc_opts } ],
120 clone => [ \&cmd_clone, "Initialize and fetch revisions",
121 { 'revision|r=s' => \$_revision,
122 %fc_opts, %init_opts } ],
123 init => [ \&cmd_init, "Initialize a repo for tracking" .
124 " (requires URL argument)",
125 \%init_opts ],
126 'multi-init' => [ \&cmd_multi_init,
127 "Deprecated alias for ".
128 "'$0 init -T<trunk> -b<branches> -t<tags>'",
129 \%init_opts ],
130 dcommit => [ \&cmd_dcommit,
131 'Commit several diffs to merge with upstream',
132 { 'merge|m|M' => \$_merge,
133 'strategy|s=s' => \$_strategy,
134 'verbose|v' => \$_verbose,
135 'dry-run|n' => \$_dry_run,
136 'fetch-all|all' => \$_fetch_all,
137 'commit-url=s' => \$_commit_url,
138 'revision|r=i' => \$_revision,
139 'no-rebase' => \$_no_rebase,
140 %cmt_opts, %fc_opts } ],
141 branch => [ \&cmd_branch,
142 'Create a branch in the SVN repository',
143 { 'message|m=s' => \$_message,
144 'dry-run|n' => \$_dry_run,
145 'tag|t' => \$_tag } ],
146 tag => [ sub { $_tag = 1; cmd_branch(@_) },
147 'Create a tag in the SVN repository',
148 { 'message|m=s' => \$_message,
149 'dry-run|n' => \$_dry_run } ],
150 'set-tree' => [ \&cmd_set_tree,
151 "Set an SVN repository to a git tree-ish",
152 { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
153 'create-ignore' => [ \&cmd_create_ignore,
154 'Create a .gitignore per svn:ignore',
155 { 'revision|r=i' => \$_revision
156 } ],
157 'propget' => [ \&cmd_propget,
158 'Print the value of a property on a file or directory',
159 { 'revision|r=i' => \$_revision } ],
160 'proplist' => [ \&cmd_proplist,
161 'List all properties of a file or directory',
162 { 'revision|r=i' => \$_revision } ],
163 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
164 { 'revision|r=i' => \$_revision
165 } ],
166 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
167 { 'revision|r=i' => \$_revision
168 } ],
169 'multi-fetch' => [ \&cmd_multi_fetch,
170 "Deprecated alias for $0 fetch --all",
171 { 'revision|r=s' => \$_revision, %fc_opts } ],
172 'migrate' => [ sub { },
173 # no-op, we automatically run this anyways,
174 'Migrate configuration/metadata/layout from
175 previous versions of git-svn',
176 { 'minimize' => \$Git::SVN::Migration::_minimize,
177 %remote_opts } ],
178 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
179 { 'limit=i' => \$Git::SVN::Log::limit,
180 'revision|r=s' => \$_revision,
181 'verbose|v' => \$Git::SVN::Log::verbose,
182 'incremental' => \$Git::SVN::Log::incremental,
183 'oneline' => \$Git::SVN::Log::oneline,
184 'show-commit' => \$Git::SVN::Log::show_commit,
185 'non-recursive' => \$Git::SVN::Log::non_recursive,
186 'authors-file|A=s' => \$_authors,
187 'color' => \$Git::SVN::Log::color,
188 'pager=s' => \$Git::SVN::Log::pager
189 } ],
190 'find-rev' => [ \&cmd_find_rev,
191 "Translate between SVN revision numbers and tree-ish",
192 {} ],
193 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
194 { 'merge|m|M' => \$_merge,
195 'verbose|v' => \$_verbose,
196 'strategy|s=s' => \$_strategy,
197 'local|l' => \$_local,
198 'fetch-all|all' => \$_fetch_all,
199 'dry-run|n' => \$_dry_run,
200 %fc_opts } ],
201 'commit-diff' => [ \&cmd_commit_diff,
202 'Commit a diff between two trees',
203 { 'message|m=s' => \$_message,
204 'file|F=s' => \$_file,
205 'revision|r=s' => \$_revision,
206 %cmt_opts } ],
207 'info' => [ \&cmd_info,
208 "Show info about the latest SVN revision
209 on the current branch",
210 { 'url' => \$_url, } ],
211 'blame' => [ \&Git::SVN::Log::cmd_blame,
212 "Show what revision and author last modified each line of a file",
213 { 'git-format' => \$_git_format } ],
214 'reset' => [ \&cmd_reset,
215 "Undo fetches back to the specified SVN revision",
216 { 'revision|r=s' => \$_revision,
217 'parent|p' => \$_fetch_parent } ],
220 my $cmd;
221 for (my $i = 0; $i < @ARGV; $i++) {
222 if (defined $cmd{$ARGV[$i]}) {
223 $cmd = $ARGV[$i];
224 splice @ARGV, $i, 1;
225 last;
226 } elsif ($ARGV[$i] eq 'help') {
227 $cmd = $ARGV[$i+1];
228 usage(0);
232 # make sure we're always running at the top-level working directory
233 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
234 unless (-d $ENV{GIT_DIR}) {
235 if ($git_dir_user_set) {
236 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
237 "but it is not a directory\n";
239 my $git_dir = delete $ENV{GIT_DIR};
240 my $cdup = undef;
241 git_cmd_try {
242 $cdup = command_oneline(qw/rev-parse --show-cdup/);
243 $git_dir = '.' unless ($cdup);
244 chomp $cdup if ($cdup);
245 $cdup = "." unless ($cdup && length $cdup);
246 } "Already at toplevel, but $git_dir not found\n";
247 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
248 unless (-d $git_dir) {
249 die "$git_dir still not found after going to ",
250 "'$cdup'\n";
252 $ENV{GIT_DIR} = $git_dir;
254 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
257 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
259 read_repo_config(\%opts);
260 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
261 Getopt::Long::Configure('pass_through');
263 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
264 'minimize-connections' => \$Git::SVN::Migration::_minimize,
265 'id|i=s' => \$Git::SVN::default_ref_id,
266 'svn-remote|remote|R=s' => sub {
267 $Git::SVN::no_reuse_existing = 1;
268 $Git::SVN::default_repo_id = $_[1] });
269 exit 1 if (!$rv && $cmd && $cmd ne 'log');
271 usage(0) if $_help;
272 version() if $_version;
273 usage(1) unless defined $cmd;
274 load_authors() if $_authors;
275 if (defined $_authors_prog) {
276 $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
279 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
280 Git::SVN::Migration::migration_check();
282 Git::SVN::init_vars();
283 eval {
284 Git::SVN::verify_remotes_sanity();
285 $cmd{$cmd}->[0]->(@ARGV);
287 fatal $@ if $@;
288 post_fetch_checkout();
289 exit 0;
291 ####################### primary functions ######################
292 sub usage {
293 my $exit = shift || 0;
294 my $fd = $exit ? \*STDERR : \*STDOUT;
295 print $fd <<"";
296 git-svn - bidirectional operations between a single Subversion tree and git
297 Usage: git svn <command> [options] [arguments]\n
299 print $fd "Available commands:\n" unless $cmd;
301 foreach (sort keys %cmd) {
302 next if $cmd && $cmd ne $_;
303 next if /^multi-/; # don't show deprecated commands
304 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
305 foreach (sort keys %{$cmd{$_}->[2]}) {
306 # mixed-case options are for .git/config only
307 next if /[A-Z]/ && /^[a-z]+$/i;
308 # prints out arguments as they should be passed:
309 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
310 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
311 "--$_" : "-$_" }
312 split /\|/,$_)," $x\n";
315 print $fd <<"";
316 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
317 arbitrary identifier if you're tracking multiple SVN branches/repositories in
318 one git repository and want to keep them separate. See git-svn(1) for more
319 information.
321 exit $exit;
324 sub version {
325 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
326 exit 0;
329 sub do_git_init_db {
330 unless (-d $ENV{GIT_DIR}) {
331 my @init_db = ('init');
332 push @init_db, "--template=$_template" if defined $_template;
333 if (defined $_shared) {
334 if ($_shared =~ /[a-z]/) {
335 push @init_db, "--shared=$_shared";
336 } else {
337 push @init_db, "--shared";
340 command_noisy(@init_db);
341 $_repository = Git->repository(Repository => ".git");
343 command_noisy('config', 'core.autocrlf', 'false');
344 my $set;
345 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
346 foreach my $i (keys %icv) {
347 die "'$set' and '$i' cannot both be set\n" if $set;
348 next unless defined $icv{$i};
349 command_noisy('config', "$pfx.$i", $icv{$i});
350 $set = $i;
352 my $ignore_regex = \$SVN::Git::Fetcher::_ignore_regex;
353 command_noisy('config', "$pfx.ignore-paths", $$ignore_regex)
354 if defined $$ignore_regex;
357 sub init_subdir {
358 my $repo_path = shift or return;
359 mkpath([$repo_path]) unless -d $repo_path;
360 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
361 $ENV{GIT_DIR} = '.git';
362 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
365 sub cmd_clone {
366 my ($url, $path) = @_;
367 if (!defined $path &&
368 (defined $_trunk || defined $_branches || defined $_tags ||
369 defined $_stdlayout) &&
370 $url !~ m#^[a-z\+]+://#) {
371 $path = $url;
373 $path = basename($url) if !defined $path || !length $path;
374 cmd_init($url, $path);
375 Git::SVN::fetch_all($Git::SVN::default_repo_id);
376 command_oneline('config', 'svn.authorsfile', $_authors) if $_authors;
379 sub cmd_init {
380 if (defined $_stdlayout) {
381 $_trunk = 'trunk' if (!defined $_trunk);
382 $_tags = 'tags' if (!defined $_tags);
383 $_branches = 'branches' if (!defined $_branches);
385 if (defined $_trunk || defined $_branches || defined $_tags) {
386 return cmd_multi_init(@_);
388 my $url = shift or die "SVN repository location required ",
389 "as a command-line argument\n";
390 init_subdir(@_);
391 do_git_init_db();
393 Git::SVN->init($url);
396 sub cmd_fetch {
397 if (grep /^\d+=./, @_) {
398 die "'<rev>=<commit>' fetch arguments are ",
399 "no longer supported.\n";
401 my ($remote) = @_;
402 if (@_ > 1) {
403 die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
405 if ($_fetch_parent) {
406 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
407 unless ($gs) {
408 die "Unable to determine upstream SVN information from ",
409 "working tree history\n";
411 # just fetch, don't checkout.
412 $_no_checkout = 'true';
413 $_fetch_all ? $gs->fetch_all : $gs->fetch;
414 } elsif ($_fetch_all) {
415 cmd_multi_fetch();
416 } else {
417 $remote ||= $Git::SVN::default_repo_id;
418 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
422 sub cmd_set_tree {
423 my (@commits) = @_;
424 if ($_stdin || !@commits) {
425 print "Reading from stdin...\n";
426 @commits = ();
427 while (<STDIN>) {
428 if (/\b($sha1_short)\b/o) {
429 unshift @commits, $1;
433 my @revs;
434 foreach my $c (@commits) {
435 my @tmp = command('rev-parse',$c);
436 if (scalar @tmp == 1) {
437 push @revs, $tmp[0];
438 } elsif (scalar @tmp > 1) {
439 push @revs, reverse(command('rev-list',@tmp));
440 } else {
441 fatal "Failed to rev-parse $c";
444 my $gs = Git::SVN->new;
445 my ($r_last, $cmt_last) = $gs->last_rev_commit;
446 $gs->fetch;
447 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
448 fatal "There are new revisions that were fetched ",
449 "and need to be merged (or acknowledged) ",
450 "before committing.\nlast rev: $r_last\n",
451 " current: $gs->{last_rev}";
453 $gs->set_tree($_) foreach @revs;
454 print "Done committing ",scalar @revs," revisions to SVN\n";
455 unlink $gs->{index};
458 sub cmd_dcommit {
459 my $head = shift;
460 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
461 'Cannot dcommit with a dirty index. Commit your changes first, '
462 . "or stash them with `git stash'.\n";
463 $head ||= 'HEAD';
465 my $old_head;
466 if ($head ne 'HEAD') {
467 $old_head = eval {
468 command_oneline([qw/symbolic-ref -q HEAD/])
470 if ($old_head) {
471 $old_head =~ s{^refs/heads/}{};
472 } else {
473 $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
475 command(['checkout', $head], STDERR => 0);
478 my @refs;
479 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
480 unless ($gs) {
481 die "Unable to determine upstream SVN information from ",
482 "$head history.\nPerhaps the repository is empty.";
485 if (defined $_commit_url) {
486 $url = $_commit_url;
487 } else {
488 $url = eval { command_oneline('config', '--get',
489 "svn-remote.$gs->{repo_id}.commiturl") };
490 if (!$url) {
491 $url = $gs->full_url
495 my $last_rev = $_revision if defined $_revision;
496 if ($url) {
497 print "Committing to $url ...\n";
499 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
500 if ($_no_rebase && scalar(@$linear_refs) > 1) {
501 warn "Attempting to commit more than one change while ",
502 "--no-rebase is enabled.\n",
503 "If these changes depend on each other, re-running ",
504 "without --no-rebase may be required."
506 my $expect_url = $url;
507 Git::SVN::remove_username($expect_url);
508 while (1) {
509 my $d = shift @$linear_refs or last;
510 unless (defined $last_rev) {
511 (undef, $last_rev, undef) = cmt_metadata("$d~1");
512 unless (defined $last_rev) {
513 fatal "Unable to extract revision information ",
514 "from commit $d~1";
517 if ($_dry_run) {
518 print "diff-tree $d~1 $d\n";
519 } else {
520 my $cmt_rev;
521 my %ed_opts = ( r => $last_rev,
522 log => get_commit_entry($d)->{log},
523 ra => Git::SVN::Ra->new($url),
524 config => SVN::Core::config_get_config(
525 $Git::SVN::Ra::config_dir
527 tree_a => "$d~1",
528 tree_b => $d,
529 editor_cb => sub {
530 print "Committed r$_[0]\n";
531 $cmt_rev = $_[0];
533 svn_path => '');
534 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
535 print "No changes\n$d~1 == $d\n";
536 } elsif ($parents->{$d} && @{$parents->{$d}}) {
537 $gs->{inject_parents_dcommit}->{$cmt_rev} =
538 $parents->{$d};
540 $_fetch_all ? $gs->fetch_all : $gs->fetch;
541 $last_rev = $cmt_rev;
542 next if $_no_rebase;
544 # we always want to rebase against the current HEAD,
545 # not any head that was passed to us
546 my @diff = command('diff-tree', $d,
547 $gs->refname, '--');
548 my @finish;
549 if (@diff) {
550 @finish = rebase_cmd();
551 print STDERR "W: $d and ", $gs->refname,
552 " differ, using @finish:\n",
553 join("\n", @diff), "\n";
554 } else {
555 print "No changes between current HEAD and ",
556 $gs->refname,
557 "\nResetting to the latest ",
558 $gs->refname, "\n";
559 @finish = qw/reset --mixed/;
561 command_noisy(@finish, $gs->refname);
562 if (@diff) {
563 @refs = ();
564 my ($url_, $rev_, $uuid_, $gs_) =
565 working_head_info('HEAD', \@refs);
566 my ($linear_refs_, $parents_) =
567 linearize_history($gs_, \@refs);
568 if (scalar(@$linear_refs) !=
569 scalar(@$linear_refs_)) {
570 fatal "# of revisions changed ",
571 "\nbefore:\n",
572 join("\n", @$linear_refs),
573 "\n\nafter:\n",
574 join("\n", @$linear_refs_), "\n",
575 'If you are attempting to commit ',
576 "merges, try running:\n\t",
577 'git rebase --interactive',
578 '--preserve-merges ',
579 $gs->refname,
580 "\nBefore dcommitting";
582 if ($url_ ne $expect_url) {
583 fatal "URL mismatch after rebase: ",
584 "$url_ != $expect_url";
586 if ($uuid_ ne $uuid) {
587 fatal "uuid mismatch after rebase: ",
588 "$uuid_ != $uuid";
590 # remap parents
591 my (%p, @l, $i);
592 for ($i = 0; $i < scalar @$linear_refs; $i++) {
593 my $new = $linear_refs_->[$i] or next;
594 $p{$new} =
595 $parents->{$linear_refs->[$i]};
596 push @l, $new;
598 $parents = \%p;
599 $linear_refs = \@l;
604 if ($old_head) {
605 my $new_head = command_oneline(qw/rev-parse HEAD/);
606 my $new_is_symbolic = eval {
607 command_oneline(qw/symbolic-ref -q HEAD/);
609 if ($new_is_symbolic) {
610 print "dcommitted the branch ", $head, "\n";
611 } else {
612 print "dcommitted on a detached HEAD because you gave ",
613 "a revision argument.\n",
614 "The rewritten commit is: ", $new_head, "\n";
616 command(['checkout', $old_head], STDERR => 0);
619 unlink $gs->{index};
622 sub cmd_branch {
623 my ($branch_name, $head) = @_;
625 unless (defined $branch_name && length $branch_name) {
626 die(($_tag ? "tag" : "branch") . " name required\n");
628 $head ||= 'HEAD';
630 my ($src, $rev, undef, $gs) = working_head_info($head);
632 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
633 my $glob = $remote->{ $_tag ? 'tags' : 'branches' };
634 my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
635 my $dst = join '/', $remote->{url}, $lft, $branch_name, ($rgt || ());
637 my $ctx = SVN::Client->new(
638 auth => Git::SVN::Ra::_auth_providers(),
639 log_msg => sub {
640 ${ $_[0] } = defined $_message
641 ? $_message
642 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
643 . $branch_name;
647 eval {
648 $ctx->ls($dst, 'HEAD', 0);
649 } and die "branch ${branch_name} already exists\n";
651 print "Copying ${src} at r${rev} to ${dst}...\n";
652 $ctx->copy($src, $rev, $dst)
653 unless $_dry_run;
655 $gs->fetch_all;
658 sub cmd_find_rev {
659 my $revision_or_hash = shift or die "SVN or git revision required ",
660 "as a command-line argument\n";
661 my $result;
662 if ($revision_or_hash =~ /^r\d+$/) {
663 my $head = shift;
664 $head ||= 'HEAD';
665 my @refs;
666 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
667 unless ($gs) {
668 die "Unable to determine upstream SVN information from ",
669 "$head history\n";
671 my $desired_revision = substr($revision_or_hash, 1);
672 $result = $gs->rev_map_get($desired_revision, $uuid);
673 } else {
674 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
675 $result = $rev;
677 print "$result\n" if $result;
680 sub cmd_rebase {
681 command_noisy(qw/update-index --refresh/);
682 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
683 unless ($gs) {
684 die "Unable to determine upstream SVN information from ",
685 "working tree history\n";
687 if ($_dry_run) {
688 print "Remote Branch: " . $gs->refname . "\n";
689 print "SVN URL: " . $url . "\n";
690 return;
692 if (command(qw/diff-index HEAD --/)) {
693 print STDERR "Cannot rebase with uncommited changes:\n";
694 command_noisy('status');
695 exit 1;
697 unless ($_local) {
698 # rebase will checkout for us, so no need to do it explicitly
699 $_no_checkout = 'true';
700 $_fetch_all ? $gs->fetch_all : $gs->fetch;
702 command_noisy(rebase_cmd(), $gs->refname);
705 sub cmd_show_ignore {
706 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
707 $gs ||= Git::SVN->new;
708 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
709 $gs->prop_walk($gs->{path}, $r, sub {
710 my ($gs, $path, $props) = @_;
711 print STDOUT "\n# $path\n";
712 my $s = $props->{'svn:ignore'} or return;
713 $s =~ s/[\r\n]+/\n/g;
714 chomp $s;
715 $s =~ s#^#$path#gm;
716 print STDOUT "$s\n";
720 sub cmd_show_externals {
721 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
722 $gs ||= Git::SVN->new;
723 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
724 $gs->prop_walk($gs->{path}, $r, sub {
725 my ($gs, $path, $props) = @_;
726 print STDOUT "\n# $path\n";
727 my $s = $props->{'svn:externals'} or return;
728 $s =~ s/[\r\n]+/\n/g;
729 chomp $s;
730 $s =~ s#^#$path#gm;
731 print STDOUT "$s\n";
735 sub cmd_create_ignore {
736 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
737 $gs ||= Git::SVN->new;
738 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
739 $gs->prop_walk($gs->{path}, $r, sub {
740 my ($gs, $path, $props) = @_;
741 # $path is of the form /path/to/dir/
742 $path = '.' . $path;
743 # SVN can have attributes on empty directories,
744 # which git won't track
745 mkpath([$path]) unless -d $path;
746 my $ignore = $path . '.gitignore';
747 my $s = $props->{'svn:ignore'} or return;
748 open(GITIGNORE, '>', $ignore)
749 or fatal("Failed to open `$ignore' for writing: $!");
750 $s =~ s/[\r\n]+/\n/g;
751 chomp $s;
752 # Prefix all patterns so that the ignore doesn't apply
753 # to sub-directories.
754 $s =~ s#^#/#gm;
755 print GITIGNORE "$s\n";
756 close(GITIGNORE)
757 or fatal("Failed to close `$ignore': $!");
758 command_noisy('add', '-f', $ignore);
762 sub canonicalize_path {
763 my ($path) = @_;
764 my $dot_slash_added = 0;
765 if (substr($path, 0, 1) ne "/") {
766 $path = "./" . $path;
767 $dot_slash_added = 1;
769 # File::Spec->canonpath doesn't collapse x/../y into y (for a
770 # good reason), so let's do this manually.
771 $path =~ s#/+#/#g;
772 $path =~ s#/\.(?:/|$)#/#g;
773 $path =~ s#/[^/]+/\.\.##g;
774 $path =~ s#/$##g;
775 $path =~ s#^\./## if $dot_slash_added;
776 $path =~ s#^/##;
777 $path =~ s#^\.$##;
778 return $path;
781 # get_svnprops(PATH)
782 # ------------------
783 # Helper for cmd_propget and cmd_proplist below.
784 sub get_svnprops {
785 my $path = shift;
786 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
787 $gs ||= Git::SVN->new;
789 # prefix THE PATH by the sub-directory from which the user
790 # invoked us.
791 $path = $cmd_dir_prefix . $path;
792 fatal("No such file or directory: $path") unless -e $path;
793 my $is_dir = -d $path ? 1 : 0;
794 $path = $gs->{path} . '/' . $path;
796 # canonicalize the path (otherwise libsvn will abort or fail to
797 # find the file)
798 $path = canonicalize_path($path);
800 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
801 my $props;
802 if ($is_dir) {
803 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
805 else {
806 (undef, $props) = $gs->ra->get_file($path, $r, undef);
808 return $props;
811 # cmd_propget (PROP, PATH)
812 # ------------------------
813 # Print the SVN property PROP for PATH.
814 sub cmd_propget {
815 my ($prop, $path) = @_;
816 $path = '.' if not defined $path;
817 usage(1) if not defined $prop;
818 my $props = get_svnprops($path);
819 if (not defined $props->{$prop}) {
820 fatal("`$path' does not have a `$prop' SVN property.");
822 print $props->{$prop} . "\n";
825 # cmd_proplist (PATH)
826 # -------------------
827 # Print the list of SVN properties for PATH.
828 sub cmd_proplist {
829 my $path = shift;
830 $path = '.' if not defined $path;
831 my $props = get_svnprops($path);
832 print "Properties on '$path':\n";
833 foreach (sort keys %{$props}) {
834 print " $_\n";
838 sub cmd_multi_init {
839 my $url = shift;
840 unless (defined $_trunk || defined $_branches || defined $_tags) {
841 usage(1);
844 # there are currently some bugs that prevent multi-init/multi-fetch
845 # setups from working well without this.
846 $Git::SVN::_minimize_url = 1;
848 $_prefix = '' unless defined $_prefix;
849 if (defined $url) {
850 $url =~ s#/+$##;
851 init_subdir(@_);
853 do_git_init_db();
854 if (defined $_trunk) {
855 my $trunk_ref = $_prefix . 'trunk';
856 # try both old-style and new-style lookups:
857 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
858 unless ($gs_trunk) {
859 my ($trunk_url, $trunk_path) =
860 complete_svn_url($url, $_trunk);
861 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
862 undef, $trunk_ref);
865 return unless defined $_branches || defined $_tags;
866 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
867 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
868 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
871 sub cmd_multi_fetch {
872 my $remotes = Git::SVN::read_all_remotes();
873 foreach my $repo_id (sort keys %$remotes) {
874 if ($remotes->{$repo_id}->{url}) {
875 Git::SVN::fetch_all($repo_id, $remotes);
880 # this command is special because it requires no metadata
881 sub cmd_commit_diff {
882 my ($ta, $tb, $url) = @_;
883 my $usage = "Usage: $0 commit-diff -r<revision> ".
884 "<tree-ish> <tree-ish> [<URL>]";
885 fatal($usage) if (!defined $ta || !defined $tb);
886 my $svn_path = '';
887 if (!defined $url) {
888 my $gs = eval { Git::SVN->new };
889 if (!$gs) {
890 fatal("Needed URL or usable git-svn --id in ",
891 "the command-line\n", $usage);
893 $url = $gs->{url};
894 $svn_path = $gs->{path};
896 unless (defined $_revision) {
897 fatal("-r|--revision is a required argument\n", $usage);
899 if (defined $_message && defined $_file) {
900 fatal("Both --message/-m and --file/-F specified ",
901 "for the commit message.\n",
902 "I have no idea what you mean");
904 if (defined $_file) {
905 $_message = file_to_s($_file);
906 } else {
907 $_message ||= get_commit_entry($tb)->{log};
909 my $ra ||= Git::SVN::Ra->new($url);
910 my $r = $_revision;
911 if ($r eq 'HEAD') {
912 $r = $ra->get_latest_revnum;
913 } elsif ($r !~ /^\d+$/) {
914 die "revision argument: $r not understood by git-svn\n";
916 my %ed_opts = ( r => $r,
917 log => $_message,
918 ra => $ra,
919 tree_a => $ta,
920 tree_b => $tb,
921 editor_cb => sub { print "Committed r$_[0]\n" },
922 svn_path => $svn_path );
923 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
924 print "No changes\n$ta == $tb\n";
928 sub escape_uri_only {
929 my ($uri) = @_;
930 my @tmp;
931 foreach (split m{/}, $uri) {
932 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
933 push @tmp, $_;
935 join('/', @tmp);
938 sub escape_url {
939 my ($url) = @_;
940 if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
941 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
942 $url = "$scheme://$domain$uri";
944 $url;
947 sub cmd_info {
948 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
949 my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
950 if (exists $_[1]) {
951 die "Too many arguments specified\n";
954 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
956 if (!$file_type && !$diff_status) {
957 print STDERR "svn: '$path' is not under version control\n";
958 exit 1;
961 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
962 unless ($gs) {
963 die "Unable to determine upstream SVN information from ",
964 "working tree history\n";
967 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
968 $path = "." if $path eq "";
970 my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
972 if ($_url) {
973 print escape_url($full_url), "\n";
974 return;
977 my $result = "Path: $path\n";
978 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
979 $result .= "URL: " . escape_url($full_url) . "\n";
981 eval {
982 my $repos_root = $gs->repos_root;
983 Git::SVN::remove_username($repos_root);
984 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
986 if ($@) {
987 $result .= "Repository Root: (offline)\n";
989 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
990 ($SVN::Core::VERSION le '1.5.4' || $file_type ne "dir");
991 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
993 $result .= "Node Kind: " .
994 ($file_type eq "dir" ? "directory" : "file") . "\n";
996 my $schedule = $diff_status eq "A"
997 ? "add"
998 : ($diff_status eq "D" ? "delete" : "normal");
999 $result .= "Schedule: $schedule\n";
1001 if ($diff_status eq "A") {
1002 print $result, "\n";
1003 return;
1006 my ($lc_author, $lc_rev, $lc_date_utc);
1007 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
1008 my $log = command_output_pipe(@args);
1009 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
1010 while (<$log>) {
1011 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
1012 $lc_author = $1;
1013 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
1014 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
1015 (undef, $lc_rev, undef) = ::extract_metadata($1);
1018 close $log;
1020 Git::SVN::Log::set_local_timezone();
1022 $result .= "Last Changed Author: $lc_author\n";
1023 $result .= "Last Changed Rev: $lc_rev\n";
1024 $result .= "Last Changed Date: " .
1025 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
1027 if ($file_type ne "dir") {
1028 my $text_last_updated_date =
1029 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
1030 $result .=
1031 "Text Last Updated: " .
1032 Git::SVN::Log::format_svn_date($text_last_updated_date) .
1033 "\n";
1034 my $checksum;
1035 if ($diff_status eq "D") {
1036 my ($fh, $ctx) =
1037 command_output_pipe(qw(cat-file blob), "HEAD:$path");
1038 if ($file_type eq "link") {
1039 my $file_name = <$fh>;
1040 $checksum = md5sum("link $file_name");
1041 } else {
1042 $checksum = md5sum($fh);
1044 command_close_pipe($fh, $ctx);
1045 } elsif ($file_type eq "link") {
1046 my $file_name =
1047 command(qw(cat-file blob), "HEAD:$path");
1048 $checksum =
1049 md5sum("link " . $file_name);
1050 } else {
1051 open FILE, "<", $path or die $!;
1052 $checksum = md5sum(\*FILE);
1053 close FILE or die $!;
1055 $result .= "Checksum: " . $checksum . "\n";
1058 print $result, "\n";
1061 sub cmd_reset {
1062 my $target = shift || $_revision or die "SVN revision required\n";
1063 $target = $1 if $target =~ /^r(\d+)$/;
1064 $target =~ /^\d+$/ or die "Numeric SVN revision expected\n";
1065 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1066 unless ($gs) {
1067 die "Unable to determine upstream SVN information from ".
1068 "history\n";
1070 my ($r, $c) = $gs->find_rev_before($target, not $_fetch_parent);
1071 $gs->rev_map_set($r, $c, 'reset', $uuid);
1072 print "r$r = $c ($gs->{ref_id})\n";
1075 ########################### utility functions #########################
1077 sub rebase_cmd {
1078 my @cmd = qw/rebase/;
1079 push @cmd, '-v' if $_verbose;
1080 push @cmd, qw/--merge/ if $_merge;
1081 push @cmd, "--strategy=$_strategy" if $_strategy;
1082 @cmd;
1085 sub post_fetch_checkout {
1086 return if $_no_checkout;
1087 my $gs = $Git::SVN::_head or return;
1088 return if verify_ref('refs/heads/master^0');
1090 my $valid_head = verify_ref('HEAD^0');
1091 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1092 return if ($valid_head || !verify_ref('HEAD^0'));
1094 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1095 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1096 return if -f $index;
1098 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1099 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1100 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1101 print STDERR "Checked out HEAD:\n ",
1102 $gs->full_url, " r", $gs->last_rev, "\n";
1105 sub complete_svn_url {
1106 my ($url, $path) = @_;
1107 $path =~ s#/+$##;
1108 if ($path !~ m#^[a-z\+]+://#) {
1109 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1110 fatal("E: '$path' is not a complete URL ",
1111 "and a separate URL is not specified");
1113 return ($url, $path);
1115 return ($path, '');
1118 sub complete_url_ls_init {
1119 my ($ra, $repo_path, $switch, $pfx) = @_;
1120 unless ($repo_path) {
1121 print STDERR "W: $switch not specified\n";
1122 return;
1124 $repo_path =~ s#/+$##;
1125 if ($repo_path =~ m#^[a-z\+]+://#) {
1126 $ra = Git::SVN::Ra->new($repo_path);
1127 $repo_path = '';
1128 } else {
1129 $repo_path =~ s#^/+##;
1130 unless ($ra) {
1131 fatal("E: '$repo_path' is not a complete URL ",
1132 "and a separate URL is not specified");
1135 my $url = $ra->{url};
1136 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1137 my $k = "svn-remote.$gs->{repo_id}.url";
1138 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1139 if ($orig_url && ($orig_url ne $gs->{url})) {
1140 die "$k already set: $orig_url\n",
1141 "wanted to set to: $gs->{url}\n";
1143 command_oneline('config', $k, $gs->{url}) unless $orig_url;
1144 my $remote_path = "$ra->{svn_path}/$repo_path";
1145 $remote_path =~ s#/+#/#g;
1146 $remote_path =~ s#^/##g;
1147 $remote_path .= "/*" if $remote_path !~ /\*/;
1148 my ($n) = ($switch =~ /^--(\w+)/);
1149 if (length $pfx && $pfx !~ m#/$#) {
1150 die "--prefix='$pfx' must have a trailing slash '/'\n";
1152 command_noisy('config',
1153 "svn-remote.$gs->{repo_id}.$n",
1154 "$remote_path:refs/remotes/$pfx*" .
1155 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1158 sub verify_ref {
1159 my ($ref) = @_;
1160 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1161 { STDERR => 0 }); };
1164 sub get_tree_from_treeish {
1165 my ($treeish) = @_;
1166 # $treeish can be a symbolic ref, too:
1167 my $type = command_oneline(qw/cat-file -t/, $treeish);
1168 my $expected;
1169 while ($type eq 'tag') {
1170 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1172 if ($type eq 'commit') {
1173 $expected = (grep /^tree /, command(qw/cat-file commit/,
1174 $treeish))[0];
1175 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1176 die "Unable to get tree from $treeish\n" unless $expected;
1177 } elsif ($type eq 'tree') {
1178 $expected = $treeish;
1179 } else {
1180 die "$treeish is a $type, expected tree, tag or commit\n";
1182 return $expected;
1185 sub get_commit_entry {
1186 my ($treeish) = shift;
1187 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1188 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1189 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1190 open my $log_fh, '>', $commit_editmsg or croak $!;
1192 my $type = command_oneline(qw/cat-file -t/, $treeish);
1193 if ($type eq 'commit' || $type eq 'tag') {
1194 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1195 $type, $treeish);
1196 my $in_msg = 0;
1197 my $author;
1198 my $saw_from = 0;
1199 my $msgbuf = "";
1200 while (<$msg_fh>) {
1201 if (!$in_msg) {
1202 $in_msg = 1 if (/^\s*$/);
1203 $author = $1 if (/^author (.*>)/);
1204 } elsif (/^git-svn-id: /) {
1205 # skip this for now, we regenerate the
1206 # correct one on re-fetch anyways
1207 # TODO: set *:merge properties or like...
1208 } else {
1209 if (/^From:/ || /^Signed-off-by:/) {
1210 $saw_from = 1;
1212 $msgbuf .= $_;
1215 $msgbuf =~ s/\s+$//s;
1216 if ($Git::SVN::_add_author_from && defined($author)
1217 && !$saw_from) {
1218 $msgbuf .= "\n\nFrom: $author";
1220 print $log_fh $msgbuf or croak $!;
1221 command_close_pipe($msg_fh, $ctx);
1223 close $log_fh or croak $!;
1225 if ($_edit || ($type eq 'tree')) {
1226 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1227 # TODO: strip out spaces, comments, like git-commit.sh
1228 system($editor, $commit_editmsg);
1230 rename $commit_editmsg, $commit_msg or croak $!;
1232 require Encode;
1233 # SVN requires messages to be UTF-8 when entering the repo
1234 local $/;
1235 open $log_fh, '<', $commit_msg or croak $!;
1236 binmode $log_fh;
1237 chomp($log_entry{log} = <$log_fh>);
1239 my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
1240 my $msg = $log_entry{log};
1242 eval { $msg = Encode::decode($enc, $msg, 1) };
1243 if ($@) {
1244 die "Could not decode as $enc:\n", $msg,
1245 "\nPerhaps you need to set i18n.commitencoding\n";
1248 eval { $msg = Encode::encode('UTF-8', $msg, 1) };
1249 die "Could not encode as UTF-8:\n$msg\n" if $@;
1251 $log_entry{log} = $msg;
1253 close $log_fh or croak $!;
1255 unlink $commit_msg;
1256 \%log_entry;
1259 sub s_to_file {
1260 my ($str, $file, $mode) = @_;
1261 open my $fd,'>',$file or croak $!;
1262 print $fd $str,"\n" or croak $!;
1263 close $fd or croak $!;
1264 chmod ($mode &~ umask, $file) if (defined $mode);
1267 sub file_to_s {
1268 my $file = shift;
1269 open my $fd,'<',$file or croak "$!: file: $file\n";
1270 local $/;
1271 my $ret = <$fd>;
1272 close $fd or croak $!;
1273 $ret =~ s/\s*$//s;
1274 return $ret;
1277 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1278 sub load_authors {
1279 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1280 my $log = $cmd eq 'log';
1281 while (<$authors>) {
1282 chomp;
1283 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1284 my ($user, $name, $email) = ($1, $2, $3);
1285 if ($log) {
1286 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1287 } else {
1288 $users{$user} = [$name, $email];
1291 close $authors or croak $!;
1294 # convert GetOpt::Long specs for use by git-config
1295 sub read_repo_config {
1296 return unless -d $ENV{GIT_DIR};
1297 my $opts = shift;
1298 my @config_only;
1299 foreach my $o (keys %$opts) {
1300 # if we have mixedCase and a long option-only, then
1301 # it's a config-only variable that we don't need for
1302 # the command-line.
1303 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1304 my $v = $opts->{$o};
1305 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1306 $key =~ s/-//g;
1307 my $arg = 'git config';
1308 $arg .= ' --int' if ($o =~ /[:=]i$/);
1309 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1310 if (ref $v eq 'ARRAY') {
1311 chomp(my @tmp = `$arg --get-all svn.$key`);
1312 @$v = @tmp if @tmp;
1313 } else {
1314 chomp(my $tmp = `$arg --get svn.$key`);
1315 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1316 $$v = $tmp;
1320 delete @$opts{@config_only} if @config_only;
1323 sub extract_metadata {
1324 my $id = shift or return (undef, undef, undef);
1325 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1326 \s([a-f\d\-]+)$/x);
1327 if (!defined $rev || !$uuid || !$url) {
1328 # some of the original repositories I made had
1329 # identifiers like this:
1330 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
1332 return ($url, $rev, $uuid);
1335 sub cmt_metadata {
1336 return extract_metadata((grep(/^git-svn-id: /,
1337 command(qw/cat-file commit/, shift)))[-1]);
1340 sub cmt_sha2rev_batch {
1341 my %s2r;
1342 my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1343 my $list = shift;
1345 foreach my $sha (@{$list}) {
1346 my $first = 1;
1347 my $size = 0;
1348 print $out $sha, "\n";
1350 while (my $line = <$in>) {
1351 if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1352 last;
1353 } elsif ($first &&
1354 $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1355 $first = 0;
1356 $size = $1;
1357 next;
1358 } elsif ($line =~ /^(git-svn-id: )/) {
1359 my (undef, $rev, undef) =
1360 extract_metadata($line);
1361 $s2r{$sha} = $rev;
1364 $size -= length($line);
1365 last if ($size == 0);
1369 command_close_bidi_pipe($pid, $in, $out, $ctx);
1371 return \%s2r;
1374 sub working_head_info {
1375 my ($head, $refs) = @_;
1376 my @args = ('log', '--no-color', '--first-parent', '--pretty=medium');
1377 my ($fh, $ctx) = command_output_pipe(@args, $head);
1378 my $hash;
1379 my %max;
1380 while (<$fh>) {
1381 if ( m{^commit ($::sha1)$} ) {
1382 unshift @$refs, $hash if $hash and $refs;
1383 $hash = $1;
1384 next;
1386 next unless s{^\s*(git-svn-id:)}{$1};
1387 my ($url, $rev, $uuid) = extract_metadata($_);
1388 if (defined $url && defined $rev) {
1389 next if $max{$url} and $max{$url} < $rev;
1390 if (my $gs = Git::SVN->find_by_url($url)) {
1391 my $c = $gs->rev_map_get($rev, $uuid);
1392 if ($c && $c eq $hash) {
1393 close $fh; # break the pipe
1394 return ($url, $rev, $uuid, $gs);
1395 } else {
1396 $max{$url} ||= $gs->rev_map_max;
1401 command_close_pipe($fh, $ctx);
1402 (undef, undef, undef, undef);
1405 sub read_commit_parents {
1406 my ($parents, $c) = @_;
1407 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1408 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1409 @{$parents->{$c}} = split(/ /, $p);
1412 sub linearize_history {
1413 my ($gs, $refs) = @_;
1414 my %parents;
1415 foreach my $c (@$refs) {
1416 read_commit_parents(\%parents, $c);
1419 my @linear_refs;
1420 my %skip = ();
1421 my $last_svn_commit = $gs->last_commit;
1422 foreach my $c (reverse @$refs) {
1423 next if $c eq $last_svn_commit;
1424 last if $skip{$c};
1426 unshift @linear_refs, $c;
1427 $skip{$c} = 1;
1429 # we only want the first parent to diff against for linear
1430 # history, we save the rest to inject when we finalize the
1431 # svn commit
1432 my $fp_a = verify_ref("$c~1");
1433 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1434 if (!$fp_a || !$fp_b) {
1435 die "Commit $c\n",
1436 "has no parent commit, and therefore ",
1437 "nothing to diff against.\n",
1438 "You should be working from a repository ",
1439 "originally created by git-svn\n";
1441 if ($fp_a ne $fp_b) {
1442 die "$c~1 = $fp_a, however parsing commit $c ",
1443 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1446 foreach my $p (@{$parents{$c}}) {
1447 $skip{$p} = 1;
1450 (\@linear_refs, \%parents);
1453 sub find_file_type_and_diff_status {
1454 my ($path) = @_;
1455 return ('dir', '') if $path eq '';
1457 my $diff_output =
1458 command_oneline(qw(diff --cached --name-status --), $path) || "";
1459 my $diff_status = (split(' ', $diff_output))[0] || "";
1461 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1463 return (undef, undef) if !$diff_status && !$ls_tree;
1465 if ($diff_status eq "A") {
1466 return ("link", $diff_status) if -l $path;
1467 return ("dir", $diff_status) if -d $path;
1468 return ("file", $diff_status);
1471 my $mode = (split(' ', $ls_tree))[0] || "";
1473 return ("link", $diff_status) if $mode eq "120000";
1474 return ("dir", $diff_status) if $mode eq "040000";
1475 return ("file", $diff_status);
1478 sub md5sum {
1479 my $arg = shift;
1480 my $ref = ref $arg;
1481 my $md5 = Digest::MD5->new();
1482 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
1483 $md5->addfile($arg) or croak $!;
1484 } elsif ($ref eq 'SCALAR') {
1485 $md5->add($$arg) or croak $!;
1486 } elsif (!$ref) {
1487 $md5->add($arg) or croak $!;
1488 } else {
1489 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1491 return $md5->hexdigest();
1494 package Git::SVN;
1495 use strict;
1496 use warnings;
1497 use Fcntl qw/:DEFAULT :seek/;
1498 use constant rev_map_fmt => 'NH40';
1499 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1500 $_repack $_repack_flags $_use_svm_props $_head
1501 $_use_svnsync_props $no_reuse_existing $_minimize_url
1502 $_use_log_author $_add_author_from $_localtime/;
1503 use Carp qw/croak/;
1504 use File::Path qw/mkpath/;
1505 use File::Copy qw/copy/;
1506 use IPC::Open3;
1508 my ($_gc_nr, $_gc_period);
1510 # properties that we do not log:
1511 my %SKIP_PROP;
1512 BEGIN {
1513 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1514 svn:special svn:executable
1515 svn:entry:committed-rev
1516 svn:entry:last-author
1517 svn:entry:uuid
1518 svn:entry:committed-date/;
1520 # some options are read globally, but can be overridden locally
1521 # per [svn-remote "..."] section. Command-line options will *NOT*
1522 # override options set in an [svn-remote "..."] section
1523 no strict 'refs';
1524 for my $option (qw/follow_parent no_metadata use_svm_props
1525 use_svnsync_props/) {
1526 my $key = $option;
1527 $key =~ tr/_//d;
1528 my $prop = "-$option";
1529 *$option = sub {
1530 my ($self) = @_;
1531 return $self->{$prop} if exists $self->{$prop};
1532 my $k = "svn-remote.$self->{repo_id}.$key";
1533 eval { command_oneline(qw/config --get/, $k) };
1534 if ($@) {
1535 $self->{$prop} = ${"Git::SVN::_$option"};
1536 } else {
1537 my $v = command_oneline(qw/config --bool/,$k);
1538 $self->{$prop} = $v eq 'false' ? 0 : 1;
1540 return $self->{$prop};
1546 my (%LOCKFILES, %INDEX_FILES);
1547 END {
1548 unlink keys %LOCKFILES if %LOCKFILES;
1549 unlink keys %INDEX_FILES if %INDEX_FILES;
1552 sub resolve_local_globs {
1553 my ($url, $fetch, $glob_spec) = @_;
1554 return unless defined $glob_spec;
1555 my $ref = $glob_spec->{ref};
1556 my $path = $glob_spec->{path};
1557 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
1558 next unless m#^refs/remotes/$ref->{regex}$#;
1559 my $p = $1;
1560 my $pathname = desanitize_refname($path->full_path($p));
1561 my $refname = desanitize_refname($ref->full_path($p));
1562 if (my $existing = $fetch->{$pathname}) {
1563 if ($existing ne $refname) {
1564 die "Refspec conflict:\n",
1565 "existing: refs/remotes/$existing\n",
1566 " globbed: refs/remotes/$refname\n";
1568 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
1569 $u =~ s!^\Q$url\E(/|$)!! or die
1570 "refs/remotes/$refname: '$url' not found in '$u'\n";
1571 if ($pathname ne $u) {
1572 warn "W: Refspec glob conflict ",
1573 "(ref: refs/remotes/$refname):\n",
1574 "expected path: $pathname\n",
1575 " real path: $u\n",
1576 "Continuing ahead with $u\n";
1577 next;
1579 } else {
1580 $fetch->{$pathname} = $refname;
1585 sub parse_revision_argument {
1586 my ($base, $head) = @_;
1587 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1588 return ($base, $head);
1590 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1591 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1592 return ($head, $head) if ($::_revision eq 'HEAD');
1593 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1594 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1595 die "revision argument: $::_revision not understood by git-svn\n";
1598 sub fetch_all {
1599 my ($repo_id, $remotes) = @_;
1600 if (ref $repo_id) {
1601 my $gs = $repo_id;
1602 $repo_id = undef;
1603 $repo_id = $gs->{repo_id};
1605 $remotes ||= read_all_remotes();
1606 my $remote = $remotes->{$repo_id} or
1607 die "[svn-remote \"$repo_id\"] unknown\n";
1608 my $fetch = $remote->{fetch};
1609 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1610 my (@gs, @globs);
1611 my $ra = Git::SVN::Ra->new($url);
1612 my $uuid = $ra->get_uuid;
1613 my $head = $ra->get_latest_revnum;
1614 my $base = defined $fetch ? $head : 0;
1616 # read the max revs for wildcard expansion (branches/*, tags/*)
1617 foreach my $t (qw/branches tags/) {
1618 defined $remote->{$t} or next;
1619 push @globs, $remote->{$t};
1620 my $max_rev = eval { tmp_config(qw/--int --get/,
1621 "svn-remote.$repo_id.${t}-maxRev") };
1622 if (defined $max_rev && ($max_rev < $base)) {
1623 $base = $max_rev;
1624 } elsif (!defined $max_rev) {
1625 $base = 0;
1629 if ($fetch) {
1630 foreach my $p (sort keys %$fetch) {
1631 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1632 my $lr = $gs->rev_map_max;
1633 if (defined $lr) {
1634 $base = $lr if ($lr < $base);
1636 push @gs, $gs;
1640 ($base, $head) = parse_revision_argument($base, $head);
1641 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1644 sub read_all_remotes {
1645 my $r = {};
1646 my $use_svm_props = eval { command_oneline(qw/config --bool
1647 svn.useSvmProps/) };
1648 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
1649 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1650 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*(.+)\s*$!) {
1651 my ($remote, $local_ref, $_remote_ref) = ($1, $2, $3);
1652 die("svn-remote.$remote: remote ref '$_remote_ref' "
1653 . "must start with 'refs/remotes/'\n")
1654 unless $_remote_ref =~ m{^refs/remotes/(.+)};
1655 my $remote_ref = $1;
1656 $local_ref =~ s{^/}{};
1657 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1658 $r->{$remote}->{svm} = {} if $use_svm_props;
1659 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
1660 $r->{$1}->{svm} = {};
1661 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1662 $r->{$1}->{url} = $2;
1663 } elsif (m!^(.+)\.(branches|tags)=
1664 (.*):refs/remotes/(.+)\s*$/!x) {
1665 my ($p, $g) = ($3, $4);
1666 my $rs = $r->{$1}->{$2} = {
1667 t => $2,
1668 remote => $1,
1669 path => Git::SVN::GlobSpec->new($p),
1670 ref => Git::SVN::GlobSpec->new($g) };
1671 if (length($rs->{ref}->{right}) != 0) {
1672 die "The '*' glob character must be the last ",
1673 "character of '$g'\n";
1678 map {
1679 if (defined $r->{$_}->{svm}) {
1680 my $svm;
1681 eval {
1682 my $section = "svn-remote.$_";
1683 $svm = {
1684 source => tmp_config('--get',
1685 "$section.svm-source"),
1686 replace => tmp_config('--get',
1687 "$section.svm-replace"),
1690 $r->{$_}->{svm} = $svm;
1692 } keys %$r;
1697 sub init_vars {
1698 $_gc_nr = $_gc_period = 1000;
1699 if (defined $_repack || defined $_repack_flags) {
1700 warn "Repack options are obsolete; they have no effect.\n";
1704 sub verify_remotes_sanity {
1705 return unless -d $ENV{GIT_DIR};
1706 my %seen;
1707 foreach (command(qw/config -l/)) {
1708 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1709 if ($seen{$1}) {
1710 die "Remote ref refs/remote/$1 is tracked by",
1711 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1712 "Please resolve this ambiguity in ",
1713 "your git configuration file before ",
1714 "continuing\n";
1716 $seen{$1} = $_;
1721 sub find_existing_remote {
1722 my ($url, $remotes) = @_;
1723 return undef if $no_reuse_existing;
1724 my $existing;
1725 foreach my $repo_id (keys %$remotes) {
1726 my $u = $remotes->{$repo_id}->{url} or next;
1727 next if $u ne $url;
1728 $existing = $repo_id;
1729 last;
1731 $existing;
1734 sub init_remote_config {
1735 my ($self, $url, $no_write) = @_;
1736 $url =~ s!/+$!!; # strip trailing slash
1737 my $r = read_all_remotes();
1738 my $existing = find_existing_remote($url, $r);
1739 if ($existing) {
1740 unless ($no_write) {
1741 print STDERR "Using existing ",
1742 "[svn-remote \"$existing\"]\n";
1744 $self->{repo_id} = $existing;
1745 } elsif ($_minimize_url) {
1746 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1747 $existing = find_existing_remote($min_url, $r);
1748 if ($existing) {
1749 unless ($no_write) {
1750 print STDERR "Using existing ",
1751 "[svn-remote \"$existing\"]\n";
1753 $self->{repo_id} = $existing;
1755 if ($min_url ne $url) {
1756 unless ($no_write) {
1757 print STDERR "Using higher level of URL: ",
1758 "$url => $min_url\n";
1760 my $old_path = $self->{path};
1761 $self->{path} = $url;
1762 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1763 if (length $old_path) {
1764 $self->{path} .= "/$old_path";
1766 $url = $min_url;
1769 my $orig_url;
1770 if (!$existing) {
1771 # verify that we aren't overwriting anything:
1772 $orig_url = eval {
1773 command_oneline('config', '--get',
1774 "svn-remote.$self->{repo_id}.url")
1776 if ($orig_url && ($orig_url ne $url)) {
1777 die "svn-remote.$self->{repo_id}.url already set: ",
1778 "$orig_url\nwanted to set to: $url\n";
1781 my ($xrepo_id, $xpath) = find_ref($self->refname);
1782 if (defined $xpath) {
1783 die "svn-remote.$xrepo_id.fetch already set to track ",
1784 "$xpath:refs/remotes/", $self->refname, "\n";
1786 unless ($no_write) {
1787 command_noisy('config',
1788 "svn-remote.$self->{repo_id}.url", $url);
1789 $self->{path} =~ s{^/}{};
1790 command_noisy('config', '--add',
1791 "svn-remote.$self->{repo_id}.fetch",
1792 "$self->{path}:".$self->refname);
1794 $self->{url} = $url;
1797 sub find_by_url { # repos_root and, path are optional
1798 my ($class, $full_url, $repos_root, $path) = @_;
1800 return undef unless defined $full_url;
1801 remove_username($full_url);
1802 remove_username($repos_root) if defined $repos_root;
1803 my $remotes = read_all_remotes();
1804 if (defined $full_url && defined $repos_root && !defined $path) {
1805 $path = $full_url;
1806 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1808 foreach my $repo_id (keys %$remotes) {
1809 my $u = $remotes->{$repo_id}->{url} or next;
1810 remove_username($u);
1811 next if defined $repos_root && $repos_root ne $u;
1813 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1814 foreach (qw/branches tags/) {
1815 resolve_local_globs($u, $fetch,
1816 $remotes->{$repo_id}->{$_});
1818 my $p = $path;
1819 my $rwr = rewrite_root({repo_id => $repo_id});
1820 my $svm = $remotes->{$repo_id}->{svm}
1821 if defined $remotes->{$repo_id}->{svm};
1822 unless (defined $p) {
1823 $p = $full_url;
1824 my $z = $u;
1825 my $prefix = '';
1826 if ($rwr) {
1827 $z = $rwr;
1828 remove_username($z);
1829 } elsif (defined $svm) {
1830 $z = $svm->{source};
1831 $prefix = $svm->{replace};
1832 $prefix =~ s#^\Q$u\E(?:/|$)##;
1833 $prefix =~ s#/$##;
1835 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
1837 foreach my $f (keys %$fetch) {
1838 next if $f ne $p;
1839 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1842 undef;
1845 sub init {
1846 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1847 my $self = _new($class, $repo_id, $ref_id, $path);
1848 if (defined $url) {
1849 $self->init_remote_config($url, $no_write);
1851 $self;
1854 sub find_ref {
1855 my ($ref_id) = @_;
1856 foreach (command(qw/config -l/)) {
1857 next unless m!^svn-remote\.(.+)\.fetch=
1858 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1859 my ($repo_id, $path, $ref) = ($1, $2, $3);
1860 if ($ref eq $ref_id) {
1861 $path = '' if ($path =~ m#^\./?#);
1862 return ($repo_id, $path);
1865 (undef, undef, undef);
1868 sub new {
1869 my ($class, $ref_id, $repo_id, $path) = @_;
1870 if (defined $ref_id && !defined $repo_id && !defined $path) {
1871 ($repo_id, $path) = find_ref($ref_id);
1872 if (!defined $repo_id) {
1873 die "Could not find a \"svn-remote.*.fetch\" key ",
1874 "in the repository configuration matching: ",
1875 "refs/remotes/$ref_id\n";
1878 my $self = _new($class, $repo_id, $ref_id, $path);
1879 if (!defined $self->{path} || !length $self->{path}) {
1880 my $fetch = command_oneline('config', '--get',
1881 "svn-remote.$repo_id.fetch",
1882 ":refs/remotes/$ref_id\$") or
1883 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1884 "\":refs/remotes/$ref_id\$\" in config\n";
1885 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1887 $self->{url} = command_oneline('config', '--get',
1888 "svn-remote.$repo_id.url") or
1889 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1890 $self->rebuild;
1891 $self;
1894 sub refname {
1895 my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1897 # It cannot end with a slash /, we'll throw up on this because
1898 # SVN can't have directories with a slash in their name, either:
1899 if ($refname =~ m{/$}) {
1900 die "ref: '$refname' ends with a trailing slash, this is ",
1901 "not permitted by git nor Subversion\n";
1904 # It cannot have ASCII control character space, tilde ~, caret ^,
1905 # colon :, question-mark ?, asterisk *, space, or open bracket [
1906 # anywhere.
1908 # Additionally, % must be escaped because it is used for escaping
1909 # and we want our escaped refname to be reversible
1910 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1912 # no slash-separated component can begin with a dot .
1913 # /.* becomes /%2E*
1914 $refname =~ s{/\.}{/%2E}g;
1916 # It cannot have two consecutive dots .. anywhere
1917 # .. becomes %2E%2E
1918 $refname =~ s{\.\.}{%2E%2E}g;
1920 return $refname;
1923 sub desanitize_refname {
1924 my ($refname) = @_;
1925 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1926 return $refname;
1929 sub svm_uuid {
1930 my ($self) = @_;
1931 return $self->{svm}->{uuid} if $self->svm;
1932 $self->ra;
1933 unless ($self->{svm}) {
1934 die "SVM UUID not cached, and reading remotely failed\n";
1936 $self->{svm}->{uuid};
1939 sub svm {
1940 my ($self) = @_;
1941 return $self->{svm} if $self->{svm};
1942 my $svm;
1943 # see if we have it in our config, first:
1944 eval {
1945 my $section = "svn-remote.$self->{repo_id}";
1946 $svm = {
1947 source => tmp_config('--get', "$section.svm-source"),
1948 uuid => tmp_config('--get', "$section.svm-uuid"),
1949 replace => tmp_config('--get', "$section.svm-replace"),
1952 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1953 $self->{svm} = $svm;
1955 $self->{svm};
1958 sub _set_svm_vars {
1959 my ($self, $ra) = @_;
1960 return $ra if $self->svm;
1962 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1963 "(svm:source, svm:uuid) ",
1964 "from the following URLs:\n" );
1965 sub read_svm_props {
1966 my ($self, $ra, $path, $r) = @_;
1967 my $props = ($ra->get_dir($path, $r))[2];
1968 my $src = $props->{'svm:source'};
1969 my $uuid = $props->{'svm:uuid'};
1970 return undef if (!$src || !$uuid);
1972 chomp($src, $uuid);
1974 $uuid =~ m{^[0-9a-f\-]{30,}$}
1975 or die "doesn't look right - svm:uuid is '$uuid'\n";
1977 # the '!' is used to mark the repos_root!/relative/path
1978 $src =~ s{/?!/?}{/};
1979 $src =~ s{/+$}{}; # no trailing slashes please
1980 # username is of no interest
1981 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1983 my $replace = $ra->{url};
1984 $replace .= "/$path" if length $path;
1986 my $section = "svn-remote.$self->{repo_id}";
1987 tmp_config("$section.svm-source", $src);
1988 tmp_config("$section.svm-replace", $replace);
1989 tmp_config("$section.svm-uuid", $uuid);
1990 $self->{svm} = {
1991 source => $src,
1992 uuid => $uuid,
1993 replace => $replace
1997 my $r = $ra->get_latest_revnum;
1998 my $path = $self->{path};
1999 my %tried;
2000 while (length $path) {
2001 unless ($tried{"$self->{url}/$path"}) {
2002 return $ra if $self->read_svm_props($ra, $path, $r);
2003 $tried{"$self->{url}/$path"} = 1;
2005 $path =~ s#/?[^/]+$##;
2007 die "Path: '$path' should be ''\n" if $path ne '';
2008 return $ra if $self->read_svm_props($ra, $path, $r);
2009 $tried{"$self->{url}/$path"} = 1;
2011 if ($ra->{repos_root} eq $self->{url}) {
2012 die @err, (map { " $_\n" } keys %tried), "\n";
2015 # nope, make sure we're connected to the repository root:
2016 my $ok;
2017 my @tried_b;
2018 $path = $ra->{svn_path};
2019 $ra = Git::SVN::Ra->new($ra->{repos_root});
2020 while (length $path) {
2021 unless ($tried{"$ra->{url}/$path"}) {
2022 $ok = $self->read_svm_props($ra, $path, $r);
2023 last if $ok;
2024 $tried{"$ra->{url}/$path"} = 1;
2026 $path =~ s#/?[^/]+$##;
2028 die "Path: '$path' should be ''\n" if $path ne '';
2029 $ok ||= $self->read_svm_props($ra, $path, $r);
2030 $tried{"$ra->{url}/$path"} = 1;
2031 if (!$ok) {
2032 die @err, (map { " $_\n" } keys %tried), "\n";
2034 Git::SVN::Ra->new($self->{url});
2037 sub svnsync {
2038 my ($self) = @_;
2039 return $self->{svnsync} if $self->{svnsync};
2041 if ($self->no_metadata) {
2042 die "Can't have both 'noMetadata' and ",
2043 "'useSvnsyncProps' options set!\n";
2045 if ($self->rewrite_root) {
2046 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
2047 "options set!\n";
2050 my $svnsync;
2051 # see if we have it in our config, first:
2052 eval {
2053 my $section = "svn-remote.$self->{repo_id}";
2055 my $url = tmp_config('--get', "$section.svnsync-url");
2056 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2057 die "doesn't look right - svn:sync-from-url is '$url'\n";
2059 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
2060 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
2061 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2063 $svnsync = { url => $url, uuid => $uuid }
2065 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
2066 return $self->{svnsync} = $svnsync;
2069 my $err = "useSvnsyncProps set, but failed to read " .
2070 "svnsync property: svn:sync-from-";
2071 my $rp = $self->ra->rev_proplist(0);
2073 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
2074 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2075 die "doesn't look right - svn:sync-from-url is '$url'\n";
2077 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
2078 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
2079 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2081 my $section = "svn-remote.$self->{repo_id}";
2082 tmp_config('--add', "$section.svnsync-uuid", $uuid);
2083 tmp_config('--add', "$section.svnsync-url", $url);
2084 return $self->{svnsync} = { url => $url, uuid => $uuid };
2087 # this allows us to memoize our SVN::Ra UUID locally and avoid a
2088 # remote lookup (useful for 'git svn log').
2089 sub ra_uuid {
2090 my ($self) = @_;
2091 unless ($self->{ra_uuid}) {
2092 my $key = "svn-remote.$self->{repo_id}.uuid";
2093 my $uuid = eval { tmp_config('--get', $key) };
2094 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
2095 $self->{ra_uuid} = $uuid;
2096 } else {
2097 die "ra_uuid called without URL\n" unless $self->{url};
2098 $self->{ra_uuid} = $self->ra->get_uuid;
2099 tmp_config('--add', $key, $self->{ra_uuid});
2102 $self->{ra_uuid};
2105 sub _set_repos_root {
2106 my ($self, $repos_root) = @_;
2107 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2108 $repos_root ||= $self->ra->{repos_root};
2109 tmp_config($k, $repos_root);
2110 $repos_root;
2113 sub repos_root {
2114 my ($self) = @_;
2115 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2116 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
2119 sub ra {
2120 my ($self) = shift;
2121 my $ra = Git::SVN::Ra->new($self->{url});
2122 $self->_set_repos_root($ra->{repos_root});
2123 if ($self->use_svm_props && !$self->{svm}) {
2124 if ($self->no_metadata) {
2125 die "Can't have both 'noMetadata' and ",
2126 "'useSvmProps' options set!\n";
2127 } elsif ($self->use_svnsync_props) {
2128 die "Can't have both 'useSvnsyncProps' and ",
2129 "'useSvmProps' options set!\n";
2131 $ra = $self->_set_svm_vars($ra);
2132 $self->{-want_revprops} = 1;
2134 $ra;
2137 sub rel_path {
2138 my ($self) = @_;
2139 my $repos_root = $self->ra->{repos_root};
2140 return $self->{path} if ($self->{url} eq $repos_root);
2141 my $url = $self->{url} .
2142 (length $self->{path} ? "/$self->{path}" : $self->{path});
2143 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
2144 $url;
2147 # prop_walk(PATH, REV, SUB)
2148 # -------------------------
2149 # Recursively traverse PATH at revision REV and invoke SUB for each
2150 # directory that contains a SVN property. SUB will be invoked as
2151 # follows: &SUB(gs, path, props); where `gs' is this instance of
2152 # Git::SVN, `path' the path to the directory where the properties
2153 # `props' were found. The `path' will be relative to point of checkout,
2154 # that is, if url://repo/trunk is the current Git branch, and that
2155 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
2156 # as `path' (note the trailing `/').
2157 sub prop_walk {
2158 my ($self, $path, $rev, $sub) = @_;
2160 $path =~ s#^/##;
2161 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2162 $path =~ s#^/*#/#g;
2163 my $p = $path;
2164 # Strip the irrelevant part of the path.
2165 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2166 # Ensure the path is terminated by a `/'.
2167 $p =~ s#/*$#/#;
2169 # The properties contain all the internal SVN stuff nobody
2170 # (usually) cares about.
2171 my $interesting_props = 0;
2172 foreach (keys %{$props}) {
2173 # If it doesn't start with `svn:', it must be a
2174 # user-defined property.
2175 ++$interesting_props and next if $_ !~ /^svn:/;
2176 # FIXME: Fragile, if SVN adds new public properties,
2177 # this needs to be updated.
2178 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2179 |eol-style|mime-type
2180 |externals|needs-lock)$/x;
2182 &$sub($self, $p, $props) if $interesting_props;
2184 foreach (sort keys %$dirent) {
2185 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
2186 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
2190 sub last_rev { ($_[0]->last_rev_commit)[0] }
2191 sub last_commit { ($_[0]->last_rev_commit)[1] }
2193 # returns the newest SVN revision number and newest commit SHA1
2194 sub last_rev_commit {
2195 my ($self) = @_;
2196 if (defined $self->{last_rev} && defined $self->{last_commit}) {
2197 return ($self->{last_rev}, $self->{last_commit});
2199 my $c = ::verify_ref($self->refname.'^0');
2200 if ($c && !$self->use_svm_props && !$self->no_metadata) {
2201 my $rev = (::cmt_metadata($c))[1];
2202 if (defined $rev) {
2203 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2204 return ($rev, $c);
2207 my $map_path = $self->map_path;
2208 unless (-e $map_path) {
2209 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2210 return (undef, undef);
2212 my ($rev, $commit) = $self->rev_map_max(1);
2213 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2214 return ($rev, $commit);
2217 sub get_fetch_range {
2218 my ($self, $min, $max) = @_;
2219 $max ||= $self->ra->get_latest_revnum;
2220 $min ||= $self->rev_map_max;
2221 (++$min, $max);
2224 sub tmp_config {
2225 my (@args) = @_;
2226 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2227 my $config = "$ENV{GIT_DIR}/svn/.metadata";
2228 if (! -f $config && -f $old_def_config) {
2229 rename $old_def_config, $config or
2230 die "Failed rename $old_def_config => $config: $!\n";
2232 my $old_config = $ENV{GIT_CONFIG};
2233 $ENV{GIT_CONFIG} = $config;
2234 $@ = undef;
2235 my @ret = eval {
2236 unless (-f $config) {
2237 mkfile($config);
2238 open my $fh, '>', $config or
2239 die "Can't open $config: $!\n";
2240 print $fh "; This file is used internally by ",
2241 "git-svn\n" or die
2242 "Couldn't write to $config: $!\n";
2243 print $fh "; You should not have to edit it\n" or
2244 die "Couldn't write to $config: $!\n";
2245 close $fh or die "Couldn't close $config: $!\n";
2247 command('config', @args);
2249 my $err = $@;
2250 if (defined $old_config) {
2251 $ENV{GIT_CONFIG} = $old_config;
2252 } else {
2253 delete $ENV{GIT_CONFIG};
2255 die $err if $err;
2256 wantarray ? @ret : $ret[0];
2259 sub tmp_index_do {
2260 my ($self, $sub) = @_;
2261 my $old_index = $ENV{GIT_INDEX_FILE};
2262 $ENV{GIT_INDEX_FILE} = $self->{index};
2263 $@ = undef;
2264 my @ret = eval {
2265 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2266 mkpath([$dir]) unless -d $dir;
2267 &$sub;
2269 my $err = $@;
2270 if (defined $old_index) {
2271 $ENV{GIT_INDEX_FILE} = $old_index;
2272 } else {
2273 delete $ENV{GIT_INDEX_FILE};
2275 die $err if $err;
2276 wantarray ? @ret : $ret[0];
2279 sub assert_index_clean {
2280 my ($self, $treeish) = @_;
2282 $self->tmp_index_do(sub {
2283 command_noisy('read-tree', $treeish) unless -e $self->{index};
2284 my $x = command_oneline('write-tree');
2285 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2286 /^tree ($::sha1)/mo);
2287 return if $y eq $x;
2289 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2290 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2291 command_noisy('read-tree', $treeish);
2292 $x = command_oneline('write-tree');
2293 if ($y ne $x) {
2294 ::fatal "trees ($treeish) $y != $x\n",
2295 "Something is seriously wrong...";
2300 sub get_commit_parents {
2301 my ($self, $log_entry) = @_;
2302 my (%seen, @ret, @tmp);
2303 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2304 if (my $ip = $self->{inject_parents}) {
2305 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2306 push @tmp, $commit;
2309 if (my $cur = ::verify_ref($self->refname.'^0')) {
2310 push @tmp, $cur;
2312 if (my $ipd = $self->{inject_parents_dcommit}) {
2313 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2314 push @tmp, @$commit;
2317 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2318 while (my $p = shift @tmp) {
2319 next if $seen{$p};
2320 $seen{$p} = 1;
2321 push @ret, $p;
2322 # MAXPARENT is defined to 16 in commit-tree.c:
2323 last if @ret >= 16;
2325 if (@tmp) {
2326 die "r$log_entry->{revision}: No room for parents:\n\t",
2327 join("\n\t", @tmp), "\n";
2329 @ret;
2332 sub rewrite_root {
2333 my ($self) = @_;
2334 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2335 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2336 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2337 if ($rwr) {
2338 $rwr =~ s#/+$##;
2339 if ($rwr !~ m#^[a-z\+]+://#) {
2340 die "$rwr is not a valid URL (key: $k)\n";
2343 $self->{-rewrite_root} = $rwr;
2346 sub metadata_url {
2347 my ($self) = @_;
2348 ($self->rewrite_root || $self->{url}) .
2349 (length $self->{path} ? '/' . $self->{path} : '');
2352 sub full_url {
2353 my ($self) = @_;
2354 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2358 sub set_commit_header_env {
2359 my ($log_entry) = @_;
2360 my %env;
2361 foreach my $ned (qw/NAME EMAIL DATE/) {
2362 foreach my $ac (qw/AUTHOR COMMITTER/) {
2363 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2367 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2368 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2369 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2371 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2372 ? $log_entry->{commit_name}
2373 : $log_entry->{name};
2374 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2375 ? $log_entry->{commit_email}
2376 : $log_entry->{email};
2377 \%env;
2380 sub restore_commit_header_env {
2381 my ($env) = @_;
2382 foreach my $ned (qw/NAME EMAIL DATE/) {
2383 foreach my $ac (qw/AUTHOR COMMITTER/) {
2384 my $k = "GIT_${ac}_${ned}";
2385 if (defined $env->{$k}) {
2386 $ENV{$k} = $env->{$k};
2387 } else {
2388 delete $ENV{$k};
2394 sub gc {
2395 command_noisy('gc', '--auto');
2398 sub do_git_commit {
2399 my ($self, $log_entry) = @_;
2400 my $lr = $self->last_rev;
2401 if (defined $lr && $lr >= $log_entry->{revision}) {
2402 die "Last fetched revision of ", $self->refname,
2403 " was r$lr, but we are about to fetch: ",
2404 "r$log_entry->{revision}!\n";
2406 if (my $c = $self->rev_map_get($log_entry->{revision})) {
2407 croak "$log_entry->{revision} = $c already exists! ",
2408 "Why are we refetching it?\n";
2410 my $old_env = set_commit_header_env($log_entry);
2411 my $tree = $log_entry->{tree};
2412 if (!defined $tree) {
2413 $tree = $self->tmp_index_do(sub {
2414 command_oneline('write-tree') });
2416 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2418 my @exec = ('git', 'commit-tree', $tree);
2419 foreach ($self->get_commit_parents($log_entry)) {
2420 push @exec, '-p', $_;
2422 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2423 or croak $!;
2424 binmode $msg_fh;
2426 # we always get UTF-8 from SVN, but we may want our commits in
2427 # a different encoding.
2428 if (my $enc = Git::config('i18n.commitencoding')) {
2429 require Encode;
2430 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
2432 print $msg_fh $log_entry->{log} or croak $!;
2433 restore_commit_header_env($old_env);
2434 unless ($self->no_metadata) {
2435 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2436 or croak $!;
2438 $msg_fh->flush == 0 or croak $!;
2439 close $msg_fh or croak $!;
2440 chomp(my $commit = do { local $/; <$out_fh> });
2441 close $out_fh or croak $!;
2442 waitpid $pid, 0;
2443 croak $? if $?;
2444 if ($commit !~ /^$::sha1$/o) {
2445 die "Failed to commit, invalid sha1: $commit\n";
2448 $self->rev_map_set($log_entry->{revision}, $commit, 1);
2450 $self->{last_rev} = $log_entry->{revision};
2451 $self->{last_commit} = $commit;
2452 print "r$log_entry->{revision}" unless $::_q > 1;
2453 if (defined $log_entry->{svm_revision}) {
2454 print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
2455 $self->rev_map_set($log_entry->{svm_revision}, $commit,
2456 0, $self->svm_uuid);
2458 print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
2459 if (--$_gc_nr == 0) {
2460 $_gc_nr = $_gc_period;
2461 gc();
2463 return $commit;
2466 sub match_paths {
2467 my ($self, $paths, $r) = @_;
2468 return 1 if $self->{path} eq '';
2469 if (my $path = $paths->{"/$self->{path}"}) {
2470 return ($path->{action} eq 'D') ? 0 : 1;
2472 my $repos_root = $self->ra->{repos_root};
2473 my $extended_path = $self->{url} . '/' . $self->{path};
2474 $extended_path =~ s#^\Q$repos_root\E(/|$)##;
2475 $self->{path_regex} ||= qr/^\/\Q$extended_path\E\//;
2476 if (grep /$self->{path_regex}/, keys %$paths) {
2477 return 1;
2479 my $c = '';
2480 foreach (split m#/#, $self->{path}) {
2481 $c .= "/$_";
2482 next unless ($paths->{$c} &&
2483 ($paths->{$c}->{action} =~ /^[AR]$/));
2484 if ($self->ra->check_path($self->{path}, $r) ==
2485 $SVN::Node::dir) {
2486 return 1;
2489 return 0;
2492 sub find_parent_branch {
2493 my ($self, $paths, $rev) = @_;
2494 return undef unless $self->follow_parent;
2495 unless (defined $paths) {
2496 my $err_handler = $SVN::Error::handler;
2497 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2498 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
2499 $paths =
2500 Git::SVN::Ra::dup_changed_paths($_[0]) });
2501 $SVN::Error::handler = $err_handler;
2503 return undef unless defined $paths;
2505 # look for a parent from another branch:
2506 my @b_path_components = split m#/#, $self->rel_path;
2507 my @a_path_components;
2508 my $i;
2509 while (@b_path_components) {
2510 $i = $paths->{'/'.join('/', @b_path_components)};
2511 last if $i && defined $i->{copyfrom_path};
2512 unshift(@a_path_components, pop(@b_path_components));
2514 return undef unless defined $i && defined $i->{copyfrom_path};
2515 my $branch_from = $i->{copyfrom_path};
2516 if (@a_path_components) {
2517 print STDERR "branch_from: $branch_from => ";
2518 $branch_from .= '/'.join('/', @a_path_components);
2519 print STDERR $branch_from, "\n";
2521 my $r = $i->{copyfrom_rev};
2522 my $repos_root = $self->ra->{repos_root};
2523 my $url = $self->ra->{url};
2524 my $new_url = $repos_root . $branch_from;
2525 print STDERR "Found possible branch point: ",
2526 "$new_url => ", $self->full_url, ", $r\n";
2527 $branch_from =~ s#^/##;
2528 my $gs = $self->other_gs($new_url, $url, $repos_root,
2529 $branch_from, $r, $self->{ref_id});
2530 my ($r0, $parent) = $gs->find_rev_before($r, 1);
2532 my ($base, $head);
2533 if (!defined $r0 || !defined $parent) {
2534 ($base, $head) = parse_revision_argument(0, $r);
2535 } else {
2536 if ($r0 < $r) {
2537 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
2538 0, 1, sub { $base = $_[1] - 1 });
2541 if (defined $base && $base <= $r) {
2542 $gs->fetch($base, $r);
2544 ($r0, $parent) = $gs->find_rev_before($r, 1);
2546 if (defined $r0 && defined $parent) {
2547 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
2548 my $ed;
2549 if ($self->ra->can_do_switch) {
2550 $self->assert_index_clean($parent);
2551 print STDERR "Following parent with do_switch\n";
2552 # do_switch works with svn/trunk >= r22312, but that
2553 # is not included with SVN 1.4.3 (the latest version
2554 # at the moment), so we can't rely on it
2555 $self->{last_rev} = $r0;
2556 $self->{last_commit} = $parent;
2557 $ed = SVN::Git::Fetcher->new($self, $gs->{path});
2558 $gs->ra->gs_do_switch($r0, $rev, $gs,
2559 $self->full_url, $ed)
2560 or die "SVN connection failed somewhere...\n";
2561 } elsif ($self->ra->trees_match($new_url, $r0,
2562 $self->full_url, $rev)) {
2563 print STDERR "Trees match:\n",
2564 " $new_url\@$r0\n",
2565 " ${\$self->full_url}\@$rev\n",
2566 "Following parent with no changes\n";
2567 $self->tmp_index_do(sub {
2568 command_noisy('read-tree', $parent);
2570 $self->{last_commit} = $parent;
2571 } else {
2572 print STDERR "Following parent with do_update\n";
2573 $ed = SVN::Git::Fetcher->new($self);
2574 $self->ra->gs_do_update($rev, $rev, $self, $ed)
2575 or die "SVN connection failed somewhere...\n";
2577 print STDERR "Successfully followed parent\n";
2578 return $self->make_log_entry($rev, [$parent], $ed);
2580 return undef;
2583 sub do_fetch {
2584 my ($self, $paths, $rev) = @_;
2585 my $ed;
2586 my ($last_rev, @parents);
2587 if (my $lc = $self->last_commit) {
2588 # we can have a branch that was deleted, then re-added
2589 # under the same name but copied from another path, in
2590 # which case we'll have multiple parents (we don't
2591 # want to break the original ref, nor lose copypath info):
2592 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2593 push @{$log_entry->{parents}}, $lc;
2594 return $log_entry;
2596 $ed = SVN::Git::Fetcher->new($self);
2597 $last_rev = $self->{last_rev};
2598 $ed->{c} = $lc;
2599 @parents = ($lc);
2600 } else {
2601 $last_rev = $rev;
2602 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2603 return $log_entry;
2605 $ed = SVN::Git::Fetcher->new($self);
2607 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2608 die "SVN connection failed somewhere...\n";
2610 $self->make_log_entry($rev, \@parents, $ed);
2613 sub get_untracked {
2614 my ($self, $ed) = @_;
2615 my @out;
2616 my $h = $ed->{empty};
2617 foreach (sort keys %$h) {
2618 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2619 push @out, " $act: " . uri_encode($_);
2620 warn "W: $act: $_\n";
2622 foreach my $t (qw/dir_prop file_prop/) {
2623 $h = $ed->{$t} or next;
2624 foreach my $path (sort keys %$h) {
2625 my $ppath = $path eq '' ? '.' : $path;
2626 foreach my $prop (sort keys %{$h->{$path}}) {
2627 next if $SKIP_PROP{$prop};
2628 my $v = $h->{$path}->{$prop};
2629 my $t_ppath_prop = "$t: " .
2630 uri_encode($ppath) . ' ' .
2631 uri_encode($prop);
2632 if (defined $v) {
2633 push @out, " +$t_ppath_prop " .
2634 uri_encode($v);
2635 } else {
2636 push @out, " -$t_ppath_prop";
2641 foreach my $t (qw/absent_file absent_directory/) {
2642 $h = $ed->{$t} or next;
2643 foreach my $parent (sort keys %$h) {
2644 foreach my $path (sort @{$h->{$parent}}) {
2645 push @out, " $t: " .
2646 uri_encode("$parent/$path");
2647 warn "W: $t: $parent/$path ",
2648 "Insufficient permissions?\n";
2652 \@out;
2655 # parse_svn_date(DATE)
2656 # --------------------
2657 # Given a date (in UTC) from Subversion, return a string in the format
2658 # "<TZ Offset> <local date/time>" that Git will use.
2660 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
2661 # is true we'll convert it to the local timezone instead.
2662 sub parse_svn_date {
2663 my $date = shift || return '+0000 1970-01-01 00:00:00';
2664 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2665 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
2666 croak "Unable to parse date: $date\n";
2667 my $parsed_date; # Set next.
2669 if ($Git::SVN::_localtime) {
2670 # Translate the Subversion datetime to an epoch time.
2671 # Begin by switching ourselves to $date's timezone, UTC.
2672 my $old_env_TZ = $ENV{TZ};
2673 $ENV{TZ} = 'UTC';
2675 my $epoch_in_UTC =
2676 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
2678 # Determine our local timezone (including DST) at the
2679 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
2680 # value of TZ, if any, at the time we were run.
2681 if (defined $Git::SVN::Log::TZ) {
2682 $ENV{TZ} = $Git::SVN::Log::TZ;
2683 } else {
2684 delete $ENV{TZ};
2687 my $our_TZ =
2688 POSIX::strftime('%Z', $S, $M, $H, $d, $m - 1, $Y - 1900);
2690 # This converts $epoch_in_UTC into our local timezone.
2691 my ($sec, $min, $hour, $mday, $mon, $year,
2692 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
2694 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
2695 $our_TZ, $year + 1900, $mon + 1,
2696 $mday, $hour, $min, $sec);
2698 # Reset us to the timezone in effect when we entered
2699 # this routine.
2700 if (defined $old_env_TZ) {
2701 $ENV{TZ} = $old_env_TZ;
2702 } else {
2703 delete $ENV{TZ};
2705 } else {
2706 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
2709 return $parsed_date;
2712 sub other_gs {
2713 my ($self, $new_url, $url, $repos_root,
2714 $branch_from, $r, $old_ref_id) = @_;
2715 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
2716 unless ($gs) {
2717 my $ref_id = $old_ref_id;
2718 $ref_id =~ s/\@\d+$//;
2719 $ref_id .= "\@$r";
2720 # just grow a tail if we're not unique enough :x
2721 $ref_id .= '-' while find_ref($ref_id);
2722 print STDERR "Initializing parent: $ref_id\n";
2723 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
2724 if ($u =~ s#^\Q$url\E(/|$)##) {
2725 $p = $u;
2726 $u = $url;
2727 $repo_id = $self->{repo_id};
2729 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
2734 sub call_authors_prog {
2735 my ($orig_author) = @_;
2736 my $author = `$::_authors_prog $orig_author`;
2737 if ($? != 0) {
2738 die "$::_authors_prog failed with exit code $?\n"
2740 if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
2741 my ($name, $email) = ($1, $2);
2742 $email = undef if length $2 == 0;
2743 return [$name, $email];
2744 } else {
2745 die "Author: $orig_author: $::_authors_prog returned "
2746 . "invalid author format: $author\n";
2750 sub check_author {
2751 my ($author) = @_;
2752 if (!defined $author || length $author == 0) {
2753 $author = '(no author)';
2755 if (!defined $::users{$author}) {
2756 if (defined $::_authors_prog) {
2757 $::users{$author} = call_authors_prog($author);
2758 } elsif (defined $::_authors) {
2759 die "Author: $author not defined in $::_authors file\n";
2762 $author;
2765 sub make_log_entry {
2766 my ($self, $rev, $parents, $ed) = @_;
2767 my $untracked = $self->get_untracked($ed);
2769 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
2770 print $un "r$rev\n" or croak $!;
2771 print $un $_, "\n" foreach @$untracked;
2772 my %log_entry = ( parents => $parents || [], revision => $rev,
2773 log => '');
2775 my $headrev;
2776 my $logged = delete $self->{logged_rev_props};
2777 if (!$logged || $self->{-want_revprops}) {
2778 my $rp = $self->ra->rev_proplist($rev);
2779 foreach (sort keys %$rp) {
2780 my $v = $rp->{$_};
2781 if (/^svn:(author|date|log)$/) {
2782 $log_entry{$1} = $v;
2783 } elsif ($_ eq 'svm:headrev') {
2784 $headrev = $v;
2785 } else {
2786 print $un " rev_prop: ", uri_encode($_), ' ',
2787 uri_encode($v), "\n";
2790 } else {
2791 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
2793 close $un or croak $!;
2795 $log_entry{date} = parse_svn_date($log_entry{date});
2796 $log_entry{log} .= "\n";
2797 my $author = $log_entry{author} = check_author($log_entry{author});
2798 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
2799 : ($author, undef);
2801 my ($commit_name, $commit_email) = ($name, $email);
2802 if ($_use_log_author) {
2803 my $name_field;
2804 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
2805 $name_field = $1;
2806 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
2807 $name_field = $1;
2809 if (!defined $name_field) {
2810 if (!defined $email) {
2811 $email = $name;
2813 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
2814 ($name, $email) = ($1, $2);
2815 } elsif ($name_field =~ /(.*)@/) {
2816 ($name, $email) = ($1, $name_field);
2817 } else {
2818 ($name, $email) = ($name_field, $name_field);
2821 if (defined $headrev && $self->use_svm_props) {
2822 if ($self->rewrite_root) {
2823 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2824 "options set!\n";
2826 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
2827 # we don't want "SVM: initializing mirror for junk" ...
2828 return undef if $r == 0;
2829 my $svm = $self->svm;
2830 if ($uuid ne $svm->{uuid}) {
2831 die "UUID mismatch on SVM path:\n",
2832 "expected: $svm->{uuid}\n",
2833 " got: $uuid\n";
2835 my $full_url = $self->full_url;
2836 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2837 die "Failed to replace '$svm->{replace}' with ",
2838 "'$svm->{source}' in $full_url\n";
2839 # throw away username for storing in records
2840 remove_username($full_url);
2841 $log_entry{metadata} = "$full_url\@$r $uuid";
2842 $log_entry{svm_revision} = $r;
2843 $email ||= "$author\@$uuid";
2844 $commit_email ||= "$author\@$uuid";
2845 } elsif ($self->use_svnsync_props) {
2846 my $full_url = $self->svnsync->{url};
2847 $full_url .= "/$self->{path}" if length $self->{path};
2848 remove_username($full_url);
2849 my $uuid = $self->svnsync->{uuid};
2850 $log_entry{metadata} = "$full_url\@$rev $uuid";
2851 $email ||= "$author\@$uuid";
2852 $commit_email ||= "$author\@$uuid";
2853 } else {
2854 my $url = $self->metadata_url;
2855 remove_username($url);
2856 $log_entry{metadata} = "$url\@$rev " .
2857 $self->ra->get_uuid;
2858 $email ||= "$author\@" . $self->ra->get_uuid;
2859 $commit_email ||= "$author\@" . $self->ra->get_uuid;
2861 $log_entry{name} = $name;
2862 $log_entry{email} = $email;
2863 $log_entry{commit_name} = $commit_name;
2864 $log_entry{commit_email} = $commit_email;
2865 \%log_entry;
2868 sub fetch {
2869 my ($self, $min_rev, $max_rev, @parents) = @_;
2870 my ($last_rev, $last_commit) = $self->last_rev_commit;
2871 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2872 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2875 sub set_tree_cb {
2876 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2877 $self->{inject_parents} = { $rev => $tree };
2878 $self->fetch(undef, undef);
2881 sub set_tree {
2882 my ($self, $tree) = (shift, shift);
2883 my $log_entry = ::get_commit_entry($tree);
2884 unless ($self->{last_rev}) {
2885 ::fatal("Must have an existing revision to commit");
2887 my %ed_opts = ( r => $self->{last_rev},
2888 log => $log_entry->{log},
2889 ra => $self->ra,
2890 tree_a => $self->{last_commit},
2891 tree_b => $tree,
2892 editor_cb => sub {
2893 $self->set_tree_cb($log_entry, $tree, @_) },
2894 svn_path => $self->{path} );
2895 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2896 print "No changes\nr$self->{last_rev} = $tree\n";
2900 sub rebuild_from_rev_db {
2901 my ($self, $path) = @_;
2902 my $r = -1;
2903 open my $fh, '<', $path or croak "open: $!";
2904 binmode $fh or croak "binmode: $!";
2905 while (<$fh>) {
2906 length($_) == 41 or croak "inconsistent size in ($_) != 41";
2907 chomp($_);
2908 ++$r;
2909 next if $_ eq ('0' x 40);
2910 $self->rev_map_set($r, $_);
2911 print "r$r = $_\n";
2913 close $fh or croak "close: $!";
2914 unlink $path or croak "unlink: $!";
2917 sub rebuild {
2918 my ($self) = @_;
2919 my $map_path = $self->map_path;
2920 my $partial = (-e $map_path && ! -z $map_path);
2921 return unless ::verify_ref($self->refname.'^0');
2922 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
2923 my $rev_db = $self->rev_db_path;
2924 $self->rebuild_from_rev_db($rev_db);
2925 if ($self->use_svm_props) {
2926 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
2927 $self->rebuild_from_rev_db($svm_rev_db);
2929 $self->unlink_rev_db_symlink;
2930 return;
2932 print "Rebuilding $map_path ...\n" if (!$partial);
2933 my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
2934 (undef, undef));
2935 my ($log, $ctx) =
2936 command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
2937 ($head ? "$head.." : "") . $self->refname,
2938 '--');
2939 my $metadata_url = $self->metadata_url;
2940 remove_username($metadata_url);
2941 my $svn_uuid = $self->ra_uuid;
2942 my $c;
2943 while (<$log>) {
2944 if ( m{^commit ($::sha1)$} ) {
2945 $c = $1;
2946 next;
2948 next unless s{^\s*(git-svn-id:)}{$1};
2949 my ($url, $rev, $uuid) = ::extract_metadata($_);
2950 remove_username($url);
2952 # ignore merges (from set-tree)
2953 next if (!defined $rev || !$uuid);
2955 # if we merged or otherwise started elsewhere, this is
2956 # how we break out of it
2957 if (($uuid ne $svn_uuid) ||
2958 ($metadata_url && $url && ($url ne $metadata_url))) {
2959 next;
2961 if ($partial && $head) {
2962 print "Partial-rebuilding $map_path ...\n";
2963 print "Currently at $base_rev = $head\n";
2964 $head = undef;
2967 $self->rev_map_set($rev, $c);
2968 print "r$rev = $c\n";
2970 command_close_pipe($log, $ctx);
2971 print "Done rebuilding $map_path\n" if (!$partial || !$head);
2972 my $rev_db_path = $self->rev_db_path;
2973 if (-f $self->rev_db_path) {
2974 unlink $self->rev_db_path or croak "unlink: $!";
2976 $self->unlink_rev_db_symlink;
2979 # rev_map:
2980 # Tie::File seems to be prone to offset errors if revisions get sparse,
2981 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2982 # one of my favorite modules is out :< Next up would be one of the DBM
2983 # modules, but I'm not sure which is most portable...
2985 # This is the replacement for the rev_db format, which was too big
2986 # and inefficient for large repositories with a lot of sparse history
2987 # (mainly tags)
2989 # The format is this:
2990 # - 24 bytes for every record,
2991 # * 4 bytes for the integer representing an SVN revision number
2992 # * 20 bytes representing the sha1 of a git commit
2993 # - No empty padding records like the old format
2994 # (except the last record, which can be overwritten)
2995 # - new records are written append-only since SVN revision numbers
2996 # increase monotonically
2997 # - lookups on SVN revision number are done via a binary search
2998 # - Piping the file to xxd -c24 is a good way of dumping it for
2999 # viewing or editing (piped back through xxd -r), should the need
3000 # ever arise.
3001 # - The last record can be padding revision with an all-zero sha1
3002 # This is used to optimize fetch performance when using multiple
3003 # "fetch" directives in .git/config
3005 # These files are disposable unless noMetadata or useSvmProps is set
3007 sub _rev_map_set {
3008 my ($fh, $rev, $commit) = @_;
3010 binmode $fh or croak "binmode: $!";
3011 my $size = (stat($fh))[7];
3012 ($size % 24) == 0 or croak "inconsistent size: $size";
3014 my $wr_offset = 0;
3015 if ($size > 0) {
3016 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3017 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
3018 $read == 24 or croak "read only $read bytes (!= 24)";
3019 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
3020 if ($last_commit eq ('0' x40)) {
3021 if ($size >= 48) {
3022 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3023 $read = sysread($fh, $buf, 24) or
3024 croak "read: $!";
3025 $read == 24 or
3026 croak "read only $read bytes (!= 24)";
3027 ($last_rev, $last_commit) =
3028 unpack(rev_map_fmt, $buf);
3029 if ($last_commit eq ('0' x40)) {
3030 croak "inconsistent .rev_map\n";
3033 if ($last_rev >= $rev) {
3034 croak "last_rev is higher!: $last_rev >= $rev";
3036 $wr_offset = -24;
3039 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
3040 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
3041 croak "write: $!";
3044 sub _rev_map_reset {
3045 my ($fh, $rev, $commit) = @_;
3046 my $c = _rev_map_get($fh, $rev);
3047 $c eq $commit or die "_rev_map_reset(@_) commit $c does not match!\n";
3048 my $offset = sysseek($fh, 0, SEEK_CUR) or croak "seek: $!";
3049 truncate $fh, $offset or croak "truncate: $!";
3052 sub mkfile {
3053 my ($path) = @_;
3054 unless (-e $path) {
3055 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
3056 mkpath([$dir]) unless -d $dir;
3057 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
3058 close $fh or die "Couldn't close (create) $path: $!\n";
3062 sub rev_map_set {
3063 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
3064 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
3065 my $db = $self->map_path($uuid);
3066 my $db_lock = "$db.lock";
3067 my $sig;
3068 $update_ref ||= 0;
3069 if ($update_ref) {
3070 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3071 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
3073 mkfile($db);
3075 $LOCKFILES{$db_lock} = 1;
3076 my $sync;
3077 # both of these options make our .rev_db file very, very important
3078 # and we can't afford to lose it because rebuild() won't work
3079 if ($self->use_svm_props || $self->no_metadata) {
3080 $sync = 1;
3081 copy($db, $db_lock) or die "rev_map_set(@_): ",
3082 "Failed to copy: ",
3083 "$db => $db_lock ($!)\n";
3084 } else {
3085 rename $db, $db_lock or die "rev_map_set(@_): ",
3086 "Failed to rename: ",
3087 "$db => $db_lock ($!)\n";
3090 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
3091 or croak "Couldn't open $db_lock: $!\n";
3092 $update_ref eq 'reset' ? _rev_map_reset($fh, $rev, $commit) :
3093 _rev_map_set($fh, $rev, $commit);
3094 if ($sync) {
3095 $fh->flush or die "Couldn't flush $db_lock: $!\n";
3096 $fh->sync or die "Couldn't sync $db_lock: $!\n";
3098 close $fh or croak $!;
3099 if ($update_ref) {
3100 $_head = $self;
3101 my $note = "";
3102 $note = " ($update_ref)" if ($update_ref !~ /^\d*$/);
3103 command_noisy('update-ref', '-m', "r$rev$note",
3104 $self->refname, $commit);
3106 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
3107 "$db_lock => $db ($!)\n";
3108 delete $LOCKFILES{$db_lock};
3109 if ($update_ref) {
3110 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3111 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
3112 kill $sig, $$ if defined $sig;
3116 # If want_commit, this will return an array of (rev, commit) where
3117 # commit _must_ be a valid commit in the archive.
3118 # Otherwise, it'll return the max revision (whether or not the
3119 # commit is valid or just a 0x40 placeholder).
3120 sub rev_map_max {
3121 my ($self, $want_commit) = @_;
3122 $self->rebuild;
3123 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
3124 $want_commit ? ($r, $c) : $r;
3127 sub rev_map_max_norebuild {
3128 my ($self, $want_commit) = @_;
3129 my $map_path = $self->map_path;
3130 stat $map_path or return $want_commit ? (0, undef) : 0;
3131 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3132 binmode $fh or croak "binmode: $!";
3133 my $size = (stat($fh))[7];
3134 ($size % 24) == 0 or croak "inconsistent size: $size";
3136 if ($size == 0) {
3137 close $fh or croak "close: $!";
3138 return $want_commit ? (0, undef) : 0;
3141 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3142 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3143 my ($r, $c) = unpack(rev_map_fmt, $buf);
3144 if ($want_commit && $c eq ('0' x40)) {
3145 if ($size < 48) {
3146 return $want_commit ? (0, undef) : 0;
3148 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3149 sysread($fh, $buf, 24) == 24 or croak "read: $!";
3150 ($r, $c) = unpack(rev_map_fmt, $buf);
3151 if ($c eq ('0'x40)) {
3152 croak "Penultimate record is all-zeroes in $map_path";
3155 close $fh or croak "close: $!";
3156 $want_commit ? ($r, $c) : $r;
3159 sub rev_map_get {
3160 my ($self, $rev, $uuid) = @_;
3161 my $map_path = $self->map_path($uuid);
3162 return undef unless -e $map_path;
3164 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3165 my $c = _rev_map_get($fh, $rev);
3166 close($fh) or croak "close: $!";
3170 sub _rev_map_get {
3171 my ($fh, $rev) = @_;
3173 binmode $fh or croak "binmode: $!";
3174 my $size = (stat($fh))[7];
3175 ($size % 24) == 0 or croak "inconsistent size: $size";
3177 if ($size == 0) {
3178 return undef;
3181 my ($l, $u) = (0, $size - 24);
3182 my ($r, $c, $buf);
3184 while ($l <= $u) {
3185 my $i = int(($l/24 + $u/24) / 2) * 24;
3186 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
3187 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3188 my ($r, $c) = unpack('NH40', $buf);
3190 if ($r < $rev) {
3191 $l = $i + 24;
3192 } elsif ($r > $rev) {
3193 $u = $i - 24;
3194 } else { # $r == $rev
3195 return $c eq ('0' x 40) ? undef : $c;
3198 undef;
3201 # Finds the first svn revision that exists on (if $eq_ok is true) or
3202 # before $rev for the current branch. It will not search any lower
3203 # than $min_rev. Returns the git commit hash and svn revision number
3204 # if found, else (undef, undef).
3205 sub find_rev_before {
3206 my ($self, $rev, $eq_ok, $min_rev) = @_;
3207 --$rev unless $eq_ok;
3208 $min_rev ||= 1;
3209 my $max_rev = $self->rev_map_max;
3210 $rev = $max_rev if ($rev > $max_rev);
3211 while ($rev >= $min_rev) {
3212 if (my $c = $self->rev_map_get($rev)) {
3213 return ($rev, $c);
3215 --$rev;
3217 return (undef, undef);
3220 # Finds the first svn revision that exists on (if $eq_ok is true) or
3221 # after $rev for the current branch. It will not search any higher
3222 # than $max_rev. Returns the git commit hash and svn revision number
3223 # if found, else (undef, undef).
3224 sub find_rev_after {
3225 my ($self, $rev, $eq_ok, $max_rev) = @_;
3226 ++$rev unless $eq_ok;
3227 $max_rev ||= $self->rev_map_max;
3228 while ($rev <= $max_rev) {
3229 if (my $c = $self->rev_map_get($rev)) {
3230 return ($rev, $c);
3232 ++$rev;
3234 return (undef, undef);
3237 sub _new {
3238 my ($class, $repo_id, $ref_id, $path) = @_;
3239 unless (defined $repo_id && length $repo_id) {
3240 $repo_id = $Git::SVN::default_repo_id;
3242 unless (defined $ref_id && length $ref_id) {
3243 $_[2] = $ref_id = $Git::SVN::default_ref_id;
3245 $_[1] = $repo_id;
3246 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
3247 $_[3] = $path = '' unless (defined $path);
3248 mkpath(["$ENV{GIT_DIR}/svn"]);
3249 bless {
3250 ref_id => $ref_id, dir => $dir, index => "$dir/index",
3251 path => $path, config => "$ENV{GIT_DIR}/svn/config",
3252 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
3255 # for read-only access of old .rev_db formats
3256 sub unlink_rev_db_symlink {
3257 my ($self) = @_;
3258 my $link = $self->rev_db_path;
3259 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
3260 if (-l $link) {
3261 unlink $link or croak "unlink: $link failed!";
3265 sub rev_db_path {
3266 my ($self, $uuid) = @_;
3267 my $db_path = $self->map_path($uuid);
3268 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
3269 or croak "map_path: $db_path does not contain '/.rev_map.' !";
3270 $db_path;
3273 # the new replacement for .rev_db
3274 sub map_path {
3275 my ($self, $uuid) = @_;
3276 $uuid ||= $self->ra_uuid;
3277 "$self->{map_root}.$uuid";
3280 sub uri_encode {
3281 my ($f) = @_;
3282 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
3286 sub remove_username {
3287 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
3290 package Git::SVN::Prompt;
3291 use strict;
3292 use warnings;
3293 require SVN::Core;
3294 use vars qw/$_no_auth_cache $_username/;
3296 sub simple {
3297 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
3298 $may_save = undef if $_no_auth_cache;
3299 $default_username = $_username if defined $_username;
3300 if (defined $default_username && length $default_username) {
3301 if (defined $realm && length $realm) {
3302 print STDERR "Authentication realm: $realm\n";
3303 STDERR->flush;
3305 $cred->username($default_username);
3306 } else {
3307 username($cred, $realm, $may_save, $pool);
3309 $cred->password(_read_password("Password for '" .
3310 $cred->username . "': ", $realm));
3311 $cred->may_save($may_save);
3312 $SVN::_Core::SVN_NO_ERROR;
3315 sub ssl_server_trust {
3316 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
3317 $may_save = undef if $_no_auth_cache;
3318 print STDERR "Error validating server certificate for '$realm':\n";
3320 no warnings 'once';
3321 # All variables SVN::Auth::SSL::* are used only once,
3322 # so we're shutting up Perl warnings about this.
3323 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
3324 print STDERR " - The certificate is not issued ",
3325 "by a trusted authority. Use the\n",
3326 " fingerprint to validate ",
3327 "the certificate manually!\n";
3329 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
3330 print STDERR " - The certificate hostname ",
3331 "does not match.\n";
3333 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
3334 print STDERR " - The certificate is not yet valid.\n";
3336 if ($failures & $SVN::Auth::SSL::EXPIRED) {
3337 print STDERR " - The certificate has expired.\n";
3339 if ($failures & $SVN::Auth::SSL::OTHER) {
3340 print STDERR " - The certificate has ",
3341 "an unknown error.\n";
3343 } # no warnings 'once'
3344 printf STDERR
3345 "Certificate information:\n".
3346 " - Hostname: %s\n".
3347 " - Valid: from %s until %s\n".
3348 " - Issuer: %s\n".
3349 " - Fingerprint: %s\n",
3350 map $cert_info->$_, qw(hostname valid_from valid_until
3351 issuer_dname fingerprint);
3352 my $choice;
3353 prompt:
3354 print STDERR $may_save ?
3355 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
3356 "(R)eject or accept (t)emporarily? ";
3357 STDERR->flush;
3358 $choice = lc(substr(<STDIN> || 'R', 0, 1));
3359 if ($choice =~ /^t$/i) {
3360 $cred->may_save(undef);
3361 } elsif ($choice =~ /^r$/i) {
3362 return -1;
3363 } elsif ($may_save && $choice =~ /^p$/i) {
3364 $cred->may_save($may_save);
3365 } else {
3366 goto prompt;
3368 $cred->accepted_failures($failures);
3369 $SVN::_Core::SVN_NO_ERROR;
3372 sub ssl_client_cert {
3373 my ($cred, $realm, $may_save, $pool) = @_;
3374 $may_save = undef if $_no_auth_cache;
3375 print STDERR "Client certificate filename: ";
3376 STDERR->flush;
3377 chomp(my $filename = <STDIN>);
3378 $cred->cert_file($filename);
3379 $cred->may_save($may_save);
3380 $SVN::_Core::SVN_NO_ERROR;
3383 sub ssl_client_cert_pw {
3384 my ($cred, $realm, $may_save, $pool) = @_;
3385 $may_save = undef if $_no_auth_cache;
3386 $cred->password(_read_password("Password: ", $realm));
3387 $cred->may_save($may_save);
3388 $SVN::_Core::SVN_NO_ERROR;
3391 sub username {
3392 my ($cred, $realm, $may_save, $pool) = @_;
3393 $may_save = undef if $_no_auth_cache;
3394 if (defined $realm && length $realm) {
3395 print STDERR "Authentication realm: $realm\n";
3397 my $username;
3398 if (defined $_username) {
3399 $username = $_username;
3400 } else {
3401 print STDERR "Username: ";
3402 STDERR->flush;
3403 chomp($username = <STDIN>);
3405 $cred->username($username);
3406 $cred->may_save($may_save);
3407 $SVN::_Core::SVN_NO_ERROR;
3410 sub _read_password {
3411 my ($prompt, $realm) = @_;
3412 print STDERR $prompt;
3413 STDERR->flush;
3414 require Term::ReadKey;
3415 Term::ReadKey::ReadMode('noecho');
3416 my $password = '';
3417 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
3418 last if $key =~ /[\012\015]/; # \n\r
3419 $password .= $key;
3421 Term::ReadKey::ReadMode('restore');
3422 print STDERR "\n";
3423 STDERR->flush;
3424 $password;
3427 package SVN::Git::Fetcher;
3428 use vars qw/@ISA/;
3429 use strict;
3430 use warnings;
3431 use Carp qw/croak/;
3432 use File::Temp qw/tempfile/;
3433 use IO::File qw//;
3434 use vars qw/$_ignore_regex/;
3436 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
3437 sub new {
3438 my ($class, $git_svn, $switch_path) = @_;
3439 my $self = SVN::Delta::Editor->new;
3440 bless $self, $class;
3441 if (exists $git_svn->{last_commit}) {
3442 $self->{c} = $git_svn->{last_commit};
3443 $self->{empty_symlinks} =
3444 _mark_empty_symlinks($git_svn, $switch_path);
3446 $self->{ignore_regex} = eval { command_oneline('config', '--get',
3447 "svn-remote.$git_svn->{repo_id}.ignore-paths") };
3448 $self->{empty} = {};
3449 $self->{dir_prop} = {};
3450 $self->{file_prop} = {};
3451 $self->{absent_dir} = {};
3452 $self->{absent_file} = {};
3453 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
3454 $self;
3457 # this uses the Ra object, so it must be called before do_{switch,update},
3458 # not inside them (when the Git::SVN::Fetcher object is passed) to
3459 # do_{switch,update}
3460 sub _mark_empty_symlinks {
3461 my ($git_svn, $switch_path) = @_;
3462 my $bool = Git::config_bool('svn.brokenSymlinkWorkaround');
3463 return {} if (!defined($bool)) || (defined($bool) && ! $bool);
3465 my %ret;
3466 my ($rev, $cmt) = $git_svn->last_rev_commit;
3467 return {} unless ($rev && $cmt);
3469 # allow the warning to be printed for each revision we fetch to
3470 # ensure the user sees it. The user can also disable the workaround
3471 # on the repository even while git svn is running and the next
3472 # revision fetched will skip this expensive function.
3473 my $printed_warning;
3474 chomp(my $empty_blob = `git hash-object -t blob --stdin < /dev/null`);
3475 my ($ls, $ctx) = command_output_pipe(qw/ls-tree -r -z/, $cmt);
3476 local $/ = "\0";
3477 my $pfx = defined($switch_path) ? $switch_path : $git_svn->{path};
3478 $pfx .= '/' if length($pfx);
3479 while (<$ls>) {
3480 chomp;
3481 s/\A100644 blob $empty_blob\t//o or next;
3482 unless ($printed_warning) {
3483 print STDERR "Scanning for empty symlinks, ",
3484 "this may take a while if you have ",
3485 "many empty files\n",
3486 "You may disable this with `",
3487 "git config svn.brokenSymlinkWorkaround ",
3488 "false'.\n",
3489 "This may be done in a different ",
3490 "terminal without restarting ",
3491 "git svn\n";
3492 $printed_warning = 1;
3494 my $path = $_;
3495 my (undef, $props) =
3496 $git_svn->ra->get_file($pfx.$path, $rev, undef);
3497 if ($props->{'svn:special'}) {
3498 $ret{$path} = 1;
3501 command_close_pipe($ls, $ctx);
3502 \%ret;
3505 # returns true if a given path is inside a ".git" directory
3506 sub in_dot_git {
3507 $_[0] =~ m{(?:^|/)\.git(?:/|$)};
3510 # return value: 0 -- don't ignore, 1 -- ignore
3511 sub is_path_ignored {
3512 my ($self, $path) = @_;
3513 return 1 if in_dot_git($path);
3514 return 1 if defined($self->{ignore_regex}) &&
3515 $path =~ m!$self->{ignore_regex}!;
3516 return 0 unless defined($_ignore_regex);
3517 return 1 if $path =~ m!$_ignore_regex!o;
3518 return 0;
3521 sub set_path_strip {
3522 my ($self, $path) = @_;
3523 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
3526 sub open_root {
3527 { path => '' };
3530 sub open_directory {
3531 my ($self, $path, $pb, $rev) = @_;
3532 { path => $path };
3535 sub git_path {
3536 my ($self, $path) = @_;
3537 if ($self->{path_strip}) {
3538 $path =~ s!$self->{path_strip}!! or
3539 die "Failed to strip path '$path' ($self->{path_strip})\n";
3541 $path;
3544 sub delete_entry {
3545 my ($self, $path, $rev, $pb) = @_;
3546 return undef if $self->is_path_ignored($path);
3548 my $gpath = $self->git_path($path);
3549 return undef if ($gpath eq '');
3551 # remove entire directories.
3552 my ($tree) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
3553 =~ /\A040000 tree ([a-f\d]{40})\t\Q$gpath\E\0/);
3554 if ($tree) {
3555 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3556 -r --name-only -z/,
3557 $tree);
3558 local $/ = "\0";
3559 while (<$ls>) {
3560 chomp;
3561 my $rmpath = "$gpath/$_";
3562 $self->{gii}->remove($rmpath);
3563 print "\tD\t$rmpath\n" unless $::_q;
3565 print "\tD\t$gpath/\n" unless $::_q;
3566 command_close_pipe($ls, $ctx);
3567 $self->{empty}->{$path} = 0
3568 } else {
3569 $self->{gii}->remove($gpath);
3570 print "\tD\t$gpath\n" unless $::_q;
3572 undef;
3575 sub open_file {
3576 my ($self, $path, $pb, $rev) = @_;
3577 my ($mode, $blob);
3579 goto out if $self->is_path_ignored($path);
3581 my $gpath = $self->git_path($path);
3582 ($mode, $blob) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
3583 =~ /\A(\d{6}) blob ([a-f\d]{40})\t\Q$gpath\E\0/);
3584 unless (defined $mode && defined $blob) {
3585 die "$path was not found in commit $self->{c} (r$rev)\n";
3587 if ($mode eq '100644' && $self->{empty_symlinks}->{$path}) {
3588 $mode = '120000';
3590 out:
3591 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
3592 pool => SVN::Pool->new, action => 'M' };
3595 sub add_file {
3596 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
3597 my $mode;
3599 if (!$self->is_path_ignored($path)) {
3600 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3601 delete $self->{empty}->{$dir};
3602 $mode = '100644';
3604 { path => $path, mode_a => $mode, mode_b => $mode,
3605 pool => SVN::Pool->new, action => 'A' };
3608 sub add_directory {
3609 my ($self, $path, $cp_path, $cp_rev) = @_;
3610 goto out if $self->is_path_ignored($path);
3611 my $gpath = $self->git_path($path);
3612 if ($gpath eq '') {
3613 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3614 -r --name-only -z/,
3615 $self->{c});
3616 local $/ = "\0";
3617 while (<$ls>) {
3618 chomp;
3619 $self->{gii}->remove($_);
3620 print "\tD\t$_\n" unless $::_q;
3622 command_close_pipe($ls, $ctx);
3623 $self->{empty}->{$path} = 0;
3625 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3626 delete $self->{empty}->{$dir};
3627 $self->{empty}->{$path} = 1;
3628 out:
3629 { path => $path };
3632 sub change_dir_prop {
3633 my ($self, $db, $prop, $value) = @_;
3634 return undef if $self->is_path_ignored($db->{path});
3635 $self->{dir_prop}->{$db->{path}} ||= {};
3636 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
3637 undef;
3640 sub absent_directory {
3641 my ($self, $path, $pb) = @_;
3642 return undef if $self->is_path_ignored($path);
3643 $self->{absent_dir}->{$pb->{path}} ||= [];
3644 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
3645 undef;
3648 sub absent_file {
3649 my ($self, $path, $pb) = @_;
3650 return undef if $self->is_path_ignored($path);
3651 $self->{absent_file}->{$pb->{path}} ||= [];
3652 push @{$self->{absent_file}->{$pb->{path}}}, $path;
3653 undef;
3656 sub change_file_prop {
3657 my ($self, $fb, $prop, $value) = @_;
3658 return undef if $self->is_path_ignored($fb->{path});
3659 if ($prop eq 'svn:executable') {
3660 if ($fb->{mode_b} != 120000) {
3661 $fb->{mode_b} = defined $value ? 100755 : 100644;
3663 } elsif ($prop eq 'svn:special') {
3664 $fb->{mode_b} = defined $value ? 120000 : 100644;
3665 } else {
3666 $self->{file_prop}->{$fb->{path}} ||= {};
3667 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
3669 undef;
3672 sub apply_textdelta {
3673 my ($self, $fb, $exp) = @_;
3674 return undef if $self->is_path_ignored($fb->{path});
3675 my $fh = $::_repository->temp_acquire('svn_delta');
3676 # $fh gets auto-closed() by SVN::TxDelta::apply(),
3677 # (but $base does not,) so dup() it for reading in close_file
3678 open my $dup, '<&', $fh or croak $!;
3679 my $base = $::_repository->temp_acquire('git_blob');
3681 if ($fb->{blob}) {
3682 my ($base_is_link, $size);
3684 if ($fb->{mode_a} eq '120000' &&
3685 ! $self->{empty_symlinks}->{$fb->{path}}) {
3686 print $base 'link ' or die "print $!\n";
3687 $base_is_link = 1;
3689 retry:
3690 $size = $::_repository->cat_blob($fb->{blob}, $base);
3691 die "Failed to read object $fb->{blob}" if ($size < 0);
3693 if (defined $exp) {
3694 seek $base, 0, 0 or croak $!;
3695 my $got = ::md5sum($base);
3696 if ($got ne $exp) {
3697 my $err = "Checksum mismatch: ".
3698 "$fb->{path} $fb->{blob}\n" .
3699 "expected: $exp\n" .
3700 " got: $got\n";
3701 if ($base_is_link) {
3702 warn $err,
3703 "Retrying... (possibly ",
3704 "a bad symlink from SVN)\n";
3705 $::_repository->temp_reset($base);
3706 $base_is_link = 0;
3707 goto retry;
3709 die $err;
3713 seek $base, 0, 0 or croak $!;
3714 $fb->{fh} = $fh;
3715 $fb->{base} = $base;
3716 [ SVN::TxDelta::apply($base, $dup, undef, $fb->{path}, $fb->{pool}) ];
3719 sub close_file {
3720 my ($self, $fb, $exp) = @_;
3721 return undef if $self->is_path_ignored($fb->{path});
3723 my $hash;
3724 my $path = $self->git_path($fb->{path});
3725 if (my $fh = $fb->{fh}) {
3726 if (defined $exp) {
3727 seek($fh, 0, 0) or croak $!;
3728 my $got = ::md5sum($fh);
3729 if ($got ne $exp) {
3730 die "Checksum mismatch: $path\n",
3731 "expected: $exp\n got: $got\n";
3734 if ($fb->{mode_b} == 120000) {
3735 sysseek($fh, 0, 0) or croak $!;
3736 my $rd = sysread($fh, my $buf, 5);
3738 if (!defined $rd) {
3739 croak "sysread: $!\n";
3740 } elsif ($rd == 0) {
3741 warn "$path has mode 120000",
3742 " but it points to nothing\n",
3743 "converting to an empty file with mode",
3744 " 100644\n";
3745 $fb->{mode_b} = '100644';
3746 } elsif ($buf ne 'link ') {
3747 warn "$path has mode 120000",
3748 " but is not a link\n";
3749 } else {
3750 my $tmp_fh = $::_repository->temp_acquire(
3751 'svn_hash');
3752 my $res;
3753 while ($res = sysread($fh, my $str, 1024)) {
3754 my $out = syswrite($tmp_fh, $str, $res);
3755 defined($out) && $out == $res
3756 or croak("write ",
3757 Git::temp_path($tmp_fh),
3758 ": $!\n");
3760 defined $res or croak $!;
3762 ($fh, $tmp_fh) = ($tmp_fh, $fh);
3763 Git::temp_release($tmp_fh, 1);
3767 $hash = $::_repository->hash_and_insert_object(
3768 Git::temp_path($fh));
3769 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
3771 Git::temp_release($fb->{base}, 1);
3772 Git::temp_release($fh, 1);
3773 } else {
3774 $hash = $fb->{blob} or die "no blob information\n";
3776 $fb->{pool}->clear;
3777 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
3778 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
3779 undef;
3782 sub abort_edit {
3783 my $self = shift;
3784 $self->{nr} = $self->{gii}->{nr};
3785 delete $self->{gii};
3786 $self->SUPER::abort_edit(@_);
3789 sub close_edit {
3790 my $self = shift;
3791 $self->{git_commit_ok} = 1;
3792 $self->{nr} = $self->{gii}->{nr};
3793 delete $self->{gii};
3794 $self->SUPER::close_edit(@_);
3797 package SVN::Git::Editor;
3798 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
3799 use strict;
3800 use warnings;
3801 use Carp qw/croak/;
3802 use IO::File;
3804 sub new {
3805 my ($class, $opts) = @_;
3806 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
3807 die "$_ required!\n" unless (defined $opts->{$_});
3810 my $pool = SVN::Pool->new;
3811 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
3812 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
3813 $opts->{r}, $mods);
3815 # $opts->{ra} functions should not be used after this:
3816 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
3817 $opts->{editor_cb}, $pool);
3818 my $self = SVN::Delta::Editor->new(@ce, $pool);
3819 bless $self, $class;
3820 foreach (qw/svn_path r tree_a tree_b/) {
3821 $self->{$_} = $opts->{$_};
3823 $self->{url} = $opts->{ra}->{url};
3824 $self->{mods} = $mods;
3825 $self->{types} = $types;
3826 $self->{pool} = $pool;
3827 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
3828 $self->{rm} = { };
3829 $self->{path_prefix} = length $self->{svn_path} ?
3830 "$self->{svn_path}/" : '';
3831 $self->{config} = $opts->{config};
3832 return $self;
3835 sub generate_diff {
3836 my ($tree_a, $tree_b) = @_;
3837 my @diff_tree = qw(diff-tree -z -r);
3838 if ($_cp_similarity) {
3839 push @diff_tree, "-C$_cp_similarity";
3840 } else {
3841 push @diff_tree, '-C';
3843 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
3844 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
3845 push @diff_tree, $tree_a, $tree_b;
3846 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
3847 local $/ = "\0";
3848 my $state = 'meta';
3849 my @mods;
3850 while (<$diff_fh>) {
3851 chomp $_; # this gets rid of the trailing "\0"
3852 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
3853 ($::sha1)\s($::sha1)\s
3854 ([MTCRAD])\d*$/xo) {
3855 push @mods, { mode_a => $1, mode_b => $2,
3856 sha1_a => $3, sha1_b => $4,
3857 chg => $5 };
3858 if ($5 =~ /^(?:C|R)$/) {
3859 $state = 'file_a';
3860 } else {
3861 $state = 'file_b';
3863 } elsif ($state eq 'file_a') {
3864 my $x = $mods[$#mods] or croak "Empty array\n";
3865 if ($x->{chg} !~ /^(?:C|R)$/) {
3866 croak "Error parsing $_, $x->{chg}\n";
3868 $x->{file_a} = $_;
3869 $state = 'file_b';
3870 } elsif ($state eq 'file_b') {
3871 my $x = $mods[$#mods] or croak "Empty array\n";
3872 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
3873 croak "Error parsing $_, $x->{chg}\n";
3875 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
3876 croak "Error parsing $_, $x->{chg}\n";
3878 $x->{file_b} = $_;
3879 $state = 'meta';
3880 } else {
3881 croak "Error parsing $_\n";
3884 command_close_pipe($diff_fh, $ctx);
3885 \@mods;
3888 sub check_diff_paths {
3889 my ($ra, $pfx, $rev, $mods) = @_;
3890 my %types;
3891 $pfx .= '/' if length $pfx;
3893 sub type_diff_paths {
3894 my ($ra, $types, $path, $rev) = @_;
3895 my @p = split m#/+#, $path;
3896 my $c = shift @p;
3897 unless (defined $types->{$c}) {
3898 $types->{$c} = $ra->check_path($c, $rev);
3900 while (@p) {
3901 $c .= '/' . shift @p;
3902 next if defined $types->{$c};
3903 $types->{$c} = $ra->check_path($c, $rev);
3907 foreach my $m (@$mods) {
3908 foreach my $f (qw/file_a file_b/) {
3909 next unless defined $m->{$f};
3910 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
3911 if (length $pfx.$dir && ! defined $types{$dir}) {
3912 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
3916 \%types;
3919 sub split_path {
3920 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
3923 sub repo_path {
3924 my ($self, $path) = @_;
3925 $self->{path_prefix}.(defined $path ? $path : '');
3928 sub url_path {
3929 my ($self, $path) = @_;
3930 if ($self->{url} =~ m#^https?://#) {
3931 $path =~ s/([^~a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
3933 $self->{url} . '/' . $self->repo_path($path);
3936 sub rmdirs {
3937 my ($self) = @_;
3938 my $rm = $self->{rm};
3939 delete $rm->{''}; # we never delete the url we're tracking
3940 return unless %$rm;
3942 foreach (keys %$rm) {
3943 my @d = split m#/#, $_;
3944 my $c = shift @d;
3945 $rm->{$c} = 1;
3946 while (@d) {
3947 $c .= '/' . shift @d;
3948 $rm->{$c} = 1;
3951 delete $rm->{$self->{svn_path}};
3952 delete $rm->{''}; # we never delete the url we're tracking
3953 return unless %$rm;
3955 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
3956 $self->{tree_b});
3957 local $/ = "\0";
3958 while (<$fh>) {
3959 chomp;
3960 my @dn = split m#/#, $_;
3961 while (pop @dn) {
3962 delete $rm->{join '/', @dn};
3964 unless (%$rm) {
3965 close $fh;
3966 return;
3969 command_close_pipe($fh, $ctx);
3971 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
3972 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
3973 $self->close_directory($bat->{$d}, $p);
3974 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
3975 print "\tD+\t$d/\n" unless $::_q;
3976 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
3977 delete $bat->{$d};
3981 sub open_or_add_dir {
3982 my ($self, $full_path, $baton) = @_;
3983 my $t = $self->{types}->{$full_path};
3984 if (!defined $t) {
3985 die "$full_path not known in r$self->{r} or we have a bug!\n";
3988 no warnings 'once';
3989 # SVN::Node::none and SVN::Node::file are used only once,
3990 # so we're shutting up Perl's warnings about them.
3991 if ($t == $SVN::Node::none) {
3992 return $self->add_directory($full_path, $baton,
3993 undef, -1, $self->{pool});
3994 } elsif ($t == $SVN::Node::dir) {
3995 return $self->open_directory($full_path, $baton,
3996 $self->{r}, $self->{pool});
3997 } # no warnings 'once'
3998 print STDERR "$full_path already exists in repository at ",
3999 "r$self->{r} and it is not a directory (",
4000 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
4001 } # no warnings 'once'
4002 exit 1;
4005 sub ensure_path {
4006 my ($self, $path) = @_;
4007 my $bat = $self->{bat};
4008 my $repo_path = $self->repo_path($path);
4009 return $bat->{''} unless (length $repo_path);
4010 my @p = split m#/+#, $repo_path;
4011 my $c = shift @p;
4012 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
4013 while (@p) {
4014 my $c0 = $c;
4015 $c .= '/' . shift @p;
4016 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
4018 return $bat->{$c};
4021 # Subroutine to convert a globbing pattern to a regular expression.
4022 # From perl cookbook.
4023 sub glob2pat {
4024 my $globstr = shift;
4025 my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
4026 $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
4027 return '^' . $globstr . '$';
4030 sub check_autoprop {
4031 my ($self, $pattern, $properties, $file, $fbat) = @_;
4032 # Convert the globbing pattern to a regular expression.
4033 my $regex = glob2pat($pattern);
4034 # Check if the pattern matches the file name.
4035 if($file =~ m/($regex)/) {
4036 # Parse the list of properties to set.
4037 my @props = split(/;/, $properties);
4038 foreach my $prop (@props) {
4039 # Parse 'name=value' syntax and set the property.
4040 if ($prop =~ /([^=]+)=(.*)/) {
4041 my ($n,$v) = ($1,$2);
4042 for ($n, $v) {
4043 s/^\s+//; s/\s+$//;
4045 $self->change_file_prop($fbat, $n, $v);
4051 sub apply_autoprops {
4052 my ($self, $file, $fbat) = @_;
4053 my $conf_t = ${$self->{config}}{'config'};
4054 no warnings 'once';
4055 # Check [miscellany]/enable-auto-props in svn configuration.
4056 if (SVN::_Core::svn_config_get_bool(
4057 $conf_t,
4058 $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
4059 $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
4060 0)) {
4061 # Auto-props are enabled. Enumerate them to look for matches.
4062 my $callback = sub {
4063 $self->check_autoprop($_[0], $_[1], $file, $fbat);
4065 SVN::_Core::svn_config_enumerate(
4066 $conf_t,
4067 $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
4068 $callback);
4072 sub A {
4073 my ($self, $m) = @_;
4074 my ($dir, $file) = split_path($m->{file_b});
4075 my $pbat = $self->ensure_path($dir);
4076 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4077 undef, -1);
4078 print "\tA\t$m->{file_b}\n" unless $::_q;
4079 $self->apply_autoprops($file, $fbat);
4080 $self->chg_file($fbat, $m);
4081 $self->close_file($fbat,undef,$self->{pool});
4084 sub C {
4085 my ($self, $m) = @_;
4086 my ($dir, $file) = split_path($m->{file_b});
4087 my $pbat = $self->ensure_path($dir);
4088 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4089 $self->url_path($m->{file_a}), $self->{r});
4090 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
4091 $self->chg_file($fbat, $m);
4092 $self->close_file($fbat,undef,$self->{pool});
4095 sub delete_entry {
4096 my ($self, $path, $pbat) = @_;
4097 my $rpath = $self->repo_path($path);
4098 my ($dir, $file) = split_path($rpath);
4099 $self->{rm}->{$dir} = 1;
4100 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
4103 sub R {
4104 my ($self, $m) = @_;
4105 my ($dir, $file) = split_path($m->{file_b});
4106 my $pbat = $self->ensure_path($dir);
4107 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4108 $self->url_path($m->{file_a}), $self->{r});
4109 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
4110 $self->apply_autoprops($file, $fbat);
4111 $self->chg_file($fbat, $m);
4112 $self->close_file($fbat,undef,$self->{pool});
4114 ($dir, $file) = split_path($m->{file_a});
4115 $pbat = $self->ensure_path($dir);
4116 $self->delete_entry($m->{file_a}, $pbat);
4119 sub M {
4120 my ($self, $m) = @_;
4121 my ($dir, $file) = split_path($m->{file_b});
4122 my $pbat = $self->ensure_path($dir);
4123 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
4124 $pbat,$self->{r},$self->{pool});
4125 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
4126 $self->chg_file($fbat, $m);
4127 $self->close_file($fbat,undef,$self->{pool});
4130 sub T { shift->M(@_) }
4132 sub change_file_prop {
4133 my ($self, $fbat, $pname, $pval) = @_;
4134 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
4137 sub _chg_file_get_blob ($$$$) {
4138 my ($self, $fbat, $m, $which) = @_;
4139 my $fh = $::_repository->temp_acquire("git_blob_$which");
4140 if ($m->{"mode_$which"} =~ /^120/) {
4141 print $fh 'link ' or croak $!;
4142 $self->change_file_prop($fbat,'svn:special','*');
4143 } elsif ($m->{mode_a} =~ /^120/ && $m->{"mode_$which"} !~ /^120/) {
4144 $self->change_file_prop($fbat,'svn:special',undef);
4146 my $blob = $m->{"sha1_$which"};
4147 return ($fh,) if ($blob =~ /^0{40}$/);
4148 my $size = $::_repository->cat_blob($blob, $fh);
4149 croak "Failed to read object $blob" if ($size < 0);
4150 $fh->flush == 0 or croak $!;
4151 seek $fh, 0, 0 or croak $!;
4153 my $exp = ::md5sum($fh);
4154 seek $fh, 0, 0 or croak $!;
4155 return ($fh, $exp);
4158 sub chg_file {
4159 my ($self, $fbat, $m) = @_;
4160 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
4161 $self->change_file_prop($fbat,'svn:executable','*');
4162 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
4163 $self->change_file_prop($fbat,'svn:executable',undef);
4165 my ($fh_a, $exp_a) = _chg_file_get_blob $self, $fbat, $m, 'a';
4166 my ($fh_b, $exp_b) = _chg_file_get_blob $self, $fbat, $m, 'b';
4167 my $pool = SVN::Pool->new;
4168 my $atd = $self->apply_textdelta($fbat, $exp_a, $pool);
4169 if (-s $fh_a) {
4170 my $txstream = SVN::TxDelta::new ($fh_a, $fh_b, $pool);
4171 my $res = SVN::TxDelta::send_txstream($txstream, @$atd, $pool);
4172 if (defined $res) {
4173 die "Unexpected result from send_txstream: $res\n",
4174 "(SVN::Core::VERSION: $SVN::Core::VERSION)\n";
4176 } else {
4177 my $got = SVN::TxDelta::send_stream($fh_b, @$atd, $pool);
4178 die "Checksum mismatch\nexpected: $exp_b\ngot: $got\n"
4179 if ($got ne $exp_b);
4181 Git::temp_release($fh_b, 1);
4182 Git::temp_release($fh_a, 1);
4183 $pool->clear;
4186 sub D {
4187 my ($self, $m) = @_;
4188 my ($dir, $file) = split_path($m->{file_b});
4189 my $pbat = $self->ensure_path($dir);
4190 print "\tD\t$m->{file_b}\n" unless $::_q;
4191 $self->delete_entry($m->{file_b}, $pbat);
4194 sub close_edit {
4195 my ($self) = @_;
4196 my ($p,$bat) = ($self->{pool}, $self->{bat});
4197 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
4198 next if $_ eq '';
4199 $self->close_directory($bat->{$_}, $p);
4201 $self->close_directory($bat->{''}, $p);
4202 $self->SUPER::close_edit($p);
4203 $p->clear;
4206 sub abort_edit {
4207 my ($self) = @_;
4208 $self->SUPER::abort_edit($self->{pool});
4211 sub DESTROY {
4212 my $self = shift;
4213 $self->SUPER::DESTROY(@_);
4214 $self->{pool}->clear;
4217 # this drives the editor
4218 sub apply_diff {
4219 my ($self) = @_;
4220 my $mods = $self->{mods};
4221 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
4222 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
4223 my $f = $m->{chg};
4224 if (defined $o{$f}) {
4225 $self->$f($m);
4226 } else {
4227 fatal("Invalid change type: $f");
4230 $self->rmdirs if $_rmdir;
4231 if (@$mods == 0) {
4232 $self->abort_edit;
4233 } else {
4234 $self->close_edit;
4236 return scalar @$mods;
4239 package Git::SVN::Ra;
4240 use vars qw/@ISA $config_dir $_log_window_size/;
4241 use strict;
4242 use warnings;
4243 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
4245 BEGIN {
4246 # enforce temporary pool usage for some simple functions
4247 no strict 'refs';
4248 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root
4249 get_file/) {
4250 my $SUPER = "SUPER::$f";
4251 *$f = sub {
4252 my $self = shift;
4253 my $pool = SVN::Pool->new;
4254 my @ret = $self->$SUPER(@_,$pool);
4255 $pool->clear;
4256 wantarray ? @ret : $ret[0];
4261 sub _auth_providers () {
4263 SVN::Client::get_simple_provider(),
4264 SVN::Client::get_ssl_server_trust_file_provider(),
4265 SVN::Client::get_simple_prompt_provider(
4266 \&Git::SVN::Prompt::simple, 2),
4267 SVN::Client::get_ssl_client_cert_file_provider(),
4268 SVN::Client::get_ssl_client_cert_prompt_provider(
4269 \&Git::SVN::Prompt::ssl_client_cert, 2),
4270 SVN::Client::get_ssl_client_cert_pw_file_provider(),
4271 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
4272 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
4273 SVN::Client::get_username_provider(),
4274 SVN::Client::get_ssl_server_trust_prompt_provider(
4275 \&Git::SVN::Prompt::ssl_server_trust),
4276 SVN::Client::get_username_prompt_provider(
4277 \&Git::SVN::Prompt::username, 2)
4281 sub escape_uri_only {
4282 my ($uri) = @_;
4283 my @tmp;
4284 foreach (split m{/}, $uri) {
4285 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
4286 push @tmp, $_;
4288 join('/', @tmp);
4291 sub escape_url {
4292 my ($url) = @_;
4293 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
4294 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
4295 $url = "$scheme://$domain$uri";
4297 $url;
4300 sub new {
4301 my ($class, $url) = @_;
4302 $url =~ s!/+$!!;
4303 return $RA if ($RA && $RA->{url} eq $url);
4305 SVN::_Core::svn_config_ensure($config_dir, undef);
4306 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
4307 my $config = SVN::Core::config_get_config($config_dir);
4308 $RA = undef;
4309 my $dont_store_passwords = 1;
4310 my $conf_t = ${$config}{'config'};
4312 no warnings 'once';
4313 # The usage of $SVN::_Core::SVN_CONFIG_* variables
4314 # produces warnings that variables are used only once.
4315 # I had not found the better way to shut them up, so
4316 # the warnings of type 'once' are disabled in this block.
4317 if (SVN::_Core::svn_config_get_bool($conf_t,
4318 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4319 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
4320 1) == 0) {
4321 SVN::_Core::svn_auth_set_parameter($baton,
4322 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
4323 bless (\$dont_store_passwords, "_p_void"));
4325 if (SVN::_Core::svn_config_get_bool($conf_t,
4326 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4327 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
4328 1) == 0) {
4329 $Git::SVN::Prompt::_no_auth_cache = 1;
4331 } # no warnings 'once'
4332 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
4333 config => $config,
4334 pool => SVN::Pool->new,
4335 auth_provider_callbacks => $callbacks);
4336 $self->{url} = $url;
4337 $self->{svn_path} = $url;
4338 $self->{repos_root} = $self->get_repos_root;
4339 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
4340 $self->{cache} = { check_path => { r => 0, data => {} },
4341 get_dir => { r => 0, data => {} } };
4342 $RA = bless $self, $class;
4345 sub check_path {
4346 my ($self, $path, $r) = @_;
4347 my $cache = $self->{cache}->{check_path};
4348 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
4349 return $cache->{data}->{$path};
4351 my $pool = SVN::Pool->new;
4352 my $t = $self->SUPER::check_path($path, $r, $pool);
4353 $pool->clear;
4354 if ($r != $cache->{r}) {
4355 %{$cache->{data}} = ();
4356 $cache->{r} = $r;
4358 $cache->{data}->{$path} = $t;
4361 sub get_dir {
4362 my ($self, $dir, $r) = @_;
4363 my $cache = $self->{cache}->{get_dir};
4364 if ($r == $cache->{r}) {
4365 if (my $x = $cache->{data}->{$dir}) {
4366 return wantarray ? @$x : $x->[0];
4369 my $pool = SVN::Pool->new;
4370 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
4371 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
4372 $pool->clear;
4373 if ($r != $cache->{r}) {
4374 %{$cache->{data}} = ();
4375 $cache->{r} = $r;
4377 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
4378 wantarray ? (\%dirents, $r, $props) : \%dirents;
4381 sub DESTROY {
4382 # do not call the real DESTROY since we store ourselves in $RA
4385 # get_log(paths, start, end, limit,
4386 # discover_changed_paths, strict_node_history, receiver)
4387 sub get_log {
4388 my ($self, @args) = @_;
4389 my $pool = SVN::Pool->new;
4391 # the limit parameter was not supported in SVN 1.1.x, so we
4392 # drop it. Therefore, the receiver callback passed to it
4393 # is made aware of this limitation by being wrapped if
4394 # the limit passed to is being wrapped.
4395 if ($SVN::Core::VERSION le '1.2.0') {
4396 my $limit = splice(@args, 3, 1);
4397 if ($limit > 0) {
4398 my $receiver = pop @args;
4399 push(@args, sub { &$receiver(@_) if (--$limit >= 0) });
4402 my $ret = $self->SUPER::get_log(@args, $pool);
4403 $pool->clear;
4404 $ret;
4407 sub trees_match {
4408 my ($self, $url1, $rev1, $url2, $rev2) = @_;
4409 my $ctx = SVN::Client->new(auth => _auth_providers);
4410 my $out = IO::File->new_tmpfile;
4412 # older SVN (1.1.x) doesn't take $pool as the last parameter for
4413 # $ctx->diff(), so we'll create a default one
4414 my $pool = SVN::Pool->new_default_sub;
4416 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
4417 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
4418 $out->flush;
4419 my $ret = (($out->stat)[7] == 0);
4420 close $out or croak $!;
4422 $ret;
4425 sub get_commit_editor {
4426 my ($self, $log, $cb, $pool) = @_;
4427 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
4428 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
4431 sub gs_do_update {
4432 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
4433 my $new = ($rev_a == $rev_b);
4434 my $path = $gs->{path};
4436 if ($new && -e $gs->{index}) {
4437 unlink $gs->{index} or die
4438 "Couldn't unlink index: $gs->{index}: $!\n";
4440 my $pool = SVN::Pool->new;
4441 $editor->set_path_strip($path);
4442 my (@pc) = split m#/#, $path;
4443 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
4444 1, $editor, $pool);
4445 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4447 # Since we can't rely on svn_ra_reparent being available, we'll
4448 # just have to do some magic with set_path to make it so
4449 # we only want a partial path.
4450 my $sp = '';
4451 my $final = join('/', @pc);
4452 while (@pc) {
4453 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
4454 $sp .= '/' if length $sp;
4455 $sp .= shift @pc;
4457 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
4459 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
4461 $reporter->finish_report($pool);
4462 $pool->clear;
4463 $editor->{git_commit_ok};
4466 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
4467 # svn_ra_reparent didn't work before 1.4)
4468 sub gs_do_switch {
4469 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
4470 my $path = $gs->{path};
4471 my $pool = SVN::Pool->new;
4473 my $full_url = $self->{url};
4474 my $old_url = $full_url;
4475 $full_url .= '/' . escape_uri_only($path) if length $path;
4476 my ($ra, $reparented);
4478 if ($old_url =~ m#^svn(\+ssh)?://#) {
4479 $_[0] = undef;
4480 $self = undef;
4481 $RA = undef;
4482 $ra = Git::SVN::Ra->new($full_url);
4483 $ra_invalid = 1;
4484 } elsif ($old_url ne $full_url) {
4485 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url, $pool);
4486 $self->{url} = $full_url;
4487 $reparented = 1;
4490 $ra ||= $self;
4491 $url_b = escape_url($url_b);
4492 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
4493 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4494 $reporter->set_path('', $rev_a, 0, @lock, $pool);
4495 $reporter->finish_report($pool);
4497 if ($reparented) {
4498 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
4499 $self->{url} = $old_url;
4502 $pool->clear;
4503 $editor->{git_commit_ok};
4506 sub longest_common_path {
4507 my ($gsv, $globs) = @_;
4508 my %common;
4509 my $common_max = scalar @$gsv;
4511 foreach my $gs (@$gsv) {
4512 my @tmp = split m#/#, $gs->{path};
4513 my $p = '';
4514 foreach (@tmp) {
4515 $p .= length($p) ? "/$_" : $_;
4516 $common{$p} ||= 0;
4517 $common{$p}++;
4520 $globs ||= [];
4521 $common_max += scalar @$globs;
4522 foreach my $glob (@$globs) {
4523 my @tmp = split m#/#, $glob->{path}->{left};
4524 my $p = '';
4525 foreach (@tmp) {
4526 $p .= length($p) ? "/$_" : $_;
4527 $common{$p} ||= 0;
4528 $common{$p}++;
4532 my $longest_path = '';
4533 foreach (sort {length $b <=> length $a} keys %common) {
4534 if ($common{$_} == $common_max) {
4535 $longest_path = $_;
4536 last;
4539 $longest_path;
4542 sub gs_fetch_loop_common {
4543 my ($self, $base, $head, $gsv, $globs) = @_;
4544 return if ($base > $head);
4545 my $inc = $_log_window_size;
4546 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
4547 my $longest_path = longest_common_path($gsv, $globs);
4548 my $ra_url = $self->{url};
4549 my $find_trailing_edge;
4550 while (1) {
4551 my %revs;
4552 my $err;
4553 my $err_handler = $SVN::Error::handler;
4554 $SVN::Error::handler = sub {
4555 ($err) = @_;
4556 skip_unknown_revs($err);
4558 sub _cb {
4559 my ($paths, $r, $author, $date, $log) = @_;
4560 [ dup_changed_paths($paths),
4561 { author => $author, date => $date, log => $log } ];
4563 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
4564 sub { $revs{$_[1]} = _cb(@_) });
4565 if ($err) {
4566 print "Checked through r$max\r";
4567 } else {
4568 $find_trailing_edge = 1;
4570 if ($err and $find_trailing_edge) {
4571 print STDERR "Path '$longest_path' ",
4572 "was probably deleted:\n",
4573 $err->expanded_message,
4574 "\nWill attempt to follow ",
4575 "revisions r$min .. r$max ",
4576 "committed before the deletion\n";
4577 my $hi = $max;
4578 while (--$hi >= $min) {
4579 my $ok;
4580 $self->get_log([$longest_path], $min, $hi,
4581 0, 1, 1, sub {
4582 $ok = $_[1];
4583 $revs{$_[1]} = _cb(@_) });
4584 if ($ok) {
4585 print STDERR "r$min .. r$ok OK\n";
4586 last;
4589 $find_trailing_edge = 0;
4591 $SVN::Error::handler = $err_handler;
4593 my %exists = map { $_->{path} => $_ } @$gsv;
4594 foreach my $r (sort {$a <=> $b} keys %revs) {
4595 my ($paths, $logged) = @{$revs{$r}};
4597 foreach my $gs ($self->match_globs(\%exists, $paths,
4598 $globs, $r)) {
4599 if ($gs->rev_map_max >= $r) {
4600 next;
4602 next unless $gs->match_paths($paths, $r);
4603 $gs->{logged_rev_props} = $logged;
4604 if (my $last_commit = $gs->last_commit) {
4605 $gs->assert_index_clean($last_commit);
4607 my $log_entry = $gs->do_fetch($paths, $r);
4608 if ($log_entry) {
4609 $gs->do_git_commit($log_entry);
4611 $INDEX_FILES{$gs->{index}} = 1;
4613 foreach my $g (@$globs) {
4614 my $k = "svn-remote.$g->{remote}." .
4615 "$g->{t}-maxRev";
4616 Git::SVN::tmp_config($k, $r);
4618 if ($ra_invalid) {
4619 $_[0] = undef;
4620 $self = undef;
4621 $RA = undef;
4622 $self = Git::SVN::Ra->new($ra_url);
4623 $ra_invalid = undef;
4626 # pre-fill the .rev_db since it'll eventually get filled in
4627 # with '0' x40 if something new gets committed
4628 foreach my $gs (@$gsv) {
4629 next if $gs->rev_map_max >= $max;
4630 next if defined $gs->rev_map_get($max);
4631 $gs->rev_map_set($max, 0 x40);
4633 foreach my $g (@$globs) {
4634 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
4635 Git::SVN::tmp_config($k, $max);
4637 last if $max >= $head;
4638 $min = $max + 1;
4639 $max += $inc;
4640 $max = $head if ($max > $head);
4642 Git::SVN::gc();
4645 sub get_dir_globbed {
4646 my ($self, $left, $depth, $r) = @_;
4648 my @x = eval { $self->get_dir($left, $r) };
4649 return unless scalar @x == 3;
4650 my $dirents = $x[0];
4651 my @finalents;
4652 foreach my $de (keys %$dirents) {
4653 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
4654 if ($depth > 1) {
4655 my @args = ("$left/$de", $depth - 1, $r);
4656 foreach my $dir ($self->get_dir_globbed(@args)) {
4657 push @finalents, "$de/$dir";
4659 } else {
4660 push @finalents, $de;
4663 @finalents;
4666 sub match_globs {
4667 my ($self, $exists, $paths, $globs, $r) = @_;
4669 sub get_dir_check {
4670 my ($self, $exists, $g, $r) = @_;
4672 my @dirs = $self->get_dir_globbed($g->{path}->{left},
4673 $g->{path}->{depth},
4674 $r);
4676 foreach my $de (@dirs) {
4677 my $p = $g->{path}->full_path($de);
4678 next if $exists->{$p};
4679 next if (length $g->{path}->{right} &&
4680 ($self->check_path($p, $r) !=
4681 $SVN::Node::dir));
4682 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
4683 $g->{ref}->full_path($de), 1);
4686 foreach my $g (@$globs) {
4687 if (my $path = $paths->{"/$g->{path}->{left}"}) {
4688 if ($path->{action} =~ /^[AR]$/) {
4689 get_dir_check($self, $exists, $g, $r);
4692 foreach (keys %$paths) {
4693 if (/$g->{path}->{left_regex}/ &&
4694 !/$g->{path}->{regex}/) {
4695 next if $paths->{$_}->{action} !~ /^[AR]$/;
4696 get_dir_check($self, $exists, $g, $r);
4698 next unless /$g->{path}->{regex}/;
4699 my $p = $1;
4700 my $pathname = $g->{path}->full_path($p);
4701 next if $exists->{$pathname};
4702 next if ($self->check_path($pathname, $r) !=
4703 $SVN::Node::dir);
4704 $exists->{$pathname} = Git::SVN->init(
4705 $self->{url}, $pathname, undef,
4706 $g->{ref}->full_path($p), 1);
4708 my $c = '';
4709 foreach (split m#/#, $g->{path}->{left}) {
4710 $c .= "/$_";
4711 next unless ($paths->{$c} &&
4712 ($paths->{$c}->{action} =~ /^[AR]$/));
4713 get_dir_check($self, $exists, $g, $r);
4716 values %$exists;
4719 sub minimize_url {
4720 my ($self) = @_;
4721 return $self->{url} if ($self->{url} eq $self->{repos_root});
4722 my $url = $self->{repos_root};
4723 my @components = split(m!/!, $self->{svn_path});
4724 my $c = '';
4725 do {
4726 $url .= "/$c" if length $c;
4727 eval { (ref $self)->new($url)->get_latest_revnum };
4728 } while ($@ && ($c = shift @components));
4729 $url;
4732 sub can_do_switch {
4733 my $self = shift;
4734 unless (defined $can_do_switch) {
4735 my $pool = SVN::Pool->new;
4736 my $rep = eval {
4737 $self->do_switch(1, '', 0, $self->{url},
4738 SVN::Delta::Editor->new, $pool);
4740 if ($@) {
4741 $can_do_switch = 0;
4742 } else {
4743 $rep->abort_report($pool);
4744 $can_do_switch = 1;
4746 $pool->clear;
4748 $can_do_switch;
4751 sub skip_unknown_revs {
4752 my ($err) = @_;
4753 my $errno = $err->apr_err();
4754 # Maybe the branch we're tracking didn't
4755 # exist when the repo started, so it's
4756 # not an error if it doesn't, just continue
4758 # Wonderfully consistent library, eh?
4759 # 160013 - svn:// and file://
4760 # 175002 - http(s)://
4761 # 175007 - http(s):// (this repo required authorization, too...)
4762 # More codes may be discovered later...
4763 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
4764 my $err_key = $err->expanded_message;
4765 # revision numbers change every time, filter them out
4766 $err_key =~ s/\d+/\0/g;
4767 $err_key = "$errno\0$err_key";
4768 unless ($ignored_err{$err_key}) {
4769 warn "W: Ignoring error from SVN, path probably ",
4770 "does not exist: ($errno): ",
4771 $err->expanded_message,"\n";
4772 warn "W: Do not be alarmed at the above message ",
4773 "git-svn is just searching aggressively for ",
4774 "old history.\n",
4775 "This may take a while on large repositories\n";
4776 $ignored_err{$err_key} = 1;
4778 return;
4780 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
4783 # svn_log_changed_path_t objects passed to get_log are likely to be
4784 # overwritten even if only the refs are copied to an external variable,
4785 # so we should dup the structures in their entirety. Using an externally
4786 # passed pool (instead of our temporary and quickly cleared pool in
4787 # Git::SVN::Ra) does not help matters at all...
4788 sub dup_changed_paths {
4789 my ($paths) = @_;
4790 return undef unless $paths;
4791 my %ret;
4792 foreach my $p (keys %$paths) {
4793 my $i = $paths->{$p};
4794 my %s = map { $_ => $i->$_ }
4795 qw/copyfrom_path copyfrom_rev action/;
4796 $ret{$p} = \%s;
4798 \%ret;
4801 package Git::SVN::Log;
4802 use strict;
4803 use warnings;
4804 use POSIX qw/strftime/;
4805 use Time::Local;
4806 use constant commit_log_separator => ('-' x 72) . "\n";
4807 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
4808 %rusers $show_commit $incremental/;
4809 my $l_fmt;
4811 sub cmt_showable {
4812 my ($c) = @_;
4813 return 1 if defined $c->{r};
4815 # big commit message got truncated by the 16k pretty buffer in rev-list
4816 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
4817 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
4818 @{$c->{l}} = ();
4819 my @log = command(qw/cat-file commit/, $c->{c});
4821 # shift off the headers
4822 shift @log while ($log[0] ne '');
4823 shift @log;
4825 # TODO: make $c->{l} not have a trailing newline in the future
4826 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
4828 (undef, $c->{r}, undef) = ::extract_metadata(
4829 (grep(/^git-svn-id: /, @log))[-1]);
4831 return defined $c->{r};
4834 sub log_use_color {
4835 return $color || Git->repository->get_colorbool('color.diff');
4838 sub git_svn_log_cmd {
4839 my ($r_min, $r_max, @args) = @_;
4840 my $head = 'HEAD';
4841 my (@files, @log_opts);
4842 foreach my $x (@args) {
4843 if ($x eq '--' || @files) {
4844 push @files, $x;
4845 } else {
4846 if (::verify_ref("$x^0")) {
4847 $head = $x;
4848 } else {
4849 push @log_opts, $x;
4854 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
4855 $gs ||= Git::SVN->_new;
4856 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
4857 $gs->refname);
4858 push @cmd, '-r' unless $non_recursive;
4859 push @cmd, qw/--raw --name-status/ if $verbose;
4860 push @cmd, '--color' if log_use_color();
4861 push @cmd, @log_opts;
4862 if (defined $r_max && $r_max == $r_min) {
4863 push @cmd, '--max-count=1';
4864 if (my $c = $gs->rev_map_get($r_max)) {
4865 push @cmd, $c;
4867 } elsif (defined $r_max) {
4868 if ($r_max < $r_min) {
4869 ($r_min, $r_max) = ($r_max, $r_min);
4871 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
4872 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
4873 # If there are no commits in the range, both $c_max and $c_min
4874 # will be undefined. If there is at least 1 commit in the
4875 # range, both will be defined.
4876 return () if !defined $c_min || !defined $c_max;
4877 if ($c_min eq $c_max) {
4878 push @cmd, '--max-count=1', $c_min;
4879 } else {
4880 push @cmd, '--boundary', "$c_min..$c_max";
4883 return (@cmd, @files);
4886 # adapted from pager.c
4887 sub config_pager {
4888 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
4889 if (!defined $pager) {
4890 $pager = 'less';
4891 } elsif (length $pager == 0 || $pager eq 'cat') {
4892 $pager = undef;
4894 $ENV{GIT_PAGER_IN_USE} = defined($pager);
4897 sub run_pager {
4898 return unless -t *STDOUT && defined $pager;
4899 pipe my ($rfd, $wfd) or return;
4900 defined(my $pid = fork) or ::fatal "Can't fork: $!";
4901 if (!$pid) {
4902 open STDOUT, '>&', $wfd or
4903 ::fatal "Can't redirect to stdout: $!";
4904 return;
4906 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
4907 $ENV{LESS} ||= 'FRSX';
4908 exec $pager or ::fatal "Can't run pager: $! ($pager)";
4911 sub format_svn_date {
4912 # some systmes don't handle or mishandle %z, so be creative.
4913 my $t = shift || time;
4914 my $gm = timelocal(gmtime($t));
4915 my $sign = qw( + + - )[ $t <=> $gm ];
4916 my $gmoff = sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
4917 return strftime("%Y-%m-%d %H:%M:%S $gmoff (%a, %d %b %Y)", localtime($t));
4920 sub parse_git_date {
4921 my ($t, $tz) = @_;
4922 # Date::Parse isn't in the standard Perl distro :(
4923 if ($tz =~ s/^\+//) {
4924 $t += tz_to_s_offset($tz);
4925 } elsif ($tz =~ s/^\-//) {
4926 $t -= tz_to_s_offset($tz);
4928 return $t;
4931 sub set_local_timezone {
4932 if (defined $TZ) {
4933 $ENV{TZ} = $TZ;
4934 } else {
4935 delete $ENV{TZ};
4939 sub tz_to_s_offset {
4940 my ($tz) = @_;
4941 $tz =~ s/(\d\d)$//;
4942 return ($1 * 60) + ($tz * 3600);
4945 sub get_author_info {
4946 my ($dest, $author, $t, $tz) = @_;
4947 $author =~ s/(?:^\s*|\s*$)//g;
4948 $dest->{a_raw} = $author;
4949 my $au;
4950 if ($::_authors) {
4951 $au = $rusers{$author} || undef;
4953 if (!$au) {
4954 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
4956 $dest->{t} = $t;
4957 $dest->{tz} = $tz;
4958 $dest->{a} = $au;
4959 $dest->{t_utc} = parse_git_date($t, $tz);
4962 sub process_commit {
4963 my ($c, $r_min, $r_max, $defer) = @_;
4964 if (defined $r_min && defined $r_max) {
4965 if ($r_min == $c->{r} && $r_min == $r_max) {
4966 show_commit($c);
4967 return 0;
4969 return 1 if $r_min == $r_max;
4970 if ($r_min < $r_max) {
4971 # we need to reverse the print order
4972 return 0 if (defined $limit && --$limit < 0);
4973 push @$defer, $c;
4974 return 1;
4976 if ($r_min != $r_max) {
4977 return 1 if ($r_min < $c->{r});
4978 return 1 if ($r_max > $c->{r});
4981 return 0 if (defined $limit && --$limit < 0);
4982 show_commit($c);
4983 return 1;
4986 sub show_commit {
4987 my $c = shift;
4988 if ($oneline) {
4989 my $x = "\n";
4990 if (my $l = $c->{l}) {
4991 while ($l->[0] =~ /^\s*$/) { shift @$l }
4992 $x = $l->[0];
4994 $l_fmt ||= 'A' . length($c->{r});
4995 print 'r',pack($l_fmt, $c->{r}),' | ';
4996 print "$c->{c} | " if $show_commit;
4997 print $x;
4998 } else {
4999 show_commit_normal($c);
5003 sub show_commit_changed_paths {
5004 my ($c) = @_;
5005 return unless $c->{changed};
5006 print "Changed paths:\n", @{$c->{changed}};
5009 sub show_commit_normal {
5010 my ($c) = @_;
5011 print commit_log_separator, "r$c->{r} | ";
5012 print "$c->{c} | " if $show_commit;
5013 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
5014 my $nr_line = 0;
5016 if (my $l = $c->{l}) {
5017 while ($l->[$#$l] eq "\n" && $#$l > 0
5018 && $l->[($#$l - 1)] eq "\n") {
5019 pop @$l;
5021 $nr_line = scalar @$l;
5022 if (!$nr_line) {
5023 print "1 line\n\n\n";
5024 } else {
5025 if ($nr_line == 1) {
5026 $nr_line = '1 line';
5027 } else {
5028 $nr_line .= ' lines';
5030 print $nr_line, "\n";
5031 show_commit_changed_paths($c);
5032 print "\n";
5033 print $_ foreach @$l;
5035 } else {
5036 print "1 line\n";
5037 show_commit_changed_paths($c);
5038 print "\n";
5041 foreach my $x (qw/raw stat diff/) {
5042 if ($c->{$x}) {
5043 print "\n";
5044 print $_ foreach @{$c->{$x}}
5049 sub cmd_show_log {
5050 my (@args) = @_;
5051 my ($r_min, $r_max);
5052 my $r_last = -1; # prevent dupes
5053 set_local_timezone();
5054 if (defined $::_revision) {
5055 if ($::_revision =~ /^(\d+):(\d+)$/) {
5056 ($r_min, $r_max) = ($1, $2);
5057 } elsif ($::_revision =~ /^\d+$/) {
5058 $r_min = $r_max = $::_revision;
5059 } else {
5060 ::fatal "-r$::_revision is not supported, use ",
5061 "standard 'git log' arguments instead";
5065 config_pager();
5066 @args = git_svn_log_cmd($r_min, $r_max, @args);
5067 if (!@args) {
5068 print commit_log_separator unless $incremental || $oneline;
5069 return;
5071 my $log = command_output_pipe(@args);
5072 run_pager();
5073 my (@k, $c, $d, $stat);
5074 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
5075 while (<$log>) {
5076 if (/^${esc_color}commit -?($::sha1_short)/o) {
5077 my $cmt = $1;
5078 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
5079 $r_last = $c->{r};
5080 process_commit($c, $r_min, $r_max, \@k) or
5081 goto out;
5083 $d = undef;
5084 $c = { c => $cmt };
5085 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
5086 get_author_info($c, $1, $2, $3);
5087 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
5088 # ignore
5089 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
5090 push @{$c->{raw}}, $_;
5091 } elsif (/^${esc_color}[ACRMDT]\t/) {
5092 # we could add $SVN->{svn_path} here, but that requires
5093 # remote access at the moment (repo_path_split)...
5094 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
5095 push @{$c->{changed}}, $_;
5096 } elsif (/^${esc_color}diff /o) {
5097 $d = 1;
5098 push @{$c->{diff}}, $_;
5099 } elsif ($d) {
5100 push @{$c->{diff}}, $_;
5101 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
5102 $esc_color*[\+\-]*$esc_color$/x) {
5103 $stat = 1;
5104 push @{$c->{stat}}, $_;
5105 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
5106 push @{$c->{stat}}, $_;
5107 $stat = undef;
5108 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
5109 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
5110 } elsif (s/^${esc_color} //o) {
5111 push @{$c->{l}}, $_;
5114 if ($c && defined $c->{r} && $c->{r} != $r_last) {
5115 $r_last = $c->{r};
5116 process_commit($c, $r_min, $r_max, \@k);
5118 if (@k) {
5119 ($r_min, $r_max) = ($r_max, $r_min);
5120 process_commit($_, $r_min, $r_max) foreach reverse @k;
5122 out:
5123 close $log;
5124 print commit_log_separator unless $incremental || $oneline;
5127 sub cmd_blame {
5128 my $path = pop;
5130 config_pager();
5131 run_pager();
5133 my ($fh, $ctx, $rev);
5135 if ($_git_format) {
5136 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
5137 while (my $line = <$fh>) {
5138 if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
5139 # Uncommitted edits show up as a rev ID of
5140 # all zeros, which we can't look up with
5141 # cmt_metadata
5142 if ($1 !~ /^0+$/) {
5143 (undef, $rev, undef) =
5144 ::cmt_metadata($1);
5145 $rev = '0' if (!$rev);
5146 } else {
5147 $rev = '0';
5149 $rev = sprintf('%-10s', $rev);
5150 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
5152 print $line;
5154 } else {
5155 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
5156 '--', $path);
5157 my ($sha1);
5158 my %authors;
5159 my @buffer;
5160 my %dsha; #distinct sha keys
5162 while (my $line = <$fh>) {
5163 push @buffer, $line;
5164 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5165 $dsha{$1} = 1;
5169 my $s2r = ::cmt_sha2rev_batch([keys %dsha]);
5171 foreach my $line (@buffer) {
5172 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5173 $rev = $s2r->{$1};
5174 $rev = '0' if (!$rev)
5176 elsif ($line =~ /^author (.*)/) {
5177 $authors{$rev} = $1;
5178 $authors{$rev} =~ s/\s/_/g;
5180 elsif ($line =~ /^\t(.*)$/) {
5181 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
5185 command_close_pipe($fh, $ctx);
5188 package Git::SVN::Migration;
5189 # these version numbers do NOT correspond to actual version numbers
5190 # of git nor git-svn. They are just relative.
5192 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
5194 # v1 layout: .git/$id/info/url, refs/remotes/$id
5196 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
5198 # v3 layout: .git/svn/$id, refs/remotes/$id
5199 # - info/url may remain for backwards compatibility
5200 # - this is what we migrate up to this layout automatically,
5201 # - this will be used by git svn init on single branches
5202 # v3.1 layout (auto migrated):
5203 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
5204 # for backwards compatibility
5206 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
5207 # - this is only created for newly multi-init-ed
5208 # repositories. Similar in spirit to the
5209 # --use-separate-remotes option in git-clone (now default)
5210 # - we do not automatically migrate to this (following
5211 # the example set by core git)
5213 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
5214 # - newer, more-efficient format that uses 24-bytes per record
5215 # with no filler space.
5216 # - use xxd -c24 < .rev_map.$UUID to view and debug
5217 # - This is a one-way migration, repositories updated to the
5218 # new format will not be able to use old git-svn without
5219 # rebuilding the .rev_db. Rebuilding the rev_db is not
5220 # possible if noMetadata or useSvmProps are set; but should
5221 # be no problem for users that use the (sensible) defaults.
5222 use strict;
5223 use warnings;
5224 use Carp qw/croak/;
5225 use File::Path qw/mkpath/;
5226 use File::Basename qw/dirname basename/;
5227 use vars qw/$_minimize/;
5229 sub migrate_from_v0 {
5230 my $git_dir = $ENV{GIT_DIR};
5231 return undef unless -d $git_dir;
5232 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5233 my $migrated = 0;
5234 while (<$fh>) {
5235 chomp;
5236 my ($id, $orig_ref) = ($_, $_);
5237 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
5238 next unless -f "$git_dir/$id/info/url";
5239 my $new_ref = "refs/remotes/$id";
5240 if (::verify_ref("$new_ref^0")) {
5241 print STDERR "W: $orig_ref is probably an old ",
5242 "branch used by an ancient version of ",
5243 "git-svn.\n",
5244 "However, $new_ref also exists.\n",
5245 "We will not be able ",
5246 "to use this branch until this ",
5247 "ambiguity is resolved.\n";
5248 next;
5250 print STDERR "Migrating from v0 layout...\n" if !$migrated;
5251 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
5252 command_noisy('update-ref', $new_ref, $orig_ref);
5253 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
5254 $migrated++;
5256 command_close_pipe($fh, $ctx);
5257 print STDERR "Done migrating from v0 layout...\n" if $migrated;
5258 $migrated;
5261 sub migrate_from_v1 {
5262 my $git_dir = $ENV{GIT_DIR};
5263 my $migrated = 0;
5264 return $migrated unless -d $git_dir;
5265 my $svn_dir = "$git_dir/svn";
5267 # just in case somebody used 'svn' as their $id at some point...
5268 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
5270 print STDERR "Migrating from a git-svn v1 layout...\n";
5271 mkpath([$svn_dir]);
5272 print STDERR "Data from a previous version of git-svn exists, but\n\t",
5273 "$svn_dir\n\t(required for this version ",
5274 "($::VERSION) of git-svn) does not exist.\n";
5275 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5276 while (<$fh>) {
5277 my $x = $_;
5278 next unless $x =~ s#^refs/remotes/##;
5279 chomp $x;
5280 next unless -f "$git_dir/$x/info/url";
5281 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
5282 next unless $u;
5283 my $dn = dirname("$git_dir/svn/$x");
5284 mkpath([$dn]) unless -d $dn;
5285 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
5286 mkpath(["$git_dir/svn/svn"]);
5287 print STDERR " - $git_dir/$x/info => ",
5288 "$git_dir/svn/$x/info\n";
5289 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
5290 croak "$!: $x";
5291 # don't worry too much about these, they probably
5292 # don't exist with repos this old (save for index,
5293 # and we can easily regenerate that)
5294 foreach my $f (qw/unhandled.log index .rev_db/) {
5295 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
5297 } else {
5298 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
5299 rename "$git_dir/$x", "$git_dir/svn/$x" or
5300 croak "$!: $x";
5302 $migrated++;
5304 command_close_pipe($fh, $ctx);
5305 print STDERR "Done migrating from a git-svn v1 layout\n";
5306 $migrated;
5309 sub read_old_urls {
5310 my ($l_map, $pfx, $path) = @_;
5311 my @dir;
5312 foreach (<$path/*>) {
5313 if (-r "$_/info/url") {
5314 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
5315 my $ref_id = $pfx . basename $_;
5316 my $url = ::file_to_s("$_/info/url");
5317 $l_map->{$ref_id} = $url;
5318 } elsif (-d $_) {
5319 push @dir, $_;
5322 foreach (@dir) {
5323 my $x = $_;
5324 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
5325 read_old_urls($l_map, $x, $_);
5329 sub migrate_from_v2 {
5330 my @cfg = command(qw/config -l/);
5331 return if grep /^svn-remote\..+\.url=/, @cfg;
5332 my %l_map;
5333 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
5334 my $migrated = 0;
5336 foreach my $ref_id (sort keys %l_map) {
5337 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
5338 if ($@) {
5339 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
5341 $migrated++;
5343 $migrated;
5346 sub minimize_connections {
5347 my $r = Git::SVN::read_all_remotes();
5348 my $new_urls = {};
5349 my $root_repos = {};
5350 foreach my $repo_id (keys %$r) {
5351 my $url = $r->{$repo_id}->{url} or next;
5352 my $fetch = $r->{$repo_id}->{fetch} or next;
5353 my $ra = Git::SVN::Ra->new($url);
5355 # skip existing cases where we already connect to the root
5356 if (($ra->{url} eq $ra->{repos_root}) ||
5357 ($ra->{repos_root} eq $repo_id)) {
5358 $root_repos->{$ra->{url}} = $repo_id;
5359 next;
5362 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
5363 my $root_path = $ra->{url};
5364 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
5365 foreach my $path (keys %$fetch) {
5366 my $ref_id = $fetch->{$path};
5367 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
5369 # make sure we can read when connecting to
5370 # a higher level of a repository
5371 my ($last_rev, undef) = $gs->last_rev_commit;
5372 if (!defined $last_rev) {
5373 $last_rev = eval {
5374 $root_ra->get_latest_revnum;
5376 next if $@;
5378 my $new = $root_path;
5379 $new .= length $path ? "/$path" : '';
5380 eval {
5381 $root_ra->get_log([$new], $last_rev, $last_rev,
5382 0, 0, 1, sub { });
5384 next if $@;
5385 $new_urls->{$ra->{repos_root}}->{$new} =
5386 { ref_id => $ref_id,
5387 old_repo_id => $repo_id,
5388 old_path => $path };
5392 my @emptied;
5393 foreach my $url (keys %$new_urls) {
5394 # see if we can re-use an existing [svn-remote "repo_id"]
5395 # instead of creating a(n ugly) new section:
5396 my $repo_id = $root_repos->{$url} || $url;
5398 my $fetch = $new_urls->{$url};
5399 foreach my $path (keys %$fetch) {
5400 my $x = $fetch->{$path};
5401 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
5402 my $pfx = "svn-remote.$x->{old_repo_id}";
5404 my $old_fetch = quotemeta("$x->{old_path}:".
5405 "refs/remotes/$x->{ref_id}");
5406 command_noisy(qw/config --unset/,
5407 "$pfx.fetch", '^'. $old_fetch . '$');
5408 delete $r->{$x->{old_repo_id}}->
5409 {fetch}->{$x->{old_path}};
5410 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
5411 command_noisy(qw/config --unset/,
5412 "$pfx.url");
5413 push @emptied, $x->{old_repo_id}
5417 if (@emptied) {
5418 my $file = $ENV{GIT_CONFIG} || "$ENV{GIT_DIR}/config";
5419 print STDERR <<EOF;
5420 The following [svn-remote] sections in your config file ($file) are empty
5421 and can be safely removed:
5423 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
5427 sub migration_check {
5428 migrate_from_v0();
5429 migrate_from_v1();
5430 migrate_from_v2();
5431 minimize_connections() if $_minimize;
5434 package Git::IndexInfo;
5435 use strict;
5436 use warnings;
5437 use Git qw/command_input_pipe command_close_pipe/;
5439 sub new {
5440 my ($class) = @_;
5441 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
5442 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
5445 sub remove {
5446 my ($self, $path) = @_;
5447 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
5448 return ++$self->{nr};
5450 undef;
5453 sub update {
5454 my ($self, $mode, $hash, $path) = @_;
5455 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
5456 return ++$self->{nr};
5458 undef;
5461 sub DESTROY {
5462 my ($self) = @_;
5463 command_close_pipe($self->{gui}, $self->{ctx});
5466 package Git::SVN::GlobSpec;
5467 use strict;
5468 use warnings;
5470 sub new {
5471 my ($class, $glob) = @_;
5472 my $re = $glob;
5473 $re =~ s!/+$!!g; # no need for trailing slashes
5474 $re =~ m!^([^*]*)(\*(?:/\*)*)([^*]*)$!;
5475 my $temp = $re;
5476 my ($left, $right) = ($1, $3);
5477 $re = $2;
5478 my $depth = $re =~ tr/*/*/;
5479 if ($depth != $temp =~ tr/*/*/) {
5480 die "Only one set of wildcard directories " .
5481 "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
5483 if ($depth == 0) {
5484 die "One '*' is needed for glob: '$glob'\n";
5486 $re =~ s!\*!\[^/\]*!g;
5487 $re = quotemeta($left) . "($re)" . quotemeta($right);
5488 if (length $left && !($left =~ s!/+$!!g)) {
5489 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
5491 if (length $right && !($right =~ s!^/+!!g)) {
5492 die "Missing leading '/' on right side of: '$glob' ($right)\n";
5494 my $left_re = qr/^\/\Q$left\E(\/|$)/;
5495 bless { left => $left, right => $right, left_regex => $left_re,
5496 regex => qr/$re/, glob => $glob, depth => $depth }, $class;
5499 sub full_path {
5500 my ($self, $path) = @_;
5501 return (length $self->{left} ? "$self->{left}/" : '') .
5502 $path . (length $self->{right} ? "/$self->{right}" : '');
5505 __END__
5507 Data structures:
5510 $remotes = { # returned by read_all_remotes()
5511 'svn' => {
5512 # svn-remote.svn.url=https://svn.musicpd.org
5513 url => 'https://svn.musicpd.org',
5514 # svn-remote.svn.fetch=mpd/trunk:trunk
5515 fetch => {
5516 'mpd/trunk' => 'trunk',
5518 # svn-remote.svn.tags=mpd/tags/*:tags/*
5519 tags => {
5520 path => {
5521 left => 'mpd/tags',
5522 right => '',
5523 regex => qr!mpd/tags/([^/]+)$!,
5524 glob => 'tags/*',
5526 ref => {
5527 left => 'tags',
5528 right => '',
5529 regex => qr!tags/([^/]+)$!,
5530 glob => 'tags/*',
5536 $log_entry hashref as returned by libsvn_log_entry()
5538 log => 'whitespace-formatted log entry
5539 ', # trailing newline is preserved
5540 revision => '8', # integer
5541 date => '2004-02-24T17:01:44.108345Z', # commit date
5542 author => 'committer name'
5546 # this is generated by generate_diff();
5547 @mods = array of diff-index line hashes, each element represents one line
5548 of diff-index output
5550 diff-index line ($m hash)
5552 mode_a => first column of diff-index output, no leading ':',
5553 mode_b => second column of diff-index output,
5554 sha1_b => sha1sum of the final blob,
5555 chg => change type [MCRADT],
5556 file_a => original file name of a file (iff chg is 'C' or 'R')
5557 file_b => new/current file name of a file (any chg)
5561 # retval of read_url_paths{,_all}();
5562 $l_map = {
5563 # repository root url
5564 'https://svn.musicpd.org' => {
5565 # repository path # GIT_SVN_ID
5566 'mpd/trunk' => 'trunk',
5567 'mpd/tags/0.11.5' => 'tags/0.11.5',
5571 Notes:
5572 I don't trust the each() function on unless I created %hash myself
5573 because the internal iterator may not have started at base.