Merge branch 'jk/color-parse'
[git/gitweb.git] / git-svn.perl
blobd4cb538b93418ccb6205181d0c54932f92d3962f
1 #!/usr/bin/env perl
2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
4 use warnings;
5 use strict;
6 use vars qw/ $AUTHOR $VERSION
7 $sha1 $sha1_short $_revision $_repository
8 $_q $_authors %users/;
9 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
10 $VERSION = '@@GIT_VERSION@@';
12 # From which subdir have we been invoked?
13 my $cmd_dir_prefix = eval {
14 command_oneline([qw/rev-parse --show-prefix/], STDERR => 0)
15 } || '';
17 my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
18 $ENV{GIT_DIR} ||= '.git';
19 $Git::SVN::default_repo_id = 'svn';
20 $Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
21 $Git::SVN::Ra::_log_window_size = 100;
23 $Git::SVN::Log::TZ = $ENV{TZ};
24 $ENV{TZ} = 'UTC';
25 $| = 1; # unbuffer STDOUT
27 sub fatal (@) { print STDERR "@_\n"; exit 1 }
28 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
29 require SVN::Ra;
30 require SVN::Delta;
31 if ($SVN::Core::VERSION lt '1.1.0') {
32 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
34 push @Git::SVN::Ra::ISA, 'SVN::Ra';
35 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
36 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
37 use Carp qw/croak/;
38 use Digest::MD5;
39 use IO::File qw//;
40 use File::Basename qw/dirname basename/;
41 use File::Path qw/mkpath/;
42 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
43 use IPC::Open3;
44 use Git;
46 BEGIN {
47 # import functions from Git into our packages, en masse
48 no strict 'refs';
49 foreach (qw/command command_oneline command_noisy command_output_pipe
50 command_input_pipe command_close_pipe/) {
51 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
52 Git::SVN::Migration Git::SVN::Log Git::SVN),
53 __PACKAGE__) {
54 *{"${package}::$_"} = \&{"Git::$_"};
59 my ($SVN);
61 $sha1 = qr/[a-f\d]{40}/;
62 $sha1_short = qr/[a-f\d]{4,40}/;
63 my ($_stdin, $_help, $_edit,
64 $_message, $_file,
65 $_template, $_shared,
66 $_version, $_fetch_all, $_no_rebase,
67 $_merge, $_strategy, $_dry_run, $_local,
68 $_prefix, $_no_checkout, $_url, $_verbose,
69 $_git_format, $_commit_url, $_tag);
70 $Git::SVN::_follow_parent = 1;
71 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
72 'config-dir=s' => \$Git::SVN::Ra::config_dir,
73 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache );
74 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
75 'authors-file|A=s' => \$_authors,
76 'repack:i' => \$Git::SVN::_repack,
77 'noMetadata' => \$Git::SVN::_no_metadata,
78 'useSvmProps' => \$Git::SVN::_use_svm_props,
79 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
80 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
81 'no-checkout' => \$_no_checkout,
82 'quiet|q' => \$_q,
83 'repack-flags|repack-args|repack-opts=s' =>
84 \$Git::SVN::_repack_flags,
85 'use-log-author' => \$Git::SVN::_use_log_author,
86 'add-author-from' => \$Git::SVN::_add_author_from,
87 'localtime' => \$Git::SVN::_localtime,
88 %remote_opts );
90 my ($_trunk, $_tags, $_branches, $_stdlayout);
91 my %icv;
92 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
93 'trunk|T=s' => \$_trunk, 'tags|t=s' => \$_tags,
94 'branches|b=s' => \$_branches, 'prefix=s' => \$_prefix,
95 'stdlayout|s' => \$_stdlayout,
96 'minimize-url|m' => \$Git::SVN::_minimize_url,
97 'no-metadata' => sub { $icv{noMetadata} = 1 },
98 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
99 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
100 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
101 %remote_opts );
102 my %cmt_opts = ( 'edit|e' => \$_edit,
103 'rmdir' => \$SVN::Git::Editor::_rmdir,
104 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
105 'l=i' => \$SVN::Git::Editor::_rename_limit,
106 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
109 my %cmd = (
110 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
111 { 'revision|r=s' => \$_revision,
112 'fetch-all|all' => \$_fetch_all,
113 %fc_opts } ],
114 clone => [ \&cmd_clone, "Initialize and fetch revisions",
115 { 'revision|r=s' => \$_revision,
116 %fc_opts, %init_opts } ],
117 init => [ \&cmd_init, "Initialize a repo for tracking" .
118 " (requires URL argument)",
119 \%init_opts ],
120 'multi-init' => [ \&cmd_multi_init,
121 "Deprecated alias for ".
122 "'$0 init -T<trunk> -b<branches> -t<tags>'",
123 \%init_opts ],
124 dcommit => [ \&cmd_dcommit,
125 'Commit several diffs to merge with upstream',
126 { 'merge|m|M' => \$_merge,
127 'strategy|s=s' => \$_strategy,
128 'verbose|v' => \$_verbose,
129 'dry-run|n' => \$_dry_run,
130 'fetch-all|all' => \$_fetch_all,
131 'commit-url=s' => \$_commit_url,
132 'revision|r=i' => \$_revision,
133 'no-rebase' => \$_no_rebase,
134 %cmt_opts, %fc_opts } ],
135 branch => [ \&cmd_branch,
136 'Create a branch in the SVN repository',
137 { 'message|m=s' => \$_message,
138 'dry-run|n' => \$_dry_run,
139 'tag|t' => \$_tag } ],
140 tag => [ sub { $_tag = 1; cmd_branch(@_) },
141 'Create a tag in the SVN repository',
142 { 'message|m=s' => \$_message,
143 'dry-run|n' => \$_dry_run } ],
144 'set-tree' => [ \&cmd_set_tree,
145 "Set an SVN repository to a git tree-ish",
146 { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
147 'create-ignore' => [ \&cmd_create_ignore,
148 'Create a .gitignore per svn:ignore',
149 { 'revision|r=i' => \$_revision
150 } ],
151 'propget' => [ \&cmd_propget,
152 'Print the value of a property on a file or directory',
153 { 'revision|r=i' => \$_revision } ],
154 'proplist' => [ \&cmd_proplist,
155 'List all properties of a file or directory',
156 { 'revision|r=i' => \$_revision } ],
157 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
158 { 'revision|r=i' => \$_revision
159 } ],
160 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
161 { 'revision|r=i' => \$_revision
162 } ],
163 'multi-fetch' => [ \&cmd_multi_fetch,
164 "Deprecated alias for $0 fetch --all",
165 { 'revision|r=s' => \$_revision, %fc_opts } ],
166 'migrate' => [ sub { },
167 # no-op, we automatically run this anyways,
168 'Migrate configuration/metadata/layout from
169 previous versions of git-svn',
170 { 'minimize' => \$Git::SVN::Migration::_minimize,
171 %remote_opts } ],
172 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
173 { 'limit=i' => \$Git::SVN::Log::limit,
174 'revision|r=s' => \$_revision,
175 'verbose|v' => \$Git::SVN::Log::verbose,
176 'incremental' => \$Git::SVN::Log::incremental,
177 'oneline' => \$Git::SVN::Log::oneline,
178 'show-commit' => \$Git::SVN::Log::show_commit,
179 'non-recursive' => \$Git::SVN::Log::non_recursive,
180 'authors-file|A=s' => \$_authors,
181 'color' => \$Git::SVN::Log::color,
182 'pager=s' => \$Git::SVN::Log::pager
183 } ],
184 'find-rev' => [ \&cmd_find_rev,
185 "Translate between SVN revision numbers and tree-ish",
186 {} ],
187 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
188 { 'merge|m|M' => \$_merge,
189 'verbose|v' => \$_verbose,
190 'strategy|s=s' => \$_strategy,
191 'local|l' => \$_local,
192 'fetch-all|all' => \$_fetch_all,
193 'dry-run|n' => \$_dry_run,
194 %fc_opts } ],
195 'commit-diff' => [ \&cmd_commit_diff,
196 'Commit a diff between two trees',
197 { 'message|m=s' => \$_message,
198 'file|F=s' => \$_file,
199 'revision|r=s' => \$_revision,
200 %cmt_opts } ],
201 'info' => [ \&cmd_info,
202 "Show info about the latest SVN revision
203 on the current branch",
204 { 'url' => \$_url, } ],
205 'blame' => [ \&Git::SVN::Log::cmd_blame,
206 "Show what revision and author last modified each line of a file",
207 { 'git-format' => \$_git_format } ],
210 my $cmd;
211 for (my $i = 0; $i < @ARGV; $i++) {
212 if (defined $cmd{$ARGV[$i]}) {
213 $cmd = $ARGV[$i];
214 splice @ARGV, $i, 1;
215 last;
219 # make sure we're always running at the top-level working directory
220 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
221 unless (-d $ENV{GIT_DIR}) {
222 if ($git_dir_user_set) {
223 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
224 "but it is not a directory\n";
226 my $git_dir = delete $ENV{GIT_DIR};
227 my $cdup = undef;
228 git_cmd_try {
229 $cdup = command_oneline(qw/rev-parse --show-cdup/);
230 $git_dir = '.' unless ($cdup);
231 chomp $cdup if ($cdup);
232 $cdup = "." unless ($cdup && length $cdup);
233 } "Already at toplevel, but $git_dir not found\n";
234 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
235 unless (-d $git_dir) {
236 die "$git_dir still not found after going to ",
237 "'$cdup'\n";
239 $ENV{GIT_DIR} = $git_dir;
241 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
244 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
246 read_repo_config(\%opts);
247 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
248 Getopt::Long::Configure('pass_through');
250 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
251 'minimize-connections' => \$Git::SVN::Migration::_minimize,
252 'id|i=s' => \$Git::SVN::default_ref_id,
253 'svn-remote|remote|R=s' => sub {
254 $Git::SVN::no_reuse_existing = 1;
255 $Git::SVN::default_repo_id = $_[1] });
256 exit 1 if (!$rv && $cmd && $cmd ne 'log');
258 usage(0) if $_help;
259 version() if $_version;
260 usage(1) unless defined $cmd;
261 load_authors() if $_authors;
263 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
264 Git::SVN::Migration::migration_check();
266 Git::SVN::init_vars();
267 eval {
268 Git::SVN::verify_remotes_sanity();
269 $cmd{$cmd}->[0]->(@ARGV);
271 fatal $@ if $@;
272 post_fetch_checkout();
273 exit 0;
275 ####################### primary functions ######################
276 sub usage {
277 my $exit = shift || 0;
278 my $fd = $exit ? \*STDERR : \*STDOUT;
279 print $fd <<"";
280 git-svn - bidirectional operations between a single Subversion tree and git
281 Usage: git svn <command> [options] [arguments]\n
283 print $fd "Available commands:\n" unless $cmd;
285 foreach (sort keys %cmd) {
286 next if $cmd && $cmd ne $_;
287 next if /^multi-/; # don't show deprecated commands
288 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
289 foreach (sort keys %{$cmd{$_}->[2]}) {
290 # mixed-case options are for .git/config only
291 next if /[A-Z]/ && /^[a-z]+$/i;
292 # prints out arguments as they should be passed:
293 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
294 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
295 "--$_" : "-$_" }
296 split /\|/,$_)," $x\n";
299 print $fd <<"";
300 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
301 arbitrary identifier if you're tracking multiple SVN branches/repositories in
302 one git repository and want to keep them separate. See git-svn(1) for more
303 information.
305 exit $exit;
308 sub version {
309 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
310 exit 0;
313 sub do_git_init_db {
314 unless (-d $ENV{GIT_DIR}) {
315 my @init_db = ('init');
316 push @init_db, "--template=$_template" if defined $_template;
317 if (defined $_shared) {
318 if ($_shared =~ /[a-z]/) {
319 push @init_db, "--shared=$_shared";
320 } else {
321 push @init_db, "--shared";
324 command_noisy(@init_db);
325 $_repository = Git->repository(Repository => ".git");
327 my $set;
328 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
329 foreach my $i (keys %icv) {
330 die "'$set' and '$i' cannot both be set\n" if $set;
331 next unless defined $icv{$i};
332 command_noisy('config', "$pfx.$i", $icv{$i});
333 $set = $i;
337 sub init_subdir {
338 my $repo_path = shift or return;
339 mkpath([$repo_path]) unless -d $repo_path;
340 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
341 $ENV{GIT_DIR} = '.git';
342 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
345 sub cmd_clone {
346 my ($url, $path) = @_;
347 if (!defined $path &&
348 (defined $_trunk || defined $_branches || defined $_tags ||
349 defined $_stdlayout) &&
350 $url !~ m#^[a-z\+]+://#) {
351 $path = $url;
353 $path = basename($url) if !defined $path || !length $path;
354 cmd_init($url, $path);
355 Git::SVN::fetch_all($Git::SVN::default_repo_id);
358 sub cmd_init {
359 if (defined $_stdlayout) {
360 $_trunk = 'trunk' if (!defined $_trunk);
361 $_tags = 'tags' if (!defined $_tags);
362 $_branches = 'branches' if (!defined $_branches);
364 if (defined $_trunk || defined $_branches || defined $_tags) {
365 return cmd_multi_init(@_);
367 my $url = shift or die "SVN repository location required ",
368 "as a command-line argument\n";
369 init_subdir(@_);
370 do_git_init_db();
372 Git::SVN->init($url);
375 sub cmd_fetch {
376 if (grep /^\d+=./, @_) {
377 die "'<rev>=<commit>' fetch arguments are ",
378 "no longer supported.\n";
380 my ($remote) = @_;
381 if (@_ > 1) {
382 die "Usage: $0 fetch [--all] [svn-remote]\n";
384 $remote ||= $Git::SVN::default_repo_id;
385 if ($_fetch_all) {
386 cmd_multi_fetch();
387 } else {
388 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
392 sub cmd_set_tree {
393 my (@commits) = @_;
394 if ($_stdin || !@commits) {
395 print "Reading from stdin...\n";
396 @commits = ();
397 while (<STDIN>) {
398 if (/\b($sha1_short)\b/o) {
399 unshift @commits, $1;
403 my @revs;
404 foreach my $c (@commits) {
405 my @tmp = command('rev-parse',$c);
406 if (scalar @tmp == 1) {
407 push @revs, $tmp[0];
408 } elsif (scalar @tmp > 1) {
409 push @revs, reverse(command('rev-list',@tmp));
410 } else {
411 fatal "Failed to rev-parse $c";
414 my $gs = Git::SVN->new;
415 my ($r_last, $cmt_last) = $gs->last_rev_commit;
416 $gs->fetch;
417 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
418 fatal "There are new revisions that were fetched ",
419 "and need to be merged (or acknowledged) ",
420 "before committing.\nlast rev: $r_last\n",
421 " current: $gs->{last_rev}";
423 $gs->set_tree($_) foreach @revs;
424 print "Done committing ",scalar @revs," revisions to SVN\n";
425 unlink $gs->{index};
428 sub cmd_dcommit {
429 my $head = shift;
430 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
431 'Cannot dcommit with a dirty index. Commit your changes first, '
432 . "or stash them with `git stash'.\n";
433 $head ||= 'HEAD';
434 my @refs;
435 my ($url, $rev, $uuid, $gs) = working_head_info($head, \@refs);
436 unless ($gs) {
437 die "Unable to determine upstream SVN information from ",
438 "$head history.\nPerhaps the repository is empty.";
440 $url = defined $_commit_url ? $_commit_url : $gs->full_url;
441 my $last_rev = $_revision if defined $_revision;
442 if ($url) {
443 print "Committing to $url ...\n";
445 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
446 if ($_no_rebase && scalar(@$linear_refs) > 1) {
447 warn "Attempting to commit more than one change while ",
448 "--no-rebase is enabled.\n",
449 "If these changes depend on each other, re-running ",
450 "without --no-rebase may be required."
452 my $expect_url = $url;
453 Git::SVN::remove_username($expect_url);
454 while (1) {
455 my $d = shift @$linear_refs or last;
456 unless (defined $last_rev) {
457 (undef, $last_rev, undef) = cmt_metadata("$d~1");
458 unless (defined $last_rev) {
459 fatal "Unable to extract revision information ",
460 "from commit $d~1";
463 if ($_dry_run) {
464 print "diff-tree $d~1 $d\n";
465 } else {
466 my $cmt_rev;
467 my %ed_opts = ( r => $last_rev,
468 log => get_commit_entry($d)->{log},
469 ra => Git::SVN::Ra->new($url),
470 config => SVN::Core::config_get_config(
471 $Git::SVN::Ra::config_dir
473 tree_a => "$d~1",
474 tree_b => $d,
475 editor_cb => sub {
476 print "Committed r$_[0]\n";
477 $cmt_rev = $_[0];
479 svn_path => '');
480 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
481 print "No changes\n$d~1 == $d\n";
482 } elsif ($parents->{$d} && @{$parents->{$d}}) {
483 $gs->{inject_parents_dcommit}->{$cmt_rev} =
484 $parents->{$d};
486 $_fetch_all ? $gs->fetch_all : $gs->fetch;
487 $last_rev = $cmt_rev;
488 next if $_no_rebase;
490 # we always want to rebase against the current HEAD,
491 # not any head that was passed to us
492 my @diff = command('diff-tree', $d,
493 $gs->refname, '--');
494 my @finish;
495 if (@diff) {
496 @finish = rebase_cmd();
497 print STDERR "W: $d and ", $gs->refname,
498 " differ, using @finish:\n",
499 join("\n", @diff), "\n";
500 } else {
501 print "No changes between current HEAD and ",
502 $gs->refname,
503 "\nResetting to the latest ",
504 $gs->refname, "\n";
505 @finish = qw/reset --mixed/;
507 command_noisy(@finish, $gs->refname);
508 if (@diff) {
509 @refs = ();
510 my ($url_, $rev_, $uuid_, $gs_) =
511 working_head_info($head, \@refs);
512 my ($linear_refs_, $parents_) =
513 linearize_history($gs_, \@refs);
514 if (scalar(@$linear_refs) !=
515 scalar(@$linear_refs_)) {
516 fatal "# of revisions changed ",
517 "\nbefore:\n",
518 join("\n", @$linear_refs),
519 "\n\nafter:\n",
520 join("\n", @$linear_refs_), "\n",
521 'If you are attempting to commit ',
522 "merges, try running:\n\t",
523 'git rebase --interactive',
524 '--preserve-merges ',
525 $gs->refname,
526 "\nBefore dcommitting";
528 if ($url_ ne $expect_url) {
529 fatal "URL mismatch after rebase: ",
530 "$url_ != $expect_url";
532 if ($uuid_ ne $uuid) {
533 fatal "uuid mismatch after rebase: ",
534 "$uuid_ != $uuid";
536 # remap parents
537 my (%p, @l, $i);
538 for ($i = 0; $i < scalar @$linear_refs; $i++) {
539 my $new = $linear_refs_->[$i] or next;
540 $p{$new} =
541 $parents->{$linear_refs->[$i]};
542 push @l, $new;
544 $parents = \%p;
545 $linear_refs = \@l;
549 unlink $gs->{index};
552 sub cmd_branch {
553 my ($branch_name, $head) = @_;
555 unless (defined $branch_name && length $branch_name) {
556 die(($_tag ? "tag" : "branch") . " name required\n");
558 $head ||= 'HEAD';
560 my ($src, $rev, undef, $gs) = working_head_info($head);
562 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
563 my $glob = $remote->{ $_tag ? 'tags' : 'branches' };
564 my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
565 my $dst = join '/', $remote->{url}, $lft, $branch_name, ($rgt || ());
567 my $ctx = SVN::Client->new(
568 auth => Git::SVN::Ra::_auth_providers(),
569 log_msg => sub {
570 ${ $_[0] } = defined $_message
571 ? $_message
572 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
573 . $branch_name;
577 eval {
578 $ctx->ls($dst, 'HEAD', 0);
579 } and die "branch ${branch_name} already exists\n";
581 print "Copying ${src} at r${rev} to ${dst}...\n";
582 $ctx->copy($src, $rev, $dst)
583 unless $_dry_run;
585 $gs->fetch_all;
588 sub cmd_find_rev {
589 my $revision_or_hash = shift or die "SVN or git revision required ",
590 "as a command-line argument\n";
591 my $result;
592 if ($revision_or_hash =~ /^r\d+$/) {
593 my $head = shift;
594 $head ||= 'HEAD';
595 my @refs;
596 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
597 unless ($gs) {
598 die "Unable to determine upstream SVN information from ",
599 "$head history\n";
601 my $desired_revision = substr($revision_or_hash, 1);
602 $result = $gs->rev_map_get($desired_revision, $uuid);
603 } else {
604 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
605 $result = $rev;
607 print "$result\n" if $result;
610 sub cmd_rebase {
611 command_noisy(qw/update-index --refresh/);
612 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
613 unless ($gs) {
614 die "Unable to determine upstream SVN information from ",
615 "working tree history\n";
617 if ($_dry_run) {
618 print "Remote Branch: " . $gs->refname . "\n";
619 print "SVN URL: " . $url . "\n";
620 return;
622 if (command(qw/diff-index HEAD --/)) {
623 print STDERR "Cannot rebase with uncommited changes:\n";
624 command_noisy('status');
625 exit 1;
627 unless ($_local) {
628 # rebase will checkout for us, so no need to do it explicitly
629 $_no_checkout = 'true';
630 $_fetch_all ? $gs->fetch_all : $gs->fetch;
632 command_noisy(rebase_cmd(), $gs->refname);
635 sub cmd_show_ignore {
636 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
637 $gs ||= Git::SVN->new;
638 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
639 $gs->prop_walk($gs->{path}, $r, sub {
640 my ($gs, $path, $props) = @_;
641 print STDOUT "\n# $path\n";
642 my $s = $props->{'svn:ignore'} or return;
643 $s =~ s/[\r\n]+/\n/g;
644 chomp $s;
645 $s =~ s#^#$path#gm;
646 print STDOUT "$s\n";
650 sub cmd_show_externals {
651 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
652 $gs ||= Git::SVN->new;
653 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
654 $gs->prop_walk($gs->{path}, $r, sub {
655 my ($gs, $path, $props) = @_;
656 print STDOUT "\n# $path\n";
657 my $s = $props->{'svn:externals'} or return;
658 $s =~ s/[\r\n]+/\n/g;
659 chomp $s;
660 $s =~ s#^#$path#gm;
661 print STDOUT "$s\n";
665 sub cmd_create_ignore {
666 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
667 $gs ||= Git::SVN->new;
668 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
669 $gs->prop_walk($gs->{path}, $r, sub {
670 my ($gs, $path, $props) = @_;
671 # $path is of the form /path/to/dir/
672 my $ignore = '.' . $path . '.gitignore';
673 my $s = $props->{'svn:ignore'} or return;
674 open(GITIGNORE, '>', $ignore)
675 or fatal("Failed to open `$ignore' for writing: $!");
676 $s =~ s/[\r\n]+/\n/g;
677 chomp $s;
678 # Prefix all patterns so that the ignore doesn't apply
679 # to sub-directories.
680 $s =~ s#^#/#gm;
681 print GITIGNORE "$s\n";
682 close(GITIGNORE)
683 or fatal("Failed to close `$ignore': $!");
684 command_noisy('add', '-f', $ignore);
688 sub canonicalize_path {
689 my ($path) = @_;
690 my $dot_slash_added = 0;
691 if (substr($path, 0, 1) ne "/") {
692 $path = "./" . $path;
693 $dot_slash_added = 1;
695 # File::Spec->canonpath doesn't collapse x/../y into y (for a
696 # good reason), so let's do this manually.
697 $path =~ s#/+#/#g;
698 $path =~ s#/\.(?:/|$)#/#g;
699 $path =~ s#/[^/]+/\.\.##g;
700 $path =~ s#/$##g;
701 $path =~ s#^\./## if $dot_slash_added;
702 $path =~ s#^/##;
703 $path =~ s#^\.$##;
704 return $path;
707 # get_svnprops(PATH)
708 # ------------------
709 # Helper for cmd_propget and cmd_proplist below.
710 sub get_svnprops {
711 my $path = shift;
712 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
713 $gs ||= Git::SVN->new;
715 # prefix THE PATH by the sub-directory from which the user
716 # invoked us.
717 $path = $cmd_dir_prefix . $path;
718 fatal("No such file or directory: $path") unless -e $path;
719 my $is_dir = -d $path ? 1 : 0;
720 $path = $gs->{path} . '/' . $path;
722 # canonicalize the path (otherwise libsvn will abort or fail to
723 # find the file)
724 $path = canonicalize_path($path);
726 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
727 my $props;
728 if ($is_dir) {
729 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
731 else {
732 (undef, $props) = $gs->ra->get_file($path, $r, undef);
734 return $props;
737 # cmd_propget (PROP, PATH)
738 # ------------------------
739 # Print the SVN property PROP for PATH.
740 sub cmd_propget {
741 my ($prop, $path) = @_;
742 $path = '.' if not defined $path;
743 usage(1) if not defined $prop;
744 my $props = get_svnprops($path);
745 if (not defined $props->{$prop}) {
746 fatal("`$path' does not have a `$prop' SVN property.");
748 print $props->{$prop} . "\n";
751 # cmd_proplist (PATH)
752 # -------------------
753 # Print the list of SVN properties for PATH.
754 sub cmd_proplist {
755 my $path = shift;
756 $path = '.' if not defined $path;
757 my $props = get_svnprops($path);
758 print "Properties on '$path':\n";
759 foreach (sort keys %{$props}) {
760 print " $_\n";
764 sub cmd_multi_init {
765 my $url = shift;
766 unless (defined $_trunk || defined $_branches || defined $_tags) {
767 usage(1);
770 # there are currently some bugs that prevent multi-init/multi-fetch
771 # setups from working well without this.
772 $Git::SVN::_minimize_url = 1;
774 $_prefix = '' unless defined $_prefix;
775 if (defined $url) {
776 $url =~ s#/+$##;
777 init_subdir(@_);
779 do_git_init_db();
780 if (defined $_trunk) {
781 my $trunk_ref = $_prefix . 'trunk';
782 # try both old-style and new-style lookups:
783 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
784 unless ($gs_trunk) {
785 my ($trunk_url, $trunk_path) =
786 complete_svn_url($url, $_trunk);
787 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
788 undef, $trunk_ref);
791 return unless defined $_branches || defined $_tags;
792 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
793 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
794 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
797 sub cmd_multi_fetch {
798 my $remotes = Git::SVN::read_all_remotes();
799 foreach my $repo_id (sort keys %$remotes) {
800 if ($remotes->{$repo_id}->{url}) {
801 Git::SVN::fetch_all($repo_id, $remotes);
806 # this command is special because it requires no metadata
807 sub cmd_commit_diff {
808 my ($ta, $tb, $url) = @_;
809 my $usage = "Usage: $0 commit-diff -r<revision> ".
810 "<tree-ish> <tree-ish> [<URL>]";
811 fatal($usage) if (!defined $ta || !defined $tb);
812 my $svn_path = '';
813 if (!defined $url) {
814 my $gs = eval { Git::SVN->new };
815 if (!$gs) {
816 fatal("Needed URL or usable git-svn --id in ",
817 "the command-line\n", $usage);
819 $url = $gs->{url};
820 $svn_path = $gs->{path};
822 unless (defined $_revision) {
823 fatal("-r|--revision is a required argument\n", $usage);
825 if (defined $_message && defined $_file) {
826 fatal("Both --message/-m and --file/-F specified ",
827 "for the commit message.\n",
828 "I have no idea what you mean");
830 if (defined $_file) {
831 $_message = file_to_s($_file);
832 } else {
833 $_message ||= get_commit_entry($tb)->{log};
835 my $ra ||= Git::SVN::Ra->new($url);
836 my $r = $_revision;
837 if ($r eq 'HEAD') {
838 $r = $ra->get_latest_revnum;
839 } elsif ($r !~ /^\d+$/) {
840 die "revision argument: $r not understood by git-svn\n";
842 my %ed_opts = ( r => $r,
843 log => $_message,
844 ra => $ra,
845 tree_a => $ta,
846 tree_b => $tb,
847 editor_cb => sub { print "Committed r$_[0]\n" },
848 svn_path => $svn_path );
849 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
850 print "No changes\n$ta == $tb\n";
854 sub escape_uri_only {
855 my ($uri) = @_;
856 my @tmp;
857 foreach (split m{/}, $uri) {
858 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
859 push @tmp, $_;
861 join('/', @tmp);
864 sub escape_url {
865 my ($url) = @_;
866 if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
867 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
868 $url = "$scheme://$domain$uri";
870 $url;
873 sub cmd_info {
874 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
875 my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
876 if (exists $_[1]) {
877 die "Too many arguments specified\n";
880 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
882 if (!$file_type && !$diff_status) {
883 print STDERR "svn: '$path' is not under version control\n";
884 exit 1;
887 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
888 unless ($gs) {
889 die "Unable to determine upstream SVN information from ",
890 "working tree history\n";
893 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
894 $path = "." if $path eq "";
896 my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
898 if ($_url) {
899 print escape_url($full_url), "\n";
900 return;
903 my $result = "Path: $path\n";
904 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
905 $result .= "URL: " . escape_url($full_url) . "\n";
907 eval {
908 my $repos_root = $gs->repos_root;
909 Git::SVN::remove_username($repos_root);
910 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
912 if ($@) {
913 $result .= "Repository Root: (offline)\n";
915 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
916 ($SVN::Core::VERSION le '1.5.4' || $file_type ne "dir");
917 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
919 $result .= "Node Kind: " .
920 ($file_type eq "dir" ? "directory" : "file") . "\n";
922 my $schedule = $diff_status eq "A"
923 ? "add"
924 : ($diff_status eq "D" ? "delete" : "normal");
925 $result .= "Schedule: $schedule\n";
927 if ($diff_status eq "A") {
928 print $result, "\n";
929 return;
932 my ($lc_author, $lc_rev, $lc_date_utc);
933 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
934 my $log = command_output_pipe(@args);
935 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
936 while (<$log>) {
937 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
938 $lc_author = $1;
939 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
940 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
941 (undef, $lc_rev, undef) = ::extract_metadata($1);
944 close $log;
946 Git::SVN::Log::set_local_timezone();
948 $result .= "Last Changed Author: $lc_author\n";
949 $result .= "Last Changed Rev: $lc_rev\n";
950 $result .= "Last Changed Date: " .
951 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
953 if ($file_type ne "dir") {
954 my $text_last_updated_date =
955 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
956 $result .=
957 "Text Last Updated: " .
958 Git::SVN::Log::format_svn_date($text_last_updated_date) .
959 "\n";
960 my $checksum;
961 if ($diff_status eq "D") {
962 my ($fh, $ctx) =
963 command_output_pipe(qw(cat-file blob), "HEAD:$path");
964 if ($file_type eq "link") {
965 my $file_name = <$fh>;
966 $checksum = md5sum("link $file_name");
967 } else {
968 $checksum = md5sum($fh);
970 command_close_pipe($fh, $ctx);
971 } elsif ($file_type eq "link") {
972 my $file_name =
973 command(qw(cat-file blob), "HEAD:$path");
974 $checksum =
975 md5sum("link " . $file_name);
976 } else {
977 open FILE, "<", $path or die $!;
978 $checksum = md5sum(\*FILE);
979 close FILE or die $!;
981 $result .= "Checksum: " . $checksum . "\n";
984 print $result, "\n";
987 ########################### utility functions #########################
989 sub rebase_cmd {
990 my @cmd = qw/rebase/;
991 push @cmd, '-v' if $_verbose;
992 push @cmd, qw/--merge/ if $_merge;
993 push @cmd, "--strategy=$_strategy" if $_strategy;
994 @cmd;
997 sub post_fetch_checkout {
998 return if $_no_checkout;
999 my $gs = $Git::SVN::_head or return;
1000 return if verify_ref('refs/heads/master^0');
1002 my $valid_head = verify_ref('HEAD^0');
1003 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1004 return if ($valid_head || !verify_ref('HEAD^0'));
1006 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1007 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1008 return if -f $index;
1010 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1011 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1012 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1013 print STDERR "Checked out HEAD:\n ",
1014 $gs->full_url, " r", $gs->last_rev, "\n";
1017 sub complete_svn_url {
1018 my ($url, $path) = @_;
1019 $path =~ s#/+$##;
1020 if ($path !~ m#^[a-z\+]+://#) {
1021 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1022 fatal("E: '$path' is not a complete URL ",
1023 "and a separate URL is not specified");
1025 return ($url, $path);
1027 return ($path, '');
1030 sub complete_url_ls_init {
1031 my ($ra, $repo_path, $switch, $pfx) = @_;
1032 unless ($repo_path) {
1033 print STDERR "W: $switch not specified\n";
1034 return;
1036 $repo_path =~ s#/+$##;
1037 if ($repo_path =~ m#^[a-z\+]+://#) {
1038 $ra = Git::SVN::Ra->new($repo_path);
1039 $repo_path = '';
1040 } else {
1041 $repo_path =~ s#^/+##;
1042 unless ($ra) {
1043 fatal("E: '$repo_path' is not a complete URL ",
1044 "and a separate URL is not specified");
1047 my $url = $ra->{url};
1048 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1049 my $k = "svn-remote.$gs->{repo_id}.url";
1050 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1051 if ($orig_url && ($orig_url ne $gs->{url})) {
1052 die "$k already set: $orig_url\n",
1053 "wanted to set to: $gs->{url}\n";
1055 command_oneline('config', $k, $gs->{url}) unless $orig_url;
1056 my $remote_path = "$ra->{svn_path}/$repo_path";
1057 $remote_path =~ s#/+#/#g;
1058 $remote_path =~ s#^/##g;
1059 $remote_path .= "/*" if $remote_path !~ /\*/;
1060 my ($n) = ($switch =~ /^--(\w+)/);
1061 if (length $pfx && $pfx !~ m#/$#) {
1062 die "--prefix='$pfx' must have a trailing slash '/'\n";
1064 command_noisy('config',
1065 "svn-remote.$gs->{repo_id}.$n",
1066 "$remote_path:refs/remotes/$pfx*" .
1067 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1070 sub verify_ref {
1071 my ($ref) = @_;
1072 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1073 { STDERR => 0 }); };
1076 sub get_tree_from_treeish {
1077 my ($treeish) = @_;
1078 # $treeish can be a symbolic ref, too:
1079 my $type = command_oneline(qw/cat-file -t/, $treeish);
1080 my $expected;
1081 while ($type eq 'tag') {
1082 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1084 if ($type eq 'commit') {
1085 $expected = (grep /^tree /, command(qw/cat-file commit/,
1086 $treeish))[0];
1087 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1088 die "Unable to get tree from $treeish\n" unless $expected;
1089 } elsif ($type eq 'tree') {
1090 $expected = $treeish;
1091 } else {
1092 die "$treeish is a $type, expected tree, tag or commit\n";
1094 return $expected;
1097 sub get_commit_entry {
1098 my ($treeish) = shift;
1099 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1100 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1101 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1102 open my $log_fh, '>', $commit_editmsg or croak $!;
1104 my $type = command_oneline(qw/cat-file -t/, $treeish);
1105 if ($type eq 'commit' || $type eq 'tag') {
1106 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1107 $type, $treeish);
1108 my $in_msg = 0;
1109 my $author;
1110 my $saw_from = 0;
1111 my $msgbuf = "";
1112 while (<$msg_fh>) {
1113 if (!$in_msg) {
1114 $in_msg = 1 if (/^\s*$/);
1115 $author = $1 if (/^author (.*>)/);
1116 } elsif (/^git-svn-id: /) {
1117 # skip this for now, we regenerate the
1118 # correct one on re-fetch anyways
1119 # TODO: set *:merge properties or like...
1120 } else {
1121 if (/^From:/ || /^Signed-off-by:/) {
1122 $saw_from = 1;
1124 $msgbuf .= $_;
1127 $msgbuf =~ s/\s+$//s;
1128 if ($Git::SVN::_add_author_from && defined($author)
1129 && !$saw_from) {
1130 $msgbuf .= "\n\nFrom: $author";
1132 print $log_fh $msgbuf or croak $!;
1133 command_close_pipe($msg_fh, $ctx);
1135 close $log_fh or croak $!;
1137 if ($_edit || ($type eq 'tree')) {
1138 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1139 # TODO: strip out spaces, comments, like git-commit.sh
1140 system($editor, $commit_editmsg);
1142 rename $commit_editmsg, $commit_msg or croak $!;
1144 # SVN requires messages to be UTF-8 when entering the repo
1145 local $/;
1146 open $log_fh, '<', $commit_msg or croak $!;
1147 binmode $log_fh;
1148 chomp($log_entry{log} = <$log_fh>);
1150 if (my $enc = Git::config('i18n.commitencoding')) {
1151 require Encode;
1152 Encode::from_to($log_entry{log}, $enc, 'UTF-8');
1154 close $log_fh or croak $!;
1156 unlink $commit_msg;
1157 \%log_entry;
1160 sub s_to_file {
1161 my ($str, $file, $mode) = @_;
1162 open my $fd,'>',$file or croak $!;
1163 print $fd $str,"\n" or croak $!;
1164 close $fd or croak $!;
1165 chmod ($mode &~ umask, $file) if (defined $mode);
1168 sub file_to_s {
1169 my $file = shift;
1170 open my $fd,'<',$file or croak "$!: file: $file\n";
1171 local $/;
1172 my $ret = <$fd>;
1173 close $fd or croak $!;
1174 $ret =~ s/\s*$//s;
1175 return $ret;
1178 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1179 sub load_authors {
1180 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1181 my $log = $cmd eq 'log';
1182 while (<$authors>) {
1183 chomp;
1184 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1185 my ($user, $name, $email) = ($1, $2, $3);
1186 if ($log) {
1187 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1188 } else {
1189 $users{$user} = [$name, $email];
1192 close $authors or croak $!;
1195 # convert GetOpt::Long specs for use by git-config
1196 sub read_repo_config {
1197 return unless -d $ENV{GIT_DIR};
1198 my $opts = shift;
1199 my @config_only;
1200 foreach my $o (keys %$opts) {
1201 # if we have mixedCase and a long option-only, then
1202 # it's a config-only variable that we don't need for
1203 # the command-line.
1204 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1205 my $v = $opts->{$o};
1206 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1207 $key =~ s/-//g;
1208 my $arg = 'git config';
1209 $arg .= ' --int' if ($o =~ /[:=]i$/);
1210 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1211 if (ref $v eq 'ARRAY') {
1212 chomp(my @tmp = `$arg --get-all svn.$key`);
1213 @$v = @tmp if @tmp;
1214 } else {
1215 chomp(my $tmp = `$arg --get svn.$key`);
1216 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1217 $$v = $tmp;
1221 delete @$opts{@config_only} if @config_only;
1224 sub extract_metadata {
1225 my $id = shift or return (undef, undef, undef);
1226 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1227 \s([a-f\d\-]+)$/x);
1228 if (!defined $rev || !$uuid || !$url) {
1229 # some of the original repositories I made had
1230 # identifiers like this:
1231 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
1233 return ($url, $rev, $uuid);
1236 sub cmt_metadata {
1237 return extract_metadata((grep(/^git-svn-id: /,
1238 command(qw/cat-file commit/, shift)))[-1]);
1241 sub working_head_info {
1242 my ($head, $refs) = @_;
1243 my @args = ('log', '--no-color', '--first-parent', '--pretty=medium');
1244 my ($fh, $ctx) = command_output_pipe(@args, $head);
1245 my $hash;
1246 my %max;
1247 while (<$fh>) {
1248 if ( m{^commit ($::sha1)$} ) {
1249 unshift @$refs, $hash if $hash and $refs;
1250 $hash = $1;
1251 next;
1253 next unless s{^\s*(git-svn-id:)}{$1};
1254 my ($url, $rev, $uuid) = extract_metadata($_);
1255 if (defined $url && defined $rev) {
1256 next if $max{$url} and $max{$url} < $rev;
1257 if (my $gs = Git::SVN->find_by_url($url)) {
1258 my $c = $gs->rev_map_get($rev, $uuid);
1259 if ($c && $c eq $hash) {
1260 close $fh; # break the pipe
1261 return ($url, $rev, $uuid, $gs);
1262 } else {
1263 $max{$url} ||= $gs->rev_map_max;
1268 command_close_pipe($fh, $ctx);
1269 (undef, undef, undef, undef);
1272 sub read_commit_parents {
1273 my ($parents, $c) = @_;
1274 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1275 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1276 @{$parents->{$c}} = split(/ /, $p);
1279 sub linearize_history {
1280 my ($gs, $refs) = @_;
1281 my %parents;
1282 foreach my $c (@$refs) {
1283 read_commit_parents(\%parents, $c);
1286 my @linear_refs;
1287 my %skip = ();
1288 my $last_svn_commit = $gs->last_commit;
1289 foreach my $c (reverse @$refs) {
1290 next if $c eq $last_svn_commit;
1291 last if $skip{$c};
1293 unshift @linear_refs, $c;
1294 $skip{$c} = 1;
1296 # we only want the first parent to diff against for linear
1297 # history, we save the rest to inject when we finalize the
1298 # svn commit
1299 my $fp_a = verify_ref("$c~1");
1300 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1301 if (!$fp_a || !$fp_b) {
1302 die "Commit $c\n",
1303 "has no parent commit, and therefore ",
1304 "nothing to diff against.\n",
1305 "You should be working from a repository ",
1306 "originally created by git-svn\n";
1308 if ($fp_a ne $fp_b) {
1309 die "$c~1 = $fp_a, however parsing commit $c ",
1310 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1313 foreach my $p (@{$parents{$c}}) {
1314 $skip{$p} = 1;
1317 (\@linear_refs, \%parents);
1320 sub find_file_type_and_diff_status {
1321 my ($path) = @_;
1322 return ('dir', '') if $path eq '';
1324 my $diff_output =
1325 command_oneline(qw(diff --cached --name-status --), $path) || "";
1326 my $diff_status = (split(' ', $diff_output))[0] || "";
1328 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1330 return (undef, undef) if !$diff_status && !$ls_tree;
1332 if ($diff_status eq "A") {
1333 return ("link", $diff_status) if -l $path;
1334 return ("dir", $diff_status) if -d $path;
1335 return ("file", $diff_status);
1338 my $mode = (split(' ', $ls_tree))[0] || "";
1340 return ("link", $diff_status) if $mode eq "120000";
1341 return ("dir", $diff_status) if $mode eq "040000";
1342 return ("file", $diff_status);
1345 sub md5sum {
1346 my $arg = shift;
1347 my $ref = ref $arg;
1348 my $md5 = Digest::MD5->new();
1349 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
1350 $md5->addfile($arg) or croak $!;
1351 } elsif ($ref eq 'SCALAR') {
1352 $md5->add($$arg) or croak $!;
1353 } elsif (!$ref) {
1354 $md5->add($arg) or croak $!;
1355 } else {
1356 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1358 return $md5->hexdigest();
1361 package Git::SVN;
1362 use strict;
1363 use warnings;
1364 use Fcntl qw/:DEFAULT :seek/;
1365 use constant rev_map_fmt => 'NH40';
1366 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1367 $_repack $_repack_flags $_use_svm_props $_head
1368 $_use_svnsync_props $no_reuse_existing $_minimize_url
1369 $_use_log_author $_add_author_from $_localtime/;
1370 use Carp qw/croak/;
1371 use File::Path qw/mkpath/;
1372 use File::Copy qw/copy/;
1373 use IPC::Open3;
1375 my ($_gc_nr, $_gc_period);
1377 # properties that we do not log:
1378 my %SKIP_PROP;
1379 BEGIN {
1380 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1381 svn:special svn:executable
1382 svn:entry:committed-rev
1383 svn:entry:last-author
1384 svn:entry:uuid
1385 svn:entry:committed-date/;
1387 # some options are read globally, but can be overridden locally
1388 # per [svn-remote "..."] section. Command-line options will *NOT*
1389 # override options set in an [svn-remote "..."] section
1390 no strict 'refs';
1391 for my $option (qw/follow_parent no_metadata use_svm_props
1392 use_svnsync_props/) {
1393 my $key = $option;
1394 $key =~ tr/_//d;
1395 my $prop = "-$option";
1396 *$option = sub {
1397 my ($self) = @_;
1398 return $self->{$prop} if exists $self->{$prop};
1399 my $k = "svn-remote.$self->{repo_id}.$key";
1400 eval { command_oneline(qw/config --get/, $k) };
1401 if ($@) {
1402 $self->{$prop} = ${"Git::SVN::_$option"};
1403 } else {
1404 my $v = command_oneline(qw/config --bool/,$k);
1405 $self->{$prop} = $v eq 'false' ? 0 : 1;
1407 return $self->{$prop};
1413 my (%LOCKFILES, %INDEX_FILES);
1414 END {
1415 unlink keys %LOCKFILES if %LOCKFILES;
1416 unlink keys %INDEX_FILES if %INDEX_FILES;
1419 sub resolve_local_globs {
1420 my ($url, $fetch, $glob_spec) = @_;
1421 return unless defined $glob_spec;
1422 my $ref = $glob_spec->{ref};
1423 my $path = $glob_spec->{path};
1424 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
1425 next unless m#^refs/remotes/$ref->{regex}$#;
1426 my $p = $1;
1427 my $pathname = desanitize_refname($path->full_path($p));
1428 my $refname = desanitize_refname($ref->full_path($p));
1429 if (my $existing = $fetch->{$pathname}) {
1430 if ($existing ne $refname) {
1431 die "Refspec conflict:\n",
1432 "existing: refs/remotes/$existing\n",
1433 " globbed: refs/remotes/$refname\n";
1435 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
1436 $u =~ s!^\Q$url\E(/|$)!! or die
1437 "refs/remotes/$refname: '$url' not found in '$u'\n";
1438 if ($pathname ne $u) {
1439 warn "W: Refspec glob conflict ",
1440 "(ref: refs/remotes/$refname):\n",
1441 "expected path: $pathname\n",
1442 " real path: $u\n",
1443 "Continuing ahead with $u\n";
1444 next;
1446 } else {
1447 $fetch->{$pathname} = $refname;
1452 sub parse_revision_argument {
1453 my ($base, $head) = @_;
1454 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1455 return ($base, $head);
1457 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1458 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1459 return ($head, $head) if ($::_revision eq 'HEAD');
1460 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1461 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1462 die "revision argument: $::_revision not understood by git-svn\n";
1465 sub fetch_all {
1466 my ($repo_id, $remotes) = @_;
1467 if (ref $repo_id) {
1468 my $gs = $repo_id;
1469 $repo_id = undef;
1470 $repo_id = $gs->{repo_id};
1472 $remotes ||= read_all_remotes();
1473 my $remote = $remotes->{$repo_id} or
1474 die "[svn-remote \"$repo_id\"] unknown\n";
1475 my $fetch = $remote->{fetch};
1476 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1477 my (@gs, @globs);
1478 my $ra = Git::SVN::Ra->new($url);
1479 my $uuid = $ra->get_uuid;
1480 my $head = $ra->get_latest_revnum;
1481 my $base = defined $fetch ? $head : 0;
1483 # read the max revs for wildcard expansion (branches/*, tags/*)
1484 foreach my $t (qw/branches tags/) {
1485 defined $remote->{$t} or next;
1486 push @globs, $remote->{$t};
1487 my $max_rev = eval { tmp_config(qw/--int --get/,
1488 "svn-remote.$repo_id.${t}-maxRev") };
1489 if (defined $max_rev && ($max_rev < $base)) {
1490 $base = $max_rev;
1491 } elsif (!defined $max_rev) {
1492 $base = 0;
1496 if ($fetch) {
1497 foreach my $p (sort keys %$fetch) {
1498 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1499 my $lr = $gs->rev_map_max;
1500 if (defined $lr) {
1501 $base = $lr if ($lr < $base);
1503 push @gs, $gs;
1507 ($base, $head) = parse_revision_argument($base, $head);
1508 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1511 sub read_all_remotes {
1512 my $r = {};
1513 my $use_svm_props = eval { command_oneline(qw/config --bool
1514 svn.useSvmProps/) };
1515 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
1516 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1517 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*(.+)\s*$!) {
1518 my ($remote, $local_ref, $_remote_ref) = ($1, $2, $3);
1519 die("svn-remote.$remote: remote ref '$_remote_ref' "
1520 . "must start with 'refs/remotes/'\n")
1521 unless $_remote_ref =~ m{^refs/remotes/(.+)};
1522 my $remote_ref = $1;
1523 $local_ref =~ s{^/}{};
1524 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1525 $r->{$remote}->{svm} = {} if $use_svm_props;
1526 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
1527 $r->{$1}->{svm} = {};
1528 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1529 $r->{$1}->{url} = $2;
1530 } elsif (m!^(.+)\.(branches|tags)=
1531 (.*):refs/remotes/(.+)\s*$/!x) {
1532 my ($p, $g) = ($3, $4);
1533 my $rs = $r->{$1}->{$2} = {
1534 t => $2,
1535 remote => $1,
1536 path => Git::SVN::GlobSpec->new($p),
1537 ref => Git::SVN::GlobSpec->new($g) };
1538 if (length($rs->{ref}->{right}) != 0) {
1539 die "The '*' glob character must be the last ",
1540 "character of '$g'\n";
1545 map {
1546 if (defined $r->{$_}->{svm}) {
1547 my $svm;
1548 eval {
1549 my $section = "svn-remote.$_";
1550 $svm = {
1551 source => tmp_config('--get',
1552 "$section.svm-source"),
1553 replace => tmp_config('--get',
1554 "$section.svm-replace"),
1557 $r->{$_}->{svm} = $svm;
1559 } keys %$r;
1564 sub init_vars {
1565 $_gc_nr = $_gc_period = 1000;
1566 if (defined $_repack || defined $_repack_flags) {
1567 warn "Repack options are obsolete; they have no effect.\n";
1571 sub verify_remotes_sanity {
1572 return unless -d $ENV{GIT_DIR};
1573 my %seen;
1574 foreach (command(qw/config -l/)) {
1575 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1576 if ($seen{$1}) {
1577 die "Remote ref refs/remote/$1 is tracked by",
1578 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1579 "Please resolve this ambiguity in ",
1580 "your git configuration file before ",
1581 "continuing\n";
1583 $seen{$1} = $_;
1588 sub find_existing_remote {
1589 my ($url, $remotes) = @_;
1590 return undef if $no_reuse_existing;
1591 my $existing;
1592 foreach my $repo_id (keys %$remotes) {
1593 my $u = $remotes->{$repo_id}->{url} or next;
1594 next if $u ne $url;
1595 $existing = $repo_id;
1596 last;
1598 $existing;
1601 sub init_remote_config {
1602 my ($self, $url, $no_write) = @_;
1603 $url =~ s!/+$!!; # strip trailing slash
1604 my $r = read_all_remotes();
1605 my $existing = find_existing_remote($url, $r);
1606 if ($existing) {
1607 unless ($no_write) {
1608 print STDERR "Using existing ",
1609 "[svn-remote \"$existing\"]\n";
1611 $self->{repo_id} = $existing;
1612 } elsif ($_minimize_url) {
1613 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1614 $existing = find_existing_remote($min_url, $r);
1615 if ($existing) {
1616 unless ($no_write) {
1617 print STDERR "Using existing ",
1618 "[svn-remote \"$existing\"]\n";
1620 $self->{repo_id} = $existing;
1622 if ($min_url ne $url) {
1623 unless ($no_write) {
1624 print STDERR "Using higher level of URL: ",
1625 "$url => $min_url\n";
1627 my $old_path = $self->{path};
1628 $self->{path} = $url;
1629 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1630 if (length $old_path) {
1631 $self->{path} .= "/$old_path";
1633 $url = $min_url;
1636 my $orig_url;
1637 if (!$existing) {
1638 # verify that we aren't overwriting anything:
1639 $orig_url = eval {
1640 command_oneline('config', '--get',
1641 "svn-remote.$self->{repo_id}.url")
1643 if ($orig_url && ($orig_url ne $url)) {
1644 die "svn-remote.$self->{repo_id}.url already set: ",
1645 "$orig_url\nwanted to set to: $url\n";
1648 my ($xrepo_id, $xpath) = find_ref($self->refname);
1649 if (defined $xpath) {
1650 die "svn-remote.$xrepo_id.fetch already set to track ",
1651 "$xpath:refs/remotes/", $self->refname, "\n";
1653 unless ($no_write) {
1654 command_noisy('config',
1655 "svn-remote.$self->{repo_id}.url", $url);
1656 $self->{path} =~ s{^/}{};
1657 command_noisy('config', '--add',
1658 "svn-remote.$self->{repo_id}.fetch",
1659 "$self->{path}:".$self->refname);
1661 $self->{url} = $url;
1664 sub find_by_url { # repos_root and, path are optional
1665 my ($class, $full_url, $repos_root, $path) = @_;
1667 return undef unless defined $full_url;
1668 remove_username($full_url);
1669 remove_username($repos_root) if defined $repos_root;
1670 my $remotes = read_all_remotes();
1671 if (defined $full_url && defined $repos_root && !defined $path) {
1672 $path = $full_url;
1673 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1675 foreach my $repo_id (keys %$remotes) {
1676 my $u = $remotes->{$repo_id}->{url} or next;
1677 remove_username($u);
1678 next if defined $repos_root && $repos_root ne $u;
1680 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1681 foreach (qw/branches tags/) {
1682 resolve_local_globs($u, $fetch,
1683 $remotes->{$repo_id}->{$_});
1685 my $p = $path;
1686 my $rwr = rewrite_root({repo_id => $repo_id});
1687 my $svm = $remotes->{$repo_id}->{svm}
1688 if defined $remotes->{$repo_id}->{svm};
1689 unless (defined $p) {
1690 $p = $full_url;
1691 my $z = $u;
1692 my $prefix = '';
1693 if ($rwr) {
1694 $z = $rwr;
1695 } elsif (defined $svm) {
1696 $z = $svm->{source};
1697 $prefix = $svm->{replace};
1698 $prefix =~ s#^\Q$u\E(?:/|$)##;
1699 $prefix =~ s#/$##;
1701 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
1703 foreach my $f (keys %$fetch) {
1704 next if $f ne $p;
1705 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1708 undef;
1711 sub init {
1712 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1713 my $self = _new($class, $repo_id, $ref_id, $path);
1714 if (defined $url) {
1715 $self->init_remote_config($url, $no_write);
1717 $self;
1720 sub find_ref {
1721 my ($ref_id) = @_;
1722 foreach (command(qw/config -l/)) {
1723 next unless m!^svn-remote\.(.+)\.fetch=
1724 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1725 my ($repo_id, $path, $ref) = ($1, $2, $3);
1726 if ($ref eq $ref_id) {
1727 $path = '' if ($path =~ m#^\./?#);
1728 return ($repo_id, $path);
1731 (undef, undef, undef);
1734 sub new {
1735 my ($class, $ref_id, $repo_id, $path) = @_;
1736 if (defined $ref_id && !defined $repo_id && !defined $path) {
1737 ($repo_id, $path) = find_ref($ref_id);
1738 if (!defined $repo_id) {
1739 die "Could not find a \"svn-remote.*.fetch\" key ",
1740 "in the repository configuration matching: ",
1741 "refs/remotes/$ref_id\n";
1744 my $self = _new($class, $repo_id, $ref_id, $path);
1745 if (!defined $self->{path} || !length $self->{path}) {
1746 my $fetch = command_oneline('config', '--get',
1747 "svn-remote.$repo_id.fetch",
1748 ":refs/remotes/$ref_id\$") or
1749 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1750 "\":refs/remotes/$ref_id\$\" in config\n";
1751 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1753 $self->{url} = command_oneline('config', '--get',
1754 "svn-remote.$repo_id.url") or
1755 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1756 $self->rebuild;
1757 $self;
1760 sub refname {
1761 my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1763 # It cannot end with a slash /, we'll throw up on this because
1764 # SVN can't have directories with a slash in their name, either:
1765 if ($refname =~ m{/$}) {
1766 die "ref: '$refname' ends with a trailing slash, this is ",
1767 "not permitted by git nor Subversion\n";
1770 # It cannot have ASCII control character space, tilde ~, caret ^,
1771 # colon :, question-mark ?, asterisk *, space, or open bracket [
1772 # anywhere.
1774 # Additionally, % must be escaped because it is used for escaping
1775 # and we want our escaped refname to be reversible
1776 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1778 # no slash-separated component can begin with a dot .
1779 # /.* becomes /%2E*
1780 $refname =~ s{/\.}{/%2E}g;
1782 # It cannot have two consecutive dots .. anywhere
1783 # .. becomes %2E%2E
1784 $refname =~ s{\.\.}{%2E%2E}g;
1786 return $refname;
1789 sub desanitize_refname {
1790 my ($refname) = @_;
1791 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1792 return $refname;
1795 sub svm_uuid {
1796 my ($self) = @_;
1797 return $self->{svm}->{uuid} if $self->svm;
1798 $self->ra;
1799 unless ($self->{svm}) {
1800 die "SVM UUID not cached, and reading remotely failed\n";
1802 $self->{svm}->{uuid};
1805 sub svm {
1806 my ($self) = @_;
1807 return $self->{svm} if $self->{svm};
1808 my $svm;
1809 # see if we have it in our config, first:
1810 eval {
1811 my $section = "svn-remote.$self->{repo_id}";
1812 $svm = {
1813 source => tmp_config('--get', "$section.svm-source"),
1814 uuid => tmp_config('--get', "$section.svm-uuid"),
1815 replace => tmp_config('--get', "$section.svm-replace"),
1818 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1819 $self->{svm} = $svm;
1821 $self->{svm};
1824 sub _set_svm_vars {
1825 my ($self, $ra) = @_;
1826 return $ra if $self->svm;
1828 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1829 "(svm:source, svm:uuid) ",
1830 "from the following URLs:\n" );
1831 sub read_svm_props {
1832 my ($self, $ra, $path, $r) = @_;
1833 my $props = ($ra->get_dir($path, $r))[2];
1834 my $src = $props->{'svm:source'};
1835 my $uuid = $props->{'svm:uuid'};
1836 return undef if (!$src || !$uuid);
1838 chomp($src, $uuid);
1840 $uuid =~ m{^[0-9a-f\-]{30,}$}
1841 or die "doesn't look right - svm:uuid is '$uuid'\n";
1843 # the '!' is used to mark the repos_root!/relative/path
1844 $src =~ s{/?!/?}{/};
1845 $src =~ s{/+$}{}; # no trailing slashes please
1846 # username is of no interest
1847 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1849 my $replace = $ra->{url};
1850 $replace .= "/$path" if length $path;
1852 my $section = "svn-remote.$self->{repo_id}";
1853 tmp_config("$section.svm-source", $src);
1854 tmp_config("$section.svm-replace", $replace);
1855 tmp_config("$section.svm-uuid", $uuid);
1856 $self->{svm} = {
1857 source => $src,
1858 uuid => $uuid,
1859 replace => $replace
1863 my $r = $ra->get_latest_revnum;
1864 my $path = $self->{path};
1865 my %tried;
1866 while (length $path) {
1867 unless ($tried{"$self->{url}/$path"}) {
1868 return $ra if $self->read_svm_props($ra, $path, $r);
1869 $tried{"$self->{url}/$path"} = 1;
1871 $path =~ s#/?[^/]+$##;
1873 die "Path: '$path' should be ''\n" if $path ne '';
1874 return $ra if $self->read_svm_props($ra, $path, $r);
1875 $tried{"$self->{url}/$path"} = 1;
1877 if ($ra->{repos_root} eq $self->{url}) {
1878 die @err, (map { " $_\n" } keys %tried), "\n";
1881 # nope, make sure we're connected to the repository root:
1882 my $ok;
1883 my @tried_b;
1884 $path = $ra->{svn_path};
1885 $ra = Git::SVN::Ra->new($ra->{repos_root});
1886 while (length $path) {
1887 unless ($tried{"$ra->{url}/$path"}) {
1888 $ok = $self->read_svm_props($ra, $path, $r);
1889 last if $ok;
1890 $tried{"$ra->{url}/$path"} = 1;
1892 $path =~ s#/?[^/]+$##;
1894 die "Path: '$path' should be ''\n" if $path ne '';
1895 $ok ||= $self->read_svm_props($ra, $path, $r);
1896 $tried{"$ra->{url}/$path"} = 1;
1897 if (!$ok) {
1898 die @err, (map { " $_\n" } keys %tried), "\n";
1900 Git::SVN::Ra->new($self->{url});
1903 sub svnsync {
1904 my ($self) = @_;
1905 return $self->{svnsync} if $self->{svnsync};
1907 if ($self->no_metadata) {
1908 die "Can't have both 'noMetadata' and ",
1909 "'useSvnsyncProps' options set!\n";
1911 if ($self->rewrite_root) {
1912 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1913 "options set!\n";
1916 my $svnsync;
1917 # see if we have it in our config, first:
1918 eval {
1919 my $section = "svn-remote.$self->{repo_id}";
1921 my $url = tmp_config('--get', "$section.svnsync-url");
1922 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
1923 die "doesn't look right - svn:sync-from-url is '$url'\n";
1925 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
1926 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
1927 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1929 $svnsync = { url => $url, uuid => $uuid }
1931 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1932 return $self->{svnsync} = $svnsync;
1935 my $err = "useSvnsyncProps set, but failed to read " .
1936 "svnsync property: svn:sync-from-";
1937 my $rp = $self->ra->rev_proplist(0);
1939 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
1940 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
1941 die "doesn't look right - svn:sync-from-url is '$url'\n";
1943 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
1944 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
1945 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1947 my $section = "svn-remote.$self->{repo_id}";
1948 tmp_config('--add', "$section.svnsync-uuid", $uuid);
1949 tmp_config('--add', "$section.svnsync-url", $url);
1950 return $self->{svnsync} = { url => $url, uuid => $uuid };
1953 # this allows us to memoize our SVN::Ra UUID locally and avoid a
1954 # remote lookup (useful for 'git svn log').
1955 sub ra_uuid {
1956 my ($self) = @_;
1957 unless ($self->{ra_uuid}) {
1958 my $key = "svn-remote.$self->{repo_id}.uuid";
1959 my $uuid = eval { tmp_config('--get', $key) };
1960 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1961 $self->{ra_uuid} = $uuid;
1962 } else {
1963 die "ra_uuid called without URL\n" unless $self->{url};
1964 $self->{ra_uuid} = $self->ra->get_uuid;
1965 tmp_config('--add', $key, $self->{ra_uuid});
1968 $self->{ra_uuid};
1971 sub _set_repos_root {
1972 my ($self, $repos_root) = @_;
1973 my $k = "svn-remote.$self->{repo_id}.reposRoot";
1974 $repos_root ||= $self->ra->{repos_root};
1975 tmp_config($k, $repos_root);
1976 $repos_root;
1979 sub repos_root {
1980 my ($self) = @_;
1981 my $k = "svn-remote.$self->{repo_id}.reposRoot";
1982 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
1985 sub ra {
1986 my ($self) = shift;
1987 my $ra = Git::SVN::Ra->new($self->{url});
1988 $self->_set_repos_root($ra->{repos_root});
1989 if ($self->use_svm_props && !$self->{svm}) {
1990 if ($self->no_metadata) {
1991 die "Can't have both 'noMetadata' and ",
1992 "'useSvmProps' options set!\n";
1993 } elsif ($self->use_svnsync_props) {
1994 die "Can't have both 'useSvnsyncProps' and ",
1995 "'useSvmProps' options set!\n";
1997 $ra = $self->_set_svm_vars($ra);
1998 $self->{-want_revprops} = 1;
2000 $ra;
2003 sub rel_path {
2004 my ($self) = @_;
2005 my $repos_root = $self->ra->{repos_root};
2006 return $self->{path} if ($self->{url} eq $repos_root);
2007 my $url = $self->{url} .
2008 (length $self->{path} ? "/$self->{path}" : $self->{path});
2009 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
2010 $url;
2013 # prop_walk(PATH, REV, SUB)
2014 # -------------------------
2015 # Recursively traverse PATH at revision REV and invoke SUB for each
2016 # directory that contains a SVN property. SUB will be invoked as
2017 # follows: &SUB(gs, path, props); where `gs' is this instance of
2018 # Git::SVN, `path' the path to the directory where the properties
2019 # `props' were found. The `path' will be relative to point of checkout,
2020 # that is, if url://repo/trunk is the current Git branch, and that
2021 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
2022 # as `path' (note the trailing `/').
2023 sub prop_walk {
2024 my ($self, $path, $rev, $sub) = @_;
2026 $path =~ s#^/##;
2027 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2028 $path =~ s#^/*#/#g;
2029 my $p = $path;
2030 # Strip the irrelevant part of the path.
2031 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2032 # Ensure the path is terminated by a `/'.
2033 $p =~ s#/*$#/#;
2035 # The properties contain all the internal SVN stuff nobody
2036 # (usually) cares about.
2037 my $interesting_props = 0;
2038 foreach (keys %{$props}) {
2039 # If it doesn't start with `svn:', it must be a
2040 # user-defined property.
2041 ++$interesting_props and next if $_ !~ /^svn:/;
2042 # FIXME: Fragile, if SVN adds new public properties,
2043 # this needs to be updated.
2044 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2045 |eol-style|mime-type
2046 |externals|needs-lock)$/x;
2048 &$sub($self, $p, $props) if $interesting_props;
2050 foreach (sort keys %$dirent) {
2051 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
2052 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
2056 sub last_rev { ($_[0]->last_rev_commit)[0] }
2057 sub last_commit { ($_[0]->last_rev_commit)[1] }
2059 # returns the newest SVN revision number and newest commit SHA1
2060 sub last_rev_commit {
2061 my ($self) = @_;
2062 if (defined $self->{last_rev} && defined $self->{last_commit}) {
2063 return ($self->{last_rev}, $self->{last_commit});
2065 my $c = ::verify_ref($self->refname.'^0');
2066 if ($c && !$self->use_svm_props && !$self->no_metadata) {
2067 my $rev = (::cmt_metadata($c))[1];
2068 if (defined $rev) {
2069 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2070 return ($rev, $c);
2073 my $map_path = $self->map_path;
2074 unless (-e $map_path) {
2075 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2076 return (undef, undef);
2078 my ($rev, $commit) = $self->rev_map_max(1);
2079 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2080 return ($rev, $commit);
2083 sub get_fetch_range {
2084 my ($self, $min, $max) = @_;
2085 $max ||= $self->ra->get_latest_revnum;
2086 $min ||= $self->rev_map_max;
2087 (++$min, $max);
2090 sub tmp_config {
2091 my (@args) = @_;
2092 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2093 my $config = "$ENV{GIT_DIR}/svn/.metadata";
2094 if (! -f $config && -f $old_def_config) {
2095 rename $old_def_config, $config or
2096 die "Failed rename $old_def_config => $config: $!\n";
2098 my $old_config = $ENV{GIT_CONFIG};
2099 $ENV{GIT_CONFIG} = $config;
2100 $@ = undef;
2101 my @ret = eval {
2102 unless (-f $config) {
2103 mkfile($config);
2104 open my $fh, '>', $config or
2105 die "Can't open $config: $!\n";
2106 print $fh "; This file is used internally by ",
2107 "git-svn\n" or die
2108 "Couldn't write to $config: $!\n";
2109 print $fh "; You should not have to edit it\n" or
2110 die "Couldn't write to $config: $!\n";
2111 close $fh or die "Couldn't close $config: $!\n";
2113 command('config', @args);
2115 my $err = $@;
2116 if (defined $old_config) {
2117 $ENV{GIT_CONFIG} = $old_config;
2118 } else {
2119 delete $ENV{GIT_CONFIG};
2121 die $err if $err;
2122 wantarray ? @ret : $ret[0];
2125 sub tmp_index_do {
2126 my ($self, $sub) = @_;
2127 my $old_index = $ENV{GIT_INDEX_FILE};
2128 $ENV{GIT_INDEX_FILE} = $self->{index};
2129 $@ = undef;
2130 my @ret = eval {
2131 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2132 mkpath([$dir]) unless -d $dir;
2133 &$sub;
2135 my $err = $@;
2136 if (defined $old_index) {
2137 $ENV{GIT_INDEX_FILE} = $old_index;
2138 } else {
2139 delete $ENV{GIT_INDEX_FILE};
2141 die $err if $err;
2142 wantarray ? @ret : $ret[0];
2145 sub assert_index_clean {
2146 my ($self, $treeish) = @_;
2148 $self->tmp_index_do(sub {
2149 command_noisy('read-tree', $treeish) unless -e $self->{index};
2150 my $x = command_oneline('write-tree');
2151 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2152 /^tree ($::sha1)/mo);
2153 return if $y eq $x;
2155 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2156 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2157 command_noisy('read-tree', $treeish);
2158 $x = command_oneline('write-tree');
2159 if ($y ne $x) {
2160 ::fatal "trees ($treeish) $y != $x\n",
2161 "Something is seriously wrong...";
2166 sub get_commit_parents {
2167 my ($self, $log_entry) = @_;
2168 my (%seen, @ret, @tmp);
2169 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2170 if (my $ip = $self->{inject_parents}) {
2171 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2172 push @tmp, $commit;
2175 if (my $cur = ::verify_ref($self->refname.'^0')) {
2176 push @tmp, $cur;
2178 if (my $ipd = $self->{inject_parents_dcommit}) {
2179 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2180 push @tmp, @$commit;
2183 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2184 while (my $p = shift @tmp) {
2185 next if $seen{$p};
2186 $seen{$p} = 1;
2187 push @ret, $p;
2188 # MAXPARENT is defined to 16 in commit-tree.c:
2189 last if @ret >= 16;
2191 if (@tmp) {
2192 die "r$log_entry->{revision}: No room for parents:\n\t",
2193 join("\n\t", @tmp), "\n";
2195 @ret;
2198 sub rewrite_root {
2199 my ($self) = @_;
2200 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2201 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2202 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2203 if ($rwr) {
2204 $rwr =~ s#/+$##;
2205 if ($rwr !~ m#^[a-z\+]+://#) {
2206 die "$rwr is not a valid URL (key: $k)\n";
2209 $self->{-rewrite_root} = $rwr;
2212 sub metadata_url {
2213 my ($self) = @_;
2214 ($self->rewrite_root || $self->{url}) .
2215 (length $self->{path} ? '/' . $self->{path} : '');
2218 sub full_url {
2219 my ($self) = @_;
2220 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2224 sub set_commit_header_env {
2225 my ($log_entry) = @_;
2226 my %env;
2227 foreach my $ned (qw/NAME EMAIL DATE/) {
2228 foreach my $ac (qw/AUTHOR COMMITTER/) {
2229 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2233 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2234 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2235 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2237 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2238 ? $log_entry->{commit_name}
2239 : $log_entry->{name};
2240 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2241 ? $log_entry->{commit_email}
2242 : $log_entry->{email};
2243 \%env;
2246 sub restore_commit_header_env {
2247 my ($env) = @_;
2248 foreach my $ned (qw/NAME EMAIL DATE/) {
2249 foreach my $ac (qw/AUTHOR COMMITTER/) {
2250 my $k = "GIT_${ac}_${ned}";
2251 if (defined $env->{$k}) {
2252 $ENV{$k} = $env->{$k};
2253 } else {
2254 delete $ENV{$k};
2260 sub gc {
2261 command_noisy('gc', '--auto');
2264 sub do_git_commit {
2265 my ($self, $log_entry) = @_;
2266 my $lr = $self->last_rev;
2267 if (defined $lr && $lr >= $log_entry->{revision}) {
2268 die "Last fetched revision of ", $self->refname,
2269 " was r$lr, but we are about to fetch: ",
2270 "r$log_entry->{revision}!\n";
2272 if (my $c = $self->rev_map_get($log_entry->{revision})) {
2273 croak "$log_entry->{revision} = $c already exists! ",
2274 "Why are we refetching it?\n";
2276 my $old_env = set_commit_header_env($log_entry);
2277 my $tree = $log_entry->{tree};
2278 if (!defined $tree) {
2279 $tree = $self->tmp_index_do(sub {
2280 command_oneline('write-tree') });
2282 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2284 my @exec = ('git', 'commit-tree', $tree);
2285 foreach ($self->get_commit_parents($log_entry)) {
2286 push @exec, '-p', $_;
2288 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2289 or croak $!;
2290 binmode $msg_fh;
2292 # we always get UTF-8 from SVN, but we may want our commits in
2293 # a different encoding.
2294 if (my $enc = Git::config('i18n.commitencoding')) {
2295 require Encode;
2296 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
2298 print $msg_fh $log_entry->{log} or croak $!;
2299 restore_commit_header_env($old_env);
2300 unless ($self->no_metadata) {
2301 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2302 or croak $!;
2304 $msg_fh->flush == 0 or croak $!;
2305 close $msg_fh or croak $!;
2306 chomp(my $commit = do { local $/; <$out_fh> });
2307 close $out_fh or croak $!;
2308 waitpid $pid, 0;
2309 croak $? if $?;
2310 if ($commit !~ /^$::sha1$/o) {
2311 die "Failed to commit, invalid sha1: $commit\n";
2314 $self->rev_map_set($log_entry->{revision}, $commit, 1);
2316 $self->{last_rev} = $log_entry->{revision};
2317 $self->{last_commit} = $commit;
2318 print "r$log_entry->{revision}";
2319 if (defined $log_entry->{svm_revision}) {
2320 print " (\@$log_entry->{svm_revision})";
2321 $self->rev_map_set($log_entry->{svm_revision}, $commit,
2322 0, $self->svm_uuid);
2324 print " = $commit ($self->{ref_id})\n";
2325 if (--$_gc_nr == 0) {
2326 $_gc_nr = $_gc_period;
2327 gc();
2329 return $commit;
2332 sub match_paths {
2333 my ($self, $paths, $r) = @_;
2334 return 1 if $self->{path} eq '';
2335 if (my $path = $paths->{"/$self->{path}"}) {
2336 return ($path->{action} eq 'D') ? 0 : 1;
2338 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
2339 if (grep /$self->{path_regex}/, keys %$paths) {
2340 return 1;
2342 my $c = '';
2343 foreach (split m#/#, $self->{path}) {
2344 $c .= "/$_";
2345 next unless ($paths->{$c} &&
2346 ($paths->{$c}->{action} =~ /^[AR]$/));
2347 if ($self->ra->check_path($self->{path}, $r) ==
2348 $SVN::Node::dir) {
2349 return 1;
2352 return 0;
2355 sub find_parent_branch {
2356 my ($self, $paths, $rev) = @_;
2357 return undef unless $self->follow_parent;
2358 unless (defined $paths) {
2359 my $err_handler = $SVN::Error::handler;
2360 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2361 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
2362 $paths =
2363 Git::SVN::Ra::dup_changed_paths($_[0]) });
2364 $SVN::Error::handler = $err_handler;
2366 return undef unless defined $paths;
2368 # look for a parent from another branch:
2369 my @b_path_components = split m#/#, $self->rel_path;
2370 my @a_path_components;
2371 my $i;
2372 while (@b_path_components) {
2373 $i = $paths->{'/'.join('/', @b_path_components)};
2374 last if $i && defined $i->{copyfrom_path};
2375 unshift(@a_path_components, pop(@b_path_components));
2377 return undef unless defined $i && defined $i->{copyfrom_path};
2378 my $branch_from = $i->{copyfrom_path};
2379 if (@a_path_components) {
2380 print STDERR "branch_from: $branch_from => ";
2381 $branch_from .= '/'.join('/', @a_path_components);
2382 print STDERR $branch_from, "\n";
2384 my $r = $i->{copyfrom_rev};
2385 my $repos_root = $self->ra->{repos_root};
2386 my $url = $self->ra->{url};
2387 my $new_url = $repos_root . $branch_from;
2388 print STDERR "Found possible branch point: ",
2389 "$new_url => ", $self->full_url, ", $r\n";
2390 $branch_from =~ s#^/##;
2391 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
2392 unless ($gs) {
2393 my $ref_id = $self->{ref_id};
2394 $ref_id =~ s/\@\d+$//;
2395 $ref_id .= "\@$r";
2396 # just grow a tail if we're not unique enough :x
2397 $ref_id .= '-' while find_ref($ref_id);
2398 print STDERR "Initializing parent: $ref_id\n";
2399 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
2400 if ($u =~ s#^\Q$url\E(/|$)##) {
2401 $p = $u;
2402 $u = $url;
2403 $repo_id = $self->{repo_id};
2405 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
2407 my ($r0, $parent) = $gs->find_rev_before($r, 1);
2409 my ($base, $head);
2410 if (!defined $r0 || !defined $parent) {
2411 ($base, $head) = parse_revision_argument(0, $r);
2412 } else {
2413 if ($r0 < $r) {
2414 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
2415 0, 1, sub { $base = $_[1] - 1 });
2418 if (defined $base && $base <= $r) {
2419 $gs->fetch($base, $r);
2421 ($r0, $parent) = $gs->find_rev_before($r, 1);
2423 if (defined $r0 && defined $parent) {
2424 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
2425 my $ed;
2426 if ($self->ra->can_do_switch) {
2427 $self->assert_index_clean($parent);
2428 print STDERR "Following parent with do_switch\n";
2429 # do_switch works with svn/trunk >= r22312, but that
2430 # is not included with SVN 1.4.3 (the latest version
2431 # at the moment), so we can't rely on it
2432 $self->{last_commit} = $parent;
2433 $ed = SVN::Git::Fetcher->new($self);
2434 $gs->ra->gs_do_switch($r0, $rev, $gs,
2435 $self->full_url, $ed)
2436 or die "SVN connection failed somewhere...\n";
2437 } elsif ($self->ra->trees_match($new_url, $r0,
2438 $self->full_url, $rev)) {
2439 print STDERR "Trees match:\n",
2440 " $new_url\@$r0\n",
2441 " ${\$self->full_url}\@$rev\n",
2442 "Following parent with no changes\n";
2443 $self->tmp_index_do(sub {
2444 command_noisy('read-tree', $parent);
2446 $self->{last_commit} = $parent;
2447 } else {
2448 print STDERR "Following parent with do_update\n";
2449 $ed = SVN::Git::Fetcher->new($self);
2450 $self->ra->gs_do_update($rev, $rev, $self, $ed)
2451 or die "SVN connection failed somewhere...\n";
2453 print STDERR "Successfully followed parent\n";
2454 return $self->make_log_entry($rev, [$parent], $ed);
2456 return undef;
2459 sub do_fetch {
2460 my ($self, $paths, $rev) = @_;
2461 my $ed;
2462 my ($last_rev, @parents);
2463 if (my $lc = $self->last_commit) {
2464 # we can have a branch that was deleted, then re-added
2465 # under the same name but copied from another path, in
2466 # which case we'll have multiple parents (we don't
2467 # want to break the original ref, nor lose copypath info):
2468 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2469 push @{$log_entry->{parents}}, $lc;
2470 return $log_entry;
2472 $ed = SVN::Git::Fetcher->new($self);
2473 $last_rev = $self->{last_rev};
2474 $ed->{c} = $lc;
2475 @parents = ($lc);
2476 } else {
2477 $last_rev = $rev;
2478 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2479 return $log_entry;
2481 $ed = SVN::Git::Fetcher->new($self);
2483 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2484 die "SVN connection failed somewhere...\n";
2486 $self->make_log_entry($rev, \@parents, $ed);
2489 sub get_untracked {
2490 my ($self, $ed) = @_;
2491 my @out;
2492 my $h = $ed->{empty};
2493 foreach (sort keys %$h) {
2494 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2495 push @out, " $act: " . uri_encode($_);
2496 warn "W: $act: $_\n";
2498 foreach my $t (qw/dir_prop file_prop/) {
2499 $h = $ed->{$t} or next;
2500 foreach my $path (sort keys %$h) {
2501 my $ppath = $path eq '' ? '.' : $path;
2502 foreach my $prop (sort keys %{$h->{$path}}) {
2503 next if $SKIP_PROP{$prop};
2504 my $v = $h->{$path}->{$prop};
2505 my $t_ppath_prop = "$t: " .
2506 uri_encode($ppath) . ' ' .
2507 uri_encode($prop);
2508 if (defined $v) {
2509 push @out, " +$t_ppath_prop " .
2510 uri_encode($v);
2511 } else {
2512 push @out, " -$t_ppath_prop";
2517 foreach my $t (qw/absent_file absent_directory/) {
2518 $h = $ed->{$t} or next;
2519 foreach my $parent (sort keys %$h) {
2520 foreach my $path (sort @{$h->{$parent}}) {
2521 push @out, " $t: " .
2522 uri_encode("$parent/$path");
2523 warn "W: $t: $parent/$path ",
2524 "Insufficient permissions?\n";
2528 \@out;
2531 # parse_svn_date(DATE)
2532 # --------------------
2533 # Given a date (in UTC) from Subversion, return a string in the format
2534 # "<TZ Offset> <local date/time>" that Git will use.
2536 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
2537 # is true we'll convert it to the local timezone instead.
2538 sub parse_svn_date {
2539 my $date = shift || return '+0000 1970-01-01 00:00:00';
2540 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2541 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
2542 croak "Unable to parse date: $date\n";
2543 my $parsed_date; # Set next.
2545 if ($Git::SVN::_localtime) {
2546 # Translate the Subversion datetime to an epoch time.
2547 # Begin by switching ourselves to $date's timezone, UTC.
2548 my $old_env_TZ = $ENV{TZ};
2549 $ENV{TZ} = 'UTC';
2551 my $epoch_in_UTC =
2552 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
2554 # Determine our local timezone (including DST) at the
2555 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
2556 # value of TZ, if any, at the time we were run.
2557 if (defined $Git::SVN::Log::TZ) {
2558 $ENV{TZ} = $Git::SVN::Log::TZ;
2559 } else {
2560 delete $ENV{TZ};
2563 my $our_TZ =
2564 POSIX::strftime('%Z', $S, $M, $H, $d, $m - 1, $Y - 1900);
2566 # This converts $epoch_in_UTC into our local timezone.
2567 my ($sec, $min, $hour, $mday, $mon, $year,
2568 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
2570 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
2571 $our_TZ, $year + 1900, $mon + 1,
2572 $mday, $hour, $min, $sec);
2574 # Reset us to the timezone in effect when we entered
2575 # this routine.
2576 if (defined $old_env_TZ) {
2577 $ENV{TZ} = $old_env_TZ;
2578 } else {
2579 delete $ENV{TZ};
2581 } else {
2582 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
2585 return $parsed_date;
2588 sub check_author {
2589 my ($author) = @_;
2590 if (!defined $author || length $author == 0) {
2591 $author = '(no author)';
2592 } elsif (defined $::_authors && ! defined $::users{$author}) {
2593 die "Author: $author not defined in $::_authors file\n";
2595 $author;
2598 sub make_log_entry {
2599 my ($self, $rev, $parents, $ed) = @_;
2600 my $untracked = $self->get_untracked($ed);
2602 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
2603 print $un "r$rev\n" or croak $!;
2604 print $un $_, "\n" foreach @$untracked;
2605 my %log_entry = ( parents => $parents || [], revision => $rev,
2606 log => '');
2608 my $headrev;
2609 my $logged = delete $self->{logged_rev_props};
2610 if (!$logged || $self->{-want_revprops}) {
2611 my $rp = $self->ra->rev_proplist($rev);
2612 foreach (sort keys %$rp) {
2613 my $v = $rp->{$_};
2614 if (/^svn:(author|date|log)$/) {
2615 $log_entry{$1} = $v;
2616 } elsif ($_ eq 'svm:headrev') {
2617 $headrev = $v;
2618 } else {
2619 print $un " rev_prop: ", uri_encode($_), ' ',
2620 uri_encode($v), "\n";
2623 } else {
2624 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
2626 close $un or croak $!;
2628 $log_entry{date} = parse_svn_date($log_entry{date});
2629 $log_entry{log} .= "\n";
2630 my $author = $log_entry{author} = check_author($log_entry{author});
2631 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
2632 : ($author, undef);
2634 my ($commit_name, $commit_email) = ($name, $email);
2635 if ($_use_log_author) {
2636 my $name_field;
2637 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
2638 $name_field = $1;
2639 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
2640 $name_field = $1;
2642 if (!defined $name_field) {
2643 if (!defined $email) {
2644 $email = $name;
2646 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
2647 ($name, $email) = ($1, $2);
2648 } elsif ($name_field =~ /(.*)@/) {
2649 ($name, $email) = ($1, $name_field);
2650 } else {
2651 ($name, $email) = ($name_field, $name_field);
2654 if (defined $headrev && $self->use_svm_props) {
2655 if ($self->rewrite_root) {
2656 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2657 "options set!\n";
2659 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
2660 # we don't want "SVM: initializing mirror for junk" ...
2661 return undef if $r == 0;
2662 my $svm = $self->svm;
2663 if ($uuid ne $svm->{uuid}) {
2664 die "UUID mismatch on SVM path:\n",
2665 "expected: $svm->{uuid}\n",
2666 " got: $uuid\n";
2668 my $full_url = $self->full_url;
2669 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2670 die "Failed to replace '$svm->{replace}' with ",
2671 "'$svm->{source}' in $full_url\n";
2672 # throw away username for storing in records
2673 remove_username($full_url);
2674 $log_entry{metadata} = "$full_url\@$r $uuid";
2675 $log_entry{svm_revision} = $r;
2676 $email ||= "$author\@$uuid";
2677 $commit_email ||= "$author\@$uuid";
2678 } elsif ($self->use_svnsync_props) {
2679 my $full_url = $self->svnsync->{url};
2680 $full_url .= "/$self->{path}" if length $self->{path};
2681 remove_username($full_url);
2682 my $uuid = $self->svnsync->{uuid};
2683 $log_entry{metadata} = "$full_url\@$rev $uuid";
2684 $email ||= "$author\@$uuid";
2685 $commit_email ||= "$author\@$uuid";
2686 } else {
2687 my $url = $self->metadata_url;
2688 remove_username($url);
2689 $log_entry{metadata} = "$url\@$rev " .
2690 $self->ra->get_uuid;
2691 $email ||= "$author\@" . $self->ra->get_uuid;
2692 $commit_email ||= "$author\@" . $self->ra->get_uuid;
2694 $log_entry{name} = $name;
2695 $log_entry{email} = $email;
2696 $log_entry{commit_name} = $commit_name;
2697 $log_entry{commit_email} = $commit_email;
2698 \%log_entry;
2701 sub fetch {
2702 my ($self, $min_rev, $max_rev, @parents) = @_;
2703 my ($last_rev, $last_commit) = $self->last_rev_commit;
2704 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2705 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2708 sub set_tree_cb {
2709 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2710 $self->{inject_parents} = { $rev => $tree };
2711 $self->fetch(undef, undef);
2714 sub set_tree {
2715 my ($self, $tree) = (shift, shift);
2716 my $log_entry = ::get_commit_entry($tree);
2717 unless ($self->{last_rev}) {
2718 ::fatal("Must have an existing revision to commit");
2720 my %ed_opts = ( r => $self->{last_rev},
2721 log => $log_entry->{log},
2722 ra => $self->ra,
2723 tree_a => $self->{last_commit},
2724 tree_b => $tree,
2725 editor_cb => sub {
2726 $self->set_tree_cb($log_entry, $tree, @_) },
2727 svn_path => $self->{path} );
2728 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2729 print "No changes\nr$self->{last_rev} = $tree\n";
2733 sub rebuild_from_rev_db {
2734 my ($self, $path) = @_;
2735 my $r = -1;
2736 open my $fh, '<', $path or croak "open: $!";
2737 binmode $fh or croak "binmode: $!";
2738 while (<$fh>) {
2739 length($_) == 41 or croak "inconsistent size in ($_) != 41";
2740 chomp($_);
2741 ++$r;
2742 next if $_ eq ('0' x 40);
2743 $self->rev_map_set($r, $_);
2744 print "r$r = $_\n";
2746 close $fh or croak "close: $!";
2747 unlink $path or croak "unlink: $!";
2750 sub rebuild {
2751 my ($self) = @_;
2752 my $map_path = $self->map_path;
2753 my $partial = (-e $map_path && ! -z $map_path);
2754 return unless ::verify_ref($self->refname.'^0');
2755 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
2756 my $rev_db = $self->rev_db_path;
2757 $self->rebuild_from_rev_db($rev_db);
2758 if ($self->use_svm_props) {
2759 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
2760 $self->rebuild_from_rev_db($svm_rev_db);
2762 $self->unlink_rev_db_symlink;
2763 return;
2765 print "Rebuilding $map_path ...\n" if (!$partial);
2766 my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
2767 (undef, undef));
2768 my ($log, $ctx) =
2769 command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
2770 ($head ? "$head.." : "") . $self->refname,
2771 '--');
2772 my $metadata_url = $self->metadata_url;
2773 remove_username($metadata_url);
2774 my $svn_uuid = $self->ra_uuid;
2775 my $c;
2776 while (<$log>) {
2777 if ( m{^commit ($::sha1)$} ) {
2778 $c = $1;
2779 next;
2781 next unless s{^\s*(git-svn-id:)}{$1};
2782 my ($url, $rev, $uuid) = ::extract_metadata($_);
2783 remove_username($url);
2785 # ignore merges (from set-tree)
2786 next if (!defined $rev || !$uuid);
2788 # if we merged or otherwise started elsewhere, this is
2789 # how we break out of it
2790 if (($uuid ne $svn_uuid) ||
2791 ($metadata_url && $url && ($url ne $metadata_url))) {
2792 next;
2794 if ($partial && $head) {
2795 print "Partial-rebuilding $map_path ...\n";
2796 print "Currently at $base_rev = $head\n";
2797 $head = undef;
2800 $self->rev_map_set($rev, $c);
2801 print "r$rev = $c\n";
2803 command_close_pipe($log, $ctx);
2804 print "Done rebuilding $map_path\n" if (!$partial || !$head);
2805 my $rev_db_path = $self->rev_db_path;
2806 if (-f $self->rev_db_path) {
2807 unlink $self->rev_db_path or croak "unlink: $!";
2809 $self->unlink_rev_db_symlink;
2812 # rev_map:
2813 # Tie::File seems to be prone to offset errors if revisions get sparse,
2814 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2815 # one of my favorite modules is out :< Next up would be one of the DBM
2816 # modules, but I'm not sure which is most portable...
2818 # This is the replacement for the rev_db format, which was too big
2819 # and inefficient for large repositories with a lot of sparse history
2820 # (mainly tags)
2822 # The format is this:
2823 # - 24 bytes for every record,
2824 # * 4 bytes for the integer representing an SVN revision number
2825 # * 20 bytes representing the sha1 of a git commit
2826 # - No empty padding records like the old format
2827 # (except the last record, which can be overwritten)
2828 # - new records are written append-only since SVN revision numbers
2829 # increase monotonically
2830 # - lookups on SVN revision number are done via a binary search
2831 # - Piping the file to xxd -c24 is a good way of dumping it for
2832 # viewing or editing (piped back through xxd -r), should the need
2833 # ever arise.
2834 # - The last record can be padding revision with an all-zero sha1
2835 # This is used to optimize fetch performance when using multiple
2836 # "fetch" directives in .git/config
2838 # These files are disposable unless noMetadata or useSvmProps is set
2840 sub _rev_map_set {
2841 my ($fh, $rev, $commit) = @_;
2843 binmode $fh or croak "binmode: $!";
2844 my $size = (stat($fh))[7];
2845 ($size % 24) == 0 or croak "inconsistent size: $size";
2847 my $wr_offset = 0;
2848 if ($size > 0) {
2849 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2850 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
2851 $read == 24 or croak "read only $read bytes (!= 24)";
2852 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
2853 if ($last_commit eq ('0' x40)) {
2854 if ($size >= 48) {
2855 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2856 $read = sysread($fh, $buf, 24) or
2857 croak "read: $!";
2858 $read == 24 or
2859 croak "read only $read bytes (!= 24)";
2860 ($last_rev, $last_commit) =
2861 unpack(rev_map_fmt, $buf);
2862 if ($last_commit eq ('0' x40)) {
2863 croak "inconsistent .rev_map\n";
2866 if ($last_rev >= $rev) {
2867 croak "last_rev is higher!: $last_rev >= $rev";
2869 $wr_offset = -24;
2872 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
2873 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
2874 croak "write: $!";
2877 sub mkfile {
2878 my ($path) = @_;
2879 unless (-e $path) {
2880 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2881 mkpath([$dir]) unless -d $dir;
2882 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2883 close $fh or die "Couldn't close (create) $path: $!\n";
2887 sub rev_map_set {
2888 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2889 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2890 my $db = $self->map_path($uuid);
2891 my $db_lock = "$db.lock";
2892 my $sig;
2893 if ($update_ref) {
2894 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2895 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2897 mkfile($db);
2899 $LOCKFILES{$db_lock} = 1;
2900 my $sync;
2901 # both of these options make our .rev_db file very, very important
2902 # and we can't afford to lose it because rebuild() won't work
2903 if ($self->use_svm_props || $self->no_metadata) {
2904 $sync = 1;
2905 copy($db, $db_lock) or die "rev_map_set(@_): ",
2906 "Failed to copy: ",
2907 "$db => $db_lock ($!)\n";
2908 } else {
2909 rename $db, $db_lock or die "rev_map_set(@_): ",
2910 "Failed to rename: ",
2911 "$db => $db_lock ($!)\n";
2914 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
2915 or croak "Couldn't open $db_lock: $!\n";
2916 _rev_map_set($fh, $rev, $commit);
2917 if ($sync) {
2918 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2919 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2921 close $fh or croak $!;
2922 if ($update_ref) {
2923 $_head = $self;
2924 command_noisy('update-ref', '-m', "r$rev",
2925 $self->refname, $commit);
2927 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
2928 "$db_lock => $db ($!)\n";
2929 delete $LOCKFILES{$db_lock};
2930 if ($update_ref) {
2931 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2932 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
2933 kill $sig, $$ if defined $sig;
2937 # If want_commit, this will return an array of (rev, commit) where
2938 # commit _must_ be a valid commit in the archive.
2939 # Otherwise, it'll return the max revision (whether or not the
2940 # commit is valid or just a 0x40 placeholder).
2941 sub rev_map_max {
2942 my ($self, $want_commit) = @_;
2943 $self->rebuild;
2944 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
2945 $want_commit ? ($r, $c) : $r;
2948 sub rev_map_max_norebuild {
2949 my ($self, $want_commit) = @_;
2950 my $map_path = $self->map_path;
2951 stat $map_path or return $want_commit ? (0, undef) : 0;
2952 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
2953 binmode $fh or croak "binmode: $!";
2954 my $size = (stat($fh))[7];
2955 ($size % 24) == 0 or croak "inconsistent size: $size";
2957 if ($size == 0) {
2958 close $fh or croak "close: $!";
2959 return $want_commit ? (0, undef) : 0;
2962 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2963 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
2964 my ($r, $c) = unpack(rev_map_fmt, $buf);
2965 if ($want_commit && $c eq ('0' x40)) {
2966 if ($size < 48) {
2967 return $want_commit ? (0, undef) : 0;
2969 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2970 sysread($fh, $buf, 24) == 24 or croak "read: $!";
2971 ($r, $c) = unpack(rev_map_fmt, $buf);
2972 if ($c eq ('0'x40)) {
2973 croak "Penultimate record is all-zeroes in $map_path";
2976 close $fh or croak "close: $!";
2977 $want_commit ? ($r, $c) : $r;
2980 sub rev_map_get {
2981 my ($self, $rev, $uuid) = @_;
2982 my $map_path = $self->map_path($uuid);
2983 return undef unless -e $map_path;
2985 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
2986 binmode $fh or croak "binmode: $!";
2987 my $size = (stat($fh))[7];
2988 ($size % 24) == 0 or croak "inconsistent size: $size";
2990 if ($size == 0) {
2991 close $fh or croak "close: $fh";
2992 return undef;
2995 my ($l, $u) = (0, $size - 24);
2996 my ($r, $c, $buf);
2998 while ($l <= $u) {
2999 my $i = int(($l/24 + $u/24) / 2) * 24;
3000 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
3001 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3002 my ($r, $c) = unpack('NH40', $buf);
3004 if ($r < $rev) {
3005 $l = $i + 24;
3006 } elsif ($r > $rev) {
3007 $u = $i - 24;
3008 } else { # $r == $rev
3009 close($fh) or croak "close: $!";
3010 return $c eq ('0' x 40) ? undef : $c;
3013 close($fh) or croak "close: $!";
3014 undef;
3017 # Finds the first svn revision that exists on (if $eq_ok is true) or
3018 # before $rev for the current branch. It will not search any lower
3019 # than $min_rev. Returns the git commit hash and svn revision number
3020 # if found, else (undef, undef).
3021 sub find_rev_before {
3022 my ($self, $rev, $eq_ok, $min_rev) = @_;
3023 --$rev unless $eq_ok;
3024 $min_rev ||= 1;
3025 while ($rev >= $min_rev) {
3026 if (my $c = $self->rev_map_get($rev)) {
3027 return ($rev, $c);
3029 --$rev;
3031 return (undef, undef);
3034 # Finds the first svn revision that exists on (if $eq_ok is true) or
3035 # after $rev for the current branch. It will not search any higher
3036 # than $max_rev. Returns the git commit hash and svn revision number
3037 # if found, else (undef, undef).
3038 sub find_rev_after {
3039 my ($self, $rev, $eq_ok, $max_rev) = @_;
3040 ++$rev unless $eq_ok;
3041 $max_rev ||= $self->rev_map_max;
3042 while ($rev <= $max_rev) {
3043 if (my $c = $self->rev_map_get($rev)) {
3044 return ($rev, $c);
3046 ++$rev;
3048 return (undef, undef);
3051 sub _new {
3052 my ($class, $repo_id, $ref_id, $path) = @_;
3053 unless (defined $repo_id && length $repo_id) {
3054 $repo_id = $Git::SVN::default_repo_id;
3056 unless (defined $ref_id && length $ref_id) {
3057 $_[2] = $ref_id = $Git::SVN::default_ref_id;
3059 $_[1] = $repo_id;
3060 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
3061 $_[3] = $path = '' unless (defined $path);
3062 mkpath(["$ENV{GIT_DIR}/svn"]);
3063 bless {
3064 ref_id => $ref_id, dir => $dir, index => "$dir/index",
3065 path => $path, config => "$ENV{GIT_DIR}/svn/config",
3066 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
3069 # for read-only access of old .rev_db formats
3070 sub unlink_rev_db_symlink {
3071 my ($self) = @_;
3072 my $link = $self->rev_db_path;
3073 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
3074 if (-l $link) {
3075 unlink $link or croak "unlink: $link failed!";
3079 sub rev_db_path {
3080 my ($self, $uuid) = @_;
3081 my $db_path = $self->map_path($uuid);
3082 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
3083 or croak "map_path: $db_path does not contain '/.rev_map.' !";
3084 $db_path;
3087 # the new replacement for .rev_db
3088 sub map_path {
3089 my ($self, $uuid) = @_;
3090 $uuid ||= $self->ra_uuid;
3091 "$self->{map_root}.$uuid";
3094 sub uri_encode {
3095 my ($f) = @_;
3096 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
3100 sub remove_username {
3101 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
3104 package Git::SVN::Prompt;
3105 use strict;
3106 use warnings;
3107 require SVN::Core;
3108 use vars qw/$_no_auth_cache $_username/;
3110 sub simple {
3111 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
3112 $may_save = undef if $_no_auth_cache;
3113 $default_username = $_username if defined $_username;
3114 if (defined $default_username && length $default_username) {
3115 if (defined $realm && length $realm) {
3116 print STDERR "Authentication realm: $realm\n";
3117 STDERR->flush;
3119 $cred->username($default_username);
3120 } else {
3121 username($cred, $realm, $may_save, $pool);
3123 $cred->password(_read_password("Password for '" .
3124 $cred->username . "': ", $realm));
3125 $cred->may_save($may_save);
3126 $SVN::_Core::SVN_NO_ERROR;
3129 sub ssl_server_trust {
3130 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
3131 $may_save = undef if $_no_auth_cache;
3132 print STDERR "Error validating server certificate for '$realm':\n";
3134 no warnings 'once';
3135 # All variables SVN::Auth::SSL::* are used only once,
3136 # so we're shutting up Perl warnings about this.
3137 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
3138 print STDERR " - The certificate is not issued ",
3139 "by a trusted authority. Use the\n",
3140 " fingerprint to validate ",
3141 "the certificate manually!\n";
3143 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
3144 print STDERR " - The certificate hostname ",
3145 "does not match.\n";
3147 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
3148 print STDERR " - The certificate is not yet valid.\n";
3150 if ($failures & $SVN::Auth::SSL::EXPIRED) {
3151 print STDERR " - The certificate has expired.\n";
3153 if ($failures & $SVN::Auth::SSL::OTHER) {
3154 print STDERR " - The certificate has ",
3155 "an unknown error.\n";
3157 } # no warnings 'once'
3158 printf STDERR
3159 "Certificate information:\n".
3160 " - Hostname: %s\n".
3161 " - Valid: from %s until %s\n".
3162 " - Issuer: %s\n".
3163 " - Fingerprint: %s\n",
3164 map $cert_info->$_, qw(hostname valid_from valid_until
3165 issuer_dname fingerprint);
3166 my $choice;
3167 prompt:
3168 print STDERR $may_save ?
3169 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
3170 "(R)eject or accept (t)emporarily? ";
3171 STDERR->flush;
3172 $choice = lc(substr(<STDIN> || 'R', 0, 1));
3173 if ($choice =~ /^t$/i) {
3174 $cred->may_save(undef);
3175 } elsif ($choice =~ /^r$/i) {
3176 return -1;
3177 } elsif ($may_save && $choice =~ /^p$/i) {
3178 $cred->may_save($may_save);
3179 } else {
3180 goto prompt;
3182 $cred->accepted_failures($failures);
3183 $SVN::_Core::SVN_NO_ERROR;
3186 sub ssl_client_cert {
3187 my ($cred, $realm, $may_save, $pool) = @_;
3188 $may_save = undef if $_no_auth_cache;
3189 print STDERR "Client certificate filename: ";
3190 STDERR->flush;
3191 chomp(my $filename = <STDIN>);
3192 $cred->cert_file($filename);
3193 $cred->may_save($may_save);
3194 $SVN::_Core::SVN_NO_ERROR;
3197 sub ssl_client_cert_pw {
3198 my ($cred, $realm, $may_save, $pool) = @_;
3199 $may_save = undef if $_no_auth_cache;
3200 $cred->password(_read_password("Password: ", $realm));
3201 $cred->may_save($may_save);
3202 $SVN::_Core::SVN_NO_ERROR;
3205 sub username {
3206 my ($cred, $realm, $may_save, $pool) = @_;
3207 $may_save = undef if $_no_auth_cache;
3208 if (defined $realm && length $realm) {
3209 print STDERR "Authentication realm: $realm\n";
3211 my $username;
3212 if (defined $_username) {
3213 $username = $_username;
3214 } else {
3215 print STDERR "Username: ";
3216 STDERR->flush;
3217 chomp($username = <STDIN>);
3219 $cred->username($username);
3220 $cred->may_save($may_save);
3221 $SVN::_Core::SVN_NO_ERROR;
3224 sub _read_password {
3225 my ($prompt, $realm) = @_;
3226 print STDERR $prompt;
3227 STDERR->flush;
3228 require Term::ReadKey;
3229 Term::ReadKey::ReadMode('noecho');
3230 my $password = '';
3231 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
3232 last if $key =~ /[\012\015]/; # \n\r
3233 $password .= $key;
3235 Term::ReadKey::ReadMode('restore');
3236 print STDERR "\n";
3237 STDERR->flush;
3238 $password;
3241 package SVN::Git::Fetcher;
3242 use vars qw/@ISA/;
3243 use strict;
3244 use warnings;
3245 use Carp qw/croak/;
3246 use File::Temp qw/tempfile/;
3247 use IO::File qw//;
3249 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
3250 sub new {
3251 my ($class, $git_svn) = @_;
3252 my $self = SVN::Delta::Editor->new;
3253 bless $self, $class;
3254 if (exists $git_svn->{last_commit}) {
3255 $self->{c} = $git_svn->{last_commit};
3256 $self->{empty_symlinks} = _mark_empty_symlinks($git_svn);
3258 $self->{empty} = {};
3259 $self->{dir_prop} = {};
3260 $self->{file_prop} = {};
3261 $self->{absent_dir} = {};
3262 $self->{absent_file} = {};
3263 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
3264 $self;
3267 # this uses the Ra object, so it must be called before do_{switch,update},
3268 # not inside them (when the Git::SVN::Fetcher object is passed) to
3269 # do_{switch,update}
3270 sub _mark_empty_symlinks {
3271 my ($git_svn) = @_;
3272 my %ret;
3273 my ($rev, $cmt) = $git_svn->last_rev_commit;
3274 return {} unless ($rev && $cmt);
3276 chomp(my $empty_blob = `git hash-object -t blob --stdin < /dev/null`);
3277 my ($ls, $ctx) = command_output_pipe(qw/ls-tree -r -z/, $cmt);
3278 local $/ = "\0";
3279 my $pfx = $git_svn->{path};
3280 $pfx .= '/' if length($pfx);
3281 while (<$ls>) {
3282 chomp;
3283 s/\A100644 blob $empty_blob\t//o or next;
3284 my $path = $_;
3285 my (undef, $props) =
3286 $git_svn->ra->get_file($pfx.$path, $rev, undef);
3287 if ($props->{'svn:special'}) {
3288 $ret{$path} = 1;
3291 command_close_pipe($ls, $ctx);
3292 \%ret;
3295 # returns true if a given path is inside a ".git" directory
3296 sub in_dot_git {
3297 $_[0] =~ m{(?:^|/)\.git(?:/|$)};
3300 sub set_path_strip {
3301 my ($self, $path) = @_;
3302 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
3305 sub open_root {
3306 { path => '' };
3309 sub open_directory {
3310 my ($self, $path, $pb, $rev) = @_;
3311 { path => $path };
3314 sub git_path {
3315 my ($self, $path) = @_;
3316 if ($self->{path_strip}) {
3317 $path =~ s!$self->{path_strip}!! or
3318 die "Failed to strip path '$path' ($self->{path_strip})\n";
3320 $path;
3323 sub delete_entry {
3324 my ($self, $path, $rev, $pb) = @_;
3325 return undef if in_dot_git($path);
3327 my $gpath = $self->git_path($path);
3328 return undef if ($gpath eq '');
3330 # remove entire directories.
3331 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
3332 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3333 -r --name-only -z/,
3334 $self->{c}, '--', $gpath);
3335 local $/ = "\0";
3336 while (<$ls>) {
3337 chomp;
3338 $self->{gii}->remove($_);
3339 print "\tD\t$_\n" unless $::_q;
3341 print "\tD\t$gpath/\n" unless $::_q;
3342 command_close_pipe($ls, $ctx);
3343 $self->{empty}->{$path} = 0
3344 } else {
3345 $self->{gii}->remove($gpath);
3346 print "\tD\t$gpath\n" unless $::_q;
3348 undef;
3351 sub open_file {
3352 my ($self, $path, $pb, $rev) = @_;
3353 my ($mode, $blob);
3355 goto out if in_dot_git($path);
3357 my $gpath = $self->git_path($path);
3358 ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
3359 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
3360 unless (defined $mode && defined $blob) {
3361 die "$path was not found in commit $self->{c} (r$rev)\n";
3363 if ($mode eq '100644' && $self->{empty_symlinks}->{$path}) {
3364 $mode = '120000';
3366 out:
3367 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
3368 pool => SVN::Pool->new, action => 'M' };
3371 sub add_file {
3372 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
3373 my $mode;
3375 if (!in_dot_git($path)) {
3376 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3377 delete $self->{empty}->{$dir};
3378 $mode = '100644';
3380 { path => $path, mode_a => $mode, mode_b => $mode,
3381 pool => SVN::Pool->new, action => 'A' };
3384 sub add_directory {
3385 my ($self, $path, $cp_path, $cp_rev) = @_;
3386 goto out if in_dot_git($path);
3387 my $gpath = $self->git_path($path);
3388 if ($gpath eq '') {
3389 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3390 -r --name-only -z/,
3391 $self->{c});
3392 local $/ = "\0";
3393 while (<$ls>) {
3394 chomp;
3395 $self->{gii}->remove($_);
3396 print "\tD\t$_\n" unless $::_q;
3398 command_close_pipe($ls, $ctx);
3399 $self->{empty}->{$path} = 0;
3401 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3402 delete $self->{empty}->{$dir};
3403 $self->{empty}->{$path} = 1;
3404 out:
3405 { path => $path };
3408 sub change_dir_prop {
3409 my ($self, $db, $prop, $value) = @_;
3410 return undef if in_dot_git($db->{path});
3411 $self->{dir_prop}->{$db->{path}} ||= {};
3412 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
3413 undef;
3416 sub absent_directory {
3417 my ($self, $path, $pb) = @_;
3418 return undef if in_dot_git($pb->{path});
3419 $self->{absent_dir}->{$pb->{path}} ||= [];
3420 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
3421 undef;
3424 sub absent_file {
3425 my ($self, $path, $pb) = @_;
3426 return undef if in_dot_git($pb->{path});
3427 $self->{absent_file}->{$pb->{path}} ||= [];
3428 push @{$self->{absent_file}->{$pb->{path}}}, $path;
3429 undef;
3432 sub change_file_prop {
3433 my ($self, $fb, $prop, $value) = @_;
3434 return undef if in_dot_git($fb->{path});
3435 if ($prop eq 'svn:executable') {
3436 if ($fb->{mode_b} != 120000) {
3437 $fb->{mode_b} = defined $value ? 100755 : 100644;
3439 } elsif ($prop eq 'svn:special') {
3440 $fb->{mode_b} = defined $value ? 120000 : 100644;
3441 } else {
3442 $self->{file_prop}->{$fb->{path}} ||= {};
3443 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
3445 undef;
3448 sub apply_textdelta {
3449 my ($self, $fb, $exp) = @_;
3450 return undef if (in_dot_git($fb->{path}));
3451 my $fh = $::_repository->temp_acquire('svn_delta');
3452 # $fh gets auto-closed() by SVN::TxDelta::apply(),
3453 # (but $base does not,) so dup() it for reading in close_file
3454 open my $dup, '<&', $fh or croak $!;
3455 my $base = $::_repository->temp_acquire('git_blob');
3457 if ($fb->{blob}) {
3458 my ($base_is_link, $size);
3460 if ($fb->{mode_a} eq '120000' &&
3461 ! $self->{empty_symlinks}->{$fb->{path}}) {
3462 print $base 'link ' or die "print $!\n";
3463 $base_is_link = 1;
3465 retry:
3466 $size = $::_repository->cat_blob($fb->{blob}, $base);
3467 die "Failed to read object $fb->{blob}" if ($size < 0);
3469 if (defined $exp) {
3470 seek $base, 0, 0 or croak $!;
3471 my $got = ::md5sum($base);
3472 if ($got ne $exp) {
3473 my $err = "Checksum mismatch: ".
3474 "$fb->{path} $fb->{blob}\n" .
3475 "expected: $exp\n" .
3476 " got: $got\n";
3477 if ($base_is_link) {
3478 warn $err,
3479 "Retrying... (possibly ",
3480 "a bad symlink from SVN)\n";
3481 $::_repository->temp_reset($base);
3482 $base_is_link = 0;
3483 goto retry;
3485 die $err;
3489 seek $base, 0, 0 or croak $!;
3490 $fb->{fh} = $fh;
3491 $fb->{base} = $base;
3492 [ SVN::TxDelta::apply($base, $dup, undef, $fb->{path}, $fb->{pool}) ];
3495 sub close_file {
3496 my ($self, $fb, $exp) = @_;
3497 return undef if (in_dot_git($fb->{path}));
3499 my $hash;
3500 my $path = $self->git_path($fb->{path});
3501 if (my $fh = $fb->{fh}) {
3502 if (defined $exp) {
3503 seek($fh, 0, 0) or croak $!;
3504 my $got = ::md5sum($fh);
3505 if ($got ne $exp) {
3506 die "Checksum mismatch: $path\n",
3507 "expected: $exp\n got: $got\n";
3510 if ($fb->{mode_b} == 120000) {
3511 sysseek($fh, 0, 0) or croak $!;
3512 my $rd = sysread($fh, my $buf, 5);
3514 if (!defined $rd) {
3515 croak "sysread: $!\n";
3516 } elsif ($rd == 0) {
3517 warn "$path has mode 120000",
3518 " but it points to nothing\n",
3519 "converting to an empty file with mode",
3520 " 100644\n";
3521 $fb->{mode_b} = '100644';
3522 } elsif ($buf ne 'link ') {
3523 warn "$path has mode 120000",
3524 " but is not a link\n";
3525 } else {
3526 my $tmp_fh = $::_repository->temp_acquire(
3527 'svn_hash');
3528 my $res;
3529 while ($res = sysread($fh, my $str, 1024)) {
3530 my $out = syswrite($tmp_fh, $str, $res);
3531 defined($out) && $out == $res
3532 or croak("write ",
3533 Git::temp_path($tmp_fh),
3534 ": $!\n");
3536 defined $res or croak $!;
3538 ($fh, $tmp_fh) = ($tmp_fh, $fh);
3539 Git::temp_release($tmp_fh, 1);
3543 $hash = $::_repository->hash_and_insert_object(
3544 Git::temp_path($fh));
3545 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
3547 Git::temp_release($fb->{base}, 1);
3548 Git::temp_release($fh, 1);
3549 } else {
3550 $hash = $fb->{blob} or die "no blob information\n";
3552 $fb->{pool}->clear;
3553 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
3554 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
3555 undef;
3558 sub abort_edit {
3559 my $self = shift;
3560 $self->{nr} = $self->{gii}->{nr};
3561 delete $self->{gii};
3562 $self->SUPER::abort_edit(@_);
3565 sub close_edit {
3566 my $self = shift;
3567 $self->{git_commit_ok} = 1;
3568 $self->{nr} = $self->{gii}->{nr};
3569 delete $self->{gii};
3570 $self->SUPER::close_edit(@_);
3573 package SVN::Git::Editor;
3574 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
3575 use strict;
3576 use warnings;
3577 use Carp qw/croak/;
3578 use IO::File;
3580 sub new {
3581 my ($class, $opts) = @_;
3582 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
3583 die "$_ required!\n" unless (defined $opts->{$_});
3586 my $pool = SVN::Pool->new;
3587 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
3588 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
3589 $opts->{r}, $mods);
3591 # $opts->{ra} functions should not be used after this:
3592 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
3593 $opts->{editor_cb}, $pool);
3594 my $self = SVN::Delta::Editor->new(@ce, $pool);
3595 bless $self, $class;
3596 foreach (qw/svn_path r tree_a tree_b/) {
3597 $self->{$_} = $opts->{$_};
3599 $self->{url} = $opts->{ra}->{url};
3600 $self->{mods} = $mods;
3601 $self->{types} = $types;
3602 $self->{pool} = $pool;
3603 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
3604 $self->{rm} = { };
3605 $self->{path_prefix} = length $self->{svn_path} ?
3606 "$self->{svn_path}/" : '';
3607 $self->{config} = $opts->{config};
3608 return $self;
3611 sub generate_diff {
3612 my ($tree_a, $tree_b) = @_;
3613 my @diff_tree = qw(diff-tree -z -r);
3614 if ($_cp_similarity) {
3615 push @diff_tree, "-C$_cp_similarity";
3616 } else {
3617 push @diff_tree, '-C';
3619 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
3620 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
3621 push @diff_tree, $tree_a, $tree_b;
3622 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
3623 local $/ = "\0";
3624 my $state = 'meta';
3625 my @mods;
3626 while (<$diff_fh>) {
3627 chomp $_; # this gets rid of the trailing "\0"
3628 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
3629 ($::sha1)\s($::sha1)\s
3630 ([MTCRAD])\d*$/xo) {
3631 push @mods, { mode_a => $1, mode_b => $2,
3632 sha1_a => $3, sha1_b => $4,
3633 chg => $5 };
3634 if ($5 =~ /^(?:C|R)$/) {
3635 $state = 'file_a';
3636 } else {
3637 $state = 'file_b';
3639 } elsif ($state eq 'file_a') {
3640 my $x = $mods[$#mods] or croak "Empty array\n";
3641 if ($x->{chg} !~ /^(?:C|R)$/) {
3642 croak "Error parsing $_, $x->{chg}\n";
3644 $x->{file_a} = $_;
3645 $state = 'file_b';
3646 } elsif ($state eq 'file_b') {
3647 my $x = $mods[$#mods] or croak "Empty array\n";
3648 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
3649 croak "Error parsing $_, $x->{chg}\n";
3651 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
3652 croak "Error parsing $_, $x->{chg}\n";
3654 $x->{file_b} = $_;
3655 $state = 'meta';
3656 } else {
3657 croak "Error parsing $_\n";
3660 command_close_pipe($diff_fh, $ctx);
3661 \@mods;
3664 sub check_diff_paths {
3665 my ($ra, $pfx, $rev, $mods) = @_;
3666 my %types;
3667 $pfx .= '/' if length $pfx;
3669 sub type_diff_paths {
3670 my ($ra, $types, $path, $rev) = @_;
3671 my @p = split m#/+#, $path;
3672 my $c = shift @p;
3673 unless (defined $types->{$c}) {
3674 $types->{$c} = $ra->check_path($c, $rev);
3676 while (@p) {
3677 $c .= '/' . shift @p;
3678 next if defined $types->{$c};
3679 $types->{$c} = $ra->check_path($c, $rev);
3683 foreach my $m (@$mods) {
3684 foreach my $f (qw/file_a file_b/) {
3685 next unless defined $m->{$f};
3686 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
3687 if (length $pfx.$dir && ! defined $types{$dir}) {
3688 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
3692 \%types;
3695 sub split_path {
3696 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
3699 sub repo_path {
3700 my ($self, $path) = @_;
3701 $self->{path_prefix}.(defined $path ? $path : '');
3704 sub url_path {
3705 my ($self, $path) = @_;
3706 if ($self->{url} =~ m#^https?://#) {
3707 $path =~ s/([^~a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
3709 $self->{url} . '/' . $self->repo_path($path);
3712 sub rmdirs {
3713 my ($self) = @_;
3714 my $rm = $self->{rm};
3715 delete $rm->{''}; # we never delete the url we're tracking
3716 return unless %$rm;
3718 foreach (keys %$rm) {
3719 my @d = split m#/#, $_;
3720 my $c = shift @d;
3721 $rm->{$c} = 1;
3722 while (@d) {
3723 $c .= '/' . shift @d;
3724 $rm->{$c} = 1;
3727 delete $rm->{$self->{svn_path}};
3728 delete $rm->{''}; # we never delete the url we're tracking
3729 return unless %$rm;
3731 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
3732 $self->{tree_b});
3733 local $/ = "\0";
3734 while (<$fh>) {
3735 chomp;
3736 my @dn = split m#/#, $_;
3737 while (pop @dn) {
3738 delete $rm->{join '/', @dn};
3740 unless (%$rm) {
3741 close $fh;
3742 return;
3745 command_close_pipe($fh, $ctx);
3747 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
3748 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
3749 $self->close_directory($bat->{$d}, $p);
3750 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
3751 print "\tD+\t$d/\n" unless $::_q;
3752 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
3753 delete $bat->{$d};
3757 sub open_or_add_dir {
3758 my ($self, $full_path, $baton) = @_;
3759 my $t = $self->{types}->{$full_path};
3760 if (!defined $t) {
3761 die "$full_path not known in r$self->{r} or we have a bug!\n";
3764 no warnings 'once';
3765 # SVN::Node::none and SVN::Node::file are used only once,
3766 # so we're shutting up Perl's warnings about them.
3767 if ($t == $SVN::Node::none) {
3768 return $self->add_directory($full_path, $baton,
3769 undef, -1, $self->{pool});
3770 } elsif ($t == $SVN::Node::dir) {
3771 return $self->open_directory($full_path, $baton,
3772 $self->{r}, $self->{pool});
3773 } # no warnings 'once'
3774 print STDERR "$full_path already exists in repository at ",
3775 "r$self->{r} and it is not a directory (",
3776 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
3777 } # no warnings 'once'
3778 exit 1;
3781 sub ensure_path {
3782 my ($self, $path) = @_;
3783 my $bat = $self->{bat};
3784 my $repo_path = $self->repo_path($path);
3785 return $bat->{''} unless (length $repo_path);
3786 my @p = split m#/+#, $repo_path;
3787 my $c = shift @p;
3788 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
3789 while (@p) {
3790 my $c0 = $c;
3791 $c .= '/' . shift @p;
3792 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
3794 return $bat->{$c};
3797 # Subroutine to convert a globbing pattern to a regular expression.
3798 # From perl cookbook.
3799 sub glob2pat {
3800 my $globstr = shift;
3801 my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
3802 $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
3803 return '^' . $globstr . '$';
3806 sub check_autoprop {
3807 my ($self, $pattern, $properties, $file, $fbat) = @_;
3808 # Convert the globbing pattern to a regular expression.
3809 my $regex = glob2pat($pattern);
3810 # Check if the pattern matches the file name.
3811 if($file =~ m/($regex)/) {
3812 # Parse the list of properties to set.
3813 my @props = split(/;/, $properties);
3814 foreach my $prop (@props) {
3815 # Parse 'name=value' syntax and set the property.
3816 if ($prop =~ /([^=]+)=(.*)/) {
3817 my ($n,$v) = ($1,$2);
3818 for ($n, $v) {
3819 s/^\s+//; s/\s+$//;
3821 $self->change_file_prop($fbat, $n, $v);
3827 sub apply_autoprops {
3828 my ($self, $file, $fbat) = @_;
3829 my $conf_t = ${$self->{config}}{'config'};
3830 no warnings 'once';
3831 # Check [miscellany]/enable-auto-props in svn configuration.
3832 if (SVN::_Core::svn_config_get_bool(
3833 $conf_t,
3834 $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
3835 $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
3836 0)) {
3837 # Auto-props are enabled. Enumerate them to look for matches.
3838 my $callback = sub {
3839 $self->check_autoprop($_[0], $_[1], $file, $fbat);
3841 SVN::_Core::svn_config_enumerate(
3842 $conf_t,
3843 $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
3844 $callback);
3848 sub A {
3849 my ($self, $m) = @_;
3850 my ($dir, $file) = split_path($m->{file_b});
3851 my $pbat = $self->ensure_path($dir);
3852 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3853 undef, -1);
3854 print "\tA\t$m->{file_b}\n" unless $::_q;
3855 $self->apply_autoprops($file, $fbat);
3856 $self->chg_file($fbat, $m);
3857 $self->close_file($fbat,undef,$self->{pool});
3860 sub C {
3861 my ($self, $m) = @_;
3862 my ($dir, $file) = split_path($m->{file_b});
3863 my $pbat = $self->ensure_path($dir);
3864 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3865 $self->url_path($m->{file_a}), $self->{r});
3866 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3867 $self->chg_file($fbat, $m);
3868 $self->close_file($fbat,undef,$self->{pool});
3871 sub delete_entry {
3872 my ($self, $path, $pbat) = @_;
3873 my $rpath = $self->repo_path($path);
3874 my ($dir, $file) = split_path($rpath);
3875 $self->{rm}->{$dir} = 1;
3876 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
3879 sub R {
3880 my ($self, $m) = @_;
3881 my ($dir, $file) = split_path($m->{file_b});
3882 my $pbat = $self->ensure_path($dir);
3883 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3884 $self->url_path($m->{file_a}), $self->{r});
3885 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3886 $self->apply_autoprops($file, $fbat);
3887 $self->chg_file($fbat, $m);
3888 $self->close_file($fbat,undef,$self->{pool});
3890 ($dir, $file) = split_path($m->{file_a});
3891 $pbat = $self->ensure_path($dir);
3892 $self->delete_entry($m->{file_a}, $pbat);
3895 sub M {
3896 my ($self, $m) = @_;
3897 my ($dir, $file) = split_path($m->{file_b});
3898 my $pbat = $self->ensure_path($dir);
3899 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
3900 $pbat,$self->{r},$self->{pool});
3901 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
3902 $self->chg_file($fbat, $m);
3903 $self->close_file($fbat,undef,$self->{pool});
3906 sub T { shift->M(@_) }
3908 sub change_file_prop {
3909 my ($self, $fbat, $pname, $pval) = @_;
3910 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
3913 sub _chg_file_get_blob ($$$$) {
3914 my ($self, $fbat, $m, $which) = @_;
3915 my $fh = $::_repository->temp_acquire("git_blob_$which");
3916 if ($m->{"mode_$which"} =~ /^120/) {
3917 print $fh 'link ' or croak $!;
3918 $self->change_file_prop($fbat,'svn:special','*');
3919 } elsif ($m->{mode_a} =~ /^120/ && $m->{"mode_$which"} !~ /^120/) {
3920 $self->change_file_prop($fbat,'svn:special',undef);
3922 my $blob = $m->{"sha1_$which"};
3923 return ($fh,) if ($blob =~ /^0{40}$/);
3924 my $size = $::_repository->cat_blob($blob, $fh);
3925 croak "Failed to read object $blob" if ($size < 0);
3926 $fh->flush == 0 or croak $!;
3927 seek $fh, 0, 0 or croak $!;
3929 my $exp = ::md5sum($fh);
3930 seek $fh, 0, 0 or croak $!;
3931 return ($fh, $exp);
3934 sub chg_file {
3935 my ($self, $fbat, $m) = @_;
3936 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
3937 $self->change_file_prop($fbat,'svn:executable','*');
3938 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
3939 $self->change_file_prop($fbat,'svn:executable',undef);
3941 my ($fh_a, $exp_a) = _chg_file_get_blob $self, $fbat, $m, 'a';
3942 my ($fh_b, $exp_b) = _chg_file_get_blob $self, $fbat, $m, 'b';
3943 my $pool = SVN::Pool->new;
3944 my $atd = $self->apply_textdelta($fbat, $exp_a, $pool);
3945 if (-s $fh_a) {
3946 my $txstream = SVN::TxDelta::new ($fh_a, $fh_b, $pool);
3947 my $res = SVN::TxDelta::send_txstream($txstream, @$atd, $pool);
3948 if (defined $res) {
3949 die "Unexpected result from send_txstream: $res\n",
3950 "(SVN::Core::VERSION: $SVN::Core::VERSION)\n";
3952 } else {
3953 my $got = SVN::TxDelta::send_stream($fh_b, @$atd, $pool);
3954 die "Checksum mismatch\nexpected: $exp_b\ngot: $got\n"
3955 if ($got ne $exp_b);
3957 Git::temp_release($fh_b, 1);
3958 Git::temp_release($fh_a, 1);
3959 $pool->clear;
3962 sub D {
3963 my ($self, $m) = @_;
3964 my ($dir, $file) = split_path($m->{file_b});
3965 my $pbat = $self->ensure_path($dir);
3966 print "\tD\t$m->{file_b}\n" unless $::_q;
3967 $self->delete_entry($m->{file_b}, $pbat);
3970 sub close_edit {
3971 my ($self) = @_;
3972 my ($p,$bat) = ($self->{pool}, $self->{bat});
3973 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
3974 next if $_ eq '';
3975 $self->close_directory($bat->{$_}, $p);
3977 $self->close_directory($bat->{''}, $p);
3978 $self->SUPER::close_edit($p);
3979 $p->clear;
3982 sub abort_edit {
3983 my ($self) = @_;
3984 $self->SUPER::abort_edit($self->{pool});
3987 sub DESTROY {
3988 my $self = shift;
3989 $self->SUPER::DESTROY(@_);
3990 $self->{pool}->clear;
3993 # this drives the editor
3994 sub apply_diff {
3995 my ($self) = @_;
3996 my $mods = $self->{mods};
3997 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
3998 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
3999 my $f = $m->{chg};
4000 if (defined $o{$f}) {
4001 $self->$f($m);
4002 } else {
4003 fatal("Invalid change type: $f");
4006 $self->rmdirs if $_rmdir;
4007 if (@$mods == 0) {
4008 $self->abort_edit;
4009 } else {
4010 $self->close_edit;
4012 return scalar @$mods;
4015 package Git::SVN::Ra;
4016 use vars qw/@ISA $config_dir $_log_window_size/;
4017 use strict;
4018 use warnings;
4019 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
4021 BEGIN {
4022 # enforce temporary pool usage for some simple functions
4023 no strict 'refs';
4024 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root/) {
4025 my $SUPER = "SUPER::$f";
4026 *$f = sub {
4027 my $self = shift;
4028 my $pool = SVN::Pool->new;
4029 my @ret = $self->$SUPER(@_,$pool);
4030 $pool->clear;
4031 wantarray ? @ret : $ret[0];
4036 sub _auth_providers () {
4038 SVN::Client::get_simple_provider(),
4039 SVN::Client::get_ssl_server_trust_file_provider(),
4040 SVN::Client::get_simple_prompt_provider(
4041 \&Git::SVN::Prompt::simple, 2),
4042 SVN::Client::get_ssl_client_cert_file_provider(),
4043 SVN::Client::get_ssl_client_cert_prompt_provider(
4044 \&Git::SVN::Prompt::ssl_client_cert, 2),
4045 SVN::Client::get_ssl_client_cert_pw_file_provider(),
4046 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
4047 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
4048 SVN::Client::get_username_provider(),
4049 SVN::Client::get_ssl_server_trust_prompt_provider(
4050 \&Git::SVN::Prompt::ssl_server_trust),
4051 SVN::Client::get_username_prompt_provider(
4052 \&Git::SVN::Prompt::username, 2)
4056 sub escape_uri_only {
4057 my ($uri) = @_;
4058 my @tmp;
4059 foreach (split m{/}, $uri) {
4060 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
4061 push @tmp, $_;
4063 join('/', @tmp);
4066 sub escape_url {
4067 my ($url) = @_;
4068 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
4069 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
4070 $url = "$scheme://$domain$uri";
4072 $url;
4075 sub new {
4076 my ($class, $url) = @_;
4077 $url =~ s!/+$!!;
4078 return $RA if ($RA && $RA->{url} eq $url);
4080 SVN::_Core::svn_config_ensure($config_dir, undef);
4081 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
4082 my $config = SVN::Core::config_get_config($config_dir);
4083 $RA = undef;
4084 my $dont_store_passwords = 1;
4085 my $conf_t = ${$config}{'config'};
4087 no warnings 'once';
4088 # The usage of $SVN::_Core::SVN_CONFIG_* variables
4089 # produces warnings that variables are used only once.
4090 # I had not found the better way to shut them up, so
4091 # the warnings of type 'once' are disabled in this block.
4092 if (SVN::_Core::svn_config_get_bool($conf_t,
4093 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4094 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
4095 1) == 0) {
4096 SVN::_Core::svn_auth_set_parameter($baton,
4097 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
4098 bless (\$dont_store_passwords, "_p_void"));
4100 if (SVN::_Core::svn_config_get_bool($conf_t,
4101 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4102 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
4103 1) == 0) {
4104 $Git::SVN::Prompt::_no_auth_cache = 1;
4106 } # no warnings 'once'
4107 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
4108 config => $config,
4109 pool => SVN::Pool->new,
4110 auth_provider_callbacks => $callbacks);
4111 $self->{url} = $url;
4112 $self->{svn_path} = $url;
4113 $self->{repos_root} = $self->get_repos_root;
4114 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
4115 $self->{cache} = { check_path => { r => 0, data => {} },
4116 get_dir => { r => 0, data => {} } };
4117 $RA = bless $self, $class;
4120 sub check_path {
4121 my ($self, $path, $r) = @_;
4122 my $cache = $self->{cache}->{check_path};
4123 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
4124 return $cache->{data}->{$path};
4126 my $pool = SVN::Pool->new;
4127 my $t = $self->SUPER::check_path($path, $r, $pool);
4128 $pool->clear;
4129 if ($r != $cache->{r}) {
4130 %{$cache->{data}} = ();
4131 $cache->{r} = $r;
4133 $cache->{data}->{$path} = $t;
4136 sub get_dir {
4137 my ($self, $dir, $r) = @_;
4138 my $cache = $self->{cache}->{get_dir};
4139 if ($r == $cache->{r}) {
4140 if (my $x = $cache->{data}->{$dir}) {
4141 return wantarray ? @$x : $x->[0];
4144 my $pool = SVN::Pool->new;
4145 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
4146 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
4147 $pool->clear;
4148 if ($r != $cache->{r}) {
4149 %{$cache->{data}} = ();
4150 $cache->{r} = $r;
4152 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
4153 wantarray ? (\%dirents, $r, $props) : \%dirents;
4156 sub DESTROY {
4157 # do not call the real DESTROY since we store ourselves in $RA
4160 # get_log(paths, start, end, limit,
4161 # discover_changed_paths, strict_node_history, receiver)
4162 sub get_log {
4163 my ($self, @args) = @_;
4164 my $pool = SVN::Pool->new;
4166 # the limit parameter was not supported in SVN 1.1.x, so we
4167 # drop it. Therefore, the receiver callback passed to it
4168 # is made aware of this limitation by being wrapped if
4169 # the limit passed to is being wrapped.
4170 if ($SVN::Core::VERSION le '1.2.0') {
4171 my $limit = splice(@args, 3, 1);
4172 if ($limit > 0) {
4173 my $receiver = pop @args;
4174 push(@args, sub { &$receiver(@_) if (--$limit >= 0) });
4177 my $ret = $self->SUPER::get_log(@args, $pool);
4178 $pool->clear;
4179 $ret;
4182 sub trees_match {
4183 my ($self, $url1, $rev1, $url2, $rev2) = @_;
4184 my $ctx = SVN::Client->new(auth => _auth_providers);
4185 my $out = IO::File->new_tmpfile;
4187 # older SVN (1.1.x) doesn't take $pool as the last parameter for
4188 # $ctx->diff(), so we'll create a default one
4189 my $pool = SVN::Pool->new_default_sub;
4191 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
4192 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
4193 $out->flush;
4194 my $ret = (($out->stat)[7] == 0);
4195 close $out or croak $!;
4197 $ret;
4200 sub get_commit_editor {
4201 my ($self, $log, $cb, $pool) = @_;
4202 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
4203 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
4206 sub gs_do_update {
4207 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
4208 my $new = ($rev_a == $rev_b);
4209 my $path = $gs->{path};
4211 if ($new && -e $gs->{index}) {
4212 unlink $gs->{index} or die
4213 "Couldn't unlink index: $gs->{index}: $!\n";
4215 my $pool = SVN::Pool->new;
4216 $editor->set_path_strip($path);
4217 my (@pc) = split m#/#, $path;
4218 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
4219 1, $editor, $pool);
4220 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4222 # Since we can't rely on svn_ra_reparent being available, we'll
4223 # just have to do some magic with set_path to make it so
4224 # we only want a partial path.
4225 my $sp = '';
4226 my $final = join('/', @pc);
4227 while (@pc) {
4228 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
4229 $sp .= '/' if length $sp;
4230 $sp .= shift @pc;
4232 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
4234 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
4236 $reporter->finish_report($pool);
4237 $pool->clear;
4238 $editor->{git_commit_ok};
4241 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
4242 # svn_ra_reparent didn't work before 1.4)
4243 sub gs_do_switch {
4244 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
4245 my $path = $gs->{path};
4246 my $pool = SVN::Pool->new;
4248 my $full_url = $self->{url};
4249 my $old_url = $full_url;
4250 $full_url .= '/' . escape_uri_only($path) if length $path;
4251 my ($ra, $reparented);
4253 if ($old_url =~ m#^svn(\+ssh)?://#) {
4254 $_[0] = undef;
4255 $self = undef;
4256 $RA = undef;
4257 $ra = Git::SVN::Ra->new($full_url);
4258 $ra_invalid = 1;
4259 } elsif ($old_url ne $full_url) {
4260 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url, $pool);
4261 $self->{url} = $full_url;
4262 $reparented = 1;
4265 $ra ||= $self;
4266 $url_b = escape_url($url_b);
4267 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
4268 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4269 $reporter->set_path('', $rev_a, 0, @lock, $pool);
4270 $reporter->finish_report($pool);
4272 if ($reparented) {
4273 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
4274 $self->{url} = $old_url;
4277 $pool->clear;
4278 $editor->{git_commit_ok};
4281 sub longest_common_path {
4282 my ($gsv, $globs) = @_;
4283 my %common;
4284 my $common_max = scalar @$gsv;
4286 foreach my $gs (@$gsv) {
4287 my @tmp = split m#/#, $gs->{path};
4288 my $p = '';
4289 foreach (@tmp) {
4290 $p .= length($p) ? "/$_" : $_;
4291 $common{$p} ||= 0;
4292 $common{$p}++;
4295 $globs ||= [];
4296 $common_max += scalar @$globs;
4297 foreach my $glob (@$globs) {
4298 my @tmp = split m#/#, $glob->{path}->{left};
4299 my $p = '';
4300 foreach (@tmp) {
4301 $p .= length($p) ? "/$_" : $_;
4302 $common{$p} ||= 0;
4303 $common{$p}++;
4307 my $longest_path = '';
4308 foreach (sort {length $b <=> length $a} keys %common) {
4309 if ($common{$_} == $common_max) {
4310 $longest_path = $_;
4311 last;
4314 $longest_path;
4317 sub gs_fetch_loop_common {
4318 my ($self, $base, $head, $gsv, $globs) = @_;
4319 return if ($base > $head);
4320 my $inc = $_log_window_size;
4321 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
4322 my $longest_path = longest_common_path($gsv, $globs);
4323 my $ra_url = $self->{url};
4324 while (1) {
4325 my %revs;
4326 my $err;
4327 my $err_handler = $SVN::Error::handler;
4328 $SVN::Error::handler = sub {
4329 ($err) = @_;
4330 skip_unknown_revs($err);
4332 sub _cb {
4333 my ($paths, $r, $author, $date, $log) = @_;
4334 [ dup_changed_paths($paths),
4335 { author => $author, date => $date, log => $log } ];
4337 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
4338 sub { $revs{$_[1]} = _cb(@_) });
4339 if ($err && $max >= $head) {
4340 print STDERR "Path '$longest_path' ",
4341 "was probably deleted:\n",
4342 $err->expanded_message,
4343 "\nWill attempt to follow ",
4344 "revisions r$min .. r$max ",
4345 "committed before the deletion\n";
4346 my $hi = $max;
4347 while (--$hi >= $min) {
4348 my $ok;
4349 $self->get_log([$longest_path], $min, $hi,
4350 0, 1, 1, sub {
4351 $ok ||= $_[1];
4352 $revs{$_[1]} = _cb(@_) });
4353 if ($ok) {
4354 print STDERR "r$min .. r$ok OK\n";
4355 last;
4359 $SVN::Error::handler = $err_handler;
4361 my %exists = map { $_->{path} => $_ } @$gsv;
4362 foreach my $r (sort {$a <=> $b} keys %revs) {
4363 my ($paths, $logged) = @{$revs{$r}};
4365 foreach my $gs ($self->match_globs(\%exists, $paths,
4366 $globs, $r)) {
4367 if ($gs->rev_map_max >= $r) {
4368 next;
4370 next unless $gs->match_paths($paths, $r);
4371 $gs->{logged_rev_props} = $logged;
4372 if (my $last_commit = $gs->last_commit) {
4373 $gs->assert_index_clean($last_commit);
4375 my $log_entry = $gs->do_fetch($paths, $r);
4376 if ($log_entry) {
4377 $gs->do_git_commit($log_entry);
4379 $INDEX_FILES{$gs->{index}} = 1;
4381 foreach my $g (@$globs) {
4382 my $k = "svn-remote.$g->{remote}." .
4383 "$g->{t}-maxRev";
4384 Git::SVN::tmp_config($k, $r);
4386 if ($ra_invalid) {
4387 $_[0] = undef;
4388 $self = undef;
4389 $RA = undef;
4390 $self = Git::SVN::Ra->new($ra_url);
4391 $ra_invalid = undef;
4394 # pre-fill the .rev_db since it'll eventually get filled in
4395 # with '0' x40 if something new gets committed
4396 foreach my $gs (@$gsv) {
4397 next if $gs->rev_map_max >= $max;
4398 next if defined $gs->rev_map_get($max);
4399 $gs->rev_map_set($max, 0 x40);
4401 foreach my $g (@$globs) {
4402 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
4403 Git::SVN::tmp_config($k, $max);
4405 last if $max >= $head;
4406 $min = $max + 1;
4407 $max += $inc;
4408 $max = $head if ($max > $head);
4410 Git::SVN::gc();
4413 sub get_dir_globbed {
4414 my ($self, $left, $depth, $r) = @_;
4416 my @x = eval { $self->get_dir($left, $r) };
4417 return unless scalar @x == 3;
4418 my $dirents = $x[0];
4419 my @finalents;
4420 foreach my $de (keys %$dirents) {
4421 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
4422 if ($depth > 1) {
4423 my @args = ("$left/$de", $depth - 1, $r);
4424 foreach my $dir ($self->get_dir_globbed(@args)) {
4425 push @finalents, "$de/$dir";
4427 } else {
4428 push @finalents, $de;
4431 @finalents;
4434 sub match_globs {
4435 my ($self, $exists, $paths, $globs, $r) = @_;
4437 sub get_dir_check {
4438 my ($self, $exists, $g, $r) = @_;
4440 my @dirs = $self->get_dir_globbed($g->{path}->{left},
4441 $g->{path}->{depth},
4442 $r);
4444 foreach my $de (@dirs) {
4445 my $p = $g->{path}->full_path($de);
4446 next if $exists->{$p};
4447 next if (length $g->{path}->{right} &&
4448 ($self->check_path($p, $r) !=
4449 $SVN::Node::dir));
4450 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
4451 $g->{ref}->full_path($de), 1);
4454 foreach my $g (@$globs) {
4455 if (my $path = $paths->{"/$g->{path}->{left}"}) {
4456 if ($path->{action} =~ /^[AR]$/) {
4457 get_dir_check($self, $exists, $g, $r);
4460 foreach (keys %$paths) {
4461 if (/$g->{path}->{left_regex}/ &&
4462 !/$g->{path}->{regex}/) {
4463 next if $paths->{$_}->{action} !~ /^[AR]$/;
4464 get_dir_check($self, $exists, $g, $r);
4466 next unless /$g->{path}->{regex}/;
4467 my $p = $1;
4468 my $pathname = $g->{path}->full_path($p);
4469 next if $exists->{$pathname};
4470 next if ($self->check_path($pathname, $r) !=
4471 $SVN::Node::dir);
4472 $exists->{$pathname} = Git::SVN->init(
4473 $self->{url}, $pathname, undef,
4474 $g->{ref}->full_path($p), 1);
4476 my $c = '';
4477 foreach (split m#/#, $g->{path}->{left}) {
4478 $c .= "/$_";
4479 next unless ($paths->{$c} &&
4480 ($paths->{$c}->{action} =~ /^[AR]$/));
4481 get_dir_check($self, $exists, $g, $r);
4484 values %$exists;
4487 sub minimize_url {
4488 my ($self) = @_;
4489 return $self->{url} if ($self->{url} eq $self->{repos_root});
4490 my $url = $self->{repos_root};
4491 my @components = split(m!/!, $self->{svn_path});
4492 my $c = '';
4493 do {
4494 $url .= "/$c" if length $c;
4495 eval { (ref $self)->new($url)->get_latest_revnum };
4496 } while ($@ && ($c = shift @components));
4497 $url;
4500 sub can_do_switch {
4501 my $self = shift;
4502 unless (defined $can_do_switch) {
4503 my $pool = SVN::Pool->new;
4504 my $rep = eval {
4505 $self->do_switch(1, '', 0, $self->{url},
4506 SVN::Delta::Editor->new, $pool);
4508 if ($@) {
4509 $can_do_switch = 0;
4510 } else {
4511 $rep->abort_report($pool);
4512 $can_do_switch = 1;
4514 $pool->clear;
4516 $can_do_switch;
4519 sub skip_unknown_revs {
4520 my ($err) = @_;
4521 my $errno = $err->apr_err();
4522 # Maybe the branch we're tracking didn't
4523 # exist when the repo started, so it's
4524 # not an error if it doesn't, just continue
4526 # Wonderfully consistent library, eh?
4527 # 160013 - svn:// and file://
4528 # 175002 - http(s)://
4529 # 175007 - http(s):// (this repo required authorization, too...)
4530 # More codes may be discovered later...
4531 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
4532 my $err_key = $err->expanded_message;
4533 # revision numbers change every time, filter them out
4534 $err_key =~ s/\d+/\0/g;
4535 $err_key = "$errno\0$err_key";
4536 unless ($ignored_err{$err_key}) {
4537 warn "W: Ignoring error from SVN, path probably ",
4538 "does not exist: ($errno): ",
4539 $err->expanded_message,"\n";
4540 warn "W: Do not be alarmed at the above message ",
4541 "git-svn is just searching aggressively for ",
4542 "old history.\n",
4543 "This may take a while on large repositories\n";
4544 $ignored_err{$err_key} = 1;
4546 return;
4548 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
4551 # svn_log_changed_path_t objects passed to get_log are likely to be
4552 # overwritten even if only the refs are copied to an external variable,
4553 # so we should dup the structures in their entirety. Using an externally
4554 # passed pool (instead of our temporary and quickly cleared pool in
4555 # Git::SVN::Ra) does not help matters at all...
4556 sub dup_changed_paths {
4557 my ($paths) = @_;
4558 return undef unless $paths;
4559 my %ret;
4560 foreach my $p (keys %$paths) {
4561 my $i = $paths->{$p};
4562 my %s = map { $_ => $i->$_ }
4563 qw/copyfrom_path copyfrom_rev action/;
4564 $ret{$p} = \%s;
4566 \%ret;
4569 package Git::SVN::Log;
4570 use strict;
4571 use warnings;
4572 use POSIX qw/strftime/;
4573 use constant commit_log_separator => ('-' x 72) . "\n";
4574 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
4575 %rusers $show_commit $incremental/;
4576 my $l_fmt;
4578 sub cmt_showable {
4579 my ($c) = @_;
4580 return 1 if defined $c->{r};
4582 # big commit message got truncated by the 16k pretty buffer in rev-list
4583 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
4584 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
4585 @{$c->{l}} = ();
4586 my @log = command(qw/cat-file commit/, $c->{c});
4588 # shift off the headers
4589 shift @log while ($log[0] ne '');
4590 shift @log;
4592 # TODO: make $c->{l} not have a trailing newline in the future
4593 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
4595 (undef, $c->{r}, undef) = ::extract_metadata(
4596 (grep(/^git-svn-id: /, @log))[-1]);
4598 return defined $c->{r};
4601 sub log_use_color {
4602 return $color || Git->repository->get_colorbool('color.diff');
4605 sub git_svn_log_cmd {
4606 my ($r_min, $r_max, @args) = @_;
4607 my $head = 'HEAD';
4608 my (@files, @log_opts);
4609 foreach my $x (@args) {
4610 if ($x eq '--' || @files) {
4611 push @files, $x;
4612 } else {
4613 if (::verify_ref("$x^0")) {
4614 $head = $x;
4615 } else {
4616 push @log_opts, $x;
4621 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
4622 $gs ||= Git::SVN->_new;
4623 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
4624 $gs->refname);
4625 push @cmd, '-r' unless $non_recursive;
4626 push @cmd, qw/--raw --name-status/ if $verbose;
4627 push @cmd, '--color' if log_use_color();
4628 push @cmd, @log_opts;
4629 if (defined $r_max && $r_max == $r_min) {
4630 push @cmd, '--max-count=1';
4631 if (my $c = $gs->rev_map_get($r_max)) {
4632 push @cmd, $c;
4634 } elsif (defined $r_max) {
4635 if ($r_max < $r_min) {
4636 ($r_min, $r_max) = ($r_max, $r_min);
4638 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
4639 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
4640 # If there are no commits in the range, both $c_max and $c_min
4641 # will be undefined. If there is at least 1 commit in the
4642 # range, both will be defined.
4643 return () if !defined $c_min || !defined $c_max;
4644 if ($c_min eq $c_max) {
4645 push @cmd, '--max-count=1', $c_min;
4646 } else {
4647 push @cmd, '--boundary', "$c_min..$c_max";
4650 return (@cmd, @files);
4653 # adapted from pager.c
4654 sub config_pager {
4655 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
4656 if (!defined $pager) {
4657 $pager = 'less';
4658 } elsif (length $pager == 0 || $pager eq 'cat') {
4659 $pager = undef;
4661 $ENV{GIT_PAGER_IN_USE} = defined($pager);
4664 sub run_pager {
4665 return unless -t *STDOUT && defined $pager;
4666 pipe my ($rfd, $wfd) or return;
4667 defined(my $pid = fork) or ::fatal "Can't fork: $!";
4668 if (!$pid) {
4669 open STDOUT, '>&', $wfd or
4670 ::fatal "Can't redirect to stdout: $!";
4671 return;
4673 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
4674 $ENV{LESS} ||= 'FRSX';
4675 exec $pager or ::fatal "Can't run pager: $! ($pager)";
4678 sub format_svn_date {
4679 return strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)", localtime(shift));
4682 sub parse_git_date {
4683 my ($t, $tz) = @_;
4684 # Date::Parse isn't in the standard Perl distro :(
4685 if ($tz =~ s/^\+//) {
4686 $t += tz_to_s_offset($tz);
4687 } elsif ($tz =~ s/^\-//) {
4688 $t -= tz_to_s_offset($tz);
4690 return $t;
4693 sub set_local_timezone {
4694 if (defined $TZ) {
4695 $ENV{TZ} = $TZ;
4696 } else {
4697 delete $ENV{TZ};
4701 sub tz_to_s_offset {
4702 my ($tz) = @_;
4703 $tz =~ s/(\d\d)$//;
4704 return ($1 * 60) + ($tz * 3600);
4707 sub get_author_info {
4708 my ($dest, $author, $t, $tz) = @_;
4709 $author =~ s/(?:^\s*|\s*$)//g;
4710 $dest->{a_raw} = $author;
4711 my $au;
4712 if ($::_authors) {
4713 $au = $rusers{$author} || undef;
4715 if (!$au) {
4716 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
4718 $dest->{t} = $t;
4719 $dest->{tz} = $tz;
4720 $dest->{a} = $au;
4721 $dest->{t_utc} = parse_git_date($t, $tz);
4724 sub process_commit {
4725 my ($c, $r_min, $r_max, $defer) = @_;
4726 if (defined $r_min && defined $r_max) {
4727 if ($r_min == $c->{r} && $r_min == $r_max) {
4728 show_commit($c);
4729 return 0;
4731 return 1 if $r_min == $r_max;
4732 if ($r_min < $r_max) {
4733 # we need to reverse the print order
4734 return 0 if (defined $limit && --$limit < 0);
4735 push @$defer, $c;
4736 return 1;
4738 if ($r_min != $r_max) {
4739 return 1 if ($r_min < $c->{r});
4740 return 1 if ($r_max > $c->{r});
4743 return 0 if (defined $limit && --$limit < 0);
4744 show_commit($c);
4745 return 1;
4748 sub show_commit {
4749 my $c = shift;
4750 if ($oneline) {
4751 my $x = "\n";
4752 if (my $l = $c->{l}) {
4753 while ($l->[0] =~ /^\s*$/) { shift @$l }
4754 $x = $l->[0];
4756 $l_fmt ||= 'A' . length($c->{r});
4757 print 'r',pack($l_fmt, $c->{r}),' | ';
4758 print "$c->{c} | " if $show_commit;
4759 print $x;
4760 } else {
4761 show_commit_normal($c);
4765 sub show_commit_changed_paths {
4766 my ($c) = @_;
4767 return unless $c->{changed};
4768 print "Changed paths:\n", @{$c->{changed}};
4771 sub show_commit_normal {
4772 my ($c) = @_;
4773 print commit_log_separator, "r$c->{r} | ";
4774 print "$c->{c} | " if $show_commit;
4775 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
4776 my $nr_line = 0;
4778 if (my $l = $c->{l}) {
4779 while ($l->[$#$l] eq "\n" && $#$l > 0
4780 && $l->[($#$l - 1)] eq "\n") {
4781 pop @$l;
4783 $nr_line = scalar @$l;
4784 if (!$nr_line) {
4785 print "1 line\n\n\n";
4786 } else {
4787 if ($nr_line == 1) {
4788 $nr_line = '1 line';
4789 } else {
4790 $nr_line .= ' lines';
4792 print $nr_line, "\n";
4793 show_commit_changed_paths($c);
4794 print "\n";
4795 print $_ foreach @$l;
4797 } else {
4798 print "1 line\n";
4799 show_commit_changed_paths($c);
4800 print "\n";
4803 foreach my $x (qw/raw stat diff/) {
4804 if ($c->{$x}) {
4805 print "\n";
4806 print $_ foreach @{$c->{$x}}
4811 sub cmd_show_log {
4812 my (@args) = @_;
4813 my ($r_min, $r_max);
4814 my $r_last = -1; # prevent dupes
4815 set_local_timezone();
4816 if (defined $::_revision) {
4817 if ($::_revision =~ /^(\d+):(\d+)$/) {
4818 ($r_min, $r_max) = ($1, $2);
4819 } elsif ($::_revision =~ /^\d+$/) {
4820 $r_min = $r_max = $::_revision;
4821 } else {
4822 ::fatal "-r$::_revision is not supported, use ",
4823 "standard 'git log' arguments instead";
4827 config_pager();
4828 @args = git_svn_log_cmd($r_min, $r_max, @args);
4829 if (!@args) {
4830 print commit_log_separator unless $incremental || $oneline;
4831 return;
4833 my $log = command_output_pipe(@args);
4834 run_pager();
4835 my (@k, $c, $d, $stat);
4836 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
4837 while (<$log>) {
4838 if (/^${esc_color}commit -?($::sha1_short)/o) {
4839 my $cmt = $1;
4840 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
4841 $r_last = $c->{r};
4842 process_commit($c, $r_min, $r_max, \@k) or
4843 goto out;
4845 $d = undef;
4846 $c = { c => $cmt };
4847 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
4848 get_author_info($c, $1, $2, $3);
4849 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
4850 # ignore
4851 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
4852 push @{$c->{raw}}, $_;
4853 } elsif (/^${esc_color}[ACRMDT]\t/) {
4854 # we could add $SVN->{svn_path} here, but that requires
4855 # remote access at the moment (repo_path_split)...
4856 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
4857 push @{$c->{changed}}, $_;
4858 } elsif (/^${esc_color}diff /o) {
4859 $d = 1;
4860 push @{$c->{diff}}, $_;
4861 } elsif ($d) {
4862 push @{$c->{diff}}, $_;
4863 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
4864 $esc_color*[\+\-]*$esc_color$/x) {
4865 $stat = 1;
4866 push @{$c->{stat}}, $_;
4867 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
4868 push @{$c->{stat}}, $_;
4869 $stat = undef;
4870 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
4871 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
4872 } elsif (s/^${esc_color} //o) {
4873 push @{$c->{l}}, $_;
4876 if ($c && defined $c->{r} && $c->{r} != $r_last) {
4877 $r_last = $c->{r};
4878 process_commit($c, $r_min, $r_max, \@k);
4880 if (@k) {
4881 ($r_min, $r_max) = ($r_max, $r_min);
4882 process_commit($_, $r_min, $r_max) foreach reverse @k;
4884 out:
4885 close $log;
4886 print commit_log_separator unless $incremental || $oneline;
4889 sub cmd_blame {
4890 my $path = pop;
4892 config_pager();
4893 run_pager();
4895 my ($fh, $ctx, $rev);
4897 if ($_git_format) {
4898 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
4899 while (my $line = <$fh>) {
4900 if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
4901 # Uncommitted edits show up as a rev ID of
4902 # all zeros, which we can't look up with
4903 # cmt_metadata
4904 if ($1 !~ /^0+$/) {
4905 (undef, $rev, undef) =
4906 ::cmt_metadata($1);
4907 $rev = '0' if (!$rev);
4908 } else {
4909 $rev = '0';
4911 $rev = sprintf('%-10s', $rev);
4912 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
4914 print $line;
4916 } else {
4917 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
4918 '--', $path);
4919 my ($sha1);
4920 my %authors;
4921 while (my $line = <$fh>) {
4922 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
4923 $sha1 = $1;
4924 (undef, $rev, undef) = ::cmt_metadata($1);
4925 $rev = '0' if (!$rev);
4927 elsif ($line =~ /^author (.*)/) {
4928 $authors{$rev} = $1;
4929 $authors{$rev} =~ s/\s/_/g;
4931 elsif ($line =~ /^\t(.*)$/) {
4932 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
4936 command_close_pipe($fh, $ctx);
4939 package Git::SVN::Migration;
4940 # these version numbers do NOT correspond to actual version numbers
4941 # of git nor git-svn. They are just relative.
4943 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
4945 # v1 layout: .git/$id/info/url, refs/remotes/$id
4947 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
4949 # v3 layout: .git/svn/$id, refs/remotes/$id
4950 # - info/url may remain for backwards compatibility
4951 # - this is what we migrate up to this layout automatically,
4952 # - this will be used by git svn init on single branches
4953 # v3.1 layout (auto migrated):
4954 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
4955 # for backwards compatibility
4957 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
4958 # - this is only created for newly multi-init-ed
4959 # repositories. Similar in spirit to the
4960 # --use-separate-remotes option in git-clone (now default)
4961 # - we do not automatically migrate to this (following
4962 # the example set by core git)
4964 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
4965 # - newer, more-efficient format that uses 24-bytes per record
4966 # with no filler space.
4967 # - use xxd -c24 < .rev_map.$UUID to view and debug
4968 # - This is a one-way migration, repositories updated to the
4969 # new format will not be able to use old git-svn without
4970 # rebuilding the .rev_db. Rebuilding the rev_db is not
4971 # possible if noMetadata or useSvmProps are set; but should
4972 # be no problem for users that use the (sensible) defaults.
4973 use strict;
4974 use warnings;
4975 use Carp qw/croak/;
4976 use File::Path qw/mkpath/;
4977 use File::Basename qw/dirname basename/;
4978 use vars qw/$_minimize/;
4980 sub migrate_from_v0 {
4981 my $git_dir = $ENV{GIT_DIR};
4982 return undef unless -d $git_dir;
4983 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
4984 my $migrated = 0;
4985 while (<$fh>) {
4986 chomp;
4987 my ($id, $orig_ref) = ($_, $_);
4988 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
4989 next unless -f "$git_dir/$id/info/url";
4990 my $new_ref = "refs/remotes/$id";
4991 if (::verify_ref("$new_ref^0")) {
4992 print STDERR "W: $orig_ref is probably an old ",
4993 "branch used by an ancient version of ",
4994 "git-svn.\n",
4995 "However, $new_ref also exists.\n",
4996 "We will not be able ",
4997 "to use this branch until this ",
4998 "ambiguity is resolved.\n";
4999 next;
5001 print STDERR "Migrating from v0 layout...\n" if !$migrated;
5002 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
5003 command_noisy('update-ref', $new_ref, $orig_ref);
5004 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
5005 $migrated++;
5007 command_close_pipe($fh, $ctx);
5008 print STDERR "Done migrating from v0 layout...\n" if $migrated;
5009 $migrated;
5012 sub migrate_from_v1 {
5013 my $git_dir = $ENV{GIT_DIR};
5014 my $migrated = 0;
5015 return $migrated unless -d $git_dir;
5016 my $svn_dir = "$git_dir/svn";
5018 # just in case somebody used 'svn' as their $id at some point...
5019 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
5021 print STDERR "Migrating from a git-svn v1 layout...\n";
5022 mkpath([$svn_dir]);
5023 print STDERR "Data from a previous version of git-svn exists, but\n\t",
5024 "$svn_dir\n\t(required for this version ",
5025 "($::VERSION) of git-svn) does not exist.\n";
5026 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5027 while (<$fh>) {
5028 my $x = $_;
5029 next unless $x =~ s#^refs/remotes/##;
5030 chomp $x;
5031 next unless -f "$git_dir/$x/info/url";
5032 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
5033 next unless $u;
5034 my $dn = dirname("$git_dir/svn/$x");
5035 mkpath([$dn]) unless -d $dn;
5036 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
5037 mkpath(["$git_dir/svn/svn"]);
5038 print STDERR " - $git_dir/$x/info => ",
5039 "$git_dir/svn/$x/info\n";
5040 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
5041 croak "$!: $x";
5042 # don't worry too much about these, they probably
5043 # don't exist with repos this old (save for index,
5044 # and we can easily regenerate that)
5045 foreach my $f (qw/unhandled.log index .rev_db/) {
5046 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
5048 } else {
5049 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
5050 rename "$git_dir/$x", "$git_dir/svn/$x" or
5051 croak "$!: $x";
5053 $migrated++;
5055 command_close_pipe($fh, $ctx);
5056 print STDERR "Done migrating from a git-svn v1 layout\n";
5057 $migrated;
5060 sub read_old_urls {
5061 my ($l_map, $pfx, $path) = @_;
5062 my @dir;
5063 foreach (<$path/*>) {
5064 if (-r "$_/info/url") {
5065 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
5066 my $ref_id = $pfx . basename $_;
5067 my $url = ::file_to_s("$_/info/url");
5068 $l_map->{$ref_id} = $url;
5069 } elsif (-d $_) {
5070 push @dir, $_;
5073 foreach (@dir) {
5074 my $x = $_;
5075 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
5076 read_old_urls($l_map, $x, $_);
5080 sub migrate_from_v2 {
5081 my @cfg = command(qw/config -l/);
5082 return if grep /^svn-remote\..+\.url=/, @cfg;
5083 my %l_map;
5084 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
5085 my $migrated = 0;
5087 foreach my $ref_id (sort keys %l_map) {
5088 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
5089 if ($@) {
5090 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
5092 $migrated++;
5094 $migrated;
5097 sub minimize_connections {
5098 my $r = Git::SVN::read_all_remotes();
5099 my $new_urls = {};
5100 my $root_repos = {};
5101 foreach my $repo_id (keys %$r) {
5102 my $url = $r->{$repo_id}->{url} or next;
5103 my $fetch = $r->{$repo_id}->{fetch} or next;
5104 my $ra = Git::SVN::Ra->new($url);
5106 # skip existing cases where we already connect to the root
5107 if (($ra->{url} eq $ra->{repos_root}) ||
5108 ($ra->{repos_root} eq $repo_id)) {
5109 $root_repos->{$ra->{url}} = $repo_id;
5110 next;
5113 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
5114 my $root_path = $ra->{url};
5115 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
5116 foreach my $path (keys %$fetch) {
5117 my $ref_id = $fetch->{$path};
5118 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
5120 # make sure we can read when connecting to
5121 # a higher level of a repository
5122 my ($last_rev, undef) = $gs->last_rev_commit;
5123 if (!defined $last_rev) {
5124 $last_rev = eval {
5125 $root_ra->get_latest_revnum;
5127 next if $@;
5129 my $new = $root_path;
5130 $new .= length $path ? "/$path" : '';
5131 eval {
5132 $root_ra->get_log([$new], $last_rev, $last_rev,
5133 0, 0, 1, sub { });
5135 next if $@;
5136 $new_urls->{$ra->{repos_root}}->{$new} =
5137 { ref_id => $ref_id,
5138 old_repo_id => $repo_id,
5139 old_path => $path };
5143 my @emptied;
5144 foreach my $url (keys %$new_urls) {
5145 # see if we can re-use an existing [svn-remote "repo_id"]
5146 # instead of creating a(n ugly) new section:
5147 my $repo_id = $root_repos->{$url} || $url;
5149 my $fetch = $new_urls->{$url};
5150 foreach my $path (keys %$fetch) {
5151 my $x = $fetch->{$path};
5152 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
5153 my $pfx = "svn-remote.$x->{old_repo_id}";
5155 my $old_fetch = quotemeta("$x->{old_path}:".
5156 "refs/remotes/$x->{ref_id}");
5157 command_noisy(qw/config --unset/,
5158 "$pfx.fetch", '^'. $old_fetch . '$');
5159 delete $r->{$x->{old_repo_id}}->
5160 {fetch}->{$x->{old_path}};
5161 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
5162 command_noisy(qw/config --unset/,
5163 "$pfx.url");
5164 push @emptied, $x->{old_repo_id}
5168 if (@emptied) {
5169 my $file = $ENV{GIT_CONFIG} || "$ENV{GIT_DIR}/config";
5170 print STDERR <<EOF;
5171 The following [svn-remote] sections in your config file ($file) are empty
5172 and can be safely removed:
5174 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
5178 sub migration_check {
5179 migrate_from_v0();
5180 migrate_from_v1();
5181 migrate_from_v2();
5182 minimize_connections() if $_minimize;
5185 package Git::IndexInfo;
5186 use strict;
5187 use warnings;
5188 use Git qw/command_input_pipe command_close_pipe/;
5190 sub new {
5191 my ($class) = @_;
5192 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
5193 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
5196 sub remove {
5197 my ($self, $path) = @_;
5198 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
5199 return ++$self->{nr};
5201 undef;
5204 sub update {
5205 my ($self, $mode, $hash, $path) = @_;
5206 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
5207 return ++$self->{nr};
5209 undef;
5212 sub DESTROY {
5213 my ($self) = @_;
5214 command_close_pipe($self->{gui}, $self->{ctx});
5217 package Git::SVN::GlobSpec;
5218 use strict;
5219 use warnings;
5221 sub new {
5222 my ($class, $glob) = @_;
5223 my $re = $glob;
5224 $re =~ s!/+$!!g; # no need for trailing slashes
5225 $re =~ m!^([^*]*)(\*(?:/\*)*)([^*]*)$!;
5226 my $temp = $re;
5227 my ($left, $right) = ($1, $3);
5228 $re = $2;
5229 my $depth = $re =~ tr/*/*/;
5230 if ($depth != $temp =~ tr/*/*/) {
5231 die "Only one set of wildcard directories " .
5232 "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
5234 if ($depth == 0) {
5235 die "One '*' is needed for glob: '$glob'\n";
5237 $re =~ s!\*!\[^/\]*!g;
5238 $re = quotemeta($left) . "($re)" . quotemeta($right);
5239 if (length $left && !($left =~ s!/+$!!g)) {
5240 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
5242 if (length $right && !($right =~ s!^/+!!g)) {
5243 die "Missing leading '/' on right side of: '$glob' ($right)\n";
5245 my $left_re = qr/^\/\Q$left\E(\/|$)/;
5246 bless { left => $left, right => $right, left_regex => $left_re,
5247 regex => qr/$re/, glob => $glob, depth => $depth }, $class;
5250 sub full_path {
5251 my ($self, $path) = @_;
5252 return (length $self->{left} ? "$self->{left}/" : '') .
5253 $path . (length $self->{right} ? "/$self->{right}" : '');
5256 __END__
5258 Data structures:
5261 $remotes = { # returned by read_all_remotes()
5262 'svn' => {
5263 # svn-remote.svn.url=https://svn.musicpd.org
5264 url => 'https://svn.musicpd.org',
5265 # svn-remote.svn.fetch=mpd/trunk:trunk
5266 fetch => {
5267 'mpd/trunk' => 'trunk',
5269 # svn-remote.svn.tags=mpd/tags/*:tags/*
5270 tags => {
5271 path => {
5272 left => 'mpd/tags',
5273 right => '',
5274 regex => qr!mpd/tags/([^/]+)$!,
5275 glob => 'tags/*',
5277 ref => {
5278 left => 'tags',
5279 right => '',
5280 regex => qr!tags/([^/]+)$!,
5281 glob => 'tags/*',
5287 $log_entry hashref as returned by libsvn_log_entry()
5289 log => 'whitespace-formatted log entry
5290 ', # trailing newline is preserved
5291 revision => '8', # integer
5292 date => '2004-02-24T17:01:44.108345Z', # commit date
5293 author => 'committer name'
5297 # this is generated by generate_diff();
5298 @mods = array of diff-index line hashes, each element represents one line
5299 of diff-index output
5301 diff-index line ($m hash)
5303 mode_a => first column of diff-index output, no leading ':',
5304 mode_b => second column of diff-index output,
5305 sha1_b => sha1sum of the final blob,
5306 chg => change type [MCRADT],
5307 file_a => original file name of a file (iff chg is 'C' or 'R')
5308 file_b => new/current file name of a file (any chg)
5312 # retval of read_url_paths{,_all}();
5313 $l_map = {
5314 # repository root url
5315 'https://svn.musicpd.org' => {
5316 # repository path # GIT_SVN_ID
5317 'mpd/trunk' => 'trunk',
5318 'mpd/tags/0.11.5' => 'tags/0.11.5',
5322 Notes:
5323 I don't trust the each() function on unless I created %hash myself
5324 because the internal iterator may not have started at base.