Merge branch 'ao/send-email-irt'
[git/kirr.git] / git-svn.perl
blob757de82161e05b9d12c489efeff05c7fec341fe4
1 #!/usr/bin/env perl
2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
4 use 5.008;
5 use warnings;
6 use strict;
7 use vars qw/ $AUTHOR $VERSION
8 $sha1 $sha1_short $_revision $_repository
9 $_q $_authors $_authors_prog %users/;
10 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
11 $VERSION = '@@GIT_VERSION@@';
13 # From which subdir have we been invoked?
14 my $cmd_dir_prefix = eval {
15 command_oneline([qw/rev-parse --show-prefix/], STDERR => 0)
16 } || '';
18 my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
19 $ENV{GIT_DIR} ||= '.git';
20 $Git::SVN::default_repo_id = 'svn';
21 $Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
22 $Git::SVN::Ra::_log_window_size = 100;
23 $Git::SVN::_minimize_url = 'unset';
25 if (! exists $ENV{SVN_SSH}) {
26 if (exists $ENV{GIT_SSH}) {
27 $ENV{SVN_SSH} = $ENV{GIT_SSH};
28 if ($^O eq 'msys') {
29 $ENV{SVN_SSH} =~ s/\\/\\\\/g;
30 $ENV{SVN_SSH} =~ s/(.*)/"$1"/;
35 $Git::SVN::Log::TZ = $ENV{TZ};
36 $ENV{TZ} = 'UTC';
37 $| = 1; # unbuffer STDOUT
39 sub fatal (@) { print STDERR "@_\n"; exit 1 }
40 sub _req_svn {
41 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
42 require SVN::Ra;
43 require SVN::Delta;
44 if ($SVN::Core::VERSION lt '1.1.0') {
45 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
48 my $can_compress = eval { require Compress::Zlib; 1};
49 push @Git::SVN::Ra::ISA, 'SVN::Ra';
50 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
51 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
52 use Carp qw/croak/;
53 use Digest::MD5;
54 use IO::File qw//;
55 use File::Basename qw/dirname basename/;
56 use File::Path qw/mkpath/;
57 use File::Spec;
58 use File::Find;
59 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
60 use IPC::Open3;
61 use Git;
63 BEGIN {
64 # import functions from Git into our packages, en masse
65 no strict 'refs';
66 foreach (qw/command command_oneline command_noisy command_output_pipe
67 command_input_pipe command_close_pipe
68 command_bidi_pipe command_close_bidi_pipe/) {
69 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
70 Git::SVN::Migration Git::SVN::Log Git::SVN),
71 __PACKAGE__) {
72 *{"${package}::$_"} = \&{"Git::$_"};
77 my ($SVN);
79 $sha1 = qr/[a-f\d]{40}/;
80 $sha1_short = qr/[a-f\d]{4,40}/;
81 my ($_stdin, $_help, $_edit,
82 $_message, $_file, $_branch_dest,
83 $_template, $_shared,
84 $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
85 $_merge, $_strategy, $_dry_run, $_local,
86 $_prefix, $_no_checkout, $_url, $_verbose,
87 $_git_format, $_commit_url, $_tag);
88 $Git::SVN::_follow_parent = 1;
89 $_q ||= 0;
90 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
91 'config-dir=s' => \$Git::SVN::Ra::config_dir,
92 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
93 'ignore-paths=s' => \$SVN::Git::Fetcher::_ignore_regex );
94 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
95 'authors-file|A=s' => \$_authors,
96 'authors-prog=s' => \$_authors_prog,
97 'repack:i' => \$Git::SVN::_repack,
98 'noMetadata' => \$Git::SVN::_no_metadata,
99 'useSvmProps' => \$Git::SVN::_use_svm_props,
100 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
101 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
102 'no-checkout' => \$_no_checkout,
103 'quiet|q+' => \$_q,
104 'repack-flags|repack-args|repack-opts=s' =>
105 \$Git::SVN::_repack_flags,
106 'use-log-author' => \$Git::SVN::_use_log_author,
107 'add-author-from' => \$Git::SVN::_add_author_from,
108 'localtime' => \$Git::SVN::_localtime,
109 %remote_opts );
111 my ($_trunk, @_tags, @_branches, $_stdlayout);
112 my %icv;
113 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
114 'trunk|T=s' => \$_trunk, 'tags|t=s@' => \@_tags,
115 'branches|b=s@' => \@_branches, 'prefix=s' => \$_prefix,
116 'stdlayout|s' => \$_stdlayout,
117 'minimize-url|m!' => \$Git::SVN::_minimize_url,
118 'no-metadata' => sub { $icv{noMetadata} = 1 },
119 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
120 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
121 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
122 'rewrite-uuid=s' => sub { $icv{rewriteUUID} = $_[1] },
123 %remote_opts );
124 my %cmt_opts = ( 'edit|e' => \$_edit,
125 'rmdir' => \$SVN::Git::Editor::_rmdir,
126 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
127 'l=i' => \$SVN::Git::Editor::_rename_limit,
128 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
131 my %cmd = (
132 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
133 { 'revision|r=s' => \$_revision,
134 'fetch-all|all' => \$_fetch_all,
135 'parent|p' => \$_fetch_parent,
136 %fc_opts } ],
137 clone => [ \&cmd_clone, "Initialize and fetch revisions",
138 { 'revision|r=s' => \$_revision,
139 %fc_opts, %init_opts } ],
140 init => [ \&cmd_init, "Initialize a repo for tracking" .
141 " (requires URL argument)",
142 \%init_opts ],
143 'multi-init' => [ \&cmd_multi_init,
144 "Deprecated alias for ".
145 "'$0 init -T<trunk> -b<branches> -t<tags>'",
146 \%init_opts ],
147 dcommit => [ \&cmd_dcommit,
148 'Commit several diffs to merge with upstream',
149 { 'merge|m|M' => \$_merge,
150 'strategy|s=s' => \$_strategy,
151 'verbose|v' => \$_verbose,
152 'dry-run|n' => \$_dry_run,
153 'fetch-all|all' => \$_fetch_all,
154 'commit-url=s' => \$_commit_url,
155 'revision|r=i' => \$_revision,
156 'no-rebase' => \$_no_rebase,
157 %cmt_opts, %fc_opts } ],
158 branch => [ \&cmd_branch,
159 'Create a branch in the SVN repository',
160 { 'message|m=s' => \$_message,
161 'destination|d=s' => \$_branch_dest,
162 'dry-run|n' => \$_dry_run,
163 'tag|t' => \$_tag,
164 'username=s' => \$Git::SVN::Prompt::_username,
165 'commit-url=s' => \$_commit_url } ],
166 tag => [ sub { $_tag = 1; cmd_branch(@_) },
167 'Create a tag in the SVN repository',
168 { 'message|m=s' => \$_message,
169 'destination|d=s' => \$_branch_dest,
170 'dry-run|n' => \$_dry_run,
171 'username=s' => \$Git::SVN::Prompt::_username,
172 'commit-url=s' => \$_commit_url } ],
173 'set-tree' => [ \&cmd_set_tree,
174 "Set an SVN repository to a git tree-ish",
175 { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
176 'create-ignore' => [ \&cmd_create_ignore,
177 'Create a .gitignore per svn:ignore',
178 { 'revision|r=i' => \$_revision
179 } ],
180 'mkdirs' => [ \&cmd_mkdirs ,
181 "recreate empty directories after a checkout",
182 { 'revision|r=i' => \$_revision } ],
183 'propget' => [ \&cmd_propget,
184 'Print the value of a property on a file or directory',
185 { 'revision|r=i' => \$_revision } ],
186 'proplist' => [ \&cmd_proplist,
187 'List all properties of a file or directory',
188 { 'revision|r=i' => \$_revision } ],
189 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
190 { 'revision|r=i' => \$_revision
191 } ],
192 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
193 { 'revision|r=i' => \$_revision
194 } ],
195 'multi-fetch' => [ \&cmd_multi_fetch,
196 "Deprecated alias for $0 fetch --all",
197 { 'revision|r=s' => \$_revision, %fc_opts } ],
198 'migrate' => [ sub { },
199 # no-op, we automatically run this anyways,
200 'Migrate configuration/metadata/layout from
201 previous versions of git-svn',
202 { 'minimize' => \$Git::SVN::Migration::_minimize,
203 %remote_opts } ],
204 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
205 { 'limit=i' => \$Git::SVN::Log::limit,
206 'revision|r=s' => \$_revision,
207 'verbose|v' => \$Git::SVN::Log::verbose,
208 'incremental' => \$Git::SVN::Log::incremental,
209 'oneline' => \$Git::SVN::Log::oneline,
210 'show-commit' => \$Git::SVN::Log::show_commit,
211 'non-recursive' => \$Git::SVN::Log::non_recursive,
212 'authors-file|A=s' => \$_authors,
213 'color' => \$Git::SVN::Log::color,
214 'pager=s' => \$Git::SVN::Log::pager
215 } ],
216 'find-rev' => [ \&cmd_find_rev,
217 "Translate between SVN revision numbers and tree-ish",
218 {} ],
219 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
220 { 'merge|m|M' => \$_merge,
221 'verbose|v' => \$_verbose,
222 'strategy|s=s' => \$_strategy,
223 'local|l' => \$_local,
224 'fetch-all|all' => \$_fetch_all,
225 'dry-run|n' => \$_dry_run,
226 %fc_opts } ],
227 'commit-diff' => [ \&cmd_commit_diff,
228 'Commit a diff between two trees',
229 { 'message|m=s' => \$_message,
230 'file|F=s' => \$_file,
231 'revision|r=s' => \$_revision,
232 %cmt_opts } ],
233 'info' => [ \&cmd_info,
234 "Show info about the latest SVN revision
235 on the current branch",
236 { 'url' => \$_url, } ],
237 'blame' => [ \&Git::SVN::Log::cmd_blame,
238 "Show what revision and author last modified each line of a file",
239 { 'git-format' => \$_git_format } ],
240 'reset' => [ \&cmd_reset,
241 "Undo fetches back to the specified SVN revision",
242 { 'revision|r=s' => \$_revision,
243 'parent|p' => \$_fetch_parent } ],
244 'gc' => [ \&cmd_gc,
245 "Compress unhandled.log files in .git/svn and remove " .
246 "index files in .git/svn",
247 {} ],
250 my $cmd;
251 for (my $i = 0; $i < @ARGV; $i++) {
252 if (defined $cmd{$ARGV[$i]}) {
253 $cmd = $ARGV[$i];
254 splice @ARGV, $i, 1;
255 last;
256 } elsif ($ARGV[$i] eq 'help') {
257 $cmd = $ARGV[$i+1];
258 usage(0);
262 # make sure we're always running at the top-level working directory
263 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
264 unless (-d $ENV{GIT_DIR}) {
265 if ($git_dir_user_set) {
266 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
267 "but it is not a directory\n";
269 my $git_dir = delete $ENV{GIT_DIR};
270 my $cdup = undef;
271 git_cmd_try {
272 $cdup = command_oneline(qw/rev-parse --show-cdup/);
273 $git_dir = '.' unless ($cdup);
274 chomp $cdup if ($cdup);
275 $cdup = "." unless ($cdup && length $cdup);
276 } "Already at toplevel, but $git_dir not found\n";
277 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
278 unless (-d $git_dir) {
279 die "$git_dir still not found after going to ",
280 "'$cdup'\n";
282 $ENV{GIT_DIR} = $git_dir;
284 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
287 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
289 read_git_config(\%opts);
290 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
291 Getopt::Long::Configure('pass_through');
293 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
294 'minimize-connections' => \$Git::SVN::Migration::_minimize,
295 'id|i=s' => \$Git::SVN::default_ref_id,
296 'svn-remote|remote|R=s' => sub {
297 $Git::SVN::no_reuse_existing = 1;
298 $Git::SVN::default_repo_id = $_[1] });
299 exit 1 if (!$rv && $cmd && $cmd ne 'log');
301 usage(0) if $_help;
302 version() if $_version;
303 usage(1) unless defined $cmd;
304 load_authors() if $_authors;
305 if (defined $_authors_prog) {
306 $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
309 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
310 Git::SVN::Migration::migration_check();
312 Git::SVN::init_vars();
313 eval {
314 Git::SVN::verify_remotes_sanity();
315 $cmd{$cmd}->[0]->(@ARGV);
317 fatal $@ if $@;
318 post_fetch_checkout();
319 exit 0;
321 ####################### primary functions ######################
322 sub usage {
323 my $exit = shift || 0;
324 my $fd = $exit ? \*STDERR : \*STDOUT;
325 print $fd <<"";
326 git-svn - bidirectional operations between a single Subversion tree and git
327 Usage: git svn <command> [options] [arguments]\n
329 print $fd "Available commands:\n" unless $cmd;
331 foreach (sort keys %cmd) {
332 next if $cmd && $cmd ne $_;
333 next if /^multi-/; # don't show deprecated commands
334 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
335 foreach (sort keys %{$cmd{$_}->[2]}) {
336 # mixed-case options are for .git/config only
337 next if /[A-Z]/ && /^[a-z]+$/i;
338 # prints out arguments as they should be passed:
339 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
340 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
341 "--$_" : "-$_" }
342 split /\|/,$_)," $x\n";
345 print $fd <<"";
346 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
347 arbitrary identifier if you're tracking multiple SVN branches/repositories in
348 one git repository and want to keep them separate. See git-svn(1) for more
349 information.
351 exit $exit;
354 sub version {
355 ::_req_svn();
356 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
357 exit 0;
360 sub do_git_init_db {
361 unless (-d $ENV{GIT_DIR}) {
362 my @init_db = ('init');
363 push @init_db, "--template=$_template" if defined $_template;
364 if (defined $_shared) {
365 if ($_shared =~ /[a-z]/) {
366 push @init_db, "--shared=$_shared";
367 } else {
368 push @init_db, "--shared";
371 command_noisy(@init_db);
372 $_repository = Git->repository(Repository => ".git");
374 my $set;
375 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
376 foreach my $i (keys %icv) {
377 die "'$set' and '$i' cannot both be set\n" if $set;
378 next unless defined $icv{$i};
379 command_noisy('config', "$pfx.$i", $icv{$i});
380 $set = $i;
382 my $ignore_regex = \$SVN::Git::Fetcher::_ignore_regex;
383 command_noisy('config', "$pfx.ignore-paths", $$ignore_regex)
384 if defined $$ignore_regex;
387 sub init_subdir {
388 my $repo_path = shift or return;
389 mkpath([$repo_path]) unless -d $repo_path;
390 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
391 $ENV{GIT_DIR} = '.git';
392 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
395 sub cmd_clone {
396 my ($url, $path) = @_;
397 if (!defined $path &&
398 (defined $_trunk || @_branches || @_tags ||
399 defined $_stdlayout) &&
400 $url !~ m#^[a-z\+]+://#) {
401 $path = $url;
403 $path = basename($url) if !defined $path || !length $path;
404 my $authors_absolute = $_authors ? File::Spec->rel2abs($_authors) : "";
405 cmd_init($url, $path);
406 command_oneline('config', 'svn.authorsfile', $authors_absolute)
407 if $_authors;
408 Git::SVN::fetch_all($Git::SVN::default_repo_id);
411 sub cmd_init {
412 if (defined $_stdlayout) {
413 $_trunk = 'trunk' if (!defined $_trunk);
414 @_tags = 'tags' if (! @_tags);
415 @_branches = 'branches' if (! @_branches);
417 if (defined $_trunk || @_branches || @_tags) {
418 return cmd_multi_init(@_);
420 my $url = shift or die "SVN repository location required ",
421 "as a command-line argument\n";
422 $url = canonicalize_url($url);
423 init_subdir(@_);
424 do_git_init_db();
426 if ($Git::SVN::_minimize_url eq 'unset') {
427 $Git::SVN::_minimize_url = 0;
430 Git::SVN->init($url);
433 sub cmd_fetch {
434 if (grep /^\d+=./, @_) {
435 die "'<rev>=<commit>' fetch arguments are ",
436 "no longer supported.\n";
438 my ($remote) = @_;
439 if (@_ > 1) {
440 die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
442 $Git::SVN::no_reuse_existing = undef;
443 if ($_fetch_parent) {
444 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
445 unless ($gs) {
446 die "Unable to determine upstream SVN information from ",
447 "working tree history\n";
449 # just fetch, don't checkout.
450 $_no_checkout = 'true';
451 $_fetch_all ? $gs->fetch_all : $gs->fetch;
452 } elsif ($_fetch_all) {
453 cmd_multi_fetch();
454 } else {
455 $remote ||= $Git::SVN::default_repo_id;
456 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
460 sub cmd_set_tree {
461 my (@commits) = @_;
462 if ($_stdin || !@commits) {
463 print "Reading from stdin...\n";
464 @commits = ();
465 while (<STDIN>) {
466 if (/\b($sha1_short)\b/o) {
467 unshift @commits, $1;
471 my @revs;
472 foreach my $c (@commits) {
473 my @tmp = command('rev-parse',$c);
474 if (scalar @tmp == 1) {
475 push @revs, $tmp[0];
476 } elsif (scalar @tmp > 1) {
477 push @revs, reverse(command('rev-list',@tmp));
478 } else {
479 fatal "Failed to rev-parse $c";
482 my $gs = Git::SVN->new;
483 my ($r_last, $cmt_last) = $gs->last_rev_commit;
484 $gs->fetch;
485 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
486 fatal "There are new revisions that were fetched ",
487 "and need to be merged (or acknowledged) ",
488 "before committing.\nlast rev: $r_last\n",
489 " current: $gs->{last_rev}";
491 $gs->set_tree($_) foreach @revs;
492 print "Done committing ",scalar @revs," revisions to SVN\n";
493 unlink $gs->{index};
496 sub cmd_dcommit {
497 my $head = shift;
498 command_noisy(qw/update-index --refresh/);
499 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
500 'Cannot dcommit with a dirty index. Commit your changes first, '
501 . "or stash them with `git stash'.\n";
502 $head ||= 'HEAD';
504 my $old_head;
505 if ($head ne 'HEAD') {
506 $old_head = eval {
507 command_oneline([qw/symbolic-ref -q HEAD/])
509 if ($old_head) {
510 $old_head =~ s{^refs/heads/}{};
511 } else {
512 $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
514 command(['checkout', $head], STDERR => 0);
517 my @refs;
518 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
519 unless ($gs) {
520 die "Unable to determine upstream SVN information from ",
521 "$head history.\nPerhaps the repository is empty.";
524 if (defined $_commit_url) {
525 $url = $_commit_url;
526 } else {
527 $url = eval { command_oneline('config', '--get',
528 "svn-remote.$gs->{repo_id}.commiturl") };
529 if (!$url) {
530 $url = $gs->full_url
534 my $last_rev = $_revision if defined $_revision;
535 if ($url) {
536 print "Committing to $url ...\n";
538 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
539 if ($_no_rebase && scalar(@$linear_refs) > 1) {
540 warn "Attempting to commit more than one change while ",
541 "--no-rebase is enabled.\n",
542 "If these changes depend on each other, re-running ",
543 "without --no-rebase may be required."
545 my $expect_url = $url;
546 Git::SVN::remove_username($expect_url);
547 while (1) {
548 my $d = shift @$linear_refs or last;
549 unless (defined $last_rev) {
550 (undef, $last_rev, undef) = cmt_metadata("$d~1");
551 unless (defined $last_rev) {
552 fatal "Unable to extract revision information ",
553 "from commit $d~1";
556 if ($_dry_run) {
557 print "diff-tree $d~1 $d\n";
558 } else {
559 my $cmt_rev;
560 my %ed_opts = ( r => $last_rev,
561 log => get_commit_entry($d)->{log},
562 ra => Git::SVN::Ra->new($url),
563 config => SVN::Core::config_get_config(
564 $Git::SVN::Ra::config_dir
566 tree_a => "$d~1",
567 tree_b => $d,
568 editor_cb => sub {
569 print "Committed r$_[0]\n";
570 $cmt_rev = $_[0];
572 svn_path => '');
573 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
574 print "No changes\n$d~1 == $d\n";
575 } elsif ($parents->{$d} && @{$parents->{$d}}) {
576 $gs->{inject_parents_dcommit}->{$cmt_rev} =
577 $parents->{$d};
579 $_fetch_all ? $gs->fetch_all : $gs->fetch;
580 $last_rev = $cmt_rev;
581 next if $_no_rebase;
583 # we always want to rebase against the current HEAD,
584 # not any head that was passed to us
585 my @diff = command('diff-tree', $d,
586 $gs->refname, '--');
587 my @finish;
588 if (@diff) {
589 @finish = rebase_cmd();
590 print STDERR "W: $d and ", $gs->refname,
591 " differ, using @finish:\n",
592 join("\n", @diff), "\n";
593 } else {
594 print "No changes between current HEAD and ",
595 $gs->refname,
596 "\nResetting to the latest ",
597 $gs->refname, "\n";
598 @finish = qw/reset --mixed/;
600 command_noisy(@finish, $gs->refname);
601 if (@diff) {
602 @refs = ();
603 my ($url_, $rev_, $uuid_, $gs_) =
604 working_head_info('HEAD', \@refs);
605 my ($linear_refs_, $parents_) =
606 linearize_history($gs_, \@refs);
607 if (scalar(@$linear_refs) !=
608 scalar(@$linear_refs_)) {
609 fatal "# of revisions changed ",
610 "\nbefore:\n",
611 join("\n", @$linear_refs),
612 "\n\nafter:\n",
613 join("\n", @$linear_refs_), "\n",
614 'If you are attempting to commit ',
615 "merges, try running:\n\t",
616 'git rebase --interactive',
617 '--preserve-merges ',
618 $gs->refname,
619 "\nBefore dcommitting";
621 if ($url_ ne $expect_url) {
622 if ($url_ eq $gs->metadata_url) {
623 print
624 "Accepting rewritten URL:",
625 " $url_\n";
626 } else {
627 fatal
628 "URL mismatch after rebase:",
629 " $url_ != $expect_url";
632 if ($uuid_ ne $uuid) {
633 fatal "uuid mismatch after rebase: ",
634 "$uuid_ != $uuid";
636 # remap parents
637 my (%p, @l, $i);
638 for ($i = 0; $i < scalar @$linear_refs; $i++) {
639 my $new = $linear_refs_->[$i] or next;
640 $p{$new} =
641 $parents->{$linear_refs->[$i]};
642 push @l, $new;
644 $parents = \%p;
645 $linear_refs = \@l;
650 if ($old_head) {
651 my $new_head = command_oneline(qw/rev-parse HEAD/);
652 my $new_is_symbolic = eval {
653 command_oneline(qw/symbolic-ref -q HEAD/);
655 if ($new_is_symbolic) {
656 print "dcommitted the branch ", $head, "\n";
657 } else {
658 print "dcommitted on a detached HEAD because you gave ",
659 "a revision argument.\n",
660 "The rewritten commit is: ", $new_head, "\n";
662 command(['checkout', $old_head], STDERR => 0);
665 unlink $gs->{index};
668 sub cmd_branch {
669 my ($branch_name, $head) = @_;
671 unless (defined $branch_name && length $branch_name) {
672 die(($_tag ? "tag" : "branch") . " name required\n");
674 $head ||= 'HEAD';
676 my (undef, $rev, undef, $gs) = working_head_info($head);
677 my $src = $gs->full_url;
679 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
680 my $allglobs = $remote->{ $_tag ? 'tags' : 'branches' };
681 my $glob;
682 if ($#{$allglobs} == 0) {
683 $glob = $allglobs->[0];
684 } else {
685 unless(defined $_branch_dest) {
686 die "Multiple ",
687 $_tag ? "tag" : "branch",
688 " paths defined for Subversion repository.\n",
689 "You must specify where you want to create the ",
690 $_tag ? "tag" : "branch",
691 " with the --destination argument.\n";
693 foreach my $g (@{$allglobs}) {
694 # SVN::Git::Editor could probably be moved to Git.pm..
695 my $re = SVN::Git::Editor::glob2pat($g->{path}->{left});
696 if ($_branch_dest =~ /$re/) {
697 $glob = $g;
698 last;
701 unless (defined $glob) {
702 my $dest_re = qr/\b\Q$_branch_dest\E\b/;
703 foreach my $g (@{$allglobs}) {
704 $g->{path}->{left} =~ /$dest_re/ or next;
705 if (defined $glob) {
706 die "Ambiguous destination: ",
707 $_branch_dest, "\nmatches both '",
708 $glob->{path}->{left}, "' and '",
709 $g->{path}->{left}, "'\n";
711 $glob = $g;
713 unless (defined $glob) {
714 die "Unknown ",
715 $_tag ? "tag" : "branch",
716 " destination $_branch_dest\n";
720 my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
721 my $url;
722 if (defined $_commit_url) {
723 $url = $_commit_url;
724 } else {
725 $url = eval { command_oneline('config', '--get',
726 "svn-remote.$gs->{repo_id}.commiturl") };
727 if (!$url) {
728 $url = $remote->{url};
731 my $dst = join '/', $url, $lft, $branch_name, ($rgt || ());
733 if ($dst =~ /^https:/ && $src =~ /^http:/) {
734 $src=~s/^http:/https:/;
737 ::_req_svn();
739 my $ctx = SVN::Client->new(
740 auth => Git::SVN::Ra::_auth_providers(),
741 log_msg => sub {
742 ${ $_[0] } = defined $_message
743 ? $_message
744 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
745 . $branch_name;
749 eval {
750 $ctx->ls($dst, 'HEAD', 0);
751 } and die "branch ${branch_name} already exists\n";
753 print "Copying ${src} at r${rev} to ${dst}...\n";
754 $ctx->copy($src, $rev, $dst)
755 unless $_dry_run;
757 $gs->fetch_all;
760 sub cmd_find_rev {
761 my $revision_or_hash = shift or die "SVN or git revision required ",
762 "as a command-line argument\n";
763 my $result;
764 if ($revision_or_hash =~ /^r\d+$/) {
765 my $head = shift;
766 $head ||= 'HEAD';
767 my @refs;
768 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
769 unless ($gs) {
770 die "Unable to determine upstream SVN information from ",
771 "$head history\n";
773 my $desired_revision = substr($revision_or_hash, 1);
774 $result = $gs->rev_map_get($desired_revision, $uuid);
775 } else {
776 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
777 $result = $rev;
779 print "$result\n" if $result;
782 sub cmd_rebase {
783 command_noisy(qw/update-index --refresh/);
784 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
785 unless ($gs) {
786 die "Unable to determine upstream SVN information from ",
787 "working tree history\n";
789 if ($_dry_run) {
790 print "Remote Branch: " . $gs->refname . "\n";
791 print "SVN URL: " . $url . "\n";
792 return;
794 if (command(qw/diff-index HEAD --/)) {
795 print STDERR "Cannot rebase with uncommited changes:\n";
796 command_noisy('status');
797 exit 1;
799 unless ($_local) {
800 # rebase will checkout for us, so no need to do it explicitly
801 $_no_checkout = 'true';
802 $_fetch_all ? $gs->fetch_all : $gs->fetch;
804 command_noisy(rebase_cmd(), $gs->refname);
805 $gs->mkemptydirs;
808 sub cmd_show_ignore {
809 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
810 $gs ||= Git::SVN->new;
811 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
812 $gs->prop_walk($gs->{path}, $r, sub {
813 my ($gs, $path, $props) = @_;
814 print STDOUT "\n# $path\n";
815 my $s = $props->{'svn:ignore'} or return;
816 $s =~ s/[\r\n]+/\n/g;
817 $s =~ s/^\n+//;
818 chomp $s;
819 $s =~ s#^#$path#gm;
820 print STDOUT "$s\n";
824 sub cmd_show_externals {
825 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
826 $gs ||= Git::SVN->new;
827 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
828 $gs->prop_walk($gs->{path}, $r, sub {
829 my ($gs, $path, $props) = @_;
830 print STDOUT "\n# $path\n";
831 my $s = $props->{'svn:externals'} or return;
832 $s =~ s/[\r\n]+/\n/g;
833 chomp $s;
834 $s =~ s#^#$path#gm;
835 print STDOUT "$s\n";
839 sub cmd_create_ignore {
840 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
841 $gs ||= Git::SVN->new;
842 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
843 $gs->prop_walk($gs->{path}, $r, sub {
844 my ($gs, $path, $props) = @_;
845 # $path is of the form /path/to/dir/
846 $path = '.' . $path;
847 # SVN can have attributes on empty directories,
848 # which git won't track
849 mkpath([$path]) unless -d $path;
850 my $ignore = $path . '.gitignore';
851 my $s = $props->{'svn:ignore'} or return;
852 open(GITIGNORE, '>', $ignore)
853 or fatal("Failed to open `$ignore' for writing: $!");
854 $s =~ s/[\r\n]+/\n/g;
855 $s =~ s/^\n+//;
856 chomp $s;
857 # Prefix all patterns so that the ignore doesn't apply
858 # to sub-directories.
859 $s =~ s#^#/#gm;
860 print GITIGNORE "$s\n";
861 close(GITIGNORE)
862 or fatal("Failed to close `$ignore': $!");
863 command_noisy('add', '-f', $ignore);
867 sub cmd_mkdirs {
868 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
869 $gs ||= Git::SVN->new;
870 $gs->mkemptydirs($_revision);
873 sub canonicalize_path {
874 my ($path) = @_;
875 my $dot_slash_added = 0;
876 if (substr($path, 0, 1) ne "/") {
877 $path = "./" . $path;
878 $dot_slash_added = 1;
880 # File::Spec->canonpath doesn't collapse x/../y into y (for a
881 # good reason), so let's do this manually.
882 $path =~ s#/+#/#g;
883 $path =~ s#/\.(?:/|$)#/#g;
884 $path =~ s#/[^/]+/\.\.##g;
885 $path =~ s#/$##g;
886 $path =~ s#^\./## if $dot_slash_added;
887 $path =~ s#^/##;
888 $path =~ s#^\.$##;
889 return $path;
892 sub canonicalize_url {
893 my ($url) = @_;
894 $url =~ s#^([^:]+://[^/]*/)(.*)$#$1 . canonicalize_path($2)#e;
895 return $url;
898 # get_svnprops(PATH)
899 # ------------------
900 # Helper for cmd_propget and cmd_proplist below.
901 sub get_svnprops {
902 my $path = shift;
903 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
904 $gs ||= Git::SVN->new;
906 # prefix THE PATH by the sub-directory from which the user
907 # invoked us.
908 $path = $cmd_dir_prefix . $path;
909 fatal("No such file or directory: $path") unless -e $path;
910 my $is_dir = -d $path ? 1 : 0;
911 $path = $gs->{path} . '/' . $path;
913 # canonicalize the path (otherwise libsvn will abort or fail to
914 # find the file)
915 $path = canonicalize_path($path);
917 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
918 my $props;
919 if ($is_dir) {
920 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
922 else {
923 (undef, $props) = $gs->ra->get_file($path, $r, undef);
925 return $props;
928 # cmd_propget (PROP, PATH)
929 # ------------------------
930 # Print the SVN property PROP for PATH.
931 sub cmd_propget {
932 my ($prop, $path) = @_;
933 $path = '.' if not defined $path;
934 usage(1) if not defined $prop;
935 my $props = get_svnprops($path);
936 if (not defined $props->{$prop}) {
937 fatal("`$path' does not have a `$prop' SVN property.");
939 print $props->{$prop} . "\n";
942 # cmd_proplist (PATH)
943 # -------------------
944 # Print the list of SVN properties for PATH.
945 sub cmd_proplist {
946 my $path = shift;
947 $path = '.' if not defined $path;
948 my $props = get_svnprops($path);
949 print "Properties on '$path':\n";
950 foreach (sort keys %{$props}) {
951 print " $_\n";
955 sub cmd_multi_init {
956 my $url = shift;
957 unless (defined $_trunk || @_branches || @_tags) {
958 usage(1);
961 $_prefix = '' unless defined $_prefix;
962 if (defined $url) {
963 $url = canonicalize_url($url);
964 init_subdir(@_);
966 do_git_init_db();
967 if (defined $_trunk) {
968 $_trunk =~ s#^/+##;
969 my $trunk_ref = 'refs/remotes/' . $_prefix . 'trunk';
970 # try both old-style and new-style lookups:
971 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
972 unless ($gs_trunk) {
973 my ($trunk_url, $trunk_path) =
974 complete_svn_url($url, $_trunk);
975 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
976 undef, $trunk_ref);
979 return unless @_branches || @_tags;
980 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
981 foreach my $path (@_branches) {
982 complete_url_ls_init($ra, $path, '--branches/-b', $_prefix);
984 foreach my $path (@_tags) {
985 complete_url_ls_init($ra, $path, '--tags/-t', $_prefix.'tags/');
989 sub cmd_multi_fetch {
990 $Git::SVN::no_reuse_existing = undef;
991 my $remotes = Git::SVN::read_all_remotes();
992 foreach my $repo_id (sort keys %$remotes) {
993 if ($remotes->{$repo_id}->{url}) {
994 Git::SVN::fetch_all($repo_id, $remotes);
999 # this command is special because it requires no metadata
1000 sub cmd_commit_diff {
1001 my ($ta, $tb, $url) = @_;
1002 my $usage = "Usage: $0 commit-diff -r<revision> ".
1003 "<tree-ish> <tree-ish> [<URL>]";
1004 fatal($usage) if (!defined $ta || !defined $tb);
1005 my $svn_path = '';
1006 if (!defined $url) {
1007 my $gs = eval { Git::SVN->new };
1008 if (!$gs) {
1009 fatal("Needed URL or usable git-svn --id in ",
1010 "the command-line\n", $usage);
1012 $url = $gs->{url};
1013 $svn_path = $gs->{path};
1015 unless (defined $_revision) {
1016 fatal("-r|--revision is a required argument\n", $usage);
1018 if (defined $_message && defined $_file) {
1019 fatal("Both --message/-m and --file/-F specified ",
1020 "for the commit message.\n",
1021 "I have no idea what you mean");
1023 if (defined $_file) {
1024 $_message = file_to_s($_file);
1025 } else {
1026 $_message ||= get_commit_entry($tb)->{log};
1028 my $ra ||= Git::SVN::Ra->new($url);
1029 my $r = $_revision;
1030 if ($r eq 'HEAD') {
1031 $r = $ra->get_latest_revnum;
1032 } elsif ($r !~ /^\d+$/) {
1033 die "revision argument: $r not understood by git-svn\n";
1035 my %ed_opts = ( r => $r,
1036 log => $_message,
1037 ra => $ra,
1038 tree_a => $ta,
1039 tree_b => $tb,
1040 editor_cb => sub { print "Committed r$_[0]\n" },
1041 svn_path => $svn_path );
1042 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
1043 print "No changes\n$ta == $tb\n";
1047 sub escape_uri_only {
1048 my ($uri) = @_;
1049 my @tmp;
1050 foreach (split m{/}, $uri) {
1051 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
1052 push @tmp, $_;
1054 join('/', @tmp);
1057 sub escape_url {
1058 my ($url) = @_;
1059 if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
1060 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
1061 $url = "$scheme://$domain$uri";
1063 $url;
1066 sub cmd_info {
1067 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
1068 my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
1069 if (exists $_[1]) {
1070 die "Too many arguments specified\n";
1073 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
1075 if (!$file_type && !$diff_status) {
1076 print STDERR "svn: '$path' is not under version control\n";
1077 exit 1;
1080 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1081 unless ($gs) {
1082 die "Unable to determine upstream SVN information from ",
1083 "working tree history\n";
1086 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
1087 $path = "." if $path eq "";
1089 my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
1091 if ($_url) {
1092 print escape_url($full_url), "\n";
1093 return;
1096 my $result = "Path: $path\n";
1097 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
1098 $result .= "URL: " . escape_url($full_url) . "\n";
1100 eval {
1101 my $repos_root = $gs->repos_root;
1102 Git::SVN::remove_username($repos_root);
1103 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
1105 if ($@) {
1106 $result .= "Repository Root: (offline)\n";
1108 ::_req_svn();
1109 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
1110 ($SVN::Core::VERSION le '1.5.4' || $file_type ne "dir");
1111 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
1113 $result .= "Node Kind: " .
1114 ($file_type eq "dir" ? "directory" : "file") . "\n";
1116 my $schedule = $diff_status eq "A"
1117 ? "add"
1118 : ($diff_status eq "D" ? "delete" : "normal");
1119 $result .= "Schedule: $schedule\n";
1121 if ($diff_status eq "A") {
1122 print $result, "\n";
1123 return;
1126 my ($lc_author, $lc_rev, $lc_date_utc);
1127 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
1128 my $log = command_output_pipe(@args);
1129 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
1130 while (<$log>) {
1131 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
1132 $lc_author = $1;
1133 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
1134 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
1135 (undef, $lc_rev, undef) = ::extract_metadata($1);
1138 close $log;
1140 Git::SVN::Log::set_local_timezone();
1142 $result .= "Last Changed Author: $lc_author\n";
1143 $result .= "Last Changed Rev: $lc_rev\n";
1144 $result .= "Last Changed Date: " .
1145 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
1147 if ($file_type ne "dir") {
1148 my $text_last_updated_date =
1149 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
1150 $result .=
1151 "Text Last Updated: " .
1152 Git::SVN::Log::format_svn_date($text_last_updated_date) .
1153 "\n";
1154 my $checksum;
1155 if ($diff_status eq "D") {
1156 my ($fh, $ctx) =
1157 command_output_pipe(qw(cat-file blob), "HEAD:$path");
1158 if ($file_type eq "link") {
1159 my $file_name = <$fh>;
1160 $checksum = md5sum("link $file_name");
1161 } else {
1162 $checksum = md5sum($fh);
1164 command_close_pipe($fh, $ctx);
1165 } elsif ($file_type eq "link") {
1166 my $file_name =
1167 command(qw(cat-file blob), "HEAD:$path");
1168 $checksum =
1169 md5sum("link " . $file_name);
1170 } else {
1171 open FILE, "<", $path or die $!;
1172 $checksum = md5sum(\*FILE);
1173 close FILE or die $!;
1175 $result .= "Checksum: " . $checksum . "\n";
1178 print $result, "\n";
1181 sub cmd_reset {
1182 my $target = shift || $_revision or die "SVN revision required\n";
1183 $target = $1 if $target =~ /^r(\d+)$/;
1184 $target =~ /^\d+$/ or die "Numeric SVN revision expected\n";
1185 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1186 unless ($gs) {
1187 die "Unable to determine upstream SVN information from ".
1188 "history\n";
1190 my ($r, $c) = $gs->find_rev_before($target, not $_fetch_parent);
1191 die "Cannot find SVN revision $target\n" unless defined($c);
1192 $gs->rev_map_set($r, $c, 'reset', $uuid);
1193 print "r$r = $c ($gs->{ref_id})\n";
1196 sub cmd_gc {
1197 if (!$can_compress) {
1198 warn "Compress::Zlib could not be found; unhandled.log " .
1199 "files will not be compressed.\n";
1201 find({ wanted => \&gc_directory, no_chdir => 1}, "$ENV{GIT_DIR}/svn");
1204 ########################### utility functions #########################
1206 sub rebase_cmd {
1207 my @cmd = qw/rebase/;
1208 push @cmd, '-v' if $_verbose;
1209 push @cmd, qw/--merge/ if $_merge;
1210 push @cmd, "--strategy=$_strategy" if $_strategy;
1211 @cmd;
1214 sub post_fetch_checkout {
1215 return if $_no_checkout;
1216 my $gs = $Git::SVN::_head or return;
1217 return if verify_ref('refs/heads/master^0');
1219 # look for "trunk" ref if it exists
1220 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
1221 my $fetch = $remote->{fetch};
1222 if ($fetch) {
1223 foreach my $p (keys %$fetch) {
1224 basename($fetch->{$p}) eq 'trunk' or next;
1225 $gs = Git::SVN->new($fetch->{$p}, $gs->{repo_id}, $p);
1226 last;
1230 my $valid_head = verify_ref('HEAD^0');
1231 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1232 return if ($valid_head || !verify_ref('HEAD^0'));
1234 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1235 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1236 return if -f $index;
1238 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1239 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1240 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1241 print STDERR "Checked out HEAD:\n ",
1242 $gs->full_url, " r", $gs->last_rev, "\n";
1243 $gs->mkemptydirs($gs->last_rev);
1246 sub complete_svn_url {
1247 my ($url, $path) = @_;
1248 $path =~ s#/+$##;
1249 if ($path !~ m#^[a-z\+]+://#) {
1250 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1251 fatal("E: '$path' is not a complete URL ",
1252 "and a separate URL is not specified");
1254 return ($url, $path);
1256 return ($path, '');
1259 sub complete_url_ls_init {
1260 my ($ra, $repo_path, $switch, $pfx) = @_;
1261 unless ($repo_path) {
1262 print STDERR "W: $switch not specified\n";
1263 return;
1265 $repo_path =~ s#/+$##;
1266 if ($repo_path =~ m#^[a-z\+]+://#) {
1267 $ra = Git::SVN::Ra->new($repo_path);
1268 $repo_path = '';
1269 } else {
1270 $repo_path =~ s#^/+##;
1271 unless ($ra) {
1272 fatal("E: '$repo_path' is not a complete URL ",
1273 "and a separate URL is not specified");
1276 my $url = $ra->{url};
1277 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1278 my $k = "svn-remote.$gs->{repo_id}.url";
1279 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1280 if ($orig_url && ($orig_url ne $gs->{url})) {
1281 die "$k already set: $orig_url\n",
1282 "wanted to set to: $gs->{url}\n";
1284 command_oneline('config', $k, $gs->{url}) unless $orig_url;
1285 my $remote_path = "$gs->{path}/$repo_path";
1286 $remote_path =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
1287 $remote_path =~ s#/+#/#g;
1288 $remote_path =~ s#^/##g;
1289 $remote_path .= "/*" if $remote_path !~ /\*/;
1290 my ($n) = ($switch =~ /^--(\w+)/);
1291 if (length $pfx && $pfx !~ m#/$#) {
1292 die "--prefix='$pfx' must have a trailing slash '/'\n";
1294 command_noisy('config',
1295 '--add',
1296 "svn-remote.$gs->{repo_id}.$n",
1297 "$remote_path:refs/remotes/$pfx*" .
1298 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1301 sub verify_ref {
1302 my ($ref) = @_;
1303 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1304 { STDERR => 0 }); };
1307 sub get_tree_from_treeish {
1308 my ($treeish) = @_;
1309 # $treeish can be a symbolic ref, too:
1310 my $type = command_oneline(qw/cat-file -t/, $treeish);
1311 my $expected;
1312 while ($type eq 'tag') {
1313 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1315 if ($type eq 'commit') {
1316 $expected = (grep /^tree /, command(qw/cat-file commit/,
1317 $treeish))[0];
1318 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1319 die "Unable to get tree from $treeish\n" unless $expected;
1320 } elsif ($type eq 'tree') {
1321 $expected = $treeish;
1322 } else {
1323 die "$treeish is a $type, expected tree, tag or commit\n";
1325 return $expected;
1328 sub get_commit_entry {
1329 my ($treeish) = shift;
1330 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1331 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1332 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1333 open my $log_fh, '>', $commit_editmsg or croak $!;
1335 my $type = command_oneline(qw/cat-file -t/, $treeish);
1336 if ($type eq 'commit' || $type eq 'tag') {
1337 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1338 $type, $treeish);
1339 my $in_msg = 0;
1340 my $author;
1341 my $saw_from = 0;
1342 my $msgbuf = "";
1343 while (<$msg_fh>) {
1344 if (!$in_msg) {
1345 $in_msg = 1 if (/^\s*$/);
1346 $author = $1 if (/^author (.*>)/);
1347 } elsif (/^git-svn-id: /) {
1348 # skip this for now, we regenerate the
1349 # correct one on re-fetch anyways
1350 # TODO: set *:merge properties or like...
1351 } else {
1352 if (/^From:/ || /^Signed-off-by:/) {
1353 $saw_from = 1;
1355 $msgbuf .= $_;
1358 $msgbuf =~ s/\s+$//s;
1359 if ($Git::SVN::_add_author_from && defined($author)
1360 && !$saw_from) {
1361 $msgbuf .= "\n\nFrom: $author";
1363 print $log_fh $msgbuf or croak $!;
1364 command_close_pipe($msg_fh, $ctx);
1366 close $log_fh or croak $!;
1368 if ($_edit || ($type eq 'tree')) {
1369 chomp(my $editor = command_oneline(qw(var GIT_EDITOR)));
1370 system('sh', '-c', $editor.' "$@"', $editor, $commit_editmsg);
1372 rename $commit_editmsg, $commit_msg or croak $!;
1374 require Encode;
1375 # SVN requires messages to be UTF-8 when entering the repo
1376 local $/;
1377 open $log_fh, '<', $commit_msg or croak $!;
1378 binmode $log_fh;
1379 chomp($log_entry{log} = <$log_fh>);
1381 my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
1382 my $msg = $log_entry{log};
1384 eval { $msg = Encode::decode($enc, $msg, 1) };
1385 if ($@) {
1386 die "Could not decode as $enc:\n", $msg,
1387 "\nPerhaps you need to set i18n.commitencoding\n";
1390 eval { $msg = Encode::encode('UTF-8', $msg, 1) };
1391 die "Could not encode as UTF-8:\n$msg\n" if $@;
1393 $log_entry{log} = $msg;
1395 close $log_fh or croak $!;
1397 unlink $commit_msg;
1398 \%log_entry;
1401 sub s_to_file {
1402 my ($str, $file, $mode) = @_;
1403 open my $fd,'>',$file or croak $!;
1404 print $fd $str,"\n" or croak $!;
1405 close $fd or croak $!;
1406 chmod ($mode &~ umask, $file) if (defined $mode);
1409 sub file_to_s {
1410 my $file = shift;
1411 open my $fd,'<',$file or croak "$!: file: $file\n";
1412 local $/;
1413 my $ret = <$fd>;
1414 close $fd or croak $!;
1415 $ret =~ s/\s*$//s;
1416 return $ret;
1419 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1420 sub load_authors {
1421 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1422 my $log = $cmd eq 'log';
1423 while (<$authors>) {
1424 chomp;
1425 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1426 my ($user, $name, $email) = ($1, $2, $3);
1427 if ($log) {
1428 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1429 } else {
1430 $users{$user} = [$name, $email];
1433 close $authors or croak $!;
1436 # convert GetOpt::Long specs for use by git-config
1437 sub read_git_config {
1438 my $opts = shift;
1439 my @config_only;
1440 foreach my $o (keys %$opts) {
1441 # if we have mixedCase and a long option-only, then
1442 # it's a config-only variable that we don't need for
1443 # the command-line.
1444 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1445 my $v = $opts->{$o};
1446 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1447 $key =~ s/-//g;
1448 my $arg = 'git config';
1449 $arg .= ' --int' if ($o =~ /[:=]i$/);
1450 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1451 if (ref $v eq 'ARRAY') {
1452 chomp(my @tmp = `$arg --get-all svn.$key`);
1453 @$v = @tmp if @tmp;
1454 } else {
1455 chomp(my $tmp = `$arg --get svn.$key`);
1456 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1457 $$v = $tmp;
1461 delete @$opts{@config_only} if @config_only;
1464 sub extract_metadata {
1465 my $id = shift or return (undef, undef, undef);
1466 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1467 \s([a-f\d\-]+)$/ix);
1468 if (!defined $rev || !$uuid || !$url) {
1469 # some of the original repositories I made had
1470 # identifiers like this:
1471 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/i);
1473 return ($url, $rev, $uuid);
1476 sub cmt_metadata {
1477 return extract_metadata((grep(/^git-svn-id: /,
1478 command(qw/cat-file commit/, shift)))[-1]);
1481 sub cmt_sha2rev_batch {
1482 my %s2r;
1483 my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1484 my $list = shift;
1486 foreach my $sha (@{$list}) {
1487 my $first = 1;
1488 my $size = 0;
1489 print $out $sha, "\n";
1491 while (my $line = <$in>) {
1492 if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1493 last;
1494 } elsif ($first &&
1495 $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1496 $first = 0;
1497 $size = $1;
1498 next;
1499 } elsif ($line =~ /^(git-svn-id: )/) {
1500 my (undef, $rev, undef) =
1501 extract_metadata($line);
1502 $s2r{$sha} = $rev;
1505 $size -= length($line);
1506 last if ($size == 0);
1510 command_close_bidi_pipe($pid, $in, $out, $ctx);
1512 return \%s2r;
1515 sub working_head_info {
1516 my ($head, $refs) = @_;
1517 my @args = qw/log --no-color --no-decorate --first-parent
1518 --pretty=medium/;
1519 my ($fh, $ctx) = command_output_pipe(@args, $head);
1520 my $hash;
1521 my %max;
1522 while (<$fh>) {
1523 if ( m{^commit ($::sha1)$} ) {
1524 unshift @$refs, $hash if $hash and $refs;
1525 $hash = $1;
1526 next;
1528 next unless s{^\s*(git-svn-id:)}{$1};
1529 my ($url, $rev, $uuid) = extract_metadata($_);
1530 if (defined $url && defined $rev) {
1531 next if $max{$url} and $max{$url} < $rev;
1532 if (my $gs = Git::SVN->find_by_url($url)) {
1533 my $c = $gs->rev_map_get($rev, $uuid);
1534 if ($c && $c eq $hash) {
1535 close $fh; # break the pipe
1536 return ($url, $rev, $uuid, $gs);
1537 } else {
1538 $max{$url} ||= $gs->rev_map_max;
1543 command_close_pipe($fh, $ctx);
1544 (undef, undef, undef, undef);
1547 sub read_commit_parents {
1548 my ($parents, $c) = @_;
1549 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1550 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1551 @{$parents->{$c}} = split(/ /, $p);
1554 sub linearize_history {
1555 my ($gs, $refs) = @_;
1556 my %parents;
1557 foreach my $c (@$refs) {
1558 read_commit_parents(\%parents, $c);
1561 my @linear_refs;
1562 my %skip = ();
1563 my $last_svn_commit = $gs->last_commit;
1564 foreach my $c (reverse @$refs) {
1565 next if $c eq $last_svn_commit;
1566 last if $skip{$c};
1568 unshift @linear_refs, $c;
1569 $skip{$c} = 1;
1571 # we only want the first parent to diff against for linear
1572 # history, we save the rest to inject when we finalize the
1573 # svn commit
1574 my $fp_a = verify_ref("$c~1");
1575 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1576 if (!$fp_a || !$fp_b) {
1577 die "Commit $c\n",
1578 "has no parent commit, and therefore ",
1579 "nothing to diff against.\n",
1580 "You should be working from a repository ",
1581 "originally created by git-svn\n";
1583 if ($fp_a ne $fp_b) {
1584 die "$c~1 = $fp_a, however parsing commit $c ",
1585 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1588 foreach my $p (@{$parents{$c}}) {
1589 $skip{$p} = 1;
1592 (\@linear_refs, \%parents);
1595 sub find_file_type_and_diff_status {
1596 my ($path) = @_;
1597 return ('dir', '') if $path eq '';
1599 my $diff_output =
1600 command_oneline(qw(diff --cached --name-status --), $path) || "";
1601 my $diff_status = (split(' ', $diff_output))[0] || "";
1603 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1605 return (undef, undef) if !$diff_status && !$ls_tree;
1607 if ($diff_status eq "A") {
1608 return ("link", $diff_status) if -l $path;
1609 return ("dir", $diff_status) if -d $path;
1610 return ("file", $diff_status);
1613 my $mode = (split(' ', $ls_tree))[0] || "";
1615 return ("link", $diff_status) if $mode eq "120000";
1616 return ("dir", $diff_status) if $mode eq "040000";
1617 return ("file", $diff_status);
1620 sub md5sum {
1621 my $arg = shift;
1622 my $ref = ref $arg;
1623 my $md5 = Digest::MD5->new();
1624 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
1625 $md5->addfile($arg) or croak $!;
1626 } elsif ($ref eq 'SCALAR') {
1627 $md5->add($$arg) or croak $!;
1628 } elsif (!$ref) {
1629 $md5->add($arg) or croak $!;
1630 } else {
1631 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1633 return $md5->hexdigest();
1636 sub gc_directory {
1637 if ($can_compress && -f $_ && basename($_) eq "unhandled.log") {
1638 my $out_filename = $_ . ".gz";
1639 open my $in_fh, "<", $_ or die "Unable to open $_: $!\n";
1640 binmode $in_fh;
1641 my $gz = Compress::Zlib::gzopen($out_filename, "ab") or
1642 die "Unable to open $out_filename: $!\n";
1644 my $res;
1645 while ($res = sysread($in_fh, my $str, 1024)) {
1646 $gz->gzwrite($str) or
1647 die "Unable to write: ".$gz->gzerror()."!\n";
1649 unlink $_ or die "unlink $File::Find::name: $!\n";
1650 } elsif (-f $_ && basename($_) eq "index") {
1651 unlink $_ or die "unlink $_: $!\n";
1655 package Git::SVN;
1656 use strict;
1657 use warnings;
1658 use Fcntl qw/:DEFAULT :seek/;
1659 use constant rev_map_fmt => 'NH40';
1660 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1661 $_repack $_repack_flags $_use_svm_props $_head
1662 $_use_svnsync_props $no_reuse_existing $_minimize_url
1663 $_use_log_author $_add_author_from $_localtime/;
1664 use Carp qw/croak/;
1665 use File::Path qw/mkpath/;
1666 use File::Copy qw/copy/;
1667 use IPC::Open3;
1668 use Memoize; # core since 5.8.0, Jul 2002
1669 use Memoize::Storable;
1671 my ($_gc_nr, $_gc_period);
1673 # properties that we do not log:
1674 my %SKIP_PROP;
1675 BEGIN {
1676 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1677 svn:special svn:executable
1678 svn:entry:committed-rev
1679 svn:entry:last-author
1680 svn:entry:uuid
1681 svn:entry:committed-date/;
1683 # some options are read globally, but can be overridden locally
1684 # per [svn-remote "..."] section. Command-line options will *NOT*
1685 # override options set in an [svn-remote "..."] section
1686 no strict 'refs';
1687 for my $option (qw/follow_parent no_metadata use_svm_props
1688 use_svnsync_props/) {
1689 my $key = $option;
1690 $key =~ tr/_//d;
1691 my $prop = "-$option";
1692 *$option = sub {
1693 my ($self) = @_;
1694 return $self->{$prop} if exists $self->{$prop};
1695 my $k = "svn-remote.$self->{repo_id}.$key";
1696 eval { command_oneline(qw/config --get/, $k) };
1697 if ($@) {
1698 $self->{$prop} = ${"Git::SVN::_$option"};
1699 } else {
1700 my $v = command_oneline(qw/config --bool/,$k);
1701 $self->{$prop} = $v eq 'false' ? 0 : 1;
1703 return $self->{$prop};
1709 my (%LOCKFILES, %INDEX_FILES);
1710 END {
1711 unlink keys %LOCKFILES if %LOCKFILES;
1712 unlink keys %INDEX_FILES if %INDEX_FILES;
1715 sub resolve_local_globs {
1716 my ($url, $fetch, $glob_spec) = @_;
1717 return unless defined $glob_spec;
1718 my $ref = $glob_spec->{ref};
1719 my $path = $glob_spec->{path};
1720 foreach (command(qw#for-each-ref --format=%(refname) refs/#)) {
1721 next unless m#^$ref->{regex}$#;
1722 my $p = $1;
1723 my $pathname = desanitize_refname($path->full_path($p));
1724 my $refname = desanitize_refname($ref->full_path($p));
1725 if (my $existing = $fetch->{$pathname}) {
1726 if ($existing ne $refname) {
1727 die "Refspec conflict:\n",
1728 "existing: $existing\n",
1729 " globbed: $refname\n";
1731 my $u = (::cmt_metadata("$refname"))[0];
1732 $u =~ s!^\Q$url\E(/|$)!! or die
1733 "$refname: '$url' not found in '$u'\n";
1734 if ($pathname ne $u) {
1735 warn "W: Refspec glob conflict ",
1736 "(ref: $refname):\n",
1737 "expected path: $pathname\n",
1738 " real path: $u\n",
1739 "Continuing ahead with $u\n";
1740 next;
1742 } else {
1743 $fetch->{$pathname} = $refname;
1748 sub parse_revision_argument {
1749 my ($base, $head) = @_;
1750 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1751 return ($base, $head);
1753 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1754 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1755 return ($head, $head) if ($::_revision eq 'HEAD');
1756 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1757 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1758 die "revision argument: $::_revision not understood by git-svn\n";
1761 sub fetch_all {
1762 my ($repo_id, $remotes) = @_;
1763 if (ref $repo_id) {
1764 my $gs = $repo_id;
1765 $repo_id = undef;
1766 $repo_id = $gs->{repo_id};
1768 $remotes ||= read_all_remotes();
1769 my $remote = $remotes->{$repo_id} or
1770 die "[svn-remote \"$repo_id\"] unknown\n";
1771 my $fetch = $remote->{fetch};
1772 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1773 my (@gs, @globs);
1774 my $ra = Git::SVN::Ra->new($url);
1775 my $uuid = $ra->get_uuid;
1776 my $head = $ra->get_latest_revnum;
1778 # ignore errors, $head revision may not even exist anymore
1779 eval { $ra->get_log("", $head, 0, 1, 0, 1, sub { $head = $_[1] }) };
1780 warn "W: $@\n" if $@;
1782 my $base = defined $fetch ? $head : 0;
1784 # read the max revs for wildcard expansion (branches/*, tags/*)
1785 foreach my $t (qw/branches tags/) {
1786 defined $remote->{$t} or next;
1787 push @globs, @{$remote->{$t}};
1789 my $max_rev = eval { tmp_config(qw/--int --get/,
1790 "svn-remote.$repo_id.${t}-maxRev") };
1791 if (defined $max_rev && ($max_rev < $base)) {
1792 $base = $max_rev;
1793 } elsif (!defined $max_rev) {
1794 $base = 0;
1798 if ($fetch) {
1799 foreach my $p (sort keys %$fetch) {
1800 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1801 my $lr = $gs->rev_map_max;
1802 if (defined $lr) {
1803 $base = $lr if ($lr < $base);
1805 push @gs, $gs;
1809 ($base, $head) = parse_revision_argument($base, $head);
1810 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1813 sub read_all_remotes {
1814 my $r = {};
1815 my $use_svm_props = eval { command_oneline(qw/config --bool
1816 svn.useSvmProps/) };
1817 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
1818 my $svn_refspec = qr{\s*(.*?)\s*:\s*(.+?)\s*};
1819 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1820 if (m!^(.+)\.fetch=$svn_refspec$!) {
1821 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
1822 die("svn-remote.$remote: remote ref '$remote_ref' "
1823 . "must start with 'refs/'\n")
1824 unless $remote_ref =~ m{^refs/};
1825 $local_ref = uri_decode($local_ref);
1826 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1827 $r->{$remote}->{svm} = {} if $use_svm_props;
1828 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
1829 $r->{$1}->{svm} = {};
1830 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1831 $r->{$1}->{url} = $2;
1832 } elsif (m!^(.+)\.(branches|tags)=$svn_refspec$!) {
1833 my ($remote, $t, $local_ref, $remote_ref) =
1834 ($1, $2, $3, $4);
1835 die("svn-remote.$remote: remote ref '$remote_ref' ($t) "
1836 . "must start with 'refs/'\n")
1837 unless $remote_ref =~ m{^refs/};
1838 $local_ref = uri_decode($local_ref);
1839 my $rs = {
1840 t => $t,
1841 remote => $remote,
1842 path => Git::SVN::GlobSpec->new($local_ref, 1),
1843 ref => Git::SVN::GlobSpec->new($remote_ref, 0) };
1844 if (length($rs->{ref}->{right}) != 0) {
1845 die "The '*' glob character must be the last ",
1846 "character of '$remote_ref'\n";
1848 push @{ $r->{$remote}->{$t} }, $rs;
1852 map {
1853 if (defined $r->{$_}->{svm}) {
1854 my $svm;
1855 eval {
1856 my $section = "svn-remote.$_";
1857 $svm = {
1858 source => tmp_config('--get',
1859 "$section.svm-source"),
1860 replace => tmp_config('--get',
1861 "$section.svm-replace"),
1864 $r->{$_}->{svm} = $svm;
1866 } keys %$r;
1871 sub init_vars {
1872 $_gc_nr = $_gc_period = 1000;
1873 if (defined $_repack || defined $_repack_flags) {
1874 warn "Repack options are obsolete; they have no effect.\n";
1878 sub verify_remotes_sanity {
1879 return unless -d $ENV{GIT_DIR};
1880 my %seen;
1881 foreach (command(qw/config -l/)) {
1882 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1883 if ($seen{$1}) {
1884 die "Remote ref refs/remote/$1 is tracked by",
1885 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1886 "Please resolve this ambiguity in ",
1887 "your git configuration file before ",
1888 "continuing\n";
1890 $seen{$1} = $_;
1895 sub find_existing_remote {
1896 my ($url, $remotes) = @_;
1897 return undef if $no_reuse_existing;
1898 my $existing;
1899 foreach my $repo_id (keys %$remotes) {
1900 my $u = $remotes->{$repo_id}->{url} or next;
1901 next if $u ne $url;
1902 $existing = $repo_id;
1903 last;
1905 $existing;
1908 sub init_remote_config {
1909 my ($self, $url, $no_write) = @_;
1910 $url =~ s!/+$!!; # strip trailing slash
1911 my $r = read_all_remotes();
1912 my $existing = find_existing_remote($url, $r);
1913 if ($existing) {
1914 unless ($no_write) {
1915 print STDERR "Using existing ",
1916 "[svn-remote \"$existing\"]\n";
1918 $self->{repo_id} = $existing;
1919 } elsif ($_minimize_url) {
1920 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1921 $existing = find_existing_remote($min_url, $r);
1922 if ($existing) {
1923 unless ($no_write) {
1924 print STDERR "Using existing ",
1925 "[svn-remote \"$existing\"]\n";
1927 $self->{repo_id} = $existing;
1929 if ($min_url ne $url) {
1930 unless ($no_write) {
1931 print STDERR "Using higher level of URL: ",
1932 "$url => $min_url\n";
1934 my $old_path = $self->{path};
1935 $self->{path} = $url;
1936 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1937 if (length $old_path) {
1938 $self->{path} .= "/$old_path";
1940 $url = $min_url;
1943 my $orig_url;
1944 if (!$existing) {
1945 # verify that we aren't overwriting anything:
1946 $orig_url = eval {
1947 command_oneline('config', '--get',
1948 "svn-remote.$self->{repo_id}.url")
1950 if ($orig_url && ($orig_url ne $url)) {
1951 die "svn-remote.$self->{repo_id}.url already set: ",
1952 "$orig_url\nwanted to set to: $url\n";
1955 my ($xrepo_id, $xpath) = find_ref($self->refname);
1956 if (!$no_write && defined $xpath) {
1957 die "svn-remote.$xrepo_id.fetch already set to track ",
1958 "$xpath:", $self->refname, "\n";
1960 unless ($no_write) {
1961 command_noisy('config',
1962 "svn-remote.$self->{repo_id}.url", $url);
1963 $self->{path} =~ s{^/}{};
1964 $self->{path} =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
1965 command_noisy('config', '--add',
1966 "svn-remote.$self->{repo_id}.fetch",
1967 "$self->{path}:".$self->refname);
1969 $self->{url} = $url;
1972 sub find_by_url { # repos_root and, path are optional
1973 my ($class, $full_url, $repos_root, $path) = @_;
1975 return undef unless defined $full_url;
1976 remove_username($full_url);
1977 remove_username($repos_root) if defined $repos_root;
1978 my $remotes = read_all_remotes();
1979 if (defined $full_url && defined $repos_root && !defined $path) {
1980 $path = $full_url;
1981 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1983 foreach my $repo_id (keys %$remotes) {
1984 my $u = $remotes->{$repo_id}->{url} or next;
1985 remove_username($u);
1986 next if defined $repos_root && $repos_root ne $u;
1988 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1989 foreach my $t (qw/branches tags/) {
1990 foreach my $globspec (@{$remotes->{$repo_id}->{$t}}) {
1991 resolve_local_globs($u, $fetch, $globspec);
1994 my $p = $path;
1995 my $rwr = rewrite_root({repo_id => $repo_id});
1996 my $svm = $remotes->{$repo_id}->{svm}
1997 if defined $remotes->{$repo_id}->{svm};
1998 unless (defined $p) {
1999 $p = $full_url;
2000 my $z = $u;
2001 my $prefix = '';
2002 if ($rwr) {
2003 $z = $rwr;
2004 remove_username($z);
2005 } elsif (defined $svm) {
2006 $z = $svm->{source};
2007 $prefix = $svm->{replace};
2008 $prefix =~ s#^\Q$u\E(?:/|$)##;
2009 $prefix =~ s#/$##;
2011 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
2013 foreach my $f (keys %$fetch) {
2014 next if $f ne $p;
2015 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
2018 undef;
2021 sub init {
2022 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
2023 my $self = _new($class, $repo_id, $ref_id, $path);
2024 if (defined $url) {
2025 $self->init_remote_config($url, $no_write);
2027 $self;
2030 sub find_ref {
2031 my ($ref_id) = @_;
2032 foreach (command(qw/config -l/)) {
2033 next unless m!^svn-remote\.(.+)\.fetch=
2034 \s*(.*?)\s*:\s*(.+?)\s*$!x;
2035 my ($repo_id, $path, $ref) = ($1, $2, $3);
2036 if ($ref eq $ref_id) {
2037 $path = '' if ($path =~ m#^\./?#);
2038 return ($repo_id, $path);
2041 (undef, undef, undef);
2044 sub new {
2045 my ($class, $ref_id, $repo_id, $path) = @_;
2046 if (defined $ref_id && !defined $repo_id && !defined $path) {
2047 ($repo_id, $path) = find_ref($ref_id);
2048 if (!defined $repo_id) {
2049 die "Could not find a \"svn-remote.*.fetch\" key ",
2050 "in the repository configuration matching: ",
2051 "$ref_id\n";
2054 my $self = _new($class, $repo_id, $ref_id, $path);
2055 if (!defined $self->{path} || !length $self->{path}) {
2056 my $fetch = command_oneline('config', '--get',
2057 "svn-remote.$repo_id.fetch",
2058 ":$ref_id\$") or
2059 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
2060 "\":$ref_id\$\" in config\n";
2061 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
2063 $self->{path} =~ s{/+}{/}g;
2064 $self->{path} =~ s{\A/}{};
2065 $self->{path} =~ s{/\z}{};
2066 $self->{url} = command_oneline('config', '--get',
2067 "svn-remote.$repo_id.url") or
2068 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
2069 $self->rebuild;
2070 $self;
2073 sub refname {
2074 my ($refname) = $_[0]->{ref_id} ;
2076 # It cannot end with a slash /, we'll throw up on this because
2077 # SVN can't have directories with a slash in their name, either:
2078 if ($refname =~ m{/$}) {
2079 die "ref: '$refname' ends with a trailing slash, this is ",
2080 "not permitted by git nor Subversion\n";
2083 # It cannot have ASCII control character space, tilde ~, caret ^,
2084 # colon :, question-mark ?, asterisk *, space, or open bracket [
2085 # anywhere.
2087 # Additionally, % must be escaped because it is used for escaping
2088 # and we want our escaped refname to be reversible
2089 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
2091 # no slash-separated component can begin with a dot .
2092 # /.* becomes /%2E*
2093 $refname =~ s{/\.}{/%2E}g;
2095 # It cannot have two consecutive dots .. anywhere
2096 # .. becomes %2E%2E
2097 $refname =~ s{\.\.}{%2E%2E}g;
2099 # trailing dots and .lock are not allowed
2100 # .$ becomes %2E and .lock becomes %2Elock
2101 $refname =~ s{\.(?=$|lock$)}{%2E};
2103 # the sequence @{ is used to access the reflog
2104 # @{ becomes %40{
2105 $refname =~ s{\@\{}{%40\{}g;
2107 return $refname;
2110 sub desanitize_refname {
2111 my ($refname) = @_;
2112 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
2113 return $refname;
2116 sub svm_uuid {
2117 my ($self) = @_;
2118 return $self->{svm}->{uuid} if $self->svm;
2119 $self->ra;
2120 unless ($self->{svm}) {
2121 die "SVM UUID not cached, and reading remotely failed\n";
2123 $self->{svm}->{uuid};
2126 sub svm {
2127 my ($self) = @_;
2128 return $self->{svm} if $self->{svm};
2129 my $svm;
2130 # see if we have it in our config, first:
2131 eval {
2132 my $section = "svn-remote.$self->{repo_id}";
2133 $svm = {
2134 source => tmp_config('--get', "$section.svm-source"),
2135 uuid => tmp_config('--get', "$section.svm-uuid"),
2136 replace => tmp_config('--get', "$section.svm-replace"),
2139 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
2140 $self->{svm} = $svm;
2142 $self->{svm};
2145 sub _set_svm_vars {
2146 my ($self, $ra) = @_;
2147 return $ra if $self->svm;
2149 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
2150 "(svm:source, svm:uuid) ",
2151 "from the following URLs:\n" );
2152 sub read_svm_props {
2153 my ($self, $ra, $path, $r) = @_;
2154 my $props = ($ra->get_dir($path, $r))[2];
2155 my $src = $props->{'svm:source'};
2156 my $uuid = $props->{'svm:uuid'};
2157 return undef if (!$src || !$uuid);
2159 chomp($src, $uuid);
2161 $uuid =~ m{^[0-9a-f\-]{30,}$}i
2162 or die "doesn't look right - svm:uuid is '$uuid'\n";
2164 # the '!' is used to mark the repos_root!/relative/path
2165 $src =~ s{/?!/?}{/};
2166 $src =~ s{/+$}{}; # no trailing slashes please
2167 # username is of no interest
2168 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
2170 my $replace = $ra->{url};
2171 $replace .= "/$path" if length $path;
2173 my $section = "svn-remote.$self->{repo_id}";
2174 tmp_config("$section.svm-source", $src);
2175 tmp_config("$section.svm-replace", $replace);
2176 tmp_config("$section.svm-uuid", $uuid);
2177 $self->{svm} = {
2178 source => $src,
2179 uuid => $uuid,
2180 replace => $replace
2184 my $r = $ra->get_latest_revnum;
2185 my $path = $self->{path};
2186 my %tried;
2187 while (length $path) {
2188 unless ($tried{"$self->{url}/$path"}) {
2189 return $ra if $self->read_svm_props($ra, $path, $r);
2190 $tried{"$self->{url}/$path"} = 1;
2192 $path =~ s#/?[^/]+$##;
2194 die "Path: '$path' should be ''\n" if $path ne '';
2195 return $ra if $self->read_svm_props($ra, $path, $r);
2196 $tried{"$self->{url}/$path"} = 1;
2198 if ($ra->{repos_root} eq $self->{url}) {
2199 die @err, (map { " $_\n" } keys %tried), "\n";
2202 # nope, make sure we're connected to the repository root:
2203 my $ok;
2204 my @tried_b;
2205 $path = $ra->{svn_path};
2206 $ra = Git::SVN::Ra->new($ra->{repos_root});
2207 while (length $path) {
2208 unless ($tried{"$ra->{url}/$path"}) {
2209 $ok = $self->read_svm_props($ra, $path, $r);
2210 last if $ok;
2211 $tried{"$ra->{url}/$path"} = 1;
2213 $path =~ s#/?[^/]+$##;
2215 die "Path: '$path' should be ''\n" if $path ne '';
2216 $ok ||= $self->read_svm_props($ra, $path, $r);
2217 $tried{"$ra->{url}/$path"} = 1;
2218 if (!$ok) {
2219 die @err, (map { " $_\n" } keys %tried), "\n";
2221 Git::SVN::Ra->new($self->{url});
2224 sub svnsync {
2225 my ($self) = @_;
2226 return $self->{svnsync} if $self->{svnsync};
2228 if ($self->no_metadata) {
2229 die "Can't have both 'noMetadata' and ",
2230 "'useSvnsyncProps' options set!\n";
2232 if ($self->rewrite_root) {
2233 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
2234 "options set!\n";
2236 if ($self->rewrite_uuid) {
2237 die "Can't have both 'useSvnsyncProps' and 'rewriteUUID' ",
2238 "options set!\n";
2241 my $svnsync;
2242 # see if we have it in our config, first:
2243 eval {
2244 my $section = "svn-remote.$self->{repo_id}";
2246 my $url = tmp_config('--get', "$section.svnsync-url");
2247 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2248 die "doesn't look right - svn:sync-from-url is '$url'\n";
2250 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
2251 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2252 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2254 $svnsync = { url => $url, uuid => $uuid }
2256 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
2257 return $self->{svnsync} = $svnsync;
2260 my $err = "useSvnsyncProps set, but failed to read " .
2261 "svnsync property: svn:sync-from-";
2262 my $rp = $self->ra->rev_proplist(0);
2264 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
2265 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2266 die "doesn't look right - svn:sync-from-url is '$url'\n";
2268 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
2269 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2270 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2272 my $section = "svn-remote.$self->{repo_id}";
2273 tmp_config('--add', "$section.svnsync-uuid", $uuid);
2274 tmp_config('--add', "$section.svnsync-url", $url);
2275 return $self->{svnsync} = { url => $url, uuid => $uuid };
2278 # this allows us to memoize our SVN::Ra UUID locally and avoid a
2279 # remote lookup (useful for 'git svn log').
2280 sub ra_uuid {
2281 my ($self) = @_;
2282 unless ($self->{ra_uuid}) {
2283 my $key = "svn-remote.$self->{repo_id}.uuid";
2284 my $uuid = eval { tmp_config('--get', $key) };
2285 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/i) {
2286 $self->{ra_uuid} = $uuid;
2287 } else {
2288 die "ra_uuid called without URL\n" unless $self->{url};
2289 $self->{ra_uuid} = $self->ra->get_uuid;
2290 tmp_config('--add', $key, $self->{ra_uuid});
2293 $self->{ra_uuid};
2296 sub _set_repos_root {
2297 my ($self, $repos_root) = @_;
2298 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2299 $repos_root ||= $self->ra->{repos_root};
2300 tmp_config($k, $repos_root);
2301 $repos_root;
2304 sub repos_root {
2305 my ($self) = @_;
2306 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2307 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
2310 sub ra {
2311 my ($self) = shift;
2312 my $ra = Git::SVN::Ra->new($self->{url});
2313 $self->_set_repos_root($ra->{repos_root});
2314 if ($self->use_svm_props && !$self->{svm}) {
2315 if ($self->no_metadata) {
2316 die "Can't have both 'noMetadata' and ",
2317 "'useSvmProps' options set!\n";
2318 } elsif ($self->use_svnsync_props) {
2319 die "Can't have both 'useSvnsyncProps' and ",
2320 "'useSvmProps' options set!\n";
2322 $ra = $self->_set_svm_vars($ra);
2323 $self->{-want_revprops} = 1;
2325 $ra;
2328 # prop_walk(PATH, REV, SUB)
2329 # -------------------------
2330 # Recursively traverse PATH at revision REV and invoke SUB for each
2331 # directory that contains a SVN property. SUB will be invoked as
2332 # follows: &SUB(gs, path, props); where `gs' is this instance of
2333 # Git::SVN, `path' the path to the directory where the properties
2334 # `props' were found. The `path' will be relative to point of checkout,
2335 # that is, if url://repo/trunk is the current Git branch, and that
2336 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
2337 # as `path' (note the trailing `/').
2338 sub prop_walk {
2339 my ($self, $path, $rev, $sub) = @_;
2341 $path =~ s#^/##;
2342 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2343 $path =~ s#^/*#/#g;
2344 my $p = $path;
2345 # Strip the irrelevant part of the path.
2346 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2347 # Ensure the path is terminated by a `/'.
2348 $p =~ s#/*$#/#;
2350 # The properties contain all the internal SVN stuff nobody
2351 # (usually) cares about.
2352 my $interesting_props = 0;
2353 foreach (keys %{$props}) {
2354 # If it doesn't start with `svn:', it must be a
2355 # user-defined property.
2356 ++$interesting_props and next if $_ !~ /^svn:/;
2357 # FIXME: Fragile, if SVN adds new public properties,
2358 # this needs to be updated.
2359 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2360 |eol-style|mime-type
2361 |externals|needs-lock)$/x;
2363 &$sub($self, $p, $props) if $interesting_props;
2365 foreach (sort keys %$dirent) {
2366 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
2367 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
2371 sub last_rev { ($_[0]->last_rev_commit)[0] }
2372 sub last_commit { ($_[0]->last_rev_commit)[1] }
2374 # returns the newest SVN revision number and newest commit SHA1
2375 sub last_rev_commit {
2376 my ($self) = @_;
2377 if (defined $self->{last_rev} && defined $self->{last_commit}) {
2378 return ($self->{last_rev}, $self->{last_commit});
2380 my $c = ::verify_ref($self->refname.'^0');
2381 if ($c && !$self->use_svm_props && !$self->no_metadata) {
2382 my $rev = (::cmt_metadata($c))[1];
2383 if (defined $rev) {
2384 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2385 return ($rev, $c);
2388 my $map_path = $self->map_path;
2389 unless (-e $map_path) {
2390 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2391 return (undef, undef);
2393 my ($rev, $commit) = $self->rev_map_max(1);
2394 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2395 return ($rev, $commit);
2398 sub get_fetch_range {
2399 my ($self, $min, $max) = @_;
2400 $max ||= $self->ra->get_latest_revnum;
2401 $min ||= $self->rev_map_max;
2402 (++$min, $max);
2405 sub tmp_config {
2406 my (@args) = @_;
2407 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2408 my $config = "$ENV{GIT_DIR}/svn/.metadata";
2409 if (! -f $config && -f $old_def_config) {
2410 rename $old_def_config, $config or
2411 die "Failed rename $old_def_config => $config: $!\n";
2413 my $old_config = $ENV{GIT_CONFIG};
2414 $ENV{GIT_CONFIG} = $config;
2415 $@ = undef;
2416 my @ret = eval {
2417 unless (-f $config) {
2418 mkfile($config);
2419 open my $fh, '>', $config or
2420 die "Can't open $config: $!\n";
2421 print $fh "; This file is used internally by ",
2422 "git-svn\n" or die
2423 "Couldn't write to $config: $!\n";
2424 print $fh "; You should not have to edit it\n" or
2425 die "Couldn't write to $config: $!\n";
2426 close $fh or die "Couldn't close $config: $!\n";
2428 command('config', @args);
2430 my $err = $@;
2431 if (defined $old_config) {
2432 $ENV{GIT_CONFIG} = $old_config;
2433 } else {
2434 delete $ENV{GIT_CONFIG};
2436 die $err if $err;
2437 wantarray ? @ret : $ret[0];
2440 sub tmp_index_do {
2441 my ($self, $sub) = @_;
2442 my $old_index = $ENV{GIT_INDEX_FILE};
2443 $ENV{GIT_INDEX_FILE} = $self->{index};
2444 $@ = undef;
2445 my @ret = eval {
2446 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2447 mkpath([$dir]) unless -d $dir;
2448 &$sub;
2450 my $err = $@;
2451 if (defined $old_index) {
2452 $ENV{GIT_INDEX_FILE} = $old_index;
2453 } else {
2454 delete $ENV{GIT_INDEX_FILE};
2456 die $err if $err;
2457 wantarray ? @ret : $ret[0];
2460 sub assert_index_clean {
2461 my ($self, $treeish) = @_;
2463 $self->tmp_index_do(sub {
2464 command_noisy('read-tree', $treeish) unless -e $self->{index};
2465 my $x = command_oneline('write-tree');
2466 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2467 /^tree ($::sha1)/mo);
2468 return if $y eq $x;
2470 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2471 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2472 command_noisy('read-tree', $treeish);
2473 $x = command_oneline('write-tree');
2474 if ($y ne $x) {
2475 ::fatal "trees ($treeish) $y != $x\n",
2476 "Something is seriously wrong...";
2481 sub get_commit_parents {
2482 my ($self, $log_entry) = @_;
2483 my (%seen, @ret, @tmp);
2484 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2485 if (my $ip = $self->{inject_parents}) {
2486 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2487 push @tmp, $commit;
2490 if (my $cur = ::verify_ref($self->refname.'^0')) {
2491 push @tmp, $cur;
2493 if (my $ipd = $self->{inject_parents_dcommit}) {
2494 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2495 push @tmp, @$commit;
2498 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2499 while (my $p = shift @tmp) {
2500 next if $seen{$p};
2501 $seen{$p} = 1;
2502 push @ret, $p;
2504 @ret;
2507 sub rewrite_root {
2508 my ($self) = @_;
2509 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2510 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2511 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2512 if ($rwr) {
2513 $rwr =~ s#/+$##;
2514 if ($rwr !~ m#^[a-z\+]+://#) {
2515 die "$rwr is not a valid URL (key: $k)\n";
2518 $self->{-rewrite_root} = $rwr;
2521 sub rewrite_uuid {
2522 my ($self) = @_;
2523 return $self->{-rewrite_uuid} if exists $self->{-rewrite_uuid};
2524 my $k = "svn-remote.$self->{repo_id}.rewriteUUID";
2525 my $rwid = eval { command_oneline(qw/config --get/, $k) };
2526 if ($rwid) {
2527 $rwid =~ s#/+$##;
2528 if ($rwid !~ m#^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$#) {
2529 die "$rwid is not a valid UUID (key: $k)\n";
2532 $self->{-rewrite_uuid} = $rwid;
2535 sub metadata_url {
2536 my ($self) = @_;
2537 ($self->rewrite_root || $self->{url}) .
2538 (length $self->{path} ? '/' . $self->{path} : '');
2541 sub full_url {
2542 my ($self) = @_;
2543 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2547 sub set_commit_header_env {
2548 my ($log_entry) = @_;
2549 my %env;
2550 foreach my $ned (qw/NAME EMAIL DATE/) {
2551 foreach my $ac (qw/AUTHOR COMMITTER/) {
2552 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2556 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2557 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2558 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2560 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2561 ? $log_entry->{commit_name}
2562 : $log_entry->{name};
2563 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2564 ? $log_entry->{commit_email}
2565 : $log_entry->{email};
2566 \%env;
2569 sub restore_commit_header_env {
2570 my ($env) = @_;
2571 foreach my $ned (qw/NAME EMAIL DATE/) {
2572 foreach my $ac (qw/AUTHOR COMMITTER/) {
2573 my $k = "GIT_${ac}_${ned}";
2574 if (defined $env->{$k}) {
2575 $ENV{$k} = $env->{$k};
2576 } else {
2577 delete $ENV{$k};
2583 sub gc {
2584 command_noisy('gc', '--auto');
2587 sub do_git_commit {
2588 my ($self, $log_entry) = @_;
2589 my $lr = $self->last_rev;
2590 if (defined $lr && $lr >= $log_entry->{revision}) {
2591 die "Last fetched revision of ", $self->refname,
2592 " was r$lr, but we are about to fetch: ",
2593 "r$log_entry->{revision}!\n";
2595 if (my $c = $self->rev_map_get($log_entry->{revision})) {
2596 croak "$log_entry->{revision} = $c already exists! ",
2597 "Why are we refetching it?\n";
2599 my $old_env = set_commit_header_env($log_entry);
2600 my $tree = $log_entry->{tree};
2601 if (!defined $tree) {
2602 $tree = $self->tmp_index_do(sub {
2603 command_oneline('write-tree') });
2605 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2607 my @exec = ('git', 'commit-tree', $tree);
2608 foreach ($self->get_commit_parents($log_entry)) {
2609 push @exec, '-p', $_;
2611 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2612 or croak $!;
2613 binmode $msg_fh;
2615 # we always get UTF-8 from SVN, but we may want our commits in
2616 # a different encoding.
2617 if (my $enc = Git::config('i18n.commitencoding')) {
2618 require Encode;
2619 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
2621 print $msg_fh $log_entry->{log} or croak $!;
2622 restore_commit_header_env($old_env);
2623 unless ($self->no_metadata) {
2624 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2625 or croak $!;
2627 $msg_fh->flush == 0 or croak $!;
2628 close $msg_fh or croak $!;
2629 chomp(my $commit = do { local $/; <$out_fh> });
2630 close $out_fh or croak $!;
2631 waitpid $pid, 0;
2632 croak $? if $?;
2633 if ($commit !~ /^$::sha1$/o) {
2634 die "Failed to commit, invalid sha1: $commit\n";
2637 $self->rev_map_set($log_entry->{revision}, $commit, 1);
2639 $self->{last_rev} = $log_entry->{revision};
2640 $self->{last_commit} = $commit;
2641 print "r$log_entry->{revision}" unless $::_q > 1;
2642 if (defined $log_entry->{svm_revision}) {
2643 print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
2644 $self->rev_map_set($log_entry->{svm_revision}, $commit,
2645 0, $self->svm_uuid);
2647 print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
2648 if (--$_gc_nr == 0) {
2649 $_gc_nr = $_gc_period;
2650 gc();
2652 return $commit;
2655 sub match_paths {
2656 my ($self, $paths, $r) = @_;
2657 return 1 if $self->{path} eq '';
2658 if (my $path = $paths->{"/$self->{path}"}) {
2659 return ($path->{action} eq 'D') ? 0 : 1;
2661 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
2662 if (grep /$self->{path_regex}/, keys %$paths) {
2663 return 1;
2665 my $c = '';
2666 foreach (split m#/#, $self->{path}) {
2667 $c .= "/$_";
2668 next unless ($paths->{$c} &&
2669 ($paths->{$c}->{action} =~ /^[AR]$/));
2670 if ($self->ra->check_path($self->{path}, $r) ==
2671 $SVN::Node::dir) {
2672 return 1;
2675 return 0;
2678 sub find_parent_branch {
2679 my ($self, $paths, $rev) = @_;
2680 return undef unless $self->follow_parent;
2681 unless (defined $paths) {
2682 my $err_handler = $SVN::Error::handler;
2683 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2684 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1,
2685 sub { $paths = $_[0] });
2686 $SVN::Error::handler = $err_handler;
2688 return undef unless defined $paths;
2690 # look for a parent from another branch:
2691 my @b_path_components = split m#/#, $self->{path};
2692 my @a_path_components;
2693 my $i;
2694 while (@b_path_components) {
2695 $i = $paths->{'/'.join('/', @b_path_components)};
2696 last if $i && defined $i->{copyfrom_path};
2697 unshift(@a_path_components, pop(@b_path_components));
2699 return undef unless defined $i && defined $i->{copyfrom_path};
2700 my $branch_from = $i->{copyfrom_path};
2701 if (@a_path_components) {
2702 print STDERR "branch_from: $branch_from => ";
2703 $branch_from .= '/'.join('/', @a_path_components);
2704 print STDERR $branch_from, "\n";
2706 my $r = $i->{copyfrom_rev};
2707 my $repos_root = $self->ra->{repos_root};
2708 my $url = $self->ra->{url};
2709 my $new_url = $url . $branch_from;
2710 print STDERR "Found possible branch point: ",
2711 "$new_url => ", $self->full_url, ", $r\n"
2712 unless $::_q > 1;
2713 $branch_from =~ s#^/##;
2714 my $gs = $self->other_gs($new_url, $url,
2715 $branch_from, $r, $self->{ref_id});
2716 my ($r0, $parent) = $gs->find_rev_before($r, 1);
2718 my ($base, $head);
2719 if (!defined $r0 || !defined $parent) {
2720 ($base, $head) = parse_revision_argument(0, $r);
2721 } else {
2722 if ($r0 < $r) {
2723 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
2724 0, 1, sub { $base = $_[1] - 1 });
2727 if (defined $base && $base <= $r) {
2728 $gs->fetch($base, $r);
2730 ($r0, $parent) = $gs->find_rev_before($r, 1);
2732 if (defined $r0 && defined $parent) {
2733 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n"
2734 unless $::_q > 1;
2735 my $ed;
2736 if ($self->ra->can_do_switch) {
2737 $self->assert_index_clean($parent);
2738 print STDERR "Following parent with do_switch\n"
2739 unless $::_q > 1;
2740 # do_switch works with svn/trunk >= r22312, but that
2741 # is not included with SVN 1.4.3 (the latest version
2742 # at the moment), so we can't rely on it
2743 $self->{last_rev} = $r0;
2744 $self->{last_commit} = $parent;
2745 $ed = SVN::Git::Fetcher->new($self, $gs->{path});
2746 $gs->ra->gs_do_switch($r0, $rev, $gs,
2747 $self->full_url, $ed)
2748 or die "SVN connection failed somewhere...\n";
2749 } elsif ($self->ra->trees_match($new_url, $r0,
2750 $self->full_url, $rev)) {
2751 print STDERR "Trees match:\n",
2752 " $new_url\@$r0\n",
2753 " ${\$self->full_url}\@$rev\n",
2754 "Following parent with no changes\n"
2755 unless $::_q > 1;
2756 $self->tmp_index_do(sub {
2757 command_noisy('read-tree', $parent);
2759 $self->{last_commit} = $parent;
2760 } else {
2761 print STDERR "Following parent with do_update\n"
2762 unless $::_q > 1;
2763 $ed = SVN::Git::Fetcher->new($self);
2764 $self->ra->gs_do_update($rev, $rev, $self, $ed)
2765 or die "SVN connection failed somewhere...\n";
2767 print STDERR "Successfully followed parent\n" unless $::_q > 1;
2768 return $self->make_log_entry($rev, [$parent], $ed);
2770 return undef;
2773 sub do_fetch {
2774 my ($self, $paths, $rev) = @_;
2775 my $ed;
2776 my ($last_rev, @parents);
2777 if (my $lc = $self->last_commit) {
2778 # we can have a branch that was deleted, then re-added
2779 # under the same name but copied from another path, in
2780 # which case we'll have multiple parents (we don't
2781 # want to break the original ref, nor lose copypath info):
2782 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2783 push @{$log_entry->{parents}}, $lc;
2784 return $log_entry;
2786 $ed = SVN::Git::Fetcher->new($self);
2787 $last_rev = $self->{last_rev};
2788 $ed->{c} = $lc;
2789 @parents = ($lc);
2790 } else {
2791 $last_rev = $rev;
2792 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2793 return $log_entry;
2795 $ed = SVN::Git::Fetcher->new($self);
2797 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2798 die "SVN connection failed somewhere...\n";
2800 $self->make_log_entry($rev, \@parents, $ed);
2803 sub mkemptydirs {
2804 my ($self, $r) = @_;
2806 sub scan {
2807 my ($r, $empty_dirs, $line) = @_;
2808 if (defined $r && $line =~ /^r(\d+)$/) {
2809 return 0 if $1 > $r;
2810 } elsif ($line =~ /^ \+empty_dir: (.+)$/) {
2811 $empty_dirs->{$1} = 1;
2812 } elsif ($line =~ /^ \-empty_dir: (.+)$/) {
2813 my @d = grep {m[^\Q$1\E(/|$)]} (keys %$empty_dirs);
2814 delete @$empty_dirs{@d};
2816 1; # continue
2819 my %empty_dirs = ();
2820 my $gz_file = "$self->{dir}/unhandled.log.gz";
2821 if (-f $gz_file) {
2822 if (!$can_compress) {
2823 warn "Compress::Zlib could not be found; ",
2824 "empty directories in $gz_file will not be read\n";
2825 } else {
2826 my $gz = Compress::Zlib::gzopen($gz_file, "rb") or
2827 die "Unable to open $gz_file: $!\n";
2828 my $line;
2829 while ($gz->gzreadline($line) > 0) {
2830 scan($r, \%empty_dirs, $line) or last;
2832 $gz->gzclose;
2836 if (open my $fh, '<', "$self->{dir}/unhandled.log") {
2837 binmode $fh or croak "binmode: $!";
2838 while (<$fh>) {
2839 scan($r, \%empty_dirs, $_) or last;
2841 close $fh;
2844 my $strip = qr/\A\Q$self->{path}\E(?:\/|$)/;
2845 foreach my $d (sort keys %empty_dirs) {
2846 $d = uri_decode($d);
2847 $d =~ s/$strip//;
2848 next unless length($d);
2849 next if -d $d;
2850 if (-e $d) {
2851 warn "$d exists but is not a directory\n";
2852 } else {
2853 print "creating empty directory: $d\n";
2854 mkpath([$d]);
2859 sub get_untracked {
2860 my ($self, $ed) = @_;
2861 my @out;
2862 my $h = $ed->{empty};
2863 foreach (sort keys %$h) {
2864 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2865 push @out, " $act: " . uri_encode($_);
2866 warn "W: $act: $_\n";
2868 foreach my $t (qw/dir_prop file_prop/) {
2869 $h = $ed->{$t} or next;
2870 foreach my $path (sort keys %$h) {
2871 my $ppath = $path eq '' ? '.' : $path;
2872 foreach my $prop (sort keys %{$h->{$path}}) {
2873 next if $SKIP_PROP{$prop};
2874 my $v = $h->{$path}->{$prop};
2875 my $t_ppath_prop = "$t: " .
2876 uri_encode($ppath) . ' ' .
2877 uri_encode($prop);
2878 if (defined $v) {
2879 push @out, " +$t_ppath_prop " .
2880 uri_encode($v);
2881 } else {
2882 push @out, " -$t_ppath_prop";
2887 foreach my $t (qw/absent_file absent_directory/) {
2888 $h = $ed->{$t} or next;
2889 foreach my $parent (sort keys %$h) {
2890 foreach my $path (sort @{$h->{$parent}}) {
2891 push @out, " $t: " .
2892 uri_encode("$parent/$path");
2893 warn "W: $t: $parent/$path ",
2894 "Insufficient permissions?\n";
2898 \@out;
2901 # parse_svn_date(DATE)
2902 # --------------------
2903 # Given a date (in UTC) from Subversion, return a string in the format
2904 # "<TZ Offset> <local date/time>" that Git will use.
2906 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
2907 # is true we'll convert it to the local timezone instead.
2908 sub parse_svn_date {
2909 my $date = shift || return '+0000 1970-01-01 00:00:00';
2910 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2911 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
2912 croak "Unable to parse date: $date\n";
2913 my $parsed_date; # Set next.
2915 if ($Git::SVN::_localtime) {
2916 # Translate the Subversion datetime to an epoch time.
2917 # Begin by switching ourselves to $date's timezone, UTC.
2918 my $old_env_TZ = $ENV{TZ};
2919 $ENV{TZ} = 'UTC';
2921 my $epoch_in_UTC =
2922 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
2924 # Determine our local timezone (including DST) at the
2925 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
2926 # value of TZ, if any, at the time we were run.
2927 if (defined $Git::SVN::Log::TZ) {
2928 $ENV{TZ} = $Git::SVN::Log::TZ;
2929 } else {
2930 delete $ENV{TZ};
2933 my $our_TZ =
2934 POSIX::strftime('%Z', $S, $M, $H, $d, $m - 1, $Y - 1900);
2936 # This converts $epoch_in_UTC into our local timezone.
2937 my ($sec, $min, $hour, $mday, $mon, $year,
2938 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
2940 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
2941 $our_TZ, $year + 1900, $mon + 1,
2942 $mday, $hour, $min, $sec);
2944 # Reset us to the timezone in effect when we entered
2945 # this routine.
2946 if (defined $old_env_TZ) {
2947 $ENV{TZ} = $old_env_TZ;
2948 } else {
2949 delete $ENV{TZ};
2951 } else {
2952 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
2955 return $parsed_date;
2958 sub other_gs {
2959 my ($self, $new_url, $url,
2960 $branch_from, $r, $old_ref_id) = @_;
2961 my $gs = Git::SVN->find_by_url($new_url, $url, $branch_from);
2962 unless ($gs) {
2963 my $ref_id = $old_ref_id;
2964 $ref_id =~ s/\@\d+-*$//;
2965 $ref_id .= "\@$r";
2966 # just grow a tail if we're not unique enough :x
2967 $ref_id .= '-' while find_ref($ref_id);
2968 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
2969 if ($u =~ s#^\Q$url\E(/|$)##) {
2970 $p = $u;
2971 $u = $url;
2972 $repo_id = $self->{repo_id};
2974 while (1) {
2975 # It is possible to tag two different subdirectories at
2976 # the same revision. If the url for an existing ref
2977 # does not match, we must either find a ref with a
2978 # matching url or create a new ref by growing a tail.
2979 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
2980 my (undef, $max_commit) = $gs->rev_map_max(1);
2981 last if (!$max_commit);
2982 my ($url) = ::cmt_metadata($max_commit);
2983 last if ($url eq $gs->full_url);
2984 $ref_id .= '-';
2986 print STDERR "Initializing parent: $ref_id\n" unless $::_q > 1;
2991 sub call_authors_prog {
2992 my ($orig_author) = @_;
2993 $orig_author = command_oneline('rev-parse', '--sq-quote', $orig_author);
2994 my $author = `$::_authors_prog $orig_author`;
2995 if ($? != 0) {
2996 die "$::_authors_prog failed with exit code $?\n"
2998 if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
2999 my ($name, $email) = ($1, $2);
3000 $email = undef if length $2 == 0;
3001 return [$name, $email];
3002 } else {
3003 die "Author: $orig_author: $::_authors_prog returned "
3004 . "invalid author format: $author\n";
3008 sub check_author {
3009 my ($author) = @_;
3010 if (!defined $author || length $author == 0) {
3011 $author = '(no author)';
3013 if (!defined $::users{$author}) {
3014 if (defined $::_authors_prog) {
3015 $::users{$author} = call_authors_prog($author);
3016 } elsif (defined $::_authors) {
3017 die "Author: $author not defined in $::_authors file\n";
3020 $author;
3023 sub find_extra_svk_parents {
3024 my ($self, $ed, $tickets, $parents) = @_;
3025 # aha! svk:merge property changed...
3026 my @tickets = split "\n", $tickets;
3027 my @known_parents;
3028 for my $ticket ( @tickets ) {
3029 my ($uuid, $path, $rev) = split /:/, $ticket;
3030 if ( $uuid eq $self->ra_uuid ) {
3031 my $url = $self->{url};
3032 my $repos_root = $url;
3033 my $branch_from = $path;
3034 $branch_from =~ s{^/}{};
3035 my $gs = $self->other_gs($repos_root."/".$branch_from,
3036 $url,
3037 $branch_from,
3038 $rev,
3039 $self->{ref_id});
3040 if ( my $commit = $gs->rev_map_get($rev, $uuid) ) {
3041 # wahey! we found it, but it might be
3042 # an old one (!)
3043 push @known_parents, [ $rev, $commit ];
3047 # Ordering matters; highest-numbered commit merge tickets
3048 # first, as they may account for later merge ticket additions
3049 # or changes.
3050 @known_parents = map {$_->[1]} sort {$b->[0] <=> $a->[0]} @known_parents;
3051 for my $parent ( @known_parents ) {
3052 my @cmd = ('rev-list', $parent, map { "^$_" } @$parents );
3053 my ($msg_fh, $ctx) = command_output_pipe(@cmd);
3054 my $new;
3055 while ( <$msg_fh> ) {
3056 $new=1;last;
3058 command_close_pipe($msg_fh, $ctx);
3059 if ( $new ) {
3060 print STDERR
3061 "Found merge parent (svk:merge ticket): $parent\n";
3062 push @$parents, $parent;
3067 sub lookup_svn_merge {
3068 my $uuid = shift;
3069 my $url = shift;
3070 my $merge = shift;
3072 my ($source, $revs) = split ":", $merge;
3073 my $path = $source;
3074 $path =~ s{^/}{};
3075 my $gs = Git::SVN->find_by_url($url.$source, $url, $path);
3076 if ( !$gs ) {
3077 warn "Couldn't find revmap for $url$source\n";
3078 return;
3080 my @ranges = split ",", $revs;
3081 my ($tip, $tip_commit);
3082 my @merged_commit_ranges;
3083 # find the tip
3084 for my $range ( @ranges ) {
3085 my ($bottom, $top) = split "-", $range;
3086 $top ||= $bottom;
3087 my $bottom_commit = $gs->find_rev_after( $bottom, 1, $top );
3088 my $top_commit = $gs->find_rev_before( $top, 1, $bottom );
3090 unless ($top_commit and $bottom_commit) {
3091 warn "W:unknown path/rev in svn:mergeinfo "
3092 ."dirprop: $source:$range\n";
3093 next;
3096 push @merged_commit_ranges,
3097 "$bottom_commit^..$top_commit";
3099 if ( !defined $tip or $top > $tip ) {
3100 $tip = $top;
3101 $tip_commit = $top_commit;
3104 return ($tip_commit, @merged_commit_ranges);
3107 sub _rev_list {
3108 my ($msg_fh, $ctx) = command_output_pipe(
3109 "rev-list", @_,
3111 my @rv;
3112 while ( <$msg_fh> ) {
3113 chomp;
3114 push @rv, $_;
3116 command_close_pipe($msg_fh, $ctx);
3117 @rv;
3120 sub check_cherry_pick {
3121 my $base = shift;
3122 my $tip = shift;
3123 my $parents = shift;
3124 my @ranges = @_;
3125 my %commits = map { $_ => 1 }
3126 _rev_list("--no-merges", $tip, "--not", $base, @$parents);
3127 for my $range ( @ranges ) {
3128 delete @commits{_rev_list($range)};
3130 for my $commit (keys %commits) {
3131 if (has_no_changes($commit)) {
3132 delete $commits{$commit};
3135 return (keys %commits);
3138 sub has_no_changes {
3139 my $commit = shift;
3141 my @revs = split / /, command_oneline(
3142 qw(rev-list --parents -1 -m), $commit);
3144 # Commits with no parents, e.g. the start of a partial branch,
3145 # have changes by definition.
3146 return 1 if (@revs < 2);
3148 # Commits with multiple parents, e.g a merge, have no changes
3149 # by definition.
3150 return 0 if (@revs > 2);
3152 return (command_oneline("rev-parse", "$commit^{tree}") eq
3153 command_oneline("rev-parse", "$commit~1^{tree}"));
3156 # The GIT_DIR environment variable is not always set until after the command
3157 # line arguments are processed, so we can't memoize in a BEGIN block.
3159 my $memoized = 0;
3161 sub memoize_svn_mergeinfo_functions {
3162 return if $memoized;
3163 $memoized = 1;
3165 my $cache_path = "$ENV{GIT_DIR}/svn/.caches/";
3166 mkpath([$cache_path]) unless -d $cache_path;
3168 tie my %lookup_svn_merge_cache => 'Memoize::Storable',
3169 "$cache_path/lookup_svn_merge.db", 'nstore';
3170 memoize 'lookup_svn_merge',
3171 SCALAR_CACHE => 'FAULT',
3172 LIST_CACHE => ['HASH' => \%lookup_svn_merge_cache],
3175 tie my %check_cherry_pick_cache => 'Memoize::Storable',
3176 "$cache_path/check_cherry_pick.db", 'nstore';
3177 memoize 'check_cherry_pick',
3178 SCALAR_CACHE => 'FAULT',
3179 LIST_CACHE => ['HASH' => \%check_cherry_pick_cache],
3182 tie my %has_no_changes_cache => 'Memoize::Storable',
3183 "$cache_path/has_no_changes.db", 'nstore';
3184 memoize 'has_no_changes',
3185 SCALAR_CACHE => ['HASH' => \%has_no_changes_cache],
3186 LIST_CACHE => 'FAULT',
3190 sub unmemoize_svn_mergeinfo_functions {
3191 return if not $memoized;
3192 $memoized = 0;
3194 Memoize::unmemoize 'lookup_svn_merge';
3195 Memoize::unmemoize 'check_cherry_pick';
3196 Memoize::unmemoize 'has_no_changes';
3200 END {
3201 # Force cache writeout explicitly instead of waiting for
3202 # global destruction to avoid segfault in Storable:
3203 # http://rt.cpan.org/Public/Bug/Display.html?id=36087
3204 unmemoize_svn_mergeinfo_functions();
3207 sub parents_exclude {
3208 my $parents = shift;
3209 my @commits = @_;
3210 return unless @commits;
3212 my @excluded;
3213 my $excluded;
3214 do {
3215 my @cmd = ('rev-list', "-1", @commits, "--not", @$parents );
3216 $excluded = command_oneline(@cmd);
3217 if ( $excluded ) {
3218 my @new;
3219 my $found;
3220 for my $commit ( @commits ) {
3221 if ( $commit eq $excluded ) {
3222 push @excluded, $commit;
3223 $found++;
3224 last;
3226 else {
3227 push @new, $commit;
3230 die "saw commit '$excluded' in rev-list output, "
3231 ."but we didn't ask for that commit (wanted: @commits --not @$parents)"
3232 unless $found;
3233 @commits = @new;
3236 while ($excluded and @commits);
3238 return @excluded;
3242 # note: this function should only be called if the various dirprops
3243 # have actually changed
3244 sub find_extra_svn_parents {
3245 my ($self, $ed, $mergeinfo, $parents) = @_;
3246 # aha! svk:merge property changed...
3248 memoize_svn_mergeinfo_functions();
3250 # We first search for merged tips which are not in our
3251 # history. Then, we figure out which git revisions are in
3252 # that tip, but not this revision. If all of those revisions
3253 # are now marked as merge, we can add the tip as a parent.
3254 my @merges = split "\n", $mergeinfo;
3255 my @merge_tips;
3256 my $url = $self->{url};
3257 my $uuid = $self->ra_uuid;
3258 my %ranges;
3259 for my $merge ( @merges ) {
3260 my ($tip_commit, @ranges) =
3261 lookup_svn_merge( $uuid, $url, $merge );
3262 unless (!$tip_commit or
3263 grep { $_ eq $tip_commit } @$parents ) {
3264 push @merge_tips, $tip_commit;
3265 $ranges{$tip_commit} = \@ranges;
3266 } else {
3267 push @merge_tips, undef;
3271 my %excluded = map { $_ => 1 }
3272 parents_exclude($parents, grep { defined } @merge_tips);
3274 # check merge tips for new parents
3275 my @new_parents;
3276 for my $merge_tip ( @merge_tips ) {
3277 my $spec = shift @merges;
3278 next unless $merge_tip and $excluded{$merge_tip};
3280 my $ranges = $ranges{$merge_tip};
3282 # check out 'new' tips
3283 my $merge_base;
3284 eval {
3285 $merge_base = command_oneline(
3286 "merge-base",
3287 @$parents, $merge_tip,
3290 if ($@) {
3291 die "An error occurred during merge-base"
3292 unless $@->isa("Git::Error::Command");
3294 warn "W: Cannot find common ancestor between ".
3295 "@$parents and $merge_tip. Ignoring merge info.\n";
3296 next;
3299 # double check that there are no missing non-merge commits
3300 my (@incomplete) = check_cherry_pick(
3301 $merge_base, $merge_tip,
3302 $parents,
3303 @$ranges,
3306 if ( @incomplete ) {
3307 warn "W:svn cherry-pick ignored ($spec) - missing "
3308 .@incomplete." commit(s) (eg $incomplete[0])\n";
3309 } else {
3310 warn
3311 "Found merge parent (svn:mergeinfo prop): ",
3312 $merge_tip, "\n";
3313 push @new_parents, $merge_tip;
3317 # cater for merges which merge commits from multiple branches
3318 if ( @new_parents > 1 ) {
3319 for ( my $i = 0; $i <= $#new_parents; $i++ ) {
3320 for ( my $j = 0; $j <= $#new_parents; $j++ ) {
3321 next if $i == $j;
3322 next unless $new_parents[$i];
3323 next unless $new_parents[$j];
3324 my $revs = command_oneline(
3325 "rev-list", "-1",
3326 "$new_parents[$i]..$new_parents[$j]",
3328 if ( !$revs ) {
3329 undef($new_parents[$j]);
3334 push @$parents, grep { defined } @new_parents;
3337 sub make_log_entry {
3338 my ($self, $rev, $parents, $ed) = @_;
3339 my $untracked = $self->get_untracked($ed);
3341 my @parents = @$parents;
3342 my $ps = $ed->{path_strip} || "";
3343 for my $path ( grep { m/$ps/ } %{$ed->{dir_prop}} ) {
3344 my $props = $ed->{dir_prop}{$path};
3345 if ( $props->{"svk:merge"} ) {
3346 $self->find_extra_svk_parents
3347 ($ed, $props->{"svk:merge"}, \@parents);
3349 if ( $props->{"svn:mergeinfo"} ) {
3350 $self->find_extra_svn_parents
3351 ($ed,
3352 $props->{"svn:mergeinfo"},
3353 \@parents);
3357 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
3358 print $un "r$rev\n" or croak $!;
3359 print $un $_, "\n" foreach @$untracked;
3360 my %log_entry = ( parents => \@parents, revision => $rev,
3361 log => '');
3363 my $headrev;
3364 my $logged = delete $self->{logged_rev_props};
3365 if (!$logged || $self->{-want_revprops}) {
3366 my $rp = $self->ra->rev_proplist($rev);
3367 foreach (sort keys %$rp) {
3368 my $v = $rp->{$_};
3369 if (/^svn:(author|date|log)$/) {
3370 $log_entry{$1} = $v;
3371 } elsif ($_ eq 'svm:headrev') {
3372 $headrev = $v;
3373 } else {
3374 print $un " rev_prop: ", uri_encode($_), ' ',
3375 uri_encode($v), "\n";
3378 } else {
3379 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
3381 close $un or croak $!;
3383 $log_entry{date} = parse_svn_date($log_entry{date});
3384 $log_entry{log} .= "\n";
3385 my $author = $log_entry{author} = check_author($log_entry{author});
3386 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
3387 : ($author, undef);
3389 my ($commit_name, $commit_email) = ($name, $email);
3390 if ($_use_log_author) {
3391 my $name_field;
3392 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
3393 $name_field = $1;
3394 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
3395 $name_field = $1;
3397 if (!defined $name_field) {
3398 if (!defined $email) {
3399 $email = $name;
3401 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
3402 ($name, $email) = ($1, $2);
3403 } elsif ($name_field =~ /(.*)@/) {
3404 ($name, $email) = ($1, $name_field);
3405 } else {
3406 ($name, $email) = ($name_field, $name_field);
3409 if (defined $headrev && $self->use_svm_props) {
3410 if ($self->rewrite_root) {
3411 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
3412 "options set!\n";
3414 if ($self->rewrite_uuid) {
3415 die "Can't have both 'useSvmProps' and 'rewriteUUID' ",
3416 "options set!\n";
3418 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$}i;
3419 # we don't want "SVM: initializing mirror for junk" ...
3420 return undef if $r == 0;
3421 my $svm = $self->svm;
3422 if ($uuid ne $svm->{uuid}) {
3423 die "UUID mismatch on SVM path:\n",
3424 "expected: $svm->{uuid}\n",
3425 " got: $uuid\n";
3427 my $full_url = $self->full_url;
3428 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
3429 die "Failed to replace '$svm->{replace}' with ",
3430 "'$svm->{source}' in $full_url\n";
3431 # throw away username for storing in records
3432 remove_username($full_url);
3433 $log_entry{metadata} = "$full_url\@$r $uuid";
3434 $log_entry{svm_revision} = $r;
3435 $email ||= "$author\@$uuid";
3436 $commit_email ||= "$author\@$uuid";
3437 } elsif ($self->use_svnsync_props) {
3438 my $full_url = $self->svnsync->{url};
3439 $full_url .= "/$self->{path}" if length $self->{path};
3440 remove_username($full_url);
3441 my $uuid = $self->svnsync->{uuid};
3442 $log_entry{metadata} = "$full_url\@$rev $uuid";
3443 $email ||= "$author\@$uuid";
3444 $commit_email ||= "$author\@$uuid";
3445 } else {
3446 my $url = $self->metadata_url;
3447 remove_username($url);
3448 my $uuid = $self->rewrite_uuid || $self->ra->get_uuid;
3449 $log_entry{metadata} = "$url\@$rev " . $uuid;
3450 $email ||= "$author\@" . $uuid;
3451 $commit_email ||= "$author\@" . $uuid;
3453 $log_entry{name} = $name;
3454 $log_entry{email} = $email;
3455 $log_entry{commit_name} = $commit_name;
3456 $log_entry{commit_email} = $commit_email;
3457 \%log_entry;
3460 sub fetch {
3461 my ($self, $min_rev, $max_rev, @parents) = @_;
3462 my ($last_rev, $last_commit) = $self->last_rev_commit;
3463 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
3464 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
3467 sub set_tree_cb {
3468 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
3469 $self->{inject_parents} = { $rev => $tree };
3470 $self->fetch(undef, undef);
3473 sub set_tree {
3474 my ($self, $tree) = (shift, shift);
3475 my $log_entry = ::get_commit_entry($tree);
3476 unless ($self->{last_rev}) {
3477 ::fatal("Must have an existing revision to commit");
3479 my %ed_opts = ( r => $self->{last_rev},
3480 log => $log_entry->{log},
3481 ra => $self->ra,
3482 tree_a => $self->{last_commit},
3483 tree_b => $tree,
3484 editor_cb => sub {
3485 $self->set_tree_cb($log_entry, $tree, @_) },
3486 svn_path => $self->{path} );
3487 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
3488 print "No changes\nr$self->{last_rev} = $tree\n";
3492 sub rebuild_from_rev_db {
3493 my ($self, $path) = @_;
3494 my $r = -1;
3495 open my $fh, '<', $path or croak "open: $!";
3496 binmode $fh or croak "binmode: $!";
3497 while (<$fh>) {
3498 length($_) == 41 or croak "inconsistent size in ($_) != 41";
3499 chomp($_);
3500 ++$r;
3501 next if $_ eq ('0' x 40);
3502 $self->rev_map_set($r, $_);
3503 print "r$r = $_\n";
3505 close $fh or croak "close: $!";
3506 unlink $path or croak "unlink: $!";
3509 sub rebuild {
3510 my ($self) = @_;
3511 my $map_path = $self->map_path;
3512 my $partial = (-e $map_path && ! -z $map_path);
3513 return unless ::verify_ref($self->refname.'^0');
3514 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
3515 my $rev_db = $self->rev_db_path;
3516 $self->rebuild_from_rev_db($rev_db);
3517 if ($self->use_svm_props) {
3518 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
3519 $self->rebuild_from_rev_db($svm_rev_db);
3521 $self->unlink_rev_db_symlink;
3522 return;
3524 print "Rebuilding $map_path ...\n" if (!$partial);
3525 my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
3526 (undef, undef));
3527 my ($log, $ctx) =
3528 command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
3529 ($head ? "$head.." : "") . $self->refname,
3530 '--');
3531 my $metadata_url = $self->metadata_url;
3532 remove_username($metadata_url);
3533 my $svn_uuid = $self->rewrite_uuid || $self->ra_uuid;
3534 my $c;
3535 while (<$log>) {
3536 if ( m{^commit ($::sha1)$} ) {
3537 $c = $1;
3538 next;
3540 next unless s{^\s*(git-svn-id:)}{$1};
3541 my ($url, $rev, $uuid) = ::extract_metadata($_);
3542 remove_username($url);
3544 # ignore merges (from set-tree)
3545 next if (!defined $rev || !$uuid);
3547 # if we merged or otherwise started elsewhere, this is
3548 # how we break out of it
3549 if (($uuid ne $svn_uuid) ||
3550 ($metadata_url && $url && ($url ne $metadata_url))) {
3551 next;
3553 if ($partial && $head) {
3554 print "Partial-rebuilding $map_path ...\n";
3555 print "Currently at $base_rev = $head\n";
3556 $head = undef;
3559 $self->rev_map_set($rev, $c);
3560 print "r$rev = $c\n";
3562 command_close_pipe($log, $ctx);
3563 print "Done rebuilding $map_path\n" if (!$partial || !$head);
3564 my $rev_db_path = $self->rev_db_path;
3565 if (-f $self->rev_db_path) {
3566 unlink $self->rev_db_path or croak "unlink: $!";
3568 $self->unlink_rev_db_symlink;
3571 # rev_map:
3572 # Tie::File seems to be prone to offset errors if revisions get sparse,
3573 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
3574 # one of my favorite modules is out :< Next up would be one of the DBM
3575 # modules, but I'm not sure which is most portable...
3577 # This is the replacement for the rev_db format, which was too big
3578 # and inefficient for large repositories with a lot of sparse history
3579 # (mainly tags)
3581 # The format is this:
3582 # - 24 bytes for every record,
3583 # * 4 bytes for the integer representing an SVN revision number
3584 # * 20 bytes representing the sha1 of a git commit
3585 # - No empty padding records like the old format
3586 # (except the last record, which can be overwritten)
3587 # - new records are written append-only since SVN revision numbers
3588 # increase monotonically
3589 # - lookups on SVN revision number are done via a binary search
3590 # - Piping the file to xxd -c24 is a good way of dumping it for
3591 # viewing or editing (piped back through xxd -r), should the need
3592 # ever arise.
3593 # - The last record can be padding revision with an all-zero sha1
3594 # This is used to optimize fetch performance when using multiple
3595 # "fetch" directives in .git/config
3597 # These files are disposable unless noMetadata or useSvmProps is set
3599 sub _rev_map_set {
3600 my ($fh, $rev, $commit) = @_;
3602 binmode $fh or croak "binmode: $!";
3603 my $size = (stat($fh))[7];
3604 ($size % 24) == 0 or croak "inconsistent size: $size";
3606 my $wr_offset = 0;
3607 if ($size > 0) {
3608 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3609 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
3610 $read == 24 or croak "read only $read bytes (!= 24)";
3611 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
3612 if ($last_commit eq ('0' x40)) {
3613 if ($size >= 48) {
3614 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3615 $read = sysread($fh, $buf, 24) or
3616 croak "read: $!";
3617 $read == 24 or
3618 croak "read only $read bytes (!= 24)";
3619 ($last_rev, $last_commit) =
3620 unpack(rev_map_fmt, $buf);
3621 if ($last_commit eq ('0' x40)) {
3622 croak "inconsistent .rev_map\n";
3625 if ($last_rev >= $rev) {
3626 croak "last_rev is higher!: $last_rev >= $rev";
3628 $wr_offset = -24;
3631 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
3632 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
3633 croak "write: $!";
3636 sub _rev_map_reset {
3637 my ($fh, $rev, $commit) = @_;
3638 my $c = _rev_map_get($fh, $rev);
3639 $c eq $commit or die "_rev_map_reset(@_) commit $c does not match!\n";
3640 my $offset = sysseek($fh, 0, SEEK_CUR) or croak "seek: $!";
3641 truncate $fh, $offset or croak "truncate: $!";
3644 sub mkfile {
3645 my ($path) = @_;
3646 unless (-e $path) {
3647 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
3648 mkpath([$dir]) unless -d $dir;
3649 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
3650 close $fh or die "Couldn't close (create) $path: $!\n";
3654 sub rev_map_set {
3655 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
3656 defined $commit or die "missing arg3\n";
3657 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
3658 my $db = $self->map_path($uuid);
3659 my $db_lock = "$db.lock";
3660 my $sig;
3661 $update_ref ||= 0;
3662 if ($update_ref) {
3663 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3664 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
3666 mkfile($db);
3668 $LOCKFILES{$db_lock} = 1;
3669 my $sync;
3670 # both of these options make our .rev_db file very, very important
3671 # and we can't afford to lose it because rebuild() won't work
3672 if ($self->use_svm_props || $self->no_metadata) {
3673 $sync = 1;
3674 copy($db, $db_lock) or die "rev_map_set(@_): ",
3675 "Failed to copy: ",
3676 "$db => $db_lock ($!)\n";
3677 } else {
3678 rename $db, $db_lock or die "rev_map_set(@_): ",
3679 "Failed to rename: ",
3680 "$db => $db_lock ($!)\n";
3683 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
3684 or croak "Couldn't open $db_lock: $!\n";
3685 $update_ref eq 'reset' ? _rev_map_reset($fh, $rev, $commit) :
3686 _rev_map_set($fh, $rev, $commit);
3687 if ($sync) {
3688 $fh->flush or die "Couldn't flush $db_lock: $!\n";
3689 $fh->sync or die "Couldn't sync $db_lock: $!\n";
3691 close $fh or croak $!;
3692 if ($update_ref) {
3693 $_head = $self;
3694 my $note = "";
3695 $note = " ($update_ref)" if ($update_ref !~ /^\d*$/);
3696 command_noisy('update-ref', '-m', "r$rev$note",
3697 $self->refname, $commit);
3699 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
3700 "$db_lock => $db ($!)\n";
3701 delete $LOCKFILES{$db_lock};
3702 if ($update_ref) {
3703 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3704 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
3705 kill $sig, $$ if defined $sig;
3709 # If want_commit, this will return an array of (rev, commit) where
3710 # commit _must_ be a valid commit in the archive.
3711 # Otherwise, it'll return the max revision (whether or not the
3712 # commit is valid or just a 0x40 placeholder).
3713 sub rev_map_max {
3714 my ($self, $want_commit) = @_;
3715 $self->rebuild;
3716 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
3717 $want_commit ? ($r, $c) : $r;
3720 sub rev_map_max_norebuild {
3721 my ($self, $want_commit) = @_;
3722 my $map_path = $self->map_path;
3723 stat $map_path or return $want_commit ? (0, undef) : 0;
3724 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3725 binmode $fh or croak "binmode: $!";
3726 my $size = (stat($fh))[7];
3727 ($size % 24) == 0 or croak "inconsistent size: $size";
3729 if ($size == 0) {
3730 close $fh or croak "close: $!";
3731 return $want_commit ? (0, undef) : 0;
3734 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3735 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3736 my ($r, $c) = unpack(rev_map_fmt, $buf);
3737 if ($want_commit && $c eq ('0' x40)) {
3738 if ($size < 48) {
3739 return $want_commit ? (0, undef) : 0;
3741 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3742 sysread($fh, $buf, 24) == 24 or croak "read: $!";
3743 ($r, $c) = unpack(rev_map_fmt, $buf);
3744 if ($c eq ('0'x40)) {
3745 croak "Penultimate record is all-zeroes in $map_path";
3748 close $fh or croak "close: $!";
3749 $want_commit ? ($r, $c) : $r;
3752 sub rev_map_get {
3753 my ($self, $rev, $uuid) = @_;
3754 my $map_path = $self->map_path($uuid);
3755 return undef unless -e $map_path;
3757 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3758 my $c = _rev_map_get($fh, $rev);
3759 close($fh) or croak "close: $!";
3763 sub _rev_map_get {
3764 my ($fh, $rev) = @_;
3766 binmode $fh or croak "binmode: $!";
3767 my $size = (stat($fh))[7];
3768 ($size % 24) == 0 or croak "inconsistent size: $size";
3770 if ($size == 0) {
3771 return undef;
3774 my ($l, $u) = (0, $size - 24);
3775 my ($r, $c, $buf);
3777 while ($l <= $u) {
3778 my $i = int(($l/24 + $u/24) / 2) * 24;
3779 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
3780 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3781 my ($r, $c) = unpack(rev_map_fmt, $buf);
3783 if ($r < $rev) {
3784 $l = $i + 24;
3785 } elsif ($r > $rev) {
3786 $u = $i - 24;
3787 } else { # $r == $rev
3788 return $c eq ('0' x 40) ? undef : $c;
3791 undef;
3794 # Finds the first svn revision that exists on (if $eq_ok is true) or
3795 # before $rev for the current branch. It will not search any lower
3796 # than $min_rev. Returns the git commit hash and svn revision number
3797 # if found, else (undef, undef).
3798 sub find_rev_before {
3799 my ($self, $rev, $eq_ok, $min_rev) = @_;
3800 --$rev unless $eq_ok;
3801 $min_rev ||= 1;
3802 my $max_rev = $self->rev_map_max;
3803 $rev = $max_rev if ($rev > $max_rev);
3804 while ($rev >= $min_rev) {
3805 if (my $c = $self->rev_map_get($rev)) {
3806 return ($rev, $c);
3808 --$rev;
3810 return (undef, undef);
3813 # Finds the first svn revision that exists on (if $eq_ok is true) or
3814 # after $rev for the current branch. It will not search any higher
3815 # than $max_rev. Returns the git commit hash and svn revision number
3816 # if found, else (undef, undef).
3817 sub find_rev_after {
3818 my ($self, $rev, $eq_ok, $max_rev) = @_;
3819 ++$rev unless $eq_ok;
3820 $max_rev ||= $self->rev_map_max;
3821 while ($rev <= $max_rev) {
3822 if (my $c = $self->rev_map_get($rev)) {
3823 return ($rev, $c);
3825 ++$rev;
3827 return (undef, undef);
3830 sub _new {
3831 my ($class, $repo_id, $ref_id, $path) = @_;
3832 unless (defined $repo_id && length $repo_id) {
3833 $repo_id = $Git::SVN::default_repo_id;
3835 unless (defined $ref_id && length $ref_id) {
3836 $_prefix = '' unless defined($_prefix);
3837 $_[2] = $ref_id =
3838 "refs/remotes/$_prefix$Git::SVN::default_ref_id";
3840 $_[1] = $repo_id;
3841 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
3843 # Older repos imported by us used $GIT_DIR/svn/foo instead of
3844 # $GIT_DIR/svn/refs/remotes/foo when tracking refs/remotes/foo
3845 if ($ref_id =~ m{^refs/remotes/(.*)}) {
3846 my $old_dir = "$ENV{GIT_DIR}/svn/$1";
3847 if (-d $old_dir && ! -d $dir) {
3848 $dir = $old_dir;
3852 $_[3] = $path = '' unless (defined $path);
3853 mkpath([$dir]);
3854 bless {
3855 ref_id => $ref_id, dir => $dir, index => "$dir/index",
3856 path => $path, config => "$ENV{GIT_DIR}/svn/config",
3857 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
3860 # for read-only access of old .rev_db formats
3861 sub unlink_rev_db_symlink {
3862 my ($self) = @_;
3863 my $link = $self->rev_db_path;
3864 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
3865 if (-l $link) {
3866 unlink $link or croak "unlink: $link failed!";
3870 sub rev_db_path {
3871 my ($self, $uuid) = @_;
3872 my $db_path = $self->map_path($uuid);
3873 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
3874 or croak "map_path: $db_path does not contain '/.rev_map.' !";
3875 $db_path;
3878 # the new replacement for .rev_db
3879 sub map_path {
3880 my ($self, $uuid) = @_;
3881 $uuid ||= $self->ra_uuid;
3882 "$self->{map_root}.$uuid";
3885 sub uri_encode {
3886 my ($f) = @_;
3887 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
3891 sub uri_decode {
3892 my ($f) = @_;
3893 $f =~ s#%([0-9a-fA-F]{2})#chr(hex($1))#eg;
3897 sub remove_username {
3898 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
3901 package Git::SVN::Prompt;
3902 use strict;
3903 use warnings;
3904 require SVN::Core;
3905 use vars qw/$_no_auth_cache $_username/;
3907 sub simple {
3908 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
3909 $may_save = undef if $_no_auth_cache;
3910 $default_username = $_username if defined $_username;
3911 if (defined $default_username && length $default_username) {
3912 if (defined $realm && length $realm) {
3913 print STDERR "Authentication realm: $realm\n";
3914 STDERR->flush;
3916 $cred->username($default_username);
3917 } else {
3918 username($cred, $realm, $may_save, $pool);
3920 $cred->password(_read_password("Password for '" .
3921 $cred->username . "': ", $realm));
3922 $cred->may_save($may_save);
3923 $SVN::_Core::SVN_NO_ERROR;
3926 sub ssl_server_trust {
3927 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
3928 $may_save = undef if $_no_auth_cache;
3929 print STDERR "Error validating server certificate for '$realm':\n";
3931 no warnings 'once';
3932 # All variables SVN::Auth::SSL::* are used only once,
3933 # so we're shutting up Perl warnings about this.
3934 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
3935 print STDERR " - The certificate is not issued ",
3936 "by a trusted authority. Use the\n",
3937 " fingerprint to validate ",
3938 "the certificate manually!\n";
3940 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
3941 print STDERR " - The certificate hostname ",
3942 "does not match.\n";
3944 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
3945 print STDERR " - The certificate is not yet valid.\n";
3947 if ($failures & $SVN::Auth::SSL::EXPIRED) {
3948 print STDERR " - The certificate has expired.\n";
3950 if ($failures & $SVN::Auth::SSL::OTHER) {
3951 print STDERR " - The certificate has ",
3952 "an unknown error.\n";
3954 } # no warnings 'once'
3955 printf STDERR
3956 "Certificate information:\n".
3957 " - Hostname: %s\n".
3958 " - Valid: from %s until %s\n".
3959 " - Issuer: %s\n".
3960 " - Fingerprint: %s\n",
3961 map $cert_info->$_, qw(hostname valid_from valid_until
3962 issuer_dname fingerprint);
3963 my $choice;
3964 prompt:
3965 print STDERR $may_save ?
3966 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
3967 "(R)eject or accept (t)emporarily? ";
3968 STDERR->flush;
3969 $choice = lc(substr(<STDIN> || 'R', 0, 1));
3970 if ($choice =~ /^t$/i) {
3971 $cred->may_save(undef);
3972 } elsif ($choice =~ /^r$/i) {
3973 return -1;
3974 } elsif ($may_save && $choice =~ /^p$/i) {
3975 $cred->may_save($may_save);
3976 } else {
3977 goto prompt;
3979 $cred->accepted_failures($failures);
3980 $SVN::_Core::SVN_NO_ERROR;
3983 sub ssl_client_cert {
3984 my ($cred, $realm, $may_save, $pool) = @_;
3985 $may_save = undef if $_no_auth_cache;
3986 print STDERR "Client certificate filename: ";
3987 STDERR->flush;
3988 chomp(my $filename = <STDIN>);
3989 $cred->cert_file($filename);
3990 $cred->may_save($may_save);
3991 $SVN::_Core::SVN_NO_ERROR;
3994 sub ssl_client_cert_pw {
3995 my ($cred, $realm, $may_save, $pool) = @_;
3996 $may_save = undef if $_no_auth_cache;
3997 $cred->password(_read_password("Password: ", $realm));
3998 $cred->may_save($may_save);
3999 $SVN::_Core::SVN_NO_ERROR;
4002 sub username {
4003 my ($cred, $realm, $may_save, $pool) = @_;
4004 $may_save = undef if $_no_auth_cache;
4005 if (defined $realm && length $realm) {
4006 print STDERR "Authentication realm: $realm\n";
4008 my $username;
4009 if (defined $_username) {
4010 $username = $_username;
4011 } else {
4012 print STDERR "Username: ";
4013 STDERR->flush;
4014 chomp($username = <STDIN>);
4016 $cred->username($username);
4017 $cred->may_save($may_save);
4018 $SVN::_Core::SVN_NO_ERROR;
4021 sub _read_password {
4022 my ($prompt, $realm) = @_;
4023 my $password = '';
4024 if (exists $ENV{GIT_ASKPASS}) {
4025 open(PH, "-|", $ENV{GIT_ASKPASS}, $prompt);
4026 $password = <PH>;
4027 $password =~ s/[\012\015]//; # \n\r
4028 close(PH);
4029 } else {
4030 print STDERR $prompt;
4031 STDERR->flush;
4032 require Term::ReadKey;
4033 Term::ReadKey::ReadMode('noecho');
4034 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
4035 last if $key =~ /[\012\015]/; # \n\r
4036 $password .= $key;
4038 Term::ReadKey::ReadMode('restore');
4039 print STDERR "\n";
4040 STDERR->flush;
4042 $password;
4045 package SVN::Git::Fetcher;
4046 use vars qw/@ISA/;
4047 use strict;
4048 use warnings;
4049 use Carp qw/croak/;
4050 use IO::File qw//;
4051 use vars qw/$_ignore_regex/;
4053 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
4054 sub new {
4055 my ($class, $git_svn, $switch_path) = @_;
4056 my $self = SVN::Delta::Editor->new;
4057 bless $self, $class;
4058 if (exists $git_svn->{last_commit}) {
4059 $self->{c} = $git_svn->{last_commit};
4060 $self->{empty_symlinks} =
4061 _mark_empty_symlinks($git_svn, $switch_path);
4063 $self->{ignore_regex} = eval { command_oneline('config', '--get',
4064 "svn-remote.$git_svn->{repo_id}.ignore-paths") };
4065 $self->{empty} = {};
4066 $self->{dir_prop} = {};
4067 $self->{file_prop} = {};
4068 $self->{absent_dir} = {};
4069 $self->{absent_file} = {};
4070 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
4071 $self->{pathnameencoding} = Git::config('svn.pathnameencoding');
4072 $self;
4075 # this uses the Ra object, so it must be called before do_{switch,update},
4076 # not inside them (when the Git::SVN::Fetcher object is passed) to
4077 # do_{switch,update}
4078 sub _mark_empty_symlinks {
4079 my ($git_svn, $switch_path) = @_;
4080 my $bool = Git::config_bool('svn.brokenSymlinkWorkaround');
4081 return {} if (!defined($bool)) || (defined($bool) && ! $bool);
4083 my %ret;
4084 my ($rev, $cmt) = $git_svn->last_rev_commit;
4085 return {} unless ($rev && $cmt);
4087 # allow the warning to be printed for each revision we fetch to
4088 # ensure the user sees it. The user can also disable the workaround
4089 # on the repository even while git svn is running and the next
4090 # revision fetched will skip this expensive function.
4091 my $printed_warning;
4092 chomp(my $empty_blob = `git hash-object -t blob --stdin < /dev/null`);
4093 my ($ls, $ctx) = command_output_pipe(qw/ls-tree -r -z/, $cmt);
4094 local $/ = "\0";
4095 my $pfx = defined($switch_path) ? $switch_path : $git_svn->{path};
4096 $pfx .= '/' if length($pfx);
4097 while (<$ls>) {
4098 chomp;
4099 s/\A100644 blob $empty_blob\t//o or next;
4100 unless ($printed_warning) {
4101 print STDERR "Scanning for empty symlinks, ",
4102 "this may take a while if you have ",
4103 "many empty files\n",
4104 "You may disable this with `",
4105 "git config svn.brokenSymlinkWorkaround ",
4106 "false'.\n",
4107 "This may be done in a different ",
4108 "terminal without restarting ",
4109 "git svn\n";
4110 $printed_warning = 1;
4112 my $path = $_;
4113 my (undef, $props) =
4114 $git_svn->ra->get_file($pfx.$path, $rev, undef);
4115 if ($props->{'svn:special'}) {
4116 $ret{$path} = 1;
4119 command_close_pipe($ls, $ctx);
4120 \%ret;
4123 # returns true if a given path is inside a ".git" directory
4124 sub in_dot_git {
4125 $_[0] =~ m{(?:^|/)\.git(?:/|$)};
4128 # return value: 0 -- don't ignore, 1 -- ignore
4129 sub is_path_ignored {
4130 my ($self, $path) = @_;
4131 return 1 if in_dot_git($path);
4132 return 1 if defined($self->{ignore_regex}) &&
4133 $path =~ m!$self->{ignore_regex}!;
4134 return 0 unless defined($_ignore_regex);
4135 return 1 if $path =~ m!$_ignore_regex!o;
4136 return 0;
4139 sub set_path_strip {
4140 my ($self, $path) = @_;
4141 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
4144 sub open_root {
4145 { path => '' };
4148 sub open_directory {
4149 my ($self, $path, $pb, $rev) = @_;
4150 { path => $path };
4153 sub git_path {
4154 my ($self, $path) = @_;
4155 if (my $enc = $self->{pathnameencoding}) {
4156 require Encode;
4157 Encode::from_to($path, 'UTF-8', $enc);
4159 if ($self->{path_strip}) {
4160 $path =~ s!$self->{path_strip}!! or
4161 die "Failed to strip path '$path' ($self->{path_strip})\n";
4163 $path;
4166 sub delete_entry {
4167 my ($self, $path, $rev, $pb) = @_;
4168 return undef if $self->is_path_ignored($path);
4170 my $gpath = $self->git_path($path);
4171 return undef if ($gpath eq '');
4173 # remove entire directories.
4174 my ($tree) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
4175 =~ /\A040000 tree ([a-f\d]{40})\t\Q$gpath\E\0/);
4176 if ($tree) {
4177 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
4178 -r --name-only -z/,
4179 $tree);
4180 local $/ = "\0";
4181 while (<$ls>) {
4182 chomp;
4183 my $rmpath = "$gpath/$_";
4184 $self->{gii}->remove($rmpath);
4185 print "\tD\t$rmpath\n" unless $::_q;
4187 print "\tD\t$gpath/\n" unless $::_q;
4188 command_close_pipe($ls, $ctx);
4189 } else {
4190 $self->{gii}->remove($gpath);
4191 print "\tD\t$gpath\n" unless $::_q;
4193 $self->{empty}->{$path} = 0;
4194 undef;
4197 sub open_file {
4198 my ($self, $path, $pb, $rev) = @_;
4199 my ($mode, $blob);
4201 goto out if $self->is_path_ignored($path);
4203 my $gpath = $self->git_path($path);
4204 ($mode, $blob) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
4205 =~ /\A(\d{6}) blob ([a-f\d]{40})\t\Q$gpath\E\0/);
4206 unless (defined $mode && defined $blob) {
4207 die "$path was not found in commit $self->{c} (r$rev)\n";
4209 if ($mode eq '100644' && $self->{empty_symlinks}->{$path}) {
4210 $mode = '120000';
4212 out:
4213 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
4214 pool => SVN::Pool->new, action => 'M' };
4217 sub add_file {
4218 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
4219 my $mode;
4221 if (!$self->is_path_ignored($path)) {
4222 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
4223 delete $self->{empty}->{$dir};
4224 $mode = '100644';
4226 { path => $path, mode_a => $mode, mode_b => $mode,
4227 pool => SVN::Pool->new, action => 'A' };
4230 sub add_directory {
4231 my ($self, $path, $cp_path, $cp_rev) = @_;
4232 goto out if $self->is_path_ignored($path);
4233 my $gpath = $self->git_path($path);
4234 if ($gpath eq '') {
4235 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
4236 -r --name-only -z/,
4237 $self->{c});
4238 local $/ = "\0";
4239 while (<$ls>) {
4240 chomp;
4241 $self->{gii}->remove($_);
4242 print "\tD\t$_\n" unless $::_q;
4244 command_close_pipe($ls, $ctx);
4245 $self->{empty}->{$path} = 0;
4247 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
4248 delete $self->{empty}->{$dir};
4249 $self->{empty}->{$path} = 1;
4250 out:
4251 { path => $path };
4254 sub change_dir_prop {
4255 my ($self, $db, $prop, $value) = @_;
4256 return undef if $self->is_path_ignored($db->{path});
4257 $self->{dir_prop}->{$db->{path}} ||= {};
4258 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
4259 undef;
4262 sub absent_directory {
4263 my ($self, $path, $pb) = @_;
4264 return undef if $self->is_path_ignored($path);
4265 $self->{absent_dir}->{$pb->{path}} ||= [];
4266 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
4267 undef;
4270 sub absent_file {
4271 my ($self, $path, $pb) = @_;
4272 return undef if $self->is_path_ignored($path);
4273 $self->{absent_file}->{$pb->{path}} ||= [];
4274 push @{$self->{absent_file}->{$pb->{path}}}, $path;
4275 undef;
4278 sub change_file_prop {
4279 my ($self, $fb, $prop, $value) = @_;
4280 return undef if $self->is_path_ignored($fb->{path});
4281 if ($prop eq 'svn:executable') {
4282 if ($fb->{mode_b} != 120000) {
4283 $fb->{mode_b} = defined $value ? 100755 : 100644;
4285 } elsif ($prop eq 'svn:special') {
4286 $fb->{mode_b} = defined $value ? 120000 : 100644;
4287 } else {
4288 $self->{file_prop}->{$fb->{path}} ||= {};
4289 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
4291 undef;
4294 sub apply_textdelta {
4295 my ($self, $fb, $exp) = @_;
4296 return undef if $self->is_path_ignored($fb->{path});
4297 my $fh = $::_repository->temp_acquire('svn_delta');
4298 # $fh gets auto-closed() by SVN::TxDelta::apply(),
4299 # (but $base does not,) so dup() it for reading in close_file
4300 open my $dup, '<&', $fh or croak $!;
4301 my $base = $::_repository->temp_acquire('git_blob');
4303 if ($fb->{blob}) {
4304 my ($base_is_link, $size);
4306 if ($fb->{mode_a} eq '120000' &&
4307 ! $self->{empty_symlinks}->{$fb->{path}}) {
4308 print $base 'link ' or die "print $!\n";
4309 $base_is_link = 1;
4311 retry:
4312 $size = $::_repository->cat_blob($fb->{blob}, $base);
4313 die "Failed to read object $fb->{blob}" if ($size < 0);
4315 if (defined $exp) {
4316 seek $base, 0, 0 or croak $!;
4317 my $got = ::md5sum($base);
4318 if ($got ne $exp) {
4319 my $err = "Checksum mismatch: ".
4320 "$fb->{path} $fb->{blob}\n" .
4321 "expected: $exp\n" .
4322 " got: $got\n";
4323 if ($base_is_link) {
4324 warn $err,
4325 "Retrying... (possibly ",
4326 "a bad symlink from SVN)\n";
4327 $::_repository->temp_reset($base);
4328 $base_is_link = 0;
4329 goto retry;
4331 die $err;
4335 seek $base, 0, 0 or croak $!;
4336 $fb->{fh} = $fh;
4337 $fb->{base} = $base;
4338 [ SVN::TxDelta::apply($base, $dup, undef, $fb->{path}, $fb->{pool}) ];
4341 sub close_file {
4342 my ($self, $fb, $exp) = @_;
4343 return undef if $self->is_path_ignored($fb->{path});
4345 my $hash;
4346 my $path = $self->git_path($fb->{path});
4347 if (my $fh = $fb->{fh}) {
4348 if (defined $exp) {
4349 seek($fh, 0, 0) or croak $!;
4350 my $got = ::md5sum($fh);
4351 if ($got ne $exp) {
4352 die "Checksum mismatch: $path\n",
4353 "expected: $exp\n got: $got\n";
4356 if ($fb->{mode_b} == 120000) {
4357 sysseek($fh, 0, 0) or croak $!;
4358 my $rd = sysread($fh, my $buf, 5);
4360 if (!defined $rd) {
4361 croak "sysread: $!\n";
4362 } elsif ($rd == 0) {
4363 warn "$path has mode 120000",
4364 " but it points to nothing\n",
4365 "converting to an empty file with mode",
4366 " 100644\n";
4367 $fb->{mode_b} = '100644';
4368 } elsif ($buf ne 'link ') {
4369 warn "$path has mode 120000",
4370 " but is not a link\n";
4371 } else {
4372 my $tmp_fh = $::_repository->temp_acquire(
4373 'svn_hash');
4374 my $res;
4375 while ($res = sysread($fh, my $str, 1024)) {
4376 my $out = syswrite($tmp_fh, $str, $res);
4377 defined($out) && $out == $res
4378 or croak("write ",
4379 Git::temp_path($tmp_fh),
4380 ": $!\n");
4382 defined $res or croak $!;
4384 ($fh, $tmp_fh) = ($tmp_fh, $fh);
4385 Git::temp_release($tmp_fh, 1);
4389 $hash = $::_repository->hash_and_insert_object(
4390 Git::temp_path($fh));
4391 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
4393 Git::temp_release($fb->{base}, 1);
4394 Git::temp_release($fh, 1);
4395 } else {
4396 $hash = $fb->{blob} or die "no blob information\n";
4398 $fb->{pool}->clear;
4399 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
4400 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
4401 undef;
4404 sub abort_edit {
4405 my $self = shift;
4406 $self->{nr} = $self->{gii}->{nr};
4407 delete $self->{gii};
4408 $self->SUPER::abort_edit(@_);
4411 sub close_edit {
4412 my $self = shift;
4413 $self->{git_commit_ok} = 1;
4414 $self->{nr} = $self->{gii}->{nr};
4415 delete $self->{gii};
4416 $self->SUPER::close_edit(@_);
4419 package SVN::Git::Editor;
4420 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
4421 use strict;
4422 use warnings;
4423 use Carp qw/croak/;
4424 use IO::File;
4426 sub new {
4427 my ($class, $opts) = @_;
4428 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
4429 die "$_ required!\n" unless (defined $opts->{$_});
4432 my $pool = SVN::Pool->new;
4433 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
4434 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
4435 $opts->{r}, $mods);
4437 # $opts->{ra} functions should not be used after this:
4438 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
4439 $opts->{editor_cb}, $pool);
4440 my $self = SVN::Delta::Editor->new(@ce, $pool);
4441 bless $self, $class;
4442 foreach (qw/svn_path r tree_a tree_b/) {
4443 $self->{$_} = $opts->{$_};
4445 $self->{url} = $opts->{ra}->{url};
4446 $self->{mods} = $mods;
4447 $self->{types} = $types;
4448 $self->{pool} = $pool;
4449 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
4450 $self->{rm} = { };
4451 $self->{path_prefix} = length $self->{svn_path} ?
4452 "$self->{svn_path}/" : '';
4453 $self->{config} = $opts->{config};
4454 return $self;
4457 sub generate_diff {
4458 my ($tree_a, $tree_b) = @_;
4459 my @diff_tree = qw(diff-tree -z -r);
4460 if ($_cp_similarity) {
4461 push @diff_tree, "-C$_cp_similarity";
4462 } else {
4463 push @diff_tree, '-C';
4465 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
4466 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
4467 push @diff_tree, $tree_a, $tree_b;
4468 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
4469 local $/ = "\0";
4470 my $state = 'meta';
4471 my @mods;
4472 while (<$diff_fh>) {
4473 chomp $_; # this gets rid of the trailing "\0"
4474 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
4475 ($::sha1)\s($::sha1)\s
4476 ([MTCRAD])\d*$/xo) {
4477 push @mods, { mode_a => $1, mode_b => $2,
4478 sha1_a => $3, sha1_b => $4,
4479 chg => $5 };
4480 if ($5 =~ /^(?:C|R)$/) {
4481 $state = 'file_a';
4482 } else {
4483 $state = 'file_b';
4485 } elsif ($state eq 'file_a') {
4486 my $x = $mods[$#mods] or croak "Empty array\n";
4487 if ($x->{chg} !~ /^(?:C|R)$/) {
4488 croak "Error parsing $_, $x->{chg}\n";
4490 $x->{file_a} = $_;
4491 $state = 'file_b';
4492 } elsif ($state eq 'file_b') {
4493 my $x = $mods[$#mods] or croak "Empty array\n";
4494 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
4495 croak "Error parsing $_, $x->{chg}\n";
4497 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
4498 croak "Error parsing $_, $x->{chg}\n";
4500 $x->{file_b} = $_;
4501 $state = 'meta';
4502 } else {
4503 croak "Error parsing $_\n";
4506 command_close_pipe($diff_fh, $ctx);
4507 \@mods;
4510 sub check_diff_paths {
4511 my ($ra, $pfx, $rev, $mods) = @_;
4512 my %types;
4513 $pfx .= '/' if length $pfx;
4515 sub type_diff_paths {
4516 my ($ra, $types, $path, $rev) = @_;
4517 my @p = split m#/+#, $path;
4518 my $c = shift @p;
4519 unless (defined $types->{$c}) {
4520 $types->{$c} = $ra->check_path($c, $rev);
4522 while (@p) {
4523 $c .= '/' . shift @p;
4524 next if defined $types->{$c};
4525 $types->{$c} = $ra->check_path($c, $rev);
4529 foreach my $m (@$mods) {
4530 foreach my $f (qw/file_a file_b/) {
4531 next unless defined $m->{$f};
4532 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
4533 if (length $pfx.$dir && ! defined $types{$dir}) {
4534 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
4538 \%types;
4541 sub split_path {
4542 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
4545 sub repo_path {
4546 my ($self, $path) = @_;
4547 if (my $enc = $self->{pathnameencoding}) {
4548 require Encode;
4549 Encode::from_to($path, $enc, 'UTF-8');
4551 $self->{path_prefix}.(defined $path ? $path : '');
4554 sub url_path {
4555 my ($self, $path) = @_;
4556 if ($self->{url} =~ m#^https?://#) {
4557 $path =~ s!([^~a-zA-Z0-9_./-])!uc sprintf("%%%02x",ord($1))!eg;
4559 $self->{url} . '/' . $self->repo_path($path);
4562 sub rmdirs {
4563 my ($self) = @_;
4564 my $rm = $self->{rm};
4565 delete $rm->{''}; # we never delete the url we're tracking
4566 return unless %$rm;
4568 foreach (keys %$rm) {
4569 my @d = split m#/#, $_;
4570 my $c = shift @d;
4571 $rm->{$c} = 1;
4572 while (@d) {
4573 $c .= '/' . shift @d;
4574 $rm->{$c} = 1;
4577 delete $rm->{$self->{svn_path}};
4578 delete $rm->{''}; # we never delete the url we're tracking
4579 return unless %$rm;
4581 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
4582 $self->{tree_b});
4583 local $/ = "\0";
4584 while (<$fh>) {
4585 chomp;
4586 my @dn = split m#/#, $_;
4587 while (pop @dn) {
4588 delete $rm->{join '/', @dn};
4590 unless (%$rm) {
4591 close $fh;
4592 return;
4595 command_close_pipe($fh, $ctx);
4597 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
4598 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
4599 $self->close_directory($bat->{$d}, $p);
4600 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
4601 print "\tD+\t$d/\n" unless $::_q;
4602 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
4603 delete $bat->{$d};
4607 sub open_or_add_dir {
4608 my ($self, $full_path, $baton) = @_;
4609 my $t = $self->{types}->{$full_path};
4610 if (!defined $t) {
4611 die "$full_path not known in r$self->{r} or we have a bug!\n";
4614 no warnings 'once';
4615 # SVN::Node::none and SVN::Node::file are used only once,
4616 # so we're shutting up Perl's warnings about them.
4617 if ($t == $SVN::Node::none) {
4618 return $self->add_directory($full_path, $baton,
4619 undef, -1, $self->{pool});
4620 } elsif ($t == $SVN::Node::dir) {
4621 return $self->open_directory($full_path, $baton,
4622 $self->{r}, $self->{pool});
4623 } # no warnings 'once'
4624 print STDERR "$full_path already exists in repository at ",
4625 "r$self->{r} and it is not a directory (",
4626 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
4627 } # no warnings 'once'
4628 exit 1;
4631 sub ensure_path {
4632 my ($self, $path) = @_;
4633 my $bat = $self->{bat};
4634 my $repo_path = $self->repo_path($path);
4635 return $bat->{''} unless (length $repo_path);
4636 my @p = split m#/+#, $repo_path;
4637 my $c = shift @p;
4638 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
4639 while (@p) {
4640 my $c0 = $c;
4641 $c .= '/' . shift @p;
4642 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
4644 return $bat->{$c};
4647 # Subroutine to convert a globbing pattern to a regular expression.
4648 # From perl cookbook.
4649 sub glob2pat {
4650 my $globstr = shift;
4651 my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
4652 $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
4653 return '^' . $globstr . '$';
4656 sub check_autoprop {
4657 my ($self, $pattern, $properties, $file, $fbat) = @_;
4658 # Convert the globbing pattern to a regular expression.
4659 my $regex = glob2pat($pattern);
4660 # Check if the pattern matches the file name.
4661 if($file =~ m/($regex)/) {
4662 # Parse the list of properties to set.
4663 my @props = split(/;/, $properties);
4664 foreach my $prop (@props) {
4665 # Parse 'name=value' syntax and set the property.
4666 if ($prop =~ /([^=]+)=(.*)/) {
4667 my ($n,$v) = ($1,$2);
4668 for ($n, $v) {
4669 s/^\s+//; s/\s+$//;
4671 $self->change_file_prop($fbat, $n, $v);
4677 sub apply_autoprops {
4678 my ($self, $file, $fbat) = @_;
4679 my $conf_t = ${$self->{config}}{'config'};
4680 no warnings 'once';
4681 # Check [miscellany]/enable-auto-props in svn configuration.
4682 if (SVN::_Core::svn_config_get_bool(
4683 $conf_t,
4684 $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
4685 $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
4686 0)) {
4687 # Auto-props are enabled. Enumerate them to look for matches.
4688 my $callback = sub {
4689 $self->check_autoprop($_[0], $_[1], $file, $fbat);
4691 SVN::_Core::svn_config_enumerate(
4692 $conf_t,
4693 $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
4694 $callback);
4698 sub A {
4699 my ($self, $m) = @_;
4700 my ($dir, $file) = split_path($m->{file_b});
4701 my $pbat = $self->ensure_path($dir);
4702 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4703 undef, -1);
4704 print "\tA\t$m->{file_b}\n" unless $::_q;
4705 $self->apply_autoprops($file, $fbat);
4706 $self->chg_file($fbat, $m);
4707 $self->close_file($fbat,undef,$self->{pool});
4710 sub C {
4711 my ($self, $m) = @_;
4712 my ($dir, $file) = split_path($m->{file_b});
4713 my $pbat = $self->ensure_path($dir);
4714 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4715 $self->url_path($m->{file_a}), $self->{r});
4716 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
4717 $self->chg_file($fbat, $m);
4718 $self->close_file($fbat,undef,$self->{pool});
4721 sub delete_entry {
4722 my ($self, $path, $pbat) = @_;
4723 my $rpath = $self->repo_path($path);
4724 my ($dir, $file) = split_path($rpath);
4725 $self->{rm}->{$dir} = 1;
4726 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
4729 sub R {
4730 my ($self, $m) = @_;
4731 my ($dir, $file) = split_path($m->{file_b});
4732 my $pbat = $self->ensure_path($dir);
4733 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4734 $self->url_path($m->{file_a}), $self->{r});
4735 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
4736 $self->apply_autoprops($file, $fbat);
4737 $self->chg_file($fbat, $m);
4738 $self->close_file($fbat,undef,$self->{pool});
4740 ($dir, $file) = split_path($m->{file_a});
4741 $pbat = $self->ensure_path($dir);
4742 $self->delete_entry($m->{file_a}, $pbat);
4745 sub M {
4746 my ($self, $m) = @_;
4747 my ($dir, $file) = split_path($m->{file_b});
4748 my $pbat = $self->ensure_path($dir);
4749 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
4750 $pbat,$self->{r},$self->{pool});
4751 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
4752 $self->chg_file($fbat, $m);
4753 $self->close_file($fbat,undef,$self->{pool});
4756 sub T { shift->M(@_) }
4758 sub change_file_prop {
4759 my ($self, $fbat, $pname, $pval) = @_;
4760 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
4763 sub _chg_file_get_blob ($$$$) {
4764 my ($self, $fbat, $m, $which) = @_;
4765 my $fh = $::_repository->temp_acquire("git_blob_$which");
4766 if ($m->{"mode_$which"} =~ /^120/) {
4767 print $fh 'link ' or croak $!;
4768 $self->change_file_prop($fbat,'svn:special','*');
4769 } elsif ($m->{mode_a} =~ /^120/ && $m->{"mode_$which"} !~ /^120/) {
4770 $self->change_file_prop($fbat,'svn:special',undef);
4772 my $blob = $m->{"sha1_$which"};
4773 return ($fh,) if ($blob =~ /^0{40}$/);
4774 my $size = $::_repository->cat_blob($blob, $fh);
4775 croak "Failed to read object $blob" if ($size < 0);
4776 $fh->flush == 0 or croak $!;
4777 seek $fh, 0, 0 or croak $!;
4779 my $exp = ::md5sum($fh);
4780 seek $fh, 0, 0 or croak $!;
4781 return ($fh, $exp);
4784 sub chg_file {
4785 my ($self, $fbat, $m) = @_;
4786 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
4787 $self->change_file_prop($fbat,'svn:executable','*');
4788 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
4789 $self->change_file_prop($fbat,'svn:executable',undef);
4791 my ($fh_a, $exp_a) = _chg_file_get_blob $self, $fbat, $m, 'a';
4792 my ($fh_b, $exp_b) = _chg_file_get_blob $self, $fbat, $m, 'b';
4793 my $pool = SVN::Pool->new;
4794 my $atd = $self->apply_textdelta($fbat, $exp_a, $pool);
4795 if (-s $fh_a) {
4796 my $txstream = SVN::TxDelta::new ($fh_a, $fh_b, $pool);
4797 my $res = SVN::TxDelta::send_txstream($txstream, @$atd, $pool);
4798 if (defined $res) {
4799 die "Unexpected result from send_txstream: $res\n",
4800 "(SVN::Core::VERSION: $SVN::Core::VERSION)\n";
4802 } else {
4803 my $got = SVN::TxDelta::send_stream($fh_b, @$atd, $pool);
4804 die "Checksum mismatch\nexpected: $exp_b\ngot: $got\n"
4805 if ($got ne $exp_b);
4807 Git::temp_release($fh_b, 1);
4808 Git::temp_release($fh_a, 1);
4809 $pool->clear;
4812 sub D {
4813 my ($self, $m) = @_;
4814 my ($dir, $file) = split_path($m->{file_b});
4815 my $pbat = $self->ensure_path($dir);
4816 print "\tD\t$m->{file_b}\n" unless $::_q;
4817 $self->delete_entry($m->{file_b}, $pbat);
4820 sub close_edit {
4821 my ($self) = @_;
4822 my ($p,$bat) = ($self->{pool}, $self->{bat});
4823 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
4824 next if $_ eq '';
4825 $self->close_directory($bat->{$_}, $p);
4827 $self->close_directory($bat->{''}, $p);
4828 $self->SUPER::close_edit($p);
4829 $p->clear;
4832 sub abort_edit {
4833 my ($self) = @_;
4834 $self->SUPER::abort_edit($self->{pool});
4837 sub DESTROY {
4838 my $self = shift;
4839 $self->SUPER::DESTROY(@_);
4840 $self->{pool}->clear;
4843 # this drives the editor
4844 sub apply_diff {
4845 my ($self) = @_;
4846 my $mods = $self->{mods};
4847 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
4848 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
4849 my $f = $m->{chg};
4850 if (defined $o{$f}) {
4851 $self->$f($m);
4852 } else {
4853 fatal("Invalid change type: $f");
4856 $self->rmdirs if $_rmdir;
4857 if (@$mods == 0) {
4858 $self->abort_edit;
4859 } else {
4860 $self->close_edit;
4862 return scalar @$mods;
4865 package Git::SVN::Ra;
4866 use vars qw/@ISA $config_dir $_log_window_size/;
4867 use strict;
4868 use warnings;
4869 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
4871 BEGIN {
4872 # enforce temporary pool usage for some simple functions
4873 no strict 'refs';
4874 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root
4875 get_file/) {
4876 my $SUPER = "SUPER::$f";
4877 *$f = sub {
4878 my $self = shift;
4879 my $pool = SVN::Pool->new;
4880 my @ret = $self->$SUPER(@_,$pool);
4881 $pool->clear;
4882 wantarray ? @ret : $ret[0];
4887 sub _auth_providers () {
4889 SVN::Client::get_simple_provider(),
4890 SVN::Client::get_ssl_server_trust_file_provider(),
4891 SVN::Client::get_simple_prompt_provider(
4892 \&Git::SVN::Prompt::simple, 2),
4893 SVN::Client::get_ssl_client_cert_file_provider(),
4894 SVN::Client::get_ssl_client_cert_prompt_provider(
4895 \&Git::SVN::Prompt::ssl_client_cert, 2),
4896 SVN::Client::get_ssl_client_cert_pw_file_provider(),
4897 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
4898 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
4899 SVN::Client::get_username_provider(),
4900 SVN::Client::get_ssl_server_trust_prompt_provider(
4901 \&Git::SVN::Prompt::ssl_server_trust),
4902 SVN::Client::get_username_prompt_provider(
4903 \&Git::SVN::Prompt::username, 2)
4907 sub escape_uri_only {
4908 my ($uri) = @_;
4909 my @tmp;
4910 foreach (split m{/}, $uri) {
4911 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
4912 push @tmp, $_;
4914 join('/', @tmp);
4917 sub escape_url {
4918 my ($url) = @_;
4919 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
4920 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
4921 $url = "$scheme://$domain$uri";
4923 $url;
4926 sub new {
4927 my ($class, $url) = @_;
4928 $url =~ s!/+$!!;
4929 return $RA if ($RA && $RA->{url} eq $url);
4931 ::_req_svn();
4933 SVN::_Core::svn_config_ensure($config_dir, undef);
4934 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
4935 my $config = SVN::Core::config_get_config($config_dir);
4936 $RA = undef;
4937 my $dont_store_passwords = 1;
4938 my $conf_t = ${$config}{'config'};
4940 no warnings 'once';
4941 # The usage of $SVN::_Core::SVN_CONFIG_* variables
4942 # produces warnings that variables are used only once.
4943 # I had not found the better way to shut them up, so
4944 # the warnings of type 'once' are disabled in this block.
4945 if (SVN::_Core::svn_config_get_bool($conf_t,
4946 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4947 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
4948 1) == 0) {
4949 SVN::_Core::svn_auth_set_parameter($baton,
4950 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
4951 bless (\$dont_store_passwords, "_p_void"));
4953 if (SVN::_Core::svn_config_get_bool($conf_t,
4954 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4955 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
4956 1) == 0) {
4957 $Git::SVN::Prompt::_no_auth_cache = 1;
4959 } # no warnings 'once'
4960 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
4961 config => $config,
4962 pool => SVN::Pool->new,
4963 auth_provider_callbacks => $callbacks);
4964 $self->{url} = $url;
4965 $self->{svn_path} = $url;
4966 $self->{repos_root} = $self->get_repos_root;
4967 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
4968 $self->{cache} = { check_path => { r => 0, data => {} },
4969 get_dir => { r => 0, data => {} } };
4970 $RA = bless $self, $class;
4973 sub check_path {
4974 my ($self, $path, $r) = @_;
4975 my $cache = $self->{cache}->{check_path};
4976 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
4977 return $cache->{data}->{$path};
4979 my $pool = SVN::Pool->new;
4980 my $t = $self->SUPER::check_path($path, $r, $pool);
4981 $pool->clear;
4982 if ($r != $cache->{r}) {
4983 %{$cache->{data}} = ();
4984 $cache->{r} = $r;
4986 $cache->{data}->{$path} = $t;
4989 sub get_dir {
4990 my ($self, $dir, $r) = @_;
4991 my $cache = $self->{cache}->{get_dir};
4992 if ($r == $cache->{r}) {
4993 if (my $x = $cache->{data}->{$dir}) {
4994 return wantarray ? @$x : $x->[0];
4997 my $pool = SVN::Pool->new;
4998 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
4999 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
5000 $pool->clear;
5001 if ($r != $cache->{r}) {
5002 %{$cache->{data}} = ();
5003 $cache->{r} = $r;
5005 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
5006 wantarray ? (\%dirents, $r, $props) : \%dirents;
5009 sub DESTROY {
5010 # do not call the real DESTROY since we store ourselves in $RA
5013 # get_log(paths, start, end, limit,
5014 # discover_changed_paths, strict_node_history, receiver)
5015 sub get_log {
5016 my ($self, @args) = @_;
5017 my $pool = SVN::Pool->new;
5019 # svn_log_changed_path_t objects passed to get_log are likely to be
5020 # overwritten even if only the refs are copied to an external variable,
5021 # so we should dup the structures in their entirety. Using an
5022 # externally passed pool (instead of our temporary and quickly cleared
5023 # pool in Git::SVN::Ra) does not help matters at all...
5024 my $receiver = pop @args;
5025 my $prefix = "/".$self->{svn_path};
5026 $prefix =~ s#/+($)##;
5027 my $prefix_regex = qr#^\Q$prefix\E#;
5028 push(@args, sub {
5029 my ($paths) = $_[0];
5030 return &$receiver(@_) unless $paths;
5031 $_[0] = ();
5032 foreach my $p (keys %$paths) {
5033 my $i = $paths->{$p};
5034 # Make path relative to our url, not repos_root
5035 $p =~ s/$prefix_regex//;
5036 my %s = map { $_ => $i->$_; }
5037 qw/copyfrom_path copyfrom_rev action/;
5038 if ($s{'copyfrom_path'}) {
5039 $s{'copyfrom_path'} =~ s/$prefix_regex//;
5041 $_[0]{$p} = \%s;
5043 &$receiver(@_);
5047 # the limit parameter was not supported in SVN 1.1.x, so we
5048 # drop it. Therefore, the receiver callback passed to it
5049 # is made aware of this limitation by being wrapped if
5050 # the limit passed to is being wrapped.
5051 if ($SVN::Core::VERSION le '1.2.0') {
5052 my $limit = splice(@args, 3, 1);
5053 if ($limit > 0) {
5054 my $receiver = pop @args;
5055 push(@args, sub { &$receiver(@_) if (--$limit >= 0) });
5058 my $ret = $self->SUPER::get_log(@args, $pool);
5059 $pool->clear;
5060 $ret;
5063 sub trees_match {
5064 my ($self, $url1, $rev1, $url2, $rev2) = @_;
5065 my $ctx = SVN::Client->new(auth => _auth_providers);
5066 my $out = IO::File->new_tmpfile;
5068 # older SVN (1.1.x) doesn't take $pool as the last parameter for
5069 # $ctx->diff(), so we'll create a default one
5070 my $pool = SVN::Pool->new_default_sub;
5072 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
5073 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
5074 $out->flush;
5075 my $ret = (($out->stat)[7] == 0);
5076 close $out or croak $!;
5078 $ret;
5081 sub get_commit_editor {
5082 my ($self, $log, $cb, $pool) = @_;
5083 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
5084 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
5087 sub gs_do_update {
5088 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
5089 my $new = ($rev_a == $rev_b);
5090 my $path = $gs->{path};
5092 if ($new && -e $gs->{index}) {
5093 unlink $gs->{index} or die
5094 "Couldn't unlink index: $gs->{index}: $!\n";
5096 my $pool = SVN::Pool->new;
5097 $editor->set_path_strip($path);
5098 my (@pc) = split m#/#, $path;
5099 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
5100 1, $editor, $pool);
5101 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
5103 # Since we can't rely on svn_ra_reparent being available, we'll
5104 # just have to do some magic with set_path to make it so
5105 # we only want a partial path.
5106 my $sp = '';
5107 my $final = join('/', @pc);
5108 while (@pc) {
5109 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
5110 $sp .= '/' if length $sp;
5111 $sp .= shift @pc;
5113 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
5115 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
5117 $reporter->finish_report($pool);
5118 $pool->clear;
5119 $editor->{git_commit_ok};
5122 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
5123 # svn_ra_reparent didn't work before 1.4)
5124 sub gs_do_switch {
5125 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
5126 my $path = $gs->{path};
5127 my $pool = SVN::Pool->new;
5129 my $full_url = $self->{url};
5130 my $old_url = $full_url;
5131 $full_url .= '/' . $path if length $path;
5132 my ($ra, $reparented);
5134 if ($old_url =~ m#^svn(\+ssh)?://# ||
5135 ($full_url =~ m#^https?://# &&
5136 escape_url($full_url) ne $full_url)) {
5137 $_[0] = undef;
5138 $self = undef;
5139 $RA = undef;
5140 $ra = Git::SVN::Ra->new($full_url);
5141 $ra_invalid = 1;
5142 } elsif ($old_url ne $full_url) {
5143 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url, $pool);
5144 $self->{url} = $full_url;
5145 $reparented = 1;
5148 $ra ||= $self;
5149 $url_b = escape_url($url_b);
5150 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
5151 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
5152 $reporter->set_path('', $rev_a, 0, @lock, $pool);
5153 $reporter->finish_report($pool);
5155 if ($reparented) {
5156 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
5157 $self->{url} = $old_url;
5160 $pool->clear;
5161 $editor->{git_commit_ok};
5164 sub longest_common_path {
5165 my ($gsv, $globs) = @_;
5166 my %common;
5167 my $common_max = scalar @$gsv;
5169 foreach my $gs (@$gsv) {
5170 my @tmp = split m#/#, $gs->{path};
5171 my $p = '';
5172 foreach (@tmp) {
5173 $p .= length($p) ? "/$_" : $_;
5174 $common{$p} ||= 0;
5175 $common{$p}++;
5178 $globs ||= [];
5179 $common_max += scalar @$globs;
5180 foreach my $glob (@$globs) {
5181 my @tmp = split m#/#, $glob->{path}->{left};
5182 my $p = '';
5183 foreach (@tmp) {
5184 $p .= length($p) ? "/$_" : $_;
5185 $common{$p} ||= 0;
5186 $common{$p}++;
5190 my $longest_path = '';
5191 foreach (sort {length $b <=> length $a} keys %common) {
5192 if ($common{$_} == $common_max) {
5193 $longest_path = $_;
5194 last;
5197 $longest_path;
5200 sub gs_fetch_loop_common {
5201 my ($self, $base, $head, $gsv, $globs) = @_;
5202 return if ($base > $head);
5203 my $inc = $_log_window_size;
5204 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
5205 my $longest_path = longest_common_path($gsv, $globs);
5206 my $ra_url = $self->{url};
5207 my $find_trailing_edge;
5208 while (1) {
5209 my %revs;
5210 my $err;
5211 my $err_handler = $SVN::Error::handler;
5212 $SVN::Error::handler = sub {
5213 ($err) = @_;
5214 skip_unknown_revs($err);
5216 sub _cb {
5217 my ($paths, $r, $author, $date, $log) = @_;
5218 [ $paths,
5219 { author => $author, date => $date, log => $log } ];
5221 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
5222 sub { $revs{$_[1]} = _cb(@_) });
5223 if ($err) {
5224 print "Checked through r$max\r";
5225 } else {
5226 $find_trailing_edge = 1;
5228 if ($err and $find_trailing_edge) {
5229 print STDERR "Path '$longest_path' ",
5230 "was probably deleted:\n",
5231 $err->expanded_message,
5232 "\nWill attempt to follow ",
5233 "revisions r$min .. r$max ",
5234 "committed before the deletion\n";
5235 my $hi = $max;
5236 while (--$hi >= $min) {
5237 my $ok;
5238 $self->get_log([$longest_path], $min, $hi,
5239 0, 1, 1, sub {
5240 $ok = $_[1];
5241 $revs{$_[1]} = _cb(@_) });
5242 if ($ok) {
5243 print STDERR "r$min .. r$ok OK\n";
5244 last;
5247 $find_trailing_edge = 0;
5249 $SVN::Error::handler = $err_handler;
5251 my %exists = map { $_->{path} => $_ } @$gsv;
5252 foreach my $r (sort {$a <=> $b} keys %revs) {
5253 my ($paths, $logged) = @{$revs{$r}};
5255 foreach my $gs ($self->match_globs(\%exists, $paths,
5256 $globs, $r)) {
5257 if ($gs->rev_map_max >= $r) {
5258 next;
5260 next unless $gs->match_paths($paths, $r);
5261 $gs->{logged_rev_props} = $logged;
5262 if (my $last_commit = $gs->last_commit) {
5263 $gs->assert_index_clean($last_commit);
5265 my $log_entry = $gs->do_fetch($paths, $r);
5266 if ($log_entry) {
5267 $gs->do_git_commit($log_entry);
5269 $INDEX_FILES{$gs->{index}} = 1;
5271 foreach my $g (@$globs) {
5272 my $k = "svn-remote.$g->{remote}." .
5273 "$g->{t}-maxRev";
5274 Git::SVN::tmp_config($k, $r);
5276 if ($ra_invalid) {
5277 $_[0] = undef;
5278 $self = undef;
5279 $RA = undef;
5280 $self = Git::SVN::Ra->new($ra_url);
5281 $ra_invalid = undef;
5284 # pre-fill the .rev_db since it'll eventually get filled in
5285 # with '0' x40 if something new gets committed
5286 foreach my $gs (@$gsv) {
5287 next if $gs->rev_map_max >= $max;
5288 next if defined $gs->rev_map_get($max);
5289 $gs->rev_map_set($max, 0 x40);
5291 foreach my $g (@$globs) {
5292 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
5293 Git::SVN::tmp_config($k, $max);
5295 last if $max >= $head;
5296 $min = $max + 1;
5297 $max += $inc;
5298 $max = $head if ($max > $head);
5300 Git::SVN::gc();
5303 sub get_dir_globbed {
5304 my ($self, $left, $depth, $r) = @_;
5306 my @x = eval { $self->get_dir($left, $r) };
5307 return unless scalar @x == 3;
5308 my $dirents = $x[0];
5309 my @finalents;
5310 foreach my $de (keys %$dirents) {
5311 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
5312 if ($depth > 1) {
5313 my @args = ("$left/$de", $depth - 1, $r);
5314 foreach my $dir ($self->get_dir_globbed(@args)) {
5315 push @finalents, "$de/$dir";
5317 } else {
5318 push @finalents, $de;
5321 @finalents;
5324 sub match_globs {
5325 my ($self, $exists, $paths, $globs, $r) = @_;
5327 sub get_dir_check {
5328 my ($self, $exists, $g, $r) = @_;
5330 my @dirs = $self->get_dir_globbed($g->{path}->{left},
5331 $g->{path}->{depth},
5332 $r);
5334 foreach my $de (@dirs) {
5335 my $p = $g->{path}->full_path($de);
5336 next if $exists->{$p};
5337 next if (length $g->{path}->{right} &&
5338 ($self->check_path($p, $r) !=
5339 $SVN::Node::dir));
5340 next unless $p =~ /$g->{path}->{regex}/;
5341 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
5342 $g->{ref}->full_path($de), 1);
5345 foreach my $g (@$globs) {
5346 if (my $path = $paths->{"/$g->{path}->{left}"}) {
5347 if ($path->{action} =~ /^[AR]$/) {
5348 get_dir_check($self, $exists, $g, $r);
5351 foreach (keys %$paths) {
5352 if (/$g->{path}->{left_regex}/ &&
5353 !/$g->{path}->{regex}/) {
5354 next if $paths->{$_}->{action} !~ /^[AR]$/;
5355 get_dir_check($self, $exists, $g, $r);
5357 next unless /$g->{path}->{regex}/;
5358 my $p = $1;
5359 my $pathname = $g->{path}->full_path($p);
5360 next if $exists->{$pathname};
5361 next if ($self->check_path($pathname, $r) !=
5362 $SVN::Node::dir);
5363 $exists->{$pathname} = Git::SVN->init(
5364 $self->{url}, $pathname, undef,
5365 $g->{ref}->full_path($p), 1);
5367 my $c = '';
5368 foreach (split m#/#, $g->{path}->{left}) {
5369 $c .= "/$_";
5370 next unless ($paths->{$c} &&
5371 ($paths->{$c}->{action} =~ /^[AR]$/));
5372 get_dir_check($self, $exists, $g, $r);
5375 values %$exists;
5378 sub minimize_url {
5379 my ($self) = @_;
5380 return $self->{url} if ($self->{url} eq $self->{repos_root});
5381 my $url = $self->{repos_root};
5382 my @components = split(m!/!, $self->{svn_path});
5383 my $c = '';
5384 do {
5385 $url .= "/$c" if length $c;
5386 eval {
5387 my $ra = (ref $self)->new($url);
5388 my $latest = $ra->get_latest_revnum;
5389 $ra->get_log("", $latest, 0, 1, 0, 1, sub {});
5391 } while ($@ && ($c = shift @components));
5392 $url;
5395 sub can_do_switch {
5396 my $self = shift;
5397 unless (defined $can_do_switch) {
5398 my $pool = SVN::Pool->new;
5399 my $rep = eval {
5400 $self->do_switch(1, '', 0, $self->{url},
5401 SVN::Delta::Editor->new, $pool);
5403 if ($@) {
5404 $can_do_switch = 0;
5405 } else {
5406 $rep->abort_report($pool);
5407 $can_do_switch = 1;
5409 $pool->clear;
5411 $can_do_switch;
5414 sub skip_unknown_revs {
5415 my ($err) = @_;
5416 my $errno = $err->apr_err();
5417 # Maybe the branch we're tracking didn't
5418 # exist when the repo started, so it's
5419 # not an error if it doesn't, just continue
5421 # Wonderfully consistent library, eh?
5422 # 160013 - svn:// and file://
5423 # 175002 - http(s)://
5424 # 175007 - http(s):// (this repo required authorization, too...)
5425 # More codes may be discovered later...
5426 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
5427 my $err_key = $err->expanded_message;
5428 # revision numbers change every time, filter them out
5429 $err_key =~ s/\d+/\0/g;
5430 $err_key = "$errno\0$err_key";
5431 unless ($ignored_err{$err_key}) {
5432 warn "W: Ignoring error from SVN, path probably ",
5433 "does not exist: ($errno): ",
5434 $err->expanded_message,"\n";
5435 warn "W: Do not be alarmed at the above message ",
5436 "git-svn is just searching aggressively for ",
5437 "old history.\n",
5438 "This may take a while on large repositories\n";
5439 $ignored_err{$err_key} = 1;
5441 return;
5443 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
5446 package Git::SVN::Log;
5447 use strict;
5448 use warnings;
5449 use POSIX qw/strftime/;
5450 use Time::Local;
5451 use constant commit_log_separator => ('-' x 72) . "\n";
5452 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
5453 %rusers $show_commit $incremental/;
5454 my $l_fmt;
5456 sub cmt_showable {
5457 my ($c) = @_;
5458 return 1 if defined $c->{r};
5460 # big commit message got truncated by the 16k pretty buffer in rev-list
5461 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
5462 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
5463 @{$c->{l}} = ();
5464 my @log = command(qw/cat-file commit/, $c->{c});
5466 # shift off the headers
5467 shift @log while ($log[0] ne '');
5468 shift @log;
5470 # TODO: make $c->{l} not have a trailing newline in the future
5471 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
5473 (undef, $c->{r}, undef) = ::extract_metadata(
5474 (grep(/^git-svn-id: /, @log))[-1]);
5476 return defined $c->{r};
5479 sub log_use_color {
5480 return $color || Git->repository->get_colorbool('color.diff');
5483 sub git_svn_log_cmd {
5484 my ($r_min, $r_max, @args) = @_;
5485 my $head = 'HEAD';
5486 my (@files, @log_opts);
5487 foreach my $x (@args) {
5488 if ($x eq '--' || @files) {
5489 push @files, $x;
5490 } else {
5491 if (::verify_ref("$x^0")) {
5492 $head = $x;
5493 } else {
5494 push @log_opts, $x;
5499 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
5500 $gs ||= Git::SVN->_new;
5501 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
5502 $gs->refname);
5503 push @cmd, '-r' unless $non_recursive;
5504 push @cmd, qw/--raw --name-status/ if $verbose;
5505 push @cmd, '--color' if log_use_color();
5506 push @cmd, @log_opts;
5507 if (defined $r_max && $r_max == $r_min) {
5508 push @cmd, '--max-count=1';
5509 if (my $c = $gs->rev_map_get($r_max)) {
5510 push @cmd, $c;
5512 } elsif (defined $r_max) {
5513 if ($r_max < $r_min) {
5514 ($r_min, $r_max) = ($r_max, $r_min);
5516 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
5517 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
5518 # If there are no commits in the range, both $c_max and $c_min
5519 # will be undefined. If there is at least 1 commit in the
5520 # range, both will be defined.
5521 return () if !defined $c_min || !defined $c_max;
5522 if ($c_min eq $c_max) {
5523 push @cmd, '--max-count=1', $c_min;
5524 } else {
5525 push @cmd, '--boundary', "$c_min..$c_max";
5528 return (@cmd, @files);
5531 # adapted from pager.c
5532 sub config_pager {
5533 if (! -t *STDOUT) {
5534 $ENV{GIT_PAGER_IN_USE} = 'false';
5535 $pager = undef;
5536 return;
5538 chomp($pager = command_oneline(qw(var GIT_PAGER)));
5539 if ($pager eq 'cat') {
5540 $pager = undef;
5542 $ENV{GIT_PAGER_IN_USE} = defined($pager);
5545 sub run_pager {
5546 return unless defined $pager;
5547 pipe my ($rfd, $wfd) or return;
5548 defined(my $pid = fork) or ::fatal "Can't fork: $!";
5549 if (!$pid) {
5550 open STDOUT, '>&', $wfd or
5551 ::fatal "Can't redirect to stdout: $!";
5552 return;
5554 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
5555 $ENV{LESS} ||= 'FRSX';
5556 exec $pager or ::fatal "Can't run pager: $! ($pager)";
5559 sub format_svn_date {
5560 # some systmes don't handle or mishandle %z, so be creative.
5561 my $t = shift || time;
5562 my $gm = timelocal(gmtime($t));
5563 my $sign = qw( + + - )[ $t <=> $gm ];
5564 my $gmoff = sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
5565 return strftime("%Y-%m-%d %H:%M:%S $gmoff (%a, %d %b %Y)", localtime($t));
5568 sub parse_git_date {
5569 my ($t, $tz) = @_;
5570 # Date::Parse isn't in the standard Perl distro :(
5571 if ($tz =~ s/^\+//) {
5572 $t += tz_to_s_offset($tz);
5573 } elsif ($tz =~ s/^\-//) {
5574 $t -= tz_to_s_offset($tz);
5576 return $t;
5579 sub set_local_timezone {
5580 if (defined $TZ) {
5581 $ENV{TZ} = $TZ;
5582 } else {
5583 delete $ENV{TZ};
5587 sub tz_to_s_offset {
5588 my ($tz) = @_;
5589 $tz =~ s/(\d\d)$//;
5590 return ($1 * 60) + ($tz * 3600);
5593 sub get_author_info {
5594 my ($dest, $author, $t, $tz) = @_;
5595 $author =~ s/(?:^\s*|\s*$)//g;
5596 $dest->{a_raw} = $author;
5597 my $au;
5598 if ($::_authors) {
5599 $au = $rusers{$author} || undef;
5601 if (!$au) {
5602 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
5604 $dest->{t} = $t;
5605 $dest->{tz} = $tz;
5606 $dest->{a} = $au;
5607 $dest->{t_utc} = parse_git_date($t, $tz);
5610 sub process_commit {
5611 my ($c, $r_min, $r_max, $defer) = @_;
5612 if (defined $r_min && defined $r_max) {
5613 if ($r_min == $c->{r} && $r_min == $r_max) {
5614 show_commit($c);
5615 return 0;
5617 return 1 if $r_min == $r_max;
5618 if ($r_min < $r_max) {
5619 # we need to reverse the print order
5620 return 0 if (defined $limit && --$limit < 0);
5621 push @$defer, $c;
5622 return 1;
5624 if ($r_min != $r_max) {
5625 return 1 if ($r_min < $c->{r});
5626 return 1 if ($r_max > $c->{r});
5629 return 0 if (defined $limit && --$limit < 0);
5630 show_commit($c);
5631 return 1;
5634 sub show_commit {
5635 my $c = shift;
5636 if ($oneline) {
5637 my $x = "\n";
5638 if (my $l = $c->{l}) {
5639 while ($l->[0] =~ /^\s*$/) { shift @$l }
5640 $x = $l->[0];
5642 $l_fmt ||= 'A' . length($c->{r});
5643 print 'r',pack($l_fmt, $c->{r}),' | ';
5644 print "$c->{c} | " if $show_commit;
5645 print $x;
5646 } else {
5647 show_commit_normal($c);
5651 sub show_commit_changed_paths {
5652 my ($c) = @_;
5653 return unless $c->{changed};
5654 print "Changed paths:\n", @{$c->{changed}};
5657 sub show_commit_normal {
5658 my ($c) = @_;
5659 print commit_log_separator, "r$c->{r} | ";
5660 print "$c->{c} | " if $show_commit;
5661 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
5662 my $nr_line = 0;
5664 if (my $l = $c->{l}) {
5665 while ($l->[$#$l] eq "\n" && $#$l > 0
5666 && $l->[($#$l - 1)] eq "\n") {
5667 pop @$l;
5669 $nr_line = scalar @$l;
5670 if (!$nr_line) {
5671 print "1 line\n\n\n";
5672 } else {
5673 if ($nr_line == 1) {
5674 $nr_line = '1 line';
5675 } else {
5676 $nr_line .= ' lines';
5678 print $nr_line, "\n";
5679 show_commit_changed_paths($c);
5680 print "\n";
5681 print $_ foreach @$l;
5683 } else {
5684 print "1 line\n";
5685 show_commit_changed_paths($c);
5686 print "\n";
5689 foreach my $x (qw/raw stat diff/) {
5690 if ($c->{$x}) {
5691 print "\n";
5692 print $_ foreach @{$c->{$x}}
5697 sub cmd_show_log {
5698 my (@args) = @_;
5699 my ($r_min, $r_max);
5700 my $r_last = -1; # prevent dupes
5701 set_local_timezone();
5702 if (defined $::_revision) {
5703 if ($::_revision =~ /^(\d+):(\d+)$/) {
5704 ($r_min, $r_max) = ($1, $2);
5705 } elsif ($::_revision =~ /^\d+$/) {
5706 $r_min = $r_max = $::_revision;
5707 } else {
5708 ::fatal "-r$::_revision is not supported, use ",
5709 "standard 'git log' arguments instead";
5713 config_pager();
5714 @args = git_svn_log_cmd($r_min, $r_max, @args);
5715 if (!@args) {
5716 print commit_log_separator unless $incremental || $oneline;
5717 return;
5719 my $log = command_output_pipe(@args);
5720 run_pager();
5721 my (@k, $c, $d, $stat);
5722 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
5723 while (<$log>) {
5724 if (/^${esc_color}commit -?($::sha1_short)/o) {
5725 my $cmt = $1;
5726 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
5727 $r_last = $c->{r};
5728 process_commit($c, $r_min, $r_max, \@k) or
5729 goto out;
5731 $d = undef;
5732 $c = { c => $cmt };
5733 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
5734 get_author_info($c, $1, $2, $3);
5735 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
5736 # ignore
5737 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
5738 push @{$c->{raw}}, $_;
5739 } elsif (/^${esc_color}[ACRMDT]\t/) {
5740 # we could add $SVN->{svn_path} here, but that requires
5741 # remote access at the moment (repo_path_split)...
5742 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
5743 push @{$c->{changed}}, $_;
5744 } elsif (/^${esc_color}diff /o) {
5745 $d = 1;
5746 push @{$c->{diff}}, $_;
5747 } elsif ($d) {
5748 push @{$c->{diff}}, $_;
5749 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
5750 $esc_color*[\+\-]*$esc_color$/x) {
5751 $stat = 1;
5752 push @{$c->{stat}}, $_;
5753 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
5754 push @{$c->{stat}}, $_;
5755 $stat = undef;
5756 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
5757 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
5758 } elsif (s/^${esc_color} //o) {
5759 push @{$c->{l}}, $_;
5762 if ($c && defined $c->{r} && $c->{r} != $r_last) {
5763 $r_last = $c->{r};
5764 process_commit($c, $r_min, $r_max, \@k);
5766 if (@k) {
5767 ($r_min, $r_max) = ($r_max, $r_min);
5768 process_commit($_, $r_min, $r_max) foreach reverse @k;
5770 out:
5771 close $log;
5772 print commit_log_separator unless $incremental || $oneline;
5775 sub cmd_blame {
5776 my $path = pop;
5778 config_pager();
5779 run_pager();
5781 my ($fh, $ctx, $rev);
5783 if ($_git_format) {
5784 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
5785 while (my $line = <$fh>) {
5786 if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
5787 # Uncommitted edits show up as a rev ID of
5788 # all zeros, which we can't look up with
5789 # cmt_metadata
5790 if ($1 !~ /^0+$/) {
5791 (undef, $rev, undef) =
5792 ::cmt_metadata($1);
5793 $rev = '0' if (!$rev);
5794 } else {
5795 $rev = '0';
5797 $rev = sprintf('%-10s', $rev);
5798 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
5800 print $line;
5802 } else {
5803 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
5804 '--', $path);
5805 my ($sha1);
5806 my %authors;
5807 my @buffer;
5808 my %dsha; #distinct sha keys
5810 while (my $line = <$fh>) {
5811 push @buffer, $line;
5812 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5813 $dsha{$1} = 1;
5817 my $s2r = ::cmt_sha2rev_batch([keys %dsha]);
5819 foreach my $line (@buffer) {
5820 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5821 $rev = $s2r->{$1};
5822 $rev = '0' if (!$rev)
5824 elsif ($line =~ /^author (.*)/) {
5825 $authors{$rev} = $1;
5826 $authors{$rev} =~ s/\s/_/g;
5828 elsif ($line =~ /^\t(.*)$/) {
5829 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
5833 command_close_pipe($fh, $ctx);
5836 package Git::SVN::Migration;
5837 # these version numbers do NOT correspond to actual version numbers
5838 # of git nor git-svn. They are just relative.
5840 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
5842 # v1 layout: .git/$id/info/url, refs/remotes/$id
5844 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
5846 # v3 layout: .git/svn/$id, refs/remotes/$id
5847 # - info/url may remain for backwards compatibility
5848 # - this is what we migrate up to this layout automatically,
5849 # - this will be used by git svn init on single branches
5850 # v3.1 layout (auto migrated):
5851 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
5852 # for backwards compatibility
5854 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
5855 # - this is only created for newly multi-init-ed
5856 # repositories. Similar in spirit to the
5857 # --use-separate-remotes option in git-clone (now default)
5858 # - we do not automatically migrate to this (following
5859 # the example set by core git)
5861 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
5862 # - newer, more-efficient format that uses 24-bytes per record
5863 # with no filler space.
5864 # - use xxd -c24 < .rev_map.$UUID to view and debug
5865 # - This is a one-way migration, repositories updated to the
5866 # new format will not be able to use old git-svn without
5867 # rebuilding the .rev_db. Rebuilding the rev_db is not
5868 # possible if noMetadata or useSvmProps are set; but should
5869 # be no problem for users that use the (sensible) defaults.
5870 use strict;
5871 use warnings;
5872 use Carp qw/croak/;
5873 use File::Path qw/mkpath/;
5874 use File::Basename qw/dirname basename/;
5875 use vars qw/$_minimize/;
5877 sub migrate_from_v0 {
5878 my $git_dir = $ENV{GIT_DIR};
5879 return undef unless -d $git_dir;
5880 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5881 my $migrated = 0;
5882 while (<$fh>) {
5883 chomp;
5884 my ($id, $orig_ref) = ($_, $_);
5885 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
5886 next unless -f "$git_dir/$id/info/url";
5887 my $new_ref = "refs/remotes/$id";
5888 if (::verify_ref("$new_ref^0")) {
5889 print STDERR "W: $orig_ref is probably an old ",
5890 "branch used by an ancient version of ",
5891 "git-svn.\n",
5892 "However, $new_ref also exists.\n",
5893 "We will not be able ",
5894 "to use this branch until this ",
5895 "ambiguity is resolved.\n";
5896 next;
5898 print STDERR "Migrating from v0 layout...\n" if !$migrated;
5899 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
5900 command_noisy('update-ref', $new_ref, $orig_ref);
5901 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
5902 $migrated++;
5904 command_close_pipe($fh, $ctx);
5905 print STDERR "Done migrating from v0 layout...\n" if $migrated;
5906 $migrated;
5909 sub migrate_from_v1 {
5910 my $git_dir = $ENV{GIT_DIR};
5911 my $migrated = 0;
5912 return $migrated unless -d $git_dir;
5913 my $svn_dir = "$git_dir/svn";
5915 # just in case somebody used 'svn' as their $id at some point...
5916 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
5918 print STDERR "Migrating from a git-svn v1 layout...\n";
5919 mkpath([$svn_dir]);
5920 print STDERR "Data from a previous version of git-svn exists, but\n\t",
5921 "$svn_dir\n\t(required for this version ",
5922 "($::VERSION) of git-svn) does not exist.\n";
5923 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5924 while (<$fh>) {
5925 my $x = $_;
5926 next unless $x =~ s#^refs/remotes/##;
5927 chomp $x;
5928 next unless -f "$git_dir/$x/info/url";
5929 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
5930 next unless $u;
5931 my $dn = dirname("$git_dir/svn/$x");
5932 mkpath([$dn]) unless -d $dn;
5933 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
5934 mkpath(["$git_dir/svn/svn"]);
5935 print STDERR " - $git_dir/$x/info => ",
5936 "$git_dir/svn/$x/info\n";
5937 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
5938 croak "$!: $x";
5939 # don't worry too much about these, they probably
5940 # don't exist with repos this old (save for index,
5941 # and we can easily regenerate that)
5942 foreach my $f (qw/unhandled.log index .rev_db/) {
5943 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
5945 } else {
5946 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
5947 rename "$git_dir/$x", "$git_dir/svn/$x" or
5948 croak "$!: $x";
5950 $migrated++;
5952 command_close_pipe($fh, $ctx);
5953 print STDERR "Done migrating from a git-svn v1 layout\n";
5954 $migrated;
5957 sub read_old_urls {
5958 my ($l_map, $pfx, $path) = @_;
5959 my @dir;
5960 foreach (<$path/*>) {
5961 if (-r "$_/info/url") {
5962 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
5963 my $ref_id = $pfx . basename $_;
5964 my $url = ::file_to_s("$_/info/url");
5965 $l_map->{$ref_id} = $url;
5966 } elsif (-d $_) {
5967 push @dir, $_;
5970 foreach (@dir) {
5971 my $x = $_;
5972 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
5973 read_old_urls($l_map, $x, $_);
5977 sub migrate_from_v2 {
5978 my @cfg = command(qw/config -l/);
5979 return if grep /^svn-remote\..+\.url=/, @cfg;
5980 my %l_map;
5981 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
5982 my $migrated = 0;
5984 foreach my $ref_id (sort keys %l_map) {
5985 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
5986 if ($@) {
5987 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
5989 $migrated++;
5991 $migrated;
5994 sub minimize_connections {
5995 my $r = Git::SVN::read_all_remotes();
5996 my $new_urls = {};
5997 my $root_repos = {};
5998 foreach my $repo_id (keys %$r) {
5999 my $url = $r->{$repo_id}->{url} or next;
6000 my $fetch = $r->{$repo_id}->{fetch} or next;
6001 my $ra = Git::SVN::Ra->new($url);
6003 # skip existing cases where we already connect to the root
6004 if (($ra->{url} eq $ra->{repos_root}) ||
6005 ($ra->{repos_root} eq $repo_id)) {
6006 $root_repos->{$ra->{url}} = $repo_id;
6007 next;
6010 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
6011 my $root_path = $ra->{url};
6012 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
6013 foreach my $path (keys %$fetch) {
6014 my $ref_id = $fetch->{$path};
6015 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
6017 # make sure we can read when connecting to
6018 # a higher level of a repository
6019 my ($last_rev, undef) = $gs->last_rev_commit;
6020 if (!defined $last_rev) {
6021 $last_rev = eval {
6022 $root_ra->get_latest_revnum;
6024 next if $@;
6026 my $new = $root_path;
6027 $new .= length $path ? "/$path" : '';
6028 eval {
6029 $root_ra->get_log([$new], $last_rev, $last_rev,
6030 0, 0, 1, sub { });
6032 next if $@;
6033 $new_urls->{$ra->{repos_root}}->{$new} =
6034 { ref_id => $ref_id,
6035 old_repo_id => $repo_id,
6036 old_path => $path };
6040 my @emptied;
6041 foreach my $url (keys %$new_urls) {
6042 # see if we can re-use an existing [svn-remote "repo_id"]
6043 # instead of creating a(n ugly) new section:
6044 my $repo_id = $root_repos->{$url} || $url;
6046 my $fetch = $new_urls->{$url};
6047 foreach my $path (keys %$fetch) {
6048 my $x = $fetch->{$path};
6049 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
6050 my $pfx = "svn-remote.$x->{old_repo_id}";
6052 my $old_fetch = quotemeta("$x->{old_path}:".
6053 "$x->{ref_id}");
6054 command_noisy(qw/config --unset/,
6055 "$pfx.fetch", '^'. $old_fetch . '$');
6056 delete $r->{$x->{old_repo_id}}->
6057 {fetch}->{$x->{old_path}};
6058 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
6059 command_noisy(qw/config --unset/,
6060 "$pfx.url");
6061 push @emptied, $x->{old_repo_id}
6065 if (@emptied) {
6066 my $file = $ENV{GIT_CONFIG} || "$ENV{GIT_DIR}/config";
6067 print STDERR <<EOF;
6068 The following [svn-remote] sections in your config file ($file) are empty
6069 and can be safely removed:
6071 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
6075 sub migration_check {
6076 migrate_from_v0();
6077 migrate_from_v1();
6078 migrate_from_v2();
6079 minimize_connections() if $_minimize;
6082 package Git::IndexInfo;
6083 use strict;
6084 use warnings;
6085 use Git qw/command_input_pipe command_close_pipe/;
6087 sub new {
6088 my ($class) = @_;
6089 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
6090 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
6093 sub remove {
6094 my ($self, $path) = @_;
6095 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
6096 return ++$self->{nr};
6098 undef;
6101 sub update {
6102 my ($self, $mode, $hash, $path) = @_;
6103 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
6104 return ++$self->{nr};
6106 undef;
6109 sub DESTROY {
6110 my ($self) = @_;
6111 command_close_pipe($self->{gui}, $self->{ctx});
6114 package Git::SVN::GlobSpec;
6115 use strict;
6116 use warnings;
6118 sub new {
6119 my ($class, $glob, $pattern_ok) = @_;
6120 my $re = $glob;
6121 $re =~ s!/+$!!g; # no need for trailing slashes
6122 my (@left, @right, @patterns);
6123 my $state = "left";
6124 my $die_msg = "Only one set of wildcard directories " .
6125 "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
6126 for my $part (split(m|/|, $glob)) {
6127 if ($part =~ /\*/ && $part ne "*") {
6128 die "Invalid pattern in '$glob': $part\n";
6129 } elsif ($pattern_ok && $part =~ /[{}]/ &&
6130 $part !~ /^\{[^{}]+\}/) {
6131 die "Invalid pattern in '$glob': $part\n";
6133 if ($part eq "*") {
6134 die $die_msg if $state eq "right";
6135 $state = "pattern";
6136 push(@patterns, "[^/]*");
6137 } elsif ($pattern_ok && $part =~ /^\{(.*)\}$/) {
6138 die $die_msg if $state eq "right";
6139 $state = "pattern";
6140 my $p = quotemeta($1);
6141 $p =~ s/\\,/|/g;
6142 push(@patterns, "(?:$p)");
6143 } else {
6144 if ($state eq "left") {
6145 push(@left, $part);
6146 } else {
6147 push(@right, $part);
6148 $state = "right";
6152 my $depth = @patterns;
6153 if ($depth == 0) {
6154 die "One '*' is needed in glob: '$glob'\n";
6156 my $left = join('/', @left);
6157 my $right = join('/', @right);
6158 $re = join('/', @patterns);
6159 $re = join('\/',
6160 grep(length, quotemeta($left), "($re)", quotemeta($right)));
6161 my $left_re = qr/^\/\Q$left\E(\/|$)/;
6162 bless { left => $left, right => $right, left_regex => $left_re,
6163 regex => qr/$re/, glob => $glob, depth => $depth }, $class;
6166 sub full_path {
6167 my ($self, $path) = @_;
6168 return (length $self->{left} ? "$self->{left}/" : '') .
6169 $path . (length $self->{right} ? "/$self->{right}" : '');
6172 __END__
6174 Data structures:
6177 $remotes = { # returned by read_all_remotes()
6178 'svn' => {
6179 # svn-remote.svn.url=https://svn.musicpd.org
6180 url => 'https://svn.musicpd.org',
6181 # svn-remote.svn.fetch=mpd/trunk:trunk
6182 fetch => {
6183 'mpd/trunk' => 'trunk',
6185 # svn-remote.svn.tags=mpd/tags/*:tags/*
6186 tags => {
6187 path => {
6188 left => 'mpd/tags',
6189 right => '',
6190 regex => qr!mpd/tags/([^/]+)$!,
6191 glob => 'tags/*',
6193 ref => {
6194 left => 'tags',
6195 right => '',
6196 regex => qr!tags/([^/]+)$!,
6197 glob => 'tags/*',
6203 $log_entry hashref as returned by libsvn_log_entry()
6205 log => 'whitespace-formatted log entry
6206 ', # trailing newline is preserved
6207 revision => '8', # integer
6208 date => '2004-02-24T17:01:44.108345Z', # commit date
6209 author => 'committer name'
6213 # this is generated by generate_diff();
6214 @mods = array of diff-index line hashes, each element represents one line
6215 of diff-index output
6217 diff-index line ($m hash)
6219 mode_a => first column of diff-index output, no leading ':',
6220 mode_b => second column of diff-index output,
6221 sha1_b => sha1sum of the final blob,
6222 chg => change type [MCRADT],
6223 file_a => original file name of a file (iff chg is 'C' or 'R')
6224 file_b => new/current file name of a file (any chg)
6228 # retval of read_url_paths{,_all}();
6229 $l_map = {
6230 # repository root url
6231 'https://svn.musicpd.org' => {
6232 # repository path # GIT_SVN_ID
6233 'mpd/trunk' => 'trunk',
6234 'mpd/tags/0.11.5' => 'tags/0.11.5',
6238 Notes:
6239 I don't trust the each() function on unless I created %hash myself
6240 because the internal iterator may not have started at base.