Add selftest for 'git submodule foreach'
[git/git-svn.git] / git-svn.perl
blob1da9f0781c24b4f4f6f63c137a0caccec85024d6
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;
22 $Git::SVN::_minimize_url = 'unset';
24 $Git::SVN::Log::TZ = $ENV{TZ};
25 $ENV{TZ} = 'UTC';
26 $| = 1; # unbuffer STDOUT
28 sub fatal (@) { print STDERR "@_\n"; exit 1 }
29 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
30 require SVN::Ra;
31 require SVN::Delta;
32 if ($SVN::Core::VERSION lt '1.1.0') {
33 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
35 my $can_compress = eval { require Compress::Zlib; 1};
36 push @Git::SVN::Ra::ISA, 'SVN::Ra';
37 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
38 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
39 use Carp qw/croak/;
40 use Digest::MD5;
41 use IO::File qw//;
42 use File::Basename qw/dirname basename/;
43 use File::Path qw/mkpath/;
44 use File::Spec;
45 use File::Find;
46 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
47 use IPC::Open3;
48 use Git;
50 BEGIN {
51 # import functions from Git into our packages, en masse
52 no strict 'refs';
53 foreach (qw/command command_oneline command_noisy command_output_pipe
54 command_input_pipe command_close_pipe
55 command_bidi_pipe command_close_bidi_pipe/) {
56 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
57 Git::SVN::Migration Git::SVN::Log Git::SVN),
58 __PACKAGE__) {
59 *{"${package}::$_"} = \&{"Git::$_"};
64 my ($SVN);
66 $sha1 = qr/[a-f\d]{40}/;
67 $sha1_short = qr/[a-f\d]{4,40}/;
68 my ($_stdin, $_help, $_edit,
69 $_message, $_file, $_branch_dest,
70 $_template, $_shared,
71 $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
72 $_merge, $_strategy, $_dry_run, $_local,
73 $_prefix, $_no_checkout, $_url, $_verbose,
74 $_git_format, $_commit_url, $_tag);
75 $Git::SVN::_follow_parent = 1;
76 $_q ||= 0;
77 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
78 'config-dir=s' => \$Git::SVN::Ra::config_dir,
79 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
80 'ignore-paths=s' => \$SVN::Git::Fetcher::_ignore_regex );
81 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
82 'authors-file|A=s' => \$_authors,
83 'authors-prog=s' => \$_authors_prog,
84 'repack:i' => \$Git::SVN::_repack,
85 'noMetadata' => \$Git::SVN::_no_metadata,
86 'useSvmProps' => \$Git::SVN::_use_svm_props,
87 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
88 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
89 'no-checkout' => \$_no_checkout,
90 'quiet|q+' => \$_q,
91 'repack-flags|repack-args|repack-opts=s' =>
92 \$Git::SVN::_repack_flags,
93 'use-log-author' => \$Git::SVN::_use_log_author,
94 'add-author-from' => \$Git::SVN::_add_author_from,
95 'localtime' => \$Git::SVN::_localtime,
96 %remote_opts );
98 my ($_trunk, @_tags, @_branches, $_stdlayout);
99 my %icv;
100 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
101 'trunk|T=s' => \$_trunk, 'tags|t=s@' => \@_tags,
102 'branches|b=s@' => \@_branches, 'prefix=s' => \$_prefix,
103 'stdlayout|s' => \$_stdlayout,
104 'minimize-url|m!' => \$Git::SVN::_minimize_url,
105 'no-metadata' => sub { $icv{noMetadata} = 1 },
106 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
107 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
108 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
109 %remote_opts );
110 my %cmt_opts = ( 'edit|e' => \$_edit,
111 'rmdir' => \$SVN::Git::Editor::_rmdir,
112 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
113 'l=i' => \$SVN::Git::Editor::_rename_limit,
114 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
117 my %cmd = (
118 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
119 { 'revision|r=s' => \$_revision,
120 'fetch-all|all' => \$_fetch_all,
121 'parent|p' => \$_fetch_parent,
122 %fc_opts } ],
123 clone => [ \&cmd_clone, "Initialize and fetch revisions",
124 { 'revision|r=s' => \$_revision,
125 %fc_opts, %init_opts } ],
126 init => [ \&cmd_init, "Initialize a repo for tracking" .
127 " (requires URL argument)",
128 \%init_opts ],
129 'multi-init' => [ \&cmd_multi_init,
130 "Deprecated alias for ".
131 "'$0 init -T<trunk> -b<branches> -t<tags>'",
132 \%init_opts ],
133 dcommit => [ \&cmd_dcommit,
134 'Commit several diffs to merge with upstream',
135 { 'merge|m|M' => \$_merge,
136 'strategy|s=s' => \$_strategy,
137 'verbose|v' => \$_verbose,
138 'dry-run|n' => \$_dry_run,
139 'fetch-all|all' => \$_fetch_all,
140 'commit-url=s' => \$_commit_url,
141 'revision|r=i' => \$_revision,
142 'no-rebase' => \$_no_rebase,
143 %cmt_opts, %fc_opts } ],
144 branch => [ \&cmd_branch,
145 'Create a branch in the SVN repository',
146 { 'message|m=s' => \$_message,
147 'destination|d=s' => \$_branch_dest,
148 'dry-run|n' => \$_dry_run,
149 'tag|t' => \$_tag } ],
150 tag => [ sub { $_tag = 1; cmd_branch(@_) },
151 'Create a tag in the SVN repository',
152 { 'message|m=s' => \$_message,
153 'destination|d=s' => \$_branch_dest,
154 'dry-run|n' => \$_dry_run } ],
155 'set-tree' => [ \&cmd_set_tree,
156 "Set an SVN repository to a git tree-ish",
157 { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
158 'create-ignore' => [ \&cmd_create_ignore,
159 'Create a .gitignore per svn:ignore',
160 { 'revision|r=i' => \$_revision
161 } ],
162 'propget' => [ \&cmd_propget,
163 'Print the value of a property on a file or directory',
164 { 'revision|r=i' => \$_revision } ],
165 'proplist' => [ \&cmd_proplist,
166 'List all properties of a file or directory',
167 { 'revision|r=i' => \$_revision } ],
168 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
169 { 'revision|r=i' => \$_revision
170 } ],
171 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
172 { 'revision|r=i' => \$_revision
173 } ],
174 'multi-fetch' => [ \&cmd_multi_fetch,
175 "Deprecated alias for $0 fetch --all",
176 { 'revision|r=s' => \$_revision, %fc_opts } ],
177 'migrate' => [ sub { },
178 # no-op, we automatically run this anyways,
179 'Migrate configuration/metadata/layout from
180 previous versions of git-svn',
181 { 'minimize' => \$Git::SVN::Migration::_minimize,
182 %remote_opts } ],
183 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
184 { 'limit=i' => \$Git::SVN::Log::limit,
185 'revision|r=s' => \$_revision,
186 'verbose|v' => \$Git::SVN::Log::verbose,
187 'incremental' => \$Git::SVN::Log::incremental,
188 'oneline' => \$Git::SVN::Log::oneline,
189 'show-commit' => \$Git::SVN::Log::show_commit,
190 'non-recursive' => \$Git::SVN::Log::non_recursive,
191 'authors-file|A=s' => \$_authors,
192 'color' => \$Git::SVN::Log::color,
193 'pager=s' => \$Git::SVN::Log::pager
194 } ],
195 'find-rev' => [ \&cmd_find_rev,
196 "Translate between SVN revision numbers and tree-ish",
197 {} ],
198 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
199 { 'merge|m|M' => \$_merge,
200 'verbose|v' => \$_verbose,
201 'strategy|s=s' => \$_strategy,
202 'local|l' => \$_local,
203 'fetch-all|all' => \$_fetch_all,
204 'dry-run|n' => \$_dry_run,
205 %fc_opts } ],
206 'commit-diff' => [ \&cmd_commit_diff,
207 'Commit a diff between two trees',
208 { 'message|m=s' => \$_message,
209 'file|F=s' => \$_file,
210 'revision|r=s' => \$_revision,
211 %cmt_opts } ],
212 'info' => [ \&cmd_info,
213 "Show info about the latest SVN revision
214 on the current branch",
215 { 'url' => \$_url, } ],
216 'blame' => [ \&Git::SVN::Log::cmd_blame,
217 "Show what revision and author last modified each line of a file",
218 { 'git-format' => \$_git_format } ],
219 'reset' => [ \&cmd_reset,
220 "Undo fetches back to the specified SVN revision",
221 { 'revision|r=s' => \$_revision,
222 'parent|p' => \$_fetch_parent } ],
223 'gc' => [ \&cmd_gc,
224 "Compress unhandled.log files in .git/svn and remove " .
225 "index files in .git/svn",
226 {} ],
229 my $cmd;
230 for (my $i = 0; $i < @ARGV; $i++) {
231 if (defined $cmd{$ARGV[$i]}) {
232 $cmd = $ARGV[$i];
233 splice @ARGV, $i, 1;
234 last;
235 } elsif ($ARGV[$i] eq 'help') {
236 $cmd = $ARGV[$i+1];
237 usage(0);
241 # make sure we're always running at the top-level working directory
242 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
243 unless (-d $ENV{GIT_DIR}) {
244 if ($git_dir_user_set) {
245 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
246 "but it is not a directory\n";
248 my $git_dir = delete $ENV{GIT_DIR};
249 my $cdup = undef;
250 git_cmd_try {
251 $cdup = command_oneline(qw/rev-parse --show-cdup/);
252 $git_dir = '.' unless ($cdup);
253 chomp $cdup if ($cdup);
254 $cdup = "." unless ($cdup && length $cdup);
255 } "Already at toplevel, but $git_dir not found\n";
256 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
257 unless (-d $git_dir) {
258 die "$git_dir still not found after going to ",
259 "'$cdup'\n";
261 $ENV{GIT_DIR} = $git_dir;
263 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
266 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
268 read_repo_config(\%opts);
269 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
270 Getopt::Long::Configure('pass_through');
272 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
273 'minimize-connections' => \$Git::SVN::Migration::_minimize,
274 'id|i=s' => \$Git::SVN::default_ref_id,
275 'svn-remote|remote|R=s' => sub {
276 $Git::SVN::no_reuse_existing = 1;
277 $Git::SVN::default_repo_id = $_[1] });
278 exit 1 if (!$rv && $cmd && $cmd ne 'log');
280 usage(0) if $_help;
281 version() if $_version;
282 usage(1) unless defined $cmd;
283 load_authors() if $_authors;
284 if (defined $_authors_prog) {
285 $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
288 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
289 Git::SVN::Migration::migration_check();
291 Git::SVN::init_vars();
292 eval {
293 Git::SVN::verify_remotes_sanity();
294 $cmd{$cmd}->[0]->(@ARGV);
296 fatal $@ if $@;
297 post_fetch_checkout();
298 exit 0;
300 ####################### primary functions ######################
301 sub usage {
302 my $exit = shift || 0;
303 my $fd = $exit ? \*STDERR : \*STDOUT;
304 print $fd <<"";
305 git-svn - bidirectional operations between a single Subversion tree and git
306 Usage: git svn <command> [options] [arguments]\n
308 print $fd "Available commands:\n" unless $cmd;
310 foreach (sort keys %cmd) {
311 next if $cmd && $cmd ne $_;
312 next if /^multi-/; # don't show deprecated commands
313 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
314 foreach (sort keys %{$cmd{$_}->[2]}) {
315 # mixed-case options are for .git/config only
316 next if /[A-Z]/ && /^[a-z]+$/i;
317 # prints out arguments as they should be passed:
318 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
319 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
320 "--$_" : "-$_" }
321 split /\|/,$_)," $x\n";
324 print $fd <<"";
325 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
326 arbitrary identifier if you're tracking multiple SVN branches/repositories in
327 one git repository and want to keep them separate. See git-svn(1) for more
328 information.
330 exit $exit;
333 sub version {
334 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
335 exit 0;
338 sub do_git_init_db {
339 unless (-d $ENV{GIT_DIR}) {
340 my @init_db = ('init');
341 push @init_db, "--template=$_template" if defined $_template;
342 if (defined $_shared) {
343 if ($_shared =~ /[a-z]/) {
344 push @init_db, "--shared=$_shared";
345 } else {
346 push @init_db, "--shared";
349 command_noisy(@init_db);
350 $_repository = Git->repository(Repository => ".git");
352 command_noisy('config', 'core.autocrlf', 'false');
353 my $set;
354 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
355 foreach my $i (keys %icv) {
356 die "'$set' and '$i' cannot both be set\n" if $set;
357 next unless defined $icv{$i};
358 command_noisy('config', "$pfx.$i", $icv{$i});
359 $set = $i;
361 my $ignore_regex = \$SVN::Git::Fetcher::_ignore_regex;
362 command_noisy('config', "$pfx.ignore-paths", $$ignore_regex)
363 if defined $$ignore_regex;
366 sub init_subdir {
367 my $repo_path = shift or return;
368 mkpath([$repo_path]) unless -d $repo_path;
369 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
370 $ENV{GIT_DIR} = '.git';
371 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
374 sub cmd_clone {
375 my ($url, $path) = @_;
376 if (!defined $path &&
377 (defined $_trunk || @_branches || @_tags ||
378 defined $_stdlayout) &&
379 $url !~ m#^[a-z\+]+://#) {
380 $path = $url;
382 $path = basename($url) if !defined $path || !length $path;
383 cmd_init($url, $path);
384 Git::SVN::fetch_all($Git::SVN::default_repo_id);
385 command_oneline('config', 'svn.authorsfile', $_authors) if $_authors;
388 sub cmd_init {
389 if (defined $_stdlayout) {
390 $_trunk = 'trunk' if (!defined $_trunk);
391 @_tags = 'tags' if (! @_tags);
392 @_branches = 'branches' if (! @_branches);
394 if (defined $_trunk || @_branches || @_tags) {
395 return cmd_multi_init(@_);
397 my $url = shift or die "SVN repository location required ",
398 "as a command-line argument\n";
399 $url = canonicalize_url($url);
400 init_subdir(@_);
401 do_git_init_db();
403 if ($Git::SVN::_minimize_url eq 'unset') {
404 $Git::SVN::_minimize_url = 0;
407 Git::SVN->init($url);
410 sub cmd_fetch {
411 if (grep /^\d+=./, @_) {
412 die "'<rev>=<commit>' fetch arguments are ",
413 "no longer supported.\n";
415 my ($remote) = @_;
416 if (@_ > 1) {
417 die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
419 if ($_fetch_parent) {
420 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
421 unless ($gs) {
422 die "Unable to determine upstream SVN information from ",
423 "working tree history\n";
425 # just fetch, don't checkout.
426 $_no_checkout = 'true';
427 $_fetch_all ? $gs->fetch_all : $gs->fetch;
428 } elsif ($_fetch_all) {
429 cmd_multi_fetch();
430 } else {
431 $remote ||= $Git::SVN::default_repo_id;
432 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
436 sub cmd_set_tree {
437 my (@commits) = @_;
438 if ($_stdin || !@commits) {
439 print "Reading from stdin...\n";
440 @commits = ();
441 while (<STDIN>) {
442 if (/\b($sha1_short)\b/o) {
443 unshift @commits, $1;
447 my @revs;
448 foreach my $c (@commits) {
449 my @tmp = command('rev-parse',$c);
450 if (scalar @tmp == 1) {
451 push @revs, $tmp[0];
452 } elsif (scalar @tmp > 1) {
453 push @revs, reverse(command('rev-list',@tmp));
454 } else {
455 fatal "Failed to rev-parse $c";
458 my $gs = Git::SVN->new;
459 my ($r_last, $cmt_last) = $gs->last_rev_commit;
460 $gs->fetch;
461 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
462 fatal "There are new revisions that were fetched ",
463 "and need to be merged (or acknowledged) ",
464 "before committing.\nlast rev: $r_last\n",
465 " current: $gs->{last_rev}";
467 $gs->set_tree($_) foreach @revs;
468 print "Done committing ",scalar @revs," revisions to SVN\n";
469 unlink $gs->{index};
472 sub cmd_dcommit {
473 my $head = shift;
474 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
475 'Cannot dcommit with a dirty index. Commit your changes first, '
476 . "or stash them with `git stash'.\n";
477 $head ||= 'HEAD';
479 my $old_head;
480 if ($head ne 'HEAD') {
481 $old_head = eval {
482 command_oneline([qw/symbolic-ref -q HEAD/])
484 if ($old_head) {
485 $old_head =~ s{^refs/heads/}{};
486 } else {
487 $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
489 command(['checkout', $head], STDERR => 0);
492 my @refs;
493 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
494 unless ($gs) {
495 die "Unable to determine upstream SVN information from ",
496 "$head history.\nPerhaps the repository is empty.";
499 if (defined $_commit_url) {
500 $url = $_commit_url;
501 } else {
502 $url = eval { command_oneline('config', '--get',
503 "svn-remote.$gs->{repo_id}.commiturl") };
504 if (!$url) {
505 $url = $gs->full_url
509 my $last_rev = $_revision if defined $_revision;
510 if ($url) {
511 print "Committing to $url ...\n";
513 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
514 if ($_no_rebase && scalar(@$linear_refs) > 1) {
515 warn "Attempting to commit more than one change while ",
516 "--no-rebase is enabled.\n",
517 "If these changes depend on each other, re-running ",
518 "without --no-rebase may be required."
520 my $expect_url = $url;
521 Git::SVN::remove_username($expect_url);
522 while (1) {
523 my $d = shift @$linear_refs or last;
524 unless (defined $last_rev) {
525 (undef, $last_rev, undef) = cmt_metadata("$d~1");
526 unless (defined $last_rev) {
527 fatal "Unable to extract revision information ",
528 "from commit $d~1";
531 if ($_dry_run) {
532 print "diff-tree $d~1 $d\n";
533 } else {
534 my $cmt_rev;
535 my %ed_opts = ( r => $last_rev,
536 log => get_commit_entry($d)->{log},
537 ra => Git::SVN::Ra->new($url),
538 config => SVN::Core::config_get_config(
539 $Git::SVN::Ra::config_dir
541 tree_a => "$d~1",
542 tree_b => $d,
543 editor_cb => sub {
544 print "Committed r$_[0]\n";
545 $cmt_rev = $_[0];
547 svn_path => '');
548 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
549 print "No changes\n$d~1 == $d\n";
550 } elsif ($parents->{$d} && @{$parents->{$d}}) {
551 $gs->{inject_parents_dcommit}->{$cmt_rev} =
552 $parents->{$d};
554 $_fetch_all ? $gs->fetch_all : $gs->fetch;
555 $last_rev = $cmt_rev;
556 next if $_no_rebase;
558 # we always want to rebase against the current HEAD,
559 # not any head that was passed to us
560 my @diff = command('diff-tree', $d,
561 $gs->refname, '--');
562 my @finish;
563 if (@diff) {
564 @finish = rebase_cmd();
565 print STDERR "W: $d and ", $gs->refname,
566 " differ, using @finish:\n",
567 join("\n", @diff), "\n";
568 } else {
569 print "No changes between current HEAD and ",
570 $gs->refname,
571 "\nResetting to the latest ",
572 $gs->refname, "\n";
573 @finish = qw/reset --mixed/;
575 command_noisy(@finish, $gs->refname);
576 if (@diff) {
577 @refs = ();
578 my ($url_, $rev_, $uuid_, $gs_) =
579 working_head_info('HEAD', \@refs);
580 my ($linear_refs_, $parents_) =
581 linearize_history($gs_, \@refs);
582 if (scalar(@$linear_refs) !=
583 scalar(@$linear_refs_)) {
584 fatal "# of revisions changed ",
585 "\nbefore:\n",
586 join("\n", @$linear_refs),
587 "\n\nafter:\n",
588 join("\n", @$linear_refs_), "\n",
589 'If you are attempting to commit ',
590 "merges, try running:\n\t",
591 'git rebase --interactive',
592 '--preserve-merges ',
593 $gs->refname,
594 "\nBefore dcommitting";
596 if ($url_ ne $expect_url) {
597 fatal "URL mismatch after rebase: ",
598 "$url_ != $expect_url";
600 if ($uuid_ ne $uuid) {
601 fatal "uuid mismatch after rebase: ",
602 "$uuid_ != $uuid";
604 # remap parents
605 my (%p, @l, $i);
606 for ($i = 0; $i < scalar @$linear_refs; $i++) {
607 my $new = $linear_refs_->[$i] or next;
608 $p{$new} =
609 $parents->{$linear_refs->[$i]};
610 push @l, $new;
612 $parents = \%p;
613 $linear_refs = \@l;
618 if ($old_head) {
619 my $new_head = command_oneline(qw/rev-parse HEAD/);
620 my $new_is_symbolic = eval {
621 command_oneline(qw/symbolic-ref -q HEAD/);
623 if ($new_is_symbolic) {
624 print "dcommitted the branch ", $head, "\n";
625 } else {
626 print "dcommitted on a detached HEAD because you gave ",
627 "a revision argument.\n",
628 "The rewritten commit is: ", $new_head, "\n";
630 command(['checkout', $old_head], STDERR => 0);
633 unlink $gs->{index};
636 sub cmd_branch {
637 my ($branch_name, $head) = @_;
639 unless (defined $branch_name && length $branch_name) {
640 die(($_tag ? "tag" : "branch") . " name required\n");
642 $head ||= 'HEAD';
644 my ($src, $rev, undef, $gs) = working_head_info($head);
646 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
647 my $allglobs = $remote->{ $_tag ? 'tags' : 'branches' };
648 my $glob;
649 if ($#{$allglobs} == 0) {
650 $glob = $allglobs->[0];
651 } else {
652 unless(defined $_branch_dest) {
653 die "Multiple ",
654 $_tag ? "tag" : "branch",
655 " paths defined for Subversion repository.\n",
656 "You must specify where you want to create the ",
657 $_tag ? "tag" : "branch",
658 " with the --destination argument.\n";
660 foreach my $g (@{$allglobs}) {
661 # SVN::Git::Editor could probably be moved to Git.pm..
662 my $re = SVN::Git::Editor::glob2pat($g->{path}->{left});
663 if ($_branch_dest =~ /$re/) {
664 $glob = $g;
665 last;
668 unless (defined $glob) {
669 my $dest_re = qr/\b\Q$_branch_dest\E\b/;
670 foreach my $g (@{$allglobs}) {
671 $g->{path}->{left} =~ /$dest_re/ or next;
672 if (defined $glob) {
673 die "Ambiguous destination: ",
674 $_branch_dest, "\nmatches both '",
675 $glob->{path}->{left}, "' and '",
676 $g->{path}->{left}, "'\n";
678 $glob = $g;
680 unless (defined $glob) {
681 die "Unknown ",
682 $_tag ? "tag" : "branch",
683 " destination $_branch_dest\n";
687 my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
688 my $dst = join '/', $remote->{url}, $lft, $branch_name, ($rgt || ());
690 my $ctx = SVN::Client->new(
691 auth => Git::SVN::Ra::_auth_providers(),
692 log_msg => sub {
693 ${ $_[0] } = defined $_message
694 ? $_message
695 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
696 . $branch_name;
700 eval {
701 $ctx->ls($dst, 'HEAD', 0);
702 } and die "branch ${branch_name} already exists\n";
704 print "Copying ${src} at r${rev} to ${dst}...\n";
705 $ctx->copy($src, $rev, $dst)
706 unless $_dry_run;
708 $gs->fetch_all;
711 sub cmd_find_rev {
712 my $revision_or_hash = shift or die "SVN or git revision required ",
713 "as a command-line argument\n";
714 my $result;
715 if ($revision_or_hash =~ /^r\d+$/) {
716 my $head = shift;
717 $head ||= 'HEAD';
718 my @refs;
719 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
720 unless ($gs) {
721 die "Unable to determine upstream SVN information from ",
722 "$head history\n";
724 my $desired_revision = substr($revision_or_hash, 1);
725 $result = $gs->rev_map_get($desired_revision, $uuid);
726 } else {
727 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
728 $result = $rev;
730 print "$result\n" if $result;
733 sub cmd_rebase {
734 command_noisy(qw/update-index --refresh/);
735 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
736 unless ($gs) {
737 die "Unable to determine upstream SVN information from ",
738 "working tree history\n";
740 if ($_dry_run) {
741 print "Remote Branch: " . $gs->refname . "\n";
742 print "SVN URL: " . $url . "\n";
743 return;
745 if (command(qw/diff-index HEAD --/)) {
746 print STDERR "Cannot rebase with uncommited changes:\n";
747 command_noisy('status');
748 exit 1;
750 unless ($_local) {
751 # rebase will checkout for us, so no need to do it explicitly
752 $_no_checkout = 'true';
753 $_fetch_all ? $gs->fetch_all : $gs->fetch;
755 command_noisy(rebase_cmd(), $gs->refname);
758 sub cmd_show_ignore {
759 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
760 $gs ||= Git::SVN->new;
761 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
762 $gs->prop_walk($gs->{path}, $r, sub {
763 my ($gs, $path, $props) = @_;
764 print STDOUT "\n# $path\n";
765 my $s = $props->{'svn:ignore'} or return;
766 $s =~ s/[\r\n]+/\n/g;
767 $s =~ s/^\n+//;
768 chomp $s;
769 $s =~ s#^#$path#gm;
770 print STDOUT "$s\n";
774 sub cmd_show_externals {
775 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
776 $gs ||= Git::SVN->new;
777 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
778 $gs->prop_walk($gs->{path}, $r, sub {
779 my ($gs, $path, $props) = @_;
780 print STDOUT "\n# $path\n";
781 my $s = $props->{'svn:externals'} or return;
782 $s =~ s/[\r\n]+/\n/g;
783 chomp $s;
784 $s =~ s#^#$path#gm;
785 print STDOUT "$s\n";
789 sub cmd_create_ignore {
790 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
791 $gs ||= Git::SVN->new;
792 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
793 $gs->prop_walk($gs->{path}, $r, sub {
794 my ($gs, $path, $props) = @_;
795 # $path is of the form /path/to/dir/
796 $path = '.' . $path;
797 # SVN can have attributes on empty directories,
798 # which git won't track
799 mkpath([$path]) unless -d $path;
800 my $ignore = $path . '.gitignore';
801 my $s = $props->{'svn:ignore'} or return;
802 open(GITIGNORE, '>', $ignore)
803 or fatal("Failed to open `$ignore' for writing: $!");
804 $s =~ s/[\r\n]+/\n/g;
805 $s =~ s/^\n+//;
806 chomp $s;
807 # Prefix all patterns so that the ignore doesn't apply
808 # to sub-directories.
809 $s =~ s#^#/#gm;
810 print GITIGNORE "$s\n";
811 close(GITIGNORE)
812 or fatal("Failed to close `$ignore': $!");
813 command_noisy('add', '-f', $ignore);
817 sub canonicalize_path {
818 my ($path) = @_;
819 my $dot_slash_added = 0;
820 if (substr($path, 0, 1) ne "/") {
821 $path = "./" . $path;
822 $dot_slash_added = 1;
824 # File::Spec->canonpath doesn't collapse x/../y into y (for a
825 # good reason), so let's do this manually.
826 $path =~ s#/+#/#g;
827 $path =~ s#/\.(?:/|$)#/#g;
828 $path =~ s#/[^/]+/\.\.##g;
829 $path =~ s#/$##g;
830 $path =~ s#^\./## if $dot_slash_added;
831 $path =~ s#^/##;
832 $path =~ s#^\.$##;
833 return $path;
836 sub canonicalize_url {
837 my ($url) = @_;
838 $url =~ s#^([^:]+://[^/]*/)(.*)$#$1 . canonicalize_path($2)#e;
839 return $url;
842 # get_svnprops(PATH)
843 # ------------------
844 # Helper for cmd_propget and cmd_proplist below.
845 sub get_svnprops {
846 my $path = shift;
847 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
848 $gs ||= Git::SVN->new;
850 # prefix THE PATH by the sub-directory from which the user
851 # invoked us.
852 $path = $cmd_dir_prefix . $path;
853 fatal("No such file or directory: $path") unless -e $path;
854 my $is_dir = -d $path ? 1 : 0;
855 $path = $gs->{path} . '/' . $path;
857 # canonicalize the path (otherwise libsvn will abort or fail to
858 # find the file)
859 $path = canonicalize_path($path);
861 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
862 my $props;
863 if ($is_dir) {
864 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
866 else {
867 (undef, $props) = $gs->ra->get_file($path, $r, undef);
869 return $props;
872 # cmd_propget (PROP, PATH)
873 # ------------------------
874 # Print the SVN property PROP for PATH.
875 sub cmd_propget {
876 my ($prop, $path) = @_;
877 $path = '.' if not defined $path;
878 usage(1) if not defined $prop;
879 my $props = get_svnprops($path);
880 if (not defined $props->{$prop}) {
881 fatal("`$path' does not have a `$prop' SVN property.");
883 print $props->{$prop} . "\n";
886 # cmd_proplist (PATH)
887 # -------------------
888 # Print the list of SVN properties for PATH.
889 sub cmd_proplist {
890 my $path = shift;
891 $path = '.' if not defined $path;
892 my $props = get_svnprops($path);
893 print "Properties on '$path':\n";
894 foreach (sort keys %{$props}) {
895 print " $_\n";
899 sub cmd_multi_init {
900 my $url = shift;
901 unless (defined $_trunk || @_branches || @_tags) {
902 usage(1);
905 $_prefix = '' unless defined $_prefix;
906 if (defined $url) {
907 $url = canonicalize_url($url);
908 init_subdir(@_);
910 do_git_init_db();
911 if (defined $_trunk) {
912 my $trunk_ref = 'refs/remotes/' . $_prefix . 'trunk';
913 # try both old-style and new-style lookups:
914 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
915 unless ($gs_trunk) {
916 my ($trunk_url, $trunk_path) =
917 complete_svn_url($url, $_trunk);
918 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
919 undef, $trunk_ref);
922 return unless @_branches || @_tags;
923 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
924 foreach my $path (@_branches) {
925 complete_url_ls_init($ra, $path, '--branches/-b', $_prefix);
927 foreach my $path (@_tags) {
928 complete_url_ls_init($ra, $path, '--tags/-t', $_prefix.'tags/');
932 sub cmd_multi_fetch {
933 my $remotes = Git::SVN::read_all_remotes();
934 foreach my $repo_id (sort keys %$remotes) {
935 if ($remotes->{$repo_id}->{url}) {
936 Git::SVN::fetch_all($repo_id, $remotes);
941 # this command is special because it requires no metadata
942 sub cmd_commit_diff {
943 my ($ta, $tb, $url) = @_;
944 my $usage = "Usage: $0 commit-diff -r<revision> ".
945 "<tree-ish> <tree-ish> [<URL>]";
946 fatal($usage) if (!defined $ta || !defined $tb);
947 my $svn_path = '';
948 if (!defined $url) {
949 my $gs = eval { Git::SVN->new };
950 if (!$gs) {
951 fatal("Needed URL or usable git-svn --id in ",
952 "the command-line\n", $usage);
954 $url = $gs->{url};
955 $svn_path = $gs->{path};
957 unless (defined $_revision) {
958 fatal("-r|--revision is a required argument\n", $usage);
960 if (defined $_message && defined $_file) {
961 fatal("Both --message/-m and --file/-F specified ",
962 "for the commit message.\n",
963 "I have no idea what you mean");
965 if (defined $_file) {
966 $_message = file_to_s($_file);
967 } else {
968 $_message ||= get_commit_entry($tb)->{log};
970 my $ra ||= Git::SVN::Ra->new($url);
971 my $r = $_revision;
972 if ($r eq 'HEAD') {
973 $r = $ra->get_latest_revnum;
974 } elsif ($r !~ /^\d+$/) {
975 die "revision argument: $r not understood by git-svn\n";
977 my %ed_opts = ( r => $r,
978 log => $_message,
979 ra => $ra,
980 tree_a => $ta,
981 tree_b => $tb,
982 editor_cb => sub { print "Committed r$_[0]\n" },
983 svn_path => $svn_path );
984 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
985 print "No changes\n$ta == $tb\n";
989 sub escape_uri_only {
990 my ($uri) = @_;
991 my @tmp;
992 foreach (split m{/}, $uri) {
993 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
994 push @tmp, $_;
996 join('/', @tmp);
999 sub escape_url {
1000 my ($url) = @_;
1001 if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
1002 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
1003 $url = "$scheme://$domain$uri";
1005 $url;
1008 sub cmd_info {
1009 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
1010 my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
1011 if (exists $_[1]) {
1012 die "Too many arguments specified\n";
1015 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
1017 if (!$file_type && !$diff_status) {
1018 print STDERR "svn: '$path' is not under version control\n";
1019 exit 1;
1022 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1023 unless ($gs) {
1024 die "Unable to determine upstream SVN information from ",
1025 "working tree history\n";
1028 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
1029 $path = "." if $path eq "";
1031 my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
1033 if ($_url) {
1034 print escape_url($full_url), "\n";
1035 return;
1038 my $result = "Path: $path\n";
1039 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
1040 $result .= "URL: " . escape_url($full_url) . "\n";
1042 eval {
1043 my $repos_root = $gs->repos_root;
1044 Git::SVN::remove_username($repos_root);
1045 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
1047 if ($@) {
1048 $result .= "Repository Root: (offline)\n";
1050 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
1051 ($SVN::Core::VERSION le '1.5.4' || $file_type ne "dir");
1052 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
1054 $result .= "Node Kind: " .
1055 ($file_type eq "dir" ? "directory" : "file") . "\n";
1057 my $schedule = $diff_status eq "A"
1058 ? "add"
1059 : ($diff_status eq "D" ? "delete" : "normal");
1060 $result .= "Schedule: $schedule\n";
1062 if ($diff_status eq "A") {
1063 print $result, "\n";
1064 return;
1067 my ($lc_author, $lc_rev, $lc_date_utc);
1068 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
1069 my $log = command_output_pipe(@args);
1070 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
1071 while (<$log>) {
1072 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
1073 $lc_author = $1;
1074 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
1075 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
1076 (undef, $lc_rev, undef) = ::extract_metadata($1);
1079 close $log;
1081 Git::SVN::Log::set_local_timezone();
1083 $result .= "Last Changed Author: $lc_author\n";
1084 $result .= "Last Changed Rev: $lc_rev\n";
1085 $result .= "Last Changed Date: " .
1086 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
1088 if ($file_type ne "dir") {
1089 my $text_last_updated_date =
1090 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
1091 $result .=
1092 "Text Last Updated: " .
1093 Git::SVN::Log::format_svn_date($text_last_updated_date) .
1094 "\n";
1095 my $checksum;
1096 if ($diff_status eq "D") {
1097 my ($fh, $ctx) =
1098 command_output_pipe(qw(cat-file blob), "HEAD:$path");
1099 if ($file_type eq "link") {
1100 my $file_name = <$fh>;
1101 $checksum = md5sum("link $file_name");
1102 } else {
1103 $checksum = md5sum($fh);
1105 command_close_pipe($fh, $ctx);
1106 } elsif ($file_type eq "link") {
1107 my $file_name =
1108 command(qw(cat-file blob), "HEAD:$path");
1109 $checksum =
1110 md5sum("link " . $file_name);
1111 } else {
1112 open FILE, "<", $path or die $!;
1113 $checksum = md5sum(\*FILE);
1114 close FILE or die $!;
1116 $result .= "Checksum: " . $checksum . "\n";
1119 print $result, "\n";
1122 sub cmd_reset {
1123 my $target = shift || $_revision or die "SVN revision required\n";
1124 $target = $1 if $target =~ /^r(\d+)$/;
1125 $target =~ /^\d+$/ or die "Numeric SVN revision expected\n";
1126 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1127 unless ($gs) {
1128 die "Unable to determine upstream SVN information from ".
1129 "history\n";
1131 my ($r, $c) = $gs->find_rev_before($target, not $_fetch_parent);
1132 $gs->rev_map_set($r, $c, 'reset', $uuid);
1133 print "r$r = $c ($gs->{ref_id})\n";
1136 sub cmd_gc {
1137 if (!$can_compress) {
1138 warn "Compress::Zlib could not be found; unhandled.log " .
1139 "files will not be compressed.\n";
1141 find({ wanted => \&gc_directory, no_chdir => 1}, "$ENV{GIT_DIR}/svn");
1144 ########################### utility functions #########################
1146 sub rebase_cmd {
1147 my @cmd = qw/rebase/;
1148 push @cmd, '-v' if $_verbose;
1149 push @cmd, qw/--merge/ if $_merge;
1150 push @cmd, "--strategy=$_strategy" if $_strategy;
1151 @cmd;
1154 sub post_fetch_checkout {
1155 return if $_no_checkout;
1156 my $gs = $Git::SVN::_head or return;
1157 return if verify_ref('refs/heads/master^0');
1159 # look for "trunk" ref if it exists
1160 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
1161 my $fetch = $remote->{fetch};
1162 if ($fetch) {
1163 foreach my $p (keys %$fetch) {
1164 basename($fetch->{$p}) eq 'trunk' or next;
1165 $gs = Git::SVN->new($fetch->{$p}, $gs->{repo_id}, $p);
1166 last;
1170 my $valid_head = verify_ref('HEAD^0');
1171 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1172 return if ($valid_head || !verify_ref('HEAD^0'));
1174 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1175 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1176 return if -f $index;
1178 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1179 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1180 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1181 print STDERR "Checked out HEAD:\n ",
1182 $gs->full_url, " r", $gs->last_rev, "\n";
1185 sub complete_svn_url {
1186 my ($url, $path) = @_;
1187 $path =~ s#/+$##;
1188 if ($path !~ m#^[a-z\+]+://#) {
1189 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1190 fatal("E: '$path' is not a complete URL ",
1191 "and a separate URL is not specified");
1193 return ($url, $path);
1195 return ($path, '');
1198 sub complete_url_ls_init {
1199 my ($ra, $repo_path, $switch, $pfx) = @_;
1200 unless ($repo_path) {
1201 print STDERR "W: $switch not specified\n";
1202 return;
1204 $repo_path =~ s#/+$##;
1205 if ($repo_path =~ m#^[a-z\+]+://#) {
1206 $ra = Git::SVN::Ra->new($repo_path);
1207 $repo_path = '';
1208 } else {
1209 $repo_path =~ s#^/+##;
1210 unless ($ra) {
1211 fatal("E: '$repo_path' is not a complete URL ",
1212 "and a separate URL is not specified");
1215 my $url = $ra->{url};
1216 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1217 my $k = "svn-remote.$gs->{repo_id}.url";
1218 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1219 if ($orig_url && ($orig_url ne $gs->{url})) {
1220 die "$k already set: $orig_url\n",
1221 "wanted to set to: $gs->{url}\n";
1223 command_oneline('config', $k, $gs->{url}) unless $orig_url;
1224 my $remote_path = "$gs->{path}/$repo_path";
1225 $remote_path =~ s#/+#/#g;
1226 $remote_path =~ s#^/##g;
1227 $remote_path .= "/*" if $remote_path !~ /\*/;
1228 my ($n) = ($switch =~ /^--(\w+)/);
1229 if (length $pfx && $pfx !~ m#/$#) {
1230 die "--prefix='$pfx' must have a trailing slash '/'\n";
1232 command_noisy('config',
1233 '--add',
1234 "svn-remote.$gs->{repo_id}.$n",
1235 "$remote_path:refs/remotes/$pfx*" .
1236 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1239 sub verify_ref {
1240 my ($ref) = @_;
1241 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1242 { STDERR => 0 }); };
1245 sub get_tree_from_treeish {
1246 my ($treeish) = @_;
1247 # $treeish can be a symbolic ref, too:
1248 my $type = command_oneline(qw/cat-file -t/, $treeish);
1249 my $expected;
1250 while ($type eq 'tag') {
1251 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1253 if ($type eq 'commit') {
1254 $expected = (grep /^tree /, command(qw/cat-file commit/,
1255 $treeish))[0];
1256 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1257 die "Unable to get tree from $treeish\n" unless $expected;
1258 } elsif ($type eq 'tree') {
1259 $expected = $treeish;
1260 } else {
1261 die "$treeish is a $type, expected tree, tag or commit\n";
1263 return $expected;
1266 sub get_commit_entry {
1267 my ($treeish) = shift;
1268 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1269 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1270 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1271 open my $log_fh, '>', $commit_editmsg or croak $!;
1273 my $type = command_oneline(qw/cat-file -t/, $treeish);
1274 if ($type eq 'commit' || $type eq 'tag') {
1275 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1276 $type, $treeish);
1277 my $in_msg = 0;
1278 my $author;
1279 my $saw_from = 0;
1280 my $msgbuf = "";
1281 while (<$msg_fh>) {
1282 if (!$in_msg) {
1283 $in_msg = 1 if (/^\s*$/);
1284 $author = $1 if (/^author (.*>)/);
1285 } elsif (/^git-svn-id: /) {
1286 # skip this for now, we regenerate the
1287 # correct one on re-fetch anyways
1288 # TODO: set *:merge properties or like...
1289 } else {
1290 if (/^From:/ || /^Signed-off-by:/) {
1291 $saw_from = 1;
1293 $msgbuf .= $_;
1296 $msgbuf =~ s/\s+$//s;
1297 if ($Git::SVN::_add_author_from && defined($author)
1298 && !$saw_from) {
1299 $msgbuf .= "\n\nFrom: $author";
1301 print $log_fh $msgbuf or croak $!;
1302 command_close_pipe($msg_fh, $ctx);
1304 close $log_fh or croak $!;
1306 if ($_edit || ($type eq 'tree')) {
1307 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1308 # TODO: strip out spaces, comments, like git-commit.sh
1309 system($editor, $commit_editmsg);
1311 rename $commit_editmsg, $commit_msg or croak $!;
1313 require Encode;
1314 # SVN requires messages to be UTF-8 when entering the repo
1315 local $/;
1316 open $log_fh, '<', $commit_msg or croak $!;
1317 binmode $log_fh;
1318 chomp($log_entry{log} = <$log_fh>);
1320 my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
1321 my $msg = $log_entry{log};
1323 eval { $msg = Encode::decode($enc, $msg, 1) };
1324 if ($@) {
1325 die "Could not decode as $enc:\n", $msg,
1326 "\nPerhaps you need to set i18n.commitencoding\n";
1329 eval { $msg = Encode::encode('UTF-8', $msg, 1) };
1330 die "Could not encode as UTF-8:\n$msg\n" if $@;
1332 $log_entry{log} = $msg;
1334 close $log_fh or croak $!;
1336 unlink $commit_msg;
1337 \%log_entry;
1340 sub s_to_file {
1341 my ($str, $file, $mode) = @_;
1342 open my $fd,'>',$file or croak $!;
1343 print $fd $str,"\n" or croak $!;
1344 close $fd or croak $!;
1345 chmod ($mode &~ umask, $file) if (defined $mode);
1348 sub file_to_s {
1349 my $file = shift;
1350 open my $fd,'<',$file or croak "$!: file: $file\n";
1351 local $/;
1352 my $ret = <$fd>;
1353 close $fd or croak $!;
1354 $ret =~ s/\s*$//s;
1355 return $ret;
1358 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1359 sub load_authors {
1360 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1361 my $log = $cmd eq 'log';
1362 while (<$authors>) {
1363 chomp;
1364 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1365 my ($user, $name, $email) = ($1, $2, $3);
1366 if ($log) {
1367 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1368 } else {
1369 $users{$user} = [$name, $email];
1372 close $authors or croak $!;
1375 # convert GetOpt::Long specs for use by git-config
1376 sub read_repo_config {
1377 return unless -d $ENV{GIT_DIR};
1378 my $opts = shift;
1379 my @config_only;
1380 foreach my $o (keys %$opts) {
1381 # if we have mixedCase and a long option-only, then
1382 # it's a config-only variable that we don't need for
1383 # the command-line.
1384 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1385 my $v = $opts->{$o};
1386 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1387 $key =~ s/-//g;
1388 my $arg = 'git config';
1389 $arg .= ' --int' if ($o =~ /[:=]i$/);
1390 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1391 if (ref $v eq 'ARRAY') {
1392 chomp(my @tmp = `$arg --get-all svn.$key`);
1393 @$v = @tmp if @tmp;
1394 } else {
1395 chomp(my $tmp = `$arg --get svn.$key`);
1396 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1397 $$v = $tmp;
1401 delete @$opts{@config_only} if @config_only;
1404 sub extract_metadata {
1405 my $id = shift or return (undef, undef, undef);
1406 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1407 \s([a-f\d\-]+)$/ix);
1408 if (!defined $rev || !$uuid || !$url) {
1409 # some of the original repositories I made had
1410 # identifiers like this:
1411 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/i);
1413 return ($url, $rev, $uuid);
1416 sub cmt_metadata {
1417 return extract_metadata((grep(/^git-svn-id: /,
1418 command(qw/cat-file commit/, shift)))[-1]);
1421 sub cmt_sha2rev_batch {
1422 my %s2r;
1423 my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1424 my $list = shift;
1426 foreach my $sha (@{$list}) {
1427 my $first = 1;
1428 my $size = 0;
1429 print $out $sha, "\n";
1431 while (my $line = <$in>) {
1432 if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1433 last;
1434 } elsif ($first &&
1435 $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1436 $first = 0;
1437 $size = $1;
1438 next;
1439 } elsif ($line =~ /^(git-svn-id: )/) {
1440 my (undef, $rev, undef) =
1441 extract_metadata($line);
1442 $s2r{$sha} = $rev;
1445 $size -= length($line);
1446 last if ($size == 0);
1450 command_close_bidi_pipe($pid, $in, $out, $ctx);
1452 return \%s2r;
1455 sub working_head_info {
1456 my ($head, $refs) = @_;
1457 my @args = ('log', '--no-color', '--first-parent', '--pretty=medium');
1458 my ($fh, $ctx) = command_output_pipe(@args, $head);
1459 my $hash;
1460 my %max;
1461 while (<$fh>) {
1462 if ( m{^commit ($::sha1)$} ) {
1463 unshift @$refs, $hash if $hash and $refs;
1464 $hash = $1;
1465 next;
1467 next unless s{^\s*(git-svn-id:)}{$1};
1468 my ($url, $rev, $uuid) = extract_metadata($_);
1469 if (defined $url && defined $rev) {
1470 next if $max{$url} and $max{$url} < $rev;
1471 if (my $gs = Git::SVN->find_by_url($url)) {
1472 my $c = $gs->rev_map_get($rev, $uuid);
1473 if ($c && $c eq $hash) {
1474 close $fh; # break the pipe
1475 return ($url, $rev, $uuid, $gs);
1476 } else {
1477 $max{$url} ||= $gs->rev_map_max;
1482 command_close_pipe($fh, $ctx);
1483 (undef, undef, undef, undef);
1486 sub read_commit_parents {
1487 my ($parents, $c) = @_;
1488 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1489 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1490 @{$parents->{$c}} = split(/ /, $p);
1493 sub linearize_history {
1494 my ($gs, $refs) = @_;
1495 my %parents;
1496 foreach my $c (@$refs) {
1497 read_commit_parents(\%parents, $c);
1500 my @linear_refs;
1501 my %skip = ();
1502 my $last_svn_commit = $gs->last_commit;
1503 foreach my $c (reverse @$refs) {
1504 next if $c eq $last_svn_commit;
1505 last if $skip{$c};
1507 unshift @linear_refs, $c;
1508 $skip{$c} = 1;
1510 # we only want the first parent to diff against for linear
1511 # history, we save the rest to inject when we finalize the
1512 # svn commit
1513 my $fp_a = verify_ref("$c~1");
1514 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1515 if (!$fp_a || !$fp_b) {
1516 die "Commit $c\n",
1517 "has no parent commit, and therefore ",
1518 "nothing to diff against.\n",
1519 "You should be working from a repository ",
1520 "originally created by git-svn\n";
1522 if ($fp_a ne $fp_b) {
1523 die "$c~1 = $fp_a, however parsing commit $c ",
1524 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1527 foreach my $p (@{$parents{$c}}) {
1528 $skip{$p} = 1;
1531 (\@linear_refs, \%parents);
1534 sub find_file_type_and_diff_status {
1535 my ($path) = @_;
1536 return ('dir', '') if $path eq '';
1538 my $diff_output =
1539 command_oneline(qw(diff --cached --name-status --), $path) || "";
1540 my $diff_status = (split(' ', $diff_output))[0] || "";
1542 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1544 return (undef, undef) if !$diff_status && !$ls_tree;
1546 if ($diff_status eq "A") {
1547 return ("link", $diff_status) if -l $path;
1548 return ("dir", $diff_status) if -d $path;
1549 return ("file", $diff_status);
1552 my $mode = (split(' ', $ls_tree))[0] || "";
1554 return ("link", $diff_status) if $mode eq "120000";
1555 return ("dir", $diff_status) if $mode eq "040000";
1556 return ("file", $diff_status);
1559 sub md5sum {
1560 my $arg = shift;
1561 my $ref = ref $arg;
1562 my $md5 = Digest::MD5->new();
1563 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
1564 $md5->addfile($arg) or croak $!;
1565 } elsif ($ref eq 'SCALAR') {
1566 $md5->add($$arg) or croak $!;
1567 } elsif (!$ref) {
1568 $md5->add($arg) or croak $!;
1569 } else {
1570 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1572 return $md5->hexdigest();
1575 sub gc_directory {
1576 if ($can_compress && -f $_ && basename($_) eq "unhandled.log") {
1577 my $out_filename = $_ . ".gz";
1578 open my $in_fh, "<", $_ or die "Unable to open $_: $!\n";
1579 binmode $in_fh;
1580 my $gz = Compress::Zlib::gzopen($out_filename, "ab") or
1581 die "Unable to open $out_filename: $!\n";
1583 my $res;
1584 while ($res = sysread($in_fh, my $str, 1024)) {
1585 $gz->gzwrite($str) or
1586 die "Unable to write: ".$gz->gzerror()."!\n";
1588 unlink $_ or die "unlink $File::Find::name: $!\n";
1589 } elsif (-f $_ && basename($_) eq "index") {
1590 unlink $_ or die "unlink $_: $!\n";
1594 package Git::SVN;
1595 use strict;
1596 use warnings;
1597 use Fcntl qw/:DEFAULT :seek/;
1598 use constant rev_map_fmt => 'NH40';
1599 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1600 $_repack $_repack_flags $_use_svm_props $_head
1601 $_use_svnsync_props $no_reuse_existing $_minimize_url
1602 $_use_log_author $_add_author_from $_localtime/;
1603 use Carp qw/croak/;
1604 use File::Path qw/mkpath/;
1605 use File::Copy qw/copy/;
1606 use IPC::Open3;
1608 my ($_gc_nr, $_gc_period);
1610 # properties that we do not log:
1611 my %SKIP_PROP;
1612 BEGIN {
1613 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1614 svn:special svn:executable
1615 svn:entry:committed-rev
1616 svn:entry:last-author
1617 svn:entry:uuid
1618 svn:entry:committed-date/;
1620 # some options are read globally, but can be overridden locally
1621 # per [svn-remote "..."] section. Command-line options will *NOT*
1622 # override options set in an [svn-remote "..."] section
1623 no strict 'refs';
1624 for my $option (qw/follow_parent no_metadata use_svm_props
1625 use_svnsync_props/) {
1626 my $key = $option;
1627 $key =~ tr/_//d;
1628 my $prop = "-$option";
1629 *$option = sub {
1630 my ($self) = @_;
1631 return $self->{$prop} if exists $self->{$prop};
1632 my $k = "svn-remote.$self->{repo_id}.$key";
1633 eval { command_oneline(qw/config --get/, $k) };
1634 if ($@) {
1635 $self->{$prop} = ${"Git::SVN::_$option"};
1636 } else {
1637 my $v = command_oneline(qw/config --bool/,$k);
1638 $self->{$prop} = $v eq 'false' ? 0 : 1;
1640 return $self->{$prop};
1646 my (%LOCKFILES, %INDEX_FILES);
1647 END {
1648 unlink keys %LOCKFILES if %LOCKFILES;
1649 unlink keys %INDEX_FILES if %INDEX_FILES;
1652 sub resolve_local_globs {
1653 my ($url, $fetch, $glob_spec) = @_;
1654 return unless defined $glob_spec;
1655 my $ref = $glob_spec->{ref};
1656 my $path = $glob_spec->{path};
1657 foreach (command(qw#for-each-ref --format=%(refname) refs/#)) {
1658 next unless m#^$ref->{regex}$#;
1659 my $p = $1;
1660 my $pathname = desanitize_refname($path->full_path($p));
1661 my $refname = desanitize_refname($ref->full_path($p));
1662 if (my $existing = $fetch->{$pathname}) {
1663 if ($existing ne $refname) {
1664 die "Refspec conflict:\n",
1665 "existing: $existing\n",
1666 " globbed: $refname\n";
1668 my $u = (::cmt_metadata("$refname"))[0];
1669 $u =~ s!^\Q$url\E(/|$)!! or die
1670 "$refname: '$url' not found in '$u'\n";
1671 if ($pathname ne $u) {
1672 warn "W: Refspec glob conflict ",
1673 "(ref: $refname):\n",
1674 "expected path: $pathname\n",
1675 " real path: $u\n",
1676 "Continuing ahead with $u\n";
1677 next;
1679 } else {
1680 $fetch->{$pathname} = $refname;
1685 sub parse_revision_argument {
1686 my ($base, $head) = @_;
1687 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1688 return ($base, $head);
1690 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1691 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1692 return ($head, $head) if ($::_revision eq 'HEAD');
1693 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1694 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1695 die "revision argument: $::_revision not understood by git-svn\n";
1698 sub fetch_all {
1699 my ($repo_id, $remotes) = @_;
1700 if (ref $repo_id) {
1701 my $gs = $repo_id;
1702 $repo_id = undef;
1703 $repo_id = $gs->{repo_id};
1705 $remotes ||= read_all_remotes();
1706 my $remote = $remotes->{$repo_id} or
1707 die "[svn-remote \"$repo_id\"] unknown\n";
1708 my $fetch = $remote->{fetch};
1709 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1710 my (@gs, @globs);
1711 my $ra = Git::SVN::Ra->new($url);
1712 my $uuid = $ra->get_uuid;
1713 my $head = $ra->get_latest_revnum;
1714 $ra->get_log("", $head, 0, 1, 0, 1, sub { $head = $_[1] });
1715 my $base = defined $fetch ? $head : 0;
1717 # read the max revs for wildcard expansion (branches/*, tags/*)
1718 foreach my $t (qw/branches tags/) {
1719 defined $remote->{$t} or next;
1720 push @globs, @{$remote->{$t}};
1722 my $max_rev = eval { tmp_config(qw/--int --get/,
1723 "svn-remote.$repo_id.${t}-maxRev") };
1724 if (defined $max_rev && ($max_rev < $base)) {
1725 $base = $max_rev;
1726 } elsif (!defined $max_rev) {
1727 $base = 0;
1731 if ($fetch) {
1732 foreach my $p (sort keys %$fetch) {
1733 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1734 my $lr = $gs->rev_map_max;
1735 if (defined $lr) {
1736 $base = $lr if ($lr < $base);
1738 push @gs, $gs;
1742 ($base, $head) = parse_revision_argument($base, $head);
1743 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1746 sub read_all_remotes {
1747 my $r = {};
1748 my $use_svm_props = eval { command_oneline(qw/config --bool
1749 svn.useSvmProps/) };
1750 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
1751 my $svn_refspec = qr{\s*/?(.*?)\s*:\s*(.+?)\s*};
1752 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1753 if (m!^(.+)\.fetch=$svn_refspec$!) {
1754 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
1755 die("svn-remote.$remote: remote ref '$remote_ref' "
1756 . "must start with 'refs/'\n")
1757 unless $remote_ref =~ m{^refs/};
1758 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1759 $r->{$remote}->{svm} = {} if $use_svm_props;
1760 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
1761 $r->{$1}->{svm} = {};
1762 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1763 $r->{$1}->{url} = $2;
1764 } elsif (m!^(.+)\.(branches|tags)=$svn_refspec$!) {
1765 my ($remote, $t, $local_ref, $remote_ref) =
1766 ($1, $2, $3, $4);
1767 die("svn-remote.$remote: remote ref '$remote_ref' ($t) "
1768 . "must start with 'refs/'\n")
1769 unless $remote_ref =~ m{^refs/};
1770 my $rs = {
1771 t => $t,
1772 remote => $remote,
1773 path => Git::SVN::GlobSpec->new($local_ref),
1774 ref => Git::SVN::GlobSpec->new($remote_ref) };
1775 if (length($rs->{ref}->{right}) != 0) {
1776 die "The '*' glob character must be the last ",
1777 "character of '$remote_ref'\n";
1779 push @{ $r->{$remote}->{$t} }, $rs;
1783 map {
1784 if (defined $r->{$_}->{svm}) {
1785 my $svm;
1786 eval {
1787 my $section = "svn-remote.$_";
1788 $svm = {
1789 source => tmp_config('--get',
1790 "$section.svm-source"),
1791 replace => tmp_config('--get',
1792 "$section.svm-replace"),
1795 $r->{$_}->{svm} = $svm;
1797 } keys %$r;
1802 sub init_vars {
1803 $_gc_nr = $_gc_period = 1000;
1804 if (defined $_repack || defined $_repack_flags) {
1805 warn "Repack options are obsolete; they have no effect.\n";
1809 sub verify_remotes_sanity {
1810 return unless -d $ENV{GIT_DIR};
1811 my %seen;
1812 foreach (command(qw/config -l/)) {
1813 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1814 if ($seen{$1}) {
1815 die "Remote ref refs/remote/$1 is tracked by",
1816 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1817 "Please resolve this ambiguity in ",
1818 "your git configuration file before ",
1819 "continuing\n";
1821 $seen{$1} = $_;
1826 sub find_existing_remote {
1827 my ($url, $remotes) = @_;
1828 return undef if $no_reuse_existing;
1829 my $existing;
1830 foreach my $repo_id (keys %$remotes) {
1831 my $u = $remotes->{$repo_id}->{url} or next;
1832 next if $u ne $url;
1833 $existing = $repo_id;
1834 last;
1836 $existing;
1839 sub init_remote_config {
1840 my ($self, $url, $no_write) = @_;
1841 $url =~ s!/+$!!; # strip trailing slash
1842 my $r = read_all_remotes();
1843 my $existing = find_existing_remote($url, $r);
1844 if ($existing) {
1845 unless ($no_write) {
1846 print STDERR "Using existing ",
1847 "[svn-remote \"$existing\"]\n";
1849 $self->{repo_id} = $existing;
1850 } elsif ($_minimize_url) {
1851 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1852 $existing = find_existing_remote($min_url, $r);
1853 if ($existing) {
1854 unless ($no_write) {
1855 print STDERR "Using existing ",
1856 "[svn-remote \"$existing\"]\n";
1858 $self->{repo_id} = $existing;
1860 if ($min_url ne $url) {
1861 unless ($no_write) {
1862 print STDERR "Using higher level of URL: ",
1863 "$url => $min_url\n";
1865 my $old_path = $self->{path};
1866 $self->{path} = $url;
1867 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1868 if (length $old_path) {
1869 $self->{path} .= "/$old_path";
1871 $url = $min_url;
1874 my $orig_url;
1875 if (!$existing) {
1876 # verify that we aren't overwriting anything:
1877 $orig_url = eval {
1878 command_oneline('config', '--get',
1879 "svn-remote.$self->{repo_id}.url")
1881 if ($orig_url && ($orig_url ne $url)) {
1882 die "svn-remote.$self->{repo_id}.url already set: ",
1883 "$orig_url\nwanted to set to: $url\n";
1886 my ($xrepo_id, $xpath) = find_ref($self->refname);
1887 if (!$no_write && defined $xpath) {
1888 die "svn-remote.$xrepo_id.fetch already set to track ",
1889 "$xpath:", $self->refname, "\n";
1891 unless ($no_write) {
1892 command_noisy('config',
1893 "svn-remote.$self->{repo_id}.url", $url);
1894 $self->{path} =~ s{^/}{};
1895 command_noisy('config', '--add',
1896 "svn-remote.$self->{repo_id}.fetch",
1897 "$self->{path}:".$self->refname);
1899 $self->{url} = $url;
1902 sub find_by_url { # repos_root and, path are optional
1903 my ($class, $full_url, $repos_root, $path) = @_;
1905 return undef unless defined $full_url;
1906 remove_username($full_url);
1907 remove_username($repos_root) if defined $repos_root;
1908 my $remotes = read_all_remotes();
1909 if (defined $full_url && defined $repos_root && !defined $path) {
1910 $path = $full_url;
1911 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1913 foreach my $repo_id (keys %$remotes) {
1914 my $u = $remotes->{$repo_id}->{url} or next;
1915 remove_username($u);
1916 next if defined $repos_root && $repos_root ne $u;
1918 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1919 foreach my $t (qw/branches tags/) {
1920 foreach my $globspec (@{$remotes->{$repo_id}->{$t}}) {
1921 resolve_local_globs($u, $fetch, $globspec);
1924 my $p = $path;
1925 my $rwr = rewrite_root({repo_id => $repo_id});
1926 my $svm = $remotes->{$repo_id}->{svm}
1927 if defined $remotes->{$repo_id}->{svm};
1928 unless (defined $p) {
1929 $p = $full_url;
1930 my $z = $u;
1931 my $prefix = '';
1932 if ($rwr) {
1933 $z = $rwr;
1934 remove_username($z);
1935 } elsif (defined $svm) {
1936 $z = $svm->{source};
1937 $prefix = $svm->{replace};
1938 $prefix =~ s#^\Q$u\E(?:/|$)##;
1939 $prefix =~ s#/$##;
1941 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
1943 foreach my $f (keys %$fetch) {
1944 next if $f ne $p;
1945 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1948 undef;
1951 sub init {
1952 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1953 my $self = _new($class, $repo_id, $ref_id, $path);
1954 if (defined $url) {
1955 $self->init_remote_config($url, $no_write);
1957 $self;
1960 sub find_ref {
1961 my ($ref_id) = @_;
1962 foreach (command(qw/config -l/)) {
1963 next unless m!^svn-remote\.(.+)\.fetch=
1964 \s*/?(.*?)\s*:\s*(.+?)\s*$!x;
1965 my ($repo_id, $path, $ref) = ($1, $2, $3);
1966 if ($ref eq $ref_id) {
1967 $path = '' if ($path =~ m#^\./?#);
1968 return ($repo_id, $path);
1971 (undef, undef, undef);
1974 sub new {
1975 my ($class, $ref_id, $repo_id, $path) = @_;
1976 if (defined $ref_id && !defined $repo_id && !defined $path) {
1977 ($repo_id, $path) = find_ref($ref_id);
1978 if (!defined $repo_id) {
1979 die "Could not find a \"svn-remote.*.fetch\" key ",
1980 "in the repository configuration matching: ",
1981 "$ref_id\n";
1984 my $self = _new($class, $repo_id, $ref_id, $path);
1985 if (!defined $self->{path} || !length $self->{path}) {
1986 my $fetch = command_oneline('config', '--get',
1987 "svn-remote.$repo_id.fetch",
1988 ":$ref_id\$") or
1989 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1990 "\":$ref_id\$\" in config\n";
1991 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1993 $self->{url} = command_oneline('config', '--get',
1994 "svn-remote.$repo_id.url") or
1995 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1996 $self->rebuild;
1997 $self;
2000 sub refname {
2001 my ($refname) = $_[0]->{ref_id} ;
2003 # It cannot end with a slash /, we'll throw up on this because
2004 # SVN can't have directories with a slash in their name, either:
2005 if ($refname =~ m{/$}) {
2006 die "ref: '$refname' ends with a trailing slash, this is ",
2007 "not permitted by git nor Subversion\n";
2010 # It cannot have ASCII control character space, tilde ~, caret ^,
2011 # colon :, question-mark ?, asterisk *, space, or open bracket [
2012 # anywhere.
2014 # Additionally, % must be escaped because it is used for escaping
2015 # and we want our escaped refname to be reversible
2016 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
2018 # no slash-separated component can begin with a dot .
2019 # /.* becomes /%2E*
2020 $refname =~ s{/\.}{/%2E}g;
2022 # It cannot have two consecutive dots .. anywhere
2023 # .. becomes %2E%2E
2024 $refname =~ s{\.\.}{%2E%2E}g;
2026 return $refname;
2029 sub desanitize_refname {
2030 my ($refname) = @_;
2031 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
2032 return $refname;
2035 sub svm_uuid {
2036 my ($self) = @_;
2037 return $self->{svm}->{uuid} if $self->svm;
2038 $self->ra;
2039 unless ($self->{svm}) {
2040 die "SVM UUID not cached, and reading remotely failed\n";
2042 $self->{svm}->{uuid};
2045 sub svm {
2046 my ($self) = @_;
2047 return $self->{svm} if $self->{svm};
2048 my $svm;
2049 # see if we have it in our config, first:
2050 eval {
2051 my $section = "svn-remote.$self->{repo_id}";
2052 $svm = {
2053 source => tmp_config('--get', "$section.svm-source"),
2054 uuid => tmp_config('--get', "$section.svm-uuid"),
2055 replace => tmp_config('--get', "$section.svm-replace"),
2058 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
2059 $self->{svm} = $svm;
2061 $self->{svm};
2064 sub _set_svm_vars {
2065 my ($self, $ra) = @_;
2066 return $ra if $self->svm;
2068 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
2069 "(svm:source, svm:uuid) ",
2070 "from the following URLs:\n" );
2071 sub read_svm_props {
2072 my ($self, $ra, $path, $r) = @_;
2073 my $props = ($ra->get_dir($path, $r))[2];
2074 my $src = $props->{'svm:source'};
2075 my $uuid = $props->{'svm:uuid'};
2076 return undef if (!$src || !$uuid);
2078 chomp($src, $uuid);
2080 $uuid =~ m{^[0-9a-f\-]{30,}$}i
2081 or die "doesn't look right - svm:uuid is '$uuid'\n";
2083 # the '!' is used to mark the repos_root!/relative/path
2084 $src =~ s{/?!/?}{/};
2085 $src =~ s{/+$}{}; # no trailing slashes please
2086 # username is of no interest
2087 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
2089 my $replace = $ra->{url};
2090 $replace .= "/$path" if length $path;
2092 my $section = "svn-remote.$self->{repo_id}";
2093 tmp_config("$section.svm-source", $src);
2094 tmp_config("$section.svm-replace", $replace);
2095 tmp_config("$section.svm-uuid", $uuid);
2096 $self->{svm} = {
2097 source => $src,
2098 uuid => $uuid,
2099 replace => $replace
2103 my $r = $ra->get_latest_revnum;
2104 my $path = $self->{path};
2105 my %tried;
2106 while (length $path) {
2107 unless ($tried{"$self->{url}/$path"}) {
2108 return $ra if $self->read_svm_props($ra, $path, $r);
2109 $tried{"$self->{url}/$path"} = 1;
2111 $path =~ s#/?[^/]+$##;
2113 die "Path: '$path' should be ''\n" if $path ne '';
2114 return $ra if $self->read_svm_props($ra, $path, $r);
2115 $tried{"$self->{url}/$path"} = 1;
2117 if ($ra->{repos_root} eq $self->{url}) {
2118 die @err, (map { " $_\n" } keys %tried), "\n";
2121 # nope, make sure we're connected to the repository root:
2122 my $ok;
2123 my @tried_b;
2124 $path = $ra->{svn_path};
2125 $ra = Git::SVN::Ra->new($ra->{repos_root});
2126 while (length $path) {
2127 unless ($tried{"$ra->{url}/$path"}) {
2128 $ok = $self->read_svm_props($ra, $path, $r);
2129 last if $ok;
2130 $tried{"$ra->{url}/$path"} = 1;
2132 $path =~ s#/?[^/]+$##;
2134 die "Path: '$path' should be ''\n" if $path ne '';
2135 $ok ||= $self->read_svm_props($ra, $path, $r);
2136 $tried{"$ra->{url}/$path"} = 1;
2137 if (!$ok) {
2138 die @err, (map { " $_\n" } keys %tried), "\n";
2140 Git::SVN::Ra->new($self->{url});
2143 sub svnsync {
2144 my ($self) = @_;
2145 return $self->{svnsync} if $self->{svnsync};
2147 if ($self->no_metadata) {
2148 die "Can't have both 'noMetadata' and ",
2149 "'useSvnsyncProps' options set!\n";
2151 if ($self->rewrite_root) {
2152 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
2153 "options set!\n";
2156 my $svnsync;
2157 # see if we have it in our config, first:
2158 eval {
2159 my $section = "svn-remote.$self->{repo_id}";
2161 my $url = tmp_config('--get', "$section.svnsync-url");
2162 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2163 die "doesn't look right - svn:sync-from-url is '$url'\n";
2165 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
2166 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2167 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2169 $svnsync = { url => $url, uuid => $uuid }
2171 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
2172 return $self->{svnsync} = $svnsync;
2175 my $err = "useSvnsyncProps set, but failed to read " .
2176 "svnsync property: svn:sync-from-";
2177 my $rp = $self->ra->rev_proplist(0);
2179 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
2180 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2181 die "doesn't look right - svn:sync-from-url is '$url'\n";
2183 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
2184 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2185 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2187 my $section = "svn-remote.$self->{repo_id}";
2188 tmp_config('--add', "$section.svnsync-uuid", $uuid);
2189 tmp_config('--add', "$section.svnsync-url", $url);
2190 return $self->{svnsync} = { url => $url, uuid => $uuid };
2193 # this allows us to memoize our SVN::Ra UUID locally and avoid a
2194 # remote lookup (useful for 'git svn log').
2195 sub ra_uuid {
2196 my ($self) = @_;
2197 unless ($self->{ra_uuid}) {
2198 my $key = "svn-remote.$self->{repo_id}.uuid";
2199 my $uuid = eval { tmp_config('--get', $key) };
2200 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/i) {
2201 $self->{ra_uuid} = $uuid;
2202 } else {
2203 die "ra_uuid called without URL\n" unless $self->{url};
2204 $self->{ra_uuid} = $self->ra->get_uuid;
2205 tmp_config('--add', $key, $self->{ra_uuid});
2208 $self->{ra_uuid};
2211 sub _set_repos_root {
2212 my ($self, $repos_root) = @_;
2213 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2214 $repos_root ||= $self->ra->{repos_root};
2215 tmp_config($k, $repos_root);
2216 $repos_root;
2219 sub repos_root {
2220 my ($self) = @_;
2221 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2222 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
2225 sub ra {
2226 my ($self) = shift;
2227 my $ra = Git::SVN::Ra->new($self->{url});
2228 $self->_set_repos_root($ra->{repos_root});
2229 if ($self->use_svm_props && !$self->{svm}) {
2230 if ($self->no_metadata) {
2231 die "Can't have both 'noMetadata' and ",
2232 "'useSvmProps' options set!\n";
2233 } elsif ($self->use_svnsync_props) {
2234 die "Can't have both 'useSvnsyncProps' and ",
2235 "'useSvmProps' options set!\n";
2237 $ra = $self->_set_svm_vars($ra);
2238 $self->{-want_revprops} = 1;
2240 $ra;
2243 # prop_walk(PATH, REV, SUB)
2244 # -------------------------
2245 # Recursively traverse PATH at revision REV and invoke SUB for each
2246 # directory that contains a SVN property. SUB will be invoked as
2247 # follows: &SUB(gs, path, props); where `gs' is this instance of
2248 # Git::SVN, `path' the path to the directory where the properties
2249 # `props' were found. The `path' will be relative to point of checkout,
2250 # that is, if url://repo/trunk is the current Git branch, and that
2251 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
2252 # as `path' (note the trailing `/').
2253 sub prop_walk {
2254 my ($self, $path, $rev, $sub) = @_;
2256 $path =~ s#^/##;
2257 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2258 $path =~ s#^/*#/#g;
2259 my $p = $path;
2260 # Strip the irrelevant part of the path.
2261 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2262 # Ensure the path is terminated by a `/'.
2263 $p =~ s#/*$#/#;
2265 # The properties contain all the internal SVN stuff nobody
2266 # (usually) cares about.
2267 my $interesting_props = 0;
2268 foreach (keys %{$props}) {
2269 # If it doesn't start with `svn:', it must be a
2270 # user-defined property.
2271 ++$interesting_props and next if $_ !~ /^svn:/;
2272 # FIXME: Fragile, if SVN adds new public properties,
2273 # this needs to be updated.
2274 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2275 |eol-style|mime-type
2276 |externals|needs-lock)$/x;
2278 &$sub($self, $p, $props) if $interesting_props;
2280 foreach (sort keys %$dirent) {
2281 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
2282 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
2286 sub last_rev { ($_[0]->last_rev_commit)[0] }
2287 sub last_commit { ($_[0]->last_rev_commit)[1] }
2289 # returns the newest SVN revision number and newest commit SHA1
2290 sub last_rev_commit {
2291 my ($self) = @_;
2292 if (defined $self->{last_rev} && defined $self->{last_commit}) {
2293 return ($self->{last_rev}, $self->{last_commit});
2295 my $c = ::verify_ref($self->refname.'^0');
2296 if ($c && !$self->use_svm_props && !$self->no_metadata) {
2297 my $rev = (::cmt_metadata($c))[1];
2298 if (defined $rev) {
2299 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2300 return ($rev, $c);
2303 my $map_path = $self->map_path;
2304 unless (-e $map_path) {
2305 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2306 return (undef, undef);
2308 my ($rev, $commit) = $self->rev_map_max(1);
2309 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2310 return ($rev, $commit);
2313 sub get_fetch_range {
2314 my ($self, $min, $max) = @_;
2315 $max ||= $self->ra->get_latest_revnum;
2316 $min ||= $self->rev_map_max;
2317 (++$min, $max);
2320 sub tmp_config {
2321 my (@args) = @_;
2322 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2323 my $config = "$ENV{GIT_DIR}/svn/.metadata";
2324 if (! -f $config && -f $old_def_config) {
2325 rename $old_def_config, $config or
2326 die "Failed rename $old_def_config => $config: $!\n";
2328 my $old_config = $ENV{GIT_CONFIG};
2329 $ENV{GIT_CONFIG} = $config;
2330 $@ = undef;
2331 my @ret = eval {
2332 unless (-f $config) {
2333 mkfile($config);
2334 open my $fh, '>', $config or
2335 die "Can't open $config: $!\n";
2336 print $fh "; This file is used internally by ",
2337 "git-svn\n" or die
2338 "Couldn't write to $config: $!\n";
2339 print $fh "; You should not have to edit it\n" or
2340 die "Couldn't write to $config: $!\n";
2341 close $fh or die "Couldn't close $config: $!\n";
2343 command('config', @args);
2345 my $err = $@;
2346 if (defined $old_config) {
2347 $ENV{GIT_CONFIG} = $old_config;
2348 } else {
2349 delete $ENV{GIT_CONFIG};
2351 die $err if $err;
2352 wantarray ? @ret : $ret[0];
2355 sub tmp_index_do {
2356 my ($self, $sub) = @_;
2357 my $old_index = $ENV{GIT_INDEX_FILE};
2358 $ENV{GIT_INDEX_FILE} = $self->{index};
2359 $@ = undef;
2360 my @ret = eval {
2361 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2362 mkpath([$dir]) unless -d $dir;
2363 &$sub;
2365 my $err = $@;
2366 if (defined $old_index) {
2367 $ENV{GIT_INDEX_FILE} = $old_index;
2368 } else {
2369 delete $ENV{GIT_INDEX_FILE};
2371 die $err if $err;
2372 wantarray ? @ret : $ret[0];
2375 sub assert_index_clean {
2376 my ($self, $treeish) = @_;
2378 $self->tmp_index_do(sub {
2379 command_noisy('read-tree', $treeish) unless -e $self->{index};
2380 my $x = command_oneline('write-tree');
2381 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2382 /^tree ($::sha1)/mo);
2383 return if $y eq $x;
2385 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2386 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2387 command_noisy('read-tree', $treeish);
2388 $x = command_oneline('write-tree');
2389 if ($y ne $x) {
2390 ::fatal "trees ($treeish) $y != $x\n",
2391 "Something is seriously wrong...";
2396 sub get_commit_parents {
2397 my ($self, $log_entry) = @_;
2398 my (%seen, @ret, @tmp);
2399 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2400 if (my $ip = $self->{inject_parents}) {
2401 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2402 push @tmp, $commit;
2405 if (my $cur = ::verify_ref($self->refname.'^0')) {
2406 push @tmp, $cur;
2408 if (my $ipd = $self->{inject_parents_dcommit}) {
2409 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2410 push @tmp, @$commit;
2413 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2414 while (my $p = shift @tmp) {
2415 next if $seen{$p};
2416 $seen{$p} = 1;
2417 push @ret, $p;
2418 # MAXPARENT is defined to 16 in commit-tree.c:
2419 last if @ret >= 16;
2421 if (@tmp) {
2422 die "r$log_entry->{revision}: No room for parents:\n\t",
2423 join("\n\t", @tmp), "\n";
2425 @ret;
2428 sub rewrite_root {
2429 my ($self) = @_;
2430 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2431 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2432 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2433 if ($rwr) {
2434 $rwr =~ s#/+$##;
2435 if ($rwr !~ m#^[a-z\+]+://#) {
2436 die "$rwr is not a valid URL (key: $k)\n";
2439 $self->{-rewrite_root} = $rwr;
2442 sub metadata_url {
2443 my ($self) = @_;
2444 ($self->rewrite_root || $self->{url}) .
2445 (length $self->{path} ? '/' . $self->{path} : '');
2448 sub full_url {
2449 my ($self) = @_;
2450 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2454 sub set_commit_header_env {
2455 my ($log_entry) = @_;
2456 my %env;
2457 foreach my $ned (qw/NAME EMAIL DATE/) {
2458 foreach my $ac (qw/AUTHOR COMMITTER/) {
2459 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2463 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2464 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2465 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2467 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2468 ? $log_entry->{commit_name}
2469 : $log_entry->{name};
2470 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2471 ? $log_entry->{commit_email}
2472 : $log_entry->{email};
2473 \%env;
2476 sub restore_commit_header_env {
2477 my ($env) = @_;
2478 foreach my $ned (qw/NAME EMAIL DATE/) {
2479 foreach my $ac (qw/AUTHOR COMMITTER/) {
2480 my $k = "GIT_${ac}_${ned}";
2481 if (defined $env->{$k}) {
2482 $ENV{$k} = $env->{$k};
2483 } else {
2484 delete $ENV{$k};
2490 sub gc {
2491 command_noisy('gc', '--auto');
2494 sub do_git_commit {
2495 my ($self, $log_entry) = @_;
2496 my $lr = $self->last_rev;
2497 if (defined $lr && $lr >= $log_entry->{revision}) {
2498 die "Last fetched revision of ", $self->refname,
2499 " was r$lr, but we are about to fetch: ",
2500 "r$log_entry->{revision}!\n";
2502 if (my $c = $self->rev_map_get($log_entry->{revision})) {
2503 croak "$log_entry->{revision} = $c already exists! ",
2504 "Why are we refetching it?\n";
2506 my $old_env = set_commit_header_env($log_entry);
2507 my $tree = $log_entry->{tree};
2508 if (!defined $tree) {
2509 $tree = $self->tmp_index_do(sub {
2510 command_oneline('write-tree') });
2512 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2514 my @exec = ('git', 'commit-tree', $tree);
2515 foreach ($self->get_commit_parents($log_entry)) {
2516 push @exec, '-p', $_;
2518 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2519 or croak $!;
2520 binmode $msg_fh;
2522 # we always get UTF-8 from SVN, but we may want our commits in
2523 # a different encoding.
2524 if (my $enc = Git::config('i18n.commitencoding')) {
2525 require Encode;
2526 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
2528 print $msg_fh $log_entry->{log} or croak $!;
2529 restore_commit_header_env($old_env);
2530 unless ($self->no_metadata) {
2531 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2532 or croak $!;
2534 $msg_fh->flush == 0 or croak $!;
2535 close $msg_fh or croak $!;
2536 chomp(my $commit = do { local $/; <$out_fh> });
2537 close $out_fh or croak $!;
2538 waitpid $pid, 0;
2539 croak $? if $?;
2540 if ($commit !~ /^$::sha1$/o) {
2541 die "Failed to commit, invalid sha1: $commit\n";
2544 $self->rev_map_set($log_entry->{revision}, $commit, 1);
2546 $self->{last_rev} = $log_entry->{revision};
2547 $self->{last_commit} = $commit;
2548 print "r$log_entry->{revision}" unless $::_q > 1;
2549 if (defined $log_entry->{svm_revision}) {
2550 print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
2551 $self->rev_map_set($log_entry->{svm_revision}, $commit,
2552 0, $self->svm_uuid);
2554 print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
2555 if (--$_gc_nr == 0) {
2556 $_gc_nr = $_gc_period;
2557 gc();
2559 return $commit;
2562 sub match_paths {
2563 my ($self, $paths, $r) = @_;
2564 return 1 if $self->{path} eq '';
2565 if (my $path = $paths->{"/$self->{path}"}) {
2566 return ($path->{action} eq 'D') ? 0 : 1;
2568 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
2569 if (grep /$self->{path_regex}/, keys %$paths) {
2570 return 1;
2572 my $c = '';
2573 foreach (split m#/#, $self->{path}) {
2574 $c .= "/$_";
2575 next unless ($paths->{$c} &&
2576 ($paths->{$c}->{action} =~ /^[AR]$/));
2577 if ($self->ra->check_path($self->{path}, $r) ==
2578 $SVN::Node::dir) {
2579 return 1;
2582 return 0;
2585 sub find_parent_branch {
2586 my ($self, $paths, $rev) = @_;
2587 return undef unless $self->follow_parent;
2588 unless (defined $paths) {
2589 my $err_handler = $SVN::Error::handler;
2590 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2591 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1,
2592 sub { $paths = $_[0] });
2593 $SVN::Error::handler = $err_handler;
2595 return undef unless defined $paths;
2597 # look for a parent from another branch:
2598 my @b_path_components = split m#/#, $self->{path};
2599 my @a_path_components;
2600 my $i;
2601 while (@b_path_components) {
2602 $i = $paths->{'/'.join('/', @b_path_components)};
2603 last if $i && defined $i->{copyfrom_path};
2604 unshift(@a_path_components, pop(@b_path_components));
2606 return undef unless defined $i && defined $i->{copyfrom_path};
2607 my $branch_from = $i->{copyfrom_path};
2608 if (@a_path_components) {
2609 print STDERR "branch_from: $branch_from => ";
2610 $branch_from .= '/'.join('/', @a_path_components);
2611 print STDERR $branch_from, "\n";
2613 my $r = $i->{copyfrom_rev};
2614 my $repos_root = $self->ra->{repos_root};
2615 my $url = $self->ra->{url};
2616 my $new_url = $url . $branch_from;
2617 print STDERR "Found possible branch point: ",
2618 "$new_url => ", $self->full_url, ", $r\n";
2619 $branch_from =~ s#^/##;
2620 my $gs = $self->other_gs($new_url, $url,
2621 $branch_from, $r, $self->{ref_id});
2622 my ($r0, $parent) = $gs->find_rev_before($r, 1);
2624 my ($base, $head);
2625 if (!defined $r0 || !defined $parent) {
2626 ($base, $head) = parse_revision_argument(0, $r);
2627 } else {
2628 if ($r0 < $r) {
2629 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
2630 0, 1, sub { $base = $_[1] - 1 });
2633 if (defined $base && $base <= $r) {
2634 $gs->fetch($base, $r);
2636 ($r0, $parent) = $gs->find_rev_before($r, 1);
2638 if (defined $r0 && defined $parent) {
2639 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
2640 my $ed;
2641 if ($self->ra->can_do_switch) {
2642 $self->assert_index_clean($parent);
2643 print STDERR "Following parent with do_switch\n";
2644 # do_switch works with svn/trunk >= r22312, but that
2645 # is not included with SVN 1.4.3 (the latest version
2646 # at the moment), so we can't rely on it
2647 $self->{last_rev} = $r0;
2648 $self->{last_commit} = $parent;
2649 $ed = SVN::Git::Fetcher->new($self, $gs->{path});
2650 $gs->ra->gs_do_switch($r0, $rev, $gs,
2651 $self->full_url, $ed)
2652 or die "SVN connection failed somewhere...\n";
2653 } elsif ($self->ra->trees_match($new_url, $r0,
2654 $self->full_url, $rev)) {
2655 print STDERR "Trees match:\n",
2656 " $new_url\@$r0\n",
2657 " ${\$self->full_url}\@$rev\n",
2658 "Following parent with no changes\n";
2659 $self->tmp_index_do(sub {
2660 command_noisy('read-tree', $parent);
2662 $self->{last_commit} = $parent;
2663 } else {
2664 print STDERR "Following parent with do_update\n";
2665 $ed = SVN::Git::Fetcher->new($self);
2666 $self->ra->gs_do_update($rev, $rev, $self, $ed)
2667 or die "SVN connection failed somewhere...\n";
2669 print STDERR "Successfully followed parent\n";
2670 return $self->make_log_entry($rev, [$parent], $ed);
2672 return undef;
2675 sub do_fetch {
2676 my ($self, $paths, $rev) = @_;
2677 my $ed;
2678 my ($last_rev, @parents);
2679 if (my $lc = $self->last_commit) {
2680 # we can have a branch that was deleted, then re-added
2681 # under the same name but copied from another path, in
2682 # which case we'll have multiple parents (we don't
2683 # want to break the original ref, nor lose copypath info):
2684 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2685 push @{$log_entry->{parents}}, $lc;
2686 return $log_entry;
2688 $ed = SVN::Git::Fetcher->new($self);
2689 $last_rev = $self->{last_rev};
2690 $ed->{c} = $lc;
2691 @parents = ($lc);
2692 } else {
2693 $last_rev = $rev;
2694 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2695 return $log_entry;
2697 $ed = SVN::Git::Fetcher->new($self);
2699 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2700 die "SVN connection failed somewhere...\n";
2702 $self->make_log_entry($rev, \@parents, $ed);
2705 sub get_untracked {
2706 my ($self, $ed) = @_;
2707 my @out;
2708 my $h = $ed->{empty};
2709 foreach (sort keys %$h) {
2710 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2711 push @out, " $act: " . uri_encode($_);
2712 warn "W: $act: $_\n";
2714 foreach my $t (qw/dir_prop file_prop/) {
2715 $h = $ed->{$t} or next;
2716 foreach my $path (sort keys %$h) {
2717 my $ppath = $path eq '' ? '.' : $path;
2718 foreach my $prop (sort keys %{$h->{$path}}) {
2719 next if $SKIP_PROP{$prop};
2720 my $v = $h->{$path}->{$prop};
2721 my $t_ppath_prop = "$t: " .
2722 uri_encode($ppath) . ' ' .
2723 uri_encode($prop);
2724 if (defined $v) {
2725 push @out, " +$t_ppath_prop " .
2726 uri_encode($v);
2727 } else {
2728 push @out, " -$t_ppath_prop";
2733 foreach my $t (qw/absent_file absent_directory/) {
2734 $h = $ed->{$t} or next;
2735 foreach my $parent (sort keys %$h) {
2736 foreach my $path (sort @{$h->{$parent}}) {
2737 push @out, " $t: " .
2738 uri_encode("$parent/$path");
2739 warn "W: $t: $parent/$path ",
2740 "Insufficient permissions?\n";
2744 \@out;
2747 # parse_svn_date(DATE)
2748 # --------------------
2749 # Given a date (in UTC) from Subversion, return a string in the format
2750 # "<TZ Offset> <local date/time>" that Git will use.
2752 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
2753 # is true we'll convert it to the local timezone instead.
2754 sub parse_svn_date {
2755 my $date = shift || return '+0000 1970-01-01 00:00:00';
2756 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2757 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
2758 croak "Unable to parse date: $date\n";
2759 my $parsed_date; # Set next.
2761 if ($Git::SVN::_localtime) {
2762 # Translate the Subversion datetime to an epoch time.
2763 # Begin by switching ourselves to $date's timezone, UTC.
2764 my $old_env_TZ = $ENV{TZ};
2765 $ENV{TZ} = 'UTC';
2767 my $epoch_in_UTC =
2768 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
2770 # Determine our local timezone (including DST) at the
2771 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
2772 # value of TZ, if any, at the time we were run.
2773 if (defined $Git::SVN::Log::TZ) {
2774 $ENV{TZ} = $Git::SVN::Log::TZ;
2775 } else {
2776 delete $ENV{TZ};
2779 my $our_TZ =
2780 POSIX::strftime('%Z', $S, $M, $H, $d, $m - 1, $Y - 1900);
2782 # This converts $epoch_in_UTC into our local timezone.
2783 my ($sec, $min, $hour, $mday, $mon, $year,
2784 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
2786 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
2787 $our_TZ, $year + 1900, $mon + 1,
2788 $mday, $hour, $min, $sec);
2790 # Reset us to the timezone in effect when we entered
2791 # this routine.
2792 if (defined $old_env_TZ) {
2793 $ENV{TZ} = $old_env_TZ;
2794 } else {
2795 delete $ENV{TZ};
2797 } else {
2798 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
2801 return $parsed_date;
2804 sub other_gs {
2805 my ($self, $new_url, $url,
2806 $branch_from, $r, $old_ref_id) = @_;
2807 my $gs = Git::SVN->find_by_url($new_url, $url, $branch_from);
2808 unless ($gs) {
2809 my $ref_id = $old_ref_id;
2810 $ref_id =~ s/\@\d+$//;
2811 $ref_id .= "\@$r";
2812 # just grow a tail if we're not unique enough :x
2813 $ref_id .= '-' while find_ref($ref_id);
2814 print STDERR "Initializing parent: $ref_id\n";
2815 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
2816 if ($u =~ s#^\Q$url\E(/|$)##) {
2817 $p = $u;
2818 $u = $url;
2819 $repo_id = $self->{repo_id};
2821 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
2826 sub call_authors_prog {
2827 my ($orig_author) = @_;
2828 my $author = `$::_authors_prog $orig_author`;
2829 if ($? != 0) {
2830 die "$::_authors_prog failed with exit code $?\n"
2832 if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
2833 my ($name, $email) = ($1, $2);
2834 $email = undef if length $2 == 0;
2835 return [$name, $email];
2836 } else {
2837 die "Author: $orig_author: $::_authors_prog returned "
2838 . "invalid author format: $author\n";
2842 sub check_author {
2843 my ($author) = @_;
2844 if (!defined $author || length $author == 0) {
2845 $author = '(no author)';
2847 if (!defined $::users{$author}) {
2848 if (defined $::_authors_prog) {
2849 $::users{$author} = call_authors_prog($author);
2850 } elsif (defined $::_authors) {
2851 die "Author: $author not defined in $::_authors file\n";
2854 $author;
2857 sub make_log_entry {
2858 my ($self, $rev, $parents, $ed) = @_;
2859 my $untracked = $self->get_untracked($ed);
2861 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
2862 print $un "r$rev\n" or croak $!;
2863 print $un $_, "\n" foreach @$untracked;
2864 my %log_entry = ( parents => $parents || [], revision => $rev,
2865 log => '');
2867 my $headrev;
2868 my $logged = delete $self->{logged_rev_props};
2869 if (!$logged || $self->{-want_revprops}) {
2870 my $rp = $self->ra->rev_proplist($rev);
2871 foreach (sort keys %$rp) {
2872 my $v = $rp->{$_};
2873 if (/^svn:(author|date|log)$/) {
2874 $log_entry{$1} = $v;
2875 } elsif ($_ eq 'svm:headrev') {
2876 $headrev = $v;
2877 } else {
2878 print $un " rev_prop: ", uri_encode($_), ' ',
2879 uri_encode($v), "\n";
2882 } else {
2883 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
2885 close $un or croak $!;
2887 $log_entry{date} = parse_svn_date($log_entry{date});
2888 $log_entry{log} .= "\n";
2889 my $author = $log_entry{author} = check_author($log_entry{author});
2890 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
2891 : ($author, undef);
2893 my ($commit_name, $commit_email) = ($name, $email);
2894 if ($_use_log_author) {
2895 my $name_field;
2896 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
2897 $name_field = $1;
2898 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
2899 $name_field = $1;
2901 if (!defined $name_field) {
2902 if (!defined $email) {
2903 $email = $name;
2905 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
2906 ($name, $email) = ($1, $2);
2907 } elsif ($name_field =~ /(.*)@/) {
2908 ($name, $email) = ($1, $name_field);
2909 } else {
2910 ($name, $email) = ($name_field, $name_field);
2913 if (defined $headrev && $self->use_svm_props) {
2914 if ($self->rewrite_root) {
2915 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2916 "options set!\n";
2918 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$}i;
2919 # we don't want "SVM: initializing mirror for junk" ...
2920 return undef if $r == 0;
2921 my $svm = $self->svm;
2922 if ($uuid ne $svm->{uuid}) {
2923 die "UUID mismatch on SVM path:\n",
2924 "expected: $svm->{uuid}\n",
2925 " got: $uuid\n";
2927 my $full_url = $self->full_url;
2928 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2929 die "Failed to replace '$svm->{replace}' with ",
2930 "'$svm->{source}' in $full_url\n";
2931 # throw away username for storing in records
2932 remove_username($full_url);
2933 $log_entry{metadata} = "$full_url\@$r $uuid";
2934 $log_entry{svm_revision} = $r;
2935 $email ||= "$author\@$uuid";
2936 $commit_email ||= "$author\@$uuid";
2937 } elsif ($self->use_svnsync_props) {
2938 my $full_url = $self->svnsync->{url};
2939 $full_url .= "/$self->{path}" if length $self->{path};
2940 remove_username($full_url);
2941 my $uuid = $self->svnsync->{uuid};
2942 $log_entry{metadata} = "$full_url\@$rev $uuid";
2943 $email ||= "$author\@$uuid";
2944 $commit_email ||= "$author\@$uuid";
2945 } else {
2946 my $url = $self->metadata_url;
2947 remove_username($url);
2948 $log_entry{metadata} = "$url\@$rev " .
2949 $self->ra->get_uuid;
2950 $email ||= "$author\@" . $self->ra->get_uuid;
2951 $commit_email ||= "$author\@" . $self->ra->get_uuid;
2953 $log_entry{name} = $name;
2954 $log_entry{email} = $email;
2955 $log_entry{commit_name} = $commit_name;
2956 $log_entry{commit_email} = $commit_email;
2957 \%log_entry;
2960 sub fetch {
2961 my ($self, $min_rev, $max_rev, @parents) = @_;
2962 my ($last_rev, $last_commit) = $self->last_rev_commit;
2963 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2964 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2967 sub set_tree_cb {
2968 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2969 $self->{inject_parents} = { $rev => $tree };
2970 $self->fetch(undef, undef);
2973 sub set_tree {
2974 my ($self, $tree) = (shift, shift);
2975 my $log_entry = ::get_commit_entry($tree);
2976 unless ($self->{last_rev}) {
2977 ::fatal("Must have an existing revision to commit");
2979 my %ed_opts = ( r => $self->{last_rev},
2980 log => $log_entry->{log},
2981 ra => $self->ra,
2982 tree_a => $self->{last_commit},
2983 tree_b => $tree,
2984 editor_cb => sub {
2985 $self->set_tree_cb($log_entry, $tree, @_) },
2986 svn_path => $self->{path} );
2987 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2988 print "No changes\nr$self->{last_rev} = $tree\n";
2992 sub rebuild_from_rev_db {
2993 my ($self, $path) = @_;
2994 my $r = -1;
2995 open my $fh, '<', $path or croak "open: $!";
2996 binmode $fh or croak "binmode: $!";
2997 while (<$fh>) {
2998 length($_) == 41 or croak "inconsistent size in ($_) != 41";
2999 chomp($_);
3000 ++$r;
3001 next if $_ eq ('0' x 40);
3002 $self->rev_map_set($r, $_);
3003 print "r$r = $_\n";
3005 close $fh or croak "close: $!";
3006 unlink $path or croak "unlink: $!";
3009 sub rebuild {
3010 my ($self) = @_;
3011 my $map_path = $self->map_path;
3012 my $partial = (-e $map_path && ! -z $map_path);
3013 return unless ::verify_ref($self->refname.'^0');
3014 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
3015 my $rev_db = $self->rev_db_path;
3016 $self->rebuild_from_rev_db($rev_db);
3017 if ($self->use_svm_props) {
3018 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
3019 $self->rebuild_from_rev_db($svm_rev_db);
3021 $self->unlink_rev_db_symlink;
3022 return;
3024 print "Rebuilding $map_path ...\n" if (!$partial);
3025 my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
3026 (undef, undef));
3027 my ($log, $ctx) =
3028 command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
3029 ($head ? "$head.." : "") . $self->refname,
3030 '--');
3031 my $metadata_url = $self->metadata_url;
3032 remove_username($metadata_url);
3033 my $svn_uuid = $self->ra_uuid;
3034 my $c;
3035 while (<$log>) {
3036 if ( m{^commit ($::sha1)$} ) {
3037 $c = $1;
3038 next;
3040 next unless s{^\s*(git-svn-id:)}{$1};
3041 my ($url, $rev, $uuid) = ::extract_metadata($_);
3042 remove_username($url);
3044 # ignore merges (from set-tree)
3045 next if (!defined $rev || !$uuid);
3047 # if we merged or otherwise started elsewhere, this is
3048 # how we break out of it
3049 if (($uuid ne $svn_uuid) ||
3050 ($metadata_url && $url && ($url ne $metadata_url))) {
3051 next;
3053 if ($partial && $head) {
3054 print "Partial-rebuilding $map_path ...\n";
3055 print "Currently at $base_rev = $head\n";
3056 $head = undef;
3059 $self->rev_map_set($rev, $c);
3060 print "r$rev = $c\n";
3062 command_close_pipe($log, $ctx);
3063 print "Done rebuilding $map_path\n" if (!$partial || !$head);
3064 my $rev_db_path = $self->rev_db_path;
3065 if (-f $self->rev_db_path) {
3066 unlink $self->rev_db_path or croak "unlink: $!";
3068 $self->unlink_rev_db_symlink;
3071 # rev_map:
3072 # Tie::File seems to be prone to offset errors if revisions get sparse,
3073 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
3074 # one of my favorite modules is out :< Next up would be one of the DBM
3075 # modules, but I'm not sure which is most portable...
3077 # This is the replacement for the rev_db format, which was too big
3078 # and inefficient for large repositories with a lot of sparse history
3079 # (mainly tags)
3081 # The format is this:
3082 # - 24 bytes for every record,
3083 # * 4 bytes for the integer representing an SVN revision number
3084 # * 20 bytes representing the sha1 of a git commit
3085 # - No empty padding records like the old format
3086 # (except the last record, which can be overwritten)
3087 # - new records are written append-only since SVN revision numbers
3088 # increase monotonically
3089 # - lookups on SVN revision number are done via a binary search
3090 # - Piping the file to xxd -c24 is a good way of dumping it for
3091 # viewing or editing (piped back through xxd -r), should the need
3092 # ever arise.
3093 # - The last record can be padding revision with an all-zero sha1
3094 # This is used to optimize fetch performance when using multiple
3095 # "fetch" directives in .git/config
3097 # These files are disposable unless noMetadata or useSvmProps is set
3099 sub _rev_map_set {
3100 my ($fh, $rev, $commit) = @_;
3102 binmode $fh or croak "binmode: $!";
3103 my $size = (stat($fh))[7];
3104 ($size % 24) == 0 or croak "inconsistent size: $size";
3106 my $wr_offset = 0;
3107 if ($size > 0) {
3108 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3109 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
3110 $read == 24 or croak "read only $read bytes (!= 24)";
3111 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
3112 if ($last_commit eq ('0' x40)) {
3113 if ($size >= 48) {
3114 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3115 $read = sysread($fh, $buf, 24) or
3116 croak "read: $!";
3117 $read == 24 or
3118 croak "read only $read bytes (!= 24)";
3119 ($last_rev, $last_commit) =
3120 unpack(rev_map_fmt, $buf);
3121 if ($last_commit eq ('0' x40)) {
3122 croak "inconsistent .rev_map\n";
3125 if ($last_rev >= $rev) {
3126 croak "last_rev is higher!: $last_rev >= $rev";
3128 $wr_offset = -24;
3131 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
3132 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
3133 croak "write: $!";
3136 sub _rev_map_reset {
3137 my ($fh, $rev, $commit) = @_;
3138 my $c = _rev_map_get($fh, $rev);
3139 $c eq $commit or die "_rev_map_reset(@_) commit $c does not match!\n";
3140 my $offset = sysseek($fh, 0, SEEK_CUR) or croak "seek: $!";
3141 truncate $fh, $offset or croak "truncate: $!";
3144 sub mkfile {
3145 my ($path) = @_;
3146 unless (-e $path) {
3147 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
3148 mkpath([$dir]) unless -d $dir;
3149 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
3150 close $fh or die "Couldn't close (create) $path: $!\n";
3154 sub rev_map_set {
3155 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
3156 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
3157 my $db = $self->map_path($uuid);
3158 my $db_lock = "$db.lock";
3159 my $sig;
3160 $update_ref ||= 0;
3161 if ($update_ref) {
3162 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3163 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
3165 mkfile($db);
3167 $LOCKFILES{$db_lock} = 1;
3168 my $sync;
3169 # both of these options make our .rev_db file very, very important
3170 # and we can't afford to lose it because rebuild() won't work
3171 if ($self->use_svm_props || $self->no_metadata) {
3172 $sync = 1;
3173 copy($db, $db_lock) or die "rev_map_set(@_): ",
3174 "Failed to copy: ",
3175 "$db => $db_lock ($!)\n";
3176 } else {
3177 rename $db, $db_lock or die "rev_map_set(@_): ",
3178 "Failed to rename: ",
3179 "$db => $db_lock ($!)\n";
3182 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
3183 or croak "Couldn't open $db_lock: $!\n";
3184 $update_ref eq 'reset' ? _rev_map_reset($fh, $rev, $commit) :
3185 _rev_map_set($fh, $rev, $commit);
3186 if ($sync) {
3187 $fh->flush or die "Couldn't flush $db_lock: $!\n";
3188 $fh->sync or die "Couldn't sync $db_lock: $!\n";
3190 close $fh or croak $!;
3191 if ($update_ref) {
3192 $_head = $self;
3193 my $note = "";
3194 $note = " ($update_ref)" if ($update_ref !~ /^\d*$/);
3195 command_noisy('update-ref', '-m', "r$rev$note",
3196 $self->refname, $commit);
3198 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
3199 "$db_lock => $db ($!)\n";
3200 delete $LOCKFILES{$db_lock};
3201 if ($update_ref) {
3202 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3203 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
3204 kill $sig, $$ if defined $sig;
3208 # If want_commit, this will return an array of (rev, commit) where
3209 # commit _must_ be a valid commit in the archive.
3210 # Otherwise, it'll return the max revision (whether or not the
3211 # commit is valid or just a 0x40 placeholder).
3212 sub rev_map_max {
3213 my ($self, $want_commit) = @_;
3214 $self->rebuild;
3215 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
3216 $want_commit ? ($r, $c) : $r;
3219 sub rev_map_max_norebuild {
3220 my ($self, $want_commit) = @_;
3221 my $map_path = $self->map_path;
3222 stat $map_path or return $want_commit ? (0, undef) : 0;
3223 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3224 binmode $fh or croak "binmode: $!";
3225 my $size = (stat($fh))[7];
3226 ($size % 24) == 0 or croak "inconsistent size: $size";
3228 if ($size == 0) {
3229 close $fh or croak "close: $!";
3230 return $want_commit ? (0, undef) : 0;
3233 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3234 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3235 my ($r, $c) = unpack(rev_map_fmt, $buf);
3236 if ($want_commit && $c eq ('0' x40)) {
3237 if ($size < 48) {
3238 return $want_commit ? (0, undef) : 0;
3240 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3241 sysread($fh, $buf, 24) == 24 or croak "read: $!";
3242 ($r, $c) = unpack(rev_map_fmt, $buf);
3243 if ($c eq ('0'x40)) {
3244 croak "Penultimate record is all-zeroes in $map_path";
3247 close $fh or croak "close: $!";
3248 $want_commit ? ($r, $c) : $r;
3251 sub rev_map_get {
3252 my ($self, $rev, $uuid) = @_;
3253 my $map_path = $self->map_path($uuid);
3254 return undef unless -e $map_path;
3256 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3257 my $c = _rev_map_get($fh, $rev);
3258 close($fh) or croak "close: $!";
3262 sub _rev_map_get {
3263 my ($fh, $rev) = @_;
3265 binmode $fh or croak "binmode: $!";
3266 my $size = (stat($fh))[7];
3267 ($size % 24) == 0 or croak "inconsistent size: $size";
3269 if ($size == 0) {
3270 return undef;
3273 my ($l, $u) = (0, $size - 24);
3274 my ($r, $c, $buf);
3276 while ($l <= $u) {
3277 my $i = int(($l/24 + $u/24) / 2) * 24;
3278 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
3279 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3280 my ($r, $c) = unpack(rev_map_fmt, $buf);
3282 if ($r < $rev) {
3283 $l = $i + 24;
3284 } elsif ($r > $rev) {
3285 $u = $i - 24;
3286 } else { # $r == $rev
3287 return $c eq ('0' x 40) ? undef : $c;
3290 undef;
3293 # Finds the first svn revision that exists on (if $eq_ok is true) or
3294 # before $rev for the current branch. It will not search any lower
3295 # than $min_rev. Returns the git commit hash and svn revision number
3296 # if found, else (undef, undef).
3297 sub find_rev_before {
3298 my ($self, $rev, $eq_ok, $min_rev) = @_;
3299 --$rev unless $eq_ok;
3300 $min_rev ||= 1;
3301 my $max_rev = $self->rev_map_max;
3302 $rev = $max_rev if ($rev > $max_rev);
3303 while ($rev >= $min_rev) {
3304 if (my $c = $self->rev_map_get($rev)) {
3305 return ($rev, $c);
3307 --$rev;
3309 return (undef, undef);
3312 # Finds the first svn revision that exists on (if $eq_ok is true) or
3313 # after $rev for the current branch. It will not search any higher
3314 # than $max_rev. Returns the git commit hash and svn revision number
3315 # if found, else (undef, undef).
3316 sub find_rev_after {
3317 my ($self, $rev, $eq_ok, $max_rev) = @_;
3318 ++$rev unless $eq_ok;
3319 $max_rev ||= $self->rev_map_max;
3320 while ($rev <= $max_rev) {
3321 if (my $c = $self->rev_map_get($rev)) {
3322 return ($rev, $c);
3324 ++$rev;
3326 return (undef, undef);
3329 sub _new {
3330 my ($class, $repo_id, $ref_id, $path) = @_;
3331 unless (defined $repo_id && length $repo_id) {
3332 $repo_id = $Git::SVN::default_repo_id;
3334 unless (defined $ref_id && length $ref_id) {
3335 $_prefix = '' unless defined($_prefix);
3336 $_[2] = $ref_id =
3337 "refs/remotes/$_prefix$Git::SVN::default_ref_id";
3339 $_[1] = $repo_id;
3340 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
3342 # Older repos imported by us used $GIT_DIR/svn/foo instead of
3343 # $GIT_DIR/svn/refs/remotes/foo when tracking refs/remotes/foo
3344 if ($ref_id =~ m{^refs/remotes/(.*)}) {
3345 my $old_dir = "$ENV{GIT_DIR}/svn/$1";
3346 if (-d $old_dir && ! -d $dir) {
3347 $dir = $old_dir;
3351 $_[3] = $path = '' unless (defined $path);
3352 mkpath([$dir]);
3353 bless {
3354 ref_id => $ref_id, dir => $dir, index => "$dir/index",
3355 path => $path, config => "$ENV{GIT_DIR}/svn/config",
3356 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
3359 # for read-only access of old .rev_db formats
3360 sub unlink_rev_db_symlink {
3361 my ($self) = @_;
3362 my $link = $self->rev_db_path;
3363 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
3364 if (-l $link) {
3365 unlink $link or croak "unlink: $link failed!";
3369 sub rev_db_path {
3370 my ($self, $uuid) = @_;
3371 my $db_path = $self->map_path($uuid);
3372 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
3373 or croak "map_path: $db_path does not contain '/.rev_map.' !";
3374 $db_path;
3377 # the new replacement for .rev_db
3378 sub map_path {
3379 my ($self, $uuid) = @_;
3380 $uuid ||= $self->ra_uuid;
3381 "$self->{map_root}.$uuid";
3384 sub uri_encode {
3385 my ($f) = @_;
3386 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
3390 sub remove_username {
3391 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
3394 package Git::SVN::Prompt;
3395 use strict;
3396 use warnings;
3397 require SVN::Core;
3398 use vars qw/$_no_auth_cache $_username/;
3400 sub simple {
3401 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
3402 $may_save = undef if $_no_auth_cache;
3403 $default_username = $_username if defined $_username;
3404 if (defined $default_username && length $default_username) {
3405 if (defined $realm && length $realm) {
3406 print STDERR "Authentication realm: $realm\n";
3407 STDERR->flush;
3409 $cred->username($default_username);
3410 } else {
3411 username($cred, $realm, $may_save, $pool);
3413 $cred->password(_read_password("Password for '" .
3414 $cred->username . "': ", $realm));
3415 $cred->may_save($may_save);
3416 $SVN::_Core::SVN_NO_ERROR;
3419 sub ssl_server_trust {
3420 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
3421 $may_save = undef if $_no_auth_cache;
3422 print STDERR "Error validating server certificate for '$realm':\n";
3424 no warnings 'once';
3425 # All variables SVN::Auth::SSL::* are used only once,
3426 # so we're shutting up Perl warnings about this.
3427 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
3428 print STDERR " - The certificate is not issued ",
3429 "by a trusted authority. Use the\n",
3430 " fingerprint to validate ",
3431 "the certificate manually!\n";
3433 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
3434 print STDERR " - The certificate hostname ",
3435 "does not match.\n";
3437 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
3438 print STDERR " - The certificate is not yet valid.\n";
3440 if ($failures & $SVN::Auth::SSL::EXPIRED) {
3441 print STDERR " - The certificate has expired.\n";
3443 if ($failures & $SVN::Auth::SSL::OTHER) {
3444 print STDERR " - The certificate has ",
3445 "an unknown error.\n";
3447 } # no warnings 'once'
3448 printf STDERR
3449 "Certificate information:\n".
3450 " - Hostname: %s\n".
3451 " - Valid: from %s until %s\n".
3452 " - Issuer: %s\n".
3453 " - Fingerprint: %s\n",
3454 map $cert_info->$_, qw(hostname valid_from valid_until
3455 issuer_dname fingerprint);
3456 my $choice;
3457 prompt:
3458 print STDERR $may_save ?
3459 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
3460 "(R)eject or accept (t)emporarily? ";
3461 STDERR->flush;
3462 $choice = lc(substr(<STDIN> || 'R', 0, 1));
3463 if ($choice =~ /^t$/i) {
3464 $cred->may_save(undef);
3465 } elsif ($choice =~ /^r$/i) {
3466 return -1;
3467 } elsif ($may_save && $choice =~ /^p$/i) {
3468 $cred->may_save($may_save);
3469 } else {
3470 goto prompt;
3472 $cred->accepted_failures($failures);
3473 $SVN::_Core::SVN_NO_ERROR;
3476 sub ssl_client_cert {
3477 my ($cred, $realm, $may_save, $pool) = @_;
3478 $may_save = undef if $_no_auth_cache;
3479 print STDERR "Client certificate filename: ";
3480 STDERR->flush;
3481 chomp(my $filename = <STDIN>);
3482 $cred->cert_file($filename);
3483 $cred->may_save($may_save);
3484 $SVN::_Core::SVN_NO_ERROR;
3487 sub ssl_client_cert_pw {
3488 my ($cred, $realm, $may_save, $pool) = @_;
3489 $may_save = undef if $_no_auth_cache;
3490 $cred->password(_read_password("Password: ", $realm));
3491 $cred->may_save($may_save);
3492 $SVN::_Core::SVN_NO_ERROR;
3495 sub username {
3496 my ($cred, $realm, $may_save, $pool) = @_;
3497 $may_save = undef if $_no_auth_cache;
3498 if (defined $realm && length $realm) {
3499 print STDERR "Authentication realm: $realm\n";
3501 my $username;
3502 if (defined $_username) {
3503 $username = $_username;
3504 } else {
3505 print STDERR "Username: ";
3506 STDERR->flush;
3507 chomp($username = <STDIN>);
3509 $cred->username($username);
3510 $cred->may_save($may_save);
3511 $SVN::_Core::SVN_NO_ERROR;
3514 sub _read_password {
3515 my ($prompt, $realm) = @_;
3516 print STDERR $prompt;
3517 STDERR->flush;
3518 require Term::ReadKey;
3519 Term::ReadKey::ReadMode('noecho');
3520 my $password = '';
3521 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
3522 last if $key =~ /[\012\015]/; # \n\r
3523 $password .= $key;
3525 Term::ReadKey::ReadMode('restore');
3526 print STDERR "\n";
3527 STDERR->flush;
3528 $password;
3531 package SVN::Git::Fetcher;
3532 use vars qw/@ISA/;
3533 use strict;
3534 use warnings;
3535 use Carp qw/croak/;
3536 use File::Temp qw/tempfile/;
3537 use IO::File qw//;
3538 use vars qw/$_ignore_regex/;
3540 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
3541 sub new {
3542 my ($class, $git_svn, $switch_path) = @_;
3543 my $self = SVN::Delta::Editor->new;
3544 bless $self, $class;
3545 if (exists $git_svn->{last_commit}) {
3546 $self->{c} = $git_svn->{last_commit};
3547 $self->{empty_symlinks} =
3548 _mark_empty_symlinks($git_svn, $switch_path);
3550 $self->{ignore_regex} = eval { command_oneline('config', '--get',
3551 "svn-remote.$git_svn->{repo_id}.ignore-paths") };
3552 $self->{empty} = {};
3553 $self->{dir_prop} = {};
3554 $self->{file_prop} = {};
3555 $self->{absent_dir} = {};
3556 $self->{absent_file} = {};
3557 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
3558 $self;
3561 # this uses the Ra object, so it must be called before do_{switch,update},
3562 # not inside them (when the Git::SVN::Fetcher object is passed) to
3563 # do_{switch,update}
3564 sub _mark_empty_symlinks {
3565 my ($git_svn, $switch_path) = @_;
3566 my $bool = Git::config_bool('svn.brokenSymlinkWorkaround');
3567 return {} if (!defined($bool)) || (defined($bool) && ! $bool);
3569 my %ret;
3570 my ($rev, $cmt) = $git_svn->last_rev_commit;
3571 return {} unless ($rev && $cmt);
3573 # allow the warning to be printed for each revision we fetch to
3574 # ensure the user sees it. The user can also disable the workaround
3575 # on the repository even while git svn is running and the next
3576 # revision fetched will skip this expensive function.
3577 my $printed_warning;
3578 chomp(my $empty_blob = `git hash-object -t blob --stdin < /dev/null`);
3579 my ($ls, $ctx) = command_output_pipe(qw/ls-tree -r -z/, $cmt);
3580 local $/ = "\0";
3581 my $pfx = defined($switch_path) ? $switch_path : $git_svn->{path};
3582 $pfx .= '/' if length($pfx);
3583 while (<$ls>) {
3584 chomp;
3585 s/\A100644 blob $empty_blob\t//o or next;
3586 unless ($printed_warning) {
3587 print STDERR "Scanning for empty symlinks, ",
3588 "this may take a while if you have ",
3589 "many empty files\n",
3590 "You may disable this with `",
3591 "git config svn.brokenSymlinkWorkaround ",
3592 "false'.\n",
3593 "This may be done in a different ",
3594 "terminal without restarting ",
3595 "git svn\n";
3596 $printed_warning = 1;
3598 my $path = $_;
3599 my (undef, $props) =
3600 $git_svn->ra->get_file($pfx.$path, $rev, undef);
3601 if ($props->{'svn:special'}) {
3602 $ret{$path} = 1;
3605 command_close_pipe($ls, $ctx);
3606 \%ret;
3609 # returns true if a given path is inside a ".git" directory
3610 sub in_dot_git {
3611 $_[0] =~ m{(?:^|/)\.git(?:/|$)};
3614 # return value: 0 -- don't ignore, 1 -- ignore
3615 sub is_path_ignored {
3616 my ($self, $path) = @_;
3617 return 1 if in_dot_git($path);
3618 return 1 if defined($self->{ignore_regex}) &&
3619 $path =~ m!$self->{ignore_regex}!;
3620 return 0 unless defined($_ignore_regex);
3621 return 1 if $path =~ m!$_ignore_regex!o;
3622 return 0;
3625 sub set_path_strip {
3626 my ($self, $path) = @_;
3627 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
3630 sub open_root {
3631 { path => '' };
3634 sub open_directory {
3635 my ($self, $path, $pb, $rev) = @_;
3636 { path => $path };
3639 sub git_path {
3640 my ($self, $path) = @_;
3641 if ($self->{path_strip}) {
3642 $path =~ s!$self->{path_strip}!! or
3643 die "Failed to strip path '$path' ($self->{path_strip})\n";
3645 $path;
3648 sub delete_entry {
3649 my ($self, $path, $rev, $pb) = @_;
3650 return undef if $self->is_path_ignored($path);
3652 my $gpath = $self->git_path($path);
3653 return undef if ($gpath eq '');
3655 # remove entire directories.
3656 my ($tree) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
3657 =~ /\A040000 tree ([a-f\d]{40})\t\Q$gpath\E\0/);
3658 if ($tree) {
3659 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3660 -r --name-only -z/,
3661 $tree);
3662 local $/ = "\0";
3663 while (<$ls>) {
3664 chomp;
3665 my $rmpath = "$gpath/$_";
3666 $self->{gii}->remove($rmpath);
3667 print "\tD\t$rmpath\n" unless $::_q;
3669 print "\tD\t$gpath/\n" unless $::_q;
3670 command_close_pipe($ls, $ctx);
3671 $self->{empty}->{$path} = 0
3672 } else {
3673 $self->{gii}->remove($gpath);
3674 print "\tD\t$gpath\n" unless $::_q;
3676 undef;
3679 sub open_file {
3680 my ($self, $path, $pb, $rev) = @_;
3681 my ($mode, $blob);
3683 goto out if $self->is_path_ignored($path);
3685 my $gpath = $self->git_path($path);
3686 ($mode, $blob) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
3687 =~ /\A(\d{6}) blob ([a-f\d]{40})\t\Q$gpath\E\0/);
3688 unless (defined $mode && defined $blob) {
3689 die "$path was not found in commit $self->{c} (r$rev)\n";
3691 if ($mode eq '100644' && $self->{empty_symlinks}->{$path}) {
3692 $mode = '120000';
3694 out:
3695 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
3696 pool => SVN::Pool->new, action => 'M' };
3699 sub add_file {
3700 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
3701 my $mode;
3703 if (!$self->is_path_ignored($path)) {
3704 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3705 delete $self->{empty}->{$dir};
3706 $mode = '100644';
3708 { path => $path, mode_a => $mode, mode_b => $mode,
3709 pool => SVN::Pool->new, action => 'A' };
3712 sub add_directory {
3713 my ($self, $path, $cp_path, $cp_rev) = @_;
3714 goto out if $self->is_path_ignored($path);
3715 my $gpath = $self->git_path($path);
3716 if ($gpath eq '') {
3717 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3718 -r --name-only -z/,
3719 $self->{c});
3720 local $/ = "\0";
3721 while (<$ls>) {
3722 chomp;
3723 $self->{gii}->remove($_);
3724 print "\tD\t$_\n" unless $::_q;
3726 command_close_pipe($ls, $ctx);
3727 $self->{empty}->{$path} = 0;
3729 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3730 delete $self->{empty}->{$dir};
3731 $self->{empty}->{$path} = 1;
3732 out:
3733 { path => $path };
3736 sub change_dir_prop {
3737 my ($self, $db, $prop, $value) = @_;
3738 return undef if $self->is_path_ignored($db->{path});
3739 $self->{dir_prop}->{$db->{path}} ||= {};
3740 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
3741 undef;
3744 sub absent_directory {
3745 my ($self, $path, $pb) = @_;
3746 return undef if $self->is_path_ignored($path);
3747 $self->{absent_dir}->{$pb->{path}} ||= [];
3748 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
3749 undef;
3752 sub absent_file {
3753 my ($self, $path, $pb) = @_;
3754 return undef if $self->is_path_ignored($path);
3755 $self->{absent_file}->{$pb->{path}} ||= [];
3756 push @{$self->{absent_file}->{$pb->{path}}}, $path;
3757 undef;
3760 sub change_file_prop {
3761 my ($self, $fb, $prop, $value) = @_;
3762 return undef if $self->is_path_ignored($fb->{path});
3763 if ($prop eq 'svn:executable') {
3764 if ($fb->{mode_b} != 120000) {
3765 $fb->{mode_b} = defined $value ? 100755 : 100644;
3767 } elsif ($prop eq 'svn:special') {
3768 $fb->{mode_b} = defined $value ? 120000 : 100644;
3769 } else {
3770 $self->{file_prop}->{$fb->{path}} ||= {};
3771 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
3773 undef;
3776 sub apply_textdelta {
3777 my ($self, $fb, $exp) = @_;
3778 return undef if $self->is_path_ignored($fb->{path});
3779 my $fh = $::_repository->temp_acquire('svn_delta');
3780 # $fh gets auto-closed() by SVN::TxDelta::apply(),
3781 # (but $base does not,) so dup() it for reading in close_file
3782 open my $dup, '<&', $fh or croak $!;
3783 my $base = $::_repository->temp_acquire('git_blob');
3785 if ($fb->{blob}) {
3786 my ($base_is_link, $size);
3788 if ($fb->{mode_a} eq '120000' &&
3789 ! $self->{empty_symlinks}->{$fb->{path}}) {
3790 print $base 'link ' or die "print $!\n";
3791 $base_is_link = 1;
3793 retry:
3794 $size = $::_repository->cat_blob($fb->{blob}, $base);
3795 die "Failed to read object $fb->{blob}" if ($size < 0);
3797 if (defined $exp) {
3798 seek $base, 0, 0 or croak $!;
3799 my $got = ::md5sum($base);
3800 if ($got ne $exp) {
3801 my $err = "Checksum mismatch: ".
3802 "$fb->{path} $fb->{blob}\n" .
3803 "expected: $exp\n" .
3804 " got: $got\n";
3805 if ($base_is_link) {
3806 warn $err,
3807 "Retrying... (possibly ",
3808 "a bad symlink from SVN)\n";
3809 $::_repository->temp_reset($base);
3810 $base_is_link = 0;
3811 goto retry;
3813 die $err;
3817 seek $base, 0, 0 or croak $!;
3818 $fb->{fh} = $fh;
3819 $fb->{base} = $base;
3820 [ SVN::TxDelta::apply($base, $dup, undef, $fb->{path}, $fb->{pool}) ];
3823 sub close_file {
3824 my ($self, $fb, $exp) = @_;
3825 return undef if $self->is_path_ignored($fb->{path});
3827 my $hash;
3828 my $path = $self->git_path($fb->{path});
3829 if (my $fh = $fb->{fh}) {
3830 if (defined $exp) {
3831 seek($fh, 0, 0) or croak $!;
3832 my $got = ::md5sum($fh);
3833 if ($got ne $exp) {
3834 die "Checksum mismatch: $path\n",
3835 "expected: $exp\n got: $got\n";
3838 if ($fb->{mode_b} == 120000) {
3839 sysseek($fh, 0, 0) or croak $!;
3840 my $rd = sysread($fh, my $buf, 5);
3842 if (!defined $rd) {
3843 croak "sysread: $!\n";
3844 } elsif ($rd == 0) {
3845 warn "$path has mode 120000",
3846 " but it points to nothing\n",
3847 "converting to an empty file with mode",
3848 " 100644\n";
3849 $fb->{mode_b} = '100644';
3850 } elsif ($buf ne 'link ') {
3851 warn "$path has mode 120000",
3852 " but is not a link\n";
3853 } else {
3854 my $tmp_fh = $::_repository->temp_acquire(
3855 'svn_hash');
3856 my $res;
3857 while ($res = sysread($fh, my $str, 1024)) {
3858 my $out = syswrite($tmp_fh, $str, $res);
3859 defined($out) && $out == $res
3860 or croak("write ",
3861 Git::temp_path($tmp_fh),
3862 ": $!\n");
3864 defined $res or croak $!;
3866 ($fh, $tmp_fh) = ($tmp_fh, $fh);
3867 Git::temp_release($tmp_fh, 1);
3871 $hash = $::_repository->hash_and_insert_object(
3872 Git::temp_path($fh));
3873 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
3875 Git::temp_release($fb->{base}, 1);
3876 Git::temp_release($fh, 1);
3877 } else {
3878 $hash = $fb->{blob} or die "no blob information\n";
3880 $fb->{pool}->clear;
3881 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
3882 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
3883 undef;
3886 sub abort_edit {
3887 my $self = shift;
3888 $self->{nr} = $self->{gii}->{nr};
3889 delete $self->{gii};
3890 $self->SUPER::abort_edit(@_);
3893 sub close_edit {
3894 my $self = shift;
3895 $self->{git_commit_ok} = 1;
3896 $self->{nr} = $self->{gii}->{nr};
3897 delete $self->{gii};
3898 $self->SUPER::close_edit(@_);
3901 package SVN::Git::Editor;
3902 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
3903 use strict;
3904 use warnings;
3905 use Carp qw/croak/;
3906 use IO::File;
3908 sub new {
3909 my ($class, $opts) = @_;
3910 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
3911 die "$_ required!\n" unless (defined $opts->{$_});
3914 my $pool = SVN::Pool->new;
3915 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
3916 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
3917 $opts->{r}, $mods);
3919 # $opts->{ra} functions should not be used after this:
3920 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
3921 $opts->{editor_cb}, $pool);
3922 my $self = SVN::Delta::Editor->new(@ce, $pool);
3923 bless $self, $class;
3924 foreach (qw/svn_path r tree_a tree_b/) {
3925 $self->{$_} = $opts->{$_};
3927 $self->{url} = $opts->{ra}->{url};
3928 $self->{mods} = $mods;
3929 $self->{types} = $types;
3930 $self->{pool} = $pool;
3931 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
3932 $self->{rm} = { };
3933 $self->{path_prefix} = length $self->{svn_path} ?
3934 "$self->{svn_path}/" : '';
3935 $self->{config} = $opts->{config};
3936 return $self;
3939 sub generate_diff {
3940 my ($tree_a, $tree_b) = @_;
3941 my @diff_tree = qw(diff-tree -z -r);
3942 if ($_cp_similarity) {
3943 push @diff_tree, "-C$_cp_similarity";
3944 } else {
3945 push @diff_tree, '-C';
3947 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
3948 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
3949 push @diff_tree, $tree_a, $tree_b;
3950 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
3951 local $/ = "\0";
3952 my $state = 'meta';
3953 my @mods;
3954 while (<$diff_fh>) {
3955 chomp $_; # this gets rid of the trailing "\0"
3956 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
3957 ($::sha1)\s($::sha1)\s
3958 ([MTCRAD])\d*$/xo) {
3959 push @mods, { mode_a => $1, mode_b => $2,
3960 sha1_a => $3, sha1_b => $4,
3961 chg => $5 };
3962 if ($5 =~ /^(?:C|R)$/) {
3963 $state = 'file_a';
3964 } else {
3965 $state = 'file_b';
3967 } elsif ($state eq 'file_a') {
3968 my $x = $mods[$#mods] or croak "Empty array\n";
3969 if ($x->{chg} !~ /^(?:C|R)$/) {
3970 croak "Error parsing $_, $x->{chg}\n";
3972 $x->{file_a} = $_;
3973 $state = 'file_b';
3974 } elsif ($state eq 'file_b') {
3975 my $x = $mods[$#mods] or croak "Empty array\n";
3976 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
3977 croak "Error parsing $_, $x->{chg}\n";
3979 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
3980 croak "Error parsing $_, $x->{chg}\n";
3982 $x->{file_b} = $_;
3983 $state = 'meta';
3984 } else {
3985 croak "Error parsing $_\n";
3988 command_close_pipe($diff_fh, $ctx);
3989 \@mods;
3992 sub check_diff_paths {
3993 my ($ra, $pfx, $rev, $mods) = @_;
3994 my %types;
3995 $pfx .= '/' if length $pfx;
3997 sub type_diff_paths {
3998 my ($ra, $types, $path, $rev) = @_;
3999 my @p = split m#/+#, $path;
4000 my $c = shift @p;
4001 unless (defined $types->{$c}) {
4002 $types->{$c} = $ra->check_path($c, $rev);
4004 while (@p) {
4005 $c .= '/' . shift @p;
4006 next if defined $types->{$c};
4007 $types->{$c} = $ra->check_path($c, $rev);
4011 foreach my $m (@$mods) {
4012 foreach my $f (qw/file_a file_b/) {
4013 next unless defined $m->{$f};
4014 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
4015 if (length $pfx.$dir && ! defined $types{$dir}) {
4016 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
4020 \%types;
4023 sub split_path {
4024 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
4027 sub repo_path {
4028 my ($self, $path) = @_;
4029 $self->{path_prefix}.(defined $path ? $path : '');
4032 sub url_path {
4033 my ($self, $path) = @_;
4034 if ($self->{url} =~ m#^https?://#) {
4035 $path =~ s!([^~a-zA-Z0-9_./-])!uc sprintf("%%%02x",ord($1))!eg;
4037 $self->{url} . '/' . $self->repo_path($path);
4040 sub rmdirs {
4041 my ($self) = @_;
4042 my $rm = $self->{rm};
4043 delete $rm->{''}; # we never delete the url we're tracking
4044 return unless %$rm;
4046 foreach (keys %$rm) {
4047 my @d = split m#/#, $_;
4048 my $c = shift @d;
4049 $rm->{$c} = 1;
4050 while (@d) {
4051 $c .= '/' . shift @d;
4052 $rm->{$c} = 1;
4055 delete $rm->{$self->{svn_path}};
4056 delete $rm->{''}; # we never delete the url we're tracking
4057 return unless %$rm;
4059 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
4060 $self->{tree_b});
4061 local $/ = "\0";
4062 while (<$fh>) {
4063 chomp;
4064 my @dn = split m#/#, $_;
4065 while (pop @dn) {
4066 delete $rm->{join '/', @dn};
4068 unless (%$rm) {
4069 close $fh;
4070 return;
4073 command_close_pipe($fh, $ctx);
4075 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
4076 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
4077 $self->close_directory($bat->{$d}, $p);
4078 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
4079 print "\tD+\t$d/\n" unless $::_q;
4080 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
4081 delete $bat->{$d};
4085 sub open_or_add_dir {
4086 my ($self, $full_path, $baton) = @_;
4087 my $t = $self->{types}->{$full_path};
4088 if (!defined $t) {
4089 die "$full_path not known in r$self->{r} or we have a bug!\n";
4092 no warnings 'once';
4093 # SVN::Node::none and SVN::Node::file are used only once,
4094 # so we're shutting up Perl's warnings about them.
4095 if ($t == $SVN::Node::none) {
4096 return $self->add_directory($full_path, $baton,
4097 undef, -1, $self->{pool});
4098 } elsif ($t == $SVN::Node::dir) {
4099 return $self->open_directory($full_path, $baton,
4100 $self->{r}, $self->{pool});
4101 } # no warnings 'once'
4102 print STDERR "$full_path already exists in repository at ",
4103 "r$self->{r} and it is not a directory (",
4104 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
4105 } # no warnings 'once'
4106 exit 1;
4109 sub ensure_path {
4110 my ($self, $path) = @_;
4111 my $bat = $self->{bat};
4112 my $repo_path = $self->repo_path($path);
4113 return $bat->{''} unless (length $repo_path);
4114 my @p = split m#/+#, $repo_path;
4115 my $c = shift @p;
4116 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
4117 while (@p) {
4118 my $c0 = $c;
4119 $c .= '/' . shift @p;
4120 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
4122 return $bat->{$c};
4125 # Subroutine to convert a globbing pattern to a regular expression.
4126 # From perl cookbook.
4127 sub glob2pat {
4128 my $globstr = shift;
4129 my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
4130 $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
4131 return '^' . $globstr . '$';
4134 sub check_autoprop {
4135 my ($self, $pattern, $properties, $file, $fbat) = @_;
4136 # Convert the globbing pattern to a regular expression.
4137 my $regex = glob2pat($pattern);
4138 # Check if the pattern matches the file name.
4139 if($file =~ m/($regex)/) {
4140 # Parse the list of properties to set.
4141 my @props = split(/;/, $properties);
4142 foreach my $prop (@props) {
4143 # Parse 'name=value' syntax and set the property.
4144 if ($prop =~ /([^=]+)=(.*)/) {
4145 my ($n,$v) = ($1,$2);
4146 for ($n, $v) {
4147 s/^\s+//; s/\s+$//;
4149 $self->change_file_prop($fbat, $n, $v);
4155 sub apply_autoprops {
4156 my ($self, $file, $fbat) = @_;
4157 my $conf_t = ${$self->{config}}{'config'};
4158 no warnings 'once';
4159 # Check [miscellany]/enable-auto-props in svn configuration.
4160 if (SVN::_Core::svn_config_get_bool(
4161 $conf_t,
4162 $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
4163 $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
4164 0)) {
4165 # Auto-props are enabled. Enumerate them to look for matches.
4166 my $callback = sub {
4167 $self->check_autoprop($_[0], $_[1], $file, $fbat);
4169 SVN::_Core::svn_config_enumerate(
4170 $conf_t,
4171 $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
4172 $callback);
4176 sub A {
4177 my ($self, $m) = @_;
4178 my ($dir, $file) = split_path($m->{file_b});
4179 my $pbat = $self->ensure_path($dir);
4180 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4181 undef, -1);
4182 print "\tA\t$m->{file_b}\n" unless $::_q;
4183 $self->apply_autoprops($file, $fbat);
4184 $self->chg_file($fbat, $m);
4185 $self->close_file($fbat,undef,$self->{pool});
4188 sub C {
4189 my ($self, $m) = @_;
4190 my ($dir, $file) = split_path($m->{file_b});
4191 my $pbat = $self->ensure_path($dir);
4192 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4193 $self->url_path($m->{file_a}), $self->{r});
4194 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
4195 $self->chg_file($fbat, $m);
4196 $self->close_file($fbat,undef,$self->{pool});
4199 sub delete_entry {
4200 my ($self, $path, $pbat) = @_;
4201 my $rpath = $self->repo_path($path);
4202 my ($dir, $file) = split_path($rpath);
4203 $self->{rm}->{$dir} = 1;
4204 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
4207 sub R {
4208 my ($self, $m) = @_;
4209 my ($dir, $file) = split_path($m->{file_b});
4210 my $pbat = $self->ensure_path($dir);
4211 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4212 $self->url_path($m->{file_a}), $self->{r});
4213 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
4214 $self->apply_autoprops($file, $fbat);
4215 $self->chg_file($fbat, $m);
4216 $self->close_file($fbat,undef,$self->{pool});
4218 ($dir, $file) = split_path($m->{file_a});
4219 $pbat = $self->ensure_path($dir);
4220 $self->delete_entry($m->{file_a}, $pbat);
4223 sub M {
4224 my ($self, $m) = @_;
4225 my ($dir, $file) = split_path($m->{file_b});
4226 my $pbat = $self->ensure_path($dir);
4227 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
4228 $pbat,$self->{r},$self->{pool});
4229 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
4230 $self->chg_file($fbat, $m);
4231 $self->close_file($fbat,undef,$self->{pool});
4234 sub T { shift->M(@_) }
4236 sub change_file_prop {
4237 my ($self, $fbat, $pname, $pval) = @_;
4238 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
4241 sub _chg_file_get_blob ($$$$) {
4242 my ($self, $fbat, $m, $which) = @_;
4243 my $fh = $::_repository->temp_acquire("git_blob_$which");
4244 if ($m->{"mode_$which"} =~ /^120/) {
4245 print $fh 'link ' or croak $!;
4246 $self->change_file_prop($fbat,'svn:special','*');
4247 } elsif ($m->{mode_a} =~ /^120/ && $m->{"mode_$which"} !~ /^120/) {
4248 $self->change_file_prop($fbat,'svn:special',undef);
4250 my $blob = $m->{"sha1_$which"};
4251 return ($fh,) if ($blob =~ /^0{40}$/);
4252 my $size = $::_repository->cat_blob($blob, $fh);
4253 croak "Failed to read object $blob" if ($size < 0);
4254 $fh->flush == 0 or croak $!;
4255 seek $fh, 0, 0 or croak $!;
4257 my $exp = ::md5sum($fh);
4258 seek $fh, 0, 0 or croak $!;
4259 return ($fh, $exp);
4262 sub chg_file {
4263 my ($self, $fbat, $m) = @_;
4264 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
4265 $self->change_file_prop($fbat,'svn:executable','*');
4266 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
4267 $self->change_file_prop($fbat,'svn:executable',undef);
4269 my ($fh_a, $exp_a) = _chg_file_get_blob $self, $fbat, $m, 'a';
4270 my ($fh_b, $exp_b) = _chg_file_get_blob $self, $fbat, $m, 'b';
4271 my $pool = SVN::Pool->new;
4272 my $atd = $self->apply_textdelta($fbat, $exp_a, $pool);
4273 if (-s $fh_a) {
4274 my $txstream = SVN::TxDelta::new ($fh_a, $fh_b, $pool);
4275 my $res = SVN::TxDelta::send_txstream($txstream, @$atd, $pool);
4276 if (defined $res) {
4277 die "Unexpected result from send_txstream: $res\n",
4278 "(SVN::Core::VERSION: $SVN::Core::VERSION)\n";
4280 } else {
4281 my $got = SVN::TxDelta::send_stream($fh_b, @$atd, $pool);
4282 die "Checksum mismatch\nexpected: $exp_b\ngot: $got\n"
4283 if ($got ne $exp_b);
4285 Git::temp_release($fh_b, 1);
4286 Git::temp_release($fh_a, 1);
4287 $pool->clear;
4290 sub D {
4291 my ($self, $m) = @_;
4292 my ($dir, $file) = split_path($m->{file_b});
4293 my $pbat = $self->ensure_path($dir);
4294 print "\tD\t$m->{file_b}\n" unless $::_q;
4295 $self->delete_entry($m->{file_b}, $pbat);
4298 sub close_edit {
4299 my ($self) = @_;
4300 my ($p,$bat) = ($self->{pool}, $self->{bat});
4301 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
4302 next if $_ eq '';
4303 $self->close_directory($bat->{$_}, $p);
4305 $self->close_directory($bat->{''}, $p);
4306 $self->SUPER::close_edit($p);
4307 $p->clear;
4310 sub abort_edit {
4311 my ($self) = @_;
4312 $self->SUPER::abort_edit($self->{pool});
4315 sub DESTROY {
4316 my $self = shift;
4317 $self->SUPER::DESTROY(@_);
4318 $self->{pool}->clear;
4321 # this drives the editor
4322 sub apply_diff {
4323 my ($self) = @_;
4324 my $mods = $self->{mods};
4325 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
4326 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
4327 my $f = $m->{chg};
4328 if (defined $o{$f}) {
4329 $self->$f($m);
4330 } else {
4331 fatal("Invalid change type: $f");
4334 $self->rmdirs if $_rmdir;
4335 if (@$mods == 0) {
4336 $self->abort_edit;
4337 } else {
4338 $self->close_edit;
4340 return scalar @$mods;
4343 package Git::SVN::Ra;
4344 use vars qw/@ISA $config_dir $_log_window_size/;
4345 use strict;
4346 use warnings;
4347 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
4349 BEGIN {
4350 # enforce temporary pool usage for some simple functions
4351 no strict 'refs';
4352 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root
4353 get_file/) {
4354 my $SUPER = "SUPER::$f";
4355 *$f = sub {
4356 my $self = shift;
4357 my $pool = SVN::Pool->new;
4358 my @ret = $self->$SUPER(@_,$pool);
4359 $pool->clear;
4360 wantarray ? @ret : $ret[0];
4365 sub _auth_providers () {
4367 SVN::Client::get_simple_provider(),
4368 SVN::Client::get_ssl_server_trust_file_provider(),
4369 SVN::Client::get_simple_prompt_provider(
4370 \&Git::SVN::Prompt::simple, 2),
4371 SVN::Client::get_ssl_client_cert_file_provider(),
4372 SVN::Client::get_ssl_client_cert_prompt_provider(
4373 \&Git::SVN::Prompt::ssl_client_cert, 2),
4374 SVN::Client::get_ssl_client_cert_pw_file_provider(),
4375 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
4376 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
4377 SVN::Client::get_username_provider(),
4378 SVN::Client::get_ssl_server_trust_prompt_provider(
4379 \&Git::SVN::Prompt::ssl_server_trust),
4380 SVN::Client::get_username_prompt_provider(
4381 \&Git::SVN::Prompt::username, 2)
4385 sub escape_uri_only {
4386 my ($uri) = @_;
4387 my @tmp;
4388 foreach (split m{/}, $uri) {
4389 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
4390 push @tmp, $_;
4392 join('/', @tmp);
4395 sub escape_url {
4396 my ($url) = @_;
4397 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
4398 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
4399 $url = "$scheme://$domain$uri";
4401 $url;
4404 sub new {
4405 my ($class, $url) = @_;
4406 $url =~ s!/+$!!;
4407 return $RA if ($RA && $RA->{url} eq $url);
4409 SVN::_Core::svn_config_ensure($config_dir, undef);
4410 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
4411 my $config = SVN::Core::config_get_config($config_dir);
4412 $RA = undef;
4413 my $dont_store_passwords = 1;
4414 my $conf_t = ${$config}{'config'};
4416 no warnings 'once';
4417 # The usage of $SVN::_Core::SVN_CONFIG_* variables
4418 # produces warnings that variables are used only once.
4419 # I had not found the better way to shut them up, so
4420 # the warnings of type 'once' are disabled in this block.
4421 if (SVN::_Core::svn_config_get_bool($conf_t,
4422 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4423 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
4424 1) == 0) {
4425 SVN::_Core::svn_auth_set_parameter($baton,
4426 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
4427 bless (\$dont_store_passwords, "_p_void"));
4429 if (SVN::_Core::svn_config_get_bool($conf_t,
4430 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4431 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
4432 1) == 0) {
4433 $Git::SVN::Prompt::_no_auth_cache = 1;
4435 } # no warnings 'once'
4436 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
4437 config => $config,
4438 pool => SVN::Pool->new,
4439 auth_provider_callbacks => $callbacks);
4440 $self->{url} = $url;
4441 $self->{svn_path} = $url;
4442 $self->{repos_root} = $self->get_repos_root;
4443 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
4444 $self->{cache} = { check_path => { r => 0, data => {} },
4445 get_dir => { r => 0, data => {} } };
4446 $RA = bless $self, $class;
4449 sub check_path {
4450 my ($self, $path, $r) = @_;
4451 my $cache = $self->{cache}->{check_path};
4452 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
4453 return $cache->{data}->{$path};
4455 my $pool = SVN::Pool->new;
4456 my $t = $self->SUPER::check_path($path, $r, $pool);
4457 $pool->clear;
4458 if ($r != $cache->{r}) {
4459 %{$cache->{data}} = ();
4460 $cache->{r} = $r;
4462 $cache->{data}->{$path} = $t;
4465 sub get_dir {
4466 my ($self, $dir, $r) = @_;
4467 my $cache = $self->{cache}->{get_dir};
4468 if ($r == $cache->{r}) {
4469 if (my $x = $cache->{data}->{$dir}) {
4470 return wantarray ? @$x : $x->[0];
4473 my $pool = SVN::Pool->new;
4474 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
4475 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
4476 $pool->clear;
4477 if ($r != $cache->{r}) {
4478 %{$cache->{data}} = ();
4479 $cache->{r} = $r;
4481 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
4482 wantarray ? (\%dirents, $r, $props) : \%dirents;
4485 sub DESTROY {
4486 # do not call the real DESTROY since we store ourselves in $RA
4489 # get_log(paths, start, end, limit,
4490 # discover_changed_paths, strict_node_history, receiver)
4491 sub get_log {
4492 my ($self, @args) = @_;
4493 my $pool = SVN::Pool->new;
4495 # svn_log_changed_path_t objects passed to get_log are likely to be
4496 # overwritten even if only the refs are copied to an external variable,
4497 # so we should dup the structures in their entirety. Using an
4498 # externally passed pool (instead of our temporary and quickly cleared
4499 # pool in Git::SVN::Ra) does not help matters at all...
4500 my $receiver = pop @args;
4501 my $prefix = "/".$self->{svn_path};
4502 $prefix =~ s#/+($)##;
4503 my $prefix_regex = qr#^\Q$prefix\E#;
4504 push(@args, sub {
4505 my ($paths) = $_[0];
4506 return &$receiver(@_) unless $paths;
4507 $_[0] = ();
4508 foreach my $p (keys %$paths) {
4509 my $i = $paths->{$p};
4510 # Make path relative to our url, not repos_root
4511 $p =~ s/$prefix_regex//;
4512 my %s = map { $_ => $i->$_; }
4513 qw/copyfrom_path copyfrom_rev action/;
4514 if ($s{'copyfrom_path'}) {
4515 $s{'copyfrom_path'} =~ s/$prefix_regex//;
4517 $_[0]{$p} = \%s;
4519 &$receiver(@_);
4523 # the limit parameter was not supported in SVN 1.1.x, so we
4524 # drop it. Therefore, the receiver callback passed to it
4525 # is made aware of this limitation by being wrapped if
4526 # the limit passed to is being wrapped.
4527 if ($SVN::Core::VERSION le '1.2.0') {
4528 my $limit = splice(@args, 3, 1);
4529 if ($limit > 0) {
4530 my $receiver = pop @args;
4531 push(@args, sub { &$receiver(@_) if (--$limit >= 0) });
4534 my $ret = $self->SUPER::get_log(@args, $pool);
4535 $pool->clear;
4536 $ret;
4539 sub trees_match {
4540 my ($self, $url1, $rev1, $url2, $rev2) = @_;
4541 my $ctx = SVN::Client->new(auth => _auth_providers);
4542 my $out = IO::File->new_tmpfile;
4544 # older SVN (1.1.x) doesn't take $pool as the last parameter for
4545 # $ctx->diff(), so we'll create a default one
4546 my $pool = SVN::Pool->new_default_sub;
4548 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
4549 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
4550 $out->flush;
4551 my $ret = (($out->stat)[7] == 0);
4552 close $out or croak $!;
4554 $ret;
4557 sub get_commit_editor {
4558 my ($self, $log, $cb, $pool) = @_;
4559 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
4560 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
4563 sub gs_do_update {
4564 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
4565 my $new = ($rev_a == $rev_b);
4566 my $path = $gs->{path};
4568 if ($new && -e $gs->{index}) {
4569 unlink $gs->{index} or die
4570 "Couldn't unlink index: $gs->{index}: $!\n";
4572 my $pool = SVN::Pool->new;
4573 $editor->set_path_strip($path);
4574 my (@pc) = split m#/#, $path;
4575 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
4576 1, $editor, $pool);
4577 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4579 # Since we can't rely on svn_ra_reparent being available, we'll
4580 # just have to do some magic with set_path to make it so
4581 # we only want a partial path.
4582 my $sp = '';
4583 my $final = join('/', @pc);
4584 while (@pc) {
4585 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
4586 $sp .= '/' if length $sp;
4587 $sp .= shift @pc;
4589 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
4591 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
4593 $reporter->finish_report($pool);
4594 $pool->clear;
4595 $editor->{git_commit_ok};
4598 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
4599 # svn_ra_reparent didn't work before 1.4)
4600 sub gs_do_switch {
4601 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
4602 my $path = $gs->{path};
4603 my $pool = SVN::Pool->new;
4605 my $full_url = $self->{url};
4606 my $old_url = $full_url;
4607 $full_url .= '/' . $path if length $path;
4608 my ($ra, $reparented);
4610 if ($old_url =~ m#^svn(\+ssh)?://# ||
4611 ($full_url =~ m#^https?://# &&
4612 escape_url($full_url) ne $full_url)) {
4613 $_[0] = undef;
4614 $self = undef;
4615 $RA = undef;
4616 $ra = Git::SVN::Ra->new($full_url);
4617 $ra_invalid = 1;
4618 } elsif ($old_url ne $full_url) {
4619 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url, $pool);
4620 $self->{url} = $full_url;
4621 $reparented = 1;
4624 $ra ||= $self;
4625 $url_b = escape_url($url_b);
4626 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
4627 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4628 $reporter->set_path('', $rev_a, 0, @lock, $pool);
4629 $reporter->finish_report($pool);
4631 if ($reparented) {
4632 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
4633 $self->{url} = $old_url;
4636 $pool->clear;
4637 $editor->{git_commit_ok};
4640 sub longest_common_path {
4641 my ($gsv, $globs) = @_;
4642 my %common;
4643 my $common_max = scalar @$gsv;
4645 foreach my $gs (@$gsv) {
4646 my @tmp = split m#/#, $gs->{path};
4647 my $p = '';
4648 foreach (@tmp) {
4649 $p .= length($p) ? "/$_" : $_;
4650 $common{$p} ||= 0;
4651 $common{$p}++;
4654 $globs ||= [];
4655 $common_max += scalar @$globs;
4656 foreach my $glob (@$globs) {
4657 my @tmp = split m#/#, $glob->{path}->{left};
4658 my $p = '';
4659 foreach (@tmp) {
4660 $p .= length($p) ? "/$_" : $_;
4661 $common{$p} ||= 0;
4662 $common{$p}++;
4666 my $longest_path = '';
4667 foreach (sort {length $b <=> length $a} keys %common) {
4668 if ($common{$_} == $common_max) {
4669 $longest_path = $_;
4670 last;
4673 $longest_path;
4676 sub gs_fetch_loop_common {
4677 my ($self, $base, $head, $gsv, $globs) = @_;
4678 return if ($base > $head);
4679 my $inc = $_log_window_size;
4680 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
4681 my $longest_path = longest_common_path($gsv, $globs);
4682 my $ra_url = $self->{url};
4683 my $find_trailing_edge;
4684 while (1) {
4685 my %revs;
4686 my $err;
4687 my $err_handler = $SVN::Error::handler;
4688 $SVN::Error::handler = sub {
4689 ($err) = @_;
4690 skip_unknown_revs($err);
4692 sub _cb {
4693 my ($paths, $r, $author, $date, $log) = @_;
4694 [ $paths,
4695 { author => $author, date => $date, log => $log } ];
4697 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
4698 sub { $revs{$_[1]} = _cb(@_) });
4699 if ($err) {
4700 print "Checked through r$max\r";
4701 } else {
4702 $find_trailing_edge = 1;
4704 if ($err and $find_trailing_edge) {
4705 print STDERR "Path '$longest_path' ",
4706 "was probably deleted:\n",
4707 $err->expanded_message,
4708 "\nWill attempt to follow ",
4709 "revisions r$min .. r$max ",
4710 "committed before the deletion\n";
4711 my $hi = $max;
4712 while (--$hi >= $min) {
4713 my $ok;
4714 $self->get_log([$longest_path], $min, $hi,
4715 0, 1, 1, sub {
4716 $ok = $_[1];
4717 $revs{$_[1]} = _cb(@_) });
4718 if ($ok) {
4719 print STDERR "r$min .. r$ok OK\n";
4720 last;
4723 $find_trailing_edge = 0;
4725 $SVN::Error::handler = $err_handler;
4727 my %exists = map { $_->{path} => $_ } @$gsv;
4728 foreach my $r (sort {$a <=> $b} keys %revs) {
4729 my ($paths, $logged) = @{$revs{$r}};
4731 foreach my $gs ($self->match_globs(\%exists, $paths,
4732 $globs, $r)) {
4733 if ($gs->rev_map_max >= $r) {
4734 next;
4736 next unless $gs->match_paths($paths, $r);
4737 $gs->{logged_rev_props} = $logged;
4738 if (my $last_commit = $gs->last_commit) {
4739 $gs->assert_index_clean($last_commit);
4741 my $log_entry = $gs->do_fetch($paths, $r);
4742 if ($log_entry) {
4743 $gs->do_git_commit($log_entry);
4745 $INDEX_FILES{$gs->{index}} = 1;
4747 foreach my $g (@$globs) {
4748 my $k = "svn-remote.$g->{remote}." .
4749 "$g->{t}-maxRev";
4750 Git::SVN::tmp_config($k, $r);
4752 if ($ra_invalid) {
4753 $_[0] = undef;
4754 $self = undef;
4755 $RA = undef;
4756 $self = Git::SVN::Ra->new($ra_url);
4757 $ra_invalid = undef;
4760 # pre-fill the .rev_db since it'll eventually get filled in
4761 # with '0' x40 if something new gets committed
4762 foreach my $gs (@$gsv) {
4763 next if $gs->rev_map_max >= $max;
4764 next if defined $gs->rev_map_get($max);
4765 $gs->rev_map_set($max, 0 x40);
4767 foreach my $g (@$globs) {
4768 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
4769 Git::SVN::tmp_config($k, $max);
4771 last if $max >= $head;
4772 $min = $max + 1;
4773 $max += $inc;
4774 $max = $head if ($max > $head);
4776 Git::SVN::gc();
4779 sub get_dir_globbed {
4780 my ($self, $left, $depth, $r) = @_;
4782 my @x = eval { $self->get_dir($left, $r) };
4783 return unless scalar @x == 3;
4784 my $dirents = $x[0];
4785 my @finalents;
4786 foreach my $de (keys %$dirents) {
4787 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
4788 if ($depth > 1) {
4789 my @args = ("$left/$de", $depth - 1, $r);
4790 foreach my $dir ($self->get_dir_globbed(@args)) {
4791 push @finalents, "$de/$dir";
4793 } else {
4794 push @finalents, $de;
4797 @finalents;
4800 sub match_globs {
4801 my ($self, $exists, $paths, $globs, $r) = @_;
4803 sub get_dir_check {
4804 my ($self, $exists, $g, $r) = @_;
4806 my @dirs = $self->get_dir_globbed($g->{path}->{left},
4807 $g->{path}->{depth},
4808 $r);
4810 foreach my $de (@dirs) {
4811 my $p = $g->{path}->full_path($de);
4812 next if $exists->{$p};
4813 next if (length $g->{path}->{right} &&
4814 ($self->check_path($p, $r) !=
4815 $SVN::Node::dir));
4816 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
4817 $g->{ref}->full_path($de), 1);
4820 foreach my $g (@$globs) {
4821 if (my $path = $paths->{"/$g->{path}->{left}"}) {
4822 if ($path->{action} =~ /^[AR]$/) {
4823 get_dir_check($self, $exists, $g, $r);
4826 foreach (keys %$paths) {
4827 if (/$g->{path}->{left_regex}/ &&
4828 !/$g->{path}->{regex}/) {
4829 next if $paths->{$_}->{action} !~ /^[AR]$/;
4830 get_dir_check($self, $exists, $g, $r);
4832 next unless /$g->{path}->{regex}/;
4833 my $p = $1;
4834 my $pathname = $g->{path}->full_path($p);
4835 next if $exists->{$pathname};
4836 next if ($self->check_path($pathname, $r) !=
4837 $SVN::Node::dir);
4838 $exists->{$pathname} = Git::SVN->init(
4839 $self->{url}, $pathname, undef,
4840 $g->{ref}->full_path($p), 1);
4842 my $c = '';
4843 foreach (split m#/#, $g->{path}->{left}) {
4844 $c .= "/$_";
4845 next unless ($paths->{$c} &&
4846 ($paths->{$c}->{action} =~ /^[AR]$/));
4847 get_dir_check($self, $exists, $g, $r);
4850 values %$exists;
4853 sub minimize_url {
4854 my ($self) = @_;
4855 return $self->{url} if ($self->{url} eq $self->{repos_root});
4856 my $url = $self->{repos_root};
4857 my @components = split(m!/!, $self->{svn_path});
4858 my $c = '';
4859 do {
4860 $url .= "/$c" if length $c;
4861 eval {
4862 my $ra = (ref $self)->new($url);
4863 my $latest = $ra->get_latest_revnum;
4864 $ra->get_log("", $latest, 0, 1, 0, 1, sub {});
4866 } while ($@ && ($c = shift @components));
4867 $url;
4870 sub can_do_switch {
4871 my $self = shift;
4872 unless (defined $can_do_switch) {
4873 my $pool = SVN::Pool->new;
4874 my $rep = eval {
4875 $self->do_switch(1, '', 0, $self->{url},
4876 SVN::Delta::Editor->new, $pool);
4878 if ($@) {
4879 $can_do_switch = 0;
4880 } else {
4881 $rep->abort_report($pool);
4882 $can_do_switch = 1;
4884 $pool->clear;
4886 $can_do_switch;
4889 sub skip_unknown_revs {
4890 my ($err) = @_;
4891 my $errno = $err->apr_err();
4892 # Maybe the branch we're tracking didn't
4893 # exist when the repo started, so it's
4894 # not an error if it doesn't, just continue
4896 # Wonderfully consistent library, eh?
4897 # 160013 - svn:// and file://
4898 # 175002 - http(s)://
4899 # 175007 - http(s):// (this repo required authorization, too...)
4900 # More codes may be discovered later...
4901 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
4902 my $err_key = $err->expanded_message;
4903 # revision numbers change every time, filter them out
4904 $err_key =~ s/\d+/\0/g;
4905 $err_key = "$errno\0$err_key";
4906 unless ($ignored_err{$err_key}) {
4907 warn "W: Ignoring error from SVN, path probably ",
4908 "does not exist: ($errno): ",
4909 $err->expanded_message,"\n";
4910 warn "W: Do not be alarmed at the above message ",
4911 "git-svn is just searching aggressively for ",
4912 "old history.\n",
4913 "This may take a while on large repositories\n";
4914 $ignored_err{$err_key} = 1;
4916 return;
4918 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
4921 package Git::SVN::Log;
4922 use strict;
4923 use warnings;
4924 use POSIX qw/strftime/;
4925 use Time::Local;
4926 use constant commit_log_separator => ('-' x 72) . "\n";
4927 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
4928 %rusers $show_commit $incremental/;
4929 my $l_fmt;
4931 sub cmt_showable {
4932 my ($c) = @_;
4933 return 1 if defined $c->{r};
4935 # big commit message got truncated by the 16k pretty buffer in rev-list
4936 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
4937 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
4938 @{$c->{l}} = ();
4939 my @log = command(qw/cat-file commit/, $c->{c});
4941 # shift off the headers
4942 shift @log while ($log[0] ne '');
4943 shift @log;
4945 # TODO: make $c->{l} not have a trailing newline in the future
4946 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
4948 (undef, $c->{r}, undef) = ::extract_metadata(
4949 (grep(/^git-svn-id: /, @log))[-1]);
4951 return defined $c->{r};
4954 sub log_use_color {
4955 return $color || Git->repository->get_colorbool('color.diff');
4958 sub git_svn_log_cmd {
4959 my ($r_min, $r_max, @args) = @_;
4960 my $head = 'HEAD';
4961 my (@files, @log_opts);
4962 foreach my $x (@args) {
4963 if ($x eq '--' || @files) {
4964 push @files, $x;
4965 } else {
4966 if (::verify_ref("$x^0")) {
4967 $head = $x;
4968 } else {
4969 push @log_opts, $x;
4974 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
4975 $gs ||= Git::SVN->_new;
4976 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
4977 $gs->refname);
4978 push @cmd, '-r' unless $non_recursive;
4979 push @cmd, qw/--raw --name-status/ if $verbose;
4980 push @cmd, '--color' if log_use_color();
4981 push @cmd, @log_opts;
4982 if (defined $r_max && $r_max == $r_min) {
4983 push @cmd, '--max-count=1';
4984 if (my $c = $gs->rev_map_get($r_max)) {
4985 push @cmd, $c;
4987 } elsif (defined $r_max) {
4988 if ($r_max < $r_min) {
4989 ($r_min, $r_max) = ($r_max, $r_min);
4991 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
4992 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
4993 # If there are no commits in the range, both $c_max and $c_min
4994 # will be undefined. If there is at least 1 commit in the
4995 # range, both will be defined.
4996 return () if !defined $c_min || !defined $c_max;
4997 if ($c_min eq $c_max) {
4998 push @cmd, '--max-count=1', $c_min;
4999 } else {
5000 push @cmd, '--boundary', "$c_min..$c_max";
5003 return (@cmd, @files);
5006 # adapted from pager.c
5007 sub config_pager {
5008 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
5009 if (!defined $pager) {
5010 $pager = 'less';
5011 } elsif (length $pager == 0 || $pager eq 'cat') {
5012 $pager = undef;
5014 $ENV{GIT_PAGER_IN_USE} = defined($pager);
5017 sub run_pager {
5018 return unless -t *STDOUT && defined $pager;
5019 pipe my ($rfd, $wfd) or return;
5020 defined(my $pid = fork) or ::fatal "Can't fork: $!";
5021 if (!$pid) {
5022 open STDOUT, '>&', $wfd or
5023 ::fatal "Can't redirect to stdout: $!";
5024 return;
5026 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
5027 $ENV{LESS} ||= 'FRSX';
5028 exec $pager or ::fatal "Can't run pager: $! ($pager)";
5031 sub format_svn_date {
5032 # some systmes don't handle or mishandle %z, so be creative.
5033 my $t = shift || time;
5034 my $gm = timelocal(gmtime($t));
5035 my $sign = qw( + + - )[ $t <=> $gm ];
5036 my $gmoff = sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
5037 return strftime("%Y-%m-%d %H:%M:%S $gmoff (%a, %d %b %Y)", localtime($t));
5040 sub parse_git_date {
5041 my ($t, $tz) = @_;
5042 # Date::Parse isn't in the standard Perl distro :(
5043 if ($tz =~ s/^\+//) {
5044 $t += tz_to_s_offset($tz);
5045 } elsif ($tz =~ s/^\-//) {
5046 $t -= tz_to_s_offset($tz);
5048 return $t;
5051 sub set_local_timezone {
5052 if (defined $TZ) {
5053 $ENV{TZ} = $TZ;
5054 } else {
5055 delete $ENV{TZ};
5059 sub tz_to_s_offset {
5060 my ($tz) = @_;
5061 $tz =~ s/(\d\d)$//;
5062 return ($1 * 60) + ($tz * 3600);
5065 sub get_author_info {
5066 my ($dest, $author, $t, $tz) = @_;
5067 $author =~ s/(?:^\s*|\s*$)//g;
5068 $dest->{a_raw} = $author;
5069 my $au;
5070 if ($::_authors) {
5071 $au = $rusers{$author} || undef;
5073 if (!$au) {
5074 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
5076 $dest->{t} = $t;
5077 $dest->{tz} = $tz;
5078 $dest->{a} = $au;
5079 $dest->{t_utc} = parse_git_date($t, $tz);
5082 sub process_commit {
5083 my ($c, $r_min, $r_max, $defer) = @_;
5084 if (defined $r_min && defined $r_max) {
5085 if ($r_min == $c->{r} && $r_min == $r_max) {
5086 show_commit($c);
5087 return 0;
5089 return 1 if $r_min == $r_max;
5090 if ($r_min < $r_max) {
5091 # we need to reverse the print order
5092 return 0 if (defined $limit && --$limit < 0);
5093 push @$defer, $c;
5094 return 1;
5096 if ($r_min != $r_max) {
5097 return 1 if ($r_min < $c->{r});
5098 return 1 if ($r_max > $c->{r});
5101 return 0 if (defined $limit && --$limit < 0);
5102 show_commit($c);
5103 return 1;
5106 sub show_commit {
5107 my $c = shift;
5108 if ($oneline) {
5109 my $x = "\n";
5110 if (my $l = $c->{l}) {
5111 while ($l->[0] =~ /^\s*$/) { shift @$l }
5112 $x = $l->[0];
5114 $l_fmt ||= 'A' . length($c->{r});
5115 print 'r',pack($l_fmt, $c->{r}),' | ';
5116 print "$c->{c} | " if $show_commit;
5117 print $x;
5118 } else {
5119 show_commit_normal($c);
5123 sub show_commit_changed_paths {
5124 my ($c) = @_;
5125 return unless $c->{changed};
5126 print "Changed paths:\n", @{$c->{changed}};
5129 sub show_commit_normal {
5130 my ($c) = @_;
5131 print commit_log_separator, "r$c->{r} | ";
5132 print "$c->{c} | " if $show_commit;
5133 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
5134 my $nr_line = 0;
5136 if (my $l = $c->{l}) {
5137 while ($l->[$#$l] eq "\n" && $#$l > 0
5138 && $l->[($#$l - 1)] eq "\n") {
5139 pop @$l;
5141 $nr_line = scalar @$l;
5142 if (!$nr_line) {
5143 print "1 line\n\n\n";
5144 } else {
5145 if ($nr_line == 1) {
5146 $nr_line = '1 line';
5147 } else {
5148 $nr_line .= ' lines';
5150 print $nr_line, "\n";
5151 show_commit_changed_paths($c);
5152 print "\n";
5153 print $_ foreach @$l;
5155 } else {
5156 print "1 line\n";
5157 show_commit_changed_paths($c);
5158 print "\n";
5161 foreach my $x (qw/raw stat diff/) {
5162 if ($c->{$x}) {
5163 print "\n";
5164 print $_ foreach @{$c->{$x}}
5169 sub cmd_show_log {
5170 my (@args) = @_;
5171 my ($r_min, $r_max);
5172 my $r_last = -1; # prevent dupes
5173 set_local_timezone();
5174 if (defined $::_revision) {
5175 if ($::_revision =~ /^(\d+):(\d+)$/) {
5176 ($r_min, $r_max) = ($1, $2);
5177 } elsif ($::_revision =~ /^\d+$/) {
5178 $r_min = $r_max = $::_revision;
5179 } else {
5180 ::fatal "-r$::_revision is not supported, use ",
5181 "standard 'git log' arguments instead";
5185 config_pager();
5186 @args = git_svn_log_cmd($r_min, $r_max, @args);
5187 if (!@args) {
5188 print commit_log_separator unless $incremental || $oneline;
5189 return;
5191 my $log = command_output_pipe(@args);
5192 run_pager();
5193 my (@k, $c, $d, $stat);
5194 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
5195 while (<$log>) {
5196 if (/^${esc_color}commit -?($::sha1_short)/o) {
5197 my $cmt = $1;
5198 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
5199 $r_last = $c->{r};
5200 process_commit($c, $r_min, $r_max, \@k) or
5201 goto out;
5203 $d = undef;
5204 $c = { c => $cmt };
5205 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
5206 get_author_info($c, $1, $2, $3);
5207 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
5208 # ignore
5209 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
5210 push @{$c->{raw}}, $_;
5211 } elsif (/^${esc_color}[ACRMDT]\t/) {
5212 # we could add $SVN->{svn_path} here, but that requires
5213 # remote access at the moment (repo_path_split)...
5214 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
5215 push @{$c->{changed}}, $_;
5216 } elsif (/^${esc_color}diff /o) {
5217 $d = 1;
5218 push @{$c->{diff}}, $_;
5219 } elsif ($d) {
5220 push @{$c->{diff}}, $_;
5221 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
5222 $esc_color*[\+\-]*$esc_color$/x) {
5223 $stat = 1;
5224 push @{$c->{stat}}, $_;
5225 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
5226 push @{$c->{stat}}, $_;
5227 $stat = undef;
5228 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
5229 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
5230 } elsif (s/^${esc_color} //o) {
5231 push @{$c->{l}}, $_;
5234 if ($c && defined $c->{r} && $c->{r} != $r_last) {
5235 $r_last = $c->{r};
5236 process_commit($c, $r_min, $r_max, \@k);
5238 if (@k) {
5239 ($r_min, $r_max) = ($r_max, $r_min);
5240 process_commit($_, $r_min, $r_max) foreach reverse @k;
5242 out:
5243 close $log;
5244 print commit_log_separator unless $incremental || $oneline;
5247 sub cmd_blame {
5248 my $path = pop;
5250 config_pager();
5251 run_pager();
5253 my ($fh, $ctx, $rev);
5255 if ($_git_format) {
5256 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
5257 while (my $line = <$fh>) {
5258 if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
5259 # Uncommitted edits show up as a rev ID of
5260 # all zeros, which we can't look up with
5261 # cmt_metadata
5262 if ($1 !~ /^0+$/) {
5263 (undef, $rev, undef) =
5264 ::cmt_metadata($1);
5265 $rev = '0' if (!$rev);
5266 } else {
5267 $rev = '0';
5269 $rev = sprintf('%-10s', $rev);
5270 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
5272 print $line;
5274 } else {
5275 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
5276 '--', $path);
5277 my ($sha1);
5278 my %authors;
5279 my @buffer;
5280 my %dsha; #distinct sha keys
5282 while (my $line = <$fh>) {
5283 push @buffer, $line;
5284 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5285 $dsha{$1} = 1;
5289 my $s2r = ::cmt_sha2rev_batch([keys %dsha]);
5291 foreach my $line (@buffer) {
5292 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5293 $rev = $s2r->{$1};
5294 $rev = '0' if (!$rev)
5296 elsif ($line =~ /^author (.*)/) {
5297 $authors{$rev} = $1;
5298 $authors{$rev} =~ s/\s/_/g;
5300 elsif ($line =~ /^\t(.*)$/) {
5301 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
5305 command_close_pipe($fh, $ctx);
5308 package Git::SVN::Migration;
5309 # these version numbers do NOT correspond to actual version numbers
5310 # of git nor git-svn. They are just relative.
5312 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
5314 # v1 layout: .git/$id/info/url, refs/remotes/$id
5316 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
5318 # v3 layout: .git/svn/$id, refs/remotes/$id
5319 # - info/url may remain for backwards compatibility
5320 # - this is what we migrate up to this layout automatically,
5321 # - this will be used by git svn init on single branches
5322 # v3.1 layout (auto migrated):
5323 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
5324 # for backwards compatibility
5326 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
5327 # - this is only created for newly multi-init-ed
5328 # repositories. Similar in spirit to the
5329 # --use-separate-remotes option in git-clone (now default)
5330 # - we do not automatically migrate to this (following
5331 # the example set by core git)
5333 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
5334 # - newer, more-efficient format that uses 24-bytes per record
5335 # with no filler space.
5336 # - use xxd -c24 < .rev_map.$UUID to view and debug
5337 # - This is a one-way migration, repositories updated to the
5338 # new format will not be able to use old git-svn without
5339 # rebuilding the .rev_db. Rebuilding the rev_db is not
5340 # possible if noMetadata or useSvmProps are set; but should
5341 # be no problem for users that use the (sensible) defaults.
5342 use strict;
5343 use warnings;
5344 use Carp qw/croak/;
5345 use File::Path qw/mkpath/;
5346 use File::Basename qw/dirname basename/;
5347 use vars qw/$_minimize/;
5349 sub migrate_from_v0 {
5350 my $git_dir = $ENV{GIT_DIR};
5351 return undef unless -d $git_dir;
5352 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5353 my $migrated = 0;
5354 while (<$fh>) {
5355 chomp;
5356 my ($id, $orig_ref) = ($_, $_);
5357 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
5358 next unless -f "$git_dir/$id/info/url";
5359 my $new_ref = "refs/remotes/$id";
5360 if (::verify_ref("$new_ref^0")) {
5361 print STDERR "W: $orig_ref is probably an old ",
5362 "branch used by an ancient version of ",
5363 "git-svn.\n",
5364 "However, $new_ref also exists.\n",
5365 "We will not be able ",
5366 "to use this branch until this ",
5367 "ambiguity is resolved.\n";
5368 next;
5370 print STDERR "Migrating from v0 layout...\n" if !$migrated;
5371 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
5372 command_noisy('update-ref', $new_ref, $orig_ref);
5373 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
5374 $migrated++;
5376 command_close_pipe($fh, $ctx);
5377 print STDERR "Done migrating from v0 layout...\n" if $migrated;
5378 $migrated;
5381 sub migrate_from_v1 {
5382 my $git_dir = $ENV{GIT_DIR};
5383 my $migrated = 0;
5384 return $migrated unless -d $git_dir;
5385 my $svn_dir = "$git_dir/svn";
5387 # just in case somebody used 'svn' as their $id at some point...
5388 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
5390 print STDERR "Migrating from a git-svn v1 layout...\n";
5391 mkpath([$svn_dir]);
5392 print STDERR "Data from a previous version of git-svn exists, but\n\t",
5393 "$svn_dir\n\t(required for this version ",
5394 "($::VERSION) of git-svn) does not exist.\n";
5395 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5396 while (<$fh>) {
5397 my $x = $_;
5398 next unless $x =~ s#^refs/remotes/##;
5399 chomp $x;
5400 next unless -f "$git_dir/$x/info/url";
5401 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
5402 next unless $u;
5403 my $dn = dirname("$git_dir/svn/$x");
5404 mkpath([$dn]) unless -d $dn;
5405 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
5406 mkpath(["$git_dir/svn/svn"]);
5407 print STDERR " - $git_dir/$x/info => ",
5408 "$git_dir/svn/$x/info\n";
5409 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
5410 croak "$!: $x";
5411 # don't worry too much about these, they probably
5412 # don't exist with repos this old (save for index,
5413 # and we can easily regenerate that)
5414 foreach my $f (qw/unhandled.log index .rev_db/) {
5415 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
5417 } else {
5418 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
5419 rename "$git_dir/$x", "$git_dir/svn/$x" or
5420 croak "$!: $x";
5422 $migrated++;
5424 command_close_pipe($fh, $ctx);
5425 print STDERR "Done migrating from a git-svn v1 layout\n";
5426 $migrated;
5429 sub read_old_urls {
5430 my ($l_map, $pfx, $path) = @_;
5431 my @dir;
5432 foreach (<$path/*>) {
5433 if (-r "$_/info/url") {
5434 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
5435 my $ref_id = $pfx . basename $_;
5436 my $url = ::file_to_s("$_/info/url");
5437 $l_map->{$ref_id} = $url;
5438 } elsif (-d $_) {
5439 push @dir, $_;
5442 foreach (@dir) {
5443 my $x = $_;
5444 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
5445 read_old_urls($l_map, $x, $_);
5449 sub migrate_from_v2 {
5450 my @cfg = command(qw/config -l/);
5451 return if grep /^svn-remote\..+\.url=/, @cfg;
5452 my %l_map;
5453 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
5454 my $migrated = 0;
5456 foreach my $ref_id (sort keys %l_map) {
5457 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
5458 if ($@) {
5459 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
5461 $migrated++;
5463 $migrated;
5466 sub minimize_connections {
5467 my $r = Git::SVN::read_all_remotes();
5468 my $new_urls = {};
5469 my $root_repos = {};
5470 foreach my $repo_id (keys %$r) {
5471 my $url = $r->{$repo_id}->{url} or next;
5472 my $fetch = $r->{$repo_id}->{fetch} or next;
5473 my $ra = Git::SVN::Ra->new($url);
5475 # skip existing cases where we already connect to the root
5476 if (($ra->{url} eq $ra->{repos_root}) ||
5477 ($ra->{repos_root} eq $repo_id)) {
5478 $root_repos->{$ra->{url}} = $repo_id;
5479 next;
5482 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
5483 my $root_path = $ra->{url};
5484 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
5485 foreach my $path (keys %$fetch) {
5486 my $ref_id = $fetch->{$path};
5487 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
5489 # make sure we can read when connecting to
5490 # a higher level of a repository
5491 my ($last_rev, undef) = $gs->last_rev_commit;
5492 if (!defined $last_rev) {
5493 $last_rev = eval {
5494 $root_ra->get_latest_revnum;
5496 next if $@;
5498 my $new = $root_path;
5499 $new .= length $path ? "/$path" : '';
5500 eval {
5501 $root_ra->get_log([$new], $last_rev, $last_rev,
5502 0, 0, 1, sub { });
5504 next if $@;
5505 $new_urls->{$ra->{repos_root}}->{$new} =
5506 { ref_id => $ref_id,
5507 old_repo_id => $repo_id,
5508 old_path => $path };
5512 my @emptied;
5513 foreach my $url (keys %$new_urls) {
5514 # see if we can re-use an existing [svn-remote "repo_id"]
5515 # instead of creating a(n ugly) new section:
5516 my $repo_id = $root_repos->{$url} || $url;
5518 my $fetch = $new_urls->{$url};
5519 foreach my $path (keys %$fetch) {
5520 my $x = $fetch->{$path};
5521 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
5522 my $pfx = "svn-remote.$x->{old_repo_id}";
5524 my $old_fetch = quotemeta("$x->{old_path}:".
5525 "$x->{ref_id}");
5526 command_noisy(qw/config --unset/,
5527 "$pfx.fetch", '^'. $old_fetch . '$');
5528 delete $r->{$x->{old_repo_id}}->
5529 {fetch}->{$x->{old_path}};
5530 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
5531 command_noisy(qw/config --unset/,
5532 "$pfx.url");
5533 push @emptied, $x->{old_repo_id}
5537 if (@emptied) {
5538 my $file = $ENV{GIT_CONFIG} || "$ENV{GIT_DIR}/config";
5539 print STDERR <<EOF;
5540 The following [svn-remote] sections in your config file ($file) are empty
5541 and can be safely removed:
5543 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
5547 sub migration_check {
5548 migrate_from_v0();
5549 migrate_from_v1();
5550 migrate_from_v2();
5551 minimize_connections() if $_minimize;
5554 package Git::IndexInfo;
5555 use strict;
5556 use warnings;
5557 use Git qw/command_input_pipe command_close_pipe/;
5559 sub new {
5560 my ($class) = @_;
5561 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
5562 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
5565 sub remove {
5566 my ($self, $path) = @_;
5567 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
5568 return ++$self->{nr};
5570 undef;
5573 sub update {
5574 my ($self, $mode, $hash, $path) = @_;
5575 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
5576 return ++$self->{nr};
5578 undef;
5581 sub DESTROY {
5582 my ($self) = @_;
5583 command_close_pipe($self->{gui}, $self->{ctx});
5586 package Git::SVN::GlobSpec;
5587 use strict;
5588 use warnings;
5590 sub new {
5591 my ($class, $glob) = @_;
5592 my $re = $glob;
5593 $re =~ s!/+$!!g; # no need for trailing slashes
5594 $re =~ m!^([^*]*)(\*(?:/\*)*)(.*)$!;
5595 my $temp = $re;
5596 my ($left, $right) = ($1, $3);
5597 $re = $2;
5598 my $depth = $re =~ tr/*/*/;
5599 if ($depth != $temp =~ tr/*/*/) {
5600 die "Only one set of wildcard directories " .
5601 "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
5603 if ($depth == 0) {
5604 die "One '*' is needed for glob: '$glob'\n";
5606 $re =~ s!\*!\[^/\]*!g;
5607 $re = quotemeta($left) . "($re)" . quotemeta($right);
5608 if (length $left && !($left =~ s!/+$!!g)) {
5609 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
5611 if (length $right && !($right =~ s!^/+!!g)) {
5612 die "Missing leading '/' on right side of: '$glob' ($right)\n";
5614 my $left_re = qr/^\/\Q$left\E(\/|$)/;
5615 bless { left => $left, right => $right, left_regex => $left_re,
5616 regex => qr/$re/, glob => $glob, depth => $depth }, $class;
5619 sub full_path {
5620 my ($self, $path) = @_;
5621 return (length $self->{left} ? "$self->{left}/" : '') .
5622 $path . (length $self->{right} ? "/$self->{right}" : '');
5625 __END__
5627 Data structures:
5630 $remotes = { # returned by read_all_remotes()
5631 'svn' => {
5632 # svn-remote.svn.url=https://svn.musicpd.org
5633 url => 'https://svn.musicpd.org',
5634 # svn-remote.svn.fetch=mpd/trunk:trunk
5635 fetch => {
5636 'mpd/trunk' => 'trunk',
5638 # svn-remote.svn.tags=mpd/tags/*:tags/*
5639 tags => {
5640 path => {
5641 left => 'mpd/tags',
5642 right => '',
5643 regex => qr!mpd/tags/([^/]+)$!,
5644 glob => 'tags/*',
5646 ref => {
5647 left => 'tags',
5648 right => '',
5649 regex => qr!tags/([^/]+)$!,
5650 glob => 'tags/*',
5656 $log_entry hashref as returned by libsvn_log_entry()
5658 log => 'whitespace-formatted log entry
5659 ', # trailing newline is preserved
5660 revision => '8', # integer
5661 date => '2004-02-24T17:01:44.108345Z', # commit date
5662 author => 'committer name'
5666 # this is generated by generate_diff();
5667 @mods = array of diff-index line hashes, each element represents one line
5668 of diff-index output
5670 diff-index line ($m hash)
5672 mode_a => first column of diff-index output, no leading ':',
5673 mode_b => second column of diff-index output,
5674 sha1_b => sha1sum of the final blob,
5675 chg => change type [MCRADT],
5676 file_a => original file name of a file (iff chg is 'C' or 'R')
5677 file_b => new/current file name of a file (any chg)
5681 # retval of read_url_paths{,_all}();
5682 $l_map = {
5683 # repository root url
5684 'https://svn.musicpd.org' => {
5685 # repository path # GIT_SVN_ID
5686 'mpd/trunk' => 'trunk',
5687 'mpd/tags/0.11.5' => 'tags/0.11.5',
5691 Notes:
5692 I don't trust the each() function on unless I created %hash myself
5693 because the internal iterator may not have started at base.