git-svn: respect i18n.commitencoding config
[alt-git.git] / git-svn.perl
blob2abb7b5937266999e66a8217a02394f8deb29af7
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 %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 Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
43 use IPC::Open3;
44 use Git;
46 BEGIN {
47 # import functions from Git into our packages, en masse
48 no strict 'refs';
49 foreach (qw/command command_oneline command_noisy command_output_pipe
50 command_input_pipe command_close_pipe/) {
51 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
52 Git::SVN::Migration Git::SVN::Log Git::SVN),
53 __PACKAGE__) {
54 *{"${package}::$_"} = \&{"Git::$_"};
59 my ($SVN);
61 $sha1 = qr/[a-f\d]{40}/;
62 $sha1_short = qr/[a-f\d]{4,40}/;
63 my ($_stdin, $_help, $_edit,
64 $_message, $_file,
65 $_template, $_shared,
66 $_version, $_fetch_all, $_no_rebase,
67 $_merge, $_strategy, $_dry_run, $_local,
68 $_prefix, $_no_checkout, $_url, $_verbose,
69 $_git_format, $_commit_url, $_tag);
70 $Git::SVN::_follow_parent = 1;
71 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
72 'config-dir=s' => \$Git::SVN::Ra::config_dir,
73 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache );
74 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
75 'authors-file|A=s' => \$_authors,
76 'repack:i' => \$Git::SVN::_repack,
77 'noMetadata' => \$Git::SVN::_no_metadata,
78 'useSvmProps' => \$Git::SVN::_use_svm_props,
79 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
80 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
81 'no-checkout' => \$_no_checkout,
82 'quiet|q' => \$_q,
83 'repack-flags|repack-args|repack-opts=s' =>
84 \$Git::SVN::_repack_flags,
85 'use-log-author' => \$Git::SVN::_use_log_author,
86 'add-author-from' => \$Git::SVN::_add_author_from,
87 %remote_opts );
89 my ($_trunk, $_tags, $_branches, $_stdlayout);
90 my %icv;
91 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
92 'trunk|T=s' => \$_trunk, 'tags|t=s' => \$_tags,
93 'branches|b=s' => \$_branches, 'prefix=s' => \$_prefix,
94 'stdlayout|s' => \$_stdlayout,
95 'minimize-url|m' => \$Git::SVN::_minimize_url,
96 'no-metadata' => sub { $icv{noMetadata} = 1 },
97 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
98 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
99 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
100 %remote_opts );
101 my %cmt_opts = ( 'edit|e' => \$_edit,
102 'rmdir' => \$SVN::Git::Editor::_rmdir,
103 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
104 'l=i' => \$SVN::Git::Editor::_rename_limit,
105 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
108 my %cmd = (
109 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
110 { 'revision|r=s' => \$_revision,
111 'fetch-all|all' => \$_fetch_all,
112 %fc_opts } ],
113 clone => [ \&cmd_clone, "Initialize and fetch revisions",
114 { 'revision|r=s' => \$_revision,
115 %fc_opts, %init_opts } ],
116 init => [ \&cmd_init, "Initialize a repo for tracking" .
117 " (requires URL argument)",
118 \%init_opts ],
119 'multi-init' => [ \&cmd_multi_init,
120 "Deprecated alias for ".
121 "'$0 init -T<trunk> -b<branches> -t<tags>'",
122 \%init_opts ],
123 dcommit => [ \&cmd_dcommit,
124 'Commit several diffs to merge with upstream',
125 { 'merge|m|M' => \$_merge,
126 'strategy|s=s' => \$_strategy,
127 'verbose|v' => \$_verbose,
128 'dry-run|n' => \$_dry_run,
129 'fetch-all|all' => \$_fetch_all,
130 'commit-url=s' => \$_commit_url,
131 'revision|r=i' => \$_revision,
132 'no-rebase' => \$_no_rebase,
133 %cmt_opts, %fc_opts } ],
134 branch => [ \&cmd_branch,
135 'Create a branch in the SVN repository',
136 { 'message|m=s' => \$_message,
137 'dry-run|n' => \$_dry_run,
138 'tag|t' => \$_tag } ],
139 tag => [ sub { $_tag = 1; cmd_branch(@_) },
140 'Create a tag in the SVN repository',
141 { 'message|m=s' => \$_message,
142 'dry-run|n' => \$_dry_run } ],
143 'set-tree' => [ \&cmd_set_tree,
144 "Set an SVN repository to a git tree-ish",
145 { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
146 'create-ignore' => [ \&cmd_create_ignore,
147 'Create a .gitignore per svn:ignore',
148 { 'revision|r=i' => \$_revision
149 } ],
150 'propget' => [ \&cmd_propget,
151 'Print the value of a property on a file or directory',
152 { 'revision|r=i' => \$_revision } ],
153 'proplist' => [ \&cmd_proplist,
154 'List all properties of a file or directory',
155 { 'revision|r=i' => \$_revision } ],
156 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
157 { 'revision|r=i' => \$_revision
158 } ],
159 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
160 { 'revision|r=i' => \$_revision
161 } ],
162 'multi-fetch' => [ \&cmd_multi_fetch,
163 "Deprecated alias for $0 fetch --all",
164 { 'revision|r=s' => \$_revision, %fc_opts } ],
165 'migrate' => [ sub { },
166 # no-op, we automatically run this anyways,
167 'Migrate configuration/metadata/layout from
168 previous versions of git-svn',
169 { 'minimize' => \$Git::SVN::Migration::_minimize,
170 %remote_opts } ],
171 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
172 { 'limit=i' => \$Git::SVN::Log::limit,
173 'revision|r=s' => \$_revision,
174 'verbose|v' => \$Git::SVN::Log::verbose,
175 'incremental' => \$Git::SVN::Log::incremental,
176 'oneline' => \$Git::SVN::Log::oneline,
177 'show-commit' => \$Git::SVN::Log::show_commit,
178 'non-recursive' => \$Git::SVN::Log::non_recursive,
179 'authors-file|A=s' => \$_authors,
180 'color' => \$Git::SVN::Log::color,
181 'pager=s' => \$Git::SVN::Log::pager
182 } ],
183 'find-rev' => [ \&cmd_find_rev,
184 "Translate between SVN revision numbers and tree-ish",
185 {} ],
186 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
187 { 'merge|m|M' => \$_merge,
188 'verbose|v' => \$_verbose,
189 'strategy|s=s' => \$_strategy,
190 'local|l' => \$_local,
191 'fetch-all|all' => \$_fetch_all,
192 'dry-run|n' => \$_dry_run,
193 %fc_opts } ],
194 'commit-diff' => [ \&cmd_commit_diff,
195 'Commit a diff between two trees',
196 { 'message|m=s' => \$_message,
197 'file|F=s' => \$_file,
198 'revision|r=s' => \$_revision,
199 %cmt_opts } ],
200 'info' => [ \&cmd_info,
201 "Show info about the latest SVN revision
202 on the current branch",
203 { 'url' => \$_url, } ],
204 'blame' => [ \&Git::SVN::Log::cmd_blame,
205 "Show what revision and author last modified each line of a file",
206 { 'git-format' => \$_git_format } ],
209 my $cmd;
210 for (my $i = 0; $i < @ARGV; $i++) {
211 if (defined $cmd{$ARGV[$i]}) {
212 $cmd = $ARGV[$i];
213 splice @ARGV, $i, 1;
214 last;
218 # make sure we're always running at the top-level working directory
219 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
220 unless (-d $ENV{GIT_DIR}) {
221 if ($git_dir_user_set) {
222 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
223 "but it is not a directory\n";
225 my $git_dir = delete $ENV{GIT_DIR};
226 chomp(my $cdup = command_oneline(qw/rev-parse --show-cdup/));
227 unless (length $cdup) {
228 die "Already at toplevel, but $git_dir ",
229 "not found '$cdup'\n";
231 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
232 unless (-d $git_dir) {
233 die "$git_dir still not found after going to ",
234 "'$cdup'\n";
236 $ENV{GIT_DIR} = $git_dir;
238 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
241 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
243 read_repo_config(\%opts);
244 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
245 Getopt::Long::Configure('pass_through');
247 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
248 'minimize-connections' => \$Git::SVN::Migration::_minimize,
249 'id|i=s' => \$Git::SVN::default_ref_id,
250 'svn-remote|remote|R=s' => sub {
251 $Git::SVN::no_reuse_existing = 1;
252 $Git::SVN::default_repo_id = $_[1] });
253 exit 1 if (!$rv && $cmd && $cmd ne 'log');
255 usage(0) if $_help;
256 version() if $_version;
257 usage(1) unless defined $cmd;
258 load_authors() if $_authors;
260 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
261 Git::SVN::Migration::migration_check();
263 Git::SVN::init_vars();
264 eval {
265 Git::SVN::verify_remotes_sanity();
266 $cmd{$cmd}->[0]->(@ARGV);
268 fatal $@ if $@;
269 post_fetch_checkout();
270 exit 0;
272 ####################### primary functions ######################
273 sub usage {
274 my $exit = shift || 0;
275 my $fd = $exit ? \*STDERR : \*STDOUT;
276 print $fd <<"";
277 git-svn - bidirectional operations between a single Subversion tree and git
278 Usage: git svn <command> [options] [arguments]\n
280 print $fd "Available commands:\n" unless $cmd;
282 foreach (sort keys %cmd) {
283 next if $cmd && $cmd ne $_;
284 next if /^multi-/; # don't show deprecated commands
285 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
286 foreach (sort keys %{$cmd{$_}->[2]}) {
287 # mixed-case options are for .git/config only
288 next if /[A-Z]/ && /^[a-z]+$/i;
289 # prints out arguments as they should be passed:
290 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
291 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
292 "--$_" : "-$_" }
293 split /\|/,$_)," $x\n";
296 print $fd <<"";
297 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
298 arbitrary identifier if you're tracking multiple SVN branches/repositories in
299 one git repository and want to keep them separate. See git-svn(1) for more
300 information.
302 exit $exit;
305 sub version {
306 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
307 exit 0;
310 sub do_git_init_db {
311 unless (-d $ENV{GIT_DIR}) {
312 my @init_db = ('init');
313 push @init_db, "--template=$_template" if defined $_template;
314 if (defined $_shared) {
315 if ($_shared =~ /[a-z]/) {
316 push @init_db, "--shared=$_shared";
317 } else {
318 push @init_db, "--shared";
321 command_noisy(@init_db);
322 $_repository = Git->repository(Repository => ".git");
324 my $set;
325 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
326 foreach my $i (keys %icv) {
327 die "'$set' and '$i' cannot both be set\n" if $set;
328 next unless defined $icv{$i};
329 command_noisy('config', "$pfx.$i", $icv{$i});
330 $set = $i;
334 sub init_subdir {
335 my $repo_path = shift or return;
336 mkpath([$repo_path]) unless -d $repo_path;
337 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
338 $ENV{GIT_DIR} = '.git';
339 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
342 sub cmd_clone {
343 my ($url, $path) = @_;
344 if (!defined $path &&
345 (defined $_trunk || defined $_branches || defined $_tags ||
346 defined $_stdlayout) &&
347 $url !~ m#^[a-z\+]+://#) {
348 $path = $url;
350 $path = basename($url) if !defined $path || !length $path;
351 cmd_init($url, $path);
352 Git::SVN::fetch_all($Git::SVN::default_repo_id);
355 sub cmd_init {
356 if (defined $_stdlayout) {
357 $_trunk = 'trunk' if (!defined $_trunk);
358 $_tags = 'tags' if (!defined $_tags);
359 $_branches = 'branches' if (!defined $_branches);
361 if (defined $_trunk || defined $_branches || defined $_tags) {
362 return cmd_multi_init(@_);
364 my $url = shift or die "SVN repository location required ",
365 "as a command-line argument\n";
366 init_subdir(@_);
367 do_git_init_db();
369 Git::SVN->init($url);
372 sub cmd_fetch {
373 if (grep /^\d+=./, @_) {
374 die "'<rev>=<commit>' fetch arguments are ",
375 "no longer supported.\n";
377 my ($remote) = @_;
378 if (@_ > 1) {
379 die "Usage: $0 fetch [--all] [svn-remote]\n";
381 $remote ||= $Git::SVN::default_repo_id;
382 if ($_fetch_all) {
383 cmd_multi_fetch();
384 } else {
385 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
389 sub cmd_set_tree {
390 my (@commits) = @_;
391 if ($_stdin || !@commits) {
392 print "Reading from stdin...\n";
393 @commits = ();
394 while (<STDIN>) {
395 if (/\b($sha1_short)\b/o) {
396 unshift @commits, $1;
400 my @revs;
401 foreach my $c (@commits) {
402 my @tmp = command('rev-parse',$c);
403 if (scalar @tmp == 1) {
404 push @revs, $tmp[0];
405 } elsif (scalar @tmp > 1) {
406 push @revs, reverse(command('rev-list',@tmp));
407 } else {
408 fatal "Failed to rev-parse $c";
411 my $gs = Git::SVN->new;
412 my ($r_last, $cmt_last) = $gs->last_rev_commit;
413 $gs->fetch;
414 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
415 fatal "There are new revisions that were fetched ",
416 "and need to be merged (or acknowledged) ",
417 "before committing.\nlast rev: $r_last\n",
418 " current: $gs->{last_rev}";
420 $gs->set_tree($_) foreach @revs;
421 print "Done committing ",scalar @revs," revisions to SVN\n";
422 unlink $gs->{index};
425 sub cmd_dcommit {
426 my $head = shift;
427 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
428 'Cannot dcommit with a dirty index. Commit your changes first, '
429 . "or stash them with `git stash'.\n";
430 $head ||= 'HEAD';
431 my @refs;
432 my ($url, $rev, $uuid, $gs) = working_head_info($head, \@refs);
433 unless ($gs) {
434 die "Unable to determine upstream SVN information from ",
435 "$head history.\nPerhaps the repository is empty.";
437 $url = defined $_commit_url ? $_commit_url : $gs->full_url;
438 my $last_rev = $_revision if defined $_revision;
439 if ($url) {
440 print "Committing to $url ...\n";
442 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
443 if ($_no_rebase && scalar(@$linear_refs) > 1) {
444 warn "Attempting to commit more than one change while ",
445 "--no-rebase is enabled.\n",
446 "If these changes depend on each other, re-running ",
447 "without --no-rebase may be required."
449 my $expect_url = $url;
450 Git::SVN::remove_username($expect_url);
451 while (1) {
452 my $d = shift @$linear_refs or last;
453 unless (defined $last_rev) {
454 (undef, $last_rev, undef) = cmt_metadata("$d~1");
455 unless (defined $last_rev) {
456 fatal "Unable to extract revision information ",
457 "from commit $d~1";
460 if ($_dry_run) {
461 print "diff-tree $d~1 $d\n";
462 } else {
463 my $cmt_rev;
464 my %ed_opts = ( r => $last_rev,
465 log => get_commit_entry($d)->{log},
466 ra => Git::SVN::Ra->new($url),
467 config => SVN::Core::config_get_config(
468 $Git::SVN::Ra::config_dir
470 tree_a => "$d~1",
471 tree_b => $d,
472 editor_cb => sub {
473 print "Committed r$_[0]\n";
474 $cmt_rev = $_[0];
476 svn_path => '');
477 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
478 print "No changes\n$d~1 == $d\n";
479 } elsif ($parents->{$d} && @{$parents->{$d}}) {
480 $gs->{inject_parents_dcommit}->{$cmt_rev} =
481 $parents->{$d};
483 $_fetch_all ? $gs->fetch_all : $gs->fetch;
484 $last_rev = $cmt_rev;
485 next if $_no_rebase;
487 # we always want to rebase against the current HEAD,
488 # not any head that was passed to us
489 my @diff = command('diff-tree', $d,
490 $gs->refname, '--');
491 my @finish;
492 if (@diff) {
493 @finish = rebase_cmd();
494 print STDERR "W: $d and ", $gs->refname,
495 " differ, using @finish:\n",
496 join("\n", @diff), "\n";
497 } else {
498 print "No changes between current HEAD and ",
499 $gs->refname,
500 "\nResetting to the latest ",
501 $gs->refname, "\n";
502 @finish = qw/reset --mixed/;
504 command_noisy(@finish, $gs->refname);
505 if (@diff) {
506 @refs = ();
507 my ($url_, $rev_, $uuid_, $gs_) =
508 working_head_info($head, \@refs);
509 my ($linear_refs_, $parents_) =
510 linearize_history($gs_, \@refs);
511 if (scalar(@$linear_refs) !=
512 scalar(@$linear_refs_)) {
513 fatal "# of revisions changed ",
514 "\nbefore:\n",
515 join("\n", @$linear_refs),
516 "\n\nafter:\n",
517 join("\n", @$linear_refs_), "\n",
518 'If you are attempting to commit ',
519 "merges, try running:\n\t",
520 'git rebase --interactive',
521 '--preserve-merges ',
522 $gs->refname,
523 "\nBefore dcommitting";
525 if ($url_ ne $expect_url) {
526 fatal "URL mismatch after rebase: ",
527 "$url_ != $expect_url";
529 if ($uuid_ ne $uuid) {
530 fatal "uuid mismatch after rebase: ",
531 "$uuid_ != $uuid";
533 # remap parents
534 my (%p, @l, $i);
535 for ($i = 0; $i < scalar @$linear_refs; $i++) {
536 my $new = $linear_refs_->[$i] or next;
537 $p{$new} =
538 $parents->{$linear_refs->[$i]};
539 push @l, $new;
541 $parents = \%p;
542 $linear_refs = \@l;
546 unlink $gs->{index};
549 sub cmd_branch {
550 my ($branch_name, $head) = @_;
552 unless (defined $branch_name && length $branch_name) {
553 die(($_tag ? "tag" : "branch") . " name required\n");
555 $head ||= 'HEAD';
557 my ($src, $rev, undef, $gs) = working_head_info($head);
559 my $remote = Git::SVN::read_all_remotes()->{svn};
560 my $glob = $remote->{ $_tag ? 'tags' : 'branches' };
561 my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
562 my $dst = join '/', $remote->{url}, $lft, $branch_name, ($rgt || ());
564 my $ctx = SVN::Client->new(
565 auth => Git::SVN::Ra::_auth_providers(),
566 log_msg => sub {
567 ${ $_[0] } = defined $_message
568 ? $_message
569 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
570 . $branch_name;
574 eval {
575 $ctx->ls($dst, 'HEAD', 0);
576 } and die "branch ${branch_name} already exists\n";
578 print "Copying ${src} at r${rev} to ${dst}...\n";
579 $ctx->copy($src, $rev, $dst)
580 unless $_dry_run;
582 $gs->fetch_all;
585 sub cmd_find_rev {
586 my $revision_or_hash = shift or die "SVN or git revision required ",
587 "as a command-line argument\n";
588 my $result;
589 if ($revision_or_hash =~ /^r\d+$/) {
590 my $head = shift;
591 $head ||= 'HEAD';
592 my @refs;
593 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
594 unless ($gs) {
595 die "Unable to determine upstream SVN information from ",
596 "$head history\n";
598 my $desired_revision = substr($revision_or_hash, 1);
599 $result = $gs->rev_map_get($desired_revision, $uuid);
600 } else {
601 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
602 $result = $rev;
604 print "$result\n" if $result;
607 sub cmd_rebase {
608 command_noisy(qw/update-index --refresh/);
609 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
610 unless ($gs) {
611 die "Unable to determine upstream SVN information from ",
612 "working tree history\n";
614 if ($_dry_run) {
615 print "Remote Branch: " . $gs->refname . "\n";
616 print "SVN URL: " . $url . "\n";
617 return;
619 if (command(qw/diff-index HEAD --/)) {
620 print STDERR "Cannot rebase with uncommited changes:\n";
621 command_noisy('status');
622 exit 1;
624 unless ($_local) {
625 # rebase will checkout for us, so no need to do it explicitly
626 $_no_checkout = 'true';
627 $_fetch_all ? $gs->fetch_all : $gs->fetch;
629 command_noisy(rebase_cmd(), $gs->refname);
632 sub cmd_show_ignore {
633 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
634 $gs ||= Git::SVN->new;
635 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
636 $gs->prop_walk($gs->{path}, $r, sub {
637 my ($gs, $path, $props) = @_;
638 print STDOUT "\n# $path\n";
639 my $s = $props->{'svn:ignore'} or return;
640 $s =~ s/[\r\n]+/\n/g;
641 chomp $s;
642 $s =~ s#^#$path#gm;
643 print STDOUT "$s\n";
647 sub cmd_show_externals {
648 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
649 $gs ||= Git::SVN->new;
650 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
651 $gs->prop_walk($gs->{path}, $r, sub {
652 my ($gs, $path, $props) = @_;
653 print STDOUT "\n# $path\n";
654 my $s = $props->{'svn:externals'} or return;
655 $s =~ s/[\r\n]+/\n/g;
656 chomp $s;
657 $s =~ s#^#$path#gm;
658 print STDOUT "$s\n";
662 sub cmd_create_ignore {
663 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
664 $gs ||= Git::SVN->new;
665 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
666 $gs->prop_walk($gs->{path}, $r, sub {
667 my ($gs, $path, $props) = @_;
668 # $path is of the form /path/to/dir/
669 my $ignore = '.' . $path . '.gitignore';
670 my $s = $props->{'svn:ignore'} or return;
671 open(GITIGNORE, '>', $ignore)
672 or fatal("Failed to open `$ignore' for writing: $!");
673 $s =~ s/[\r\n]+/\n/g;
674 chomp $s;
675 # Prefix all patterns so that the ignore doesn't apply
676 # to sub-directories.
677 $s =~ s#^#/#gm;
678 print GITIGNORE "$s\n";
679 close(GITIGNORE)
680 or fatal("Failed to close `$ignore': $!");
681 command_noisy('add', '-f', $ignore);
685 sub canonicalize_path {
686 my ($path) = @_;
687 my $dot_slash_added = 0;
688 if (substr($path, 0, 1) ne "/") {
689 $path = "./" . $path;
690 $dot_slash_added = 1;
692 # File::Spec->canonpath doesn't collapse x/../y into y (for a
693 # good reason), so let's do this manually.
694 $path =~ s#/+#/#g;
695 $path =~ s#/\.(?:/|$)#/#g;
696 $path =~ s#/[^/]+/\.\.##g;
697 $path =~ s#/$##g;
698 $path =~ s#^\./## if $dot_slash_added;
699 $path =~ s#^/##;
700 $path =~ s#^\.$##;
701 return $path;
704 # get_svnprops(PATH)
705 # ------------------
706 # Helper for cmd_propget and cmd_proplist below.
707 sub get_svnprops {
708 my $path = shift;
709 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
710 $gs ||= Git::SVN->new;
712 # prefix THE PATH by the sub-directory from which the user
713 # invoked us.
714 $path = $cmd_dir_prefix . $path;
715 fatal("No such file or directory: $path") unless -e $path;
716 my $is_dir = -d $path ? 1 : 0;
717 $path = $gs->{path} . '/' . $path;
719 # canonicalize the path (otherwise libsvn will abort or fail to
720 # find the file)
721 $path = canonicalize_path($path);
723 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
724 my $props;
725 if ($is_dir) {
726 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
728 else {
729 (undef, $props) = $gs->ra->get_file($path, $r, undef);
731 return $props;
734 # cmd_propget (PROP, PATH)
735 # ------------------------
736 # Print the SVN property PROP for PATH.
737 sub cmd_propget {
738 my ($prop, $path) = @_;
739 $path = '.' if not defined $path;
740 usage(1) if not defined $prop;
741 my $props = get_svnprops($path);
742 if (not defined $props->{$prop}) {
743 fatal("`$path' does not have a `$prop' SVN property.");
745 print $props->{$prop} . "\n";
748 # cmd_proplist (PATH)
749 # -------------------
750 # Print the list of SVN properties for PATH.
751 sub cmd_proplist {
752 my $path = shift;
753 $path = '.' if not defined $path;
754 my $props = get_svnprops($path);
755 print "Properties on '$path':\n";
756 foreach (sort keys %{$props}) {
757 print " $_\n";
761 sub cmd_multi_init {
762 my $url = shift;
763 unless (defined $_trunk || defined $_branches || defined $_tags) {
764 usage(1);
767 # there are currently some bugs that prevent multi-init/multi-fetch
768 # setups from working well without this.
769 $Git::SVN::_minimize_url = 1;
771 $_prefix = '' unless defined $_prefix;
772 if (defined $url) {
773 $url =~ s#/+$##;
774 init_subdir(@_);
776 do_git_init_db();
777 if (defined $_trunk) {
778 my $trunk_ref = $_prefix . 'trunk';
779 # try both old-style and new-style lookups:
780 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
781 unless ($gs_trunk) {
782 my ($trunk_url, $trunk_path) =
783 complete_svn_url($url, $_trunk);
784 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
785 undef, $trunk_ref);
788 return unless defined $_branches || defined $_tags;
789 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
790 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
791 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
794 sub cmd_multi_fetch {
795 my $remotes = Git::SVN::read_all_remotes();
796 foreach my $repo_id (sort keys %$remotes) {
797 if ($remotes->{$repo_id}->{url}) {
798 Git::SVN::fetch_all($repo_id, $remotes);
803 # this command is special because it requires no metadata
804 sub cmd_commit_diff {
805 my ($ta, $tb, $url) = @_;
806 my $usage = "Usage: $0 commit-diff -r<revision> ".
807 "<tree-ish> <tree-ish> [<URL>]";
808 fatal($usage) if (!defined $ta || !defined $tb);
809 my $svn_path = '';
810 if (!defined $url) {
811 my $gs = eval { Git::SVN->new };
812 if (!$gs) {
813 fatal("Needed URL or usable git-svn --id in ",
814 "the command-line\n", $usage);
816 $url = $gs->{url};
817 $svn_path = $gs->{path};
819 unless (defined $_revision) {
820 fatal("-r|--revision is a required argument\n", $usage);
822 if (defined $_message && defined $_file) {
823 fatal("Both --message/-m and --file/-F specified ",
824 "for the commit message.\n",
825 "I have no idea what you mean");
827 if (defined $_file) {
828 $_message = file_to_s($_file);
829 } else {
830 $_message ||= get_commit_entry($tb)->{log};
832 my $ra ||= Git::SVN::Ra->new($url);
833 my $r = $_revision;
834 if ($r eq 'HEAD') {
835 $r = $ra->get_latest_revnum;
836 } elsif ($r !~ /^\d+$/) {
837 die "revision argument: $r not understood by git-svn\n";
839 my %ed_opts = ( r => $r,
840 log => $_message,
841 ra => $ra,
842 tree_a => $ta,
843 tree_b => $tb,
844 editor_cb => sub { print "Committed r$_[0]\n" },
845 svn_path => $svn_path );
846 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
847 print "No changes\n$ta == $tb\n";
851 sub escape_uri_only {
852 my ($uri) = @_;
853 my @tmp;
854 foreach (split m{/}, $uri) {
855 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
856 push @tmp, $_;
858 join('/', @tmp);
861 sub escape_url {
862 my ($url) = @_;
863 if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
864 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
865 $url = "$scheme://$domain$uri";
867 $url;
870 sub cmd_info {
871 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
872 my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
873 if (exists $_[1]) {
874 die "Too many arguments specified\n";
877 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
879 if (!$file_type && !$diff_status) {
880 print STDERR "svn: '$path' is not under version control\n";
881 exit 1;
884 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
885 unless ($gs) {
886 die "Unable to determine upstream SVN information from ",
887 "working tree history\n";
890 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
891 $path = "." if $path eq "";
893 my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
895 if ($_url) {
896 print escape_url($full_url), "\n";
897 return;
900 my $result = "Path: $path\n";
901 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
902 $result .= "URL: " . escape_url($full_url) . "\n";
904 eval {
905 my $repos_root = $gs->repos_root;
906 Git::SVN::remove_username($repos_root);
907 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
909 if ($@) {
910 $result .= "Repository Root: (offline)\n";
912 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A";
913 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
915 $result .= "Node Kind: " .
916 ($file_type eq "dir" ? "directory" : "file") . "\n";
918 my $schedule = $diff_status eq "A"
919 ? "add"
920 : ($diff_status eq "D" ? "delete" : "normal");
921 $result .= "Schedule: $schedule\n";
923 if ($diff_status eq "A") {
924 print $result, "\n";
925 return;
928 my ($lc_author, $lc_rev, $lc_date_utc);
929 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
930 my $log = command_output_pipe(@args);
931 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
932 while (<$log>) {
933 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
934 $lc_author = $1;
935 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
936 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
937 (undef, $lc_rev, undef) = ::extract_metadata($1);
940 close $log;
942 Git::SVN::Log::set_local_timezone();
944 $result .= "Last Changed Author: $lc_author\n";
945 $result .= "Last Changed Rev: $lc_rev\n";
946 $result .= "Last Changed Date: " .
947 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
949 if ($file_type ne "dir") {
950 my $text_last_updated_date =
951 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
952 $result .=
953 "Text Last Updated: " .
954 Git::SVN::Log::format_svn_date($text_last_updated_date) .
955 "\n";
956 my $checksum;
957 if ($diff_status eq "D") {
958 my ($fh, $ctx) =
959 command_output_pipe(qw(cat-file blob), "HEAD:$path");
960 if ($file_type eq "link") {
961 my $file_name = <$fh>;
962 $checksum = md5sum("link $file_name");
963 } else {
964 $checksum = md5sum($fh);
966 command_close_pipe($fh, $ctx);
967 } elsif ($file_type eq "link") {
968 my $file_name =
969 command(qw(cat-file blob), "HEAD:$path");
970 $checksum =
971 md5sum("link " . $file_name);
972 } else {
973 open FILE, "<", $path or die $!;
974 $checksum = md5sum(\*FILE);
975 close FILE or die $!;
977 $result .= "Checksum: " . $checksum . "\n";
980 print $result, "\n";
983 ########################### utility functions #########################
985 sub rebase_cmd {
986 my @cmd = qw/rebase/;
987 push @cmd, '-v' if $_verbose;
988 push @cmd, qw/--merge/ if $_merge;
989 push @cmd, "--strategy=$_strategy" if $_strategy;
990 @cmd;
993 sub post_fetch_checkout {
994 return if $_no_checkout;
995 my $gs = $Git::SVN::_head or return;
996 return if verify_ref('refs/heads/master^0');
998 my $valid_head = verify_ref('HEAD^0');
999 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1000 return if ($valid_head || !verify_ref('HEAD^0'));
1002 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1003 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1004 return if -f $index;
1006 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1007 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1008 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1009 print STDERR "Checked out HEAD:\n ",
1010 $gs->full_url, " r", $gs->last_rev, "\n";
1013 sub complete_svn_url {
1014 my ($url, $path) = @_;
1015 $path =~ s#/+$##;
1016 if ($path !~ m#^[a-z\+]+://#) {
1017 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1018 fatal("E: '$path' is not a complete URL ",
1019 "and a separate URL is not specified");
1021 return ($url, $path);
1023 return ($path, '');
1026 sub complete_url_ls_init {
1027 my ($ra, $repo_path, $switch, $pfx) = @_;
1028 unless ($repo_path) {
1029 print STDERR "W: $switch not specified\n";
1030 return;
1032 $repo_path =~ s#/+$##;
1033 if ($repo_path =~ m#^[a-z\+]+://#) {
1034 $ra = Git::SVN::Ra->new($repo_path);
1035 $repo_path = '';
1036 } else {
1037 $repo_path =~ s#^/+##;
1038 unless ($ra) {
1039 fatal("E: '$repo_path' is not a complete URL ",
1040 "and a separate URL is not specified");
1043 my $url = $ra->{url};
1044 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1045 my $k = "svn-remote.$gs->{repo_id}.url";
1046 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1047 if ($orig_url && ($orig_url ne $gs->{url})) {
1048 die "$k already set: $orig_url\n",
1049 "wanted to set to: $gs->{url}\n";
1051 command_oneline('config', $k, $gs->{url}) unless $orig_url;
1052 my $remote_path = "$ra->{svn_path}/$repo_path";
1053 $remote_path =~ s#/+#/#g;
1054 $remote_path =~ s#^/##g;
1055 $remote_path .= "/*" if $remote_path !~ /\*/;
1056 my ($n) = ($switch =~ /^--(\w+)/);
1057 if (length $pfx && $pfx !~ m#/$#) {
1058 die "--prefix='$pfx' must have a trailing slash '/'\n";
1060 command_noisy('config',
1061 "svn-remote.$gs->{repo_id}.$n",
1062 "$remote_path:refs/remotes/$pfx*" .
1063 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1066 sub verify_ref {
1067 my ($ref) = @_;
1068 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1069 { STDERR => 0 }); };
1072 sub get_tree_from_treeish {
1073 my ($treeish) = @_;
1074 # $treeish can be a symbolic ref, too:
1075 my $type = command_oneline(qw/cat-file -t/, $treeish);
1076 my $expected;
1077 while ($type eq 'tag') {
1078 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1080 if ($type eq 'commit') {
1081 $expected = (grep /^tree /, command(qw/cat-file commit/,
1082 $treeish))[0];
1083 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1084 die "Unable to get tree from $treeish\n" unless $expected;
1085 } elsif ($type eq 'tree') {
1086 $expected = $treeish;
1087 } else {
1088 die "$treeish is a $type, expected tree, tag or commit\n";
1090 return $expected;
1093 sub get_commit_entry {
1094 my ($treeish) = shift;
1095 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1096 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1097 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1098 open my $log_fh, '>', $commit_editmsg or croak $!;
1100 my $type = command_oneline(qw/cat-file -t/, $treeish);
1101 if ($type eq 'commit' || $type eq 'tag') {
1102 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1103 $type, $treeish);
1104 my $in_msg = 0;
1105 my $author;
1106 my $saw_from = 0;
1107 my $msgbuf = "";
1108 while (<$msg_fh>) {
1109 if (!$in_msg) {
1110 $in_msg = 1 if (/^\s*$/);
1111 $author = $1 if (/^author (.*>)/);
1112 } elsif (/^git-svn-id: /) {
1113 # skip this for now, we regenerate the
1114 # correct one on re-fetch anyways
1115 # TODO: set *:merge properties or like...
1116 } else {
1117 if (/^From:/ || /^Signed-off-by:/) {
1118 $saw_from = 1;
1120 $msgbuf .= $_;
1123 $msgbuf =~ s/\s+$//s;
1124 if ($Git::SVN::_add_author_from && defined($author)
1125 && !$saw_from) {
1126 $msgbuf .= "\n\nFrom: $author";
1128 print $log_fh $msgbuf or croak $!;
1129 command_close_pipe($msg_fh, $ctx);
1131 close $log_fh or croak $!;
1133 if ($_edit || ($type eq 'tree')) {
1134 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1135 # TODO: strip out spaces, comments, like git-commit.sh
1136 system($editor, $commit_editmsg);
1138 rename $commit_editmsg, $commit_msg or croak $!;
1140 # SVN requires messages to be UTF-8 when entering the repo
1141 local $/;
1142 open $log_fh, '<', $commit_msg or croak $!;
1143 binmode $log_fh;
1144 chomp($log_entry{log} = <$log_fh>);
1146 if (my $enc = Git::config('i18n.commitencoding')) {
1147 require Encode;
1148 Encode::from_to($log_entry{log}, $enc, 'UTF-8');
1150 close $log_fh or croak $!;
1152 unlink $commit_msg;
1153 \%log_entry;
1156 sub s_to_file {
1157 my ($str, $file, $mode) = @_;
1158 open my $fd,'>',$file or croak $!;
1159 print $fd $str,"\n" or croak $!;
1160 close $fd or croak $!;
1161 chmod ($mode &~ umask, $file) if (defined $mode);
1164 sub file_to_s {
1165 my $file = shift;
1166 open my $fd,'<',$file or croak "$!: file: $file\n";
1167 local $/;
1168 my $ret = <$fd>;
1169 close $fd or croak $!;
1170 $ret =~ s/\s*$//s;
1171 return $ret;
1174 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1175 sub load_authors {
1176 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1177 my $log = $cmd eq 'log';
1178 while (<$authors>) {
1179 chomp;
1180 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1181 my ($user, $name, $email) = ($1, $2, $3);
1182 if ($log) {
1183 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1184 } else {
1185 $users{$user} = [$name, $email];
1188 close $authors or croak $!;
1191 # convert GetOpt::Long specs for use by git-config
1192 sub read_repo_config {
1193 return unless -d $ENV{GIT_DIR};
1194 my $opts = shift;
1195 my @config_only;
1196 foreach my $o (keys %$opts) {
1197 # if we have mixedCase and a long option-only, then
1198 # it's a config-only variable that we don't need for
1199 # the command-line.
1200 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1201 my $v = $opts->{$o};
1202 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1203 $key =~ s/-//g;
1204 my $arg = 'git config';
1205 $arg .= ' --int' if ($o =~ /[:=]i$/);
1206 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1207 if (ref $v eq 'ARRAY') {
1208 chomp(my @tmp = `$arg --get-all svn.$key`);
1209 @$v = @tmp if @tmp;
1210 } else {
1211 chomp(my $tmp = `$arg --get svn.$key`);
1212 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1213 $$v = $tmp;
1217 delete @$opts{@config_only} if @config_only;
1220 sub extract_metadata {
1221 my $id = shift or return (undef, undef, undef);
1222 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1223 \s([a-f\d\-]+)$/x);
1224 if (!defined $rev || !$uuid || !$url) {
1225 # some of the original repositories I made had
1226 # identifiers like this:
1227 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
1229 return ($url, $rev, $uuid);
1232 sub cmt_metadata {
1233 return extract_metadata((grep(/^git-svn-id: /,
1234 command(qw/cat-file commit/, shift)))[-1]);
1237 sub working_head_info {
1238 my ($head, $refs) = @_;
1239 my @args = ('log', '--no-color', '--first-parent', '--pretty=medium');
1240 my ($fh, $ctx) = command_output_pipe(@args, $head);
1241 my $hash;
1242 my %max;
1243 while (<$fh>) {
1244 if ( m{^commit ($::sha1)$} ) {
1245 unshift @$refs, $hash if $hash and $refs;
1246 $hash = $1;
1247 next;
1249 next unless s{^\s*(git-svn-id:)}{$1};
1250 my ($url, $rev, $uuid) = extract_metadata($_);
1251 if (defined $url && defined $rev) {
1252 next if $max{$url} and $max{$url} < $rev;
1253 if (my $gs = Git::SVN->find_by_url($url)) {
1254 my $c = $gs->rev_map_get($rev, $uuid);
1255 if ($c && $c eq $hash) {
1256 close $fh; # break the pipe
1257 return ($url, $rev, $uuid, $gs);
1258 } else {
1259 $max{$url} ||= $gs->rev_map_max;
1264 command_close_pipe($fh, $ctx);
1265 (undef, undef, undef, undef);
1268 sub read_commit_parents {
1269 my ($parents, $c) = @_;
1270 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1271 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1272 @{$parents->{$c}} = split(/ /, $p);
1275 sub linearize_history {
1276 my ($gs, $refs) = @_;
1277 my %parents;
1278 foreach my $c (@$refs) {
1279 read_commit_parents(\%parents, $c);
1282 my @linear_refs;
1283 my %skip = ();
1284 my $last_svn_commit = $gs->last_commit;
1285 foreach my $c (reverse @$refs) {
1286 next if $c eq $last_svn_commit;
1287 last if $skip{$c};
1289 unshift @linear_refs, $c;
1290 $skip{$c} = 1;
1292 # we only want the first parent to diff against for linear
1293 # history, we save the rest to inject when we finalize the
1294 # svn commit
1295 my $fp_a = verify_ref("$c~1");
1296 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1297 if (!$fp_a || !$fp_b) {
1298 die "Commit $c\n",
1299 "has no parent commit, and therefore ",
1300 "nothing to diff against.\n",
1301 "You should be working from a repository ",
1302 "originally created by git-svn\n";
1304 if ($fp_a ne $fp_b) {
1305 die "$c~1 = $fp_a, however parsing commit $c ",
1306 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1309 foreach my $p (@{$parents{$c}}) {
1310 $skip{$p} = 1;
1313 (\@linear_refs, \%parents);
1316 sub find_file_type_and_diff_status {
1317 my ($path) = @_;
1318 return ('dir', '') if $path eq '';
1320 my $diff_output =
1321 command_oneline(qw(diff --cached --name-status --), $path) || "";
1322 my $diff_status = (split(' ', $diff_output))[0] || "";
1324 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1326 return (undef, undef) if !$diff_status && !$ls_tree;
1328 if ($diff_status eq "A") {
1329 return ("link", $diff_status) if -l $path;
1330 return ("dir", $diff_status) if -d $path;
1331 return ("file", $diff_status);
1334 my $mode = (split(' ', $ls_tree))[0] || "";
1336 return ("link", $diff_status) if $mode eq "120000";
1337 return ("dir", $diff_status) if $mode eq "040000";
1338 return ("file", $diff_status);
1341 sub md5sum {
1342 my $arg = shift;
1343 my $ref = ref $arg;
1344 my $md5 = Digest::MD5->new();
1345 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
1346 $md5->addfile($arg) or croak $!;
1347 } elsif ($ref eq 'SCALAR') {
1348 $md5->add($$arg) or croak $!;
1349 } elsif (!$ref) {
1350 $md5->add($arg) or croak $!;
1351 } else {
1352 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1354 return $md5->hexdigest();
1357 package Git::SVN;
1358 use strict;
1359 use warnings;
1360 use Fcntl qw/:DEFAULT :seek/;
1361 use constant rev_map_fmt => 'NH40';
1362 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1363 $_repack $_repack_flags $_use_svm_props $_head
1364 $_use_svnsync_props $no_reuse_existing $_minimize_url
1365 $_use_log_author $_add_author_from/;
1366 use Carp qw/croak/;
1367 use File::Path qw/mkpath/;
1368 use File::Copy qw/copy/;
1369 use IPC::Open3;
1371 my ($_gc_nr, $_gc_period);
1373 # properties that we do not log:
1374 my %SKIP_PROP;
1375 BEGIN {
1376 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1377 svn:special svn:executable
1378 svn:entry:committed-rev
1379 svn:entry:last-author
1380 svn:entry:uuid
1381 svn:entry:committed-date/;
1383 # some options are read globally, but can be overridden locally
1384 # per [svn-remote "..."] section. Command-line options will *NOT*
1385 # override options set in an [svn-remote "..."] section
1386 no strict 'refs';
1387 for my $option (qw/follow_parent no_metadata use_svm_props
1388 use_svnsync_props/) {
1389 my $key = $option;
1390 $key =~ tr/_//d;
1391 my $prop = "-$option";
1392 *$option = sub {
1393 my ($self) = @_;
1394 return $self->{$prop} if exists $self->{$prop};
1395 my $k = "svn-remote.$self->{repo_id}.$key";
1396 eval { command_oneline(qw/config --get/, $k) };
1397 if ($@) {
1398 $self->{$prop} = ${"Git::SVN::_$option"};
1399 } else {
1400 my $v = command_oneline(qw/config --bool/,$k);
1401 $self->{$prop} = $v eq 'false' ? 0 : 1;
1403 return $self->{$prop};
1409 my (%LOCKFILES, %INDEX_FILES);
1410 END {
1411 unlink keys %LOCKFILES if %LOCKFILES;
1412 unlink keys %INDEX_FILES if %INDEX_FILES;
1415 sub resolve_local_globs {
1416 my ($url, $fetch, $glob_spec) = @_;
1417 return unless defined $glob_spec;
1418 my $ref = $glob_spec->{ref};
1419 my $path = $glob_spec->{path};
1420 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
1421 next unless m#^refs/remotes/$ref->{regex}$#;
1422 my $p = $1;
1423 my $pathname = desanitize_refname($path->full_path($p));
1424 my $refname = desanitize_refname($ref->full_path($p));
1425 if (my $existing = $fetch->{$pathname}) {
1426 if ($existing ne $refname) {
1427 die "Refspec conflict:\n",
1428 "existing: refs/remotes/$existing\n",
1429 " globbed: refs/remotes/$refname\n";
1431 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
1432 $u =~ s!^\Q$url\E(/|$)!! or die
1433 "refs/remotes/$refname: '$url' not found in '$u'\n";
1434 if ($pathname ne $u) {
1435 warn "W: Refspec glob conflict ",
1436 "(ref: refs/remotes/$refname):\n",
1437 "expected path: $pathname\n",
1438 " real path: $u\n",
1439 "Continuing ahead with $u\n";
1440 next;
1442 } else {
1443 $fetch->{$pathname} = $refname;
1448 sub parse_revision_argument {
1449 my ($base, $head) = @_;
1450 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1451 return ($base, $head);
1453 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1454 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1455 return ($head, $head) if ($::_revision eq 'HEAD');
1456 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1457 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1458 die "revision argument: $::_revision not understood by git-svn\n";
1461 sub fetch_all {
1462 my ($repo_id, $remotes) = @_;
1463 if (ref $repo_id) {
1464 my $gs = $repo_id;
1465 $repo_id = undef;
1466 $repo_id = $gs->{repo_id};
1468 $remotes ||= read_all_remotes();
1469 my $remote = $remotes->{$repo_id} or
1470 die "[svn-remote \"$repo_id\"] unknown\n";
1471 my $fetch = $remote->{fetch};
1472 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1473 my (@gs, @globs);
1474 my $ra = Git::SVN::Ra->new($url);
1475 my $uuid = $ra->get_uuid;
1476 my $head = $ra->get_latest_revnum;
1477 my $base = defined $fetch ? $head : 0;
1479 # read the max revs for wildcard expansion (branches/*, tags/*)
1480 foreach my $t (qw/branches tags/) {
1481 defined $remote->{$t} or next;
1482 push @globs, $remote->{$t};
1483 my $max_rev = eval { tmp_config(qw/--int --get/,
1484 "svn-remote.$repo_id.${t}-maxRev") };
1485 if (defined $max_rev && ($max_rev < $base)) {
1486 $base = $max_rev;
1487 } elsif (!defined $max_rev) {
1488 $base = 0;
1492 if ($fetch) {
1493 foreach my $p (sort keys %$fetch) {
1494 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1495 my $lr = $gs->rev_map_max;
1496 if (defined $lr) {
1497 $base = $lr if ($lr < $base);
1499 push @gs, $gs;
1503 ($base, $head) = parse_revision_argument($base, $head);
1504 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1507 sub read_all_remotes {
1508 my $r = {};
1509 my $use_svm_props = eval { command_oneline(qw/config --bool
1510 svn.useSvmProps/) };
1511 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
1512 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1513 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*(.+)\s*$!) {
1514 my ($remote, $local_ref, $_remote_ref) = ($1, $2, $3);
1515 die("svn-remote.$remote: remote ref '$_remote_ref' "
1516 . "must start with 'refs/remotes/'\n")
1517 unless $_remote_ref =~ m{^refs/remotes/(.+)};
1518 my $remote_ref = $1;
1519 $local_ref =~ s{^/}{};
1520 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1521 $r->{$remote}->{svm} = {} if $use_svm_props;
1522 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
1523 $r->{$1}->{svm} = {};
1524 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1525 $r->{$1}->{url} = $2;
1526 } elsif (m!^(.+)\.(branches|tags)=
1527 (.*):refs/remotes/(.+)\s*$/!x) {
1528 my ($p, $g) = ($3, $4);
1529 my $rs = $r->{$1}->{$2} = {
1530 t => $2,
1531 remote => $1,
1532 path => Git::SVN::GlobSpec->new($p),
1533 ref => Git::SVN::GlobSpec->new($g) };
1534 if (length($rs->{ref}->{right}) != 0) {
1535 die "The '*' glob character must be the last ",
1536 "character of '$g'\n";
1541 map {
1542 if (defined $r->{$_}->{svm}) {
1543 my $svm;
1544 eval {
1545 my $section = "svn-remote.$_";
1546 $svm = {
1547 source => tmp_config('--get',
1548 "$section.svm-source"),
1549 replace => tmp_config('--get',
1550 "$section.svm-replace"),
1553 $r->{$_}->{svm} = $svm;
1555 } keys %$r;
1560 sub init_vars {
1561 $_gc_nr = $_gc_period = 1000;
1562 if (defined $_repack || defined $_repack_flags) {
1563 warn "Repack options are obsolete; they have no effect.\n";
1567 sub verify_remotes_sanity {
1568 return unless -d $ENV{GIT_DIR};
1569 my %seen;
1570 foreach (command(qw/config -l/)) {
1571 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1572 if ($seen{$1}) {
1573 die "Remote ref refs/remote/$1 is tracked by",
1574 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1575 "Please resolve this ambiguity in ",
1576 "your git configuration file before ",
1577 "continuing\n";
1579 $seen{$1} = $_;
1584 sub find_existing_remote {
1585 my ($url, $remotes) = @_;
1586 return undef if $no_reuse_existing;
1587 my $existing;
1588 foreach my $repo_id (keys %$remotes) {
1589 my $u = $remotes->{$repo_id}->{url} or next;
1590 next if $u ne $url;
1591 $existing = $repo_id;
1592 last;
1594 $existing;
1597 sub init_remote_config {
1598 my ($self, $url, $no_write) = @_;
1599 $url =~ s!/+$!!; # strip trailing slash
1600 my $r = read_all_remotes();
1601 my $existing = find_existing_remote($url, $r);
1602 if ($existing) {
1603 unless ($no_write) {
1604 print STDERR "Using existing ",
1605 "[svn-remote \"$existing\"]\n";
1607 $self->{repo_id} = $existing;
1608 } elsif ($_minimize_url) {
1609 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1610 $existing = find_existing_remote($min_url, $r);
1611 if ($existing) {
1612 unless ($no_write) {
1613 print STDERR "Using existing ",
1614 "[svn-remote \"$existing\"]\n";
1616 $self->{repo_id} = $existing;
1618 if ($min_url ne $url) {
1619 unless ($no_write) {
1620 print STDERR "Using higher level of URL: ",
1621 "$url => $min_url\n";
1623 my $old_path = $self->{path};
1624 $self->{path} = $url;
1625 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1626 if (length $old_path) {
1627 $self->{path} .= "/$old_path";
1629 $url = $min_url;
1632 my $orig_url;
1633 if (!$existing) {
1634 # verify that we aren't overwriting anything:
1635 $orig_url = eval {
1636 command_oneline('config', '--get',
1637 "svn-remote.$self->{repo_id}.url")
1639 if ($orig_url && ($orig_url ne $url)) {
1640 die "svn-remote.$self->{repo_id}.url already set: ",
1641 "$orig_url\nwanted to set to: $url\n";
1644 my ($xrepo_id, $xpath) = find_ref($self->refname);
1645 if (defined $xpath) {
1646 die "svn-remote.$xrepo_id.fetch already set to track ",
1647 "$xpath:refs/remotes/", $self->refname, "\n";
1649 unless ($no_write) {
1650 command_noisy('config',
1651 "svn-remote.$self->{repo_id}.url", $url);
1652 $self->{path} =~ s{^/}{};
1653 command_noisy('config', '--add',
1654 "svn-remote.$self->{repo_id}.fetch",
1655 "$self->{path}:".$self->refname);
1657 $self->{url} = $url;
1660 sub find_by_url { # repos_root and, path are optional
1661 my ($class, $full_url, $repos_root, $path) = @_;
1663 return undef unless defined $full_url;
1664 remove_username($full_url);
1665 remove_username($repos_root) if defined $repos_root;
1666 my $remotes = read_all_remotes();
1667 if (defined $full_url && defined $repos_root && !defined $path) {
1668 $path = $full_url;
1669 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1671 foreach my $repo_id (keys %$remotes) {
1672 my $u = $remotes->{$repo_id}->{url} or next;
1673 remove_username($u);
1674 next if defined $repos_root && $repos_root ne $u;
1676 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1677 foreach (qw/branches tags/) {
1678 resolve_local_globs($u, $fetch,
1679 $remotes->{$repo_id}->{$_});
1681 my $p = $path;
1682 my $rwr = rewrite_root({repo_id => $repo_id});
1683 my $svm = $remotes->{$repo_id}->{svm}
1684 if defined $remotes->{$repo_id}->{svm};
1685 unless (defined $p) {
1686 $p = $full_url;
1687 my $z = $u;
1688 my $prefix = '';
1689 if ($rwr) {
1690 $z = $rwr;
1691 } elsif (defined $svm) {
1692 $z = $svm->{source};
1693 $prefix = $svm->{replace};
1694 $prefix =~ s#^\Q$u\E(?:/|$)##;
1695 $prefix =~ s#/$##;
1697 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
1699 foreach my $f (keys %$fetch) {
1700 next if $f ne $p;
1701 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1704 undef;
1707 sub init {
1708 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1709 my $self = _new($class, $repo_id, $ref_id, $path);
1710 if (defined $url) {
1711 $self->init_remote_config($url, $no_write);
1713 $self;
1716 sub find_ref {
1717 my ($ref_id) = @_;
1718 foreach (command(qw/config -l/)) {
1719 next unless m!^svn-remote\.(.+)\.fetch=
1720 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1721 my ($repo_id, $path, $ref) = ($1, $2, $3);
1722 if ($ref eq $ref_id) {
1723 $path = '' if ($path =~ m#^\./?#);
1724 return ($repo_id, $path);
1727 (undef, undef, undef);
1730 sub new {
1731 my ($class, $ref_id, $repo_id, $path) = @_;
1732 if (defined $ref_id && !defined $repo_id && !defined $path) {
1733 ($repo_id, $path) = find_ref($ref_id);
1734 if (!defined $repo_id) {
1735 die "Could not find a \"svn-remote.*.fetch\" key ",
1736 "in the repository configuration matching: ",
1737 "refs/remotes/$ref_id\n";
1740 my $self = _new($class, $repo_id, $ref_id, $path);
1741 if (!defined $self->{path} || !length $self->{path}) {
1742 my $fetch = command_oneline('config', '--get',
1743 "svn-remote.$repo_id.fetch",
1744 ":refs/remotes/$ref_id\$") or
1745 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1746 "\":refs/remotes/$ref_id\$\" in config\n";
1747 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1749 $self->{url} = command_oneline('config', '--get',
1750 "svn-remote.$repo_id.url") or
1751 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1752 $self->rebuild;
1753 $self;
1756 sub refname {
1757 my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1759 # It cannot end with a slash /, we'll throw up on this because
1760 # SVN can't have directories with a slash in their name, either:
1761 if ($refname =~ m{/$}) {
1762 die "ref: '$refname' ends with a trailing slash, this is ",
1763 "not permitted by git nor Subversion\n";
1766 # It cannot have ASCII control character space, tilde ~, caret ^,
1767 # colon :, question-mark ?, asterisk *, space, or open bracket [
1768 # anywhere.
1770 # Additionally, % must be escaped because it is used for escaping
1771 # and we want our escaped refname to be reversible
1772 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1774 # no slash-separated component can begin with a dot .
1775 # /.* becomes /%2E*
1776 $refname =~ s{/\.}{/%2E}g;
1778 # It cannot have two consecutive dots .. anywhere
1779 # .. becomes %2E%2E
1780 $refname =~ s{\.\.}{%2E%2E}g;
1782 return $refname;
1785 sub desanitize_refname {
1786 my ($refname) = @_;
1787 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1788 return $refname;
1791 sub svm_uuid {
1792 my ($self) = @_;
1793 return $self->{svm}->{uuid} if $self->svm;
1794 $self->ra;
1795 unless ($self->{svm}) {
1796 die "SVM UUID not cached, and reading remotely failed\n";
1798 $self->{svm}->{uuid};
1801 sub svm {
1802 my ($self) = @_;
1803 return $self->{svm} if $self->{svm};
1804 my $svm;
1805 # see if we have it in our config, first:
1806 eval {
1807 my $section = "svn-remote.$self->{repo_id}";
1808 $svm = {
1809 source => tmp_config('--get', "$section.svm-source"),
1810 uuid => tmp_config('--get', "$section.svm-uuid"),
1811 replace => tmp_config('--get', "$section.svm-replace"),
1814 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1815 $self->{svm} = $svm;
1817 $self->{svm};
1820 sub _set_svm_vars {
1821 my ($self, $ra) = @_;
1822 return $ra if $self->svm;
1824 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1825 "(svm:source, svm:uuid) ",
1826 "from the following URLs:\n" );
1827 sub read_svm_props {
1828 my ($self, $ra, $path, $r) = @_;
1829 my $props = ($ra->get_dir($path, $r))[2];
1830 my $src = $props->{'svm:source'};
1831 my $uuid = $props->{'svm:uuid'};
1832 return undef if (!$src || !$uuid);
1834 chomp($src, $uuid);
1836 $uuid =~ m{^[0-9a-f\-]{30,}$}
1837 or die "doesn't look right - svm:uuid is '$uuid'\n";
1839 # the '!' is used to mark the repos_root!/relative/path
1840 $src =~ s{/?!/?}{/};
1841 $src =~ s{/+$}{}; # no trailing slashes please
1842 # username is of no interest
1843 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1845 my $replace = $ra->{url};
1846 $replace .= "/$path" if length $path;
1848 my $section = "svn-remote.$self->{repo_id}";
1849 tmp_config("$section.svm-source", $src);
1850 tmp_config("$section.svm-replace", $replace);
1851 tmp_config("$section.svm-uuid", $uuid);
1852 $self->{svm} = {
1853 source => $src,
1854 uuid => $uuid,
1855 replace => $replace
1859 my $r = $ra->get_latest_revnum;
1860 my $path = $self->{path};
1861 my %tried;
1862 while (length $path) {
1863 unless ($tried{"$self->{url}/$path"}) {
1864 return $ra if $self->read_svm_props($ra, $path, $r);
1865 $tried{"$self->{url}/$path"} = 1;
1867 $path =~ s#/?[^/]+$##;
1869 die "Path: '$path' should be ''\n" if $path ne '';
1870 return $ra if $self->read_svm_props($ra, $path, $r);
1871 $tried{"$self->{url}/$path"} = 1;
1873 if ($ra->{repos_root} eq $self->{url}) {
1874 die @err, (map { " $_\n" } keys %tried), "\n";
1877 # nope, make sure we're connected to the repository root:
1878 my $ok;
1879 my @tried_b;
1880 $path = $ra->{svn_path};
1881 $ra = Git::SVN::Ra->new($ra->{repos_root});
1882 while (length $path) {
1883 unless ($tried{"$ra->{url}/$path"}) {
1884 $ok = $self->read_svm_props($ra, $path, $r);
1885 last if $ok;
1886 $tried{"$ra->{url}/$path"} = 1;
1888 $path =~ s#/?[^/]+$##;
1890 die "Path: '$path' should be ''\n" if $path ne '';
1891 $ok ||= $self->read_svm_props($ra, $path, $r);
1892 $tried{"$ra->{url}/$path"} = 1;
1893 if (!$ok) {
1894 die @err, (map { " $_\n" } keys %tried), "\n";
1896 Git::SVN::Ra->new($self->{url});
1899 sub svnsync {
1900 my ($self) = @_;
1901 return $self->{svnsync} if $self->{svnsync};
1903 if ($self->no_metadata) {
1904 die "Can't have both 'noMetadata' and ",
1905 "'useSvnsyncProps' options set!\n";
1907 if ($self->rewrite_root) {
1908 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1909 "options set!\n";
1912 my $svnsync;
1913 # see if we have it in our config, first:
1914 eval {
1915 my $section = "svn-remote.$self->{repo_id}";
1917 my $url = tmp_config('--get', "$section.svnsync-url");
1918 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
1919 die "doesn't look right - svn:sync-from-url is '$url'\n";
1921 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
1922 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
1923 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1925 $svnsync = { url => $url, uuid => $uuid }
1927 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1928 return $self->{svnsync} = $svnsync;
1931 my $err = "useSvnsyncProps set, but failed to read " .
1932 "svnsync property: svn:sync-from-";
1933 my $rp = $self->ra->rev_proplist(0);
1935 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
1936 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
1937 die "doesn't look right - svn:sync-from-url is '$url'\n";
1939 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
1940 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
1941 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1943 my $section = "svn-remote.$self->{repo_id}";
1944 tmp_config('--add', "$section.svnsync-uuid", $uuid);
1945 tmp_config('--add', "$section.svnsync-url", $url);
1946 return $self->{svnsync} = { url => $url, uuid => $uuid };
1949 # this allows us to memoize our SVN::Ra UUID locally and avoid a
1950 # remote lookup (useful for 'git svn log').
1951 sub ra_uuid {
1952 my ($self) = @_;
1953 unless ($self->{ra_uuid}) {
1954 my $key = "svn-remote.$self->{repo_id}.uuid";
1955 my $uuid = eval { tmp_config('--get', $key) };
1956 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1957 $self->{ra_uuid} = $uuid;
1958 } else {
1959 die "ra_uuid called without URL\n" unless $self->{url};
1960 $self->{ra_uuid} = $self->ra->get_uuid;
1961 tmp_config('--add', $key, $self->{ra_uuid});
1964 $self->{ra_uuid};
1967 sub _set_repos_root {
1968 my ($self, $repos_root) = @_;
1969 my $k = "svn-remote.$self->{repo_id}.reposRoot";
1970 $repos_root ||= $self->ra->{repos_root};
1971 tmp_config($k, $repos_root);
1972 $repos_root;
1975 sub repos_root {
1976 my ($self) = @_;
1977 my $k = "svn-remote.$self->{repo_id}.reposRoot";
1978 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
1981 sub ra {
1982 my ($self) = shift;
1983 my $ra = Git::SVN::Ra->new($self->{url});
1984 $self->_set_repos_root($ra->{repos_root});
1985 if ($self->use_svm_props && !$self->{svm}) {
1986 if ($self->no_metadata) {
1987 die "Can't have both 'noMetadata' and ",
1988 "'useSvmProps' options set!\n";
1989 } elsif ($self->use_svnsync_props) {
1990 die "Can't have both 'useSvnsyncProps' and ",
1991 "'useSvmProps' options set!\n";
1993 $ra = $self->_set_svm_vars($ra);
1994 $self->{-want_revprops} = 1;
1996 $ra;
1999 sub rel_path {
2000 my ($self) = @_;
2001 my $repos_root = $self->ra->{repos_root};
2002 return $self->{path} if ($self->{url} eq $repos_root);
2003 my $url = $self->{url} .
2004 (length $self->{path} ? "/$self->{path}" : $self->{path});
2005 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
2006 $url;
2009 # prop_walk(PATH, REV, SUB)
2010 # -------------------------
2011 # Recursively traverse PATH at revision REV and invoke SUB for each
2012 # directory that contains a SVN property. SUB will be invoked as
2013 # follows: &SUB(gs, path, props); where `gs' is this instance of
2014 # Git::SVN, `path' the path to the directory where the properties
2015 # `props' were found. The `path' will be relative to point of checkout,
2016 # that is, if url://repo/trunk is the current Git branch, and that
2017 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
2018 # as `path' (note the trailing `/').
2019 sub prop_walk {
2020 my ($self, $path, $rev, $sub) = @_;
2022 $path =~ s#^/##;
2023 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2024 $path =~ s#^/*#/#g;
2025 my $p = $path;
2026 # Strip the irrelevant part of the path.
2027 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2028 # Ensure the path is terminated by a `/'.
2029 $p =~ s#/*$#/#;
2031 # The properties contain all the internal SVN stuff nobody
2032 # (usually) cares about.
2033 my $interesting_props = 0;
2034 foreach (keys %{$props}) {
2035 # If it doesn't start with `svn:', it must be a
2036 # user-defined property.
2037 ++$interesting_props and next if $_ !~ /^svn:/;
2038 # FIXME: Fragile, if SVN adds new public properties,
2039 # this needs to be updated.
2040 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2041 |eol-style|mime-type
2042 |externals|needs-lock)$/x;
2044 &$sub($self, $p, $props) if $interesting_props;
2046 foreach (sort keys %$dirent) {
2047 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
2048 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
2052 sub last_rev { ($_[0]->last_rev_commit)[0] }
2053 sub last_commit { ($_[0]->last_rev_commit)[1] }
2055 # returns the newest SVN revision number and newest commit SHA1
2056 sub last_rev_commit {
2057 my ($self) = @_;
2058 if (defined $self->{last_rev} && defined $self->{last_commit}) {
2059 return ($self->{last_rev}, $self->{last_commit});
2061 my $c = ::verify_ref($self->refname.'^0');
2062 if ($c && !$self->use_svm_props && !$self->no_metadata) {
2063 my $rev = (::cmt_metadata($c))[1];
2064 if (defined $rev) {
2065 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2066 return ($rev, $c);
2069 my $map_path = $self->map_path;
2070 unless (-e $map_path) {
2071 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2072 return (undef, undef);
2074 my ($rev, $commit) = $self->rev_map_max(1);
2075 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2076 return ($rev, $commit);
2079 sub get_fetch_range {
2080 my ($self, $min, $max) = @_;
2081 $max ||= $self->ra->get_latest_revnum;
2082 $min ||= $self->rev_map_max;
2083 (++$min, $max);
2086 sub tmp_config {
2087 my (@args) = @_;
2088 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2089 my $config = "$ENV{GIT_DIR}/svn/.metadata";
2090 if (! -f $config && -f $old_def_config) {
2091 rename $old_def_config, $config or
2092 die "Failed rename $old_def_config => $config: $!\n";
2094 my $old_config = $ENV{GIT_CONFIG};
2095 $ENV{GIT_CONFIG} = $config;
2096 $@ = undef;
2097 my @ret = eval {
2098 unless (-f $config) {
2099 mkfile($config);
2100 open my $fh, '>', $config or
2101 die "Can't open $config: $!\n";
2102 print $fh "; This file is used internally by ",
2103 "git-svn\n" or die
2104 "Couldn't write to $config: $!\n";
2105 print $fh "; You should not have to edit it\n" or
2106 die "Couldn't write to $config: $!\n";
2107 close $fh or die "Couldn't close $config: $!\n";
2109 command('config', @args);
2111 my $err = $@;
2112 if (defined $old_config) {
2113 $ENV{GIT_CONFIG} = $old_config;
2114 } else {
2115 delete $ENV{GIT_CONFIG};
2117 die $err if $err;
2118 wantarray ? @ret : $ret[0];
2121 sub tmp_index_do {
2122 my ($self, $sub) = @_;
2123 my $old_index = $ENV{GIT_INDEX_FILE};
2124 $ENV{GIT_INDEX_FILE} = $self->{index};
2125 $@ = undef;
2126 my @ret = eval {
2127 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2128 mkpath([$dir]) unless -d $dir;
2129 &$sub;
2131 my $err = $@;
2132 if (defined $old_index) {
2133 $ENV{GIT_INDEX_FILE} = $old_index;
2134 } else {
2135 delete $ENV{GIT_INDEX_FILE};
2137 die $err if $err;
2138 wantarray ? @ret : $ret[0];
2141 sub assert_index_clean {
2142 my ($self, $treeish) = @_;
2144 $self->tmp_index_do(sub {
2145 command_noisy('read-tree', $treeish) unless -e $self->{index};
2146 my $x = command_oneline('write-tree');
2147 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2148 /^tree ($::sha1)/mo);
2149 return if $y eq $x;
2151 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2152 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2153 command_noisy('read-tree', $treeish);
2154 $x = command_oneline('write-tree');
2155 if ($y ne $x) {
2156 ::fatal "trees ($treeish) $y != $x\n",
2157 "Something is seriously wrong...";
2162 sub get_commit_parents {
2163 my ($self, $log_entry) = @_;
2164 my (%seen, @ret, @tmp);
2165 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2166 if (my $ip = $self->{inject_parents}) {
2167 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2168 push @tmp, $commit;
2171 if (my $cur = ::verify_ref($self->refname.'^0')) {
2172 push @tmp, $cur;
2174 if (my $ipd = $self->{inject_parents_dcommit}) {
2175 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2176 push @tmp, @$commit;
2179 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2180 while (my $p = shift @tmp) {
2181 next if $seen{$p};
2182 $seen{$p} = 1;
2183 push @ret, $p;
2184 # MAXPARENT is defined to 16 in commit-tree.c:
2185 last if @ret >= 16;
2187 if (@tmp) {
2188 die "r$log_entry->{revision}: No room for parents:\n\t",
2189 join("\n\t", @tmp), "\n";
2191 @ret;
2194 sub rewrite_root {
2195 my ($self) = @_;
2196 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2197 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2198 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2199 if ($rwr) {
2200 $rwr =~ s#/+$##;
2201 if ($rwr !~ m#^[a-z\+]+://#) {
2202 die "$rwr is not a valid URL (key: $k)\n";
2205 $self->{-rewrite_root} = $rwr;
2208 sub metadata_url {
2209 my ($self) = @_;
2210 ($self->rewrite_root || $self->{url}) .
2211 (length $self->{path} ? '/' . $self->{path} : '');
2214 sub full_url {
2215 my ($self) = @_;
2216 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2220 sub set_commit_header_env {
2221 my ($log_entry) = @_;
2222 my %env;
2223 foreach my $ned (qw/NAME EMAIL DATE/) {
2224 foreach my $ac (qw/AUTHOR COMMITTER/) {
2225 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2229 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2230 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2231 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2233 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2234 ? $log_entry->{commit_name}
2235 : $log_entry->{name};
2236 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2237 ? $log_entry->{commit_email}
2238 : $log_entry->{email};
2239 \%env;
2242 sub restore_commit_header_env {
2243 my ($env) = @_;
2244 foreach my $ned (qw/NAME EMAIL DATE/) {
2245 foreach my $ac (qw/AUTHOR COMMITTER/) {
2246 my $k = "GIT_${ac}_${ned}";
2247 if (defined $env->{$k}) {
2248 $ENV{$k} = $env->{$k};
2249 } else {
2250 delete $ENV{$k};
2256 sub gc {
2257 command_noisy('gc', '--auto');
2260 sub do_git_commit {
2261 my ($self, $log_entry) = @_;
2262 my $lr = $self->last_rev;
2263 if (defined $lr && $lr >= $log_entry->{revision}) {
2264 die "Last fetched revision of ", $self->refname,
2265 " was r$lr, but we are about to fetch: ",
2266 "r$log_entry->{revision}!\n";
2268 if (my $c = $self->rev_map_get($log_entry->{revision})) {
2269 croak "$log_entry->{revision} = $c already exists! ",
2270 "Why are we refetching it?\n";
2272 my $old_env = set_commit_header_env($log_entry);
2273 my $tree = $log_entry->{tree};
2274 if (!defined $tree) {
2275 $tree = $self->tmp_index_do(sub {
2276 command_oneline('write-tree') });
2278 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2280 my @exec = ('git', 'commit-tree', $tree);
2281 foreach ($self->get_commit_parents($log_entry)) {
2282 push @exec, '-p', $_;
2284 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2285 or croak $!;
2286 binmode $msg_fh;
2288 # we always get UTF-8 from SVN, but we may want our commits in
2289 # a different encoding.
2290 if (my $enc = Git::config('i18n.commitencoding')) {
2291 require Encode;
2292 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
2294 print $msg_fh $log_entry->{log} or croak $!;
2295 restore_commit_header_env($old_env);
2296 unless ($self->no_metadata) {
2297 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2298 or croak $!;
2300 $msg_fh->flush == 0 or croak $!;
2301 close $msg_fh or croak $!;
2302 chomp(my $commit = do { local $/; <$out_fh> });
2303 close $out_fh or croak $!;
2304 waitpid $pid, 0;
2305 croak $? if $?;
2306 if ($commit !~ /^$::sha1$/o) {
2307 die "Failed to commit, invalid sha1: $commit\n";
2310 $self->rev_map_set($log_entry->{revision}, $commit, 1);
2312 $self->{last_rev} = $log_entry->{revision};
2313 $self->{last_commit} = $commit;
2314 print "r$log_entry->{revision}";
2315 if (defined $log_entry->{svm_revision}) {
2316 print " (\@$log_entry->{svm_revision})";
2317 $self->rev_map_set($log_entry->{svm_revision}, $commit,
2318 0, $self->svm_uuid);
2320 print " = $commit ($self->{ref_id})\n";
2321 if (--$_gc_nr == 0) {
2322 $_gc_nr = $_gc_period;
2323 gc();
2325 return $commit;
2328 sub match_paths {
2329 my ($self, $paths, $r) = @_;
2330 return 1 if $self->{path} eq '';
2331 if (my $path = $paths->{"/$self->{path}"}) {
2332 return ($path->{action} eq 'D') ? 0 : 1;
2334 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
2335 if (grep /$self->{path_regex}/, keys %$paths) {
2336 return 1;
2338 my $c = '';
2339 foreach (split m#/#, $self->{path}) {
2340 $c .= "/$_";
2341 next unless ($paths->{$c} &&
2342 ($paths->{$c}->{action} =~ /^[AR]$/));
2343 if ($self->ra->check_path($self->{path}, $r) ==
2344 $SVN::Node::dir) {
2345 return 1;
2348 return 0;
2351 sub find_parent_branch {
2352 my ($self, $paths, $rev) = @_;
2353 return undef unless $self->follow_parent;
2354 unless (defined $paths) {
2355 my $err_handler = $SVN::Error::handler;
2356 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2357 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
2358 $paths =
2359 Git::SVN::Ra::dup_changed_paths($_[0]) });
2360 $SVN::Error::handler = $err_handler;
2362 return undef unless defined $paths;
2364 # look for a parent from another branch:
2365 my @b_path_components = split m#/#, $self->rel_path;
2366 my @a_path_components;
2367 my $i;
2368 while (@b_path_components) {
2369 $i = $paths->{'/'.join('/', @b_path_components)};
2370 last if $i && defined $i->{copyfrom_path};
2371 unshift(@a_path_components, pop(@b_path_components));
2373 return undef unless defined $i && defined $i->{copyfrom_path};
2374 my $branch_from = $i->{copyfrom_path};
2375 if (@a_path_components) {
2376 print STDERR "branch_from: $branch_from => ";
2377 $branch_from .= '/'.join('/', @a_path_components);
2378 print STDERR $branch_from, "\n";
2380 my $r = $i->{copyfrom_rev};
2381 my $repos_root = $self->ra->{repos_root};
2382 my $url = $self->ra->{url};
2383 my $new_url = $repos_root . $branch_from;
2384 print STDERR "Found possible branch point: ",
2385 "$new_url => ", $self->full_url, ", $r\n";
2386 $branch_from =~ s#^/##;
2387 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
2388 unless ($gs) {
2389 my $ref_id = $self->{ref_id};
2390 $ref_id =~ s/\@\d+$//;
2391 $ref_id .= "\@$r";
2392 # just grow a tail if we're not unique enough :x
2393 $ref_id .= '-' while find_ref($ref_id);
2394 print STDERR "Initializing parent: $ref_id\n";
2395 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
2396 if ($u =~ s#^\Q$url\E(/|$)##) {
2397 $p = $u;
2398 $u = $url;
2399 $repo_id = $self->{repo_id};
2401 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
2403 my ($r0, $parent) = $gs->find_rev_before($r, 1);
2404 if (!defined $r0 || !defined $parent) {
2405 my ($base, $head) = parse_revision_argument(0, $r);
2406 if ($base <= $r) {
2407 $gs->fetch($base, $r);
2409 ($r0, $parent) = $gs->last_rev_commit;
2411 if (defined $r0 && defined $parent) {
2412 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
2413 my $ed;
2414 if ($self->ra->can_do_switch) {
2415 $self->assert_index_clean($parent);
2416 print STDERR "Following parent with do_switch\n";
2417 # do_switch works with svn/trunk >= r22312, but that
2418 # is not included with SVN 1.4.3 (the latest version
2419 # at the moment), so we can't rely on it
2420 $self->{last_commit} = $parent;
2421 $ed = SVN::Git::Fetcher->new($self);
2422 $gs->ra->gs_do_switch($r0, $rev, $gs,
2423 $self->full_url, $ed)
2424 or die "SVN connection failed somewhere...\n";
2425 } elsif ($self->ra->trees_match($new_url, $r0,
2426 $self->full_url, $rev)) {
2427 print STDERR "Trees match:\n",
2428 " $new_url\@$r0\n",
2429 " ${\$self->full_url}\@$rev\n",
2430 "Following parent with no changes\n";
2431 $self->tmp_index_do(sub {
2432 command_noisy('read-tree', $parent);
2434 $self->{last_commit} = $parent;
2435 } else {
2436 print STDERR "Following parent with do_update\n";
2437 $ed = SVN::Git::Fetcher->new($self);
2438 $self->ra->gs_do_update($rev, $rev, $self, $ed)
2439 or die "SVN connection failed somewhere...\n";
2441 print STDERR "Successfully followed parent\n";
2442 return $self->make_log_entry($rev, [$parent], $ed);
2444 return undef;
2447 sub do_fetch {
2448 my ($self, $paths, $rev) = @_;
2449 my $ed;
2450 my ($last_rev, @parents);
2451 if (my $lc = $self->last_commit) {
2452 # we can have a branch that was deleted, then re-added
2453 # under the same name but copied from another path, in
2454 # which case we'll have multiple parents (we don't
2455 # want to break the original ref, nor lose copypath info):
2456 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2457 push @{$log_entry->{parents}}, $lc;
2458 return $log_entry;
2460 $ed = SVN::Git::Fetcher->new($self);
2461 $last_rev = $self->{last_rev};
2462 $ed->{c} = $lc;
2463 @parents = ($lc);
2464 } else {
2465 $last_rev = $rev;
2466 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2467 return $log_entry;
2469 $ed = SVN::Git::Fetcher->new($self);
2471 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2472 die "SVN connection failed somewhere...\n";
2474 $self->make_log_entry($rev, \@parents, $ed);
2477 sub get_untracked {
2478 my ($self, $ed) = @_;
2479 my @out;
2480 my $h = $ed->{empty};
2481 foreach (sort keys %$h) {
2482 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2483 push @out, " $act: " . uri_encode($_);
2484 warn "W: $act: $_\n";
2486 foreach my $t (qw/dir_prop file_prop/) {
2487 $h = $ed->{$t} or next;
2488 foreach my $path (sort keys %$h) {
2489 my $ppath = $path eq '' ? '.' : $path;
2490 foreach my $prop (sort keys %{$h->{$path}}) {
2491 next if $SKIP_PROP{$prop};
2492 my $v = $h->{$path}->{$prop};
2493 my $t_ppath_prop = "$t: " .
2494 uri_encode($ppath) . ' ' .
2495 uri_encode($prop);
2496 if (defined $v) {
2497 push @out, " +$t_ppath_prop " .
2498 uri_encode($v);
2499 } else {
2500 push @out, " -$t_ppath_prop";
2505 foreach my $t (qw/absent_file absent_directory/) {
2506 $h = $ed->{$t} or next;
2507 foreach my $parent (sort keys %$h) {
2508 foreach my $path (sort @{$h->{$parent}}) {
2509 push @out, " $t: " .
2510 uri_encode("$parent/$path");
2511 warn "W: $t: $parent/$path ",
2512 "Insufficient permissions?\n";
2516 \@out;
2519 sub parse_svn_date {
2520 my $date = shift || return '+0000 1970-01-01 00:00:00';
2521 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2522 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
2523 croak "Unable to parse date: $date\n";
2524 "+0000 $Y-$m-$d $H:$M:$S";
2527 sub check_author {
2528 my ($author) = @_;
2529 if (!defined $author || length $author == 0) {
2530 $author = '(no author)';
2531 } elsif (defined $::_authors && ! defined $::users{$author}) {
2532 die "Author: $author not defined in $::_authors file\n";
2534 $author;
2537 sub make_log_entry {
2538 my ($self, $rev, $parents, $ed) = @_;
2539 my $untracked = $self->get_untracked($ed);
2541 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
2542 print $un "r$rev\n" or croak $!;
2543 print $un $_, "\n" foreach @$untracked;
2544 my %log_entry = ( parents => $parents || [], revision => $rev,
2545 log => '');
2547 my $headrev;
2548 my $logged = delete $self->{logged_rev_props};
2549 if (!$logged || $self->{-want_revprops}) {
2550 my $rp = $self->ra->rev_proplist($rev);
2551 foreach (sort keys %$rp) {
2552 my $v = $rp->{$_};
2553 if (/^svn:(author|date|log)$/) {
2554 $log_entry{$1} = $v;
2555 } elsif ($_ eq 'svm:headrev') {
2556 $headrev = $v;
2557 } else {
2558 print $un " rev_prop: ", uri_encode($_), ' ',
2559 uri_encode($v), "\n";
2562 } else {
2563 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
2565 close $un or croak $!;
2567 $log_entry{date} = parse_svn_date($log_entry{date});
2568 $log_entry{log} .= "\n";
2569 my $author = $log_entry{author} = check_author($log_entry{author});
2570 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
2571 : ($author, undef);
2573 my ($commit_name, $commit_email) = ($name, $email);
2574 if ($_use_log_author) {
2575 my $name_field;
2576 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
2577 $name_field = $1;
2578 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
2579 $name_field = $1;
2581 if (!defined $name_field) {
2582 if (!defined $email) {
2583 $email = $name;
2585 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
2586 ($name, $email) = ($1, $2);
2587 } elsif ($name_field =~ /(.*)@/) {
2588 ($name, $email) = ($1, $name_field);
2589 } else {
2590 ($name, $email) = ($name_field, $name_field);
2593 if (defined $headrev && $self->use_svm_props) {
2594 if ($self->rewrite_root) {
2595 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2596 "options set!\n";
2598 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
2599 # we don't want "SVM: initializing mirror for junk" ...
2600 return undef if $r == 0;
2601 my $svm = $self->svm;
2602 if ($uuid ne $svm->{uuid}) {
2603 die "UUID mismatch on SVM path:\n",
2604 "expected: $svm->{uuid}\n",
2605 " got: $uuid\n";
2607 my $full_url = $self->full_url;
2608 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2609 die "Failed to replace '$svm->{replace}' with ",
2610 "'$svm->{source}' in $full_url\n";
2611 # throw away username for storing in records
2612 remove_username($full_url);
2613 $log_entry{metadata} = "$full_url\@$r $uuid";
2614 $log_entry{svm_revision} = $r;
2615 $email ||= "$author\@$uuid";
2616 $commit_email ||= "$author\@$uuid";
2617 } elsif ($self->use_svnsync_props) {
2618 my $full_url = $self->svnsync->{url};
2619 $full_url .= "/$self->{path}" if length $self->{path};
2620 remove_username($full_url);
2621 my $uuid = $self->svnsync->{uuid};
2622 $log_entry{metadata} = "$full_url\@$rev $uuid";
2623 $email ||= "$author\@$uuid";
2624 $commit_email ||= "$author\@$uuid";
2625 } else {
2626 my $url = $self->metadata_url;
2627 remove_username($url);
2628 $log_entry{metadata} = "$url\@$rev " .
2629 $self->ra->get_uuid;
2630 $email ||= "$author\@" . $self->ra->get_uuid;
2631 $commit_email ||= "$author\@" . $self->ra->get_uuid;
2633 $log_entry{name} = $name;
2634 $log_entry{email} = $email;
2635 $log_entry{commit_name} = $commit_name;
2636 $log_entry{commit_email} = $commit_email;
2637 \%log_entry;
2640 sub fetch {
2641 my ($self, $min_rev, $max_rev, @parents) = @_;
2642 my ($last_rev, $last_commit) = $self->last_rev_commit;
2643 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2644 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2647 sub set_tree_cb {
2648 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2649 $self->{inject_parents} = { $rev => $tree };
2650 $self->fetch(undef, undef);
2653 sub set_tree {
2654 my ($self, $tree) = (shift, shift);
2655 my $log_entry = ::get_commit_entry($tree);
2656 unless ($self->{last_rev}) {
2657 ::fatal("Must have an existing revision to commit");
2659 my %ed_opts = ( r => $self->{last_rev},
2660 log => $log_entry->{log},
2661 ra => $self->ra,
2662 tree_a => $self->{last_commit},
2663 tree_b => $tree,
2664 editor_cb => sub {
2665 $self->set_tree_cb($log_entry, $tree, @_) },
2666 svn_path => $self->{path} );
2667 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2668 print "No changes\nr$self->{last_rev} = $tree\n";
2672 sub rebuild_from_rev_db {
2673 my ($self, $path) = @_;
2674 my $r = -1;
2675 open my $fh, '<', $path or croak "open: $!";
2676 binmode $fh or croak "binmode: $!";
2677 while (<$fh>) {
2678 length($_) == 41 or croak "inconsistent size in ($_) != 41";
2679 chomp($_);
2680 ++$r;
2681 next if $_ eq ('0' x 40);
2682 $self->rev_map_set($r, $_);
2683 print "r$r = $_\n";
2685 close $fh or croak "close: $!";
2686 unlink $path or croak "unlink: $!";
2689 sub rebuild {
2690 my ($self) = @_;
2691 my $map_path = $self->map_path;
2692 my $partial = (-e $map_path && ! -z $map_path);
2693 return unless ::verify_ref($self->refname.'^0');
2694 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
2695 my $rev_db = $self->rev_db_path;
2696 $self->rebuild_from_rev_db($rev_db);
2697 if ($self->use_svm_props) {
2698 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
2699 $self->rebuild_from_rev_db($svm_rev_db);
2701 $self->unlink_rev_db_symlink;
2702 return;
2704 print "Rebuilding $map_path ...\n" if (!$partial);
2705 my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
2706 (undef, undef));
2707 my ($log, $ctx) =
2708 command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
2709 ($head ? "$head.." : "") . $self->refname,
2710 '--');
2711 my $metadata_url = $self->metadata_url;
2712 remove_username($metadata_url);
2713 my $svn_uuid = $self->ra_uuid;
2714 my $c;
2715 while (<$log>) {
2716 if ( m{^commit ($::sha1)$} ) {
2717 $c = $1;
2718 next;
2720 next unless s{^\s*(git-svn-id:)}{$1};
2721 my ($url, $rev, $uuid) = ::extract_metadata($_);
2722 remove_username($url);
2724 # ignore merges (from set-tree)
2725 next if (!defined $rev || !$uuid);
2727 # if we merged or otherwise started elsewhere, this is
2728 # how we break out of it
2729 if (($uuid ne $svn_uuid) ||
2730 ($metadata_url && $url && ($url ne $metadata_url))) {
2731 next;
2733 if ($partial && $head) {
2734 print "Partial-rebuilding $map_path ...\n";
2735 print "Currently at $base_rev = $head\n";
2736 $head = undef;
2739 $self->rev_map_set($rev, $c);
2740 print "r$rev = $c\n";
2742 command_close_pipe($log, $ctx);
2743 print "Done rebuilding $map_path\n" if (!$partial || !$head);
2744 my $rev_db_path = $self->rev_db_path;
2745 if (-f $self->rev_db_path) {
2746 unlink $self->rev_db_path or croak "unlink: $!";
2748 $self->unlink_rev_db_symlink;
2751 # rev_map:
2752 # Tie::File seems to be prone to offset errors if revisions get sparse,
2753 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2754 # one of my favorite modules is out :< Next up would be one of the DBM
2755 # modules, but I'm not sure which is most portable...
2757 # This is the replacement for the rev_db format, which was too big
2758 # and inefficient for large repositories with a lot of sparse history
2759 # (mainly tags)
2761 # The format is this:
2762 # - 24 bytes for every record,
2763 # * 4 bytes for the integer representing an SVN revision number
2764 # * 20 bytes representing the sha1 of a git commit
2765 # - No empty padding records like the old format
2766 # (except the last record, which can be overwritten)
2767 # - new records are written append-only since SVN revision numbers
2768 # increase monotonically
2769 # - lookups on SVN revision number are done via a binary search
2770 # - Piping the file to xxd -c24 is a good way of dumping it for
2771 # viewing or editing (piped back through xxd -r), should the need
2772 # ever arise.
2773 # - The last record can be padding revision with an all-zero sha1
2774 # This is used to optimize fetch performance when using multiple
2775 # "fetch" directives in .git/config
2777 # These files are disposable unless noMetadata or useSvmProps is set
2779 sub _rev_map_set {
2780 my ($fh, $rev, $commit) = @_;
2782 binmode $fh or croak "binmode: $!";
2783 my $size = (stat($fh))[7];
2784 ($size % 24) == 0 or croak "inconsistent size: $size";
2786 my $wr_offset = 0;
2787 if ($size > 0) {
2788 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2789 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
2790 $read == 24 or croak "read only $read bytes (!= 24)";
2791 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
2792 if ($last_commit eq ('0' x40)) {
2793 if ($size >= 48) {
2794 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2795 $read = sysread($fh, $buf, 24) or
2796 croak "read: $!";
2797 $read == 24 or
2798 croak "read only $read bytes (!= 24)";
2799 ($last_rev, $last_commit) =
2800 unpack(rev_map_fmt, $buf);
2801 if ($last_commit eq ('0' x40)) {
2802 croak "inconsistent .rev_map\n";
2805 if ($last_rev >= $rev) {
2806 croak "last_rev is higher!: $last_rev >= $rev";
2808 $wr_offset = -24;
2811 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
2812 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
2813 croak "write: $!";
2816 sub mkfile {
2817 my ($path) = @_;
2818 unless (-e $path) {
2819 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2820 mkpath([$dir]) unless -d $dir;
2821 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2822 close $fh or die "Couldn't close (create) $path: $!\n";
2826 sub rev_map_set {
2827 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2828 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2829 my $db = $self->map_path($uuid);
2830 my $db_lock = "$db.lock";
2831 my $sig;
2832 if ($update_ref) {
2833 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2834 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2836 mkfile($db);
2838 $LOCKFILES{$db_lock} = 1;
2839 my $sync;
2840 # both of these options make our .rev_db file very, very important
2841 # and we can't afford to lose it because rebuild() won't work
2842 if ($self->use_svm_props || $self->no_metadata) {
2843 $sync = 1;
2844 copy($db, $db_lock) or die "rev_map_set(@_): ",
2845 "Failed to copy: ",
2846 "$db => $db_lock ($!)\n";
2847 } else {
2848 rename $db, $db_lock or die "rev_map_set(@_): ",
2849 "Failed to rename: ",
2850 "$db => $db_lock ($!)\n";
2853 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
2854 or croak "Couldn't open $db_lock: $!\n";
2855 _rev_map_set($fh, $rev, $commit);
2856 if ($sync) {
2857 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2858 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2860 close $fh or croak $!;
2861 if ($update_ref) {
2862 $_head = $self;
2863 command_noisy('update-ref', '-m', "r$rev",
2864 $self->refname, $commit);
2866 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
2867 "$db_lock => $db ($!)\n";
2868 delete $LOCKFILES{$db_lock};
2869 if ($update_ref) {
2870 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2871 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
2872 kill $sig, $$ if defined $sig;
2876 # If want_commit, this will return an array of (rev, commit) where
2877 # commit _must_ be a valid commit in the archive.
2878 # Otherwise, it'll return the max revision (whether or not the
2879 # commit is valid or just a 0x40 placeholder).
2880 sub rev_map_max {
2881 my ($self, $want_commit) = @_;
2882 $self->rebuild;
2883 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
2884 $want_commit ? ($r, $c) : $r;
2887 sub rev_map_max_norebuild {
2888 my ($self, $want_commit) = @_;
2889 my $map_path = $self->map_path;
2890 stat $map_path or return $want_commit ? (0, undef) : 0;
2891 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
2892 binmode $fh or croak "binmode: $!";
2893 my $size = (stat($fh))[7];
2894 ($size % 24) == 0 or croak "inconsistent size: $size";
2896 if ($size == 0) {
2897 close $fh or croak "close: $!";
2898 return $want_commit ? (0, undef) : 0;
2901 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2902 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
2903 my ($r, $c) = unpack(rev_map_fmt, $buf);
2904 if ($want_commit && $c eq ('0' x40)) {
2905 if ($size < 48) {
2906 return $want_commit ? (0, undef) : 0;
2908 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2909 sysread($fh, $buf, 24) == 24 or croak "read: $!";
2910 ($r, $c) = unpack(rev_map_fmt, $buf);
2911 if ($c eq ('0'x40)) {
2912 croak "Penultimate record is all-zeroes in $map_path";
2915 close $fh or croak "close: $!";
2916 $want_commit ? ($r, $c) : $r;
2919 sub rev_map_get {
2920 my ($self, $rev, $uuid) = @_;
2921 my $map_path = $self->map_path($uuid);
2922 return undef unless -e $map_path;
2924 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
2925 binmode $fh or croak "binmode: $!";
2926 my $size = (stat($fh))[7];
2927 ($size % 24) == 0 or croak "inconsistent size: $size";
2929 if ($size == 0) {
2930 close $fh or croak "close: $fh";
2931 return undef;
2934 my ($l, $u) = (0, $size - 24);
2935 my ($r, $c, $buf);
2937 while ($l <= $u) {
2938 my $i = int(($l/24 + $u/24) / 2) * 24;
2939 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
2940 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
2941 my ($r, $c) = unpack('NH40', $buf);
2943 if ($r < $rev) {
2944 $l = $i + 24;
2945 } elsif ($r > $rev) {
2946 $u = $i - 24;
2947 } else { # $r == $rev
2948 close($fh) or croak "close: $!";
2949 return $c eq ('0' x 40) ? undef : $c;
2952 close($fh) or croak "close: $!";
2953 undef;
2956 # Finds the first svn revision that exists on (if $eq_ok is true) or
2957 # before $rev for the current branch. It will not search any lower
2958 # than $min_rev. Returns the git commit hash and svn revision number
2959 # if found, else (undef, undef).
2960 sub find_rev_before {
2961 my ($self, $rev, $eq_ok, $min_rev) = @_;
2962 --$rev unless $eq_ok;
2963 $min_rev ||= 1;
2964 while ($rev >= $min_rev) {
2965 if (my $c = $self->rev_map_get($rev)) {
2966 return ($rev, $c);
2968 --$rev;
2970 return (undef, undef);
2973 # Finds the first svn revision that exists on (if $eq_ok is true) or
2974 # after $rev for the current branch. It will not search any higher
2975 # than $max_rev. Returns the git commit hash and svn revision number
2976 # if found, else (undef, undef).
2977 sub find_rev_after {
2978 my ($self, $rev, $eq_ok, $max_rev) = @_;
2979 ++$rev unless $eq_ok;
2980 $max_rev ||= $self->rev_map_max;
2981 while ($rev <= $max_rev) {
2982 if (my $c = $self->rev_map_get($rev)) {
2983 return ($rev, $c);
2985 ++$rev;
2987 return (undef, undef);
2990 sub _new {
2991 my ($class, $repo_id, $ref_id, $path) = @_;
2992 unless (defined $repo_id && length $repo_id) {
2993 $repo_id = $Git::SVN::default_repo_id;
2995 unless (defined $ref_id && length $ref_id) {
2996 $_[2] = $ref_id = $Git::SVN::default_ref_id;
2998 $_[1] = $repo_id;
2999 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
3000 $_[3] = $path = '' unless (defined $path);
3001 mkpath(["$ENV{GIT_DIR}/svn"]);
3002 bless {
3003 ref_id => $ref_id, dir => $dir, index => "$dir/index",
3004 path => $path, config => "$ENV{GIT_DIR}/svn/config",
3005 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
3008 # for read-only access of old .rev_db formats
3009 sub unlink_rev_db_symlink {
3010 my ($self) = @_;
3011 my $link = $self->rev_db_path;
3012 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
3013 if (-l $link) {
3014 unlink $link or croak "unlink: $link failed!";
3018 sub rev_db_path {
3019 my ($self, $uuid) = @_;
3020 my $db_path = $self->map_path($uuid);
3021 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
3022 or croak "map_path: $db_path does not contain '/.rev_map.' !";
3023 $db_path;
3026 # the new replacement for .rev_db
3027 sub map_path {
3028 my ($self, $uuid) = @_;
3029 $uuid ||= $self->ra_uuid;
3030 "$self->{map_root}.$uuid";
3033 sub uri_encode {
3034 my ($f) = @_;
3035 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
3039 sub remove_username {
3040 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
3043 package Git::SVN::Prompt;
3044 use strict;
3045 use warnings;
3046 require SVN::Core;
3047 use vars qw/$_no_auth_cache $_username/;
3049 sub simple {
3050 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
3051 $may_save = undef if $_no_auth_cache;
3052 $default_username = $_username if defined $_username;
3053 if (defined $default_username && length $default_username) {
3054 if (defined $realm && length $realm) {
3055 print STDERR "Authentication realm: $realm\n";
3056 STDERR->flush;
3058 $cred->username($default_username);
3059 } else {
3060 username($cred, $realm, $may_save, $pool);
3062 $cred->password(_read_password("Password for '" .
3063 $cred->username . "': ", $realm));
3064 $cred->may_save($may_save);
3065 $SVN::_Core::SVN_NO_ERROR;
3068 sub ssl_server_trust {
3069 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
3070 $may_save = undef if $_no_auth_cache;
3071 print STDERR "Error validating server certificate for '$realm':\n";
3073 no warnings 'once';
3074 # All variables SVN::Auth::SSL::* are used only once,
3075 # so we're shutting up Perl warnings about this.
3076 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
3077 print STDERR " - The certificate is not issued ",
3078 "by a trusted authority. Use the\n",
3079 " fingerprint to validate ",
3080 "the certificate manually!\n";
3082 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
3083 print STDERR " - The certificate hostname ",
3084 "does not match.\n";
3086 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
3087 print STDERR " - The certificate is not yet valid.\n";
3089 if ($failures & $SVN::Auth::SSL::EXPIRED) {
3090 print STDERR " - The certificate has expired.\n";
3092 if ($failures & $SVN::Auth::SSL::OTHER) {
3093 print STDERR " - The certificate has ",
3094 "an unknown error.\n";
3096 } # no warnings 'once'
3097 printf STDERR
3098 "Certificate information:\n".
3099 " - Hostname: %s\n".
3100 " - Valid: from %s until %s\n".
3101 " - Issuer: %s\n".
3102 " - Fingerprint: %s\n",
3103 map $cert_info->$_, qw(hostname valid_from valid_until
3104 issuer_dname fingerprint);
3105 my $choice;
3106 prompt:
3107 print STDERR $may_save ?
3108 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
3109 "(R)eject or accept (t)emporarily? ";
3110 STDERR->flush;
3111 $choice = lc(substr(<STDIN> || 'R', 0, 1));
3112 if ($choice =~ /^t$/i) {
3113 $cred->may_save(undef);
3114 } elsif ($choice =~ /^r$/i) {
3115 return -1;
3116 } elsif ($may_save && $choice =~ /^p$/i) {
3117 $cred->may_save($may_save);
3118 } else {
3119 goto prompt;
3121 $cred->accepted_failures($failures);
3122 $SVN::_Core::SVN_NO_ERROR;
3125 sub ssl_client_cert {
3126 my ($cred, $realm, $may_save, $pool) = @_;
3127 $may_save = undef if $_no_auth_cache;
3128 print STDERR "Client certificate filename: ";
3129 STDERR->flush;
3130 chomp(my $filename = <STDIN>);
3131 $cred->cert_file($filename);
3132 $cred->may_save($may_save);
3133 $SVN::_Core::SVN_NO_ERROR;
3136 sub ssl_client_cert_pw {
3137 my ($cred, $realm, $may_save, $pool) = @_;
3138 $may_save = undef if $_no_auth_cache;
3139 $cred->password(_read_password("Password: ", $realm));
3140 $cred->may_save($may_save);
3141 $SVN::_Core::SVN_NO_ERROR;
3144 sub username {
3145 my ($cred, $realm, $may_save, $pool) = @_;
3146 $may_save = undef if $_no_auth_cache;
3147 if (defined $realm && length $realm) {
3148 print STDERR "Authentication realm: $realm\n";
3150 my $username;
3151 if (defined $_username) {
3152 $username = $_username;
3153 } else {
3154 print STDERR "Username: ";
3155 STDERR->flush;
3156 chomp($username = <STDIN>);
3158 $cred->username($username);
3159 $cred->may_save($may_save);
3160 $SVN::_Core::SVN_NO_ERROR;
3163 sub _read_password {
3164 my ($prompt, $realm) = @_;
3165 print STDERR $prompt;
3166 STDERR->flush;
3167 require Term::ReadKey;
3168 Term::ReadKey::ReadMode('noecho');
3169 my $password = '';
3170 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
3171 last if $key =~ /[\012\015]/; # \n\r
3172 $password .= $key;
3174 Term::ReadKey::ReadMode('restore');
3175 print STDERR "\n";
3176 STDERR->flush;
3177 $password;
3180 package SVN::Git::Fetcher;
3181 use vars qw/@ISA/;
3182 use strict;
3183 use warnings;
3184 use Carp qw/croak/;
3185 use File::Temp qw/tempfile/;
3186 use IO::File qw//;
3188 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
3189 sub new {
3190 my ($class, $git_svn) = @_;
3191 my $self = SVN::Delta::Editor->new;
3192 bless $self, $class;
3193 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
3194 $self->{empty} = {};
3195 $self->{dir_prop} = {};
3196 $self->{file_prop} = {};
3197 $self->{absent_dir} = {};
3198 $self->{absent_file} = {};
3199 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
3200 $self;
3203 sub set_path_strip {
3204 my ($self, $path) = @_;
3205 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
3208 sub open_root {
3209 { path => '' };
3212 sub open_directory {
3213 my ($self, $path, $pb, $rev) = @_;
3214 { path => $path };
3217 sub git_path {
3218 my ($self, $path) = @_;
3219 if ($self->{path_strip}) {
3220 $path =~ s!$self->{path_strip}!! or
3221 die "Failed to strip path '$path' ($self->{path_strip})\n";
3223 $path;
3226 sub delete_entry {
3227 my ($self, $path, $rev, $pb) = @_;
3229 my $gpath = $self->git_path($path);
3230 return undef if ($gpath eq '');
3232 # remove entire directories.
3233 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
3234 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3235 -r --name-only -z/,
3236 $self->{c}, '--', $gpath);
3237 local $/ = "\0";
3238 while (<$ls>) {
3239 chomp;
3240 $self->{gii}->remove($_);
3241 print "\tD\t$_\n" unless $::_q;
3243 print "\tD\t$gpath/\n" unless $::_q;
3244 command_close_pipe($ls, $ctx);
3245 $self->{empty}->{$path} = 0
3246 } else {
3247 $self->{gii}->remove($gpath);
3248 print "\tD\t$gpath\n" unless $::_q;
3250 undef;
3253 sub open_file {
3254 my ($self, $path, $pb, $rev) = @_;
3255 my $gpath = $self->git_path($path);
3256 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
3257 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
3258 unless (defined $mode && defined $blob) {
3259 die "$path was not found in commit $self->{c} (r$rev)\n";
3261 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
3262 pool => SVN::Pool->new, action => 'M' };
3265 sub add_file {
3266 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
3267 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3268 delete $self->{empty}->{$dir};
3269 { path => $path, mode_a => 100644, mode_b => 100644,
3270 pool => SVN::Pool->new, action => 'A' };
3273 sub add_directory {
3274 my ($self, $path, $cp_path, $cp_rev) = @_;
3275 my $gpath = $self->git_path($path);
3276 if ($gpath eq '') {
3277 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3278 -r --name-only -z/,
3279 $self->{c});
3280 local $/ = "\0";
3281 while (<$ls>) {
3282 chomp;
3283 $self->{gii}->remove($_);
3284 print "\tD\t$_\n" unless $::_q;
3286 command_close_pipe($ls, $ctx);
3287 $self->{empty}->{$path} = 0;
3289 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3290 delete $self->{empty}->{$dir};
3291 $self->{empty}->{$path} = 1;
3292 { path => $path };
3295 sub change_dir_prop {
3296 my ($self, $db, $prop, $value) = @_;
3297 $self->{dir_prop}->{$db->{path}} ||= {};
3298 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
3299 undef;
3302 sub absent_directory {
3303 my ($self, $path, $pb) = @_;
3304 $self->{absent_dir}->{$pb->{path}} ||= [];
3305 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
3306 undef;
3309 sub absent_file {
3310 my ($self, $path, $pb) = @_;
3311 $self->{absent_file}->{$pb->{path}} ||= [];
3312 push @{$self->{absent_file}->{$pb->{path}}}, $path;
3313 undef;
3316 sub change_file_prop {
3317 my ($self, $fb, $prop, $value) = @_;
3318 if ($prop eq 'svn:executable') {
3319 if ($fb->{mode_b} != 120000) {
3320 $fb->{mode_b} = defined $value ? 100755 : 100644;
3322 } elsif ($prop eq 'svn:special') {
3323 $fb->{mode_b} = defined $value ? 120000 : 100644;
3324 } else {
3325 $self->{file_prop}->{$fb->{path}} ||= {};
3326 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
3328 undef;
3331 sub apply_textdelta {
3332 my ($self, $fb, $exp) = @_;
3333 my $fh = Git::temp_acquire('svn_delta');
3334 # $fh gets auto-closed() by SVN::TxDelta::apply(),
3335 # (but $base does not,) so dup() it for reading in close_file
3336 open my $dup, '<&', $fh or croak $!;
3337 my $base = Git::temp_acquire('git_blob');
3338 if ($fb->{blob}) {
3339 print $base 'link ' if ($fb->{mode_a} == 120000);
3340 my $size = $::_repository->cat_blob($fb->{blob}, $base);
3341 die "Failed to read object $fb->{blob}" if ($size < 0);
3343 if (defined $exp) {
3344 seek $base, 0, 0 or croak $!;
3345 my $got = ::md5sum($base);
3346 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
3347 "expected: $exp\n",
3348 " got: $got\n" if ($got ne $exp);
3351 seek $base, 0, 0 or croak $!;
3352 $fb->{fh} = $fh;
3353 $fb->{base} = $base;
3354 [ SVN::TxDelta::apply($base, $dup, undef, $fb->{path}, $fb->{pool}) ];
3357 sub close_file {
3358 my ($self, $fb, $exp) = @_;
3359 my $hash;
3360 my $path = $self->git_path($fb->{path});
3361 if (my $fh = $fb->{fh}) {
3362 if (defined $exp) {
3363 seek($fh, 0, 0) or croak $!;
3364 my $got = ::md5sum($fh);
3365 if ($got ne $exp) {
3366 die "Checksum mismatch: $path\n",
3367 "expected: $exp\n got: $got\n";
3370 if ($fb->{mode_b} == 120000) {
3371 sysseek($fh, 0, 0) or croak $!;
3372 sysread($fh, my $buf, 5) == 5 or croak $!;
3374 unless ($buf eq 'link ') {
3375 warn "$path has mode 120000",
3376 " but is not a link\n";
3377 } else {
3378 my $tmp_fh = Git::temp_acquire('svn_hash');
3379 my $res;
3380 while ($res = sysread($fh, my $str, 1024)) {
3381 my $out = syswrite($tmp_fh, $str, $res);
3382 defined($out) && $out == $res
3383 or croak("write ",
3384 Git::temp_path($tmp_fh),
3385 ": $!\n");
3387 defined $res or croak $!;
3389 ($fh, $tmp_fh) = ($tmp_fh, $fh);
3390 Git::temp_release($tmp_fh, 1);
3394 $hash = $::_repository->hash_and_insert_object(
3395 Git::temp_path($fh));
3396 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
3398 Git::temp_release($fb->{base}, 1);
3399 Git::temp_release($fh, 1);
3400 } else {
3401 $hash = $fb->{blob} or die "no blob information\n";
3403 $fb->{pool}->clear;
3404 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
3405 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
3406 undef;
3409 sub abort_edit {
3410 my $self = shift;
3411 $self->{nr} = $self->{gii}->{nr};
3412 delete $self->{gii};
3413 $self->SUPER::abort_edit(@_);
3416 sub close_edit {
3417 my $self = shift;
3418 $self->{git_commit_ok} = 1;
3419 $self->{nr} = $self->{gii}->{nr};
3420 delete $self->{gii};
3421 $self->SUPER::close_edit(@_);
3424 package SVN::Git::Editor;
3425 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
3426 use strict;
3427 use warnings;
3428 use Carp qw/croak/;
3429 use IO::File;
3431 sub new {
3432 my ($class, $opts) = @_;
3433 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
3434 die "$_ required!\n" unless (defined $opts->{$_});
3437 my $pool = SVN::Pool->new;
3438 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
3439 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
3440 $opts->{r}, $mods);
3442 # $opts->{ra} functions should not be used after this:
3443 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
3444 $opts->{editor_cb}, $pool);
3445 my $self = SVN::Delta::Editor->new(@ce, $pool);
3446 bless $self, $class;
3447 foreach (qw/svn_path r tree_a tree_b/) {
3448 $self->{$_} = $opts->{$_};
3450 $self->{url} = $opts->{ra}->{url};
3451 $self->{mods} = $mods;
3452 $self->{types} = $types;
3453 $self->{pool} = $pool;
3454 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
3455 $self->{rm} = { };
3456 $self->{path_prefix} = length $self->{svn_path} ?
3457 "$self->{svn_path}/" : '';
3458 $self->{config} = $opts->{config};
3459 return $self;
3462 sub generate_diff {
3463 my ($tree_a, $tree_b) = @_;
3464 my @diff_tree = qw(diff-tree -z -r);
3465 if ($_cp_similarity) {
3466 push @diff_tree, "-C$_cp_similarity";
3467 } else {
3468 push @diff_tree, '-C';
3470 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
3471 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
3472 push @diff_tree, $tree_a, $tree_b;
3473 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
3474 local $/ = "\0";
3475 my $state = 'meta';
3476 my @mods;
3477 while (<$diff_fh>) {
3478 chomp $_; # this gets rid of the trailing "\0"
3479 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
3480 ($::sha1)\s($::sha1)\s
3481 ([MTCRAD])\d*$/xo) {
3482 push @mods, { mode_a => $1, mode_b => $2,
3483 sha1_a => $3, sha1_b => $4,
3484 chg => $5 };
3485 if ($5 =~ /^(?:C|R)$/) {
3486 $state = 'file_a';
3487 } else {
3488 $state = 'file_b';
3490 } elsif ($state eq 'file_a') {
3491 my $x = $mods[$#mods] or croak "Empty array\n";
3492 if ($x->{chg} !~ /^(?:C|R)$/) {
3493 croak "Error parsing $_, $x->{chg}\n";
3495 $x->{file_a} = $_;
3496 $state = 'file_b';
3497 } elsif ($state eq 'file_b') {
3498 my $x = $mods[$#mods] or croak "Empty array\n";
3499 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
3500 croak "Error parsing $_, $x->{chg}\n";
3502 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
3503 croak "Error parsing $_, $x->{chg}\n";
3505 $x->{file_b} = $_;
3506 $state = 'meta';
3507 } else {
3508 croak "Error parsing $_\n";
3511 command_close_pipe($diff_fh, $ctx);
3512 \@mods;
3515 sub check_diff_paths {
3516 my ($ra, $pfx, $rev, $mods) = @_;
3517 my %types;
3518 $pfx .= '/' if length $pfx;
3520 sub type_diff_paths {
3521 my ($ra, $types, $path, $rev) = @_;
3522 my @p = split m#/+#, $path;
3523 my $c = shift @p;
3524 unless (defined $types->{$c}) {
3525 $types->{$c} = $ra->check_path($c, $rev);
3527 while (@p) {
3528 $c .= '/' . shift @p;
3529 next if defined $types->{$c};
3530 $types->{$c} = $ra->check_path($c, $rev);
3534 foreach my $m (@$mods) {
3535 foreach my $f (qw/file_a file_b/) {
3536 next unless defined $m->{$f};
3537 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
3538 if (length $pfx.$dir && ! defined $types{$dir}) {
3539 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
3543 \%types;
3546 sub split_path {
3547 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
3550 sub repo_path {
3551 my ($self, $path) = @_;
3552 $self->{path_prefix}.(defined $path ? $path : '');
3555 sub url_path {
3556 my ($self, $path) = @_;
3557 if ($self->{url} =~ m#^https?://#) {
3558 $path =~ s/([^~a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
3560 $self->{url} . '/' . $self->repo_path($path);
3563 sub rmdirs {
3564 my ($self) = @_;
3565 my $rm = $self->{rm};
3566 delete $rm->{''}; # we never delete the url we're tracking
3567 return unless %$rm;
3569 foreach (keys %$rm) {
3570 my @d = split m#/#, $_;
3571 my $c = shift @d;
3572 $rm->{$c} = 1;
3573 while (@d) {
3574 $c .= '/' . shift @d;
3575 $rm->{$c} = 1;
3578 delete $rm->{$self->{svn_path}};
3579 delete $rm->{''}; # we never delete the url we're tracking
3580 return unless %$rm;
3582 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
3583 $self->{tree_b});
3584 local $/ = "\0";
3585 while (<$fh>) {
3586 chomp;
3587 my @dn = split m#/#, $_;
3588 while (pop @dn) {
3589 delete $rm->{join '/', @dn};
3591 unless (%$rm) {
3592 close $fh;
3593 return;
3596 command_close_pipe($fh, $ctx);
3598 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
3599 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
3600 $self->close_directory($bat->{$d}, $p);
3601 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
3602 print "\tD+\t$d/\n" unless $::_q;
3603 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
3604 delete $bat->{$d};
3608 sub open_or_add_dir {
3609 my ($self, $full_path, $baton) = @_;
3610 my $t = $self->{types}->{$full_path};
3611 if (!defined $t) {
3612 die "$full_path not known in r$self->{r} or we have a bug!\n";
3615 no warnings 'once';
3616 # SVN::Node::none and SVN::Node::file are used only once,
3617 # so we're shutting up Perl's warnings about them.
3618 if ($t == $SVN::Node::none) {
3619 return $self->add_directory($full_path, $baton,
3620 undef, -1, $self->{pool});
3621 } elsif ($t == $SVN::Node::dir) {
3622 return $self->open_directory($full_path, $baton,
3623 $self->{r}, $self->{pool});
3624 } # no warnings 'once'
3625 print STDERR "$full_path already exists in repository at ",
3626 "r$self->{r} and it is not a directory (",
3627 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
3628 } # no warnings 'once'
3629 exit 1;
3632 sub ensure_path {
3633 my ($self, $path) = @_;
3634 my $bat = $self->{bat};
3635 my $repo_path = $self->repo_path($path);
3636 return $bat->{''} unless (length $repo_path);
3637 my @p = split m#/+#, $repo_path;
3638 my $c = shift @p;
3639 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
3640 while (@p) {
3641 my $c0 = $c;
3642 $c .= '/' . shift @p;
3643 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
3645 return $bat->{$c};
3648 # Subroutine to convert a globbing pattern to a regular expression.
3649 # From perl cookbook.
3650 sub glob2pat {
3651 my $globstr = shift;
3652 my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
3653 $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
3654 return '^' . $globstr . '$';
3657 sub check_autoprop {
3658 my ($self, $pattern, $properties, $file, $fbat) = @_;
3659 # Convert the globbing pattern to a regular expression.
3660 my $regex = glob2pat($pattern);
3661 # Check if the pattern matches the file name.
3662 if($file =~ m/($regex)/) {
3663 # Parse the list of properties to set.
3664 my @props = split(/;/, $properties);
3665 foreach my $prop (@props) {
3666 # Parse 'name=value' syntax and set the property.
3667 if ($prop =~ /([^=]+)=(.*)/) {
3668 my ($n,$v) = ($1,$2);
3669 for ($n, $v) {
3670 s/^\s+//; s/\s+$//;
3672 $self->change_file_prop($fbat, $n, $v);
3678 sub apply_autoprops {
3679 my ($self, $file, $fbat) = @_;
3680 my $conf_t = ${$self->{config}}{'config'};
3681 no warnings 'once';
3682 # Check [miscellany]/enable-auto-props in svn configuration.
3683 if (SVN::_Core::svn_config_get_bool(
3684 $conf_t,
3685 $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
3686 $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
3687 0)) {
3688 # Auto-props are enabled. Enumerate them to look for matches.
3689 my $callback = sub {
3690 $self->check_autoprop($_[0], $_[1], $file, $fbat);
3692 SVN::_Core::svn_config_enumerate(
3693 $conf_t,
3694 $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
3695 $callback);
3699 sub A {
3700 my ($self, $m) = @_;
3701 my ($dir, $file) = split_path($m->{file_b});
3702 my $pbat = $self->ensure_path($dir);
3703 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3704 undef, -1);
3705 print "\tA\t$m->{file_b}\n" unless $::_q;
3706 $self->apply_autoprops($file, $fbat);
3707 $self->chg_file($fbat, $m);
3708 $self->close_file($fbat,undef,$self->{pool});
3711 sub C {
3712 my ($self, $m) = @_;
3713 my ($dir, $file) = split_path($m->{file_b});
3714 my $pbat = $self->ensure_path($dir);
3715 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3716 $self->url_path($m->{file_a}), $self->{r});
3717 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3718 $self->chg_file($fbat, $m);
3719 $self->close_file($fbat,undef,$self->{pool});
3722 sub delete_entry {
3723 my ($self, $path, $pbat) = @_;
3724 my $rpath = $self->repo_path($path);
3725 my ($dir, $file) = split_path($rpath);
3726 $self->{rm}->{$dir} = 1;
3727 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
3730 sub R {
3731 my ($self, $m) = @_;
3732 my ($dir, $file) = split_path($m->{file_b});
3733 my $pbat = $self->ensure_path($dir);
3734 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3735 $self->url_path($m->{file_a}), $self->{r});
3736 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3737 $self->apply_autoprops($file, $fbat);
3738 $self->chg_file($fbat, $m);
3739 $self->close_file($fbat,undef,$self->{pool});
3741 ($dir, $file) = split_path($m->{file_a});
3742 $pbat = $self->ensure_path($dir);
3743 $self->delete_entry($m->{file_a}, $pbat);
3746 sub M {
3747 my ($self, $m) = @_;
3748 my ($dir, $file) = split_path($m->{file_b});
3749 my $pbat = $self->ensure_path($dir);
3750 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
3751 $pbat,$self->{r},$self->{pool});
3752 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
3753 $self->chg_file($fbat, $m);
3754 $self->close_file($fbat,undef,$self->{pool});
3757 sub T { shift->M(@_) }
3759 sub change_file_prop {
3760 my ($self, $fbat, $pname, $pval) = @_;
3761 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
3764 sub _chg_file_get_blob ($$$$) {
3765 my ($self, $fbat, $m, $which) = @_;
3766 my $fh = Git::temp_acquire("git_blob_$which");
3767 if ($m->{"mode_$which"} =~ /^120/) {
3768 print $fh 'link ' or croak $!;
3769 $self->change_file_prop($fbat,'svn:special','*');
3770 } elsif ($m->{mode_a} =~ /^120/ && $m->{"mode_$which"} !~ /^120/) {
3771 $self->change_file_prop($fbat,'svn:special',undef);
3773 my $blob = $m->{"sha1_$which"};
3774 return ($fh,) if ($blob =~ /^0{40}$/);
3775 my $size = $::_repository->cat_blob($blob, $fh);
3776 croak "Failed to read object $blob" if ($size < 0);
3777 $fh->flush == 0 or croak $!;
3778 seek $fh, 0, 0 or croak $!;
3780 my $exp = ::md5sum($fh);
3781 seek $fh, 0, 0 or croak $!;
3782 return ($fh, $exp);
3785 sub chg_file {
3786 my ($self, $fbat, $m) = @_;
3787 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
3788 $self->change_file_prop($fbat,'svn:executable','*');
3789 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
3790 $self->change_file_prop($fbat,'svn:executable',undef);
3792 my ($fh_a, $exp_a) = _chg_file_get_blob $self, $fbat, $m, 'a';
3793 my ($fh_b, $exp_b) = _chg_file_get_blob $self, $fbat, $m, 'b';
3794 my $pool = SVN::Pool->new;
3795 my $atd = $self->apply_textdelta($fbat, $exp_a, $pool);
3796 if (-s $fh_a) {
3797 my $txstream = SVN::TxDelta::new ($fh_a, $fh_b, $pool);
3798 my $res = SVN::TxDelta::send_txstream($txstream, @$atd, $pool);
3799 if (defined $res) {
3800 die "Unexpected result from send_txstream: $res\n",
3801 "(SVN::Core::VERSION: $SVN::Core::VERSION)\n";
3803 } else {
3804 my $got = SVN::TxDelta::send_stream($fh_b, @$atd, $pool);
3805 die "Checksum mismatch\nexpected: $exp_b\ngot: $got\n"
3806 if ($got ne $exp_b);
3808 Git::temp_release($fh_b, 1);
3809 Git::temp_release($fh_a, 1);
3810 $pool->clear;
3813 sub D {
3814 my ($self, $m) = @_;
3815 my ($dir, $file) = split_path($m->{file_b});
3816 my $pbat = $self->ensure_path($dir);
3817 print "\tD\t$m->{file_b}\n" unless $::_q;
3818 $self->delete_entry($m->{file_b}, $pbat);
3821 sub close_edit {
3822 my ($self) = @_;
3823 my ($p,$bat) = ($self->{pool}, $self->{bat});
3824 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
3825 next if $_ eq '';
3826 $self->close_directory($bat->{$_}, $p);
3828 $self->close_directory($bat->{''}, $p);
3829 $self->SUPER::close_edit($p);
3830 $p->clear;
3833 sub abort_edit {
3834 my ($self) = @_;
3835 $self->SUPER::abort_edit($self->{pool});
3838 sub DESTROY {
3839 my $self = shift;
3840 $self->SUPER::DESTROY(@_);
3841 $self->{pool}->clear;
3844 # this drives the editor
3845 sub apply_diff {
3846 my ($self) = @_;
3847 my $mods = $self->{mods};
3848 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
3849 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
3850 my $f = $m->{chg};
3851 if (defined $o{$f}) {
3852 $self->$f($m);
3853 } else {
3854 fatal("Invalid change type: $f");
3857 $self->rmdirs if $_rmdir;
3858 if (@$mods == 0) {
3859 $self->abort_edit;
3860 } else {
3861 $self->close_edit;
3863 return scalar @$mods;
3866 package Git::SVN::Ra;
3867 use vars qw/@ISA $config_dir $_log_window_size/;
3868 use strict;
3869 use warnings;
3870 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
3872 BEGIN {
3873 # enforce temporary pool usage for some simple functions
3874 no strict 'refs';
3875 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root/) {
3876 my $SUPER = "SUPER::$f";
3877 *$f = sub {
3878 my $self = shift;
3879 my $pool = SVN::Pool->new;
3880 my @ret = $self->$SUPER(@_,$pool);
3881 $pool->clear;
3882 wantarray ? @ret : $ret[0];
3887 sub _auth_providers () {
3889 SVN::Client::get_simple_provider(),
3890 SVN::Client::get_ssl_server_trust_file_provider(),
3891 SVN::Client::get_simple_prompt_provider(
3892 \&Git::SVN::Prompt::simple, 2),
3893 SVN::Client::get_ssl_client_cert_file_provider(),
3894 SVN::Client::get_ssl_client_cert_prompt_provider(
3895 \&Git::SVN::Prompt::ssl_client_cert, 2),
3896 SVN::Client::get_ssl_client_cert_pw_file_provider(),
3897 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
3898 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
3899 SVN::Client::get_username_provider(),
3900 SVN::Client::get_ssl_server_trust_prompt_provider(
3901 \&Git::SVN::Prompt::ssl_server_trust),
3902 SVN::Client::get_username_prompt_provider(
3903 \&Git::SVN::Prompt::username, 2)
3907 sub escape_uri_only {
3908 my ($uri) = @_;
3909 my @tmp;
3910 foreach (split m{/}, $uri) {
3911 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
3912 push @tmp, $_;
3914 join('/', @tmp);
3917 sub escape_url {
3918 my ($url) = @_;
3919 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
3920 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
3921 $url = "$scheme://$domain$uri";
3923 $url;
3926 sub new {
3927 my ($class, $url) = @_;
3928 $url =~ s!/+$!!;
3929 return $RA if ($RA && $RA->{url} eq $url);
3931 SVN::_Core::svn_config_ensure($config_dir, undef);
3932 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
3933 my $config = SVN::Core::config_get_config($config_dir);
3934 $RA = undef;
3935 my $dont_store_passwords = 1;
3936 my $conf_t = ${$config}{'config'};
3938 no warnings 'once';
3939 # The usage of $SVN::_Core::SVN_CONFIG_* variables
3940 # produces warnings that variables are used only once.
3941 # I had not found the better way to shut them up, so
3942 # the warnings of type 'once' are disabled in this block.
3943 if (SVN::_Core::svn_config_get_bool($conf_t,
3944 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
3945 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
3946 1) == 0) {
3947 SVN::_Core::svn_auth_set_parameter($baton,
3948 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
3949 bless (\$dont_store_passwords, "_p_void"));
3951 if (SVN::_Core::svn_config_get_bool($conf_t,
3952 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
3953 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
3954 1) == 0) {
3955 $Git::SVN::Prompt::_no_auth_cache = 1;
3957 } # no warnings 'once'
3958 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
3959 config => $config,
3960 pool => SVN::Pool->new,
3961 auth_provider_callbacks => $callbacks);
3962 $self->{url} = $url;
3963 $self->{svn_path} = $url;
3964 $self->{repos_root} = $self->get_repos_root;
3965 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
3966 $self->{cache} = { check_path => { r => 0, data => {} },
3967 get_dir => { r => 0, data => {} } };
3968 $RA = bless $self, $class;
3971 sub check_path {
3972 my ($self, $path, $r) = @_;
3973 my $cache = $self->{cache}->{check_path};
3974 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
3975 return $cache->{data}->{$path};
3977 my $pool = SVN::Pool->new;
3978 my $t = $self->SUPER::check_path($path, $r, $pool);
3979 $pool->clear;
3980 if ($r != $cache->{r}) {
3981 %{$cache->{data}} = ();
3982 $cache->{r} = $r;
3984 $cache->{data}->{$path} = $t;
3987 sub get_dir {
3988 my ($self, $dir, $r) = @_;
3989 my $cache = $self->{cache}->{get_dir};
3990 if ($r == $cache->{r}) {
3991 if (my $x = $cache->{data}->{$dir}) {
3992 return wantarray ? @$x : $x->[0];
3995 my $pool = SVN::Pool->new;
3996 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
3997 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
3998 $pool->clear;
3999 if ($r != $cache->{r}) {
4000 %{$cache->{data}} = ();
4001 $cache->{r} = $r;
4003 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
4004 wantarray ? (\%dirents, $r, $props) : \%dirents;
4007 sub DESTROY {
4008 # do not call the real DESTROY since we store ourselves in $RA
4011 sub get_log {
4012 my ($self, @args) = @_;
4013 my $pool = SVN::Pool->new;
4014 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
4015 my $ret = $self->SUPER::get_log(@args, $pool);
4016 $pool->clear;
4017 $ret;
4020 sub trees_match {
4021 my ($self, $url1, $rev1, $url2, $rev2) = @_;
4022 my $ctx = SVN::Client->new(auth => _auth_providers);
4023 my $out = IO::File->new_tmpfile;
4025 # older SVN (1.1.x) doesn't take $pool as the last parameter for
4026 # $ctx->diff(), so we'll create a default one
4027 my $pool = SVN::Pool->new_default_sub;
4029 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
4030 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
4031 $out->flush;
4032 my $ret = (($out->stat)[7] == 0);
4033 close $out or croak $!;
4035 $ret;
4038 sub get_commit_editor {
4039 my ($self, $log, $cb, $pool) = @_;
4040 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
4041 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
4044 sub gs_do_update {
4045 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
4046 my $new = ($rev_a == $rev_b);
4047 my $path = $gs->{path};
4049 if ($new && -e $gs->{index}) {
4050 unlink $gs->{index} or die
4051 "Couldn't unlink index: $gs->{index}: $!\n";
4053 my $pool = SVN::Pool->new;
4054 $editor->set_path_strip($path);
4055 my (@pc) = split m#/#, $path;
4056 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
4057 1, $editor, $pool);
4058 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4060 # Since we can't rely on svn_ra_reparent being available, we'll
4061 # just have to do some magic with set_path to make it so
4062 # we only want a partial path.
4063 my $sp = '';
4064 my $final = join('/', @pc);
4065 while (@pc) {
4066 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
4067 $sp .= '/' if length $sp;
4068 $sp .= shift @pc;
4070 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
4072 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
4074 $reporter->finish_report($pool);
4075 $pool->clear;
4076 $editor->{git_commit_ok};
4079 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
4080 # svn_ra_reparent didn't work before 1.4)
4081 sub gs_do_switch {
4082 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
4083 my $path = $gs->{path};
4084 my $pool = SVN::Pool->new;
4086 my $full_url = $self->{url};
4087 my $old_url = $full_url;
4088 $full_url .= '/' . escape_uri_only($path) if length $path;
4089 my ($ra, $reparented);
4091 if ($old_url =~ m#^svn(\+ssh)?://#) {
4092 $_[0] = undef;
4093 $self = undef;
4094 $RA = undef;
4095 $ra = Git::SVN::Ra->new($full_url);
4096 $ra_invalid = 1;
4097 } elsif ($old_url ne $full_url) {
4098 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url, $pool);
4099 $self->{url} = $full_url;
4100 $reparented = 1;
4103 $ra ||= $self;
4104 $url_b = escape_url($url_b);
4105 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
4106 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4107 $reporter->set_path('', $rev_a, 0, @lock, $pool);
4108 $reporter->finish_report($pool);
4110 if ($reparented) {
4111 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
4112 $self->{url} = $old_url;
4115 $pool->clear;
4116 $editor->{git_commit_ok};
4119 sub longest_common_path {
4120 my ($gsv, $globs) = @_;
4121 my %common;
4122 my $common_max = scalar @$gsv;
4124 foreach my $gs (@$gsv) {
4125 my @tmp = split m#/#, $gs->{path};
4126 my $p = '';
4127 foreach (@tmp) {
4128 $p .= length($p) ? "/$_" : $_;
4129 $common{$p} ||= 0;
4130 $common{$p}++;
4133 $globs ||= [];
4134 $common_max += scalar @$globs;
4135 foreach my $glob (@$globs) {
4136 my @tmp = split m#/#, $glob->{path}->{left};
4137 my $p = '';
4138 foreach (@tmp) {
4139 $p .= length($p) ? "/$_" : $_;
4140 $common{$p} ||= 0;
4141 $common{$p}++;
4145 my $longest_path = '';
4146 foreach (sort {length $b <=> length $a} keys %common) {
4147 if ($common{$_} == $common_max) {
4148 $longest_path = $_;
4149 last;
4152 $longest_path;
4155 sub gs_fetch_loop_common {
4156 my ($self, $base, $head, $gsv, $globs) = @_;
4157 return if ($base > $head);
4158 my $inc = $_log_window_size;
4159 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
4160 my $longest_path = longest_common_path($gsv, $globs);
4161 my $ra_url = $self->{url};
4162 while (1) {
4163 my %revs;
4164 my $err;
4165 my $err_handler = $SVN::Error::handler;
4166 $SVN::Error::handler = sub {
4167 ($err) = @_;
4168 skip_unknown_revs($err);
4170 sub _cb {
4171 my ($paths, $r, $author, $date, $log) = @_;
4172 [ dup_changed_paths($paths),
4173 { author => $author, date => $date, log => $log } ];
4175 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
4176 sub { $revs{$_[1]} = _cb(@_) });
4177 if ($err && $max >= $head) {
4178 print STDERR "Path '$longest_path' ",
4179 "was probably deleted:\n",
4180 $err->expanded_message,
4181 "\nWill attempt to follow ",
4182 "revisions r$min .. r$max ",
4183 "committed before the deletion\n";
4184 my $hi = $max;
4185 while (--$hi >= $min) {
4186 my $ok;
4187 $self->get_log([$longest_path], $min, $hi,
4188 0, 1, 1, sub {
4189 $ok ||= $_[1];
4190 $revs{$_[1]} = _cb(@_) });
4191 if ($ok) {
4192 print STDERR "r$min .. r$ok OK\n";
4193 last;
4197 $SVN::Error::handler = $err_handler;
4199 my %exists = map { $_->{path} => $_ } @$gsv;
4200 foreach my $r (sort {$a <=> $b} keys %revs) {
4201 my ($paths, $logged) = @{$revs{$r}};
4203 foreach my $gs ($self->match_globs(\%exists, $paths,
4204 $globs, $r)) {
4205 if ($gs->rev_map_max >= $r) {
4206 next;
4208 next unless $gs->match_paths($paths, $r);
4209 $gs->{logged_rev_props} = $logged;
4210 if (my $last_commit = $gs->last_commit) {
4211 $gs->assert_index_clean($last_commit);
4213 my $log_entry = $gs->do_fetch($paths, $r);
4214 if ($log_entry) {
4215 $gs->do_git_commit($log_entry);
4217 $INDEX_FILES{$gs->{index}} = 1;
4219 foreach my $g (@$globs) {
4220 my $k = "svn-remote.$g->{remote}." .
4221 "$g->{t}-maxRev";
4222 Git::SVN::tmp_config($k, $r);
4224 if ($ra_invalid) {
4225 $_[0] = undef;
4226 $self = undef;
4227 $RA = undef;
4228 $self = Git::SVN::Ra->new($ra_url);
4229 $ra_invalid = undef;
4232 # pre-fill the .rev_db since it'll eventually get filled in
4233 # with '0' x40 if something new gets committed
4234 foreach my $gs (@$gsv) {
4235 next if $gs->rev_map_max >= $max;
4236 next if defined $gs->rev_map_get($max);
4237 $gs->rev_map_set($max, 0 x40);
4239 foreach my $g (@$globs) {
4240 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
4241 Git::SVN::tmp_config($k, $max);
4243 last if $max >= $head;
4244 $min = $max + 1;
4245 $max += $inc;
4246 $max = $head if ($max > $head);
4248 Git::SVN::gc();
4251 sub get_dir_globbed {
4252 my ($self, $left, $depth, $r) = @_;
4254 my @x = eval { $self->get_dir($left, $r) };
4255 return unless scalar @x == 3;
4256 my $dirents = $x[0];
4257 my @finalents;
4258 foreach my $de (keys %$dirents) {
4259 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
4260 if ($depth > 1) {
4261 my @args = ("$left/$de", $depth - 1, $r);
4262 foreach my $dir ($self->get_dir_globbed(@args)) {
4263 push @finalents, "$de/$dir";
4265 } else {
4266 push @finalents, $de;
4269 @finalents;
4272 sub match_globs {
4273 my ($self, $exists, $paths, $globs, $r) = @_;
4275 sub get_dir_check {
4276 my ($self, $exists, $g, $r) = @_;
4278 my @dirs = $self->get_dir_globbed($g->{path}->{left},
4279 $g->{path}->{depth},
4280 $r);
4282 foreach my $de (@dirs) {
4283 my $p = $g->{path}->full_path($de);
4284 next if $exists->{$p};
4285 next if (length $g->{path}->{right} &&
4286 ($self->check_path($p, $r) !=
4287 $SVN::Node::dir));
4288 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
4289 $g->{ref}->full_path($de), 1);
4292 foreach my $g (@$globs) {
4293 if (my $path = $paths->{"/$g->{path}->{left}"}) {
4294 if ($path->{action} =~ /^[AR]$/) {
4295 get_dir_check($self, $exists, $g, $r);
4298 foreach (keys %$paths) {
4299 if (/$g->{path}->{left_regex}/ &&
4300 !/$g->{path}->{regex}/) {
4301 next if $paths->{$_}->{action} !~ /^[AR]$/;
4302 get_dir_check($self, $exists, $g, $r);
4304 next unless /$g->{path}->{regex}/;
4305 my $p = $1;
4306 my $pathname = $g->{path}->full_path($p);
4307 next if $exists->{$pathname};
4308 next if ($self->check_path($pathname, $r) !=
4309 $SVN::Node::dir);
4310 $exists->{$pathname} = Git::SVN->init(
4311 $self->{url}, $pathname, undef,
4312 $g->{ref}->full_path($p), 1);
4314 my $c = '';
4315 foreach (split m#/#, $g->{path}->{left}) {
4316 $c .= "/$_";
4317 next unless ($paths->{$c} &&
4318 ($paths->{$c}->{action} =~ /^[AR]$/));
4319 get_dir_check($self, $exists, $g, $r);
4322 values %$exists;
4325 sub minimize_url {
4326 my ($self) = @_;
4327 return $self->{url} if ($self->{url} eq $self->{repos_root});
4328 my $url = $self->{repos_root};
4329 my @components = split(m!/!, $self->{svn_path});
4330 my $c = '';
4331 do {
4332 $url .= "/$c" if length $c;
4333 eval { (ref $self)->new($url)->get_latest_revnum };
4334 } while ($@ && ($c = shift @components));
4335 $url;
4338 sub can_do_switch {
4339 my $self = shift;
4340 unless (defined $can_do_switch) {
4341 my $pool = SVN::Pool->new;
4342 my $rep = eval {
4343 $self->do_switch(1, '', 0, $self->{url},
4344 SVN::Delta::Editor->new, $pool);
4346 if ($@) {
4347 $can_do_switch = 0;
4348 } else {
4349 $rep->abort_report($pool);
4350 $can_do_switch = 1;
4352 $pool->clear;
4354 $can_do_switch;
4357 sub skip_unknown_revs {
4358 my ($err) = @_;
4359 my $errno = $err->apr_err();
4360 # Maybe the branch we're tracking didn't
4361 # exist when the repo started, so it's
4362 # not an error if it doesn't, just continue
4364 # Wonderfully consistent library, eh?
4365 # 160013 - svn:// and file://
4366 # 175002 - http(s)://
4367 # 175007 - http(s):// (this repo required authorization, too...)
4368 # More codes may be discovered later...
4369 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
4370 my $err_key = $err->expanded_message;
4371 # revision numbers change every time, filter them out
4372 $err_key =~ s/\d+/\0/g;
4373 $err_key = "$errno\0$err_key";
4374 unless ($ignored_err{$err_key}) {
4375 warn "W: Ignoring error from SVN, path probably ",
4376 "does not exist: ($errno): ",
4377 $err->expanded_message,"\n";
4378 warn "W: Do not be alarmed at the above message ",
4379 "git-svn is just searching aggressively for ",
4380 "old history.\n",
4381 "This may take a while on large repositories\n";
4382 $ignored_err{$err_key} = 1;
4384 return;
4386 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
4389 # svn_log_changed_path_t objects passed to get_log are likely to be
4390 # overwritten even if only the refs are copied to an external variable,
4391 # so we should dup the structures in their entirety. Using an externally
4392 # passed pool (instead of our temporary and quickly cleared pool in
4393 # Git::SVN::Ra) does not help matters at all...
4394 sub dup_changed_paths {
4395 my ($paths) = @_;
4396 return undef unless $paths;
4397 my %ret;
4398 foreach my $p (keys %$paths) {
4399 my $i = $paths->{$p};
4400 my %s = map { $_ => $i->$_ }
4401 qw/copyfrom_path copyfrom_rev action/;
4402 $ret{$p} = \%s;
4404 \%ret;
4407 package Git::SVN::Log;
4408 use strict;
4409 use warnings;
4410 use POSIX qw/strftime/;
4411 use constant commit_log_separator => ('-' x 72) . "\n";
4412 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
4413 %rusers $show_commit $incremental/;
4414 my $l_fmt;
4416 sub cmt_showable {
4417 my ($c) = @_;
4418 return 1 if defined $c->{r};
4420 # big commit message got truncated by the 16k pretty buffer in rev-list
4421 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
4422 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
4423 @{$c->{l}} = ();
4424 my @log = command(qw/cat-file commit/, $c->{c});
4426 # shift off the headers
4427 shift @log while ($log[0] ne '');
4428 shift @log;
4430 # TODO: make $c->{l} not have a trailing newline in the future
4431 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
4433 (undef, $c->{r}, undef) = ::extract_metadata(
4434 (grep(/^git-svn-id: /, @log))[-1]);
4436 return defined $c->{r};
4439 sub log_use_color {
4440 return $color || Git->repository->get_colorbool('color.diff');
4443 sub git_svn_log_cmd {
4444 my ($r_min, $r_max, @args) = @_;
4445 my $head = 'HEAD';
4446 my (@files, @log_opts);
4447 foreach my $x (@args) {
4448 if ($x eq '--' || @files) {
4449 push @files, $x;
4450 } else {
4451 if (::verify_ref("$x^0")) {
4452 $head = $x;
4453 } else {
4454 push @log_opts, $x;
4459 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
4460 $gs ||= Git::SVN->_new;
4461 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
4462 $gs->refname);
4463 push @cmd, '-r' unless $non_recursive;
4464 push @cmd, qw/--raw --name-status/ if $verbose;
4465 push @cmd, '--color' if log_use_color();
4466 push @cmd, @log_opts;
4467 if (defined $r_max && $r_max == $r_min) {
4468 push @cmd, '--max-count=1';
4469 if (my $c = $gs->rev_map_get($r_max)) {
4470 push @cmd, $c;
4472 } elsif (defined $r_max) {
4473 if ($r_max < $r_min) {
4474 ($r_min, $r_max) = ($r_max, $r_min);
4476 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
4477 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
4478 # If there are no commits in the range, both $c_max and $c_min
4479 # will be undefined. If there is at least 1 commit in the
4480 # range, both will be defined.
4481 return () if !defined $c_min || !defined $c_max;
4482 if ($c_min eq $c_max) {
4483 push @cmd, '--max-count=1', $c_min;
4484 } else {
4485 push @cmd, '--boundary', "$c_min..$c_max";
4488 return (@cmd, @files);
4491 # adapted from pager.c
4492 sub config_pager {
4493 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
4494 if (!defined $pager) {
4495 $pager = 'less';
4496 } elsif (length $pager == 0 || $pager eq 'cat') {
4497 $pager = undef;
4499 $ENV{GIT_PAGER_IN_USE} = defined($pager);
4502 sub run_pager {
4503 return unless -t *STDOUT && defined $pager;
4504 pipe my ($rfd, $wfd) or return;
4505 defined(my $pid = fork) or ::fatal "Can't fork: $!";
4506 if (!$pid) {
4507 open STDOUT, '>&', $wfd or
4508 ::fatal "Can't redirect to stdout: $!";
4509 return;
4511 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
4512 $ENV{LESS} ||= 'FRSX';
4513 exec $pager or ::fatal "Can't run pager: $! ($pager)";
4516 sub format_svn_date {
4517 return strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)", localtime(shift));
4520 sub parse_git_date {
4521 my ($t, $tz) = @_;
4522 # Date::Parse isn't in the standard Perl distro :(
4523 if ($tz =~ s/^\+//) {
4524 $t += tz_to_s_offset($tz);
4525 } elsif ($tz =~ s/^\-//) {
4526 $t -= tz_to_s_offset($tz);
4528 return $t;
4531 sub set_local_timezone {
4532 if (defined $TZ) {
4533 $ENV{TZ} = $TZ;
4534 } else {
4535 delete $ENV{TZ};
4539 sub tz_to_s_offset {
4540 my ($tz) = @_;
4541 $tz =~ s/(\d\d)$//;
4542 return ($1 * 60) + ($tz * 3600);
4545 sub get_author_info {
4546 my ($dest, $author, $t, $tz) = @_;
4547 $author =~ s/(?:^\s*|\s*$)//g;
4548 $dest->{a_raw} = $author;
4549 my $au;
4550 if ($::_authors) {
4551 $au = $rusers{$author} || undef;
4553 if (!$au) {
4554 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
4556 $dest->{t} = $t;
4557 $dest->{tz} = $tz;
4558 $dest->{a} = $au;
4559 $dest->{t_utc} = parse_git_date($t, $tz);
4562 sub process_commit {
4563 my ($c, $r_min, $r_max, $defer) = @_;
4564 if (defined $r_min && defined $r_max) {
4565 if ($r_min == $c->{r} && $r_min == $r_max) {
4566 show_commit($c);
4567 return 0;
4569 return 1 if $r_min == $r_max;
4570 if ($r_min < $r_max) {
4571 # we need to reverse the print order
4572 return 0 if (defined $limit && --$limit < 0);
4573 push @$defer, $c;
4574 return 1;
4576 if ($r_min != $r_max) {
4577 return 1 if ($r_min < $c->{r});
4578 return 1 if ($r_max > $c->{r});
4581 return 0 if (defined $limit && --$limit < 0);
4582 show_commit($c);
4583 return 1;
4586 sub show_commit {
4587 my $c = shift;
4588 if ($oneline) {
4589 my $x = "\n";
4590 if (my $l = $c->{l}) {
4591 while ($l->[0] =~ /^\s*$/) { shift @$l }
4592 $x = $l->[0];
4594 $l_fmt ||= 'A' . length($c->{r});
4595 print 'r',pack($l_fmt, $c->{r}),' | ';
4596 print "$c->{c} | " if $show_commit;
4597 print $x;
4598 } else {
4599 show_commit_normal($c);
4603 sub show_commit_changed_paths {
4604 my ($c) = @_;
4605 return unless $c->{changed};
4606 print "Changed paths:\n", @{$c->{changed}};
4609 sub show_commit_normal {
4610 my ($c) = @_;
4611 print commit_log_separator, "r$c->{r} | ";
4612 print "$c->{c} | " if $show_commit;
4613 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
4614 my $nr_line = 0;
4616 if (my $l = $c->{l}) {
4617 while ($l->[$#$l] eq "\n" && $#$l > 0
4618 && $l->[($#$l - 1)] eq "\n") {
4619 pop @$l;
4621 $nr_line = scalar @$l;
4622 if (!$nr_line) {
4623 print "1 line\n\n\n";
4624 } else {
4625 if ($nr_line == 1) {
4626 $nr_line = '1 line';
4627 } else {
4628 $nr_line .= ' lines';
4630 print $nr_line, "\n";
4631 show_commit_changed_paths($c);
4632 print "\n";
4633 print $_ foreach @$l;
4635 } else {
4636 print "1 line\n";
4637 show_commit_changed_paths($c);
4638 print "\n";
4641 foreach my $x (qw/raw stat diff/) {
4642 if ($c->{$x}) {
4643 print "\n";
4644 print $_ foreach @{$c->{$x}}
4649 sub cmd_show_log {
4650 my (@args) = @_;
4651 my ($r_min, $r_max);
4652 my $r_last = -1; # prevent dupes
4653 set_local_timezone();
4654 if (defined $::_revision) {
4655 if ($::_revision =~ /^(\d+):(\d+)$/) {
4656 ($r_min, $r_max) = ($1, $2);
4657 } elsif ($::_revision =~ /^\d+$/) {
4658 $r_min = $r_max = $::_revision;
4659 } else {
4660 ::fatal "-r$::_revision is not supported, use ",
4661 "standard 'git log' arguments instead";
4665 config_pager();
4666 @args = git_svn_log_cmd($r_min, $r_max, @args);
4667 if (!@args) {
4668 print commit_log_separator unless $incremental || $oneline;
4669 return;
4671 my $log = command_output_pipe(@args);
4672 run_pager();
4673 my (@k, $c, $d, $stat);
4674 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
4675 while (<$log>) {
4676 if (/^${esc_color}commit -?($::sha1_short)/o) {
4677 my $cmt = $1;
4678 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
4679 $r_last = $c->{r};
4680 process_commit($c, $r_min, $r_max, \@k) or
4681 goto out;
4683 $d = undef;
4684 $c = { c => $cmt };
4685 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
4686 get_author_info($c, $1, $2, $3);
4687 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
4688 # ignore
4689 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
4690 push @{$c->{raw}}, $_;
4691 } elsif (/^${esc_color}[ACRMDT]\t/) {
4692 # we could add $SVN->{svn_path} here, but that requires
4693 # remote access at the moment (repo_path_split)...
4694 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
4695 push @{$c->{changed}}, $_;
4696 } elsif (/^${esc_color}diff /o) {
4697 $d = 1;
4698 push @{$c->{diff}}, $_;
4699 } elsif ($d) {
4700 push @{$c->{diff}}, $_;
4701 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
4702 $esc_color*[\+\-]*$esc_color$/x) {
4703 $stat = 1;
4704 push @{$c->{stat}}, $_;
4705 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
4706 push @{$c->{stat}}, $_;
4707 $stat = undef;
4708 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
4709 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
4710 } elsif (s/^${esc_color} //o) {
4711 push @{$c->{l}}, $_;
4714 if ($c && defined $c->{r} && $c->{r} != $r_last) {
4715 $r_last = $c->{r};
4716 process_commit($c, $r_min, $r_max, \@k);
4718 if (@k) {
4719 ($r_min, $r_max) = ($r_max, $r_min);
4720 process_commit($_, $r_min, $r_max) foreach reverse @k;
4722 out:
4723 close $log;
4724 print commit_log_separator unless $incremental || $oneline;
4727 sub cmd_blame {
4728 my $path = pop;
4730 config_pager();
4731 run_pager();
4733 my ($fh, $ctx, $rev);
4735 if ($_git_format) {
4736 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
4737 while (my $line = <$fh>) {
4738 if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
4739 # Uncommitted edits show up as a rev ID of
4740 # all zeros, which we can't look up with
4741 # cmt_metadata
4742 if ($1 !~ /^0+$/) {
4743 (undef, $rev, undef) =
4744 ::cmt_metadata($1);
4745 $rev = '0' if (!$rev);
4746 } else {
4747 $rev = '0';
4749 $rev = sprintf('%-10s', $rev);
4750 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
4752 print $line;
4754 } else {
4755 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
4756 '--', $path);
4757 my ($sha1);
4758 my %authors;
4759 while (my $line = <$fh>) {
4760 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
4761 $sha1 = $1;
4762 (undef, $rev, undef) = ::cmt_metadata($1);
4763 $rev = '0' if (!$rev);
4765 elsif ($line =~ /^author (.*)/) {
4766 $authors{$rev} = $1;
4767 $authors{$rev} =~ s/\s/_/g;
4769 elsif ($line =~ /^\t(.*)$/) {
4770 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
4774 command_close_pipe($fh, $ctx);
4777 package Git::SVN::Migration;
4778 # these version numbers do NOT correspond to actual version numbers
4779 # of git nor git-svn. They are just relative.
4781 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
4783 # v1 layout: .git/$id/info/url, refs/remotes/$id
4785 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
4787 # v3 layout: .git/svn/$id, refs/remotes/$id
4788 # - info/url may remain for backwards compatibility
4789 # - this is what we migrate up to this layout automatically,
4790 # - this will be used by git svn init on single branches
4791 # v3.1 layout (auto migrated):
4792 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
4793 # for backwards compatibility
4795 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
4796 # - this is only created for newly multi-init-ed
4797 # repositories. Similar in spirit to the
4798 # --use-separate-remotes option in git-clone (now default)
4799 # - we do not automatically migrate to this (following
4800 # the example set by core git)
4802 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
4803 # - newer, more-efficient format that uses 24-bytes per record
4804 # with no filler space.
4805 # - use xxd -c24 < .rev_map.$UUID to view and debug
4806 # - This is a one-way migration, repositories updated to the
4807 # new format will not be able to use old git-svn without
4808 # rebuilding the .rev_db. Rebuilding the rev_db is not
4809 # possible if noMetadata or useSvmProps are set; but should
4810 # be no problem for users that use the (sensible) defaults.
4811 use strict;
4812 use warnings;
4813 use Carp qw/croak/;
4814 use File::Path qw/mkpath/;
4815 use File::Basename qw/dirname basename/;
4816 use vars qw/$_minimize/;
4818 sub migrate_from_v0 {
4819 my $git_dir = $ENV{GIT_DIR};
4820 return undef unless -d $git_dir;
4821 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
4822 my $migrated = 0;
4823 while (<$fh>) {
4824 chomp;
4825 my ($id, $orig_ref) = ($_, $_);
4826 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
4827 next unless -f "$git_dir/$id/info/url";
4828 my $new_ref = "refs/remotes/$id";
4829 if (::verify_ref("$new_ref^0")) {
4830 print STDERR "W: $orig_ref is probably an old ",
4831 "branch used by an ancient version of ",
4832 "git-svn.\n",
4833 "However, $new_ref also exists.\n",
4834 "We will not be able ",
4835 "to use this branch until this ",
4836 "ambiguity is resolved.\n";
4837 next;
4839 print STDERR "Migrating from v0 layout...\n" if !$migrated;
4840 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
4841 command_noisy('update-ref', $new_ref, $orig_ref);
4842 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
4843 $migrated++;
4845 command_close_pipe($fh, $ctx);
4846 print STDERR "Done migrating from v0 layout...\n" if $migrated;
4847 $migrated;
4850 sub migrate_from_v1 {
4851 my $git_dir = $ENV{GIT_DIR};
4852 my $migrated = 0;
4853 return $migrated unless -d $git_dir;
4854 my $svn_dir = "$git_dir/svn";
4856 # just in case somebody used 'svn' as their $id at some point...
4857 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
4859 print STDERR "Migrating from a git-svn v1 layout...\n";
4860 mkpath([$svn_dir]);
4861 print STDERR "Data from a previous version of git-svn exists, but\n\t",
4862 "$svn_dir\n\t(required for this version ",
4863 "($::VERSION) of git-svn) does not exist.\n";
4864 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
4865 while (<$fh>) {
4866 my $x = $_;
4867 next unless $x =~ s#^refs/remotes/##;
4868 chomp $x;
4869 next unless -f "$git_dir/$x/info/url";
4870 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
4871 next unless $u;
4872 my $dn = dirname("$git_dir/svn/$x");
4873 mkpath([$dn]) unless -d $dn;
4874 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
4875 mkpath(["$git_dir/svn/svn"]);
4876 print STDERR " - $git_dir/$x/info => ",
4877 "$git_dir/svn/$x/info\n";
4878 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
4879 croak "$!: $x";
4880 # don't worry too much about these, they probably
4881 # don't exist with repos this old (save for index,
4882 # and we can easily regenerate that)
4883 foreach my $f (qw/unhandled.log index .rev_db/) {
4884 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
4886 } else {
4887 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
4888 rename "$git_dir/$x", "$git_dir/svn/$x" or
4889 croak "$!: $x";
4891 $migrated++;
4893 command_close_pipe($fh, $ctx);
4894 print STDERR "Done migrating from a git-svn v1 layout\n";
4895 $migrated;
4898 sub read_old_urls {
4899 my ($l_map, $pfx, $path) = @_;
4900 my @dir;
4901 foreach (<$path/*>) {
4902 if (-r "$_/info/url") {
4903 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
4904 my $ref_id = $pfx . basename $_;
4905 my $url = ::file_to_s("$_/info/url");
4906 $l_map->{$ref_id} = $url;
4907 } elsif (-d $_) {
4908 push @dir, $_;
4911 foreach (@dir) {
4912 my $x = $_;
4913 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
4914 read_old_urls($l_map, $x, $_);
4918 sub migrate_from_v2 {
4919 my @cfg = command(qw/config -l/);
4920 return if grep /^svn-remote\..+\.url=/, @cfg;
4921 my %l_map;
4922 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
4923 my $migrated = 0;
4925 foreach my $ref_id (sort keys %l_map) {
4926 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
4927 if ($@) {
4928 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
4930 $migrated++;
4932 $migrated;
4935 sub minimize_connections {
4936 my $r = Git::SVN::read_all_remotes();
4937 my $new_urls = {};
4938 my $root_repos = {};
4939 foreach my $repo_id (keys %$r) {
4940 my $url = $r->{$repo_id}->{url} or next;
4941 my $fetch = $r->{$repo_id}->{fetch} or next;
4942 my $ra = Git::SVN::Ra->new($url);
4944 # skip existing cases where we already connect to the root
4945 if (($ra->{url} eq $ra->{repos_root}) ||
4946 ($ra->{repos_root} eq $repo_id)) {
4947 $root_repos->{$ra->{url}} = $repo_id;
4948 next;
4951 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
4952 my $root_path = $ra->{url};
4953 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
4954 foreach my $path (keys %$fetch) {
4955 my $ref_id = $fetch->{$path};
4956 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
4958 # make sure we can read when connecting to
4959 # a higher level of a repository
4960 my ($last_rev, undef) = $gs->last_rev_commit;
4961 if (!defined $last_rev) {
4962 $last_rev = eval {
4963 $root_ra->get_latest_revnum;
4965 next if $@;
4967 my $new = $root_path;
4968 $new .= length $path ? "/$path" : '';
4969 eval {
4970 $root_ra->get_log([$new], $last_rev, $last_rev,
4971 0, 0, 1, sub { });
4973 next if $@;
4974 $new_urls->{$ra->{repos_root}}->{$new} =
4975 { ref_id => $ref_id,
4976 old_repo_id => $repo_id,
4977 old_path => $path };
4981 my @emptied;
4982 foreach my $url (keys %$new_urls) {
4983 # see if we can re-use an existing [svn-remote "repo_id"]
4984 # instead of creating a(n ugly) new section:
4985 my $repo_id = $root_repos->{$url} || $url;
4987 my $fetch = $new_urls->{$url};
4988 foreach my $path (keys %$fetch) {
4989 my $x = $fetch->{$path};
4990 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
4991 my $pfx = "svn-remote.$x->{old_repo_id}";
4993 my $old_fetch = quotemeta("$x->{old_path}:".
4994 "refs/remotes/$x->{ref_id}");
4995 command_noisy(qw/config --unset/,
4996 "$pfx.fetch", '^'. $old_fetch . '$');
4997 delete $r->{$x->{old_repo_id}}->
4998 {fetch}->{$x->{old_path}};
4999 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
5000 command_noisy(qw/config --unset/,
5001 "$pfx.url");
5002 push @emptied, $x->{old_repo_id}
5006 if (@emptied) {
5007 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
5008 "$ENV{GIT_DIR}/config";
5009 print STDERR <<EOF;
5010 The following [svn-remote] sections in your config file ($file) are empty
5011 and can be safely removed:
5013 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
5017 sub migration_check {
5018 migrate_from_v0();
5019 migrate_from_v1();
5020 migrate_from_v2();
5021 minimize_connections() if $_minimize;
5024 package Git::IndexInfo;
5025 use strict;
5026 use warnings;
5027 use Git qw/command_input_pipe command_close_pipe/;
5029 sub new {
5030 my ($class) = @_;
5031 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
5032 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
5035 sub remove {
5036 my ($self, $path) = @_;
5037 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
5038 return ++$self->{nr};
5040 undef;
5043 sub update {
5044 my ($self, $mode, $hash, $path) = @_;
5045 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
5046 return ++$self->{nr};
5048 undef;
5051 sub DESTROY {
5052 my ($self) = @_;
5053 command_close_pipe($self->{gui}, $self->{ctx});
5056 package Git::SVN::GlobSpec;
5057 use strict;
5058 use warnings;
5060 sub new {
5061 my ($class, $glob) = @_;
5062 my $re = $glob;
5063 $re =~ s!/+$!!g; # no need for trailing slashes
5064 $re =~ m!^([^*]*)(\*(?:/\*)*)([^*]*)$!;
5065 my $temp = $re;
5066 my ($left, $right) = ($1, $3);
5067 $re = $2;
5068 my $depth = $re =~ tr/*/*/;
5069 if ($depth != $temp =~ tr/*/*/) {
5070 die "Only one set of wildcard directories " .
5071 "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
5073 if ($depth == 0) {
5074 die "One '*' is needed for glob: '$glob'\n";
5076 $re =~ s!\*!\[^/\]*!g;
5077 $re = quotemeta($left) . "($re)" . quotemeta($right);
5078 if (length $left && !($left =~ s!/+$!!g)) {
5079 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
5081 if (length $right && !($right =~ s!^/+!!g)) {
5082 die "Missing leading '/' on right side of: '$glob' ($right)\n";
5084 my $left_re = qr/^\/\Q$left\E(\/|$)/;
5085 bless { left => $left, right => $right, left_regex => $left_re,
5086 regex => qr/$re/, glob => $glob, depth => $depth }, $class;
5089 sub full_path {
5090 my ($self, $path) = @_;
5091 return (length $self->{left} ? "$self->{left}/" : '') .
5092 $path . (length $self->{right} ? "/$self->{right}" : '');
5095 __END__
5097 Data structures:
5100 $remotes = { # returned by read_all_remotes()
5101 'svn' => {
5102 # svn-remote.svn.url=https://svn.musicpd.org
5103 url => 'https://svn.musicpd.org',
5104 # svn-remote.svn.fetch=mpd/trunk:trunk
5105 fetch => {
5106 'mpd/trunk' => 'trunk',
5108 # svn-remote.svn.tags=mpd/tags/*:tags/*
5109 tags => {
5110 path => {
5111 left => 'mpd/tags',
5112 right => '',
5113 regex => qr!mpd/tags/([^/]+)$!,
5114 glob => 'tags/*',
5116 ref => {
5117 left => 'tags',
5118 right => '',
5119 regex => qr!tags/([^/]+)$!,
5120 glob => 'tags/*',
5126 $log_entry hashref as returned by libsvn_log_entry()
5128 log => 'whitespace-formatted log entry
5129 ', # trailing newline is preserved
5130 revision => '8', # integer
5131 date => '2004-02-24T17:01:44.108345Z', # commit date
5132 author => 'committer name'
5136 # this is generated by generate_diff();
5137 @mods = array of diff-index line hashes, each element represents one line
5138 of diff-index output
5140 diff-index line ($m hash)
5142 mode_a => first column of diff-index output, no leading ':',
5143 mode_b => second column of diff-index output,
5144 sha1_b => sha1sum of the final blob,
5145 chg => change type [MCRADT],
5146 file_a => original file name of a file (iff chg is 'C' or 'R')
5147 file_b => new/current file name of a file (any chg)
5151 # retval of read_url_paths{,_all}();
5152 $l_map = {
5153 # repository root url
5154 'https://svn.musicpd.org' => {
5155 # repository path # GIT_SVN_ID
5156 'mpd/trunk' => 'trunk',
5157 'mpd/tags/0.11.5' => 'tags/0.11.5',
5161 Notes:
5162 I don't trust the each() function on unless I created %hash myself
5163 because the internal iterator may not have started at base.