Merge branch 'jk/unwanted-advices'
[git/spearce.git] / git-svn.perl
blobe0ec258e335ceb88e97f749e22f997a4f699eb8b
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 if (! exists $ENV{SVN_SSH}) {
25 if (exists $ENV{GIT_SSH}) {
26 $ENV{SVN_SSH} = $ENV{GIT_SSH};
27 if ($^O eq 'msys') {
28 $ENV{SVN_SSH} =~ s/\\/\\\\/g;
33 $Git::SVN::Log::TZ = $ENV{TZ};
34 $ENV{TZ} = 'UTC';
35 $| = 1; # unbuffer STDOUT
37 sub fatal (@) { print STDERR "@_\n"; exit 1 }
38 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
39 require SVN::Ra;
40 require SVN::Delta;
41 if ($SVN::Core::VERSION lt '1.1.0') {
42 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
44 my $can_compress = eval { require Compress::Zlib; 1};
45 push @Git::SVN::Ra::ISA, 'SVN::Ra';
46 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
47 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
48 use Carp qw/croak/;
49 use Digest::MD5;
50 use IO::File qw//;
51 use File::Basename qw/dirname basename/;
52 use File::Path qw/mkpath/;
53 use File::Spec;
54 use File::Find;
55 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
56 use IPC::Open3;
57 use Git;
59 BEGIN {
60 # import functions from Git into our packages, en masse
61 no strict 'refs';
62 foreach (qw/command command_oneline command_noisy command_output_pipe
63 command_input_pipe command_close_pipe
64 command_bidi_pipe command_close_bidi_pipe/) {
65 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
66 Git::SVN::Migration Git::SVN::Log Git::SVN),
67 __PACKAGE__) {
68 *{"${package}::$_"} = \&{"Git::$_"};
73 my ($SVN);
75 $sha1 = qr/[a-f\d]{40}/;
76 $sha1_short = qr/[a-f\d]{4,40}/;
77 my ($_stdin, $_help, $_edit,
78 $_message, $_file, $_branch_dest,
79 $_template, $_shared,
80 $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
81 $_merge, $_strategy, $_dry_run, $_local,
82 $_prefix, $_no_checkout, $_url, $_verbose,
83 $_git_format, $_commit_url, $_tag);
84 $Git::SVN::_follow_parent = 1;
85 $_q ||= 0;
86 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
87 'config-dir=s' => \$Git::SVN::Ra::config_dir,
88 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
89 'ignore-paths=s' => \$SVN::Git::Fetcher::_ignore_regex );
90 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
91 'authors-file|A=s' => \$_authors,
92 'authors-prog=s' => \$_authors_prog,
93 'repack:i' => \$Git::SVN::_repack,
94 'noMetadata' => \$Git::SVN::_no_metadata,
95 'useSvmProps' => \$Git::SVN::_use_svm_props,
96 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
97 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
98 'no-checkout' => \$_no_checkout,
99 'quiet|q+' => \$_q,
100 'repack-flags|repack-args|repack-opts=s' =>
101 \$Git::SVN::_repack_flags,
102 'use-log-author' => \$Git::SVN::_use_log_author,
103 'add-author-from' => \$Git::SVN::_add_author_from,
104 'localtime' => \$Git::SVN::_localtime,
105 %remote_opts );
107 my ($_trunk, @_tags, @_branches, $_stdlayout);
108 my %icv;
109 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
110 'trunk|T=s' => \$_trunk, 'tags|t=s@' => \@_tags,
111 'branches|b=s@' => \@_branches, 'prefix=s' => \$_prefix,
112 'stdlayout|s' => \$_stdlayout,
113 'minimize-url|m!' => \$Git::SVN::_minimize_url,
114 'no-metadata' => sub { $icv{noMetadata} = 1 },
115 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
116 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
117 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
118 %remote_opts );
119 my %cmt_opts = ( 'edit|e' => \$_edit,
120 'rmdir' => \$SVN::Git::Editor::_rmdir,
121 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
122 'l=i' => \$SVN::Git::Editor::_rename_limit,
123 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
126 my %cmd = (
127 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
128 { 'revision|r=s' => \$_revision,
129 'fetch-all|all' => \$_fetch_all,
130 'parent|p' => \$_fetch_parent,
131 %fc_opts } ],
132 clone => [ \&cmd_clone, "Initialize and fetch revisions",
133 { 'revision|r=s' => \$_revision,
134 %fc_opts, %init_opts } ],
135 init => [ \&cmd_init, "Initialize a repo for tracking" .
136 " (requires URL argument)",
137 \%init_opts ],
138 'multi-init' => [ \&cmd_multi_init,
139 "Deprecated alias for ".
140 "'$0 init -T<trunk> -b<branches> -t<tags>'",
141 \%init_opts ],
142 dcommit => [ \&cmd_dcommit,
143 'Commit several diffs to merge with upstream',
144 { 'merge|m|M' => \$_merge,
145 'strategy|s=s' => \$_strategy,
146 'verbose|v' => \$_verbose,
147 'dry-run|n' => \$_dry_run,
148 'fetch-all|all' => \$_fetch_all,
149 'commit-url=s' => \$_commit_url,
150 'revision|r=i' => \$_revision,
151 'no-rebase' => \$_no_rebase,
152 %cmt_opts, %fc_opts } ],
153 branch => [ \&cmd_branch,
154 'Create a branch in the SVN repository',
155 { 'message|m=s' => \$_message,
156 'destination|d=s' => \$_branch_dest,
157 'dry-run|n' => \$_dry_run,
158 'tag|t' => \$_tag } ],
159 tag => [ sub { $_tag = 1; cmd_branch(@_) },
160 'Create a tag in the SVN repository',
161 { 'message|m=s' => \$_message,
162 'destination|d=s' => \$_branch_dest,
163 'dry-run|n' => \$_dry_run } ],
164 'set-tree' => [ \&cmd_set_tree,
165 "Set an SVN repository to a git tree-ish",
166 { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
167 'create-ignore' => [ \&cmd_create_ignore,
168 'Create a .gitignore per svn:ignore',
169 { 'revision|r=i' => \$_revision
170 } ],
171 'propget' => [ \&cmd_propget,
172 'Print the value of a property on a file or directory',
173 { 'revision|r=i' => \$_revision } ],
174 'proplist' => [ \&cmd_proplist,
175 'List all properties of a file or directory',
176 { 'revision|r=i' => \$_revision } ],
177 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
178 { 'revision|r=i' => \$_revision
179 } ],
180 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
181 { 'revision|r=i' => \$_revision
182 } ],
183 'multi-fetch' => [ \&cmd_multi_fetch,
184 "Deprecated alias for $0 fetch --all",
185 { 'revision|r=s' => \$_revision, %fc_opts } ],
186 'migrate' => [ sub { },
187 # no-op, we automatically run this anyways,
188 'Migrate configuration/metadata/layout from
189 previous versions of git-svn',
190 { 'minimize' => \$Git::SVN::Migration::_minimize,
191 %remote_opts } ],
192 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
193 { 'limit=i' => \$Git::SVN::Log::limit,
194 'revision|r=s' => \$_revision,
195 'verbose|v' => \$Git::SVN::Log::verbose,
196 'incremental' => \$Git::SVN::Log::incremental,
197 'oneline' => \$Git::SVN::Log::oneline,
198 'show-commit' => \$Git::SVN::Log::show_commit,
199 'non-recursive' => \$Git::SVN::Log::non_recursive,
200 'authors-file|A=s' => \$_authors,
201 'color' => \$Git::SVN::Log::color,
202 'pager=s' => \$Git::SVN::Log::pager
203 } ],
204 'find-rev' => [ \&cmd_find_rev,
205 "Translate between SVN revision numbers and tree-ish",
206 {} ],
207 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
208 { 'merge|m|M' => \$_merge,
209 'verbose|v' => \$_verbose,
210 'strategy|s=s' => \$_strategy,
211 'local|l' => \$_local,
212 'fetch-all|all' => \$_fetch_all,
213 'dry-run|n' => \$_dry_run,
214 %fc_opts } ],
215 'commit-diff' => [ \&cmd_commit_diff,
216 'Commit a diff between two trees',
217 { 'message|m=s' => \$_message,
218 'file|F=s' => \$_file,
219 'revision|r=s' => \$_revision,
220 %cmt_opts } ],
221 'info' => [ \&cmd_info,
222 "Show info about the latest SVN revision
223 on the current branch",
224 { 'url' => \$_url, } ],
225 'blame' => [ \&Git::SVN::Log::cmd_blame,
226 "Show what revision and author last modified each line of a file",
227 { 'git-format' => \$_git_format } ],
228 'reset' => [ \&cmd_reset,
229 "Undo fetches back to the specified SVN revision",
230 { 'revision|r=s' => \$_revision,
231 'parent|p' => \$_fetch_parent } ],
232 'gc' => [ \&cmd_gc,
233 "Compress unhandled.log files in .git/svn and remove " .
234 "index files in .git/svn",
235 {} ],
238 my $cmd;
239 for (my $i = 0; $i < @ARGV; $i++) {
240 if (defined $cmd{$ARGV[$i]}) {
241 $cmd = $ARGV[$i];
242 splice @ARGV, $i, 1;
243 last;
244 } elsif ($ARGV[$i] eq 'help') {
245 $cmd = $ARGV[$i+1];
246 usage(0);
250 # make sure we're always running at the top-level working directory
251 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
252 unless (-d $ENV{GIT_DIR}) {
253 if ($git_dir_user_set) {
254 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
255 "but it is not a directory\n";
257 my $git_dir = delete $ENV{GIT_DIR};
258 my $cdup = undef;
259 git_cmd_try {
260 $cdup = command_oneline(qw/rev-parse --show-cdup/);
261 $git_dir = '.' unless ($cdup);
262 chomp $cdup if ($cdup);
263 $cdup = "." unless ($cdup && length $cdup);
264 } "Already at toplevel, but $git_dir not found\n";
265 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
266 unless (-d $git_dir) {
267 die "$git_dir still not found after going to ",
268 "'$cdup'\n";
270 $ENV{GIT_DIR} = $git_dir;
272 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
275 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
277 read_repo_config(\%opts);
278 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
279 Getopt::Long::Configure('pass_through');
281 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
282 'minimize-connections' => \$Git::SVN::Migration::_minimize,
283 'id|i=s' => \$Git::SVN::default_ref_id,
284 'svn-remote|remote|R=s' => sub {
285 $Git::SVN::no_reuse_existing = 1;
286 $Git::SVN::default_repo_id = $_[1] });
287 exit 1 if (!$rv && $cmd && $cmd ne 'log');
289 usage(0) if $_help;
290 version() if $_version;
291 usage(1) unless defined $cmd;
292 load_authors() if $_authors;
293 if (defined $_authors_prog) {
294 $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
297 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
298 Git::SVN::Migration::migration_check();
300 Git::SVN::init_vars();
301 eval {
302 Git::SVN::verify_remotes_sanity();
303 $cmd{$cmd}->[0]->(@ARGV);
305 fatal $@ if $@;
306 post_fetch_checkout();
307 exit 0;
309 ####################### primary functions ######################
310 sub usage {
311 my $exit = shift || 0;
312 my $fd = $exit ? \*STDERR : \*STDOUT;
313 print $fd <<"";
314 git-svn - bidirectional operations between a single Subversion tree and git
315 Usage: git svn <command> [options] [arguments]\n
317 print $fd "Available commands:\n" unless $cmd;
319 foreach (sort keys %cmd) {
320 next if $cmd && $cmd ne $_;
321 next if /^multi-/; # don't show deprecated commands
322 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
323 foreach (sort keys %{$cmd{$_}->[2]}) {
324 # mixed-case options are for .git/config only
325 next if /[A-Z]/ && /^[a-z]+$/i;
326 # prints out arguments as they should be passed:
327 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
328 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
329 "--$_" : "-$_" }
330 split /\|/,$_)," $x\n";
333 print $fd <<"";
334 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
335 arbitrary identifier if you're tracking multiple SVN branches/repositories in
336 one git repository and want to keep them separate. See git-svn(1) for more
337 information.
339 exit $exit;
342 sub version {
343 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
344 exit 0;
347 sub do_git_init_db {
348 unless (-d $ENV{GIT_DIR}) {
349 my @init_db = ('init');
350 push @init_db, "--template=$_template" if defined $_template;
351 if (defined $_shared) {
352 if ($_shared =~ /[a-z]/) {
353 push @init_db, "--shared=$_shared";
354 } else {
355 push @init_db, "--shared";
358 command_noisy(@init_db);
359 $_repository = Git->repository(Repository => ".git");
361 command_noisy('config', 'core.autocrlf', 'false');
362 my $set;
363 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
364 foreach my $i (keys %icv) {
365 die "'$set' and '$i' cannot both be set\n" if $set;
366 next unless defined $icv{$i};
367 command_noisy('config', "$pfx.$i", $icv{$i});
368 $set = $i;
370 my $ignore_regex = \$SVN::Git::Fetcher::_ignore_regex;
371 command_noisy('config', "$pfx.ignore-paths", $$ignore_regex)
372 if defined $$ignore_regex;
375 sub init_subdir {
376 my $repo_path = shift or return;
377 mkpath([$repo_path]) unless -d $repo_path;
378 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
379 $ENV{GIT_DIR} = '.git';
380 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
383 sub cmd_clone {
384 my ($url, $path) = @_;
385 if (!defined $path &&
386 (defined $_trunk || @_branches || @_tags ||
387 defined $_stdlayout) &&
388 $url !~ m#^[a-z\+]+://#) {
389 $path = $url;
391 $path = basename($url) if !defined $path || !length $path;
392 cmd_init($url, $path);
393 Git::SVN::fetch_all($Git::SVN::default_repo_id);
394 command_oneline('config', 'svn.authorsfile', $_authors) if $_authors;
397 sub cmd_init {
398 if (defined $_stdlayout) {
399 $_trunk = 'trunk' if (!defined $_trunk);
400 @_tags = 'tags' if (! @_tags);
401 @_branches = 'branches' if (! @_branches);
403 if (defined $_trunk || @_branches || @_tags) {
404 return cmd_multi_init(@_);
406 my $url = shift or die "SVN repository location required ",
407 "as a command-line argument\n";
408 $url = canonicalize_url($url);
409 init_subdir(@_);
410 do_git_init_db();
412 if ($Git::SVN::_minimize_url eq 'unset') {
413 $Git::SVN::_minimize_url = 0;
416 Git::SVN->init($url);
419 sub cmd_fetch {
420 if (grep /^\d+=./, @_) {
421 die "'<rev>=<commit>' fetch arguments are ",
422 "no longer supported.\n";
424 my ($remote) = @_;
425 if (@_ > 1) {
426 die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
428 if ($_fetch_parent) {
429 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
430 unless ($gs) {
431 die "Unable to determine upstream SVN information from ",
432 "working tree history\n";
434 # just fetch, don't checkout.
435 $_no_checkout = 'true';
436 $_fetch_all ? $gs->fetch_all : $gs->fetch;
437 } elsif ($_fetch_all) {
438 cmd_multi_fetch();
439 } else {
440 $remote ||= $Git::SVN::default_repo_id;
441 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
445 sub cmd_set_tree {
446 my (@commits) = @_;
447 if ($_stdin || !@commits) {
448 print "Reading from stdin...\n";
449 @commits = ();
450 while (<STDIN>) {
451 if (/\b($sha1_short)\b/o) {
452 unshift @commits, $1;
456 my @revs;
457 foreach my $c (@commits) {
458 my @tmp = command('rev-parse',$c);
459 if (scalar @tmp == 1) {
460 push @revs, $tmp[0];
461 } elsif (scalar @tmp > 1) {
462 push @revs, reverse(command('rev-list',@tmp));
463 } else {
464 fatal "Failed to rev-parse $c";
467 my $gs = Git::SVN->new;
468 my ($r_last, $cmt_last) = $gs->last_rev_commit;
469 $gs->fetch;
470 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
471 fatal "There are new revisions that were fetched ",
472 "and need to be merged (or acknowledged) ",
473 "before committing.\nlast rev: $r_last\n",
474 " current: $gs->{last_rev}";
476 $gs->set_tree($_) foreach @revs;
477 print "Done committing ",scalar @revs," revisions to SVN\n";
478 unlink $gs->{index};
481 sub cmd_dcommit {
482 my $head = shift;
483 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
484 'Cannot dcommit with a dirty index. Commit your changes first, '
485 . "or stash them with `git stash'.\n";
486 $head ||= 'HEAD';
488 my $old_head;
489 if ($head ne 'HEAD') {
490 $old_head = eval {
491 command_oneline([qw/symbolic-ref -q HEAD/])
493 if ($old_head) {
494 $old_head =~ s{^refs/heads/}{};
495 } else {
496 $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
498 command(['checkout', $head], STDERR => 0);
501 my @refs;
502 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
503 unless ($gs) {
504 die "Unable to determine upstream SVN information from ",
505 "$head history.\nPerhaps the repository is empty.";
508 if (defined $_commit_url) {
509 $url = $_commit_url;
510 } else {
511 $url = eval { command_oneline('config', '--get',
512 "svn-remote.$gs->{repo_id}.commiturl") };
513 if (!$url) {
514 $url = $gs->full_url
518 my $last_rev = $_revision if defined $_revision;
519 if ($url) {
520 print "Committing to $url ...\n";
522 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
523 if ($_no_rebase && scalar(@$linear_refs) > 1) {
524 warn "Attempting to commit more than one change while ",
525 "--no-rebase is enabled.\n",
526 "If these changes depend on each other, re-running ",
527 "without --no-rebase may be required."
529 my $expect_url = $url;
530 Git::SVN::remove_username($expect_url);
531 while (1) {
532 my $d = shift @$linear_refs or last;
533 unless (defined $last_rev) {
534 (undef, $last_rev, undef) = cmt_metadata("$d~1");
535 unless (defined $last_rev) {
536 fatal "Unable to extract revision information ",
537 "from commit $d~1";
540 if ($_dry_run) {
541 print "diff-tree $d~1 $d\n";
542 } else {
543 my $cmt_rev;
544 my %ed_opts = ( r => $last_rev,
545 log => get_commit_entry($d)->{log},
546 ra => Git::SVN::Ra->new($url),
547 config => SVN::Core::config_get_config(
548 $Git::SVN::Ra::config_dir
550 tree_a => "$d~1",
551 tree_b => $d,
552 editor_cb => sub {
553 print "Committed r$_[0]\n";
554 $cmt_rev = $_[0];
556 svn_path => '');
557 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
558 print "No changes\n$d~1 == $d\n";
559 } elsif ($parents->{$d} && @{$parents->{$d}}) {
560 $gs->{inject_parents_dcommit}->{$cmt_rev} =
561 $parents->{$d};
563 $_fetch_all ? $gs->fetch_all : $gs->fetch;
564 $last_rev = $cmt_rev;
565 next if $_no_rebase;
567 # we always want to rebase against the current HEAD,
568 # not any head that was passed to us
569 my @diff = command('diff-tree', $d,
570 $gs->refname, '--');
571 my @finish;
572 if (@diff) {
573 @finish = rebase_cmd();
574 print STDERR "W: $d and ", $gs->refname,
575 " differ, using @finish:\n",
576 join("\n", @diff), "\n";
577 } else {
578 print "No changes between current HEAD and ",
579 $gs->refname,
580 "\nResetting to the latest ",
581 $gs->refname, "\n";
582 @finish = qw/reset --mixed/;
584 command_noisy(@finish, $gs->refname);
585 if (@diff) {
586 @refs = ();
587 my ($url_, $rev_, $uuid_, $gs_) =
588 working_head_info('HEAD', \@refs);
589 my ($linear_refs_, $parents_) =
590 linearize_history($gs_, \@refs);
591 if (scalar(@$linear_refs) !=
592 scalar(@$linear_refs_)) {
593 fatal "# of revisions changed ",
594 "\nbefore:\n",
595 join("\n", @$linear_refs),
596 "\n\nafter:\n",
597 join("\n", @$linear_refs_), "\n",
598 'If you are attempting to commit ',
599 "merges, try running:\n\t",
600 'git rebase --interactive',
601 '--preserve-merges ',
602 $gs->refname,
603 "\nBefore dcommitting";
605 if ($url_ ne $expect_url) {
606 fatal "URL mismatch after rebase: ",
607 "$url_ != $expect_url";
609 if ($uuid_ ne $uuid) {
610 fatal "uuid mismatch after rebase: ",
611 "$uuid_ != $uuid";
613 # remap parents
614 my (%p, @l, $i);
615 for ($i = 0; $i < scalar @$linear_refs; $i++) {
616 my $new = $linear_refs_->[$i] or next;
617 $p{$new} =
618 $parents->{$linear_refs->[$i]};
619 push @l, $new;
621 $parents = \%p;
622 $linear_refs = \@l;
627 if ($old_head) {
628 my $new_head = command_oneline(qw/rev-parse HEAD/);
629 my $new_is_symbolic = eval {
630 command_oneline(qw/symbolic-ref -q HEAD/);
632 if ($new_is_symbolic) {
633 print "dcommitted the branch ", $head, "\n";
634 } else {
635 print "dcommitted on a detached HEAD because you gave ",
636 "a revision argument.\n",
637 "The rewritten commit is: ", $new_head, "\n";
639 command(['checkout', $old_head], STDERR => 0);
642 unlink $gs->{index};
645 sub cmd_branch {
646 my ($branch_name, $head) = @_;
648 unless (defined $branch_name && length $branch_name) {
649 die(($_tag ? "tag" : "branch") . " name required\n");
651 $head ||= 'HEAD';
653 my ($src, $rev, undef, $gs) = working_head_info($head);
655 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
656 my $allglobs = $remote->{ $_tag ? 'tags' : 'branches' };
657 my $glob;
658 if ($#{$allglobs} == 0) {
659 $glob = $allglobs->[0];
660 } else {
661 unless(defined $_branch_dest) {
662 die "Multiple ",
663 $_tag ? "tag" : "branch",
664 " paths defined for Subversion repository.\n",
665 "You must specify where you want to create the ",
666 $_tag ? "tag" : "branch",
667 " with the --destination argument.\n";
669 foreach my $g (@{$allglobs}) {
670 # SVN::Git::Editor could probably be moved to Git.pm..
671 my $re = SVN::Git::Editor::glob2pat($g->{path}->{left});
672 if ($_branch_dest =~ /$re/) {
673 $glob = $g;
674 last;
677 unless (defined $glob) {
678 my $dest_re = qr/\b\Q$_branch_dest\E\b/;
679 foreach my $g (@{$allglobs}) {
680 $g->{path}->{left} =~ /$dest_re/ or next;
681 if (defined $glob) {
682 die "Ambiguous destination: ",
683 $_branch_dest, "\nmatches both '",
684 $glob->{path}->{left}, "' and '",
685 $g->{path}->{left}, "'\n";
687 $glob = $g;
689 unless (defined $glob) {
690 die "Unknown ",
691 $_tag ? "tag" : "branch",
692 " destination $_branch_dest\n";
696 my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
697 my $dst = join '/', $remote->{url}, $lft, $branch_name, ($rgt || ());
699 my $ctx = SVN::Client->new(
700 auth => Git::SVN::Ra::_auth_providers(),
701 log_msg => sub {
702 ${ $_[0] } = defined $_message
703 ? $_message
704 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
705 . $branch_name;
709 eval {
710 $ctx->ls($dst, 'HEAD', 0);
711 } and die "branch ${branch_name} already exists\n";
713 print "Copying ${src} at r${rev} to ${dst}...\n";
714 $ctx->copy($src, $rev, $dst)
715 unless $_dry_run;
717 $gs->fetch_all;
720 sub cmd_find_rev {
721 my $revision_or_hash = shift or die "SVN or git revision required ",
722 "as a command-line argument\n";
723 my $result;
724 if ($revision_or_hash =~ /^r\d+$/) {
725 my $head = shift;
726 $head ||= 'HEAD';
727 my @refs;
728 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
729 unless ($gs) {
730 die "Unable to determine upstream SVN information from ",
731 "$head history\n";
733 my $desired_revision = substr($revision_or_hash, 1);
734 $result = $gs->rev_map_get($desired_revision, $uuid);
735 } else {
736 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
737 $result = $rev;
739 print "$result\n" if $result;
742 sub cmd_rebase {
743 command_noisy(qw/update-index --refresh/);
744 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
745 unless ($gs) {
746 die "Unable to determine upstream SVN information from ",
747 "working tree history\n";
749 if ($_dry_run) {
750 print "Remote Branch: " . $gs->refname . "\n";
751 print "SVN URL: " . $url . "\n";
752 return;
754 if (command(qw/diff-index HEAD --/)) {
755 print STDERR "Cannot rebase with uncommited changes:\n";
756 command_noisy('status');
757 exit 1;
759 unless ($_local) {
760 # rebase will checkout for us, so no need to do it explicitly
761 $_no_checkout = 'true';
762 $_fetch_all ? $gs->fetch_all : $gs->fetch;
764 command_noisy(rebase_cmd(), $gs->refname);
767 sub cmd_show_ignore {
768 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
769 $gs ||= Git::SVN->new;
770 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
771 $gs->prop_walk($gs->{path}, $r, sub {
772 my ($gs, $path, $props) = @_;
773 print STDOUT "\n# $path\n";
774 my $s = $props->{'svn:ignore'} or return;
775 $s =~ s/[\r\n]+/\n/g;
776 $s =~ s/^\n+//;
777 chomp $s;
778 $s =~ s#^#$path#gm;
779 print STDOUT "$s\n";
783 sub cmd_show_externals {
784 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
785 $gs ||= Git::SVN->new;
786 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
787 $gs->prop_walk($gs->{path}, $r, sub {
788 my ($gs, $path, $props) = @_;
789 print STDOUT "\n# $path\n";
790 my $s = $props->{'svn:externals'} or return;
791 $s =~ s/[\r\n]+/\n/g;
792 chomp $s;
793 $s =~ s#^#$path#gm;
794 print STDOUT "$s\n";
798 sub cmd_create_ignore {
799 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
800 $gs ||= Git::SVN->new;
801 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
802 $gs->prop_walk($gs->{path}, $r, sub {
803 my ($gs, $path, $props) = @_;
804 # $path is of the form /path/to/dir/
805 $path = '.' . $path;
806 # SVN can have attributes on empty directories,
807 # which git won't track
808 mkpath([$path]) unless -d $path;
809 my $ignore = $path . '.gitignore';
810 my $s = $props->{'svn:ignore'} or return;
811 open(GITIGNORE, '>', $ignore)
812 or fatal("Failed to open `$ignore' for writing: $!");
813 $s =~ s/[\r\n]+/\n/g;
814 $s =~ s/^\n+//;
815 chomp $s;
816 # Prefix all patterns so that the ignore doesn't apply
817 # to sub-directories.
818 $s =~ s#^#/#gm;
819 print GITIGNORE "$s\n";
820 close(GITIGNORE)
821 or fatal("Failed to close `$ignore': $!");
822 command_noisy('add', '-f', $ignore);
826 sub canonicalize_path {
827 my ($path) = @_;
828 my $dot_slash_added = 0;
829 if (substr($path, 0, 1) ne "/") {
830 $path = "./" . $path;
831 $dot_slash_added = 1;
833 # File::Spec->canonpath doesn't collapse x/../y into y (for a
834 # good reason), so let's do this manually.
835 $path =~ s#/+#/#g;
836 $path =~ s#/\.(?:/|$)#/#g;
837 $path =~ s#/[^/]+/\.\.##g;
838 $path =~ s#/$##g;
839 $path =~ s#^\./## if $dot_slash_added;
840 $path =~ s#^/##;
841 $path =~ s#^\.$##;
842 return $path;
845 sub canonicalize_url {
846 my ($url) = @_;
847 $url =~ s#^([^:]+://[^/]*/)(.*)$#$1 . canonicalize_path($2)#e;
848 return $url;
851 # get_svnprops(PATH)
852 # ------------------
853 # Helper for cmd_propget and cmd_proplist below.
854 sub get_svnprops {
855 my $path = shift;
856 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
857 $gs ||= Git::SVN->new;
859 # prefix THE PATH by the sub-directory from which the user
860 # invoked us.
861 $path = $cmd_dir_prefix . $path;
862 fatal("No such file or directory: $path") unless -e $path;
863 my $is_dir = -d $path ? 1 : 0;
864 $path = $gs->{path} . '/' . $path;
866 # canonicalize the path (otherwise libsvn will abort or fail to
867 # find the file)
868 $path = canonicalize_path($path);
870 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
871 my $props;
872 if ($is_dir) {
873 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
875 else {
876 (undef, $props) = $gs->ra->get_file($path, $r, undef);
878 return $props;
881 # cmd_propget (PROP, PATH)
882 # ------------------------
883 # Print the SVN property PROP for PATH.
884 sub cmd_propget {
885 my ($prop, $path) = @_;
886 $path = '.' if not defined $path;
887 usage(1) if not defined $prop;
888 my $props = get_svnprops($path);
889 if (not defined $props->{$prop}) {
890 fatal("`$path' does not have a `$prop' SVN property.");
892 print $props->{$prop} . "\n";
895 # cmd_proplist (PATH)
896 # -------------------
897 # Print the list of SVN properties for PATH.
898 sub cmd_proplist {
899 my $path = shift;
900 $path = '.' if not defined $path;
901 my $props = get_svnprops($path);
902 print "Properties on '$path':\n";
903 foreach (sort keys %{$props}) {
904 print " $_\n";
908 sub cmd_multi_init {
909 my $url = shift;
910 unless (defined $_trunk || @_branches || @_tags) {
911 usage(1);
914 $_prefix = '' unless defined $_prefix;
915 if (defined $url) {
916 $url = canonicalize_url($url);
917 init_subdir(@_);
919 do_git_init_db();
920 if (defined $_trunk) {
921 my $trunk_ref = 'refs/remotes/' . $_prefix . 'trunk';
922 # try both old-style and new-style lookups:
923 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
924 unless ($gs_trunk) {
925 my ($trunk_url, $trunk_path) =
926 complete_svn_url($url, $_trunk);
927 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
928 undef, $trunk_ref);
931 return unless @_branches || @_tags;
932 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
933 foreach my $path (@_branches) {
934 complete_url_ls_init($ra, $path, '--branches/-b', $_prefix);
936 foreach my $path (@_tags) {
937 complete_url_ls_init($ra, $path, '--tags/-t', $_prefix.'tags/');
941 sub cmd_multi_fetch {
942 my $remotes = Git::SVN::read_all_remotes();
943 foreach my $repo_id (sort keys %$remotes) {
944 if ($remotes->{$repo_id}->{url}) {
945 Git::SVN::fetch_all($repo_id, $remotes);
950 # this command is special because it requires no metadata
951 sub cmd_commit_diff {
952 my ($ta, $tb, $url) = @_;
953 my $usage = "Usage: $0 commit-diff -r<revision> ".
954 "<tree-ish> <tree-ish> [<URL>]";
955 fatal($usage) if (!defined $ta || !defined $tb);
956 my $svn_path = '';
957 if (!defined $url) {
958 my $gs = eval { Git::SVN->new };
959 if (!$gs) {
960 fatal("Needed URL or usable git-svn --id in ",
961 "the command-line\n", $usage);
963 $url = $gs->{url};
964 $svn_path = $gs->{path};
966 unless (defined $_revision) {
967 fatal("-r|--revision is a required argument\n", $usage);
969 if (defined $_message && defined $_file) {
970 fatal("Both --message/-m and --file/-F specified ",
971 "for the commit message.\n",
972 "I have no idea what you mean");
974 if (defined $_file) {
975 $_message = file_to_s($_file);
976 } else {
977 $_message ||= get_commit_entry($tb)->{log};
979 my $ra ||= Git::SVN::Ra->new($url);
980 my $r = $_revision;
981 if ($r eq 'HEAD') {
982 $r = $ra->get_latest_revnum;
983 } elsif ($r !~ /^\d+$/) {
984 die "revision argument: $r not understood by git-svn\n";
986 my %ed_opts = ( r => $r,
987 log => $_message,
988 ra => $ra,
989 tree_a => $ta,
990 tree_b => $tb,
991 editor_cb => sub { print "Committed r$_[0]\n" },
992 svn_path => $svn_path );
993 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
994 print "No changes\n$ta == $tb\n";
998 sub escape_uri_only {
999 my ($uri) = @_;
1000 my @tmp;
1001 foreach (split m{/}, $uri) {
1002 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
1003 push @tmp, $_;
1005 join('/', @tmp);
1008 sub escape_url {
1009 my ($url) = @_;
1010 if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
1011 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
1012 $url = "$scheme://$domain$uri";
1014 $url;
1017 sub cmd_info {
1018 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
1019 my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
1020 if (exists $_[1]) {
1021 die "Too many arguments specified\n";
1024 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
1026 if (!$file_type && !$diff_status) {
1027 print STDERR "svn: '$path' is not under version control\n";
1028 exit 1;
1031 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1032 unless ($gs) {
1033 die "Unable to determine upstream SVN information from ",
1034 "working tree history\n";
1037 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
1038 $path = "." if $path eq "";
1040 my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
1042 if ($_url) {
1043 print escape_url($full_url), "\n";
1044 return;
1047 my $result = "Path: $path\n";
1048 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
1049 $result .= "URL: " . escape_url($full_url) . "\n";
1051 eval {
1052 my $repos_root = $gs->repos_root;
1053 Git::SVN::remove_username($repos_root);
1054 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
1056 if ($@) {
1057 $result .= "Repository Root: (offline)\n";
1059 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
1060 ($SVN::Core::VERSION le '1.5.4' || $file_type ne "dir");
1061 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
1063 $result .= "Node Kind: " .
1064 ($file_type eq "dir" ? "directory" : "file") . "\n";
1066 my $schedule = $diff_status eq "A"
1067 ? "add"
1068 : ($diff_status eq "D" ? "delete" : "normal");
1069 $result .= "Schedule: $schedule\n";
1071 if ($diff_status eq "A") {
1072 print $result, "\n";
1073 return;
1076 my ($lc_author, $lc_rev, $lc_date_utc);
1077 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
1078 my $log = command_output_pipe(@args);
1079 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
1080 while (<$log>) {
1081 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
1082 $lc_author = $1;
1083 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
1084 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
1085 (undef, $lc_rev, undef) = ::extract_metadata($1);
1088 close $log;
1090 Git::SVN::Log::set_local_timezone();
1092 $result .= "Last Changed Author: $lc_author\n";
1093 $result .= "Last Changed Rev: $lc_rev\n";
1094 $result .= "Last Changed Date: " .
1095 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
1097 if ($file_type ne "dir") {
1098 my $text_last_updated_date =
1099 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
1100 $result .=
1101 "Text Last Updated: " .
1102 Git::SVN::Log::format_svn_date($text_last_updated_date) .
1103 "\n";
1104 my $checksum;
1105 if ($diff_status eq "D") {
1106 my ($fh, $ctx) =
1107 command_output_pipe(qw(cat-file blob), "HEAD:$path");
1108 if ($file_type eq "link") {
1109 my $file_name = <$fh>;
1110 $checksum = md5sum("link $file_name");
1111 } else {
1112 $checksum = md5sum($fh);
1114 command_close_pipe($fh, $ctx);
1115 } elsif ($file_type eq "link") {
1116 my $file_name =
1117 command(qw(cat-file blob), "HEAD:$path");
1118 $checksum =
1119 md5sum("link " . $file_name);
1120 } else {
1121 open FILE, "<", $path or die $!;
1122 $checksum = md5sum(\*FILE);
1123 close FILE or die $!;
1125 $result .= "Checksum: " . $checksum . "\n";
1128 print $result, "\n";
1131 sub cmd_reset {
1132 my $target = shift || $_revision or die "SVN revision required\n";
1133 $target = $1 if $target =~ /^r(\d+)$/;
1134 $target =~ /^\d+$/ or die "Numeric SVN revision expected\n";
1135 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1136 unless ($gs) {
1137 die "Unable to determine upstream SVN information from ".
1138 "history\n";
1140 my ($r, $c) = $gs->find_rev_before($target, not $_fetch_parent);
1141 $gs->rev_map_set($r, $c, 'reset', $uuid);
1142 print "r$r = $c ($gs->{ref_id})\n";
1145 sub cmd_gc {
1146 if (!$can_compress) {
1147 warn "Compress::Zlib could not be found; unhandled.log " .
1148 "files will not be compressed.\n";
1150 find({ wanted => \&gc_directory, no_chdir => 1}, "$ENV{GIT_DIR}/svn");
1153 ########################### utility functions #########################
1155 sub rebase_cmd {
1156 my @cmd = qw/rebase/;
1157 push @cmd, '-v' if $_verbose;
1158 push @cmd, qw/--merge/ if $_merge;
1159 push @cmd, "--strategy=$_strategy" if $_strategy;
1160 @cmd;
1163 sub post_fetch_checkout {
1164 return if $_no_checkout;
1165 my $gs = $Git::SVN::_head or return;
1166 return if verify_ref('refs/heads/master^0');
1168 # look for "trunk" ref if it exists
1169 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
1170 my $fetch = $remote->{fetch};
1171 if ($fetch) {
1172 foreach my $p (keys %$fetch) {
1173 basename($fetch->{$p}) eq 'trunk' or next;
1174 $gs = Git::SVN->new($fetch->{$p}, $gs->{repo_id}, $p);
1175 last;
1179 my $valid_head = verify_ref('HEAD^0');
1180 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1181 return if ($valid_head || !verify_ref('HEAD^0'));
1183 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1184 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1185 return if -f $index;
1187 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1188 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1189 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1190 print STDERR "Checked out HEAD:\n ",
1191 $gs->full_url, " r", $gs->last_rev, "\n";
1194 sub complete_svn_url {
1195 my ($url, $path) = @_;
1196 $path =~ s#/+$##;
1197 if ($path !~ m#^[a-z\+]+://#) {
1198 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1199 fatal("E: '$path' is not a complete URL ",
1200 "and a separate URL is not specified");
1202 return ($url, $path);
1204 return ($path, '');
1207 sub complete_url_ls_init {
1208 my ($ra, $repo_path, $switch, $pfx) = @_;
1209 unless ($repo_path) {
1210 print STDERR "W: $switch not specified\n";
1211 return;
1213 $repo_path =~ s#/+$##;
1214 if ($repo_path =~ m#^[a-z\+]+://#) {
1215 $ra = Git::SVN::Ra->new($repo_path);
1216 $repo_path = '';
1217 } else {
1218 $repo_path =~ s#^/+##;
1219 unless ($ra) {
1220 fatal("E: '$repo_path' is not a complete URL ",
1221 "and a separate URL is not specified");
1224 my $url = $ra->{url};
1225 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1226 my $k = "svn-remote.$gs->{repo_id}.url";
1227 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1228 if ($orig_url && ($orig_url ne $gs->{url})) {
1229 die "$k already set: $orig_url\n",
1230 "wanted to set to: $gs->{url}\n";
1232 command_oneline('config', $k, $gs->{url}) unless $orig_url;
1233 my $remote_path = "$gs->{path}/$repo_path";
1234 $remote_path =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
1235 $remote_path =~ s#/+#/#g;
1236 $remote_path =~ s#^/##g;
1237 $remote_path .= "/*" if $remote_path !~ /\*/;
1238 my ($n) = ($switch =~ /^--(\w+)/);
1239 if (length $pfx && $pfx !~ m#/$#) {
1240 die "--prefix='$pfx' must have a trailing slash '/'\n";
1242 command_noisy('config',
1243 '--add',
1244 "svn-remote.$gs->{repo_id}.$n",
1245 "$remote_path:refs/remotes/$pfx*" .
1246 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1249 sub verify_ref {
1250 my ($ref) = @_;
1251 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1252 { STDERR => 0 }); };
1255 sub get_tree_from_treeish {
1256 my ($treeish) = @_;
1257 # $treeish can be a symbolic ref, too:
1258 my $type = command_oneline(qw/cat-file -t/, $treeish);
1259 my $expected;
1260 while ($type eq 'tag') {
1261 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1263 if ($type eq 'commit') {
1264 $expected = (grep /^tree /, command(qw/cat-file commit/,
1265 $treeish))[0];
1266 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1267 die "Unable to get tree from $treeish\n" unless $expected;
1268 } elsif ($type eq 'tree') {
1269 $expected = $treeish;
1270 } else {
1271 die "$treeish is a $type, expected tree, tag or commit\n";
1273 return $expected;
1276 sub get_commit_entry {
1277 my ($treeish) = shift;
1278 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1279 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1280 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1281 open my $log_fh, '>', $commit_editmsg or croak $!;
1283 my $type = command_oneline(qw/cat-file -t/, $treeish);
1284 if ($type eq 'commit' || $type eq 'tag') {
1285 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1286 $type, $treeish);
1287 my $in_msg = 0;
1288 my $author;
1289 my $saw_from = 0;
1290 my $msgbuf = "";
1291 while (<$msg_fh>) {
1292 if (!$in_msg) {
1293 $in_msg = 1 if (/^\s*$/);
1294 $author = $1 if (/^author (.*>)/);
1295 } elsif (/^git-svn-id: /) {
1296 # skip this for now, we regenerate the
1297 # correct one on re-fetch anyways
1298 # TODO: set *:merge properties or like...
1299 } else {
1300 if (/^From:/ || /^Signed-off-by:/) {
1301 $saw_from = 1;
1303 $msgbuf .= $_;
1306 $msgbuf =~ s/\s+$//s;
1307 if ($Git::SVN::_add_author_from && defined($author)
1308 && !$saw_from) {
1309 $msgbuf .= "\n\nFrom: $author";
1311 print $log_fh $msgbuf or croak $!;
1312 command_close_pipe($msg_fh, $ctx);
1314 close $log_fh or croak $!;
1316 if ($_edit || ($type eq 'tree')) {
1317 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1318 # TODO: strip out spaces, comments, like git-commit.sh
1319 system($editor, $commit_editmsg);
1321 rename $commit_editmsg, $commit_msg or croak $!;
1323 require Encode;
1324 # SVN requires messages to be UTF-8 when entering the repo
1325 local $/;
1326 open $log_fh, '<', $commit_msg or croak $!;
1327 binmode $log_fh;
1328 chomp($log_entry{log} = <$log_fh>);
1330 my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
1331 my $msg = $log_entry{log};
1333 eval { $msg = Encode::decode($enc, $msg, 1) };
1334 if ($@) {
1335 die "Could not decode as $enc:\n", $msg,
1336 "\nPerhaps you need to set i18n.commitencoding\n";
1339 eval { $msg = Encode::encode('UTF-8', $msg, 1) };
1340 die "Could not encode as UTF-8:\n$msg\n" if $@;
1342 $log_entry{log} = $msg;
1344 close $log_fh or croak $!;
1346 unlink $commit_msg;
1347 \%log_entry;
1350 sub s_to_file {
1351 my ($str, $file, $mode) = @_;
1352 open my $fd,'>',$file or croak $!;
1353 print $fd $str,"\n" or croak $!;
1354 close $fd or croak $!;
1355 chmod ($mode &~ umask, $file) if (defined $mode);
1358 sub file_to_s {
1359 my $file = shift;
1360 open my $fd,'<',$file or croak "$!: file: $file\n";
1361 local $/;
1362 my $ret = <$fd>;
1363 close $fd or croak $!;
1364 $ret =~ s/\s*$//s;
1365 return $ret;
1368 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1369 sub load_authors {
1370 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1371 my $log = $cmd eq 'log';
1372 while (<$authors>) {
1373 chomp;
1374 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1375 my ($user, $name, $email) = ($1, $2, $3);
1376 if ($log) {
1377 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1378 } else {
1379 $users{$user} = [$name, $email];
1382 close $authors or croak $!;
1385 # convert GetOpt::Long specs for use by git-config
1386 sub read_repo_config {
1387 return unless -d $ENV{GIT_DIR};
1388 my $opts = shift;
1389 my @config_only;
1390 foreach my $o (keys %$opts) {
1391 # if we have mixedCase and a long option-only, then
1392 # it's a config-only variable that we don't need for
1393 # the command-line.
1394 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1395 my $v = $opts->{$o};
1396 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1397 $key =~ s/-//g;
1398 my $arg = 'git config';
1399 $arg .= ' --int' if ($o =~ /[:=]i$/);
1400 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1401 if (ref $v eq 'ARRAY') {
1402 chomp(my @tmp = `$arg --get-all svn.$key`);
1403 @$v = @tmp if @tmp;
1404 } else {
1405 chomp(my $tmp = `$arg --get svn.$key`);
1406 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1407 $$v = $tmp;
1411 delete @$opts{@config_only} if @config_only;
1414 sub extract_metadata {
1415 my $id = shift or return (undef, undef, undef);
1416 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1417 \s([a-f\d\-]+)$/ix);
1418 if (!defined $rev || !$uuid || !$url) {
1419 # some of the original repositories I made had
1420 # identifiers like this:
1421 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/i);
1423 return ($url, $rev, $uuid);
1426 sub cmt_metadata {
1427 return extract_metadata((grep(/^git-svn-id: /,
1428 command(qw/cat-file commit/, shift)))[-1]);
1431 sub cmt_sha2rev_batch {
1432 my %s2r;
1433 my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1434 my $list = shift;
1436 foreach my $sha (@{$list}) {
1437 my $first = 1;
1438 my $size = 0;
1439 print $out $sha, "\n";
1441 while (my $line = <$in>) {
1442 if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1443 last;
1444 } elsif ($first &&
1445 $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1446 $first = 0;
1447 $size = $1;
1448 next;
1449 } elsif ($line =~ /^(git-svn-id: )/) {
1450 my (undef, $rev, undef) =
1451 extract_metadata($line);
1452 $s2r{$sha} = $rev;
1455 $size -= length($line);
1456 last if ($size == 0);
1460 command_close_bidi_pipe($pid, $in, $out, $ctx);
1462 return \%s2r;
1465 sub working_head_info {
1466 my ($head, $refs) = @_;
1467 my @args = ('log', '--no-color', '--first-parent', '--pretty=medium');
1468 my ($fh, $ctx) = command_output_pipe(@args, $head);
1469 my $hash;
1470 my %max;
1471 while (<$fh>) {
1472 if ( m{^commit ($::sha1)$} ) {
1473 unshift @$refs, $hash if $hash and $refs;
1474 $hash = $1;
1475 next;
1477 next unless s{^\s*(git-svn-id:)}{$1};
1478 my ($url, $rev, $uuid) = extract_metadata($_);
1479 if (defined $url && defined $rev) {
1480 next if $max{$url} and $max{$url} < $rev;
1481 if (my $gs = Git::SVN->find_by_url($url)) {
1482 my $c = $gs->rev_map_get($rev, $uuid);
1483 if ($c && $c eq $hash) {
1484 close $fh; # break the pipe
1485 return ($url, $rev, $uuid, $gs);
1486 } else {
1487 $max{$url} ||= $gs->rev_map_max;
1492 command_close_pipe($fh, $ctx);
1493 (undef, undef, undef, undef);
1496 sub read_commit_parents {
1497 my ($parents, $c) = @_;
1498 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1499 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1500 @{$parents->{$c}} = split(/ /, $p);
1503 sub linearize_history {
1504 my ($gs, $refs) = @_;
1505 my %parents;
1506 foreach my $c (@$refs) {
1507 read_commit_parents(\%parents, $c);
1510 my @linear_refs;
1511 my %skip = ();
1512 my $last_svn_commit = $gs->last_commit;
1513 foreach my $c (reverse @$refs) {
1514 next if $c eq $last_svn_commit;
1515 last if $skip{$c};
1517 unshift @linear_refs, $c;
1518 $skip{$c} = 1;
1520 # we only want the first parent to diff against for linear
1521 # history, we save the rest to inject when we finalize the
1522 # svn commit
1523 my $fp_a = verify_ref("$c~1");
1524 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1525 if (!$fp_a || !$fp_b) {
1526 die "Commit $c\n",
1527 "has no parent commit, and therefore ",
1528 "nothing to diff against.\n",
1529 "You should be working from a repository ",
1530 "originally created by git-svn\n";
1532 if ($fp_a ne $fp_b) {
1533 die "$c~1 = $fp_a, however parsing commit $c ",
1534 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1537 foreach my $p (@{$parents{$c}}) {
1538 $skip{$p} = 1;
1541 (\@linear_refs, \%parents);
1544 sub find_file_type_and_diff_status {
1545 my ($path) = @_;
1546 return ('dir', '') if $path eq '';
1548 my $diff_output =
1549 command_oneline(qw(diff --cached --name-status --), $path) || "";
1550 my $diff_status = (split(' ', $diff_output))[0] || "";
1552 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1554 return (undef, undef) if !$diff_status && !$ls_tree;
1556 if ($diff_status eq "A") {
1557 return ("link", $diff_status) if -l $path;
1558 return ("dir", $diff_status) if -d $path;
1559 return ("file", $diff_status);
1562 my $mode = (split(' ', $ls_tree))[0] || "";
1564 return ("link", $diff_status) if $mode eq "120000";
1565 return ("dir", $diff_status) if $mode eq "040000";
1566 return ("file", $diff_status);
1569 sub md5sum {
1570 my $arg = shift;
1571 my $ref = ref $arg;
1572 my $md5 = Digest::MD5->new();
1573 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
1574 $md5->addfile($arg) or croak $!;
1575 } elsif ($ref eq 'SCALAR') {
1576 $md5->add($$arg) or croak $!;
1577 } elsif (!$ref) {
1578 $md5->add($arg) or croak $!;
1579 } else {
1580 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1582 return $md5->hexdigest();
1585 sub gc_directory {
1586 if ($can_compress && -f $_ && basename($_) eq "unhandled.log") {
1587 my $out_filename = $_ . ".gz";
1588 open my $in_fh, "<", $_ or die "Unable to open $_: $!\n";
1589 binmode $in_fh;
1590 my $gz = Compress::Zlib::gzopen($out_filename, "ab") or
1591 die "Unable to open $out_filename: $!\n";
1593 my $res;
1594 while ($res = sysread($in_fh, my $str, 1024)) {
1595 $gz->gzwrite($str) or
1596 die "Unable to write: ".$gz->gzerror()."!\n";
1598 unlink $_ or die "unlink $File::Find::name: $!\n";
1599 } elsif (-f $_ && basename($_) eq "index") {
1600 unlink $_ or die "unlink $_: $!\n";
1604 package Git::SVN;
1605 use strict;
1606 use warnings;
1607 use Fcntl qw/:DEFAULT :seek/;
1608 use constant rev_map_fmt => 'NH40';
1609 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1610 $_repack $_repack_flags $_use_svm_props $_head
1611 $_use_svnsync_props $no_reuse_existing $_minimize_url
1612 $_use_log_author $_add_author_from $_localtime/;
1613 use Carp qw/croak/;
1614 use File::Path qw/mkpath/;
1615 use File::Copy qw/copy/;
1616 use IPC::Open3;
1618 my ($_gc_nr, $_gc_period);
1620 # properties that we do not log:
1621 my %SKIP_PROP;
1622 BEGIN {
1623 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1624 svn:special svn:executable
1625 svn:entry:committed-rev
1626 svn:entry:last-author
1627 svn:entry:uuid
1628 svn:entry:committed-date/;
1630 # some options are read globally, but can be overridden locally
1631 # per [svn-remote "..."] section. Command-line options will *NOT*
1632 # override options set in an [svn-remote "..."] section
1633 no strict 'refs';
1634 for my $option (qw/follow_parent no_metadata use_svm_props
1635 use_svnsync_props/) {
1636 my $key = $option;
1637 $key =~ tr/_//d;
1638 my $prop = "-$option";
1639 *$option = sub {
1640 my ($self) = @_;
1641 return $self->{$prop} if exists $self->{$prop};
1642 my $k = "svn-remote.$self->{repo_id}.$key";
1643 eval { command_oneline(qw/config --get/, $k) };
1644 if ($@) {
1645 $self->{$prop} = ${"Git::SVN::_$option"};
1646 } else {
1647 my $v = command_oneline(qw/config --bool/,$k);
1648 $self->{$prop} = $v eq 'false' ? 0 : 1;
1650 return $self->{$prop};
1656 my (%LOCKFILES, %INDEX_FILES);
1657 END {
1658 unlink keys %LOCKFILES if %LOCKFILES;
1659 unlink keys %INDEX_FILES if %INDEX_FILES;
1662 sub resolve_local_globs {
1663 my ($url, $fetch, $glob_spec) = @_;
1664 return unless defined $glob_spec;
1665 my $ref = $glob_spec->{ref};
1666 my $path = $glob_spec->{path};
1667 foreach (command(qw#for-each-ref --format=%(refname) refs/#)) {
1668 next unless m#^$ref->{regex}$#;
1669 my $p = $1;
1670 my $pathname = desanitize_refname($path->full_path($p));
1671 my $refname = desanitize_refname($ref->full_path($p));
1672 if (my $existing = $fetch->{$pathname}) {
1673 if ($existing ne $refname) {
1674 die "Refspec conflict:\n",
1675 "existing: $existing\n",
1676 " globbed: $refname\n";
1678 my $u = (::cmt_metadata("$refname"))[0];
1679 $u =~ s!^\Q$url\E(/|$)!! or die
1680 "$refname: '$url' not found in '$u'\n";
1681 if ($pathname ne $u) {
1682 warn "W: Refspec glob conflict ",
1683 "(ref: $refname):\n",
1684 "expected path: $pathname\n",
1685 " real path: $u\n",
1686 "Continuing ahead with $u\n";
1687 next;
1689 } else {
1690 $fetch->{$pathname} = $refname;
1695 sub parse_revision_argument {
1696 my ($base, $head) = @_;
1697 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1698 return ($base, $head);
1700 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1701 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1702 return ($head, $head) if ($::_revision eq 'HEAD');
1703 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1704 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1705 die "revision argument: $::_revision not understood by git-svn\n";
1708 sub fetch_all {
1709 my ($repo_id, $remotes) = @_;
1710 if (ref $repo_id) {
1711 my $gs = $repo_id;
1712 $repo_id = undef;
1713 $repo_id = $gs->{repo_id};
1715 $remotes ||= read_all_remotes();
1716 my $remote = $remotes->{$repo_id} or
1717 die "[svn-remote \"$repo_id\"] unknown\n";
1718 my $fetch = $remote->{fetch};
1719 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1720 my (@gs, @globs);
1721 my $ra = Git::SVN::Ra->new($url);
1722 my $uuid = $ra->get_uuid;
1723 my $head = $ra->get_latest_revnum;
1724 $ra->get_log("", $head, 0, 1, 0, 1, sub { $head = $_[1] });
1725 my $base = defined $fetch ? $head : 0;
1727 # read the max revs for wildcard expansion (branches/*, tags/*)
1728 foreach my $t (qw/branches tags/) {
1729 defined $remote->{$t} or next;
1730 push @globs, @{$remote->{$t}};
1732 my $max_rev = eval { tmp_config(qw/--int --get/,
1733 "svn-remote.$repo_id.${t}-maxRev") };
1734 if (defined $max_rev && ($max_rev < $base)) {
1735 $base = $max_rev;
1736 } elsif (!defined $max_rev) {
1737 $base = 0;
1741 if ($fetch) {
1742 foreach my $p (sort keys %$fetch) {
1743 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1744 my $lr = $gs->rev_map_max;
1745 if (defined $lr) {
1746 $base = $lr if ($lr < $base);
1748 push @gs, $gs;
1752 ($base, $head) = parse_revision_argument($base, $head);
1753 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1756 sub read_all_remotes {
1757 my $r = {};
1758 my $use_svm_props = eval { command_oneline(qw/config --bool
1759 svn.useSvmProps/) };
1760 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
1761 my $svn_refspec = qr{\s*/?(.*?)\s*:\s*(.+?)\s*};
1762 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1763 if (m!^(.+)\.fetch=$svn_refspec$!) {
1764 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
1765 die("svn-remote.$remote: remote ref '$remote_ref' "
1766 . "must start with 'refs/'\n")
1767 unless $remote_ref =~ m{^refs/};
1768 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1769 $r->{$remote}->{svm} = {} if $use_svm_props;
1770 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
1771 $r->{$1}->{svm} = {};
1772 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1773 $r->{$1}->{url} = $2;
1774 } elsif (m!^(.+)\.(branches|tags)=$svn_refspec$!) {
1775 my ($remote, $t, $local_ref, $remote_ref) =
1776 ($1, $2, $3, $4);
1777 die("svn-remote.$remote: remote ref '$remote_ref' ($t) "
1778 . "must start with 'refs/'\n")
1779 unless $remote_ref =~ m{^refs/};
1780 my $rs = {
1781 t => $t,
1782 remote => $remote,
1783 path => Git::SVN::GlobSpec->new($local_ref),
1784 ref => Git::SVN::GlobSpec->new($remote_ref) };
1785 if (length($rs->{ref}->{right}) != 0) {
1786 die "The '*' glob character must be the last ",
1787 "character of '$remote_ref'\n";
1789 push @{ $r->{$remote}->{$t} }, $rs;
1793 map {
1794 if (defined $r->{$_}->{svm}) {
1795 my $svm;
1796 eval {
1797 my $section = "svn-remote.$_";
1798 $svm = {
1799 source => tmp_config('--get',
1800 "$section.svm-source"),
1801 replace => tmp_config('--get',
1802 "$section.svm-replace"),
1805 $r->{$_}->{svm} = $svm;
1807 } keys %$r;
1812 sub init_vars {
1813 $_gc_nr = $_gc_period = 1000;
1814 if (defined $_repack || defined $_repack_flags) {
1815 warn "Repack options are obsolete; they have no effect.\n";
1819 sub verify_remotes_sanity {
1820 return unless -d $ENV{GIT_DIR};
1821 my %seen;
1822 foreach (command(qw/config -l/)) {
1823 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1824 if ($seen{$1}) {
1825 die "Remote ref refs/remote/$1 is tracked by",
1826 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1827 "Please resolve this ambiguity in ",
1828 "your git configuration file before ",
1829 "continuing\n";
1831 $seen{$1} = $_;
1836 sub find_existing_remote {
1837 my ($url, $remotes) = @_;
1838 return undef if $no_reuse_existing;
1839 my $existing;
1840 foreach my $repo_id (keys %$remotes) {
1841 my $u = $remotes->{$repo_id}->{url} or next;
1842 next if $u ne $url;
1843 $existing = $repo_id;
1844 last;
1846 $existing;
1849 sub init_remote_config {
1850 my ($self, $url, $no_write) = @_;
1851 $url =~ s!/+$!!; # strip trailing slash
1852 my $r = read_all_remotes();
1853 my $existing = find_existing_remote($url, $r);
1854 if ($existing) {
1855 unless ($no_write) {
1856 print STDERR "Using existing ",
1857 "[svn-remote \"$existing\"]\n";
1859 $self->{repo_id} = $existing;
1860 } elsif ($_minimize_url) {
1861 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1862 $existing = find_existing_remote($min_url, $r);
1863 if ($existing) {
1864 unless ($no_write) {
1865 print STDERR "Using existing ",
1866 "[svn-remote \"$existing\"]\n";
1868 $self->{repo_id} = $existing;
1870 if ($min_url ne $url) {
1871 unless ($no_write) {
1872 print STDERR "Using higher level of URL: ",
1873 "$url => $min_url\n";
1875 my $old_path = $self->{path};
1876 $self->{path} = $url;
1877 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1878 if (length $old_path) {
1879 $self->{path} .= "/$old_path";
1881 $url = $min_url;
1884 my $orig_url;
1885 if (!$existing) {
1886 # verify that we aren't overwriting anything:
1887 $orig_url = eval {
1888 command_oneline('config', '--get',
1889 "svn-remote.$self->{repo_id}.url")
1891 if ($orig_url && ($orig_url ne $url)) {
1892 die "svn-remote.$self->{repo_id}.url already set: ",
1893 "$orig_url\nwanted to set to: $url\n";
1896 my ($xrepo_id, $xpath) = find_ref($self->refname);
1897 if (!$no_write && defined $xpath) {
1898 die "svn-remote.$xrepo_id.fetch already set to track ",
1899 "$xpath:", $self->refname, "\n";
1901 unless ($no_write) {
1902 command_noisy('config',
1903 "svn-remote.$self->{repo_id}.url", $url);
1904 $self->{path} =~ s{^/}{};
1905 $self->{path} =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
1906 command_noisy('config', '--add',
1907 "svn-remote.$self->{repo_id}.fetch",
1908 "$self->{path}:".$self->refname);
1910 $self->{url} = $url;
1913 sub find_by_url { # repos_root and, path are optional
1914 my ($class, $full_url, $repos_root, $path) = @_;
1916 return undef unless defined $full_url;
1917 remove_username($full_url);
1918 remove_username($repos_root) if defined $repos_root;
1919 my $remotes = read_all_remotes();
1920 if (defined $full_url && defined $repos_root && !defined $path) {
1921 $path = $full_url;
1922 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1924 foreach my $repo_id (keys %$remotes) {
1925 my $u = $remotes->{$repo_id}->{url} or next;
1926 remove_username($u);
1927 next if defined $repos_root && $repos_root ne $u;
1929 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1930 foreach my $t (qw/branches tags/) {
1931 foreach my $globspec (@{$remotes->{$repo_id}->{$t}}) {
1932 resolve_local_globs($u, $fetch, $globspec);
1935 my $p = $path;
1936 my $rwr = rewrite_root({repo_id => $repo_id});
1937 my $svm = $remotes->{$repo_id}->{svm}
1938 if defined $remotes->{$repo_id}->{svm};
1939 unless (defined $p) {
1940 $p = $full_url;
1941 my $z = $u;
1942 my $prefix = '';
1943 if ($rwr) {
1944 $z = $rwr;
1945 remove_username($z);
1946 } elsif (defined $svm) {
1947 $z = $svm->{source};
1948 $prefix = $svm->{replace};
1949 $prefix =~ s#^\Q$u\E(?:/|$)##;
1950 $prefix =~ s#/$##;
1952 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
1954 foreach my $f (keys %$fetch) {
1955 next if $f ne $p;
1956 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1959 undef;
1962 sub init {
1963 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1964 my $self = _new($class, $repo_id, $ref_id, $path);
1965 if (defined $url) {
1966 $self->init_remote_config($url, $no_write);
1968 $self;
1971 sub find_ref {
1972 my ($ref_id) = @_;
1973 foreach (command(qw/config -l/)) {
1974 next unless m!^svn-remote\.(.+)\.fetch=
1975 \s*/?(.*?)\s*:\s*(.+?)\s*$!x;
1976 my ($repo_id, $path, $ref) = ($1, $2, $3);
1977 if ($ref eq $ref_id) {
1978 $path = '' if ($path =~ m#^\./?#);
1979 return ($repo_id, $path);
1982 (undef, undef, undef);
1985 sub new {
1986 my ($class, $ref_id, $repo_id, $path) = @_;
1987 if (defined $ref_id && !defined $repo_id && !defined $path) {
1988 ($repo_id, $path) = find_ref($ref_id);
1989 if (!defined $repo_id) {
1990 die "Could not find a \"svn-remote.*.fetch\" key ",
1991 "in the repository configuration matching: ",
1992 "$ref_id\n";
1995 my $self = _new($class, $repo_id, $ref_id, $path);
1996 if (!defined $self->{path} || !length $self->{path}) {
1997 my $fetch = command_oneline('config', '--get',
1998 "svn-remote.$repo_id.fetch",
1999 ":$ref_id\$") or
2000 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
2001 "\":$ref_id\$\" in config\n";
2002 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
2004 $self->{url} = command_oneline('config', '--get',
2005 "svn-remote.$repo_id.url") or
2006 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
2007 $self->rebuild;
2008 $self;
2011 sub refname {
2012 my ($refname) = $_[0]->{ref_id} ;
2014 # It cannot end with a slash /, we'll throw up on this because
2015 # SVN can't have directories with a slash in their name, either:
2016 if ($refname =~ m{/$}) {
2017 die "ref: '$refname' ends with a trailing slash, this is ",
2018 "not permitted by git nor Subversion\n";
2021 # It cannot have ASCII control character space, tilde ~, caret ^,
2022 # colon :, question-mark ?, asterisk *, space, or open bracket [
2023 # anywhere.
2025 # Additionally, % must be escaped because it is used for escaping
2026 # and we want our escaped refname to be reversible
2027 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
2029 # no slash-separated component can begin with a dot .
2030 # /.* becomes /%2E*
2031 $refname =~ s{/\.}{/%2E}g;
2033 # It cannot have two consecutive dots .. anywhere
2034 # .. becomes %2E%2E
2035 $refname =~ s{\.\.}{%2E%2E}g;
2037 return $refname;
2040 sub desanitize_refname {
2041 my ($refname) = @_;
2042 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
2043 return $refname;
2046 sub svm_uuid {
2047 my ($self) = @_;
2048 return $self->{svm}->{uuid} if $self->svm;
2049 $self->ra;
2050 unless ($self->{svm}) {
2051 die "SVM UUID not cached, and reading remotely failed\n";
2053 $self->{svm}->{uuid};
2056 sub svm {
2057 my ($self) = @_;
2058 return $self->{svm} if $self->{svm};
2059 my $svm;
2060 # see if we have it in our config, first:
2061 eval {
2062 my $section = "svn-remote.$self->{repo_id}";
2063 $svm = {
2064 source => tmp_config('--get', "$section.svm-source"),
2065 uuid => tmp_config('--get', "$section.svm-uuid"),
2066 replace => tmp_config('--get', "$section.svm-replace"),
2069 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
2070 $self->{svm} = $svm;
2072 $self->{svm};
2075 sub _set_svm_vars {
2076 my ($self, $ra) = @_;
2077 return $ra if $self->svm;
2079 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
2080 "(svm:source, svm:uuid) ",
2081 "from the following URLs:\n" );
2082 sub read_svm_props {
2083 my ($self, $ra, $path, $r) = @_;
2084 my $props = ($ra->get_dir($path, $r))[2];
2085 my $src = $props->{'svm:source'};
2086 my $uuid = $props->{'svm:uuid'};
2087 return undef if (!$src || !$uuid);
2089 chomp($src, $uuid);
2091 $uuid =~ m{^[0-9a-f\-]{30,}$}i
2092 or die "doesn't look right - svm:uuid is '$uuid'\n";
2094 # the '!' is used to mark the repos_root!/relative/path
2095 $src =~ s{/?!/?}{/};
2096 $src =~ s{/+$}{}; # no trailing slashes please
2097 # username is of no interest
2098 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
2100 my $replace = $ra->{url};
2101 $replace .= "/$path" if length $path;
2103 my $section = "svn-remote.$self->{repo_id}";
2104 tmp_config("$section.svm-source", $src);
2105 tmp_config("$section.svm-replace", $replace);
2106 tmp_config("$section.svm-uuid", $uuid);
2107 $self->{svm} = {
2108 source => $src,
2109 uuid => $uuid,
2110 replace => $replace
2114 my $r = $ra->get_latest_revnum;
2115 my $path = $self->{path};
2116 my %tried;
2117 while (length $path) {
2118 unless ($tried{"$self->{url}/$path"}) {
2119 return $ra if $self->read_svm_props($ra, $path, $r);
2120 $tried{"$self->{url}/$path"} = 1;
2122 $path =~ s#/?[^/]+$##;
2124 die "Path: '$path' should be ''\n" if $path ne '';
2125 return $ra if $self->read_svm_props($ra, $path, $r);
2126 $tried{"$self->{url}/$path"} = 1;
2128 if ($ra->{repos_root} eq $self->{url}) {
2129 die @err, (map { " $_\n" } keys %tried), "\n";
2132 # nope, make sure we're connected to the repository root:
2133 my $ok;
2134 my @tried_b;
2135 $path = $ra->{svn_path};
2136 $ra = Git::SVN::Ra->new($ra->{repos_root});
2137 while (length $path) {
2138 unless ($tried{"$ra->{url}/$path"}) {
2139 $ok = $self->read_svm_props($ra, $path, $r);
2140 last if $ok;
2141 $tried{"$ra->{url}/$path"} = 1;
2143 $path =~ s#/?[^/]+$##;
2145 die "Path: '$path' should be ''\n" if $path ne '';
2146 $ok ||= $self->read_svm_props($ra, $path, $r);
2147 $tried{"$ra->{url}/$path"} = 1;
2148 if (!$ok) {
2149 die @err, (map { " $_\n" } keys %tried), "\n";
2151 Git::SVN::Ra->new($self->{url});
2154 sub svnsync {
2155 my ($self) = @_;
2156 return $self->{svnsync} if $self->{svnsync};
2158 if ($self->no_metadata) {
2159 die "Can't have both 'noMetadata' and ",
2160 "'useSvnsyncProps' options set!\n";
2162 if ($self->rewrite_root) {
2163 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
2164 "options set!\n";
2167 my $svnsync;
2168 # see if we have it in our config, first:
2169 eval {
2170 my $section = "svn-remote.$self->{repo_id}";
2172 my $url = tmp_config('--get', "$section.svnsync-url");
2173 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2174 die "doesn't look right - svn:sync-from-url is '$url'\n";
2176 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
2177 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2178 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2180 $svnsync = { url => $url, uuid => $uuid }
2182 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
2183 return $self->{svnsync} = $svnsync;
2186 my $err = "useSvnsyncProps set, but failed to read " .
2187 "svnsync property: svn:sync-from-";
2188 my $rp = $self->ra->rev_proplist(0);
2190 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
2191 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2192 die "doesn't look right - svn:sync-from-url is '$url'\n";
2194 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
2195 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2196 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2198 my $section = "svn-remote.$self->{repo_id}";
2199 tmp_config('--add', "$section.svnsync-uuid", $uuid);
2200 tmp_config('--add', "$section.svnsync-url", $url);
2201 return $self->{svnsync} = { url => $url, uuid => $uuid };
2204 # this allows us to memoize our SVN::Ra UUID locally and avoid a
2205 # remote lookup (useful for 'git svn log').
2206 sub ra_uuid {
2207 my ($self) = @_;
2208 unless ($self->{ra_uuid}) {
2209 my $key = "svn-remote.$self->{repo_id}.uuid";
2210 my $uuid = eval { tmp_config('--get', $key) };
2211 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/i) {
2212 $self->{ra_uuid} = $uuid;
2213 } else {
2214 die "ra_uuid called without URL\n" unless $self->{url};
2215 $self->{ra_uuid} = $self->ra->get_uuid;
2216 tmp_config('--add', $key, $self->{ra_uuid});
2219 $self->{ra_uuid};
2222 sub _set_repos_root {
2223 my ($self, $repos_root) = @_;
2224 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2225 $repos_root ||= $self->ra->{repos_root};
2226 tmp_config($k, $repos_root);
2227 $repos_root;
2230 sub repos_root {
2231 my ($self) = @_;
2232 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2233 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
2236 sub ra {
2237 my ($self) = shift;
2238 my $ra = Git::SVN::Ra->new($self->{url});
2239 $self->_set_repos_root($ra->{repos_root});
2240 if ($self->use_svm_props && !$self->{svm}) {
2241 if ($self->no_metadata) {
2242 die "Can't have both 'noMetadata' and ",
2243 "'useSvmProps' options set!\n";
2244 } elsif ($self->use_svnsync_props) {
2245 die "Can't have both 'useSvnsyncProps' and ",
2246 "'useSvmProps' options set!\n";
2248 $ra = $self->_set_svm_vars($ra);
2249 $self->{-want_revprops} = 1;
2251 $ra;
2254 # prop_walk(PATH, REV, SUB)
2255 # -------------------------
2256 # Recursively traverse PATH at revision REV and invoke SUB for each
2257 # directory that contains a SVN property. SUB will be invoked as
2258 # follows: &SUB(gs, path, props); where `gs' is this instance of
2259 # Git::SVN, `path' the path to the directory where the properties
2260 # `props' were found. The `path' will be relative to point of checkout,
2261 # that is, if url://repo/trunk is the current Git branch, and that
2262 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
2263 # as `path' (note the trailing `/').
2264 sub prop_walk {
2265 my ($self, $path, $rev, $sub) = @_;
2267 $path =~ s#^/##;
2268 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2269 $path =~ s#^/*#/#g;
2270 my $p = $path;
2271 # Strip the irrelevant part of the path.
2272 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2273 # Ensure the path is terminated by a `/'.
2274 $p =~ s#/*$#/#;
2276 # The properties contain all the internal SVN stuff nobody
2277 # (usually) cares about.
2278 my $interesting_props = 0;
2279 foreach (keys %{$props}) {
2280 # If it doesn't start with `svn:', it must be a
2281 # user-defined property.
2282 ++$interesting_props and next if $_ !~ /^svn:/;
2283 # FIXME: Fragile, if SVN adds new public properties,
2284 # this needs to be updated.
2285 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2286 |eol-style|mime-type
2287 |externals|needs-lock)$/x;
2289 &$sub($self, $p, $props) if $interesting_props;
2291 foreach (sort keys %$dirent) {
2292 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
2293 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
2297 sub last_rev { ($_[0]->last_rev_commit)[0] }
2298 sub last_commit { ($_[0]->last_rev_commit)[1] }
2300 # returns the newest SVN revision number and newest commit SHA1
2301 sub last_rev_commit {
2302 my ($self) = @_;
2303 if (defined $self->{last_rev} && defined $self->{last_commit}) {
2304 return ($self->{last_rev}, $self->{last_commit});
2306 my $c = ::verify_ref($self->refname.'^0');
2307 if ($c && !$self->use_svm_props && !$self->no_metadata) {
2308 my $rev = (::cmt_metadata($c))[1];
2309 if (defined $rev) {
2310 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2311 return ($rev, $c);
2314 my $map_path = $self->map_path;
2315 unless (-e $map_path) {
2316 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2317 return (undef, undef);
2319 my ($rev, $commit) = $self->rev_map_max(1);
2320 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2321 return ($rev, $commit);
2324 sub get_fetch_range {
2325 my ($self, $min, $max) = @_;
2326 $max ||= $self->ra->get_latest_revnum;
2327 $min ||= $self->rev_map_max;
2328 (++$min, $max);
2331 sub tmp_config {
2332 my (@args) = @_;
2333 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2334 my $config = "$ENV{GIT_DIR}/svn/.metadata";
2335 if (! -f $config && -f $old_def_config) {
2336 rename $old_def_config, $config or
2337 die "Failed rename $old_def_config => $config: $!\n";
2339 my $old_config = $ENV{GIT_CONFIG};
2340 $ENV{GIT_CONFIG} = $config;
2341 $@ = undef;
2342 my @ret = eval {
2343 unless (-f $config) {
2344 mkfile($config);
2345 open my $fh, '>', $config or
2346 die "Can't open $config: $!\n";
2347 print $fh "; This file is used internally by ",
2348 "git-svn\n" or die
2349 "Couldn't write to $config: $!\n";
2350 print $fh "; You should not have to edit it\n" or
2351 die "Couldn't write to $config: $!\n";
2352 close $fh or die "Couldn't close $config: $!\n";
2354 command('config', @args);
2356 my $err = $@;
2357 if (defined $old_config) {
2358 $ENV{GIT_CONFIG} = $old_config;
2359 } else {
2360 delete $ENV{GIT_CONFIG};
2362 die $err if $err;
2363 wantarray ? @ret : $ret[0];
2366 sub tmp_index_do {
2367 my ($self, $sub) = @_;
2368 my $old_index = $ENV{GIT_INDEX_FILE};
2369 $ENV{GIT_INDEX_FILE} = $self->{index};
2370 $@ = undef;
2371 my @ret = eval {
2372 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2373 mkpath([$dir]) unless -d $dir;
2374 &$sub;
2376 my $err = $@;
2377 if (defined $old_index) {
2378 $ENV{GIT_INDEX_FILE} = $old_index;
2379 } else {
2380 delete $ENV{GIT_INDEX_FILE};
2382 die $err if $err;
2383 wantarray ? @ret : $ret[0];
2386 sub assert_index_clean {
2387 my ($self, $treeish) = @_;
2389 $self->tmp_index_do(sub {
2390 command_noisy('read-tree', $treeish) unless -e $self->{index};
2391 my $x = command_oneline('write-tree');
2392 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2393 /^tree ($::sha1)/mo);
2394 return if $y eq $x;
2396 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2397 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2398 command_noisy('read-tree', $treeish);
2399 $x = command_oneline('write-tree');
2400 if ($y ne $x) {
2401 ::fatal "trees ($treeish) $y != $x\n",
2402 "Something is seriously wrong...";
2407 sub get_commit_parents {
2408 my ($self, $log_entry) = @_;
2409 my (%seen, @ret, @tmp);
2410 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2411 if (my $ip = $self->{inject_parents}) {
2412 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2413 push @tmp, $commit;
2416 if (my $cur = ::verify_ref($self->refname.'^0')) {
2417 push @tmp, $cur;
2419 if (my $ipd = $self->{inject_parents_dcommit}) {
2420 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2421 push @tmp, @$commit;
2424 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2425 while (my $p = shift @tmp) {
2426 next if $seen{$p};
2427 $seen{$p} = 1;
2428 push @ret, $p;
2429 # MAXPARENT is defined to 16 in commit-tree.c:
2430 last if @ret >= 16;
2432 if (@tmp) {
2433 die "r$log_entry->{revision}: No room for parents:\n\t",
2434 join("\n\t", @tmp), "\n";
2436 @ret;
2439 sub rewrite_root {
2440 my ($self) = @_;
2441 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2442 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2443 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2444 if ($rwr) {
2445 $rwr =~ s#/+$##;
2446 if ($rwr !~ m#^[a-z\+]+://#) {
2447 die "$rwr is not a valid URL (key: $k)\n";
2450 $self->{-rewrite_root} = $rwr;
2453 sub metadata_url {
2454 my ($self) = @_;
2455 ($self->rewrite_root || $self->{url}) .
2456 (length $self->{path} ? '/' . $self->{path} : '');
2459 sub full_url {
2460 my ($self) = @_;
2461 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2465 sub set_commit_header_env {
2466 my ($log_entry) = @_;
2467 my %env;
2468 foreach my $ned (qw/NAME EMAIL DATE/) {
2469 foreach my $ac (qw/AUTHOR COMMITTER/) {
2470 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2474 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2475 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2476 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2478 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2479 ? $log_entry->{commit_name}
2480 : $log_entry->{name};
2481 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2482 ? $log_entry->{commit_email}
2483 : $log_entry->{email};
2484 \%env;
2487 sub restore_commit_header_env {
2488 my ($env) = @_;
2489 foreach my $ned (qw/NAME EMAIL DATE/) {
2490 foreach my $ac (qw/AUTHOR COMMITTER/) {
2491 my $k = "GIT_${ac}_${ned}";
2492 if (defined $env->{$k}) {
2493 $ENV{$k} = $env->{$k};
2494 } else {
2495 delete $ENV{$k};
2501 sub gc {
2502 command_noisy('gc', '--auto');
2505 sub do_git_commit {
2506 my ($self, $log_entry) = @_;
2507 my $lr = $self->last_rev;
2508 if (defined $lr && $lr >= $log_entry->{revision}) {
2509 die "Last fetched revision of ", $self->refname,
2510 " was r$lr, but we are about to fetch: ",
2511 "r$log_entry->{revision}!\n";
2513 if (my $c = $self->rev_map_get($log_entry->{revision})) {
2514 croak "$log_entry->{revision} = $c already exists! ",
2515 "Why are we refetching it?\n";
2517 my $old_env = set_commit_header_env($log_entry);
2518 my $tree = $log_entry->{tree};
2519 if (!defined $tree) {
2520 $tree = $self->tmp_index_do(sub {
2521 command_oneline('write-tree') });
2523 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2525 my @exec = ('git', 'commit-tree', $tree);
2526 foreach ($self->get_commit_parents($log_entry)) {
2527 push @exec, '-p', $_;
2529 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2530 or croak $!;
2531 binmode $msg_fh;
2533 # we always get UTF-8 from SVN, but we may want our commits in
2534 # a different encoding.
2535 if (my $enc = Git::config('i18n.commitencoding')) {
2536 require Encode;
2537 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
2539 print $msg_fh $log_entry->{log} or croak $!;
2540 restore_commit_header_env($old_env);
2541 unless ($self->no_metadata) {
2542 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2543 or croak $!;
2545 $msg_fh->flush == 0 or croak $!;
2546 close $msg_fh or croak $!;
2547 chomp(my $commit = do { local $/; <$out_fh> });
2548 close $out_fh or croak $!;
2549 waitpid $pid, 0;
2550 croak $? if $?;
2551 if ($commit !~ /^$::sha1$/o) {
2552 die "Failed to commit, invalid sha1: $commit\n";
2555 $self->rev_map_set($log_entry->{revision}, $commit, 1);
2557 $self->{last_rev} = $log_entry->{revision};
2558 $self->{last_commit} = $commit;
2559 print "r$log_entry->{revision}" unless $::_q > 1;
2560 if (defined $log_entry->{svm_revision}) {
2561 print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
2562 $self->rev_map_set($log_entry->{svm_revision}, $commit,
2563 0, $self->svm_uuid);
2565 print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
2566 if (--$_gc_nr == 0) {
2567 $_gc_nr = $_gc_period;
2568 gc();
2570 return $commit;
2573 sub match_paths {
2574 my ($self, $paths, $r) = @_;
2575 return 1 if $self->{path} eq '';
2576 if (my $path = $paths->{"/$self->{path}"}) {
2577 return ($path->{action} eq 'D') ? 0 : 1;
2579 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
2580 if (grep /$self->{path_regex}/, keys %$paths) {
2581 return 1;
2583 my $c = '';
2584 foreach (split m#/#, $self->{path}) {
2585 $c .= "/$_";
2586 next unless ($paths->{$c} &&
2587 ($paths->{$c}->{action} =~ /^[AR]$/));
2588 if ($self->ra->check_path($self->{path}, $r) ==
2589 $SVN::Node::dir) {
2590 return 1;
2593 return 0;
2596 sub find_parent_branch {
2597 my ($self, $paths, $rev) = @_;
2598 return undef unless $self->follow_parent;
2599 unless (defined $paths) {
2600 my $err_handler = $SVN::Error::handler;
2601 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2602 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1,
2603 sub { $paths = $_[0] });
2604 $SVN::Error::handler = $err_handler;
2606 return undef unless defined $paths;
2608 # look for a parent from another branch:
2609 my @b_path_components = split m#/#, $self->{path};
2610 my @a_path_components;
2611 my $i;
2612 while (@b_path_components) {
2613 $i = $paths->{'/'.join('/', @b_path_components)};
2614 last if $i && defined $i->{copyfrom_path};
2615 unshift(@a_path_components, pop(@b_path_components));
2617 return undef unless defined $i && defined $i->{copyfrom_path};
2618 my $branch_from = $i->{copyfrom_path};
2619 if (@a_path_components) {
2620 print STDERR "branch_from: $branch_from => ";
2621 $branch_from .= '/'.join('/', @a_path_components);
2622 print STDERR $branch_from, "\n";
2624 my $r = $i->{copyfrom_rev};
2625 my $repos_root = $self->ra->{repos_root};
2626 my $url = $self->ra->{url};
2627 my $new_url = $url . $branch_from;
2628 print STDERR "Found possible branch point: ",
2629 "$new_url => ", $self->full_url, ", $r\n";
2630 $branch_from =~ s#^/##;
2631 my $gs = $self->other_gs($new_url, $url,
2632 $branch_from, $r, $self->{ref_id});
2633 my ($r0, $parent) = $gs->find_rev_before($r, 1);
2635 my ($base, $head);
2636 if (!defined $r0 || !defined $parent) {
2637 ($base, $head) = parse_revision_argument(0, $r);
2638 } else {
2639 if ($r0 < $r) {
2640 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
2641 0, 1, sub { $base = $_[1] - 1 });
2644 if (defined $base && $base <= $r) {
2645 $gs->fetch($base, $r);
2647 ($r0, $parent) = $gs->find_rev_before($r, 1);
2649 if (defined $r0 && defined $parent) {
2650 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
2651 my $ed;
2652 if ($self->ra->can_do_switch) {
2653 $self->assert_index_clean($parent);
2654 print STDERR "Following parent with do_switch\n";
2655 # do_switch works with svn/trunk >= r22312, but that
2656 # is not included with SVN 1.4.3 (the latest version
2657 # at the moment), so we can't rely on it
2658 $self->{last_rev} = $r0;
2659 $self->{last_commit} = $parent;
2660 $ed = SVN::Git::Fetcher->new($self, $gs->{path});
2661 $gs->ra->gs_do_switch($r0, $rev, $gs,
2662 $self->full_url, $ed)
2663 or die "SVN connection failed somewhere...\n";
2664 } elsif ($self->ra->trees_match($new_url, $r0,
2665 $self->full_url, $rev)) {
2666 print STDERR "Trees match:\n",
2667 " $new_url\@$r0\n",
2668 " ${\$self->full_url}\@$rev\n",
2669 "Following parent with no changes\n";
2670 $self->tmp_index_do(sub {
2671 command_noisy('read-tree', $parent);
2673 $self->{last_commit} = $parent;
2674 } else {
2675 print STDERR "Following parent with do_update\n";
2676 $ed = SVN::Git::Fetcher->new($self);
2677 $self->ra->gs_do_update($rev, $rev, $self, $ed)
2678 or die "SVN connection failed somewhere...\n";
2680 print STDERR "Successfully followed parent\n";
2681 return $self->make_log_entry($rev, [$parent], $ed);
2683 return undef;
2686 sub do_fetch {
2687 my ($self, $paths, $rev) = @_;
2688 my $ed;
2689 my ($last_rev, @parents);
2690 if (my $lc = $self->last_commit) {
2691 # we can have a branch that was deleted, then re-added
2692 # under the same name but copied from another path, in
2693 # which case we'll have multiple parents (we don't
2694 # want to break the original ref, nor lose copypath info):
2695 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2696 push @{$log_entry->{parents}}, $lc;
2697 return $log_entry;
2699 $ed = SVN::Git::Fetcher->new($self);
2700 $last_rev = $self->{last_rev};
2701 $ed->{c} = $lc;
2702 @parents = ($lc);
2703 } else {
2704 $last_rev = $rev;
2705 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2706 return $log_entry;
2708 $ed = SVN::Git::Fetcher->new($self);
2710 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2711 die "SVN connection failed somewhere...\n";
2713 $self->make_log_entry($rev, \@parents, $ed);
2716 sub get_untracked {
2717 my ($self, $ed) = @_;
2718 my @out;
2719 my $h = $ed->{empty};
2720 foreach (sort keys %$h) {
2721 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2722 push @out, " $act: " . uri_encode($_);
2723 warn "W: $act: $_\n";
2725 foreach my $t (qw/dir_prop file_prop/) {
2726 $h = $ed->{$t} or next;
2727 foreach my $path (sort keys %$h) {
2728 my $ppath = $path eq '' ? '.' : $path;
2729 foreach my $prop (sort keys %{$h->{$path}}) {
2730 next if $SKIP_PROP{$prop};
2731 my $v = $h->{$path}->{$prop};
2732 my $t_ppath_prop = "$t: " .
2733 uri_encode($ppath) . ' ' .
2734 uri_encode($prop);
2735 if (defined $v) {
2736 push @out, " +$t_ppath_prop " .
2737 uri_encode($v);
2738 } else {
2739 push @out, " -$t_ppath_prop";
2744 foreach my $t (qw/absent_file absent_directory/) {
2745 $h = $ed->{$t} or next;
2746 foreach my $parent (sort keys %$h) {
2747 foreach my $path (sort @{$h->{$parent}}) {
2748 push @out, " $t: " .
2749 uri_encode("$parent/$path");
2750 warn "W: $t: $parent/$path ",
2751 "Insufficient permissions?\n";
2755 \@out;
2758 # parse_svn_date(DATE)
2759 # --------------------
2760 # Given a date (in UTC) from Subversion, return a string in the format
2761 # "<TZ Offset> <local date/time>" that Git will use.
2763 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
2764 # is true we'll convert it to the local timezone instead.
2765 sub parse_svn_date {
2766 my $date = shift || return '+0000 1970-01-01 00:00:00';
2767 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2768 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
2769 croak "Unable to parse date: $date\n";
2770 my $parsed_date; # Set next.
2772 if ($Git::SVN::_localtime) {
2773 # Translate the Subversion datetime to an epoch time.
2774 # Begin by switching ourselves to $date's timezone, UTC.
2775 my $old_env_TZ = $ENV{TZ};
2776 $ENV{TZ} = 'UTC';
2778 my $epoch_in_UTC =
2779 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
2781 # Determine our local timezone (including DST) at the
2782 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
2783 # value of TZ, if any, at the time we were run.
2784 if (defined $Git::SVN::Log::TZ) {
2785 $ENV{TZ} = $Git::SVN::Log::TZ;
2786 } else {
2787 delete $ENV{TZ};
2790 my $our_TZ =
2791 POSIX::strftime('%Z', $S, $M, $H, $d, $m - 1, $Y - 1900);
2793 # This converts $epoch_in_UTC into our local timezone.
2794 my ($sec, $min, $hour, $mday, $mon, $year,
2795 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
2797 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
2798 $our_TZ, $year + 1900, $mon + 1,
2799 $mday, $hour, $min, $sec);
2801 # Reset us to the timezone in effect when we entered
2802 # this routine.
2803 if (defined $old_env_TZ) {
2804 $ENV{TZ} = $old_env_TZ;
2805 } else {
2806 delete $ENV{TZ};
2808 } else {
2809 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
2812 return $parsed_date;
2815 sub other_gs {
2816 my ($self, $new_url, $url,
2817 $branch_from, $r, $old_ref_id) = @_;
2818 my $gs = Git::SVN->find_by_url($new_url, $url, $branch_from);
2819 unless ($gs) {
2820 my $ref_id = $old_ref_id;
2821 $ref_id =~ s/\@\d+$//;
2822 $ref_id .= "\@$r";
2823 # just grow a tail if we're not unique enough :x
2824 $ref_id .= '-' while find_ref($ref_id);
2825 print STDERR "Initializing parent: $ref_id\n";
2826 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
2827 if ($u =~ s#^\Q$url\E(/|$)##) {
2828 $p = $u;
2829 $u = $url;
2830 $repo_id = $self->{repo_id};
2832 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
2837 sub call_authors_prog {
2838 my ($orig_author) = @_;
2839 $orig_author = command_oneline('rev-parse', '--sq-quote', $orig_author);
2840 my $author = `$::_authors_prog $orig_author`;
2841 if ($? != 0) {
2842 die "$::_authors_prog failed with exit code $?\n"
2844 if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
2845 my ($name, $email) = ($1, $2);
2846 $email = undef if length $2 == 0;
2847 return [$name, $email];
2848 } else {
2849 die "Author: $orig_author: $::_authors_prog returned "
2850 . "invalid author format: $author\n";
2854 sub check_author {
2855 my ($author) = @_;
2856 if (!defined $author || length $author == 0) {
2857 $author = '(no author)';
2859 if (!defined $::users{$author}) {
2860 if (defined $::_authors_prog) {
2861 $::users{$author} = call_authors_prog($author);
2862 } elsif (defined $::_authors) {
2863 die "Author: $author not defined in $::_authors file\n";
2866 $author;
2869 sub make_log_entry {
2870 my ($self, $rev, $parents, $ed) = @_;
2871 my $untracked = $self->get_untracked($ed);
2873 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
2874 print $un "r$rev\n" or croak $!;
2875 print $un $_, "\n" foreach @$untracked;
2876 my %log_entry = ( parents => $parents || [], revision => $rev,
2877 log => '');
2879 my $headrev;
2880 my $logged = delete $self->{logged_rev_props};
2881 if (!$logged || $self->{-want_revprops}) {
2882 my $rp = $self->ra->rev_proplist($rev);
2883 foreach (sort keys %$rp) {
2884 my $v = $rp->{$_};
2885 if (/^svn:(author|date|log)$/) {
2886 $log_entry{$1} = $v;
2887 } elsif ($_ eq 'svm:headrev') {
2888 $headrev = $v;
2889 } else {
2890 print $un " rev_prop: ", uri_encode($_), ' ',
2891 uri_encode($v), "\n";
2894 } else {
2895 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
2897 close $un or croak $!;
2899 $log_entry{date} = parse_svn_date($log_entry{date});
2900 $log_entry{log} .= "\n";
2901 my $author = $log_entry{author} = check_author($log_entry{author});
2902 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
2903 : ($author, undef);
2905 my ($commit_name, $commit_email) = ($name, $email);
2906 if ($_use_log_author) {
2907 my $name_field;
2908 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
2909 $name_field = $1;
2910 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
2911 $name_field = $1;
2913 if (!defined $name_field) {
2914 if (!defined $email) {
2915 $email = $name;
2917 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
2918 ($name, $email) = ($1, $2);
2919 } elsif ($name_field =~ /(.*)@/) {
2920 ($name, $email) = ($1, $name_field);
2921 } else {
2922 ($name, $email) = ($name_field, $name_field);
2925 if (defined $headrev && $self->use_svm_props) {
2926 if ($self->rewrite_root) {
2927 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2928 "options set!\n";
2930 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$}i;
2931 # we don't want "SVM: initializing mirror for junk" ...
2932 return undef if $r == 0;
2933 my $svm = $self->svm;
2934 if ($uuid ne $svm->{uuid}) {
2935 die "UUID mismatch on SVM path:\n",
2936 "expected: $svm->{uuid}\n",
2937 " got: $uuid\n";
2939 my $full_url = $self->full_url;
2940 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2941 die "Failed to replace '$svm->{replace}' with ",
2942 "'$svm->{source}' in $full_url\n";
2943 # throw away username for storing in records
2944 remove_username($full_url);
2945 $log_entry{metadata} = "$full_url\@$r $uuid";
2946 $log_entry{svm_revision} = $r;
2947 $email ||= "$author\@$uuid";
2948 $commit_email ||= "$author\@$uuid";
2949 } elsif ($self->use_svnsync_props) {
2950 my $full_url = $self->svnsync->{url};
2951 $full_url .= "/$self->{path}" if length $self->{path};
2952 remove_username($full_url);
2953 my $uuid = $self->svnsync->{uuid};
2954 $log_entry{metadata} = "$full_url\@$rev $uuid";
2955 $email ||= "$author\@$uuid";
2956 $commit_email ||= "$author\@$uuid";
2957 } else {
2958 my $url = $self->metadata_url;
2959 remove_username($url);
2960 $log_entry{metadata} = "$url\@$rev " .
2961 $self->ra->get_uuid;
2962 $email ||= "$author\@" . $self->ra->get_uuid;
2963 $commit_email ||= "$author\@" . $self->ra->get_uuid;
2965 $log_entry{name} = $name;
2966 $log_entry{email} = $email;
2967 $log_entry{commit_name} = $commit_name;
2968 $log_entry{commit_email} = $commit_email;
2969 \%log_entry;
2972 sub fetch {
2973 my ($self, $min_rev, $max_rev, @parents) = @_;
2974 my ($last_rev, $last_commit) = $self->last_rev_commit;
2975 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2976 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2979 sub set_tree_cb {
2980 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2981 $self->{inject_parents} = { $rev => $tree };
2982 $self->fetch(undef, undef);
2985 sub set_tree {
2986 my ($self, $tree) = (shift, shift);
2987 my $log_entry = ::get_commit_entry($tree);
2988 unless ($self->{last_rev}) {
2989 ::fatal("Must have an existing revision to commit");
2991 my %ed_opts = ( r => $self->{last_rev},
2992 log => $log_entry->{log},
2993 ra => $self->ra,
2994 tree_a => $self->{last_commit},
2995 tree_b => $tree,
2996 editor_cb => sub {
2997 $self->set_tree_cb($log_entry, $tree, @_) },
2998 svn_path => $self->{path} );
2999 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
3000 print "No changes\nr$self->{last_rev} = $tree\n";
3004 sub rebuild_from_rev_db {
3005 my ($self, $path) = @_;
3006 my $r = -1;
3007 open my $fh, '<', $path or croak "open: $!";
3008 binmode $fh or croak "binmode: $!";
3009 while (<$fh>) {
3010 length($_) == 41 or croak "inconsistent size in ($_) != 41";
3011 chomp($_);
3012 ++$r;
3013 next if $_ eq ('0' x 40);
3014 $self->rev_map_set($r, $_);
3015 print "r$r = $_\n";
3017 close $fh or croak "close: $!";
3018 unlink $path or croak "unlink: $!";
3021 sub rebuild {
3022 my ($self) = @_;
3023 my $map_path = $self->map_path;
3024 my $partial = (-e $map_path && ! -z $map_path);
3025 return unless ::verify_ref($self->refname.'^0');
3026 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
3027 my $rev_db = $self->rev_db_path;
3028 $self->rebuild_from_rev_db($rev_db);
3029 if ($self->use_svm_props) {
3030 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
3031 $self->rebuild_from_rev_db($svm_rev_db);
3033 $self->unlink_rev_db_symlink;
3034 return;
3036 print "Rebuilding $map_path ...\n" if (!$partial);
3037 my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
3038 (undef, undef));
3039 my ($log, $ctx) =
3040 command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
3041 ($head ? "$head.." : "") . $self->refname,
3042 '--');
3043 my $metadata_url = $self->metadata_url;
3044 remove_username($metadata_url);
3045 my $svn_uuid = $self->ra_uuid;
3046 my $c;
3047 while (<$log>) {
3048 if ( m{^commit ($::sha1)$} ) {
3049 $c = $1;
3050 next;
3052 next unless s{^\s*(git-svn-id:)}{$1};
3053 my ($url, $rev, $uuid) = ::extract_metadata($_);
3054 remove_username($url);
3056 # ignore merges (from set-tree)
3057 next if (!defined $rev || !$uuid);
3059 # if we merged or otherwise started elsewhere, this is
3060 # how we break out of it
3061 if (($uuid ne $svn_uuid) ||
3062 ($metadata_url && $url && ($url ne $metadata_url))) {
3063 next;
3065 if ($partial && $head) {
3066 print "Partial-rebuilding $map_path ...\n";
3067 print "Currently at $base_rev = $head\n";
3068 $head = undef;
3071 $self->rev_map_set($rev, $c);
3072 print "r$rev = $c\n";
3074 command_close_pipe($log, $ctx);
3075 print "Done rebuilding $map_path\n" if (!$partial || !$head);
3076 my $rev_db_path = $self->rev_db_path;
3077 if (-f $self->rev_db_path) {
3078 unlink $self->rev_db_path or croak "unlink: $!";
3080 $self->unlink_rev_db_symlink;
3083 # rev_map:
3084 # Tie::File seems to be prone to offset errors if revisions get sparse,
3085 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
3086 # one of my favorite modules is out :< Next up would be one of the DBM
3087 # modules, but I'm not sure which is most portable...
3089 # This is the replacement for the rev_db format, which was too big
3090 # and inefficient for large repositories with a lot of sparse history
3091 # (mainly tags)
3093 # The format is this:
3094 # - 24 bytes for every record,
3095 # * 4 bytes for the integer representing an SVN revision number
3096 # * 20 bytes representing the sha1 of a git commit
3097 # - No empty padding records like the old format
3098 # (except the last record, which can be overwritten)
3099 # - new records are written append-only since SVN revision numbers
3100 # increase monotonically
3101 # - lookups on SVN revision number are done via a binary search
3102 # - Piping the file to xxd -c24 is a good way of dumping it for
3103 # viewing or editing (piped back through xxd -r), should the need
3104 # ever arise.
3105 # - The last record can be padding revision with an all-zero sha1
3106 # This is used to optimize fetch performance when using multiple
3107 # "fetch" directives in .git/config
3109 # These files are disposable unless noMetadata or useSvmProps is set
3111 sub _rev_map_set {
3112 my ($fh, $rev, $commit) = @_;
3114 binmode $fh or croak "binmode: $!";
3115 my $size = (stat($fh))[7];
3116 ($size % 24) == 0 or croak "inconsistent size: $size";
3118 my $wr_offset = 0;
3119 if ($size > 0) {
3120 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3121 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
3122 $read == 24 or croak "read only $read bytes (!= 24)";
3123 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
3124 if ($last_commit eq ('0' x40)) {
3125 if ($size >= 48) {
3126 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3127 $read = sysread($fh, $buf, 24) or
3128 croak "read: $!";
3129 $read == 24 or
3130 croak "read only $read bytes (!= 24)";
3131 ($last_rev, $last_commit) =
3132 unpack(rev_map_fmt, $buf);
3133 if ($last_commit eq ('0' x40)) {
3134 croak "inconsistent .rev_map\n";
3137 if ($last_rev >= $rev) {
3138 croak "last_rev is higher!: $last_rev >= $rev";
3140 $wr_offset = -24;
3143 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
3144 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
3145 croak "write: $!";
3148 sub _rev_map_reset {
3149 my ($fh, $rev, $commit) = @_;
3150 my $c = _rev_map_get($fh, $rev);
3151 $c eq $commit or die "_rev_map_reset(@_) commit $c does not match!\n";
3152 my $offset = sysseek($fh, 0, SEEK_CUR) or croak "seek: $!";
3153 truncate $fh, $offset or croak "truncate: $!";
3156 sub mkfile {
3157 my ($path) = @_;
3158 unless (-e $path) {
3159 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
3160 mkpath([$dir]) unless -d $dir;
3161 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
3162 close $fh or die "Couldn't close (create) $path: $!\n";
3166 sub rev_map_set {
3167 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
3168 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
3169 my $db = $self->map_path($uuid);
3170 my $db_lock = "$db.lock";
3171 my $sig;
3172 $update_ref ||= 0;
3173 if ($update_ref) {
3174 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3175 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
3177 mkfile($db);
3179 $LOCKFILES{$db_lock} = 1;
3180 my $sync;
3181 # both of these options make our .rev_db file very, very important
3182 # and we can't afford to lose it because rebuild() won't work
3183 if ($self->use_svm_props || $self->no_metadata) {
3184 $sync = 1;
3185 copy($db, $db_lock) or die "rev_map_set(@_): ",
3186 "Failed to copy: ",
3187 "$db => $db_lock ($!)\n";
3188 } else {
3189 rename $db, $db_lock or die "rev_map_set(@_): ",
3190 "Failed to rename: ",
3191 "$db => $db_lock ($!)\n";
3194 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
3195 or croak "Couldn't open $db_lock: $!\n";
3196 $update_ref eq 'reset' ? _rev_map_reset($fh, $rev, $commit) :
3197 _rev_map_set($fh, $rev, $commit);
3198 if ($sync) {
3199 $fh->flush or die "Couldn't flush $db_lock: $!\n";
3200 $fh->sync or die "Couldn't sync $db_lock: $!\n";
3202 close $fh or croak $!;
3203 if ($update_ref) {
3204 $_head = $self;
3205 my $note = "";
3206 $note = " ($update_ref)" if ($update_ref !~ /^\d*$/);
3207 command_noisy('update-ref', '-m', "r$rev$note",
3208 $self->refname, $commit);
3210 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
3211 "$db_lock => $db ($!)\n";
3212 delete $LOCKFILES{$db_lock};
3213 if ($update_ref) {
3214 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3215 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
3216 kill $sig, $$ if defined $sig;
3220 # If want_commit, this will return an array of (rev, commit) where
3221 # commit _must_ be a valid commit in the archive.
3222 # Otherwise, it'll return the max revision (whether or not the
3223 # commit is valid or just a 0x40 placeholder).
3224 sub rev_map_max {
3225 my ($self, $want_commit) = @_;
3226 $self->rebuild;
3227 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
3228 $want_commit ? ($r, $c) : $r;
3231 sub rev_map_max_norebuild {
3232 my ($self, $want_commit) = @_;
3233 my $map_path = $self->map_path;
3234 stat $map_path or return $want_commit ? (0, undef) : 0;
3235 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3236 binmode $fh or croak "binmode: $!";
3237 my $size = (stat($fh))[7];
3238 ($size % 24) == 0 or croak "inconsistent size: $size";
3240 if ($size == 0) {
3241 close $fh or croak "close: $!";
3242 return $want_commit ? (0, undef) : 0;
3245 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3246 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3247 my ($r, $c) = unpack(rev_map_fmt, $buf);
3248 if ($want_commit && $c eq ('0' x40)) {
3249 if ($size < 48) {
3250 return $want_commit ? (0, undef) : 0;
3252 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3253 sysread($fh, $buf, 24) == 24 or croak "read: $!";
3254 ($r, $c) = unpack(rev_map_fmt, $buf);
3255 if ($c eq ('0'x40)) {
3256 croak "Penultimate record is all-zeroes in $map_path";
3259 close $fh or croak "close: $!";
3260 $want_commit ? ($r, $c) : $r;
3263 sub rev_map_get {
3264 my ($self, $rev, $uuid) = @_;
3265 my $map_path = $self->map_path($uuid);
3266 return undef unless -e $map_path;
3268 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3269 my $c = _rev_map_get($fh, $rev);
3270 close($fh) or croak "close: $!";
3274 sub _rev_map_get {
3275 my ($fh, $rev) = @_;
3277 binmode $fh or croak "binmode: $!";
3278 my $size = (stat($fh))[7];
3279 ($size % 24) == 0 or croak "inconsistent size: $size";
3281 if ($size == 0) {
3282 return undef;
3285 my ($l, $u) = (0, $size - 24);
3286 my ($r, $c, $buf);
3288 while ($l <= $u) {
3289 my $i = int(($l/24 + $u/24) / 2) * 24;
3290 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
3291 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3292 my ($r, $c) = unpack(rev_map_fmt, $buf);
3294 if ($r < $rev) {
3295 $l = $i + 24;
3296 } elsif ($r > $rev) {
3297 $u = $i - 24;
3298 } else { # $r == $rev
3299 return $c eq ('0' x 40) ? undef : $c;
3302 undef;
3305 # Finds the first svn revision that exists on (if $eq_ok is true) or
3306 # before $rev for the current branch. It will not search any lower
3307 # than $min_rev. Returns the git commit hash and svn revision number
3308 # if found, else (undef, undef).
3309 sub find_rev_before {
3310 my ($self, $rev, $eq_ok, $min_rev) = @_;
3311 --$rev unless $eq_ok;
3312 $min_rev ||= 1;
3313 my $max_rev = $self->rev_map_max;
3314 $rev = $max_rev if ($rev > $max_rev);
3315 while ($rev >= $min_rev) {
3316 if (my $c = $self->rev_map_get($rev)) {
3317 return ($rev, $c);
3319 --$rev;
3321 return (undef, undef);
3324 # Finds the first svn revision that exists on (if $eq_ok is true) or
3325 # after $rev for the current branch. It will not search any higher
3326 # than $max_rev. Returns the git commit hash and svn revision number
3327 # if found, else (undef, undef).
3328 sub find_rev_after {
3329 my ($self, $rev, $eq_ok, $max_rev) = @_;
3330 ++$rev unless $eq_ok;
3331 $max_rev ||= $self->rev_map_max;
3332 while ($rev <= $max_rev) {
3333 if (my $c = $self->rev_map_get($rev)) {
3334 return ($rev, $c);
3336 ++$rev;
3338 return (undef, undef);
3341 sub _new {
3342 my ($class, $repo_id, $ref_id, $path) = @_;
3343 unless (defined $repo_id && length $repo_id) {
3344 $repo_id = $Git::SVN::default_repo_id;
3346 unless (defined $ref_id && length $ref_id) {
3347 $_prefix = '' unless defined($_prefix);
3348 $_[2] = $ref_id =
3349 "refs/remotes/$_prefix$Git::SVN::default_ref_id";
3351 $_[1] = $repo_id;
3352 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
3354 # Older repos imported by us used $GIT_DIR/svn/foo instead of
3355 # $GIT_DIR/svn/refs/remotes/foo when tracking refs/remotes/foo
3356 if ($ref_id =~ m{^refs/remotes/(.*)}) {
3357 my $old_dir = "$ENV{GIT_DIR}/svn/$1";
3358 if (-d $old_dir && ! -d $dir) {
3359 $dir = $old_dir;
3363 $_[3] = $path = '' unless (defined $path);
3364 mkpath([$dir]);
3365 bless {
3366 ref_id => $ref_id, dir => $dir, index => "$dir/index",
3367 path => $path, config => "$ENV{GIT_DIR}/svn/config",
3368 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
3371 # for read-only access of old .rev_db formats
3372 sub unlink_rev_db_symlink {
3373 my ($self) = @_;
3374 my $link = $self->rev_db_path;
3375 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
3376 if (-l $link) {
3377 unlink $link or croak "unlink: $link failed!";
3381 sub rev_db_path {
3382 my ($self, $uuid) = @_;
3383 my $db_path = $self->map_path($uuid);
3384 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
3385 or croak "map_path: $db_path does not contain '/.rev_map.' !";
3386 $db_path;
3389 # the new replacement for .rev_db
3390 sub map_path {
3391 my ($self, $uuid) = @_;
3392 $uuid ||= $self->ra_uuid;
3393 "$self->{map_root}.$uuid";
3396 sub uri_encode {
3397 my ($f) = @_;
3398 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
3402 sub remove_username {
3403 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
3406 package Git::SVN::Prompt;
3407 use strict;
3408 use warnings;
3409 require SVN::Core;
3410 use vars qw/$_no_auth_cache $_username/;
3412 sub simple {
3413 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
3414 $may_save = undef if $_no_auth_cache;
3415 $default_username = $_username if defined $_username;
3416 if (defined $default_username && length $default_username) {
3417 if (defined $realm && length $realm) {
3418 print STDERR "Authentication realm: $realm\n";
3419 STDERR->flush;
3421 $cred->username($default_username);
3422 } else {
3423 username($cred, $realm, $may_save, $pool);
3425 $cred->password(_read_password("Password for '" .
3426 $cred->username . "': ", $realm));
3427 $cred->may_save($may_save);
3428 $SVN::_Core::SVN_NO_ERROR;
3431 sub ssl_server_trust {
3432 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
3433 $may_save = undef if $_no_auth_cache;
3434 print STDERR "Error validating server certificate for '$realm':\n";
3436 no warnings 'once';
3437 # All variables SVN::Auth::SSL::* are used only once,
3438 # so we're shutting up Perl warnings about this.
3439 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
3440 print STDERR " - The certificate is not issued ",
3441 "by a trusted authority. Use the\n",
3442 " fingerprint to validate ",
3443 "the certificate manually!\n";
3445 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
3446 print STDERR " - The certificate hostname ",
3447 "does not match.\n";
3449 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
3450 print STDERR " - The certificate is not yet valid.\n";
3452 if ($failures & $SVN::Auth::SSL::EXPIRED) {
3453 print STDERR " - The certificate has expired.\n";
3455 if ($failures & $SVN::Auth::SSL::OTHER) {
3456 print STDERR " - The certificate has ",
3457 "an unknown error.\n";
3459 } # no warnings 'once'
3460 printf STDERR
3461 "Certificate information:\n".
3462 " - Hostname: %s\n".
3463 " - Valid: from %s until %s\n".
3464 " - Issuer: %s\n".
3465 " - Fingerprint: %s\n",
3466 map $cert_info->$_, qw(hostname valid_from valid_until
3467 issuer_dname fingerprint);
3468 my $choice;
3469 prompt:
3470 print STDERR $may_save ?
3471 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
3472 "(R)eject or accept (t)emporarily? ";
3473 STDERR->flush;
3474 $choice = lc(substr(<STDIN> || 'R', 0, 1));
3475 if ($choice =~ /^t$/i) {
3476 $cred->may_save(undef);
3477 } elsif ($choice =~ /^r$/i) {
3478 return -1;
3479 } elsif ($may_save && $choice =~ /^p$/i) {
3480 $cred->may_save($may_save);
3481 } else {
3482 goto prompt;
3484 $cred->accepted_failures($failures);
3485 $SVN::_Core::SVN_NO_ERROR;
3488 sub ssl_client_cert {
3489 my ($cred, $realm, $may_save, $pool) = @_;
3490 $may_save = undef if $_no_auth_cache;
3491 print STDERR "Client certificate filename: ";
3492 STDERR->flush;
3493 chomp(my $filename = <STDIN>);
3494 $cred->cert_file($filename);
3495 $cred->may_save($may_save);
3496 $SVN::_Core::SVN_NO_ERROR;
3499 sub ssl_client_cert_pw {
3500 my ($cred, $realm, $may_save, $pool) = @_;
3501 $may_save = undef if $_no_auth_cache;
3502 $cred->password(_read_password("Password: ", $realm));
3503 $cred->may_save($may_save);
3504 $SVN::_Core::SVN_NO_ERROR;
3507 sub username {
3508 my ($cred, $realm, $may_save, $pool) = @_;
3509 $may_save = undef if $_no_auth_cache;
3510 if (defined $realm && length $realm) {
3511 print STDERR "Authentication realm: $realm\n";
3513 my $username;
3514 if (defined $_username) {
3515 $username = $_username;
3516 } else {
3517 print STDERR "Username: ";
3518 STDERR->flush;
3519 chomp($username = <STDIN>);
3521 $cred->username($username);
3522 $cred->may_save($may_save);
3523 $SVN::_Core::SVN_NO_ERROR;
3526 sub _read_password {
3527 my ($prompt, $realm) = @_;
3528 print STDERR $prompt;
3529 STDERR->flush;
3530 require Term::ReadKey;
3531 Term::ReadKey::ReadMode('noecho');
3532 my $password = '';
3533 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
3534 last if $key =~ /[\012\015]/; # \n\r
3535 $password .= $key;
3537 Term::ReadKey::ReadMode('restore');
3538 print STDERR "\n";
3539 STDERR->flush;
3540 $password;
3543 package SVN::Git::Fetcher;
3544 use vars qw/@ISA/;
3545 use strict;
3546 use warnings;
3547 use Carp qw/croak/;
3548 use File::Temp qw/tempfile/;
3549 use IO::File qw//;
3550 use vars qw/$_ignore_regex/;
3552 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
3553 sub new {
3554 my ($class, $git_svn, $switch_path) = @_;
3555 my $self = SVN::Delta::Editor->new;
3556 bless $self, $class;
3557 if (exists $git_svn->{last_commit}) {
3558 $self->{c} = $git_svn->{last_commit};
3559 $self->{empty_symlinks} =
3560 _mark_empty_symlinks($git_svn, $switch_path);
3562 $self->{ignore_regex} = eval { command_oneline('config', '--get',
3563 "svn-remote.$git_svn->{repo_id}.ignore-paths") };
3564 $self->{empty} = {};
3565 $self->{dir_prop} = {};
3566 $self->{file_prop} = {};
3567 $self->{absent_dir} = {};
3568 $self->{absent_file} = {};
3569 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
3570 $self;
3573 # this uses the Ra object, so it must be called before do_{switch,update},
3574 # not inside them (when the Git::SVN::Fetcher object is passed) to
3575 # do_{switch,update}
3576 sub _mark_empty_symlinks {
3577 my ($git_svn, $switch_path) = @_;
3578 my $bool = Git::config_bool('svn.brokenSymlinkWorkaround');
3579 return {} if (!defined($bool)) || (defined($bool) && ! $bool);
3581 my %ret;
3582 my ($rev, $cmt) = $git_svn->last_rev_commit;
3583 return {} unless ($rev && $cmt);
3585 # allow the warning to be printed for each revision we fetch to
3586 # ensure the user sees it. The user can also disable the workaround
3587 # on the repository even while git svn is running and the next
3588 # revision fetched will skip this expensive function.
3589 my $printed_warning;
3590 chomp(my $empty_blob = `git hash-object -t blob --stdin < /dev/null`);
3591 my ($ls, $ctx) = command_output_pipe(qw/ls-tree -r -z/, $cmt);
3592 local $/ = "\0";
3593 my $pfx = defined($switch_path) ? $switch_path : $git_svn->{path};
3594 $pfx .= '/' if length($pfx);
3595 while (<$ls>) {
3596 chomp;
3597 s/\A100644 blob $empty_blob\t//o or next;
3598 unless ($printed_warning) {
3599 print STDERR "Scanning for empty symlinks, ",
3600 "this may take a while if you have ",
3601 "many empty files\n",
3602 "You may disable this with `",
3603 "git config svn.brokenSymlinkWorkaround ",
3604 "false'.\n",
3605 "This may be done in a different ",
3606 "terminal without restarting ",
3607 "git svn\n";
3608 $printed_warning = 1;
3610 my $path = $_;
3611 my (undef, $props) =
3612 $git_svn->ra->get_file($pfx.$path, $rev, undef);
3613 if ($props->{'svn:special'}) {
3614 $ret{$path} = 1;
3617 command_close_pipe($ls, $ctx);
3618 \%ret;
3621 # returns true if a given path is inside a ".git" directory
3622 sub in_dot_git {
3623 $_[0] =~ m{(?:^|/)\.git(?:/|$)};
3626 # return value: 0 -- don't ignore, 1 -- ignore
3627 sub is_path_ignored {
3628 my ($self, $path) = @_;
3629 return 1 if in_dot_git($path);
3630 return 1 if defined($self->{ignore_regex}) &&
3631 $path =~ m!$self->{ignore_regex}!;
3632 return 0 unless defined($_ignore_regex);
3633 return 1 if $path =~ m!$_ignore_regex!o;
3634 return 0;
3637 sub set_path_strip {
3638 my ($self, $path) = @_;
3639 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
3642 sub open_root {
3643 { path => '' };
3646 sub open_directory {
3647 my ($self, $path, $pb, $rev) = @_;
3648 { path => $path };
3651 sub git_path {
3652 my ($self, $path) = @_;
3653 if ($self->{path_strip}) {
3654 $path =~ s!$self->{path_strip}!! or
3655 die "Failed to strip path '$path' ($self->{path_strip})\n";
3657 $path;
3660 sub delete_entry {
3661 my ($self, $path, $rev, $pb) = @_;
3662 return undef if $self->is_path_ignored($path);
3664 my $gpath = $self->git_path($path);
3665 return undef if ($gpath eq '');
3667 # remove entire directories.
3668 my ($tree) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
3669 =~ /\A040000 tree ([a-f\d]{40})\t\Q$gpath\E\0/);
3670 if ($tree) {
3671 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3672 -r --name-only -z/,
3673 $tree);
3674 local $/ = "\0";
3675 while (<$ls>) {
3676 chomp;
3677 my $rmpath = "$gpath/$_";
3678 $self->{gii}->remove($rmpath);
3679 print "\tD\t$rmpath\n" unless $::_q;
3681 print "\tD\t$gpath/\n" unless $::_q;
3682 command_close_pipe($ls, $ctx);
3683 $self->{empty}->{$path} = 0
3684 } else {
3685 $self->{gii}->remove($gpath);
3686 print "\tD\t$gpath\n" unless $::_q;
3688 undef;
3691 sub open_file {
3692 my ($self, $path, $pb, $rev) = @_;
3693 my ($mode, $blob);
3695 goto out if $self->is_path_ignored($path);
3697 my $gpath = $self->git_path($path);
3698 ($mode, $blob) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
3699 =~ /\A(\d{6}) blob ([a-f\d]{40})\t\Q$gpath\E\0/);
3700 unless (defined $mode && defined $blob) {
3701 die "$path was not found in commit $self->{c} (r$rev)\n";
3703 if ($mode eq '100644' && $self->{empty_symlinks}->{$path}) {
3704 $mode = '120000';
3706 out:
3707 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
3708 pool => SVN::Pool->new, action => 'M' };
3711 sub add_file {
3712 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
3713 my $mode;
3715 if (!$self->is_path_ignored($path)) {
3716 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3717 delete $self->{empty}->{$dir};
3718 $mode = '100644';
3720 { path => $path, mode_a => $mode, mode_b => $mode,
3721 pool => SVN::Pool->new, action => 'A' };
3724 sub add_directory {
3725 my ($self, $path, $cp_path, $cp_rev) = @_;
3726 goto out if $self->is_path_ignored($path);
3727 my $gpath = $self->git_path($path);
3728 if ($gpath eq '') {
3729 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3730 -r --name-only -z/,
3731 $self->{c});
3732 local $/ = "\0";
3733 while (<$ls>) {
3734 chomp;
3735 $self->{gii}->remove($_);
3736 print "\tD\t$_\n" unless $::_q;
3738 command_close_pipe($ls, $ctx);
3739 $self->{empty}->{$path} = 0;
3741 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3742 delete $self->{empty}->{$dir};
3743 $self->{empty}->{$path} = 1;
3744 out:
3745 { path => $path };
3748 sub change_dir_prop {
3749 my ($self, $db, $prop, $value) = @_;
3750 return undef if $self->is_path_ignored($db->{path});
3751 $self->{dir_prop}->{$db->{path}} ||= {};
3752 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
3753 undef;
3756 sub absent_directory {
3757 my ($self, $path, $pb) = @_;
3758 return undef if $self->is_path_ignored($path);
3759 $self->{absent_dir}->{$pb->{path}} ||= [];
3760 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
3761 undef;
3764 sub absent_file {
3765 my ($self, $path, $pb) = @_;
3766 return undef if $self->is_path_ignored($path);
3767 $self->{absent_file}->{$pb->{path}} ||= [];
3768 push @{$self->{absent_file}->{$pb->{path}}}, $path;
3769 undef;
3772 sub change_file_prop {
3773 my ($self, $fb, $prop, $value) = @_;
3774 return undef if $self->is_path_ignored($fb->{path});
3775 if ($prop eq 'svn:executable') {
3776 if ($fb->{mode_b} != 120000) {
3777 $fb->{mode_b} = defined $value ? 100755 : 100644;
3779 } elsif ($prop eq 'svn:special') {
3780 $fb->{mode_b} = defined $value ? 120000 : 100644;
3781 } else {
3782 $self->{file_prop}->{$fb->{path}} ||= {};
3783 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
3785 undef;
3788 sub apply_textdelta {
3789 my ($self, $fb, $exp) = @_;
3790 return undef if $self->is_path_ignored($fb->{path});
3791 my $fh = $::_repository->temp_acquire('svn_delta');
3792 # $fh gets auto-closed() by SVN::TxDelta::apply(),
3793 # (but $base does not,) so dup() it for reading in close_file
3794 open my $dup, '<&', $fh or croak $!;
3795 my $base = $::_repository->temp_acquire('git_blob');
3797 if ($fb->{blob}) {
3798 my ($base_is_link, $size);
3800 if ($fb->{mode_a} eq '120000' &&
3801 ! $self->{empty_symlinks}->{$fb->{path}}) {
3802 print $base 'link ' or die "print $!\n";
3803 $base_is_link = 1;
3805 retry:
3806 $size = $::_repository->cat_blob($fb->{blob}, $base);
3807 die "Failed to read object $fb->{blob}" if ($size < 0);
3809 if (defined $exp) {
3810 seek $base, 0, 0 or croak $!;
3811 my $got = ::md5sum($base);
3812 if ($got ne $exp) {
3813 my $err = "Checksum mismatch: ".
3814 "$fb->{path} $fb->{blob}\n" .
3815 "expected: $exp\n" .
3816 " got: $got\n";
3817 if ($base_is_link) {
3818 warn $err,
3819 "Retrying... (possibly ",
3820 "a bad symlink from SVN)\n";
3821 $::_repository->temp_reset($base);
3822 $base_is_link = 0;
3823 goto retry;
3825 die $err;
3829 seek $base, 0, 0 or croak $!;
3830 $fb->{fh} = $fh;
3831 $fb->{base} = $base;
3832 [ SVN::TxDelta::apply($base, $dup, undef, $fb->{path}, $fb->{pool}) ];
3835 sub close_file {
3836 my ($self, $fb, $exp) = @_;
3837 return undef if $self->is_path_ignored($fb->{path});
3839 my $hash;
3840 my $path = $self->git_path($fb->{path});
3841 if (my $fh = $fb->{fh}) {
3842 if (defined $exp) {
3843 seek($fh, 0, 0) or croak $!;
3844 my $got = ::md5sum($fh);
3845 if ($got ne $exp) {
3846 die "Checksum mismatch: $path\n",
3847 "expected: $exp\n got: $got\n";
3850 if ($fb->{mode_b} == 120000) {
3851 sysseek($fh, 0, 0) or croak $!;
3852 my $rd = sysread($fh, my $buf, 5);
3854 if (!defined $rd) {
3855 croak "sysread: $!\n";
3856 } elsif ($rd == 0) {
3857 warn "$path has mode 120000",
3858 " but it points to nothing\n",
3859 "converting to an empty file with mode",
3860 " 100644\n";
3861 $fb->{mode_b} = '100644';
3862 } elsif ($buf ne 'link ') {
3863 warn "$path has mode 120000",
3864 " but is not a link\n";
3865 } else {
3866 my $tmp_fh = $::_repository->temp_acquire(
3867 'svn_hash');
3868 my $res;
3869 while ($res = sysread($fh, my $str, 1024)) {
3870 my $out = syswrite($tmp_fh, $str, $res);
3871 defined($out) && $out == $res
3872 or croak("write ",
3873 Git::temp_path($tmp_fh),
3874 ": $!\n");
3876 defined $res or croak $!;
3878 ($fh, $tmp_fh) = ($tmp_fh, $fh);
3879 Git::temp_release($tmp_fh, 1);
3883 $hash = $::_repository->hash_and_insert_object(
3884 Git::temp_path($fh));
3885 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
3887 Git::temp_release($fb->{base}, 1);
3888 Git::temp_release($fh, 1);
3889 } else {
3890 $hash = $fb->{blob} or die "no blob information\n";
3892 $fb->{pool}->clear;
3893 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
3894 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
3895 undef;
3898 sub abort_edit {
3899 my $self = shift;
3900 $self->{nr} = $self->{gii}->{nr};
3901 delete $self->{gii};
3902 $self->SUPER::abort_edit(@_);
3905 sub close_edit {
3906 my $self = shift;
3907 $self->{git_commit_ok} = 1;
3908 $self->{nr} = $self->{gii}->{nr};
3909 delete $self->{gii};
3910 $self->SUPER::close_edit(@_);
3913 package SVN::Git::Editor;
3914 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
3915 use strict;
3916 use warnings;
3917 use Carp qw/croak/;
3918 use IO::File;
3920 sub new {
3921 my ($class, $opts) = @_;
3922 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
3923 die "$_ required!\n" unless (defined $opts->{$_});
3926 my $pool = SVN::Pool->new;
3927 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
3928 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
3929 $opts->{r}, $mods);
3931 # $opts->{ra} functions should not be used after this:
3932 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
3933 $opts->{editor_cb}, $pool);
3934 my $self = SVN::Delta::Editor->new(@ce, $pool);
3935 bless $self, $class;
3936 foreach (qw/svn_path r tree_a tree_b/) {
3937 $self->{$_} = $opts->{$_};
3939 $self->{url} = $opts->{ra}->{url};
3940 $self->{mods} = $mods;
3941 $self->{types} = $types;
3942 $self->{pool} = $pool;
3943 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
3944 $self->{rm} = { };
3945 $self->{path_prefix} = length $self->{svn_path} ?
3946 "$self->{svn_path}/" : '';
3947 $self->{config} = $opts->{config};
3948 return $self;
3951 sub generate_diff {
3952 my ($tree_a, $tree_b) = @_;
3953 my @diff_tree = qw(diff-tree -z -r);
3954 if ($_cp_similarity) {
3955 push @diff_tree, "-C$_cp_similarity";
3956 } else {
3957 push @diff_tree, '-C';
3959 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
3960 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
3961 push @diff_tree, $tree_a, $tree_b;
3962 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
3963 local $/ = "\0";
3964 my $state = 'meta';
3965 my @mods;
3966 while (<$diff_fh>) {
3967 chomp $_; # this gets rid of the trailing "\0"
3968 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
3969 ($::sha1)\s($::sha1)\s
3970 ([MTCRAD])\d*$/xo) {
3971 push @mods, { mode_a => $1, mode_b => $2,
3972 sha1_a => $3, sha1_b => $4,
3973 chg => $5 };
3974 if ($5 =~ /^(?:C|R)$/) {
3975 $state = 'file_a';
3976 } else {
3977 $state = 'file_b';
3979 } elsif ($state eq 'file_a') {
3980 my $x = $mods[$#mods] or croak "Empty array\n";
3981 if ($x->{chg} !~ /^(?:C|R)$/) {
3982 croak "Error parsing $_, $x->{chg}\n";
3984 $x->{file_a} = $_;
3985 $state = 'file_b';
3986 } elsif ($state eq 'file_b') {
3987 my $x = $mods[$#mods] or croak "Empty array\n";
3988 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
3989 croak "Error parsing $_, $x->{chg}\n";
3991 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
3992 croak "Error parsing $_, $x->{chg}\n";
3994 $x->{file_b} = $_;
3995 $state = 'meta';
3996 } else {
3997 croak "Error parsing $_\n";
4000 command_close_pipe($diff_fh, $ctx);
4001 \@mods;
4004 sub check_diff_paths {
4005 my ($ra, $pfx, $rev, $mods) = @_;
4006 my %types;
4007 $pfx .= '/' if length $pfx;
4009 sub type_diff_paths {
4010 my ($ra, $types, $path, $rev) = @_;
4011 my @p = split m#/+#, $path;
4012 my $c = shift @p;
4013 unless (defined $types->{$c}) {
4014 $types->{$c} = $ra->check_path($c, $rev);
4016 while (@p) {
4017 $c .= '/' . shift @p;
4018 next if defined $types->{$c};
4019 $types->{$c} = $ra->check_path($c, $rev);
4023 foreach my $m (@$mods) {
4024 foreach my $f (qw/file_a file_b/) {
4025 next unless defined $m->{$f};
4026 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
4027 if (length $pfx.$dir && ! defined $types{$dir}) {
4028 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
4032 \%types;
4035 sub split_path {
4036 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
4039 sub repo_path {
4040 my ($self, $path) = @_;
4041 $self->{path_prefix}.(defined $path ? $path : '');
4044 sub url_path {
4045 my ($self, $path) = @_;
4046 if ($self->{url} =~ m#^https?://#) {
4047 $path =~ s!([^~a-zA-Z0-9_./-])!uc sprintf("%%%02x",ord($1))!eg;
4049 $self->{url} . '/' . $self->repo_path($path);
4052 sub rmdirs {
4053 my ($self) = @_;
4054 my $rm = $self->{rm};
4055 delete $rm->{''}; # we never delete the url we're tracking
4056 return unless %$rm;
4058 foreach (keys %$rm) {
4059 my @d = split m#/#, $_;
4060 my $c = shift @d;
4061 $rm->{$c} = 1;
4062 while (@d) {
4063 $c .= '/' . shift @d;
4064 $rm->{$c} = 1;
4067 delete $rm->{$self->{svn_path}};
4068 delete $rm->{''}; # we never delete the url we're tracking
4069 return unless %$rm;
4071 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
4072 $self->{tree_b});
4073 local $/ = "\0";
4074 while (<$fh>) {
4075 chomp;
4076 my @dn = split m#/#, $_;
4077 while (pop @dn) {
4078 delete $rm->{join '/', @dn};
4080 unless (%$rm) {
4081 close $fh;
4082 return;
4085 command_close_pipe($fh, $ctx);
4087 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
4088 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
4089 $self->close_directory($bat->{$d}, $p);
4090 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
4091 print "\tD+\t$d/\n" unless $::_q;
4092 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
4093 delete $bat->{$d};
4097 sub open_or_add_dir {
4098 my ($self, $full_path, $baton) = @_;
4099 my $t = $self->{types}->{$full_path};
4100 if (!defined $t) {
4101 die "$full_path not known in r$self->{r} or we have a bug!\n";
4104 no warnings 'once';
4105 # SVN::Node::none and SVN::Node::file are used only once,
4106 # so we're shutting up Perl's warnings about them.
4107 if ($t == $SVN::Node::none) {
4108 return $self->add_directory($full_path, $baton,
4109 undef, -1, $self->{pool});
4110 } elsif ($t == $SVN::Node::dir) {
4111 return $self->open_directory($full_path, $baton,
4112 $self->{r}, $self->{pool});
4113 } # no warnings 'once'
4114 print STDERR "$full_path already exists in repository at ",
4115 "r$self->{r} and it is not a directory (",
4116 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
4117 } # no warnings 'once'
4118 exit 1;
4121 sub ensure_path {
4122 my ($self, $path) = @_;
4123 my $bat = $self->{bat};
4124 my $repo_path = $self->repo_path($path);
4125 return $bat->{''} unless (length $repo_path);
4126 my @p = split m#/+#, $repo_path;
4127 my $c = shift @p;
4128 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
4129 while (@p) {
4130 my $c0 = $c;
4131 $c .= '/' . shift @p;
4132 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
4134 return $bat->{$c};
4137 # Subroutine to convert a globbing pattern to a regular expression.
4138 # From perl cookbook.
4139 sub glob2pat {
4140 my $globstr = shift;
4141 my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
4142 $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
4143 return '^' . $globstr . '$';
4146 sub check_autoprop {
4147 my ($self, $pattern, $properties, $file, $fbat) = @_;
4148 # Convert the globbing pattern to a regular expression.
4149 my $regex = glob2pat($pattern);
4150 # Check if the pattern matches the file name.
4151 if($file =~ m/($regex)/) {
4152 # Parse the list of properties to set.
4153 my @props = split(/;/, $properties);
4154 foreach my $prop (@props) {
4155 # Parse 'name=value' syntax and set the property.
4156 if ($prop =~ /([^=]+)=(.*)/) {
4157 my ($n,$v) = ($1,$2);
4158 for ($n, $v) {
4159 s/^\s+//; s/\s+$//;
4161 $self->change_file_prop($fbat, $n, $v);
4167 sub apply_autoprops {
4168 my ($self, $file, $fbat) = @_;
4169 my $conf_t = ${$self->{config}}{'config'};
4170 no warnings 'once';
4171 # Check [miscellany]/enable-auto-props in svn configuration.
4172 if (SVN::_Core::svn_config_get_bool(
4173 $conf_t,
4174 $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
4175 $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
4176 0)) {
4177 # Auto-props are enabled. Enumerate them to look for matches.
4178 my $callback = sub {
4179 $self->check_autoprop($_[0], $_[1], $file, $fbat);
4181 SVN::_Core::svn_config_enumerate(
4182 $conf_t,
4183 $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
4184 $callback);
4188 sub A {
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 undef, -1);
4194 print "\tA\t$m->{file_b}\n" unless $::_q;
4195 $self->apply_autoprops($file, $fbat);
4196 $self->chg_file($fbat, $m);
4197 $self->close_file($fbat,undef,$self->{pool});
4200 sub C {
4201 my ($self, $m) = @_;
4202 my ($dir, $file) = split_path($m->{file_b});
4203 my $pbat = $self->ensure_path($dir);
4204 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4205 $self->url_path($m->{file_a}), $self->{r});
4206 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
4207 $self->chg_file($fbat, $m);
4208 $self->close_file($fbat,undef,$self->{pool});
4211 sub delete_entry {
4212 my ($self, $path, $pbat) = @_;
4213 my $rpath = $self->repo_path($path);
4214 my ($dir, $file) = split_path($rpath);
4215 $self->{rm}->{$dir} = 1;
4216 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
4219 sub R {
4220 my ($self, $m) = @_;
4221 my ($dir, $file) = split_path($m->{file_b});
4222 my $pbat = $self->ensure_path($dir);
4223 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4224 $self->url_path($m->{file_a}), $self->{r});
4225 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
4226 $self->apply_autoprops($file, $fbat);
4227 $self->chg_file($fbat, $m);
4228 $self->close_file($fbat,undef,$self->{pool});
4230 ($dir, $file) = split_path($m->{file_a});
4231 $pbat = $self->ensure_path($dir);
4232 $self->delete_entry($m->{file_a}, $pbat);
4235 sub M {
4236 my ($self, $m) = @_;
4237 my ($dir, $file) = split_path($m->{file_b});
4238 my $pbat = $self->ensure_path($dir);
4239 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
4240 $pbat,$self->{r},$self->{pool});
4241 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
4242 $self->chg_file($fbat, $m);
4243 $self->close_file($fbat,undef,$self->{pool});
4246 sub T { shift->M(@_) }
4248 sub change_file_prop {
4249 my ($self, $fbat, $pname, $pval) = @_;
4250 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
4253 sub _chg_file_get_blob ($$$$) {
4254 my ($self, $fbat, $m, $which) = @_;
4255 my $fh = $::_repository->temp_acquire("git_blob_$which");
4256 if ($m->{"mode_$which"} =~ /^120/) {
4257 print $fh 'link ' or croak $!;
4258 $self->change_file_prop($fbat,'svn:special','*');
4259 } elsif ($m->{mode_a} =~ /^120/ && $m->{"mode_$which"} !~ /^120/) {
4260 $self->change_file_prop($fbat,'svn:special',undef);
4262 my $blob = $m->{"sha1_$which"};
4263 return ($fh,) if ($blob =~ /^0{40}$/);
4264 my $size = $::_repository->cat_blob($blob, $fh);
4265 croak "Failed to read object $blob" if ($size < 0);
4266 $fh->flush == 0 or croak $!;
4267 seek $fh, 0, 0 or croak $!;
4269 my $exp = ::md5sum($fh);
4270 seek $fh, 0, 0 or croak $!;
4271 return ($fh, $exp);
4274 sub chg_file {
4275 my ($self, $fbat, $m) = @_;
4276 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
4277 $self->change_file_prop($fbat,'svn:executable','*');
4278 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
4279 $self->change_file_prop($fbat,'svn:executable',undef);
4281 my ($fh_a, $exp_a) = _chg_file_get_blob $self, $fbat, $m, 'a';
4282 my ($fh_b, $exp_b) = _chg_file_get_blob $self, $fbat, $m, 'b';
4283 my $pool = SVN::Pool->new;
4284 my $atd = $self->apply_textdelta($fbat, $exp_a, $pool);
4285 if (-s $fh_a) {
4286 my $txstream = SVN::TxDelta::new ($fh_a, $fh_b, $pool);
4287 my $res = SVN::TxDelta::send_txstream($txstream, @$atd, $pool);
4288 if (defined $res) {
4289 die "Unexpected result from send_txstream: $res\n",
4290 "(SVN::Core::VERSION: $SVN::Core::VERSION)\n";
4292 } else {
4293 my $got = SVN::TxDelta::send_stream($fh_b, @$atd, $pool);
4294 die "Checksum mismatch\nexpected: $exp_b\ngot: $got\n"
4295 if ($got ne $exp_b);
4297 Git::temp_release($fh_b, 1);
4298 Git::temp_release($fh_a, 1);
4299 $pool->clear;
4302 sub D {
4303 my ($self, $m) = @_;
4304 my ($dir, $file) = split_path($m->{file_b});
4305 my $pbat = $self->ensure_path($dir);
4306 print "\tD\t$m->{file_b}\n" unless $::_q;
4307 $self->delete_entry($m->{file_b}, $pbat);
4310 sub close_edit {
4311 my ($self) = @_;
4312 my ($p,$bat) = ($self->{pool}, $self->{bat});
4313 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
4314 next if $_ eq '';
4315 $self->close_directory($bat->{$_}, $p);
4317 $self->close_directory($bat->{''}, $p);
4318 $self->SUPER::close_edit($p);
4319 $p->clear;
4322 sub abort_edit {
4323 my ($self) = @_;
4324 $self->SUPER::abort_edit($self->{pool});
4327 sub DESTROY {
4328 my $self = shift;
4329 $self->SUPER::DESTROY(@_);
4330 $self->{pool}->clear;
4333 # this drives the editor
4334 sub apply_diff {
4335 my ($self) = @_;
4336 my $mods = $self->{mods};
4337 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
4338 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
4339 my $f = $m->{chg};
4340 if (defined $o{$f}) {
4341 $self->$f($m);
4342 } else {
4343 fatal("Invalid change type: $f");
4346 $self->rmdirs if $_rmdir;
4347 if (@$mods == 0) {
4348 $self->abort_edit;
4349 } else {
4350 $self->close_edit;
4352 return scalar @$mods;
4355 package Git::SVN::Ra;
4356 use vars qw/@ISA $config_dir $_log_window_size/;
4357 use strict;
4358 use warnings;
4359 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
4361 BEGIN {
4362 # enforce temporary pool usage for some simple functions
4363 no strict 'refs';
4364 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root
4365 get_file/) {
4366 my $SUPER = "SUPER::$f";
4367 *$f = sub {
4368 my $self = shift;
4369 my $pool = SVN::Pool->new;
4370 my @ret = $self->$SUPER(@_,$pool);
4371 $pool->clear;
4372 wantarray ? @ret : $ret[0];
4377 sub _auth_providers () {
4379 SVN::Client::get_simple_provider(),
4380 SVN::Client::get_ssl_server_trust_file_provider(),
4381 SVN::Client::get_simple_prompt_provider(
4382 \&Git::SVN::Prompt::simple, 2),
4383 SVN::Client::get_ssl_client_cert_file_provider(),
4384 SVN::Client::get_ssl_client_cert_prompt_provider(
4385 \&Git::SVN::Prompt::ssl_client_cert, 2),
4386 SVN::Client::get_ssl_client_cert_pw_file_provider(),
4387 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
4388 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
4389 SVN::Client::get_username_provider(),
4390 SVN::Client::get_ssl_server_trust_prompt_provider(
4391 \&Git::SVN::Prompt::ssl_server_trust),
4392 SVN::Client::get_username_prompt_provider(
4393 \&Git::SVN::Prompt::username, 2)
4397 sub escape_uri_only {
4398 my ($uri) = @_;
4399 my @tmp;
4400 foreach (split m{/}, $uri) {
4401 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
4402 push @tmp, $_;
4404 join('/', @tmp);
4407 sub escape_url {
4408 my ($url) = @_;
4409 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
4410 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
4411 $url = "$scheme://$domain$uri";
4413 $url;
4416 sub new {
4417 my ($class, $url) = @_;
4418 $url =~ s!/+$!!;
4419 return $RA if ($RA && $RA->{url} eq $url);
4421 SVN::_Core::svn_config_ensure($config_dir, undef);
4422 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
4423 my $config = SVN::Core::config_get_config($config_dir);
4424 $RA = undef;
4425 my $dont_store_passwords = 1;
4426 my $conf_t = ${$config}{'config'};
4428 no warnings 'once';
4429 # The usage of $SVN::_Core::SVN_CONFIG_* variables
4430 # produces warnings that variables are used only once.
4431 # I had not found the better way to shut them up, so
4432 # the warnings of type 'once' are disabled in this block.
4433 if (SVN::_Core::svn_config_get_bool($conf_t,
4434 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4435 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
4436 1) == 0) {
4437 SVN::_Core::svn_auth_set_parameter($baton,
4438 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
4439 bless (\$dont_store_passwords, "_p_void"));
4441 if (SVN::_Core::svn_config_get_bool($conf_t,
4442 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4443 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
4444 1) == 0) {
4445 $Git::SVN::Prompt::_no_auth_cache = 1;
4447 } # no warnings 'once'
4448 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
4449 config => $config,
4450 pool => SVN::Pool->new,
4451 auth_provider_callbacks => $callbacks);
4452 $self->{url} = $url;
4453 $self->{svn_path} = $url;
4454 $self->{repos_root} = $self->get_repos_root;
4455 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
4456 $self->{cache} = { check_path => { r => 0, data => {} },
4457 get_dir => { r => 0, data => {} } };
4458 $RA = bless $self, $class;
4461 sub check_path {
4462 my ($self, $path, $r) = @_;
4463 my $cache = $self->{cache}->{check_path};
4464 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
4465 return $cache->{data}->{$path};
4467 my $pool = SVN::Pool->new;
4468 my $t = $self->SUPER::check_path($path, $r, $pool);
4469 $pool->clear;
4470 if ($r != $cache->{r}) {
4471 %{$cache->{data}} = ();
4472 $cache->{r} = $r;
4474 $cache->{data}->{$path} = $t;
4477 sub get_dir {
4478 my ($self, $dir, $r) = @_;
4479 my $cache = $self->{cache}->{get_dir};
4480 if ($r == $cache->{r}) {
4481 if (my $x = $cache->{data}->{$dir}) {
4482 return wantarray ? @$x : $x->[0];
4485 my $pool = SVN::Pool->new;
4486 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
4487 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
4488 $pool->clear;
4489 if ($r != $cache->{r}) {
4490 %{$cache->{data}} = ();
4491 $cache->{r} = $r;
4493 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
4494 wantarray ? (\%dirents, $r, $props) : \%dirents;
4497 sub DESTROY {
4498 # do not call the real DESTROY since we store ourselves in $RA
4501 # get_log(paths, start, end, limit,
4502 # discover_changed_paths, strict_node_history, receiver)
4503 sub get_log {
4504 my ($self, @args) = @_;
4505 my $pool = SVN::Pool->new;
4507 # svn_log_changed_path_t objects passed to get_log are likely to be
4508 # overwritten even if only the refs are copied to an external variable,
4509 # so we should dup the structures in their entirety. Using an
4510 # externally passed pool (instead of our temporary and quickly cleared
4511 # pool in Git::SVN::Ra) does not help matters at all...
4512 my $receiver = pop @args;
4513 my $prefix = "/".$self->{svn_path};
4514 $prefix =~ s#/+($)##;
4515 my $prefix_regex = qr#^\Q$prefix\E#;
4516 push(@args, sub {
4517 my ($paths) = $_[0];
4518 return &$receiver(@_) unless $paths;
4519 $_[0] = ();
4520 foreach my $p (keys %$paths) {
4521 my $i = $paths->{$p};
4522 # Make path relative to our url, not repos_root
4523 $p =~ s/$prefix_regex//;
4524 my %s = map { $_ => $i->$_; }
4525 qw/copyfrom_path copyfrom_rev action/;
4526 if ($s{'copyfrom_path'}) {
4527 $s{'copyfrom_path'} =~ s/$prefix_regex//;
4529 $_[0]{$p} = \%s;
4531 &$receiver(@_);
4535 # the limit parameter was not supported in SVN 1.1.x, so we
4536 # drop it. Therefore, the receiver callback passed to it
4537 # is made aware of this limitation by being wrapped if
4538 # the limit passed to is being wrapped.
4539 if ($SVN::Core::VERSION le '1.2.0') {
4540 my $limit = splice(@args, 3, 1);
4541 if ($limit > 0) {
4542 my $receiver = pop @args;
4543 push(@args, sub { &$receiver(@_) if (--$limit >= 0) });
4546 my $ret = $self->SUPER::get_log(@args, $pool);
4547 $pool->clear;
4548 $ret;
4551 sub trees_match {
4552 my ($self, $url1, $rev1, $url2, $rev2) = @_;
4553 my $ctx = SVN::Client->new(auth => _auth_providers);
4554 my $out = IO::File->new_tmpfile;
4556 # older SVN (1.1.x) doesn't take $pool as the last parameter for
4557 # $ctx->diff(), so we'll create a default one
4558 my $pool = SVN::Pool->new_default_sub;
4560 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
4561 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
4562 $out->flush;
4563 my $ret = (($out->stat)[7] == 0);
4564 close $out or croak $!;
4566 $ret;
4569 sub get_commit_editor {
4570 my ($self, $log, $cb, $pool) = @_;
4571 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
4572 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
4575 sub gs_do_update {
4576 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
4577 my $new = ($rev_a == $rev_b);
4578 my $path = $gs->{path};
4580 if ($new && -e $gs->{index}) {
4581 unlink $gs->{index} or die
4582 "Couldn't unlink index: $gs->{index}: $!\n";
4584 my $pool = SVN::Pool->new;
4585 $editor->set_path_strip($path);
4586 my (@pc) = split m#/#, $path;
4587 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
4588 1, $editor, $pool);
4589 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4591 # Since we can't rely on svn_ra_reparent being available, we'll
4592 # just have to do some magic with set_path to make it so
4593 # we only want a partial path.
4594 my $sp = '';
4595 my $final = join('/', @pc);
4596 while (@pc) {
4597 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
4598 $sp .= '/' if length $sp;
4599 $sp .= shift @pc;
4601 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
4603 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
4605 $reporter->finish_report($pool);
4606 $pool->clear;
4607 $editor->{git_commit_ok};
4610 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
4611 # svn_ra_reparent didn't work before 1.4)
4612 sub gs_do_switch {
4613 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
4614 my $path = $gs->{path};
4615 my $pool = SVN::Pool->new;
4617 my $full_url = $self->{url};
4618 my $old_url = $full_url;
4619 $full_url .= '/' . $path if length $path;
4620 my ($ra, $reparented);
4622 if ($old_url =~ m#^svn(\+ssh)?://# ||
4623 ($full_url =~ m#^https?://# &&
4624 escape_url($full_url) ne $full_url)) {
4625 $_[0] = undef;
4626 $self = undef;
4627 $RA = undef;
4628 $ra = Git::SVN::Ra->new($full_url);
4629 $ra_invalid = 1;
4630 } elsif ($old_url ne $full_url) {
4631 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url, $pool);
4632 $self->{url} = $full_url;
4633 $reparented = 1;
4636 $ra ||= $self;
4637 $url_b = escape_url($url_b);
4638 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
4639 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4640 $reporter->set_path('', $rev_a, 0, @lock, $pool);
4641 $reporter->finish_report($pool);
4643 if ($reparented) {
4644 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
4645 $self->{url} = $old_url;
4648 $pool->clear;
4649 $editor->{git_commit_ok};
4652 sub longest_common_path {
4653 my ($gsv, $globs) = @_;
4654 my %common;
4655 my $common_max = scalar @$gsv;
4657 foreach my $gs (@$gsv) {
4658 my @tmp = split m#/#, $gs->{path};
4659 my $p = '';
4660 foreach (@tmp) {
4661 $p .= length($p) ? "/$_" : $_;
4662 $common{$p} ||= 0;
4663 $common{$p}++;
4666 $globs ||= [];
4667 $common_max += scalar @$globs;
4668 foreach my $glob (@$globs) {
4669 my @tmp = split m#/#, $glob->{path}->{left};
4670 my $p = '';
4671 foreach (@tmp) {
4672 $p .= length($p) ? "/$_" : $_;
4673 $common{$p} ||= 0;
4674 $common{$p}++;
4678 my $longest_path = '';
4679 foreach (sort {length $b <=> length $a} keys %common) {
4680 if ($common{$_} == $common_max) {
4681 $longest_path = $_;
4682 last;
4685 $longest_path;
4688 sub gs_fetch_loop_common {
4689 my ($self, $base, $head, $gsv, $globs) = @_;
4690 return if ($base > $head);
4691 my $inc = $_log_window_size;
4692 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
4693 my $longest_path = longest_common_path($gsv, $globs);
4694 my $ra_url = $self->{url};
4695 my $find_trailing_edge;
4696 while (1) {
4697 my %revs;
4698 my $err;
4699 my $err_handler = $SVN::Error::handler;
4700 $SVN::Error::handler = sub {
4701 ($err) = @_;
4702 skip_unknown_revs($err);
4704 sub _cb {
4705 my ($paths, $r, $author, $date, $log) = @_;
4706 [ $paths,
4707 { author => $author, date => $date, log => $log } ];
4709 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
4710 sub { $revs{$_[1]} = _cb(@_) });
4711 if ($err) {
4712 print "Checked through r$max\r";
4713 } else {
4714 $find_trailing_edge = 1;
4716 if ($err and $find_trailing_edge) {
4717 print STDERR "Path '$longest_path' ",
4718 "was probably deleted:\n",
4719 $err->expanded_message,
4720 "\nWill attempt to follow ",
4721 "revisions r$min .. r$max ",
4722 "committed before the deletion\n";
4723 my $hi = $max;
4724 while (--$hi >= $min) {
4725 my $ok;
4726 $self->get_log([$longest_path], $min, $hi,
4727 0, 1, 1, sub {
4728 $ok = $_[1];
4729 $revs{$_[1]} = _cb(@_) });
4730 if ($ok) {
4731 print STDERR "r$min .. r$ok OK\n";
4732 last;
4735 $find_trailing_edge = 0;
4737 $SVN::Error::handler = $err_handler;
4739 my %exists = map { $_->{path} => $_ } @$gsv;
4740 foreach my $r (sort {$a <=> $b} keys %revs) {
4741 my ($paths, $logged) = @{$revs{$r}};
4743 foreach my $gs ($self->match_globs(\%exists, $paths,
4744 $globs, $r)) {
4745 if ($gs->rev_map_max >= $r) {
4746 next;
4748 next unless $gs->match_paths($paths, $r);
4749 $gs->{logged_rev_props} = $logged;
4750 if (my $last_commit = $gs->last_commit) {
4751 $gs->assert_index_clean($last_commit);
4753 my $log_entry = $gs->do_fetch($paths, $r);
4754 if ($log_entry) {
4755 $gs->do_git_commit($log_entry);
4757 $INDEX_FILES{$gs->{index}} = 1;
4759 foreach my $g (@$globs) {
4760 my $k = "svn-remote.$g->{remote}." .
4761 "$g->{t}-maxRev";
4762 Git::SVN::tmp_config($k, $r);
4764 if ($ra_invalid) {
4765 $_[0] = undef;
4766 $self = undef;
4767 $RA = undef;
4768 $self = Git::SVN::Ra->new($ra_url);
4769 $ra_invalid = undef;
4772 # pre-fill the .rev_db since it'll eventually get filled in
4773 # with '0' x40 if something new gets committed
4774 foreach my $gs (@$gsv) {
4775 next if $gs->rev_map_max >= $max;
4776 next if defined $gs->rev_map_get($max);
4777 $gs->rev_map_set($max, 0 x40);
4779 foreach my $g (@$globs) {
4780 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
4781 Git::SVN::tmp_config($k, $max);
4783 last if $max >= $head;
4784 $min = $max + 1;
4785 $max += $inc;
4786 $max = $head if ($max > $head);
4788 Git::SVN::gc();
4791 sub get_dir_globbed {
4792 my ($self, $left, $depth, $r) = @_;
4794 my @x = eval { $self->get_dir($left, $r) };
4795 return unless scalar @x == 3;
4796 my $dirents = $x[0];
4797 my @finalents;
4798 foreach my $de (keys %$dirents) {
4799 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
4800 if ($depth > 1) {
4801 my @args = ("$left/$de", $depth - 1, $r);
4802 foreach my $dir ($self->get_dir_globbed(@args)) {
4803 push @finalents, "$de/$dir";
4805 } else {
4806 push @finalents, $de;
4809 @finalents;
4812 sub match_globs {
4813 my ($self, $exists, $paths, $globs, $r) = @_;
4815 sub get_dir_check {
4816 my ($self, $exists, $g, $r) = @_;
4818 my @dirs = $self->get_dir_globbed($g->{path}->{left},
4819 $g->{path}->{depth},
4820 $r);
4822 foreach my $de (@dirs) {
4823 my $p = $g->{path}->full_path($de);
4824 next if $exists->{$p};
4825 next if (length $g->{path}->{right} &&
4826 ($self->check_path($p, $r) !=
4827 $SVN::Node::dir));
4828 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
4829 $g->{ref}->full_path($de), 1);
4832 foreach my $g (@$globs) {
4833 if (my $path = $paths->{"/$g->{path}->{left}"}) {
4834 if ($path->{action} =~ /^[AR]$/) {
4835 get_dir_check($self, $exists, $g, $r);
4838 foreach (keys %$paths) {
4839 if (/$g->{path}->{left_regex}/ &&
4840 !/$g->{path}->{regex}/) {
4841 next if $paths->{$_}->{action} !~ /^[AR]$/;
4842 get_dir_check($self, $exists, $g, $r);
4844 next unless /$g->{path}->{regex}/;
4845 my $p = $1;
4846 my $pathname = $g->{path}->full_path($p);
4847 next if $exists->{$pathname};
4848 next if ($self->check_path($pathname, $r) !=
4849 $SVN::Node::dir);
4850 $exists->{$pathname} = Git::SVN->init(
4851 $self->{url}, $pathname, undef,
4852 $g->{ref}->full_path($p), 1);
4854 my $c = '';
4855 foreach (split m#/#, $g->{path}->{left}) {
4856 $c .= "/$_";
4857 next unless ($paths->{$c} &&
4858 ($paths->{$c}->{action} =~ /^[AR]$/));
4859 get_dir_check($self, $exists, $g, $r);
4862 values %$exists;
4865 sub minimize_url {
4866 my ($self) = @_;
4867 return $self->{url} if ($self->{url} eq $self->{repos_root});
4868 my $url = $self->{repos_root};
4869 my @components = split(m!/!, $self->{svn_path});
4870 my $c = '';
4871 do {
4872 $url .= "/$c" if length $c;
4873 eval {
4874 my $ra = (ref $self)->new($url);
4875 my $latest = $ra->get_latest_revnum;
4876 $ra->get_log("", $latest, 0, 1, 0, 1, sub {});
4878 } while ($@ && ($c = shift @components));
4879 $url;
4882 sub can_do_switch {
4883 my $self = shift;
4884 unless (defined $can_do_switch) {
4885 my $pool = SVN::Pool->new;
4886 my $rep = eval {
4887 $self->do_switch(1, '', 0, $self->{url},
4888 SVN::Delta::Editor->new, $pool);
4890 if ($@) {
4891 $can_do_switch = 0;
4892 } else {
4893 $rep->abort_report($pool);
4894 $can_do_switch = 1;
4896 $pool->clear;
4898 $can_do_switch;
4901 sub skip_unknown_revs {
4902 my ($err) = @_;
4903 my $errno = $err->apr_err();
4904 # Maybe the branch we're tracking didn't
4905 # exist when the repo started, so it's
4906 # not an error if it doesn't, just continue
4908 # Wonderfully consistent library, eh?
4909 # 160013 - svn:// and file://
4910 # 175002 - http(s)://
4911 # 175007 - http(s):// (this repo required authorization, too...)
4912 # More codes may be discovered later...
4913 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
4914 my $err_key = $err->expanded_message;
4915 # revision numbers change every time, filter them out
4916 $err_key =~ s/\d+/\0/g;
4917 $err_key = "$errno\0$err_key";
4918 unless ($ignored_err{$err_key}) {
4919 warn "W: Ignoring error from SVN, path probably ",
4920 "does not exist: ($errno): ",
4921 $err->expanded_message,"\n";
4922 warn "W: Do not be alarmed at the above message ",
4923 "git-svn is just searching aggressively for ",
4924 "old history.\n",
4925 "This may take a while on large repositories\n";
4926 $ignored_err{$err_key} = 1;
4928 return;
4930 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
4933 package Git::SVN::Log;
4934 use strict;
4935 use warnings;
4936 use POSIX qw/strftime/;
4937 use Time::Local;
4938 use constant commit_log_separator => ('-' x 72) . "\n";
4939 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
4940 %rusers $show_commit $incremental/;
4941 my $l_fmt;
4943 sub cmt_showable {
4944 my ($c) = @_;
4945 return 1 if defined $c->{r};
4947 # big commit message got truncated by the 16k pretty buffer in rev-list
4948 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
4949 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
4950 @{$c->{l}} = ();
4951 my @log = command(qw/cat-file commit/, $c->{c});
4953 # shift off the headers
4954 shift @log while ($log[0] ne '');
4955 shift @log;
4957 # TODO: make $c->{l} not have a trailing newline in the future
4958 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
4960 (undef, $c->{r}, undef) = ::extract_metadata(
4961 (grep(/^git-svn-id: /, @log))[-1]);
4963 return defined $c->{r};
4966 sub log_use_color {
4967 return $color || Git->repository->get_colorbool('color.diff');
4970 sub git_svn_log_cmd {
4971 my ($r_min, $r_max, @args) = @_;
4972 my $head = 'HEAD';
4973 my (@files, @log_opts);
4974 foreach my $x (@args) {
4975 if ($x eq '--' || @files) {
4976 push @files, $x;
4977 } else {
4978 if (::verify_ref("$x^0")) {
4979 $head = $x;
4980 } else {
4981 push @log_opts, $x;
4986 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
4987 $gs ||= Git::SVN->_new;
4988 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
4989 $gs->refname);
4990 push @cmd, '-r' unless $non_recursive;
4991 push @cmd, qw/--raw --name-status/ if $verbose;
4992 push @cmd, '--color' if log_use_color();
4993 push @cmd, @log_opts;
4994 if (defined $r_max && $r_max == $r_min) {
4995 push @cmd, '--max-count=1';
4996 if (my $c = $gs->rev_map_get($r_max)) {
4997 push @cmd, $c;
4999 } elsif (defined $r_max) {
5000 if ($r_max < $r_min) {
5001 ($r_min, $r_max) = ($r_max, $r_min);
5003 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
5004 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
5005 # If there are no commits in the range, both $c_max and $c_min
5006 # will be undefined. If there is at least 1 commit in the
5007 # range, both will be defined.
5008 return () if !defined $c_min || !defined $c_max;
5009 if ($c_min eq $c_max) {
5010 push @cmd, '--max-count=1', $c_min;
5011 } else {
5012 push @cmd, '--boundary', "$c_min..$c_max";
5015 return (@cmd, @files);
5018 # adapted from pager.c
5019 sub config_pager {
5020 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
5021 if (!defined $pager) {
5022 $pager = 'less';
5023 } elsif (length $pager == 0 || $pager eq 'cat') {
5024 $pager = undef;
5026 $ENV{GIT_PAGER_IN_USE} = defined($pager);
5029 sub run_pager {
5030 return unless -t *STDOUT && defined $pager;
5031 pipe my ($rfd, $wfd) or return;
5032 defined(my $pid = fork) or ::fatal "Can't fork: $!";
5033 if (!$pid) {
5034 open STDOUT, '>&', $wfd or
5035 ::fatal "Can't redirect to stdout: $!";
5036 return;
5038 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
5039 $ENV{LESS} ||= 'FRSX';
5040 exec $pager or ::fatal "Can't run pager: $! ($pager)";
5043 sub format_svn_date {
5044 # some systmes don't handle or mishandle %z, so be creative.
5045 my $t = shift || time;
5046 my $gm = timelocal(gmtime($t));
5047 my $sign = qw( + + - )[ $t <=> $gm ];
5048 my $gmoff = sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
5049 return strftime("%Y-%m-%d %H:%M:%S $gmoff (%a, %d %b %Y)", localtime($t));
5052 sub parse_git_date {
5053 my ($t, $tz) = @_;
5054 # Date::Parse isn't in the standard Perl distro :(
5055 if ($tz =~ s/^\+//) {
5056 $t += tz_to_s_offset($tz);
5057 } elsif ($tz =~ s/^\-//) {
5058 $t -= tz_to_s_offset($tz);
5060 return $t;
5063 sub set_local_timezone {
5064 if (defined $TZ) {
5065 $ENV{TZ} = $TZ;
5066 } else {
5067 delete $ENV{TZ};
5071 sub tz_to_s_offset {
5072 my ($tz) = @_;
5073 $tz =~ s/(\d\d)$//;
5074 return ($1 * 60) + ($tz * 3600);
5077 sub get_author_info {
5078 my ($dest, $author, $t, $tz) = @_;
5079 $author =~ s/(?:^\s*|\s*$)//g;
5080 $dest->{a_raw} = $author;
5081 my $au;
5082 if ($::_authors) {
5083 $au = $rusers{$author} || undef;
5085 if (!$au) {
5086 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
5088 $dest->{t} = $t;
5089 $dest->{tz} = $tz;
5090 $dest->{a} = $au;
5091 $dest->{t_utc} = parse_git_date($t, $tz);
5094 sub process_commit {
5095 my ($c, $r_min, $r_max, $defer) = @_;
5096 if (defined $r_min && defined $r_max) {
5097 if ($r_min == $c->{r} && $r_min == $r_max) {
5098 show_commit($c);
5099 return 0;
5101 return 1 if $r_min == $r_max;
5102 if ($r_min < $r_max) {
5103 # we need to reverse the print order
5104 return 0 if (defined $limit && --$limit < 0);
5105 push @$defer, $c;
5106 return 1;
5108 if ($r_min != $r_max) {
5109 return 1 if ($r_min < $c->{r});
5110 return 1 if ($r_max > $c->{r});
5113 return 0 if (defined $limit && --$limit < 0);
5114 show_commit($c);
5115 return 1;
5118 sub show_commit {
5119 my $c = shift;
5120 if ($oneline) {
5121 my $x = "\n";
5122 if (my $l = $c->{l}) {
5123 while ($l->[0] =~ /^\s*$/) { shift @$l }
5124 $x = $l->[0];
5126 $l_fmt ||= 'A' . length($c->{r});
5127 print 'r',pack($l_fmt, $c->{r}),' | ';
5128 print "$c->{c} | " if $show_commit;
5129 print $x;
5130 } else {
5131 show_commit_normal($c);
5135 sub show_commit_changed_paths {
5136 my ($c) = @_;
5137 return unless $c->{changed};
5138 print "Changed paths:\n", @{$c->{changed}};
5141 sub show_commit_normal {
5142 my ($c) = @_;
5143 print commit_log_separator, "r$c->{r} | ";
5144 print "$c->{c} | " if $show_commit;
5145 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
5146 my $nr_line = 0;
5148 if (my $l = $c->{l}) {
5149 while ($l->[$#$l] eq "\n" && $#$l > 0
5150 && $l->[($#$l - 1)] eq "\n") {
5151 pop @$l;
5153 $nr_line = scalar @$l;
5154 if (!$nr_line) {
5155 print "1 line\n\n\n";
5156 } else {
5157 if ($nr_line == 1) {
5158 $nr_line = '1 line';
5159 } else {
5160 $nr_line .= ' lines';
5162 print $nr_line, "\n";
5163 show_commit_changed_paths($c);
5164 print "\n";
5165 print $_ foreach @$l;
5167 } else {
5168 print "1 line\n";
5169 show_commit_changed_paths($c);
5170 print "\n";
5173 foreach my $x (qw/raw stat diff/) {
5174 if ($c->{$x}) {
5175 print "\n";
5176 print $_ foreach @{$c->{$x}}
5181 sub cmd_show_log {
5182 my (@args) = @_;
5183 my ($r_min, $r_max);
5184 my $r_last = -1; # prevent dupes
5185 set_local_timezone();
5186 if (defined $::_revision) {
5187 if ($::_revision =~ /^(\d+):(\d+)$/) {
5188 ($r_min, $r_max) = ($1, $2);
5189 } elsif ($::_revision =~ /^\d+$/) {
5190 $r_min = $r_max = $::_revision;
5191 } else {
5192 ::fatal "-r$::_revision is not supported, use ",
5193 "standard 'git log' arguments instead";
5197 config_pager();
5198 @args = git_svn_log_cmd($r_min, $r_max, @args);
5199 if (!@args) {
5200 print commit_log_separator unless $incremental || $oneline;
5201 return;
5203 my $log = command_output_pipe(@args);
5204 run_pager();
5205 my (@k, $c, $d, $stat);
5206 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
5207 while (<$log>) {
5208 if (/^${esc_color}commit -?($::sha1_short)/o) {
5209 my $cmt = $1;
5210 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
5211 $r_last = $c->{r};
5212 process_commit($c, $r_min, $r_max, \@k) or
5213 goto out;
5215 $d = undef;
5216 $c = { c => $cmt };
5217 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
5218 get_author_info($c, $1, $2, $3);
5219 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
5220 # ignore
5221 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
5222 push @{$c->{raw}}, $_;
5223 } elsif (/^${esc_color}[ACRMDT]\t/) {
5224 # we could add $SVN->{svn_path} here, but that requires
5225 # remote access at the moment (repo_path_split)...
5226 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
5227 push @{$c->{changed}}, $_;
5228 } elsif (/^${esc_color}diff /o) {
5229 $d = 1;
5230 push @{$c->{diff}}, $_;
5231 } elsif ($d) {
5232 push @{$c->{diff}}, $_;
5233 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
5234 $esc_color*[\+\-]*$esc_color$/x) {
5235 $stat = 1;
5236 push @{$c->{stat}}, $_;
5237 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
5238 push @{$c->{stat}}, $_;
5239 $stat = undef;
5240 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
5241 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
5242 } elsif (s/^${esc_color} //o) {
5243 push @{$c->{l}}, $_;
5246 if ($c && defined $c->{r} && $c->{r} != $r_last) {
5247 $r_last = $c->{r};
5248 process_commit($c, $r_min, $r_max, \@k);
5250 if (@k) {
5251 ($r_min, $r_max) = ($r_max, $r_min);
5252 process_commit($_, $r_min, $r_max) foreach reverse @k;
5254 out:
5255 close $log;
5256 print commit_log_separator unless $incremental || $oneline;
5259 sub cmd_blame {
5260 my $path = pop;
5262 config_pager();
5263 run_pager();
5265 my ($fh, $ctx, $rev);
5267 if ($_git_format) {
5268 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
5269 while (my $line = <$fh>) {
5270 if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
5271 # Uncommitted edits show up as a rev ID of
5272 # all zeros, which we can't look up with
5273 # cmt_metadata
5274 if ($1 !~ /^0+$/) {
5275 (undef, $rev, undef) =
5276 ::cmt_metadata($1);
5277 $rev = '0' if (!$rev);
5278 } else {
5279 $rev = '0';
5281 $rev = sprintf('%-10s', $rev);
5282 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
5284 print $line;
5286 } else {
5287 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
5288 '--', $path);
5289 my ($sha1);
5290 my %authors;
5291 my @buffer;
5292 my %dsha; #distinct sha keys
5294 while (my $line = <$fh>) {
5295 push @buffer, $line;
5296 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5297 $dsha{$1} = 1;
5301 my $s2r = ::cmt_sha2rev_batch([keys %dsha]);
5303 foreach my $line (@buffer) {
5304 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5305 $rev = $s2r->{$1};
5306 $rev = '0' if (!$rev)
5308 elsif ($line =~ /^author (.*)/) {
5309 $authors{$rev} = $1;
5310 $authors{$rev} =~ s/\s/_/g;
5312 elsif ($line =~ /^\t(.*)$/) {
5313 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
5317 command_close_pipe($fh, $ctx);
5320 package Git::SVN::Migration;
5321 # these version numbers do NOT correspond to actual version numbers
5322 # of git nor git-svn. They are just relative.
5324 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
5326 # v1 layout: .git/$id/info/url, refs/remotes/$id
5328 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
5330 # v3 layout: .git/svn/$id, refs/remotes/$id
5331 # - info/url may remain for backwards compatibility
5332 # - this is what we migrate up to this layout automatically,
5333 # - this will be used by git svn init on single branches
5334 # v3.1 layout (auto migrated):
5335 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
5336 # for backwards compatibility
5338 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
5339 # - this is only created for newly multi-init-ed
5340 # repositories. Similar in spirit to the
5341 # --use-separate-remotes option in git-clone (now default)
5342 # - we do not automatically migrate to this (following
5343 # the example set by core git)
5345 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
5346 # - newer, more-efficient format that uses 24-bytes per record
5347 # with no filler space.
5348 # - use xxd -c24 < .rev_map.$UUID to view and debug
5349 # - This is a one-way migration, repositories updated to the
5350 # new format will not be able to use old git-svn without
5351 # rebuilding the .rev_db. Rebuilding the rev_db is not
5352 # possible if noMetadata or useSvmProps are set; but should
5353 # be no problem for users that use the (sensible) defaults.
5354 use strict;
5355 use warnings;
5356 use Carp qw/croak/;
5357 use File::Path qw/mkpath/;
5358 use File::Basename qw/dirname basename/;
5359 use vars qw/$_minimize/;
5361 sub migrate_from_v0 {
5362 my $git_dir = $ENV{GIT_DIR};
5363 return undef unless -d $git_dir;
5364 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5365 my $migrated = 0;
5366 while (<$fh>) {
5367 chomp;
5368 my ($id, $orig_ref) = ($_, $_);
5369 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
5370 next unless -f "$git_dir/$id/info/url";
5371 my $new_ref = "refs/remotes/$id";
5372 if (::verify_ref("$new_ref^0")) {
5373 print STDERR "W: $orig_ref is probably an old ",
5374 "branch used by an ancient version of ",
5375 "git-svn.\n",
5376 "However, $new_ref also exists.\n",
5377 "We will not be able ",
5378 "to use this branch until this ",
5379 "ambiguity is resolved.\n";
5380 next;
5382 print STDERR "Migrating from v0 layout...\n" if !$migrated;
5383 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
5384 command_noisy('update-ref', $new_ref, $orig_ref);
5385 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
5386 $migrated++;
5388 command_close_pipe($fh, $ctx);
5389 print STDERR "Done migrating from v0 layout...\n" if $migrated;
5390 $migrated;
5393 sub migrate_from_v1 {
5394 my $git_dir = $ENV{GIT_DIR};
5395 my $migrated = 0;
5396 return $migrated unless -d $git_dir;
5397 my $svn_dir = "$git_dir/svn";
5399 # just in case somebody used 'svn' as their $id at some point...
5400 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
5402 print STDERR "Migrating from a git-svn v1 layout...\n";
5403 mkpath([$svn_dir]);
5404 print STDERR "Data from a previous version of git-svn exists, but\n\t",
5405 "$svn_dir\n\t(required for this version ",
5406 "($::VERSION) of git-svn) does not exist.\n";
5407 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5408 while (<$fh>) {
5409 my $x = $_;
5410 next unless $x =~ s#^refs/remotes/##;
5411 chomp $x;
5412 next unless -f "$git_dir/$x/info/url";
5413 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
5414 next unless $u;
5415 my $dn = dirname("$git_dir/svn/$x");
5416 mkpath([$dn]) unless -d $dn;
5417 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
5418 mkpath(["$git_dir/svn/svn"]);
5419 print STDERR " - $git_dir/$x/info => ",
5420 "$git_dir/svn/$x/info\n";
5421 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
5422 croak "$!: $x";
5423 # don't worry too much about these, they probably
5424 # don't exist with repos this old (save for index,
5425 # and we can easily regenerate that)
5426 foreach my $f (qw/unhandled.log index .rev_db/) {
5427 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
5429 } else {
5430 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
5431 rename "$git_dir/$x", "$git_dir/svn/$x" or
5432 croak "$!: $x";
5434 $migrated++;
5436 command_close_pipe($fh, $ctx);
5437 print STDERR "Done migrating from a git-svn v1 layout\n";
5438 $migrated;
5441 sub read_old_urls {
5442 my ($l_map, $pfx, $path) = @_;
5443 my @dir;
5444 foreach (<$path/*>) {
5445 if (-r "$_/info/url") {
5446 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
5447 my $ref_id = $pfx . basename $_;
5448 my $url = ::file_to_s("$_/info/url");
5449 $l_map->{$ref_id} = $url;
5450 } elsif (-d $_) {
5451 push @dir, $_;
5454 foreach (@dir) {
5455 my $x = $_;
5456 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
5457 read_old_urls($l_map, $x, $_);
5461 sub migrate_from_v2 {
5462 my @cfg = command(qw/config -l/);
5463 return if grep /^svn-remote\..+\.url=/, @cfg;
5464 my %l_map;
5465 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
5466 my $migrated = 0;
5468 foreach my $ref_id (sort keys %l_map) {
5469 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
5470 if ($@) {
5471 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
5473 $migrated++;
5475 $migrated;
5478 sub minimize_connections {
5479 my $r = Git::SVN::read_all_remotes();
5480 my $new_urls = {};
5481 my $root_repos = {};
5482 foreach my $repo_id (keys %$r) {
5483 my $url = $r->{$repo_id}->{url} or next;
5484 my $fetch = $r->{$repo_id}->{fetch} or next;
5485 my $ra = Git::SVN::Ra->new($url);
5487 # skip existing cases where we already connect to the root
5488 if (($ra->{url} eq $ra->{repos_root}) ||
5489 ($ra->{repos_root} eq $repo_id)) {
5490 $root_repos->{$ra->{url}} = $repo_id;
5491 next;
5494 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
5495 my $root_path = $ra->{url};
5496 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
5497 foreach my $path (keys %$fetch) {
5498 my $ref_id = $fetch->{$path};
5499 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
5501 # make sure we can read when connecting to
5502 # a higher level of a repository
5503 my ($last_rev, undef) = $gs->last_rev_commit;
5504 if (!defined $last_rev) {
5505 $last_rev = eval {
5506 $root_ra->get_latest_revnum;
5508 next if $@;
5510 my $new = $root_path;
5511 $new .= length $path ? "/$path" : '';
5512 eval {
5513 $root_ra->get_log([$new], $last_rev, $last_rev,
5514 0, 0, 1, sub { });
5516 next if $@;
5517 $new_urls->{$ra->{repos_root}}->{$new} =
5518 { ref_id => $ref_id,
5519 old_repo_id => $repo_id,
5520 old_path => $path };
5524 my @emptied;
5525 foreach my $url (keys %$new_urls) {
5526 # see if we can re-use an existing [svn-remote "repo_id"]
5527 # instead of creating a(n ugly) new section:
5528 my $repo_id = $root_repos->{$url} || $url;
5530 my $fetch = $new_urls->{$url};
5531 foreach my $path (keys %$fetch) {
5532 my $x = $fetch->{$path};
5533 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
5534 my $pfx = "svn-remote.$x->{old_repo_id}";
5536 my $old_fetch = quotemeta("$x->{old_path}:".
5537 "$x->{ref_id}");
5538 command_noisy(qw/config --unset/,
5539 "$pfx.fetch", '^'. $old_fetch . '$');
5540 delete $r->{$x->{old_repo_id}}->
5541 {fetch}->{$x->{old_path}};
5542 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
5543 command_noisy(qw/config --unset/,
5544 "$pfx.url");
5545 push @emptied, $x->{old_repo_id}
5549 if (@emptied) {
5550 my $file = $ENV{GIT_CONFIG} || "$ENV{GIT_DIR}/config";
5551 print STDERR <<EOF;
5552 The following [svn-remote] sections in your config file ($file) are empty
5553 and can be safely removed:
5555 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
5559 sub migration_check {
5560 migrate_from_v0();
5561 migrate_from_v1();
5562 migrate_from_v2();
5563 minimize_connections() if $_minimize;
5566 package Git::IndexInfo;
5567 use strict;
5568 use warnings;
5569 use Git qw/command_input_pipe command_close_pipe/;
5571 sub new {
5572 my ($class) = @_;
5573 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
5574 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
5577 sub remove {
5578 my ($self, $path) = @_;
5579 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
5580 return ++$self->{nr};
5582 undef;
5585 sub update {
5586 my ($self, $mode, $hash, $path) = @_;
5587 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
5588 return ++$self->{nr};
5590 undef;
5593 sub DESTROY {
5594 my ($self) = @_;
5595 command_close_pipe($self->{gui}, $self->{ctx});
5598 package Git::SVN::GlobSpec;
5599 use strict;
5600 use warnings;
5602 sub new {
5603 my ($class, $glob) = @_;
5604 my $re = $glob;
5605 $re =~ s!/+$!!g; # no need for trailing slashes
5606 $re =~ m!^([^*]*)(\*(?:/\*)*)(.*)$!;
5607 my $temp = $re;
5608 my ($left, $right) = ($1, $3);
5609 $re = $2;
5610 my $depth = $re =~ tr/*/*/;
5611 if ($depth != $temp =~ tr/*/*/) {
5612 die "Only one set of wildcard directories " .
5613 "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
5615 if ($depth == 0) {
5616 die "One '*' is needed for glob: '$glob'\n";
5618 $re =~ s!\*!\[^/\]*!g;
5619 $re = quotemeta($left) . "($re)" . quotemeta($right);
5620 if (length $left && !($left =~ s!/+$!!g)) {
5621 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
5623 if (length $right && !($right =~ s!^/+!!g)) {
5624 die "Missing leading '/' on right side of: '$glob' ($right)\n";
5626 my $left_re = qr/^\/\Q$left\E(\/|$)/;
5627 bless { left => $left, right => $right, left_regex => $left_re,
5628 regex => qr/$re/, glob => $glob, depth => $depth }, $class;
5631 sub full_path {
5632 my ($self, $path) = @_;
5633 return (length $self->{left} ? "$self->{left}/" : '') .
5634 $path . (length $self->{right} ? "/$self->{right}" : '');
5637 __END__
5639 Data structures:
5642 $remotes = { # returned by read_all_remotes()
5643 'svn' => {
5644 # svn-remote.svn.url=https://svn.musicpd.org
5645 url => 'https://svn.musicpd.org',
5646 # svn-remote.svn.fetch=mpd/trunk:trunk
5647 fetch => {
5648 'mpd/trunk' => 'trunk',
5650 # svn-remote.svn.tags=mpd/tags/*:tags/*
5651 tags => {
5652 path => {
5653 left => 'mpd/tags',
5654 right => '',
5655 regex => qr!mpd/tags/([^/]+)$!,
5656 glob => 'tags/*',
5658 ref => {
5659 left => 'tags',
5660 right => '',
5661 regex => qr!tags/([^/]+)$!,
5662 glob => 'tags/*',
5668 $log_entry hashref as returned by libsvn_log_entry()
5670 log => 'whitespace-formatted log entry
5671 ', # trailing newline is preserved
5672 revision => '8', # integer
5673 date => '2004-02-24T17:01:44.108345Z', # commit date
5674 author => 'committer name'
5678 # this is generated by generate_diff();
5679 @mods = array of diff-index line hashes, each element represents one line
5680 of diff-index output
5682 diff-index line ($m hash)
5684 mode_a => first column of diff-index output, no leading ':',
5685 mode_b => second column of diff-index output,
5686 sha1_b => sha1sum of the final blob,
5687 chg => change type [MCRADT],
5688 file_a => original file name of a file (iff chg is 'C' or 'R')
5689 file_b => new/current file name of a file (any chg)
5693 # retval of read_url_paths{,_all}();
5694 $l_map = {
5695 # repository root url
5696 'https://svn.musicpd.org' => {
5697 # repository path # GIT_SVN_ID
5698 'mpd/trunk' => 'trunk',
5699 'mpd/tags/0.11.5' => 'tags/0.11.5',
5703 Notes:
5704 I don't trust the each() function on unless I created %hash myself
5705 because the internal iterator may not have started at base.