git-svn: convert globs to regexps for branch destinations
[alt-git.git] / git-svn.perl
blob6c42e2afca8f0fdc699fe36b866050f20e8a7f1a
1 #!/usr/bin/env perl
2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
4 use warnings;
5 use strict;
6 use vars qw/ $AUTHOR $VERSION
7 $sha1 $sha1_short $_revision $_repository
8 $_q $_authors $_authors_prog %users/;
9 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
10 $VERSION = '@@GIT_VERSION@@';
12 # From which subdir have we been invoked?
13 my $cmd_dir_prefix = eval {
14 command_oneline([qw/rev-parse --show-prefix/], STDERR => 0)
15 } || '';
17 my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
18 $ENV{GIT_DIR} ||= '.git';
19 $Git::SVN::default_repo_id = 'svn';
20 $Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
21 $Git::SVN::Ra::_log_window_size = 100;
23 $Git::SVN::Log::TZ = $ENV{TZ};
24 $ENV{TZ} = 'UTC';
25 $| = 1; # unbuffer STDOUT
27 sub fatal (@) { print STDERR "@_\n"; exit 1 }
28 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
29 require SVN::Ra;
30 require SVN::Delta;
31 if ($SVN::Core::VERSION lt '1.1.0') {
32 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
34 push @Git::SVN::Ra::ISA, 'SVN::Ra';
35 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
36 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
37 use Carp qw/croak/;
38 use Digest::MD5;
39 use IO::File qw//;
40 use File::Basename qw/dirname basename/;
41 use File::Path qw/mkpath/;
42 use File::Spec;
43 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
44 use IPC::Open3;
45 use Git;
47 BEGIN {
48 # import functions from Git into our packages, en masse
49 no strict 'refs';
50 foreach (qw/command command_oneline command_noisy command_output_pipe
51 command_input_pipe command_close_pipe
52 command_bidi_pipe command_close_bidi_pipe/) {
53 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
54 Git::SVN::Migration Git::SVN::Log Git::SVN),
55 __PACKAGE__) {
56 *{"${package}::$_"} = \&{"Git::$_"};
61 my ($SVN);
63 $sha1 = qr/[a-f\d]{40}/;
64 $sha1_short = qr/[a-f\d]{4,40}/;
65 my ($_stdin, $_help, $_edit,
66 $_message, $_file, $_branch_dest,
67 $_template, $_shared,
68 $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
69 $_merge, $_strategy, $_dry_run, $_local,
70 $_prefix, $_no_checkout, $_url, $_verbose,
71 $_git_format, $_commit_url, $_tag);
72 $Git::SVN::_follow_parent = 1;
73 $_q ||= 0;
74 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
75 'config-dir=s' => \$Git::SVN::Ra::config_dir,
76 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
77 'ignore-paths=s' => \$SVN::Git::Fetcher::_ignore_regex );
78 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
79 'authors-file|A=s' => \$_authors,
80 'authors-prog=s' => \$_authors_prog,
81 'repack:i' => \$Git::SVN::_repack,
82 'noMetadata' => \$Git::SVN::_no_metadata,
83 'useSvmProps' => \$Git::SVN::_use_svm_props,
84 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
85 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
86 'no-checkout' => \$_no_checkout,
87 'quiet|q+' => \$_q,
88 'repack-flags|repack-args|repack-opts=s' =>
89 \$Git::SVN::_repack_flags,
90 'use-log-author' => \$Git::SVN::_use_log_author,
91 'add-author-from' => \$Git::SVN::_add_author_from,
92 'localtime' => \$Git::SVN::_localtime,
93 %remote_opts );
95 my ($_trunk, @_tags, @_branches, $_stdlayout);
96 my %icv;
97 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
98 'trunk|T=s' => \$_trunk, 'tags|t=s@' => \@_tags,
99 'branches|b=s@' => \@_branches, 'prefix=s' => \$_prefix,
100 'stdlayout|s' => \$_stdlayout,
101 'minimize-url|m' => \$Git::SVN::_minimize_url,
102 'no-metadata' => sub { $icv{noMetadata} = 1 },
103 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
104 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
105 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
106 %remote_opts );
107 my %cmt_opts = ( 'edit|e' => \$_edit,
108 'rmdir' => \$SVN::Git::Editor::_rmdir,
109 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
110 'l=i' => \$SVN::Git::Editor::_rename_limit,
111 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
114 my %cmd = (
115 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
116 { 'revision|r=s' => \$_revision,
117 'fetch-all|all' => \$_fetch_all,
118 'parent|p' => \$_fetch_parent,
119 %fc_opts } ],
120 clone => [ \&cmd_clone, "Initialize and fetch revisions",
121 { 'revision|r=s' => \$_revision,
122 %fc_opts, %init_opts } ],
123 init => [ \&cmd_init, "Initialize a repo for tracking" .
124 " (requires URL argument)",
125 \%init_opts ],
126 'multi-init' => [ \&cmd_multi_init,
127 "Deprecated alias for ".
128 "'$0 init -T<trunk> -b<branches> -t<tags>'",
129 \%init_opts ],
130 dcommit => [ \&cmd_dcommit,
131 'Commit several diffs to merge with upstream',
132 { 'merge|m|M' => \$_merge,
133 'strategy|s=s' => \$_strategy,
134 'verbose|v' => \$_verbose,
135 'dry-run|n' => \$_dry_run,
136 'fetch-all|all' => \$_fetch_all,
137 'commit-url=s' => \$_commit_url,
138 'revision|r=i' => \$_revision,
139 'no-rebase' => \$_no_rebase,
140 %cmt_opts, %fc_opts } ],
141 branch => [ \&cmd_branch,
142 'Create a branch in the SVN repository',
143 { 'message|m=s' => \$_message,
144 'destination|d=s' => \$_branch_dest,
145 'dry-run|n' => \$_dry_run,
146 'tag|t' => \$_tag } ],
147 tag => [ sub { $_tag = 1; cmd_branch(@_) },
148 'Create a tag in the SVN repository',
149 { 'message|m=s' => \$_message,
150 'destination|d=s' => \$_branch_dest,
151 'dry-run|n' => \$_dry_run } ],
152 'set-tree' => [ \&cmd_set_tree,
153 "Set an SVN repository to a git tree-ish",
154 { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
155 'create-ignore' => [ \&cmd_create_ignore,
156 'Create a .gitignore per svn:ignore',
157 { 'revision|r=i' => \$_revision
158 } ],
159 'propget' => [ \&cmd_propget,
160 'Print the value of a property on a file or directory',
161 { 'revision|r=i' => \$_revision } ],
162 'proplist' => [ \&cmd_proplist,
163 'List all properties of a file or directory',
164 { 'revision|r=i' => \$_revision } ],
165 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
166 { 'revision|r=i' => \$_revision
167 } ],
168 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
169 { 'revision|r=i' => \$_revision
170 } ],
171 'multi-fetch' => [ \&cmd_multi_fetch,
172 "Deprecated alias for $0 fetch --all",
173 { 'revision|r=s' => \$_revision, %fc_opts } ],
174 'migrate' => [ sub { },
175 # no-op, we automatically run this anyways,
176 'Migrate configuration/metadata/layout from
177 previous versions of git-svn',
178 { 'minimize' => \$Git::SVN::Migration::_minimize,
179 %remote_opts } ],
180 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
181 { 'limit=i' => \$Git::SVN::Log::limit,
182 'revision|r=s' => \$_revision,
183 'verbose|v' => \$Git::SVN::Log::verbose,
184 'incremental' => \$Git::SVN::Log::incremental,
185 'oneline' => \$Git::SVN::Log::oneline,
186 'show-commit' => \$Git::SVN::Log::show_commit,
187 'non-recursive' => \$Git::SVN::Log::non_recursive,
188 'authors-file|A=s' => \$_authors,
189 'color' => \$Git::SVN::Log::color,
190 'pager=s' => \$Git::SVN::Log::pager
191 } ],
192 'find-rev' => [ \&cmd_find_rev,
193 "Translate between SVN revision numbers and tree-ish",
194 {} ],
195 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
196 { 'merge|m|M' => \$_merge,
197 'verbose|v' => \$_verbose,
198 'strategy|s=s' => \$_strategy,
199 'local|l' => \$_local,
200 'fetch-all|all' => \$_fetch_all,
201 'dry-run|n' => \$_dry_run,
202 %fc_opts } ],
203 'commit-diff' => [ \&cmd_commit_diff,
204 'Commit a diff between two trees',
205 { 'message|m=s' => \$_message,
206 'file|F=s' => \$_file,
207 'revision|r=s' => \$_revision,
208 %cmt_opts } ],
209 'info' => [ \&cmd_info,
210 "Show info about the latest SVN revision
211 on the current branch",
212 { 'url' => \$_url, } ],
213 'blame' => [ \&Git::SVN::Log::cmd_blame,
214 "Show what revision and author last modified each line of a file",
215 { 'git-format' => \$_git_format } ],
216 'reset' => [ \&cmd_reset,
217 "Undo fetches back to the specified SVN revision",
218 { 'revision|r=s' => \$_revision,
219 'parent|p' => \$_fetch_parent } ],
222 my $cmd;
223 for (my $i = 0; $i < @ARGV; $i++) {
224 if (defined $cmd{$ARGV[$i]}) {
225 $cmd = $ARGV[$i];
226 splice @ARGV, $i, 1;
227 last;
228 } elsif ($ARGV[$i] eq 'help') {
229 $cmd = $ARGV[$i+1];
230 usage(0);
234 # make sure we're always running at the top-level working directory
235 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
236 unless (-d $ENV{GIT_DIR}) {
237 if ($git_dir_user_set) {
238 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
239 "but it is not a directory\n";
241 my $git_dir = delete $ENV{GIT_DIR};
242 my $cdup = undef;
243 git_cmd_try {
244 $cdup = command_oneline(qw/rev-parse --show-cdup/);
245 $git_dir = '.' unless ($cdup);
246 chomp $cdup if ($cdup);
247 $cdup = "." unless ($cdup && length $cdup);
248 } "Already at toplevel, but $git_dir not found\n";
249 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
250 unless (-d $git_dir) {
251 die "$git_dir still not found after going to ",
252 "'$cdup'\n";
254 $ENV{GIT_DIR} = $git_dir;
256 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
259 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
261 read_repo_config(\%opts);
262 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
263 Getopt::Long::Configure('pass_through');
265 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
266 'minimize-connections' => \$Git::SVN::Migration::_minimize,
267 'id|i=s' => \$Git::SVN::default_ref_id,
268 'svn-remote|remote|R=s' => sub {
269 $Git::SVN::no_reuse_existing = 1;
270 $Git::SVN::default_repo_id = $_[1] });
271 exit 1 if (!$rv && $cmd && $cmd ne 'log');
273 usage(0) if $_help;
274 version() if $_version;
275 usage(1) unless defined $cmd;
276 load_authors() if $_authors;
277 if (defined $_authors_prog) {
278 $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
281 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
282 Git::SVN::Migration::migration_check();
284 Git::SVN::init_vars();
285 eval {
286 Git::SVN::verify_remotes_sanity();
287 $cmd{$cmd}->[0]->(@ARGV);
289 fatal $@ if $@;
290 post_fetch_checkout();
291 exit 0;
293 ####################### primary functions ######################
294 sub usage {
295 my $exit = shift || 0;
296 my $fd = $exit ? \*STDERR : \*STDOUT;
297 print $fd <<"";
298 git-svn - bidirectional operations between a single Subversion tree and git
299 Usage: git svn <command> [options] [arguments]\n
301 print $fd "Available commands:\n" unless $cmd;
303 foreach (sort keys %cmd) {
304 next if $cmd && $cmd ne $_;
305 next if /^multi-/; # don't show deprecated commands
306 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
307 foreach (sort keys %{$cmd{$_}->[2]}) {
308 # mixed-case options are for .git/config only
309 next if /[A-Z]/ && /^[a-z]+$/i;
310 # prints out arguments as they should be passed:
311 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
312 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
313 "--$_" : "-$_" }
314 split /\|/,$_)," $x\n";
317 print $fd <<"";
318 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
319 arbitrary identifier if you're tracking multiple SVN branches/repositories in
320 one git repository and want to keep them separate. See git-svn(1) for more
321 information.
323 exit $exit;
326 sub version {
327 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
328 exit 0;
331 sub do_git_init_db {
332 unless (-d $ENV{GIT_DIR}) {
333 my @init_db = ('init');
334 push @init_db, "--template=$_template" if defined $_template;
335 if (defined $_shared) {
336 if ($_shared =~ /[a-z]/) {
337 push @init_db, "--shared=$_shared";
338 } else {
339 push @init_db, "--shared";
342 command_noisy(@init_db);
343 $_repository = Git->repository(Repository => ".git");
345 command_noisy('config', 'core.autocrlf', 'false');
346 my $set;
347 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
348 foreach my $i (keys %icv) {
349 die "'$set' and '$i' cannot both be set\n" if $set;
350 next unless defined $icv{$i};
351 command_noisy('config', "$pfx.$i", $icv{$i});
352 $set = $i;
354 my $ignore_regex = \$SVN::Git::Fetcher::_ignore_regex;
355 command_noisy('config', "$pfx.ignore-paths", $$ignore_regex)
356 if defined $$ignore_regex;
359 sub init_subdir {
360 my $repo_path = shift or return;
361 mkpath([$repo_path]) unless -d $repo_path;
362 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
363 $ENV{GIT_DIR} = '.git';
364 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
367 sub cmd_clone {
368 my ($url, $path) = @_;
369 if (!defined $path &&
370 (defined $_trunk || @_branches || @_tags ||
371 defined $_stdlayout) &&
372 $url !~ m#^[a-z\+]+://#) {
373 $path = $url;
375 $path = basename($url) if !defined $path || !length $path;
376 cmd_init($url, $path);
377 Git::SVN::fetch_all($Git::SVN::default_repo_id);
378 command_oneline('config', 'svn.authorsfile', $_authors) if $_authors;
381 sub cmd_init {
382 if (defined $_stdlayout) {
383 $_trunk = 'trunk' if (!defined $_trunk);
384 @_tags = 'tags' if (! @_tags);
385 @_branches = 'branches' if (! @_branches);
387 if (defined $_trunk || @_branches || @_tags) {
388 return cmd_multi_init(@_);
390 my $url = shift or die "SVN repository location required ",
391 "as a command-line argument\n";
392 init_subdir(@_);
393 do_git_init_db();
395 Git::SVN->init($url);
398 sub cmd_fetch {
399 if (grep /^\d+=./, @_) {
400 die "'<rev>=<commit>' fetch arguments are ",
401 "no longer supported.\n";
403 my ($remote) = @_;
404 if (@_ > 1) {
405 die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
407 if ($_fetch_parent) {
408 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
409 unless ($gs) {
410 die "Unable to determine upstream SVN information from ",
411 "working tree history\n";
413 # just fetch, don't checkout.
414 $_no_checkout = 'true';
415 $_fetch_all ? $gs->fetch_all : $gs->fetch;
416 } elsif ($_fetch_all) {
417 cmd_multi_fetch();
418 } else {
419 $remote ||= $Git::SVN::default_repo_id;
420 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
424 sub cmd_set_tree {
425 my (@commits) = @_;
426 if ($_stdin || !@commits) {
427 print "Reading from stdin...\n";
428 @commits = ();
429 while (<STDIN>) {
430 if (/\b($sha1_short)\b/o) {
431 unshift @commits, $1;
435 my @revs;
436 foreach my $c (@commits) {
437 my @tmp = command('rev-parse',$c);
438 if (scalar @tmp == 1) {
439 push @revs, $tmp[0];
440 } elsif (scalar @tmp > 1) {
441 push @revs, reverse(command('rev-list',@tmp));
442 } else {
443 fatal "Failed to rev-parse $c";
446 my $gs = Git::SVN->new;
447 my ($r_last, $cmt_last) = $gs->last_rev_commit;
448 $gs->fetch;
449 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
450 fatal "There are new revisions that were fetched ",
451 "and need to be merged (or acknowledged) ",
452 "before committing.\nlast rev: $r_last\n",
453 " current: $gs->{last_rev}";
455 $gs->set_tree($_) foreach @revs;
456 print "Done committing ",scalar @revs," revisions to SVN\n";
457 unlink $gs->{index};
460 sub cmd_dcommit {
461 my $head = shift;
462 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
463 'Cannot dcommit with a dirty index. Commit your changes first, '
464 . "or stash them with `git stash'.\n";
465 $head ||= 'HEAD';
467 my $old_head;
468 if ($head ne 'HEAD') {
469 $old_head = eval {
470 command_oneline([qw/symbolic-ref -q HEAD/])
472 if ($old_head) {
473 $old_head =~ s{^refs/heads/}{};
474 } else {
475 $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
477 command(['checkout', $head], STDERR => 0);
480 my @refs;
481 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
482 unless ($gs) {
483 die "Unable to determine upstream SVN information from ",
484 "$head history.\nPerhaps the repository is empty.";
487 if (defined $_commit_url) {
488 $url = $_commit_url;
489 } else {
490 $url = eval { command_oneline('config', '--get',
491 "svn-remote.$gs->{repo_id}.commiturl") };
492 if (!$url) {
493 $url = $gs->full_url
497 my $last_rev = $_revision if defined $_revision;
498 if ($url) {
499 print "Committing to $url ...\n";
501 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
502 if ($_no_rebase && scalar(@$linear_refs) > 1) {
503 warn "Attempting to commit more than one change while ",
504 "--no-rebase is enabled.\n",
505 "If these changes depend on each other, re-running ",
506 "without --no-rebase may be required."
508 my $expect_url = $url;
509 Git::SVN::remove_username($expect_url);
510 while (1) {
511 my $d = shift @$linear_refs or last;
512 unless (defined $last_rev) {
513 (undef, $last_rev, undef) = cmt_metadata("$d~1");
514 unless (defined $last_rev) {
515 fatal "Unable to extract revision information ",
516 "from commit $d~1";
519 if ($_dry_run) {
520 print "diff-tree $d~1 $d\n";
521 } else {
522 my $cmt_rev;
523 my %ed_opts = ( r => $last_rev,
524 log => get_commit_entry($d)->{log},
525 ra => Git::SVN::Ra->new($url),
526 config => SVN::Core::config_get_config(
527 $Git::SVN::Ra::config_dir
529 tree_a => "$d~1",
530 tree_b => $d,
531 editor_cb => sub {
532 print "Committed r$_[0]\n";
533 $cmt_rev = $_[0];
535 svn_path => '');
536 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
537 print "No changes\n$d~1 == $d\n";
538 } elsif ($parents->{$d} && @{$parents->{$d}}) {
539 $gs->{inject_parents_dcommit}->{$cmt_rev} =
540 $parents->{$d};
542 $_fetch_all ? $gs->fetch_all : $gs->fetch;
543 $last_rev = $cmt_rev;
544 next if $_no_rebase;
546 # we always want to rebase against the current HEAD,
547 # not any head that was passed to us
548 my @diff = command('diff-tree', $d,
549 $gs->refname, '--');
550 my @finish;
551 if (@diff) {
552 @finish = rebase_cmd();
553 print STDERR "W: $d and ", $gs->refname,
554 " differ, using @finish:\n",
555 join("\n", @diff), "\n";
556 } else {
557 print "No changes between current HEAD and ",
558 $gs->refname,
559 "\nResetting to the latest ",
560 $gs->refname, "\n";
561 @finish = qw/reset --mixed/;
563 command_noisy(@finish, $gs->refname);
564 if (@diff) {
565 @refs = ();
566 my ($url_, $rev_, $uuid_, $gs_) =
567 working_head_info('HEAD', \@refs);
568 my ($linear_refs_, $parents_) =
569 linearize_history($gs_, \@refs);
570 if (scalar(@$linear_refs) !=
571 scalar(@$linear_refs_)) {
572 fatal "# of revisions changed ",
573 "\nbefore:\n",
574 join("\n", @$linear_refs),
575 "\n\nafter:\n",
576 join("\n", @$linear_refs_), "\n",
577 'If you are attempting to commit ',
578 "merges, try running:\n\t",
579 'git rebase --interactive',
580 '--preserve-merges ',
581 $gs->refname,
582 "\nBefore dcommitting";
584 if ($url_ ne $expect_url) {
585 fatal "URL mismatch after rebase: ",
586 "$url_ != $expect_url";
588 if ($uuid_ ne $uuid) {
589 fatal "uuid mismatch after rebase: ",
590 "$uuid_ != $uuid";
592 # remap parents
593 my (%p, @l, $i);
594 for ($i = 0; $i < scalar @$linear_refs; $i++) {
595 my $new = $linear_refs_->[$i] or next;
596 $p{$new} =
597 $parents->{$linear_refs->[$i]};
598 push @l, $new;
600 $parents = \%p;
601 $linear_refs = \@l;
606 if ($old_head) {
607 my $new_head = command_oneline(qw/rev-parse HEAD/);
608 my $new_is_symbolic = eval {
609 command_oneline(qw/symbolic-ref -q HEAD/);
611 if ($new_is_symbolic) {
612 print "dcommitted the branch ", $head, "\n";
613 } else {
614 print "dcommitted on a detached HEAD because you gave ",
615 "a revision argument.\n",
616 "The rewritten commit is: ", $new_head, "\n";
618 command(['checkout', $old_head], STDERR => 0);
621 unlink $gs->{index};
624 sub cmd_branch {
625 my ($branch_name, $head) = @_;
627 unless (defined $branch_name && length $branch_name) {
628 die(($_tag ? "tag" : "branch") . " name required\n");
630 $head ||= 'HEAD';
632 my ($src, $rev, undef, $gs) = working_head_info($head);
634 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
635 my $allglobs = $remote->{ $_tag ? 'tags' : 'branches' };
636 my $glob;
637 if ($#{$allglobs} == 0) {
638 $glob = $allglobs->[0];
639 } else {
640 unless(defined $_branch_dest) {
641 die "Multiple ",
642 $_tag ? "tag" : "branch",
643 " paths defined for Subversion repository.\n",
644 "You must specify where you want to create the ",
645 $_tag ? "tag" : "branch",
646 " with the --destination argument.\n";
648 foreach my $g (@{$allglobs}) {
649 # SVN::Git::Editor could probably be moved to Git.pm..
650 my $re = SVN::Git::Editor::glob2pat($g->{path}->{left});
651 if ($_branch_dest =~ /$re/) {
652 $glob = $g;
653 last;
656 unless (defined $glob) {
657 die "Unknown ",
658 $_tag ? "tag" : "branch",
659 " destination $_branch_dest\n";
662 my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
663 my $dst = join '/', $remote->{url}, $lft, $branch_name, ($rgt || ());
665 my $ctx = SVN::Client->new(
666 auth => Git::SVN::Ra::_auth_providers(),
667 log_msg => sub {
668 ${ $_[0] } = defined $_message
669 ? $_message
670 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
671 . $branch_name;
675 eval {
676 $ctx->ls($dst, 'HEAD', 0);
677 } and die "branch ${branch_name} already exists\n";
679 print "Copying ${src} at r${rev} to ${dst}...\n";
680 $ctx->copy($src, $rev, $dst)
681 unless $_dry_run;
683 $gs->fetch_all;
686 sub cmd_find_rev {
687 my $revision_or_hash = shift or die "SVN or git revision required ",
688 "as a command-line argument\n";
689 my $result;
690 if ($revision_or_hash =~ /^r\d+$/) {
691 my $head = shift;
692 $head ||= 'HEAD';
693 my @refs;
694 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
695 unless ($gs) {
696 die "Unable to determine upstream SVN information from ",
697 "$head history\n";
699 my $desired_revision = substr($revision_or_hash, 1);
700 $result = $gs->rev_map_get($desired_revision, $uuid);
701 } else {
702 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
703 $result = $rev;
705 print "$result\n" if $result;
708 sub cmd_rebase {
709 command_noisy(qw/update-index --refresh/);
710 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
711 unless ($gs) {
712 die "Unable to determine upstream SVN information from ",
713 "working tree history\n";
715 if ($_dry_run) {
716 print "Remote Branch: " . $gs->refname . "\n";
717 print "SVN URL: " . $url . "\n";
718 return;
720 if (command(qw/diff-index HEAD --/)) {
721 print STDERR "Cannot rebase with uncommited changes:\n";
722 command_noisy('status');
723 exit 1;
725 unless ($_local) {
726 # rebase will checkout for us, so no need to do it explicitly
727 $_no_checkout = 'true';
728 $_fetch_all ? $gs->fetch_all : $gs->fetch;
730 command_noisy(rebase_cmd(), $gs->refname);
733 sub cmd_show_ignore {
734 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
735 $gs ||= Git::SVN->new;
736 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
737 $gs->prop_walk($gs->{path}, $r, sub {
738 my ($gs, $path, $props) = @_;
739 print STDOUT "\n# $path\n";
740 my $s = $props->{'svn:ignore'} or return;
741 $s =~ s/[\r\n]+/\n/g;
742 chomp $s;
743 $s =~ s#^#$path#gm;
744 print STDOUT "$s\n";
748 sub cmd_show_externals {
749 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
750 $gs ||= Git::SVN->new;
751 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
752 $gs->prop_walk($gs->{path}, $r, sub {
753 my ($gs, $path, $props) = @_;
754 print STDOUT "\n# $path\n";
755 my $s = $props->{'svn:externals'} or return;
756 $s =~ s/[\r\n]+/\n/g;
757 chomp $s;
758 $s =~ s#^#$path#gm;
759 print STDOUT "$s\n";
763 sub cmd_create_ignore {
764 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
765 $gs ||= Git::SVN->new;
766 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
767 $gs->prop_walk($gs->{path}, $r, sub {
768 my ($gs, $path, $props) = @_;
769 # $path is of the form /path/to/dir/
770 $path = '.' . $path;
771 # SVN can have attributes on empty directories,
772 # which git won't track
773 mkpath([$path]) unless -d $path;
774 my $ignore = $path . '.gitignore';
775 my $s = $props->{'svn:ignore'} or return;
776 open(GITIGNORE, '>', $ignore)
777 or fatal("Failed to open `$ignore' for writing: $!");
778 $s =~ s/[\r\n]+/\n/g;
779 chomp $s;
780 # Prefix all patterns so that the ignore doesn't apply
781 # to sub-directories.
782 $s =~ s#^#/#gm;
783 print GITIGNORE "$s\n";
784 close(GITIGNORE)
785 or fatal("Failed to close `$ignore': $!");
786 command_noisy('add', '-f', $ignore);
790 sub canonicalize_path {
791 my ($path) = @_;
792 my $dot_slash_added = 0;
793 if (substr($path, 0, 1) ne "/") {
794 $path = "./" . $path;
795 $dot_slash_added = 1;
797 # File::Spec->canonpath doesn't collapse x/../y into y (for a
798 # good reason), so let's do this manually.
799 $path =~ s#/+#/#g;
800 $path =~ s#/\.(?:/|$)#/#g;
801 $path =~ s#/[^/]+/\.\.##g;
802 $path =~ s#/$##g;
803 $path =~ s#^\./## if $dot_slash_added;
804 $path =~ s#^/##;
805 $path =~ s#^\.$##;
806 return $path;
809 # get_svnprops(PATH)
810 # ------------------
811 # Helper for cmd_propget and cmd_proplist below.
812 sub get_svnprops {
813 my $path = shift;
814 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
815 $gs ||= Git::SVN->new;
817 # prefix THE PATH by the sub-directory from which the user
818 # invoked us.
819 $path = $cmd_dir_prefix . $path;
820 fatal("No such file or directory: $path") unless -e $path;
821 my $is_dir = -d $path ? 1 : 0;
822 $path = $gs->{path} . '/' . $path;
824 # canonicalize the path (otherwise libsvn will abort or fail to
825 # find the file)
826 $path = canonicalize_path($path);
828 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
829 my $props;
830 if ($is_dir) {
831 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
833 else {
834 (undef, $props) = $gs->ra->get_file($path, $r, undef);
836 return $props;
839 # cmd_propget (PROP, PATH)
840 # ------------------------
841 # Print the SVN property PROP for PATH.
842 sub cmd_propget {
843 my ($prop, $path) = @_;
844 $path = '.' if not defined $path;
845 usage(1) if not defined $prop;
846 my $props = get_svnprops($path);
847 if (not defined $props->{$prop}) {
848 fatal("`$path' does not have a `$prop' SVN property.");
850 print $props->{$prop} . "\n";
853 # cmd_proplist (PATH)
854 # -------------------
855 # Print the list of SVN properties for PATH.
856 sub cmd_proplist {
857 my $path = shift;
858 $path = '.' if not defined $path;
859 my $props = get_svnprops($path);
860 print "Properties on '$path':\n";
861 foreach (sort keys %{$props}) {
862 print " $_\n";
866 sub cmd_multi_init {
867 my $url = shift;
868 unless (defined $_trunk || @_branches || @_tags) {
869 usage(1);
872 # there are currently some bugs that prevent multi-init/multi-fetch
873 # setups from working well without this.
874 $Git::SVN::_minimize_url = 1;
876 $_prefix = '' unless defined $_prefix;
877 if (defined $url) {
878 $url =~ s#/+$##;
879 init_subdir(@_);
881 do_git_init_db();
882 if (defined $_trunk) {
883 my $trunk_ref = $_prefix . 'trunk';
884 # try both old-style and new-style lookups:
885 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
886 unless ($gs_trunk) {
887 my ($trunk_url, $trunk_path) =
888 complete_svn_url($url, $_trunk);
889 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
890 undef, $trunk_ref);
893 return unless @_branches || @_tags;
894 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
895 foreach my $path (@_branches) {
896 complete_url_ls_init($ra, $path, '--branches/-b', $_prefix);
898 foreach my $path (@_tags) {
899 complete_url_ls_init($ra, $path, '--tags/-t', $_prefix.'tags/');
903 sub cmd_multi_fetch {
904 my $remotes = Git::SVN::read_all_remotes();
905 foreach my $repo_id (sort keys %$remotes) {
906 if ($remotes->{$repo_id}->{url}) {
907 Git::SVN::fetch_all($repo_id, $remotes);
912 # this command is special because it requires no metadata
913 sub cmd_commit_diff {
914 my ($ta, $tb, $url) = @_;
915 my $usage = "Usage: $0 commit-diff -r<revision> ".
916 "<tree-ish> <tree-ish> [<URL>]";
917 fatal($usage) if (!defined $ta || !defined $tb);
918 my $svn_path = '';
919 if (!defined $url) {
920 my $gs = eval { Git::SVN->new };
921 if (!$gs) {
922 fatal("Needed URL or usable git-svn --id in ",
923 "the command-line\n", $usage);
925 $url = $gs->{url};
926 $svn_path = $gs->{path};
928 unless (defined $_revision) {
929 fatal("-r|--revision is a required argument\n", $usage);
931 if (defined $_message && defined $_file) {
932 fatal("Both --message/-m and --file/-F specified ",
933 "for the commit message.\n",
934 "I have no idea what you mean");
936 if (defined $_file) {
937 $_message = file_to_s($_file);
938 } else {
939 $_message ||= get_commit_entry($tb)->{log};
941 my $ra ||= Git::SVN::Ra->new($url);
942 my $r = $_revision;
943 if ($r eq 'HEAD') {
944 $r = $ra->get_latest_revnum;
945 } elsif ($r !~ /^\d+$/) {
946 die "revision argument: $r not understood by git-svn\n";
948 my %ed_opts = ( r => $r,
949 log => $_message,
950 ra => $ra,
951 tree_a => $ta,
952 tree_b => $tb,
953 editor_cb => sub { print "Committed r$_[0]\n" },
954 svn_path => $svn_path );
955 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
956 print "No changes\n$ta == $tb\n";
960 sub escape_uri_only {
961 my ($uri) = @_;
962 my @tmp;
963 foreach (split m{/}, $uri) {
964 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
965 push @tmp, $_;
967 join('/', @tmp);
970 sub escape_url {
971 my ($url) = @_;
972 if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
973 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
974 $url = "$scheme://$domain$uri";
976 $url;
979 sub cmd_info {
980 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
981 my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
982 if (exists $_[1]) {
983 die "Too many arguments specified\n";
986 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
988 if (!$file_type && !$diff_status) {
989 print STDERR "svn: '$path' is not under version control\n";
990 exit 1;
993 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
994 unless ($gs) {
995 die "Unable to determine upstream SVN information from ",
996 "working tree history\n";
999 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
1000 $path = "." if $path eq "";
1002 my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
1004 if ($_url) {
1005 print escape_url($full_url), "\n";
1006 return;
1009 my $result = "Path: $path\n";
1010 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
1011 $result .= "URL: " . escape_url($full_url) . "\n";
1013 eval {
1014 my $repos_root = $gs->repos_root;
1015 Git::SVN::remove_username($repos_root);
1016 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
1018 if ($@) {
1019 $result .= "Repository Root: (offline)\n";
1021 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
1022 ($SVN::Core::VERSION le '1.5.4' || $file_type ne "dir");
1023 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
1025 $result .= "Node Kind: " .
1026 ($file_type eq "dir" ? "directory" : "file") . "\n";
1028 my $schedule = $diff_status eq "A"
1029 ? "add"
1030 : ($diff_status eq "D" ? "delete" : "normal");
1031 $result .= "Schedule: $schedule\n";
1033 if ($diff_status eq "A") {
1034 print $result, "\n";
1035 return;
1038 my ($lc_author, $lc_rev, $lc_date_utc);
1039 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
1040 my $log = command_output_pipe(@args);
1041 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
1042 while (<$log>) {
1043 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
1044 $lc_author = $1;
1045 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
1046 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
1047 (undef, $lc_rev, undef) = ::extract_metadata($1);
1050 close $log;
1052 Git::SVN::Log::set_local_timezone();
1054 $result .= "Last Changed Author: $lc_author\n";
1055 $result .= "Last Changed Rev: $lc_rev\n";
1056 $result .= "Last Changed Date: " .
1057 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
1059 if ($file_type ne "dir") {
1060 my $text_last_updated_date =
1061 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
1062 $result .=
1063 "Text Last Updated: " .
1064 Git::SVN::Log::format_svn_date($text_last_updated_date) .
1065 "\n";
1066 my $checksum;
1067 if ($diff_status eq "D") {
1068 my ($fh, $ctx) =
1069 command_output_pipe(qw(cat-file blob), "HEAD:$path");
1070 if ($file_type eq "link") {
1071 my $file_name = <$fh>;
1072 $checksum = md5sum("link $file_name");
1073 } else {
1074 $checksum = md5sum($fh);
1076 command_close_pipe($fh, $ctx);
1077 } elsif ($file_type eq "link") {
1078 my $file_name =
1079 command(qw(cat-file blob), "HEAD:$path");
1080 $checksum =
1081 md5sum("link " . $file_name);
1082 } else {
1083 open FILE, "<", $path or die $!;
1084 $checksum = md5sum(\*FILE);
1085 close FILE or die $!;
1087 $result .= "Checksum: " . $checksum . "\n";
1090 print $result, "\n";
1093 sub cmd_reset {
1094 my $target = shift || $_revision or die "SVN revision required\n";
1095 $target = $1 if $target =~ /^r(\d+)$/;
1096 $target =~ /^\d+$/ or die "Numeric SVN revision expected\n";
1097 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1098 unless ($gs) {
1099 die "Unable to determine upstream SVN information from ".
1100 "history\n";
1102 my ($r, $c) = $gs->find_rev_before($target, not $_fetch_parent);
1103 $gs->rev_map_set($r, $c, 'reset', $uuid);
1104 print "r$r = $c ($gs->{ref_id})\n";
1107 ########################### utility functions #########################
1109 sub rebase_cmd {
1110 my @cmd = qw/rebase/;
1111 push @cmd, '-v' if $_verbose;
1112 push @cmd, qw/--merge/ if $_merge;
1113 push @cmd, "--strategy=$_strategy" if $_strategy;
1114 @cmd;
1117 sub post_fetch_checkout {
1118 return if $_no_checkout;
1119 my $gs = $Git::SVN::_head or return;
1120 return if verify_ref('refs/heads/master^0');
1122 my $valid_head = verify_ref('HEAD^0');
1123 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1124 return if ($valid_head || !verify_ref('HEAD^0'));
1126 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1127 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1128 return if -f $index;
1130 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1131 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1132 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1133 print STDERR "Checked out HEAD:\n ",
1134 $gs->full_url, " r", $gs->last_rev, "\n";
1137 sub complete_svn_url {
1138 my ($url, $path) = @_;
1139 $path =~ s#/+$##;
1140 if ($path !~ m#^[a-z\+]+://#) {
1141 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1142 fatal("E: '$path' is not a complete URL ",
1143 "and a separate URL is not specified");
1145 return ($url, $path);
1147 return ($path, '');
1150 sub complete_url_ls_init {
1151 my ($ra, $repo_path, $switch, $pfx) = @_;
1152 unless ($repo_path) {
1153 print STDERR "W: $switch not specified\n";
1154 return;
1156 $repo_path =~ s#/+$##;
1157 if ($repo_path =~ m#^[a-z\+]+://#) {
1158 $ra = Git::SVN::Ra->new($repo_path);
1159 $repo_path = '';
1160 } else {
1161 $repo_path =~ s#^/+##;
1162 unless ($ra) {
1163 fatal("E: '$repo_path' is not a complete URL ",
1164 "and a separate URL is not specified");
1167 my $url = $ra->{url};
1168 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1169 my $k = "svn-remote.$gs->{repo_id}.url";
1170 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1171 if ($orig_url && ($orig_url ne $gs->{url})) {
1172 die "$k already set: $orig_url\n",
1173 "wanted to set to: $gs->{url}\n";
1175 command_oneline('config', $k, $gs->{url}) unless $orig_url;
1176 my $remote_path = "$ra->{svn_path}/$repo_path";
1177 $remote_path =~ s#/+#/#g;
1178 $remote_path =~ s#^/##g;
1179 $remote_path .= "/*" if $remote_path !~ /\*/;
1180 my ($n) = ($switch =~ /^--(\w+)/);
1181 if (length $pfx && $pfx !~ m#/$#) {
1182 die "--prefix='$pfx' must have a trailing slash '/'\n";
1184 command_noisy('config',
1185 '--add',
1186 "svn-remote.$gs->{repo_id}.$n",
1187 "$remote_path:refs/remotes/$pfx*" .
1188 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1191 sub verify_ref {
1192 my ($ref) = @_;
1193 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1194 { STDERR => 0 }); };
1197 sub get_tree_from_treeish {
1198 my ($treeish) = @_;
1199 # $treeish can be a symbolic ref, too:
1200 my $type = command_oneline(qw/cat-file -t/, $treeish);
1201 my $expected;
1202 while ($type eq 'tag') {
1203 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1205 if ($type eq 'commit') {
1206 $expected = (grep /^tree /, command(qw/cat-file commit/,
1207 $treeish))[0];
1208 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1209 die "Unable to get tree from $treeish\n" unless $expected;
1210 } elsif ($type eq 'tree') {
1211 $expected = $treeish;
1212 } else {
1213 die "$treeish is a $type, expected tree, tag or commit\n";
1215 return $expected;
1218 sub get_commit_entry {
1219 my ($treeish) = shift;
1220 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1221 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1222 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1223 open my $log_fh, '>', $commit_editmsg or croak $!;
1225 my $type = command_oneline(qw/cat-file -t/, $treeish);
1226 if ($type eq 'commit' || $type eq 'tag') {
1227 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1228 $type, $treeish);
1229 my $in_msg = 0;
1230 my $author;
1231 my $saw_from = 0;
1232 my $msgbuf = "";
1233 while (<$msg_fh>) {
1234 if (!$in_msg) {
1235 $in_msg = 1 if (/^\s*$/);
1236 $author = $1 if (/^author (.*>)/);
1237 } elsif (/^git-svn-id: /) {
1238 # skip this for now, we regenerate the
1239 # correct one on re-fetch anyways
1240 # TODO: set *:merge properties or like...
1241 } else {
1242 if (/^From:/ || /^Signed-off-by:/) {
1243 $saw_from = 1;
1245 $msgbuf .= $_;
1248 $msgbuf =~ s/\s+$//s;
1249 if ($Git::SVN::_add_author_from && defined($author)
1250 && !$saw_from) {
1251 $msgbuf .= "\n\nFrom: $author";
1253 print $log_fh $msgbuf or croak $!;
1254 command_close_pipe($msg_fh, $ctx);
1256 close $log_fh or croak $!;
1258 if ($_edit || ($type eq 'tree')) {
1259 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1260 # TODO: strip out spaces, comments, like git-commit.sh
1261 system($editor, $commit_editmsg);
1263 rename $commit_editmsg, $commit_msg or croak $!;
1265 require Encode;
1266 # SVN requires messages to be UTF-8 when entering the repo
1267 local $/;
1268 open $log_fh, '<', $commit_msg or croak $!;
1269 binmode $log_fh;
1270 chomp($log_entry{log} = <$log_fh>);
1272 my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
1273 my $msg = $log_entry{log};
1275 eval { $msg = Encode::decode($enc, $msg, 1) };
1276 if ($@) {
1277 die "Could not decode as $enc:\n", $msg,
1278 "\nPerhaps you need to set i18n.commitencoding\n";
1281 eval { $msg = Encode::encode('UTF-8', $msg, 1) };
1282 die "Could not encode as UTF-8:\n$msg\n" if $@;
1284 $log_entry{log} = $msg;
1286 close $log_fh or croak $!;
1288 unlink $commit_msg;
1289 \%log_entry;
1292 sub s_to_file {
1293 my ($str, $file, $mode) = @_;
1294 open my $fd,'>',$file or croak $!;
1295 print $fd $str,"\n" or croak $!;
1296 close $fd or croak $!;
1297 chmod ($mode &~ umask, $file) if (defined $mode);
1300 sub file_to_s {
1301 my $file = shift;
1302 open my $fd,'<',$file or croak "$!: file: $file\n";
1303 local $/;
1304 my $ret = <$fd>;
1305 close $fd or croak $!;
1306 $ret =~ s/\s*$//s;
1307 return $ret;
1310 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1311 sub load_authors {
1312 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1313 my $log = $cmd eq 'log';
1314 while (<$authors>) {
1315 chomp;
1316 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1317 my ($user, $name, $email) = ($1, $2, $3);
1318 if ($log) {
1319 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1320 } else {
1321 $users{$user} = [$name, $email];
1324 close $authors or croak $!;
1327 # convert GetOpt::Long specs for use by git-config
1328 sub read_repo_config {
1329 return unless -d $ENV{GIT_DIR};
1330 my $opts = shift;
1331 my @config_only;
1332 foreach my $o (keys %$opts) {
1333 # if we have mixedCase and a long option-only, then
1334 # it's a config-only variable that we don't need for
1335 # the command-line.
1336 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1337 my $v = $opts->{$o};
1338 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1339 $key =~ s/-//g;
1340 my $arg = 'git config';
1341 $arg .= ' --int' if ($o =~ /[:=]i$/);
1342 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1343 if (ref $v eq 'ARRAY') {
1344 chomp(my @tmp = `$arg --get-all svn.$key`);
1345 @$v = @tmp if @tmp;
1346 } else {
1347 chomp(my $tmp = `$arg --get svn.$key`);
1348 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1349 $$v = $tmp;
1353 delete @$opts{@config_only} if @config_only;
1356 sub extract_metadata {
1357 my $id = shift or return (undef, undef, undef);
1358 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1359 \s([a-f\d\-]+)$/x);
1360 if (!defined $rev || !$uuid || !$url) {
1361 # some of the original repositories I made had
1362 # identifiers like this:
1363 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
1365 return ($url, $rev, $uuid);
1368 sub cmt_metadata {
1369 return extract_metadata((grep(/^git-svn-id: /,
1370 command(qw/cat-file commit/, shift)))[-1]);
1373 sub cmt_sha2rev_batch {
1374 my %s2r;
1375 my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1376 my $list = shift;
1378 foreach my $sha (@{$list}) {
1379 my $first = 1;
1380 my $size = 0;
1381 print $out $sha, "\n";
1383 while (my $line = <$in>) {
1384 if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1385 last;
1386 } elsif ($first &&
1387 $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1388 $first = 0;
1389 $size = $1;
1390 next;
1391 } elsif ($line =~ /^(git-svn-id: )/) {
1392 my (undef, $rev, undef) =
1393 extract_metadata($line);
1394 $s2r{$sha} = $rev;
1397 $size -= length($line);
1398 last if ($size == 0);
1402 command_close_bidi_pipe($pid, $in, $out, $ctx);
1404 return \%s2r;
1407 sub working_head_info {
1408 my ($head, $refs) = @_;
1409 my @args = ('log', '--no-color', '--first-parent', '--pretty=medium');
1410 my ($fh, $ctx) = command_output_pipe(@args, $head);
1411 my $hash;
1412 my %max;
1413 while (<$fh>) {
1414 if ( m{^commit ($::sha1)$} ) {
1415 unshift @$refs, $hash if $hash and $refs;
1416 $hash = $1;
1417 next;
1419 next unless s{^\s*(git-svn-id:)}{$1};
1420 my ($url, $rev, $uuid) = extract_metadata($_);
1421 if (defined $url && defined $rev) {
1422 next if $max{$url} and $max{$url} < $rev;
1423 if (my $gs = Git::SVN->find_by_url($url)) {
1424 my $c = $gs->rev_map_get($rev, $uuid);
1425 if ($c && $c eq $hash) {
1426 close $fh; # break the pipe
1427 return ($url, $rev, $uuid, $gs);
1428 } else {
1429 $max{$url} ||= $gs->rev_map_max;
1434 command_close_pipe($fh, $ctx);
1435 (undef, undef, undef, undef);
1438 sub read_commit_parents {
1439 my ($parents, $c) = @_;
1440 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1441 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1442 @{$parents->{$c}} = split(/ /, $p);
1445 sub linearize_history {
1446 my ($gs, $refs) = @_;
1447 my %parents;
1448 foreach my $c (@$refs) {
1449 read_commit_parents(\%parents, $c);
1452 my @linear_refs;
1453 my %skip = ();
1454 my $last_svn_commit = $gs->last_commit;
1455 foreach my $c (reverse @$refs) {
1456 next if $c eq $last_svn_commit;
1457 last if $skip{$c};
1459 unshift @linear_refs, $c;
1460 $skip{$c} = 1;
1462 # we only want the first parent to diff against for linear
1463 # history, we save the rest to inject when we finalize the
1464 # svn commit
1465 my $fp_a = verify_ref("$c~1");
1466 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1467 if (!$fp_a || !$fp_b) {
1468 die "Commit $c\n",
1469 "has no parent commit, and therefore ",
1470 "nothing to diff against.\n",
1471 "You should be working from a repository ",
1472 "originally created by git-svn\n";
1474 if ($fp_a ne $fp_b) {
1475 die "$c~1 = $fp_a, however parsing commit $c ",
1476 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1479 foreach my $p (@{$parents{$c}}) {
1480 $skip{$p} = 1;
1483 (\@linear_refs, \%parents);
1486 sub find_file_type_and_diff_status {
1487 my ($path) = @_;
1488 return ('dir', '') if $path eq '';
1490 my $diff_output =
1491 command_oneline(qw(diff --cached --name-status --), $path) || "";
1492 my $diff_status = (split(' ', $diff_output))[0] || "";
1494 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1496 return (undef, undef) if !$diff_status && !$ls_tree;
1498 if ($diff_status eq "A") {
1499 return ("link", $diff_status) if -l $path;
1500 return ("dir", $diff_status) if -d $path;
1501 return ("file", $diff_status);
1504 my $mode = (split(' ', $ls_tree))[0] || "";
1506 return ("link", $diff_status) if $mode eq "120000";
1507 return ("dir", $diff_status) if $mode eq "040000";
1508 return ("file", $diff_status);
1511 sub md5sum {
1512 my $arg = shift;
1513 my $ref = ref $arg;
1514 my $md5 = Digest::MD5->new();
1515 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
1516 $md5->addfile($arg) or croak $!;
1517 } elsif ($ref eq 'SCALAR') {
1518 $md5->add($$arg) or croak $!;
1519 } elsif (!$ref) {
1520 $md5->add($arg) or croak $!;
1521 } else {
1522 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1524 return $md5->hexdigest();
1527 package Git::SVN;
1528 use strict;
1529 use warnings;
1530 use Fcntl qw/:DEFAULT :seek/;
1531 use constant rev_map_fmt => 'NH40';
1532 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1533 $_repack $_repack_flags $_use_svm_props $_head
1534 $_use_svnsync_props $no_reuse_existing $_minimize_url
1535 $_use_log_author $_add_author_from $_localtime/;
1536 use Carp qw/croak/;
1537 use File::Path qw/mkpath/;
1538 use File::Copy qw/copy/;
1539 use IPC::Open3;
1541 my ($_gc_nr, $_gc_period);
1543 # properties that we do not log:
1544 my %SKIP_PROP;
1545 BEGIN {
1546 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1547 svn:special svn:executable
1548 svn:entry:committed-rev
1549 svn:entry:last-author
1550 svn:entry:uuid
1551 svn:entry:committed-date/;
1553 # some options are read globally, but can be overridden locally
1554 # per [svn-remote "..."] section. Command-line options will *NOT*
1555 # override options set in an [svn-remote "..."] section
1556 no strict 'refs';
1557 for my $option (qw/follow_parent no_metadata use_svm_props
1558 use_svnsync_props/) {
1559 my $key = $option;
1560 $key =~ tr/_//d;
1561 my $prop = "-$option";
1562 *$option = sub {
1563 my ($self) = @_;
1564 return $self->{$prop} if exists $self->{$prop};
1565 my $k = "svn-remote.$self->{repo_id}.$key";
1566 eval { command_oneline(qw/config --get/, $k) };
1567 if ($@) {
1568 $self->{$prop} = ${"Git::SVN::_$option"};
1569 } else {
1570 my $v = command_oneline(qw/config --bool/,$k);
1571 $self->{$prop} = $v eq 'false' ? 0 : 1;
1573 return $self->{$prop};
1579 my (%LOCKFILES, %INDEX_FILES);
1580 END {
1581 unlink keys %LOCKFILES if %LOCKFILES;
1582 unlink keys %INDEX_FILES if %INDEX_FILES;
1585 sub resolve_local_globs {
1586 my ($url, $fetch, $glob_spec) = @_;
1587 return unless defined $glob_spec;
1588 my $ref = $glob_spec->{ref};
1589 my $path = $glob_spec->{path};
1590 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
1591 next unless m#^refs/remotes/$ref->{regex}$#;
1592 my $p = $1;
1593 my $pathname = desanitize_refname($path->full_path($p));
1594 my $refname = desanitize_refname($ref->full_path($p));
1595 if (my $existing = $fetch->{$pathname}) {
1596 if ($existing ne $refname) {
1597 die "Refspec conflict:\n",
1598 "existing: refs/remotes/$existing\n",
1599 " globbed: refs/remotes/$refname\n";
1601 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
1602 $u =~ s!^\Q$url\E(/|$)!! or die
1603 "refs/remotes/$refname: '$url' not found in '$u'\n";
1604 if ($pathname ne $u) {
1605 warn "W: Refspec glob conflict ",
1606 "(ref: refs/remotes/$refname):\n",
1607 "expected path: $pathname\n",
1608 " real path: $u\n",
1609 "Continuing ahead with $u\n";
1610 next;
1612 } else {
1613 $fetch->{$pathname} = $refname;
1618 sub parse_revision_argument {
1619 my ($base, $head) = @_;
1620 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1621 return ($base, $head);
1623 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1624 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1625 return ($head, $head) if ($::_revision eq 'HEAD');
1626 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1627 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1628 die "revision argument: $::_revision not understood by git-svn\n";
1631 sub fetch_all {
1632 my ($repo_id, $remotes) = @_;
1633 if (ref $repo_id) {
1634 my $gs = $repo_id;
1635 $repo_id = undef;
1636 $repo_id = $gs->{repo_id};
1638 $remotes ||= read_all_remotes();
1639 my $remote = $remotes->{$repo_id} or
1640 die "[svn-remote \"$repo_id\"] unknown\n";
1641 my $fetch = $remote->{fetch};
1642 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1643 my (@gs, @globs);
1644 my $ra = Git::SVN::Ra->new($url);
1645 my $uuid = $ra->get_uuid;
1646 my $head = $ra->get_latest_revnum;
1647 my $base = defined $fetch ? $head : 0;
1649 # read the max revs for wildcard expansion (branches/*, tags/*)
1650 foreach my $t (qw/branches tags/) {
1651 defined $remote->{$t} or next;
1652 push @globs, @{$remote->{$t}};
1654 my $max_rev = eval { tmp_config(qw/--int --get/,
1655 "svn-remote.$repo_id.${t}-maxRev") };
1656 if (defined $max_rev && ($max_rev < $base)) {
1657 $base = $max_rev;
1658 } elsif (!defined $max_rev) {
1659 $base = 0;
1663 if ($fetch) {
1664 foreach my $p (sort keys %$fetch) {
1665 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1666 my $lr = $gs->rev_map_max;
1667 if (defined $lr) {
1668 $base = $lr if ($lr < $base);
1670 push @gs, $gs;
1674 ($base, $head) = parse_revision_argument($base, $head);
1675 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1678 sub read_all_remotes {
1679 my $r = {};
1680 my $use_svm_props = eval { command_oneline(qw/config --bool
1681 svn.useSvmProps/) };
1682 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
1683 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1684 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*(.+)\s*$!) {
1685 my ($remote, $local_ref, $_remote_ref) = ($1, $2, $3);
1686 die("svn-remote.$remote: remote ref '$_remote_ref' "
1687 . "must start with 'refs/remotes/'\n")
1688 unless $_remote_ref =~ m{^refs/remotes/(.+)};
1689 my $remote_ref = $1;
1690 $local_ref =~ s{^/}{};
1691 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1692 $r->{$remote}->{svm} = {} if $use_svm_props;
1693 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
1694 $r->{$1}->{svm} = {};
1695 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1696 $r->{$1}->{url} = $2;
1697 } elsif (m!^(.+)\.(branches|tags)=
1698 (.*):refs/remotes/(.+)\s*$/!x) {
1699 my ($p, $g) = ($3, $4);
1700 my $rs = {
1701 t => $2,
1702 remote => $1,
1703 path => Git::SVN::GlobSpec->new($p),
1704 ref => Git::SVN::GlobSpec->new($g) };
1705 if (length($rs->{ref}->{right}) != 0) {
1706 die "The '*' glob character must be the last ",
1707 "character of '$g'\n";
1709 push @{ $r->{$1}->{$2} }, $rs;
1713 map {
1714 if (defined $r->{$_}->{svm}) {
1715 my $svm;
1716 eval {
1717 my $section = "svn-remote.$_";
1718 $svm = {
1719 source => tmp_config('--get',
1720 "$section.svm-source"),
1721 replace => tmp_config('--get',
1722 "$section.svm-replace"),
1725 $r->{$_}->{svm} = $svm;
1727 } keys %$r;
1732 sub init_vars {
1733 $_gc_nr = $_gc_period = 1000;
1734 if (defined $_repack || defined $_repack_flags) {
1735 warn "Repack options are obsolete; they have no effect.\n";
1739 sub verify_remotes_sanity {
1740 return unless -d $ENV{GIT_DIR};
1741 my %seen;
1742 foreach (command(qw/config -l/)) {
1743 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1744 if ($seen{$1}) {
1745 die "Remote ref refs/remote/$1 is tracked by",
1746 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1747 "Please resolve this ambiguity in ",
1748 "your git configuration file before ",
1749 "continuing\n";
1751 $seen{$1} = $_;
1756 sub find_existing_remote {
1757 my ($url, $remotes) = @_;
1758 return undef if $no_reuse_existing;
1759 my $existing;
1760 foreach my $repo_id (keys %$remotes) {
1761 my $u = $remotes->{$repo_id}->{url} or next;
1762 next if $u ne $url;
1763 $existing = $repo_id;
1764 last;
1766 $existing;
1769 sub init_remote_config {
1770 my ($self, $url, $no_write) = @_;
1771 $url =~ s!/+$!!; # strip trailing slash
1772 my $r = read_all_remotes();
1773 my $existing = find_existing_remote($url, $r);
1774 if ($existing) {
1775 unless ($no_write) {
1776 print STDERR "Using existing ",
1777 "[svn-remote \"$existing\"]\n";
1779 $self->{repo_id} = $existing;
1780 } elsif ($_minimize_url) {
1781 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1782 $existing = find_existing_remote($min_url, $r);
1783 if ($existing) {
1784 unless ($no_write) {
1785 print STDERR "Using existing ",
1786 "[svn-remote \"$existing\"]\n";
1788 $self->{repo_id} = $existing;
1790 if ($min_url ne $url) {
1791 unless ($no_write) {
1792 print STDERR "Using higher level of URL: ",
1793 "$url => $min_url\n";
1795 my $old_path = $self->{path};
1796 $self->{path} = $url;
1797 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1798 if (length $old_path) {
1799 $self->{path} .= "/$old_path";
1801 $url = $min_url;
1804 my $orig_url;
1805 if (!$existing) {
1806 # verify that we aren't overwriting anything:
1807 $orig_url = eval {
1808 command_oneline('config', '--get',
1809 "svn-remote.$self->{repo_id}.url")
1811 if ($orig_url && ($orig_url ne $url)) {
1812 die "svn-remote.$self->{repo_id}.url already set: ",
1813 "$orig_url\nwanted to set to: $url\n";
1816 my ($xrepo_id, $xpath) = find_ref($self->refname);
1817 if (defined $xpath) {
1818 die "svn-remote.$xrepo_id.fetch already set to track ",
1819 "$xpath:refs/remotes/", $self->refname, "\n";
1821 unless ($no_write) {
1822 command_noisy('config',
1823 "svn-remote.$self->{repo_id}.url", $url);
1824 $self->{path} =~ s{^/}{};
1825 command_noisy('config', '--add',
1826 "svn-remote.$self->{repo_id}.fetch",
1827 "$self->{path}:".$self->refname);
1829 $self->{url} = $url;
1832 sub find_by_url { # repos_root and, path are optional
1833 my ($class, $full_url, $repos_root, $path) = @_;
1835 return undef unless defined $full_url;
1836 remove_username($full_url);
1837 remove_username($repos_root) if defined $repos_root;
1838 my $remotes = read_all_remotes();
1839 if (defined $full_url && defined $repos_root && !defined $path) {
1840 $path = $full_url;
1841 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1843 foreach my $repo_id (keys %$remotes) {
1844 my $u = $remotes->{$repo_id}->{url} or next;
1845 remove_username($u);
1846 next if defined $repos_root && $repos_root ne $u;
1848 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1849 foreach my $t (qw/branches tags/) {
1850 foreach my $globspec (@{$remotes->{$repo_id}->{$t}}) {
1851 resolve_local_globs($u, $fetch, $globspec);
1854 my $p = $path;
1855 my $rwr = rewrite_root({repo_id => $repo_id});
1856 my $svm = $remotes->{$repo_id}->{svm}
1857 if defined $remotes->{$repo_id}->{svm};
1858 unless (defined $p) {
1859 $p = $full_url;
1860 my $z = $u;
1861 my $prefix = '';
1862 if ($rwr) {
1863 $z = $rwr;
1864 remove_username($z);
1865 } elsif (defined $svm) {
1866 $z = $svm->{source};
1867 $prefix = $svm->{replace};
1868 $prefix =~ s#^\Q$u\E(?:/|$)##;
1869 $prefix =~ s#/$##;
1871 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
1873 foreach my $f (keys %$fetch) {
1874 next if $f ne $p;
1875 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1878 undef;
1881 sub init {
1882 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1883 my $self = _new($class, $repo_id, $ref_id, $path);
1884 if (defined $url) {
1885 $self->init_remote_config($url, $no_write);
1887 $self;
1890 sub find_ref {
1891 my ($ref_id) = @_;
1892 foreach (command(qw/config -l/)) {
1893 next unless m!^svn-remote\.(.+)\.fetch=
1894 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1895 my ($repo_id, $path, $ref) = ($1, $2, $3);
1896 if ($ref eq $ref_id) {
1897 $path = '' if ($path =~ m#^\./?#);
1898 return ($repo_id, $path);
1901 (undef, undef, undef);
1904 sub new {
1905 my ($class, $ref_id, $repo_id, $path) = @_;
1906 if (defined $ref_id && !defined $repo_id && !defined $path) {
1907 ($repo_id, $path) = find_ref($ref_id);
1908 if (!defined $repo_id) {
1909 die "Could not find a \"svn-remote.*.fetch\" key ",
1910 "in the repository configuration matching: ",
1911 "refs/remotes/$ref_id\n";
1914 my $self = _new($class, $repo_id, $ref_id, $path);
1915 if (!defined $self->{path} || !length $self->{path}) {
1916 my $fetch = command_oneline('config', '--get',
1917 "svn-remote.$repo_id.fetch",
1918 ":refs/remotes/$ref_id\$") or
1919 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1920 "\":refs/remotes/$ref_id\$\" in config\n";
1921 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1923 $self->{url} = command_oneline('config', '--get',
1924 "svn-remote.$repo_id.url") or
1925 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1926 $self->rebuild;
1927 $self;
1930 sub refname {
1931 my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1933 # It cannot end with a slash /, we'll throw up on this because
1934 # SVN can't have directories with a slash in their name, either:
1935 if ($refname =~ m{/$}) {
1936 die "ref: '$refname' ends with a trailing slash, this is ",
1937 "not permitted by git nor Subversion\n";
1940 # It cannot have ASCII control character space, tilde ~, caret ^,
1941 # colon :, question-mark ?, asterisk *, space, or open bracket [
1942 # anywhere.
1944 # Additionally, % must be escaped because it is used for escaping
1945 # and we want our escaped refname to be reversible
1946 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1948 # no slash-separated component can begin with a dot .
1949 # /.* becomes /%2E*
1950 $refname =~ s{/\.}{/%2E}g;
1952 # It cannot have two consecutive dots .. anywhere
1953 # .. becomes %2E%2E
1954 $refname =~ s{\.\.}{%2E%2E}g;
1956 return $refname;
1959 sub desanitize_refname {
1960 my ($refname) = @_;
1961 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1962 return $refname;
1965 sub svm_uuid {
1966 my ($self) = @_;
1967 return $self->{svm}->{uuid} if $self->svm;
1968 $self->ra;
1969 unless ($self->{svm}) {
1970 die "SVM UUID not cached, and reading remotely failed\n";
1972 $self->{svm}->{uuid};
1975 sub svm {
1976 my ($self) = @_;
1977 return $self->{svm} if $self->{svm};
1978 my $svm;
1979 # see if we have it in our config, first:
1980 eval {
1981 my $section = "svn-remote.$self->{repo_id}";
1982 $svm = {
1983 source => tmp_config('--get', "$section.svm-source"),
1984 uuid => tmp_config('--get', "$section.svm-uuid"),
1985 replace => tmp_config('--get', "$section.svm-replace"),
1988 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1989 $self->{svm} = $svm;
1991 $self->{svm};
1994 sub _set_svm_vars {
1995 my ($self, $ra) = @_;
1996 return $ra if $self->svm;
1998 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1999 "(svm:source, svm:uuid) ",
2000 "from the following URLs:\n" );
2001 sub read_svm_props {
2002 my ($self, $ra, $path, $r) = @_;
2003 my $props = ($ra->get_dir($path, $r))[2];
2004 my $src = $props->{'svm:source'};
2005 my $uuid = $props->{'svm:uuid'};
2006 return undef if (!$src || !$uuid);
2008 chomp($src, $uuid);
2010 $uuid =~ m{^[0-9a-f\-]{30,}$}
2011 or die "doesn't look right - svm:uuid is '$uuid'\n";
2013 # the '!' is used to mark the repos_root!/relative/path
2014 $src =~ s{/?!/?}{/};
2015 $src =~ s{/+$}{}; # no trailing slashes please
2016 # username is of no interest
2017 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
2019 my $replace = $ra->{url};
2020 $replace .= "/$path" if length $path;
2022 my $section = "svn-remote.$self->{repo_id}";
2023 tmp_config("$section.svm-source", $src);
2024 tmp_config("$section.svm-replace", $replace);
2025 tmp_config("$section.svm-uuid", $uuid);
2026 $self->{svm} = {
2027 source => $src,
2028 uuid => $uuid,
2029 replace => $replace
2033 my $r = $ra->get_latest_revnum;
2034 my $path = $self->{path};
2035 my %tried;
2036 while (length $path) {
2037 unless ($tried{"$self->{url}/$path"}) {
2038 return $ra if $self->read_svm_props($ra, $path, $r);
2039 $tried{"$self->{url}/$path"} = 1;
2041 $path =~ s#/?[^/]+$##;
2043 die "Path: '$path' should be ''\n" if $path ne '';
2044 return $ra if $self->read_svm_props($ra, $path, $r);
2045 $tried{"$self->{url}/$path"} = 1;
2047 if ($ra->{repos_root} eq $self->{url}) {
2048 die @err, (map { " $_\n" } keys %tried), "\n";
2051 # nope, make sure we're connected to the repository root:
2052 my $ok;
2053 my @tried_b;
2054 $path = $ra->{svn_path};
2055 $ra = Git::SVN::Ra->new($ra->{repos_root});
2056 while (length $path) {
2057 unless ($tried{"$ra->{url}/$path"}) {
2058 $ok = $self->read_svm_props($ra, $path, $r);
2059 last if $ok;
2060 $tried{"$ra->{url}/$path"} = 1;
2062 $path =~ s#/?[^/]+$##;
2064 die "Path: '$path' should be ''\n" if $path ne '';
2065 $ok ||= $self->read_svm_props($ra, $path, $r);
2066 $tried{"$ra->{url}/$path"} = 1;
2067 if (!$ok) {
2068 die @err, (map { " $_\n" } keys %tried), "\n";
2070 Git::SVN::Ra->new($self->{url});
2073 sub svnsync {
2074 my ($self) = @_;
2075 return $self->{svnsync} if $self->{svnsync};
2077 if ($self->no_metadata) {
2078 die "Can't have both 'noMetadata' and ",
2079 "'useSvnsyncProps' options set!\n";
2081 if ($self->rewrite_root) {
2082 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
2083 "options set!\n";
2086 my $svnsync;
2087 # see if we have it in our config, first:
2088 eval {
2089 my $section = "svn-remote.$self->{repo_id}";
2091 my $url = tmp_config('--get', "$section.svnsync-url");
2092 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2093 die "doesn't look right - svn:sync-from-url is '$url'\n";
2095 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
2096 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
2097 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2099 $svnsync = { url => $url, uuid => $uuid }
2101 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
2102 return $self->{svnsync} = $svnsync;
2105 my $err = "useSvnsyncProps set, but failed to read " .
2106 "svnsync property: svn:sync-from-";
2107 my $rp = $self->ra->rev_proplist(0);
2109 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
2110 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2111 die "doesn't look right - svn:sync-from-url is '$url'\n";
2113 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
2114 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
2115 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2117 my $section = "svn-remote.$self->{repo_id}";
2118 tmp_config('--add', "$section.svnsync-uuid", $uuid);
2119 tmp_config('--add', "$section.svnsync-url", $url);
2120 return $self->{svnsync} = { url => $url, uuid => $uuid };
2123 # this allows us to memoize our SVN::Ra UUID locally and avoid a
2124 # remote lookup (useful for 'git svn log').
2125 sub ra_uuid {
2126 my ($self) = @_;
2127 unless ($self->{ra_uuid}) {
2128 my $key = "svn-remote.$self->{repo_id}.uuid";
2129 my $uuid = eval { tmp_config('--get', $key) };
2130 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
2131 $self->{ra_uuid} = $uuid;
2132 } else {
2133 die "ra_uuid called without URL\n" unless $self->{url};
2134 $self->{ra_uuid} = $self->ra->get_uuid;
2135 tmp_config('--add', $key, $self->{ra_uuid});
2138 $self->{ra_uuid};
2141 sub _set_repos_root {
2142 my ($self, $repos_root) = @_;
2143 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2144 $repos_root ||= $self->ra->{repos_root};
2145 tmp_config($k, $repos_root);
2146 $repos_root;
2149 sub repos_root {
2150 my ($self) = @_;
2151 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2152 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
2155 sub ra {
2156 my ($self) = shift;
2157 my $ra = Git::SVN::Ra->new($self->{url});
2158 $self->_set_repos_root($ra->{repos_root});
2159 if ($self->use_svm_props && !$self->{svm}) {
2160 if ($self->no_metadata) {
2161 die "Can't have both 'noMetadata' and ",
2162 "'useSvmProps' options set!\n";
2163 } elsif ($self->use_svnsync_props) {
2164 die "Can't have both 'useSvnsyncProps' and ",
2165 "'useSvmProps' options set!\n";
2167 $ra = $self->_set_svm_vars($ra);
2168 $self->{-want_revprops} = 1;
2170 $ra;
2173 sub rel_path {
2174 my ($self) = @_;
2175 my $repos_root = $self->ra->{repos_root};
2176 return $self->{path} if ($self->{url} eq $repos_root);
2177 my $url = $self->{url} .
2178 (length $self->{path} ? "/$self->{path}" : $self->{path});
2179 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
2180 $url;
2183 # prop_walk(PATH, REV, SUB)
2184 # -------------------------
2185 # Recursively traverse PATH at revision REV and invoke SUB for each
2186 # directory that contains a SVN property. SUB will be invoked as
2187 # follows: &SUB(gs, path, props); where `gs' is this instance of
2188 # Git::SVN, `path' the path to the directory where the properties
2189 # `props' were found. The `path' will be relative to point of checkout,
2190 # that is, if url://repo/trunk is the current Git branch, and that
2191 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
2192 # as `path' (note the trailing `/').
2193 sub prop_walk {
2194 my ($self, $path, $rev, $sub) = @_;
2196 $path =~ s#^/##;
2197 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2198 $path =~ s#^/*#/#g;
2199 my $p = $path;
2200 # Strip the irrelevant part of the path.
2201 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2202 # Ensure the path is terminated by a `/'.
2203 $p =~ s#/*$#/#;
2205 # The properties contain all the internal SVN stuff nobody
2206 # (usually) cares about.
2207 my $interesting_props = 0;
2208 foreach (keys %{$props}) {
2209 # If it doesn't start with `svn:', it must be a
2210 # user-defined property.
2211 ++$interesting_props and next if $_ !~ /^svn:/;
2212 # FIXME: Fragile, if SVN adds new public properties,
2213 # this needs to be updated.
2214 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2215 |eol-style|mime-type
2216 |externals|needs-lock)$/x;
2218 &$sub($self, $p, $props) if $interesting_props;
2220 foreach (sort keys %$dirent) {
2221 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
2222 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
2226 sub last_rev { ($_[0]->last_rev_commit)[0] }
2227 sub last_commit { ($_[0]->last_rev_commit)[1] }
2229 # returns the newest SVN revision number and newest commit SHA1
2230 sub last_rev_commit {
2231 my ($self) = @_;
2232 if (defined $self->{last_rev} && defined $self->{last_commit}) {
2233 return ($self->{last_rev}, $self->{last_commit});
2235 my $c = ::verify_ref($self->refname.'^0');
2236 if ($c && !$self->use_svm_props && !$self->no_metadata) {
2237 my $rev = (::cmt_metadata($c))[1];
2238 if (defined $rev) {
2239 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2240 return ($rev, $c);
2243 my $map_path = $self->map_path;
2244 unless (-e $map_path) {
2245 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2246 return (undef, undef);
2248 my ($rev, $commit) = $self->rev_map_max(1);
2249 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2250 return ($rev, $commit);
2253 sub get_fetch_range {
2254 my ($self, $min, $max) = @_;
2255 $max ||= $self->ra->get_latest_revnum;
2256 $min ||= $self->rev_map_max;
2257 (++$min, $max);
2260 sub tmp_config {
2261 my (@args) = @_;
2262 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2263 my $config = "$ENV{GIT_DIR}/svn/.metadata";
2264 if (! -f $config && -f $old_def_config) {
2265 rename $old_def_config, $config or
2266 die "Failed rename $old_def_config => $config: $!\n";
2268 my $old_config = $ENV{GIT_CONFIG};
2269 $ENV{GIT_CONFIG} = $config;
2270 $@ = undef;
2271 my @ret = eval {
2272 unless (-f $config) {
2273 mkfile($config);
2274 open my $fh, '>', $config or
2275 die "Can't open $config: $!\n";
2276 print $fh "; This file is used internally by ",
2277 "git-svn\n" or die
2278 "Couldn't write to $config: $!\n";
2279 print $fh "; You should not have to edit it\n" or
2280 die "Couldn't write to $config: $!\n";
2281 close $fh or die "Couldn't close $config: $!\n";
2283 command('config', @args);
2285 my $err = $@;
2286 if (defined $old_config) {
2287 $ENV{GIT_CONFIG} = $old_config;
2288 } else {
2289 delete $ENV{GIT_CONFIG};
2291 die $err if $err;
2292 wantarray ? @ret : $ret[0];
2295 sub tmp_index_do {
2296 my ($self, $sub) = @_;
2297 my $old_index = $ENV{GIT_INDEX_FILE};
2298 $ENV{GIT_INDEX_FILE} = $self->{index};
2299 $@ = undef;
2300 my @ret = eval {
2301 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2302 mkpath([$dir]) unless -d $dir;
2303 &$sub;
2305 my $err = $@;
2306 if (defined $old_index) {
2307 $ENV{GIT_INDEX_FILE} = $old_index;
2308 } else {
2309 delete $ENV{GIT_INDEX_FILE};
2311 die $err if $err;
2312 wantarray ? @ret : $ret[0];
2315 sub assert_index_clean {
2316 my ($self, $treeish) = @_;
2318 $self->tmp_index_do(sub {
2319 command_noisy('read-tree', $treeish) unless -e $self->{index};
2320 my $x = command_oneline('write-tree');
2321 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2322 /^tree ($::sha1)/mo);
2323 return if $y eq $x;
2325 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2326 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2327 command_noisy('read-tree', $treeish);
2328 $x = command_oneline('write-tree');
2329 if ($y ne $x) {
2330 ::fatal "trees ($treeish) $y != $x\n",
2331 "Something is seriously wrong...";
2336 sub get_commit_parents {
2337 my ($self, $log_entry) = @_;
2338 my (%seen, @ret, @tmp);
2339 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2340 if (my $ip = $self->{inject_parents}) {
2341 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2342 push @tmp, $commit;
2345 if (my $cur = ::verify_ref($self->refname.'^0')) {
2346 push @tmp, $cur;
2348 if (my $ipd = $self->{inject_parents_dcommit}) {
2349 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2350 push @tmp, @$commit;
2353 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2354 while (my $p = shift @tmp) {
2355 next if $seen{$p};
2356 $seen{$p} = 1;
2357 push @ret, $p;
2358 # MAXPARENT is defined to 16 in commit-tree.c:
2359 last if @ret >= 16;
2361 if (@tmp) {
2362 die "r$log_entry->{revision}: No room for parents:\n\t",
2363 join("\n\t", @tmp), "\n";
2365 @ret;
2368 sub rewrite_root {
2369 my ($self) = @_;
2370 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2371 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2372 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2373 if ($rwr) {
2374 $rwr =~ s#/+$##;
2375 if ($rwr !~ m#^[a-z\+]+://#) {
2376 die "$rwr is not a valid URL (key: $k)\n";
2379 $self->{-rewrite_root} = $rwr;
2382 sub metadata_url {
2383 my ($self) = @_;
2384 ($self->rewrite_root || $self->{url}) .
2385 (length $self->{path} ? '/' . $self->{path} : '');
2388 sub full_url {
2389 my ($self) = @_;
2390 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2394 sub set_commit_header_env {
2395 my ($log_entry) = @_;
2396 my %env;
2397 foreach my $ned (qw/NAME EMAIL DATE/) {
2398 foreach my $ac (qw/AUTHOR COMMITTER/) {
2399 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2403 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2404 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2405 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2407 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2408 ? $log_entry->{commit_name}
2409 : $log_entry->{name};
2410 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2411 ? $log_entry->{commit_email}
2412 : $log_entry->{email};
2413 \%env;
2416 sub restore_commit_header_env {
2417 my ($env) = @_;
2418 foreach my $ned (qw/NAME EMAIL DATE/) {
2419 foreach my $ac (qw/AUTHOR COMMITTER/) {
2420 my $k = "GIT_${ac}_${ned}";
2421 if (defined $env->{$k}) {
2422 $ENV{$k} = $env->{$k};
2423 } else {
2424 delete $ENV{$k};
2430 sub gc {
2431 command_noisy('gc', '--auto');
2434 sub do_git_commit {
2435 my ($self, $log_entry) = @_;
2436 my $lr = $self->last_rev;
2437 if (defined $lr && $lr >= $log_entry->{revision}) {
2438 die "Last fetched revision of ", $self->refname,
2439 " was r$lr, but we are about to fetch: ",
2440 "r$log_entry->{revision}!\n";
2442 if (my $c = $self->rev_map_get($log_entry->{revision})) {
2443 croak "$log_entry->{revision} = $c already exists! ",
2444 "Why are we refetching it?\n";
2446 my $old_env = set_commit_header_env($log_entry);
2447 my $tree = $log_entry->{tree};
2448 if (!defined $tree) {
2449 $tree = $self->tmp_index_do(sub {
2450 command_oneline('write-tree') });
2452 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2454 my @exec = ('git', 'commit-tree', $tree);
2455 foreach ($self->get_commit_parents($log_entry)) {
2456 push @exec, '-p', $_;
2458 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2459 or croak $!;
2460 binmode $msg_fh;
2462 # we always get UTF-8 from SVN, but we may want our commits in
2463 # a different encoding.
2464 if (my $enc = Git::config('i18n.commitencoding')) {
2465 require Encode;
2466 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
2468 print $msg_fh $log_entry->{log} or croak $!;
2469 restore_commit_header_env($old_env);
2470 unless ($self->no_metadata) {
2471 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2472 or croak $!;
2474 $msg_fh->flush == 0 or croak $!;
2475 close $msg_fh or croak $!;
2476 chomp(my $commit = do { local $/; <$out_fh> });
2477 close $out_fh or croak $!;
2478 waitpid $pid, 0;
2479 croak $? if $?;
2480 if ($commit !~ /^$::sha1$/o) {
2481 die "Failed to commit, invalid sha1: $commit\n";
2484 $self->rev_map_set($log_entry->{revision}, $commit, 1);
2486 $self->{last_rev} = $log_entry->{revision};
2487 $self->{last_commit} = $commit;
2488 print "r$log_entry->{revision}" unless $::_q > 1;
2489 if (defined $log_entry->{svm_revision}) {
2490 print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
2491 $self->rev_map_set($log_entry->{svm_revision}, $commit,
2492 0, $self->svm_uuid);
2494 print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
2495 if (--$_gc_nr == 0) {
2496 $_gc_nr = $_gc_period;
2497 gc();
2499 return $commit;
2502 sub match_paths {
2503 my ($self, $paths, $r) = @_;
2504 return 1 if $self->{path} eq '';
2505 if (my $path = $paths->{"/$self->{path}"}) {
2506 return ($path->{action} eq 'D') ? 0 : 1;
2508 my $repos_root = $self->ra->{repos_root};
2509 my $extended_path = $self->{url} . '/' . $self->{path};
2510 $extended_path =~ s#^\Q$repos_root\E(/|$)##;
2511 $self->{path_regex} ||= qr/^\/\Q$extended_path\E\//;
2512 if (grep /$self->{path_regex}/, keys %$paths) {
2513 return 1;
2515 my $c = '';
2516 foreach (split m#/#, $self->{path}) {
2517 $c .= "/$_";
2518 next unless ($paths->{$c} &&
2519 ($paths->{$c}->{action} =~ /^[AR]$/));
2520 if ($self->ra->check_path($self->{path}, $r) ==
2521 $SVN::Node::dir) {
2522 return 1;
2525 return 0;
2528 sub find_parent_branch {
2529 my ($self, $paths, $rev) = @_;
2530 return undef unless $self->follow_parent;
2531 unless (defined $paths) {
2532 my $err_handler = $SVN::Error::handler;
2533 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2534 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
2535 $paths =
2536 Git::SVN::Ra::dup_changed_paths($_[0]) });
2537 $SVN::Error::handler = $err_handler;
2539 return undef unless defined $paths;
2541 # look for a parent from another branch:
2542 my @b_path_components = split m#/#, $self->rel_path;
2543 my @a_path_components;
2544 my $i;
2545 while (@b_path_components) {
2546 $i = $paths->{'/'.join('/', @b_path_components)};
2547 last if $i && defined $i->{copyfrom_path};
2548 unshift(@a_path_components, pop(@b_path_components));
2550 return undef unless defined $i && defined $i->{copyfrom_path};
2551 my $branch_from = $i->{copyfrom_path};
2552 if (@a_path_components) {
2553 print STDERR "branch_from: $branch_from => ";
2554 $branch_from .= '/'.join('/', @a_path_components);
2555 print STDERR $branch_from, "\n";
2557 my $r = $i->{copyfrom_rev};
2558 my $repos_root = $self->ra->{repos_root};
2559 my $url = $self->ra->{url};
2560 my $new_url = $repos_root . $branch_from;
2561 print STDERR "Found possible branch point: ",
2562 "$new_url => ", $self->full_url, ", $r\n";
2563 $branch_from =~ s#^/##;
2564 my $gs = $self->other_gs($new_url, $url, $repos_root,
2565 $branch_from, $r, $self->{ref_id});
2566 my ($r0, $parent) = $gs->find_rev_before($r, 1);
2568 my ($base, $head);
2569 if (!defined $r0 || !defined $parent) {
2570 ($base, $head) = parse_revision_argument(0, $r);
2571 } else {
2572 if ($r0 < $r) {
2573 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
2574 0, 1, sub { $base = $_[1] - 1 });
2577 if (defined $base && $base <= $r) {
2578 $gs->fetch($base, $r);
2580 ($r0, $parent) = $gs->find_rev_before($r, 1);
2582 if (defined $r0 && defined $parent) {
2583 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
2584 my $ed;
2585 if ($self->ra->can_do_switch) {
2586 $self->assert_index_clean($parent);
2587 print STDERR "Following parent with do_switch\n";
2588 # do_switch works with svn/trunk >= r22312, but that
2589 # is not included with SVN 1.4.3 (the latest version
2590 # at the moment), so we can't rely on it
2591 $self->{last_rev} = $r0;
2592 $self->{last_commit} = $parent;
2593 $ed = SVN::Git::Fetcher->new($self, $gs->{path});
2594 $gs->ra->gs_do_switch($r0, $rev, $gs,
2595 $self->full_url, $ed)
2596 or die "SVN connection failed somewhere...\n";
2597 } elsif ($self->ra->trees_match($new_url, $r0,
2598 $self->full_url, $rev)) {
2599 print STDERR "Trees match:\n",
2600 " $new_url\@$r0\n",
2601 " ${\$self->full_url}\@$rev\n",
2602 "Following parent with no changes\n";
2603 $self->tmp_index_do(sub {
2604 command_noisy('read-tree', $parent);
2606 $self->{last_commit} = $parent;
2607 } else {
2608 print STDERR "Following parent with do_update\n";
2609 $ed = SVN::Git::Fetcher->new($self);
2610 $self->ra->gs_do_update($rev, $rev, $self, $ed)
2611 or die "SVN connection failed somewhere...\n";
2613 print STDERR "Successfully followed parent\n";
2614 return $self->make_log_entry($rev, [$parent], $ed);
2616 return undef;
2619 sub do_fetch {
2620 my ($self, $paths, $rev) = @_;
2621 my $ed;
2622 my ($last_rev, @parents);
2623 if (my $lc = $self->last_commit) {
2624 # we can have a branch that was deleted, then re-added
2625 # under the same name but copied from another path, in
2626 # which case we'll have multiple parents (we don't
2627 # want to break the original ref, nor lose copypath info):
2628 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2629 push @{$log_entry->{parents}}, $lc;
2630 return $log_entry;
2632 $ed = SVN::Git::Fetcher->new($self);
2633 $last_rev = $self->{last_rev};
2634 $ed->{c} = $lc;
2635 @parents = ($lc);
2636 } else {
2637 $last_rev = $rev;
2638 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2639 return $log_entry;
2641 $ed = SVN::Git::Fetcher->new($self);
2643 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2644 die "SVN connection failed somewhere...\n";
2646 $self->make_log_entry($rev, \@parents, $ed);
2649 sub get_untracked {
2650 my ($self, $ed) = @_;
2651 my @out;
2652 my $h = $ed->{empty};
2653 foreach (sort keys %$h) {
2654 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2655 push @out, " $act: " . uri_encode($_);
2656 warn "W: $act: $_\n";
2658 foreach my $t (qw/dir_prop file_prop/) {
2659 $h = $ed->{$t} or next;
2660 foreach my $path (sort keys %$h) {
2661 my $ppath = $path eq '' ? '.' : $path;
2662 foreach my $prop (sort keys %{$h->{$path}}) {
2663 next if $SKIP_PROP{$prop};
2664 my $v = $h->{$path}->{$prop};
2665 my $t_ppath_prop = "$t: " .
2666 uri_encode($ppath) . ' ' .
2667 uri_encode($prop);
2668 if (defined $v) {
2669 push @out, " +$t_ppath_prop " .
2670 uri_encode($v);
2671 } else {
2672 push @out, " -$t_ppath_prop";
2677 foreach my $t (qw/absent_file absent_directory/) {
2678 $h = $ed->{$t} or next;
2679 foreach my $parent (sort keys %$h) {
2680 foreach my $path (sort @{$h->{$parent}}) {
2681 push @out, " $t: " .
2682 uri_encode("$parent/$path");
2683 warn "W: $t: $parent/$path ",
2684 "Insufficient permissions?\n";
2688 \@out;
2691 # parse_svn_date(DATE)
2692 # --------------------
2693 # Given a date (in UTC) from Subversion, return a string in the format
2694 # "<TZ Offset> <local date/time>" that Git will use.
2696 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
2697 # is true we'll convert it to the local timezone instead.
2698 sub parse_svn_date {
2699 my $date = shift || return '+0000 1970-01-01 00:00:00';
2700 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2701 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
2702 croak "Unable to parse date: $date\n";
2703 my $parsed_date; # Set next.
2705 if ($Git::SVN::_localtime) {
2706 # Translate the Subversion datetime to an epoch time.
2707 # Begin by switching ourselves to $date's timezone, UTC.
2708 my $old_env_TZ = $ENV{TZ};
2709 $ENV{TZ} = 'UTC';
2711 my $epoch_in_UTC =
2712 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
2714 # Determine our local timezone (including DST) at the
2715 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
2716 # value of TZ, if any, at the time we were run.
2717 if (defined $Git::SVN::Log::TZ) {
2718 $ENV{TZ} = $Git::SVN::Log::TZ;
2719 } else {
2720 delete $ENV{TZ};
2723 my $our_TZ =
2724 POSIX::strftime('%Z', $S, $M, $H, $d, $m - 1, $Y - 1900);
2726 # This converts $epoch_in_UTC into our local timezone.
2727 my ($sec, $min, $hour, $mday, $mon, $year,
2728 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
2730 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
2731 $our_TZ, $year + 1900, $mon + 1,
2732 $mday, $hour, $min, $sec);
2734 # Reset us to the timezone in effect when we entered
2735 # this routine.
2736 if (defined $old_env_TZ) {
2737 $ENV{TZ} = $old_env_TZ;
2738 } else {
2739 delete $ENV{TZ};
2741 } else {
2742 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
2745 return $parsed_date;
2748 sub other_gs {
2749 my ($self, $new_url, $url, $repos_root,
2750 $branch_from, $r, $old_ref_id) = @_;
2751 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
2752 unless ($gs) {
2753 my $ref_id = $old_ref_id;
2754 $ref_id =~ s/\@\d+$//;
2755 $ref_id .= "\@$r";
2756 # just grow a tail if we're not unique enough :x
2757 $ref_id .= '-' while find_ref($ref_id);
2758 print STDERR "Initializing parent: $ref_id\n";
2759 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
2760 if ($u =~ s#^\Q$url\E(/|$)##) {
2761 $p = $u;
2762 $u = $url;
2763 $repo_id = $self->{repo_id};
2765 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
2770 sub call_authors_prog {
2771 my ($orig_author) = @_;
2772 my $author = `$::_authors_prog $orig_author`;
2773 if ($? != 0) {
2774 die "$::_authors_prog failed with exit code $?\n"
2776 if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
2777 my ($name, $email) = ($1, $2);
2778 $email = undef if length $2 == 0;
2779 return [$name, $email];
2780 } else {
2781 die "Author: $orig_author: $::_authors_prog returned "
2782 . "invalid author format: $author\n";
2786 sub check_author {
2787 my ($author) = @_;
2788 if (!defined $author || length $author == 0) {
2789 $author = '(no author)';
2791 if (!defined $::users{$author}) {
2792 if (defined $::_authors_prog) {
2793 $::users{$author} = call_authors_prog($author);
2794 } elsif (defined $::_authors) {
2795 die "Author: $author not defined in $::_authors file\n";
2798 $author;
2801 sub make_log_entry {
2802 my ($self, $rev, $parents, $ed) = @_;
2803 my $untracked = $self->get_untracked($ed);
2805 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
2806 print $un "r$rev\n" or croak $!;
2807 print $un $_, "\n" foreach @$untracked;
2808 my %log_entry = ( parents => $parents || [], revision => $rev,
2809 log => '');
2811 my $headrev;
2812 my $logged = delete $self->{logged_rev_props};
2813 if (!$logged || $self->{-want_revprops}) {
2814 my $rp = $self->ra->rev_proplist($rev);
2815 foreach (sort keys %$rp) {
2816 my $v = $rp->{$_};
2817 if (/^svn:(author|date|log)$/) {
2818 $log_entry{$1} = $v;
2819 } elsif ($_ eq 'svm:headrev') {
2820 $headrev = $v;
2821 } else {
2822 print $un " rev_prop: ", uri_encode($_), ' ',
2823 uri_encode($v), "\n";
2826 } else {
2827 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
2829 close $un or croak $!;
2831 $log_entry{date} = parse_svn_date($log_entry{date});
2832 $log_entry{log} .= "\n";
2833 my $author = $log_entry{author} = check_author($log_entry{author});
2834 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
2835 : ($author, undef);
2837 my ($commit_name, $commit_email) = ($name, $email);
2838 if ($_use_log_author) {
2839 my $name_field;
2840 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
2841 $name_field = $1;
2842 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
2843 $name_field = $1;
2845 if (!defined $name_field) {
2846 if (!defined $email) {
2847 $email = $name;
2849 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
2850 ($name, $email) = ($1, $2);
2851 } elsif ($name_field =~ /(.*)@/) {
2852 ($name, $email) = ($1, $name_field);
2853 } else {
2854 ($name, $email) = ($name_field, $name_field);
2857 if (defined $headrev && $self->use_svm_props) {
2858 if ($self->rewrite_root) {
2859 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2860 "options set!\n";
2862 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
2863 # we don't want "SVM: initializing mirror for junk" ...
2864 return undef if $r == 0;
2865 my $svm = $self->svm;
2866 if ($uuid ne $svm->{uuid}) {
2867 die "UUID mismatch on SVM path:\n",
2868 "expected: $svm->{uuid}\n",
2869 " got: $uuid\n";
2871 my $full_url = $self->full_url;
2872 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2873 die "Failed to replace '$svm->{replace}' with ",
2874 "'$svm->{source}' in $full_url\n";
2875 # throw away username for storing in records
2876 remove_username($full_url);
2877 $log_entry{metadata} = "$full_url\@$r $uuid";
2878 $log_entry{svm_revision} = $r;
2879 $email ||= "$author\@$uuid";
2880 $commit_email ||= "$author\@$uuid";
2881 } elsif ($self->use_svnsync_props) {
2882 my $full_url = $self->svnsync->{url};
2883 $full_url .= "/$self->{path}" if length $self->{path};
2884 remove_username($full_url);
2885 my $uuid = $self->svnsync->{uuid};
2886 $log_entry{metadata} = "$full_url\@$rev $uuid";
2887 $email ||= "$author\@$uuid";
2888 $commit_email ||= "$author\@$uuid";
2889 } else {
2890 my $url = $self->metadata_url;
2891 remove_username($url);
2892 $log_entry{metadata} = "$url\@$rev " .
2893 $self->ra->get_uuid;
2894 $email ||= "$author\@" . $self->ra->get_uuid;
2895 $commit_email ||= "$author\@" . $self->ra->get_uuid;
2897 $log_entry{name} = $name;
2898 $log_entry{email} = $email;
2899 $log_entry{commit_name} = $commit_name;
2900 $log_entry{commit_email} = $commit_email;
2901 \%log_entry;
2904 sub fetch {
2905 my ($self, $min_rev, $max_rev, @parents) = @_;
2906 my ($last_rev, $last_commit) = $self->last_rev_commit;
2907 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2908 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2911 sub set_tree_cb {
2912 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2913 $self->{inject_parents} = { $rev => $tree };
2914 $self->fetch(undef, undef);
2917 sub set_tree {
2918 my ($self, $tree) = (shift, shift);
2919 my $log_entry = ::get_commit_entry($tree);
2920 unless ($self->{last_rev}) {
2921 ::fatal("Must have an existing revision to commit");
2923 my %ed_opts = ( r => $self->{last_rev},
2924 log => $log_entry->{log},
2925 ra => $self->ra,
2926 tree_a => $self->{last_commit},
2927 tree_b => $tree,
2928 editor_cb => sub {
2929 $self->set_tree_cb($log_entry, $tree, @_) },
2930 svn_path => $self->{path} );
2931 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2932 print "No changes\nr$self->{last_rev} = $tree\n";
2936 sub rebuild_from_rev_db {
2937 my ($self, $path) = @_;
2938 my $r = -1;
2939 open my $fh, '<', $path or croak "open: $!";
2940 binmode $fh or croak "binmode: $!";
2941 while (<$fh>) {
2942 length($_) == 41 or croak "inconsistent size in ($_) != 41";
2943 chomp($_);
2944 ++$r;
2945 next if $_ eq ('0' x 40);
2946 $self->rev_map_set($r, $_);
2947 print "r$r = $_\n";
2949 close $fh or croak "close: $!";
2950 unlink $path or croak "unlink: $!";
2953 sub rebuild {
2954 my ($self) = @_;
2955 my $map_path = $self->map_path;
2956 my $partial = (-e $map_path && ! -z $map_path);
2957 return unless ::verify_ref($self->refname.'^0');
2958 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
2959 my $rev_db = $self->rev_db_path;
2960 $self->rebuild_from_rev_db($rev_db);
2961 if ($self->use_svm_props) {
2962 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
2963 $self->rebuild_from_rev_db($svm_rev_db);
2965 $self->unlink_rev_db_symlink;
2966 return;
2968 print "Rebuilding $map_path ...\n" if (!$partial);
2969 my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
2970 (undef, undef));
2971 my ($log, $ctx) =
2972 command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
2973 ($head ? "$head.." : "") . $self->refname,
2974 '--');
2975 my $metadata_url = $self->metadata_url;
2976 remove_username($metadata_url);
2977 my $svn_uuid = $self->ra_uuid;
2978 my $c;
2979 while (<$log>) {
2980 if ( m{^commit ($::sha1)$} ) {
2981 $c = $1;
2982 next;
2984 next unless s{^\s*(git-svn-id:)}{$1};
2985 my ($url, $rev, $uuid) = ::extract_metadata($_);
2986 remove_username($url);
2988 # ignore merges (from set-tree)
2989 next if (!defined $rev || !$uuid);
2991 # if we merged or otherwise started elsewhere, this is
2992 # how we break out of it
2993 if (($uuid ne $svn_uuid) ||
2994 ($metadata_url && $url && ($url ne $metadata_url))) {
2995 next;
2997 if ($partial && $head) {
2998 print "Partial-rebuilding $map_path ...\n";
2999 print "Currently at $base_rev = $head\n";
3000 $head = undef;
3003 $self->rev_map_set($rev, $c);
3004 print "r$rev = $c\n";
3006 command_close_pipe($log, $ctx);
3007 print "Done rebuilding $map_path\n" if (!$partial || !$head);
3008 my $rev_db_path = $self->rev_db_path;
3009 if (-f $self->rev_db_path) {
3010 unlink $self->rev_db_path or croak "unlink: $!";
3012 $self->unlink_rev_db_symlink;
3015 # rev_map:
3016 # Tie::File seems to be prone to offset errors if revisions get sparse,
3017 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
3018 # one of my favorite modules is out :< Next up would be one of the DBM
3019 # modules, but I'm not sure which is most portable...
3021 # This is the replacement for the rev_db format, which was too big
3022 # and inefficient for large repositories with a lot of sparse history
3023 # (mainly tags)
3025 # The format is this:
3026 # - 24 bytes for every record,
3027 # * 4 bytes for the integer representing an SVN revision number
3028 # * 20 bytes representing the sha1 of a git commit
3029 # - No empty padding records like the old format
3030 # (except the last record, which can be overwritten)
3031 # - new records are written append-only since SVN revision numbers
3032 # increase monotonically
3033 # - lookups on SVN revision number are done via a binary search
3034 # - Piping the file to xxd -c24 is a good way of dumping it for
3035 # viewing or editing (piped back through xxd -r), should the need
3036 # ever arise.
3037 # - The last record can be padding revision with an all-zero sha1
3038 # This is used to optimize fetch performance when using multiple
3039 # "fetch" directives in .git/config
3041 # These files are disposable unless noMetadata or useSvmProps is set
3043 sub _rev_map_set {
3044 my ($fh, $rev, $commit) = @_;
3046 binmode $fh or croak "binmode: $!";
3047 my $size = (stat($fh))[7];
3048 ($size % 24) == 0 or croak "inconsistent size: $size";
3050 my $wr_offset = 0;
3051 if ($size > 0) {
3052 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3053 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
3054 $read == 24 or croak "read only $read bytes (!= 24)";
3055 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
3056 if ($last_commit eq ('0' x40)) {
3057 if ($size >= 48) {
3058 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3059 $read = sysread($fh, $buf, 24) or
3060 croak "read: $!";
3061 $read == 24 or
3062 croak "read only $read bytes (!= 24)";
3063 ($last_rev, $last_commit) =
3064 unpack(rev_map_fmt, $buf);
3065 if ($last_commit eq ('0' x40)) {
3066 croak "inconsistent .rev_map\n";
3069 if ($last_rev >= $rev) {
3070 croak "last_rev is higher!: $last_rev >= $rev";
3072 $wr_offset = -24;
3075 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
3076 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
3077 croak "write: $!";
3080 sub _rev_map_reset {
3081 my ($fh, $rev, $commit) = @_;
3082 my $c = _rev_map_get($fh, $rev);
3083 $c eq $commit or die "_rev_map_reset(@_) commit $c does not match!\n";
3084 my $offset = sysseek($fh, 0, SEEK_CUR) or croak "seek: $!";
3085 truncate $fh, $offset or croak "truncate: $!";
3088 sub mkfile {
3089 my ($path) = @_;
3090 unless (-e $path) {
3091 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
3092 mkpath([$dir]) unless -d $dir;
3093 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
3094 close $fh or die "Couldn't close (create) $path: $!\n";
3098 sub rev_map_set {
3099 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
3100 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
3101 my $db = $self->map_path($uuid);
3102 my $db_lock = "$db.lock";
3103 my $sig;
3104 $update_ref ||= 0;
3105 if ($update_ref) {
3106 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3107 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
3109 mkfile($db);
3111 $LOCKFILES{$db_lock} = 1;
3112 my $sync;
3113 # both of these options make our .rev_db file very, very important
3114 # and we can't afford to lose it because rebuild() won't work
3115 if ($self->use_svm_props || $self->no_metadata) {
3116 $sync = 1;
3117 copy($db, $db_lock) or die "rev_map_set(@_): ",
3118 "Failed to copy: ",
3119 "$db => $db_lock ($!)\n";
3120 } else {
3121 rename $db, $db_lock or die "rev_map_set(@_): ",
3122 "Failed to rename: ",
3123 "$db => $db_lock ($!)\n";
3126 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
3127 or croak "Couldn't open $db_lock: $!\n";
3128 $update_ref eq 'reset' ? _rev_map_reset($fh, $rev, $commit) :
3129 _rev_map_set($fh, $rev, $commit);
3130 if ($sync) {
3131 $fh->flush or die "Couldn't flush $db_lock: $!\n";
3132 $fh->sync or die "Couldn't sync $db_lock: $!\n";
3134 close $fh or croak $!;
3135 if ($update_ref) {
3136 $_head = $self;
3137 my $note = "";
3138 $note = " ($update_ref)" if ($update_ref !~ /^\d*$/);
3139 command_noisy('update-ref', '-m', "r$rev$note",
3140 $self->refname, $commit);
3142 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
3143 "$db_lock => $db ($!)\n";
3144 delete $LOCKFILES{$db_lock};
3145 if ($update_ref) {
3146 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3147 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
3148 kill $sig, $$ if defined $sig;
3152 # If want_commit, this will return an array of (rev, commit) where
3153 # commit _must_ be a valid commit in the archive.
3154 # Otherwise, it'll return the max revision (whether or not the
3155 # commit is valid or just a 0x40 placeholder).
3156 sub rev_map_max {
3157 my ($self, $want_commit) = @_;
3158 $self->rebuild;
3159 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
3160 $want_commit ? ($r, $c) : $r;
3163 sub rev_map_max_norebuild {
3164 my ($self, $want_commit) = @_;
3165 my $map_path = $self->map_path;
3166 stat $map_path or return $want_commit ? (0, undef) : 0;
3167 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3168 binmode $fh or croak "binmode: $!";
3169 my $size = (stat($fh))[7];
3170 ($size % 24) == 0 or croak "inconsistent size: $size";
3172 if ($size == 0) {
3173 close $fh or croak "close: $!";
3174 return $want_commit ? (0, undef) : 0;
3177 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3178 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3179 my ($r, $c) = unpack(rev_map_fmt, $buf);
3180 if ($want_commit && $c eq ('0' x40)) {
3181 if ($size < 48) {
3182 return $want_commit ? (0, undef) : 0;
3184 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3185 sysread($fh, $buf, 24) == 24 or croak "read: $!";
3186 ($r, $c) = unpack(rev_map_fmt, $buf);
3187 if ($c eq ('0'x40)) {
3188 croak "Penultimate record is all-zeroes in $map_path";
3191 close $fh or croak "close: $!";
3192 $want_commit ? ($r, $c) : $r;
3195 sub rev_map_get {
3196 my ($self, $rev, $uuid) = @_;
3197 my $map_path = $self->map_path($uuid);
3198 return undef unless -e $map_path;
3200 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3201 my $c = _rev_map_get($fh, $rev);
3202 close($fh) or croak "close: $!";
3206 sub _rev_map_get {
3207 my ($fh, $rev) = @_;
3209 binmode $fh or croak "binmode: $!";
3210 my $size = (stat($fh))[7];
3211 ($size % 24) == 0 or croak "inconsistent size: $size";
3213 if ($size == 0) {
3214 return undef;
3217 my ($l, $u) = (0, $size - 24);
3218 my ($r, $c, $buf);
3220 while ($l <= $u) {
3221 my $i = int(($l/24 + $u/24) / 2) * 24;
3222 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
3223 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3224 my ($r, $c) = unpack('NH40', $buf);
3226 if ($r < $rev) {
3227 $l = $i + 24;
3228 } elsif ($r > $rev) {
3229 $u = $i - 24;
3230 } else { # $r == $rev
3231 return $c eq ('0' x 40) ? undef : $c;
3234 undef;
3237 # Finds the first svn revision that exists on (if $eq_ok is true) or
3238 # before $rev for the current branch. It will not search any lower
3239 # than $min_rev. Returns the git commit hash and svn revision number
3240 # if found, else (undef, undef).
3241 sub find_rev_before {
3242 my ($self, $rev, $eq_ok, $min_rev) = @_;
3243 --$rev unless $eq_ok;
3244 $min_rev ||= 1;
3245 my $max_rev = $self->rev_map_max;
3246 $rev = $max_rev if ($rev > $max_rev);
3247 while ($rev >= $min_rev) {
3248 if (my $c = $self->rev_map_get($rev)) {
3249 return ($rev, $c);
3251 --$rev;
3253 return (undef, undef);
3256 # Finds the first svn revision that exists on (if $eq_ok is true) or
3257 # after $rev for the current branch. It will not search any higher
3258 # than $max_rev. Returns the git commit hash and svn revision number
3259 # if found, else (undef, undef).
3260 sub find_rev_after {
3261 my ($self, $rev, $eq_ok, $max_rev) = @_;
3262 ++$rev unless $eq_ok;
3263 $max_rev ||= $self->rev_map_max;
3264 while ($rev <= $max_rev) {
3265 if (my $c = $self->rev_map_get($rev)) {
3266 return ($rev, $c);
3268 ++$rev;
3270 return (undef, undef);
3273 sub _new {
3274 my ($class, $repo_id, $ref_id, $path) = @_;
3275 unless (defined $repo_id && length $repo_id) {
3276 $repo_id = $Git::SVN::default_repo_id;
3278 unless (defined $ref_id && length $ref_id) {
3279 $_[2] = $ref_id = $Git::SVN::default_ref_id;
3281 $_[1] = $repo_id;
3282 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
3283 $_[3] = $path = '' unless (defined $path);
3284 mkpath(["$ENV{GIT_DIR}/svn"]);
3285 bless {
3286 ref_id => $ref_id, dir => $dir, index => "$dir/index",
3287 path => $path, config => "$ENV{GIT_DIR}/svn/config",
3288 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
3291 # for read-only access of old .rev_db formats
3292 sub unlink_rev_db_symlink {
3293 my ($self) = @_;
3294 my $link = $self->rev_db_path;
3295 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
3296 if (-l $link) {
3297 unlink $link or croak "unlink: $link failed!";
3301 sub rev_db_path {
3302 my ($self, $uuid) = @_;
3303 my $db_path = $self->map_path($uuid);
3304 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
3305 or croak "map_path: $db_path does not contain '/.rev_map.' !";
3306 $db_path;
3309 # the new replacement for .rev_db
3310 sub map_path {
3311 my ($self, $uuid) = @_;
3312 $uuid ||= $self->ra_uuid;
3313 "$self->{map_root}.$uuid";
3316 sub uri_encode {
3317 my ($f) = @_;
3318 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
3322 sub remove_username {
3323 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
3326 package Git::SVN::Prompt;
3327 use strict;
3328 use warnings;
3329 require SVN::Core;
3330 use vars qw/$_no_auth_cache $_username/;
3332 sub simple {
3333 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
3334 $may_save = undef if $_no_auth_cache;
3335 $default_username = $_username if defined $_username;
3336 if (defined $default_username && length $default_username) {
3337 if (defined $realm && length $realm) {
3338 print STDERR "Authentication realm: $realm\n";
3339 STDERR->flush;
3341 $cred->username($default_username);
3342 } else {
3343 username($cred, $realm, $may_save, $pool);
3345 $cred->password(_read_password("Password for '" .
3346 $cred->username . "': ", $realm));
3347 $cred->may_save($may_save);
3348 $SVN::_Core::SVN_NO_ERROR;
3351 sub ssl_server_trust {
3352 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
3353 $may_save = undef if $_no_auth_cache;
3354 print STDERR "Error validating server certificate for '$realm':\n";
3356 no warnings 'once';
3357 # All variables SVN::Auth::SSL::* are used only once,
3358 # so we're shutting up Perl warnings about this.
3359 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
3360 print STDERR " - The certificate is not issued ",
3361 "by a trusted authority. Use the\n",
3362 " fingerprint to validate ",
3363 "the certificate manually!\n";
3365 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
3366 print STDERR " - The certificate hostname ",
3367 "does not match.\n";
3369 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
3370 print STDERR " - The certificate is not yet valid.\n";
3372 if ($failures & $SVN::Auth::SSL::EXPIRED) {
3373 print STDERR " - The certificate has expired.\n";
3375 if ($failures & $SVN::Auth::SSL::OTHER) {
3376 print STDERR " - The certificate has ",
3377 "an unknown error.\n";
3379 } # no warnings 'once'
3380 printf STDERR
3381 "Certificate information:\n".
3382 " - Hostname: %s\n".
3383 " - Valid: from %s until %s\n".
3384 " - Issuer: %s\n".
3385 " - Fingerprint: %s\n",
3386 map $cert_info->$_, qw(hostname valid_from valid_until
3387 issuer_dname fingerprint);
3388 my $choice;
3389 prompt:
3390 print STDERR $may_save ?
3391 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
3392 "(R)eject or accept (t)emporarily? ";
3393 STDERR->flush;
3394 $choice = lc(substr(<STDIN> || 'R', 0, 1));
3395 if ($choice =~ /^t$/i) {
3396 $cred->may_save(undef);
3397 } elsif ($choice =~ /^r$/i) {
3398 return -1;
3399 } elsif ($may_save && $choice =~ /^p$/i) {
3400 $cred->may_save($may_save);
3401 } else {
3402 goto prompt;
3404 $cred->accepted_failures($failures);
3405 $SVN::_Core::SVN_NO_ERROR;
3408 sub ssl_client_cert {
3409 my ($cred, $realm, $may_save, $pool) = @_;
3410 $may_save = undef if $_no_auth_cache;
3411 print STDERR "Client certificate filename: ";
3412 STDERR->flush;
3413 chomp(my $filename = <STDIN>);
3414 $cred->cert_file($filename);
3415 $cred->may_save($may_save);
3416 $SVN::_Core::SVN_NO_ERROR;
3419 sub ssl_client_cert_pw {
3420 my ($cred, $realm, $may_save, $pool) = @_;
3421 $may_save = undef if $_no_auth_cache;
3422 $cred->password(_read_password("Password: ", $realm));
3423 $cred->may_save($may_save);
3424 $SVN::_Core::SVN_NO_ERROR;
3427 sub username {
3428 my ($cred, $realm, $may_save, $pool) = @_;
3429 $may_save = undef if $_no_auth_cache;
3430 if (defined $realm && length $realm) {
3431 print STDERR "Authentication realm: $realm\n";
3433 my $username;
3434 if (defined $_username) {
3435 $username = $_username;
3436 } else {
3437 print STDERR "Username: ";
3438 STDERR->flush;
3439 chomp($username = <STDIN>);
3441 $cred->username($username);
3442 $cred->may_save($may_save);
3443 $SVN::_Core::SVN_NO_ERROR;
3446 sub _read_password {
3447 my ($prompt, $realm) = @_;
3448 print STDERR $prompt;
3449 STDERR->flush;
3450 require Term::ReadKey;
3451 Term::ReadKey::ReadMode('noecho');
3452 my $password = '';
3453 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
3454 last if $key =~ /[\012\015]/; # \n\r
3455 $password .= $key;
3457 Term::ReadKey::ReadMode('restore');
3458 print STDERR "\n";
3459 STDERR->flush;
3460 $password;
3463 package SVN::Git::Fetcher;
3464 use vars qw/@ISA/;
3465 use strict;
3466 use warnings;
3467 use Carp qw/croak/;
3468 use File::Temp qw/tempfile/;
3469 use IO::File qw//;
3470 use vars qw/$_ignore_regex/;
3472 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
3473 sub new {
3474 my ($class, $git_svn, $switch_path) = @_;
3475 my $self = SVN::Delta::Editor->new;
3476 bless $self, $class;
3477 if (exists $git_svn->{last_commit}) {
3478 $self->{c} = $git_svn->{last_commit};
3479 $self->{empty_symlinks} =
3480 _mark_empty_symlinks($git_svn, $switch_path);
3482 $self->{ignore_regex} = eval { command_oneline('config', '--get',
3483 "svn-remote.$git_svn->{repo_id}.ignore-paths") };
3484 $self->{empty} = {};
3485 $self->{dir_prop} = {};
3486 $self->{file_prop} = {};
3487 $self->{absent_dir} = {};
3488 $self->{absent_file} = {};
3489 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
3490 $self;
3493 # this uses the Ra object, so it must be called before do_{switch,update},
3494 # not inside them (when the Git::SVN::Fetcher object is passed) to
3495 # do_{switch,update}
3496 sub _mark_empty_symlinks {
3497 my ($git_svn, $switch_path) = @_;
3498 my $bool = Git::config_bool('svn.brokenSymlinkWorkaround');
3499 return {} if (!defined($bool)) || (defined($bool) && ! $bool);
3501 my %ret;
3502 my ($rev, $cmt) = $git_svn->last_rev_commit;
3503 return {} unless ($rev && $cmt);
3505 # allow the warning to be printed for each revision we fetch to
3506 # ensure the user sees it. The user can also disable the workaround
3507 # on the repository even while git svn is running and the next
3508 # revision fetched will skip this expensive function.
3509 my $printed_warning;
3510 chomp(my $empty_blob = `git hash-object -t blob --stdin < /dev/null`);
3511 my ($ls, $ctx) = command_output_pipe(qw/ls-tree -r -z/, $cmt);
3512 local $/ = "\0";
3513 my $pfx = defined($switch_path) ? $switch_path : $git_svn->{path};
3514 $pfx .= '/' if length($pfx);
3515 while (<$ls>) {
3516 chomp;
3517 s/\A100644 blob $empty_blob\t//o or next;
3518 unless ($printed_warning) {
3519 print STDERR "Scanning for empty symlinks, ",
3520 "this may take a while if you have ",
3521 "many empty files\n",
3522 "You may disable this with `",
3523 "git config svn.brokenSymlinkWorkaround ",
3524 "false'.\n",
3525 "This may be done in a different ",
3526 "terminal without restarting ",
3527 "git svn\n";
3528 $printed_warning = 1;
3530 my $path = $_;
3531 my (undef, $props) =
3532 $git_svn->ra->get_file($pfx.$path, $rev, undef);
3533 if ($props->{'svn:special'}) {
3534 $ret{$path} = 1;
3537 command_close_pipe($ls, $ctx);
3538 \%ret;
3541 # returns true if a given path is inside a ".git" directory
3542 sub in_dot_git {
3543 $_[0] =~ m{(?:^|/)\.git(?:/|$)};
3546 # return value: 0 -- don't ignore, 1 -- ignore
3547 sub is_path_ignored {
3548 my ($self, $path) = @_;
3549 return 1 if in_dot_git($path);
3550 return 1 if defined($self->{ignore_regex}) &&
3551 $path =~ m!$self->{ignore_regex}!;
3552 return 0 unless defined($_ignore_regex);
3553 return 1 if $path =~ m!$_ignore_regex!o;
3554 return 0;
3557 sub set_path_strip {
3558 my ($self, $path) = @_;
3559 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
3562 sub open_root {
3563 { path => '' };
3566 sub open_directory {
3567 my ($self, $path, $pb, $rev) = @_;
3568 { path => $path };
3571 sub git_path {
3572 my ($self, $path) = @_;
3573 if ($self->{path_strip}) {
3574 $path =~ s!$self->{path_strip}!! or
3575 die "Failed to strip path '$path' ($self->{path_strip})\n";
3577 $path;
3580 sub delete_entry {
3581 my ($self, $path, $rev, $pb) = @_;
3582 return undef if $self->is_path_ignored($path);
3584 my $gpath = $self->git_path($path);
3585 return undef if ($gpath eq '');
3587 # remove entire directories.
3588 my ($tree) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
3589 =~ /\A040000 tree ([a-f\d]{40})\t\Q$gpath\E\0/);
3590 if ($tree) {
3591 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3592 -r --name-only -z/,
3593 $tree);
3594 local $/ = "\0";
3595 while (<$ls>) {
3596 chomp;
3597 my $rmpath = "$gpath/$_";
3598 $self->{gii}->remove($rmpath);
3599 print "\tD\t$rmpath\n" unless $::_q;
3601 print "\tD\t$gpath/\n" unless $::_q;
3602 command_close_pipe($ls, $ctx);
3603 $self->{empty}->{$path} = 0
3604 } else {
3605 $self->{gii}->remove($gpath);
3606 print "\tD\t$gpath\n" unless $::_q;
3608 undef;
3611 sub open_file {
3612 my ($self, $path, $pb, $rev) = @_;
3613 my ($mode, $blob);
3615 goto out if $self->is_path_ignored($path);
3617 my $gpath = $self->git_path($path);
3618 ($mode, $blob) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
3619 =~ /\A(\d{6}) blob ([a-f\d]{40})\t\Q$gpath\E\0/);
3620 unless (defined $mode && defined $blob) {
3621 die "$path was not found in commit $self->{c} (r$rev)\n";
3623 if ($mode eq '100644' && $self->{empty_symlinks}->{$path}) {
3624 $mode = '120000';
3626 out:
3627 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
3628 pool => SVN::Pool->new, action => 'M' };
3631 sub add_file {
3632 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
3633 my $mode;
3635 if (!$self->is_path_ignored($path)) {
3636 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3637 delete $self->{empty}->{$dir};
3638 $mode = '100644';
3640 { path => $path, mode_a => $mode, mode_b => $mode,
3641 pool => SVN::Pool->new, action => 'A' };
3644 sub add_directory {
3645 my ($self, $path, $cp_path, $cp_rev) = @_;
3646 goto out if $self->is_path_ignored($path);
3647 my $gpath = $self->git_path($path);
3648 if ($gpath eq '') {
3649 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3650 -r --name-only -z/,
3651 $self->{c});
3652 local $/ = "\0";
3653 while (<$ls>) {
3654 chomp;
3655 $self->{gii}->remove($_);
3656 print "\tD\t$_\n" unless $::_q;
3658 command_close_pipe($ls, $ctx);
3659 $self->{empty}->{$path} = 0;
3661 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3662 delete $self->{empty}->{$dir};
3663 $self->{empty}->{$path} = 1;
3664 out:
3665 { path => $path };
3668 sub change_dir_prop {
3669 my ($self, $db, $prop, $value) = @_;
3670 return undef if $self->is_path_ignored($db->{path});
3671 $self->{dir_prop}->{$db->{path}} ||= {};
3672 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
3673 undef;
3676 sub absent_directory {
3677 my ($self, $path, $pb) = @_;
3678 return undef if $self->is_path_ignored($path);
3679 $self->{absent_dir}->{$pb->{path}} ||= [];
3680 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
3681 undef;
3684 sub absent_file {
3685 my ($self, $path, $pb) = @_;
3686 return undef if $self->is_path_ignored($path);
3687 $self->{absent_file}->{$pb->{path}} ||= [];
3688 push @{$self->{absent_file}->{$pb->{path}}}, $path;
3689 undef;
3692 sub change_file_prop {
3693 my ($self, $fb, $prop, $value) = @_;
3694 return undef if $self->is_path_ignored($fb->{path});
3695 if ($prop eq 'svn:executable') {
3696 if ($fb->{mode_b} != 120000) {
3697 $fb->{mode_b} = defined $value ? 100755 : 100644;
3699 } elsif ($prop eq 'svn:special') {
3700 $fb->{mode_b} = defined $value ? 120000 : 100644;
3701 } else {
3702 $self->{file_prop}->{$fb->{path}} ||= {};
3703 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
3705 undef;
3708 sub apply_textdelta {
3709 my ($self, $fb, $exp) = @_;
3710 return undef if $self->is_path_ignored($fb->{path});
3711 my $fh = $::_repository->temp_acquire('svn_delta');
3712 # $fh gets auto-closed() by SVN::TxDelta::apply(),
3713 # (but $base does not,) so dup() it for reading in close_file
3714 open my $dup, '<&', $fh or croak $!;
3715 my $base = $::_repository->temp_acquire('git_blob');
3717 if ($fb->{blob}) {
3718 my ($base_is_link, $size);
3720 if ($fb->{mode_a} eq '120000' &&
3721 ! $self->{empty_symlinks}->{$fb->{path}}) {
3722 print $base 'link ' or die "print $!\n";
3723 $base_is_link = 1;
3725 retry:
3726 $size = $::_repository->cat_blob($fb->{blob}, $base);
3727 die "Failed to read object $fb->{blob}" if ($size < 0);
3729 if (defined $exp) {
3730 seek $base, 0, 0 or croak $!;
3731 my $got = ::md5sum($base);
3732 if ($got ne $exp) {
3733 my $err = "Checksum mismatch: ".
3734 "$fb->{path} $fb->{blob}\n" .
3735 "expected: $exp\n" .
3736 " got: $got\n";
3737 if ($base_is_link) {
3738 warn $err,
3739 "Retrying... (possibly ",
3740 "a bad symlink from SVN)\n";
3741 $::_repository->temp_reset($base);
3742 $base_is_link = 0;
3743 goto retry;
3745 die $err;
3749 seek $base, 0, 0 or croak $!;
3750 $fb->{fh} = $fh;
3751 $fb->{base} = $base;
3752 [ SVN::TxDelta::apply($base, $dup, undef, $fb->{path}, $fb->{pool}) ];
3755 sub close_file {
3756 my ($self, $fb, $exp) = @_;
3757 return undef if $self->is_path_ignored($fb->{path});
3759 my $hash;
3760 my $path = $self->git_path($fb->{path});
3761 if (my $fh = $fb->{fh}) {
3762 if (defined $exp) {
3763 seek($fh, 0, 0) or croak $!;
3764 my $got = ::md5sum($fh);
3765 if ($got ne $exp) {
3766 die "Checksum mismatch: $path\n",
3767 "expected: $exp\n got: $got\n";
3770 if ($fb->{mode_b} == 120000) {
3771 sysseek($fh, 0, 0) or croak $!;
3772 my $rd = sysread($fh, my $buf, 5);
3774 if (!defined $rd) {
3775 croak "sysread: $!\n";
3776 } elsif ($rd == 0) {
3777 warn "$path has mode 120000",
3778 " but it points to nothing\n",
3779 "converting to an empty file with mode",
3780 " 100644\n";
3781 $fb->{mode_b} = '100644';
3782 } elsif ($buf ne 'link ') {
3783 warn "$path has mode 120000",
3784 " but is not a link\n";
3785 } else {
3786 my $tmp_fh = $::_repository->temp_acquire(
3787 'svn_hash');
3788 my $res;
3789 while ($res = sysread($fh, my $str, 1024)) {
3790 my $out = syswrite($tmp_fh, $str, $res);
3791 defined($out) && $out == $res
3792 or croak("write ",
3793 Git::temp_path($tmp_fh),
3794 ": $!\n");
3796 defined $res or croak $!;
3798 ($fh, $tmp_fh) = ($tmp_fh, $fh);
3799 Git::temp_release($tmp_fh, 1);
3803 $hash = $::_repository->hash_and_insert_object(
3804 Git::temp_path($fh));
3805 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
3807 Git::temp_release($fb->{base}, 1);
3808 Git::temp_release($fh, 1);
3809 } else {
3810 $hash = $fb->{blob} or die "no blob information\n";
3812 $fb->{pool}->clear;
3813 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
3814 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
3815 undef;
3818 sub abort_edit {
3819 my $self = shift;
3820 $self->{nr} = $self->{gii}->{nr};
3821 delete $self->{gii};
3822 $self->SUPER::abort_edit(@_);
3825 sub close_edit {
3826 my $self = shift;
3827 $self->{git_commit_ok} = 1;
3828 $self->{nr} = $self->{gii}->{nr};
3829 delete $self->{gii};
3830 $self->SUPER::close_edit(@_);
3833 package SVN::Git::Editor;
3834 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
3835 use strict;
3836 use warnings;
3837 use Carp qw/croak/;
3838 use IO::File;
3840 sub new {
3841 my ($class, $opts) = @_;
3842 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
3843 die "$_ required!\n" unless (defined $opts->{$_});
3846 my $pool = SVN::Pool->new;
3847 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
3848 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
3849 $opts->{r}, $mods);
3851 # $opts->{ra} functions should not be used after this:
3852 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
3853 $opts->{editor_cb}, $pool);
3854 my $self = SVN::Delta::Editor->new(@ce, $pool);
3855 bless $self, $class;
3856 foreach (qw/svn_path r tree_a tree_b/) {
3857 $self->{$_} = $opts->{$_};
3859 $self->{url} = $opts->{ra}->{url};
3860 $self->{mods} = $mods;
3861 $self->{types} = $types;
3862 $self->{pool} = $pool;
3863 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
3864 $self->{rm} = { };
3865 $self->{path_prefix} = length $self->{svn_path} ?
3866 "$self->{svn_path}/" : '';
3867 $self->{config} = $opts->{config};
3868 return $self;
3871 sub generate_diff {
3872 my ($tree_a, $tree_b) = @_;
3873 my @diff_tree = qw(diff-tree -z -r);
3874 if ($_cp_similarity) {
3875 push @diff_tree, "-C$_cp_similarity";
3876 } else {
3877 push @diff_tree, '-C';
3879 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
3880 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
3881 push @diff_tree, $tree_a, $tree_b;
3882 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
3883 local $/ = "\0";
3884 my $state = 'meta';
3885 my @mods;
3886 while (<$diff_fh>) {
3887 chomp $_; # this gets rid of the trailing "\0"
3888 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
3889 ($::sha1)\s($::sha1)\s
3890 ([MTCRAD])\d*$/xo) {
3891 push @mods, { mode_a => $1, mode_b => $2,
3892 sha1_a => $3, sha1_b => $4,
3893 chg => $5 };
3894 if ($5 =~ /^(?:C|R)$/) {
3895 $state = 'file_a';
3896 } else {
3897 $state = 'file_b';
3899 } elsif ($state eq 'file_a') {
3900 my $x = $mods[$#mods] or croak "Empty array\n";
3901 if ($x->{chg} !~ /^(?:C|R)$/) {
3902 croak "Error parsing $_, $x->{chg}\n";
3904 $x->{file_a} = $_;
3905 $state = 'file_b';
3906 } elsif ($state eq 'file_b') {
3907 my $x = $mods[$#mods] or croak "Empty array\n";
3908 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
3909 croak "Error parsing $_, $x->{chg}\n";
3911 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
3912 croak "Error parsing $_, $x->{chg}\n";
3914 $x->{file_b} = $_;
3915 $state = 'meta';
3916 } else {
3917 croak "Error parsing $_\n";
3920 command_close_pipe($diff_fh, $ctx);
3921 \@mods;
3924 sub check_diff_paths {
3925 my ($ra, $pfx, $rev, $mods) = @_;
3926 my %types;
3927 $pfx .= '/' if length $pfx;
3929 sub type_diff_paths {
3930 my ($ra, $types, $path, $rev) = @_;
3931 my @p = split m#/+#, $path;
3932 my $c = shift @p;
3933 unless (defined $types->{$c}) {
3934 $types->{$c} = $ra->check_path($c, $rev);
3936 while (@p) {
3937 $c .= '/' . shift @p;
3938 next if defined $types->{$c};
3939 $types->{$c} = $ra->check_path($c, $rev);
3943 foreach my $m (@$mods) {
3944 foreach my $f (qw/file_a file_b/) {
3945 next unless defined $m->{$f};
3946 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
3947 if (length $pfx.$dir && ! defined $types{$dir}) {
3948 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
3952 \%types;
3955 sub split_path {
3956 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
3959 sub repo_path {
3960 my ($self, $path) = @_;
3961 $self->{path_prefix}.(defined $path ? $path : '');
3964 sub url_path {
3965 my ($self, $path) = @_;
3966 if ($self->{url} =~ m#^https?://#) {
3967 $path =~ s/([^~a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
3969 $self->{url} . '/' . $self->repo_path($path);
3972 sub rmdirs {
3973 my ($self) = @_;
3974 my $rm = $self->{rm};
3975 delete $rm->{''}; # we never delete the url we're tracking
3976 return unless %$rm;
3978 foreach (keys %$rm) {
3979 my @d = split m#/#, $_;
3980 my $c = shift @d;
3981 $rm->{$c} = 1;
3982 while (@d) {
3983 $c .= '/' . shift @d;
3984 $rm->{$c} = 1;
3987 delete $rm->{$self->{svn_path}};
3988 delete $rm->{''}; # we never delete the url we're tracking
3989 return unless %$rm;
3991 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
3992 $self->{tree_b});
3993 local $/ = "\0";
3994 while (<$fh>) {
3995 chomp;
3996 my @dn = split m#/#, $_;
3997 while (pop @dn) {
3998 delete $rm->{join '/', @dn};
4000 unless (%$rm) {
4001 close $fh;
4002 return;
4005 command_close_pipe($fh, $ctx);
4007 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
4008 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
4009 $self->close_directory($bat->{$d}, $p);
4010 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
4011 print "\tD+\t$d/\n" unless $::_q;
4012 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
4013 delete $bat->{$d};
4017 sub open_or_add_dir {
4018 my ($self, $full_path, $baton) = @_;
4019 my $t = $self->{types}->{$full_path};
4020 if (!defined $t) {
4021 die "$full_path not known in r$self->{r} or we have a bug!\n";
4024 no warnings 'once';
4025 # SVN::Node::none and SVN::Node::file are used only once,
4026 # so we're shutting up Perl's warnings about them.
4027 if ($t == $SVN::Node::none) {
4028 return $self->add_directory($full_path, $baton,
4029 undef, -1, $self->{pool});
4030 } elsif ($t == $SVN::Node::dir) {
4031 return $self->open_directory($full_path, $baton,
4032 $self->{r}, $self->{pool});
4033 } # no warnings 'once'
4034 print STDERR "$full_path already exists in repository at ",
4035 "r$self->{r} and it is not a directory (",
4036 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
4037 } # no warnings 'once'
4038 exit 1;
4041 sub ensure_path {
4042 my ($self, $path) = @_;
4043 my $bat = $self->{bat};
4044 my $repo_path = $self->repo_path($path);
4045 return $bat->{''} unless (length $repo_path);
4046 my @p = split m#/+#, $repo_path;
4047 my $c = shift @p;
4048 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
4049 while (@p) {
4050 my $c0 = $c;
4051 $c .= '/' . shift @p;
4052 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
4054 return $bat->{$c};
4057 # Subroutine to convert a globbing pattern to a regular expression.
4058 # From perl cookbook.
4059 sub glob2pat {
4060 my $globstr = shift;
4061 my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
4062 $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
4063 return '^' . $globstr . '$';
4066 sub check_autoprop {
4067 my ($self, $pattern, $properties, $file, $fbat) = @_;
4068 # Convert the globbing pattern to a regular expression.
4069 my $regex = glob2pat($pattern);
4070 # Check if the pattern matches the file name.
4071 if($file =~ m/($regex)/) {
4072 # Parse the list of properties to set.
4073 my @props = split(/;/, $properties);
4074 foreach my $prop (@props) {
4075 # Parse 'name=value' syntax and set the property.
4076 if ($prop =~ /([^=]+)=(.*)/) {
4077 my ($n,$v) = ($1,$2);
4078 for ($n, $v) {
4079 s/^\s+//; s/\s+$//;
4081 $self->change_file_prop($fbat, $n, $v);
4087 sub apply_autoprops {
4088 my ($self, $file, $fbat) = @_;
4089 my $conf_t = ${$self->{config}}{'config'};
4090 no warnings 'once';
4091 # Check [miscellany]/enable-auto-props in svn configuration.
4092 if (SVN::_Core::svn_config_get_bool(
4093 $conf_t,
4094 $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
4095 $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
4096 0)) {
4097 # Auto-props are enabled. Enumerate them to look for matches.
4098 my $callback = sub {
4099 $self->check_autoprop($_[0], $_[1], $file, $fbat);
4101 SVN::_Core::svn_config_enumerate(
4102 $conf_t,
4103 $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
4104 $callback);
4108 sub A {
4109 my ($self, $m) = @_;
4110 my ($dir, $file) = split_path($m->{file_b});
4111 my $pbat = $self->ensure_path($dir);
4112 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4113 undef, -1);
4114 print "\tA\t$m->{file_b}\n" unless $::_q;
4115 $self->apply_autoprops($file, $fbat);
4116 $self->chg_file($fbat, $m);
4117 $self->close_file($fbat,undef,$self->{pool});
4120 sub C {
4121 my ($self, $m) = @_;
4122 my ($dir, $file) = split_path($m->{file_b});
4123 my $pbat = $self->ensure_path($dir);
4124 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4125 $self->url_path($m->{file_a}), $self->{r});
4126 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
4127 $self->chg_file($fbat, $m);
4128 $self->close_file($fbat,undef,$self->{pool});
4131 sub delete_entry {
4132 my ($self, $path, $pbat) = @_;
4133 my $rpath = $self->repo_path($path);
4134 my ($dir, $file) = split_path($rpath);
4135 $self->{rm}->{$dir} = 1;
4136 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
4139 sub R {
4140 my ($self, $m) = @_;
4141 my ($dir, $file) = split_path($m->{file_b});
4142 my $pbat = $self->ensure_path($dir);
4143 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4144 $self->url_path($m->{file_a}), $self->{r});
4145 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
4146 $self->apply_autoprops($file, $fbat);
4147 $self->chg_file($fbat, $m);
4148 $self->close_file($fbat,undef,$self->{pool});
4150 ($dir, $file) = split_path($m->{file_a});
4151 $pbat = $self->ensure_path($dir);
4152 $self->delete_entry($m->{file_a}, $pbat);
4155 sub M {
4156 my ($self, $m) = @_;
4157 my ($dir, $file) = split_path($m->{file_b});
4158 my $pbat = $self->ensure_path($dir);
4159 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
4160 $pbat,$self->{r},$self->{pool});
4161 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
4162 $self->chg_file($fbat, $m);
4163 $self->close_file($fbat,undef,$self->{pool});
4166 sub T { shift->M(@_) }
4168 sub change_file_prop {
4169 my ($self, $fbat, $pname, $pval) = @_;
4170 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
4173 sub _chg_file_get_blob ($$$$) {
4174 my ($self, $fbat, $m, $which) = @_;
4175 my $fh = $::_repository->temp_acquire("git_blob_$which");
4176 if ($m->{"mode_$which"} =~ /^120/) {
4177 print $fh 'link ' or croak $!;
4178 $self->change_file_prop($fbat,'svn:special','*');
4179 } elsif ($m->{mode_a} =~ /^120/ && $m->{"mode_$which"} !~ /^120/) {
4180 $self->change_file_prop($fbat,'svn:special',undef);
4182 my $blob = $m->{"sha1_$which"};
4183 return ($fh,) if ($blob =~ /^0{40}$/);
4184 my $size = $::_repository->cat_blob($blob, $fh);
4185 croak "Failed to read object $blob" if ($size < 0);
4186 $fh->flush == 0 or croak $!;
4187 seek $fh, 0, 0 or croak $!;
4189 my $exp = ::md5sum($fh);
4190 seek $fh, 0, 0 or croak $!;
4191 return ($fh, $exp);
4194 sub chg_file {
4195 my ($self, $fbat, $m) = @_;
4196 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
4197 $self->change_file_prop($fbat,'svn:executable','*');
4198 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
4199 $self->change_file_prop($fbat,'svn:executable',undef);
4201 my ($fh_a, $exp_a) = _chg_file_get_blob $self, $fbat, $m, 'a';
4202 my ($fh_b, $exp_b) = _chg_file_get_blob $self, $fbat, $m, 'b';
4203 my $pool = SVN::Pool->new;
4204 my $atd = $self->apply_textdelta($fbat, $exp_a, $pool);
4205 if (-s $fh_a) {
4206 my $txstream = SVN::TxDelta::new ($fh_a, $fh_b, $pool);
4207 my $res = SVN::TxDelta::send_txstream($txstream, @$atd, $pool);
4208 if (defined $res) {
4209 die "Unexpected result from send_txstream: $res\n",
4210 "(SVN::Core::VERSION: $SVN::Core::VERSION)\n";
4212 } else {
4213 my $got = SVN::TxDelta::send_stream($fh_b, @$atd, $pool);
4214 die "Checksum mismatch\nexpected: $exp_b\ngot: $got\n"
4215 if ($got ne $exp_b);
4217 Git::temp_release($fh_b, 1);
4218 Git::temp_release($fh_a, 1);
4219 $pool->clear;
4222 sub D {
4223 my ($self, $m) = @_;
4224 my ($dir, $file) = split_path($m->{file_b});
4225 my $pbat = $self->ensure_path($dir);
4226 print "\tD\t$m->{file_b}\n" unless $::_q;
4227 $self->delete_entry($m->{file_b}, $pbat);
4230 sub close_edit {
4231 my ($self) = @_;
4232 my ($p,$bat) = ($self->{pool}, $self->{bat});
4233 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
4234 next if $_ eq '';
4235 $self->close_directory($bat->{$_}, $p);
4237 $self->close_directory($bat->{''}, $p);
4238 $self->SUPER::close_edit($p);
4239 $p->clear;
4242 sub abort_edit {
4243 my ($self) = @_;
4244 $self->SUPER::abort_edit($self->{pool});
4247 sub DESTROY {
4248 my $self = shift;
4249 $self->SUPER::DESTROY(@_);
4250 $self->{pool}->clear;
4253 # this drives the editor
4254 sub apply_diff {
4255 my ($self) = @_;
4256 my $mods = $self->{mods};
4257 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
4258 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
4259 my $f = $m->{chg};
4260 if (defined $o{$f}) {
4261 $self->$f($m);
4262 } else {
4263 fatal("Invalid change type: $f");
4266 $self->rmdirs if $_rmdir;
4267 if (@$mods == 0) {
4268 $self->abort_edit;
4269 } else {
4270 $self->close_edit;
4272 return scalar @$mods;
4275 package Git::SVN::Ra;
4276 use vars qw/@ISA $config_dir $_log_window_size/;
4277 use strict;
4278 use warnings;
4279 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
4281 BEGIN {
4282 # enforce temporary pool usage for some simple functions
4283 no strict 'refs';
4284 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root
4285 get_file/) {
4286 my $SUPER = "SUPER::$f";
4287 *$f = sub {
4288 my $self = shift;
4289 my $pool = SVN::Pool->new;
4290 my @ret = $self->$SUPER(@_,$pool);
4291 $pool->clear;
4292 wantarray ? @ret : $ret[0];
4297 sub _auth_providers () {
4299 SVN::Client::get_simple_provider(),
4300 SVN::Client::get_ssl_server_trust_file_provider(),
4301 SVN::Client::get_simple_prompt_provider(
4302 \&Git::SVN::Prompt::simple, 2),
4303 SVN::Client::get_ssl_client_cert_file_provider(),
4304 SVN::Client::get_ssl_client_cert_prompt_provider(
4305 \&Git::SVN::Prompt::ssl_client_cert, 2),
4306 SVN::Client::get_ssl_client_cert_pw_file_provider(),
4307 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
4308 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
4309 SVN::Client::get_username_provider(),
4310 SVN::Client::get_ssl_server_trust_prompt_provider(
4311 \&Git::SVN::Prompt::ssl_server_trust),
4312 SVN::Client::get_username_prompt_provider(
4313 \&Git::SVN::Prompt::username, 2)
4317 sub escape_uri_only {
4318 my ($uri) = @_;
4319 my @tmp;
4320 foreach (split m{/}, $uri) {
4321 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
4322 push @tmp, $_;
4324 join('/', @tmp);
4327 sub escape_url {
4328 my ($url) = @_;
4329 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
4330 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
4331 $url = "$scheme://$domain$uri";
4333 $url;
4336 sub new {
4337 my ($class, $url) = @_;
4338 $url =~ s!/+$!!;
4339 return $RA if ($RA && $RA->{url} eq $url);
4341 SVN::_Core::svn_config_ensure($config_dir, undef);
4342 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
4343 my $config = SVN::Core::config_get_config($config_dir);
4344 $RA = undef;
4345 my $dont_store_passwords = 1;
4346 my $conf_t = ${$config}{'config'};
4348 no warnings 'once';
4349 # The usage of $SVN::_Core::SVN_CONFIG_* variables
4350 # produces warnings that variables are used only once.
4351 # I had not found the better way to shut them up, so
4352 # the warnings of type 'once' are disabled in this block.
4353 if (SVN::_Core::svn_config_get_bool($conf_t,
4354 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4355 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
4356 1) == 0) {
4357 SVN::_Core::svn_auth_set_parameter($baton,
4358 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
4359 bless (\$dont_store_passwords, "_p_void"));
4361 if (SVN::_Core::svn_config_get_bool($conf_t,
4362 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4363 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
4364 1) == 0) {
4365 $Git::SVN::Prompt::_no_auth_cache = 1;
4367 } # no warnings 'once'
4368 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
4369 config => $config,
4370 pool => SVN::Pool->new,
4371 auth_provider_callbacks => $callbacks);
4372 $self->{url} = $url;
4373 $self->{svn_path} = $url;
4374 $self->{repos_root} = $self->get_repos_root;
4375 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
4376 $self->{cache} = { check_path => { r => 0, data => {} },
4377 get_dir => { r => 0, data => {} } };
4378 $RA = bless $self, $class;
4381 sub check_path {
4382 my ($self, $path, $r) = @_;
4383 my $cache = $self->{cache}->{check_path};
4384 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
4385 return $cache->{data}->{$path};
4387 my $pool = SVN::Pool->new;
4388 my $t = $self->SUPER::check_path($path, $r, $pool);
4389 $pool->clear;
4390 if ($r != $cache->{r}) {
4391 %{$cache->{data}} = ();
4392 $cache->{r} = $r;
4394 $cache->{data}->{$path} = $t;
4397 sub get_dir {
4398 my ($self, $dir, $r) = @_;
4399 my $cache = $self->{cache}->{get_dir};
4400 if ($r == $cache->{r}) {
4401 if (my $x = $cache->{data}->{$dir}) {
4402 return wantarray ? @$x : $x->[0];
4405 my $pool = SVN::Pool->new;
4406 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
4407 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
4408 $pool->clear;
4409 if ($r != $cache->{r}) {
4410 %{$cache->{data}} = ();
4411 $cache->{r} = $r;
4413 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
4414 wantarray ? (\%dirents, $r, $props) : \%dirents;
4417 sub DESTROY {
4418 # do not call the real DESTROY since we store ourselves in $RA
4421 # get_log(paths, start, end, limit,
4422 # discover_changed_paths, strict_node_history, receiver)
4423 sub get_log {
4424 my ($self, @args) = @_;
4425 my $pool = SVN::Pool->new;
4427 # the limit parameter was not supported in SVN 1.1.x, so we
4428 # drop it. Therefore, the receiver callback passed to it
4429 # is made aware of this limitation by being wrapped if
4430 # the limit passed to is being wrapped.
4431 if ($SVN::Core::VERSION le '1.2.0') {
4432 my $limit = splice(@args, 3, 1);
4433 if ($limit > 0) {
4434 my $receiver = pop @args;
4435 push(@args, sub { &$receiver(@_) if (--$limit >= 0) });
4438 my $ret = $self->SUPER::get_log(@args, $pool);
4439 $pool->clear;
4440 $ret;
4443 sub trees_match {
4444 my ($self, $url1, $rev1, $url2, $rev2) = @_;
4445 my $ctx = SVN::Client->new(auth => _auth_providers);
4446 my $out = IO::File->new_tmpfile;
4448 # older SVN (1.1.x) doesn't take $pool as the last parameter for
4449 # $ctx->diff(), so we'll create a default one
4450 my $pool = SVN::Pool->new_default_sub;
4452 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
4453 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
4454 $out->flush;
4455 my $ret = (($out->stat)[7] == 0);
4456 close $out or croak $!;
4458 $ret;
4461 sub get_commit_editor {
4462 my ($self, $log, $cb, $pool) = @_;
4463 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
4464 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
4467 sub gs_do_update {
4468 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
4469 my $new = ($rev_a == $rev_b);
4470 my $path = $gs->{path};
4472 if ($new && -e $gs->{index}) {
4473 unlink $gs->{index} or die
4474 "Couldn't unlink index: $gs->{index}: $!\n";
4476 my $pool = SVN::Pool->new;
4477 $editor->set_path_strip($path);
4478 my (@pc) = split m#/#, $path;
4479 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
4480 1, $editor, $pool);
4481 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4483 # Since we can't rely on svn_ra_reparent being available, we'll
4484 # just have to do some magic with set_path to make it so
4485 # we only want a partial path.
4486 my $sp = '';
4487 my $final = join('/', @pc);
4488 while (@pc) {
4489 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
4490 $sp .= '/' if length $sp;
4491 $sp .= shift @pc;
4493 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
4495 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
4497 $reporter->finish_report($pool);
4498 $pool->clear;
4499 $editor->{git_commit_ok};
4502 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
4503 # svn_ra_reparent didn't work before 1.4)
4504 sub gs_do_switch {
4505 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
4506 my $path = $gs->{path};
4507 my $pool = SVN::Pool->new;
4509 my $full_url = $self->{url};
4510 my $old_url = $full_url;
4511 $full_url .= '/' . escape_uri_only($path) if length $path;
4512 my ($ra, $reparented);
4514 if ($old_url =~ m#^svn(\+ssh)?://#) {
4515 $_[0] = undef;
4516 $self = undef;
4517 $RA = undef;
4518 $ra = Git::SVN::Ra->new($full_url);
4519 $ra_invalid = 1;
4520 } elsif ($old_url ne $full_url) {
4521 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url, $pool);
4522 $self->{url} = $full_url;
4523 $reparented = 1;
4526 $ra ||= $self;
4527 $url_b = escape_url($url_b);
4528 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
4529 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4530 $reporter->set_path('', $rev_a, 0, @lock, $pool);
4531 $reporter->finish_report($pool);
4533 if ($reparented) {
4534 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
4535 $self->{url} = $old_url;
4538 $pool->clear;
4539 $editor->{git_commit_ok};
4542 sub longest_common_path {
4543 my ($gsv, $globs) = @_;
4544 my %common;
4545 my $common_max = scalar @$gsv;
4547 foreach my $gs (@$gsv) {
4548 my @tmp = split m#/#, $gs->{path};
4549 my $p = '';
4550 foreach (@tmp) {
4551 $p .= length($p) ? "/$_" : $_;
4552 $common{$p} ||= 0;
4553 $common{$p}++;
4556 $globs ||= [];
4557 $common_max += scalar @$globs;
4558 foreach my $glob (@$globs) {
4559 my @tmp = split m#/#, $glob->{path}->{left};
4560 my $p = '';
4561 foreach (@tmp) {
4562 $p .= length($p) ? "/$_" : $_;
4563 $common{$p} ||= 0;
4564 $common{$p}++;
4568 my $longest_path = '';
4569 foreach (sort {length $b <=> length $a} keys %common) {
4570 if ($common{$_} == $common_max) {
4571 $longest_path = $_;
4572 last;
4575 $longest_path;
4578 sub gs_fetch_loop_common {
4579 my ($self, $base, $head, $gsv, $globs) = @_;
4580 return if ($base > $head);
4581 my $inc = $_log_window_size;
4582 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
4583 my $longest_path = longest_common_path($gsv, $globs);
4584 my $ra_url = $self->{url};
4585 my $find_trailing_edge;
4586 while (1) {
4587 my %revs;
4588 my $err;
4589 my $err_handler = $SVN::Error::handler;
4590 $SVN::Error::handler = sub {
4591 ($err) = @_;
4592 skip_unknown_revs($err);
4594 sub _cb {
4595 my ($paths, $r, $author, $date, $log) = @_;
4596 [ dup_changed_paths($paths),
4597 { author => $author, date => $date, log => $log } ];
4599 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
4600 sub { $revs{$_[1]} = _cb(@_) });
4601 if ($err) {
4602 print "Checked through r$max\r";
4603 } else {
4604 $find_trailing_edge = 1;
4606 if ($err and $find_trailing_edge) {
4607 print STDERR "Path '$longest_path' ",
4608 "was probably deleted:\n",
4609 $err->expanded_message,
4610 "\nWill attempt to follow ",
4611 "revisions r$min .. r$max ",
4612 "committed before the deletion\n";
4613 my $hi = $max;
4614 while (--$hi >= $min) {
4615 my $ok;
4616 $self->get_log([$longest_path], $min, $hi,
4617 0, 1, 1, sub {
4618 $ok = $_[1];
4619 $revs{$_[1]} = _cb(@_) });
4620 if ($ok) {
4621 print STDERR "r$min .. r$ok OK\n";
4622 last;
4625 $find_trailing_edge = 0;
4627 $SVN::Error::handler = $err_handler;
4629 my %exists = map { $_->{path} => $_ } @$gsv;
4630 foreach my $r (sort {$a <=> $b} keys %revs) {
4631 my ($paths, $logged) = @{$revs{$r}};
4633 foreach my $gs ($self->match_globs(\%exists, $paths,
4634 $globs, $r)) {
4635 if ($gs->rev_map_max >= $r) {
4636 next;
4638 next unless $gs->match_paths($paths, $r);
4639 $gs->{logged_rev_props} = $logged;
4640 if (my $last_commit = $gs->last_commit) {
4641 $gs->assert_index_clean($last_commit);
4643 my $log_entry = $gs->do_fetch($paths, $r);
4644 if ($log_entry) {
4645 $gs->do_git_commit($log_entry);
4647 $INDEX_FILES{$gs->{index}} = 1;
4649 foreach my $g (@$globs) {
4650 my $k = "svn-remote.$g->{remote}." .
4651 "$g->{t}-maxRev";
4652 Git::SVN::tmp_config($k, $r);
4654 if ($ra_invalid) {
4655 $_[0] = undef;
4656 $self = undef;
4657 $RA = undef;
4658 $self = Git::SVN::Ra->new($ra_url);
4659 $ra_invalid = undef;
4662 # pre-fill the .rev_db since it'll eventually get filled in
4663 # with '0' x40 if something new gets committed
4664 foreach my $gs (@$gsv) {
4665 next if $gs->rev_map_max >= $max;
4666 next if defined $gs->rev_map_get($max);
4667 $gs->rev_map_set($max, 0 x40);
4669 foreach my $g (@$globs) {
4670 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
4671 Git::SVN::tmp_config($k, $max);
4673 last if $max >= $head;
4674 $min = $max + 1;
4675 $max += $inc;
4676 $max = $head if ($max > $head);
4678 Git::SVN::gc();
4681 sub get_dir_globbed {
4682 my ($self, $left, $depth, $r) = @_;
4684 my @x = eval { $self->get_dir($left, $r) };
4685 return unless scalar @x == 3;
4686 my $dirents = $x[0];
4687 my @finalents;
4688 foreach my $de (keys %$dirents) {
4689 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
4690 if ($depth > 1) {
4691 my @args = ("$left/$de", $depth - 1, $r);
4692 foreach my $dir ($self->get_dir_globbed(@args)) {
4693 push @finalents, "$de/$dir";
4695 } else {
4696 push @finalents, $de;
4699 @finalents;
4702 sub match_globs {
4703 my ($self, $exists, $paths, $globs, $r) = @_;
4705 sub get_dir_check {
4706 my ($self, $exists, $g, $r) = @_;
4708 my @dirs = $self->get_dir_globbed($g->{path}->{left},
4709 $g->{path}->{depth},
4710 $r);
4712 foreach my $de (@dirs) {
4713 my $p = $g->{path}->full_path($de);
4714 next if $exists->{$p};
4715 next if (length $g->{path}->{right} &&
4716 ($self->check_path($p, $r) !=
4717 $SVN::Node::dir));
4718 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
4719 $g->{ref}->full_path($de), 1);
4722 foreach my $g (@$globs) {
4723 if (my $path = $paths->{"/$g->{path}->{left}"}) {
4724 if ($path->{action} =~ /^[AR]$/) {
4725 get_dir_check($self, $exists, $g, $r);
4728 foreach (keys %$paths) {
4729 if (/$g->{path}->{left_regex}/ &&
4730 !/$g->{path}->{regex}/) {
4731 next if $paths->{$_}->{action} !~ /^[AR]$/;
4732 get_dir_check($self, $exists, $g, $r);
4734 next unless /$g->{path}->{regex}/;
4735 my $p = $1;
4736 my $pathname = $g->{path}->full_path($p);
4737 next if $exists->{$pathname};
4738 next if ($self->check_path($pathname, $r) !=
4739 $SVN::Node::dir);
4740 $exists->{$pathname} = Git::SVN->init(
4741 $self->{url}, $pathname, undef,
4742 $g->{ref}->full_path($p), 1);
4744 my $c = '';
4745 foreach (split m#/#, $g->{path}->{left}) {
4746 $c .= "/$_";
4747 next unless ($paths->{$c} &&
4748 ($paths->{$c}->{action} =~ /^[AR]$/));
4749 get_dir_check($self, $exists, $g, $r);
4752 values %$exists;
4755 sub minimize_url {
4756 my ($self) = @_;
4757 return $self->{url} if ($self->{url} eq $self->{repos_root});
4758 my $url = $self->{repos_root};
4759 my @components = split(m!/!, $self->{svn_path});
4760 my $c = '';
4761 do {
4762 $url .= "/$c" if length $c;
4763 eval { (ref $self)->new($url)->get_latest_revnum };
4764 } while ($@ && ($c = shift @components));
4765 $url;
4768 sub can_do_switch {
4769 my $self = shift;
4770 unless (defined $can_do_switch) {
4771 my $pool = SVN::Pool->new;
4772 my $rep = eval {
4773 $self->do_switch(1, '', 0, $self->{url},
4774 SVN::Delta::Editor->new, $pool);
4776 if ($@) {
4777 $can_do_switch = 0;
4778 } else {
4779 $rep->abort_report($pool);
4780 $can_do_switch = 1;
4782 $pool->clear;
4784 $can_do_switch;
4787 sub skip_unknown_revs {
4788 my ($err) = @_;
4789 my $errno = $err->apr_err();
4790 # Maybe the branch we're tracking didn't
4791 # exist when the repo started, so it's
4792 # not an error if it doesn't, just continue
4794 # Wonderfully consistent library, eh?
4795 # 160013 - svn:// and file://
4796 # 175002 - http(s)://
4797 # 175007 - http(s):// (this repo required authorization, too...)
4798 # More codes may be discovered later...
4799 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
4800 my $err_key = $err->expanded_message;
4801 # revision numbers change every time, filter them out
4802 $err_key =~ s/\d+/\0/g;
4803 $err_key = "$errno\0$err_key";
4804 unless ($ignored_err{$err_key}) {
4805 warn "W: Ignoring error from SVN, path probably ",
4806 "does not exist: ($errno): ",
4807 $err->expanded_message,"\n";
4808 warn "W: Do not be alarmed at the above message ",
4809 "git-svn is just searching aggressively for ",
4810 "old history.\n",
4811 "This may take a while on large repositories\n";
4812 $ignored_err{$err_key} = 1;
4814 return;
4816 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
4819 # svn_log_changed_path_t objects passed to get_log are likely to be
4820 # overwritten even if only the refs are copied to an external variable,
4821 # so we should dup the structures in their entirety. Using an externally
4822 # passed pool (instead of our temporary and quickly cleared pool in
4823 # Git::SVN::Ra) does not help matters at all...
4824 sub dup_changed_paths {
4825 my ($paths) = @_;
4826 return undef unless $paths;
4827 my %ret;
4828 foreach my $p (keys %$paths) {
4829 my $i = $paths->{$p};
4830 my %s = map { $_ => $i->$_ }
4831 qw/copyfrom_path copyfrom_rev action/;
4832 $ret{$p} = \%s;
4834 \%ret;
4837 package Git::SVN::Log;
4838 use strict;
4839 use warnings;
4840 use POSIX qw/strftime/;
4841 use Time::Local;
4842 use constant commit_log_separator => ('-' x 72) . "\n";
4843 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
4844 %rusers $show_commit $incremental/;
4845 my $l_fmt;
4847 sub cmt_showable {
4848 my ($c) = @_;
4849 return 1 if defined $c->{r};
4851 # big commit message got truncated by the 16k pretty buffer in rev-list
4852 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
4853 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
4854 @{$c->{l}} = ();
4855 my @log = command(qw/cat-file commit/, $c->{c});
4857 # shift off the headers
4858 shift @log while ($log[0] ne '');
4859 shift @log;
4861 # TODO: make $c->{l} not have a trailing newline in the future
4862 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
4864 (undef, $c->{r}, undef) = ::extract_metadata(
4865 (grep(/^git-svn-id: /, @log))[-1]);
4867 return defined $c->{r};
4870 sub log_use_color {
4871 return $color || Git->repository->get_colorbool('color.diff');
4874 sub git_svn_log_cmd {
4875 my ($r_min, $r_max, @args) = @_;
4876 my $head = 'HEAD';
4877 my (@files, @log_opts);
4878 foreach my $x (@args) {
4879 if ($x eq '--' || @files) {
4880 push @files, $x;
4881 } else {
4882 if (::verify_ref("$x^0")) {
4883 $head = $x;
4884 } else {
4885 push @log_opts, $x;
4890 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
4891 $gs ||= Git::SVN->_new;
4892 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
4893 $gs->refname);
4894 push @cmd, '-r' unless $non_recursive;
4895 push @cmd, qw/--raw --name-status/ if $verbose;
4896 push @cmd, '--color' if log_use_color();
4897 push @cmd, @log_opts;
4898 if (defined $r_max && $r_max == $r_min) {
4899 push @cmd, '--max-count=1';
4900 if (my $c = $gs->rev_map_get($r_max)) {
4901 push @cmd, $c;
4903 } elsif (defined $r_max) {
4904 if ($r_max < $r_min) {
4905 ($r_min, $r_max) = ($r_max, $r_min);
4907 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
4908 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
4909 # If there are no commits in the range, both $c_max and $c_min
4910 # will be undefined. If there is at least 1 commit in the
4911 # range, both will be defined.
4912 return () if !defined $c_min || !defined $c_max;
4913 if ($c_min eq $c_max) {
4914 push @cmd, '--max-count=1', $c_min;
4915 } else {
4916 push @cmd, '--boundary', "$c_min..$c_max";
4919 return (@cmd, @files);
4922 # adapted from pager.c
4923 sub config_pager {
4924 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
4925 if (!defined $pager) {
4926 $pager = 'less';
4927 } elsif (length $pager == 0 || $pager eq 'cat') {
4928 $pager = undef;
4930 $ENV{GIT_PAGER_IN_USE} = defined($pager);
4933 sub run_pager {
4934 return unless -t *STDOUT && defined $pager;
4935 pipe my ($rfd, $wfd) or return;
4936 defined(my $pid = fork) or ::fatal "Can't fork: $!";
4937 if (!$pid) {
4938 open STDOUT, '>&', $wfd or
4939 ::fatal "Can't redirect to stdout: $!";
4940 return;
4942 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
4943 $ENV{LESS} ||= 'FRSX';
4944 exec $pager or ::fatal "Can't run pager: $! ($pager)";
4947 sub format_svn_date {
4948 # some systmes don't handle or mishandle %z, so be creative.
4949 my $t = shift || time;
4950 my $gm = timelocal(gmtime($t));
4951 my $sign = qw( + + - )[ $t <=> $gm ];
4952 my $gmoff = sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
4953 return strftime("%Y-%m-%d %H:%M:%S $gmoff (%a, %d %b %Y)", localtime($t));
4956 sub parse_git_date {
4957 my ($t, $tz) = @_;
4958 # Date::Parse isn't in the standard Perl distro :(
4959 if ($tz =~ s/^\+//) {
4960 $t += tz_to_s_offset($tz);
4961 } elsif ($tz =~ s/^\-//) {
4962 $t -= tz_to_s_offset($tz);
4964 return $t;
4967 sub set_local_timezone {
4968 if (defined $TZ) {
4969 $ENV{TZ} = $TZ;
4970 } else {
4971 delete $ENV{TZ};
4975 sub tz_to_s_offset {
4976 my ($tz) = @_;
4977 $tz =~ s/(\d\d)$//;
4978 return ($1 * 60) + ($tz * 3600);
4981 sub get_author_info {
4982 my ($dest, $author, $t, $tz) = @_;
4983 $author =~ s/(?:^\s*|\s*$)//g;
4984 $dest->{a_raw} = $author;
4985 my $au;
4986 if ($::_authors) {
4987 $au = $rusers{$author} || undef;
4989 if (!$au) {
4990 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
4992 $dest->{t} = $t;
4993 $dest->{tz} = $tz;
4994 $dest->{a} = $au;
4995 $dest->{t_utc} = parse_git_date($t, $tz);
4998 sub process_commit {
4999 my ($c, $r_min, $r_max, $defer) = @_;
5000 if (defined $r_min && defined $r_max) {
5001 if ($r_min == $c->{r} && $r_min == $r_max) {
5002 show_commit($c);
5003 return 0;
5005 return 1 if $r_min == $r_max;
5006 if ($r_min < $r_max) {
5007 # we need to reverse the print order
5008 return 0 if (defined $limit && --$limit < 0);
5009 push @$defer, $c;
5010 return 1;
5012 if ($r_min != $r_max) {
5013 return 1 if ($r_min < $c->{r});
5014 return 1 if ($r_max > $c->{r});
5017 return 0 if (defined $limit && --$limit < 0);
5018 show_commit($c);
5019 return 1;
5022 sub show_commit {
5023 my $c = shift;
5024 if ($oneline) {
5025 my $x = "\n";
5026 if (my $l = $c->{l}) {
5027 while ($l->[0] =~ /^\s*$/) { shift @$l }
5028 $x = $l->[0];
5030 $l_fmt ||= 'A' . length($c->{r});
5031 print 'r',pack($l_fmt, $c->{r}),' | ';
5032 print "$c->{c} | " if $show_commit;
5033 print $x;
5034 } else {
5035 show_commit_normal($c);
5039 sub show_commit_changed_paths {
5040 my ($c) = @_;
5041 return unless $c->{changed};
5042 print "Changed paths:\n", @{$c->{changed}};
5045 sub show_commit_normal {
5046 my ($c) = @_;
5047 print commit_log_separator, "r$c->{r} | ";
5048 print "$c->{c} | " if $show_commit;
5049 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
5050 my $nr_line = 0;
5052 if (my $l = $c->{l}) {
5053 while ($l->[$#$l] eq "\n" && $#$l > 0
5054 && $l->[($#$l - 1)] eq "\n") {
5055 pop @$l;
5057 $nr_line = scalar @$l;
5058 if (!$nr_line) {
5059 print "1 line\n\n\n";
5060 } else {
5061 if ($nr_line == 1) {
5062 $nr_line = '1 line';
5063 } else {
5064 $nr_line .= ' lines';
5066 print $nr_line, "\n";
5067 show_commit_changed_paths($c);
5068 print "\n";
5069 print $_ foreach @$l;
5071 } else {
5072 print "1 line\n";
5073 show_commit_changed_paths($c);
5074 print "\n";
5077 foreach my $x (qw/raw stat diff/) {
5078 if ($c->{$x}) {
5079 print "\n";
5080 print $_ foreach @{$c->{$x}}
5085 sub cmd_show_log {
5086 my (@args) = @_;
5087 my ($r_min, $r_max);
5088 my $r_last = -1; # prevent dupes
5089 set_local_timezone();
5090 if (defined $::_revision) {
5091 if ($::_revision =~ /^(\d+):(\d+)$/) {
5092 ($r_min, $r_max) = ($1, $2);
5093 } elsif ($::_revision =~ /^\d+$/) {
5094 $r_min = $r_max = $::_revision;
5095 } else {
5096 ::fatal "-r$::_revision is not supported, use ",
5097 "standard 'git log' arguments instead";
5101 config_pager();
5102 @args = git_svn_log_cmd($r_min, $r_max, @args);
5103 if (!@args) {
5104 print commit_log_separator unless $incremental || $oneline;
5105 return;
5107 my $log = command_output_pipe(@args);
5108 run_pager();
5109 my (@k, $c, $d, $stat);
5110 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
5111 while (<$log>) {
5112 if (/^${esc_color}commit -?($::sha1_short)/o) {
5113 my $cmt = $1;
5114 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
5115 $r_last = $c->{r};
5116 process_commit($c, $r_min, $r_max, \@k) or
5117 goto out;
5119 $d = undef;
5120 $c = { c => $cmt };
5121 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
5122 get_author_info($c, $1, $2, $3);
5123 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
5124 # ignore
5125 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
5126 push @{$c->{raw}}, $_;
5127 } elsif (/^${esc_color}[ACRMDT]\t/) {
5128 # we could add $SVN->{svn_path} here, but that requires
5129 # remote access at the moment (repo_path_split)...
5130 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
5131 push @{$c->{changed}}, $_;
5132 } elsif (/^${esc_color}diff /o) {
5133 $d = 1;
5134 push @{$c->{diff}}, $_;
5135 } elsif ($d) {
5136 push @{$c->{diff}}, $_;
5137 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
5138 $esc_color*[\+\-]*$esc_color$/x) {
5139 $stat = 1;
5140 push @{$c->{stat}}, $_;
5141 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
5142 push @{$c->{stat}}, $_;
5143 $stat = undef;
5144 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
5145 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
5146 } elsif (s/^${esc_color} //o) {
5147 push @{$c->{l}}, $_;
5150 if ($c && defined $c->{r} && $c->{r} != $r_last) {
5151 $r_last = $c->{r};
5152 process_commit($c, $r_min, $r_max, \@k);
5154 if (@k) {
5155 ($r_min, $r_max) = ($r_max, $r_min);
5156 process_commit($_, $r_min, $r_max) foreach reverse @k;
5158 out:
5159 close $log;
5160 print commit_log_separator unless $incremental || $oneline;
5163 sub cmd_blame {
5164 my $path = pop;
5166 config_pager();
5167 run_pager();
5169 my ($fh, $ctx, $rev);
5171 if ($_git_format) {
5172 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
5173 while (my $line = <$fh>) {
5174 if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
5175 # Uncommitted edits show up as a rev ID of
5176 # all zeros, which we can't look up with
5177 # cmt_metadata
5178 if ($1 !~ /^0+$/) {
5179 (undef, $rev, undef) =
5180 ::cmt_metadata($1);
5181 $rev = '0' if (!$rev);
5182 } else {
5183 $rev = '0';
5185 $rev = sprintf('%-10s', $rev);
5186 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
5188 print $line;
5190 } else {
5191 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
5192 '--', $path);
5193 my ($sha1);
5194 my %authors;
5195 my @buffer;
5196 my %dsha; #distinct sha keys
5198 while (my $line = <$fh>) {
5199 push @buffer, $line;
5200 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5201 $dsha{$1} = 1;
5205 my $s2r = ::cmt_sha2rev_batch([keys %dsha]);
5207 foreach my $line (@buffer) {
5208 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5209 $rev = $s2r->{$1};
5210 $rev = '0' if (!$rev)
5212 elsif ($line =~ /^author (.*)/) {
5213 $authors{$rev} = $1;
5214 $authors{$rev} =~ s/\s/_/g;
5216 elsif ($line =~ /^\t(.*)$/) {
5217 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
5221 command_close_pipe($fh, $ctx);
5224 package Git::SVN::Migration;
5225 # these version numbers do NOT correspond to actual version numbers
5226 # of git nor git-svn. They are just relative.
5228 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
5230 # v1 layout: .git/$id/info/url, refs/remotes/$id
5232 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
5234 # v3 layout: .git/svn/$id, refs/remotes/$id
5235 # - info/url may remain for backwards compatibility
5236 # - this is what we migrate up to this layout automatically,
5237 # - this will be used by git svn init on single branches
5238 # v3.1 layout (auto migrated):
5239 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
5240 # for backwards compatibility
5242 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
5243 # - this is only created for newly multi-init-ed
5244 # repositories. Similar in spirit to the
5245 # --use-separate-remotes option in git-clone (now default)
5246 # - we do not automatically migrate to this (following
5247 # the example set by core git)
5249 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
5250 # - newer, more-efficient format that uses 24-bytes per record
5251 # with no filler space.
5252 # - use xxd -c24 < .rev_map.$UUID to view and debug
5253 # - This is a one-way migration, repositories updated to the
5254 # new format will not be able to use old git-svn without
5255 # rebuilding the .rev_db. Rebuilding the rev_db is not
5256 # possible if noMetadata or useSvmProps are set; but should
5257 # be no problem for users that use the (sensible) defaults.
5258 use strict;
5259 use warnings;
5260 use Carp qw/croak/;
5261 use File::Path qw/mkpath/;
5262 use File::Basename qw/dirname basename/;
5263 use vars qw/$_minimize/;
5265 sub migrate_from_v0 {
5266 my $git_dir = $ENV{GIT_DIR};
5267 return undef unless -d $git_dir;
5268 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5269 my $migrated = 0;
5270 while (<$fh>) {
5271 chomp;
5272 my ($id, $orig_ref) = ($_, $_);
5273 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
5274 next unless -f "$git_dir/$id/info/url";
5275 my $new_ref = "refs/remotes/$id";
5276 if (::verify_ref("$new_ref^0")) {
5277 print STDERR "W: $orig_ref is probably an old ",
5278 "branch used by an ancient version of ",
5279 "git-svn.\n",
5280 "However, $new_ref also exists.\n",
5281 "We will not be able ",
5282 "to use this branch until this ",
5283 "ambiguity is resolved.\n";
5284 next;
5286 print STDERR "Migrating from v0 layout...\n" if !$migrated;
5287 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
5288 command_noisy('update-ref', $new_ref, $orig_ref);
5289 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
5290 $migrated++;
5292 command_close_pipe($fh, $ctx);
5293 print STDERR "Done migrating from v0 layout...\n" if $migrated;
5294 $migrated;
5297 sub migrate_from_v1 {
5298 my $git_dir = $ENV{GIT_DIR};
5299 my $migrated = 0;
5300 return $migrated unless -d $git_dir;
5301 my $svn_dir = "$git_dir/svn";
5303 # just in case somebody used 'svn' as their $id at some point...
5304 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
5306 print STDERR "Migrating from a git-svn v1 layout...\n";
5307 mkpath([$svn_dir]);
5308 print STDERR "Data from a previous version of git-svn exists, but\n\t",
5309 "$svn_dir\n\t(required for this version ",
5310 "($::VERSION) of git-svn) does not exist.\n";
5311 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5312 while (<$fh>) {
5313 my $x = $_;
5314 next unless $x =~ s#^refs/remotes/##;
5315 chomp $x;
5316 next unless -f "$git_dir/$x/info/url";
5317 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
5318 next unless $u;
5319 my $dn = dirname("$git_dir/svn/$x");
5320 mkpath([$dn]) unless -d $dn;
5321 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
5322 mkpath(["$git_dir/svn/svn"]);
5323 print STDERR " - $git_dir/$x/info => ",
5324 "$git_dir/svn/$x/info\n";
5325 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
5326 croak "$!: $x";
5327 # don't worry too much about these, they probably
5328 # don't exist with repos this old (save for index,
5329 # and we can easily regenerate that)
5330 foreach my $f (qw/unhandled.log index .rev_db/) {
5331 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
5333 } else {
5334 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
5335 rename "$git_dir/$x", "$git_dir/svn/$x" or
5336 croak "$!: $x";
5338 $migrated++;
5340 command_close_pipe($fh, $ctx);
5341 print STDERR "Done migrating from a git-svn v1 layout\n";
5342 $migrated;
5345 sub read_old_urls {
5346 my ($l_map, $pfx, $path) = @_;
5347 my @dir;
5348 foreach (<$path/*>) {
5349 if (-r "$_/info/url") {
5350 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
5351 my $ref_id = $pfx . basename $_;
5352 my $url = ::file_to_s("$_/info/url");
5353 $l_map->{$ref_id} = $url;
5354 } elsif (-d $_) {
5355 push @dir, $_;
5358 foreach (@dir) {
5359 my $x = $_;
5360 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
5361 read_old_urls($l_map, $x, $_);
5365 sub migrate_from_v2 {
5366 my @cfg = command(qw/config -l/);
5367 return if grep /^svn-remote\..+\.url=/, @cfg;
5368 my %l_map;
5369 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
5370 my $migrated = 0;
5372 foreach my $ref_id (sort keys %l_map) {
5373 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
5374 if ($@) {
5375 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
5377 $migrated++;
5379 $migrated;
5382 sub minimize_connections {
5383 my $r = Git::SVN::read_all_remotes();
5384 my $new_urls = {};
5385 my $root_repos = {};
5386 foreach my $repo_id (keys %$r) {
5387 my $url = $r->{$repo_id}->{url} or next;
5388 my $fetch = $r->{$repo_id}->{fetch} or next;
5389 my $ra = Git::SVN::Ra->new($url);
5391 # skip existing cases where we already connect to the root
5392 if (($ra->{url} eq $ra->{repos_root}) ||
5393 ($ra->{repos_root} eq $repo_id)) {
5394 $root_repos->{$ra->{url}} = $repo_id;
5395 next;
5398 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
5399 my $root_path = $ra->{url};
5400 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
5401 foreach my $path (keys %$fetch) {
5402 my $ref_id = $fetch->{$path};
5403 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
5405 # make sure we can read when connecting to
5406 # a higher level of a repository
5407 my ($last_rev, undef) = $gs->last_rev_commit;
5408 if (!defined $last_rev) {
5409 $last_rev = eval {
5410 $root_ra->get_latest_revnum;
5412 next if $@;
5414 my $new = $root_path;
5415 $new .= length $path ? "/$path" : '';
5416 eval {
5417 $root_ra->get_log([$new], $last_rev, $last_rev,
5418 0, 0, 1, sub { });
5420 next if $@;
5421 $new_urls->{$ra->{repos_root}}->{$new} =
5422 { ref_id => $ref_id,
5423 old_repo_id => $repo_id,
5424 old_path => $path };
5428 my @emptied;
5429 foreach my $url (keys %$new_urls) {
5430 # see if we can re-use an existing [svn-remote "repo_id"]
5431 # instead of creating a(n ugly) new section:
5432 my $repo_id = $root_repos->{$url} || $url;
5434 my $fetch = $new_urls->{$url};
5435 foreach my $path (keys %$fetch) {
5436 my $x = $fetch->{$path};
5437 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
5438 my $pfx = "svn-remote.$x->{old_repo_id}";
5440 my $old_fetch = quotemeta("$x->{old_path}:".
5441 "refs/remotes/$x->{ref_id}");
5442 command_noisy(qw/config --unset/,
5443 "$pfx.fetch", '^'. $old_fetch . '$');
5444 delete $r->{$x->{old_repo_id}}->
5445 {fetch}->{$x->{old_path}};
5446 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
5447 command_noisy(qw/config --unset/,
5448 "$pfx.url");
5449 push @emptied, $x->{old_repo_id}
5453 if (@emptied) {
5454 my $file = $ENV{GIT_CONFIG} || "$ENV{GIT_DIR}/config";
5455 print STDERR <<EOF;
5456 The following [svn-remote] sections in your config file ($file) are empty
5457 and can be safely removed:
5459 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
5463 sub migration_check {
5464 migrate_from_v0();
5465 migrate_from_v1();
5466 migrate_from_v2();
5467 minimize_connections() if $_minimize;
5470 package Git::IndexInfo;
5471 use strict;
5472 use warnings;
5473 use Git qw/command_input_pipe command_close_pipe/;
5475 sub new {
5476 my ($class) = @_;
5477 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
5478 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
5481 sub remove {
5482 my ($self, $path) = @_;
5483 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
5484 return ++$self->{nr};
5486 undef;
5489 sub update {
5490 my ($self, $mode, $hash, $path) = @_;
5491 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
5492 return ++$self->{nr};
5494 undef;
5497 sub DESTROY {
5498 my ($self) = @_;
5499 command_close_pipe($self->{gui}, $self->{ctx});
5502 package Git::SVN::GlobSpec;
5503 use strict;
5504 use warnings;
5506 sub new {
5507 my ($class, $glob) = @_;
5508 my $re = $glob;
5509 $re =~ s!/+$!!g; # no need for trailing slashes
5510 $re =~ m!^([^*]*)(\*(?:/\*)*)([^*]*)$!;
5511 my $temp = $re;
5512 my ($left, $right) = ($1, $3);
5513 $re = $2;
5514 my $depth = $re =~ tr/*/*/;
5515 if ($depth != $temp =~ tr/*/*/) {
5516 die "Only one set of wildcard directories " .
5517 "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
5519 if ($depth == 0) {
5520 die "One '*' is needed for glob: '$glob'\n";
5522 $re =~ s!\*!\[^/\]*!g;
5523 $re = quotemeta($left) . "($re)" . quotemeta($right);
5524 if (length $left && !($left =~ s!/+$!!g)) {
5525 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
5527 if (length $right && !($right =~ s!^/+!!g)) {
5528 die "Missing leading '/' on right side of: '$glob' ($right)\n";
5530 my $left_re = qr/^\/\Q$left\E(\/|$)/;
5531 bless { left => $left, right => $right, left_regex => $left_re,
5532 regex => qr/$re/, glob => $glob, depth => $depth }, $class;
5535 sub full_path {
5536 my ($self, $path) = @_;
5537 return (length $self->{left} ? "$self->{left}/" : '') .
5538 $path . (length $self->{right} ? "/$self->{right}" : '');
5541 __END__
5543 Data structures:
5546 $remotes = { # returned by read_all_remotes()
5547 'svn' => {
5548 # svn-remote.svn.url=https://svn.musicpd.org
5549 url => 'https://svn.musicpd.org',
5550 # svn-remote.svn.fetch=mpd/trunk:trunk
5551 fetch => {
5552 'mpd/trunk' => 'trunk',
5554 # svn-remote.svn.tags=mpd/tags/*:tags/*
5555 tags => {
5556 path => {
5557 left => 'mpd/tags',
5558 right => '',
5559 regex => qr!mpd/tags/([^/]+)$!,
5560 glob => 'tags/*',
5562 ref => {
5563 left => 'tags',
5564 right => '',
5565 regex => qr!tags/([^/]+)$!,
5566 glob => 'tags/*',
5572 $log_entry hashref as returned by libsvn_log_entry()
5574 log => 'whitespace-formatted log entry
5575 ', # trailing newline is preserved
5576 revision => '8', # integer
5577 date => '2004-02-24T17:01:44.108345Z', # commit date
5578 author => 'committer name'
5582 # this is generated by generate_diff();
5583 @mods = array of diff-index line hashes, each element represents one line
5584 of diff-index output
5586 diff-index line ($m hash)
5588 mode_a => first column of diff-index output, no leading ':',
5589 mode_b => second column of diff-index output,
5590 sha1_b => sha1sum of the final blob,
5591 chg => change type [MCRADT],
5592 file_a => original file name of a file (iff chg is 'C' or 'R')
5593 file_b => new/current file name of a file (any chg)
5597 # retval of read_url_paths{,_all}();
5598 $l_map = {
5599 # repository root url
5600 'https://svn.musicpd.org' => {
5601 # repository path # GIT_SVN_ID
5602 'mpd/trunk' => 'trunk',
5603 'mpd/tags/0.11.5' => 'tags/0.11.5',
5607 Notes:
5608 I don't trust the each() function on unless I created %hash myself
5609 because the internal iterator may not have started at base.