builtin-rm: Add a --force flag
[git/git-p4.git] / git-svn.perl
blob4dc33801a88c63f62a263b5008649b05fc1b9d7d
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);
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 'set-tree' => [ \&cmd_set_tree,
135 "Set an SVN repository to a git tree-ish",
136 { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
137 'create-ignore' => [ \&cmd_create_ignore,
138 'Create a .gitignore per svn:ignore',
139 { 'revision|r=i' => \$_revision
140 } ],
141 'propget' => [ \&cmd_propget,
142 'Print the value of a property on a file or directory',
143 { 'revision|r=i' => \$_revision } ],
144 'proplist' => [ \&cmd_proplist,
145 'List all properties of a file or directory',
146 { 'revision|r=i' => \$_revision } ],
147 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
148 { 'revision|r=i' => \$_revision
149 } ],
150 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
151 { 'revision|r=i' => \$_revision
152 } ],
153 'multi-fetch' => [ \&cmd_multi_fetch,
154 "Deprecated alias for $0 fetch --all",
155 { 'revision|r=s' => \$_revision, %fc_opts } ],
156 'migrate' => [ sub { },
157 # no-op, we automatically run this anyways,
158 'Migrate configuration/metadata/layout from
159 previous versions of git-svn',
160 { 'minimize' => \$Git::SVN::Migration::_minimize,
161 %remote_opts } ],
162 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
163 { 'limit=i' => \$Git::SVN::Log::limit,
164 'revision|r=s' => \$_revision,
165 'verbose|v' => \$Git::SVN::Log::verbose,
166 'incremental' => \$Git::SVN::Log::incremental,
167 'oneline' => \$Git::SVN::Log::oneline,
168 'show-commit' => \$Git::SVN::Log::show_commit,
169 'non-recursive' => \$Git::SVN::Log::non_recursive,
170 'authors-file|A=s' => \$_authors,
171 'color' => \$Git::SVN::Log::color,
172 'pager=s' => \$Git::SVN::Log::pager
173 } ],
174 'find-rev' => [ \&cmd_find_rev,
175 "Translate between SVN revision numbers and tree-ish",
176 {} ],
177 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
178 { 'merge|m|M' => \$_merge,
179 'verbose|v' => \$_verbose,
180 'strategy|s=s' => \$_strategy,
181 'local|l' => \$_local,
182 'fetch-all|all' => \$_fetch_all,
183 'dry-run|n' => \$_dry_run,
184 %fc_opts } ],
185 'commit-diff' => [ \&cmd_commit_diff,
186 'Commit a diff between two trees',
187 { 'message|m=s' => \$_message,
188 'file|F=s' => \$_file,
189 'revision|r=s' => \$_revision,
190 %cmt_opts } ],
191 'info' => [ \&cmd_info,
192 "Show info about the latest SVN revision
193 on the current branch",
194 { 'url' => \$_url, } ],
195 'blame' => [ \&Git::SVN::Log::cmd_blame,
196 "Show what revision and author last modified each line of a file",
197 { 'git-format' => \$_git_format } ],
200 my $cmd;
201 for (my $i = 0; $i < @ARGV; $i++) {
202 if (defined $cmd{$ARGV[$i]}) {
203 $cmd = $ARGV[$i];
204 splice @ARGV, $i, 1;
205 last;
209 # make sure we're always running at the top-level working directory
210 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
211 unless (-d $ENV{GIT_DIR}) {
212 if ($git_dir_user_set) {
213 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
214 "but it is not a directory\n";
216 my $git_dir = delete $ENV{GIT_DIR};
217 chomp(my $cdup = command_oneline(qw/rev-parse --show-cdup/));
218 unless (length $cdup) {
219 die "Already at toplevel, but $git_dir ",
220 "not found '$cdup'\n";
222 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
223 unless (-d $git_dir) {
224 die "$git_dir still not found after going to ",
225 "'$cdup'\n";
227 $ENV{GIT_DIR} = $git_dir;
229 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
232 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
234 read_repo_config(\%opts);
235 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
236 Getopt::Long::Configure('pass_through');
238 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
239 'minimize-connections' => \$Git::SVN::Migration::_minimize,
240 'id|i=s' => \$Git::SVN::default_ref_id,
241 'svn-remote|remote|R=s' => sub {
242 $Git::SVN::no_reuse_existing = 1;
243 $Git::SVN::default_repo_id = $_[1] });
244 exit 1 if (!$rv && $cmd && $cmd ne 'log');
246 usage(0) if $_help;
247 version() if $_version;
248 usage(1) unless defined $cmd;
249 load_authors() if $_authors;
251 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
252 Git::SVN::Migration::migration_check();
254 Git::SVN::init_vars();
255 eval {
256 Git::SVN::verify_remotes_sanity();
257 $cmd{$cmd}->[0]->(@ARGV);
259 fatal $@ if $@;
260 post_fetch_checkout();
261 exit 0;
263 ####################### primary functions ######################
264 sub usage {
265 my $exit = shift || 0;
266 my $fd = $exit ? \*STDERR : \*STDOUT;
267 print $fd <<"";
268 git-svn - bidirectional operations between a single Subversion tree and git
269 Usage: git svn <command> [options] [arguments]\n
271 print $fd "Available commands:\n" unless $cmd;
273 foreach (sort keys %cmd) {
274 next if $cmd && $cmd ne $_;
275 next if /^multi-/; # don't show deprecated commands
276 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
277 foreach (sort keys %{$cmd{$_}->[2]}) {
278 # mixed-case options are for .git/config only
279 next if /[A-Z]/ && /^[a-z]+$/i;
280 # prints out arguments as they should be passed:
281 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
282 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
283 "--$_" : "-$_" }
284 split /\|/,$_)," $x\n";
287 print $fd <<"";
288 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
289 arbitrary identifier if you're tracking multiple SVN branches/repositories in
290 one git repository and want to keep them separate. See git-svn(1) for more
291 information.
293 exit $exit;
296 sub version {
297 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
298 exit 0;
301 sub do_git_init_db {
302 unless (-d $ENV{GIT_DIR}) {
303 my @init_db = ('init');
304 push @init_db, "--template=$_template" if defined $_template;
305 if (defined $_shared) {
306 if ($_shared =~ /[a-z]/) {
307 push @init_db, "--shared=$_shared";
308 } else {
309 push @init_db, "--shared";
312 command_noisy(@init_db);
313 $_repository = Git->repository(Repository => ".git");
315 my $set;
316 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
317 foreach my $i (keys %icv) {
318 die "'$set' and '$i' cannot both be set\n" if $set;
319 next unless defined $icv{$i};
320 command_noisy('config', "$pfx.$i", $icv{$i});
321 $set = $i;
325 sub init_subdir {
326 my $repo_path = shift or return;
327 mkpath([$repo_path]) unless -d $repo_path;
328 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
329 $ENV{GIT_DIR} = '.git';
330 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
333 sub cmd_clone {
334 my ($url, $path) = @_;
335 if (!defined $path &&
336 (defined $_trunk || defined $_branches || defined $_tags ||
337 defined $_stdlayout) &&
338 $url !~ m#^[a-z\+]+://#) {
339 $path = $url;
341 $path = basename($url) if !defined $path || !length $path;
342 cmd_init($url, $path);
343 Git::SVN::fetch_all($Git::SVN::default_repo_id);
346 sub cmd_init {
347 if (defined $_stdlayout) {
348 $_trunk = 'trunk' if (!defined $_trunk);
349 $_tags = 'tags' if (!defined $_tags);
350 $_branches = 'branches' if (!defined $_branches);
352 if (defined $_trunk || defined $_branches || defined $_tags) {
353 return cmd_multi_init(@_);
355 my $url = shift or die "SVN repository location required ",
356 "as a command-line argument\n";
357 init_subdir(@_);
358 do_git_init_db();
360 Git::SVN->init($url);
363 sub cmd_fetch {
364 if (grep /^\d+=./, @_) {
365 die "'<rev>=<commit>' fetch arguments are ",
366 "no longer supported.\n";
368 my ($remote) = @_;
369 if (@_ > 1) {
370 die "Usage: $0 fetch [--all] [svn-remote]\n";
372 $remote ||= $Git::SVN::default_repo_id;
373 if ($_fetch_all) {
374 cmd_multi_fetch();
375 } else {
376 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
380 sub cmd_set_tree {
381 my (@commits) = @_;
382 if ($_stdin || !@commits) {
383 print "Reading from stdin...\n";
384 @commits = ();
385 while (<STDIN>) {
386 if (/\b($sha1_short)\b/o) {
387 unshift @commits, $1;
391 my @revs;
392 foreach my $c (@commits) {
393 my @tmp = command('rev-parse',$c);
394 if (scalar @tmp == 1) {
395 push @revs, $tmp[0];
396 } elsif (scalar @tmp > 1) {
397 push @revs, reverse(command('rev-list',@tmp));
398 } else {
399 fatal "Failed to rev-parse $c";
402 my $gs = Git::SVN->new;
403 my ($r_last, $cmt_last) = $gs->last_rev_commit;
404 $gs->fetch;
405 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
406 fatal "There are new revisions that were fetched ",
407 "and need to be merged (or acknowledged) ",
408 "before committing.\nlast rev: $r_last\n",
409 " current: $gs->{last_rev}";
411 $gs->set_tree($_) foreach @revs;
412 print "Done committing ",scalar @revs," revisions to SVN\n";
413 unlink $gs->{index};
416 sub cmd_dcommit {
417 my $head = shift;
418 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
419 'Cannot dcommit with a dirty index. Commit your changes first, '
420 . "or stash them with `git stash'.\n";
421 $head ||= 'HEAD';
422 my @refs;
423 my ($url, $rev, $uuid, $gs) = working_head_info($head, \@refs);
424 $url = $_commit_url if defined $_commit_url;
425 my $last_rev = $_revision if defined $_revision;
426 if ($url) {
427 print "Committing to $url ...\n";
429 unless ($gs) {
430 die "Unable to determine upstream SVN information from ",
431 "$head history.\nPerhaps the repository is empty.";
433 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
434 if ($_no_rebase && scalar(@$linear_refs) > 1) {
435 warn "Attempting to commit more than one change while ",
436 "--no-rebase is enabled.\n",
437 "If these changes depend on each other, re-running ",
438 "without --no-rebase may be required."
440 while (1) {
441 my $d = shift @$linear_refs or last;
442 unless (defined $last_rev) {
443 (undef, $last_rev, undef) = cmt_metadata("$d~1");
444 unless (defined $last_rev) {
445 fatal "Unable to extract revision information ",
446 "from commit $d~1";
449 if ($_dry_run) {
450 print "diff-tree $d~1 $d\n";
451 } else {
452 my $cmt_rev;
453 my %ed_opts = ( r => $last_rev,
454 log => get_commit_entry($d)->{log},
455 ra => Git::SVN::Ra->new($url),
456 config => SVN::Core::config_get_config(
457 $Git::SVN::Ra::config_dir
459 tree_a => "$d~1",
460 tree_b => $d,
461 editor_cb => sub {
462 print "Committed r$_[0]\n";
463 $cmt_rev = $_[0];
465 svn_path => '');
466 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
467 print "No changes\n$d~1 == $d\n";
468 } elsif ($parents->{$d} && @{$parents->{$d}}) {
469 $gs->{inject_parents_dcommit}->{$cmt_rev} =
470 $parents->{$d};
472 $_fetch_all ? $gs->fetch_all : $gs->fetch;
473 $last_rev = $cmt_rev;
474 next if $_no_rebase;
476 # we always want to rebase against the current HEAD,
477 # not any head that was passed to us
478 my @diff = command('diff-tree', $d,
479 $gs->refname, '--');
480 my @finish;
481 if (@diff) {
482 @finish = rebase_cmd();
483 print STDERR "W: $d and ", $gs->refname,
484 " differ, using @finish:\n",
485 join("\n", @diff), "\n";
486 } else {
487 print "No changes between current HEAD and ",
488 $gs->refname,
489 "\nResetting to the latest ",
490 $gs->refname, "\n";
491 @finish = qw/reset --mixed/;
493 command_noisy(@finish, $gs->refname);
494 if (@diff) {
495 @refs = ();
496 my ($url_, $rev_, $uuid_, $gs_) =
497 working_head_info($head, \@refs);
498 my ($linear_refs_, $parents_) =
499 linearize_history($gs_, \@refs);
500 if (scalar(@$linear_refs) !=
501 scalar(@$linear_refs_)) {
502 fatal "# of revisions changed ",
503 "\nbefore:\n",
504 join("\n", @$linear_refs),
505 "\n\nafter:\n",
506 join("\n", @$linear_refs_), "\n",
507 'If you are attempting to commit ',
508 "merges, try running:\n\t",
509 'git rebase --interactive',
510 '--preserve-merges ',
511 $gs->refname,
512 "\nBefore dcommitting";
514 if ($url_ ne $url) {
515 fatal "URL mismatch after rebase: ",
516 "$url_ != $url";
518 if ($uuid_ ne $uuid) {
519 fatal "uuid mismatch after rebase: ",
520 "$uuid_ != $uuid";
522 # remap parents
523 my (%p, @l, $i);
524 for ($i = 0; $i < scalar @$linear_refs; $i++) {
525 my $new = $linear_refs_->[$i] or next;
526 $p{$new} =
527 $parents->{$linear_refs->[$i]};
528 push @l, $new;
530 $parents = \%p;
531 $linear_refs = \@l;
535 unlink $gs->{index};
538 sub cmd_find_rev {
539 my $revision_or_hash = shift or die "SVN or git revision required ",
540 "as a command-line argument\n";
541 my $result;
542 if ($revision_or_hash =~ /^r\d+$/) {
543 my $head = shift;
544 $head ||= 'HEAD';
545 my @refs;
546 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
547 unless ($gs) {
548 die "Unable to determine upstream SVN information from ",
549 "$head history\n";
551 my $desired_revision = substr($revision_or_hash, 1);
552 $result = $gs->rev_map_get($desired_revision, $uuid);
553 } else {
554 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
555 $result = $rev;
557 print "$result\n" if $result;
560 sub cmd_rebase {
561 command_noisy(qw/update-index --refresh/);
562 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
563 unless ($gs) {
564 die "Unable to determine upstream SVN information from ",
565 "working tree history\n";
567 if ($_dry_run) {
568 print "Remote Branch: " . $gs->refname . "\n";
569 print "SVN URL: " . $url . "\n";
570 return;
572 if (command(qw/diff-index HEAD --/)) {
573 print STDERR "Cannot rebase with uncommited changes:\n";
574 command_noisy('status');
575 exit 1;
577 unless ($_local) {
578 # rebase will checkout for us, so no need to do it explicitly
579 $_no_checkout = 'true';
580 $_fetch_all ? $gs->fetch_all : $gs->fetch;
582 command_noisy(rebase_cmd(), $gs->refname);
585 sub cmd_show_ignore {
586 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
587 $gs ||= Git::SVN->new;
588 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
589 $gs->prop_walk($gs->{path}, $r, sub {
590 my ($gs, $path, $props) = @_;
591 print STDOUT "\n# $path\n";
592 my $s = $props->{'svn:ignore'} or return;
593 $s =~ s/[\r\n]+/\n/g;
594 chomp $s;
595 $s =~ s#^#$path#gm;
596 print STDOUT "$s\n";
600 sub cmd_show_externals {
601 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
602 $gs ||= Git::SVN->new;
603 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
604 $gs->prop_walk($gs->{path}, $r, sub {
605 my ($gs, $path, $props) = @_;
606 print STDOUT "\n# $path\n";
607 my $s = $props->{'svn:externals'} or return;
608 $s =~ s/[\r\n]+/\n/g;
609 chomp $s;
610 $s =~ s#^#$path#gm;
611 print STDOUT "$s\n";
615 sub cmd_create_ignore {
616 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
617 $gs ||= Git::SVN->new;
618 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
619 $gs->prop_walk($gs->{path}, $r, sub {
620 my ($gs, $path, $props) = @_;
621 # $path is of the form /path/to/dir/
622 my $ignore = '.' . $path . '.gitignore';
623 my $s = $props->{'svn:ignore'} or return;
624 open(GITIGNORE, '>', $ignore)
625 or fatal("Failed to open `$ignore' for writing: $!");
626 $s =~ s/[\r\n]+/\n/g;
627 chomp $s;
628 # Prefix all patterns so that the ignore doesn't apply
629 # to sub-directories.
630 $s =~ s#^#/#gm;
631 print GITIGNORE "$s\n";
632 close(GITIGNORE)
633 or fatal("Failed to close `$ignore': $!");
634 command_noisy('add', '-f', $ignore);
638 sub canonicalize_path {
639 my ($path) = @_;
640 my $dot_slash_added = 0;
641 if (substr($path, 0, 1) ne "/") {
642 $path = "./" . $path;
643 $dot_slash_added = 1;
645 # File::Spec->canonpath doesn't collapse x/../y into y (for a
646 # good reason), so let's do this manually.
647 $path =~ s#/+#/#g;
648 $path =~ s#/\.(?:/|$)#/#g;
649 $path =~ s#/[^/]+/\.\.##g;
650 $path =~ s#/$##g;
651 $path =~ s#^\./## if $dot_slash_added;
652 $path =~ s#^/##;
653 $path =~ s#^\.$##;
654 return $path;
657 # get_svnprops(PATH)
658 # ------------------
659 # Helper for cmd_propget and cmd_proplist below.
660 sub get_svnprops {
661 my $path = shift;
662 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
663 $gs ||= Git::SVN->new;
665 # prefix THE PATH by the sub-directory from which the user
666 # invoked us.
667 $path = $cmd_dir_prefix . $path;
668 fatal("No such file or directory: $path") unless -e $path;
669 my $is_dir = -d $path ? 1 : 0;
670 $path = $gs->{path} . '/' . $path;
672 # canonicalize the path (otherwise libsvn will abort or fail to
673 # find the file)
674 $path = canonicalize_path($path);
676 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
677 my $props;
678 if ($is_dir) {
679 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
681 else {
682 (undef, $props) = $gs->ra->get_file($path, $r, undef);
684 return $props;
687 # cmd_propget (PROP, PATH)
688 # ------------------------
689 # Print the SVN property PROP for PATH.
690 sub cmd_propget {
691 my ($prop, $path) = @_;
692 $path = '.' if not defined $path;
693 usage(1) if not defined $prop;
694 my $props = get_svnprops($path);
695 if (not defined $props->{$prop}) {
696 fatal("`$path' does not have a `$prop' SVN property.");
698 print $props->{$prop} . "\n";
701 # cmd_proplist (PATH)
702 # -------------------
703 # Print the list of SVN properties for PATH.
704 sub cmd_proplist {
705 my $path = shift;
706 $path = '.' if not defined $path;
707 my $props = get_svnprops($path);
708 print "Properties on '$path':\n";
709 foreach (sort keys %{$props}) {
710 print " $_\n";
714 sub cmd_multi_init {
715 my $url = shift;
716 unless (defined $_trunk || defined $_branches || defined $_tags) {
717 usage(1);
720 # there are currently some bugs that prevent multi-init/multi-fetch
721 # setups from working well without this.
722 $Git::SVN::_minimize_url = 1;
724 $_prefix = '' unless defined $_prefix;
725 if (defined $url) {
726 $url =~ s#/+$##;
727 init_subdir(@_);
729 do_git_init_db();
730 if (defined $_trunk) {
731 my $trunk_ref = $_prefix . 'trunk';
732 # try both old-style and new-style lookups:
733 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
734 unless ($gs_trunk) {
735 my ($trunk_url, $trunk_path) =
736 complete_svn_url($url, $_trunk);
737 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
738 undef, $trunk_ref);
741 return unless defined $_branches || defined $_tags;
742 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
743 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
744 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
747 sub cmd_multi_fetch {
748 my $remotes = Git::SVN::read_all_remotes();
749 foreach my $repo_id (sort keys %$remotes) {
750 if ($remotes->{$repo_id}->{url}) {
751 Git::SVN::fetch_all($repo_id, $remotes);
756 # this command is special because it requires no metadata
757 sub cmd_commit_diff {
758 my ($ta, $tb, $url) = @_;
759 my $usage = "Usage: $0 commit-diff -r<revision> ".
760 "<tree-ish> <tree-ish> [<URL>]";
761 fatal($usage) if (!defined $ta || !defined $tb);
762 my $svn_path = '';
763 if (!defined $url) {
764 my $gs = eval { Git::SVN->new };
765 if (!$gs) {
766 fatal("Needed URL or usable git-svn --id in ",
767 "the command-line\n", $usage);
769 $url = $gs->{url};
770 $svn_path = $gs->{path};
772 unless (defined $_revision) {
773 fatal("-r|--revision is a required argument\n", $usage);
775 if (defined $_message && defined $_file) {
776 fatal("Both --message/-m and --file/-F specified ",
777 "for the commit message.\n",
778 "I have no idea what you mean");
780 if (defined $_file) {
781 $_message = file_to_s($_file);
782 } else {
783 $_message ||= get_commit_entry($tb)->{log};
785 my $ra ||= Git::SVN::Ra->new($url);
786 my $r = $_revision;
787 if ($r eq 'HEAD') {
788 $r = $ra->get_latest_revnum;
789 } elsif ($r !~ /^\d+$/) {
790 die "revision argument: $r not understood by git-svn\n";
792 my %ed_opts = ( r => $r,
793 log => $_message,
794 ra => $ra,
795 tree_a => $ta,
796 tree_b => $tb,
797 editor_cb => sub { print "Committed r$_[0]\n" },
798 svn_path => $svn_path );
799 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
800 print "No changes\n$ta == $tb\n";
804 sub cmd_info {
805 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
806 if (exists $_[1]) {
807 die "Too many arguments specified\n";
810 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
812 if (!$file_type && !$diff_status) {
813 print STDERR "$path: (Not a versioned resource)\n\n";
814 return;
817 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
818 unless ($gs) {
819 die "Unable to determine upstream SVN information from ",
820 "working tree history\n";
823 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
824 $path = "." if $path eq "";
826 my $full_url = $url . ($path eq "." ? "" : "/$path");
828 if ($_url) {
829 print $full_url, "\n";
830 return;
833 my $result = "Path: $path\n";
834 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
835 $result .= "URL: " . $full_url . "\n";
837 eval {
838 my $repos_root = $gs->repos_root;
839 Git::SVN::remove_username($repos_root);
840 $result .= "Repository Root: $repos_root\n";
842 if ($@) {
843 $result .= "Repository Root: (offline)\n";
845 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A";
846 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
848 $result .= "Node Kind: " .
849 ($file_type eq "dir" ? "directory" : "file") . "\n";
851 my $schedule = $diff_status eq "A"
852 ? "add"
853 : ($diff_status eq "D" ? "delete" : "normal");
854 $result .= "Schedule: $schedule\n";
856 if ($diff_status eq "A") {
857 print $result, "\n";
858 return;
861 my ($lc_author, $lc_rev, $lc_date_utc);
862 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $path);
863 my $log = command_output_pipe(@args);
864 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
865 while (<$log>) {
866 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
867 $lc_author = $1;
868 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
869 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
870 (undef, $lc_rev, undef) = ::extract_metadata($1);
873 close $log;
875 Git::SVN::Log::set_local_timezone();
877 $result .= "Last Changed Author: $lc_author\n";
878 $result .= "Last Changed Rev: $lc_rev\n";
879 $result .= "Last Changed Date: " .
880 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
882 if ($file_type ne "dir") {
883 my $text_last_updated_date =
884 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
885 $result .=
886 "Text Last Updated: " .
887 Git::SVN::Log::format_svn_date($text_last_updated_date) .
888 "\n";
889 my $checksum;
890 if ($diff_status eq "D") {
891 my ($fh, $ctx) =
892 command_output_pipe(qw(cat-file blob), "HEAD:$path");
893 if ($file_type eq "link") {
894 my $file_name = <$fh>;
895 $checksum = md5sum("link $file_name");
896 } else {
897 $checksum = md5sum($fh);
899 command_close_pipe($fh, $ctx);
900 } elsif ($file_type eq "link") {
901 my $file_name =
902 command(qw(cat-file blob), "HEAD:$path");
903 $checksum =
904 md5sum("link " . $file_name);
905 } else {
906 open FILE, "<", $path or die $!;
907 $checksum = md5sum(\*FILE);
908 close FILE or die $!;
910 $result .= "Checksum: " . $checksum . "\n";
913 print $result, "\n";
916 ########################### utility functions #########################
918 sub rebase_cmd {
919 my @cmd = qw/rebase/;
920 push @cmd, '-v' if $_verbose;
921 push @cmd, qw/--merge/ if $_merge;
922 push @cmd, "--strategy=$_strategy" if $_strategy;
923 @cmd;
926 sub post_fetch_checkout {
927 return if $_no_checkout;
928 my $gs = $Git::SVN::_head or return;
929 return if verify_ref('refs/heads/master^0');
931 my $valid_head = verify_ref('HEAD^0');
932 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
933 return if ($valid_head || !verify_ref('HEAD^0'));
935 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
936 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
937 return if -f $index;
939 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
940 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
941 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
942 print STDERR "Checked out HEAD:\n ",
943 $gs->full_url, " r", $gs->last_rev, "\n";
946 sub complete_svn_url {
947 my ($url, $path) = @_;
948 $path =~ s#/+$##;
949 if ($path !~ m#^[a-z\+]+://#) {
950 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
951 fatal("E: '$path' is not a complete URL ",
952 "and a separate URL is not specified");
954 return ($url, $path);
956 return ($path, '');
959 sub complete_url_ls_init {
960 my ($ra, $repo_path, $switch, $pfx) = @_;
961 unless ($repo_path) {
962 print STDERR "W: $switch not specified\n";
963 return;
965 $repo_path =~ s#/+$##;
966 if ($repo_path =~ m#^[a-z\+]+://#) {
967 $ra = Git::SVN::Ra->new($repo_path);
968 $repo_path = '';
969 } else {
970 $repo_path =~ s#^/+##;
971 unless ($ra) {
972 fatal("E: '$repo_path' is not a complete URL ",
973 "and a separate URL is not specified");
976 my $url = $ra->{url};
977 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
978 my $k = "svn-remote.$gs->{repo_id}.url";
979 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
980 if ($orig_url && ($orig_url ne $gs->{url})) {
981 die "$k already set: $orig_url\n",
982 "wanted to set to: $gs->{url}\n";
984 command_oneline('config', $k, $gs->{url}) unless $orig_url;
985 my $remote_path = "$ra->{svn_path}/$repo_path";
986 $remote_path =~ s#/+#/#g;
987 $remote_path =~ s#^/##g;
988 $remote_path .= "/*" if $remote_path !~ /\*/;
989 my ($n) = ($switch =~ /^--(\w+)/);
990 if (length $pfx && $pfx !~ m#/$#) {
991 die "--prefix='$pfx' must have a trailing slash '/'\n";
993 command_noisy('config',
994 "svn-remote.$gs->{repo_id}.$n",
995 "$remote_path:refs/remotes/$pfx*" .
996 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
999 sub verify_ref {
1000 my ($ref) = @_;
1001 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1002 { STDERR => 0 }); };
1005 sub get_tree_from_treeish {
1006 my ($treeish) = @_;
1007 # $treeish can be a symbolic ref, too:
1008 my $type = command_oneline(qw/cat-file -t/, $treeish);
1009 my $expected;
1010 while ($type eq 'tag') {
1011 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1013 if ($type eq 'commit') {
1014 $expected = (grep /^tree /, command(qw/cat-file commit/,
1015 $treeish))[0];
1016 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1017 die "Unable to get tree from $treeish\n" unless $expected;
1018 } elsif ($type eq 'tree') {
1019 $expected = $treeish;
1020 } else {
1021 die "$treeish is a $type, expected tree, tag or commit\n";
1023 return $expected;
1026 sub get_commit_entry {
1027 my ($treeish) = shift;
1028 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1029 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1030 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1031 open my $log_fh, '>', $commit_editmsg or croak $!;
1033 my $type = command_oneline(qw/cat-file -t/, $treeish);
1034 if ($type eq 'commit' || $type eq 'tag') {
1035 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1036 $type, $treeish);
1037 my $in_msg = 0;
1038 my $author;
1039 my $saw_from = 0;
1040 my $msgbuf = "";
1041 while (<$msg_fh>) {
1042 if (!$in_msg) {
1043 $in_msg = 1 if (/^\s*$/);
1044 $author = $1 if (/^author (.*>)/);
1045 } elsif (/^git-svn-id: /) {
1046 # skip this for now, we regenerate the
1047 # correct one on re-fetch anyways
1048 # TODO: set *:merge properties or like...
1049 } else {
1050 if (/^From:/ || /^Signed-off-by:/) {
1051 $saw_from = 1;
1053 $msgbuf .= $_;
1056 $msgbuf =~ s/\s+$//s;
1057 if ($Git::SVN::_add_author_from && defined($author)
1058 && !$saw_from) {
1059 $msgbuf .= "\n\nFrom: $author";
1061 print $log_fh $msgbuf or croak $!;
1062 command_close_pipe($msg_fh, $ctx);
1064 close $log_fh or croak $!;
1066 if ($_edit || ($type eq 'tree')) {
1067 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1068 # TODO: strip out spaces, comments, like git-commit.sh
1069 system($editor, $commit_editmsg);
1071 rename $commit_editmsg, $commit_msg or croak $!;
1072 open $log_fh, '<', $commit_msg or croak $!;
1073 { local $/; chomp($log_entry{log} = <$log_fh>); }
1074 close $log_fh or croak $!;
1075 unlink $commit_msg;
1076 \%log_entry;
1079 sub s_to_file {
1080 my ($str, $file, $mode) = @_;
1081 open my $fd,'>',$file or croak $!;
1082 print $fd $str,"\n" or croak $!;
1083 close $fd or croak $!;
1084 chmod ($mode &~ umask, $file) if (defined $mode);
1087 sub file_to_s {
1088 my $file = shift;
1089 open my $fd,'<',$file or croak "$!: file: $file\n";
1090 local $/;
1091 my $ret = <$fd>;
1092 close $fd or croak $!;
1093 $ret =~ s/\s*$//s;
1094 return $ret;
1097 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1098 sub load_authors {
1099 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1100 my $log = $cmd eq 'log';
1101 while (<$authors>) {
1102 chomp;
1103 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1104 my ($user, $name, $email) = ($1, $2, $3);
1105 if ($log) {
1106 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1107 } else {
1108 $users{$user} = [$name, $email];
1111 close $authors or croak $!;
1114 # convert GetOpt::Long specs for use by git-config
1115 sub read_repo_config {
1116 return unless -d $ENV{GIT_DIR};
1117 my $opts = shift;
1118 my @config_only;
1119 foreach my $o (keys %$opts) {
1120 # if we have mixedCase and a long option-only, then
1121 # it's a config-only variable that we don't need for
1122 # the command-line.
1123 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1124 my $v = $opts->{$o};
1125 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1126 $key =~ s/-//g;
1127 my $arg = 'git-config';
1128 $arg .= ' --int' if ($o =~ /[:=]i$/);
1129 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1130 if (ref $v eq 'ARRAY') {
1131 chomp(my @tmp = `$arg --get-all svn.$key`);
1132 @$v = @tmp if @tmp;
1133 } else {
1134 chomp(my $tmp = `$arg --get svn.$key`);
1135 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1136 $$v = $tmp;
1140 delete @$opts{@config_only} if @config_only;
1143 sub extract_metadata {
1144 my $id = shift or return (undef, undef, undef);
1145 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1146 \s([a-f\d\-]+)$/x);
1147 if (!defined $rev || !$uuid || !$url) {
1148 # some of the original repositories I made had
1149 # identifiers like this:
1150 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
1152 return ($url, $rev, $uuid);
1155 sub cmt_metadata {
1156 return extract_metadata((grep(/^git-svn-id: /,
1157 command(qw/cat-file commit/, shift)))[-1]);
1160 sub working_head_info {
1161 my ($head, $refs) = @_;
1162 my @args = ('log', '--no-color', '--first-parent', '--pretty=medium');
1163 my ($fh, $ctx) = command_output_pipe(@args, $head);
1164 my $hash;
1165 my %max;
1166 while (<$fh>) {
1167 if ( m{^commit ($::sha1)$} ) {
1168 unshift @$refs, $hash if $hash and $refs;
1169 $hash = $1;
1170 next;
1172 next unless s{^\s*(git-svn-id:)}{$1};
1173 my ($url, $rev, $uuid) = extract_metadata($_);
1174 if (defined $url && defined $rev) {
1175 next if $max{$url} and $max{$url} < $rev;
1176 if (my $gs = Git::SVN->find_by_url($url)) {
1177 my $c = $gs->rev_map_get($rev, $uuid);
1178 if ($c && $c eq $hash) {
1179 close $fh; # break the pipe
1180 return ($url, $rev, $uuid, $gs);
1181 } else {
1182 $max{$url} ||= $gs->rev_map_max;
1187 command_close_pipe($fh, $ctx);
1188 (undef, undef, undef, undef);
1191 sub read_commit_parents {
1192 my ($parents, $c) = @_;
1193 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1194 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1195 @{$parents->{$c}} = split(/ /, $p);
1198 sub linearize_history {
1199 my ($gs, $refs) = @_;
1200 my %parents;
1201 foreach my $c (@$refs) {
1202 read_commit_parents(\%parents, $c);
1205 my @linear_refs;
1206 my %skip = ();
1207 my $last_svn_commit = $gs->last_commit;
1208 foreach my $c (reverse @$refs) {
1209 next if $c eq $last_svn_commit;
1210 last if $skip{$c};
1212 unshift @linear_refs, $c;
1213 $skip{$c} = 1;
1215 # we only want the first parent to diff against for linear
1216 # history, we save the rest to inject when we finalize the
1217 # svn commit
1218 my $fp_a = verify_ref("$c~1");
1219 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1220 if (!$fp_a || !$fp_b) {
1221 die "Commit $c\n",
1222 "has no parent commit, and therefore ",
1223 "nothing to diff against.\n",
1224 "You should be working from a repository ",
1225 "originally created by git-svn\n";
1227 if ($fp_a ne $fp_b) {
1228 die "$c~1 = $fp_a, however parsing commit $c ",
1229 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1232 foreach my $p (@{$parents{$c}}) {
1233 $skip{$p} = 1;
1236 (\@linear_refs, \%parents);
1239 sub find_file_type_and_diff_status {
1240 my ($path) = @_;
1241 return ('dir', '') if $path eq '';
1243 my $diff_output =
1244 command_oneline(qw(diff --cached --name-status --), $path) || "";
1245 my $diff_status = (split(' ', $diff_output))[0] || "";
1247 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1249 return (undef, undef) if !$diff_status && !$ls_tree;
1251 if ($diff_status eq "A") {
1252 return ("link", $diff_status) if -l $path;
1253 return ("dir", $diff_status) if -d $path;
1254 return ("file", $diff_status);
1257 my $mode = (split(' ', $ls_tree))[0] || "";
1259 return ("link", $diff_status) if $mode eq "120000";
1260 return ("dir", $diff_status) if $mode eq "040000";
1261 return ("file", $diff_status);
1264 sub md5sum {
1265 my $arg = shift;
1266 my $ref = ref $arg;
1267 my $md5 = Digest::MD5->new();
1268 if ($ref eq 'GLOB' || $ref eq 'IO::File') {
1269 $md5->addfile($arg) or croak $!;
1270 } elsif ($ref eq 'SCALAR') {
1271 $md5->add($$arg) or croak $!;
1272 } elsif (!$ref) {
1273 $md5->add($arg) or croak $!;
1274 } else {
1275 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1277 return $md5->hexdigest();
1280 package Git::SVN;
1281 use strict;
1282 use warnings;
1283 use Fcntl qw/:DEFAULT :seek/;
1284 use constant rev_map_fmt => 'NH40';
1285 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1286 $_repack $_repack_flags $_use_svm_props $_head
1287 $_use_svnsync_props $no_reuse_existing $_minimize_url
1288 $_use_log_author $_add_author_from/;
1289 use Carp qw/croak/;
1290 use File::Path qw/mkpath/;
1291 use File::Copy qw/copy/;
1292 use IPC::Open3;
1294 my ($_gc_nr, $_gc_period);
1296 # properties that we do not log:
1297 my %SKIP_PROP;
1298 BEGIN {
1299 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1300 svn:special svn:executable
1301 svn:entry:committed-rev
1302 svn:entry:last-author
1303 svn:entry:uuid
1304 svn:entry:committed-date/;
1306 # some options are read globally, but can be overridden locally
1307 # per [svn-remote "..."] section. Command-line options will *NOT*
1308 # override options set in an [svn-remote "..."] section
1309 no strict 'refs';
1310 for my $option (qw/follow_parent no_metadata use_svm_props
1311 use_svnsync_props/) {
1312 my $key = $option;
1313 $key =~ tr/_//d;
1314 my $prop = "-$option";
1315 *$option = sub {
1316 my ($self) = @_;
1317 return $self->{$prop} if exists $self->{$prop};
1318 my $k = "svn-remote.$self->{repo_id}.$key";
1319 eval { command_oneline(qw/config --get/, $k) };
1320 if ($@) {
1321 $self->{$prop} = ${"Git::SVN::_$option"};
1322 } else {
1323 my $v = command_oneline(qw/config --bool/,$k);
1324 $self->{$prop} = $v eq 'false' ? 0 : 1;
1326 return $self->{$prop};
1331 my (%LOCKFILES, %INDEX_FILES);
1332 END {
1333 unlink keys %LOCKFILES if %LOCKFILES;
1334 unlink keys %INDEX_FILES if %INDEX_FILES;
1337 sub resolve_local_globs {
1338 my ($url, $fetch, $glob_spec) = @_;
1339 return unless defined $glob_spec;
1340 my $ref = $glob_spec->{ref};
1341 my $path = $glob_spec->{path};
1342 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
1343 next unless m#^refs/remotes/$ref->{regex}$#;
1344 my $p = $1;
1345 my $pathname = desanitize_refname($path->full_path($p));
1346 my $refname = desanitize_refname($ref->full_path($p));
1347 if (my $existing = $fetch->{$pathname}) {
1348 if ($existing ne $refname) {
1349 die "Refspec conflict:\n",
1350 "existing: refs/remotes/$existing\n",
1351 " globbed: refs/remotes/$refname\n";
1353 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
1354 $u =~ s!^\Q$url\E(/|$)!! or die
1355 "refs/remotes/$refname: '$url' not found in '$u'\n";
1356 if ($pathname ne $u) {
1357 warn "W: Refspec glob conflict ",
1358 "(ref: refs/remotes/$refname):\n",
1359 "expected path: $pathname\n",
1360 " real path: $u\n",
1361 "Continuing ahead with $u\n";
1362 next;
1364 } else {
1365 $fetch->{$pathname} = $refname;
1370 sub parse_revision_argument {
1371 my ($base, $head) = @_;
1372 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1373 return ($base, $head);
1375 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1376 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1377 return ($head, $head) if ($::_revision eq 'HEAD');
1378 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1379 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1380 die "revision argument: $::_revision not understood by git-svn\n";
1383 sub fetch_all {
1384 my ($repo_id, $remotes) = @_;
1385 if (ref $repo_id) {
1386 my $gs = $repo_id;
1387 $repo_id = undef;
1388 $repo_id = $gs->{repo_id};
1390 $remotes ||= read_all_remotes();
1391 my $remote = $remotes->{$repo_id} or
1392 die "[svn-remote \"$repo_id\"] unknown\n";
1393 my $fetch = $remote->{fetch};
1394 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1395 my (@gs, @globs);
1396 my $ra = Git::SVN::Ra->new($url);
1397 my $uuid = $ra->get_uuid;
1398 my $head = $ra->get_latest_revnum;
1399 my $base = defined $fetch ? $head : 0;
1401 # read the max revs for wildcard expansion (branches/*, tags/*)
1402 foreach my $t (qw/branches tags/) {
1403 defined $remote->{$t} or next;
1404 push @globs, $remote->{$t};
1405 my $max_rev = eval { tmp_config(qw/--int --get/,
1406 "svn-remote.$repo_id.${t}-maxRev") };
1407 if (defined $max_rev && ($max_rev < $base)) {
1408 $base = $max_rev;
1409 } elsif (!defined $max_rev) {
1410 $base = 0;
1414 if ($fetch) {
1415 foreach my $p (sort keys %$fetch) {
1416 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1417 my $lr = $gs->rev_map_max;
1418 if (defined $lr) {
1419 $base = $lr if ($lr < $base);
1421 push @gs, $gs;
1425 ($base, $head) = parse_revision_argument($base, $head);
1426 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1429 sub read_all_remotes {
1430 my $r = {};
1431 my $use_svm_props = eval { command_oneline(qw/config --bool
1432 svn.useSvmProps/) };
1433 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
1434 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1435 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*(.+)\s*$!) {
1436 my ($remote, $local_ref, $_remote_ref) = ($1, $2, $3);
1437 die("svn-remote.$remote: remote ref '$_remote_ref' "
1438 . "must start with 'refs/remotes/'\n")
1439 unless $_remote_ref =~ m{^refs/remotes/(.+)};
1440 my $remote_ref = $1;
1441 $local_ref =~ s{^/}{};
1442 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1443 $r->{$remote}->{svm} = {} if $use_svm_props;
1444 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
1445 $r->{$1}->{svm} = {};
1446 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1447 $r->{$1}->{url} = $2;
1448 } elsif (m!^(.+)\.(branches|tags)=
1449 (.*):refs/remotes/(.+)\s*$/!x) {
1450 my ($p, $g) = ($3, $4);
1451 my $rs = $r->{$1}->{$2} = {
1452 t => $2,
1453 remote => $1,
1454 path => Git::SVN::GlobSpec->new($p),
1455 ref => Git::SVN::GlobSpec->new($g) };
1456 if (length($rs->{ref}->{right}) != 0) {
1457 die "The '*' glob character must be the last ",
1458 "character of '$g'\n";
1463 map {
1464 if (defined $r->{$_}->{svm}) {
1465 my $svm;
1466 eval {
1467 my $section = "svn-remote.$_";
1468 $svm = {
1469 source => tmp_config('--get',
1470 "$section.svm-source"),
1471 replace => tmp_config('--get',
1472 "$section.svm-replace"),
1475 $r->{$_}->{svm} = $svm;
1477 } keys %$r;
1482 sub init_vars {
1483 $_gc_nr = $_gc_period = 1000;
1484 if (defined $_repack || defined $_repack_flags) {
1485 warn "Repack options are obsolete; they have no effect.\n";
1489 sub verify_remotes_sanity {
1490 return unless -d $ENV{GIT_DIR};
1491 my %seen;
1492 foreach (command(qw/config -l/)) {
1493 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1494 if ($seen{$1}) {
1495 die "Remote ref refs/remote/$1 is tracked by",
1496 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1497 "Please resolve this ambiguity in ",
1498 "your git configuration file before ",
1499 "continuing\n";
1501 $seen{$1} = $_;
1506 sub find_existing_remote {
1507 my ($url, $remotes) = @_;
1508 return undef if $no_reuse_existing;
1509 my $existing;
1510 foreach my $repo_id (keys %$remotes) {
1511 my $u = $remotes->{$repo_id}->{url} or next;
1512 next if $u ne $url;
1513 $existing = $repo_id;
1514 last;
1516 $existing;
1519 sub init_remote_config {
1520 my ($self, $url, $no_write) = @_;
1521 $url =~ s!/+$!!; # strip trailing slash
1522 my $r = read_all_remotes();
1523 my $existing = find_existing_remote($url, $r);
1524 if ($existing) {
1525 unless ($no_write) {
1526 print STDERR "Using existing ",
1527 "[svn-remote \"$existing\"]\n";
1529 $self->{repo_id} = $existing;
1530 } elsif ($_minimize_url) {
1531 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1532 $existing = find_existing_remote($min_url, $r);
1533 if ($existing) {
1534 unless ($no_write) {
1535 print STDERR "Using existing ",
1536 "[svn-remote \"$existing\"]\n";
1538 $self->{repo_id} = $existing;
1540 if ($min_url ne $url) {
1541 unless ($no_write) {
1542 print STDERR "Using higher level of URL: ",
1543 "$url => $min_url\n";
1545 my $old_path = $self->{path};
1546 $self->{path} = $url;
1547 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1548 if (length $old_path) {
1549 $self->{path} .= "/$old_path";
1551 $url = $min_url;
1554 my $orig_url;
1555 if (!$existing) {
1556 # verify that we aren't overwriting anything:
1557 $orig_url = eval {
1558 command_oneline('config', '--get',
1559 "svn-remote.$self->{repo_id}.url")
1561 if ($orig_url && ($orig_url ne $url)) {
1562 die "svn-remote.$self->{repo_id}.url already set: ",
1563 "$orig_url\nwanted to set to: $url\n";
1566 my ($xrepo_id, $xpath) = find_ref($self->refname);
1567 if (defined $xpath) {
1568 die "svn-remote.$xrepo_id.fetch already set to track ",
1569 "$xpath:refs/remotes/", $self->refname, "\n";
1571 unless ($no_write) {
1572 command_noisy('config',
1573 "svn-remote.$self->{repo_id}.url", $url);
1574 $self->{path} =~ s{^/}{};
1575 command_noisy('config', '--add',
1576 "svn-remote.$self->{repo_id}.fetch",
1577 "$self->{path}:".$self->refname);
1579 $self->{url} = $url;
1582 sub find_by_url { # repos_root and, path are optional
1583 my ($class, $full_url, $repos_root, $path) = @_;
1585 return undef unless defined $full_url;
1586 remove_username($full_url);
1587 remove_username($repos_root) if defined $repos_root;
1588 my $remotes = read_all_remotes();
1589 if (defined $full_url && defined $repos_root && !defined $path) {
1590 $path = $full_url;
1591 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1593 foreach my $repo_id (keys %$remotes) {
1594 my $u = $remotes->{$repo_id}->{url} or next;
1595 remove_username($u);
1596 next if defined $repos_root && $repos_root ne $u;
1598 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1599 foreach (qw/branches tags/) {
1600 resolve_local_globs($u, $fetch,
1601 $remotes->{$repo_id}->{$_});
1603 my $p = $path;
1604 my $rwr = rewrite_root({repo_id => $repo_id});
1605 my $svm = $remotes->{$repo_id}->{svm}
1606 if defined $remotes->{$repo_id}->{svm};
1607 unless (defined $p) {
1608 $p = $full_url;
1609 my $z = $u;
1610 my $prefix = '';
1611 if ($rwr) {
1612 $z = $rwr;
1613 } elsif (defined $svm) {
1614 $z = $svm->{source};
1615 $prefix = $svm->{replace};
1616 $prefix =~ s#^\Q$u\E(?:/|$)##;
1617 $prefix =~ s#/$##;
1619 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
1621 foreach my $f (keys %$fetch) {
1622 next if $f ne $p;
1623 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1626 undef;
1629 sub init {
1630 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1631 my $self = _new($class, $repo_id, $ref_id, $path);
1632 if (defined $url) {
1633 $self->init_remote_config($url, $no_write);
1635 $self;
1638 sub find_ref {
1639 my ($ref_id) = @_;
1640 foreach (command(qw/config -l/)) {
1641 next unless m!^svn-remote\.(.+)\.fetch=
1642 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1643 my ($repo_id, $path, $ref) = ($1, $2, $3);
1644 if ($ref eq $ref_id) {
1645 $path = '' if ($path =~ m#^\./?#);
1646 return ($repo_id, $path);
1649 (undef, undef, undef);
1652 sub new {
1653 my ($class, $ref_id, $repo_id, $path) = @_;
1654 if (defined $ref_id && !defined $repo_id && !defined $path) {
1655 ($repo_id, $path) = find_ref($ref_id);
1656 if (!defined $repo_id) {
1657 die "Could not find a \"svn-remote.*.fetch\" key ",
1658 "in the repository configuration matching: ",
1659 "refs/remotes/$ref_id\n";
1662 my $self = _new($class, $repo_id, $ref_id, $path);
1663 if (!defined $self->{path} || !length $self->{path}) {
1664 my $fetch = command_oneline('config', '--get',
1665 "svn-remote.$repo_id.fetch",
1666 ":refs/remotes/$ref_id\$") or
1667 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1668 "\":refs/remotes/$ref_id\$\" in config\n";
1669 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1671 $self->{url} = command_oneline('config', '--get',
1672 "svn-remote.$repo_id.url") or
1673 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1674 $self->rebuild;
1675 $self;
1678 sub refname {
1679 my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1681 # It cannot end with a slash /, we'll throw up on this because
1682 # SVN can't have directories with a slash in their name, either:
1683 if ($refname =~ m{/$}) {
1684 die "ref: '$refname' ends with a trailing slash, this is ",
1685 "not permitted by git nor Subversion\n";
1688 # It cannot have ASCII control character space, tilde ~, caret ^,
1689 # colon :, question-mark ?, asterisk *, space, or open bracket [
1690 # anywhere.
1692 # Additionally, % must be escaped because it is used for escaping
1693 # and we want our escaped refname to be reversible
1694 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1696 # no slash-separated component can begin with a dot .
1697 # /.* becomes /%2E*
1698 $refname =~ s{/\.}{/%2E}g;
1700 # It cannot have two consecutive dots .. anywhere
1701 # .. becomes %2E%2E
1702 $refname =~ s{\.\.}{%2E%2E}g;
1704 return $refname;
1707 sub desanitize_refname {
1708 my ($refname) = @_;
1709 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1710 return $refname;
1713 sub svm_uuid {
1714 my ($self) = @_;
1715 return $self->{svm}->{uuid} if $self->svm;
1716 $self->ra;
1717 unless ($self->{svm}) {
1718 die "SVM UUID not cached, and reading remotely failed\n";
1720 $self->{svm}->{uuid};
1723 sub svm {
1724 my ($self) = @_;
1725 return $self->{svm} if $self->{svm};
1726 my $svm;
1727 # see if we have it in our config, first:
1728 eval {
1729 my $section = "svn-remote.$self->{repo_id}";
1730 $svm = {
1731 source => tmp_config('--get', "$section.svm-source"),
1732 uuid => tmp_config('--get', "$section.svm-uuid"),
1733 replace => tmp_config('--get', "$section.svm-replace"),
1736 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1737 $self->{svm} = $svm;
1739 $self->{svm};
1742 sub _set_svm_vars {
1743 my ($self, $ra) = @_;
1744 return $ra if $self->svm;
1746 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1747 "(svm:source, svm:uuid) ",
1748 "from the following URLs:\n" );
1749 sub read_svm_props {
1750 my ($self, $ra, $path, $r) = @_;
1751 my $props = ($ra->get_dir($path, $r))[2];
1752 my $src = $props->{'svm:source'};
1753 my $uuid = $props->{'svm:uuid'};
1754 return undef if (!$src || !$uuid);
1756 chomp($src, $uuid);
1758 $uuid =~ m{^[0-9a-f\-]{30,}$}
1759 or die "doesn't look right - svm:uuid is '$uuid'\n";
1761 # the '!' is used to mark the repos_root!/relative/path
1762 $src =~ s{/?!/?}{/};
1763 $src =~ s{/+$}{}; # no trailing slashes please
1764 # username is of no interest
1765 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1767 my $replace = $ra->{url};
1768 $replace .= "/$path" if length $path;
1770 my $section = "svn-remote.$self->{repo_id}";
1771 tmp_config("$section.svm-source", $src);
1772 tmp_config("$section.svm-replace", $replace);
1773 tmp_config("$section.svm-uuid", $uuid);
1774 $self->{svm} = {
1775 source => $src,
1776 uuid => $uuid,
1777 replace => $replace
1781 my $r = $ra->get_latest_revnum;
1782 my $path = $self->{path};
1783 my %tried;
1784 while (length $path) {
1785 unless ($tried{"$self->{url}/$path"}) {
1786 return $ra if $self->read_svm_props($ra, $path, $r);
1787 $tried{"$self->{url}/$path"} = 1;
1789 $path =~ s#/?[^/]+$##;
1791 die "Path: '$path' should be ''\n" if $path ne '';
1792 return $ra if $self->read_svm_props($ra, $path, $r);
1793 $tried{"$self->{url}/$path"} = 1;
1795 if ($ra->{repos_root} eq $self->{url}) {
1796 die @err, (map { " $_\n" } keys %tried), "\n";
1799 # nope, make sure we're connected to the repository root:
1800 my $ok;
1801 my @tried_b;
1802 $path = $ra->{svn_path};
1803 $ra = Git::SVN::Ra->new($ra->{repos_root});
1804 while (length $path) {
1805 unless ($tried{"$ra->{url}/$path"}) {
1806 $ok = $self->read_svm_props($ra, $path, $r);
1807 last if $ok;
1808 $tried{"$ra->{url}/$path"} = 1;
1810 $path =~ s#/?[^/]+$##;
1812 die "Path: '$path' should be ''\n" if $path ne '';
1813 $ok ||= $self->read_svm_props($ra, $path, $r);
1814 $tried{"$ra->{url}/$path"} = 1;
1815 if (!$ok) {
1816 die @err, (map { " $_\n" } keys %tried), "\n";
1818 Git::SVN::Ra->new($self->{url});
1821 sub svnsync {
1822 my ($self) = @_;
1823 return $self->{svnsync} if $self->{svnsync};
1825 if ($self->no_metadata) {
1826 die "Can't have both 'noMetadata' and ",
1827 "'useSvnsyncProps' options set!\n";
1829 if ($self->rewrite_root) {
1830 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1831 "options set!\n";
1834 my $svnsync;
1835 # see if we have it in our config, first:
1836 eval {
1837 my $section = "svn-remote.$self->{repo_id}";
1839 my $url = tmp_config('--get', "$section.svnsync-url");
1840 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
1841 die "doesn't look right - svn:sync-from-url is '$url'\n";
1843 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
1844 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
1845 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1847 $svnsync = { url => $url, uuid => $uuid }
1849 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1850 return $self->{svnsync} = $svnsync;
1853 my $err = "useSvnsyncProps set, but failed to read " .
1854 "svnsync property: svn:sync-from-";
1855 my $rp = $self->ra->rev_proplist(0);
1857 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
1858 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
1859 die "doesn't look right - svn:sync-from-url is '$url'\n";
1861 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
1862 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
1863 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1865 my $section = "svn-remote.$self->{repo_id}";
1866 tmp_config('--add', "$section.svnsync-uuid", $uuid);
1867 tmp_config('--add', "$section.svnsync-url", $url);
1868 return $self->{svnsync} = { url => $url, uuid => $uuid };
1871 # this allows us to memoize our SVN::Ra UUID locally and avoid a
1872 # remote lookup (useful for 'git svn log').
1873 sub ra_uuid {
1874 my ($self) = @_;
1875 unless ($self->{ra_uuid}) {
1876 my $key = "svn-remote.$self->{repo_id}.uuid";
1877 my $uuid = eval { tmp_config('--get', $key) };
1878 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1879 $self->{ra_uuid} = $uuid;
1880 } else {
1881 die "ra_uuid called without URL\n" unless $self->{url};
1882 $self->{ra_uuid} = $self->ra->get_uuid;
1883 tmp_config('--add', $key, $self->{ra_uuid});
1886 $self->{ra_uuid};
1889 sub _set_repos_root {
1890 my ($self, $repos_root) = @_;
1891 my $k = "svn-remote.$self->{repo_id}.reposRoot";
1892 $repos_root ||= $self->ra->{repos_root};
1893 tmp_config($k, $repos_root);
1894 $repos_root;
1897 sub repos_root {
1898 my ($self) = @_;
1899 my $k = "svn-remote.$self->{repo_id}.reposRoot";
1900 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
1903 sub ra {
1904 my ($self) = shift;
1905 my $ra = Git::SVN::Ra->new($self->{url});
1906 $self->_set_repos_root($ra->{repos_root});
1907 if ($self->use_svm_props && !$self->{svm}) {
1908 if ($self->no_metadata) {
1909 die "Can't have both 'noMetadata' and ",
1910 "'useSvmProps' options set!\n";
1911 } elsif ($self->use_svnsync_props) {
1912 die "Can't have both 'useSvnsyncProps' and ",
1913 "'useSvmProps' options set!\n";
1915 $ra = $self->_set_svm_vars($ra);
1916 $self->{-want_revprops} = 1;
1918 $ra;
1921 sub rel_path {
1922 my ($self) = @_;
1923 my $repos_root = $self->ra->{repos_root};
1924 return $self->{path} if ($self->{url} eq $repos_root);
1925 my $url = $self->{url} .
1926 (length $self->{path} ? "/$self->{path}" : $self->{path});
1927 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
1928 $url;
1931 # prop_walk(PATH, REV, SUB)
1932 # -------------------------
1933 # Recursively traverse PATH at revision REV and invoke SUB for each
1934 # directory that contains a SVN property. SUB will be invoked as
1935 # follows: &SUB(gs, path, props); where `gs' is this instance of
1936 # Git::SVN, `path' the path to the directory where the properties
1937 # `props' were found. The `path' will be relative to point of checkout,
1938 # that is, if url://repo/trunk is the current Git branch, and that
1939 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
1940 # as `path' (note the trailing `/').
1941 sub prop_walk {
1942 my ($self, $path, $rev, $sub) = @_;
1944 $path =~ s#^/##;
1945 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
1946 $path =~ s#^/*#/#g;
1947 my $p = $path;
1948 # Strip the irrelevant part of the path.
1949 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
1950 # Ensure the path is terminated by a `/'.
1951 $p =~ s#/*$#/#;
1953 # The properties contain all the internal SVN stuff nobody
1954 # (usually) cares about.
1955 my $interesting_props = 0;
1956 foreach (keys %{$props}) {
1957 # If it doesn't start with `svn:', it must be a
1958 # user-defined property.
1959 ++$interesting_props and next if $_ !~ /^svn:/;
1960 # FIXME: Fragile, if SVN adds new public properties,
1961 # this needs to be updated.
1962 ++$interesting_props if /^svn:(?:ignore|keywords|executable
1963 |eol-style|mime-type
1964 |externals|needs-lock)$/x;
1966 &$sub($self, $p, $props) if $interesting_props;
1968 foreach (sort keys %$dirent) {
1969 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
1970 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
1974 sub last_rev { ($_[0]->last_rev_commit)[0] }
1975 sub last_commit { ($_[0]->last_rev_commit)[1] }
1977 # returns the newest SVN revision number and newest commit SHA1
1978 sub last_rev_commit {
1979 my ($self) = @_;
1980 if (defined $self->{last_rev} && defined $self->{last_commit}) {
1981 return ($self->{last_rev}, $self->{last_commit});
1983 my $c = ::verify_ref($self->refname.'^0');
1984 if ($c && !$self->use_svm_props && !$self->no_metadata) {
1985 my $rev = (::cmt_metadata($c))[1];
1986 if (defined $rev) {
1987 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1988 return ($rev, $c);
1991 my $map_path = $self->map_path;
1992 unless (-e $map_path) {
1993 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
1994 return (undef, undef);
1996 my ($rev, $commit) = $self->rev_map_max(1);
1997 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
1998 return ($rev, $commit);
2001 sub get_fetch_range {
2002 my ($self, $min, $max) = @_;
2003 $max ||= $self->ra->get_latest_revnum;
2004 $min ||= $self->rev_map_max;
2005 (++$min, $max);
2008 sub tmp_config {
2009 my (@args) = @_;
2010 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2011 my $config = "$ENV{GIT_DIR}/svn/.metadata";
2012 if (! -f $config && -f $old_def_config) {
2013 rename $old_def_config, $config or
2014 die "Failed rename $old_def_config => $config: $!\n";
2016 my $old_config = $ENV{GIT_CONFIG};
2017 $ENV{GIT_CONFIG} = $config;
2018 $@ = undef;
2019 my @ret = eval {
2020 unless (-f $config) {
2021 mkfile($config);
2022 open my $fh, '>', $config or
2023 die "Can't open $config: $!\n";
2024 print $fh "; This file is used internally by ",
2025 "git-svn\n" or die
2026 "Couldn't write to $config: $!\n";
2027 print $fh "; You should not have to edit it\n" or
2028 die "Couldn't write to $config: $!\n";
2029 close $fh or die "Couldn't close $config: $!\n";
2031 command('config', @args);
2033 my $err = $@;
2034 if (defined $old_config) {
2035 $ENV{GIT_CONFIG} = $old_config;
2036 } else {
2037 delete $ENV{GIT_CONFIG};
2039 die $err if $err;
2040 wantarray ? @ret : $ret[0];
2043 sub tmp_index_do {
2044 my ($self, $sub) = @_;
2045 my $old_index = $ENV{GIT_INDEX_FILE};
2046 $ENV{GIT_INDEX_FILE} = $self->{index};
2047 $@ = undef;
2048 my @ret = eval {
2049 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2050 mkpath([$dir]) unless -d $dir;
2051 &$sub;
2053 my $err = $@;
2054 if (defined $old_index) {
2055 $ENV{GIT_INDEX_FILE} = $old_index;
2056 } else {
2057 delete $ENV{GIT_INDEX_FILE};
2059 die $err if $err;
2060 wantarray ? @ret : $ret[0];
2063 sub assert_index_clean {
2064 my ($self, $treeish) = @_;
2066 $self->tmp_index_do(sub {
2067 command_noisy('read-tree', $treeish) unless -e $self->{index};
2068 my $x = command_oneline('write-tree');
2069 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2070 /^tree ($::sha1)/mo);
2071 return if $y eq $x;
2073 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2074 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2075 command_noisy('read-tree', $treeish);
2076 $x = command_oneline('write-tree');
2077 if ($y ne $x) {
2078 ::fatal "trees ($treeish) $y != $x\n",
2079 "Something is seriously wrong...";
2084 sub get_commit_parents {
2085 my ($self, $log_entry) = @_;
2086 my (%seen, @ret, @tmp);
2087 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2088 if (my $ip = $self->{inject_parents}) {
2089 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2090 push @tmp, $commit;
2093 if (my $cur = ::verify_ref($self->refname.'^0')) {
2094 push @tmp, $cur;
2096 if (my $ipd = $self->{inject_parents_dcommit}) {
2097 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2098 push @tmp, @$commit;
2101 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2102 while (my $p = shift @tmp) {
2103 next if $seen{$p};
2104 $seen{$p} = 1;
2105 push @ret, $p;
2106 # MAXPARENT is defined to 16 in commit-tree.c:
2107 last if @ret >= 16;
2109 if (@tmp) {
2110 die "r$log_entry->{revision}: No room for parents:\n\t",
2111 join("\n\t", @tmp), "\n";
2113 @ret;
2116 sub rewrite_root {
2117 my ($self) = @_;
2118 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2119 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2120 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2121 if ($rwr) {
2122 $rwr =~ s#/+$##;
2123 if ($rwr !~ m#^[a-z\+]+://#) {
2124 die "$rwr is not a valid URL (key: $k)\n";
2127 $self->{-rewrite_root} = $rwr;
2130 sub metadata_url {
2131 my ($self) = @_;
2132 ($self->rewrite_root || $self->{url}) .
2133 (length $self->{path} ? '/' . $self->{path} : '');
2136 sub full_url {
2137 my ($self) = @_;
2138 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2142 sub set_commit_header_env {
2143 my ($log_entry) = @_;
2144 my %env;
2145 foreach my $ned (qw/NAME EMAIL DATE/) {
2146 foreach my $ac (qw/AUTHOR COMMITTER/) {
2147 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2151 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2152 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2153 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2155 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2156 ? $log_entry->{commit_name}
2157 : $log_entry->{name};
2158 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2159 ? $log_entry->{commit_email}
2160 : $log_entry->{email};
2161 \%env;
2164 sub restore_commit_header_env {
2165 my ($env) = @_;
2166 foreach my $ned (qw/NAME EMAIL DATE/) {
2167 foreach my $ac (qw/AUTHOR COMMITTER/) {
2168 my $k = "GIT_${ac}_${ned}";
2169 if (defined $env->{$k}) {
2170 $ENV{$k} = $env->{$k};
2171 } else {
2172 delete $ENV{$k};
2178 sub gc {
2179 command_noisy('gc', '--auto');
2182 sub do_git_commit {
2183 my ($self, $log_entry) = @_;
2184 my $lr = $self->last_rev;
2185 if (defined $lr && $lr >= $log_entry->{revision}) {
2186 die "Last fetched revision of ", $self->refname,
2187 " was r$lr, but we are about to fetch: ",
2188 "r$log_entry->{revision}!\n";
2190 if (my $c = $self->rev_map_get($log_entry->{revision})) {
2191 croak "$log_entry->{revision} = $c already exists! ",
2192 "Why are we refetching it?\n";
2194 my $old_env = set_commit_header_env($log_entry);
2195 my $tree = $log_entry->{tree};
2196 if (!defined $tree) {
2197 $tree = $self->tmp_index_do(sub {
2198 command_oneline('write-tree') });
2200 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2202 my @exec = ('git-commit-tree', $tree);
2203 foreach ($self->get_commit_parents($log_entry)) {
2204 push @exec, '-p', $_;
2206 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2207 or croak $!;
2208 print $msg_fh $log_entry->{log} or croak $!;
2209 restore_commit_header_env($old_env);
2210 unless ($self->no_metadata) {
2211 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2212 or croak $!;
2214 $msg_fh->flush == 0 or croak $!;
2215 close $msg_fh or croak $!;
2216 chomp(my $commit = do { local $/; <$out_fh> });
2217 close $out_fh or croak $!;
2218 waitpid $pid, 0;
2219 croak $? if $?;
2220 if ($commit !~ /^$::sha1$/o) {
2221 die "Failed to commit, invalid sha1: $commit\n";
2224 $self->rev_map_set($log_entry->{revision}, $commit, 1);
2226 $self->{last_rev} = $log_entry->{revision};
2227 $self->{last_commit} = $commit;
2228 print "r$log_entry->{revision}";
2229 if (defined $log_entry->{svm_revision}) {
2230 print " (\@$log_entry->{svm_revision})";
2231 $self->rev_map_set($log_entry->{svm_revision}, $commit,
2232 0, $self->svm_uuid);
2234 print " = $commit ($self->{ref_id})\n";
2235 if (--$_gc_nr == 0) {
2236 $_gc_nr = $_gc_period;
2237 gc();
2239 return $commit;
2242 sub match_paths {
2243 my ($self, $paths, $r) = @_;
2244 return 1 if $self->{path} eq '';
2245 if (my $path = $paths->{"/$self->{path}"}) {
2246 return ($path->{action} eq 'D') ? 0 : 1;
2248 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
2249 if (grep /$self->{path_regex}/, keys %$paths) {
2250 return 1;
2252 my $c = '';
2253 foreach (split m#/#, $self->{path}) {
2254 $c .= "/$_";
2255 next unless ($paths->{$c} &&
2256 ($paths->{$c}->{action} =~ /^[AR]$/));
2257 if ($self->ra->check_path($self->{path}, $r) ==
2258 $SVN::Node::dir) {
2259 return 1;
2262 return 0;
2265 sub find_parent_branch {
2266 my ($self, $paths, $rev) = @_;
2267 return undef unless $self->follow_parent;
2268 unless (defined $paths) {
2269 my $err_handler = $SVN::Error::handler;
2270 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2271 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
2272 $paths =
2273 Git::SVN::Ra::dup_changed_paths($_[0]) });
2274 $SVN::Error::handler = $err_handler;
2276 return undef unless defined $paths;
2278 # look for a parent from another branch:
2279 my @b_path_components = split m#/#, $self->rel_path;
2280 my @a_path_components;
2281 my $i;
2282 while (@b_path_components) {
2283 $i = $paths->{'/'.join('/', @b_path_components)};
2284 last if $i && defined $i->{copyfrom_path};
2285 unshift(@a_path_components, pop(@b_path_components));
2287 return undef unless defined $i && defined $i->{copyfrom_path};
2288 my $branch_from = $i->{copyfrom_path};
2289 if (@a_path_components) {
2290 print STDERR "branch_from: $branch_from => ";
2291 $branch_from .= '/'.join('/', @a_path_components);
2292 print STDERR $branch_from, "\n";
2294 my $r = $i->{copyfrom_rev};
2295 my $repos_root = $self->ra->{repos_root};
2296 my $url = $self->ra->{url};
2297 my $new_url = $repos_root . $branch_from;
2298 print STDERR "Found possible branch point: ",
2299 "$new_url => ", $self->full_url, ", $r\n";
2300 $branch_from =~ s#^/##;
2301 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
2302 unless ($gs) {
2303 my $ref_id = $self->{ref_id};
2304 $ref_id =~ s/\@\d+$//;
2305 $ref_id .= "\@$r";
2306 # just grow a tail if we're not unique enough :x
2307 $ref_id .= '-' while find_ref($ref_id);
2308 print STDERR "Initializing parent: $ref_id\n";
2309 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
2310 if ($u =~ s#^\Q$url\E(/|$)##) {
2311 $p = $u;
2312 $u = $url;
2313 $repo_id = $self->{repo_id};
2315 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
2317 my ($r0, $parent) = $gs->find_rev_before($r, 1);
2318 if (!defined $r0 || !defined $parent) {
2319 my ($base, $head) = parse_revision_argument(0, $r);
2320 if ($base <= $r) {
2321 $gs->fetch($base, $r);
2323 ($r0, $parent) = $gs->last_rev_commit;
2325 if (defined $r0 && defined $parent) {
2326 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
2327 my $ed;
2328 if ($self->ra->can_do_switch) {
2329 $self->assert_index_clean($parent);
2330 print STDERR "Following parent with do_switch\n";
2331 # do_switch works with svn/trunk >= r22312, but that
2332 # is not included with SVN 1.4.3 (the latest version
2333 # at the moment), so we can't rely on it
2334 $self->{last_commit} = $parent;
2335 $ed = SVN::Git::Fetcher->new($self);
2336 $gs->ra->gs_do_switch($r0, $rev, $gs,
2337 $self->full_url, $ed)
2338 or die "SVN connection failed somewhere...\n";
2339 } elsif ($self->ra->trees_match($new_url, $r0,
2340 $self->full_url, $rev)) {
2341 print STDERR "Trees match:\n",
2342 " $new_url\@$r0\n",
2343 " ${\$self->full_url}\@$rev\n",
2344 "Following parent with no changes\n";
2345 $self->tmp_index_do(sub {
2346 command_noisy('read-tree', $parent);
2348 $self->{last_commit} = $parent;
2349 } else {
2350 print STDERR "Following parent with do_update\n";
2351 $ed = SVN::Git::Fetcher->new($self);
2352 $self->ra->gs_do_update($rev, $rev, $self, $ed)
2353 or die "SVN connection failed somewhere...\n";
2355 print STDERR "Successfully followed parent\n";
2356 return $self->make_log_entry($rev, [$parent], $ed);
2358 return undef;
2361 sub do_fetch {
2362 my ($self, $paths, $rev) = @_;
2363 my $ed;
2364 my ($last_rev, @parents);
2365 if (my $lc = $self->last_commit) {
2366 # we can have a branch that was deleted, then re-added
2367 # under the same name but copied from another path, in
2368 # which case we'll have multiple parents (we don't
2369 # want to break the original ref, nor lose copypath info):
2370 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2371 push @{$log_entry->{parents}}, $lc;
2372 return $log_entry;
2374 $ed = SVN::Git::Fetcher->new($self);
2375 $last_rev = $self->{last_rev};
2376 $ed->{c} = $lc;
2377 @parents = ($lc);
2378 } else {
2379 $last_rev = $rev;
2380 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2381 return $log_entry;
2383 $ed = SVN::Git::Fetcher->new($self);
2385 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2386 die "SVN connection failed somewhere...\n";
2388 $self->make_log_entry($rev, \@parents, $ed);
2391 sub get_untracked {
2392 my ($self, $ed) = @_;
2393 my @out;
2394 my $h = $ed->{empty};
2395 foreach (sort keys %$h) {
2396 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2397 push @out, " $act: " . uri_encode($_);
2398 warn "W: $act: $_\n";
2400 foreach my $t (qw/dir_prop file_prop/) {
2401 $h = $ed->{$t} or next;
2402 foreach my $path (sort keys %$h) {
2403 my $ppath = $path eq '' ? '.' : $path;
2404 foreach my $prop (sort keys %{$h->{$path}}) {
2405 next if $SKIP_PROP{$prop};
2406 my $v = $h->{$path}->{$prop};
2407 my $t_ppath_prop = "$t: " .
2408 uri_encode($ppath) . ' ' .
2409 uri_encode($prop);
2410 if (defined $v) {
2411 push @out, " +$t_ppath_prop " .
2412 uri_encode($v);
2413 } else {
2414 push @out, " -$t_ppath_prop";
2419 foreach my $t (qw/absent_file absent_directory/) {
2420 $h = $ed->{$t} or next;
2421 foreach my $parent (sort keys %$h) {
2422 foreach my $path (sort @{$h->{$parent}}) {
2423 push @out, " $t: " .
2424 uri_encode("$parent/$path");
2425 warn "W: $t: $parent/$path ",
2426 "Insufficient permissions?\n";
2430 \@out;
2433 sub parse_svn_date {
2434 my $date = shift || return '+0000 1970-01-01 00:00:00';
2435 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2436 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
2437 croak "Unable to parse date: $date\n";
2438 "+0000 $Y-$m-$d $H:$M:$S";
2441 sub check_author {
2442 my ($author) = @_;
2443 if (!defined $author || length $author == 0) {
2444 $author = '(no author)';
2445 } elsif (defined $::_authors && ! defined $::users{$author}) {
2446 die "Author: $author not defined in $::_authors file\n";
2448 $author;
2451 sub make_log_entry {
2452 my ($self, $rev, $parents, $ed) = @_;
2453 my $untracked = $self->get_untracked($ed);
2455 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
2456 print $un "r$rev\n" or croak $!;
2457 print $un $_, "\n" foreach @$untracked;
2458 my %log_entry = ( parents => $parents || [], revision => $rev,
2459 log => '');
2461 my $headrev;
2462 my $logged = delete $self->{logged_rev_props};
2463 if (!$logged || $self->{-want_revprops}) {
2464 my $rp = $self->ra->rev_proplist($rev);
2465 foreach (sort keys %$rp) {
2466 my $v = $rp->{$_};
2467 if (/^svn:(author|date|log)$/) {
2468 $log_entry{$1} = $v;
2469 } elsif ($_ eq 'svm:headrev') {
2470 $headrev = $v;
2471 } else {
2472 print $un " rev_prop: ", uri_encode($_), ' ',
2473 uri_encode($v), "\n";
2476 } else {
2477 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
2479 close $un or croak $!;
2481 $log_entry{date} = parse_svn_date($log_entry{date});
2482 $log_entry{log} .= "\n";
2483 my $author = $log_entry{author} = check_author($log_entry{author});
2484 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
2485 : ($author, undef);
2487 my ($commit_name, $commit_email) = ($name, $email);
2488 if ($_use_log_author) {
2489 my $name_field;
2490 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
2491 $name_field = $1;
2492 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
2493 $name_field = $1;
2495 if (!defined $name_field) {
2496 if (!defined $email) {
2497 $email = $name;
2499 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
2500 ($name, $email) = ($1, $2);
2501 } elsif ($name_field =~ /(.*)@/) {
2502 ($name, $email) = ($1, $name_field);
2503 } else {
2504 ($name, $email) = ($name_field, $name_field);
2507 if (defined $headrev && $self->use_svm_props) {
2508 if ($self->rewrite_root) {
2509 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2510 "options set!\n";
2512 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
2513 # we don't want "SVM: initializing mirror for junk" ...
2514 return undef if $r == 0;
2515 my $svm = $self->svm;
2516 if ($uuid ne $svm->{uuid}) {
2517 die "UUID mismatch on SVM path:\n",
2518 "expected: $svm->{uuid}\n",
2519 " got: $uuid\n";
2521 my $full_url = $self->full_url;
2522 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2523 die "Failed to replace '$svm->{replace}' with ",
2524 "'$svm->{source}' in $full_url\n";
2525 # throw away username for storing in records
2526 remove_username($full_url);
2527 $log_entry{metadata} = "$full_url\@$r $uuid";
2528 $log_entry{svm_revision} = $r;
2529 $email ||= "$author\@$uuid";
2530 $commit_email ||= "$author\@$uuid";
2531 } elsif ($self->use_svnsync_props) {
2532 my $full_url = $self->svnsync->{url};
2533 $full_url .= "/$self->{path}" if length $self->{path};
2534 remove_username($full_url);
2535 my $uuid = $self->svnsync->{uuid};
2536 $log_entry{metadata} = "$full_url\@$rev $uuid";
2537 $email ||= "$author\@$uuid";
2538 $commit_email ||= "$author\@$uuid";
2539 } else {
2540 my $url = $self->metadata_url;
2541 remove_username($url);
2542 $log_entry{metadata} = "$url\@$rev " .
2543 $self->ra->get_uuid;
2544 $email ||= "$author\@" . $self->ra->get_uuid;
2545 $commit_email ||= "$author\@" . $self->ra->get_uuid;
2547 $log_entry{name} = $name;
2548 $log_entry{email} = $email;
2549 $log_entry{commit_name} = $commit_name;
2550 $log_entry{commit_email} = $commit_email;
2551 \%log_entry;
2554 sub fetch {
2555 my ($self, $min_rev, $max_rev, @parents) = @_;
2556 my ($last_rev, $last_commit) = $self->last_rev_commit;
2557 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2558 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2561 sub set_tree_cb {
2562 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2563 $self->{inject_parents} = { $rev => $tree };
2564 $self->fetch(undef, undef);
2567 sub set_tree {
2568 my ($self, $tree) = (shift, shift);
2569 my $log_entry = ::get_commit_entry($tree);
2570 unless ($self->{last_rev}) {
2571 fatal("Must have an existing revision to commit");
2573 my %ed_opts = ( r => $self->{last_rev},
2574 log => $log_entry->{log},
2575 ra => $self->ra,
2576 tree_a => $self->{last_commit},
2577 tree_b => $tree,
2578 editor_cb => sub {
2579 $self->set_tree_cb($log_entry, $tree, @_) },
2580 svn_path => $self->{path} );
2581 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2582 print "No changes\nr$self->{last_rev} = $tree\n";
2586 sub rebuild_from_rev_db {
2587 my ($self, $path) = @_;
2588 my $r = -1;
2589 open my $fh, '<', $path or croak "open: $!";
2590 binmode $fh or croak "binmode: $!";
2591 while (<$fh>) {
2592 length($_) == 41 or croak "inconsistent size in ($_) != 41";
2593 chomp($_);
2594 ++$r;
2595 next if $_ eq ('0' x 40);
2596 $self->rev_map_set($r, $_);
2597 print "r$r = $_\n";
2599 close $fh or croak "close: $!";
2600 unlink $path or croak "unlink: $!";
2603 sub rebuild {
2604 my ($self) = @_;
2605 my $map_path = $self->map_path;
2606 return if (-e $map_path && ! -z $map_path);
2607 return unless ::verify_ref($self->refname.'^0');
2608 if ($self->use_svm_props || $self->no_metadata) {
2609 my $rev_db = $self->rev_db_path;
2610 $self->rebuild_from_rev_db($rev_db);
2611 if ($self->use_svm_props) {
2612 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
2613 $self->rebuild_from_rev_db($svm_rev_db);
2615 $self->unlink_rev_db_symlink;
2616 return;
2618 print "Rebuilding $map_path ...\n";
2619 my ($log, $ctx) =
2620 command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
2621 $self->refname, '--');
2622 my $metadata_url = $self->metadata_url;
2623 remove_username($metadata_url);
2624 my $svn_uuid = $self->ra_uuid;
2625 my $c;
2626 while (<$log>) {
2627 if ( m{^commit ($::sha1)$} ) {
2628 $c = $1;
2629 next;
2631 next unless s{^\s*(git-svn-id:)}{$1};
2632 my ($url, $rev, $uuid) = ::extract_metadata($_);
2633 remove_username($url);
2635 # ignore merges (from set-tree)
2636 next if (!defined $rev || !$uuid);
2638 # if we merged or otherwise started elsewhere, this is
2639 # how we break out of it
2640 if (($uuid ne $svn_uuid) ||
2641 ($metadata_url && $url && ($url ne $metadata_url))) {
2642 next;
2645 $self->rev_map_set($rev, $c);
2646 print "r$rev = $c\n";
2648 command_close_pipe($log, $ctx);
2649 print "Done rebuilding $map_path\n";
2650 my $rev_db_path = $self->rev_db_path;
2651 if (-f $self->rev_db_path) {
2652 unlink $self->rev_db_path or croak "unlink: $!";
2654 $self->unlink_rev_db_symlink;
2657 # rev_map:
2658 # Tie::File seems to be prone to offset errors if revisions get sparse,
2659 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2660 # one of my favorite modules is out :< Next up would be one of the DBM
2661 # modules, but I'm not sure which is most portable...
2663 # This is the replacement for the rev_db format, which was too big
2664 # and inefficient for large repositories with a lot of sparse history
2665 # (mainly tags)
2667 # The format is this:
2668 # - 24 bytes for every record,
2669 # * 4 bytes for the integer representing an SVN revision number
2670 # * 20 bytes representing the sha1 of a git commit
2671 # - No empty padding records like the old format
2672 # (except the last record, which can be overwritten)
2673 # - new records are written append-only since SVN revision numbers
2674 # increase monotonically
2675 # - lookups on SVN revision number are done via a binary search
2676 # - Piping the file to xxd -c24 is a good way of dumping it for
2677 # viewing or editing (piped back through xxd -r), should the need
2678 # ever arise.
2679 # - The last record can be padding revision with an all-zero sha1
2680 # This is used to optimize fetch performance when using multiple
2681 # "fetch" directives in .git/config
2683 # These files are disposable unless noMetadata or useSvmProps is set
2685 sub _rev_map_set {
2686 my ($fh, $rev, $commit) = @_;
2688 binmode $fh or croak "binmode: $!";
2689 my $size = (stat($fh))[7];
2690 ($size % 24) == 0 or croak "inconsistent size: $size";
2692 my $wr_offset = 0;
2693 if ($size > 0) {
2694 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2695 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
2696 $read == 24 or croak "read only $read bytes (!= 24)";
2697 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
2698 if ($last_commit eq ('0' x40)) {
2699 if ($size >= 48) {
2700 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2701 $read = sysread($fh, $buf, 24) or
2702 croak "read: $!";
2703 $read == 24 or
2704 croak "read only $read bytes (!= 24)";
2705 ($last_rev, $last_commit) =
2706 unpack(rev_map_fmt, $buf);
2707 if ($last_commit eq ('0' x40)) {
2708 croak "inconsistent .rev_map\n";
2711 if ($last_rev >= $rev) {
2712 croak "last_rev is higher!: $last_rev >= $rev";
2714 $wr_offset = -24;
2717 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
2718 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
2719 croak "write: $!";
2722 sub mkfile {
2723 my ($path) = @_;
2724 unless (-e $path) {
2725 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2726 mkpath([$dir]) unless -d $dir;
2727 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2728 close $fh or die "Couldn't close (create) $path: $!\n";
2732 sub rev_map_set {
2733 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2734 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2735 my $db = $self->map_path($uuid);
2736 my $db_lock = "$db.lock";
2737 my $sig;
2738 if ($update_ref) {
2739 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2740 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2742 mkfile($db);
2744 $LOCKFILES{$db_lock} = 1;
2745 my $sync;
2746 # both of these options make our .rev_db file very, very important
2747 # and we can't afford to lose it because rebuild() won't work
2748 if ($self->use_svm_props || $self->no_metadata) {
2749 $sync = 1;
2750 copy($db, $db_lock) or die "rev_map_set(@_): ",
2751 "Failed to copy: ",
2752 "$db => $db_lock ($!)\n";
2753 } else {
2754 rename $db, $db_lock or die "rev_map_set(@_): ",
2755 "Failed to rename: ",
2756 "$db => $db_lock ($!)\n";
2759 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
2760 or croak "Couldn't open $db_lock: $!\n";
2761 _rev_map_set($fh, $rev, $commit);
2762 if ($sync) {
2763 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2764 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2766 close $fh or croak $!;
2767 if ($update_ref) {
2768 $_head = $self;
2769 command_noisy('update-ref', '-m', "r$rev",
2770 $self->refname, $commit);
2772 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
2773 "$db_lock => $db ($!)\n";
2774 delete $LOCKFILES{$db_lock};
2775 if ($update_ref) {
2776 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2777 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
2778 kill $sig, $$ if defined $sig;
2782 # If want_commit, this will return an array of (rev, commit) where
2783 # commit _must_ be a valid commit in the archive.
2784 # Otherwise, it'll return the max revision (whether or not the
2785 # commit is valid or just a 0x40 placeholder).
2786 sub rev_map_max {
2787 my ($self, $want_commit) = @_;
2788 $self->rebuild;
2789 my $map_path = $self->map_path;
2790 stat $map_path or return $want_commit ? (0, undef) : 0;
2791 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
2792 binmode $fh or croak "binmode: $!";
2793 my $size = (stat($fh))[7];
2794 ($size % 24) == 0 or croak "inconsistent size: $size";
2796 if ($size == 0) {
2797 close $fh or croak "close: $!";
2798 return $want_commit ? (0, undef) : 0;
2801 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2802 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
2803 my ($r, $c) = unpack(rev_map_fmt, $buf);
2804 if ($want_commit && $c eq ('0' x40)) {
2805 if ($size < 48) {
2806 return $want_commit ? (0, undef) : 0;
2808 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2809 sysread($fh, $buf, 24) == 24 or croak "read: $!";
2810 ($r, $c) = unpack(rev_map_fmt, $buf);
2811 if ($c eq ('0'x40)) {
2812 croak "Penultimate record is all-zeroes in $map_path";
2815 close $fh or croak "close: $!";
2816 $want_commit ? ($r, $c) : $r;
2819 sub rev_map_get {
2820 my ($self, $rev, $uuid) = @_;
2821 my $map_path = $self->map_path($uuid);
2822 return undef unless -e $map_path;
2824 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
2825 binmode $fh or croak "binmode: $!";
2826 my $size = (stat($fh))[7];
2827 ($size % 24) == 0 or croak "inconsistent size: $size";
2829 if ($size == 0) {
2830 close $fh or croak "close: $fh";
2831 return undef;
2834 my ($l, $u) = (0, $size - 24);
2835 my ($r, $c, $buf);
2837 while ($l <= $u) {
2838 my $i = int(($l/24 + $u/24) / 2) * 24;
2839 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
2840 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
2841 my ($r, $c) = unpack('NH40', $buf);
2843 if ($r < $rev) {
2844 $l = $i + 24;
2845 } elsif ($r > $rev) {
2846 $u = $i - 24;
2847 } else { # $r == $rev
2848 close($fh) or croak "close: $!";
2849 return $c eq ('0' x 40) ? undef : $c;
2852 close($fh) or croak "close: $!";
2853 undef;
2856 # Finds the first svn revision that exists on (if $eq_ok is true) or
2857 # before $rev for the current branch. It will not search any lower
2858 # than $min_rev. Returns the git commit hash and svn revision number
2859 # if found, else (undef, undef).
2860 sub find_rev_before {
2861 my ($self, $rev, $eq_ok, $min_rev) = @_;
2862 --$rev unless $eq_ok;
2863 $min_rev ||= 1;
2864 while ($rev >= $min_rev) {
2865 if (my $c = $self->rev_map_get($rev)) {
2866 return ($rev, $c);
2868 --$rev;
2870 return (undef, undef);
2873 # Finds the first svn revision that exists on (if $eq_ok is true) or
2874 # after $rev for the current branch. It will not search any higher
2875 # than $max_rev. Returns the git commit hash and svn revision number
2876 # if found, else (undef, undef).
2877 sub find_rev_after {
2878 my ($self, $rev, $eq_ok, $max_rev) = @_;
2879 ++$rev unless $eq_ok;
2880 $max_rev ||= $self->rev_map_max;
2881 while ($rev <= $max_rev) {
2882 if (my $c = $self->rev_map_get($rev)) {
2883 return ($rev, $c);
2885 ++$rev;
2887 return (undef, undef);
2890 sub _new {
2891 my ($class, $repo_id, $ref_id, $path) = @_;
2892 unless (defined $repo_id && length $repo_id) {
2893 $repo_id = $Git::SVN::default_repo_id;
2895 unless (defined $ref_id && length $ref_id) {
2896 $_[2] = $ref_id = $Git::SVN::default_ref_id;
2898 $_[1] = $repo_id;
2899 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2900 $_[3] = $path = '' unless (defined $path);
2901 mkpath(["$ENV{GIT_DIR}/svn"]);
2902 bless {
2903 ref_id => $ref_id, dir => $dir, index => "$dir/index",
2904 path => $path, config => "$ENV{GIT_DIR}/svn/config",
2905 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
2908 # for read-only access of old .rev_db formats
2909 sub unlink_rev_db_symlink {
2910 my ($self) = @_;
2911 my $link = $self->rev_db_path;
2912 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
2913 if (-l $link) {
2914 unlink $link or croak "unlink: $link failed!";
2918 sub rev_db_path {
2919 my ($self, $uuid) = @_;
2920 my $db_path = $self->map_path($uuid);
2921 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
2922 or croak "map_path: $db_path does not contain '/.rev_map.' !";
2923 $db_path;
2926 # the new replacement for .rev_db
2927 sub map_path {
2928 my ($self, $uuid) = @_;
2929 $uuid ||= $self->ra_uuid;
2930 "$self->{map_root}.$uuid";
2933 sub uri_encode {
2934 my ($f) = @_;
2935 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2939 sub remove_username {
2940 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
2943 package Git::SVN::Prompt;
2944 use strict;
2945 use warnings;
2946 require SVN::Core;
2947 use vars qw/$_no_auth_cache $_username/;
2949 sub simple {
2950 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
2951 $may_save = undef if $_no_auth_cache;
2952 $default_username = $_username if defined $_username;
2953 if (defined $default_username && length $default_username) {
2954 if (defined $realm && length $realm) {
2955 print STDERR "Authentication realm: $realm\n";
2956 STDERR->flush;
2958 $cred->username($default_username);
2959 } else {
2960 username($cred, $realm, $may_save, $pool);
2962 $cred->password(_read_password("Password for '" .
2963 $cred->username . "': ", $realm));
2964 $cred->may_save($may_save);
2965 $SVN::_Core::SVN_NO_ERROR;
2968 sub ssl_server_trust {
2969 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2970 $may_save = undef if $_no_auth_cache;
2971 print STDERR "Error validating server certificate for '$realm':\n";
2973 no warnings 'once';
2974 # All variables SVN::Auth::SSL::* are used only once,
2975 # so we're shutting up Perl warnings about this.
2976 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
2977 print STDERR " - The certificate is not issued ",
2978 "by a trusted authority. Use the\n",
2979 " fingerprint to validate ",
2980 "the certificate manually!\n";
2982 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
2983 print STDERR " - The certificate hostname ",
2984 "does not match.\n";
2986 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
2987 print STDERR " - The certificate is not yet valid.\n";
2989 if ($failures & $SVN::Auth::SSL::EXPIRED) {
2990 print STDERR " - The certificate has expired.\n";
2992 if ($failures & $SVN::Auth::SSL::OTHER) {
2993 print STDERR " - The certificate has ",
2994 "an unknown error.\n";
2996 } # no warnings 'once'
2997 printf STDERR
2998 "Certificate information:\n".
2999 " - Hostname: %s\n".
3000 " - Valid: from %s until %s\n".
3001 " - Issuer: %s\n".
3002 " - Fingerprint: %s\n",
3003 map $cert_info->$_, qw(hostname valid_from valid_until
3004 issuer_dname fingerprint);
3005 my $choice;
3006 prompt:
3007 print STDERR $may_save ?
3008 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
3009 "(R)eject or accept (t)emporarily? ";
3010 STDERR->flush;
3011 $choice = lc(substr(<STDIN> || 'R', 0, 1));
3012 if ($choice =~ /^t$/i) {
3013 $cred->may_save(undef);
3014 } elsif ($choice =~ /^r$/i) {
3015 return -1;
3016 } elsif ($may_save && $choice =~ /^p$/i) {
3017 $cred->may_save($may_save);
3018 } else {
3019 goto prompt;
3021 $cred->accepted_failures($failures);
3022 $SVN::_Core::SVN_NO_ERROR;
3025 sub ssl_client_cert {
3026 my ($cred, $realm, $may_save, $pool) = @_;
3027 $may_save = undef if $_no_auth_cache;
3028 print STDERR "Client certificate filename: ";
3029 STDERR->flush;
3030 chomp(my $filename = <STDIN>);
3031 $cred->cert_file($filename);
3032 $cred->may_save($may_save);
3033 $SVN::_Core::SVN_NO_ERROR;
3036 sub ssl_client_cert_pw {
3037 my ($cred, $realm, $may_save, $pool) = @_;
3038 $may_save = undef if $_no_auth_cache;
3039 $cred->password(_read_password("Password: ", $realm));
3040 $cred->may_save($may_save);
3041 $SVN::_Core::SVN_NO_ERROR;
3044 sub username {
3045 my ($cred, $realm, $may_save, $pool) = @_;
3046 $may_save = undef if $_no_auth_cache;
3047 if (defined $realm && length $realm) {
3048 print STDERR "Authentication realm: $realm\n";
3050 my $username;
3051 if (defined $_username) {
3052 $username = $_username;
3053 } else {
3054 print STDERR "Username: ";
3055 STDERR->flush;
3056 chomp($username = <STDIN>);
3058 $cred->username($username);
3059 $cred->may_save($may_save);
3060 $SVN::_Core::SVN_NO_ERROR;
3063 sub _read_password {
3064 my ($prompt, $realm) = @_;
3065 print STDERR $prompt;
3066 STDERR->flush;
3067 require Term::ReadKey;
3068 Term::ReadKey::ReadMode('noecho');
3069 my $password = '';
3070 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
3071 last if $key =~ /[\012\015]/; # \n\r
3072 $password .= $key;
3074 Term::ReadKey::ReadMode('restore');
3075 print STDERR "\n";
3076 STDERR->flush;
3077 $password;
3080 package SVN::Git::Fetcher;
3081 use vars qw/@ISA/;
3082 use strict;
3083 use warnings;
3084 use Carp qw/croak/;
3085 use File::Temp qw/tempfile/;
3086 use IO::File qw//;
3088 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
3089 sub new {
3090 my ($class, $git_svn) = @_;
3091 my $self = SVN::Delta::Editor->new;
3092 bless $self, $class;
3093 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
3094 $self->{empty} = {};
3095 $self->{dir_prop} = {};
3096 $self->{file_prop} = {};
3097 $self->{absent_dir} = {};
3098 $self->{absent_file} = {};
3099 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
3100 $self;
3103 sub set_path_strip {
3104 my ($self, $path) = @_;
3105 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
3108 sub open_root {
3109 { path => '' };
3112 sub open_directory {
3113 my ($self, $path, $pb, $rev) = @_;
3114 { path => $path };
3117 sub git_path {
3118 my ($self, $path) = @_;
3119 if ($self->{path_strip}) {
3120 $path =~ s!$self->{path_strip}!! or
3121 die "Failed to strip path '$path' ($self->{path_strip})\n";
3123 $path;
3126 sub delete_entry {
3127 my ($self, $path, $rev, $pb) = @_;
3129 my $gpath = $self->git_path($path);
3130 return undef if ($gpath eq '');
3132 # remove entire directories.
3133 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
3134 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3135 -r --name-only -z/,
3136 $self->{c}, '--', $gpath);
3137 local $/ = "\0";
3138 while (<$ls>) {
3139 chomp;
3140 $self->{gii}->remove($_);
3141 print "\tD\t$_\n" unless $::_q;
3143 print "\tD\t$gpath/\n" unless $::_q;
3144 command_close_pipe($ls, $ctx);
3145 $self->{empty}->{$path} = 0
3146 } else {
3147 $self->{gii}->remove($gpath);
3148 print "\tD\t$gpath\n" unless $::_q;
3150 undef;
3153 sub open_file {
3154 my ($self, $path, $pb, $rev) = @_;
3155 my $gpath = $self->git_path($path);
3156 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
3157 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
3158 unless (defined $mode && defined $blob) {
3159 die "$path was not found in commit $self->{c} (r$rev)\n";
3161 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
3162 pool => SVN::Pool->new, action => 'M' };
3165 sub add_file {
3166 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
3167 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3168 delete $self->{empty}->{$dir};
3169 { path => $path, mode_a => 100644, mode_b => 100644,
3170 pool => SVN::Pool->new, action => 'A' };
3173 sub add_directory {
3174 my ($self, $path, $cp_path, $cp_rev) = @_;
3175 my $gpath = $self->git_path($path);
3176 if ($gpath eq '') {
3177 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3178 -r --name-only -z/,
3179 $self->{c});
3180 local $/ = "\0";
3181 while (<$ls>) {
3182 chomp;
3183 $self->{gii}->remove($_);
3184 print "\tD\t$_\n" unless $::_q;
3186 command_close_pipe($ls, $ctx);
3187 $self->{empty}->{$path} = 0;
3189 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3190 delete $self->{empty}->{$dir};
3191 $self->{empty}->{$path} = 1;
3192 { path => $path };
3195 sub change_dir_prop {
3196 my ($self, $db, $prop, $value) = @_;
3197 $self->{dir_prop}->{$db->{path}} ||= {};
3198 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
3199 undef;
3202 sub absent_directory {
3203 my ($self, $path, $pb) = @_;
3204 $self->{absent_dir}->{$pb->{path}} ||= [];
3205 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
3206 undef;
3209 sub absent_file {
3210 my ($self, $path, $pb) = @_;
3211 $self->{absent_file}->{$pb->{path}} ||= [];
3212 push @{$self->{absent_file}->{$pb->{path}}}, $path;
3213 undef;
3216 sub change_file_prop {
3217 my ($self, $fb, $prop, $value) = @_;
3218 if ($prop eq 'svn:executable') {
3219 if ($fb->{mode_b} != 120000) {
3220 $fb->{mode_b} = defined $value ? 100755 : 100644;
3222 } elsif ($prop eq 'svn:special') {
3223 $fb->{mode_b} = defined $value ? 120000 : 100644;
3224 } else {
3225 $self->{file_prop}->{$fb->{path}} ||= {};
3226 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
3228 undef;
3231 sub apply_textdelta {
3232 my ($self, $fb, $exp) = @_;
3233 my $fh = IO::File->new_tmpfile;
3234 $fh->autoflush(1);
3235 # $fh gets auto-closed() by SVN::TxDelta::apply(),
3236 # (but $base does not,) so dup() it for reading in close_file
3237 open my $dup, '<&', $fh or croak $!;
3238 my $base = IO::File->new_tmpfile;
3239 $base->autoflush(1);
3240 if ($fb->{blob}) {
3241 print $base 'link ' if ($fb->{mode_a} == 120000);
3242 my $size = $::_repository->cat_blob($fb->{blob}, $base);
3243 die "Failed to read object $fb->{blob}" if ($size < 0);
3245 if (defined $exp) {
3246 seek $base, 0, 0 or croak $!;
3247 my $got = ::md5sum($base);
3248 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
3249 "expected: $exp\n",
3250 " got: $got\n" if ($got ne $exp);
3253 seek $base, 0, 0 or croak $!;
3254 $fb->{fh} = $dup;
3255 $fb->{base} = $base;
3256 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
3259 sub close_file {
3260 my ($self, $fb, $exp) = @_;
3261 my $hash;
3262 my $path = $self->git_path($fb->{path});
3263 if (my $fh = $fb->{fh}) {
3264 if (defined $exp) {
3265 seek($fh, 0, 0) or croak $!;
3266 my $got = ::md5sum($fh);
3267 if ($got ne $exp) {
3268 die "Checksum mismatch: $path\n",
3269 "expected: $exp\n got: $got\n";
3272 sysseek($fh, 0, 0) or croak $!;
3273 if ($fb->{mode_b} == 120000) {
3274 eval {
3275 sysread($fh, my $buf, 5) == 5 or croak $!;
3276 $buf eq 'link ' or die "$path has mode 120000",
3277 " but is not a link";
3279 if ($@) {
3280 warn "$@\n";
3281 sysseek($fh, 0, 0) or croak $!;
3285 my ($tmp_fh, $tmp_filename) = File::Temp::tempfile(UNLINK => 1);
3286 my $result;
3287 while ($result = sysread($fh, my $string, 1024)) {
3288 my $wrote = syswrite($tmp_fh, $string, $result);
3289 defined($wrote) && $wrote == $result
3290 or croak("write $tmp_filename: $!\n");
3292 defined $result or croak $!;
3293 close $tmp_fh or croak $!;
3295 close $fh or croak $!;
3297 $hash = $::_repository->hash_and_insert_object($tmp_filename);
3298 unlink($tmp_filename);
3299 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
3300 close $fb->{base} or croak $!;
3301 } else {
3302 $hash = $fb->{blob} or die "no blob information\n";
3304 $fb->{pool}->clear;
3305 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
3306 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
3307 undef;
3310 sub abort_edit {
3311 my $self = shift;
3312 $self->{nr} = $self->{gii}->{nr};
3313 delete $self->{gii};
3314 $self->SUPER::abort_edit(@_);
3317 sub close_edit {
3318 my $self = shift;
3319 $self->{git_commit_ok} = 1;
3320 $self->{nr} = $self->{gii}->{nr};
3321 delete $self->{gii};
3322 $self->SUPER::close_edit(@_);
3325 package SVN::Git::Editor;
3326 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
3327 use strict;
3328 use warnings;
3329 use Carp qw/croak/;
3330 use IO::File;
3332 sub new {
3333 my ($class, $opts) = @_;
3334 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
3335 die "$_ required!\n" unless (defined $opts->{$_});
3338 my $pool = SVN::Pool->new;
3339 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
3340 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
3341 $opts->{r}, $mods);
3343 # $opts->{ra} functions should not be used after this:
3344 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
3345 $opts->{editor_cb}, $pool);
3346 my $self = SVN::Delta::Editor->new(@ce, $pool);
3347 bless $self, $class;
3348 foreach (qw/svn_path r tree_a tree_b/) {
3349 $self->{$_} = $opts->{$_};
3351 $self->{url} = $opts->{ra}->{url};
3352 $self->{mods} = $mods;
3353 $self->{types} = $types;
3354 $self->{pool} = $pool;
3355 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
3356 $self->{rm} = { };
3357 $self->{path_prefix} = length $self->{svn_path} ?
3358 "$self->{svn_path}/" : '';
3359 $self->{config} = $opts->{config};
3360 return $self;
3363 sub generate_diff {
3364 my ($tree_a, $tree_b) = @_;
3365 my @diff_tree = qw(diff-tree -z -r);
3366 if ($_cp_similarity) {
3367 push @diff_tree, "-C$_cp_similarity";
3368 } else {
3369 push @diff_tree, '-C';
3371 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
3372 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
3373 push @diff_tree, $tree_a, $tree_b;
3374 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
3375 local $/ = "\0";
3376 my $state = 'meta';
3377 my @mods;
3378 while (<$diff_fh>) {
3379 chomp $_; # this gets rid of the trailing "\0"
3380 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
3381 $::sha1\s($::sha1)\s
3382 ([MTCRAD])\d*$/xo) {
3383 push @mods, { mode_a => $1, mode_b => $2,
3384 sha1_b => $3, chg => $4 };
3385 if ($4 =~ /^(?:C|R)$/) {
3386 $state = 'file_a';
3387 } else {
3388 $state = 'file_b';
3390 } elsif ($state eq 'file_a') {
3391 my $x = $mods[$#mods] or croak "Empty array\n";
3392 if ($x->{chg} !~ /^(?:C|R)$/) {
3393 croak "Error parsing $_, $x->{chg}\n";
3395 $x->{file_a} = $_;
3396 $state = 'file_b';
3397 } elsif ($state eq 'file_b') {
3398 my $x = $mods[$#mods] or croak "Empty array\n";
3399 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
3400 croak "Error parsing $_, $x->{chg}\n";
3402 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
3403 croak "Error parsing $_, $x->{chg}\n";
3405 $x->{file_b} = $_;
3406 $state = 'meta';
3407 } else {
3408 croak "Error parsing $_\n";
3411 command_close_pipe($diff_fh, $ctx);
3412 \@mods;
3415 sub check_diff_paths {
3416 my ($ra, $pfx, $rev, $mods) = @_;
3417 my %types;
3418 $pfx .= '/' if length $pfx;
3420 sub type_diff_paths {
3421 my ($ra, $types, $path, $rev) = @_;
3422 my @p = split m#/+#, $path;
3423 my $c = shift @p;
3424 unless (defined $types->{$c}) {
3425 $types->{$c} = $ra->check_path($c, $rev);
3427 while (@p) {
3428 $c .= '/' . shift @p;
3429 next if defined $types->{$c};
3430 $types->{$c} = $ra->check_path($c, $rev);
3434 foreach my $m (@$mods) {
3435 foreach my $f (qw/file_a file_b/) {
3436 next unless defined $m->{$f};
3437 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
3438 if (length $pfx.$dir && ! defined $types{$dir}) {
3439 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
3443 \%types;
3446 sub split_path {
3447 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
3450 sub repo_path {
3451 my ($self, $path) = @_;
3452 $self->{path_prefix}.(defined $path ? $path : '');
3455 sub url_path {
3456 my ($self, $path) = @_;
3457 if ($self->{url} =~ m#^https?://#) {
3458 $path =~ s/([^a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
3460 $self->{url} . '/' . $self->repo_path($path);
3463 sub rmdirs {
3464 my ($self) = @_;
3465 my $rm = $self->{rm};
3466 delete $rm->{''}; # we never delete the url we're tracking
3467 return unless %$rm;
3469 foreach (keys %$rm) {
3470 my @d = split m#/#, $_;
3471 my $c = shift @d;
3472 $rm->{$c} = 1;
3473 while (@d) {
3474 $c .= '/' . shift @d;
3475 $rm->{$c} = 1;
3478 delete $rm->{$self->{svn_path}};
3479 delete $rm->{''}; # we never delete the url we're tracking
3480 return unless %$rm;
3482 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
3483 $self->{tree_b});
3484 local $/ = "\0";
3485 while (<$fh>) {
3486 chomp;
3487 my @dn = split m#/#, $_;
3488 while (pop @dn) {
3489 delete $rm->{join '/', @dn};
3491 unless (%$rm) {
3492 close $fh;
3493 return;
3496 command_close_pipe($fh, $ctx);
3498 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
3499 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
3500 $self->close_directory($bat->{$d}, $p);
3501 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
3502 print "\tD+\t$d/\n" unless $::_q;
3503 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
3504 delete $bat->{$d};
3508 sub open_or_add_dir {
3509 my ($self, $full_path, $baton) = @_;
3510 my $t = $self->{types}->{$full_path};
3511 if (!defined $t) {
3512 die "$full_path not known in r$self->{r} or we have a bug!\n";
3515 no warnings 'once';
3516 # SVN::Node::none and SVN::Node::file are used only once,
3517 # so we're shutting up Perl's warnings about them.
3518 if ($t == $SVN::Node::none) {
3519 return $self->add_directory($full_path, $baton,
3520 undef, -1, $self->{pool});
3521 } elsif ($t == $SVN::Node::dir) {
3522 return $self->open_directory($full_path, $baton,
3523 $self->{r}, $self->{pool});
3524 } # no warnings 'once'
3525 print STDERR "$full_path already exists in repository at ",
3526 "r$self->{r} and it is not a directory (",
3527 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
3528 } # no warnings 'once'
3529 exit 1;
3532 sub ensure_path {
3533 my ($self, $path) = @_;
3534 my $bat = $self->{bat};
3535 my $repo_path = $self->repo_path($path);
3536 return $bat->{''} unless (length $repo_path);
3537 my @p = split m#/+#, $repo_path;
3538 my $c = shift @p;
3539 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
3540 while (@p) {
3541 my $c0 = $c;
3542 $c .= '/' . shift @p;
3543 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
3545 return $bat->{$c};
3548 # Subroutine to convert a globbing pattern to a regular expression.
3549 # From perl cookbook.
3550 sub glob2pat {
3551 my $globstr = shift;
3552 my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
3553 $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
3554 return '^' . $globstr . '$';
3557 sub check_autoprop {
3558 my ($self, $pattern, $properties, $file, $fbat) = @_;
3559 # Convert the globbing pattern to a regular expression.
3560 my $regex = glob2pat($pattern);
3561 # Check if the pattern matches the file name.
3562 if($file =~ m/($regex)/) {
3563 # Parse the list of properties to set.
3564 my @props = split(/;/, $properties);
3565 foreach my $prop (@props) {
3566 # Parse 'name=value' syntax and set the property.
3567 if ($prop =~ /([^=]+)=(.*)/) {
3568 my ($n,$v) = ($1,$2);
3569 for ($n, $v) {
3570 s/^\s+//; s/\s+$//;
3572 $self->change_file_prop($fbat, $n, $v);
3578 sub apply_autoprops {
3579 my ($self, $file, $fbat) = @_;
3580 my $conf_t = ${$self->{config}}{'config'};
3581 no warnings 'once';
3582 # Check [miscellany]/enable-auto-props in svn configuration.
3583 if (SVN::_Core::svn_config_get_bool(
3584 $conf_t,
3585 $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
3586 $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
3587 0)) {
3588 # Auto-props are enabled. Enumerate them to look for matches.
3589 my $callback = sub {
3590 $self->check_autoprop($_[0], $_[1], $file, $fbat);
3592 SVN::_Core::svn_config_enumerate(
3593 $conf_t,
3594 $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
3595 $callback);
3599 sub A {
3600 my ($self, $m) = @_;
3601 my ($dir, $file) = split_path($m->{file_b});
3602 my $pbat = $self->ensure_path($dir);
3603 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3604 undef, -1);
3605 print "\tA\t$m->{file_b}\n" unless $::_q;
3606 $self->apply_autoprops($file, $fbat);
3607 $self->chg_file($fbat, $m);
3608 $self->close_file($fbat,undef,$self->{pool});
3611 sub C {
3612 my ($self, $m) = @_;
3613 my ($dir, $file) = split_path($m->{file_b});
3614 my $pbat = $self->ensure_path($dir);
3615 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3616 $self->url_path($m->{file_a}), $self->{r});
3617 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3618 $self->chg_file($fbat, $m);
3619 $self->close_file($fbat,undef,$self->{pool});
3622 sub delete_entry {
3623 my ($self, $path, $pbat) = @_;
3624 my $rpath = $self->repo_path($path);
3625 my ($dir, $file) = split_path($rpath);
3626 $self->{rm}->{$dir} = 1;
3627 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
3630 sub R {
3631 my ($self, $m) = @_;
3632 my ($dir, $file) = split_path($m->{file_b});
3633 my $pbat = $self->ensure_path($dir);
3634 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3635 $self->url_path($m->{file_a}), $self->{r});
3636 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3637 $self->chg_file($fbat, $m);
3638 $self->close_file($fbat,undef,$self->{pool});
3640 ($dir, $file) = split_path($m->{file_a});
3641 $pbat = $self->ensure_path($dir);
3642 $self->delete_entry($m->{file_a}, $pbat);
3645 sub M {
3646 my ($self, $m) = @_;
3647 my ($dir, $file) = split_path($m->{file_b});
3648 my $pbat = $self->ensure_path($dir);
3649 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
3650 $pbat,$self->{r},$self->{pool});
3651 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
3652 $self->chg_file($fbat, $m);
3653 $self->close_file($fbat,undef,$self->{pool});
3656 sub T { shift->M(@_) }
3658 sub change_file_prop {
3659 my ($self, $fbat, $pname, $pval) = @_;
3660 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
3663 sub chg_file {
3664 my ($self, $fbat, $m) = @_;
3665 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
3666 $self->change_file_prop($fbat,'svn:executable','*');
3667 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
3668 $self->change_file_prop($fbat,'svn:executable',undef);
3670 my $fh = IO::File->new_tmpfile or croak $!;
3671 if ($m->{mode_b} =~ /^120/) {
3672 print $fh 'link ' or croak $!;
3673 $self->change_file_prop($fbat,'svn:special','*');
3674 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
3675 $self->change_file_prop($fbat,'svn:special',undef);
3677 my $size = $::_repository->cat_blob($m->{sha1_b}, $fh);
3678 croak "Failed to read object $m->{sha1_b}" if ($size < 0);
3679 $fh->flush == 0 or croak $!;
3680 seek $fh, 0, 0 or croak $!;
3682 my $exp = ::md5sum($fh);
3683 seek $fh, 0, 0 or croak $!;
3685 my $pool = SVN::Pool->new;
3686 my $atd = $self->apply_textdelta($fbat, undef, $pool);
3687 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
3688 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
3689 $pool->clear;
3691 close $fh or croak $!;
3694 sub D {
3695 my ($self, $m) = @_;
3696 my ($dir, $file) = split_path($m->{file_b});
3697 my $pbat = $self->ensure_path($dir);
3698 print "\tD\t$m->{file_b}\n" unless $::_q;
3699 $self->delete_entry($m->{file_b}, $pbat);
3702 sub close_edit {
3703 my ($self) = @_;
3704 my ($p,$bat) = ($self->{pool}, $self->{bat});
3705 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
3706 next if $_ eq '';
3707 $self->close_directory($bat->{$_}, $p);
3709 $self->close_directory($bat->{''}, $p);
3710 $self->SUPER::close_edit($p);
3711 $p->clear;
3714 sub abort_edit {
3715 my ($self) = @_;
3716 $self->SUPER::abort_edit($self->{pool});
3719 sub DESTROY {
3720 my $self = shift;
3721 $self->SUPER::DESTROY(@_);
3722 $self->{pool}->clear;
3725 # this drives the editor
3726 sub apply_diff {
3727 my ($self) = @_;
3728 my $mods = $self->{mods};
3729 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
3730 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
3731 my $f = $m->{chg};
3732 if (defined $o{$f}) {
3733 $self->$f($m);
3734 } else {
3735 fatal("Invalid change type: $f");
3738 $self->rmdirs if $_rmdir;
3739 if (@$mods == 0) {
3740 $self->abort_edit;
3741 } else {
3742 $self->close_edit;
3744 return scalar @$mods;
3747 package Git::SVN::Ra;
3748 use vars qw/@ISA $config_dir $_log_window_size/;
3749 use strict;
3750 use warnings;
3751 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
3753 BEGIN {
3754 # enforce temporary pool usage for some simple functions
3755 no strict 'refs';
3756 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root/) {
3757 my $SUPER = "SUPER::$f";
3758 *$f = sub {
3759 my $self = shift;
3760 my $pool = SVN::Pool->new;
3761 my @ret = $self->$SUPER(@_,$pool);
3762 $pool->clear;
3763 wantarray ? @ret : $ret[0];
3768 sub _auth_providers () {
3770 SVN::Client::get_simple_provider(),
3771 SVN::Client::get_ssl_server_trust_file_provider(),
3772 SVN::Client::get_simple_prompt_provider(
3773 \&Git::SVN::Prompt::simple, 2),
3774 SVN::Client::get_ssl_client_cert_file_provider(),
3775 SVN::Client::get_ssl_client_cert_prompt_provider(
3776 \&Git::SVN::Prompt::ssl_client_cert, 2),
3777 SVN::Client::get_ssl_client_cert_pw_file_provider(),
3778 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
3779 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
3780 SVN::Client::get_username_provider(),
3781 SVN::Client::get_ssl_server_trust_prompt_provider(
3782 \&Git::SVN::Prompt::ssl_server_trust),
3783 SVN::Client::get_username_prompt_provider(
3784 \&Git::SVN::Prompt::username, 2)
3788 sub escape_uri_only {
3789 my ($uri) = @_;
3790 my @tmp;
3791 foreach (split m{/}, $uri) {
3792 s/([^\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
3793 push @tmp, $_;
3795 join('/', @tmp);
3798 sub escape_url {
3799 my ($url) = @_;
3800 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
3801 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
3802 $url = "$scheme://$domain$uri";
3804 $url;
3807 sub new {
3808 my ($class, $url) = @_;
3809 $url =~ s!/+$!!;
3810 return $RA if ($RA && $RA->{url} eq $url);
3812 SVN::_Core::svn_config_ensure($config_dir, undef);
3813 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
3814 my $config = SVN::Core::config_get_config($config_dir);
3815 $RA = undef;
3816 my $dont_store_passwords = 1;
3817 my $conf_t = ${$config}{'config'};
3819 no warnings 'once';
3820 # The usage of $SVN::_Core::SVN_CONFIG_* variables
3821 # produces warnings that variables are used only once.
3822 # I had not found the better way to shut them up, so
3823 # the warnings of type 'once' are disabled in this block.
3824 if (SVN::_Core::svn_config_get_bool($conf_t,
3825 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
3826 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
3827 1) == 0) {
3828 SVN::_Core::svn_auth_set_parameter($baton,
3829 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
3830 bless (\$dont_store_passwords, "_p_void"));
3832 if (SVN::_Core::svn_config_get_bool($conf_t,
3833 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
3834 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
3835 1) == 0) {
3836 $Git::SVN::Prompt::_no_auth_cache = 1;
3838 } # no warnings 'once'
3839 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
3840 config => $config,
3841 pool => SVN::Pool->new,
3842 auth_provider_callbacks => $callbacks);
3843 $self->{url} = $url;
3844 $self->{svn_path} = $url;
3845 $self->{repos_root} = $self->get_repos_root;
3846 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
3847 $self->{cache} = { check_path => { r => 0, data => {} },
3848 get_dir => { r => 0, data => {} } };
3849 $RA = bless $self, $class;
3852 sub check_path {
3853 my ($self, $path, $r) = @_;
3854 my $cache = $self->{cache}->{check_path};
3855 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
3856 return $cache->{data}->{$path};
3858 my $pool = SVN::Pool->new;
3859 my $t = $self->SUPER::check_path($path, $r, $pool);
3860 $pool->clear;
3861 if ($r != $cache->{r}) {
3862 %{$cache->{data}} = ();
3863 $cache->{r} = $r;
3865 $cache->{data}->{$path} = $t;
3868 sub get_dir {
3869 my ($self, $dir, $r) = @_;
3870 my $cache = $self->{cache}->{get_dir};
3871 if ($r == $cache->{r}) {
3872 if (my $x = $cache->{data}->{$dir}) {
3873 return wantarray ? @$x : $x->[0];
3876 my $pool = SVN::Pool->new;
3877 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
3878 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
3879 $pool->clear;
3880 if ($r != $cache->{r}) {
3881 %{$cache->{data}} = ();
3882 $cache->{r} = $r;
3884 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
3885 wantarray ? (\%dirents, $r, $props) : \%dirents;
3888 sub DESTROY {
3889 # do not call the real DESTROY since we store ourselves in $RA
3892 sub get_log {
3893 my ($self, @args) = @_;
3894 my $pool = SVN::Pool->new;
3895 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
3896 my $ret = $self->SUPER::get_log(@args, $pool);
3897 $pool->clear;
3898 $ret;
3901 sub trees_match {
3902 my ($self, $url1, $rev1, $url2, $rev2) = @_;
3903 my $ctx = SVN::Client->new(auth => _auth_providers);
3904 my $out = IO::File->new_tmpfile;
3906 # older SVN (1.1.x) doesn't take $pool as the last parameter for
3907 # $ctx->diff(), so we'll create a default one
3908 my $pool = SVN::Pool->new_default_sub;
3910 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
3911 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
3912 $out->flush;
3913 my $ret = (($out->stat)[7] == 0);
3914 close $out or croak $!;
3916 $ret;
3919 sub get_commit_editor {
3920 my ($self, $log, $cb, $pool) = @_;
3921 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
3922 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
3925 sub gs_do_update {
3926 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
3927 my $new = ($rev_a == $rev_b);
3928 my $path = $gs->{path};
3930 if ($new && -e $gs->{index}) {
3931 unlink $gs->{index} or die
3932 "Couldn't unlink index: $gs->{index}: $!\n";
3934 my $pool = SVN::Pool->new;
3935 $editor->set_path_strip($path);
3936 my (@pc) = split m#/#, $path;
3937 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
3938 1, $editor, $pool);
3939 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3941 # Since we can't rely on svn_ra_reparent being available, we'll
3942 # just have to do some magic with set_path to make it so
3943 # we only want a partial path.
3944 my $sp = '';
3945 my $final = join('/', @pc);
3946 while (@pc) {
3947 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
3948 $sp .= '/' if length $sp;
3949 $sp .= shift @pc;
3951 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
3953 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
3955 $reporter->finish_report($pool);
3956 $pool->clear;
3957 $editor->{git_commit_ok};
3960 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
3961 # svn_ra_reparent didn't work before 1.4)
3962 sub gs_do_switch {
3963 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
3964 my $path = $gs->{path};
3965 my $pool = SVN::Pool->new;
3967 my $full_url = $self->{url};
3968 my $old_url = $full_url;
3969 $full_url .= '/' . escape_uri_only($path) if length $path;
3970 my ($ra, $reparented);
3971 if ($old_url ne $full_url) {
3972 if ($old_url !~ m#^svn(\+ssh)?://#) {
3973 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
3974 $pool);
3975 $self->{url} = $full_url;
3976 $reparented = 1;
3977 } else {
3978 $_[0] = undef;
3979 $self = undef;
3980 $RA = undef;
3981 $ra = Git::SVN::Ra->new($full_url);
3982 $ra_invalid = 1;
3985 $ra ||= $self;
3986 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
3987 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3988 $reporter->set_path('', $rev_a, 0, @lock, $pool);
3989 $reporter->finish_report($pool);
3991 if ($reparented) {
3992 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
3993 $self->{url} = $old_url;
3996 $pool->clear;
3997 $editor->{git_commit_ok};
4000 sub longest_common_path {
4001 my ($gsv, $globs) = @_;
4002 my %common;
4003 my $common_max = scalar @$gsv;
4005 foreach my $gs (@$gsv) {
4006 my @tmp = split m#/#, $gs->{path};
4007 my $p = '';
4008 foreach (@tmp) {
4009 $p .= length($p) ? "/$_" : $_;
4010 $common{$p} ||= 0;
4011 $common{$p}++;
4014 $globs ||= [];
4015 $common_max += scalar @$globs;
4016 foreach my $glob (@$globs) {
4017 my @tmp = split m#/#, $glob->{path}->{left};
4018 my $p = '';
4019 foreach (@tmp) {
4020 $p .= length($p) ? "/$_" : $_;
4021 $common{$p} ||= 0;
4022 $common{$p}++;
4026 my $longest_path = '';
4027 foreach (sort {length $b <=> length $a} keys %common) {
4028 if ($common{$_} == $common_max) {
4029 $longest_path = $_;
4030 last;
4033 $longest_path;
4036 sub gs_fetch_loop_common {
4037 my ($self, $base, $head, $gsv, $globs) = @_;
4038 return if ($base > $head);
4039 my $inc = $_log_window_size;
4040 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
4041 my $longest_path = longest_common_path($gsv, $globs);
4042 my $ra_url = $self->{url};
4043 while (1) {
4044 my %revs;
4045 my $err;
4046 my $err_handler = $SVN::Error::handler;
4047 $SVN::Error::handler = sub {
4048 ($err) = @_;
4049 skip_unknown_revs($err);
4051 sub _cb {
4052 my ($paths, $r, $author, $date, $log) = @_;
4053 [ dup_changed_paths($paths),
4054 { author => $author, date => $date, log => $log } ];
4056 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
4057 sub { $revs{$_[1]} = _cb(@_) });
4058 if ($err && $max >= $head) {
4059 print STDERR "Path '$longest_path' ",
4060 "was probably deleted:\n",
4061 $err->expanded_message,
4062 "\nWill attempt to follow ",
4063 "revisions r$min .. r$max ",
4064 "committed before the deletion\n";
4065 my $hi = $max;
4066 while (--$hi >= $min) {
4067 my $ok;
4068 $self->get_log([$longest_path], $min, $hi,
4069 0, 1, 1, sub {
4070 $ok ||= $_[1];
4071 $revs{$_[1]} = _cb(@_) });
4072 if ($ok) {
4073 print STDERR "r$min .. r$ok OK\n";
4074 last;
4078 $SVN::Error::handler = $err_handler;
4080 my %exists = map { $_->{path} => $_ } @$gsv;
4081 foreach my $r (sort {$a <=> $b} keys %revs) {
4082 my ($paths, $logged) = @{$revs{$r}};
4084 foreach my $gs ($self->match_globs(\%exists, $paths,
4085 $globs, $r)) {
4086 if ($gs->rev_map_max >= $r) {
4087 next;
4089 next unless $gs->match_paths($paths, $r);
4090 $gs->{logged_rev_props} = $logged;
4091 if (my $last_commit = $gs->last_commit) {
4092 $gs->assert_index_clean($last_commit);
4094 my $log_entry = $gs->do_fetch($paths, $r);
4095 if ($log_entry) {
4096 $gs->do_git_commit($log_entry);
4098 $INDEX_FILES{$gs->{index}} = 1;
4100 foreach my $g (@$globs) {
4101 my $k = "svn-remote.$g->{remote}." .
4102 "$g->{t}-maxRev";
4103 Git::SVN::tmp_config($k, $r);
4105 if ($ra_invalid) {
4106 $_[0] = undef;
4107 $self = undef;
4108 $RA = undef;
4109 $self = Git::SVN::Ra->new($ra_url);
4110 $ra_invalid = undef;
4113 # pre-fill the .rev_db since it'll eventually get filled in
4114 # with '0' x40 if something new gets committed
4115 foreach my $gs (@$gsv) {
4116 next if $gs->rev_map_max >= $max;
4117 next if defined $gs->rev_map_get($max);
4118 $gs->rev_map_set($max, 0 x40);
4120 foreach my $g (@$globs) {
4121 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
4122 Git::SVN::tmp_config($k, $max);
4124 last if $max >= $head;
4125 $min = $max + 1;
4126 $max += $inc;
4127 $max = $head if ($max > $head);
4129 Git::SVN::gc();
4132 sub get_dir_globbed {
4133 my ($self, $left, $depth, $r) = @_;
4135 my @x = eval { $self->get_dir($left, $r) };
4136 return unless scalar @x == 3;
4137 my $dirents = $x[0];
4138 my @finalents;
4139 foreach my $de (keys %$dirents) {
4140 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
4141 if ($depth > 1) {
4142 my @args = ("$left/$de", $depth - 1, $r);
4143 foreach my $dir ($self->get_dir_globbed(@args)) {
4144 push @finalents, "$de/$dir";
4146 } else {
4147 push @finalents, $de;
4150 @finalents;
4153 sub match_globs {
4154 my ($self, $exists, $paths, $globs, $r) = @_;
4156 sub get_dir_check {
4157 my ($self, $exists, $g, $r) = @_;
4159 my @dirs = $self->get_dir_globbed($g->{path}->{left},
4160 $g->{path}->{depth},
4161 $r);
4163 foreach my $de (@dirs) {
4164 my $p = $g->{path}->full_path($de);
4165 next if $exists->{$p};
4166 next if (length $g->{path}->{right} &&
4167 ($self->check_path($p, $r) !=
4168 $SVN::Node::dir));
4169 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
4170 $g->{ref}->full_path($de), 1);
4173 foreach my $g (@$globs) {
4174 if (my $path = $paths->{"/$g->{path}->{left}"}) {
4175 if ($path->{action} =~ /^[AR]$/) {
4176 get_dir_check($self, $exists, $g, $r);
4179 foreach (keys %$paths) {
4180 if (/$g->{path}->{left_regex}/ &&
4181 !/$g->{path}->{regex}/) {
4182 next if $paths->{$_}->{action} !~ /^[AR]$/;
4183 get_dir_check($self, $exists, $g, $r);
4185 next unless /$g->{path}->{regex}/;
4186 my $p = $1;
4187 my $pathname = $g->{path}->full_path($p);
4188 next if $exists->{$pathname};
4189 next if ($self->check_path($pathname, $r) !=
4190 $SVN::Node::dir);
4191 $exists->{$pathname} = Git::SVN->init(
4192 $self->{url}, $pathname, undef,
4193 $g->{ref}->full_path($p), 1);
4195 my $c = '';
4196 foreach (split m#/#, $g->{path}->{left}) {
4197 $c .= "/$_";
4198 next unless ($paths->{$c} &&
4199 ($paths->{$c}->{action} =~ /^[AR]$/));
4200 get_dir_check($self, $exists, $g, $r);
4203 values %$exists;
4206 sub minimize_url {
4207 my ($self) = @_;
4208 return $self->{url} if ($self->{url} eq $self->{repos_root});
4209 my $url = $self->{repos_root};
4210 my @components = split(m!/!, $self->{svn_path});
4211 my $c = '';
4212 do {
4213 $url .= "/$c" if length $c;
4214 eval { (ref $self)->new($url)->get_latest_revnum };
4215 } while ($@ && ($c = shift @components));
4216 $url;
4219 sub can_do_switch {
4220 my $self = shift;
4221 unless (defined $can_do_switch) {
4222 my $pool = SVN::Pool->new;
4223 my $rep = eval {
4224 $self->do_switch(1, '', 0, $self->{url},
4225 SVN::Delta::Editor->new, $pool);
4227 if ($@) {
4228 $can_do_switch = 0;
4229 } else {
4230 $rep->abort_report($pool);
4231 $can_do_switch = 1;
4233 $pool->clear;
4235 $can_do_switch;
4238 sub skip_unknown_revs {
4239 my ($err) = @_;
4240 my $errno = $err->apr_err();
4241 # Maybe the branch we're tracking didn't
4242 # exist when the repo started, so it's
4243 # not an error if it doesn't, just continue
4245 # Wonderfully consistent library, eh?
4246 # 160013 - svn:// and file://
4247 # 175002 - http(s)://
4248 # 175007 - http(s):// (this repo required authorization, too...)
4249 # More codes may be discovered later...
4250 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
4251 my $err_key = $err->expanded_message;
4252 # revision numbers change every time, filter them out
4253 $err_key =~ s/\d+/\0/g;
4254 $err_key = "$errno\0$err_key";
4255 unless ($ignored_err{$err_key}) {
4256 warn "W: Ignoring error from SVN, path probably ",
4257 "does not exist: ($errno): ",
4258 $err->expanded_message,"\n";
4259 warn "W: Do not be alarmed at the above message ",
4260 "git-svn is just searching aggressively for ",
4261 "old history.\n",
4262 "This may take a while on large repositories\n";
4263 $ignored_err{$err_key} = 1;
4265 return;
4267 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
4270 # svn_log_changed_path_t objects passed to get_log are likely to be
4271 # overwritten even if only the refs are copied to an external variable,
4272 # so we should dup the structures in their entirety. Using an externally
4273 # passed pool (instead of our temporary and quickly cleared pool in
4274 # Git::SVN::Ra) does not help matters at all...
4275 sub dup_changed_paths {
4276 my ($paths) = @_;
4277 return undef unless $paths;
4278 my %ret;
4279 foreach my $p (keys %$paths) {
4280 my $i = $paths->{$p};
4281 my %s = map { $_ => $i->$_ }
4282 qw/copyfrom_path copyfrom_rev action/;
4283 $ret{$p} = \%s;
4285 \%ret;
4288 package Git::SVN::Log;
4289 use strict;
4290 use warnings;
4291 use POSIX qw/strftime/;
4292 use constant commit_log_separator => ('-' x 72) . "\n";
4293 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
4294 %rusers $show_commit $incremental/;
4295 my $l_fmt;
4297 sub cmt_showable {
4298 my ($c) = @_;
4299 return 1 if defined $c->{r};
4301 # big commit message got truncated by the 16k pretty buffer in rev-list
4302 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
4303 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
4304 @{$c->{l}} = ();
4305 my @log = command(qw/cat-file commit/, $c->{c});
4307 # shift off the headers
4308 shift @log while ($log[0] ne '');
4309 shift @log;
4311 # TODO: make $c->{l} not have a trailing newline in the future
4312 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
4314 (undef, $c->{r}, undef) = ::extract_metadata(
4315 (grep(/^git-svn-id: /, @log))[-1]);
4317 return defined $c->{r};
4320 sub log_use_color {
4321 return $color || Git->repository->get_colorbool('color.diff');
4324 sub git_svn_log_cmd {
4325 my ($r_min, $r_max, @args) = @_;
4326 my $head = 'HEAD';
4327 my (@files, @log_opts);
4328 foreach my $x (@args) {
4329 if ($x eq '--' || @files) {
4330 push @files, $x;
4331 } else {
4332 if (::verify_ref("$x^0")) {
4333 $head = $x;
4334 } else {
4335 push @log_opts, $x;
4340 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
4341 $gs ||= Git::SVN->_new;
4342 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
4343 $gs->refname);
4344 push @cmd, '-r' unless $non_recursive;
4345 push @cmd, qw/--raw --name-status/ if $verbose;
4346 push @cmd, '--color' if log_use_color();
4347 push @cmd, @log_opts;
4348 if (defined $r_max && $r_max == $r_min) {
4349 push @cmd, '--max-count=1';
4350 if (my $c = $gs->rev_map_get($r_max)) {
4351 push @cmd, $c;
4353 } elsif (defined $r_max) {
4354 if ($r_max < $r_min) {
4355 ($r_min, $r_max) = ($r_max, $r_min);
4357 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
4358 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
4359 # If there are no commits in the range, both $c_max and $c_min
4360 # will be undefined. If there is at least 1 commit in the
4361 # range, both will be defined.
4362 return () if !defined $c_min || !defined $c_max;
4363 if ($c_min eq $c_max) {
4364 push @cmd, '--max-count=1', $c_min;
4365 } else {
4366 push @cmd, '--boundary', "$c_min..$c_max";
4369 return (@cmd, @files);
4372 # adapted from pager.c
4373 sub config_pager {
4374 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
4375 if (!defined $pager) {
4376 $pager = 'less';
4377 } elsif (length $pager == 0 || $pager eq 'cat') {
4378 $pager = undef;
4380 $ENV{GIT_PAGER_IN_USE} = defined($pager);
4383 sub run_pager {
4384 return unless -t *STDOUT && defined $pager;
4385 pipe my $rfd, my $wfd or return;
4386 defined(my $pid = fork) or ::fatal "Can't fork: $!";
4387 if (!$pid) {
4388 open STDOUT, '>&', $wfd or
4389 ::fatal "Can't redirect to stdout: $!";
4390 return;
4392 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
4393 $ENV{LESS} ||= 'FRSX';
4394 exec $pager or ::fatal "Can't run pager: $! ($pager)";
4397 sub format_svn_date {
4398 return strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)", localtime(shift));
4401 sub parse_git_date {
4402 my ($t, $tz) = @_;
4403 # Date::Parse isn't in the standard Perl distro :(
4404 if ($tz =~ s/^\+//) {
4405 $t += tz_to_s_offset($tz);
4406 } elsif ($tz =~ s/^\-//) {
4407 $t -= tz_to_s_offset($tz);
4409 return $t;
4412 sub set_local_timezone {
4413 if (defined $TZ) {
4414 $ENV{TZ} = $TZ;
4415 } else {
4416 delete $ENV{TZ};
4420 sub tz_to_s_offset {
4421 my ($tz) = @_;
4422 $tz =~ s/(\d\d)$//;
4423 return ($1 * 60) + ($tz * 3600);
4426 sub get_author_info {
4427 my ($dest, $author, $t, $tz) = @_;
4428 $author =~ s/(?:^\s*|\s*$)//g;
4429 $dest->{a_raw} = $author;
4430 my $au;
4431 if ($::_authors) {
4432 $au = $rusers{$author} || undef;
4434 if (!$au) {
4435 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
4437 $dest->{t} = $t;
4438 $dest->{tz} = $tz;
4439 $dest->{a} = $au;
4440 $dest->{t_utc} = parse_git_date($t, $tz);
4443 sub process_commit {
4444 my ($c, $r_min, $r_max, $defer) = @_;
4445 if (defined $r_min && defined $r_max) {
4446 if ($r_min == $c->{r} && $r_min == $r_max) {
4447 show_commit($c);
4448 return 0;
4450 return 1 if $r_min == $r_max;
4451 if ($r_min < $r_max) {
4452 # we need to reverse the print order
4453 return 0 if (defined $limit && --$limit < 0);
4454 push @$defer, $c;
4455 return 1;
4457 if ($r_min != $r_max) {
4458 return 1 if ($r_min < $c->{r});
4459 return 1 if ($r_max > $c->{r});
4462 return 0 if (defined $limit && --$limit < 0);
4463 show_commit($c);
4464 return 1;
4467 sub show_commit {
4468 my $c = shift;
4469 if ($oneline) {
4470 my $x = "\n";
4471 if (my $l = $c->{l}) {
4472 while ($l->[0] =~ /^\s*$/) { shift @$l }
4473 $x = $l->[0];
4475 $l_fmt ||= 'A' . length($c->{r});
4476 print 'r',pack($l_fmt, $c->{r}),' | ';
4477 print "$c->{c} | " if $show_commit;
4478 print $x;
4479 } else {
4480 show_commit_normal($c);
4484 sub show_commit_changed_paths {
4485 my ($c) = @_;
4486 return unless $c->{changed};
4487 print "Changed paths:\n", @{$c->{changed}};
4490 sub show_commit_normal {
4491 my ($c) = @_;
4492 print commit_log_separator, "r$c->{r} | ";
4493 print "$c->{c} | " if $show_commit;
4494 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
4495 my $nr_line = 0;
4497 if (my $l = $c->{l}) {
4498 while ($l->[$#$l] eq "\n" && $#$l > 0
4499 && $l->[($#$l - 1)] eq "\n") {
4500 pop @$l;
4502 $nr_line = scalar @$l;
4503 if (!$nr_line) {
4504 print "1 line\n\n\n";
4505 } else {
4506 if ($nr_line == 1) {
4507 $nr_line = '1 line';
4508 } else {
4509 $nr_line .= ' lines';
4511 print $nr_line, "\n";
4512 show_commit_changed_paths($c);
4513 print "\n";
4514 print $_ foreach @$l;
4516 } else {
4517 print "1 line\n";
4518 show_commit_changed_paths($c);
4519 print "\n";
4522 foreach my $x (qw/raw stat diff/) {
4523 if ($c->{$x}) {
4524 print "\n";
4525 print $_ foreach @{$c->{$x}}
4530 sub cmd_show_log {
4531 my (@args) = @_;
4532 my ($r_min, $r_max);
4533 my $r_last = -1; # prevent dupes
4534 set_local_timezone();
4535 if (defined $::_revision) {
4536 if ($::_revision =~ /^(\d+):(\d+)$/) {
4537 ($r_min, $r_max) = ($1, $2);
4538 } elsif ($::_revision =~ /^\d+$/) {
4539 $r_min = $r_max = $::_revision;
4540 } else {
4541 ::fatal "-r$::_revision is not supported, use ",
4542 "standard 'git log' arguments instead";
4546 config_pager();
4547 @args = git_svn_log_cmd($r_min, $r_max, @args);
4548 if (!@args) {
4549 print commit_log_separator unless $incremental || $oneline;
4550 return;
4552 my $log = command_output_pipe(@args);
4553 run_pager();
4554 my (@k, $c, $d, $stat);
4555 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
4556 while (<$log>) {
4557 if (/^${esc_color}commit -?($::sha1_short)/o) {
4558 my $cmt = $1;
4559 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
4560 $r_last = $c->{r};
4561 process_commit($c, $r_min, $r_max, \@k) or
4562 goto out;
4564 $d = undef;
4565 $c = { c => $cmt };
4566 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
4567 get_author_info($c, $1, $2, $3);
4568 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
4569 # ignore
4570 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
4571 push @{$c->{raw}}, $_;
4572 } elsif (/^${esc_color}[ACRMDT]\t/) {
4573 # we could add $SVN->{svn_path} here, but that requires
4574 # remote access at the moment (repo_path_split)...
4575 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
4576 push @{$c->{changed}}, $_;
4577 } elsif (/^${esc_color}diff /o) {
4578 $d = 1;
4579 push @{$c->{diff}}, $_;
4580 } elsif ($d) {
4581 push @{$c->{diff}}, $_;
4582 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
4583 $esc_color*[\+\-]*$esc_color$/x) {
4584 $stat = 1;
4585 push @{$c->{stat}}, $_;
4586 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
4587 push @{$c->{stat}}, $_;
4588 $stat = undef;
4589 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
4590 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
4591 } elsif (s/^${esc_color} //o) {
4592 push @{$c->{l}}, $_;
4595 if ($c && defined $c->{r} && $c->{r} != $r_last) {
4596 $r_last = $c->{r};
4597 process_commit($c, $r_min, $r_max, \@k);
4599 if (@k) {
4600 ($r_min, $r_max) = ($r_max, $r_min);
4601 process_commit($_, $r_min, $r_max) foreach reverse @k;
4603 out:
4604 close $log;
4605 print commit_log_separator unless $incremental || $oneline;
4608 sub cmd_blame {
4609 my $path = pop;
4611 config_pager();
4612 run_pager();
4614 my ($fh, $ctx, $rev);
4616 if ($_git_format) {
4617 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
4618 while (my $line = <$fh>) {
4619 if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
4620 # Uncommitted edits show up as a rev ID of
4621 # all zeros, which we can't look up with
4622 # cmt_metadata
4623 if ($1 !~ /^0+$/) {
4624 (undef, $rev, undef) =
4625 ::cmt_metadata($1);
4626 $rev = '0' if (!$rev);
4627 } else {
4628 $rev = '0';
4630 $rev = sprintf('%-10s', $rev);
4631 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
4633 print $line;
4635 } else {
4636 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
4637 '--', $path);
4638 my ($sha1);
4639 my %authors;
4640 while (my $line = <$fh>) {
4641 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
4642 $sha1 = $1;
4643 (undef, $rev, undef) = ::cmt_metadata($1);
4644 $rev = '0' if (!$rev);
4646 elsif ($line =~ /^author (.*)/) {
4647 $authors{$rev} = $1;
4648 $authors{$rev} =~ s/\s/_/g;
4650 elsif ($line =~ /^\t(.*)$/) {
4651 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
4655 command_close_pipe($fh, $ctx);
4658 package Git::SVN::Migration;
4659 # these version numbers do NOT correspond to actual version numbers
4660 # of git nor git-svn. They are just relative.
4662 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
4664 # v1 layout: .git/$id/info/url, refs/remotes/$id
4666 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
4668 # v3 layout: .git/svn/$id, refs/remotes/$id
4669 # - info/url may remain for backwards compatibility
4670 # - this is what we migrate up to this layout automatically,
4671 # - this will be used by git svn init on single branches
4672 # v3.1 layout (auto migrated):
4673 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
4674 # for backwards compatibility
4676 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
4677 # - this is only created for newly multi-init-ed
4678 # repositories. Similar in spirit to the
4679 # --use-separate-remotes option in git-clone (now default)
4680 # - we do not automatically migrate to this (following
4681 # the example set by core git)
4683 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
4684 # - newer, more-efficient format that uses 24-bytes per record
4685 # with no filler space.
4686 # - use xxd -c24 < .rev_map.$UUID to view and debug
4687 # - This is a one-way migration, repositories updated to the
4688 # new format will not be able to use old git-svn without
4689 # rebuilding the .rev_db. Rebuilding the rev_db is not
4690 # possible if noMetadata or useSvmProps are set; but should
4691 # be no problem for users that use the (sensible) defaults.
4692 use strict;
4693 use warnings;
4694 use Carp qw/croak/;
4695 use File::Path qw/mkpath/;
4696 use File::Basename qw/dirname basename/;
4697 use vars qw/$_minimize/;
4699 sub migrate_from_v0 {
4700 my $git_dir = $ENV{GIT_DIR};
4701 return undef unless -d $git_dir;
4702 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
4703 my $migrated = 0;
4704 while (<$fh>) {
4705 chomp;
4706 my ($id, $orig_ref) = ($_, $_);
4707 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
4708 next unless -f "$git_dir/$id/info/url";
4709 my $new_ref = "refs/remotes/$id";
4710 if (::verify_ref("$new_ref^0")) {
4711 print STDERR "W: $orig_ref is probably an old ",
4712 "branch used by an ancient version of ",
4713 "git-svn.\n",
4714 "However, $new_ref also exists.\n",
4715 "We will not be able ",
4716 "to use this branch until this ",
4717 "ambiguity is resolved.\n";
4718 next;
4720 print STDERR "Migrating from v0 layout...\n" if !$migrated;
4721 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
4722 command_noisy('update-ref', $new_ref, $orig_ref);
4723 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
4724 $migrated++;
4726 command_close_pipe($fh, $ctx);
4727 print STDERR "Done migrating from v0 layout...\n" if $migrated;
4728 $migrated;
4731 sub migrate_from_v1 {
4732 my $git_dir = $ENV{GIT_DIR};
4733 my $migrated = 0;
4734 return $migrated unless -d $git_dir;
4735 my $svn_dir = "$git_dir/svn";
4737 # just in case somebody used 'svn' as their $id at some point...
4738 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
4740 print STDERR "Migrating from a git-svn v1 layout...\n";
4741 mkpath([$svn_dir]);
4742 print STDERR "Data from a previous version of git-svn exists, but\n\t",
4743 "$svn_dir\n\t(required for this version ",
4744 "($::VERSION) of git-svn) does not exist.\n";
4745 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
4746 while (<$fh>) {
4747 my $x = $_;
4748 next unless $x =~ s#^refs/remotes/##;
4749 chomp $x;
4750 next unless -f "$git_dir/$x/info/url";
4751 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
4752 next unless $u;
4753 my $dn = dirname("$git_dir/svn/$x");
4754 mkpath([$dn]) unless -d $dn;
4755 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
4756 mkpath(["$git_dir/svn/svn"]);
4757 print STDERR " - $git_dir/$x/info => ",
4758 "$git_dir/svn/$x/info\n";
4759 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
4760 croak "$!: $x";
4761 # don't worry too much about these, they probably
4762 # don't exist with repos this old (save for index,
4763 # and we can easily regenerate that)
4764 foreach my $f (qw/unhandled.log index .rev_db/) {
4765 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
4767 } else {
4768 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
4769 rename "$git_dir/$x", "$git_dir/svn/$x" or
4770 croak "$!: $x";
4772 $migrated++;
4774 command_close_pipe($fh, $ctx);
4775 print STDERR "Done migrating from a git-svn v1 layout\n";
4776 $migrated;
4779 sub read_old_urls {
4780 my ($l_map, $pfx, $path) = @_;
4781 my @dir;
4782 foreach (<$path/*>) {
4783 if (-r "$_/info/url") {
4784 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
4785 my $ref_id = $pfx . basename $_;
4786 my $url = ::file_to_s("$_/info/url");
4787 $l_map->{$ref_id} = $url;
4788 } elsif (-d $_) {
4789 push @dir, $_;
4792 foreach (@dir) {
4793 my $x = $_;
4794 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
4795 read_old_urls($l_map, $x, $_);
4799 sub migrate_from_v2 {
4800 my @cfg = command(qw/config -l/);
4801 return if grep /^svn-remote\..+\.url=/, @cfg;
4802 my %l_map;
4803 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
4804 my $migrated = 0;
4806 foreach my $ref_id (sort keys %l_map) {
4807 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
4808 if ($@) {
4809 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
4811 $migrated++;
4813 $migrated;
4816 sub minimize_connections {
4817 my $r = Git::SVN::read_all_remotes();
4818 my $new_urls = {};
4819 my $root_repos = {};
4820 foreach my $repo_id (keys %$r) {
4821 my $url = $r->{$repo_id}->{url} or next;
4822 my $fetch = $r->{$repo_id}->{fetch} or next;
4823 my $ra = Git::SVN::Ra->new($url);
4825 # skip existing cases where we already connect to the root
4826 if (($ra->{url} eq $ra->{repos_root}) ||
4827 ($ra->{repos_root} eq $repo_id)) {
4828 $root_repos->{$ra->{url}} = $repo_id;
4829 next;
4832 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
4833 my $root_path = $ra->{url};
4834 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
4835 foreach my $path (keys %$fetch) {
4836 my $ref_id = $fetch->{$path};
4837 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
4839 # make sure we can read when connecting to
4840 # a higher level of a repository
4841 my ($last_rev, undef) = $gs->last_rev_commit;
4842 if (!defined $last_rev) {
4843 $last_rev = eval {
4844 $root_ra->get_latest_revnum;
4846 next if $@;
4848 my $new = $root_path;
4849 $new .= length $path ? "/$path" : '';
4850 eval {
4851 $root_ra->get_log([$new], $last_rev, $last_rev,
4852 0, 0, 1, sub { });
4854 next if $@;
4855 $new_urls->{$ra->{repos_root}}->{$new} =
4856 { ref_id => $ref_id,
4857 old_repo_id => $repo_id,
4858 old_path => $path };
4862 my @emptied;
4863 foreach my $url (keys %$new_urls) {
4864 # see if we can re-use an existing [svn-remote "repo_id"]
4865 # instead of creating a(n ugly) new section:
4866 my $repo_id = $root_repos->{$url} || $url;
4868 my $fetch = $new_urls->{$url};
4869 foreach my $path (keys %$fetch) {
4870 my $x = $fetch->{$path};
4871 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
4872 my $pfx = "svn-remote.$x->{old_repo_id}";
4874 my $old_fetch = quotemeta("$x->{old_path}:".
4875 "refs/remotes/$x->{ref_id}");
4876 command_noisy(qw/config --unset/,
4877 "$pfx.fetch", '^'. $old_fetch . '$');
4878 delete $r->{$x->{old_repo_id}}->
4879 {fetch}->{$x->{old_path}};
4880 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
4881 command_noisy(qw/config --unset/,
4882 "$pfx.url");
4883 push @emptied, $x->{old_repo_id}
4887 if (@emptied) {
4888 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
4889 "$ENV{GIT_DIR}/config";
4890 print STDERR <<EOF;
4891 The following [svn-remote] sections in your config file ($file) are empty
4892 and can be safely removed:
4894 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
4898 sub migration_check {
4899 migrate_from_v0();
4900 migrate_from_v1();
4901 migrate_from_v2();
4902 minimize_connections() if $_minimize;
4905 package Git::IndexInfo;
4906 use strict;
4907 use warnings;
4908 use Git qw/command_input_pipe command_close_pipe/;
4910 sub new {
4911 my ($class) = @_;
4912 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
4913 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
4916 sub remove {
4917 my ($self, $path) = @_;
4918 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
4919 return ++$self->{nr};
4921 undef;
4924 sub update {
4925 my ($self, $mode, $hash, $path) = @_;
4926 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
4927 return ++$self->{nr};
4929 undef;
4932 sub DESTROY {
4933 my ($self) = @_;
4934 command_close_pipe($self->{gui}, $self->{ctx});
4937 package Git::SVN::GlobSpec;
4938 use strict;
4939 use warnings;
4941 sub new {
4942 my ($class, $glob) = @_;
4943 my $re = $glob;
4944 $re =~ s!/+$!!g; # no need for trailing slashes
4945 $re =~ m!^([^*]*)(\*(?:/\*)*)([^*]*)$!;
4946 my $temp = $re;
4947 my ($left, $right) = ($1, $3);
4948 $re = $2;
4949 my $depth = $re =~ tr/*/*/;
4950 if ($depth != $temp =~ tr/*/*/) {
4951 die "Only one set of wildcard directories " .
4952 "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
4954 if ($depth == 0) {
4955 die "One '*' is needed for glob: '$glob'\n";
4957 $re =~ s!\*!\[^/\]*!g;
4958 $re = quotemeta($left) . "($re)" . quotemeta($right);
4959 if (length $left && !($left =~ s!/+$!!g)) {
4960 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
4962 if (length $right && !($right =~ s!^/+!!g)) {
4963 die "Missing leading '/' on right side of: '$glob' ($right)\n";
4965 my $left_re = qr/^\/\Q$left\E(\/|$)/;
4966 bless { left => $left, right => $right, left_regex => $left_re,
4967 regex => qr/$re/, glob => $glob, depth => $depth }, $class;
4970 sub full_path {
4971 my ($self, $path) = @_;
4972 return (length $self->{left} ? "$self->{left}/" : '') .
4973 $path . (length $self->{right} ? "/$self->{right}" : '');
4976 __END__
4978 Data structures:
4981 $remotes = { # returned by read_all_remotes()
4982 'svn' => {
4983 # svn-remote.svn.url=https://svn.musicpd.org
4984 url => 'https://svn.musicpd.org',
4985 # svn-remote.svn.fetch=mpd/trunk:trunk
4986 fetch => {
4987 'mpd/trunk' => 'trunk',
4989 # svn-remote.svn.tags=mpd/tags/*:tags/*
4990 tags => {
4991 path => {
4992 left => 'mpd/tags',
4993 right => '',
4994 regex => qr!mpd/tags/([^/]+)$!,
4995 glob => 'tags/*',
4997 ref => {
4998 left => 'tags',
4999 right => '',
5000 regex => qr!tags/([^/]+)$!,
5001 glob => 'tags/*',
5007 $log_entry hashref as returned by libsvn_log_entry()
5009 log => 'whitespace-formatted log entry
5010 ', # trailing newline is preserved
5011 revision => '8', # integer
5012 date => '2004-02-24T17:01:44.108345Z', # commit date
5013 author => 'committer name'
5017 # this is generated by generate_diff();
5018 @mods = array of diff-index line hashes, each element represents one line
5019 of diff-index output
5021 diff-index line ($m hash)
5023 mode_a => first column of diff-index output, no leading ':',
5024 mode_b => second column of diff-index output,
5025 sha1_b => sha1sum of the final blob,
5026 chg => change type [MCRADT],
5027 file_a => original file name of a file (iff chg is 'C' or 'R')
5028 file_b => new/current file name of a file (any chg)
5032 # retval of read_url_paths{,_all}();
5033 $l_map = {
5034 # repository root url
5035 'https://svn.musicpd.org' => {
5036 # repository path # GIT_SVN_ID
5037 'mpd/trunk' => 'trunk',
5038 'mpd/tags/0.11.5' => 'tags/0.11.5',
5042 Notes:
5043 I don't trust the each() function on unless I created %hash myself
5044 because the internal iterator may not have started at base.