Documentation/git.txt: update links to release notes
[git/haiku.git] / git-svn.perl
blob33017974d0a098bdaff707ccf0e8660aa5009079
1 #!/usr/bin/env perl
2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
4 use warnings;
5 use strict;
6 use vars qw/ $AUTHOR $VERSION
7 $sha1 $sha1_short $_revision $_repository
8 $_q $_authors $_authors_prog %users/;
9 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
10 $VERSION = '@@GIT_VERSION@@';
12 # From which subdir have we been invoked?
13 my $cmd_dir_prefix = eval {
14 command_oneline([qw/rev-parse --show-prefix/], STDERR => 0)
15 } || '';
17 my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
18 $ENV{GIT_DIR} ||= '.git';
19 $Git::SVN::default_repo_id = 'svn';
20 $Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
21 $Git::SVN::Ra::_log_window_size = 100;
23 $Git::SVN::Log::TZ = $ENV{TZ};
24 $ENV{TZ} = 'UTC';
25 $| = 1; # unbuffer STDOUT
27 sub fatal (@) { print STDERR "@_\n"; exit 1 }
28 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
29 require SVN::Ra;
30 require SVN::Delta;
31 if ($SVN::Core::VERSION lt '1.1.0') {
32 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
34 push @Git::SVN::Ra::ISA, 'SVN::Ra';
35 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
36 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
37 use Carp qw/croak/;
38 use Digest::MD5;
39 use IO::File qw//;
40 use File::Basename qw/dirname basename/;
41 use File::Path qw/mkpath/;
42 use File::Spec;
43 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
44 use IPC::Open3;
45 use Git;
47 BEGIN {
48 # import functions from Git into our packages, en masse
49 no strict 'refs';
50 foreach (qw/command command_oneline command_noisy command_output_pipe
51 command_input_pipe command_close_pipe
52 command_bidi_pipe command_close_bidi_pipe/) {
53 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
54 Git::SVN::Migration Git::SVN::Log Git::SVN),
55 __PACKAGE__) {
56 *{"${package}::$_"} = \&{"Git::$_"};
61 my ($SVN);
63 $sha1 = qr/[a-f\d]{40}/;
64 $sha1_short = qr/[a-f\d]{4,40}/;
65 my ($_stdin, $_help, $_edit,
66 $_message, $_file,
67 $_template, $_shared,
68 $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
69 $_merge, $_strategy, $_dry_run, $_local,
70 $_prefix, $_no_checkout, $_url, $_verbose,
71 $_git_format, $_commit_url, $_tag);
72 $Git::SVN::_follow_parent = 1;
73 $_q ||= 0;
74 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
75 'config-dir=s' => \$Git::SVN::Ra::config_dir,
76 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
77 'ignore-paths=s' => \$SVN::Git::Fetcher::_ignore_regex );
78 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
79 'authors-file|A=s' => \$_authors,
80 'authors-prog=s' => \$_authors_prog,
81 'repack:i' => \$Git::SVN::_repack,
82 'noMetadata' => \$Git::SVN::_no_metadata,
83 'useSvmProps' => \$Git::SVN::_use_svm_props,
84 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
85 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
86 'no-checkout' => \$_no_checkout,
87 'quiet|q+' => \$_q,
88 'repack-flags|repack-args|repack-opts=s' =>
89 \$Git::SVN::_repack_flags,
90 'use-log-author' => \$Git::SVN::_use_log_author,
91 'add-author-from' => \$Git::SVN::_add_author_from,
92 'localtime' => \$Git::SVN::_localtime,
93 %remote_opts );
95 my ($_trunk, $_tags, $_branches, $_stdlayout);
96 my %icv;
97 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
98 'trunk|T=s' => \$_trunk, 'tags|t=s' => \$_tags,
99 'branches|b=s' => \$_branches, 'prefix=s' => \$_prefix,
100 'stdlayout|s' => \$_stdlayout,
101 'minimize-url|m' => \$Git::SVN::_minimize_url,
102 'no-metadata' => sub { $icv{noMetadata} = 1 },
103 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
104 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
105 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
106 %remote_opts );
107 my %cmt_opts = ( 'edit|e' => \$_edit,
108 'rmdir' => \$SVN::Git::Editor::_rmdir,
109 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
110 'l=i' => \$SVN::Git::Editor::_rename_limit,
111 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
114 my %cmd = (
115 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
116 { 'revision|r=s' => \$_revision,
117 'fetch-all|all' => \$_fetch_all,
118 'parent|p' => \$_fetch_parent,
119 %fc_opts } ],
120 clone => [ \&cmd_clone, "Initialize and fetch revisions",
121 { 'revision|r=s' => \$_revision,
122 %fc_opts, %init_opts } ],
123 init => [ \&cmd_init, "Initialize a repo for tracking" .
124 " (requires URL argument)",
125 \%init_opts ],
126 'multi-init' => [ \&cmd_multi_init,
127 "Deprecated alias for ".
128 "'$0 init -T<trunk> -b<branches> -t<tags>'",
129 \%init_opts ],
130 dcommit => [ \&cmd_dcommit,
131 'Commit several diffs to merge with upstream',
132 { 'merge|m|M' => \$_merge,
133 'strategy|s=s' => \$_strategy,
134 'verbose|v' => \$_verbose,
135 'dry-run|n' => \$_dry_run,
136 'fetch-all|all' => \$_fetch_all,
137 'commit-url=s' => \$_commit_url,
138 'revision|r=i' => \$_revision,
139 'no-rebase' => \$_no_rebase,
140 %cmt_opts, %fc_opts } ],
141 branch => [ \&cmd_branch,
142 'Create a branch in the SVN repository',
143 { 'message|m=s' => \$_message,
144 'dry-run|n' => \$_dry_run,
145 'tag|t' => \$_tag } ],
146 tag => [ sub { $_tag = 1; cmd_branch(@_) },
147 'Create a tag in the SVN repository',
148 { 'message|m=s' => \$_message,
149 'dry-run|n' => \$_dry_run } ],
150 'set-tree' => [ \&cmd_set_tree,
151 "Set an SVN repository to a git tree-ish",
152 { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
153 'create-ignore' => [ \&cmd_create_ignore,
154 'Create a .gitignore per svn:ignore',
155 { 'revision|r=i' => \$_revision
156 } ],
157 'propget' => [ \&cmd_propget,
158 'Print the value of a property on a file or directory',
159 { 'revision|r=i' => \$_revision } ],
160 'proplist' => [ \&cmd_proplist,
161 'List all properties of a file or directory',
162 { 'revision|r=i' => \$_revision } ],
163 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
164 { 'revision|r=i' => \$_revision
165 } ],
166 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
167 { 'revision|r=i' => \$_revision
168 } ],
169 'multi-fetch' => [ \&cmd_multi_fetch,
170 "Deprecated alias for $0 fetch --all",
171 { 'revision|r=s' => \$_revision, %fc_opts } ],
172 'migrate' => [ sub { },
173 # no-op, we automatically run this anyways,
174 'Migrate configuration/metadata/layout from
175 previous versions of git-svn',
176 { 'minimize' => \$Git::SVN::Migration::_minimize,
177 %remote_opts } ],
178 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
179 { 'limit=i' => \$Git::SVN::Log::limit,
180 'revision|r=s' => \$_revision,
181 'verbose|v' => \$Git::SVN::Log::verbose,
182 'incremental' => \$Git::SVN::Log::incremental,
183 'oneline' => \$Git::SVN::Log::oneline,
184 'show-commit' => \$Git::SVN::Log::show_commit,
185 'non-recursive' => \$Git::SVN::Log::non_recursive,
186 'authors-file|A=s' => \$_authors,
187 'color' => \$Git::SVN::Log::color,
188 'pager=s' => \$Git::SVN::Log::pager
189 } ],
190 'find-rev' => [ \&cmd_find_rev,
191 "Translate between SVN revision numbers and tree-ish",
192 {} ],
193 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
194 { 'merge|m|M' => \$_merge,
195 'verbose|v' => \$_verbose,
196 'strategy|s=s' => \$_strategy,
197 'local|l' => \$_local,
198 'fetch-all|all' => \$_fetch_all,
199 'dry-run|n' => \$_dry_run,
200 %fc_opts } ],
201 'commit-diff' => [ \&cmd_commit_diff,
202 'Commit a diff between two trees',
203 { 'message|m=s' => \$_message,
204 'file|F=s' => \$_file,
205 'revision|r=s' => \$_revision,
206 %cmt_opts } ],
207 'info' => [ \&cmd_info,
208 "Show info about the latest SVN revision
209 on the current branch",
210 { 'url' => \$_url, } ],
211 'blame' => [ \&Git::SVN::Log::cmd_blame,
212 "Show what revision and author last modified each line of a file",
213 { 'git-format' => \$_git_format } ],
216 my $cmd;
217 for (my $i = 0; $i < @ARGV; $i++) {
218 if (defined $cmd{$ARGV[$i]}) {
219 $cmd = $ARGV[$i];
220 splice @ARGV, $i, 1;
221 last;
225 # make sure we're always running at the top-level working directory
226 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
227 unless (-d $ENV{GIT_DIR}) {
228 if ($git_dir_user_set) {
229 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
230 "but it is not a directory\n";
232 my $git_dir = delete $ENV{GIT_DIR};
233 my $cdup = undef;
234 git_cmd_try {
235 $cdup = command_oneline(qw/rev-parse --show-cdup/);
236 $git_dir = '.' unless ($cdup);
237 chomp $cdup if ($cdup);
238 $cdup = "." unless ($cdup && length $cdup);
239 } "Already at toplevel, but $git_dir not found\n";
240 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
241 unless (-d $git_dir) {
242 die "$git_dir still not found after going to ",
243 "'$cdup'\n";
245 $ENV{GIT_DIR} = $git_dir;
247 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
250 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
252 read_repo_config(\%opts);
253 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
254 Getopt::Long::Configure('pass_through');
256 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
257 'minimize-connections' => \$Git::SVN::Migration::_minimize,
258 'id|i=s' => \$Git::SVN::default_ref_id,
259 'svn-remote|remote|R=s' => sub {
260 $Git::SVN::no_reuse_existing = 1;
261 $Git::SVN::default_repo_id = $_[1] });
262 exit 1 if (!$rv && $cmd && $cmd ne 'log');
264 usage(0) if $_help;
265 version() if $_version;
266 usage(1) unless defined $cmd;
267 load_authors() if $_authors;
268 if (defined $_authors_prog) {
269 $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
272 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
273 Git::SVN::Migration::migration_check();
275 Git::SVN::init_vars();
276 eval {
277 Git::SVN::verify_remotes_sanity();
278 $cmd{$cmd}->[0]->(@ARGV);
280 fatal $@ if $@;
281 post_fetch_checkout();
282 exit 0;
284 ####################### primary functions ######################
285 sub usage {
286 my $exit = shift || 0;
287 my $fd = $exit ? \*STDERR : \*STDOUT;
288 print $fd <<"";
289 git-svn - bidirectional operations between a single Subversion tree and git
290 Usage: git svn <command> [options] [arguments]\n
292 print $fd "Available commands:\n" unless $cmd;
294 foreach (sort keys %cmd) {
295 next if $cmd && $cmd ne $_;
296 next if /^multi-/; # don't show deprecated commands
297 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
298 foreach (sort keys %{$cmd{$_}->[2]}) {
299 # mixed-case options are for .git/config only
300 next if /[A-Z]/ && /^[a-z]+$/i;
301 # prints out arguments as they should be passed:
302 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
303 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
304 "--$_" : "-$_" }
305 split /\|/,$_)," $x\n";
308 print $fd <<"";
309 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
310 arbitrary identifier if you're tracking multiple SVN branches/repositories in
311 one git repository and want to keep them separate. See git-svn(1) for more
312 information.
314 exit $exit;
317 sub version {
318 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
319 exit 0;
322 sub do_git_init_db {
323 unless (-d $ENV{GIT_DIR}) {
324 my @init_db = ('init');
325 push @init_db, "--template=$_template" if defined $_template;
326 if (defined $_shared) {
327 if ($_shared =~ /[a-z]/) {
328 push @init_db, "--shared=$_shared";
329 } else {
330 push @init_db, "--shared";
333 command_noisy(@init_db);
334 $_repository = Git->repository(Repository => ".git");
336 command_noisy('config', 'core.autocrlf', 'false');
337 my $set;
338 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
339 foreach my $i (keys %icv) {
340 die "'$set' and '$i' cannot both be set\n" if $set;
341 next unless defined $icv{$i};
342 command_noisy('config', "$pfx.$i", $icv{$i});
343 $set = $i;
345 my $ignore_regex = \$SVN::Git::Fetcher::_ignore_regex;
346 command_noisy('config', "$pfx.ignore-paths", $$ignore_regex)
347 if defined $$ignore_regex;
350 sub init_subdir {
351 my $repo_path = shift or return;
352 mkpath([$repo_path]) unless -d $repo_path;
353 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
354 $ENV{GIT_DIR} = '.git';
355 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
358 sub cmd_clone {
359 my ($url, $path) = @_;
360 if (!defined $path &&
361 (defined $_trunk || defined $_branches || defined $_tags ||
362 defined $_stdlayout) &&
363 $url !~ m#^[a-z\+]+://#) {
364 $path = $url;
366 $path = basename($url) if !defined $path || !length $path;
367 cmd_init($url, $path);
368 Git::SVN::fetch_all($Git::SVN::default_repo_id);
369 command_oneline('config', 'svn.authorsfile', $_authors) if $_authors;
372 sub cmd_init {
373 if (defined $_stdlayout) {
374 $_trunk = 'trunk' if (!defined $_trunk);
375 $_tags = 'tags' if (!defined $_tags);
376 $_branches = 'branches' if (!defined $_branches);
378 if (defined $_trunk || defined $_branches || defined $_tags) {
379 return cmd_multi_init(@_);
381 my $url = shift or die "SVN repository location required ",
382 "as a command-line argument\n";
383 init_subdir(@_);
384 do_git_init_db();
386 Git::SVN->init($url);
389 sub cmd_fetch {
390 if (grep /^\d+=./, @_) {
391 die "'<rev>=<commit>' fetch arguments are ",
392 "no longer supported.\n";
394 my ($remote) = @_;
395 if (@_ > 1) {
396 die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
398 if ($_fetch_parent) {
399 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
400 unless ($gs) {
401 die "Unable to determine upstream SVN information from ",
402 "working tree history\n";
404 # just fetch, don't checkout.
405 $_no_checkout = 'true';
406 $_fetch_all ? $gs->fetch_all : $gs->fetch;
407 } elsif ($_fetch_all) {
408 cmd_multi_fetch();
409 } else {
410 $remote ||= $Git::SVN::default_repo_id;
411 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
415 sub cmd_set_tree {
416 my (@commits) = @_;
417 if ($_stdin || !@commits) {
418 print "Reading from stdin...\n";
419 @commits = ();
420 while (<STDIN>) {
421 if (/\b($sha1_short)\b/o) {
422 unshift @commits, $1;
426 my @revs;
427 foreach my $c (@commits) {
428 my @tmp = command('rev-parse',$c);
429 if (scalar @tmp == 1) {
430 push @revs, $tmp[0];
431 } elsif (scalar @tmp > 1) {
432 push @revs, reverse(command('rev-list',@tmp));
433 } else {
434 fatal "Failed to rev-parse $c";
437 my $gs = Git::SVN->new;
438 my ($r_last, $cmt_last) = $gs->last_rev_commit;
439 $gs->fetch;
440 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
441 fatal "There are new revisions that were fetched ",
442 "and need to be merged (or acknowledged) ",
443 "before committing.\nlast rev: $r_last\n",
444 " current: $gs->{last_rev}";
446 $gs->set_tree($_) foreach @revs;
447 print "Done committing ",scalar @revs," revisions to SVN\n";
448 unlink $gs->{index};
451 sub cmd_dcommit {
452 my $head = shift;
453 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
454 'Cannot dcommit with a dirty index. Commit your changes first, '
455 . "or stash them with `git stash'.\n";
456 $head ||= 'HEAD';
457 my @refs;
458 my ($url, $rev, $uuid, $gs) = working_head_info($head, \@refs);
459 unless ($gs) {
460 die "Unable to determine upstream SVN information from ",
461 "$head history.\nPerhaps the repository is empty.";
464 if (defined $_commit_url) {
465 $url = $_commit_url;
466 } else {
467 $url = eval { command_oneline('config', '--get',
468 "svn-remote.$gs->{repo_id}.commiturl") };
469 if (!$url) {
470 $url = $gs->full_url
474 my $last_rev = $_revision if defined $_revision;
475 if ($url) {
476 print "Committing to $url ...\n";
478 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
479 if ($_no_rebase && scalar(@$linear_refs) > 1) {
480 warn "Attempting to commit more than one change while ",
481 "--no-rebase is enabled.\n",
482 "If these changes depend on each other, re-running ",
483 "without --no-rebase may be required."
485 my $expect_url = $url;
486 Git::SVN::remove_username($expect_url);
487 while (1) {
488 my $d = shift @$linear_refs or last;
489 unless (defined $last_rev) {
490 (undef, $last_rev, undef) = cmt_metadata("$d~1");
491 unless (defined $last_rev) {
492 fatal "Unable to extract revision information ",
493 "from commit $d~1";
496 if ($_dry_run) {
497 print "diff-tree $d~1 $d\n";
498 } else {
499 my $cmt_rev;
500 my %ed_opts = ( r => $last_rev,
501 log => get_commit_entry($d)->{log},
502 ra => Git::SVN::Ra->new($url),
503 config => SVN::Core::config_get_config(
504 $Git::SVN::Ra::config_dir
506 tree_a => "$d~1",
507 tree_b => $d,
508 editor_cb => sub {
509 print "Committed r$_[0]\n";
510 $cmt_rev = $_[0];
512 svn_path => '');
513 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
514 print "No changes\n$d~1 == $d\n";
515 } elsif ($parents->{$d} && @{$parents->{$d}}) {
516 $gs->{inject_parents_dcommit}->{$cmt_rev} =
517 $parents->{$d};
519 $_fetch_all ? $gs->fetch_all : $gs->fetch;
520 $last_rev = $cmt_rev;
521 next if $_no_rebase;
523 # we always want to rebase against the current HEAD,
524 # not any head that was passed to us
525 my @diff = command('diff-tree', $d,
526 $gs->refname, '--');
527 my @finish;
528 if (@diff) {
529 @finish = rebase_cmd();
530 print STDERR "W: $d and ", $gs->refname,
531 " differ, using @finish:\n",
532 join("\n", @diff), "\n";
533 } else {
534 print "No changes between current HEAD and ",
535 $gs->refname,
536 "\nResetting to the latest ",
537 $gs->refname, "\n";
538 @finish = qw/reset --mixed/;
540 command_noisy(@finish, $gs->refname);
541 if (@diff) {
542 @refs = ();
543 my ($url_, $rev_, $uuid_, $gs_) =
544 working_head_info($head, \@refs);
545 my ($linear_refs_, $parents_) =
546 linearize_history($gs_, \@refs);
547 if (scalar(@$linear_refs) !=
548 scalar(@$linear_refs_)) {
549 fatal "# of revisions changed ",
550 "\nbefore:\n",
551 join("\n", @$linear_refs),
552 "\n\nafter:\n",
553 join("\n", @$linear_refs_), "\n",
554 'If you are attempting to commit ',
555 "merges, try running:\n\t",
556 'git rebase --interactive',
557 '--preserve-merges ',
558 $gs->refname,
559 "\nBefore dcommitting";
561 if ($url_ ne $expect_url) {
562 fatal "URL mismatch after rebase: ",
563 "$url_ != $expect_url";
565 if ($uuid_ ne $uuid) {
566 fatal "uuid mismatch after rebase: ",
567 "$uuid_ != $uuid";
569 # remap parents
570 my (%p, @l, $i);
571 for ($i = 0; $i < scalar @$linear_refs; $i++) {
572 my $new = $linear_refs_->[$i] or next;
573 $p{$new} =
574 $parents->{$linear_refs->[$i]};
575 push @l, $new;
577 $parents = \%p;
578 $linear_refs = \@l;
582 unlink $gs->{index};
585 sub cmd_branch {
586 my ($branch_name, $head) = @_;
588 unless (defined $branch_name && length $branch_name) {
589 die(($_tag ? "tag" : "branch") . " name required\n");
591 $head ||= 'HEAD';
593 my ($src, $rev, undef, $gs) = working_head_info($head);
595 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
596 my $glob = $remote->{ $_tag ? 'tags' : 'branches' };
597 my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
598 my $dst = join '/', $remote->{url}, $lft, $branch_name, ($rgt || ());
600 my $ctx = SVN::Client->new(
601 auth => Git::SVN::Ra::_auth_providers(),
602 log_msg => sub {
603 ${ $_[0] } = defined $_message
604 ? $_message
605 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
606 . $branch_name;
610 eval {
611 $ctx->ls($dst, 'HEAD', 0);
612 } and die "branch ${branch_name} already exists\n";
614 print "Copying ${src} at r${rev} to ${dst}...\n";
615 $ctx->copy($src, $rev, $dst)
616 unless $_dry_run;
618 $gs->fetch_all;
621 sub cmd_find_rev {
622 my $revision_or_hash = shift or die "SVN or git revision required ",
623 "as a command-line argument\n";
624 my $result;
625 if ($revision_or_hash =~ /^r\d+$/) {
626 my $head = shift;
627 $head ||= 'HEAD';
628 my @refs;
629 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
630 unless ($gs) {
631 die "Unable to determine upstream SVN information from ",
632 "$head history\n";
634 my $desired_revision = substr($revision_or_hash, 1);
635 $result = $gs->rev_map_get($desired_revision, $uuid);
636 } else {
637 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
638 $result = $rev;
640 print "$result\n" if $result;
643 sub cmd_rebase {
644 command_noisy(qw/update-index --refresh/);
645 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
646 unless ($gs) {
647 die "Unable to determine upstream SVN information from ",
648 "working tree history\n";
650 if ($_dry_run) {
651 print "Remote Branch: " . $gs->refname . "\n";
652 print "SVN URL: " . $url . "\n";
653 return;
655 if (command(qw/diff-index HEAD --/)) {
656 print STDERR "Cannot rebase with uncommited changes:\n";
657 command_noisy('status');
658 exit 1;
660 unless ($_local) {
661 # rebase will checkout for us, so no need to do it explicitly
662 $_no_checkout = 'true';
663 $_fetch_all ? $gs->fetch_all : $gs->fetch;
665 command_noisy(rebase_cmd(), $gs->refname);
668 sub cmd_show_ignore {
669 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
670 $gs ||= Git::SVN->new;
671 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
672 $gs->prop_walk($gs->{path}, $r, sub {
673 my ($gs, $path, $props) = @_;
674 print STDOUT "\n# $path\n";
675 my $s = $props->{'svn:ignore'} or return;
676 $s =~ s/[\r\n]+/\n/g;
677 chomp $s;
678 $s =~ s#^#$path#gm;
679 print STDOUT "$s\n";
683 sub cmd_show_externals {
684 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
685 $gs ||= Git::SVN->new;
686 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
687 $gs->prop_walk($gs->{path}, $r, sub {
688 my ($gs, $path, $props) = @_;
689 print STDOUT "\n# $path\n";
690 my $s = $props->{'svn:externals'} or return;
691 $s =~ s/[\r\n]+/\n/g;
692 chomp $s;
693 $s =~ s#^#$path#gm;
694 print STDOUT "$s\n";
698 sub cmd_create_ignore {
699 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
700 $gs ||= Git::SVN->new;
701 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
702 $gs->prop_walk($gs->{path}, $r, sub {
703 my ($gs, $path, $props) = @_;
704 # $path is of the form /path/to/dir/
705 $path = '.' . $path;
706 # SVN can have attributes on empty directories,
707 # which git won't track
708 mkpath([$path]) unless -d $path;
709 my $ignore = $path . '.gitignore';
710 my $s = $props->{'svn:ignore'} or return;
711 open(GITIGNORE, '>', $ignore)
712 or fatal("Failed to open `$ignore' for writing: $!");
713 $s =~ s/[\r\n]+/\n/g;
714 chomp $s;
715 # Prefix all patterns so that the ignore doesn't apply
716 # to sub-directories.
717 $s =~ s#^#/#gm;
718 print GITIGNORE "$s\n";
719 close(GITIGNORE)
720 or fatal("Failed to close `$ignore': $!");
721 command_noisy('add', '-f', $ignore);
725 sub canonicalize_path {
726 my ($path) = @_;
727 my $dot_slash_added = 0;
728 if (substr($path, 0, 1) ne "/") {
729 $path = "./" . $path;
730 $dot_slash_added = 1;
732 # File::Spec->canonpath doesn't collapse x/../y into y (for a
733 # good reason), so let's do this manually.
734 $path =~ s#/+#/#g;
735 $path =~ s#/\.(?:/|$)#/#g;
736 $path =~ s#/[^/]+/\.\.##g;
737 $path =~ s#/$##g;
738 $path =~ s#^\./## if $dot_slash_added;
739 $path =~ s#^/##;
740 $path =~ s#^\.$##;
741 return $path;
744 # get_svnprops(PATH)
745 # ------------------
746 # Helper for cmd_propget and cmd_proplist below.
747 sub get_svnprops {
748 my $path = shift;
749 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
750 $gs ||= Git::SVN->new;
752 # prefix THE PATH by the sub-directory from which the user
753 # invoked us.
754 $path = $cmd_dir_prefix . $path;
755 fatal("No such file or directory: $path") unless -e $path;
756 my $is_dir = -d $path ? 1 : 0;
757 $path = $gs->{path} . '/' . $path;
759 # canonicalize the path (otherwise libsvn will abort or fail to
760 # find the file)
761 $path = canonicalize_path($path);
763 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
764 my $props;
765 if ($is_dir) {
766 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
768 else {
769 (undef, $props) = $gs->ra->get_file($path, $r, undef);
771 return $props;
774 # cmd_propget (PROP, PATH)
775 # ------------------------
776 # Print the SVN property PROP for PATH.
777 sub cmd_propget {
778 my ($prop, $path) = @_;
779 $path = '.' if not defined $path;
780 usage(1) if not defined $prop;
781 my $props = get_svnprops($path);
782 if (not defined $props->{$prop}) {
783 fatal("`$path' does not have a `$prop' SVN property.");
785 print $props->{$prop} . "\n";
788 # cmd_proplist (PATH)
789 # -------------------
790 # Print the list of SVN properties for PATH.
791 sub cmd_proplist {
792 my $path = shift;
793 $path = '.' if not defined $path;
794 my $props = get_svnprops($path);
795 print "Properties on '$path':\n";
796 foreach (sort keys %{$props}) {
797 print " $_\n";
801 sub cmd_multi_init {
802 my $url = shift;
803 unless (defined $_trunk || defined $_branches || defined $_tags) {
804 usage(1);
807 # there are currently some bugs that prevent multi-init/multi-fetch
808 # setups from working well without this.
809 $Git::SVN::_minimize_url = 1;
811 $_prefix = '' unless defined $_prefix;
812 if (defined $url) {
813 $url =~ s#/+$##;
814 init_subdir(@_);
816 do_git_init_db();
817 if (defined $_trunk) {
818 my $trunk_ref = $_prefix . 'trunk';
819 # try both old-style and new-style lookups:
820 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
821 unless ($gs_trunk) {
822 my ($trunk_url, $trunk_path) =
823 complete_svn_url($url, $_trunk);
824 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
825 undef, $trunk_ref);
828 return unless defined $_branches || defined $_tags;
829 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
830 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
831 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
834 sub cmd_multi_fetch {
835 my $remotes = Git::SVN::read_all_remotes();
836 foreach my $repo_id (sort keys %$remotes) {
837 if ($remotes->{$repo_id}->{url}) {
838 Git::SVN::fetch_all($repo_id, $remotes);
843 # this command is special because it requires no metadata
844 sub cmd_commit_diff {
845 my ($ta, $tb, $url) = @_;
846 my $usage = "Usage: $0 commit-diff -r<revision> ".
847 "<tree-ish> <tree-ish> [<URL>]";
848 fatal($usage) if (!defined $ta || !defined $tb);
849 my $svn_path = '';
850 if (!defined $url) {
851 my $gs = eval { Git::SVN->new };
852 if (!$gs) {
853 fatal("Needed URL or usable git-svn --id in ",
854 "the command-line\n", $usage);
856 $url = $gs->{url};
857 $svn_path = $gs->{path};
859 unless (defined $_revision) {
860 fatal("-r|--revision is a required argument\n", $usage);
862 if (defined $_message && defined $_file) {
863 fatal("Both --message/-m and --file/-F specified ",
864 "for the commit message.\n",
865 "I have no idea what you mean");
867 if (defined $_file) {
868 $_message = file_to_s($_file);
869 } else {
870 $_message ||= get_commit_entry($tb)->{log};
872 my $ra ||= Git::SVN::Ra->new($url);
873 my $r = $_revision;
874 if ($r eq 'HEAD') {
875 $r = $ra->get_latest_revnum;
876 } elsif ($r !~ /^\d+$/) {
877 die "revision argument: $r not understood by git-svn\n";
879 my %ed_opts = ( r => $r,
880 log => $_message,
881 ra => $ra,
882 tree_a => $ta,
883 tree_b => $tb,
884 editor_cb => sub { print "Committed r$_[0]\n" },
885 svn_path => $svn_path );
886 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
887 print "No changes\n$ta == $tb\n";
891 sub escape_uri_only {
892 my ($uri) = @_;
893 my @tmp;
894 foreach (split m{/}, $uri) {
895 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
896 push @tmp, $_;
898 join('/', @tmp);
901 sub escape_url {
902 my ($url) = @_;
903 if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
904 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
905 $url = "$scheme://$domain$uri";
907 $url;
910 sub cmd_info {
911 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
912 my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
913 if (exists $_[1]) {
914 die "Too many arguments specified\n";
917 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
919 if (!$file_type && !$diff_status) {
920 print STDERR "svn: '$path' is not under version control\n";
921 exit 1;
924 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
925 unless ($gs) {
926 die "Unable to determine upstream SVN information from ",
927 "working tree history\n";
930 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
931 $path = "." if $path eq "";
933 my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
935 if ($_url) {
936 print escape_url($full_url), "\n";
937 return;
940 my $result = "Path: $path\n";
941 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
942 $result .= "URL: " . escape_url($full_url) . "\n";
944 eval {
945 my $repos_root = $gs->repos_root;
946 Git::SVN::remove_username($repos_root);
947 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
949 if ($@) {
950 $result .= "Repository Root: (offline)\n";
952 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
953 ($SVN::Core::VERSION le '1.5.4' || $file_type ne "dir");
954 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
956 $result .= "Node Kind: " .
957 ($file_type eq "dir" ? "directory" : "file") . "\n";
959 my $schedule = $diff_status eq "A"
960 ? "add"
961 : ($diff_status eq "D" ? "delete" : "normal");
962 $result .= "Schedule: $schedule\n";
964 if ($diff_status eq "A") {
965 print $result, "\n";
966 return;
969 my ($lc_author, $lc_rev, $lc_date_utc);
970 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
971 my $log = command_output_pipe(@args);
972 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
973 while (<$log>) {
974 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
975 $lc_author = $1;
976 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
977 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
978 (undef, $lc_rev, undef) = ::extract_metadata($1);
981 close $log;
983 Git::SVN::Log::set_local_timezone();
985 $result .= "Last Changed Author: $lc_author\n";
986 $result .= "Last Changed Rev: $lc_rev\n";
987 $result .= "Last Changed Date: " .
988 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
990 if ($file_type ne "dir") {
991 my $text_last_updated_date =
992 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
993 $result .=
994 "Text Last Updated: " .
995 Git::SVN::Log::format_svn_date($text_last_updated_date) .
996 "\n";
997 my $checksum;
998 if ($diff_status eq "D") {
999 my ($fh, $ctx) =
1000 command_output_pipe(qw(cat-file blob), "HEAD:$path");
1001 if ($file_type eq "link") {
1002 my $file_name = <$fh>;
1003 $checksum = md5sum("link $file_name");
1004 } else {
1005 $checksum = md5sum($fh);
1007 command_close_pipe($fh, $ctx);
1008 } elsif ($file_type eq "link") {
1009 my $file_name =
1010 command(qw(cat-file blob), "HEAD:$path");
1011 $checksum =
1012 md5sum("link " . $file_name);
1013 } else {
1014 open FILE, "<", $path or die $!;
1015 $checksum = md5sum(\*FILE);
1016 close FILE or die $!;
1018 $result .= "Checksum: " . $checksum . "\n";
1021 print $result, "\n";
1024 ########################### utility functions #########################
1026 sub rebase_cmd {
1027 my @cmd = qw/rebase/;
1028 push @cmd, '-v' if $_verbose;
1029 push @cmd, qw/--merge/ if $_merge;
1030 push @cmd, "--strategy=$_strategy" if $_strategy;
1031 @cmd;
1034 sub post_fetch_checkout {
1035 return if $_no_checkout;
1036 my $gs = $Git::SVN::_head or return;
1037 return if verify_ref('refs/heads/master^0');
1039 my $valid_head = verify_ref('HEAD^0');
1040 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1041 return if ($valid_head || !verify_ref('HEAD^0'));
1043 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1044 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1045 return if -f $index;
1047 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1048 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1049 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1050 print STDERR "Checked out HEAD:\n ",
1051 $gs->full_url, " r", $gs->last_rev, "\n";
1054 sub complete_svn_url {
1055 my ($url, $path) = @_;
1056 $path =~ s#/+$##;
1057 if ($path !~ m#^[a-z\+]+://#) {
1058 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1059 fatal("E: '$path' is not a complete URL ",
1060 "and a separate URL is not specified");
1062 return ($url, $path);
1064 return ($path, '');
1067 sub complete_url_ls_init {
1068 my ($ra, $repo_path, $switch, $pfx) = @_;
1069 unless ($repo_path) {
1070 print STDERR "W: $switch not specified\n";
1071 return;
1073 $repo_path =~ s#/+$##;
1074 if ($repo_path =~ m#^[a-z\+]+://#) {
1075 $ra = Git::SVN::Ra->new($repo_path);
1076 $repo_path = '';
1077 } else {
1078 $repo_path =~ s#^/+##;
1079 unless ($ra) {
1080 fatal("E: '$repo_path' is not a complete URL ",
1081 "and a separate URL is not specified");
1084 my $url = $ra->{url};
1085 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1086 my $k = "svn-remote.$gs->{repo_id}.url";
1087 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1088 if ($orig_url && ($orig_url ne $gs->{url})) {
1089 die "$k already set: $orig_url\n",
1090 "wanted to set to: $gs->{url}\n";
1092 command_oneline('config', $k, $gs->{url}) unless $orig_url;
1093 my $remote_path = "$ra->{svn_path}/$repo_path";
1094 $remote_path =~ s#/+#/#g;
1095 $remote_path =~ s#^/##g;
1096 $remote_path .= "/*" if $remote_path !~ /\*/;
1097 my ($n) = ($switch =~ /^--(\w+)/);
1098 if (length $pfx && $pfx !~ m#/$#) {
1099 die "--prefix='$pfx' must have a trailing slash '/'\n";
1101 command_noisy('config',
1102 "svn-remote.$gs->{repo_id}.$n",
1103 "$remote_path:refs/remotes/$pfx*" .
1104 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1107 sub verify_ref {
1108 my ($ref) = @_;
1109 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1110 { STDERR => 0 }); };
1113 sub get_tree_from_treeish {
1114 my ($treeish) = @_;
1115 # $treeish can be a symbolic ref, too:
1116 my $type = command_oneline(qw/cat-file -t/, $treeish);
1117 my $expected;
1118 while ($type eq 'tag') {
1119 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1121 if ($type eq 'commit') {
1122 $expected = (grep /^tree /, command(qw/cat-file commit/,
1123 $treeish))[0];
1124 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1125 die "Unable to get tree from $treeish\n" unless $expected;
1126 } elsif ($type eq 'tree') {
1127 $expected = $treeish;
1128 } else {
1129 die "$treeish is a $type, expected tree, tag or commit\n";
1131 return $expected;
1134 sub get_commit_entry {
1135 my ($treeish) = shift;
1136 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1137 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1138 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1139 open my $log_fh, '>', $commit_editmsg or croak $!;
1141 my $type = command_oneline(qw/cat-file -t/, $treeish);
1142 if ($type eq 'commit' || $type eq 'tag') {
1143 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1144 $type, $treeish);
1145 my $in_msg = 0;
1146 my $author;
1147 my $saw_from = 0;
1148 my $msgbuf = "";
1149 while (<$msg_fh>) {
1150 if (!$in_msg) {
1151 $in_msg = 1 if (/^\s*$/);
1152 $author = $1 if (/^author (.*>)/);
1153 } elsif (/^git-svn-id: /) {
1154 # skip this for now, we regenerate the
1155 # correct one on re-fetch anyways
1156 # TODO: set *:merge properties or like...
1157 } else {
1158 if (/^From:/ || /^Signed-off-by:/) {
1159 $saw_from = 1;
1161 $msgbuf .= $_;
1164 $msgbuf =~ s/\s+$//s;
1165 if ($Git::SVN::_add_author_from && defined($author)
1166 && !$saw_from) {
1167 $msgbuf .= "\n\nFrom: $author";
1169 print $log_fh $msgbuf or croak $!;
1170 command_close_pipe($msg_fh, $ctx);
1172 close $log_fh or croak $!;
1174 if ($_edit || ($type eq 'tree')) {
1175 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1176 # TODO: strip out spaces, comments, like git-commit.sh
1177 system($editor, $commit_editmsg);
1179 rename $commit_editmsg, $commit_msg or croak $!;
1181 require Encode;
1182 # SVN requires messages to be UTF-8 when entering the repo
1183 local $/;
1184 open $log_fh, '<', $commit_msg or croak $!;
1185 binmode $log_fh;
1186 chomp($log_entry{log} = <$log_fh>);
1188 my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
1189 my $msg = $log_entry{log};
1191 eval { $msg = Encode::decode($enc, $msg, 1) };
1192 if ($@) {
1193 die "Could not decode as $enc:\n", $msg,
1194 "\nPerhaps you need to set i18n.commitencoding\n";
1197 eval { $msg = Encode::encode('UTF-8', $msg, 1) };
1198 die "Could not encode as UTF-8:\n$msg\n" if $@;
1200 $log_entry{log} = $msg;
1202 close $log_fh or croak $!;
1204 unlink $commit_msg;
1205 \%log_entry;
1208 sub s_to_file {
1209 my ($str, $file, $mode) = @_;
1210 open my $fd,'>',$file or croak $!;
1211 print $fd $str,"\n" or croak $!;
1212 close $fd or croak $!;
1213 chmod ($mode &~ umask, $file) if (defined $mode);
1216 sub file_to_s {
1217 my $file = shift;
1218 open my $fd,'<',$file or croak "$!: file: $file\n";
1219 local $/;
1220 my $ret = <$fd>;
1221 close $fd or croak $!;
1222 $ret =~ s/\s*$//s;
1223 return $ret;
1226 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1227 sub load_authors {
1228 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1229 my $log = $cmd eq 'log';
1230 while (<$authors>) {
1231 chomp;
1232 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1233 my ($user, $name, $email) = ($1, $2, $3);
1234 if ($log) {
1235 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1236 } else {
1237 $users{$user} = [$name, $email];
1240 close $authors or croak $!;
1243 # convert GetOpt::Long specs for use by git-config
1244 sub read_repo_config {
1245 return unless -d $ENV{GIT_DIR};
1246 my $opts = shift;
1247 my @config_only;
1248 foreach my $o (keys %$opts) {
1249 # if we have mixedCase and a long option-only, then
1250 # it's a config-only variable that we don't need for
1251 # the command-line.
1252 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1253 my $v = $opts->{$o};
1254 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1255 $key =~ s/-//g;
1256 my $arg = 'git config';
1257 $arg .= ' --int' if ($o =~ /[:=]i$/);
1258 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1259 if (ref $v eq 'ARRAY') {
1260 chomp(my @tmp = `$arg --get-all svn.$key`);
1261 @$v = @tmp if @tmp;
1262 } else {
1263 chomp(my $tmp = `$arg --get svn.$key`);
1264 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1265 $$v = $tmp;
1269 delete @$opts{@config_only} if @config_only;
1272 sub extract_metadata {
1273 my $id = shift or return (undef, undef, undef);
1274 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1275 \s([a-f\d\-]+)$/x);
1276 if (!defined $rev || !$uuid || !$url) {
1277 # some of the original repositories I made had
1278 # identifiers like this:
1279 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
1281 return ($url, $rev, $uuid);
1284 sub cmt_metadata {
1285 return extract_metadata((grep(/^git-svn-id: /,
1286 command(qw/cat-file commit/, shift)))[-1]);
1289 sub cmt_sha2rev_batch {
1290 my %s2r;
1291 my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1292 my $list = shift;
1294 foreach my $sha (@{$list}) {
1295 my $first = 1;
1296 my $size = 0;
1297 print $out $sha, "\n";
1299 while (my $line = <$in>) {
1300 if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1301 last;
1302 } elsif ($first &&
1303 $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1304 $first = 0;
1305 $size = $1;
1306 next;
1307 } elsif ($line =~ /^(git-svn-id: )/) {
1308 my (undef, $rev, undef) =
1309 extract_metadata($line);
1310 $s2r{$sha} = $rev;
1313 $size -= length($line);
1314 last if ($size == 0);
1318 command_close_bidi_pipe($pid, $in, $out, $ctx);
1320 return \%s2r;
1323 sub working_head_info {
1324 my ($head, $refs) = @_;
1325 my @args = ('log', '--no-color', '--first-parent', '--pretty=medium');
1326 my ($fh, $ctx) = command_output_pipe(@args, $head);
1327 my $hash;
1328 my %max;
1329 while (<$fh>) {
1330 if ( m{^commit ($::sha1)$} ) {
1331 unshift @$refs, $hash if $hash and $refs;
1332 $hash = $1;
1333 next;
1335 next unless s{^\s*(git-svn-id:)}{$1};
1336 my ($url, $rev, $uuid) = extract_metadata($_);
1337 if (defined $url && defined $rev) {
1338 next if $max{$url} and $max{$url} < $rev;
1339 if (my $gs = Git::SVN->find_by_url($url)) {
1340 my $c = $gs->rev_map_get($rev, $uuid);
1341 if ($c && $c eq $hash) {
1342 close $fh; # break the pipe
1343 return ($url, $rev, $uuid, $gs);
1344 } else {
1345 $max{$url} ||= $gs->rev_map_max;
1350 command_close_pipe($fh, $ctx);
1351 (undef, undef, undef, undef);
1354 sub read_commit_parents {
1355 my ($parents, $c) = @_;
1356 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1357 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1358 @{$parents->{$c}} = split(/ /, $p);
1361 sub linearize_history {
1362 my ($gs, $refs) = @_;
1363 my %parents;
1364 foreach my $c (@$refs) {
1365 read_commit_parents(\%parents, $c);
1368 my @linear_refs;
1369 my %skip = ();
1370 my $last_svn_commit = $gs->last_commit;
1371 foreach my $c (reverse @$refs) {
1372 next if $c eq $last_svn_commit;
1373 last if $skip{$c};
1375 unshift @linear_refs, $c;
1376 $skip{$c} = 1;
1378 # we only want the first parent to diff against for linear
1379 # history, we save the rest to inject when we finalize the
1380 # svn commit
1381 my $fp_a = verify_ref("$c~1");
1382 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1383 if (!$fp_a || !$fp_b) {
1384 die "Commit $c\n",
1385 "has no parent commit, and therefore ",
1386 "nothing to diff against.\n",
1387 "You should be working from a repository ",
1388 "originally created by git-svn\n";
1390 if ($fp_a ne $fp_b) {
1391 die "$c~1 = $fp_a, however parsing commit $c ",
1392 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1395 foreach my $p (@{$parents{$c}}) {
1396 $skip{$p} = 1;
1399 (\@linear_refs, \%parents);
1402 sub find_file_type_and_diff_status {
1403 my ($path) = @_;
1404 return ('dir', '') if $path eq '';
1406 my $diff_output =
1407 command_oneline(qw(diff --cached --name-status --), $path) || "";
1408 my $diff_status = (split(' ', $diff_output))[0] || "";
1410 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1412 return (undef, undef) if !$diff_status && !$ls_tree;
1414 if ($diff_status eq "A") {
1415 return ("link", $diff_status) if -l $path;
1416 return ("dir", $diff_status) if -d $path;
1417 return ("file", $diff_status);
1420 my $mode = (split(' ', $ls_tree))[0] || "";
1422 return ("link", $diff_status) if $mode eq "120000";
1423 return ("dir", $diff_status) if $mode eq "040000";
1424 return ("file", $diff_status);
1427 sub md5sum {
1428 my $arg = shift;
1429 my $ref = ref $arg;
1430 my $md5 = Digest::MD5->new();
1431 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
1432 $md5->addfile($arg) or croak $!;
1433 } elsif ($ref eq 'SCALAR') {
1434 $md5->add($$arg) or croak $!;
1435 } elsif (!$ref) {
1436 $md5->add($arg) or croak $!;
1437 } else {
1438 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1440 return $md5->hexdigest();
1443 package Git::SVN;
1444 use strict;
1445 use warnings;
1446 use Fcntl qw/:DEFAULT :seek/;
1447 use constant rev_map_fmt => 'NH40';
1448 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1449 $_repack $_repack_flags $_use_svm_props $_head
1450 $_use_svnsync_props $no_reuse_existing $_minimize_url
1451 $_use_log_author $_add_author_from $_localtime/;
1452 use Carp qw/croak/;
1453 use File::Path qw/mkpath/;
1454 use File::Copy qw/copy/;
1455 use IPC::Open3;
1457 my ($_gc_nr, $_gc_period);
1459 # properties that we do not log:
1460 my %SKIP_PROP;
1461 BEGIN {
1462 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1463 svn:special svn:executable
1464 svn:entry:committed-rev
1465 svn:entry:last-author
1466 svn:entry:uuid
1467 svn:entry:committed-date/;
1469 # some options are read globally, but can be overridden locally
1470 # per [svn-remote "..."] section. Command-line options will *NOT*
1471 # override options set in an [svn-remote "..."] section
1472 no strict 'refs';
1473 for my $option (qw/follow_parent no_metadata use_svm_props
1474 use_svnsync_props/) {
1475 my $key = $option;
1476 $key =~ tr/_//d;
1477 my $prop = "-$option";
1478 *$option = sub {
1479 my ($self) = @_;
1480 return $self->{$prop} if exists $self->{$prop};
1481 my $k = "svn-remote.$self->{repo_id}.$key";
1482 eval { command_oneline(qw/config --get/, $k) };
1483 if ($@) {
1484 $self->{$prop} = ${"Git::SVN::_$option"};
1485 } else {
1486 my $v = command_oneline(qw/config --bool/,$k);
1487 $self->{$prop} = $v eq 'false' ? 0 : 1;
1489 return $self->{$prop};
1495 my (%LOCKFILES, %INDEX_FILES);
1496 END {
1497 unlink keys %LOCKFILES if %LOCKFILES;
1498 unlink keys %INDEX_FILES if %INDEX_FILES;
1501 sub resolve_local_globs {
1502 my ($url, $fetch, $glob_spec) = @_;
1503 return unless defined $glob_spec;
1504 my $ref = $glob_spec->{ref};
1505 my $path = $glob_spec->{path};
1506 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
1507 next unless m#^refs/remotes/$ref->{regex}$#;
1508 my $p = $1;
1509 my $pathname = desanitize_refname($path->full_path($p));
1510 my $refname = desanitize_refname($ref->full_path($p));
1511 if (my $existing = $fetch->{$pathname}) {
1512 if ($existing ne $refname) {
1513 die "Refspec conflict:\n",
1514 "existing: refs/remotes/$existing\n",
1515 " globbed: refs/remotes/$refname\n";
1517 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
1518 $u =~ s!^\Q$url\E(/|$)!! or die
1519 "refs/remotes/$refname: '$url' not found in '$u'\n";
1520 if ($pathname ne $u) {
1521 warn "W: Refspec glob conflict ",
1522 "(ref: refs/remotes/$refname):\n",
1523 "expected path: $pathname\n",
1524 " real path: $u\n",
1525 "Continuing ahead with $u\n";
1526 next;
1528 } else {
1529 $fetch->{$pathname} = $refname;
1534 sub parse_revision_argument {
1535 my ($base, $head) = @_;
1536 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1537 return ($base, $head);
1539 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1540 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1541 return ($head, $head) if ($::_revision eq 'HEAD');
1542 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1543 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1544 die "revision argument: $::_revision not understood by git-svn\n";
1547 sub fetch_all {
1548 my ($repo_id, $remotes) = @_;
1549 if (ref $repo_id) {
1550 my $gs = $repo_id;
1551 $repo_id = undef;
1552 $repo_id = $gs->{repo_id};
1554 $remotes ||= read_all_remotes();
1555 my $remote = $remotes->{$repo_id} or
1556 die "[svn-remote \"$repo_id\"] unknown\n";
1557 my $fetch = $remote->{fetch};
1558 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1559 my (@gs, @globs);
1560 my $ra = Git::SVN::Ra->new($url);
1561 my $uuid = $ra->get_uuid;
1562 my $head = $ra->get_latest_revnum;
1563 my $base = defined $fetch ? $head : 0;
1565 # read the max revs for wildcard expansion (branches/*, tags/*)
1566 foreach my $t (qw/branches tags/) {
1567 defined $remote->{$t} or next;
1568 push @globs, $remote->{$t};
1569 my $max_rev = eval { tmp_config(qw/--int --get/,
1570 "svn-remote.$repo_id.${t}-maxRev") };
1571 if (defined $max_rev && ($max_rev < $base)) {
1572 $base = $max_rev;
1573 } elsif (!defined $max_rev) {
1574 $base = 0;
1578 if ($fetch) {
1579 foreach my $p (sort keys %$fetch) {
1580 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1581 my $lr = $gs->rev_map_max;
1582 if (defined $lr) {
1583 $base = $lr if ($lr < $base);
1585 push @gs, $gs;
1589 ($base, $head) = parse_revision_argument($base, $head);
1590 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1593 sub read_all_remotes {
1594 my $r = {};
1595 my $use_svm_props = eval { command_oneline(qw/config --bool
1596 svn.useSvmProps/) };
1597 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
1598 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1599 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*(.+)\s*$!) {
1600 my ($remote, $local_ref, $_remote_ref) = ($1, $2, $3);
1601 die("svn-remote.$remote: remote ref '$_remote_ref' "
1602 . "must start with 'refs/remotes/'\n")
1603 unless $_remote_ref =~ m{^refs/remotes/(.+)};
1604 my $remote_ref = $1;
1605 $local_ref =~ s{^/}{};
1606 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1607 $r->{$remote}->{svm} = {} if $use_svm_props;
1608 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
1609 $r->{$1}->{svm} = {};
1610 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1611 $r->{$1}->{url} = $2;
1612 } elsif (m!^(.+)\.(branches|tags)=
1613 (.*):refs/remotes/(.+)\s*$/!x) {
1614 my ($p, $g) = ($3, $4);
1615 my $rs = $r->{$1}->{$2} = {
1616 t => $2,
1617 remote => $1,
1618 path => Git::SVN::GlobSpec->new($p),
1619 ref => Git::SVN::GlobSpec->new($g) };
1620 if (length($rs->{ref}->{right}) != 0) {
1621 die "The '*' glob character must be the last ",
1622 "character of '$g'\n";
1627 map {
1628 if (defined $r->{$_}->{svm}) {
1629 my $svm;
1630 eval {
1631 my $section = "svn-remote.$_";
1632 $svm = {
1633 source => tmp_config('--get',
1634 "$section.svm-source"),
1635 replace => tmp_config('--get',
1636 "$section.svm-replace"),
1639 $r->{$_}->{svm} = $svm;
1641 } keys %$r;
1646 sub init_vars {
1647 $_gc_nr = $_gc_period = 1000;
1648 if (defined $_repack || defined $_repack_flags) {
1649 warn "Repack options are obsolete; they have no effect.\n";
1653 sub verify_remotes_sanity {
1654 return unless -d $ENV{GIT_DIR};
1655 my %seen;
1656 foreach (command(qw/config -l/)) {
1657 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1658 if ($seen{$1}) {
1659 die "Remote ref refs/remote/$1 is tracked by",
1660 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1661 "Please resolve this ambiguity in ",
1662 "your git configuration file before ",
1663 "continuing\n";
1665 $seen{$1} = $_;
1670 sub find_existing_remote {
1671 my ($url, $remotes) = @_;
1672 return undef if $no_reuse_existing;
1673 my $existing;
1674 foreach my $repo_id (keys %$remotes) {
1675 my $u = $remotes->{$repo_id}->{url} or next;
1676 next if $u ne $url;
1677 $existing = $repo_id;
1678 last;
1680 $existing;
1683 sub init_remote_config {
1684 my ($self, $url, $no_write) = @_;
1685 $url =~ s!/+$!!; # strip trailing slash
1686 my $r = read_all_remotes();
1687 my $existing = find_existing_remote($url, $r);
1688 if ($existing) {
1689 unless ($no_write) {
1690 print STDERR "Using existing ",
1691 "[svn-remote \"$existing\"]\n";
1693 $self->{repo_id} = $existing;
1694 } elsif ($_minimize_url) {
1695 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1696 $existing = find_existing_remote($min_url, $r);
1697 if ($existing) {
1698 unless ($no_write) {
1699 print STDERR "Using existing ",
1700 "[svn-remote \"$existing\"]\n";
1702 $self->{repo_id} = $existing;
1704 if ($min_url ne $url) {
1705 unless ($no_write) {
1706 print STDERR "Using higher level of URL: ",
1707 "$url => $min_url\n";
1709 my $old_path = $self->{path};
1710 $self->{path} = $url;
1711 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1712 if (length $old_path) {
1713 $self->{path} .= "/$old_path";
1715 $url = $min_url;
1718 my $orig_url;
1719 if (!$existing) {
1720 # verify that we aren't overwriting anything:
1721 $orig_url = eval {
1722 command_oneline('config', '--get',
1723 "svn-remote.$self->{repo_id}.url")
1725 if ($orig_url && ($orig_url ne $url)) {
1726 die "svn-remote.$self->{repo_id}.url already set: ",
1727 "$orig_url\nwanted to set to: $url\n";
1730 my ($xrepo_id, $xpath) = find_ref($self->refname);
1731 if (defined $xpath) {
1732 die "svn-remote.$xrepo_id.fetch already set to track ",
1733 "$xpath:refs/remotes/", $self->refname, "\n";
1735 unless ($no_write) {
1736 command_noisy('config',
1737 "svn-remote.$self->{repo_id}.url", $url);
1738 $self->{path} =~ s{^/}{};
1739 command_noisy('config', '--add',
1740 "svn-remote.$self->{repo_id}.fetch",
1741 "$self->{path}:".$self->refname);
1743 $self->{url} = $url;
1746 sub find_by_url { # repos_root and, path are optional
1747 my ($class, $full_url, $repos_root, $path) = @_;
1749 return undef unless defined $full_url;
1750 remove_username($full_url);
1751 remove_username($repos_root) if defined $repos_root;
1752 my $remotes = read_all_remotes();
1753 if (defined $full_url && defined $repos_root && !defined $path) {
1754 $path = $full_url;
1755 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1757 foreach my $repo_id (keys %$remotes) {
1758 my $u = $remotes->{$repo_id}->{url} or next;
1759 remove_username($u);
1760 next if defined $repos_root && $repos_root ne $u;
1762 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1763 foreach (qw/branches tags/) {
1764 resolve_local_globs($u, $fetch,
1765 $remotes->{$repo_id}->{$_});
1767 my $p = $path;
1768 my $rwr = rewrite_root({repo_id => $repo_id});
1769 my $svm = $remotes->{$repo_id}->{svm}
1770 if defined $remotes->{$repo_id}->{svm};
1771 unless (defined $p) {
1772 $p = $full_url;
1773 my $z = $u;
1774 my $prefix = '';
1775 if ($rwr) {
1776 $z = $rwr;
1777 remove_username($z);
1778 } elsif (defined $svm) {
1779 $z = $svm->{source};
1780 $prefix = $svm->{replace};
1781 $prefix =~ s#^\Q$u\E(?:/|$)##;
1782 $prefix =~ s#/$##;
1784 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
1786 foreach my $f (keys %$fetch) {
1787 next if $f ne $p;
1788 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1791 undef;
1794 sub init {
1795 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1796 my $self = _new($class, $repo_id, $ref_id, $path);
1797 if (defined $url) {
1798 $self->init_remote_config($url, $no_write);
1800 $self;
1803 sub find_ref {
1804 my ($ref_id) = @_;
1805 foreach (command(qw/config -l/)) {
1806 next unless m!^svn-remote\.(.+)\.fetch=
1807 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1808 my ($repo_id, $path, $ref) = ($1, $2, $3);
1809 if ($ref eq $ref_id) {
1810 $path = '' if ($path =~ m#^\./?#);
1811 return ($repo_id, $path);
1814 (undef, undef, undef);
1817 sub new {
1818 my ($class, $ref_id, $repo_id, $path) = @_;
1819 if (defined $ref_id && !defined $repo_id && !defined $path) {
1820 ($repo_id, $path) = find_ref($ref_id);
1821 if (!defined $repo_id) {
1822 die "Could not find a \"svn-remote.*.fetch\" key ",
1823 "in the repository configuration matching: ",
1824 "refs/remotes/$ref_id\n";
1827 my $self = _new($class, $repo_id, $ref_id, $path);
1828 if (!defined $self->{path} || !length $self->{path}) {
1829 my $fetch = command_oneline('config', '--get',
1830 "svn-remote.$repo_id.fetch",
1831 ":refs/remotes/$ref_id\$") or
1832 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1833 "\":refs/remotes/$ref_id\$\" in config\n";
1834 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1836 $self->{url} = command_oneline('config', '--get',
1837 "svn-remote.$repo_id.url") or
1838 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1839 $self->rebuild;
1840 $self;
1843 sub refname {
1844 my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1846 # It cannot end with a slash /, we'll throw up on this because
1847 # SVN can't have directories with a slash in their name, either:
1848 if ($refname =~ m{/$}) {
1849 die "ref: '$refname' ends with a trailing slash, this is ",
1850 "not permitted by git nor Subversion\n";
1853 # It cannot have ASCII control character space, tilde ~, caret ^,
1854 # colon :, question-mark ?, asterisk *, space, or open bracket [
1855 # anywhere.
1857 # Additionally, % must be escaped because it is used for escaping
1858 # and we want our escaped refname to be reversible
1859 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1861 # no slash-separated component can begin with a dot .
1862 # /.* becomes /%2E*
1863 $refname =~ s{/\.}{/%2E}g;
1865 # It cannot have two consecutive dots .. anywhere
1866 # .. becomes %2E%2E
1867 $refname =~ s{\.\.}{%2E%2E}g;
1869 return $refname;
1872 sub desanitize_refname {
1873 my ($refname) = @_;
1874 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1875 return $refname;
1878 sub svm_uuid {
1879 my ($self) = @_;
1880 return $self->{svm}->{uuid} if $self->svm;
1881 $self->ra;
1882 unless ($self->{svm}) {
1883 die "SVM UUID not cached, and reading remotely failed\n";
1885 $self->{svm}->{uuid};
1888 sub svm {
1889 my ($self) = @_;
1890 return $self->{svm} if $self->{svm};
1891 my $svm;
1892 # see if we have it in our config, first:
1893 eval {
1894 my $section = "svn-remote.$self->{repo_id}";
1895 $svm = {
1896 source => tmp_config('--get', "$section.svm-source"),
1897 uuid => tmp_config('--get', "$section.svm-uuid"),
1898 replace => tmp_config('--get', "$section.svm-replace"),
1901 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1902 $self->{svm} = $svm;
1904 $self->{svm};
1907 sub _set_svm_vars {
1908 my ($self, $ra) = @_;
1909 return $ra if $self->svm;
1911 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1912 "(svm:source, svm:uuid) ",
1913 "from the following URLs:\n" );
1914 sub read_svm_props {
1915 my ($self, $ra, $path, $r) = @_;
1916 my $props = ($ra->get_dir($path, $r))[2];
1917 my $src = $props->{'svm:source'};
1918 my $uuid = $props->{'svm:uuid'};
1919 return undef if (!$src || !$uuid);
1921 chomp($src, $uuid);
1923 $uuid =~ m{^[0-9a-f\-]{30,}$}
1924 or die "doesn't look right - svm:uuid is '$uuid'\n";
1926 # the '!' is used to mark the repos_root!/relative/path
1927 $src =~ s{/?!/?}{/};
1928 $src =~ s{/+$}{}; # no trailing slashes please
1929 # username is of no interest
1930 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1932 my $replace = $ra->{url};
1933 $replace .= "/$path" if length $path;
1935 my $section = "svn-remote.$self->{repo_id}";
1936 tmp_config("$section.svm-source", $src);
1937 tmp_config("$section.svm-replace", $replace);
1938 tmp_config("$section.svm-uuid", $uuid);
1939 $self->{svm} = {
1940 source => $src,
1941 uuid => $uuid,
1942 replace => $replace
1946 my $r = $ra->get_latest_revnum;
1947 my $path = $self->{path};
1948 my %tried;
1949 while (length $path) {
1950 unless ($tried{"$self->{url}/$path"}) {
1951 return $ra if $self->read_svm_props($ra, $path, $r);
1952 $tried{"$self->{url}/$path"} = 1;
1954 $path =~ s#/?[^/]+$##;
1956 die "Path: '$path' should be ''\n" if $path ne '';
1957 return $ra if $self->read_svm_props($ra, $path, $r);
1958 $tried{"$self->{url}/$path"} = 1;
1960 if ($ra->{repos_root} eq $self->{url}) {
1961 die @err, (map { " $_\n" } keys %tried), "\n";
1964 # nope, make sure we're connected to the repository root:
1965 my $ok;
1966 my @tried_b;
1967 $path = $ra->{svn_path};
1968 $ra = Git::SVN::Ra->new($ra->{repos_root});
1969 while (length $path) {
1970 unless ($tried{"$ra->{url}/$path"}) {
1971 $ok = $self->read_svm_props($ra, $path, $r);
1972 last if $ok;
1973 $tried{"$ra->{url}/$path"} = 1;
1975 $path =~ s#/?[^/]+$##;
1977 die "Path: '$path' should be ''\n" if $path ne '';
1978 $ok ||= $self->read_svm_props($ra, $path, $r);
1979 $tried{"$ra->{url}/$path"} = 1;
1980 if (!$ok) {
1981 die @err, (map { " $_\n" } keys %tried), "\n";
1983 Git::SVN::Ra->new($self->{url});
1986 sub svnsync {
1987 my ($self) = @_;
1988 return $self->{svnsync} if $self->{svnsync};
1990 if ($self->no_metadata) {
1991 die "Can't have both 'noMetadata' and ",
1992 "'useSvnsyncProps' options set!\n";
1994 if ($self->rewrite_root) {
1995 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1996 "options set!\n";
1999 my $svnsync;
2000 # see if we have it in our config, first:
2001 eval {
2002 my $section = "svn-remote.$self->{repo_id}";
2004 my $url = tmp_config('--get', "$section.svnsync-url");
2005 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2006 die "doesn't look right - svn:sync-from-url is '$url'\n";
2008 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
2009 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
2010 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2012 $svnsync = { url => $url, uuid => $uuid }
2014 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
2015 return $self->{svnsync} = $svnsync;
2018 my $err = "useSvnsyncProps set, but failed to read " .
2019 "svnsync property: svn:sync-from-";
2020 my $rp = $self->ra->rev_proplist(0);
2022 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
2023 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2024 die "doesn't look right - svn:sync-from-url is '$url'\n";
2026 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
2027 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
2028 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2030 my $section = "svn-remote.$self->{repo_id}";
2031 tmp_config('--add', "$section.svnsync-uuid", $uuid);
2032 tmp_config('--add', "$section.svnsync-url", $url);
2033 return $self->{svnsync} = { url => $url, uuid => $uuid };
2036 # this allows us to memoize our SVN::Ra UUID locally and avoid a
2037 # remote lookup (useful for 'git svn log').
2038 sub ra_uuid {
2039 my ($self) = @_;
2040 unless ($self->{ra_uuid}) {
2041 my $key = "svn-remote.$self->{repo_id}.uuid";
2042 my $uuid = eval { tmp_config('--get', $key) };
2043 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
2044 $self->{ra_uuid} = $uuid;
2045 } else {
2046 die "ra_uuid called without URL\n" unless $self->{url};
2047 $self->{ra_uuid} = $self->ra->get_uuid;
2048 tmp_config('--add', $key, $self->{ra_uuid});
2051 $self->{ra_uuid};
2054 sub _set_repos_root {
2055 my ($self, $repos_root) = @_;
2056 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2057 $repos_root ||= $self->ra->{repos_root};
2058 tmp_config($k, $repos_root);
2059 $repos_root;
2062 sub repos_root {
2063 my ($self) = @_;
2064 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2065 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
2068 sub ra {
2069 my ($self) = shift;
2070 my $ra = Git::SVN::Ra->new($self->{url});
2071 $self->_set_repos_root($ra->{repos_root});
2072 if ($self->use_svm_props && !$self->{svm}) {
2073 if ($self->no_metadata) {
2074 die "Can't have both 'noMetadata' and ",
2075 "'useSvmProps' options set!\n";
2076 } elsif ($self->use_svnsync_props) {
2077 die "Can't have both 'useSvnsyncProps' and ",
2078 "'useSvmProps' options set!\n";
2080 $ra = $self->_set_svm_vars($ra);
2081 $self->{-want_revprops} = 1;
2083 $ra;
2086 sub rel_path {
2087 my ($self) = @_;
2088 my $repos_root = $self->ra->{repos_root};
2089 return $self->{path} if ($self->{url} eq $repos_root);
2090 my $url = $self->{url} .
2091 (length $self->{path} ? "/$self->{path}" : $self->{path});
2092 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
2093 $url;
2096 # prop_walk(PATH, REV, SUB)
2097 # -------------------------
2098 # Recursively traverse PATH at revision REV and invoke SUB for each
2099 # directory that contains a SVN property. SUB will be invoked as
2100 # follows: &SUB(gs, path, props); where `gs' is this instance of
2101 # Git::SVN, `path' the path to the directory where the properties
2102 # `props' were found. The `path' will be relative to point of checkout,
2103 # that is, if url://repo/trunk is the current Git branch, and that
2104 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
2105 # as `path' (note the trailing `/').
2106 sub prop_walk {
2107 my ($self, $path, $rev, $sub) = @_;
2109 $path =~ s#^/##;
2110 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2111 $path =~ s#^/*#/#g;
2112 my $p = $path;
2113 # Strip the irrelevant part of the path.
2114 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2115 # Ensure the path is terminated by a `/'.
2116 $p =~ s#/*$#/#;
2118 # The properties contain all the internal SVN stuff nobody
2119 # (usually) cares about.
2120 my $interesting_props = 0;
2121 foreach (keys %{$props}) {
2122 # If it doesn't start with `svn:', it must be a
2123 # user-defined property.
2124 ++$interesting_props and next if $_ !~ /^svn:/;
2125 # FIXME: Fragile, if SVN adds new public properties,
2126 # this needs to be updated.
2127 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2128 |eol-style|mime-type
2129 |externals|needs-lock)$/x;
2131 &$sub($self, $p, $props) if $interesting_props;
2133 foreach (sort keys %$dirent) {
2134 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
2135 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
2139 sub last_rev { ($_[0]->last_rev_commit)[0] }
2140 sub last_commit { ($_[0]->last_rev_commit)[1] }
2142 # returns the newest SVN revision number and newest commit SHA1
2143 sub last_rev_commit {
2144 my ($self) = @_;
2145 if (defined $self->{last_rev} && defined $self->{last_commit}) {
2146 return ($self->{last_rev}, $self->{last_commit});
2148 my $c = ::verify_ref($self->refname.'^0');
2149 if ($c && !$self->use_svm_props && !$self->no_metadata) {
2150 my $rev = (::cmt_metadata($c))[1];
2151 if (defined $rev) {
2152 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2153 return ($rev, $c);
2156 my $map_path = $self->map_path;
2157 unless (-e $map_path) {
2158 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2159 return (undef, undef);
2161 my ($rev, $commit) = $self->rev_map_max(1);
2162 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2163 return ($rev, $commit);
2166 sub get_fetch_range {
2167 my ($self, $min, $max) = @_;
2168 $max ||= $self->ra->get_latest_revnum;
2169 $min ||= $self->rev_map_max;
2170 (++$min, $max);
2173 sub tmp_config {
2174 my (@args) = @_;
2175 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2176 my $config = "$ENV{GIT_DIR}/svn/.metadata";
2177 if (! -f $config && -f $old_def_config) {
2178 rename $old_def_config, $config or
2179 die "Failed rename $old_def_config => $config: $!\n";
2181 my $old_config = $ENV{GIT_CONFIG};
2182 $ENV{GIT_CONFIG} = $config;
2183 $@ = undef;
2184 my @ret = eval {
2185 unless (-f $config) {
2186 mkfile($config);
2187 open my $fh, '>', $config or
2188 die "Can't open $config: $!\n";
2189 print $fh "; This file is used internally by ",
2190 "git-svn\n" or die
2191 "Couldn't write to $config: $!\n";
2192 print $fh "; You should not have to edit it\n" or
2193 die "Couldn't write to $config: $!\n";
2194 close $fh or die "Couldn't close $config: $!\n";
2196 command('config', @args);
2198 my $err = $@;
2199 if (defined $old_config) {
2200 $ENV{GIT_CONFIG} = $old_config;
2201 } else {
2202 delete $ENV{GIT_CONFIG};
2204 die $err if $err;
2205 wantarray ? @ret : $ret[0];
2208 sub tmp_index_do {
2209 my ($self, $sub) = @_;
2210 my $old_index = $ENV{GIT_INDEX_FILE};
2211 $ENV{GIT_INDEX_FILE} = $self->{index};
2212 $@ = undef;
2213 my @ret = eval {
2214 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2215 mkpath([$dir]) unless -d $dir;
2216 &$sub;
2218 my $err = $@;
2219 if (defined $old_index) {
2220 $ENV{GIT_INDEX_FILE} = $old_index;
2221 } else {
2222 delete $ENV{GIT_INDEX_FILE};
2224 die $err if $err;
2225 wantarray ? @ret : $ret[0];
2228 sub assert_index_clean {
2229 my ($self, $treeish) = @_;
2231 $self->tmp_index_do(sub {
2232 command_noisy('read-tree', $treeish) unless -e $self->{index};
2233 my $x = command_oneline('write-tree');
2234 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2235 /^tree ($::sha1)/mo);
2236 return if $y eq $x;
2238 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2239 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2240 command_noisy('read-tree', $treeish);
2241 $x = command_oneline('write-tree');
2242 if ($y ne $x) {
2243 ::fatal "trees ($treeish) $y != $x\n",
2244 "Something is seriously wrong...";
2249 sub get_commit_parents {
2250 my ($self, $log_entry) = @_;
2251 my (%seen, @ret, @tmp);
2252 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2253 if (my $ip = $self->{inject_parents}) {
2254 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2255 push @tmp, $commit;
2258 if (my $cur = ::verify_ref($self->refname.'^0')) {
2259 push @tmp, $cur;
2261 if (my $ipd = $self->{inject_parents_dcommit}) {
2262 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2263 push @tmp, @$commit;
2266 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2267 while (my $p = shift @tmp) {
2268 next if $seen{$p};
2269 $seen{$p} = 1;
2270 push @ret, $p;
2271 # MAXPARENT is defined to 16 in commit-tree.c:
2272 last if @ret >= 16;
2274 if (@tmp) {
2275 die "r$log_entry->{revision}: No room for parents:\n\t",
2276 join("\n\t", @tmp), "\n";
2278 @ret;
2281 sub rewrite_root {
2282 my ($self) = @_;
2283 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2284 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2285 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2286 if ($rwr) {
2287 $rwr =~ s#/+$##;
2288 if ($rwr !~ m#^[a-z\+]+://#) {
2289 die "$rwr is not a valid URL (key: $k)\n";
2292 $self->{-rewrite_root} = $rwr;
2295 sub metadata_url {
2296 my ($self) = @_;
2297 ($self->rewrite_root || $self->{url}) .
2298 (length $self->{path} ? '/' . $self->{path} : '');
2301 sub full_url {
2302 my ($self) = @_;
2303 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2307 sub set_commit_header_env {
2308 my ($log_entry) = @_;
2309 my %env;
2310 foreach my $ned (qw/NAME EMAIL DATE/) {
2311 foreach my $ac (qw/AUTHOR COMMITTER/) {
2312 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2316 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2317 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2318 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2320 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2321 ? $log_entry->{commit_name}
2322 : $log_entry->{name};
2323 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2324 ? $log_entry->{commit_email}
2325 : $log_entry->{email};
2326 \%env;
2329 sub restore_commit_header_env {
2330 my ($env) = @_;
2331 foreach my $ned (qw/NAME EMAIL DATE/) {
2332 foreach my $ac (qw/AUTHOR COMMITTER/) {
2333 my $k = "GIT_${ac}_${ned}";
2334 if (defined $env->{$k}) {
2335 $ENV{$k} = $env->{$k};
2336 } else {
2337 delete $ENV{$k};
2343 sub gc {
2344 command_noisy('gc', '--auto');
2347 sub do_git_commit {
2348 my ($self, $log_entry) = @_;
2349 my $lr = $self->last_rev;
2350 if (defined $lr && $lr >= $log_entry->{revision}) {
2351 die "Last fetched revision of ", $self->refname,
2352 " was r$lr, but we are about to fetch: ",
2353 "r$log_entry->{revision}!\n";
2355 if (my $c = $self->rev_map_get($log_entry->{revision})) {
2356 croak "$log_entry->{revision} = $c already exists! ",
2357 "Why are we refetching it?\n";
2359 my $old_env = set_commit_header_env($log_entry);
2360 my $tree = $log_entry->{tree};
2361 if (!defined $tree) {
2362 $tree = $self->tmp_index_do(sub {
2363 command_oneline('write-tree') });
2365 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2367 my @exec = ('git', 'commit-tree', $tree);
2368 foreach ($self->get_commit_parents($log_entry)) {
2369 push @exec, '-p', $_;
2371 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2372 or croak $!;
2373 binmode $msg_fh;
2375 # we always get UTF-8 from SVN, but we may want our commits in
2376 # a different encoding.
2377 if (my $enc = Git::config('i18n.commitencoding')) {
2378 require Encode;
2379 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
2381 print $msg_fh $log_entry->{log} or croak $!;
2382 restore_commit_header_env($old_env);
2383 unless ($self->no_metadata) {
2384 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2385 or croak $!;
2387 $msg_fh->flush == 0 or croak $!;
2388 close $msg_fh or croak $!;
2389 chomp(my $commit = do { local $/; <$out_fh> });
2390 close $out_fh or croak $!;
2391 waitpid $pid, 0;
2392 croak $? if $?;
2393 if ($commit !~ /^$::sha1$/o) {
2394 die "Failed to commit, invalid sha1: $commit\n";
2397 $self->rev_map_set($log_entry->{revision}, $commit, 1);
2399 $self->{last_rev} = $log_entry->{revision};
2400 $self->{last_commit} = $commit;
2401 print "r$log_entry->{revision}" unless $::_q > 1;
2402 if (defined $log_entry->{svm_revision}) {
2403 print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
2404 $self->rev_map_set($log_entry->{svm_revision}, $commit,
2405 0, $self->svm_uuid);
2407 print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
2408 if (--$_gc_nr == 0) {
2409 $_gc_nr = $_gc_period;
2410 gc();
2412 return $commit;
2415 sub match_paths {
2416 my ($self, $paths, $r) = @_;
2417 return 1 if $self->{path} eq '';
2418 if (my $path = $paths->{"/$self->{path}"}) {
2419 return ($path->{action} eq 'D') ? 0 : 1;
2421 my $repos_root = $self->ra->{repos_root};
2422 my $extended_path = $self->{url} . '/' . $self->{path};
2423 $extended_path =~ s#^\Q$repos_root\E(/|$)##;
2424 $self->{path_regex} ||= qr/^\/\Q$extended_path\E\//;
2425 if (grep /$self->{path_regex}/, keys %$paths) {
2426 return 1;
2428 my $c = '';
2429 foreach (split m#/#, $self->{path}) {
2430 $c .= "/$_";
2431 next unless ($paths->{$c} &&
2432 ($paths->{$c}->{action} =~ /^[AR]$/));
2433 if ($self->ra->check_path($self->{path}, $r) ==
2434 $SVN::Node::dir) {
2435 return 1;
2438 return 0;
2441 sub find_parent_branch {
2442 my ($self, $paths, $rev) = @_;
2443 return undef unless $self->follow_parent;
2444 unless (defined $paths) {
2445 my $err_handler = $SVN::Error::handler;
2446 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2447 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
2448 $paths =
2449 Git::SVN::Ra::dup_changed_paths($_[0]) });
2450 $SVN::Error::handler = $err_handler;
2452 return undef unless defined $paths;
2454 # look for a parent from another branch:
2455 my @b_path_components = split m#/#, $self->rel_path;
2456 my @a_path_components;
2457 my $i;
2458 while (@b_path_components) {
2459 $i = $paths->{'/'.join('/', @b_path_components)};
2460 last if $i && defined $i->{copyfrom_path};
2461 unshift(@a_path_components, pop(@b_path_components));
2463 return undef unless defined $i && defined $i->{copyfrom_path};
2464 my $branch_from = $i->{copyfrom_path};
2465 if (@a_path_components) {
2466 print STDERR "branch_from: $branch_from => ";
2467 $branch_from .= '/'.join('/', @a_path_components);
2468 print STDERR $branch_from, "\n";
2470 my $r = $i->{copyfrom_rev};
2471 my $repos_root = $self->ra->{repos_root};
2472 my $url = $self->ra->{url};
2473 my $new_url = $repos_root . $branch_from;
2474 print STDERR "Found possible branch point: ",
2475 "$new_url => ", $self->full_url, ", $r\n";
2476 $branch_from =~ s#^/##;
2477 my $gs = $self->other_gs($new_url, $url, $repos_root,
2478 $branch_from, $r, $self->{ref_id});
2479 my ($r0, $parent) = $gs->find_rev_before($r, 1);
2481 my ($base, $head);
2482 if (!defined $r0 || !defined $parent) {
2483 ($base, $head) = parse_revision_argument(0, $r);
2484 } else {
2485 if ($r0 < $r) {
2486 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
2487 0, 1, sub { $base = $_[1] - 1 });
2490 if (defined $base && $base <= $r) {
2491 $gs->fetch($base, $r);
2493 ($r0, $parent) = $gs->find_rev_before($r, 1);
2495 if (defined $r0 && defined $parent) {
2496 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
2497 my $ed;
2498 if ($self->ra->can_do_switch) {
2499 $self->assert_index_clean($parent);
2500 print STDERR "Following parent with do_switch\n";
2501 # do_switch works with svn/trunk >= r22312, but that
2502 # is not included with SVN 1.4.3 (the latest version
2503 # at the moment), so we can't rely on it
2504 $self->{last_rev} = $r0;
2505 $self->{last_commit} = $parent;
2506 $ed = SVN::Git::Fetcher->new($self, $gs->{path});
2507 $gs->ra->gs_do_switch($r0, $rev, $gs,
2508 $self->full_url, $ed)
2509 or die "SVN connection failed somewhere...\n";
2510 } elsif ($self->ra->trees_match($new_url, $r0,
2511 $self->full_url, $rev)) {
2512 print STDERR "Trees match:\n",
2513 " $new_url\@$r0\n",
2514 " ${\$self->full_url}\@$rev\n",
2515 "Following parent with no changes\n";
2516 $self->tmp_index_do(sub {
2517 command_noisy('read-tree', $parent);
2519 $self->{last_commit} = $parent;
2520 } else {
2521 print STDERR "Following parent with do_update\n";
2522 $ed = SVN::Git::Fetcher->new($self);
2523 $self->ra->gs_do_update($rev, $rev, $self, $ed)
2524 or die "SVN connection failed somewhere...\n";
2526 print STDERR "Successfully followed parent\n";
2527 return $self->make_log_entry($rev, [$parent], $ed);
2529 return undef;
2532 sub do_fetch {
2533 my ($self, $paths, $rev) = @_;
2534 my $ed;
2535 my ($last_rev, @parents);
2536 if (my $lc = $self->last_commit) {
2537 # we can have a branch that was deleted, then re-added
2538 # under the same name but copied from another path, in
2539 # which case we'll have multiple parents (we don't
2540 # want to break the original ref, nor lose copypath info):
2541 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2542 push @{$log_entry->{parents}}, $lc;
2543 return $log_entry;
2545 $ed = SVN::Git::Fetcher->new($self);
2546 $last_rev = $self->{last_rev};
2547 $ed->{c} = $lc;
2548 @parents = ($lc);
2549 } else {
2550 $last_rev = $rev;
2551 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2552 return $log_entry;
2554 $ed = SVN::Git::Fetcher->new($self);
2556 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2557 die "SVN connection failed somewhere...\n";
2559 $self->make_log_entry($rev, \@parents, $ed);
2562 sub get_untracked {
2563 my ($self, $ed) = @_;
2564 my @out;
2565 my $h = $ed->{empty};
2566 foreach (sort keys %$h) {
2567 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2568 push @out, " $act: " . uri_encode($_);
2569 warn "W: $act: $_\n";
2571 foreach my $t (qw/dir_prop file_prop/) {
2572 $h = $ed->{$t} or next;
2573 foreach my $path (sort keys %$h) {
2574 my $ppath = $path eq '' ? '.' : $path;
2575 foreach my $prop (sort keys %{$h->{$path}}) {
2576 next if $SKIP_PROP{$prop};
2577 my $v = $h->{$path}->{$prop};
2578 my $t_ppath_prop = "$t: " .
2579 uri_encode($ppath) . ' ' .
2580 uri_encode($prop);
2581 if (defined $v) {
2582 push @out, " +$t_ppath_prop " .
2583 uri_encode($v);
2584 } else {
2585 push @out, " -$t_ppath_prop";
2590 foreach my $t (qw/absent_file absent_directory/) {
2591 $h = $ed->{$t} or next;
2592 foreach my $parent (sort keys %$h) {
2593 foreach my $path (sort @{$h->{$parent}}) {
2594 push @out, " $t: " .
2595 uri_encode("$parent/$path");
2596 warn "W: $t: $parent/$path ",
2597 "Insufficient permissions?\n";
2601 \@out;
2604 # parse_svn_date(DATE)
2605 # --------------------
2606 # Given a date (in UTC) from Subversion, return a string in the format
2607 # "<TZ Offset> <local date/time>" that Git will use.
2609 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
2610 # is true we'll convert it to the local timezone instead.
2611 sub parse_svn_date {
2612 my $date = shift || return '+0000 1970-01-01 00:00:00';
2613 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2614 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
2615 croak "Unable to parse date: $date\n";
2616 my $parsed_date; # Set next.
2618 if ($Git::SVN::_localtime) {
2619 # Translate the Subversion datetime to an epoch time.
2620 # Begin by switching ourselves to $date's timezone, UTC.
2621 my $old_env_TZ = $ENV{TZ};
2622 $ENV{TZ} = 'UTC';
2624 my $epoch_in_UTC =
2625 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
2627 # Determine our local timezone (including DST) at the
2628 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
2629 # value of TZ, if any, at the time we were run.
2630 if (defined $Git::SVN::Log::TZ) {
2631 $ENV{TZ} = $Git::SVN::Log::TZ;
2632 } else {
2633 delete $ENV{TZ};
2636 my $our_TZ =
2637 POSIX::strftime('%Z', $S, $M, $H, $d, $m - 1, $Y - 1900);
2639 # This converts $epoch_in_UTC into our local timezone.
2640 my ($sec, $min, $hour, $mday, $mon, $year,
2641 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
2643 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
2644 $our_TZ, $year + 1900, $mon + 1,
2645 $mday, $hour, $min, $sec);
2647 # Reset us to the timezone in effect when we entered
2648 # this routine.
2649 if (defined $old_env_TZ) {
2650 $ENV{TZ} = $old_env_TZ;
2651 } else {
2652 delete $ENV{TZ};
2654 } else {
2655 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
2658 return $parsed_date;
2661 sub other_gs {
2662 my ($self, $new_url, $url, $repos_root,
2663 $branch_from, $r, $old_ref_id) = @_;
2664 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
2665 unless ($gs) {
2666 my $ref_id = $old_ref_id;
2667 $ref_id =~ s/\@\d+$//;
2668 $ref_id .= "\@$r";
2669 # just grow a tail if we're not unique enough :x
2670 $ref_id .= '-' while find_ref($ref_id);
2671 print STDERR "Initializing parent: $ref_id\n";
2672 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
2673 if ($u =~ s#^\Q$url\E(/|$)##) {
2674 $p = $u;
2675 $u = $url;
2676 $repo_id = $self->{repo_id};
2678 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
2683 sub call_authors_prog {
2684 my ($orig_author) = @_;
2685 my $author = `$::_authors_prog $orig_author`;
2686 if ($? != 0) {
2687 die "$::_authors_prog failed with exit code $?\n"
2689 if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
2690 my ($name, $email) = ($1, $2);
2691 $email = undef if length $2 == 0;
2692 return [$name, $email];
2693 } else {
2694 die "Author: $orig_author: $::_authors_prog returned "
2695 . "invalid author format: $author\n";
2699 sub check_author {
2700 my ($author) = @_;
2701 if (!defined $author || length $author == 0) {
2702 $author = '(no author)';
2704 if (!defined $::users{$author}) {
2705 if (defined $::_authors_prog) {
2706 $::users{$author} = call_authors_prog($author);
2707 } elsif (defined $::_authors) {
2708 die "Author: $author not defined in $::_authors file\n";
2711 $author;
2714 sub make_log_entry {
2715 my ($self, $rev, $parents, $ed) = @_;
2716 my $untracked = $self->get_untracked($ed);
2718 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
2719 print $un "r$rev\n" or croak $!;
2720 print $un $_, "\n" foreach @$untracked;
2721 my %log_entry = ( parents => $parents || [], revision => $rev,
2722 log => '');
2724 my $headrev;
2725 my $logged = delete $self->{logged_rev_props};
2726 if (!$logged || $self->{-want_revprops}) {
2727 my $rp = $self->ra->rev_proplist($rev);
2728 foreach (sort keys %$rp) {
2729 my $v = $rp->{$_};
2730 if (/^svn:(author|date|log)$/) {
2731 $log_entry{$1} = $v;
2732 } elsif ($_ eq 'svm:headrev') {
2733 $headrev = $v;
2734 } else {
2735 print $un " rev_prop: ", uri_encode($_), ' ',
2736 uri_encode($v), "\n";
2739 } else {
2740 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
2742 close $un or croak $!;
2744 $log_entry{date} = parse_svn_date($log_entry{date});
2745 $log_entry{log} .= "\n";
2746 my $author = $log_entry{author} = check_author($log_entry{author});
2747 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
2748 : ($author, undef);
2750 my ($commit_name, $commit_email) = ($name, $email);
2751 if ($_use_log_author) {
2752 my $name_field;
2753 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
2754 $name_field = $1;
2755 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
2756 $name_field = $1;
2758 if (!defined $name_field) {
2759 if (!defined $email) {
2760 $email = $name;
2762 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
2763 ($name, $email) = ($1, $2);
2764 } elsif ($name_field =~ /(.*)@/) {
2765 ($name, $email) = ($1, $name_field);
2766 } else {
2767 ($name, $email) = ($name_field, $name_field);
2770 if (defined $headrev && $self->use_svm_props) {
2771 if ($self->rewrite_root) {
2772 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2773 "options set!\n";
2775 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
2776 # we don't want "SVM: initializing mirror for junk" ...
2777 return undef if $r == 0;
2778 my $svm = $self->svm;
2779 if ($uuid ne $svm->{uuid}) {
2780 die "UUID mismatch on SVM path:\n",
2781 "expected: $svm->{uuid}\n",
2782 " got: $uuid\n";
2784 my $full_url = $self->full_url;
2785 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2786 die "Failed to replace '$svm->{replace}' with ",
2787 "'$svm->{source}' in $full_url\n";
2788 # throw away username for storing in records
2789 remove_username($full_url);
2790 $log_entry{metadata} = "$full_url\@$r $uuid";
2791 $log_entry{svm_revision} = $r;
2792 $email ||= "$author\@$uuid";
2793 $commit_email ||= "$author\@$uuid";
2794 } elsif ($self->use_svnsync_props) {
2795 my $full_url = $self->svnsync->{url};
2796 $full_url .= "/$self->{path}" if length $self->{path};
2797 remove_username($full_url);
2798 my $uuid = $self->svnsync->{uuid};
2799 $log_entry{metadata} = "$full_url\@$rev $uuid";
2800 $email ||= "$author\@$uuid";
2801 $commit_email ||= "$author\@$uuid";
2802 } else {
2803 my $url = $self->metadata_url;
2804 remove_username($url);
2805 $log_entry{metadata} = "$url\@$rev " .
2806 $self->ra->get_uuid;
2807 $email ||= "$author\@" . $self->ra->get_uuid;
2808 $commit_email ||= "$author\@" . $self->ra->get_uuid;
2810 $log_entry{name} = $name;
2811 $log_entry{email} = $email;
2812 $log_entry{commit_name} = $commit_name;
2813 $log_entry{commit_email} = $commit_email;
2814 \%log_entry;
2817 sub fetch {
2818 my ($self, $min_rev, $max_rev, @parents) = @_;
2819 my ($last_rev, $last_commit) = $self->last_rev_commit;
2820 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2821 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2824 sub set_tree_cb {
2825 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2826 $self->{inject_parents} = { $rev => $tree };
2827 $self->fetch(undef, undef);
2830 sub set_tree {
2831 my ($self, $tree) = (shift, shift);
2832 my $log_entry = ::get_commit_entry($tree);
2833 unless ($self->{last_rev}) {
2834 ::fatal("Must have an existing revision to commit");
2836 my %ed_opts = ( r => $self->{last_rev},
2837 log => $log_entry->{log},
2838 ra => $self->ra,
2839 tree_a => $self->{last_commit},
2840 tree_b => $tree,
2841 editor_cb => sub {
2842 $self->set_tree_cb($log_entry, $tree, @_) },
2843 svn_path => $self->{path} );
2844 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2845 print "No changes\nr$self->{last_rev} = $tree\n";
2849 sub rebuild_from_rev_db {
2850 my ($self, $path) = @_;
2851 my $r = -1;
2852 open my $fh, '<', $path or croak "open: $!";
2853 binmode $fh or croak "binmode: $!";
2854 while (<$fh>) {
2855 length($_) == 41 or croak "inconsistent size in ($_) != 41";
2856 chomp($_);
2857 ++$r;
2858 next if $_ eq ('0' x 40);
2859 $self->rev_map_set($r, $_);
2860 print "r$r = $_\n";
2862 close $fh or croak "close: $!";
2863 unlink $path or croak "unlink: $!";
2866 sub rebuild {
2867 my ($self) = @_;
2868 my $map_path = $self->map_path;
2869 my $partial = (-e $map_path && ! -z $map_path);
2870 return unless ::verify_ref($self->refname.'^0');
2871 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
2872 my $rev_db = $self->rev_db_path;
2873 $self->rebuild_from_rev_db($rev_db);
2874 if ($self->use_svm_props) {
2875 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
2876 $self->rebuild_from_rev_db($svm_rev_db);
2878 $self->unlink_rev_db_symlink;
2879 return;
2881 print "Rebuilding $map_path ...\n" if (!$partial);
2882 my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
2883 (undef, undef));
2884 my ($log, $ctx) =
2885 command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
2886 ($head ? "$head.." : "") . $self->refname,
2887 '--');
2888 my $metadata_url = $self->metadata_url;
2889 remove_username($metadata_url);
2890 my $svn_uuid = $self->ra_uuid;
2891 my $c;
2892 while (<$log>) {
2893 if ( m{^commit ($::sha1)$} ) {
2894 $c = $1;
2895 next;
2897 next unless s{^\s*(git-svn-id:)}{$1};
2898 my ($url, $rev, $uuid) = ::extract_metadata($_);
2899 remove_username($url);
2901 # ignore merges (from set-tree)
2902 next if (!defined $rev || !$uuid);
2904 # if we merged or otherwise started elsewhere, this is
2905 # how we break out of it
2906 if (($uuid ne $svn_uuid) ||
2907 ($metadata_url && $url && ($url ne $metadata_url))) {
2908 next;
2910 if ($partial && $head) {
2911 print "Partial-rebuilding $map_path ...\n";
2912 print "Currently at $base_rev = $head\n";
2913 $head = undef;
2916 $self->rev_map_set($rev, $c);
2917 print "r$rev = $c\n";
2919 command_close_pipe($log, $ctx);
2920 print "Done rebuilding $map_path\n" if (!$partial || !$head);
2921 my $rev_db_path = $self->rev_db_path;
2922 if (-f $self->rev_db_path) {
2923 unlink $self->rev_db_path or croak "unlink: $!";
2925 $self->unlink_rev_db_symlink;
2928 # rev_map:
2929 # Tie::File seems to be prone to offset errors if revisions get sparse,
2930 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2931 # one of my favorite modules is out :< Next up would be one of the DBM
2932 # modules, but I'm not sure which is most portable...
2934 # This is the replacement for the rev_db format, which was too big
2935 # and inefficient for large repositories with a lot of sparse history
2936 # (mainly tags)
2938 # The format is this:
2939 # - 24 bytes for every record,
2940 # * 4 bytes for the integer representing an SVN revision number
2941 # * 20 bytes representing the sha1 of a git commit
2942 # - No empty padding records like the old format
2943 # (except the last record, which can be overwritten)
2944 # - new records are written append-only since SVN revision numbers
2945 # increase monotonically
2946 # - lookups on SVN revision number are done via a binary search
2947 # - Piping the file to xxd -c24 is a good way of dumping it for
2948 # viewing or editing (piped back through xxd -r), should the need
2949 # ever arise.
2950 # - The last record can be padding revision with an all-zero sha1
2951 # This is used to optimize fetch performance when using multiple
2952 # "fetch" directives in .git/config
2954 # These files are disposable unless noMetadata or useSvmProps is set
2956 sub _rev_map_set {
2957 my ($fh, $rev, $commit) = @_;
2959 binmode $fh or croak "binmode: $!";
2960 my $size = (stat($fh))[7];
2961 ($size % 24) == 0 or croak "inconsistent size: $size";
2963 my $wr_offset = 0;
2964 if ($size > 0) {
2965 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2966 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
2967 $read == 24 or croak "read only $read bytes (!= 24)";
2968 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
2969 if ($last_commit eq ('0' x40)) {
2970 if ($size >= 48) {
2971 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2972 $read = sysread($fh, $buf, 24) or
2973 croak "read: $!";
2974 $read == 24 or
2975 croak "read only $read bytes (!= 24)";
2976 ($last_rev, $last_commit) =
2977 unpack(rev_map_fmt, $buf);
2978 if ($last_commit eq ('0' x40)) {
2979 croak "inconsistent .rev_map\n";
2982 if ($last_rev >= $rev) {
2983 croak "last_rev is higher!: $last_rev >= $rev";
2985 $wr_offset = -24;
2988 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
2989 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
2990 croak "write: $!";
2993 sub mkfile {
2994 my ($path) = @_;
2995 unless (-e $path) {
2996 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2997 mkpath([$dir]) unless -d $dir;
2998 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2999 close $fh or die "Couldn't close (create) $path: $!\n";
3003 sub rev_map_set {
3004 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
3005 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
3006 my $db = $self->map_path($uuid);
3007 my $db_lock = "$db.lock";
3008 my $sig;
3009 if ($update_ref) {
3010 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3011 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
3013 mkfile($db);
3015 $LOCKFILES{$db_lock} = 1;
3016 my $sync;
3017 # both of these options make our .rev_db file very, very important
3018 # and we can't afford to lose it because rebuild() won't work
3019 if ($self->use_svm_props || $self->no_metadata) {
3020 $sync = 1;
3021 copy($db, $db_lock) or die "rev_map_set(@_): ",
3022 "Failed to copy: ",
3023 "$db => $db_lock ($!)\n";
3024 } else {
3025 rename $db, $db_lock or die "rev_map_set(@_): ",
3026 "Failed to rename: ",
3027 "$db => $db_lock ($!)\n";
3030 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
3031 or croak "Couldn't open $db_lock: $!\n";
3032 _rev_map_set($fh, $rev, $commit);
3033 if ($sync) {
3034 $fh->flush or die "Couldn't flush $db_lock: $!\n";
3035 $fh->sync or die "Couldn't sync $db_lock: $!\n";
3037 close $fh or croak $!;
3038 if ($update_ref) {
3039 $_head = $self;
3040 command_noisy('update-ref', '-m', "r$rev",
3041 $self->refname, $commit);
3043 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
3044 "$db_lock => $db ($!)\n";
3045 delete $LOCKFILES{$db_lock};
3046 if ($update_ref) {
3047 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3048 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
3049 kill $sig, $$ if defined $sig;
3053 # If want_commit, this will return an array of (rev, commit) where
3054 # commit _must_ be a valid commit in the archive.
3055 # Otherwise, it'll return the max revision (whether or not the
3056 # commit is valid or just a 0x40 placeholder).
3057 sub rev_map_max {
3058 my ($self, $want_commit) = @_;
3059 $self->rebuild;
3060 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
3061 $want_commit ? ($r, $c) : $r;
3064 sub rev_map_max_norebuild {
3065 my ($self, $want_commit) = @_;
3066 my $map_path = $self->map_path;
3067 stat $map_path or return $want_commit ? (0, undef) : 0;
3068 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3069 binmode $fh or croak "binmode: $!";
3070 my $size = (stat($fh))[7];
3071 ($size % 24) == 0 or croak "inconsistent size: $size";
3073 if ($size == 0) {
3074 close $fh or croak "close: $!";
3075 return $want_commit ? (0, undef) : 0;
3078 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3079 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3080 my ($r, $c) = unpack(rev_map_fmt, $buf);
3081 if ($want_commit && $c eq ('0' x40)) {
3082 if ($size < 48) {
3083 return $want_commit ? (0, undef) : 0;
3085 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3086 sysread($fh, $buf, 24) == 24 or croak "read: $!";
3087 ($r, $c) = unpack(rev_map_fmt, $buf);
3088 if ($c eq ('0'x40)) {
3089 croak "Penultimate record is all-zeroes in $map_path";
3092 close $fh or croak "close: $!";
3093 $want_commit ? ($r, $c) : $r;
3096 sub rev_map_get {
3097 my ($self, $rev, $uuid) = @_;
3098 my $map_path = $self->map_path($uuid);
3099 return undef unless -e $map_path;
3101 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3102 binmode $fh or croak "binmode: $!";
3103 my $size = (stat($fh))[7];
3104 ($size % 24) == 0 or croak "inconsistent size: $size";
3106 if ($size == 0) {
3107 close $fh or croak "close: $fh";
3108 return undef;
3111 my ($l, $u) = (0, $size - 24);
3112 my ($r, $c, $buf);
3114 while ($l <= $u) {
3115 my $i = int(($l/24 + $u/24) / 2) * 24;
3116 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
3117 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3118 my ($r, $c) = unpack('NH40', $buf);
3120 if ($r < $rev) {
3121 $l = $i + 24;
3122 } elsif ($r > $rev) {
3123 $u = $i - 24;
3124 } else { # $r == $rev
3125 close($fh) or croak "close: $!";
3126 return $c eq ('0' x 40) ? undef : $c;
3129 close($fh) or croak "close: $!";
3130 undef;
3133 # Finds the first svn revision that exists on (if $eq_ok is true) or
3134 # before $rev for the current branch. It will not search any lower
3135 # than $min_rev. Returns the git commit hash and svn revision number
3136 # if found, else (undef, undef).
3137 sub find_rev_before {
3138 my ($self, $rev, $eq_ok, $min_rev) = @_;
3139 --$rev unless $eq_ok;
3140 $min_rev ||= 1;
3141 while ($rev >= $min_rev) {
3142 if (my $c = $self->rev_map_get($rev)) {
3143 return ($rev, $c);
3145 --$rev;
3147 return (undef, undef);
3150 # Finds the first svn revision that exists on (if $eq_ok is true) or
3151 # after $rev for the current branch. It will not search any higher
3152 # than $max_rev. Returns the git commit hash and svn revision number
3153 # if found, else (undef, undef).
3154 sub find_rev_after {
3155 my ($self, $rev, $eq_ok, $max_rev) = @_;
3156 ++$rev unless $eq_ok;
3157 $max_rev ||= $self->rev_map_max;
3158 while ($rev <= $max_rev) {
3159 if (my $c = $self->rev_map_get($rev)) {
3160 return ($rev, $c);
3162 ++$rev;
3164 return (undef, undef);
3167 sub _new {
3168 my ($class, $repo_id, $ref_id, $path) = @_;
3169 unless (defined $repo_id && length $repo_id) {
3170 $repo_id = $Git::SVN::default_repo_id;
3172 unless (defined $ref_id && length $ref_id) {
3173 $_[2] = $ref_id = $Git::SVN::default_ref_id;
3175 $_[1] = $repo_id;
3176 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
3177 $_[3] = $path = '' unless (defined $path);
3178 mkpath(["$ENV{GIT_DIR}/svn"]);
3179 bless {
3180 ref_id => $ref_id, dir => $dir, index => "$dir/index",
3181 path => $path, config => "$ENV{GIT_DIR}/svn/config",
3182 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
3185 # for read-only access of old .rev_db formats
3186 sub unlink_rev_db_symlink {
3187 my ($self) = @_;
3188 my $link = $self->rev_db_path;
3189 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
3190 if (-l $link) {
3191 unlink $link or croak "unlink: $link failed!";
3195 sub rev_db_path {
3196 my ($self, $uuid) = @_;
3197 my $db_path = $self->map_path($uuid);
3198 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
3199 or croak "map_path: $db_path does not contain '/.rev_map.' !";
3200 $db_path;
3203 # the new replacement for .rev_db
3204 sub map_path {
3205 my ($self, $uuid) = @_;
3206 $uuid ||= $self->ra_uuid;
3207 "$self->{map_root}.$uuid";
3210 sub uri_encode {
3211 my ($f) = @_;
3212 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
3216 sub remove_username {
3217 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
3220 package Git::SVN::Prompt;
3221 use strict;
3222 use warnings;
3223 require SVN::Core;
3224 use vars qw/$_no_auth_cache $_username/;
3226 sub simple {
3227 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
3228 $may_save = undef if $_no_auth_cache;
3229 $default_username = $_username if defined $_username;
3230 if (defined $default_username && length $default_username) {
3231 if (defined $realm && length $realm) {
3232 print STDERR "Authentication realm: $realm\n";
3233 STDERR->flush;
3235 $cred->username($default_username);
3236 } else {
3237 username($cred, $realm, $may_save, $pool);
3239 $cred->password(_read_password("Password for '" .
3240 $cred->username . "': ", $realm));
3241 $cred->may_save($may_save);
3242 $SVN::_Core::SVN_NO_ERROR;
3245 sub ssl_server_trust {
3246 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
3247 $may_save = undef if $_no_auth_cache;
3248 print STDERR "Error validating server certificate for '$realm':\n";
3250 no warnings 'once';
3251 # All variables SVN::Auth::SSL::* are used only once,
3252 # so we're shutting up Perl warnings about this.
3253 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
3254 print STDERR " - The certificate is not issued ",
3255 "by a trusted authority. Use the\n",
3256 " fingerprint to validate ",
3257 "the certificate manually!\n";
3259 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
3260 print STDERR " - The certificate hostname ",
3261 "does not match.\n";
3263 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
3264 print STDERR " - The certificate is not yet valid.\n";
3266 if ($failures & $SVN::Auth::SSL::EXPIRED) {
3267 print STDERR " - The certificate has expired.\n";
3269 if ($failures & $SVN::Auth::SSL::OTHER) {
3270 print STDERR " - The certificate has ",
3271 "an unknown error.\n";
3273 } # no warnings 'once'
3274 printf STDERR
3275 "Certificate information:\n".
3276 " - Hostname: %s\n".
3277 " - Valid: from %s until %s\n".
3278 " - Issuer: %s\n".
3279 " - Fingerprint: %s\n",
3280 map $cert_info->$_, qw(hostname valid_from valid_until
3281 issuer_dname fingerprint);
3282 my $choice;
3283 prompt:
3284 print STDERR $may_save ?
3285 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
3286 "(R)eject or accept (t)emporarily? ";
3287 STDERR->flush;
3288 $choice = lc(substr(<STDIN> || 'R', 0, 1));
3289 if ($choice =~ /^t$/i) {
3290 $cred->may_save(undef);
3291 } elsif ($choice =~ /^r$/i) {
3292 return -1;
3293 } elsif ($may_save && $choice =~ /^p$/i) {
3294 $cred->may_save($may_save);
3295 } else {
3296 goto prompt;
3298 $cred->accepted_failures($failures);
3299 $SVN::_Core::SVN_NO_ERROR;
3302 sub ssl_client_cert {
3303 my ($cred, $realm, $may_save, $pool) = @_;
3304 $may_save = undef if $_no_auth_cache;
3305 print STDERR "Client certificate filename: ";
3306 STDERR->flush;
3307 chomp(my $filename = <STDIN>);
3308 $cred->cert_file($filename);
3309 $cred->may_save($may_save);
3310 $SVN::_Core::SVN_NO_ERROR;
3313 sub ssl_client_cert_pw {
3314 my ($cred, $realm, $may_save, $pool) = @_;
3315 $may_save = undef if $_no_auth_cache;
3316 $cred->password(_read_password("Password: ", $realm));
3317 $cred->may_save($may_save);
3318 $SVN::_Core::SVN_NO_ERROR;
3321 sub username {
3322 my ($cred, $realm, $may_save, $pool) = @_;
3323 $may_save = undef if $_no_auth_cache;
3324 if (defined $realm && length $realm) {
3325 print STDERR "Authentication realm: $realm\n";
3327 my $username;
3328 if (defined $_username) {
3329 $username = $_username;
3330 } else {
3331 print STDERR "Username: ";
3332 STDERR->flush;
3333 chomp($username = <STDIN>);
3335 $cred->username($username);
3336 $cred->may_save($may_save);
3337 $SVN::_Core::SVN_NO_ERROR;
3340 sub _read_password {
3341 my ($prompt, $realm) = @_;
3342 print STDERR $prompt;
3343 STDERR->flush;
3344 require Term::ReadKey;
3345 Term::ReadKey::ReadMode('noecho');
3346 my $password = '';
3347 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
3348 last if $key =~ /[\012\015]/; # \n\r
3349 $password .= $key;
3351 Term::ReadKey::ReadMode('restore');
3352 print STDERR "\n";
3353 STDERR->flush;
3354 $password;
3357 package SVN::Git::Fetcher;
3358 use vars qw/@ISA/;
3359 use strict;
3360 use warnings;
3361 use Carp qw/croak/;
3362 use File::Temp qw/tempfile/;
3363 use IO::File qw//;
3364 use vars qw/$_ignore_regex/;
3366 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
3367 sub new {
3368 my ($class, $git_svn, $switch_path) = @_;
3369 my $self = SVN::Delta::Editor->new;
3370 bless $self, $class;
3371 if (exists $git_svn->{last_commit}) {
3372 $self->{c} = $git_svn->{last_commit};
3373 $self->{empty_symlinks} =
3374 _mark_empty_symlinks($git_svn, $switch_path);
3376 $self->{ignore_regex} = eval { command_oneline('config', '--get',
3377 "svn-remote.$git_svn->{repo_id}.ignore-paths") };
3378 $self->{empty} = {};
3379 $self->{dir_prop} = {};
3380 $self->{file_prop} = {};
3381 $self->{absent_dir} = {};
3382 $self->{absent_file} = {};
3383 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
3384 $self;
3387 # this uses the Ra object, so it must be called before do_{switch,update},
3388 # not inside them (when the Git::SVN::Fetcher object is passed) to
3389 # do_{switch,update}
3390 sub _mark_empty_symlinks {
3391 my ($git_svn, $switch_path) = @_;
3392 my $bool = Git::config_bool('svn.brokenSymlinkWorkaround');
3393 return {} if (!defined($bool)) || (defined($bool) && ! $bool);
3395 my %ret;
3396 my ($rev, $cmt) = $git_svn->last_rev_commit;
3397 return {} unless ($rev && $cmt);
3399 # allow the warning to be printed for each revision we fetch to
3400 # ensure the user sees it. The user can also disable the workaround
3401 # on the repository even while git svn is running and the next
3402 # revision fetched will skip this expensive function.
3403 my $printed_warning;
3404 chomp(my $empty_blob = `git hash-object -t blob --stdin < /dev/null`);
3405 my ($ls, $ctx) = command_output_pipe(qw/ls-tree -r -z/, $cmt);
3406 local $/ = "\0";
3407 my $pfx = defined($switch_path) ? $switch_path : $git_svn->{path};
3408 $pfx .= '/' if length($pfx);
3409 while (<$ls>) {
3410 chomp;
3411 s/\A100644 blob $empty_blob\t//o or next;
3412 unless ($printed_warning) {
3413 print STDERR "Scanning for empty symlinks, ",
3414 "this may take a while if you have ",
3415 "many empty files\n",
3416 "You may disable this with `",
3417 "git config svn.brokenSymlinkWorkaround ",
3418 "false'.\n",
3419 "This may be done in a different ",
3420 "terminal without restarting ",
3421 "git svn\n";
3422 $printed_warning = 1;
3424 my $path = $_;
3425 my (undef, $props) =
3426 $git_svn->ra->get_file($pfx.$path, $rev, undef);
3427 if ($props->{'svn:special'}) {
3428 $ret{$path} = 1;
3431 command_close_pipe($ls, $ctx);
3432 \%ret;
3435 # returns true if a given path is inside a ".git" directory
3436 sub in_dot_git {
3437 $_[0] =~ m{(?:^|/)\.git(?:/|$)};
3440 # return value: 0 -- don't ignore, 1 -- ignore
3441 sub is_path_ignored {
3442 my ($self, $path) = @_;
3443 return 1 if in_dot_git($path);
3444 return 1 if defined($self->{ignore_regex}) &&
3445 $path =~ m!$self->{ignore_regex}!;
3446 return 0 unless defined($_ignore_regex);
3447 return 1 if $path =~ m!$_ignore_regex!o;
3448 return 0;
3451 sub set_path_strip {
3452 my ($self, $path) = @_;
3453 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
3456 sub open_root {
3457 { path => '' };
3460 sub open_directory {
3461 my ($self, $path, $pb, $rev) = @_;
3462 { path => $path };
3465 sub git_path {
3466 my ($self, $path) = @_;
3467 if ($self->{path_strip}) {
3468 $path =~ s!$self->{path_strip}!! or
3469 die "Failed to strip path '$path' ($self->{path_strip})\n";
3471 $path;
3474 sub delete_entry {
3475 my ($self, $path, $rev, $pb) = @_;
3476 return undef if $self->is_path_ignored($path);
3478 my $gpath = $self->git_path($path);
3479 return undef if ($gpath eq '');
3481 # remove entire directories.
3482 my ($tree) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
3483 =~ /\A040000 tree ([a-f\d]{40})\t\Q$gpath\E\0/);
3484 if ($tree) {
3485 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3486 -r --name-only -z/,
3487 $tree);
3488 local $/ = "\0";
3489 while (<$ls>) {
3490 chomp;
3491 my $rmpath = "$gpath/$_";
3492 $self->{gii}->remove($rmpath);
3493 print "\tD\t$rmpath\n" unless $::_q;
3495 print "\tD\t$gpath/\n" unless $::_q;
3496 command_close_pipe($ls, $ctx);
3497 $self->{empty}->{$path} = 0
3498 } else {
3499 $self->{gii}->remove($gpath);
3500 print "\tD\t$gpath\n" unless $::_q;
3502 undef;
3505 sub open_file {
3506 my ($self, $path, $pb, $rev) = @_;
3507 my ($mode, $blob);
3509 goto out if $self->is_path_ignored($path);
3511 my $gpath = $self->git_path($path);
3512 ($mode, $blob) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
3513 =~ /\A(\d{6}) blob ([a-f\d]{40})\t\Q$gpath\E\0/);
3514 unless (defined $mode && defined $blob) {
3515 die "$path was not found in commit $self->{c} (r$rev)\n";
3517 if ($mode eq '100644' && $self->{empty_symlinks}->{$path}) {
3518 $mode = '120000';
3520 out:
3521 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
3522 pool => SVN::Pool->new, action => 'M' };
3525 sub add_file {
3526 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
3527 my $mode;
3529 if (!$self->is_path_ignored($path)) {
3530 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3531 delete $self->{empty}->{$dir};
3532 $mode = '100644';
3534 { path => $path, mode_a => $mode, mode_b => $mode,
3535 pool => SVN::Pool->new, action => 'A' };
3538 sub add_directory {
3539 my ($self, $path, $cp_path, $cp_rev) = @_;
3540 goto out if $self->is_path_ignored($path);
3541 my $gpath = $self->git_path($path);
3542 if ($gpath eq '') {
3543 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3544 -r --name-only -z/,
3545 $self->{c});
3546 local $/ = "\0";
3547 while (<$ls>) {
3548 chomp;
3549 $self->{gii}->remove($_);
3550 print "\tD\t$_\n" unless $::_q;
3552 command_close_pipe($ls, $ctx);
3553 $self->{empty}->{$path} = 0;
3555 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3556 delete $self->{empty}->{$dir};
3557 $self->{empty}->{$path} = 1;
3558 out:
3559 { path => $path };
3562 sub change_dir_prop {
3563 my ($self, $db, $prop, $value) = @_;
3564 return undef if $self->is_path_ignored($db->{path});
3565 $self->{dir_prop}->{$db->{path}} ||= {};
3566 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
3567 undef;
3570 sub absent_directory {
3571 my ($self, $path, $pb) = @_;
3572 return undef if $self->is_path_ignored($path);
3573 $self->{absent_dir}->{$pb->{path}} ||= [];
3574 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
3575 undef;
3578 sub absent_file {
3579 my ($self, $path, $pb) = @_;
3580 return undef if $self->is_path_ignored($path);
3581 $self->{absent_file}->{$pb->{path}} ||= [];
3582 push @{$self->{absent_file}->{$pb->{path}}}, $path;
3583 undef;
3586 sub change_file_prop {
3587 my ($self, $fb, $prop, $value) = @_;
3588 return undef if $self->is_path_ignored($fb->{path});
3589 if ($prop eq 'svn:executable') {
3590 if ($fb->{mode_b} != 120000) {
3591 $fb->{mode_b} = defined $value ? 100755 : 100644;
3593 } elsif ($prop eq 'svn:special') {
3594 $fb->{mode_b} = defined $value ? 120000 : 100644;
3595 } else {
3596 $self->{file_prop}->{$fb->{path}} ||= {};
3597 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
3599 undef;
3602 sub apply_textdelta {
3603 my ($self, $fb, $exp) = @_;
3604 return undef if $self->is_path_ignored($fb->{path});
3605 my $fh = $::_repository->temp_acquire('svn_delta');
3606 # $fh gets auto-closed() by SVN::TxDelta::apply(),
3607 # (but $base does not,) so dup() it for reading in close_file
3608 open my $dup, '<&', $fh or croak $!;
3609 my $base = $::_repository->temp_acquire('git_blob');
3611 if ($fb->{blob}) {
3612 my ($base_is_link, $size);
3614 if ($fb->{mode_a} eq '120000' &&
3615 ! $self->{empty_symlinks}->{$fb->{path}}) {
3616 print $base 'link ' or die "print $!\n";
3617 $base_is_link = 1;
3619 retry:
3620 $size = $::_repository->cat_blob($fb->{blob}, $base);
3621 die "Failed to read object $fb->{blob}" if ($size < 0);
3623 if (defined $exp) {
3624 seek $base, 0, 0 or croak $!;
3625 my $got = ::md5sum($base);
3626 if ($got ne $exp) {
3627 my $err = "Checksum mismatch: ".
3628 "$fb->{path} $fb->{blob}\n" .
3629 "expected: $exp\n" .
3630 " got: $got\n";
3631 if ($base_is_link) {
3632 warn $err,
3633 "Retrying... (possibly ",
3634 "a bad symlink from SVN)\n";
3635 $::_repository->temp_reset($base);
3636 $base_is_link = 0;
3637 goto retry;
3639 die $err;
3643 seek $base, 0, 0 or croak $!;
3644 $fb->{fh} = $fh;
3645 $fb->{base} = $base;
3646 [ SVN::TxDelta::apply($base, $dup, undef, $fb->{path}, $fb->{pool}) ];
3649 sub close_file {
3650 my ($self, $fb, $exp) = @_;
3651 return undef if $self->is_path_ignored($fb->{path});
3653 my $hash;
3654 my $path = $self->git_path($fb->{path});
3655 if (my $fh = $fb->{fh}) {
3656 if (defined $exp) {
3657 seek($fh, 0, 0) or croak $!;
3658 my $got = ::md5sum($fh);
3659 if ($got ne $exp) {
3660 die "Checksum mismatch: $path\n",
3661 "expected: $exp\n got: $got\n";
3664 if ($fb->{mode_b} == 120000) {
3665 sysseek($fh, 0, 0) or croak $!;
3666 my $rd = sysread($fh, my $buf, 5);
3668 if (!defined $rd) {
3669 croak "sysread: $!\n";
3670 } elsif ($rd == 0) {
3671 warn "$path has mode 120000",
3672 " but it points to nothing\n",
3673 "converting to an empty file with mode",
3674 " 100644\n";
3675 $fb->{mode_b} = '100644';
3676 } elsif ($buf ne 'link ') {
3677 warn "$path has mode 120000",
3678 " but is not a link\n";
3679 } else {
3680 my $tmp_fh = $::_repository->temp_acquire(
3681 'svn_hash');
3682 my $res;
3683 while ($res = sysread($fh, my $str, 1024)) {
3684 my $out = syswrite($tmp_fh, $str, $res);
3685 defined($out) && $out == $res
3686 or croak("write ",
3687 Git::temp_path($tmp_fh),
3688 ": $!\n");
3690 defined $res or croak $!;
3692 ($fh, $tmp_fh) = ($tmp_fh, $fh);
3693 Git::temp_release($tmp_fh, 1);
3697 $hash = $::_repository->hash_and_insert_object(
3698 Git::temp_path($fh));
3699 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
3701 Git::temp_release($fb->{base}, 1);
3702 Git::temp_release($fh, 1);
3703 } else {
3704 $hash = $fb->{blob} or die "no blob information\n";
3706 $fb->{pool}->clear;
3707 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
3708 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
3709 undef;
3712 sub abort_edit {
3713 my $self = shift;
3714 $self->{nr} = $self->{gii}->{nr};
3715 delete $self->{gii};
3716 $self->SUPER::abort_edit(@_);
3719 sub close_edit {
3720 my $self = shift;
3721 $self->{git_commit_ok} = 1;
3722 $self->{nr} = $self->{gii}->{nr};
3723 delete $self->{gii};
3724 $self->SUPER::close_edit(@_);
3727 package SVN::Git::Editor;
3728 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
3729 use strict;
3730 use warnings;
3731 use Carp qw/croak/;
3732 use IO::File;
3734 sub new {
3735 my ($class, $opts) = @_;
3736 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
3737 die "$_ required!\n" unless (defined $opts->{$_});
3740 my $pool = SVN::Pool->new;
3741 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
3742 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
3743 $opts->{r}, $mods);
3745 # $opts->{ra} functions should not be used after this:
3746 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
3747 $opts->{editor_cb}, $pool);
3748 my $self = SVN::Delta::Editor->new(@ce, $pool);
3749 bless $self, $class;
3750 foreach (qw/svn_path r tree_a tree_b/) {
3751 $self->{$_} = $opts->{$_};
3753 $self->{url} = $opts->{ra}->{url};
3754 $self->{mods} = $mods;
3755 $self->{types} = $types;
3756 $self->{pool} = $pool;
3757 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
3758 $self->{rm} = { };
3759 $self->{path_prefix} = length $self->{svn_path} ?
3760 "$self->{svn_path}/" : '';
3761 $self->{config} = $opts->{config};
3762 return $self;
3765 sub generate_diff {
3766 my ($tree_a, $tree_b) = @_;
3767 my @diff_tree = qw(diff-tree -z -r);