request-pull: avoid mentioning that the start point is a single commit
[git/git-svn.git] / git-svn.perl
blobb321c968af33b9995bdf326724f34e99894cec82
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 'rewrite-uuid=s' => sub { $icv{rewriteUUID} = $_[1] },
119 %remote_opts );
120 my %cmt_opts = ( 'edit|e' => \$_edit,
121 'rmdir' => \$SVN::Git::Editor::_rmdir,
122 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
123 'l=i' => \$SVN::Git::Editor::_rename_limit,
124 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
127 my %cmd = (
128 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
129 { 'revision|r=s' => \$_revision,
130 'fetch-all|all' => \$_fetch_all,
131 'parent|p' => \$_fetch_parent,
132 %fc_opts } ],
133 clone => [ \&cmd_clone, "Initialize and fetch revisions",
134 { 'revision|r=s' => \$_revision,
135 %fc_opts, %init_opts } ],
136 init => [ \&cmd_init, "Initialize a repo for tracking" .
137 " (requires URL argument)",
138 \%init_opts ],
139 'multi-init' => [ \&cmd_multi_init,
140 "Deprecated alias for ".
141 "'$0 init -T<trunk> -b<branches> -t<tags>'",
142 \%init_opts ],
143 dcommit => [ \&cmd_dcommit,
144 'Commit several diffs to merge with upstream',
145 { 'merge|m|M' => \$_merge,
146 'strategy|s=s' => \$_strategy,
147 'verbose|v' => \$_verbose,
148 'dry-run|n' => \$_dry_run,
149 'fetch-all|all' => \$_fetch_all,
150 'commit-url=s' => \$_commit_url,
151 'revision|r=i' => \$_revision,
152 'no-rebase' => \$_no_rebase,
153 %cmt_opts, %fc_opts } ],
154 branch => [ \&cmd_branch,
155 'Create a branch in the SVN repository',
156 { 'message|m=s' => \$_message,
157 'destination|d=s' => \$_branch_dest,
158 'dry-run|n' => \$_dry_run,
159 'tag|t' => \$_tag,
160 'username=s' => \$Git::SVN::Prompt::_username,
161 'commit-url=s' => \$_commit_url } ],
162 tag => [ sub { $_tag = 1; cmd_branch(@_) },
163 'Create a tag in the SVN repository',
164 { 'message|m=s' => \$_message,
165 'destination|d=s' => \$_branch_dest,
166 'dry-run|n' => \$_dry_run,
167 'username=s' => \$Git::SVN::Prompt::_username,
168 'commit-url=s' => \$_commit_url } ],
169 'set-tree' => [ \&cmd_set_tree,
170 "Set an SVN repository to a git tree-ish",
171 { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
172 'create-ignore' => [ \&cmd_create_ignore,
173 'Create a .gitignore per svn:ignore',
174 { 'revision|r=i' => \$_revision
175 } ],
176 'mkdirs' => [ \&cmd_mkdirs ,
177 "recreate empty directories after a checkout",
178 { 'revision|r=i' => \$_revision } ],
179 'propget' => [ \&cmd_propget,
180 'Print the value of a property on a file or directory',
181 { 'revision|r=i' => \$_revision } ],
182 'proplist' => [ \&cmd_proplist,
183 'List all properties of a file or directory',
184 { 'revision|r=i' => \$_revision } ],
185 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
186 { 'revision|r=i' => \$_revision
187 } ],
188 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
189 { 'revision|r=i' => \$_revision
190 } ],
191 'multi-fetch' => [ \&cmd_multi_fetch,
192 "Deprecated alias for $0 fetch --all",
193 { 'revision|r=s' => \$_revision, %fc_opts } ],
194 'migrate' => [ sub { },
195 # no-op, we automatically run this anyways,
196 'Migrate configuration/metadata/layout from
197 previous versions of git-svn',
198 { 'minimize' => \$Git::SVN::Migration::_minimize,
199 %remote_opts } ],
200 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
201 { 'limit=i' => \$Git::SVN::Log::limit,
202 'revision|r=s' => \$_revision,
203 'verbose|v' => \$Git::SVN::Log::verbose,
204 'incremental' => \$Git::SVN::Log::incremental,
205 'oneline' => \$Git::SVN::Log::oneline,
206 'show-commit' => \$Git::SVN::Log::show_commit,
207 'non-recursive' => \$Git::SVN::Log::non_recursive,
208 'authors-file|A=s' => \$_authors,
209 'color' => \$Git::SVN::Log::color,
210 'pager=s' => \$Git::SVN::Log::pager
211 } ],
212 'find-rev' => [ \&cmd_find_rev,
213 "Translate between SVN revision numbers and tree-ish",
214 {} ],
215 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
216 { 'merge|m|M' => \$_merge,
217 'verbose|v' => \$_verbose,
218 'strategy|s=s' => \$_strategy,
219 'local|l' => \$_local,
220 'fetch-all|all' => \$_fetch_all,
221 'dry-run|n' => \$_dry_run,
222 %fc_opts } ],
223 'commit-diff' => [ \&cmd_commit_diff,
224 'Commit a diff between two trees',
225 { 'message|m=s' => \$_message,
226 'file|F=s' => \$_file,
227 'revision|r=s' => \$_revision,
228 %cmt_opts } ],
229 'info' => [ \&cmd_info,
230 "Show info about the latest SVN revision
231 on the current branch",
232 { 'url' => \$_url, } ],
233 'blame' => [ \&Git::SVN::Log::cmd_blame,
234 "Show what revision and author last modified each line of a file",
235 { 'git-format' => \$_git_format } ],
236 'reset' => [ \&cmd_reset,
237 "Undo fetches back to the specified SVN revision",
238 { 'revision|r=s' => \$_revision,
239 'parent|p' => \$_fetch_parent } ],
240 'gc' => [ \&cmd_gc,
241 "Compress unhandled.log files in .git/svn and remove " .
242 "index files in .git/svn",
243 {} ],
246 my $cmd;
247 for (my $i = 0; $i < @ARGV; $i++) {
248 if (defined $cmd{$ARGV[$i]}) {
249 $cmd = $ARGV[$i];
250 splice @ARGV, $i, 1;
251 last;
252 } elsif ($ARGV[$i] eq 'help') {
253 $cmd = $ARGV[$i+1];
254 usage(0);
258 # make sure we're always running at the top-level working directory
259 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
260 unless (-d $ENV{GIT_DIR}) {
261 if ($git_dir_user_set) {
262 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
263 "but it is not a directory\n";
265 my $git_dir = delete $ENV{GIT_DIR};
266 my $cdup = undef;
267 git_cmd_try {
268 $cdup = command_oneline(qw/rev-parse --show-cdup/);
269 $git_dir = '.' unless ($cdup);
270 chomp $cdup if ($cdup);
271 $cdup = "." unless ($cdup && length $cdup);
272 } "Already at toplevel, but $git_dir not found\n";
273 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
274 unless (-d $git_dir) {
275 die "$git_dir still not found after going to ",
276 "'$cdup'\n";
278 $ENV{GIT_DIR} = $git_dir;
280 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
283 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
285 read_git_config(\%opts);
286 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
287 Getopt::Long::Configure('pass_through');
289 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
290 'minimize-connections' => \$Git::SVN::Migration::_minimize,
291 'id|i=s' => \$Git::SVN::default_ref_id,
292 'svn-remote|remote|R=s' => sub {
293 $Git::SVN::no_reuse_existing = 1;
294 $Git::SVN::default_repo_id = $_[1] });
295 exit 1 if (!$rv && $cmd && $cmd ne 'log');
297 usage(0) if $_help;
298 version() if $_version;
299 usage(1) unless defined $cmd;
300 load_authors() if $_authors;
301 if (defined $_authors_prog) {
302 $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
305 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
306 Git::SVN::Migration::migration_check();
308 Git::SVN::init_vars();
309 eval {
310 Git::SVN::verify_remotes_sanity();
311 $cmd{$cmd}->[0]->(@ARGV);
313 fatal $@ if $@;
314 post_fetch_checkout();
315 exit 0;
317 ####################### primary functions ######################
318 sub usage {
319 my $exit = shift || 0;
320 my $fd = $exit ? \*STDERR : \*STDOUT;
321 print $fd <<"";
322 git-svn - bidirectional operations between a single Subversion tree and git
323 Usage: git svn <command> [options] [arguments]\n
325 print $fd "Available commands:\n" unless $cmd;
327 foreach (sort keys %cmd) {
328 next if $cmd && $cmd ne $_;
329 next if /^multi-/; # don't show deprecated commands
330 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
331 foreach (sort keys %{$cmd{$_}->[2]}) {
332 # mixed-case options are for .git/config only
333 next if /[A-Z]/ && /^[a-z]+$/i;
334 # prints out arguments as they should be passed:
335 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
336 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
337 "--$_" : "-$_" }
338 split /\|/,$_)," $x\n";
341 print $fd <<"";
342 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
343 arbitrary identifier if you're tracking multiple SVN branches/repositories in
344 one git repository and want to keep them separate. See git-svn(1) for more
345 information.
347 exit $exit;
350 sub version {
351 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
352 exit 0;
355 sub do_git_init_db {
356 unless (-d $ENV{GIT_DIR}) {
357 my @init_db = ('init');
358 push @init_db, "--template=$_template" if defined $_template;
359 if (defined $_shared) {
360 if ($_shared =~ /[a-z]/) {
361 push @init_db, "--shared=$_shared";
362 } else {
363 push @init_db, "--shared";
366 command_noisy(@init_db);
367 $_repository = Git->repository(Repository => ".git");
369 command_noisy('config', 'core.autocrlf', 'false');
370 my $set;
371 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
372 foreach my $i (keys %icv) {
373 die "'$set' and '$i' cannot both be set\n" if $set;
374 next unless defined $icv{$i};
375 command_noisy('config', "$pfx.$i", $icv{$i});
376 $set = $i;
378 my $ignore_regex = \$SVN::Git::Fetcher::_ignore_regex;
379 command_noisy('config', "$pfx.ignore-paths", $$ignore_regex)
380 if defined $$ignore_regex;
383 sub init_subdir {
384 my $repo_path = shift or return;
385 mkpath([$repo_path]) unless -d $repo_path;
386 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
387 $ENV{GIT_DIR} = '.git';
388 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
391 sub cmd_clone {
392 my ($url, $path) = @_;
393 if (!defined $path &&
394 (defined $_trunk || @_branches || @_tags ||
395 defined $_stdlayout) &&
396 $url !~ m#^[a-z\+]+://#) {
397 $path = $url;
399 $path = basename($url) if !defined $path || !length $path;
400 my $authors_absolute = $_authors ? File::Spec->rel2abs($_authors) : "";
401 cmd_init($url, $path);
402 command_oneline('config', 'svn.authorsfile', $authors_absolute)
403 if $_authors;
404 Git::SVN::fetch_all($Git::SVN::default_repo_id);
407 sub cmd_init {
408 if (defined $_stdlayout) {
409 $_trunk = 'trunk' if (!defined $_trunk);
410 @_tags = 'tags' if (! @_tags);
411 @_branches = 'branches' if (! @_branches);
413 if (defined $_trunk || @_branches || @_tags) {
414 return cmd_multi_init(@_);
416 my $url = shift or die "SVN repository location required ",
417 "as a command-line argument\n";
418 $url = canonicalize_url($url);
419 init_subdir(@_);
420 do_git_init_db();
422 if ($Git::SVN::_minimize_url eq 'unset') {
423 $Git::SVN::_minimize_url = 0;
426 Git::SVN->init($url);
429 sub cmd_fetch {
430 if (grep /^\d+=./, @_) {
431 die "'<rev>=<commit>' fetch arguments are ",
432 "no longer supported.\n";
434 my ($remote) = @_;
435 if (@_ > 1) {
436 die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
438 $Git::SVN::no_reuse_existing = undef;
439 if ($_fetch_parent) {
440 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
441 unless ($gs) {
442 die "Unable to determine upstream SVN information from ",
443 "working tree history\n";
445 # just fetch, don't checkout.
446 $_no_checkout = 'true';
447 $_fetch_all ? $gs->fetch_all : $gs->fetch;
448 } elsif ($_fetch_all) {
449 cmd_multi_fetch();
450 } else {
451 $remote ||= $Git::SVN::default_repo_id;
452 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
456 sub cmd_set_tree {
457 my (@commits) = @_;
458 if ($_stdin || !@commits) {
459 print "Reading from stdin...\n";
460 @commits = ();
461 while (<STDIN>) {
462 if (/\b($sha1_short)\b/o) {
463 unshift @commits, $1;
467 my @revs;
468 foreach my $c (@commits) {
469 my @tmp = command('rev-parse',$c);
470 if (scalar @tmp == 1) {
471 push @revs, $tmp[0];
472 } elsif (scalar @tmp > 1) {
473 push @revs, reverse(command('rev-list',@tmp));
474 } else {
475 fatal "Failed to rev-parse $c";
478 my $gs = Git::SVN->new;
479 my ($r_last, $cmt_last) = $gs->last_rev_commit;
480 $gs->fetch;
481 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
482 fatal "There are new revisions that were fetched ",
483 "and need to be merged (or acknowledged) ",
484 "before committing.\nlast rev: $r_last\n",
485 " current: $gs->{last_rev}";
487 $gs->set_tree($_) foreach @revs;
488 print "Done committing ",scalar @revs," revisions to SVN\n";
489 unlink $gs->{index};
492 sub cmd_dcommit {
493 my $head = shift;
494 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
495 'Cannot dcommit with a dirty index. Commit your changes first, '
496 . "or stash them with `git stash'.\n";
497 $head ||= 'HEAD';
499 my $old_head;
500 if ($head ne 'HEAD') {
501 $old_head = eval {
502 command_oneline([qw/symbolic-ref -q HEAD/])
504 if ($old_head) {
505 $old_head =~ s{^refs/heads/}{};
506 } else {
507 $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
509 command(['checkout', $head], STDERR => 0);
512 my @refs;
513 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
514 unless ($gs) {
515 die "Unable to determine upstream SVN information from ",
516 "$head history.\nPerhaps the repository is empty.";
519 if (defined $_commit_url) {
520 $url = $_commit_url;
521 } else {
522 $url = eval { command_oneline('config', '--get',
523 "svn-remote.$gs->{repo_id}.commiturl") };
524 if (!$url) {
525 $url = $gs->full_url
529 my $last_rev = $_revision if defined $_revision;
530 if ($url) {
531 print "Committing to $url ...\n";
533 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
534 if ($_no_rebase && scalar(@$linear_refs) > 1) {
535 warn "Attempting to commit more than one change while ",
536 "--no-rebase is enabled.\n",
537 "If these changes depend on each other, re-running ",
538 "without --no-rebase may be required."
540 my $expect_url = $url;
541 Git::SVN::remove_username($expect_url);
542 while (1) {
543 my $d = shift @$linear_refs or last;
544 unless (defined $last_rev) {
545 (undef, $last_rev, undef) = cmt_metadata("$d~1");
546 unless (defined $last_rev) {
547 fatal "Unable to extract revision information ",
548 "from commit $d~1";
551 if ($_dry_run) {
552 print "diff-tree $d~1 $d\n";
553 } else {
554 my $cmt_rev;
555 my %ed_opts = ( r => $last_rev,
556 log => get_commit_entry($d)->{log},
557 ra => Git::SVN::Ra->new($url),
558 config => SVN::Core::config_get_config(
559 $Git::SVN::Ra::config_dir
561 tree_a => "$d~1",
562 tree_b => $d,
563 editor_cb => sub {
564 print "Committed r$_[0]\n";
565 $cmt_rev = $_[0];
567 svn_path => '');
568 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
569 print "No changes\n$d~1 == $d\n";
570 } elsif ($parents->{$d} && @{$parents->{$d}}) {
571 $gs->{inject_parents_dcommit}->{$cmt_rev} =
572 $parents->{$d};
574 $_fetch_all ? $gs->fetch_all : $gs->fetch;
575 $last_rev = $cmt_rev;
576 next if $_no_rebase;
578 # we always want to rebase against the current HEAD,
579 # not any head that was passed to us
580 my @diff = command('diff-tree', $d,
581 $gs->refname, '--');
582 my @finish;
583 if (@diff) {
584 @finish = rebase_cmd();
585 print STDERR "W: $d and ", $gs->refname,
586 " differ, using @finish:\n",
587 join("\n", @diff), "\n";
588 } else {
589 print "No changes between current HEAD and ",
590 $gs->refname,
591 "\nResetting to the latest ",
592 $gs->refname, "\n";
593 @finish = qw/reset --mixed/;
595 command_noisy(@finish, $gs->refname);
596 if (@diff) {
597 @refs = ();
598 my ($url_, $rev_, $uuid_, $gs_) =
599 working_head_info('HEAD', \@refs);
600 my ($linear_refs_, $parents_) =
601 linearize_history($gs_, \@refs);
602 if (scalar(@$linear_refs) !=
603 scalar(@$linear_refs_)) {
604 fatal "# of revisions changed ",
605 "\nbefore:\n",
606 join("\n", @$linear_refs),
607 "\n\nafter:\n",
608 join("\n", @$linear_refs_), "\n",
609 'If you are attempting to commit ',
610 "merges, try running:\n\t",
611 'git rebase --interactive',
612 '--preserve-merges ',
613 $gs->refname,
614 "\nBefore dcommitting";
616 if ($url_ ne $expect_url) {
617 if ($url_ eq $gs->metadata_url) {
618 print
619 "Accepting rewritten URL:",
620 " $url_\n";
621 } else {
622 fatal
623 "URL mismatch after rebase:",
624 " $url_ != $expect_url";
627 if ($uuid_ ne $uuid) {
628 fatal "uuid mismatch after rebase: ",
629 "$uuid_ != $uuid";
631 # remap parents
632 my (%p, @l, $i);
633 for ($i = 0; $i < scalar @$linear_refs; $i++) {
634 my $new = $linear_refs_->[$i] or next;
635 $p{$new} =
636 $parents->{$linear_refs->[$i]};
637 push @l, $new;
639 $parents = \%p;
640 $linear_refs = \@l;
645 if ($old_head) {
646 my $new_head = command_oneline(qw/rev-parse HEAD/);
647 my $new_is_symbolic = eval {
648 command_oneline(qw/symbolic-ref -q HEAD/);
650 if ($new_is_symbolic) {
651 print "dcommitted the branch ", $head, "\n";
652 } else {
653 print "dcommitted on a detached HEAD because you gave ",
654 "a revision argument.\n",
655 "The rewritten commit is: ", $new_head, "\n";
657 command(['checkout', $old_head], STDERR => 0);
660 unlink $gs->{index};
663 sub cmd_branch {
664 my ($branch_name, $head) = @_;
666 unless (defined $branch_name && length $branch_name) {
667 die(($_tag ? "tag" : "branch") . " name required\n");
669 $head ||= 'HEAD';
671 my (undef, $rev, undef, $gs) = working_head_info($head);
672 my $src = $gs->full_url;
674 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
675 my $allglobs = $remote->{ $_tag ? 'tags' : 'branches' };
676 my $glob;
677 if ($#{$allglobs} == 0) {
678 $glob = $allglobs->[0];
679 } else {
680 unless(defined $_branch_dest) {
681 die "Multiple ",
682 $_tag ? "tag" : "branch",
683 " paths defined for Subversion repository.\n",
684 "You must specify where you want to create the ",
685 $_tag ? "tag" : "branch",
686 " with the --destination argument.\n";
688 foreach my $g (@{$allglobs}) {
689 # SVN::Git::Editor could probably be moved to Git.pm..
690 my $re = SVN::Git::Editor::glob2pat($g->{path}->{left});
691 if ($_branch_dest =~ /$re/) {
692 $glob = $g;
693 last;
696 unless (defined $glob) {
697 my $dest_re = qr/\b\Q$_branch_dest\E\b/;
698 foreach my $g (@{$allglobs}) {
699 $g->{path}->{left} =~ /$dest_re/ or next;
700 if (defined $glob) {
701 die "Ambiguous destination: ",
702 $_branch_dest, "\nmatches both '",
703 $glob->{path}->{left}, "' and '",
704 $g->{path}->{left}, "'\n";
706 $glob = $g;
708 unless (defined $glob) {
709 die "Unknown ",
710 $_tag ? "tag" : "branch",
711 " destination $_branch_dest\n";
715 my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
716 my $url;
717 if (defined $_commit_url) {
718 $url = $_commit_url;
719 } else {
720 $url = eval { command_oneline('config', '--get',
721 "svn-remote.$gs->{repo_id}.commiturl") };
722 if (!$url) {
723 $url = $remote->{url};
726 my $dst = join '/', $url, $lft, $branch_name, ($rgt || ());
728 if ($dst =~ /^https:/ && $src =~ /^http:/) {
729 $src=~s/^http:/https:/;
732 my $ctx = SVN::Client->new(
733 auth => Git::SVN::Ra::_auth_providers(),
734 log_msg => sub {
735 ${ $_[0] } = defined $_message
736 ? $_message
737 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
738 . $branch_name;
742 eval {
743 $ctx->ls($dst, 'HEAD', 0);
744 } and die "branch ${branch_name} already exists\n";
746 print "Copying ${src} at r${rev} to ${dst}...\n";
747 $ctx->copy($src, $rev, $dst)
748 unless $_dry_run;
750 $gs->fetch_all;
753 sub cmd_find_rev {
754 my $revision_or_hash = shift or die "SVN or git revision required ",
755 "as a command-line argument\n";
756 my $result;
757 if ($revision_or_hash =~ /^r\d+$/) {
758 my $head = shift;
759 $head ||= 'HEAD';
760 my @refs;
761 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
762 unless ($gs) {
763 die "Unable to determine upstream SVN information from ",
764 "$head history\n";
766 my $desired_revision = substr($revision_or_hash, 1);
767 $result = $gs->rev_map_get($desired_revision, $uuid);
768 } else {
769 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
770 $result = $rev;
772 print "$result\n" if $result;
775 sub cmd_rebase {
776 command_noisy(qw/update-index --refresh/);
777 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
778 unless ($gs) {
779 die "Unable to determine upstream SVN information from ",
780 "working tree history\n";
782 if ($_dry_run) {
783 print "Remote Branch: " . $gs->refname . "\n";
784 print "SVN URL: " . $url . "\n";
785 return;
787 if (command(qw/diff-index HEAD --/)) {
788 print STDERR "Cannot rebase with uncommited changes:\n";
789 command_noisy('status');
790 exit 1;
792 unless ($_local) {
793 # rebase will checkout for us, so no need to do it explicitly
794 $_no_checkout = 'true';
795 $_fetch_all ? $gs->fetch_all : $gs->fetch;
797 command_noisy(rebase_cmd(), $gs->refname);
798 $gs->mkemptydirs;
801 sub cmd_show_ignore {
802 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
803 $gs ||= Git::SVN->new;
804 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
805 $gs->prop_walk($gs->{path}, $r, sub {
806 my ($gs, $path, $props) = @_;
807 print STDOUT "\n# $path\n";
808 my $s = $props->{'svn:ignore'} or return;
809 $s =~ s/[\r\n]+/\n/g;
810 $s =~ s/^\n+//;
811 chomp $s;
812 $s =~ s#^#$path#gm;
813 print STDOUT "$s\n";
817 sub cmd_show_externals {
818 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
819 $gs ||= Git::SVN->new;
820 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
821 $gs->prop_walk($gs->{path}, $r, sub {
822 my ($gs, $path, $props) = @_;
823 print STDOUT "\n# $path\n";
824 my $s = $props->{'svn:externals'} or return;
825 $s =~ s/[\r\n]+/\n/g;
826 chomp $s;
827 $s =~ s#^#$path#gm;
828 print STDOUT "$s\n";
832 sub cmd_create_ignore {
833 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
834 $gs ||= Git::SVN->new;
835 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
836 $gs->prop_walk($gs->{path}, $r, sub {
837 my ($gs, $path, $props) = @_;
838 # $path is of the form /path/to/dir/
839 $path = '.' . $path;
840 # SVN can have attributes on empty directories,
841 # which git won't track
842 mkpath([$path]) unless -d $path;
843 my $ignore = $path . '.gitignore';
844 my $s = $props->{'svn:ignore'} or return;
845 open(GITIGNORE, '>', $ignore)
846 or fatal("Failed to open `$ignore' for writing: $!");
847 $s =~ s/[\r\n]+/\n/g;
848 $s =~ s/^\n+//;
849 chomp $s;
850 # Prefix all patterns so that the ignore doesn't apply
851 # to sub-directories.
852 $s =~ s#^#/#gm;
853 print GITIGNORE "$s\n";
854 close(GITIGNORE)
855 or fatal("Failed to close `$ignore': $!");
856 command_noisy('add', '-f', $ignore);
860 sub cmd_mkdirs {
861 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
862 $gs ||= Git::SVN->new;
863 $gs->mkemptydirs($_revision);
866 sub canonicalize_path {
867 my ($path) = @_;
868 my $dot_slash_added = 0;
869 if (substr($path, 0, 1) ne "/") {
870 $path = "./" . $path;
871 $dot_slash_added = 1;
873 # File::Spec->canonpath doesn't collapse x/../y into y (for a
874 # good reason), so let's do this manually.
875 $path =~ s#/+#/#g;
876 $path =~ s#/\.(?:/|$)#/#g;
877 $path =~ s#/[^/]+/\.\.##g;
878 $path =~ s#/$##g;
879 $path =~ s#^\./## if $dot_slash_added;
880 $path =~ s#^/##;
881 $path =~ s#^\.$##;
882 return $path;
885 sub canonicalize_url {
886 my ($url) = @_;
887 $url =~ s#^([^:]+://[^/]*/)(.*)$#$1 . canonicalize_path($2)#e;
888 return $url;
891 # get_svnprops(PATH)
892 # ------------------
893 # Helper for cmd_propget and cmd_proplist below.
894 sub get_svnprops {
895 my $path = shift;
896 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
897 $gs ||= Git::SVN->new;
899 # prefix THE PATH by the sub-directory from which the user
900 # invoked us.
901 $path = $cmd_dir_prefix . $path;
902 fatal("No such file or directory: $path") unless -e $path;
903 my $is_dir = -d $path ? 1 : 0;
904 $path = $gs->{path} . '/' . $path;
906 # canonicalize the path (otherwise libsvn will abort or fail to
907 # find the file)
908 $path = canonicalize_path($path);
910 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
911 my $props;
912 if ($is_dir) {
913 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
915 else {
916 (undef, $props) = $gs->ra->get_file($path, $r, undef);
918 return $props;
921 # cmd_propget (PROP, PATH)
922 # ------------------------
923 # Print the SVN property PROP for PATH.
924 sub cmd_propget {
925 my ($prop, $path) = @_;
926 $path = '.' if not defined $path;
927 usage(1) if not defined $prop;
928 my $props = get_svnprops($path);
929 if (not defined $props->{$prop}) {
930 fatal("`$path' does not have a `$prop' SVN property.");
932 print $props->{$prop} . "\n";
935 # cmd_proplist (PATH)
936 # -------------------
937 # Print the list of SVN properties for PATH.
938 sub cmd_proplist {
939 my $path = shift;
940 $path = '.' if not defined $path;
941 my $props = get_svnprops($path);
942 print "Properties on '$path':\n";
943 foreach (sort keys %{$props}) {
944 print " $_\n";
948 sub cmd_multi_init {
949 my $url = shift;
950 unless (defined $_trunk || @_branches || @_tags) {
951 usage(1);
954 $_prefix = '' unless defined $_prefix;
955 if (defined $url) {
956 $url = canonicalize_url($url);
957 init_subdir(@_);
959 do_git_init_db();
960 if (defined $_trunk) {
961 my $trunk_ref = 'refs/remotes/' . $_prefix . 'trunk';
962 # try both old-style and new-style lookups:
963 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
964 unless ($gs_trunk) {
965 my ($trunk_url, $trunk_path) =
966 complete_svn_url($url, $_trunk);
967 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
968 undef, $trunk_ref);
971 return unless @_branches || @_tags;
972 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
973 foreach my $path (@_branches) {
974 complete_url_ls_init($ra, $path, '--branches/-b', $_prefix);
976 foreach my $path (@_tags) {
977 complete_url_ls_init($ra, $path, '--tags/-t', $_prefix.'tags/');
981 sub cmd_multi_fetch {
982 $Git::SVN::no_reuse_existing = undef;
983 my $remotes = Git::SVN::read_all_remotes();
984 foreach my $repo_id (sort keys %$remotes) {
985 if ($remotes->{$repo_id}->{url}) {
986 Git::SVN::fetch_all($repo_id, $remotes);
991 # this command is special because it requires no metadata
992 sub cmd_commit_diff {
993 my ($ta, $tb, $url) = @_;
994 my $usage = "Usage: $0 commit-diff -r<revision> ".
995 "<tree-ish> <tree-ish> [<URL>]";
996 fatal($usage) if (!defined $ta || !defined $tb);
997 my $svn_path = '';
998 if (!defined $url) {
999 my $gs = eval { Git::SVN->new };
1000 if (!$gs) {
1001 fatal("Needed URL or usable git-svn --id in ",
1002 "the command-line\n", $usage);
1004 $url = $gs->{url};
1005 $svn_path = $gs->{path};
1007 unless (defined $_revision) {
1008 fatal("-r|--revision is a required argument\n", $usage);
1010 if (defined $_message && defined $_file) {
1011 fatal("Both --message/-m and --file/-F specified ",
1012 "for the commit message.\n",
1013 "I have no idea what you mean");
1015 if (defined $_file) {
1016 $_message = file_to_s($_file);
1017 } else {
1018 $_message ||= get_commit_entry($tb)->{log};
1020 my $ra ||= Git::SVN::Ra->new($url);
1021 my $r = $_revision;
1022 if ($r eq 'HEAD') {
1023 $r = $ra->get_latest_revnum;
1024 } elsif ($r !~ /^\d+$/) {
1025 die "revision argument: $r not understood by git-svn\n";
1027 my %ed_opts = ( r => $r,
1028 log => $_message,
1029 ra => $ra,
1030 tree_a => $ta,
1031 tree_b => $tb,
1032 editor_cb => sub { print "Committed r$_[0]\n" },
1033 svn_path => $svn_path );
1034 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
1035 print "No changes\n$ta == $tb\n";
1039 sub escape_uri_only {
1040 my ($uri) = @_;
1041 my @tmp;
1042 foreach (split m{/}, $uri) {
1043 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
1044 push @tmp, $_;
1046 join('/', @tmp);
1049 sub escape_url {
1050 my ($url) = @_;
1051 if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
1052 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
1053 $url = "$scheme://$domain$uri";
1055 $url;
1058 sub cmd_info {
1059 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
1060 my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
1061 if (exists $_[1]) {
1062 die "Too many arguments specified\n";
1065 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
1067 if (!$file_type && !$diff_status) {
1068 print STDERR "svn: '$path' is not under version control\n";
1069 exit 1;
1072 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1073 unless ($gs) {
1074 die "Unable to determine upstream SVN information from ",
1075 "working tree history\n";
1078 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
1079 $path = "." if $path eq "";
1081 my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
1083 if ($_url) {
1084 print escape_url($full_url), "\n";
1085 return;
1088 my $result = "Path: $path\n";
1089 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
1090 $result .= "URL: " . escape_url($full_url) . "\n";
1092 eval {
1093 my $repos_root = $gs->repos_root;
1094 Git::SVN::remove_username($repos_root);
1095 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
1097 if ($@) {
1098 $result .= "Repository Root: (offline)\n";
1100 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
1101 ($SVN::Core::VERSION le '1.5.4' || $file_type ne "dir");
1102 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
1104 $result .= "Node Kind: " .
1105 ($file_type eq "dir" ? "directory" : "file") . "\n";
1107 my $schedule = $diff_status eq "A"
1108 ? "add"
1109 : ($diff_status eq "D" ? "delete" : "normal");
1110 $result .= "Schedule: $schedule\n";
1112 if ($diff_status eq "A") {
1113 print $result, "\n";
1114 return;
1117 my ($lc_author, $lc_rev, $lc_date_utc);
1118 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
1119 my $log = command_output_pipe(@args);
1120 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
1121 while (<$log>) {
1122 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
1123 $lc_author = $1;
1124 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
1125 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
1126 (undef, $lc_rev, undef) = ::extract_metadata($1);
1129 close $log;
1131 Git::SVN::Log::set_local_timezone();
1133 $result .= "Last Changed Author: $lc_author\n";
1134 $result .= "Last Changed Rev: $lc_rev\n";
1135 $result .= "Last Changed Date: " .
1136 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
1138 if ($file_type ne "dir") {
1139 my $text_last_updated_date =
1140 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
1141 $result .=
1142 "Text Last Updated: " .
1143 Git::SVN::Log::format_svn_date($text_last_updated_date) .
1144 "\n";
1145 my $checksum;
1146 if ($diff_status eq "D") {
1147 my ($fh, $ctx) =
1148 command_output_pipe(qw(cat-file blob), "HEAD:$path");
1149 if ($file_type eq "link") {
1150 my $file_name = <$fh>;
1151 $checksum = md5sum("link $file_name");
1152 } else {
1153 $checksum = md5sum($fh);
1155 command_close_pipe($fh, $ctx);
1156 } elsif ($file_type eq "link") {
1157 my $file_name =
1158 command(qw(cat-file blob), "HEAD:$path");
1159 $checksum =
1160 md5sum("link " . $file_name);
1161 } else {
1162 open FILE, "<", $path or die $!;
1163 $checksum = md5sum(\*FILE);
1164 close FILE or die $!;
1166 $result .= "Checksum: " . $checksum . "\n";
1169 print $result, "\n";
1172 sub cmd_reset {
1173 my $target = shift || $_revision or die "SVN revision required\n";
1174 $target = $1 if $target =~ /^r(\d+)$/;
1175 $target =~ /^\d+$/ or die "Numeric SVN revision expected\n";
1176 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1177 unless ($gs) {
1178 die "Unable to determine upstream SVN information from ".
1179 "history\n";
1181 my ($r, $c) = $gs->find_rev_before($target, not $_fetch_parent);
1182 $gs->rev_map_set($r, $c, 'reset', $uuid);
1183 print "r$r = $c ($gs->{ref_id})\n";
1186 sub cmd_gc {
1187 if (!$can_compress) {
1188 warn "Compress::Zlib could not be found; unhandled.log " .
1189 "files will not be compressed.\n";
1191 find({ wanted => \&gc_directory, no_chdir => 1}, "$ENV{GIT_DIR}/svn");
1194 ########################### utility functions #########################
1196 sub rebase_cmd {
1197 my @cmd = qw/rebase/;
1198 push @cmd, '-v' if $_verbose;
1199 push @cmd, qw/--merge/ if $_merge;
1200 push @cmd, "--strategy=$_strategy" if $_strategy;
1201 @cmd;
1204 sub post_fetch_checkout {
1205 return if $_no_checkout;
1206 my $gs = $Git::SVN::_head or return;
1207 return if verify_ref('refs/heads/master^0');
1209 # look for "trunk" ref if it exists
1210 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
1211 my $fetch = $remote->{fetch};
1212 if ($fetch) {
1213 foreach my $p (keys %$fetch) {
1214 basename($fetch->{$p}) eq 'trunk' or next;
1215 $gs = Git::SVN->new($fetch->{$p}, $gs->{repo_id}, $p);
1216 last;
1220 my $valid_head = verify_ref('HEAD^0');
1221 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1222 return if ($valid_head || !verify_ref('HEAD^0'));
1224 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1225 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1226 return if -f $index;
1228 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1229 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1230 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1231 print STDERR "Checked out HEAD:\n ",
1232 $gs->full_url, " r", $gs->last_rev, "\n";
1233 $gs->mkemptydirs($gs->last_rev);
1236 sub complete_svn_url {
1237 my ($url, $path) = @_;
1238 $path =~ s#/+$##;
1239 if ($path !~ m#^[a-z\+]+://#) {
1240 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1241 fatal("E: '$path' is not a complete URL ",
1242 "and a separate URL is not specified");
1244 return ($url, $path);
1246 return ($path, '');
1249 sub complete_url_ls_init {
1250 my ($ra, $repo_path, $switch, $pfx) = @_;
1251 unless ($repo_path) {
1252 print STDERR "W: $switch not specified\n";
1253 return;
1255 $repo_path =~ s#/+$##;
1256 if ($repo_path =~ m#^[a-z\+]+://#) {
1257 $ra = Git::SVN::Ra->new($repo_path);
1258 $repo_path = '';
1259 } else {
1260 $repo_path =~ s#^/+##;
1261 unless ($ra) {
1262 fatal("E: '$repo_path' is not a complete URL ",
1263 "and a separate URL is not specified");
1266 my $url = $ra->{url};
1267 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1268 my $k = "svn-remote.$gs->{repo_id}.url";
1269 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1270 if ($orig_url && ($orig_url ne $gs->{url})) {
1271 die "$k already set: $orig_url\n",
1272 "wanted to set to: $gs->{url}\n";
1274 command_oneline('config', $k, $gs->{url}) unless $orig_url;
1275 my $remote_path = "$gs->{path}/$repo_path";
1276 $remote_path =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
1277 $remote_path =~ s#/+#/#g;
1278 $remote_path =~ s#^/##g;
1279 $remote_path .= "/*" if $remote_path !~ /\*/;
1280 my ($n) = ($switch =~ /^--(\w+)/);
1281 if (length $pfx && $pfx !~ m#/$#) {
1282 die "--prefix='$pfx' must have a trailing slash '/'\n";
1284 command_noisy('config',
1285 '--add',
1286 "svn-remote.$gs->{repo_id}.$n",
1287 "$remote_path:refs/remotes/$pfx*" .
1288 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1291 sub verify_ref {
1292 my ($ref) = @_;
1293 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1294 { STDERR => 0 }); };
1297 sub get_tree_from_treeish {
1298 my ($treeish) = @_;
1299 # $treeish can be a symbolic ref, too:
1300 my $type = command_oneline(qw/cat-file -t/, $treeish);
1301 my $expected;
1302 while ($type eq 'tag') {
1303 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1305 if ($type eq 'commit') {
1306 $expected = (grep /^tree /, command(qw/cat-file commit/,
1307 $treeish))[0];
1308 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1309 die "Unable to get tree from $treeish\n" unless $expected;
1310 } elsif ($type eq 'tree') {
1311 $expected = $treeish;
1312 } else {
1313 die "$treeish is a $type, expected tree, tag or commit\n";
1315 return $expected;
1318 sub get_commit_entry {
1319 my ($treeish) = shift;
1320 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1321 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1322 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1323 open my $log_fh, '>', $commit_editmsg or croak $!;
1325 my $type = command_oneline(qw/cat-file -t/, $treeish);
1326 if ($type eq 'commit' || $type eq 'tag') {
1327 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1328 $type, $treeish);
1329 my $in_msg = 0;
1330 my $author;
1331 my $saw_from = 0;
1332 my $msgbuf = "";
1333 while (<$msg_fh>) {
1334 if (!$in_msg) {
1335 $in_msg = 1 if (/^\s*$/);
1336 $author = $1 if (/^author (.*>)/);
1337 } elsif (/^git-svn-id: /) {
1338 # skip this for now, we regenerate the
1339 # correct one on re-fetch anyways
1340 # TODO: set *:merge properties or like...
1341 } else {
1342 if (/^From:/ || /^Signed-off-by:/) {
1343 $saw_from = 1;
1345 $msgbuf .= $_;
1348 $msgbuf =~ s/\s+$//s;
1349 if ($Git::SVN::_add_author_from && defined($author)
1350 && !$saw_from) {
1351 $msgbuf .= "\n\nFrom: $author";
1353 print $log_fh $msgbuf or croak $!;
1354 command_close_pipe($msg_fh, $ctx);
1356 close $log_fh or croak $!;
1358 if ($_edit || ($type eq 'tree')) {
1359 chomp(my $editor = command_oneline(qw(var GIT_EDITOR)));
1360 system('sh', '-c', $editor.' "$@"', $editor, $commit_editmsg);
1362 rename $commit_editmsg, $commit_msg or croak $!;
1364 require Encode;
1365 # SVN requires messages to be UTF-8 when entering the repo
1366 local $/;
1367 open $log_fh, '<', $commit_msg or croak $!;
1368 binmode $log_fh;
1369 chomp($log_entry{log} = <$log_fh>);
1371 my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
1372 my $msg = $log_entry{log};
1374 eval { $msg = Encode::decode($enc, $msg, 1) };
1375 if ($@) {
1376 die "Could not decode as $enc:\n", $msg,
1377 "\nPerhaps you need to set i18n.commitencoding\n";
1380 eval { $msg = Encode::encode('UTF-8', $msg, 1) };
1381 die "Could not encode as UTF-8:\n$msg\n" if $@;
1383 $log_entry{log} = $msg;
1385 close $log_fh or croak $!;
1387 unlink $commit_msg;
1388 \%log_entry;
1391 sub s_to_file {
1392 my ($str, $file, $mode) = @_;
1393 open my $fd,'>',$file or croak $!;
1394 print $fd $str,"\n" or croak $!;
1395 close $fd or croak $!;
1396 chmod ($mode &~ umask, $file) if (defined $mode);
1399 sub file_to_s {
1400 my $file = shift;
1401 open my $fd,'<',$file or croak "$!: file: $file\n";
1402 local $/;
1403 my $ret = <$fd>;
1404 close $fd or croak $!;
1405 $ret =~ s/\s*$//s;
1406 return $ret;
1409 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1410 sub load_authors {
1411 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1412 my $log = $cmd eq 'log';
1413 while (<$authors>) {
1414 chomp;
1415 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1416 my ($user, $name, $email) = ($1, $2, $3);
1417 if ($log) {
1418 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1419 } else {
1420 $users{$user} = [$name, $email];
1423 close $authors or croak $!;
1426 # convert GetOpt::Long specs for use by git-config
1427 sub read_git_config {
1428 my $opts = shift;
1429 my @config_only;
1430 foreach my $o (keys %$opts) {
1431 # if we have mixedCase and a long option-only, then
1432 # it's a config-only variable that we don't need for
1433 # the command-line.
1434 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1435 my $v = $opts->{$o};
1436 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1437 $key =~ s/-//g;
1438 my $arg = 'git config';
1439 $arg .= ' --int' if ($o =~ /[:=]i$/);
1440 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1441 if (ref $v eq 'ARRAY') {
1442 chomp(my @tmp = `$arg --get-all svn.$key`);
1443 @$v = @tmp if @tmp;
1444 } else {
1445 chomp(my $tmp = `$arg --get svn.$key`);
1446 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1447 $$v = $tmp;
1451 delete @$opts{@config_only} if @config_only;
1454 sub extract_metadata {
1455 my $id = shift or return (undef, undef, undef);
1456 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1457 \s([a-f\d\-]+)$/ix);
1458 if (!defined $rev || !$uuid || !$url) {
1459 # some of the original repositories I made had
1460 # identifiers like this:
1461 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/i);
1463 return ($url, $rev, $uuid);
1466 sub cmt_metadata {
1467 return extract_metadata((grep(/^git-svn-id: /,
1468 command(qw/cat-file commit/, shift)))[-1]);
1471 sub cmt_sha2rev_batch {
1472 my %s2r;
1473 my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1474 my $list = shift;
1476 foreach my $sha (@{$list}) {
1477 my $first = 1;
1478 my $size = 0;
1479 print $out $sha, "\n";
1481 while (my $line = <$in>) {
1482 if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1483 last;
1484 } elsif ($first &&
1485 $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1486 $first = 0;
1487 $size = $1;
1488 next;
1489 } elsif ($line =~ /^(git-svn-id: )/) {
1490 my (undef, $rev, undef) =
1491 extract_metadata($line);
1492 $s2r{$sha} = $rev;
1495 $size -= length($line);
1496 last if ($size == 0);
1500 command_close_bidi_pipe($pid, $in, $out, $ctx);
1502 return \%s2r;
1505 sub working_head_info {
1506 my ($head, $refs) = @_;
1507 my @args = ('log', '--no-color', '--first-parent', '--pretty=medium');
1508 my ($fh, $ctx) = command_output_pipe(@args, $head);
1509 my $hash;
1510 my %max;
1511 while (<$fh>) {
1512 if ( m{^commit ($::sha1)$} ) {
1513 unshift @$refs, $hash if $hash and $refs;
1514 $hash = $1;
1515 next;
1517 next unless s{^\s*(git-svn-id:)}{$1};
1518 my ($url, $rev, $uuid) = extract_metadata($_);
1519 if (defined $url && defined $rev) {
1520 next if $max{$url} and $max{$url} < $rev;
1521 if (my $gs = Git::SVN->find_by_url($url)) {
1522 my $c = $gs->rev_map_get($rev, $uuid);
1523 if ($c && $c eq $hash) {
1524 close $fh; # break the pipe
1525 return ($url, $rev, $uuid, $gs);
1526 } else {
1527 $max{$url} ||= $gs->rev_map_max;
1532 command_close_pipe($fh, $ctx);
1533 (undef, undef, undef, undef);
1536 sub read_commit_parents {
1537 my ($parents, $c) = @_;
1538 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1539 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1540 @{$parents->{$c}} = split(/ /, $p);
1543 sub linearize_history {
1544 my ($gs, $refs) = @_;
1545 my %parents;
1546 foreach my $c (@$refs) {
1547 read_commit_parents(\%parents, $c);
1550 my @linear_refs;
1551 my %skip = ();
1552 my $last_svn_commit = $gs->last_commit;
1553 foreach my $c (reverse @$refs) {
1554 next if $c eq $last_svn_commit;
1555 last if $skip{$c};
1557 unshift @linear_refs, $c;
1558 $skip{$c} = 1;
1560 # we only want the first parent to diff against for linear
1561 # history, we save the rest to inject when we finalize the
1562 # svn commit
1563 my $fp_a = verify_ref("$c~1");
1564 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1565 if (!$fp_a || !$fp_b) {
1566 die "Commit $c\n",
1567 "has no parent commit, and therefore ",
1568 "nothing to diff against.\n",
1569 "You should be working from a repository ",
1570 "originally created by git-svn\n";
1572 if ($fp_a ne $fp_b) {
1573 die "$c~1 = $fp_a, however parsing commit $c ",
1574 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1577 foreach my $p (@{$parents{$c}}) {
1578 $skip{$p} = 1;
1581 (\@linear_refs, \%parents);
1584 sub find_file_type_and_diff_status {
1585 my ($path) = @_;
1586 return ('dir', '') if $path eq '';
1588 my $diff_output =
1589 command_oneline(qw(diff --cached --name-status --), $path) || "";
1590 my $diff_status = (split(' ', $diff_output))[0] || "";
1592 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1594 return (undef, undef) if !$diff_status && !$ls_tree;
1596 if ($diff_status eq "A") {
1597 return ("link", $diff_status) if -l $path;
1598 return ("dir", $diff_status) if -d $path;
1599 return ("file", $diff_status);
1602 my $mode = (split(' ', $ls_tree))[0] || "";
1604 return ("link", $diff_status) if $mode eq "120000";
1605 return ("dir", $diff_status) if $mode eq "040000";
1606 return ("file", $diff_status);
1609 sub md5sum {
1610 my $arg = shift;
1611 my $ref = ref $arg;
1612 my $md5 = Digest::MD5->new();
1613 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
1614 $md5->addfile($arg) or croak $!;
1615 } elsif ($ref eq 'SCALAR') {
1616 $md5->add($$arg) or croak $!;
1617 } elsif (!$ref) {
1618 $md5->add($arg) or croak $!;
1619 } else {
1620 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1622 return $md5->hexdigest();
1625 sub gc_directory {
1626 if ($can_compress && -f $_ && basename($_) eq "unhandled.log") {
1627 my $out_filename = $_ . ".gz";
1628 open my $in_fh, "<", $_ or die "Unable to open $_: $!\n";
1629 binmode $in_fh;
1630 my $gz = Compress::Zlib::gzopen($out_filename, "ab") or
1631 die "Unable to open $out_filename: $!\n";
1633 my $res;
1634 while ($res = sysread($in_fh, my $str, 1024)) {
1635 $gz->gzwrite($str) or
1636 die "Unable to write: ".$gz->gzerror()."!\n";
1638 unlink $_ or die "unlink $File::Find::name: $!\n";
1639 } elsif (-f $_ && basename($_) eq "index") {
1640 unlink $_ or die "unlink $_: $!\n";
1644 package Git::SVN;
1645 use strict;
1646 use warnings;
1647 use Fcntl qw/:DEFAULT :seek/;
1648 use constant rev_map_fmt => 'NH40';
1649 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1650 $_repack $_repack_flags $_use_svm_props $_head
1651 $_use_svnsync_props $no_reuse_existing $_minimize_url
1652 $_use_log_author $_add_author_from $_localtime/;
1653 use Carp qw/croak/;
1654 use File::Path qw/mkpath/;
1655 use File::Copy qw/copy/;
1656 use IPC::Open3;
1657 use Memoize; # core since 5.8.0, Jul 2002
1659 my ($_gc_nr, $_gc_period);
1661 # properties that we do not log:
1662 my %SKIP_PROP;
1663 BEGIN {
1664 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1665 svn:special svn:executable
1666 svn:entry:committed-rev
1667 svn:entry:last-author
1668 svn:entry:uuid
1669 svn:entry:committed-date/;
1671 # some options are read globally, but can be overridden locally
1672 # per [svn-remote "..."] section. Command-line options will *NOT*
1673 # override options set in an [svn-remote "..."] section
1674 no strict 'refs';
1675 for my $option (qw/follow_parent no_metadata use_svm_props
1676 use_svnsync_props/) {
1677 my $key = $option;
1678 $key =~ tr/_//d;
1679 my $prop = "-$option";
1680 *$option = sub {
1681 my ($self) = @_;
1682 return $self->{$prop} if exists $self->{$prop};
1683 my $k = "svn-remote.$self->{repo_id}.$key";
1684 eval { command_oneline(qw/config --get/, $k) };
1685 if ($@) {
1686 $self->{$prop} = ${"Git::SVN::_$option"};
1687 } else {
1688 my $v = command_oneline(qw/config --bool/,$k);
1689 $self->{$prop} = $v eq 'false' ? 0 : 1;
1691 return $self->{$prop};
1697 my (%LOCKFILES, %INDEX_FILES);
1698 END {
1699 unlink keys %LOCKFILES if %LOCKFILES;
1700 unlink keys %INDEX_FILES if %INDEX_FILES;
1703 sub resolve_local_globs {
1704 my ($url, $fetch, $glob_spec) = @_;
1705 return unless defined $glob_spec;
1706 my $ref = $glob_spec->{ref};
1707 my $path = $glob_spec->{path};
1708 foreach (command(qw#for-each-ref --format=%(refname) refs/#)) {
1709 next unless m#^$ref->{regex}$#;
1710 my $p = $1;
1711 my $pathname = desanitize_refname($path->full_path($p));
1712 my $refname = desanitize_refname($ref->full_path($p));
1713 if (my $existing = $fetch->{$pathname}) {
1714 if ($existing ne $refname) {
1715 die "Refspec conflict:\n",
1716 "existing: $existing\n",
1717 " globbed: $refname\n";
1719 my $u = (::cmt_metadata("$refname"))[0];
1720 $u =~ s!^\Q$url\E(/|$)!! or die
1721 "$refname: '$url' not found in '$u'\n";
1722 if ($pathname ne $u) {
1723 warn "W: Refspec glob conflict ",
1724 "(ref: $refname):\n",
1725 "expected path: $pathname\n",
1726 " real path: $u\n",
1727 "Continuing ahead with $u\n";
1728 next;
1730 } else {
1731 $fetch->{$pathname} = $refname;
1736 sub parse_revision_argument {
1737 my ($base, $head) = @_;
1738 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1739 return ($base, $head);
1741 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1742 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1743 return ($head, $head) if ($::_revision eq 'HEAD');
1744 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1745 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1746 die "revision argument: $::_revision not understood by git-svn\n";
1749 sub fetch_all {
1750 my ($repo_id, $remotes) = @_;
1751 if (ref $repo_id) {
1752 my $gs = $repo_id;
1753 $repo_id = undef;
1754 $repo_id = $gs->{repo_id};
1756 $remotes ||= read_all_remotes();
1757 my $remote = $remotes->{$repo_id} or
1758 die "[svn-remote \"$repo_id\"] unknown\n";
1759 my $fetch = $remote->{fetch};
1760 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1761 my (@gs, @globs);
1762 my $ra = Git::SVN::Ra->new($url);
1763 my $uuid = $ra->get_uuid;
1764 my $head = $ra->get_latest_revnum;
1766 # ignore errors, $head revision may not even exist anymore
1767 eval { $ra->get_log("", $head, 0, 1, 0, 1, sub { $head = $_[1] }) };
1768 warn "W: $@\n" if $@;
1770 my $base = defined $fetch ? $head : 0;
1772 # read the max revs for wildcard expansion (branches/*, tags/*)
1773 foreach my $t (qw/branches tags/) {
1774 defined $remote->{$t} or next;
1775 push @globs, @{$remote->{$t}};
1777 my $max_rev = eval { tmp_config(qw/--int --get/,
1778 "svn-remote.$repo_id.${t}-maxRev") };
1779 if (defined $max_rev && ($max_rev < $base)) {
1780 $base = $max_rev;
1781 } elsif (!defined $max_rev) {
1782 $base = 0;
1786 if ($fetch) {
1787 foreach my $p (sort keys %$fetch) {
1788 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1789 my $lr = $gs->rev_map_max;
1790 if (defined $lr) {
1791 $base = $lr if ($lr < $base);
1793 push @gs, $gs;
1797 ($base, $head) = parse_revision_argument($base, $head);
1798 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1801 sub read_all_remotes {
1802 my $r = {};
1803 my $use_svm_props = eval { command_oneline(qw/config --bool
1804 svn.useSvmProps/) };
1805 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
1806 my $svn_refspec = qr{\s*(.*?)\s*:\s*(.+?)\s*};
1807 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1808 if (m!^(.+)\.fetch=$svn_refspec$!) {
1809 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
1810 die("svn-remote.$remote: remote ref '$remote_ref' "
1811 . "must start with 'refs/'\n")
1812 unless $remote_ref =~ m{^refs/};
1813 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1814 $r->{$remote}->{svm} = {} if $use_svm_props;
1815 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
1816 $r->{$1}->{svm} = {};
1817 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1818 $r->{$1}->{url} = $2;
1819 } elsif (m!^(.+)\.(branches|tags)=$svn_refspec$!) {
1820 my ($remote, $t, $local_ref, $remote_ref) =
1821 ($1, $2, $3, $4);
1822 die("svn-remote.$remote: remote ref '$remote_ref' ($t) "
1823 . "must start with 'refs/'\n")
1824 unless $remote_ref =~ m{^refs/};
1825 my $rs = {
1826 t => $t,
1827 remote => $remote,
1828 path => Git::SVN::GlobSpec->new($local_ref, 1),
1829 ref => Git::SVN::GlobSpec->new($remote_ref, 0) };
1830 if (length($rs->{ref}->{right}) != 0) {
1831 die "The '*' glob character must be the last ",
1832 "character of '$remote_ref'\n";
1834 push @{ $r->{$remote}->{$t} }, $rs;
1838 map {
1839 if (defined $r->{$_}->{svm}) {
1840 my $svm;
1841 eval {
1842 my $section = "svn-remote.$_";
1843 $svm = {
1844 source => tmp_config('--get',
1845 "$section.svm-source"),
1846 replace => tmp_config('--get',
1847 "$section.svm-replace"),
1850 $r->{$_}->{svm} = $svm;
1852 } keys %$r;
1857 sub init_vars {
1858 $_gc_nr = $_gc_period = 1000;
1859 if (defined $_repack || defined $_repack_flags) {
1860 warn "Repack options are obsolete; they have no effect.\n";
1864 sub verify_remotes_sanity {
1865 return unless -d $ENV{GIT_DIR};
1866 my %seen;
1867 foreach (command(qw/config -l/)) {
1868 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1869 if ($seen{$1}) {
1870 die "Remote ref refs/remote/$1 is tracked by",
1871 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1872 "Please resolve this ambiguity in ",
1873 "your git configuration file before ",
1874 "continuing\n";
1876 $seen{$1} = $_;
1881 sub find_existing_remote {
1882 my ($url, $remotes) = @_;
1883 return undef if $no_reuse_existing;
1884 my $existing;
1885 foreach my $repo_id (keys %$remotes) {
1886 my $u = $remotes->{$repo_id}->{url} or next;
1887 next if $u ne $url;
1888 $existing = $repo_id;
1889 last;
1891 $existing;
1894 sub init_remote_config {
1895 my ($self, $url, $no_write) = @_;
1896 $url =~ s!/+$!!; # strip trailing slash
1897 my $r = read_all_remotes();
1898 my $existing = find_existing_remote($url, $r);
1899 if ($existing) {
1900 unless ($no_write) {
1901 print STDERR "Using existing ",
1902 "[svn-remote \"$existing\"]\n";
1904 $self->{repo_id} = $existing;
1905 } elsif ($_minimize_url) {
1906 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1907 $existing = find_existing_remote($min_url, $r);
1908 if ($existing) {
1909 unless ($no_write) {
1910 print STDERR "Using existing ",
1911 "[svn-remote \"$existing\"]\n";
1913 $self->{repo_id} = $existing;
1915 if ($min_url ne $url) {
1916 unless ($no_write) {
1917 print STDERR "Using higher level of URL: ",
1918 "$url => $min_url\n";
1920 my $old_path = $self->{path};
1921 $self->{path} = $url;
1922 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1923 if (length $old_path) {
1924 $self->{path} .= "/$old_path";
1926 $url = $min_url;
1929 my $orig_url;
1930 if (!$existing) {
1931 # verify that we aren't overwriting anything:
1932 $orig_url = eval {
1933 command_oneline('config', '--get',
1934 "svn-remote.$self->{repo_id}.url")
1936 if ($orig_url && ($orig_url ne $url)) {
1937 die "svn-remote.$self->{repo_id}.url already set: ",
1938 "$orig_url\nwanted to set to: $url\n";
1941 my ($xrepo_id, $xpath) = find_ref($self->refname);
1942 if (!$no_write && defined $xpath) {
1943 die "svn-remote.$xrepo_id.fetch already set to track ",
1944 "$xpath:", $self->refname, "\n";
1946 unless ($no_write) {
1947 command_noisy('config',
1948 "svn-remote.$self->{repo_id}.url", $url);
1949 $self->{path} =~ s{^/}{};
1950 $self->{path} =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
1951 command_noisy('config', '--add',
1952 "svn-remote.$self->{repo_id}.fetch",
1953 "$self->{path}:".$self->refname);
1955 $self->{url} = $url;
1958 sub find_by_url { # repos_root and, path are optional
1959 my ($class, $full_url, $repos_root, $path) = @_;
1961 return undef unless defined $full_url;
1962 remove_username($full_url);
1963 remove_username($repos_root) if defined $repos_root;
1964 my $remotes = read_all_remotes();
1965 if (defined $full_url && defined $repos_root && !defined $path) {
1966 $path = $full_url;
1967 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1969 foreach my $repo_id (keys %$remotes) {
1970 my $u = $remotes->{$repo_id}->{url} or next;
1971 remove_username($u);
1972 next if defined $repos_root && $repos_root ne $u;
1974 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1975 foreach my $t (qw/branches tags/) {
1976 foreach my $globspec (@{$remotes->{$repo_id}->{$t}}) {
1977 resolve_local_globs($u, $fetch, $globspec);
1980 my $p = $path;
1981 my $rwr = rewrite_root({repo_id => $repo_id});
1982 my $svm = $remotes->{$repo_id}->{svm}
1983 if defined $remotes->{$repo_id}->{svm};
1984 unless (defined $p) {
1985 $p = $full_url;
1986 my $z = $u;
1987 my $prefix = '';
1988 if ($rwr) {
1989 $z = $rwr;
1990 remove_username($z);
1991 } elsif (defined $svm) {
1992 $z = $svm->{source};
1993 $prefix = $svm->{replace};
1994 $prefix =~ s#^\Q$u\E(?:/|$)##;
1995 $prefix =~ s#/$##;
1997 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
1999 foreach my $f (keys %$fetch) {
2000 next if $f ne $p;
2001 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
2004 undef;
2007 sub init {
2008 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
2009 my $self = _new($class, $repo_id, $ref_id, $path);
2010 if (defined $url) {
2011 $self->init_remote_config($url, $no_write);
2013 $self;
2016 sub find_ref {
2017 my ($ref_id) = @_;
2018 foreach (command(qw/config -l/)) {
2019 next unless m!^svn-remote\.(.+)\.fetch=
2020 \s*(.*?)\s*:\s*(.+?)\s*$!x;
2021 my ($repo_id, $path, $ref) = ($1, $2, $3);
2022 if ($ref eq $ref_id) {
2023 $path = '' if ($path =~ m#^\./?#);
2024 return ($repo_id, $path);
2027 (undef, undef, undef);
2030 sub new {
2031 my ($class, $ref_id, $repo_id, $path) = @_;
2032 if (defined $ref_id && !defined $repo_id && !defined $path) {
2033 ($repo_id, $path) = find_ref($ref_id);
2034 if (!defined $repo_id) {
2035 die "Could not find a \"svn-remote.*.fetch\" key ",
2036 "in the repository configuration matching: ",
2037 "$ref_id\n";
2040 my $self = _new($class, $repo_id, $ref_id, $path);
2041 if (!defined $self->{path} || !length $self->{path}) {
2042 my $fetch = command_oneline('config', '--get',
2043 "svn-remote.$repo_id.fetch",
2044 ":$ref_id\$") or
2045 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
2046 "\":$ref_id\$\" in config\n";
2047 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
2049 $self->{url} = command_oneline('config', '--get',
2050 "svn-remote.$repo_id.url") or
2051 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
2052 $self->rebuild;
2053 $self;
2056 sub refname {
2057 my ($refname) = $_[0]->{ref_id} ;
2059 # It cannot end with a slash /, we'll throw up on this because
2060 # SVN can't have directories with a slash in their name, either:
2061 if ($refname =~ m{/$}) {
2062 die "ref: '$refname' ends with a trailing slash, this is ",
2063 "not permitted by git nor Subversion\n";
2066 # It cannot have ASCII control character space, tilde ~, caret ^,
2067 # colon :, question-mark ?, asterisk *, space, or open bracket [
2068 # anywhere.
2070 # Additionally, % must be escaped because it is used for escaping
2071 # and we want our escaped refname to be reversible
2072 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
2074 # no slash-separated component can begin with a dot .
2075 # /.* becomes /%2E*
2076 $refname =~ s{/\.}{/%2E}g;
2078 # It cannot have two consecutive dots .. anywhere
2079 # .. becomes %2E%2E
2080 $refname =~ s{\.\.}{%2E%2E}g;
2082 return $refname;
2085 sub desanitize_refname {
2086 my ($refname) = @_;
2087 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
2088 return $refname;
2091 sub svm_uuid {
2092 my ($self) = @_;
2093 return $self->{svm}->{uuid} if $self->svm;
2094 $self->ra;
2095 unless ($self->{svm}) {
2096 die "SVM UUID not cached, and reading remotely failed\n";
2098 $self->{svm}->{uuid};
2101 sub svm {
2102 my ($self) = @_;
2103 return $self->{svm} if $self->{svm};
2104 my $svm;
2105 # see if we have it in our config, first:
2106 eval {
2107 my $section = "svn-remote.$self->{repo_id}";
2108 $svm = {
2109 source => tmp_config('--get', "$section.svm-source"),
2110 uuid => tmp_config('--get', "$section.svm-uuid"),
2111 replace => tmp_config('--get', "$section.svm-replace"),
2114 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
2115 $self->{svm} = $svm;
2117 $self->{svm};
2120 sub _set_svm_vars {
2121 my ($self, $ra) = @_;
2122 return $ra if $self->svm;
2124 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
2125 "(svm:source, svm:uuid) ",
2126 "from the following URLs:\n" );
2127 sub read_svm_props {
2128 my ($self, $ra, $path, $r) = @_;
2129 my $props = ($ra->get_dir($path, $r))[2];
2130 my $src = $props->{'svm:source'};
2131 my $uuid = $props->{'svm:uuid'};
2132 return undef if (!$src || !$uuid);
2134 chomp($src, $uuid);
2136 $uuid =~ m{^[0-9a-f\-]{30,}$}i
2137 or die "doesn't look right - svm:uuid is '$uuid'\n";
2139 # the '!' is used to mark the repos_root!/relative/path
2140 $src =~ s{/?!/?}{/};
2141 $src =~ s{/+$}{}; # no trailing slashes please
2142 # username is of no interest
2143 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
2145 my $replace = $ra->{url};
2146 $replace .= "/$path" if length $path;
2148 my $section = "svn-remote.$self->{repo_id}";
2149 tmp_config("$section.svm-source", $src);
2150 tmp_config("$section.svm-replace", $replace);
2151 tmp_config("$section.svm-uuid", $uuid);
2152 $self->{svm} = {
2153 source => $src,
2154 uuid => $uuid,
2155 replace => $replace
2159 my $r = $ra->get_latest_revnum;
2160 my $path = $self->{path};
2161 my %tried;
2162 while (length $path) {
2163 unless ($tried{"$self->{url}/$path"}) {
2164 return $ra if $self->read_svm_props($ra, $path, $r);
2165 $tried{"$self->{url}/$path"} = 1;
2167 $path =~ s#/?[^/]+$##;
2169 die "Path: '$path' should be ''\n" if $path ne '';
2170 return $ra if $self->read_svm_props($ra, $path, $r);
2171 $tried{"$self->{url}/$path"} = 1;
2173 if ($ra->{repos_root} eq $self->{url}) {
2174 die @err, (map { " $_\n" } keys %tried), "\n";
2177 # nope, make sure we're connected to the repository root:
2178 my $ok;
2179 my @tried_b;
2180 $path = $ra->{svn_path};
2181 $ra = Git::SVN::Ra->new($ra->{repos_root});
2182 while (length $path) {
2183 unless ($tried{"$ra->{url}/$path"}) {
2184 $ok = $self->read_svm_props($ra, $path, $r);
2185 last if $ok;
2186 $tried{"$ra->{url}/$path"} = 1;
2188 $path =~ s#/?[^/]+$##;
2190 die "Path: '$path' should be ''\n" if $path ne '';
2191 $ok ||= $self->read_svm_props($ra, $path, $r);
2192 $tried{"$ra->{url}/$path"} = 1;
2193 if (!$ok) {
2194 die @err, (map { " $_\n" } keys %tried), "\n";
2196 Git::SVN::Ra->new($self->{url});
2199 sub svnsync {
2200 my ($self) = @_;
2201 return $self->{svnsync} if $self->{svnsync};
2203 if ($self->no_metadata) {
2204 die "Can't have both 'noMetadata' and ",
2205 "'useSvnsyncProps' options set!\n";
2207 if ($self->rewrite_root) {
2208 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
2209 "options set!\n";
2211 if ($self->rewrite_uuid) {
2212 die "Can't have both 'useSvnsyncProps' and 'rewriteUUID' ",
2213 "options set!\n";
2216 my $svnsync;
2217 # see if we have it in our config, first:
2218 eval {
2219 my $section = "svn-remote.$self->{repo_id}";
2221 my $url = tmp_config('--get', "$section.svnsync-url");
2222 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2223 die "doesn't look right - svn:sync-from-url is '$url'\n";
2225 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
2226 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2227 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2229 $svnsync = { url => $url, uuid => $uuid }
2231 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
2232 return $self->{svnsync} = $svnsync;
2235 my $err = "useSvnsyncProps set, but failed to read " .
2236 "svnsync property: svn:sync-from-";
2237 my $rp = $self->ra->rev_proplist(0);
2239 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
2240 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2241 die "doesn't look right - svn:sync-from-url is '$url'\n";
2243 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
2244 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2245 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2247 my $section = "svn-remote.$self->{repo_id}";
2248 tmp_config('--add', "$section.svnsync-uuid", $uuid);
2249 tmp_config('--add', "$section.svnsync-url", $url);
2250 return $self->{svnsync} = { url => $url, uuid => $uuid };
2253 # this allows us to memoize our SVN::Ra UUID locally and avoid a
2254 # remote lookup (useful for 'git svn log').
2255 sub ra_uuid {
2256 my ($self) = @_;
2257 unless ($self->{ra_uuid}) {
2258 my $key = "svn-remote.$self->{repo_id}.uuid";
2259 my $uuid = eval { tmp_config('--get', $key) };
2260 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/i) {
2261 $self->{ra_uuid} = $uuid;
2262 } else {
2263 die "ra_uuid called without URL\n" unless $self->{url};
2264 $self->{ra_uuid} = $self->ra->get_uuid;
2265 tmp_config('--add', $key, $self->{ra_uuid});
2268 $self->{ra_uuid};
2271 sub _set_repos_root {
2272 my ($self, $repos_root) = @_;
2273 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2274 $repos_root ||= $self->ra->{repos_root};
2275 tmp_config($k, $repos_root);
2276 $repos_root;
2279 sub repos_root {
2280 my ($self) = @_;
2281 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2282 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
2285 sub ra {
2286 my ($self) = shift;
2287 my $ra = Git::SVN::Ra->new($self->{url});
2288 $self->_set_repos_root($ra->{repos_root});
2289 if ($self->use_svm_props && !$self->{svm}) {
2290 if ($self->no_metadata) {
2291 die "Can't have both 'noMetadata' and ",
2292 "'useSvmProps' options set!\n";
2293 } elsif ($self->use_svnsync_props) {
2294 die "Can't have both 'useSvnsyncProps' and ",
2295 "'useSvmProps' options set!\n";
2297 $ra = $self->_set_svm_vars($ra);
2298 $self->{-want_revprops} = 1;
2300 $ra;
2303 # prop_walk(PATH, REV, SUB)
2304 # -------------------------
2305 # Recursively traverse PATH at revision REV and invoke SUB for each
2306 # directory that contains a SVN property. SUB will be invoked as
2307 # follows: &SUB(gs, path, props); where `gs' is this instance of
2308 # Git::SVN, `path' the path to the directory where the properties
2309 # `props' were found. The `path' will be relative to point of checkout,
2310 # that is, if url://repo/trunk is the current Git branch, and that
2311 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
2312 # as `path' (note the trailing `/').
2313 sub prop_walk {
2314 my ($self, $path, $rev, $sub) = @_;
2316 $path =~ s#^/##;
2317 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2318 $path =~ s#^/*#/#g;
2319 my $p = $path;
2320 # Strip the irrelevant part of the path.
2321 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2322 # Ensure the path is terminated by a `/'.
2323 $p =~ s#/*$#/#;
2325 # The properties contain all the internal SVN stuff nobody
2326 # (usually) cares about.
2327 my $interesting_props = 0;
2328 foreach (keys %{$props}) {
2329 # If it doesn't start with `svn:', it must be a
2330 # user-defined property.
2331 ++$interesting_props and next if $_ !~ /^svn:/;
2332 # FIXME: Fragile, if SVN adds new public properties,
2333 # this needs to be updated.
2334 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2335 |eol-style|mime-type
2336 |externals|needs-lock)$/x;
2338 &$sub($self, $p, $props) if $interesting_props;
2340 foreach (sort keys %$dirent) {
2341 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
2342 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
2346 sub last_rev { ($_[0]->last_rev_commit)[0] }
2347 sub last_commit { ($_[0]->last_rev_commit)[1] }
2349 # returns the newest SVN revision number and newest commit SHA1
2350 sub last_rev_commit {
2351 my ($self) = @_;
2352 if (defined $self->{last_rev} && defined $self->{last_commit}) {
2353 return ($self->{last_rev}, $self->{last_commit});
2355 my $c = ::verify_ref($self->refname.'^0');
2356 if ($c && !$self->use_svm_props && !$self->no_metadata) {
2357 my $rev = (::cmt_metadata($c))[1];
2358 if (defined $rev) {
2359 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2360 return ($rev, $c);
2363 my $map_path = $self->map_path;
2364 unless (-e $map_path) {
2365 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2366 return (undef, undef);
2368 my ($rev, $commit) = $self->rev_map_max(1);
2369 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2370 return ($rev, $commit);
2373 sub get_fetch_range {
2374 my ($self, $min, $max) = @_;
2375 $max ||= $self->ra->get_latest_revnum;
2376 $min ||= $self->rev_map_max;
2377 (++$min, $max);
2380 sub tmp_config {
2381 my (@args) = @_;
2382 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2383 my $config = "$ENV{GIT_DIR}/svn/.metadata";
2384 if (! -f $config && -f $old_def_config) {
2385 rename $old_def_config, $config or
2386 die "Failed rename $old_def_config => $config: $!\n";
2388 my $old_config = $ENV{GIT_CONFIG};
2389 $ENV{GIT_CONFIG} = $config;
2390 $@ = undef;
2391 my @ret = eval {
2392 unless (-f $config) {
2393 mkfile($config);
2394 open my $fh, '>', $config or
2395 die "Can't open $config: $!\n";
2396 print $fh "; This file is used internally by ",
2397 "git-svn\n" or die
2398 "Couldn't write to $config: $!\n";
2399 print $fh "; You should not have to edit it\n" or
2400 die "Couldn't write to $config: $!\n";
2401 close $fh or die "Couldn't close $config: $!\n";
2403 command('config', @args);
2405 my $err = $@;
2406 if (defined $old_config) {
2407 $ENV{GIT_CONFIG} = $old_config;
2408 } else {
2409 delete $ENV{GIT_CONFIG};
2411 die $err if $err;
2412 wantarray ? @ret : $ret[0];
2415 sub tmp_index_do {
2416 my ($self, $sub) = @_;
2417 my $old_index = $ENV{GIT_INDEX_FILE};
2418 $ENV{GIT_INDEX_FILE} = $self->{index};
2419 $@ = undef;
2420 my @ret = eval {
2421 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2422 mkpath([$dir]) unless -d $dir;
2423 &$sub;
2425 my $err = $@;
2426 if (defined $old_index) {
2427 $ENV{GIT_INDEX_FILE} = $old_index;
2428 } else {
2429 delete $ENV{GIT_INDEX_FILE};
2431 die $err if $err;
2432 wantarray ? @ret : $ret[0];
2435 sub assert_index_clean {
2436 my ($self, $treeish) = @_;
2438 $self->tmp_index_do(sub {
2439 command_noisy('read-tree', $treeish) unless -e $self->{index};
2440 my $x = command_oneline('write-tree');
2441 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2442 /^tree ($::sha1)/mo);
2443 return if $y eq $x;
2445 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2446 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2447 command_noisy('read-tree', $treeish);
2448 $x = command_oneline('write-tree');
2449 if ($y ne $x) {
2450 ::fatal "trees ($treeish) $y != $x\n",
2451 "Something is seriously wrong...";
2456 sub get_commit_parents {
2457 my ($self, $log_entry) = @_;
2458 my (%seen, @ret, @tmp);
2459 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2460 if (my $ip = $self->{inject_parents}) {
2461 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2462 push @tmp, $commit;
2465 if (my $cur = ::verify_ref($self->refname.'^0')) {
2466 push @tmp, $cur;
2468 if (my $ipd = $self->{inject_parents_dcommit}) {
2469 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2470 push @tmp, @$commit;
2473 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2474 while (my $p = shift @tmp) {
2475 next if $seen{$p};
2476 $seen{$p} = 1;
2477 push @ret, $p;
2479 @ret;
2482 sub rewrite_root {
2483 my ($self) = @_;
2484 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2485 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2486 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2487 if ($rwr) {
2488 $rwr =~ s#/+$##;
2489 if ($rwr !~ m#^[a-z\+]+://#) {
2490 die "$rwr is not a valid URL (key: $k)\n";
2493 $self->{-rewrite_root} = $rwr;
2496 sub rewrite_uuid {
2497 my ($self) = @_;
2498 return $self->{-rewrite_uuid} if exists $self->{-rewrite_uuid};
2499 my $k = "svn-remote.$self->{repo_id}.rewriteUUID";
2500 my $rwid = eval { command_oneline(qw/config --get/, $k) };
2501 if ($rwid) {
2502 $rwid =~ s#/+$##;
2503 if ($rwid !~ m#^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$#) {
2504 die "$rwid is not a valid UUID (key: $k)\n";
2507 $self->{-rewrite_uuid} = $rwid;
2510 sub metadata_url {
2511 my ($self) = @_;
2512 ($self->rewrite_root || $self->{url}) .
2513 (length $self->{path} ? '/' . $self->{path} : '');
2516 sub full_url {
2517 my ($self) = @_;
2518 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2522 sub set_commit_header_env {
2523 my ($log_entry) = @_;
2524 my %env;
2525 foreach my $ned (qw/NAME EMAIL DATE/) {
2526 foreach my $ac (qw/AUTHOR COMMITTER/) {
2527 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2531 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2532 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2533 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2535 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2536 ? $log_entry->{commit_name}
2537 : $log_entry->{name};
2538 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2539 ? $log_entry->{commit_email}
2540 : $log_entry->{email};
2541 \%env;
2544 sub restore_commit_header_env {
2545 my ($env) = @_;
2546 foreach my $ned (qw/NAME EMAIL DATE/) {
2547 foreach my $ac (qw/AUTHOR COMMITTER/) {
2548 my $k = "GIT_${ac}_${ned}";
2549 if (defined $env->{$k}) {
2550 $ENV{$k} = $env->{$k};
2551 } else {
2552 delete $ENV{$k};
2558 sub gc {
2559 command_noisy('gc', '--auto');
2562 sub do_git_commit {
2563 my ($self, $log_entry) = @_;
2564 my $lr = $self->last_rev;
2565 if (defined $lr && $lr >= $log_entry->{revision}) {
2566 die "Last fetched revision of ", $self->refname,
2567 " was r$lr, but we are about to fetch: ",
2568 "r$log_entry->{revision}!\n";
2570 if (my $c = $self->rev_map_get($log_entry->{revision})) {
2571 croak "$log_entry->{revision} = $c already exists! ",
2572 "Why are we refetching it?\n";
2574 my $old_env = set_commit_header_env($log_entry);
2575 my $tree = $log_entry->{tree};
2576 if (!defined $tree) {
2577 $tree = $self->tmp_index_do(sub {
2578 command_oneline('write-tree') });
2580 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2582 my @exec = ('git', 'commit-tree', $tree);
2583 foreach ($self->get_commit_parents($log_entry)) {
2584 push @exec, '-p', $_;
2586 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2587 or croak $!;
2588 binmode $msg_fh;
2590 # we always get UTF-8 from SVN, but we may want our commits in
2591 # a different encoding.
2592 if (my $enc = Git::config('i18n.commitencoding')) {
2593 require Encode;
2594 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
2596 print $msg_fh $log_entry->{log} or croak $!;
2597 restore_commit_header_env($old_env);
2598 unless ($self->no_metadata) {
2599 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2600 or croak $!;
2602 $msg_fh->flush == 0 or croak $!;
2603 close $msg_fh or croak $!;
2604 chomp(my $commit = do { local $/; <$out_fh> });
2605 close $out_fh or croak $!;
2606 waitpid $pid, 0;
2607 croak $? if $?;
2608 if ($commit !~ /^$::sha1$/o) {
2609 die "Failed to commit, invalid sha1: $commit\n";
2612 $self->rev_map_set($log_entry->{revision}, $commit, 1);
2614 $self->{last_rev} = $log_entry->{revision};
2615 $self->{last_commit} = $commit;
2616 print "r$log_entry->{revision}" unless $::_q > 1;
2617 if (defined $log_entry->{svm_revision}) {
2618 print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
2619 $self->rev_map_set($log_entry->{svm_revision}, $commit,
2620 0, $self->svm_uuid);
2622 print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
2623 if (--$_gc_nr == 0) {
2624 $_gc_nr = $_gc_period;
2625 gc();
2627 return $commit;
2630 sub match_paths {
2631 my ($self, $paths, $r) = @_;
2632 return 1 if $self->{path} eq '';
2633 if (my $path = $paths->{"/$self->{path}"}) {
2634 return ($path->{action} eq 'D') ? 0 : 1;
2636 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
2637 if (grep /$self->{path_regex}/, keys %$paths) {
2638 return 1;
2640 my $c = '';
2641 foreach (split m#/#, $self->{path}) {
2642 $c .= "/$_";
2643 next unless ($paths->{$c} &&
2644 ($paths->{$c}->{action} =~ /^[AR]$/));
2645 if ($self->ra->check_path($self->{path}, $r) ==
2646 $SVN::Node::dir) {
2647 return 1;
2650 return 0;
2653 sub find_parent_branch {
2654 my ($self, $paths, $rev) = @_;
2655 return undef unless $self->follow_parent;
2656 unless (defined $paths) {
2657 my $err_handler = $SVN::Error::handler;
2658 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2659 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1,
2660 sub { $paths = $_[0] });
2661 $SVN::Error::handler = $err_handler;
2663 return undef unless defined $paths;
2665 # look for a parent from another branch:
2666 my @b_path_components = split m#/#, $self->{path};
2667 my @a_path_components;
2668 my $i;
2669 while (@b_path_components) {
2670 $i = $paths->{'/'.join('/', @b_path_components)};
2671 last if $i && defined $i->{copyfrom_path};
2672 unshift(@a_path_components, pop(@b_path_components));
2674 return undef unless defined $i && defined $i->{copyfrom_path};
2675 my $branch_from = $i->{copyfrom_path};
2676 if (@a_path_components) {
2677 print STDERR "branch_from: $branch_from => ";
2678 $branch_from .= '/'.join('/', @a_path_components);
2679 print STDERR $branch_from, "\n";
2681 my $r = $i->{copyfrom_rev};
2682 my $repos_root = $self->ra->{repos_root};
2683 my $url = $self->ra->{url};
2684 my $new_url = $url . $branch_from;
2685 print STDERR "Found possible branch point: ",
2686 "$new_url => ", $self->full_url, ", $r\n"
2687 unless $::_q > 1;
2688 $branch_from =~ s#^/##;
2689 my $gs = $self->other_gs($new_url, $url,
2690 $branch_from, $r, $self->{ref_id});
2691 my ($r0, $parent) = $gs->find_rev_before($r, 1);
2693 my ($base, $head);
2694 if (!defined $r0 || !defined $parent) {
2695 ($base, $head) = parse_revision_argument(0, $r);
2696 } else {
2697 if ($r0 < $r) {
2698 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
2699 0, 1, sub { $base = $_[1] - 1 });
2702 if (defined $base && $base <= $r) {
2703 $gs->fetch($base, $r);
2705 ($r0, $parent) = $gs->find_rev_before($r, 1);
2707 if (defined $r0 && defined $parent) {
2708 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n"
2709 unless $::_q > 1;
2710 my $ed;
2711 if ($self->ra->can_do_switch) {
2712 $self->assert_index_clean($parent);
2713 print STDERR "Following parent with do_switch\n"
2714 unless $::_q > 1;
2715 # do_switch works with svn/trunk >= r22312, but that
2716 # is not included with SVN 1.4.3 (the latest version
2717 # at the moment), so we can't rely on it
2718 $self->{last_rev} = $r0;
2719 $self->{last_commit} = $parent;
2720 $ed = SVN::Git::Fetcher->new($self, $gs->{path});
2721 $gs->ra->gs_do_switch($r0, $rev, $gs,
2722 $self->full_url, $ed)
2723 or die "SVN connection failed somewhere...\n";
2724 } elsif ($self->ra->trees_match($new_url, $r0,
2725 $self->full_url, $rev)) {
2726 print STDERR "Trees match:\n",
2727 " $new_url\@$r0\n",
2728 " ${\$self->full_url}\@$rev\n",
2729 "Following parent with no changes\n"
2730 unless $::_q > 1;
2731 $self->tmp_index_do(sub {
2732 command_noisy('read-tree', $parent);
2734 $self->{last_commit} = $parent;
2735 } else {
2736 print STDERR "Following parent with do_update\n"
2737 unless $::_q > 1;
2738 $ed = SVN::Git::Fetcher->new($self);
2739 $self->ra->gs_do_update($rev, $rev, $self, $ed)
2740 or die "SVN connection failed somewhere...\n";
2742 print STDERR "Successfully followed parent\n" unless $::_q > 1;
2743 return $self->make_log_entry($rev, [$parent], $ed);
2745 return undef;
2748 sub do_fetch {
2749 my ($self, $paths, $rev) = @_;
2750 my $ed;
2751 my ($last_rev, @parents);
2752 if (my $lc = $self->last_commit) {
2753 # we can have a branch that was deleted, then re-added
2754 # under the same name but copied from another path, in
2755 # which case we'll have multiple parents (we don't
2756 # want to break the original ref, nor lose copypath info):
2757 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2758 push @{$log_entry->{parents}}, $lc;
2759 return $log_entry;
2761 $ed = SVN::Git::Fetcher->new($self);
2762 $last_rev = $self->{last_rev};
2763 $ed->{c} = $lc;
2764 @parents = ($lc);
2765 } else {
2766 $last_rev = $rev;
2767 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2768 return $log_entry;
2770 $ed = SVN::Git::Fetcher->new($self);
2772 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2773 die "SVN connection failed somewhere...\n";
2775 $self->make_log_entry($rev, \@parents, $ed);
2778 sub mkemptydirs {
2779 my ($self, $r) = @_;
2781 sub scan {
2782 my ($r, $empty_dirs, $line) = @_;
2783 if (defined $r && $line =~ /^r(\d+)$/) {
2784 return 0 if $1 > $r;
2785 } elsif ($line =~ /^ \+empty_dir: (.+)$/) {
2786 $empty_dirs->{$1} = 1;
2787 } elsif ($line =~ /^ \-empty_dir: (.+)$/) {
2788 my @d = grep {m[^\Q$1\E(/|$)]} (keys %$empty_dirs);
2789 delete @$empty_dirs{@d};
2791 1; # continue
2794 my %empty_dirs = ();
2795 my $gz_file = "$self->{dir}/unhandled.log.gz";
2796 if (-f $gz_file) {
2797 if (!$can_compress) {
2798 warn "Compress::Zlib could not be found; ",
2799 "empty directories in $gz_file will not be read\n";
2800 } else {
2801 my $gz = Compress::Zlib::gzopen($gz_file, "rb") or
2802 die "Unable to open $gz_file: $!\n";
2803 my $line;
2804 while ($gz->gzreadline($line) > 0) {
2805 scan($r, \%empty_dirs, $line) or last;
2807 $gz->gzclose;
2811 if (open my $fh, '<', "$self->{dir}/unhandled.log") {
2812 binmode $fh or croak "binmode: $!";
2813 while (<$fh>) {
2814 scan($r, \%empty_dirs, $_) or last;
2816 close $fh;
2819 my $strip = qr/\A\Q$self->{path}\E(?:\/|$)/;
2820 foreach my $d (sort keys %empty_dirs) {
2821 $d = uri_decode($d);
2822 $d =~ s/$strip//;
2823 next if -d $d;
2824 if (-e _) {
2825 warn "$d exists but is not a directory\n";
2826 } else {
2827 print "creating empty directory: $d\n";
2828 mkpath([$d]);
2833 sub get_untracked {
2834 my ($self, $ed) = @_;
2835 my @out;
2836 my $h = $ed->{empty};
2837 foreach (sort keys %$h) {
2838 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2839 push @out, " $act: " . uri_encode($_);
2840 warn "W: $act: $_\n";
2842 foreach my $t (qw/dir_prop file_prop/) {
2843 $h = $ed->{$t} or next;
2844 foreach my $path (sort keys %$h) {
2845 my $ppath = $path eq '' ? '.' : $path;
2846 foreach my $prop (sort keys %{$h->{$path}}) {
2847 next if $SKIP_PROP{$prop};
2848 my $v = $h->{$path}->{$prop};
2849 my $t_ppath_prop = "$t: " .
2850 uri_encode($ppath) . ' ' .
2851 uri_encode($prop);
2852 if (defined $v) {
2853 push @out, " +$t_ppath_prop " .
2854 uri_encode($v);
2855 } else {
2856 push @out, " -$t_ppath_prop";
2861 foreach my $t (qw/absent_file absent_directory/) {
2862 $h = $ed->{$t} or next;
2863 foreach my $parent (sort keys %$h) {
2864 foreach my $path (sort @{$h->{$parent}}) {
2865 push @out, " $t: " .
2866 uri_encode("$parent/$path");
2867 warn "W: $t: $parent/$path ",
2868 "Insufficient permissions?\n";
2872 \@out;
2875 # parse_svn_date(DATE)
2876 # --------------------
2877 # Given a date (in UTC) from Subversion, return a string in the format
2878 # "<TZ Offset> <local date/time>" that Git will use.
2880 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
2881 # is true we'll convert it to the local timezone instead.
2882 sub parse_svn_date {
2883 my $date = shift || return '+0000 1970-01-01 00:00:00';
2884 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2885 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
2886 croak "Unable to parse date: $date\n";
2887 my $parsed_date; # Set next.
2889 if ($Git::SVN::_localtime) {
2890 # Translate the Subversion datetime to an epoch time.
2891 # Begin by switching ourselves to $date's timezone, UTC.
2892 my $old_env_TZ = $ENV{TZ};
2893 $ENV{TZ} = 'UTC';
2895 my $epoch_in_UTC =
2896 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
2898 # Determine our local timezone (including DST) at the
2899 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
2900 # value of TZ, if any, at the time we were run.
2901 if (defined $Git::SVN::Log::TZ) {
2902 $ENV{TZ} = $Git::SVN::Log::TZ;
2903 } else {
2904 delete $ENV{TZ};
2907 my $our_TZ =
2908 POSIX::strftime('%Z', $S, $M, $H, $d, $m - 1, $Y - 1900);
2910 # This converts $epoch_in_UTC into our local timezone.
2911 my ($sec, $min, $hour, $mday, $mon, $year,
2912 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
2914 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
2915 $our_TZ, $year + 1900, $mon + 1,
2916 $mday, $hour, $min, $sec);
2918 # Reset us to the timezone in effect when we entered
2919 # this routine.
2920 if (defined $old_env_TZ) {
2921 $ENV{TZ} = $old_env_TZ;
2922 } else {
2923 delete $ENV{TZ};
2925 } else {
2926 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
2929 return $parsed_date;
2932 sub other_gs {
2933 my ($self, $new_url, $url,
2934 $branch_from, $r, $old_ref_id) = @_;
2935 my $gs = Git::SVN->find_by_url($new_url, $url, $branch_from);
2936 unless ($gs) {
2937 my $ref_id = $old_ref_id;
2938 $ref_id =~ s/\@\d+$//;
2939 $ref_id .= "\@$r";
2940 # just grow a tail if we're not unique enough :x
2941 $ref_id .= '-' while find_ref($ref_id);
2942 print STDERR "Initializing parent: $ref_id\n" unless $::_q > 1;
2943 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
2944 if ($u =~ s#^\Q$url\E(/|$)##) {
2945 $p = $u;
2946 $u = $url;
2947 $repo_id = $self->{repo_id};
2949 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
2954 sub call_authors_prog {
2955 my ($orig_author) = @_;
2956 $orig_author = command_oneline('rev-parse', '--sq-quote', $orig_author);
2957 my $author = `$::_authors_prog $orig_author`;
2958 if ($? != 0) {
2959 die "$::_authors_prog failed with exit code $?\n"
2961 if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
2962 my ($name, $email) = ($1, $2);
2963 $email = undef if length $2 == 0;
2964 return [$name, $email];
2965 } else {
2966 die "Author: $orig_author: $::_authors_prog returned "
2967 . "invalid author format: $author\n";
2971 sub check_author {
2972 my ($author) = @_;
2973 if (!defined $author || length $author == 0) {
2974 $author = '(no author)';
2976 if (!defined $::users{$author}) {
2977 if (defined $::_authors_prog) {
2978 $::users{$author} = call_authors_prog($author);
2979 } elsif (defined $::_authors) {
2980 die "Author: $author not defined in $::_authors file\n";
2983 $author;
2986 sub find_extra_svk_parents {
2987 my ($self, $ed, $tickets, $parents) = @_;
2988 # aha! svk:merge property changed...
2989 my @tickets = split "\n", $tickets;
2990 my @known_parents;
2991 for my $ticket ( @tickets ) {
2992 my ($uuid, $path, $rev) = split /:/, $ticket;
2993 if ( $uuid eq $self->ra_uuid ) {
2994 my $url = $self->rewrite_root || $self->{url};
2995 my $repos_root = $url;
2996 my $branch_from = $path;
2997 $branch_from =~ s{^/}{};
2998 my $gs = $self->other_gs($repos_root."/".$branch_from,
2999 $url,
3000 $branch_from,
3001 $rev,
3002 $self->{ref_id});
3003 if ( my $commit = $gs->rev_map_get($rev, $uuid) ) {
3004 # wahey! we found it, but it might be
3005 # an old one (!)
3006 push @known_parents, [ $rev, $commit ];
3010 # Ordering matters; highest-numbered commit merge tickets
3011 # first, as they may account for later merge ticket additions
3012 # or changes.
3013 @known_parents = map {$_->[1]} sort {$b->[0] <=> $a->[0]} @known_parents;
3014 for my $parent ( @known_parents ) {
3015 my @cmd = ('rev-list', $parent, map { "^$_" } @$parents );
3016 my ($msg_fh, $ctx) = command_output_pipe(@cmd);
3017 my $new;
3018 while ( <$msg_fh> ) {
3019 $new=1;last;
3021 command_close_pipe($msg_fh, $ctx);
3022 if ( $new ) {
3023 print STDERR
3024 "Found merge parent (svk:merge ticket): $parent\n";
3025 push @$parents, $parent;
3030 sub lookup_svn_merge {
3031 my $uuid = shift;
3032 my $url = shift;
3033 my $merge = shift;
3035 my ($source, $revs) = split ":", $merge;
3036 my $path = $source;
3037 $path =~ s{^/}{};
3038 my $gs = Git::SVN->find_by_url($url.$source, $url, $path);
3039 if ( !$gs ) {
3040 warn "Couldn't find revmap for $url$source\n";
3041 return;
3043 my @ranges = split ",", $revs;
3044 my ($tip, $tip_commit);
3045 my @merged_commit_ranges;
3046 # find the tip
3047 for my $range ( @ranges ) {
3048 my ($bottom, $top) = split "-", $range;
3049 $top ||= $bottom;
3050 my $bottom_commit = $gs->find_rev_after( $bottom, 1, $top );
3051 my $top_commit = $gs->find_rev_before( $top, 1, $bottom );
3053 unless ($top_commit and $bottom_commit) {
3054 warn "W:unknown path/rev in svn:mergeinfo "
3055 ."dirprop: $source:$range\n";
3056 next;
3059 push @merged_commit_ranges,
3060 "$bottom_commit^..$top_commit";
3062 if ( !defined $tip or $top > $tip ) {
3063 $tip = $top;
3064 $tip_commit = $top_commit;
3067 return ($tip_commit, @merged_commit_ranges);
3070 sub _rev_list {
3071 my ($msg_fh, $ctx) = command_output_pipe(
3072 "rev-list", @_,
3074 my @rv;
3075 while ( <$msg_fh> ) {
3076 chomp;
3077 push @rv, $_;
3079 command_close_pipe($msg_fh, $ctx);
3080 @rv;
3083 sub check_cherry_pick {
3084 my $base = shift;
3085 my $tip = shift;
3086 my @ranges = @_;
3087 my %commits = map { $_ => 1 }
3088 _rev_list("--no-merges", $tip, "--not", $base);
3089 for my $range ( @ranges ) {
3090 delete @commits{_rev_list($range)};
3092 for my $commit (keys %commits) {
3093 if (has_no_changes($commit)) {
3094 delete $commits{$commit};
3097 return (keys %commits);
3100 sub has_no_changes {
3101 my $commit = shift;
3103 my @revs = split / /, command_oneline(
3104 qw(rev-list --parents -1 -m), $commit);
3106 # Commits with no parents, e.g. the start of a partial branch,
3107 # have changes by definition.
3108 return 1 if (@revs < 2);
3110 # Commits with multiple parents, e.g a merge, have no changes
3111 # by definition.
3112 return 0 if (@revs > 2);
3114 return (command_oneline("rev-parse", "$commit^{tree}") eq
3115 command_oneline("rev-parse", "$commit~1^{tree}"));
3118 BEGIN {
3119 memoize 'lookup_svn_merge';
3120 memoize 'check_cherry_pick';
3121 memoize 'has_no_changes';
3124 sub parents_exclude {
3125 my $parents = shift;
3126 my @commits = @_;
3127 return unless @commits;
3129 my @excluded;
3130 my $excluded;
3131 do {
3132 my @cmd = ('rev-list', "-1", @commits, "--not", @$parents );
3133 $excluded = command_oneline(@cmd);
3134 if ( $excluded ) {
3135 my @new;
3136 my $found;
3137 for my $commit ( @commits ) {
3138 if ( $commit eq $excluded ) {
3139 push @excluded, $commit;
3140 $found++;
3141 last;
3143 else {
3144 push @new, $commit;
3147 die "saw commit '$excluded' in rev-list output, "
3148 ."but we didn't ask for that commit (wanted: @commits --not @$parents)"
3149 unless $found;
3150 @commits = @new;
3153 while ($excluded and @commits);
3155 return @excluded;
3159 # note: this function should only be called if the various dirprops
3160 # have actually changed
3161 sub find_extra_svn_parents {
3162 my ($self, $ed, $mergeinfo, $parents) = @_;
3163 # aha! svk:merge property changed...
3165 # We first search for merged tips which are not in our
3166 # history. Then, we figure out which git revisions are in
3167 # that tip, but not this revision. If all of those revisions
3168 # are now marked as merge, we can add the tip as a parent.
3169 my @merges = split "\n", $mergeinfo;
3170 my @merge_tips;
3171 my $url = $self->rewrite_root || $self->{url};
3172 my $uuid = $self->ra_uuid;
3173 my %ranges;
3174 for my $merge ( @merges ) {
3175 my ($tip_commit, @ranges) =
3176 lookup_svn_merge( $uuid, $url, $merge );
3177 unless (!$tip_commit or
3178 grep { $_ eq $tip_commit } @$parents ) {
3179 push @merge_tips, $tip_commit;
3180 $ranges{$tip_commit} = \@ranges;
3181 } else {
3182 push @merge_tips, undef;
3186 my %excluded = map { $_ => 1 }
3187 parents_exclude($parents, grep { defined } @merge_tips);
3189 # check merge tips for new parents
3190 my @new_parents;
3191 for my $merge_tip ( @merge_tips ) {
3192 my $spec = shift @merges;
3193 next unless $merge_tip and $excluded{$merge_tip};
3195 my $ranges = $ranges{$merge_tip};
3197 # check out 'new' tips
3198 my $merge_base;
3199 eval {
3200 $merge_base = command_oneline(
3201 "merge-base",
3202 @$parents, $merge_tip,
3205 if ($@) {
3206 die "An error occurred during merge-base"
3207 unless $@->isa("Git::Error::Command");
3209 warn "W: Cannot find common ancestor between ".
3210 "@$parents and $merge_tip. Ignoring merge info.\n";
3211 next;
3214 # double check that there are no missing non-merge commits
3215 my (@incomplete) = check_cherry_pick(
3216 $merge_base, $merge_tip,
3217 @$ranges,
3220 if ( @incomplete ) {
3221 warn "W:svn cherry-pick ignored ($spec) - missing "
3222 .@incomplete." commit(s) (eg $incomplete[0])\n";
3223 } else {
3224 warn
3225 "Found merge parent (svn:mergeinfo prop): ",
3226 $merge_tip, "\n";
3227 push @new_parents, $merge_tip;
3231 # cater for merges which merge commits from multiple branches
3232 if ( @new_parents > 1 ) {
3233 for ( my $i = 0; $i <= $#new_parents; $i++ ) {
3234 for ( my $j = 0; $j <= $#new_parents; $j++ ) {
3235 next if $i == $j;
3236 next unless $new_parents[$i];
3237 next unless $new_parents[$j];
3238 my $revs = command_oneline(
3239 "rev-list", "-1",
3240 "$new_parents[$i]..$new_parents[$j]",
3242 if ( !$revs ) {
3243 undef($new_parents[$i]);
3248 push @$parents, grep { defined } @new_parents;
3251 sub make_log_entry {
3252 my ($self, $rev, $parents, $ed) = @_;
3253 my $untracked = $self->get_untracked($ed);
3255 my @parents = @$parents;
3256 my $ps = $ed->{path_strip} || "";
3257 for my $path ( grep { m/$ps/ } %{$ed->{dir_prop}} ) {
3258 my $props = $ed->{dir_prop}{$path};
3259 if ( $props->{"svk:merge"} ) {
3260 $self->find_extra_svk_parents
3261 ($ed, $props->{"svk:merge"}, \@parents);
3263 if ( $props->{"svn:mergeinfo"} ) {
3264 $self->find_extra_svn_parents
3265 ($ed,
3266 $props->{"svn:mergeinfo"},
3267 \@parents);
3271 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
3272 print $un "r$rev\n" or croak $!;
3273 print $un $_, "\n" foreach @$untracked;
3274 my %log_entry = ( parents => \@parents, revision => $rev,
3275 log => '');
3277 my $headrev;
3278 my $logged = delete $self->{logged_rev_props};
3279 if (!$logged || $self->{-want_revprops}) {
3280 my $rp = $self->ra->rev_proplist($rev);
3281 foreach (sort keys %$rp) {
3282 my $v = $rp->{$_};
3283 if (/^svn:(author|date|log)$/) {
3284 $log_entry{$1} = $v;
3285 } elsif ($_ eq 'svm:headrev') {
3286 $headrev = $v;
3287 } else {
3288 print $un " rev_prop: ", uri_encode($_), ' ',
3289 uri_encode($v), "\n";
3292 } else {
3293 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
3295 close $un or croak $!;
3297 $log_entry{date} = parse_svn_date($log_entry{date});
3298 $log_entry{log} .= "\n";
3299 my $author = $log_entry{author} = check_author($log_entry{author});
3300 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
3301 : ($author, undef);
3303 my ($commit_name, $commit_email) = ($name, $email);
3304 if ($_use_log_author) {
3305 my $name_field;
3306 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
3307 $name_field = $1;
3308 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
3309 $name_field = $1;
3311 if (!defined $name_field) {
3312 if (!defined $email) {
3313 $email = $name;
3315 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
3316 ($name, $email) = ($1, $2);
3317 } elsif ($name_field =~ /(.*)@/) {
3318 ($name, $email) = ($1, $name_field);
3319 } else {
3320 ($name, $email) = ($name_field, $name_field);
3323 if (defined $headrev && $self->use_svm_props) {
3324 if ($self->rewrite_root) {
3325 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
3326 "options set!\n";
3328 if ($self->rewrite_uuid) {
3329 die "Can't have both 'useSvmProps' and 'rewriteUUID' ",
3330 "options set!\n";
3332 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$}i;
3333 # we don't want "SVM: initializing mirror for junk" ...
3334 return undef if $r == 0;
3335 my $svm = $self->svm;
3336 if ($uuid ne $svm->{uuid}) {
3337 die "UUID mismatch on SVM path:\n",
3338 "expected: $svm->{uuid}\n",
3339 " got: $uuid\n";
3341 my $full_url = $self->full_url;
3342 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
3343 die "Failed to replace '$svm->{replace}' with ",
3344 "'$svm->{source}' in $full_url\n";
3345 # throw away username for storing in records
3346 remove_username($full_url);
3347 $log_entry{metadata} = "$full_url\@$r $uuid";
3348 $log_entry{svm_revision} = $r;
3349 $email ||= "$author\@$uuid";
3350 $commit_email ||= "$author\@$uuid";
3351 } elsif ($self->use_svnsync_props) {
3352 my $full_url = $self->svnsync->{url};
3353 $full_url .= "/$self->{path}" if length $self->{path};
3354 remove_username($full_url);
3355 my $uuid = $self->svnsync->{uuid};
3356 $log_entry{metadata} = "$full_url\@$rev $uuid";
3357 $email ||= "$author\@$uuid";
3358 $commit_email ||= "$author\@$uuid";
3359 } else {
3360 my $url = $self->metadata_url;
3361 remove_username($url);
3362 my $uuid = $self->rewrite_uuid || $self->ra->get_uuid;
3363 $log_entry{metadata} = "$url\@$rev " . $uuid;
3364 $email ||= "$author\@" . $uuid;
3365 $commit_email ||= "$author\@" . $uuid;
3367 $log_entry{name} = $name;
3368 $log_entry{email} = $email;
3369 $log_entry{commit_name} = $commit_name;
3370 $log_entry{commit_email} = $commit_email;
3371 \%log_entry;
3374 sub fetch {
3375 my ($self, $min_rev, $max_rev, @parents) = @_;
3376 my ($last_rev, $last_commit) = $self->last_rev_commit;
3377 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
3378 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
3381 sub set_tree_cb {
3382 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
3383 $self->{inject_parents} = { $rev => $tree };
3384 $self->fetch(undef, undef);
3387 sub set_tree {
3388 my ($self, $tree) = (shift, shift);
3389 my $log_entry = ::get_commit_entry($tree);
3390 unless ($self->{last_rev}) {
3391 ::fatal("Must have an existing revision to commit");
3393 my %ed_opts = ( r => $self->{last_rev},
3394 log => $log_entry->{log},
3395 ra => $self->ra,
3396 tree_a => $self->{last_commit},
3397 tree_b => $tree,
3398 editor_cb => sub {
3399 $self->set_tree_cb($log_entry, $tree, @_) },
3400 svn_path => $self->{path} );
3401 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
3402 print "No changes\nr$self->{last_rev} = $tree\n";
3406 sub rebuild_from_rev_db {
3407 my ($self, $path) = @_;
3408 my $r = -1;
3409 open my $fh, '<', $path or croak "open: $!";
3410 binmode $fh or croak "binmode: $!";
3411 while (<$fh>) {
3412 length($_) == 41 or croak "inconsistent size in ($_) != 41";
3413 chomp($_);
3414 ++$r;
3415 next if $_ eq ('0' x 40);
3416 $self->rev_map_set($r, $_);
3417 print "r$r = $_\n";
3419 close $fh or croak "close: $!";
3420 unlink $path or croak "unlink: $!";
3423 sub rebuild {
3424 my ($self) = @_;
3425 my $map_path = $self->map_path;
3426 my $partial = (-e $map_path && ! -z $map_path);
3427 return unless ::verify_ref($self->refname.'^0');
3428 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
3429 my $rev_db = $self->rev_db_path;
3430 $self->rebuild_from_rev_db($rev_db);
3431 if ($self->use_svm_props) {
3432 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
3433 $self->rebuild_from_rev_db($svm_rev_db);
3435 $self->unlink_rev_db_symlink;
3436 return;
3438 print "Rebuilding $map_path ...\n" if (!$partial);
3439 my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
3440 (undef, undef));
3441 my ($log, $ctx) =
3442 command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
3443 ($head ? "$head.." : "") . $self->refname,
3444 '--');
3445 my $metadata_url = $self->metadata_url;
3446 remove_username($metadata_url);
3447 my $svn_uuid = $self->rewrite_uuid || $self->ra_uuid;
3448 my $c;
3449 while (<$log>) {
3450 if ( m{^commit ($::sha1)$} ) {
3451 $c = $1;
3452 next;
3454 next unless s{^\s*(git-svn-id:)}{$1};
3455 my ($url, $rev, $uuid) = ::extract_metadata($_);
3456 remove_username($url);
3458 # ignore merges (from set-tree)
3459 next if (!defined $rev || !$uuid);
3461 # if we merged or otherwise started elsewhere, this is
3462 # how we break out of it
3463 if (($uuid ne $svn_uuid) ||
3464 ($metadata_url && $url && ($url ne $metadata_url))) {
3465 next;
3467 if ($partial && $head) {
3468 print "Partial-rebuilding $map_path ...\n";
3469 print "Currently at $base_rev = $head\n";
3470 $head = undef;
3473 $self->rev_map_set($rev, $c);
3474 print "r$rev = $c\n";
3476 command_close_pipe($log, $ctx);
3477 print "Done rebuilding $map_path\n" if (!$partial || !$head);
3478 my $rev_db_path = $self->rev_db_path;
3479 if (-f $self->rev_db_path) {
3480 unlink $self->rev_db_path or croak "unlink: $!";
3482 $self->unlink_rev_db_symlink;
3485 # rev_map:
3486 # Tie::File seems to be prone to offset errors if revisions get sparse,
3487 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
3488 # one of my favorite modules is out :< Next up would be one of the DBM
3489 # modules, but I'm not sure which is most portable...
3491 # This is the replacement for the rev_db format, which was too big
3492 # and inefficient for large repositories with a lot of sparse history
3493 # (mainly tags)
3495 # The format is this:
3496 # - 24 bytes for every record,
3497 # * 4 bytes for the integer representing an SVN revision number
3498 # * 20 bytes representing the sha1 of a git commit
3499 # - No empty padding records like the old format
3500 # (except the last record, which can be overwritten)
3501 # - new records are written append-only since SVN revision numbers
3502 # increase monotonically
3503 # - lookups on SVN revision number are done via a binary search
3504 # - Piping the file to xxd -c24 is a good way of dumping it for
3505 # viewing or editing (piped back through xxd -r), should the need
3506 # ever arise.
3507 # - The last record can be padding revision with an all-zero sha1
3508 # This is used to optimize fetch performance when using multiple
3509 # "fetch" directives in .git/config
3511 # These files are disposable unless noMetadata or useSvmProps is set
3513 sub _rev_map_set {
3514 my ($fh, $rev, $commit) = @_;
3516 binmode $fh or croak "binmode: $!";
3517 my $size = (stat($fh))[7];
3518 ($size % 24) == 0 or croak "inconsistent size: $size";
3520 my $wr_offset = 0;
3521 if ($size > 0) {
3522 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3523 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
3524 $read == 24 or croak "read only $read bytes (!= 24)";
3525 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
3526 if ($last_commit eq ('0' x40)) {
3527 if ($size >= 48) {
3528 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3529 $read = sysread($fh, $buf, 24) or
3530 croak "read: $!";
3531 $read == 24 or
3532 croak "read only $read bytes (!= 24)";
3533 ($last_rev, $last_commit) =
3534 unpack(rev_map_fmt, $buf);
3535 if ($last_commit eq ('0' x40)) {
3536 croak "inconsistent .rev_map\n";
3539 if ($last_rev >= $rev) {
3540 croak "last_rev is higher!: $last_rev >= $rev";
3542 $wr_offset = -24;
3545 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
3546 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
3547 croak "write: $!";
3550 sub _rev_map_reset {
3551 my ($fh, $rev, $commit) = @_;
3552 my $c = _rev_map_get($fh, $rev);
3553 $c eq $commit or die "_rev_map_reset(@_) commit $c does not match!\n";
3554 my $offset = sysseek($fh, 0, SEEK_CUR) or croak "seek: $!";
3555 truncate $fh, $offset or croak "truncate: $!";
3558 sub mkfile {
3559 my ($path) = @_;
3560 unless (-e $path) {
3561 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
3562 mkpath([$dir]) unless -d $dir;
3563 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
3564 close $fh or die "Couldn't close (create) $path: $!\n";
3568 sub rev_map_set {
3569 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
3570 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
3571 my $db = $self->map_path($uuid);
3572 my $db_lock = "$db.lock";
3573 my $sig;
3574 $update_ref ||= 0;
3575 if ($update_ref) {
3576 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3577 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
3579 mkfile($db);
3581 $LOCKFILES{$db_lock} = 1;
3582 my $sync;
3583 # both of these options make our .rev_db file very, very important
3584 # and we can't afford to lose it because rebuild() won't work
3585 if ($self->use_svm_props || $self->no_metadata) {
3586 $sync = 1;
3587 copy($db, $db_lock) or die "rev_map_set(@_): ",
3588 "Failed to copy: ",
3589 "$db => $db_lock ($!)\n";
3590 } else {
3591 rename $db, $db_lock or die "rev_map_set(@_): ",
3592 "Failed to rename: ",
3593 "$db => $db_lock ($!)\n";
3596 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
3597 or croak "Couldn't open $db_lock: $!\n";
3598 $update_ref eq 'reset' ? _rev_map_reset($fh, $rev, $commit) :
3599 _rev_map_set($fh, $rev, $commit);
3600 if ($sync) {
3601 $fh->flush or die "Couldn't flush $db_lock: $!\n";
3602 $fh->sync or die "Couldn't sync $db_lock: $!\n";
3604 close $fh or croak $!;
3605 if ($update_ref) {
3606 $_head = $self;
3607 my $note = "";
3608 $note = " ($update_ref)" if ($update_ref !~ /^\d*$/);
3609 command_noisy('update-ref', '-m', "r$rev$note",
3610 $self->refname, $commit);
3612 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
3613 "$db_lock => $db ($!)\n";
3614 delete $LOCKFILES{$db_lock};
3615 if ($update_ref) {
3616 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3617 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
3618 kill $sig, $$ if defined $sig;
3622 # If want_commit, this will return an array of (rev, commit) where
3623 # commit _must_ be a valid commit in the archive.
3624 # Otherwise, it'll return the max revision (whether or not the
3625 # commit is valid or just a 0x40 placeholder).
3626 sub rev_map_max {
3627 my ($self, $want_commit) = @_;
3628 $self->rebuild;
3629 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
3630 $want_commit ? ($r, $c) : $r;
3633 sub rev_map_max_norebuild {
3634 my ($self, $want_commit) = @_;
3635 my $map_path = $self->map_path;
3636 stat $map_path or return $want_commit ? (0, undef) : 0;
3637 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3638 binmode $fh or croak "binmode: $!";
3639 my $size = (stat($fh))[7];
3640 ($size % 24) == 0 or croak "inconsistent size: $size";
3642 if ($size == 0) {
3643 close $fh or croak "close: $!";
3644 return $want_commit ? (0, undef) : 0;
3647 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3648 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3649 my ($r, $c) = unpack(rev_map_fmt, $buf);
3650 if ($want_commit && $c eq ('0' x40)) {
3651 if ($size < 48) {
3652 return $want_commit ? (0, undef) : 0;
3654 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3655 sysread($fh, $buf, 24) == 24 or croak "read: $!";
3656 ($r, $c) = unpack(rev_map_fmt, $buf);
3657 if ($c eq ('0'x40)) {
3658 croak "Penultimate record is all-zeroes in $map_path";
3661 close $fh or croak "close: $!";
3662 $want_commit ? ($r, $c) : $r;
3665 sub rev_map_get {
3666 my ($self, $rev, $uuid) = @_;
3667 my $map_path = $self->map_path($uuid);
3668 return undef unless -e $map_path;
3670 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3671 my $c = _rev_map_get($fh, $rev);
3672 close($fh) or croak "close: $!";
3676 sub _rev_map_get {
3677 my ($fh, $rev) = @_;
3679 binmode $fh or croak "binmode: $!";
3680 my $size = (stat($fh))[7];
3681 ($size % 24) == 0 or croak "inconsistent size: $size";
3683 if ($size == 0) {
3684 return undef;
3687 my ($l, $u) = (0, $size - 24);
3688 my ($r, $c, $buf);
3690 while ($l <= $u) {
3691 my $i = int(($l/24 + $u/24) / 2) * 24;
3692 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
3693 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3694 my ($r, $c) = unpack(rev_map_fmt, $buf);
3696 if ($r < $rev) {
3697 $l = $i + 24;
3698 } elsif ($r > $rev) {
3699 $u = $i - 24;
3700 } else { # $r == $rev
3701 return $c eq ('0' x 40) ? undef : $c;
3704 undef;
3707 # Finds the first svn revision that exists on (if $eq_ok is true) or
3708 # before $rev for the current branch. It will not search any lower
3709 # than $min_rev. Returns the git commit hash and svn revision number
3710 # if found, else (undef, undef).
3711 sub find_rev_before {
3712 my ($self, $rev, $eq_ok, $min_rev) = @_;
3713 --$rev unless $eq_ok;
3714 $min_rev ||= 1;
3715 my $max_rev = $self->rev_map_max;
3716 $rev = $max_rev if ($rev > $max_rev);
3717 while ($rev >= $min_rev) {
3718 if (my $c = $self->rev_map_get($rev)) {
3719 return ($rev, $c);
3721 --$rev;
3723 return (undef, undef);
3726 # Finds the first svn revision that exists on (if $eq_ok is true) or
3727 # after $rev for the current branch. It will not search any higher
3728 # than $max_rev. Returns the git commit hash and svn revision number
3729 # if found, else (undef, undef).
3730 sub find_rev_after {
3731 my ($self, $rev, $eq_ok, $max_rev) = @_;
3732 ++$rev unless $eq_ok;
3733 $max_rev ||= $self->rev_map_max;
3734 while ($rev <= $max_rev) {
3735 if (my $c = $self->rev_map_get($rev)) {
3736 return ($rev, $c);
3738 ++$rev;
3740 return (undef, undef);
3743 sub _new {
3744 my ($class, $repo_id, $ref_id, $path) = @_;
3745 unless (defined $repo_id && length $repo_id) {
3746 $repo_id = $Git::SVN::default_repo_id;
3748 unless (defined $ref_id && length $ref_id) {
3749 $_prefix = '' unless defined($_prefix);
3750 $_[2] = $ref_id =
3751 "refs/remotes/$_prefix$Git::SVN::default_ref_id";
3753 $_[1] = $repo_id;
3754 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
3756 # Older repos imported by us used $GIT_DIR/svn/foo instead of
3757 # $GIT_DIR/svn/refs/remotes/foo when tracking refs/remotes/foo
3758 if ($ref_id =~ m{^refs/remotes/(.*)}) {
3759 my $old_dir = "$ENV{GIT_DIR}/svn/$1";
3760 if (-d $old_dir && ! -d $dir) {
3761 $dir = $old_dir;
3765 $_[3] = $path = '' unless (defined $path);
3766 mkpath([$dir]);
3767 bless {
3768 ref_id => $ref_id, dir => $dir, index => "$dir/index",
3769 path => $path, config => "$ENV{GIT_DIR}/svn/config",
3770 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
3773 # for read-only access of old .rev_db formats
3774 sub unlink_rev_db_symlink {
3775 my ($self) = @_;
3776 my $link = $self->rev_db_path;
3777 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
3778 if (-l $link) {
3779 unlink $link or croak "unlink: $link failed!";
3783 sub rev_db_path {
3784 my ($self, $uuid) = @_;
3785 my $db_path = $self->map_path($uuid);
3786 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
3787 or croak "map_path: $db_path does not contain '/.rev_map.' !";
3788 $db_path;
3791 # the new replacement for .rev_db
3792 sub map_path {
3793 my ($self, $uuid) = @_;
3794 $uuid ||= $self->ra_uuid;
3795 "$self->{map_root}.$uuid";
3798 sub uri_encode {
3799 my ($f) = @_;
3800 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
3804 sub uri_decode {
3805 my ($f) = @_;
3806 $f =~ s#%([0-9a-fA-F]{2})#chr(hex($1))#eg;
3810 sub remove_username {
3811 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
3814 package Git::SVN::Prompt;
3815 use strict;
3816 use warnings;
3817 require SVN::Core;
3818 use vars qw/$_no_auth_cache $_username/;
3820 sub simple {
3821 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
3822 $may_save = undef if $_no_auth_cache;
3823 $default_username = $_username if defined $_username;
3824 if (defined $default_username && length $default_username) {
3825 if (defined $realm && length $realm) {
3826 print STDERR "Authentication realm: $realm\n";
3827 STDERR->flush;
3829 $cred->username($default_username);
3830 } else {
3831 username($cred, $realm, $may_save, $pool);
3833 $cred->password(_read_password("Password for '" .
3834 $cred->username . "': ", $realm));
3835 $cred->may_save($may_save);
3836 $SVN::_Core::SVN_NO_ERROR;
3839 sub ssl_server_trust {
3840 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
3841 $may_save = undef if $_no_auth_cache;
3842 print STDERR "Error validating server certificate for '$realm':\n";
3844 no warnings 'once';
3845 # All variables SVN::Auth::SSL::* are used only once,
3846 # so we're shutting up Perl warnings about this.
3847 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
3848 print STDERR " - The certificate is not issued ",
3849 "by a trusted authority. Use the\n",
3850 " fingerprint to validate ",
3851 "the certificate manually!\n";
3853 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
3854 print STDERR " - The certificate hostname ",
3855 "does not match.\n";
3857 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
3858 print STDERR " - The certificate is not yet valid.\n";
3860 if ($failures & $SVN::Auth::SSL::EXPIRED) {
3861 print STDERR " - The certificate has expired.\n";
3863 if ($failures & $SVN::Auth::SSL::OTHER) {
3864 print STDERR " - The certificate has ",
3865 "an unknown error.\n";
3867 } # no warnings 'once'
3868 printf STDERR
3869 "Certificate information:\n".
3870 " - Hostname: %s\n".
3871 " - Valid: from %s until %s\n".
3872 " - Issuer: %s\n".
3873 " - Fingerprint: %s\n",
3874 map $cert_info->$_, qw(hostname valid_from valid_until
3875 issuer_dname fingerprint);
3876 my $choice;
3877 prompt:
3878 print STDERR $may_save ?
3879 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
3880 "(R)eject or accept (t)emporarily? ";
3881 STDERR->flush;
3882 $choice = lc(substr(<STDIN> || 'R', 0, 1));
3883 if ($choice =~ /^t$/i) {
3884 $cred->may_save(undef);
3885 } elsif ($choice =~ /^r$/i) {
3886 return -1;
3887 } elsif ($may_save && $choice =~ /^p$/i) {
3888 $cred->may_save($may_save);
3889 } else {
3890 goto prompt;
3892 $cred->accepted_failures($failures);
3893 $SVN::_Core::SVN_NO_ERROR;
3896 sub ssl_client_cert {
3897 my ($cred, $realm, $may_save, $pool) = @_;
3898 $may_save = undef if $_no_auth_cache;
3899 print STDERR "Client certificate filename: ";
3900 STDERR->flush;
3901 chomp(my $filename = <STDIN>);
3902 $cred->cert_file($filename);
3903 $cred->may_save($may_save);
3904 $SVN::_Core::SVN_NO_ERROR;
3907 sub ssl_client_cert_pw {
3908 my ($cred, $realm, $may_save, $pool) = @_;
3909 $may_save = undef if $_no_auth_cache;
3910 $cred->password(_read_password("Password: ", $realm));
3911 $cred->may_save($may_save);
3912 $SVN::_Core::SVN_NO_ERROR;
3915 sub username {
3916 my ($cred, $realm, $may_save, $pool) = @_;
3917 $may_save = undef if $_no_auth_cache;
3918 if (defined $realm && length $realm) {
3919 print STDERR "Authentication realm: $realm\n";
3921 my $username;
3922 if (defined $_username) {
3923 $username = $_username;
3924 } else {
3925 print STDERR "Username: ";
3926 STDERR->flush;
3927 chomp($username = <STDIN>);
3929 $cred->username($username);
3930 $cred->may_save($may_save);
3931 $SVN::_Core::SVN_NO_ERROR;
3934 sub _read_password {
3935 my ($prompt, $realm) = @_;
3936 print STDERR $prompt;
3937 STDERR->flush;
3938 require Term::ReadKey;
3939 Term::ReadKey::ReadMode('noecho');
3940 my $password = '';
3941 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
3942 last if $key =~ /[\012\015]/; # \n\r
3943 $password .= $key;
3945 Term::ReadKey::ReadMode('restore');
3946 print STDERR "\n";
3947 STDERR->flush;
3948 $password;
3951 package SVN::Git::Fetcher;
3952 use vars qw/@ISA/;
3953 use strict;
3954 use warnings;
3955 use Carp qw/croak/;
3956 use File::Temp qw/tempfile/;
3957 use IO::File qw//;
3958 use vars qw/$_ignore_regex/;
3960 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
3961 sub new {
3962 my ($class, $git_svn, $switch_path) = @_;
3963 my $self = SVN::Delta::Editor->new;
3964 bless $self, $class;
3965 if (exists $git_svn->{last_commit}) {
3966 $self->{c} = $git_svn->{last_commit};
3967 $self->{empty_symlinks} =
3968 _mark_empty_symlinks($git_svn, $switch_path);
3970 $self->{ignore_regex} = eval { command_oneline('config', '--get',
3971 "svn-remote.$git_svn->{repo_id}.ignore-paths") };
3972 $self->{empty} = {};
3973 $self->{dir_prop} = {};
3974 $self->{file_prop} = {};
3975 $self->{absent_dir} = {};
3976 $self->{absent_file} = {};
3977 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
3978 $self;
3981 # this uses the Ra object, so it must be called before do_{switch,update},
3982 # not inside them (when the Git::SVN::Fetcher object is passed) to
3983 # do_{switch,update}
3984 sub _mark_empty_symlinks {
3985 my ($git_svn, $switch_path) = @_;
3986 my $bool = Git::config_bool('svn.brokenSymlinkWorkaround');
3987 return {} if (!defined($bool)) || (defined($bool) && ! $bool);
3989 my %ret;
3990 my ($rev, $cmt) = $git_svn->last_rev_commit;
3991 return {} unless ($rev && $cmt);
3993 # allow the warning to be printed for each revision we fetch to
3994 # ensure the user sees it. The user can also disable the workaround
3995 # on the repository even while git svn is running and the next
3996 # revision fetched will skip this expensive function.
3997 my $printed_warning;
3998 chomp(my $empty_blob = `git hash-object -t blob --stdin < /dev/null`);
3999 my ($ls, $ctx) = command_output_pipe(qw/ls-tree -r -z/, $cmt);
4000 local $/ = "\0";
4001 my $pfx = defined($switch_path) ? $switch_path : $git_svn->{path};
4002 $pfx .= '/' if length($pfx);
4003 while (<$ls>) {
4004 chomp;
4005 s/\A100644 blob $empty_blob\t//o or next;
4006 unless ($printed_warning) {
4007 print STDERR "Scanning for empty symlinks, ",
4008 "this may take a while if you have ",
4009 "many empty files\n",
4010 "You may disable this with `",
4011 "git config svn.brokenSymlinkWorkaround ",
4012 "false'.\n",
4013 "This may be done in a different ",
4014 "terminal without restarting ",
4015 "git svn\n";
4016 $printed_warning = 1;
4018 my $path = $_;
4019 my (undef, $props) =
4020 $git_svn->ra->get_file($pfx.$path, $rev, undef);
4021 if ($props->{'svn:special'}) {
4022 $ret{$path} = 1;
4025 command_close_pipe($ls, $ctx);
4026 \%ret;
4029 # returns true if a given path is inside a ".git" directory
4030 sub in_dot_git {
4031 $_[0] =~ m{(?:^|/)\.git(?:/|$)};
4034 # return value: 0 -- don't ignore, 1 -- ignore
4035 sub is_path_ignored {
4036 my ($self, $path) = @_;
4037 return 1 if in_dot_git($path);
4038 return 1 if defined($self->{ignore_regex}) &&
4039 $path =~ m!$self->{ignore_regex}!;
4040 return 0 unless defined($_ignore_regex);
4041 return 1 if $path =~ m!$_ignore_regex!o;
4042 return 0;
4045 sub set_path_strip {
4046 my ($self, $path) = @_;
4047 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
4050 sub open_root {
4051 { path => '' };
4054 sub open_directory {
4055 my ($self, $path, $pb, $rev) = @_;
4056 { path => $path };
4059 sub git_path {
4060 my ($self, $path) = @_;
4061 if ($self->{path_strip}) {
4062 $path =~ s!$self->{path_strip}!! or
4063 die "Failed to strip path '$path' ($self->{path_strip})\n";
4065 $path;
4068 sub delete_entry {
4069 my ($self, $path, $rev, $pb) = @_;
4070 return undef if $self->is_path_ignored($path);
4072 my $gpath = $self->git_path($path);
4073 return undef if ($gpath eq '');
4075 # remove entire directories.
4076 my ($tree) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
4077 =~ /\A040000 tree ([a-f\d]{40})\t\Q$gpath\E\0/);
4078 if ($tree) {
4079 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
4080 -r --name-only -z/,
4081 $tree);
4082 local $/ = "\0";
4083 while (<$ls>) {
4084 chomp;
4085 my $rmpath = "$gpath/$_";
4086 $self->{gii}->remove($rmpath);
4087 print "\tD\t$rmpath\n" unless $::_q;
4089 print "\tD\t$gpath/\n" unless $::_q;
4090 command_close_pipe($ls, $ctx);
4091 } else {
4092 $self->{gii}->remove($gpath);
4093 print "\tD\t$gpath\n" unless $::_q;
4095 $self->{empty}->{$path} = 0;
4096 undef;
4099 sub open_file {
4100 my ($self, $path, $pb, $rev) = @_;
4101 my ($mode, $blob);
4103 goto out if $self->is_path_ignored($path);
4105 my $gpath = $self->git_path($path);
4106 ($mode, $blob) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
4107 =~ /\A(\d{6}) blob ([a-f\d]{40})\t\Q$gpath\E\0/);
4108 unless (defined $mode && defined $blob) {
4109 die "$path was not found in commit $self->{c} (r$rev)\n";
4111 if ($mode eq '100644' && $self->{empty_symlinks}->{$path}) {
4112 $mode = '120000';
4114 out:
4115 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
4116 pool => SVN::Pool->new, action => 'M' };
4119 sub add_file {
4120 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
4121 my $mode;
4123 if (!$self->is_path_ignored($path)) {
4124 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
4125 delete $self->{empty}->{$dir};
4126 $mode = '100644';
4128 { path => $path, mode_a => $mode, mode_b => $mode,
4129 pool => SVN::Pool->new, action => 'A' };
4132 sub add_directory {
4133 my ($self, $path, $cp_path, $cp_rev) = @_;
4134 goto out if $self->is_path_ignored($path);
4135 my $gpath = $self->git_path($path);
4136 if ($gpath eq '') {
4137 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
4138 -r --name-only -z/,
4139 $self->{c});
4140 local $/ = "\0";
4141 while (<$ls>) {
4142 chomp;
4143 $self->{gii}->remove($_);
4144 print "\tD\t$_\n" unless $::_q;
4146 command_close_pipe($ls, $ctx);
4147 $self->{empty}->{$path} = 0;
4149 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
4150 delete $self->{empty}->{$dir};
4151 $self->{empty}->{$path} = 1;
4152 out:
4153 { path => $path };
4156 sub change_dir_prop {
4157 my ($self, $db, $prop, $value) = @_;
4158 return undef if $self->is_path_ignored($db->{path});
4159 $self->{dir_prop}->{$db->{path}} ||= {};
4160 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
4161 undef;
4164 sub absent_directory {
4165 my ($self, $path, $pb) = @_;
4166 return undef if $self->is_path_ignored($path);
4167 $self->{absent_dir}->{$pb->{path}} ||= [];
4168 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
4169 undef;
4172 sub absent_file {
4173 my ($self, $path, $pb) = @_;
4174 return undef if $self->is_path_ignored($path);
4175 $self->{absent_file}->{$pb->{path}} ||= [];
4176 push @{$self->{absent_file}->{$pb->{path}}}, $path;
4177 undef;
4180 sub change_file_prop {
4181 my ($self, $fb, $prop, $value) = @_;
4182 return undef if $self->is_path_ignored($fb->{path});
4183 if ($prop eq 'svn:executable') {
4184 if ($fb->{mode_b} != 120000) {
4185 $fb->{mode_b} = defined $value ? 100755 : 100644;
4187 } elsif ($prop eq 'svn:special') {
4188 $fb->{mode_b} = defined $value ? 120000 : 100644;
4189 } else {
4190 $self->{file_prop}->{$fb->{path}} ||= {};
4191 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
4193 undef;
4196 sub apply_textdelta {
4197 my ($self, $fb, $exp) = @_;
4198 return undef if $self->is_path_ignored($fb->{path});
4199 my $fh = $::_repository->temp_acquire('svn_delta');
4200 # $fh gets auto-closed() by SVN::TxDelta::apply(),
4201 # (but $base does not,) so dup() it for reading in close_file
4202 open my $dup, '<&', $fh or croak $!;
4203 my $base = $::_repository->temp_acquire('git_blob');
4205 if ($fb->{blob}) {
4206 my ($base_is_link, $size);
4208 if ($fb->{mode_a} eq '120000' &&
4209 ! $self->{empty_symlinks}->{$fb->{path}}) {
4210 print $base 'link ' or die "print $!\n";
4211 $base_is_link = 1;
4213 retry:
4214 $size = $::_repository->cat_blob($fb->{blob}, $base);
4215 die "Failed to read object $fb->{blob}" if ($size < 0);
4217 if (defined $exp) {
4218 seek $base, 0, 0 or croak $!;
4219 my $got = ::md5sum($base);
4220 if ($got ne $exp) {
4221 my $err = "Checksum mismatch: ".
4222 "$fb->{path} $fb->{blob}\n" .
4223 "expected: $exp\n" .
4224 " got: $got\n";
4225 if ($base_is_link) {
4226 warn $err,
4227 "Retrying... (possibly ",
4228 "a bad symlink from SVN)\n";
4229 $::_repository->temp_reset($base);
4230 $base_is_link = 0;
4231 goto retry;
4233 die $err;
4237 seek $base, 0, 0 or croak $!;
4238 $fb->{fh} = $fh;
4239 $fb->{base} = $base;
4240 [ SVN::TxDelta::apply($base, $dup, undef, $fb->{path}, $fb->{pool}) ];
4243 sub close_file {
4244 my ($self, $fb, $exp) = @_;
4245 return undef if $self->is_path_ignored($fb->{path});
4247 my $hash;
4248 my $path = $self->git_path($fb->{path});
4249 if (my $fh = $fb->{fh}) {
4250 if (defined $exp) {
4251 seek($fh, 0, 0) or croak $!;
4252 my $got = ::md5sum($fh);
4253 if ($got ne $exp) {
4254 die "Checksum mismatch: $path\n",
4255 "expected: $exp\n got: $got\n";
4258 if ($fb->{mode_b} == 120000) {
4259 sysseek($fh, 0, 0) or croak $!;
4260 my $rd = sysread($fh, my $buf, 5);
4262 if (!defined $rd) {
4263 croak "sysread: $!\n";
4264 } elsif ($rd == 0) {
4265 warn "$path has mode 120000",
4266 " but it points to nothing\n",
4267 "converting to an empty file with mode",
4268 " 100644\n";
4269 $fb->{mode_b} = '100644';
4270 } elsif ($buf ne 'link ') {
4271 warn "$path has mode 120000",
4272 " but is not a link\n";
4273 } else {
4274 my $tmp_fh = $::_repository->temp_acquire(
4275 'svn_hash');
4276 my $res;
4277 while ($res = sysread($fh, my $str, 1024)) {
4278 my $out = syswrite($tmp_fh, $str, $res);
4279 defined($out) && $out == $res
4280 or croak("write ",
4281 Git::temp_path($tmp_fh),
4282 ": $!\n");
4284 defined $res or croak $!;
4286 ($fh, $tmp_fh) = ($tmp_fh, $fh);
4287 Git::temp_release($tmp_fh, 1);
4291 $hash = $::_repository->hash_and_insert_object(
4292 Git::temp_path($fh));
4293 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
4295 Git::temp_release($fb->{base}, 1);
4296 Git::temp_release($fh, 1);
4297 } else {
4298 $hash = $fb->{blob} or die "no blob information\n";
4300 $fb->{pool}->clear;
4301 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
4302 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
4303 undef;
4306 sub abort_edit {
4307 my $self = shift;
4308 $self->{nr} = $self->{gii}->{nr};
4309 delete $self->{gii};
4310 $self->SUPER::abort_edit(@_);
4313 sub close_edit {
4314 my $self = shift;
4315 $self->{git_commit_ok} = 1;
4316 $self->{nr} = $self->{gii}->{nr};
4317 delete $self->{gii};
4318 $self->SUPER::close_edit(@_);
4321 package SVN::Git::Editor;
4322 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
4323 use strict;
4324 use warnings;
4325 use Carp qw/croak/;
4326 use IO::File;
4328 sub new {
4329 my ($class, $opts) = @_;
4330 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
4331 die "$_ required!\n" unless (defined $opts->{$_});
4334 my $pool = SVN::Pool->new;
4335 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
4336 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
4337 $opts->{r}, $mods);
4339 # $opts->{ra} functions should not be used after this:
4340 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
4341 $opts->{editor_cb}, $pool);
4342 my $self = SVN::Delta::Editor->new(@ce, $pool);
4343 bless $self, $class;
4344 foreach (qw/svn_path r tree_a tree_b/) {
4345 $self->{$_} = $opts->{$_};
4347 $self->{url} = $opts->{ra}->{url};
4348 $self->{mods} = $mods;
4349 $self->{types} = $types;
4350 $self->{pool} = $pool;
4351 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
4352 $self->{rm} = { };
4353 $self->{path_prefix} = length $self->{svn_path} ?
4354 "$self->{svn_path}/" : '';
4355 $self->{config} = $opts->{config};
4356 return $self;
4359 sub generate_diff {
4360 my ($tree_a, $tree_b) = @_;
4361 my @diff_tree = qw(diff-tree -z -r);
4362 if ($_cp_similarity) {
4363 push @diff_tree, "-C$_cp_similarity";
4364 } else {
4365 push @diff_tree, '-C';
4367 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
4368 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
4369 push @diff_tree, $tree_a, $tree_b;
4370 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
4371 local $/ = "\0";
4372 my $state = 'meta';
4373 my @mods;
4374 while (<$diff_fh>) {
4375 chomp $_; # this gets rid of the trailing "\0"
4376 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
4377 ($::sha1)\s($::sha1)\s
4378 ([MTCRAD])\d*$/xo) {
4379 push @mods, { mode_a => $1, mode_b => $2,
4380 sha1_a => $3, sha1_b => $4,
4381 chg => $5 };
4382 if ($5 =~ /^(?:C|R)$/) {
4383 $state = 'file_a';
4384 } else {
4385 $state = 'file_b';
4387 } elsif ($state eq 'file_a') {
4388 my $x = $mods[$#mods] or croak "Empty array\n";
4389 if ($x->{chg} !~ /^(?:C|R)$/) {
4390 croak "Error parsing $_, $x->{chg}\n";
4392 $x->{file_a} = $_;
4393 $state = 'file_b';
4394 } elsif ($state eq 'file_b') {
4395 my $x = $mods[$#mods] or croak "Empty array\n";
4396 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
4397 croak "Error parsing $_, $x->{chg}\n";
4399 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
4400 croak "Error parsing $_, $x->{chg}\n";
4402 $x->{file_b} = $_;
4403 $state = 'meta';
4404 } else {
4405 croak "Error parsing $_\n";
4408 command_close_pipe($diff_fh, $ctx);
4409 \@mods;
4412 sub check_diff_paths {
4413 my ($ra, $pfx, $rev, $mods) = @_;
4414 my %types;
4415 $pfx .= '/' if length $pfx;
4417 sub type_diff_paths {
4418 my ($ra, $types, $path, $rev) = @_;
4419 my @p = split m#/+#, $path;
4420 my $c = shift @p;
4421 unless (defined $types->{$c}) {
4422 $types->{$c} = $ra->check_path($c, $rev);
4424 while (@p) {
4425 $c .= '/' . shift @p;
4426 next if defined $types->{$c};
4427 $types->{$c} = $ra->check_path($c, $rev);
4431 foreach my $m (@$mods) {
4432 foreach my $f (qw/file_a file_b/) {
4433 next unless defined $m->{$f};
4434 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
4435 if (length $pfx.$dir && ! defined $types{$dir}) {
4436 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
4440 \%types;
4443 sub split_path {
4444 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
4447 sub repo_path {
4448 my ($self, $path) = @_;
4449 $self->{path_prefix}.(defined $path ? $path : '');
4452 sub url_path {
4453 my ($self, $path) = @_;
4454 if ($self->{url} =~ m#^https?://#) {
4455 $path =~ s!([^~a-zA-Z0-9_./-])!uc sprintf("%%%02x",ord($1))!eg;
4457 $self->{url} . '/' . $self->repo_path($path);
4460 sub rmdirs {
4461 my ($self) = @_;
4462 my $rm = $self->{rm};
4463 delete $rm->{''}; # we never delete the url we're tracking
4464 return unless %$rm;
4466 foreach (keys %$rm) {
4467 my @d = split m#/#, $_;
4468 my $c = shift @d;
4469 $rm->{$c} = 1;
4470 while (@d) {
4471 $c .= '/' . shift @d;
4472 $rm->{$c} = 1;
4475 delete $rm->{$self->{svn_path}};
4476 delete $rm->{''}; # we never delete the url we're tracking
4477 return unless %$rm;
4479 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
4480 $self->{tree_b});
4481 local $/ = "\0";
4482 while (<$fh>) {
4483 chomp;
4484 my @dn = split m#/#, $_;
4485 while (pop @dn) {
4486 delete $rm->{join '/', @dn};
4488 unless (%$rm) {
4489 close $fh;
4490 return;
4493 command_close_pipe($fh, $ctx);
4495 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
4496 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
4497 $self->close_directory($bat->{$d}, $p);
4498 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
4499 print "\tD+\t$d/\n" unless $::_q;
4500 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
4501 delete $bat->{$d};
4505 sub open_or_add_dir {
4506 my ($self, $full_path, $baton) = @_;
4507 my $t = $self->{types}->{$full_path};
4508 if (!defined $t) {
4509 die "$full_path not known in r$self->{r} or we have a bug!\n";
4512 no warnings 'once';
4513 # SVN::Node::none and SVN::Node::file are used only once,
4514 # so we're shutting up Perl's warnings about them.
4515 if ($t == $SVN::Node::none) {
4516 return $self->add_directory($full_path, $baton,
4517 undef, -1, $self->{pool});
4518 } elsif ($t == $SVN::Node::dir) {
4519 return $self->open_directory($full_path, $baton,
4520 $self->{r}, $self->{pool});
4521 } # no warnings 'once'
4522 print STDERR "$full_path already exists in repository at ",
4523 "r$self->{r} and it is not a directory (",
4524 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
4525 } # no warnings 'once'
4526 exit 1;
4529 sub ensure_path {
4530 my ($self, $path) = @_;
4531 my $bat = $self->{bat};
4532 my $repo_path = $self->repo_path($path);
4533 return $bat->{''} unless (length $repo_path);
4534 my @p = split m#/+#, $repo_path;
4535 my $c = shift @p;
4536 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
4537 while (@p) {
4538 my $c0 = $c;
4539 $c .= '/' . shift @p;
4540 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
4542 return $bat->{$c};
4545 # Subroutine to convert a globbing pattern to a regular expression.
4546 # From perl cookbook.
4547 sub glob2pat {
4548 my $globstr = shift;
4549 my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
4550 $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
4551 return '^' . $globstr . '$';
4554 sub check_autoprop {
4555 my ($self, $pattern, $properties, $file, $fbat) = @_;
4556 # Convert the globbing pattern to a regular expression.
4557 my $regex = glob2pat($pattern);
4558 # Check if the pattern matches the file name.
4559 if($file =~ m/($regex)/) {
4560 # Parse the list of properties to set.
4561 my @props = split(/;/, $properties);
4562 foreach my $prop (@props) {
4563 # Parse 'name=value' syntax and set the property.
4564 if ($prop =~ /([^=]+)=(.*)/) {
4565 my ($n,$v) = ($1,$2);
4566 for ($n, $v) {
4567 s/^\s+//; s/\s+$//;
4569 $self->change_file_prop($fbat, $n, $v);
4575 sub apply_autoprops {
4576 my ($self, $file, $fbat) = @_;
4577 my $conf_t = ${$self->{config}}{'config'};
4578 no warnings 'once';
4579 # Check [miscellany]/enable-auto-props in svn configuration.
4580 if (SVN::_Core::svn_config_get_bool(
4581 $conf_t,
4582 $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
4583 $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
4584 0)) {
4585 # Auto-props are enabled. Enumerate them to look for matches.
4586 my $callback = sub {
4587 $self->check_autoprop($_[0], $_[1], $file, $fbat);
4589 SVN::_Core::svn_config_enumerate(
4590 $conf_t,
4591 $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
4592 $callback);
4596 sub A {
4597 my ($self, $m) = @_;
4598 my ($dir, $file) = split_path($m->{file_b});
4599 my $pbat = $self->ensure_path($dir);
4600 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4601 undef, -1);
4602 print "\tA\t$m->{file_b}\n" unless $::_q;
4603 $self->apply_autoprops($file, $fbat);
4604 $self->chg_file($fbat, $m);
4605 $self->close_file($fbat,undef,$self->{pool});
4608 sub C {
4609 my ($self, $m) = @_;
4610 my ($dir, $file) = split_path($m->{file_b});
4611 my $pbat = $self->ensure_path($dir);
4612 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4613 $self->url_path($m->{file_a}), $self->{r});
4614 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
4615 $self->chg_file($fbat, $m);
4616 $self->close_file($fbat,undef,$self->{pool});
4619 sub delete_entry {
4620 my ($self, $path, $pbat) = @_;
4621 my $rpath = $self->repo_path($path);
4622 my ($dir, $file) = split_path($rpath);
4623 $self->{rm}->{$dir} = 1;
4624 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
4627 sub R {
4628 my ($self, $m) = @_;
4629 my ($dir, $file) = split_path($m->{file_b});
4630 my $pbat = $self->ensure_path($dir);
4631 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4632 $self->url_path($m->{file_a}), $self->{r});
4633 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
4634 $self->apply_autoprops($file, $fbat);
4635 $self->chg_file($fbat, $m);
4636 $self->close_file($fbat,undef,$self->{pool});
4638 ($dir, $file) = split_path($m->{file_a});
4639 $pbat = $self->ensure_path($dir);
4640 $self->delete_entry($m->{file_a}, $pbat);
4643 sub M {
4644 my ($self, $m) = @_;
4645 my ($dir, $file) = split_path($m->{file_b});
4646 my $pbat = $self->ensure_path($dir);
4647 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
4648 $pbat,$self->{r},$self->{pool});
4649 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
4650 $self->chg_file($fbat, $m);
4651 $self->close_file($fbat,undef,$self->{pool});
4654 sub T { shift->M(@_) }
4656 sub change_file_prop {
4657 my ($self, $fbat, $pname, $pval) = @_;
4658 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
4661 sub _chg_file_get_blob ($$$$) {
4662 my ($self, $fbat, $m, $which) = @_;
4663 my $fh = $::_repository->temp_acquire("git_blob_$which");
4664 if ($m->{"mode_$which"} =~ /^120/) {
4665 print $fh 'link ' or croak $!;
4666 $self->change_file_prop($fbat,'svn:special','*');
4667 } elsif ($m->{mode_a} =~ /^120/ && $m->{"mode_$which"} !~ /^120/) {
4668 $self->change_file_prop($fbat,'svn:special',undef);
4670 my $blob = $m->{"sha1_$which"};
4671 return ($fh,) if ($blob =~ /^0{40}$/);
4672 my $size = $::_repository->cat_blob($blob, $fh);
4673 croak "Failed to read object $blob" if ($size < 0);
4674 $fh->flush == 0 or croak $!;
4675 seek $fh, 0, 0 or croak $!;
4677 my $exp = ::md5sum($fh);
4678 seek $fh, 0, 0 or croak $!;
4679 return ($fh, $exp);
4682 sub chg_file {
4683 my ($self, $fbat, $m) = @_;
4684 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
4685 $self->change_file_prop($fbat,'svn:executable','*');
4686 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
4687 $self->change_file_prop($fbat,'svn:executable',undef);
4689 my ($fh_a, $exp_a) = _chg_file_get_blob $self, $fbat, $m, 'a';
4690 my ($fh_b, $exp_b) = _chg_file_get_blob $self, $fbat, $m, 'b';
4691 my $pool = SVN::Pool->new;
4692 my $atd = $self->apply_textdelta($fbat, $exp_a, $pool);
4693 if (-s $fh_a) {
4694 my $txstream = SVN::TxDelta::new ($fh_a, $fh_b, $pool);
4695 my $res = SVN::TxDelta::send_txstream($txstream, @$atd, $pool);
4696 if (defined $res) {
4697 die "Unexpected result from send_txstream: $res\n",
4698 "(SVN::Core::VERSION: $SVN::Core::VERSION)\n";
4700 } else {
4701 my $got = SVN::TxDelta::send_stream($fh_b, @$atd, $pool);
4702 die "Checksum mismatch\nexpected: $exp_b\ngot: $got\n"
4703 if ($got ne $exp_b);
4705 Git::temp_release($fh_b, 1);
4706 Git::temp_release($fh_a, 1);
4707 $pool->clear;
4710 sub D {
4711 my ($self, $m) = @_;
4712 my ($dir, $file) = split_path($m->{file_b});
4713 my $pbat = $self->ensure_path($dir);
4714 print "\tD\t$m->{file_b}\n" unless $::_q;
4715 $self->delete_entry($m->{file_b}, $pbat);
4718 sub close_edit {
4719 my ($self) = @_;
4720 my ($p,$bat) = ($self->{pool}, $self->{bat});
4721 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
4722 next if $_ eq '';
4723 $self->close_directory($bat->{$_}, $p);
4725 $self->close_directory($bat->{''}, $p);
4726 $self->SUPER::close_edit($p);
4727 $p->clear;
4730 sub abort_edit {
4731 my ($self) = @_;
4732 $self->SUPER::abort_edit($self->{pool});
4735 sub DESTROY {
4736 my $self = shift;
4737 $self->SUPER::DESTROY(@_);
4738 $self->{pool}->clear;
4741 # this drives the editor
4742 sub apply_diff {
4743 my ($self) = @_;
4744 my $mods = $self->{mods};
4745 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
4746 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
4747 my $f = $m->{chg};
4748 if (defined $o{$f}) {
4749 $self->$f($m);
4750 } else {
4751 fatal("Invalid change type: $f");
4754 $self->rmdirs if $_rmdir;
4755 if (@$mods == 0) {
4756 $self->abort_edit;
4757 } else {
4758 $self->close_edit;
4760 return scalar @$mods;
4763 package Git::SVN::Ra;
4764 use vars qw/@ISA $config_dir $_log_window_size/;
4765 use strict;
4766 use warnings;
4767 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
4769 BEGIN {
4770 # enforce temporary pool usage for some simple functions
4771 no strict 'refs';
4772 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root
4773 get_file/) {
4774 my $SUPER = "SUPER::$f";
4775 *$f = sub {
4776 my $self = shift;
4777 my $pool = SVN::Pool->new;
4778 my @ret = $self->$SUPER(@_,$pool);
4779 $pool->clear;
4780 wantarray ? @ret : $ret[0];
4785 sub _auth_providers () {
4787 SVN::Client::get_simple_provider(),
4788 SVN::Client::get_ssl_server_trust_file_provider(),
4789 SVN::Client::get_simple_prompt_provider(
4790 \&Git::SVN::Prompt::simple, 2),
4791 SVN::Client::get_ssl_client_cert_file_provider(),
4792 SVN::Client::get_ssl_client_cert_prompt_provider(
4793 \&Git::SVN::Prompt::ssl_client_cert, 2),
4794 SVN::Client::get_ssl_client_cert_pw_file_provider(),
4795 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
4796 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
4797 SVN::Client::get_username_provider(),
4798 SVN::Client::get_ssl_server_trust_prompt_provider(
4799 \&Git::SVN::Prompt::ssl_server_trust),
4800 SVN::Client::get_username_prompt_provider(
4801 \&Git::SVN::Prompt::username, 2)
4805 sub escape_uri_only {
4806 my ($uri) = @_;
4807 my @tmp;
4808 foreach (split m{/}, $uri) {
4809 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
4810 push @tmp, $_;
4812 join('/', @tmp);
4815 sub escape_url {
4816 my ($url) = @_;
4817 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
4818 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
4819 $url = "$scheme://$domain$uri";
4821 $url;
4824 sub new {
4825 my ($class, $url) = @_;
4826 $url =~ s!/+$!!;
4827 return $RA if ($RA && $RA->{url} eq $url);
4829 SVN::_Core::svn_config_ensure($config_dir, undef);
4830 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
4831 my $config = SVN::Core::config_get_config($config_dir);
4832 $RA = undef;
4833 my $dont_store_passwords = 1;
4834 my $conf_t = ${$config}{'config'};
4836 no warnings 'once';
4837 # The usage of $SVN::_Core::SVN_CONFIG_* variables
4838 # produces warnings that variables are used only once.
4839 # I had not found the better way to shut them up, so
4840 # the warnings of type 'once' are disabled in this block.
4841 if (SVN::_Core::svn_config_get_bool($conf_t,
4842 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4843 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
4844 1) == 0) {
4845 SVN::_Core::svn_auth_set_parameter($baton,
4846 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
4847 bless (\$dont_store_passwords, "_p_void"));
4849 if (SVN::_Core::svn_config_get_bool($conf_t,
4850 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4851 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
4852 1) == 0) {
4853 $Git::SVN::Prompt::_no_auth_cache = 1;
4855 } # no warnings 'once'
4856 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
4857 config => $config,
4858 pool => SVN::Pool->new,
4859 auth_provider_callbacks => $callbacks);
4860 $self->{url} = $url;
4861 $self->{svn_path} = $url;
4862 $self->{repos_root} = $self->get_repos_root;
4863 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
4864 $self->{cache} = { check_path => { r => 0, data => {} },
4865 get_dir => { r => 0, data => {} } };
4866 $RA = bless $self, $class;
4869 sub check_path {
4870 my ($self, $path, $r) = @_;
4871 my $cache = $self->{cache}->{check_path};
4872 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
4873 return $cache->{data}->{$path};
4875 my $pool = SVN::Pool->new;
4876 my $t = $self->SUPER::check_path($path, $r, $pool);
4877 $pool->clear;
4878 if ($r != $cache->{r}) {
4879 %{$cache->{data}} = ();
4880 $cache->{r} = $r;
4882 $cache->{data}->{$path} = $t;
4885 sub get_dir {
4886 my ($self, $dir, $r) = @_;
4887 my $cache = $self->{cache}->{get_dir};
4888 if ($r == $cache->{r}) {
4889 if (my $x = $cache->{data}->{$dir}) {
4890 return wantarray ? @$x : $x->[0];
4893 my $pool = SVN::Pool->new;
4894 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
4895 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
4896 $pool->clear;
4897 if ($r != $cache->{r}) {
4898 %{$cache->{data}} = ();
4899 $cache->{r} = $r;
4901 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
4902 wantarray ? (\%dirents, $r, $props) : \%dirents;
4905 sub DESTROY {
4906 # do not call the real DESTROY since we store ourselves in $RA
4909 # get_log(paths, start, end, limit,
4910 # discover_changed_paths, strict_node_history, receiver)
4911 sub get_log {
4912 my ($self, @args) = @_;
4913 my $pool = SVN::Pool->new;
4915 # svn_log_changed_path_t objects passed to get_log are likely to be
4916 # overwritten even if only the refs are copied to an external variable,
4917 # so we should dup the structures in their entirety. Using an
4918 # externally passed pool (instead of our temporary and quickly cleared
4919 # pool in Git::SVN::Ra) does not help matters at all...
4920 my $receiver = pop @args;
4921 my $prefix = "/".$self->{svn_path};
4922 $prefix =~ s#/+($)##;
4923 my $prefix_regex = qr#^\Q$prefix\E#;
4924 push(@args, sub {
4925 my ($paths) = $_[0];
4926 return &$receiver(@_) unless $paths;
4927 $_[0] = ();
4928 foreach my $p (keys %$paths) {
4929 my $i = $paths->{$p};
4930 # Make path relative to our url, not repos_root
4931 $p =~ s/$prefix_regex//;
4932 my %s = map { $_ => $i->$_; }
4933 qw/copyfrom_path copyfrom_rev action/;
4934 if ($s{'copyfrom_path'}) {
4935 $s{'copyfrom_path'} =~ s/$prefix_regex//;
4937 $_[0]{$p} = \%s;
4939 &$receiver(@_);
4943 # the limit parameter was not supported in SVN 1.1.x, so we
4944 # drop it. Therefore, the receiver callback passed to it
4945 # is made aware of this limitation by being wrapped if
4946 # the limit passed to is being wrapped.
4947 if ($SVN::Core::VERSION le '1.2.0') {
4948 my $limit = splice(@args, 3, 1);
4949 if ($limit > 0) {
4950 my $receiver = pop @args;
4951 push(@args, sub { &$receiver(@_) if (--$limit >= 0) });
4954 my $ret = $self->SUPER::get_log(@args, $pool);
4955 $pool->clear;
4956 $ret;
4959 sub trees_match {
4960 my ($self, $url1, $rev1, $url2, $rev2) = @_;
4961 my $ctx = SVN::Client->new(auth => _auth_providers);
4962 my $out = IO::File->new_tmpfile;
4964 # older SVN (1.1.x) doesn't take $pool as the last parameter for
4965 # $ctx->diff(), so we'll create a default one
4966 my $pool = SVN::Pool->new_default_sub;
4968 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
4969 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
4970 $out->flush;
4971 my $ret = (($out->stat)[7] == 0);
4972 close $out or croak $!;
4974 $ret;
4977 sub get_commit_editor {
4978 my ($self, $log, $cb, $pool) = @_;
4979 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
4980 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
4983 sub gs_do_update {
4984 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
4985 my $new = ($rev_a == $rev_b);
4986 my $path = $gs->{path};
4988 if ($new && -e $gs->{index}) {
4989 unlink $gs->{index} or die
4990 "Couldn't unlink index: $gs->{index}: $!\n";
4992 my $pool = SVN::Pool->new;
4993 $editor->set_path_strip($path);
4994 my (@pc) = split m#/#, $path;
4995 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
4996 1, $editor, $pool);
4997 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4999 # Since we can't rely on svn_ra_reparent being available, we'll
5000 # just have to do some magic with set_path to make it so
5001 # we only want a partial path.
5002 my $sp = '';
5003 my $final = join('/', @pc);
5004 while (@pc) {
5005 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
5006 $sp .= '/' if length $sp;
5007 $sp .= shift @pc;
5009 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
5011 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
5013 $reporter->finish_report($pool);
5014 $pool->clear;
5015 $editor->{git_commit_ok};
5018 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
5019 # svn_ra_reparent didn't work before 1.4)
5020 sub gs_do_switch {
5021 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
5022 my $path = $gs->{path};
5023 my $pool = SVN::Pool->new;
5025 my $full_url = $self->{url};
5026 my $old_url = $full_url;
5027 $full_url .= '/' . $path if length $path;
5028 my ($ra, $reparented);
5030 if ($old_url =~ m#^svn(\+ssh)?://# ||
5031 ($full_url =~ m#^https?://# &&
5032 escape_url($full_url) ne $full_url)) {
5033 $_[0] = undef;
5034 $self = undef;
5035 $RA = undef;
5036 $ra = Git::SVN::Ra->new($full_url);
5037 $ra_invalid = 1;
5038 } elsif ($old_url ne $full_url) {
5039 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url, $pool);
5040 $self->{url} = $full_url;
5041 $reparented = 1;
5044 $ra ||= $self;
5045 $url_b = escape_url($url_b);
5046 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
5047 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
5048 $reporter->set_path('', $rev_a, 0, @lock, $pool);
5049 $reporter->finish_report($pool);
5051 if ($reparented) {
5052 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
5053 $self->{url} = $old_url;
5056 $pool->clear;
5057 $editor->{git_commit_ok};
5060 sub longest_common_path {
5061 my ($gsv, $globs) = @_;
5062 my %common;
5063 my $common_max = scalar @$gsv;
5065 foreach my $gs (@$gsv) {
5066 my @tmp = split m#/#, $gs->{path};
5067 my $p = '';
5068 foreach (@tmp) {
5069 $p .= length($p) ? "/$_" : $_;
5070 $common{$p} ||= 0;
5071 $common{$p}++;
5074 $globs ||= [];
5075 $common_max += scalar @$globs;
5076 foreach my $glob (@$globs) {
5077 my @tmp = split m#/#, $glob->{path}->{left};
5078 my $p = '';
5079 foreach (@tmp) {
5080 $p .= length($p) ? "/$_" : $_;
5081 $common{$p} ||= 0;
5082 $common{$p}++;
5086 my $longest_path = '';
5087 foreach (sort {length $b <=> length $a} keys %common) {
5088 if ($common{$_} == $common_max) {
5089 $longest_path = $_;
5090 last;
5093 $longest_path;
5096 sub gs_fetch_loop_common {
5097 my ($self, $base, $head, $gsv, $globs) = @_;
5098 return if ($base > $head);
5099 my $inc = $_log_window_size;
5100 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
5101 my $longest_path = longest_common_path($gsv, $globs);
5102 my $ra_url = $self->{url};
5103 my $find_trailing_edge;
5104 while (1) {
5105 my %revs;
5106 my $err;
5107 my $err_handler = $SVN::Error::handler;
5108 $SVN::Error::handler = sub {
5109 ($err) = @_;
5110 skip_unknown_revs($err);
5112 sub _cb {
5113 my ($paths, $r, $author, $date, $log) = @_;
5114 [ $paths,
5115 { author => $author, date => $date, log => $log } ];
5117 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
5118 sub { $revs{$_[1]} = _cb(@_) });
5119 if ($err) {
5120 print "Checked through r$max\r";
5121 } else {
5122 $find_trailing_edge = 1;
5124 if ($err and $find_trailing_edge) {
5125 print STDERR "Path '$longest_path' ",
5126 "was probably deleted:\n",
5127 $err->expanded_message,
5128 "\nWill attempt to follow ",
5129 "revisions r$min .. r$max ",
5130 "committed before the deletion\n";
5131 my $hi = $max;
5132 while (--$hi >= $min) {
5133 my $ok;
5134 $self->get_log([$longest_path], $min, $hi,
5135 0, 1, 1, sub {
5136 $ok = $_[1];
5137 $revs{$_[1]} = _cb(@_) });
5138 if ($ok) {
5139 print STDERR "r$min .. r$ok OK\n";
5140 last;
5143 $find_trailing_edge = 0;
5145 $SVN::Error::handler = $err_handler;
5147 my %exists = map { $_->{path} => $_ } @$gsv;
5148 foreach my $r (sort {$a <=> $b} keys %revs) {
5149 my ($paths, $logged) = @{$revs{$r}};
5151 foreach my $gs ($self->match_globs(\%exists, $paths,
5152 $globs, $r)) {
5153 if ($gs->rev_map_max >= $r) {
5154 next;
5156 next unless $gs->match_paths($paths, $r);
5157 $gs->{logged_rev_props} = $logged;
5158 if (my $last_commit = $gs->last_commit) {
5159 $gs->assert_index_clean($last_commit);
5161 my $log_entry = $gs->do_fetch($paths, $r);
5162 if ($log_entry) {
5163 $gs->do_git_commit($log_entry);
5165 $INDEX_FILES{$gs->{index}} = 1;
5167 foreach my $g (@$globs) {
5168 my $k = "svn-remote.$g->{remote}." .
5169 "$g->{t}-maxRev";
5170 Git::SVN::tmp_config($k, $r);
5172 if ($ra_invalid) {
5173 $_[0] = undef;
5174 $self = undef;
5175 $RA = undef;
5176 $self = Git::SVN::Ra->new($ra_url);
5177 $ra_invalid = undef;
5180 # pre-fill the .rev_db since it'll eventually get filled in
5181 # with '0' x40 if something new gets committed
5182 foreach my $gs (@$gsv) {
5183 next if $gs->rev_map_max >= $max;
5184 next if defined $gs->rev_map_get($max);
5185 $gs->rev_map_set($max, 0 x40);
5187 foreach my $g (@$globs) {
5188 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
5189 Git::SVN::tmp_config($k, $max);
5191 last if $max >= $head;
5192 $min = $max + 1;
5193 $max += $inc;
5194 $max = $head if ($max > $head);
5196 Git::SVN::gc();
5199 sub get_dir_globbed {
5200 my ($self, $left, $depth, $r) = @_;
5202 my @x = eval { $self->get_dir($left, $r) };
5203 return unless scalar @x == 3;
5204 my $dirents = $x[0];
5205 my @finalents;
5206 foreach my $de (keys %$dirents) {
5207 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
5208 if ($depth > 1) {
5209 my @args = ("$left/$de", $depth - 1, $r);
5210 foreach my $dir ($self->get_dir_globbed(@args)) {
5211 push @finalents, "$de/$dir";
5213 } else {
5214 push @finalents, $de;
5217 @finalents;
5220 sub match_globs {
5221 my ($self, $exists, $paths, $globs, $r) = @_;
5223 sub get_dir_check {
5224 my ($self, $exists, $g, $r) = @_;
5226 my @dirs = $self->get_dir_globbed($g->{path}->{left},
5227 $g->{path}->{depth},
5228 $r);
5230 foreach my $de (@dirs) {
5231 my $p = $g->{path}->full_path($de);
5232 next if $exists->{$p};
5233 next if (length $g->{path}->{right} &&
5234 ($self->check_path($p, $r) !=
5235 $SVN::Node::dir));
5236 next unless $p =~ /$g->{path}->{regex}/;
5237 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
5238 $g->{ref}->full_path($de), 1);
5241 foreach my $g (@$globs) {
5242 if (my $path = $paths->{"/$g->{path}->{left}"}) {
5243 if ($path->{action} =~ /^[AR]$/) {
5244 get_dir_check($self, $exists, $g, $r);
5247 foreach (keys %$paths) {
5248 if (/$g->{path}->{left_regex}/ &&
5249 !/$g->{path}->{regex}/) {
5250 next if $paths->{$_}->{action} !~ /^[AR]$/;
5251 get_dir_check($self, $exists, $g, $r);
5253 next unless /$g->{path}->{regex}/;
5254 my $p = $1;
5255 my $pathname = $g->{path}->full_path($p);
5256 next if $exists->{$pathname};
5257 next if ($self->check_path($pathname, $r) !=
5258 $SVN::Node::dir);
5259 $exists->{$pathname} = Git::SVN->init(
5260 $self->{url}, $pathname, undef,
5261 $g->{ref}->full_path($p), 1);
5263 my $c = '';
5264 foreach (split m#/#, $g->{path}->{left}) {
5265 $c .= "/$_";
5266 next unless ($paths->{$c} &&
5267 ($paths->{$c}->{action} =~ /^[AR]$/));
5268 get_dir_check($self, $exists, $g, $r);
5271 values %$exists;
5274 sub minimize_url {
5275 my ($self) = @_;
5276 return $self->{url} if ($self->{url} eq $self->{repos_root});
5277 my $url = $self->{repos_root};
5278 my @components = split(m!/!, $self->{svn_path});
5279 my $c = '';
5280 do {
5281 $url .= "/$c" if length $c;
5282 eval {
5283 my $ra = (ref $self)->new($url);
5284 my $latest = $ra->get_latest_revnum;
5285 $ra->get_log("", $latest, 0, 1, 0, 1, sub {});
5287 } while ($@ && ($c = shift @components));
5288 $url;
5291 sub can_do_switch {
5292 my $self = shift;
5293 unless (defined $can_do_switch) {
5294 my $pool = SVN::Pool->new;
5295 my $rep = eval {
5296 $self->do_switch(1, '', 0, $self->{url},
5297 SVN::Delta::Editor->new, $pool);
5299 if ($@) {
5300 $can_do_switch = 0;
5301 } else {
5302 $rep->abort_report($pool);
5303 $can_do_switch = 1;
5305 $pool->clear;
5307 $can_do_switch;
5310 sub skip_unknown_revs {
5311 my ($err) = @_;
5312 my $errno = $err->apr_err();
5313 # Maybe the branch we're tracking didn't
5314 # exist when the repo started, so it's
5315 # not an error if it doesn't, just continue
5317 # Wonderfully consistent library, eh?
5318 # 160013 - svn:// and file://
5319 # 175002 - http(s)://
5320 # 175007 - http(s):// (this repo required authorization, too...)
5321 # More codes may be discovered later...
5322 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
5323 my $err_key = $err->expanded_message;
5324 # revision numbers change every time, filter them out
5325 $err_key =~ s/\d+/\0/g;
5326 $err_key = "$errno\0$err_key";
5327 unless ($ignored_err{$err_key}) {
5328 warn "W: Ignoring error from SVN, path probably ",
5329 "does not exist: ($errno): ",
5330 $err->expanded_message,"\n";
5331 warn "W: Do not be alarmed at the above message ",
5332 "git-svn is just searching aggressively for ",
5333 "old history.\n",
5334 "This may take a while on large repositories\n";
5335 $ignored_err{$err_key} = 1;
5337 return;
5339 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
5342 package Git::SVN::Log;
5343 use strict;
5344 use warnings;
5345 use POSIX qw/strftime/;
5346 use Time::Local;
5347 use constant commit_log_separator => ('-' x 72) . "\n";
5348 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
5349 %rusers $show_commit $incremental/;
5350 my $l_fmt;
5352 sub cmt_showable {
5353 my ($c) = @_;
5354 return 1 if defined $c->{r};
5356 # big commit message got truncated by the 16k pretty buffer in rev-list
5357 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
5358 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
5359 @{$c->{l}} = ();
5360 my @log = command(qw/cat-file commit/, $c->{c});
5362 # shift off the headers
5363 shift @log while ($log[0] ne '');
5364 shift @log;
5366 # TODO: make $c->{l} not have a trailing newline in the future
5367 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
5369 (undef, $c->{r}, undef) = ::extract_metadata(
5370 (grep(/^git-svn-id: /, @log))[-1]);
5372 return defined $c->{r};
5375 sub log_use_color {
5376 return $color || Git->repository->get_colorbool('color.diff');
5379 sub git_svn_log_cmd {
5380 my ($r_min, $r_max, @args) = @_;
5381 my $head = 'HEAD';
5382 my (@files, @log_opts);
5383 foreach my $x (@args) {
5384 if ($x eq '--' || @files) {
5385 push @files, $x;
5386 } else {
5387 if (::verify_ref("$x^0")) {
5388 $head = $x;
5389 } else {
5390 push @log_opts, $x;
5395 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
5396 $gs ||= Git::SVN->_new;
5397 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
5398 $gs->refname);
5399 push @cmd, '-r' unless $non_recursive;
5400 push @cmd, qw/--raw --name-status/ if $verbose;
5401 push @cmd, '--color' if log_use_color();
5402 push @cmd, @log_opts;
5403 if (defined $r_max && $r_max == $r_min) {
5404 push @cmd, '--max-count=1';
5405 if (my $c = $gs->rev_map_get($r_max)) {
5406 push @cmd, $c;
5408 } elsif (defined $r_max) {
5409 if ($r_max < $r_min) {
5410 ($r_min, $r_max) = ($r_max, $r_min);
5412 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
5413 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
5414 # If there are no commits in the range, both $c_max and $c_min
5415 # will be undefined. If there is at least 1 commit in the
5416 # range, both will be defined.
5417 return () if !defined $c_min || !defined $c_max;
5418 if ($c_min eq $c_max) {
5419 push @cmd, '--max-count=1', $c_min;
5420 } else {
5421 push @cmd, '--boundary', "$c_min..$c_max";
5424 return (@cmd, @files);
5427 # adapted from pager.c
5428 sub config_pager {
5429 chomp(my $pager = command_oneline(qw(var GIT_PAGER)));
5430 if ($pager eq 'cat') {
5431 $pager = undef;
5433 $ENV{GIT_PAGER_IN_USE} = defined($pager);
5436 sub run_pager {
5437 return unless -t *STDOUT && defined $pager;
5438 pipe my ($rfd, $wfd) or return;
5439 defined(my $pid = fork) or ::fatal "Can't fork: $!";
5440 if (!$pid) {
5441 open STDOUT, '>&', $wfd or
5442 ::fatal "Can't redirect to stdout: $!";
5443 return;
5445 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
5446 $ENV{LESS} ||= 'FRSX';
5447 exec $pager or ::fatal "Can't run pager: $! ($pager)";
5450 sub format_svn_date {
5451 # some systmes don't handle or mishandle %z, so be creative.
5452 my $t = shift || time;
5453 my $gm = timelocal(gmtime($t));
5454 my $sign = qw( + + - )[ $t <=> $gm ];
5455 my $gmoff = sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
5456 return strftime("%Y-%m-%d %H:%M:%S $gmoff (%a, %d %b %Y)", localtime($t));
5459 sub parse_git_date {
5460 my ($t, $tz) = @_;
5461 # Date::Parse isn't in the standard Perl distro :(
5462 if ($tz =~ s/^\+//) {
5463 $t += tz_to_s_offset($tz);
5464 } elsif ($tz =~ s/^\-//) {
5465 $t -= tz_to_s_offset($tz);
5467 return $t;
5470 sub set_local_timezone {
5471 if (defined $TZ) {
5472 $ENV{TZ} = $TZ;
5473 } else {
5474 delete $ENV{TZ};
5478 sub tz_to_s_offset {
5479 my ($tz) = @_;
5480 $tz =~ s/(\d\d)$//;
5481 return ($1 * 60) + ($tz * 3600);
5484 sub get_author_info {
5485 my ($dest, $author, $t, $tz) = @_;
5486 $author =~ s/(?:^\s*|\s*$)//g;
5487 $dest->{a_raw} = $author;
5488 my $au;
5489 if ($::_authors) {
5490 $au = $rusers{$author} || undef;
5492 if (!$au) {
5493 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
5495 $dest->{t} = $t;
5496 $dest->{tz} = $tz;
5497 $dest->{a} = $au;
5498 $dest->{t_utc} = parse_git_date($t, $tz);
5501 sub process_commit {
5502 my ($c, $r_min, $r_max, $defer) = @_;
5503 if (defined $r_min && defined $r_max) {
5504 if ($r_min == $c->{r} && $r_min == $r_max) {
5505 show_commit($c);
5506 return 0;
5508 return 1 if $r_min == $r_max;
5509 if ($r_min < $r_max) {
5510 # we need to reverse the print order
5511 return 0 if (defined $limit && --$limit < 0);
5512 push @$defer, $c;
5513 return 1;
5515 if ($r_min != $r_max) {
5516 return 1 if ($r_min < $c->{r});
5517 return 1 if ($r_max > $c->{r});
5520 return 0 if (defined $limit && --$limit < 0);
5521 show_commit($c);
5522 return 1;
5525 sub show_commit {
5526 my $c = shift;
5527 if ($oneline) {
5528 my $x = "\n";
5529 if (my $l = $c->{l}) {
5530 while ($l->[0] =~ /^\s*$/) { shift @$l }
5531 $x = $l->[0];
5533 $l_fmt ||= 'A' . length($c->{r});
5534 print 'r',pack($l_fmt, $c->{r}),' | ';
5535 print "$c->{c} | " if $show_commit;
5536 print $x;
5537 } else {
5538 show_commit_normal($c);
5542 sub show_commit_changed_paths {
5543 my ($c) = @_;
5544 return unless $c->{changed};
5545 print "Changed paths:\n", @{$c->{changed}};
5548 sub show_commit_normal {
5549 my ($c) = @_;
5550 print commit_log_separator, "r$c->{r} | ";
5551 print "$c->{c} | " if $show_commit;
5552 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
5553 my $nr_line = 0;
5555 if (my $l = $c->{l}) {
5556 while ($l->[$#$l] eq "\n" && $#$l > 0
5557 && $l->[($#$l - 1)] eq "\n") {
5558 pop @$l;
5560 $nr_line = scalar @$l;
5561 if (!$nr_line) {
5562 print "1 line\n\n\n";
5563 } else {
5564 if ($nr_line == 1) {
5565 $nr_line = '1 line';
5566 } else {
5567 $nr_line .= ' lines';
5569 print $nr_line, "\n";
5570 show_commit_changed_paths($c);
5571 print "\n";
5572 print $_ foreach @$l;
5574 } else {
5575 print "1 line\n";
5576 show_commit_changed_paths($c);
5577 print "\n";
5580 foreach my $x (qw/raw stat diff/) {
5581 if ($c->{$x}) {
5582 print "\n";
5583 print $_ foreach @{$c->{$x}}
5588 sub cmd_show_log {
5589 my (@args) = @_;
5590 my ($r_min, $r_max);
5591 my $r_last = -1; # prevent dupes
5592 set_local_timezone();
5593 if (defined $::_revision) {
5594 if ($::_revision =~ /^(\d+):(\d+)$/) {
5595 ($r_min, $r_max) = ($1, $2);
5596 } elsif ($::_revision =~ /^\d+$/) {
5597 $r_min = $r_max = $::_revision;
5598 } else {
5599 ::fatal "-r$::_revision is not supported, use ",
5600 "standard 'git log' arguments instead";
5604 config_pager();
5605 @args = git_svn_log_cmd($r_min, $r_max, @args);
5606 if (!@args) {
5607 print commit_log_separator unless $incremental || $oneline;
5608 return;
5610 my $log = command_output_pipe(@args);
5611 run_pager();
5612 my (@k, $c, $d, $stat);
5613 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
5614 while (<$log>) {
5615 if (/^${esc_color}commit -?($::sha1_short)/o) {
5616 my $cmt = $1;
5617 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
5618 $r_last = $c->{r};
5619 process_commit($c, $r_min, $r_max, \@k) or
5620 goto out;
5622 $d = undef;
5623 $c = { c => $cmt };
5624 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
5625 get_author_info($c, $1, $2, $3);
5626 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
5627 # ignore
5628 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
5629 push @{$c->{raw}}, $_;
5630 } elsif (/^${esc_color}[ACRMDT]\t/) {
5631 # we could add $SVN->{svn_path} here, but that requires
5632 # remote access at the moment (repo_path_split)...
5633 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
5634 push @{$c->{changed}}, $_;
5635 } elsif (/^${esc_color}diff /o) {
5636 $d = 1;
5637 push @{$c->{diff}}, $_;
5638 } elsif ($d) {
5639 push @{$c->{diff}}, $_;
5640 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
5641 $esc_color*[\+\-]*$esc_color$/x) {
5642 $stat = 1;
5643 push @{$c->{stat}}, $_;
5644 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
5645 push @{$c->{stat}}, $_;
5646 $stat = undef;
5647 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
5648 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
5649 } elsif (s/^${esc_color} //o) {
5650 push @{$c->{l}}, $_;
5653 if ($c && defined $c->{r} && $c->{r} != $r_last) {
5654 $r_last = $c->{r};
5655 process_commit($c, $r_min, $r_max, \@k);
5657 if (@k) {
5658 ($r_min, $r_max) = ($r_max, $r_min);
5659 process_commit($_, $r_min, $r_max) foreach reverse @k;
5661 out:
5662 close $log;
5663 print commit_log_separator unless $incremental || $oneline;
5666 sub cmd_blame {
5667 my $path = pop;
5669 config_pager();
5670 run_pager();
5672 my ($fh, $ctx, $rev);
5674 if ($_git_format) {
5675 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
5676 while (my $line = <$fh>) {
5677 if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
5678 # Uncommitted edits show up as a rev ID of
5679 # all zeros, which we can't look up with
5680 # cmt_metadata
5681 if ($1 !~ /^0+$/) {
5682 (undef, $rev, undef) =
5683 ::cmt_metadata($1);
5684 $rev = '0' if (!$rev);
5685 } else {
5686 $rev = '0';
5688 $rev = sprintf('%-10s', $rev);
5689 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
5691 print $line;
5693 } else {
5694 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
5695 '--', $path);
5696 my ($sha1);
5697 my %authors;
5698 my @buffer;
5699 my %dsha; #distinct sha keys
5701 while (my $line = <$fh>) {
5702 push @buffer, $line;
5703 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5704 $dsha{$1} = 1;
5708 my $s2r = ::cmt_sha2rev_batch([keys %dsha]);
5710 foreach my $line (@buffer) {
5711 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5712 $rev = $s2r->{$1};
5713 $rev = '0' if (!$rev)
5715 elsif ($line =~ /^author (.*)/) {
5716 $authors{$rev} = $1;
5717 $authors{$rev} =~ s/\s/_/g;
5719 elsif ($line =~ /^\t(.*)$/) {
5720 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
5724 command_close_pipe($fh, $ctx);
5727 package Git::SVN::Migration;
5728 # these version numbers do NOT correspond to actual version numbers
5729 # of git nor git-svn. They are just relative.
5731 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
5733 # v1 layout: .git/$id/info/url, refs/remotes/$id
5735 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
5737 # v3 layout: .git/svn/$id, refs/remotes/$id
5738 # - info/url may remain for backwards compatibility
5739 # - this is what we migrate up to this layout automatically,
5740 # - this will be used by git svn init on single branches
5741 # v3.1 layout (auto migrated):
5742 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
5743 # for backwards compatibility
5745 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
5746 # - this is only created for newly multi-init-ed
5747 # repositories. Similar in spirit to the
5748 # --use-separate-remotes option in git-clone (now default)
5749 # - we do not automatically migrate to this (following
5750 # the example set by core git)
5752 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
5753 # - newer, more-efficient format that uses 24-bytes per record
5754 # with no filler space.
5755 # - use xxd -c24 < .rev_map.$UUID to view and debug
5756 # - This is a one-way migration, repositories updated to the
5757 # new format will not be able to use old git-svn without
5758 # rebuilding the .rev_db. Rebuilding the rev_db is not
5759 # possible if noMetadata or useSvmProps are set; but should
5760 # be no problem for users that use the (sensible) defaults.
5761 use strict;
5762 use warnings;
5763 use Carp qw/croak/;
5764 use File::Path qw/mkpath/;
5765 use File::Basename qw/dirname basename/;
5766 use vars qw/$_minimize/;
5768 sub migrate_from_v0 {
5769 my $git_dir = $ENV{GIT_DIR};
5770 return undef unless -d $git_dir;
5771 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5772 my $migrated = 0;
5773 while (<$fh>) {
5774 chomp;
5775 my ($id, $orig_ref) = ($_, $_);
5776 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
5777 next unless -f "$git_dir/$id/info/url";
5778 my $new_ref = "refs/remotes/$id";
5779 if (::verify_ref("$new_ref^0")) {
5780 print STDERR "W: $orig_ref is probably an old ",
5781 "branch used by an ancient version of ",
5782 "git-svn.\n",
5783 "However, $new_ref also exists.\n",
5784 "We will not be able ",
5785 "to use this branch until this ",
5786 "ambiguity is resolved.\n";
5787 next;
5789 print STDERR "Migrating from v0 layout...\n" if !$migrated;
5790 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
5791 command_noisy('update-ref', $new_ref, $orig_ref);
5792 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
5793 $migrated++;
5795 command_close_pipe($fh, $ctx);
5796 print STDERR "Done migrating from v0 layout...\n" if $migrated;
5797 $migrated;
5800 sub migrate_from_v1 {
5801 my $git_dir = $ENV{GIT_DIR};
5802 my $migrated = 0;
5803 return $migrated unless -d $git_dir;
5804 my $svn_dir = "$git_dir/svn";
5806 # just in case somebody used 'svn' as their $id at some point...
5807 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
5809 print STDERR "Migrating from a git-svn v1 layout...\n";
5810 mkpath([$svn_dir]);
5811 print STDERR "Data from a previous version of git-svn exists, but\n\t",
5812 "$svn_dir\n\t(required for this version ",
5813 "($::VERSION) of git-svn) does not exist.\n";
5814 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5815 while (<$fh>) {
5816 my $x = $_;
5817 next unless $x =~ s#^refs/remotes/##;
5818 chomp $x;
5819 next unless -f "$git_dir/$x/info/url";
5820 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
5821 next unless $u;
5822 my $dn = dirname("$git_dir/svn/$x");
5823 mkpath([$dn]) unless -d $dn;
5824 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
5825 mkpath(["$git_dir/svn/svn"]);
5826 print STDERR " - $git_dir/$x/info => ",
5827 "$git_dir/svn/$x/info\n";
5828 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
5829 croak "$!: $x";
5830 # don't worry too much about these, they probably
5831 # don't exist with repos this old (save for index,
5832 # and we can easily regenerate that)
5833 foreach my $f (qw/unhandled.log index .rev_db/) {
5834 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
5836 } else {
5837 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
5838 rename "$git_dir/$x", "$git_dir/svn/$x" or
5839 croak "$!: $x";
5841 $migrated++;
5843 command_close_pipe($fh, $ctx);
5844 print STDERR "Done migrating from a git-svn v1 layout\n";
5845 $migrated;
5848 sub read_old_urls {
5849 my ($l_map, $pfx, $path) = @_;
5850 my @dir;
5851 foreach (<$path/*>) {
5852 if (-r "$_/info/url") {
5853 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
5854 my $ref_id = $pfx . basename $_;
5855 my $url = ::file_to_s("$_/info/url");
5856 $l_map->{$ref_id} = $url;
5857 } elsif (-d $_) {
5858 push @dir, $_;
5861 foreach (@dir) {
5862 my $x = $_;
5863 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
5864 read_old_urls($l_map, $x, $_);
5868 sub migrate_from_v2 {
5869 my @cfg = command(qw/config -l/);
5870 return if grep /^svn-remote\..+\.url=/, @cfg;
5871 my %l_map;
5872 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
5873 my $migrated = 0;
5875 foreach my $ref_id (sort keys %l_map) {
5876 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
5877 if ($@) {
5878 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
5880 $migrated++;
5882 $migrated;
5885 sub minimize_connections {
5886 my $r = Git::SVN::read_all_remotes();
5887 my $new_urls = {};
5888 my $root_repos = {};
5889 foreach my $repo_id (keys %$r) {
5890 my $url = $r->{$repo_id}->{url} or next;
5891 my $fetch = $r->{$repo_id}->{fetch} or next;
5892 my $ra = Git::SVN::Ra->new($url);
5894 # skip existing cases where we already connect to the root
5895 if (($ra->{url} eq $ra->{repos_root}) ||
5896 ($ra->{repos_root} eq $repo_id)) {
5897 $root_repos->{$ra->{url}} = $repo_id;
5898 next;
5901 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
5902 my $root_path = $ra->{url};
5903 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
5904 foreach my $path (keys %$fetch) {
5905 my $ref_id = $fetch->{$path};
5906 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
5908 # make sure we can read when connecting to
5909 # a higher level of a repository
5910 my ($last_rev, undef) = $gs->last_rev_commit;
5911 if (!defined $last_rev) {
5912 $last_rev = eval {
5913 $root_ra->get_latest_revnum;
5915 next if $@;
5917 my $new = $root_path;
5918 $new .= length $path ? "/$path" : '';
5919 eval {
5920 $root_ra->get_log([$new], $last_rev, $last_rev,
5921 0, 0, 1, sub { });
5923 next if $@;
5924 $new_urls->{$ra->{repos_root}}->{$new} =
5925 { ref_id => $ref_id,
5926 old_repo_id => $repo_id,
5927 old_path => $path };
5931 my @emptied;
5932 foreach my $url (keys %$new_urls) {
5933 # see if we can re-use an existing [svn-remote "repo_id"]
5934 # instead of creating a(n ugly) new section:
5935 my $repo_id = $root_repos->{$url} || $url;
5937 my $fetch = $new_urls->{$url};
5938 foreach my $path (keys %$fetch) {
5939 my $x = $fetch->{$path};
5940 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
5941 my $pfx = "svn-remote.$x->{old_repo_id}";
5943 my $old_fetch = quotemeta("$x->{old_path}:".
5944 "$x->{ref_id}");
5945 command_noisy(qw/config --unset/,
5946 "$pfx.fetch", '^'. $old_fetch . '$');
5947 delete $r->{$x->{old_repo_id}}->
5948 {fetch}->{$x->{old_path}};
5949 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
5950 command_noisy(qw/config --unset/,
5951 "$pfx.url");
5952 push @emptied, $x->{old_repo_id}
5956 if (@emptied) {
5957 my $file = $ENV{GIT_CONFIG} || "$ENV{GIT_DIR}/config";
5958 print STDERR <<EOF;
5959 The following [svn-remote] sections in your config file ($file) are empty
5960 and can be safely removed:
5962 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
5966 sub migration_check {
5967 migrate_from_v0();
5968 migrate_from_v1();
5969 migrate_from_v2();
5970 minimize_connections() if $_minimize;
5973 package Git::IndexInfo;
5974 use strict;
5975 use warnings;
5976 use Git qw/command_input_pipe command_close_pipe/;
5978 sub new {
5979 my ($class) = @_;
5980 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
5981 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
5984 sub remove {
5985 my ($self, $path) = @_;
5986 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
5987 return ++$self->{nr};
5989 undef;
5992 sub update {
5993 my ($self, $mode, $hash, $path) = @_;
5994 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
5995 return ++$self->{nr};
5997 undef;
6000 sub DESTROY {
6001 my ($self) = @_;
6002 command_close_pipe($self->{gui}, $self->{ctx});
6005 package Git::SVN::GlobSpec;
6006 use strict;
6007 use warnings;
6009 sub new {
6010 my ($class, $glob, $pattern_ok) = @_;
6011 my $re = $glob;
6012 $re =~ s!/+$!!g; # no need for trailing slashes
6013 my (@left, @right, @patterns);
6014 my $state = "left";
6015 my $die_msg = "Only one set of wildcard directories " .
6016 "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
6017 for my $part (split(m|/|, $glob)) {
6018 if ($part =~ /\*/ && $part ne "*") {
6019 die "Invalid pattern in '$glob': $part\n";
6020 } elsif ($pattern_ok && $part =~ /[{}]/ &&
6021 $part !~ /^\{[^{}]+\}/) {
6022 die "Invalid pattern in '$glob': $part\n";
6024 if ($part eq "*") {
6025 die $die_msg if $state eq "right";
6026 $state = "pattern";
6027 push(@patterns, "[^/]*");
6028 } elsif ($pattern_ok && $part =~ /^\{(.*)\}$/) {
6029 die $die_msg if $state eq "right";
6030 $state = "pattern";
6031 my $p = quotemeta($1);
6032 $p =~ s/\\,/|/g;
6033 push(@patterns, "(?:$p)");
6034 } else {
6035 if ($state eq "left") {
6036 push(@left, $part);
6037 } else {
6038 push(@right, $part);
6039 $state = "right";
6043 my $depth = @patterns;
6044 if ($depth == 0) {
6045 die "One '*' is needed in glob: '$glob'\n";
6047 my $left = join('/', @left);
6048 my $right = join('/', @right);
6049 $re = join('/', @patterns);
6050 $re = join('\/',
6051 grep(length, quotemeta($left), "($re)", quotemeta($right)));
6052 my $left_re = qr/^\/\Q$left\E(\/|$)/;
6053 bless { left => $left, right => $right, left_regex => $left_re,
6054 regex => qr/$re/, glob => $glob, depth => $depth }, $class;
6057 sub full_path {
6058 my ($self, $path) = @_;
6059 return (length $self->{left} ? "$self->{left}/" : '') .
6060 $path . (length $self->{right} ? "/$self->{right}" : '');
6063 __END__
6065 Data structures:
6068 $remotes = { # returned by read_all_remotes()
6069 'svn' => {
6070 # svn-remote.svn.url=https://svn.musicpd.org
6071 url => 'https://svn.musicpd.org',
6072 # svn-remote.svn.fetch=mpd/trunk:trunk
6073 fetch => {
6074 'mpd/trunk' => 'trunk',
6076 # svn-remote.svn.tags=mpd/tags/*:tags/*
6077 tags => {
6078 path => {
6079 left => 'mpd/tags',
6080 right => '',
6081 regex => qr!mpd/tags/([^/]+)$!,
6082 glob => 'tags/*',
6084 ref => {
6085 left => 'tags',
6086 right => '',
6087 regex => qr!tags/([^/]+)$!,
6088 glob => 'tags/*',
6094 $log_entry hashref as returned by libsvn_log_entry()
6096 log => 'whitespace-formatted log entry
6097 ', # trailing newline is preserved
6098 revision => '8', # integer
6099 date => '2004-02-24T17:01:44.108345Z', # commit date
6100 author => 'committer name'
6104 # this is generated by generate_diff();
6105 @mods = array of diff-index line hashes, each element represents one line
6106 of diff-index output
6108 diff-index line ($m hash)
6110 mode_a => first column of diff-index output, no leading ':',
6111 mode_b => second column of diff-index output,
6112 sha1_b => sha1sum of the final blob,
6113 chg => change type [MCRADT],
6114 file_a => original file name of a file (iff chg is 'C' or 'R')
6115 file_b => new/current file name of a file (any chg)
6119 # retval of read_url_paths{,_all}();
6120 $l_map = {
6121 # repository root url
6122 'https://svn.musicpd.org' => {
6123 # repository path # GIT_SVN_ID
6124 'mpd/trunk' => 'trunk',
6125 'mpd/tags/0.11.5' => 'tags/0.11.5',
6129 Notes:
6130 I don't trust the each() function on unless I created %hash myself
6131 because the internal iterator may not have started at base.