stash: simplify defaulting to "save" and reject unknown options
[git.git] / git-svn.perl
blob9369acc4dce3681012aa2c16f6d292a3d76d9baf
1 #!/usr/bin/env perl
2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
4 use warnings;
5 use strict;
6 use vars qw/ $AUTHOR $VERSION
7 $sha1 $sha1_short $_revision $_repository
8 $_q $_authors $_authors_prog %users/;
9 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
10 $VERSION = '@@GIT_VERSION@@';
12 # From which subdir have we been invoked?
13 my $cmd_dir_prefix = eval {
14 command_oneline([qw/rev-parse --show-prefix/], STDERR => 0)
15 } || '';
17 my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
18 $ENV{GIT_DIR} ||= '.git';
19 $Git::SVN::default_repo_id = 'svn';
20 $Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
21 $Git::SVN::Ra::_log_window_size = 100;
23 $Git::SVN::Log::TZ = $ENV{TZ};
24 $ENV{TZ} = 'UTC';
25 $| = 1; # unbuffer STDOUT
27 sub fatal (@) { print STDERR "@_\n"; exit 1 }
28 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
29 require SVN::Ra;
30 require SVN::Delta;
31 if ($SVN::Core::VERSION lt '1.1.0') {
32 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
34 push @Git::SVN::Ra::ISA, 'SVN::Ra';
35 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
36 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
37 use Carp qw/croak/;
38 use Digest::MD5;
39 use IO::File qw//;
40 use File::Basename qw/dirname basename/;
41 use File::Path qw/mkpath/;
42 use File::Spec;
43 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
44 use IPC::Open3;
45 use Git;
47 BEGIN {
48 # import functions from Git into our packages, en masse
49 no strict 'refs';
50 foreach (qw/command command_oneline command_noisy command_output_pipe
51 command_input_pipe command_close_pipe
52 command_bidi_pipe command_close_bidi_pipe/) {
53 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
54 Git::SVN::Migration Git::SVN::Log Git::SVN),
55 __PACKAGE__) {
56 *{"${package}::$_"} = \&{"Git::$_"};
61 my ($SVN);
63 $sha1 = qr/[a-f\d]{40}/;
64 $sha1_short = qr/[a-f\d]{4,40}/;
65 my ($_stdin, $_help, $_edit,
66 $_message, $_file, $_branch_dest,
67 $_template, $_shared,
68 $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
69 $_merge, $_strategy, $_dry_run, $_local,
70 $_prefix, $_no_checkout, $_url, $_verbose,
71 $_git_format, $_commit_url, $_tag);
72 $Git::SVN::_follow_parent = 1;
73 $_q ||= 0;
74 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
75 'config-dir=s' => \$Git::SVN::Ra::config_dir,
76 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
77 'ignore-paths=s' => \$SVN::Git::Fetcher::_ignore_regex );
78 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
79 'authors-file|A=s' => \$_authors,
80 'authors-prog=s' => \$_authors_prog,
81 'repack:i' => \$Git::SVN::_repack,
82 'noMetadata' => \$Git::SVN::_no_metadata,
83 'useSvmProps' => \$Git::SVN::_use_svm_props,
84 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
85 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
86 'no-checkout' => \$_no_checkout,
87 'quiet|q+' => \$_q,
88 'repack-flags|repack-args|repack-opts=s' =>
89 \$Git::SVN::_repack_flags,
90 'use-log-author' => \$Git::SVN::_use_log_author,
91 'add-author-from' => \$Git::SVN::_add_author_from,
92 'localtime' => \$Git::SVN::_localtime,
93 %remote_opts );
95 my ($_trunk, @_tags, @_branches, $_stdlayout);
96 my %icv;
97 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
98 'trunk|T=s' => \$_trunk, 'tags|t=s@' => \@_tags,
99 'branches|b=s@' => \@_branches, 'prefix=s' => \$_prefix,
100 'stdlayout|s' => \$_stdlayout,
101 'minimize-url|m' => \$Git::SVN::_minimize_url,
102 'no-metadata' => sub { $icv{noMetadata} = 1 },
103 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
104 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
105 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
106 %remote_opts );
107 my %cmt_opts = ( 'edit|e' => \$_edit,
108 'rmdir' => \$SVN::Git::Editor::_rmdir,
109 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
110 'l=i' => \$SVN::Git::Editor::_rename_limit,
111 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
114 my %cmd = (
115 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
116 { 'revision|r=s' => \$_revision,
117 'fetch-all|all' => \$_fetch_all,
118 'parent|p' => \$_fetch_parent,
119 %fc_opts } ],
120 clone => [ \&cmd_clone, "Initialize and fetch revisions",
121 { 'revision|r=s' => \$_revision,
122 %fc_opts, %init_opts } ],
123 init => [ \&cmd_init, "Initialize a repo for tracking" .
124 " (requires URL argument)",
125 \%init_opts ],
126 'multi-init' => [ \&cmd_multi_init,
127 "Deprecated alias for ".
128 "'$0 init -T<trunk> -b<branches> -t<tags>'",
129 \%init_opts ],
130 dcommit => [ \&cmd_dcommit,
131 'Commit several diffs to merge with upstream',
132 { 'merge|m|M' => \$_merge,
133 'strategy|s=s' => \$_strategy,
134 'verbose|v' => \$_verbose,
135 'dry-run|n' => \$_dry_run,
136 'fetch-all|all' => \$_fetch_all,
137 'commit-url=s' => \$_commit_url,
138 'revision|r=i' => \$_revision,
139 'no-rebase' => \$_no_rebase,
140 %cmt_opts, %fc_opts } ],
141 branch => [ \&cmd_branch,
142 'Create a branch in the SVN repository',
143 { 'message|m=s' => \$_message,
144 'destination|d=s' => \$_branch_dest,
145 'dry-run|n' => \$_dry_run,
146 'tag|t' => \$_tag } ],
147 tag => [ sub { $_tag = 1; cmd_branch(@_) },
148 'Create a tag in the SVN repository',
149 { 'message|m=s' => \$_message,
150 'destination|d=s' => \$_branch_dest,
151 'dry-run|n' => \$_dry_run } ],
152 'set-tree' => [ \&cmd_set_tree,
153 "Set an SVN repository to a git tree-ish",
154 { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
155 'create-ignore' => [ \&cmd_create_ignore,
156 'Create a .gitignore per svn:ignore',
157 { 'revision|r=i' => \$_revision
158 } ],
159 'propget' => [ \&cmd_propget,
160 'Print the value of a property on a file or directory',
161 { 'revision|r=i' => \$_revision } ],
162 'proplist' => [ \&cmd_proplist,
163 'List all properties of a file or directory',
164 { 'revision|r=i' => \$_revision } ],
165 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
166 { 'revision|r=i' => \$_revision
167 } ],
168 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
169 { 'revision|r=i' => \$_revision
170 } ],
171 'multi-fetch' => [ \&cmd_multi_fetch,
172 "Deprecated alias for $0 fetch --all",
173 { 'revision|r=s' => \$_revision, %fc_opts } ],
174 'migrate' => [ sub { },
175 # no-op, we automatically run this anyways,
176 'Migrate configuration/metadata/layout from
177 previous versions of git-svn',
178 { 'minimize' => \$Git::SVN::Migration::_minimize,
179 %remote_opts } ],
180 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
181 { 'limit=i' => \$Git::SVN::Log::limit,
182 'revision|r=s' => \$_revision,
183 'verbose|v' => \$Git::SVN::Log::verbose,
184 'incremental' => \$Git::SVN::Log::incremental,
185 'oneline' => \$Git::SVN::Log::oneline,
186 'show-commit' => \$Git::SVN::Log::show_commit,
187 'non-recursive' => \$Git::SVN::Log::non_recursive,
188 'authors-file|A=s' => \$_authors,
189 'color' => \$Git::SVN::Log::color,
190 'pager=s' => \$Git::SVN::Log::pager
191 } ],
192 'find-rev' => [ \&cmd_find_rev,
193 "Translate between SVN revision numbers and tree-ish",
194 {} ],
195 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
196 { 'merge|m|M' => \$_merge,
197 'verbose|v' => \$_verbose,
198 'strategy|s=s' => \$_strategy,
199 'local|l' => \$_local,
200 'fetch-all|all' => \$_fetch_all,
201 'dry-run|n' => \$_dry_run,
202 %fc_opts } ],
203 'commit-diff' => [ \&cmd_commit_diff,
204 'Commit a diff between two trees',
205 { 'message|m=s' => \$_message,
206 'file|F=s' => \$_file,
207 'revision|r=s' => \$_revision,
208 %cmt_opts } ],
209 'info' => [ \&cmd_info,
210 "Show info about the latest SVN revision
211 on the current branch",
212 { 'url' => \$_url, } ],
213 'blame' => [ \&Git::SVN::Log::cmd_blame,
214 "Show what revision and author last modified each line of a file",
215 { 'git-format' => \$_git_format } ],
216 'reset' => [ \&cmd_reset,
217 "Undo fetches back to the specified SVN revision",
218 { 'revision|r=s' => \$_revision,
219 'parent|p' => \$_fetch_parent } ],
222 my $cmd;
223 for (my $i = 0; $i < @ARGV; $i++) {
224 if (defined $cmd{$ARGV[$i]}) {
225 $cmd = $ARGV[$i];
226 splice @ARGV, $i, 1;
227 last;
228 } elsif ($ARGV[$i] eq 'help') {
229 $cmd = $ARGV[$i+1];
230 usage(0);
234 # make sure we're always running at the top-level working directory
235 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
236 unless (-d $ENV{GIT_DIR}) {
237 if ($git_dir_user_set) {
238 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
239 "but it is not a directory\n";
241 my $git_dir = delete $ENV{GIT_DIR};
242 my $cdup = undef;
243 git_cmd_try {
244 $cdup = command_oneline(qw/rev-parse --show-cdup/);
245 $git_dir = '.' unless ($cdup);
246 chomp $cdup if ($cdup);
247 $cdup = "." unless ($cdup && length $cdup);
248 } "Already at toplevel, but $git_dir not found\n";
249 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
250 unless (-d $git_dir) {
251 die "$git_dir still not found after going to ",
252 "'$cdup'\n";
254 $ENV{GIT_DIR} = $git_dir;
256 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
259 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
261 read_repo_config(\%opts);
262 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
263 Getopt::Long::Configure('pass_through');
265 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
266 'minimize-connections' => \$Git::SVN::Migration::_minimize,
267 'id|i=s' => \$Git::SVN::default_ref_id,
268 'svn-remote|remote|R=s' => sub {
269 $Git::SVN::no_reuse_existing = 1;
270 $Git::SVN::default_repo_id = $_[1] });
271 exit 1 if (!$rv && $cmd && $cmd ne 'log');
273 usage(0) if $_help;
274 version() if $_version;
275 usage(1) unless defined $cmd;
276 load_authors() if $_authors;
277 if (defined $_authors_prog) {
278 $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
281 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
282 Git::SVN::Migration::migration_check();
284 Git::SVN::init_vars();
285 eval {
286 Git::SVN::verify_remotes_sanity();
287 $cmd{$cmd}->[0]->(@ARGV);
289 fatal $@ if $@;
290 post_fetch_checkout();
291 exit 0;
293 ####################### primary functions ######################
294 sub usage {
295 my $exit = shift || 0;
296 my $fd = $exit ? \*STDERR : \*STDOUT;
297 print $fd <<"";
298 git-svn - bidirectional operations between a single Subversion tree and git
299 Usage: git svn <command> [options] [arguments]\n
301 print $fd "Available commands:\n" unless $cmd;
303 foreach (sort keys %cmd) {
304 next if $cmd && $cmd ne $_;
305 next if /^multi-/; # don't show deprecated commands
306 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
307 foreach (sort keys %{$cmd{$_}->[2]}) {
308 # mixed-case options are for .git/config only
309 next if /[A-Z]/ && /^[a-z]+$/i;
310 # prints out arguments as they should be passed:
311 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
312 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
313 "--$_" : "-$_" }
314 split /\|/,$_)," $x\n";
317 print $fd <<"";
318 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
319 arbitrary identifier if you're tracking multiple SVN branches/repositories in
320 one git repository and want to keep them separate. See git-svn(1) for more
321 information.
323 exit $exit;
326 sub version {
327 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
328 exit 0;
331 sub do_git_init_db {
332 unless (-d $ENV{GIT_DIR}) {
333 my @init_db = ('init');
334 push @init_db, "--template=$_template" if defined $_template;
335 if (defined $_shared) {
336 if ($_shared =~ /[a-z]/) {
337 push @init_db, "--shared=$_shared";
338 } else {
339 push @init_db, "--shared";
342 command_noisy(@init_db);
343 $_repository = Git->repository(Repository => ".git");
345 command_noisy('config', 'core.autocrlf', 'false');
346 my $set;
347 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
348 foreach my $i (keys %icv) {
349 die "'$set' and '$i' cannot both be set\n" if $set;
350 next unless defined $icv{$i};
351 command_noisy('config', "$pfx.$i", $icv{$i});
352 $set = $i;
354 my $ignore_regex = \$SVN::Git::Fetcher::_ignore_regex;
355 command_noisy('config', "$pfx.ignore-paths", $$ignore_regex)
356 if defined $$ignore_regex;
359 sub init_subdir {
360 my $repo_path = shift or return;
361 mkpath([$repo_path]) unless -d $repo_path;
362 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
363 $ENV{GIT_DIR} = '.git';
364 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
367 sub cmd_clone {
368 my ($url, $path) = @_;
369 if (!defined $path &&
370 (defined $_trunk || @_branches || @_tags ||
371 defined $_stdlayout) &&
372 $url !~ m#^[a-z\+]+://#) {
373 $path = $url;
375 $path = basename($url) if !defined $path || !length $path;
376 cmd_init($url, $path);
377 Git::SVN::fetch_all($Git::SVN::default_repo_id);
378 command_oneline('config', 'svn.authorsfile', $_authors) if $_authors;
381 sub cmd_init {
382 if (defined $_stdlayout) {
383 $_trunk = 'trunk' if (!defined $_trunk);
384 @_tags = 'tags' if (! @_tags);
385 @_branches = 'branches' if (! @_branches);
387 if (defined $_trunk || @_branches || @_tags) {
388 return cmd_multi_init(@_);
390 my $url = shift or die "SVN repository location required ",
391 "as a command-line argument\n";
392 $url = canonicalize_url($url);
393 init_subdir(@_);
394 do_git_init_db();
396 Git::SVN->init($url);
399 sub cmd_fetch {
400 if (grep /^\d+=./, @_) {
401 die "'<rev>=<commit>' fetch arguments are ",
402 "no longer supported.\n";
404 my ($remote) = @_;
405 if (@_ > 1) {
406 die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
408 if ($_fetch_parent) {
409 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
410 unless ($gs) {
411 die "Unable to determine upstream SVN information from ",
412 "working tree history\n";
414 # just fetch, don't checkout.
415 $_no_checkout = 'true';
416 $_fetch_all ? $gs->fetch_all : $gs->fetch;
417 } elsif ($_fetch_all) {
418 cmd_multi_fetch();
419 } else {
420 $remote ||= $Git::SVN::default_repo_id;
421 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
425 sub cmd_set_tree {
426 my (@commits) = @_;
427 if ($_stdin || !@commits) {
428 print "Reading from stdin...\n";
429 @commits = ();
430 while (<STDIN>) {
431 if (/\b($sha1_short)\b/o) {
432 unshift @commits, $1;
436 my @revs;
437 foreach my $c (@commits) {
438 my @tmp = command('rev-parse',$c);
439 if (scalar @tmp == 1) {
440 push @revs, $tmp[0];
441 } elsif (scalar @tmp > 1) {
442 push @revs, reverse(command('rev-list',@tmp));
443 } else {
444 fatal "Failed to rev-parse $c";
447 my $gs = Git::SVN->new;
448 my ($r_last, $cmt_last) = $gs->last_rev_commit;
449 $gs->fetch;
450 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
451 fatal "There are new revisions that were fetched ",
452 "and need to be merged (or acknowledged) ",
453 "before committing.\nlast rev: $r_last\n",
454 " current: $gs->{last_rev}";
456 $gs->set_tree($_) foreach @revs;
457 print "Done committing ",scalar @revs," revisions to SVN\n";
458 unlink $gs->{index};
461 sub cmd_dcommit {
462 my $head = shift;
463 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
464 'Cannot dcommit with a dirty index. Commit your changes first, '
465 . "or stash them with `git stash'.\n";
466 $head ||= 'HEAD';
468 my $old_head;
469 if ($head ne 'HEAD') {
470 $old_head = eval {
471 command_oneline([qw/symbolic-ref -q HEAD/])
473 if ($old_head) {
474 $old_head =~ s{^refs/heads/}{};
475 } else {
476 $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
478 command(['checkout', $head], STDERR => 0);
481 my @refs;
482 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
483 unless ($gs) {
484 die "Unable to determine upstream SVN information from ",
485 "$head history.\nPerhaps the repository is empty.";
488 if (defined $_commit_url) {
489 $url = $_commit_url;
490 } else {
491 $url = eval { command_oneline('config', '--get',
492 "svn-remote.$gs->{repo_id}.commiturl") };
493 if (!$url) {
494 $url = $gs->full_url
498 my $last_rev = $_revision if defined $_revision;
499 if ($url) {
500 print "Committing to $url ...\n";
502 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
503 if ($_no_rebase && scalar(@$linear_refs) > 1) {
504 warn "Attempting to commit more than one change while ",
505 "--no-rebase is enabled.\n",
506 "If these changes depend on each other, re-running ",
507 "without --no-rebase may be required."
509 my $expect_url = $url;
510 Git::SVN::remove_username($expect_url);
511 while (1) {
512 my $d = shift @$linear_refs or last;
513 unless (defined $last_rev) {
514 (undef, $last_rev, undef) = cmt_metadata("$d~1");
515 unless (defined $last_rev) {
516 fatal "Unable to extract revision information ",
517 "from commit $d~1";
520 if ($_dry_run) {
521 print "diff-tree $d~1 $d\n";
522 } else {
523 my $cmt_rev;
524 my %ed_opts = ( r => $last_rev,
525 log => get_commit_entry($d)->{log},
526 ra => Git::SVN::Ra->new($url),
527 config => SVN::Core::config_get_config(
528 $Git::SVN::Ra::config_dir
530 tree_a => "$d~1",
531 tree_b => $d,
532 editor_cb => sub {
533 print "Committed r$_[0]\n";
534 $cmt_rev = $_[0];
536 svn_path => '');
537 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
538 print "No changes\n$d~1 == $d\n";
539 } elsif ($parents->{$d} && @{$parents->{$d}}) {
540 $gs->{inject_parents_dcommit}->{$cmt_rev} =
541 $parents->{$d};
543 $_fetch_all ? $gs->fetch_all : $gs->fetch;
544 $last_rev = $cmt_rev;
545 next if $_no_rebase;
547 # we always want to rebase against the current HEAD,
548 # not any head that was passed to us
549 my @diff = command('diff-tree', $d,
550 $gs->refname, '--');
551 my @finish;
552 if (@diff) {
553 @finish = rebase_cmd();
554 print STDERR "W: $d and ", $gs->refname,
555 " differ, using @finish:\n",
556 join("\n", @diff), "\n";
557 } else {
558 print "No changes between current HEAD and ",
559 $gs->refname,
560 "\nResetting to the latest ",
561 $gs->refname, "\n";
562 @finish = qw/reset --mixed/;
564 command_noisy(@finish, $gs->refname);
565 if (@diff) {
566 @refs = ();
567 my ($url_, $rev_, $uuid_, $gs_) =
568 working_head_info('HEAD', \@refs);
569 my ($linear_refs_, $parents_) =
570 linearize_history($gs_, \@refs);
571 if (scalar(@$linear_refs) !=
572 scalar(@$linear_refs_)) {
573 fatal "# of revisions changed ",
574 "\nbefore:\n",
575 join("\n", @$linear_refs),
576 "\n\nafter:\n",
577 join("\n", @$linear_refs_), "\n",
578 'If you are attempting to commit ',
579 "merges, try running:\n\t",
580 'git rebase --interactive',
581 '--preserve-merges ',
582 $gs->refname,
583 "\nBefore dcommitting";
585 if ($url_ ne $expect_url) {
586 fatal "URL mismatch after rebase: ",
587 "$url_ != $expect_url";
589 if ($uuid_ ne $uuid) {
590 fatal "uuid mismatch after rebase: ",
591 "$uuid_ != $uuid";
593 # remap parents
594 my (%p, @l, $i);
595 for ($i = 0; $i < scalar @$linear_refs; $i++) {
596 my $new = $linear_refs_->[$i] or next;
597 $p{$new} =
598 $parents->{$linear_refs->[$i]};
599 push @l, $new;
601 $parents = \%p;
602 $linear_refs = \@l;
607 if ($old_head) {
608 my $new_head = command_oneline(qw/rev-parse HEAD/);
609 my $new_is_symbolic = eval {
610 command_oneline(qw/symbolic-ref -q HEAD/);
612 if ($new_is_symbolic) {
613 print "dcommitted the branch ", $head, "\n";
614 } else {
615 print "dcommitted on a detached HEAD because you gave ",
616 "a revision argument.\n",
617 "The rewritten commit is: ", $new_head, "\n";
619 command(['checkout', $old_head], STDERR => 0);
622 unlink $gs->{index};
625 sub cmd_branch {
626 my ($branch_name, $head) = @_;
628 unless (defined $branch_name && length $branch_name) {
629 die(($_tag ? "tag" : "branch") . " name required\n");
631 $head ||= 'HEAD';
633 my ($src, $rev, undef, $gs) = working_head_info($head);
635 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
636 my $allglobs = $remote->{ $_tag ? 'tags' : 'branches' };
637 my $glob;
638 if ($#{$allglobs} == 0) {
639 $glob = $allglobs->[0];
640 } else {
641 unless(defined $_branch_dest) {
642 die "Multiple ",
643 $_tag ? "tag" : "branch",
644 " paths defined for Subversion repository.\n",
645 "You must specify where you want to create the ",
646 $_tag ? "tag" : "branch",
647 " with the --destination argument.\n";
649 foreach my $g (@{$allglobs}) {
650 # SVN::Git::Editor could probably be moved to Git.pm..
651 my $re = SVN::Git::Editor::glob2pat($g->{path}->{left});
652 if ($_branch_dest =~ /$re/) {
653 $glob = $g;
654 last;
657 unless (defined $glob) {
658 die "Unknown ",
659 $_tag ? "tag" : "branch",
660 " destination $_branch_dest\n";
663 my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
664 my $dst = join '/', $remote->{url}, $lft, $branch_name, ($rgt || ());
666 my $ctx = SVN::Client->new(
667 auth => Git::SVN::Ra::_auth_providers(),
668 log_msg => sub {
669 ${ $_[0] } = defined $_message
670 ? $_message
671 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
672 . $branch_name;
676 eval {
677 $ctx->ls($dst, 'HEAD', 0);
678 } and die "branch ${branch_name} already exists\n";
680 print "Copying ${src} at r${rev} to ${dst}...\n";
681 $ctx->copy($src, $rev, $dst)
682 unless $_dry_run;
684 $gs->fetch_all;
687 sub cmd_find_rev {
688 my $revision_or_hash = shift or die "SVN or git revision required ",
689 "as a command-line argument\n";
690 my $result;
691 if ($revision_or_hash =~ /^r\d+$/) {
692 my $head = shift;
693 $head ||= 'HEAD';
694 my @refs;
695 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
696 unless ($gs) {
697 die "Unable to determine upstream SVN information from ",
698 "$head history\n";
700 my $desired_revision = substr($revision_or_hash, 1);
701 $result = $gs->rev_map_get($desired_revision, $uuid);
702 } else {
703 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
704 $result = $rev;
706 print "$result\n" if $result;
709 sub cmd_rebase {
710 command_noisy(qw/update-index --refresh/);
711 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
712 unless ($gs) {
713 die "Unable to determine upstream SVN information from ",
714 "working tree history\n";
716 if ($_dry_run) {
717 print "Remote Branch: " . $gs->refname . "\n";
718 print "SVN URL: " . $url . "\n";
719 return;
721 if (command(qw/diff-index HEAD --/)) {
722 print STDERR "Cannot rebase with uncommited changes:\n";
723 command_noisy('status');
724 exit 1;
726 unless ($_local) {
727 # rebase will checkout for us, so no need to do it explicitly
728 $_no_checkout = 'true';
729 $_fetch_all ? $gs->fetch_all : $gs->fetch;
731 command_noisy(rebase_cmd(), $gs->refname);
734 sub cmd_show_ignore {
735 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
736 $gs ||= Git::SVN->new;
737 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
738 $gs->prop_walk($gs->{path}, $r, sub {
739 my ($gs, $path, $props) = @_;
740 print STDOUT "\n# $path\n";
741 my $s = $props->{'svn:ignore'} or return;
742 $s =~ s/[\r\n]+/\n/g;
743 chomp $s;
744 $s =~ s#^#$path#gm;
745 print STDOUT "$s\n";
749 sub cmd_show_externals {
750 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
751 $gs ||= Git::SVN->new;
752 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
753 $gs->prop_walk($gs->{path}, $r, sub {
754 my ($gs, $path, $props) = @_;
755 print STDOUT "\n# $path\n";
756 my $s = $props->{'svn:externals'} or return;
757 $s =~ s/[\r\n]+/\n/g;
758 chomp $s;
759 $s =~ s#^#$path#gm;
760 print STDOUT "$s\n";
764 sub cmd_create_ignore {
765 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
766 $gs ||= Git::SVN->new;
767 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
768 $gs->prop_walk($gs->{path}, $r, sub {
769 my ($gs, $path, $props) = @_;
770 # $path is of the form /path/to/dir/
771 $path = '.' . $path;
772 # SVN can have attributes on empty directories,
773 # which git won't track
774 mkpath([$path]) unless -d $path;
775 my $ignore = $path . '.gitignore';
776 my $s = $props->{'svn:ignore'} or return;
777 open(GITIGNORE, '>', $ignore)
778 or fatal("Failed to open `$ignore' for writing: $!");
779 $s =~ s/[\r\n]+/\n/g;
780 chomp $s;
781 # Prefix all patterns so that the ignore doesn't apply
782 # to sub-directories.
783 $s =~ s#^#/#gm;
784 print GITIGNORE "$s\n";
785 close(GITIGNORE)
786 or fatal("Failed to close `$ignore': $!");
787 command_noisy('add', '-f', $ignore);
791 sub canonicalize_path {
792 my ($path) = @_;
793 my $dot_slash_added = 0;
794 if (substr($path, 0, 1) ne "/") {
795 $path = "./" . $path;
796 $dot_slash_added = 1;
798 # File::Spec->canonpath doesn't collapse x/../y into y (for a
799 # good reason), so let's do this manually.
800 $path =~ s#/+#/#g;
801 $path =~ s#/\.(?:/|$)#/#g;
802 $path =~ s#/[^/]+/\.\.##g;
803 $path =~ s#/$##g;
804 $path =~ s#^\./## if $dot_slash_added;
805 $path =~ s#^/##;
806 $path =~ s#^\.$##;
807 return $path;
810 sub canonicalize_url {
811 my ($url) = @_;
812 $url =~ s#^([^:]+://[^/]*/)(.*)$#$1 . canonicalize_path($2)#e;
813 return $url;
816 # get_svnprops(PATH)
817 # ------------------
818 # Helper for cmd_propget and cmd_proplist below.
819 sub get_svnprops {
820 my $path = shift;
821 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
822 $gs ||= Git::SVN->new;
824 # prefix THE PATH by the sub-directory from which the user
825 # invoked us.
826 $path = $cmd_dir_prefix . $path;
827 fatal("No such file or directory: $path") unless -e $path;
828 my $is_dir = -d $path ? 1 : 0;
829 $path = $gs->{path} . '/' . $path;
831 # canonicalize the path (otherwise libsvn will abort or fail to
832 # find the file)
833 $path = canonicalize_path($path);
835 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
836 my $props;
837 if ($is_dir) {
838 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
840 else {
841 (undef, $props) = $gs->ra->get_file($path, $r, undef);
843 return $props;
846 # cmd_propget (PROP, PATH)
847 # ------------------------
848 # Print the SVN property PROP for PATH.
849 sub cmd_propget {
850 my ($prop, $path) = @_;
851 $path = '.' if not defined $path;
852 usage(1) if not defined $prop;
853 my $props = get_svnprops($path);
854 if (not defined $props->{$prop}) {
855 fatal("`$path' does not have a `$prop' SVN property.");
857 print $props->{$prop} . "\n";
860 # cmd_proplist (PATH)
861 # -------------------
862 # Print the list of SVN properties for PATH.
863 sub cmd_proplist {
864 my $path = shift;
865 $path = '.' if not defined $path;
866 my $props = get_svnprops($path);
867 print "Properties on '$path':\n";
868 foreach (sort keys %{$props}) {
869 print " $_\n";
873 sub cmd_multi_init {
874 my $url = shift;
875 unless (defined $_trunk || @_branches || @_tags) {
876 usage(1);
879 $_prefix = '' unless defined $_prefix;
880 if (defined $url) {
881 $url = canonicalize_url($url);
882 init_subdir(@_);
884 do_git_init_db();
885 if (defined $_trunk) {
886 my $trunk_ref = $_prefix . 'trunk';
887 # try both old-style and new-style lookups:
888 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
889 unless ($gs_trunk) {
890 my ($trunk_url, $trunk_path) =
891 complete_svn_url($url, $_trunk);
892 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
893 undef, $trunk_ref);
896 return unless @_branches || @_tags;
897 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
898 foreach my $path (@_branches) {
899 complete_url_ls_init($ra, $path, '--branches/-b', $_prefix);
901 foreach my $path (@_tags) {
902 complete_url_ls_init($ra, $path, '--tags/-t', $_prefix.'tags/');
906 sub cmd_multi_fetch {
907 my $remotes = Git::SVN::read_all_remotes();
908 foreach my $repo_id (sort keys %$remotes) {
909 if ($remotes->{$repo_id}->{url}) {
910 Git::SVN::fetch_all($repo_id, $remotes);
915 # this command is special because it requires no metadata
916 sub cmd_commit_diff {
917 my ($ta, $tb, $url) = @_;
918 my $usage = "Usage: $0 commit-diff -r<revision> ".
919 "<tree-ish> <tree-ish> [<URL>]";
920 fatal($usage) if (!defined $ta || !defined $tb);
921 my $svn_path = '';
922 if (!defined $url) {
923 my $gs = eval { Git::SVN->new };
924 if (!$gs) {
925 fatal("Needed URL or usable git-svn --id in ",
926 "the command-line\n", $usage);
928 $url = $gs->{url};
929 $svn_path = $gs->{path};
931 unless (defined $_revision) {
932 fatal("-r|--revision is a required argument\n", $usage);
934 if (defined $_message && defined $_file) {
935 fatal("Both --message/-m and --file/-F specified ",
936 "for the commit message.\n",
937 "I have no idea what you mean");
939 if (defined $_file) {
940 $_message = file_to_s($_file);
941 } else {
942 $_message ||= get_commit_entry($tb)->{log};
944 my $ra ||= Git::SVN::Ra->new($url);
945 my $r = $_revision;
946 if ($r eq 'HEAD') {
947 $r = $ra->get_latest_revnum;
948 } elsif ($r !~ /^\d+$/) {
949 die "revision argument: $r not understood by git-svn\n";
951 my %ed_opts = ( r => $r,
952 log => $_message,
953 ra => $ra,
954 tree_a => $ta,
955 tree_b => $tb,
956 editor_cb => sub { print "Committed r$_[0]\n" },
957 svn_path => $svn_path );
958 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
959 print "No changes\n$ta == $tb\n";
963 sub escape_uri_only {
964 my ($uri) = @_;
965 my @tmp;
966 foreach (split m{/}, $uri) {
967 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
968 push @tmp, $_;
970 join('/', @tmp);
973 sub escape_url {
974 my ($url) = @_;
975 if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
976 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
977 $url = "$scheme://$domain$uri";
979 $url;
982 sub cmd_info {
983 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
984 my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
985 if (exists $_[1]) {
986 die "Too many arguments specified\n";
989 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
991 if (!$file_type && !$diff_status) {
992 print STDERR "svn: '$path' is not under version control\n";
993 exit 1;
996 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
997 unless ($gs) {
998 die "Unable to determine upstream SVN information from ",
999 "working tree history\n";
1002 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
1003 $path = "." if $path eq "";
1005 my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
1007 if ($_url) {
1008 print escape_url($full_url), "\n";
1009 return;
1012 my $result = "Path: $path\n";
1013 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
1014 $result .= "URL: " . escape_url($full_url) . "\n";
1016 eval {
1017 my $repos_root = $gs->repos_root;
1018 Git::SVN::remove_username($repos_root);
1019 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
1021 if ($@) {
1022 $result .= "Repository Root: (offline)\n";
1024 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
1025 ($SVN::Core::VERSION le '1.5.4' || $file_type ne "dir");
1026 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
1028 $result .= "Node Kind: " .
1029 ($file_type eq "dir" ? "directory" : "file") . "\n";
1031 my $schedule = $diff_status eq "A"
1032 ? "add"
1033 : ($diff_status eq "D" ? "delete" : "normal");
1034 $result .= "Schedule: $schedule\n";
1036 if ($diff_status eq "A") {
1037 print $result, "\n";
1038 return;
1041 my ($lc_author, $lc_rev, $lc_date_utc);
1042 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
1043 my $log = command_output_pipe(@args);
1044 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
1045 while (<$log>) {
1046 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
1047 $lc_author = $1;
1048 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
1049 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
1050 (undef, $lc_rev, undef) = ::extract_metadata($1);
1053 close $log;
1055 Git::SVN::Log::set_local_timezone();
1057 $result .= "Last Changed Author: $lc_author\n";
1058 $result .= "Last Changed Rev: $lc_rev\n";
1059 $result .= "Last Changed Date: " .
1060 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
1062 if ($file_type ne "dir") {
1063 my $text_last_updated_date =
1064 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
1065 $result .=
1066 "Text Last Updated: " .
1067 Git::SVN::Log::format_svn_date($text_last_updated_date) .
1068 "\n";
1069 my $checksum;
1070 if ($diff_status eq "D") {
1071 my ($fh, $ctx) =
1072 command_output_pipe(qw(cat-file blob), "HEAD:$path");
1073 if ($file_type eq "link") {
1074 my $file_name = <$fh>;
1075 $checksum = md5sum("link $file_name");
1076 } else {
1077 $checksum = md5sum($fh);
1079 command_close_pipe($fh, $ctx);
1080 } elsif ($file_type eq "link") {
1081 my $file_name =
1082 command(qw(cat-file blob), "HEAD:$path");
1083 $checksum =
1084 md5sum("link " . $file_name);
1085 } else {
1086 open FILE, "<", $path or die $!;
1087 $checksum = md5sum(\*FILE);
1088 close FILE or die $!;
1090 $result .= "Checksum: " . $checksum . "\n";
1093 print $result, "\n";
1096 sub cmd_reset {
1097 my $target = shift || $_revision or die "SVN revision required\n";
1098 $target = $1 if $target =~ /^r(\d+)$/;
1099 $target =~ /^\d+$/ or die "Numeric SVN revision expected\n";
1100 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1101 unless ($gs) {
1102 die "Unable to determine upstream SVN information from ".
1103 "history\n";
1105 my ($r, $c) = $gs->find_rev_before($target, not $_fetch_parent);
1106 $gs->rev_map_set($r, $c, 'reset', $uuid);
1107 print "r$r = $c ($gs->{ref_id})\n";
1110 ########################### utility functions #########################
1112 sub rebase_cmd {
1113 my @cmd = qw/rebase/;
1114 push @cmd, '-v' if $_verbose;
1115 push @cmd, qw/--merge/ if $_merge;
1116 push @cmd, "--strategy=$_strategy" if $_strategy;
1117 @cmd;
1120 sub post_fetch_checkout {
1121 return if $_no_checkout;
1122 my $gs = $Git::SVN::_head or return;
1123 return if verify_ref('refs/heads/master^0');
1125 my $valid_head = verify_ref('HEAD^0');
1126 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1127 return if ($valid_head || !verify_ref('HEAD^0'));
1129 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1130 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1131 return if -f $index;
1133 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1134 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1135 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1136 print STDERR "Checked out HEAD:\n ",
1137 $gs->full_url, " r", $gs->last_rev, "\n";
1140 sub complete_svn_url {
1141 my ($url, $path) = @_;
1142 $path =~ s#/+$##;
1143 if ($path !~ m#^[a-z\+]+://#) {
1144 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1145 fatal("E: '$path' is not a complete URL ",
1146 "and a separate URL is not specified");
1148 return ($url, $path);
1150 return ($path, '');
1153 sub complete_url_ls_init {
1154 my ($ra, $repo_path, $switch, $pfx) = @_;
1155 unless ($repo_path) {
1156 print STDERR "W: $switch not specified\n";
1157 return;
1159 $repo_path =~ s#/+$##;
1160 if ($repo_path =~ m#^[a-z\+]+://#) {
1161 $ra = Git::SVN::Ra->new($repo_path);
1162 $repo_path = '';
1163 } else {
1164 $repo_path =~ s#^/+##;
1165 unless ($ra) {
1166 fatal("E: '$repo_path' is not a complete URL ",
1167 "and a separate URL is not specified");
1170 my $url = $ra->{url};
1171 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1172 my $k = "svn-remote.$gs->{repo_id}.url";
1173 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1174 if ($orig_url && ($orig_url ne $gs->{url})) {
1175 die "$k already set: $orig_url\n",
1176 "wanted to set to: $gs->{url}\n";
1178 command_oneline('config', $k, $gs->{url}) unless $orig_url;
1179 my $remote_path = "$gs->{path}/$repo_path";
1180 $remote_path =~ s#/+#/#g;
1181 $remote_path =~ s#^/##g;
1182 $remote_path .= "/*" if $remote_path !~ /\*/;
1183 my ($n) = ($switch =~ /^--(\w+)/);
1184 if (length $pfx && $pfx !~ m#/$#) {
1185 die "--prefix='$pfx' must have a trailing slash '/'\n";
1187 command_noisy('config',
1188 '--add',
1189 "svn-remote.$gs->{repo_id}.$n",
1190 "$remote_path:refs/remotes/$pfx*" .
1191 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1194 sub verify_ref {
1195 my ($ref) = @_;
1196 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1197 { STDERR => 0 }); };
1200 sub get_tree_from_treeish {
1201 my ($treeish) = @_;
1202 # $treeish can be a symbolic ref, too:
1203 my $type = command_oneline(qw/cat-file -t/, $treeish);
1204 my $expected;
1205 while ($type eq 'tag') {
1206 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1208 if ($type eq 'commit') {
1209 $expected = (grep /^tree /, command(qw/cat-file commit/,
1210 $treeish))[0];
1211 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1212 die "Unable to get tree from $treeish\n" unless $expected;
1213 } elsif ($type eq 'tree') {
1214 $expected = $treeish;
1215 } else {
1216 die "$treeish is a $type, expected tree, tag or commit\n";
1218 return $expected;
1221 sub get_commit_entry {
1222 my ($treeish) = shift;
1223 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1224 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1225 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1226 open my $log_fh, '>', $commit_editmsg or croak $!;
1228 my $type = command_oneline(qw/cat-file -t/, $treeish);
1229 if ($type eq 'commit' || $type eq 'tag') {
1230 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1231 $type, $treeish);
1232 my $in_msg = 0;
1233 my $author;
1234 my $saw_from = 0;
1235 my $msgbuf = "";
1236 while (<$msg_fh>) {
1237 if (!$in_msg) {
1238 $in_msg = 1 if (/^\s*$/);
1239 $author = $1 if (/^author (.*>)/);
1240 } elsif (/^git-svn-id: /) {
1241 # skip this for now, we regenerate the
1242 # correct one on re-fetch anyways
1243 # TODO: set *:merge properties or like...
1244 } else {
1245 if (/^From:/ || /^Signed-off-by:/) {
1246 $saw_from = 1;
1248 $msgbuf .= $_;
1251 $msgbuf =~ s/\s+$//s;
1252 if ($Git::SVN::_add_author_from && defined($author)
1253 && !$saw_from) {
1254 $msgbuf .= "\n\nFrom: $author";
1256 print $log_fh $msgbuf or croak $!;
1257 command_close_pipe($msg_fh, $ctx);
1259 close $log_fh or croak $!;
1261 if ($_edit || ($type eq 'tree')) {
1262 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1263 # TODO: strip out spaces, comments, like git-commit.sh
1264 system($editor, $commit_editmsg);
1266 rename $commit_editmsg, $commit_msg or croak $!;
1268 require Encode;
1269 # SVN requires messages to be UTF-8 when entering the repo
1270 local $/;
1271 open $log_fh, '<', $commit_msg or croak $!;
1272 binmode $log_fh;
1273 chomp($log_entry{log} = <$log_fh>);
1275 my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
1276 my $msg = $log_entry{log};
1278 eval { $msg = Encode::decode($enc, $msg, 1) };
1279 if ($@) {
1280 die "Could not decode as $enc:\n", $msg,
1281 "\nPerhaps you need to set i18n.commitencoding\n";
1284 eval { $msg = Encode::encode('UTF-8', $msg, 1) };
1285 die "Could not encode as UTF-8:\n$msg\n" if $@;
1287 $log_entry{log} = $msg;
1289 close $log_fh or croak $!;
1291 unlink $commit_msg;
1292 \%log_entry;
1295 sub s_to_file {
1296 my ($str, $file, $mode) = @_;
1297 open my $fd,'>',$file or croak $!;
1298 print $fd $str,"\n" or croak $!;
1299 close $fd or croak $!;
1300 chmod ($mode &~ umask, $file) if (defined $mode);
1303 sub file_to_s {
1304 my $file = shift;
1305 open my $fd,'<',$file or croak "$!: file: $file\n";
1306 local $/;
1307 my $ret = <$fd>;
1308 close $fd or croak $!;
1309 $ret =~ s/\s*$//s;
1310 return $ret;
1313 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1314 sub load_authors {
1315 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1316 my $log = $cmd eq 'log';
1317 while (<$authors>) {
1318 chomp;
1319 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1320 my ($user, $name, $email) = ($1, $2, $3);
1321 if ($log) {
1322 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1323 } else {
1324 $users{$user} = [$name, $email];
1327 close $authors or croak $!;
1330 # convert GetOpt::Long specs for use by git-config
1331 sub read_repo_config {
1332 return unless -d $ENV{GIT_DIR};
1333 my $opts = shift;
1334 my @config_only;
1335 foreach my $o (keys %$opts) {
1336 # if we have mixedCase and a long option-only, then
1337 # it's a config-only variable that we don't need for
1338 # the command-line.
1339 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1340 my $v = $opts->{$o};
1341 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1342 $key =~ s/-//g;
1343 my $arg = 'git config';
1344 $arg .= ' --int' if ($o =~ /[:=]i$/);
1345 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1346 if (ref $v eq 'ARRAY') {
1347 chomp(my @tmp = `$arg --get-all svn.$key`);
1348 @$v = @tmp if @tmp;
1349 } else {
1350 chomp(my $tmp = `$arg --get svn.$key`);
1351 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1352 $$v = $tmp;
1356 delete @$opts{@config_only} if @config_only;
1359 sub extract_metadata {
1360 my $id = shift or return (undef, undef, undef);
1361 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1362 \s([a-f\d\-]+)$/ix);
1363 if (!defined $rev || !$uuid || !$url) {
1364 # some of the original repositories I made had
1365 # identifiers like this:
1366 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/i);
1368 return ($url, $rev, $uuid);
1371 sub cmt_metadata {
1372 return extract_metadata((grep(/^git-svn-id: /,
1373 command(qw/cat-file commit/, shift)))[-1]);
1376 sub cmt_sha2rev_batch {
1377 my %s2r;
1378 my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1379 my $list = shift;
1381 foreach my $sha (@{$list}) {
1382 my $first = 1;
1383 my $size = 0;
1384 print $out $sha, "\n";
1386 while (my $line = <$in>) {
1387 if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1388 last;
1389 } elsif ($first &&
1390 $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1391 $first = 0;
1392 $size = $1;
1393 next;
1394 } elsif ($line =~ /^(git-svn-id: )/) {
1395 my (undef, $rev, undef) =
1396 extract_metadata($line);
1397 $s2r{$sha} = $rev;
1400 $size -= length($line);
1401 last if ($size == 0);
1405 command_close_bidi_pipe($pid, $in, $out, $ctx);
1407 return \%s2r;
1410 sub working_head_info {
1411 my ($head, $refs) = @_;
1412 my @args = ('log', '--no-color', '--first-parent', '--pretty=medium');
1413 my ($fh, $ctx) = command_output_pipe(@args, $head);
1414 my $hash;
1415 my %max;
1416 while (<$fh>) {
1417 if ( m{^commit ($::sha1)$} ) {
1418 unshift @$refs, $hash if $hash and $refs;
1419 $hash = $1;
1420 next;
1422 next unless s{^\s*(git-svn-id:)}{$1};
1423 my ($url, $rev, $uuid) = extract_metadata($_);
1424 if (defined $url && defined $rev) {
1425 next if $max{$url} and $max{$url} < $rev;
1426 if (my $gs = Git::SVN->find_by_url($url)) {
1427 my $c = $gs->rev_map_get($rev, $uuid);
1428 if ($c && $c eq $hash) {
1429 close $fh; # break the pipe
1430 return ($url, $rev, $uuid, $gs);
1431 } else {
1432 $max{$url} ||= $gs->rev_map_max;
1437 command_close_pipe($fh, $ctx);
1438 (undef, undef, undef, undef);
1441 sub read_commit_parents {
1442 my ($parents, $c) = @_;
1443 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1444 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1445 @{$parents->{$c}} = split(/ /, $p);
1448 sub linearize_history {
1449 my ($gs, $refs) = @_;
1450 my %parents;
1451 foreach my $c (@$refs) {
1452 read_commit_parents(\%parents, $c);
1455 my @linear_refs;
1456 my %skip = ();
1457 my $last_svn_commit = $gs->last_commit;
1458 foreach my $c (reverse @$refs) {
1459 next if $c eq $last_svn_commit;
1460 last if $skip{$c};
1462 unshift @linear_refs, $c;
1463 $skip{$c} = 1;
1465 # we only want the first parent to diff against for linear
1466 # history, we save the rest to inject when we finalize the
1467 # svn commit
1468 my $fp_a = verify_ref("$c~1");
1469 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1470 if (!$fp_a || !$fp_b) {
1471 die "Commit $c\n",
1472 "has no parent commit, and therefore ",
1473 "nothing to diff against.\n",
1474 "You should be working from a repository ",
1475 "originally created by git-svn\n";
1477 if ($fp_a ne $fp_b) {
1478 die "$c~1 = $fp_a, however parsing commit $c ",
1479 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1482 foreach my $p (@{$parents{$c}}) {
1483 $skip{$p} = 1;
1486 (\@linear_refs, \%parents);
1489 sub find_file_type_and_diff_status {
1490 my ($path) = @_;
1491 return ('dir', '') if $path eq '';
1493 my $diff_output =
1494 command_oneline(qw(diff --cached --name-status --), $path) || "";
1495 my $diff_status = (split(' ', $diff_output))[0] || "";
1497 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1499 return (undef, undef) if !$diff_status && !$ls_tree;
1501 if ($diff_status eq "A") {
1502 return ("link", $diff_status) if -l $path;
1503 return ("dir", $diff_status) if -d $path;
1504 return ("file", $diff_status);
1507 my $mode = (split(' ', $ls_tree))[0] || "";
1509 return ("link", $diff_status) if $mode eq "120000";
1510 return ("dir", $diff_status) if $mode eq "040000";
1511 return ("file", $diff_status);
1514 sub md5sum {
1515 my $arg = shift;
1516 my $ref = ref $arg;
1517 my $md5 = Digest::MD5->new();
1518 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
1519 $md5->addfile($arg) or croak $!;
1520 } elsif ($ref eq 'SCALAR') {
1521 $md5->add($$arg) or croak $!;
1522 } elsif (!$ref) {
1523 $md5->add($arg) or croak $!;
1524 } else {
1525 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1527 return $md5->hexdigest();
1530 package Git::SVN;
1531 use strict;
1532 use warnings;
1533 use Fcntl qw/:DEFAULT :seek/;
1534 use constant rev_map_fmt => 'NH40';
1535 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1536 $_repack $_repack_flags $_use_svm_props $_head
1537 $_use_svnsync_props $no_reuse_existing $_minimize_url
1538 $_use_log_author $_add_author_from $_localtime/;
1539 use Carp qw/croak/;
1540 use File::Path qw/mkpath/;
1541 use File::Copy qw/copy/;
1542 use IPC::Open3;
1544 my ($_gc_nr, $_gc_period);
1546 # properties that we do not log:
1547 my %SKIP_PROP;
1548 BEGIN {
1549 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1550 svn:special svn:executable
1551 svn:entry:committed-rev
1552 svn:entry:last-author
1553 svn:entry:uuid
1554 svn:entry:committed-date/;
1556 # some options are read globally, but can be overridden locally
1557 # per [svn-remote "..."] section. Command-line options will *NOT*
1558 # override options set in an [svn-remote "..."] section
1559 no strict 'refs';
1560 for my $option (qw/follow_parent no_metadata use_svm_props
1561 use_svnsync_props/) {
1562 my $key = $option;
1563 $key =~ tr/_//d;
1564 my $prop = "-$option";
1565 *$option = sub {
1566 my ($self) = @_;
1567 return $self->{$prop} if exists $self->{$prop};
1568 my $k = "svn-remote.$self->{repo_id}.$key";
1569 eval { command_oneline(qw/config --get/, $k) };
1570 if ($@) {
1571 $self->{$prop} = ${"Git::SVN::_$option"};
1572 } else {
1573 my $v = command_oneline(qw/config --bool/,$k);
1574 $self->{$prop} = $v eq 'false' ? 0 : 1;
1576 return $self->{$prop};
1582 my (%LOCKFILES, %INDEX_FILES);
1583 END {
1584 unlink keys %LOCKFILES if %LOCKFILES;
1585 unlink keys %INDEX_FILES if %INDEX_FILES;
1588 sub resolve_local_globs {
1589 my ($url, $fetch, $glob_spec) = @_;
1590 return unless defined $glob_spec;
1591 my $ref = $glob_spec->{ref};
1592 my $path = $glob_spec->{path};
1593 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
1594 next unless m#^refs/remotes/$ref->{regex}$#;
1595 my $p = $1;
1596 my $pathname = desanitize_refname($path->full_path($p));
1597 my $refname = desanitize_refname($ref->full_path($p));
1598 if (my $existing = $fetch->{$pathname}) {
1599 if ($existing ne $refname) {
1600 die "Refspec conflict:\n",
1601 "existing: refs/remotes/$existing\n",
1602 " globbed: refs/remotes/$refname\n";
1604 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
1605 $u =~ s!^\Q$url\E(/|$)!! or die
1606 "refs/remotes/$refname: '$url' not found in '$u'\n";
1607 if ($pathname ne $u) {
1608 warn "W: Refspec glob conflict ",
1609 "(ref: refs/remotes/$refname):\n",
1610 "expected path: $pathname\n",
1611 " real path: $u\n",
1612 "Continuing ahead with $u\n";
1613 next;
1615 } else {
1616 $fetch->{$pathname} = $refname;
1621 sub parse_revision_argument {
1622 my ($base, $head) = @_;
1623 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1624 return ($base, $head);
1626 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1627 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1628 return ($head, $head) if ($::_revision eq 'HEAD');
1629 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1630 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1631 die "revision argument: $::_revision not understood by git-svn\n";
1634 sub fetch_all {
1635 my ($repo_id, $remotes) = @_;
1636 if (ref $repo_id) {
1637 my $gs = $repo_id;
1638 $repo_id = undef;
1639 $repo_id = $gs->{repo_id};
1641 $remotes ||= read_all_remotes();
1642 my $remote = $remotes->{$repo_id} or
1643 die "[svn-remote \"$repo_id\"] unknown\n";
1644 my $fetch = $remote->{fetch};
1645 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1646 my (@gs, @globs);
1647 my $ra = Git::SVN::Ra->new($url);
1648 my $uuid = $ra->get_uuid;
1649 my $head = $ra->get_latest_revnum;
1650 $ra->get_log("", $head, 0, 1, 0, 1, sub { $head = $_[1] });
1651 my $base = defined $fetch ? $head : 0;
1653 # read the max revs for wildcard expansion (branches/*, tags/*)
1654 foreach my $t (qw/branches tags/) {
1655 defined $remote->{$t} or next;
1656 push @globs, @{$remote->{$t}};
1658 my $max_rev = eval { tmp_config(qw/--int --get/,
1659 "svn-remote.$repo_id.${t}-maxRev") };
1660 if (defined $max_rev && ($max_rev < $base)) {
1661 $base = $max_rev;
1662 } elsif (!defined $max_rev) {
1663 $base = 0;
1667 if ($fetch) {
1668 foreach my $p (sort keys %$fetch) {
1669 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1670 my $lr = $gs->rev_map_max;
1671 if (defined $lr) {
1672 $base = $lr if ($lr < $base);
1674 push @gs, $gs;
1678 ($base, $head) = parse_revision_argument($base, $head);
1679 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1682 sub read_all_remotes {
1683 my $r = {};
1684 my $use_svm_props = eval { command_oneline(qw/config --bool
1685 svn.useSvmProps/) };
1686 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
1687 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1688 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*(.+)\s*$!) {
1689 my ($remote, $local_ref, $_remote_ref) = ($1, $2, $3);
1690 die("svn-remote.$remote: remote ref '$_remote_ref' "
1691 . "must start with 'refs/remotes/'\n")
1692 unless $_remote_ref =~ m{^refs/remotes/(.+)};
1693 my $remote_ref = $1;
1694 $local_ref =~ s{^/}{};
1695 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1696 $r->{$remote}->{svm} = {} if $use_svm_props;
1697 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
1698 $r->{$1}->{svm} = {};
1699 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1700 $r->{$1}->{url} = $2;
1701 } elsif (m!^(.+)\.(branches|tags)=
1702 (.*):refs/remotes/(.+)\s*$/!x) {
1703 my ($p, $g) = ($3, $4);
1704 my $rs = {
1705 t => $2,
1706 remote => $1,
1707 path => Git::SVN::GlobSpec->new($p),
1708 ref => Git::SVN::GlobSpec->new($g) };
1709 if (length($rs->{ref}->{right}) != 0) {
1710 die "The '*' glob character must be the last ",
1711 "character of '$g'\n";
1713 push @{ $r->{$1}->{$2} }, $rs;
1717 map {
1718 if (defined $r->{$_}->{svm}) {
1719 my $svm;
1720 eval {
1721 my $section = "svn-remote.$_";
1722 $svm = {
1723 source => tmp_config('--get',
1724 "$section.svm-source"),
1725 replace => tmp_config('--get',
1726 "$section.svm-replace"),
1729 $r->{$_}->{svm} = $svm;
1731 } keys %$r;
1736 sub init_vars {
1737 $_gc_nr = $_gc_period = 1000;
1738 if (defined $_repack || defined $_repack_flags) {
1739 warn "Repack options are obsolete; they have no effect.\n";
1743 sub verify_remotes_sanity {
1744 return unless -d $ENV{GIT_DIR};
1745 my %seen;
1746 foreach (command(qw/config -l/)) {
1747 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1748 if ($seen{$1}) {
1749 die "Remote ref refs/remote/$1 is tracked by",
1750 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1751 "Please resolve this ambiguity in ",
1752 "your git configuration file before ",
1753 "continuing\n";
1755 $seen{$1} = $_;
1760 sub find_existing_remote {
1761 my ($url, $remotes) = @_;
1762 return undef if $no_reuse_existing;
1763 my $existing;
1764 foreach my $repo_id (keys %$remotes) {
1765 my $u = $remotes->{$repo_id}->{url} or next;
1766 next if $u ne $url;
1767 $existing = $repo_id;
1768 last;
1770 $existing;
1773 sub init_remote_config {
1774 my ($self, $url, $no_write) = @_;
1775 $url =~ s!/+$!!; # strip trailing slash
1776 my $r = read_all_remotes();
1777 my $existing = find_existing_remote($url, $r);
1778 if ($existing) {
1779 unless ($no_write) {
1780 print STDERR "Using existing ",
1781 "[svn-remote \"$existing\"]\n";
1783 $self->{repo_id} = $existing;
1784 } elsif ($_minimize_url) {
1785 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1786 $existing = find_existing_remote($min_url, $r);
1787 if ($existing) {
1788 unless ($no_write) {
1789 print STDERR "Using existing ",
1790 "[svn-remote \"$existing\"]\n";
1792 $self->{repo_id} = $existing;
1794 if ($min_url ne $url) {
1795 unless ($no_write) {
1796 print STDERR "Using higher level of URL: ",
1797 "$url => $min_url\n";
1799 my $old_path = $self->{path};
1800 $self->{path} = $url;
1801 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1802 if (length $old_path) {
1803 $self->{path} .= "/$old_path";
1805 $url = $min_url;
1808 my $orig_url;
1809 if (!$existing) {
1810 # verify that we aren't overwriting anything:
1811 $orig_url = eval {
1812 command_oneline('config', '--get',
1813 "svn-remote.$self->{repo_id}.url")
1815 if ($orig_url && ($orig_url ne $url)) {
1816 die "svn-remote.$self->{repo_id}.url already set: ",
1817 "$orig_url\nwanted to set to: $url\n";
1820 my ($xrepo_id, $xpath) = find_ref($self->refname);
1821 if (defined $xpath) {
1822 die "svn-remote.$xrepo_id.fetch already set to track ",
1823 "$xpath:refs/remotes/", $self->refname, "\n";
1825 unless ($no_write) {
1826 command_noisy('config',
1827 "svn-remote.$self->{repo_id}.url", $url);
1828 $self->{path} =~ s{^/}{};
1829 command_noisy('config', '--add',
1830 "svn-remote.$self->{repo_id}.fetch",
1831 "$self->{path}:".$self->refname);
1833 $self->{url} = $url;
1836 sub find_by_url { # repos_root and, path are optional
1837 my ($class, $full_url, $repos_root, $path) = @_;
1839 return undef unless defined $full_url;
1840 remove_username($full_url);
1841 remove_username($repos_root) if defined $repos_root;
1842 my $remotes = read_all_remotes();
1843 if (defined $full_url && defined $repos_root && !defined $path) {
1844 $path = $full_url;
1845 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1847 foreach my $repo_id (keys %$remotes) {
1848 my $u = $remotes->{$repo_id}->{url} or next;
1849 remove_username($u);
1850 next if defined $repos_root && $repos_root ne $u;
1852 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1853 foreach my $t (qw/branches tags/) {
1854 foreach my $globspec (@{$remotes->{$repo_id}->{$t}}) {
1855 resolve_local_globs($u, $fetch, $globspec);
1858 my $p = $path;
1859 my $rwr = rewrite_root({repo_id => $repo_id});
1860 my $svm = $remotes->{$repo_id}->{svm}
1861 if defined $remotes->{$repo_id}->{svm};
1862 unless (defined $p) {
1863 $p = $full_url;
1864 my $z = $u;
1865 my $prefix = '';
1866 if ($rwr) {
1867 $z = $rwr;
1868 remove_username($z);
1869 } elsif (defined $svm) {
1870 $z = $svm->{source};
1871 $prefix = $svm->{replace};
1872 $prefix =~ s#^\Q$u\E(?:/|$)##;
1873 $prefix =~ s#/$##;
1875 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
1877 foreach my $f (keys %$fetch) {
1878 next if $f ne $p;
1879 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1882 undef;
1885 sub init {
1886 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1887 my $self = _new($class, $repo_id, $ref_id, $path);
1888 if (defined $url) {
1889 $self->init_remote_config($url, $no_write);
1891 $self;
1894 sub find_ref {
1895 my ($ref_id) = @_;
1896 foreach (command(qw/config -l/)) {
1897 next unless m!^svn-remote\.(.+)\.fetch=
1898 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1899 my ($repo_id, $path, $ref) = ($1, $2, $3);
1900 if ($ref eq $ref_id) {
1901 $path = '' if ($path =~ m#^\./?#);
1902 return ($repo_id, $path);
1905 (undef, undef, undef);
1908 sub new {
1909 my ($class, $ref_id, $repo_id, $path) = @_;
1910 if (defined $ref_id && !defined $repo_id && !defined $path) {
1911 ($repo_id, $path) = find_ref($ref_id);
1912 if (!defined $repo_id) {
1913 die "Could not find a \"svn-remote.*.fetch\" key ",
1914 "in the repository configuration matching: ",
1915 "refs/remotes/$ref_id\n";
1918 my $self = _new($class, $repo_id, $ref_id, $path);
1919 if (!defined $self->{path} || !length $self->{path}) {
1920 my $fetch = command_oneline('config', '--get',
1921 "svn-remote.$repo_id.fetch",
1922 ":refs/remotes/$ref_id\$") or
1923 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1924 "\":refs/remotes/$ref_id\$\" in config\n";
1925 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1927 $self->{url} = command_oneline('config', '--get',
1928 "svn-remote.$repo_id.url") or
1929 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1930 $self->rebuild;
1931 $self;
1934 sub refname {
1935 my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1937 # It cannot end with a slash /, we'll throw up on this because
1938 # SVN can't have directories with a slash in their name, either:
1939 if ($refname =~ m{/$}) {
1940 die "ref: '$refname' ends with a trailing slash, this is ",
1941 "not permitted by git nor Subversion\n";
1944 # It cannot have ASCII control character space, tilde ~, caret ^,
1945 # colon :, question-mark ?, asterisk *, space, or open bracket [
1946 # anywhere.
1948 # Additionally, % must be escaped because it is used for escaping
1949 # and we want our escaped refname to be reversible
1950 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1952 # no slash-separated component can begin with a dot .
1953 # /.* becomes /%2E*
1954 $refname =~ s{/\.}{/%2E}g;
1956 # It cannot have two consecutive dots .. anywhere
1957 # .. becomes %2E%2E
1958 $refname =~ s{\.\.}{%2E%2E}g;
1960 return $refname;
1963 sub desanitize_refname {
1964 my ($refname) = @_;
1965 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1966 return $refname;
1969 sub svm_uuid {
1970 my ($self) = @_;
1971 return $self->{svm}->{uuid} if $self->svm;
1972 $self->ra;
1973 unless ($self->{svm}) {
1974 die "SVM UUID not cached, and reading remotely failed\n";
1976 $self->{svm}->{uuid};
1979 sub svm {
1980 my ($self) = @_;
1981 return $self->{svm} if $self->{svm};
1982 my $svm;
1983 # see if we have it in our config, first:
1984 eval {
1985 my $section = "svn-remote.$self->{repo_id}";
1986 $svm = {
1987 source => tmp_config('--get', "$section.svm-source"),
1988 uuid => tmp_config('--get', "$section.svm-uuid"),
1989 replace => tmp_config('--get', "$section.svm-replace"),
1992 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1993 $self->{svm} = $svm;
1995 $self->{svm};
1998 sub _set_svm_vars {
1999 my ($self, $ra) = @_;
2000 return $ra if $self->svm;
2002 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
2003 "(svm:source, svm:uuid) ",
2004 "from the following URLs:\n" );
2005 sub read_svm_props {
2006 my ($self, $ra, $path, $r) = @_;
2007 my $props = ($ra->get_dir($path, $r))[2];
2008 my $src = $props->{'svm:source'};
2009 my $uuid = $props->{'svm:uuid'};
2010 return undef if (!$src || !$uuid);
2012 chomp($src, $uuid);
2014 $uuid =~ m{^[0-9a-f\-]{30,}$}i
2015 or die "doesn't look right - svm:uuid is '$uuid'\n";
2017 # the '!' is used to mark the repos_root!/relative/path
2018 $src =~ s{/?!/?}{/};
2019 $src =~ s{/+$}{}; # no trailing slashes please
2020 # username is of no interest
2021 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
2023 my $replace = $ra->{url};
2024 $replace .= "/$path" if length $path;
2026 my $section = "svn-remote.$self->{repo_id}";
2027 tmp_config("$section.svm-source", $src);
2028 tmp_config("$section.svm-replace", $replace);
2029 tmp_config("$section.svm-uuid", $uuid);
2030 $self->{svm} = {
2031 source => $src,
2032 uuid => $uuid,
2033 replace => $replace
2037 my $r = $ra->get_latest_revnum;
2038 my $path = $self->{path};
2039 my %tried;
2040 while (length $path) {
2041 unless ($tried{"$self->{url}/$path"}) {
2042 return $ra if $self->read_svm_props($ra, $path, $r);
2043 $tried{"$self->{url}/$path"} = 1;
2045 $path =~ s#/?[^/]+$##;
2047 die "Path: '$path' should be ''\n" if $path ne '';
2048 return $ra if $self->read_svm_props($ra, $path, $r);
2049 $tried{"$self->{url}/$path"} = 1;
2051 if ($ra->{repos_root} eq $self->{url}) {
2052 die @err, (map { " $_\n" } keys %tried), "\n";
2055 # nope, make sure we're connected to the repository root:
2056 my $ok;
2057 my @tried_b;
2058 $path = $ra->{svn_path};
2059 $ra = Git::SVN::Ra->new($ra->{repos_root});
2060 while (length $path) {
2061 unless ($tried{"$ra->{url}/$path"}) {
2062 $ok = $self->read_svm_props($ra, $path, $r);
2063 last if $ok;
2064 $tried{"$ra->{url}/$path"} = 1;
2066 $path =~ s#/?[^/]+$##;
2068 die "Path: '$path' should be ''\n" if $path ne '';
2069 $ok ||= $self->read_svm_props($ra, $path, $r);
2070 $tried{"$ra->{url}/$path"} = 1;
2071 if (!$ok) {
2072 die @err, (map { " $_\n" } keys %tried), "\n";
2074 Git::SVN::Ra->new($self->{url});
2077 sub svnsync {
2078 my ($self) = @_;
2079 return $self->{svnsync} if $self->{svnsync};
2081 if ($self->no_metadata) {
2082 die "Can't have both 'noMetadata' and ",
2083 "'useSvnsyncProps' options set!\n";
2085 if ($self->rewrite_root) {
2086 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
2087 "options set!\n";
2090 my $svnsync;
2091 # see if we have it in our config, first:
2092 eval {
2093 my $section = "svn-remote.$self->{repo_id}";
2095 my $url = tmp_config('--get', "$section.svnsync-url");
2096 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2097 die "doesn't look right - svn:sync-from-url is '$url'\n";
2099 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
2100 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2101 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2103 $svnsync = { url => $url, uuid => $uuid }
2105 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
2106 return $self->{svnsync} = $svnsync;
2109 my $err = "useSvnsyncProps set, but failed to read " .
2110 "svnsync property: svn:sync-from-";
2111 my $rp = $self->ra->rev_proplist(0);
2113 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
2114 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2115 die "doesn't look right - svn:sync-from-url is '$url'\n";
2117 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
2118 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2119 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2121 my $section = "svn-remote.$self->{repo_id}";
2122 tmp_config('--add', "$section.svnsync-uuid", $uuid);
2123 tmp_config('--add', "$section.svnsync-url", $url);
2124 return $self->{svnsync} = { url => $url, uuid => $uuid };
2127 # this allows us to memoize our SVN::Ra UUID locally and avoid a
2128 # remote lookup (useful for 'git svn log').
2129 sub ra_uuid {
2130 my ($self) = @_;
2131 unless ($self->{ra_uuid}) {
2132 my $key = "svn-remote.$self->{repo_id}.uuid";
2133 my $uuid = eval { tmp_config('--get', $key) };
2134 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/i) {
2135 $self->{ra_uuid} = $uuid;
2136 } else {
2137 die "ra_uuid called without URL\n" unless $self->{url};
2138 $self->{ra_uuid} = $self->ra->get_uuid;
2139 tmp_config('--add', $key, $self->{ra_uuid});
2142 $self->{ra_uuid};
2145 sub _set_repos_root {
2146 my ($self, $repos_root) = @_;
2147 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2148 $repos_root ||= $self->ra->{repos_root};
2149 tmp_config($k, $repos_root);
2150 $repos_root;
2153 sub repos_root {
2154 my ($self) = @_;
2155 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2156 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
2159 sub ra {
2160 my ($self) = shift;
2161 my $ra = Git::SVN::Ra->new($self->{url});
2162 $self->_set_repos_root($ra->{repos_root});
2163 if ($self->use_svm_props && !$self->{svm}) {
2164 if ($self->no_metadata) {
2165 die "Can't have both 'noMetadata' and ",
2166 "'useSvmProps' options set!\n";
2167 } elsif ($self->use_svnsync_props) {
2168 die "Can't have both 'useSvnsyncProps' and ",
2169 "'useSvmProps' options set!\n";
2171 $ra = $self->_set_svm_vars($ra);
2172 $self->{-want_revprops} = 1;
2174 $ra;
2177 # prop_walk(PATH, REV, SUB)
2178 # -------------------------
2179 # Recursively traverse PATH at revision REV and invoke SUB for each
2180 # directory that contains a SVN property. SUB will be invoked as
2181 # follows: &SUB(gs, path, props); where `gs' is this instance of
2182 # Git::SVN, `path' the path to the directory where the properties
2183 # `props' were found. The `path' will be relative to point of checkout,
2184 # that is, if url://repo/trunk is the current Git branch, and that
2185 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
2186 # as `path' (note the trailing `/').
2187 sub prop_walk {
2188 my ($self, $path, $rev, $sub) = @_;
2190 $path =~ s#^/##;
2191 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2192 $path =~ s#^/*#/#g;
2193 my $p = $path;
2194 # Strip the irrelevant part of the path.
2195 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2196 # Ensure the path is terminated by a `/'.
2197 $p =~ s#/*$#/#;
2199 # The properties contain all the internal SVN stuff nobody
2200 # (usually) cares about.
2201 my $interesting_props = 0;
2202 foreach (keys %{$props}) {
2203 # If it doesn't start with `svn:', it must be a
2204 # user-defined property.
2205 ++$interesting_props and next if $_ !~ /^svn:/;
2206 # FIXME: Fragile, if SVN adds new public properties,
2207 # this needs to be updated.
2208 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2209 |eol-style|mime-type
2210 |externals|needs-lock)$/x;
2212 &$sub($self, $p, $props) if $interesting_props;
2214 foreach (sort keys %$dirent) {
2215 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
2216 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
2220 sub last_rev { ($_[0]->last_rev_commit)[0] }
2221 sub last_commit { ($_[0]->last_rev_commit)[1] }
2223 # returns the newest SVN revision number and newest commit SHA1
2224 sub last_rev_commit {
2225 my ($self) = @_;
2226 if (defined $self->{last_rev} && defined $self->{last_commit}) {
2227 return ($self->{last_rev}, $self->{last_commit});
2229 my $c = ::verify_ref($self->refname.'^0');
2230 if ($c && !$self->use_svm_props && !$self->no_metadata) {
2231 my $rev = (::cmt_metadata($c))[1];
2232 if (defined $rev) {
2233 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2234 return ($rev, $c);
2237 my $map_path = $self->map_path;
2238 unless (-e $map_path) {
2239 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2240 return (undef, undef);
2242 my ($rev, $commit) = $self->rev_map_max(1);
2243 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2244 return ($rev, $commit);
2247 sub get_fetch_range {
2248 my ($self, $min, $max) = @_;
2249 $max ||= $self->ra->get_latest_revnum;
2250 $min ||= $self->rev_map_max;
2251 (++$min, $max);
2254 sub tmp_config {
2255 my (@args) = @_;
2256 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2257 my $config = "$ENV{GIT_DIR}/svn/.metadata";
2258 if (! -f $config && -f $old_def_config) {
2259 rename $old_def_config, $config or
2260 die "Failed rename $old_def_config => $config: $!\n";
2262 my $old_config = $ENV{GIT_CONFIG};
2263 $ENV{GIT_CONFIG} = $config;
2264 $@ = undef;
2265 my @ret = eval {
2266 unless (-f $config) {
2267 mkfile($config);
2268 open my $fh, '>', $config or
2269 die "Can't open $config: $!\n";
2270 print $fh "; This file is used internally by ",
2271 "git-svn\n" or die
2272 "Couldn't write to $config: $!\n";
2273 print $fh "; You should not have to edit it\n" or
2274 die "Couldn't write to $config: $!\n";
2275 close $fh or die "Couldn't close $config: $!\n";
2277 command('config', @args);
2279 my $err = $@;
2280 if (defined $old_config) {
2281 $ENV{GIT_CONFIG} = $old_config;
2282 } else {
2283 delete $ENV{GIT_CONFIG};
2285 die $err if $err;
2286 wantarray ? @ret : $ret[0];
2289 sub tmp_index_do {
2290 my ($self, $sub) = @_;
2291 my $old_index = $ENV{GIT_INDEX_FILE};
2292 $ENV{GIT_INDEX_FILE} = $self->{index};
2293 $@ = undef;
2294 my @ret = eval {
2295 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2296 mkpath([$dir]) unless -d $dir;
2297 &$sub;
2299 my $err = $@;
2300 if (defined $old_index) {
2301 $ENV{GIT_INDEX_FILE} = $old_index;
2302 } else {
2303 delete $ENV{GIT_INDEX_FILE};
2305 die $err if $err;
2306 wantarray ? @ret : $ret[0];
2309 sub assert_index_clean {
2310 my ($self, $treeish) = @_;
2312 $self->tmp_index_do(sub {
2313 command_noisy('read-tree', $treeish) unless -e $self->{index};
2314 my $x = command_oneline('write-tree');
2315 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2316 /^tree ($::sha1)/mo);
2317 return if $y eq $x;
2319 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2320 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2321 command_noisy('read-tree', $treeish);
2322 $x = command_oneline('write-tree');
2323 if ($y ne $x) {
2324 ::fatal "trees ($treeish) $y != $x\n",
2325 "Something is seriously wrong...";
2330 sub get_commit_parents {
2331 my ($self, $log_entry) = @_;
2332 my (%seen, @ret, @tmp);
2333 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2334 if (my $ip = $self->{inject_parents}) {
2335 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2336 push @tmp, $commit;
2339 if (my $cur = ::verify_ref($self->refname.'^0')) {
2340 push @tmp, $cur;
2342 if (my $ipd = $self->{inject_parents_dcommit}) {
2343 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2344 push @tmp, @$commit;
2347 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2348 while (my $p = shift @tmp) {
2349 next if $seen{$p};
2350 $seen{$p} = 1;
2351 push @ret, $p;
2352 # MAXPARENT is defined to 16 in commit-tree.c:
2353 last if @ret >= 16;
2355 if (@tmp) {
2356 die "r$log_entry->{revision}: No room for parents:\n\t",
2357 join("\n\t", @tmp), "\n";
2359 @ret;
2362 sub rewrite_root {
2363 my ($self) = @_;
2364 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2365 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2366 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2367 if ($rwr) {
2368 $rwr =~ s#/+$##;
2369 if ($rwr !~ m#^[a-z\+]+://#) {
2370 die "$rwr is not a valid URL (key: $k)\n";
2373 $self->{-rewrite_root} = $rwr;
2376 sub metadata_url {
2377 my ($self) = @_;
2378 ($self->rewrite_root || $self->{url}) .
2379 (length $self->{path} ? '/' . $self->{path} : '');
2382 sub full_url {
2383 my ($self) = @_;
2384 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2388 sub set_commit_header_env {
2389 my ($log_entry) = @_;
2390 my %env;
2391 foreach my $ned (qw/NAME EMAIL DATE/) {
2392 foreach my $ac (qw/AUTHOR COMMITTER/) {
2393 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2397 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2398 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2399 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2401 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2402 ? $log_entry->{commit_name}
2403 : $log_entry->{name};
2404 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2405 ? $log_entry->{commit_email}
2406 : $log_entry->{email};
2407 \%env;
2410 sub restore_commit_header_env {
2411 my ($env) = @_;
2412 foreach my $ned (qw/NAME EMAIL DATE/) {
2413 foreach my $ac (qw/AUTHOR COMMITTER/) {
2414 my $k = "GIT_${ac}_${ned}";
2415 if (defined $env->{$k}) {
2416 $ENV{$k} = $env->{$k};
2417 } else {
2418 delete $ENV{$k};
2424 sub gc {
2425 command_noisy('gc', '--auto');
2428 sub do_git_commit {
2429 my ($self, $log_entry) = @_;
2430 my $lr = $self->last_rev;
2431 if (defined $lr && $lr >= $log_entry->{revision}) {
2432 die "Last fetched revision of ", $self->refname,
2433 " was r$lr, but we are about to fetch: ",
2434 "r$log_entry->{revision}!\n";
2436 if (my $c = $self->rev_map_get($log_entry->{revision})) {
2437 croak "$log_entry->{revision} = $c already exists! ",
2438 "Why are we refetching it?\n";
2440 my $old_env = set_commit_header_env($log_entry);
2441 my $tree = $log_entry->{tree};
2442 if (!defined $tree) {
2443 $tree = $self->tmp_index_do(sub {
2444 command_oneline('write-tree') });
2446 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2448 my @exec = ('git', 'commit-tree', $tree);
2449 foreach ($self->get_commit_parents($log_entry)) {
2450 push @exec, '-p', $_;
2452 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2453 or croak $!;
2454 binmode $msg_fh;
2456 # we always get UTF-8 from SVN, but we may want our commits in
2457 # a different encoding.
2458 if (my $enc = Git::config('i18n.commitencoding')) {
2459 require Encode;
2460 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
2462 print $msg_fh $log_entry->{log} or croak $!;
2463 restore_commit_header_env($old_env);
2464 unless ($self->no_metadata) {
2465 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2466 or croak $!;
2468 $msg_fh->flush == 0 or croak $!;
2469 close $msg_fh or croak $!;
2470 chomp(my $commit = do { local $/; <$out_fh> });
2471 close $out_fh or croak $!;
2472 waitpid $pid, 0;
2473 croak $? if $?;
2474 if ($commit !~ /^$::sha1$/o) {
2475 die "Failed to commit, invalid sha1: $commit\n";
2478 $self->rev_map_set($log_entry->{revision}, $commit, 1);
2480 $self->{last_rev} = $log_entry->{revision};
2481 $self->{last_commit} = $commit;
2482 print "r$log_entry->{revision}" unless $::_q > 1;
2483 if (defined $log_entry->{svm_revision}) {
2484 print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
2485 $self->rev_map_set($log_entry->{svm_revision}, $commit,
2486 0, $self->svm_uuid);
2488 print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
2489 if (--$_gc_nr == 0) {
2490 $_gc_nr = $_gc_period;
2491 gc();
2493 return $commit;
2496 sub match_paths {
2497 my ($self, $paths, $r) = @_;
2498 return 1 if $self->{path} eq '';
2499 if (my $path = $paths->{"/$self->{path}"}) {
2500 return ($path->{action} eq 'D') ? 0 : 1;
2502 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
2503 if (grep /$self->{path_regex}/, keys %$paths) {
2504 return 1;
2506 my $c = '';
2507 foreach (split m#/#, $self->{path}) {
2508 $c .= "/$_";
2509 next unless ($paths->{$c} &&
2510 ($paths->{$c}->{action} =~ /^[AR]$/));
2511 if ($self->ra->check_path($self->{path}, $r) ==
2512 $SVN::Node::dir) {
2513 return 1;
2516 return 0;
2519 sub find_parent_branch {
2520 my ($self, $paths, $rev) = @_;
2521 return undef unless $self->follow_parent;
2522 unless (defined $paths) {
2523 my $err_handler = $SVN::Error::handler;
2524 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2525 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1,
2526 sub { $paths = $_[0] });
2527 $SVN::Error::handler = $err_handler;
2529 return undef unless defined $paths;
2531 # look for a parent from another branch:
2532 my @b_path_components = split m#/#, $self->{path};
2533 my @a_path_components;
2534 my $i;
2535 while (@b_path_components) {
2536 $i = $paths->{'/'.join('/', @b_path_components)};
2537 last if $i && defined $i->{copyfrom_path};
2538 unshift(@a_path_components, pop(@b_path_components));
2540 return undef unless defined $i && defined $i->{copyfrom_path};
2541 my $branch_from = $i->{copyfrom_path};
2542 if (@a_path_components) {
2543 print STDERR "branch_from: $branch_from => ";
2544 $branch_from .= '/'.join('/', @a_path_components);
2545 print STDERR $branch_from, "\n";
2547 my $r = $i->{copyfrom_rev};
2548 my $repos_root = $self->ra->{repos_root};
2549 my $url = $self->ra->{url};
2550 my $new_url = $url . $branch_from;
2551 print STDERR "Found possible branch point: ",
2552 "$new_url => ", $self->full_url, ", $r\n";
2553 $branch_from =~ s#^/##;
2554 my $gs = $self->other_gs($new_url, $url,
2555 $branch_from, $r, $self->{ref_id});
2556 my ($r0, $parent) = $gs->find_rev_before($r, 1);
2558 my ($base, $head);
2559 if (!defined $r0 || !defined $parent) {
2560 ($base, $head) = parse_revision_argument(0, $r);
2561 } else {
2562 if ($r0 < $r) {
2563 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
2564 0, 1, sub { $base = $_[1] - 1 });
2567 if (defined $base && $base <= $r) {
2568 $gs->fetch($base, $r);
2570 ($r0, $parent) = $gs->find_rev_before($r, 1);
2572 if (defined $r0 && defined $parent) {
2573 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
2574 my $ed;
2575 if ($self->ra->can_do_switch) {
2576 $self->assert_index_clean($parent);
2577 print STDERR "Following parent with do_switch\n";
2578 # do_switch works with svn/trunk >= r22312, but that
2579 # is not included with SVN 1.4.3 (the latest version
2580 # at the moment), so we can't rely on it
2581 $self->{last_rev} = $r0;
2582 $self->{last_commit} = $parent;
2583 $ed = SVN::Git::Fetcher->new($self, $gs->{path});
2584 $gs->ra->gs_do_switch($r0, $rev, $gs,
2585 $self->full_url, $ed)
2586 or die "SVN connection failed somewhere...\n";
2587 } elsif ($self->ra->trees_match($new_url, $r0,
2588 $self->full_url, $rev)) {
2589 print STDERR "Trees match:\n",
2590 " $new_url\@$r0\n",
2591 " ${\$self->full_url}\@$rev\n",
2592 "Following parent with no changes\n";
2593 $self->tmp_index_do(sub {
2594 command_noisy('read-tree', $parent);
2596 $self->{last_commit} = $parent;
2597 } else {
2598 print STDERR "Following parent with do_update\n";
2599 $ed = SVN::Git::Fetcher->new($self);
2600 $self->ra->gs_do_update($rev, $rev, $self, $ed)
2601 or die "SVN connection failed somewhere...\n";
2603 print STDERR "Successfully followed parent\n";
2604 return $self->make_log_entry($rev, [$parent], $ed);
2606 return undef;
2609 sub do_fetch {
2610 my ($self, $paths, $rev) = @_;
2611 my $ed;
2612 my ($last_rev, @parents);
2613 if (my $lc = $self->last_commit) {
2614 # we can have a branch that was deleted, then re-added
2615 # under the same name but copied from another path, in
2616 # which case we'll have multiple parents (we don't
2617 # want to break the original ref, nor lose copypath info):
2618 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2619 push @{$log_entry->{parents}}, $lc;
2620 return $log_entry;
2622 $ed = SVN::Git::Fetcher->new($self);
2623 $last_rev = $self->{last_rev};
2624 $ed->{c} = $lc;
2625 @parents = ($lc);
2626 } else {
2627 $last_rev = $rev;
2628 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2629 return $log_entry;
2631 $ed = SVN::Git::Fetcher->new($self);
2633 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2634 die "SVN connection failed somewhere...\n";
2636 $self->make_log_entry($rev, \@parents, $ed);
2639 sub get_untracked {
2640 my ($self, $ed) = @_;
2641 my @out;
2642 my $h = $ed->{empty};
2643 foreach (sort keys %$h) {
2644 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2645 push @out, " $act: " . uri_encode($_);
2646 warn "W: $act: $_\n";
2648 foreach my $t (qw/dir_prop file_prop/) {
2649 $h = $ed->{$t} or next;
2650 foreach my $path (sort keys %$h) {
2651 my $ppath = $path eq '' ? '.' : $path;
2652 foreach my $prop (sort keys %{$h->{$path}}) {
2653 next if $SKIP_PROP{$prop};
2654 my $v = $h->{$path}->{$prop};
2655 my $t_ppath_prop = "$t: " .
2656 uri_encode($ppath) . ' ' .
2657 uri_encode($prop);
2658 if (defined $v) {
2659 push @out, " +$t_ppath_prop " .
2660 uri_encode($v);
2661 } else {
2662 push @out, " -$t_ppath_prop";
2667 foreach my $t (qw/absent_file absent_directory/) {
2668 $h = $ed->{$t} or next;
2669 foreach my $parent (sort keys %$h) {
2670 foreach my $path (sort @{$h->{$parent}}) {
2671 push @out, " $t: " .
2672 uri_encode("$parent/$path");
2673 warn "W: $t: $parent/$path ",
2674 "Insufficient permissions?\n";
2678 \@out;
2681 # parse_svn_date(DATE)
2682 # --------------------
2683 # Given a date (in UTC) from Subversion, return a string in the format
2684 # "<TZ Offset> <local date/time>" that Git will use.
2686 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
2687 # is true we'll convert it to the local timezone instead.
2688 sub parse_svn_date {
2689 my $date = shift || return '+0000 1970-01-01 00:00:00';
2690 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2691 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
2692 croak "Unable to parse date: $date\n";
2693 my $parsed_date; # Set next.
2695 if ($Git::SVN::_localtime) {
2696 # Translate the Subversion datetime to an epoch time.
2697 # Begin by switching ourselves to $date's timezone, UTC.
2698 my $old_env_TZ = $ENV{TZ};
2699 $ENV{TZ} = 'UTC';
2701 my $epoch_in_UTC =
2702 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
2704 # Determine our local timezone (including DST) at the
2705 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
2706 # value of TZ, if any, at the time we were run.
2707 if (defined $Git::SVN::Log::TZ) {
2708 $ENV{TZ} = $Git::SVN::Log::TZ;
2709 } else {
2710 delete $ENV{TZ};
2713 my $our_TZ =
2714 POSIX::strftime('%Z', $S, $M, $H, $d, $m - 1, $Y - 1900);
2716 # This converts $epoch_in_UTC into our local timezone.
2717 my ($sec, $min, $hour, $mday, $mon, $year,
2718 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
2720 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
2721 $our_TZ, $year + 1900, $mon + 1,
2722 $mday, $hour, $min, $sec);
2724 # Reset us to the timezone in effect when we entered
2725 # this routine.
2726 if (defined $old_env_TZ) {
2727 $ENV{TZ} = $old_env_TZ;
2728 } else {
2729 delete $ENV{TZ};
2731 } else {
2732 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
2735 return $parsed_date;
2738 sub other_gs {
2739 my ($self, $new_url, $url,
2740 $branch_from, $r, $old_ref_id) = @_;
2741 my $gs = Git::SVN->find_by_url($new_url, $url, $branch_from);
2742 unless ($gs) {
2743 my $ref_id = $old_ref_id;
2744 $ref_id =~ s/\@\d+$//;
2745 $ref_id .= "\@$r";
2746 # just grow a tail if we're not unique enough :x
2747 $ref_id .= '-' while find_ref($ref_id);
2748 print STDERR "Initializing parent: $ref_id\n";
2749 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
2750 if ($u =~ s#^\Q$url\E(/|$)##) {
2751 $p = $u;
2752 $u = $url;
2753 $repo_id = $self->{repo_id};
2755 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
2760 sub call_authors_prog {
2761 my ($orig_author) = @_;
2762 my $author = `$::_authors_prog $orig_author`;
2763 if ($? != 0) {
2764 die "$::_authors_prog failed with exit code $?\n"
2766 if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
2767 my ($name, $email) = ($1, $2);
2768 $email = undef if length $2 == 0;
2769 return [$name, $email];
2770 } else {
2771 die "Author: $orig_author: $::_authors_prog returned "
2772 . "invalid author format: $author\n";
2776 sub check_author {
2777 my ($author) = @_;
2778 if (!defined $author || length $author == 0) {
2779 $author = '(no author)';
2781 if (!defined $::users{$author}) {
2782 if (defined $::_authors_prog) {
2783 $::users{$author} = call_authors_prog($author);
2784 } elsif (defined $::_authors) {
2785 die "Author: $author not defined in $::_authors file\n";
2788 $author;
2791 sub make_log_entry {
2792 my ($self, $rev, $parents, $ed) = @_;
2793 my $untracked = $self->get_untracked($ed);
2795 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
2796 print $un "r$rev\n" or croak $!;
2797 print $un $_, "\n" foreach @$untracked;
2798 my %log_entry = ( parents => $parents || [], revision => $rev,
2799 log => '');
2801 my $headrev;
2802 my $logged = delete $self->{logged_rev_props};
2803 if (!$logged || $self->{-want_revprops}) {
2804 my $rp = $self->ra->rev_proplist($rev);
2805 foreach (sort keys %$rp) {
2806 my $v = $rp->{$_};
2807 if (/^svn:(author|date|log)$/) {
2808 $log_entry{$1} = $v;
2809 } elsif ($_ eq 'svm:headrev') {
2810 $headrev = $v;
2811 } else {
2812 print $un " rev_prop: ", uri_encode($_), ' ',
2813 uri_encode($v), "\n";
2816 } else {
2817 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
2819 close $un or croak $!;
2821 $log_entry{date} = parse_svn_date($log_entry{date});
2822 $log_entry{log} .= "\n";
2823 my $author = $log_entry{author} = check_author($log_entry{author});
2824 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
2825 : ($author, undef);
2827 my ($commit_name, $commit_email) = ($name, $email);
2828 if ($_use_log_author) {
2829 my $name_field;
2830 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
2831 $name_field = $1;
2832 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
2833 $name_field = $1;
2835 if (!defined $name_field) {
2836 if (!defined $email) {
2837 $email = $name;
2839 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
2840 ($name, $email) = ($1, $2);
2841 } elsif ($name_field =~ /(.*)@/) {
2842 ($name, $email) = ($1, $name_field);
2843 } else {
2844 ($name, $email) = ($name_field, $name_field);
2847 if (defined $headrev && $self->use_svm_props) {
2848 if ($self->rewrite_root) {
2849 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2850 "options set!\n";
2852 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$}i;
2853 # we don't want "SVM: initializing mirror for junk" ...
2854 return undef if $r == 0;
2855 my $svm = $self->svm;
2856 if ($uuid ne $svm->{uuid}) {
2857 die "UUID mismatch on SVM path:\n",
2858 "expected: $svm->{uuid}\n",
2859 " got: $uuid\n";
2861 my $full_url = $self->full_url;
2862 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2863 die "Failed to replace '$svm->{replace}' with ",
2864 "'$svm->{source}' in $full_url\n";
2865 # throw away username for storing in records
2866 remove_username($full_url);
2867 $log_entry{metadata} = "$full_url\@$r $uuid";
2868 $log_entry{svm_revision} = $r;
2869 $email ||= "$author\@$uuid";
2870 $commit_email ||= "$author\@$uuid";
2871 } elsif ($self->use_svnsync_props) {
2872 my $full_url = $self->svnsync->{url};
2873 $full_url .= "/$self->{path}" if length $self->{path};
2874 remove_username($full_url);
2875 my $uuid = $self->svnsync->{uuid};
2876 $log_entry{metadata} = "$full_url\@$rev $uuid";
2877 $email ||= "$author\@$uuid";
2878 $commit_email ||= "$author\@$uuid";
2879 } else {
2880 my $url = $self->metadata_url;
2881 remove_username($url);
2882 $log_entry{metadata} = "$url\@$rev " .
2883 $self->ra->get_uuid;
2884 $email ||= "$author\@" . $self->ra->get_uuid;
2885 $commit_email ||= "$author\@" . $self->ra->get_uuid;
2887 $log_entry{name} = $name;
2888 $log_entry{email} = $email;
2889 $log_entry{commit_name} = $commit_name;
2890 $log_entry{commit_email} = $commit_email;
2891 \%log_entry;
2894 sub fetch {
2895 my ($self, $min_rev, $max_rev, @parents) = @_;
2896 my ($last_rev, $last_commit) = $self->last_rev_commit;
2897 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2898 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2901 sub set_tree_cb {
2902 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2903 $self->{inject_parents} = { $rev => $tree };
2904 $self->fetch(undef, undef);
2907 sub set_tree {
2908 my ($self, $tree) = (shift, shift);
2909 my $log_entry = ::get_commit_entry($tree);
2910 unless ($self->{last_rev}) {
2911 ::fatal("Must have an existing revision to commit");
2913 my %ed_opts = ( r => $self->{last_rev},
2914 log => $log_entry->{log},
2915 ra => $self->ra,
2916 tree_a => $self->{last_commit},
2917 tree_b => $tree,
2918 editor_cb => sub {
2919 $self->set_tree_cb($log_entry, $tree, @_) },
2920 svn_path => $self->{path} );
2921 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2922 print "No changes\nr$self->{last_rev} = $tree\n";
2926 sub rebuild_from_rev_db {
2927 my ($self, $path) = @_;
2928 my $r = -1;
2929 open my $fh, '<', $path or croak "open: $!";
2930 binmode $fh or croak "binmode: $!";
2931 while (<$fh>) {
2932 length($_) == 41 or croak "inconsistent size in ($_) != 41";
2933 chomp($_);
2934 ++$r;
2935 next if $_ eq ('0' x 40);
2936 $self->rev_map_set($r, $_);
2937 print "r$r = $_\n";
2939 close $fh or croak "close: $!";
2940 unlink $path or croak "unlink: $!";
2943 sub rebuild {
2944 my ($self) = @_;
2945 my $map_path = $self->map_path;
2946 my $partial = (-e $map_path && ! -z $map_path);
2947 return unless ::verify_ref($self->refname.'^0');
2948 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
2949 my $rev_db = $self->rev_db_path;
2950 $self->rebuild_from_rev_db($rev_db);
2951 if ($self->use_svm_props) {
2952 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
2953 $self->rebuild_from_rev_db($svm_rev_db);
2955 $self->unlink_rev_db_symlink;
2956 return;
2958 print "Rebuilding $map_path ...\n" if (!$partial);
2959 my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
2960 (undef, undef));
2961 my ($log, $ctx) =
2962 command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
2963 ($head ? "$head.." : "") . $self->refname,
2964 '--');
2965 my $metadata_url = $self->metadata_url;
2966 remove_username($metadata_url);
2967 my $svn_uuid = $self->ra_uuid;
2968 my $c;
2969 while (<$log>) {
2970 if ( m{^commit ($::sha1)$} ) {
2971 $c = $1;
2972 next;
2974 next unless s{^\s*(git-svn-id:)}{$1};
2975 my ($url, $rev, $uuid) = ::extract_metadata($_);
2976 remove_username($url);
2978 # ignore merges (from set-tree)
2979 next if (!defined $rev || !$uuid);
2981 # if we merged or otherwise started elsewhere, this is
2982 # how we break out of it
2983 if (($uuid ne $svn_uuid) ||
2984 ($metadata_url && $url && ($url ne $metadata_url))) {
2985 next;
2987 if ($partial && $head) {
2988 print "Partial-rebuilding $map_path ...\n";
2989 print "Currently at $base_rev = $head\n";
2990 $head = undef;
2993 $self->rev_map_set($rev, $c);
2994 print "r$rev = $c\n";
2996 command_close_pipe($log, $ctx);
2997 print "Done rebuilding $map_path\n" if (!$partial || !$head);
2998 my $rev_db_path = $self->rev_db_path;
2999 if (-f $self->rev_db_path) {
3000 unlink $self->rev_db_path or croak "unlink: $!";
3002 $self->unlink_rev_db_symlink;
3005 # rev_map:
3006 # Tie::File seems to be prone to offset errors if revisions get sparse,
3007 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
3008 # one of my favorite modules is out :< Next up would be one of the DBM
3009 # modules, but I'm not sure which is most portable...
3011 # This is the replacement for the rev_db format, which was too big
3012 # and inefficient for large repositories with a lot of sparse history
3013 # (mainly tags)
3015 # The format is this:
3016 # - 24 bytes for every record,
3017 # * 4 bytes for the integer representing an SVN revision number
3018 # * 20 bytes representing the sha1 of a git commit
3019 # - No empty padding records like the old format
3020 # (except the last record, which can be overwritten)
3021 # - new records are written append-only since SVN revision numbers
3022 # increase monotonically
3023 # - lookups on SVN revision number are done via a binary search
3024 # - Piping the file to xxd -c24 is a good way of dumping it for
3025 # viewing or editing (piped back through xxd -r), should the need
3026 # ever arise.
3027 # - The last record can be padding revision with an all-zero sha1
3028 # This is used to optimize fetch performance when using multiple
3029 # "fetch" directives in .git/config
3031 # These files are disposable unless noMetadata or useSvmProps is set
3033 sub _rev_map_set {
3034 my ($fh, $rev, $commit) = @_;
3036 binmode $fh or croak "binmode: $!";
3037 my $size = (stat($fh))[7];
3038 ($size % 24) == 0 or croak "inconsistent size: $size";
3040 my $wr_offset = 0;
3041 if ($size > 0) {
3042 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3043 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
3044 $read == 24 or croak "read only $read bytes (!= 24)";
3045 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
3046 if ($last_commit eq ('0' x40)) {
3047 if ($size >= 48) {
3048 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3049 $read = sysread($fh, $buf, 24) or
3050 croak "read: $!";
3051 $read == 24 or
3052 croak "read only $read bytes (!= 24)";
3053 ($last_rev, $last_commit) =
3054 unpack(rev_map_fmt, $buf);
3055 if ($last_commit eq ('0' x40)) {
3056 croak "inconsistent .rev_map\n";
3059 if ($last_rev >= $rev) {
3060 croak "last_rev is higher!: $last_rev >= $rev";
3062 $wr_offset = -24;
3065 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
3066 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
3067 croak "write: $!";
3070 sub _rev_map_reset {
3071 my ($fh, $rev, $commit) = @_;
3072 my $c = _rev_map_get($fh, $rev);
3073 $c eq $commit or die "_rev_map_reset(@_) commit $c does not match!\n";
3074 my $offset = sysseek($fh, 0, SEEK_CUR) or croak "seek: $!";
3075 truncate $fh, $offset or croak "truncate: $!";
3078 sub mkfile {
3079 my ($path) = @_;
3080 unless (-e $path) {
3081 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
3082 mkpath([$dir]) unless -d $dir;
3083 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
3084 close $fh or die "Couldn't close (create) $path: $!\n";
3088 sub rev_map_set {
3089 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
3090 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
3091 my $db = $self->map_path($uuid);
3092 my $db_lock = "$db.lock";
3093 my $sig;
3094 $update_ref ||= 0;
3095 if ($update_ref) {
3096 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3097 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
3099 mkfile($db);
3101 $LOCKFILES{$db_lock} = 1;
3102 my $sync;
3103 # both of these options make our .rev_db file very, very important
3104 # and we can't afford to lose it because rebuild() won't work
3105 if ($self->use_svm_props || $self->no_metadata) {
3106 $sync = 1;
3107 copy($db, $db_lock) or die "rev_map_set(@_): ",
3108 "Failed to copy: ",
3109 "$db => $db_lock ($!)\n";
3110 } else {
3111 rename $db, $db_lock or die "rev_map_set(@_): ",
3112 "Failed to rename: ",
3113 "$db => $db_lock ($!)\n";
3116 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
3117 or croak "Couldn't open $db_lock: $!\n";
3118 $update_ref eq 'reset' ? _rev_map_reset($fh, $rev, $commit) :
3119 _rev_map_set($fh, $rev, $commit);
3120 if ($sync) {
3121 $fh->flush or die "Couldn't flush $db_lock: $!\n";
3122 $fh->sync or die "Couldn't sync $db_lock: $!\n";
3124 close $fh or croak $!;
3125 if ($update_ref) {
3126 $_head = $self;
3127 my $note = "";
3128 $note = " ($update_ref)" if ($update_ref !~ /^\d*$/);
3129 command_noisy('update-ref', '-m', "r$rev$note",
3130 $self->refname, $commit);
3132 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
3133 "$db_lock => $db ($!)\n";
3134 delete $LOCKFILES{$db_lock};
3135 if ($update_ref) {
3136 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3137 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
3138 kill $sig, $$ if defined $sig;
3142 # If want_commit, this will return an array of (rev, commit) where
3143 # commit _must_ be a valid commit in the archive.
3144 # Otherwise, it'll return the max revision (whether or not the
3145 # commit is valid or just a 0x40 placeholder).
3146 sub rev_map_max {
3147 my ($self, $want_commit) = @_;
3148 $self->rebuild;
3149 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
3150 $want_commit ? ($r, $c) : $r;
3153 sub rev_map_max_norebuild {
3154 my ($self, $want_commit) = @_;
3155 my $map_path = $self->map_path;
3156 stat $map_path or return $want_commit ? (0, undef) : 0;
3157 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3158 binmode $fh or croak "binmode: $!";
3159 my $size = (stat($fh))[7];
3160 ($size % 24) == 0 or croak "inconsistent size: $size";
3162 if ($size == 0) {
3163 close $fh or croak "close: $!";
3164 return $want_commit ? (0, undef) : 0;
3167 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3168 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3169 my ($r, $c) = unpack(rev_map_fmt, $buf);
3170 if ($want_commit && $c eq ('0' x40)) {
3171 if ($size < 48) {
3172 return $want_commit ? (0, undef) : 0;
3174 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3175 sysread($fh, $buf, 24) == 24 or croak "read: $!";
3176 ($r, $c) = unpack(rev_map_fmt, $buf);
3177 if ($c eq ('0'x40)) {
3178 croak "Penultimate record is all-zeroes in $map_path";
3181 close $fh or croak "close: $!";
3182 $want_commit ? ($r, $c) : $r;
3185 sub rev_map_get {
3186 my ($self, $rev, $uuid) = @_;
3187 my $map_path = $self->map_path($uuid);
3188 return undef unless -e $map_path;
3190 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3191 my $c = _rev_map_get($fh, $rev);
3192 close($fh) or croak "close: $!";
3196 sub _rev_map_get {
3197 my ($fh, $rev) = @_;
3199 binmode $fh or croak "binmode: $!";
3200 my $size = (stat($fh))[7];
3201 ($size % 24) == 0 or croak "inconsistent size: $size";
3203 if ($size == 0) {
3204 return undef;
3207 my ($l, $u) = (0, $size - 24);
3208 my ($r, $c, $buf);
3210 while ($l <= $u) {
3211 my $i = int(($l/24 + $u/24) / 2) * 24;
3212 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
3213 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3214 my ($r, $c) = unpack('NH40', $buf);
3216 if ($r < $rev) {
3217 $l = $i + 24;
3218 } elsif ($r > $rev) {
3219 $u = $i - 24;
3220 } else { # $r == $rev
3221 return $c eq ('0' x 40) ? undef : $c;
3224 undef;
3227 # Finds the first svn revision that exists on (if $eq_ok is true) or
3228 # before $rev for the current branch. It will not search any lower
3229 # than $min_rev. Returns the git commit hash and svn revision number
3230 # if found, else (undef, undef).
3231 sub find_rev_before {
3232 my ($self, $rev, $eq_ok, $min_rev) = @_;
3233 --$rev unless $eq_ok;
3234 $min_rev ||= 1;
3235 my $max_rev = $self->rev_map_max;
3236 $rev = $max_rev if ($rev > $max_rev);
3237 while ($rev >= $min_rev) {
3238 if (my $c = $self->rev_map_get($rev)) {
3239 return ($rev, $c);
3241 --$rev;
3243 return (undef, undef);
3246 # Finds the first svn revision that exists on (if $eq_ok is true) or
3247 # after $rev for the current branch. It will not search any higher
3248 # than $max_rev. Returns the git commit hash and svn revision number
3249 # if found, else (undef, undef).
3250 sub find_rev_after {
3251 my ($self, $rev, $eq_ok, $max_rev) = @_;
3252 ++$rev unless $eq_ok;
3253 $max_rev ||= $self->rev_map_max;
3254 while ($rev <= $max_rev) {
3255 if (my $c = $self->rev_map_get($rev)) {
3256 return ($rev, $c);
3258 ++$rev;
3260 return (undef, undef);
3263 sub _new {
3264 my ($class, $repo_id, $ref_id, $path) = @_;
3265 unless (defined $repo_id && length $repo_id) {
3266 $repo_id = $Git::SVN::default_repo_id;
3268 unless (defined $ref_id && length $ref_id) {
3269 $_[2] = $ref_id = $Git::SVN::default_ref_id;
3271 $_[1] = $repo_id;
3272 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
3273 $_[3] = $path = '' unless (defined $path);
3274 mkpath(["$ENV{GIT_DIR}/svn"]);
3275 bless {
3276 ref_id => $ref_id, dir => $dir, index => "$dir/index",
3277 path => $path, config => "$ENV{GIT_DIR}/svn/config",
3278 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
3281 # for read-only access of old .rev_db formats
3282 sub unlink_rev_db_symlink {
3283 my ($self) = @_;
3284 my $link = $self->rev_db_path;
3285 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
3286 if (-l $link) {
3287 unlink $link or croak "unlink: $link failed!";
3291 sub rev_db_path {
3292 my ($self, $uuid) = @_;
3293 my $db_path = $self->map_path($uuid);
3294 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
3295 or croak "map_path: $db_path does not contain '/.rev_map.' !";
3296 $db_path;
3299 # the new replacement for .rev_db
3300 sub map_path {
3301 my ($self, $uuid) = @_;
3302 $uuid ||= $self->ra_uuid;
3303 "$self->{map_root}.$uuid";
3306 sub uri_encode {
3307 my ($f) = @_;
3308 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
3312 sub remove_username {
3313 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
3316 package Git::SVN::Prompt;
3317 use strict;
3318 use warnings;
3319 require SVN::Core;
3320 use vars qw/$_no_auth_cache $_username/;
3322 sub simple {
3323 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
3324 $may_save = undef if $_no_auth_cache;
3325 $default_username = $_username if defined $_username;
3326 if (defined $default_username && length $default_username) {
3327 if (defined $realm && length $realm) {
3328 print STDERR "Authentication realm: $realm\n";
3329 STDERR->flush;
3331 $cred->username($default_username);
3332 } else {
3333 username($cred, $realm, $may_save, $pool);
3335 $cred->password(_read_password("Password for '" .
3336 $cred->username . "': ", $realm));
3337 $cred->may_save($may_save);
3338 $SVN::_Core::SVN_NO_ERROR;
3341 sub ssl_server_trust {
3342 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
3343 $may_save = undef if $_no_auth_cache;
3344 print STDERR "Error validating server certificate for '$realm':\n";
3346 no warnings 'once';
3347 # All variables SVN::Auth::SSL::* are used only once,
3348 # so we're shutting up Perl warnings about this.
3349 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
3350 print STDERR " - The certificate is not issued ",
3351 "by a trusted authority. Use the\n",
3352 " fingerprint to validate ",
3353 "the certificate manually!\n";
3355 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
3356 print STDERR " - The certificate hostname ",
3357 "does not match.\n";
3359 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
3360 print STDERR " - The certificate is not yet valid.\n";
3362 if ($failures & $SVN::Auth::SSL::EXPIRED) {
3363 print STDERR " - The certificate has expired.\n";
3365 if ($failures & $SVN::Auth::SSL::OTHER) {
3366 print STDERR " - The certificate has ",
3367 "an unknown error.\n";
3369 } # no warnings 'once'
3370 printf STDERR
3371 "Certificate information:\n".
3372 " - Hostname: %s\n".
3373 " - Valid: from %s until %s\n".
3374 " - Issuer: %s\n".
3375 " - Fingerprint: %s\n",
3376 map $cert_info->$_, qw(hostname valid_from valid_until
3377 issuer_dname fingerprint);
3378 my $choice;
3379 prompt:
3380 print STDERR $may_save ?
3381 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
3382 "(R)eject or accept (t)emporarily? ";
3383 STDERR->flush;
3384 $choice = lc(substr(<STDIN> || 'R', 0, 1));
3385 if ($choice =~ /^t$/i) {
3386 $cred->may_save(undef);
3387 } elsif ($choice =~ /^r$/i) {
3388 return -1;
3389 } elsif ($may_save && $choice =~ /^p$/i) {
3390 $cred->may_save($may_save);
3391 } else {
3392 goto prompt;
3394 $cred->accepted_failures($failures);
3395 $SVN::_Core::SVN_NO_ERROR;
3398 sub ssl_client_cert {
3399 my ($cred, $realm, $may_save, $pool) = @_;
3400 $may_save = undef if $_no_auth_cache;
3401 print STDERR "Client certificate filename: ";
3402 STDERR->flush;
3403 chomp(my $filename = <STDIN>);
3404 $cred->cert_file($filename);
3405 $cred->may_save($may_save);
3406 $SVN::_Core::SVN_NO_ERROR;
3409 sub ssl_client_cert_pw {
3410 my ($cred, $realm, $may_save, $pool) = @_;
3411 $may_save = undef if $_no_auth_cache;
3412 $cred->password(_read_password("Password: ", $realm));
3413 $cred->may_save($may_save);
3414 $SVN::_Core::SVN_NO_ERROR;
3417 sub username {
3418 my ($cred, $realm, $may_save, $pool) = @_;
3419 $may_save = undef if $_no_auth_cache;
3420 if (defined $realm && length $realm) {
3421 print STDERR "Authentication realm: $realm\n";
3423 my $username;
3424 if (defined $_username) {
3425 $username = $_username;
3426 } else {
3427 print STDERR "Username: ";
3428 STDERR->flush;
3429 chomp($username = <STDIN>);
3431 $cred->username($username);
3432 $cred->may_save($may_save);
3433 $SVN::_Core::SVN_NO_ERROR;
3436 sub _read_password {
3437 my ($prompt, $realm) = @_;
3438 print STDERR $prompt;
3439 STDERR->flush;
3440 require Term::ReadKey;
3441 Term::ReadKey::ReadMode('noecho');
3442 my $password = '';
3443 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
3444 last if $key =~ /[\012\015]/; # \n\r
3445 $password .= $key;
3447 Term::ReadKey::ReadMode('restore');
3448 print STDERR "\n";
3449 STDERR->flush;
3450 $password;
3453 package SVN::Git::Fetcher;
3454 use vars qw/@ISA/;
3455 use strict;
3456 use warnings;
3457 use Carp qw/croak/;
3458 use File::Temp qw/tempfile/;
3459 use IO::File qw//;
3460 use vars qw/$_ignore_regex/;
3462 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
3463 sub new {
3464 my ($class, $git_svn, $switch_path) = @_;
3465 my $self = SVN::Delta::Editor->new;
3466 bless $self, $class;
3467 if (exists $git_svn->{last_commit}) {
3468 $self->{c} = $git_svn->{last_commit};
3469 $self->{empty_symlinks} =
3470 _mark_empty_symlinks($git_svn, $switch_path);
3472 $self->{ignore_regex} = eval { command_oneline('config', '--get',
3473 "svn-remote.$git_svn->{repo_id}.ignore-paths") };
3474 $self->{empty} = {};
3475 $self->{dir_prop} = {};
3476 $self->{file_prop} = {};
3477 $self->{absent_dir} = {};
3478 $self->{absent_file} = {};
3479 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
3480 $self;
3483 # this uses the Ra object, so it must be called before do_{switch,update},
3484 # not inside them (when the Git::SVN::Fetcher object is passed) to
3485 # do_{switch,update}
3486 sub _mark_empty_symlinks {
3487 my ($git_svn, $switch_path) = @_;
3488 my $bool = Git::config_bool('svn.brokenSymlinkWorkaround');
3489 return {} if (!defined($bool)) || (defined($bool) && ! $bool);
3491 my %ret;
3492 my ($rev, $cmt) = $git_svn->last_rev_commit;
3493 return {} unless ($rev && $cmt);
3495 # allow the warning to be printed for each revision we fetch to
3496 # ensure the user sees it. The user can also disable the workaround
3497 # on the repository even while git svn is running and the next
3498 # revision fetched will skip this expensive function.
3499 my $printed_warning;
3500 chomp(my $empty_blob = `git hash-object -t blob --stdin < /dev/null`);
3501 my ($ls, $ctx) = command_output_pipe(qw/ls-tree -r -z/, $cmt);
3502 local $/ = "\0";
3503 my $pfx = defined($switch_path) ? $switch_path : $git_svn->{path};
3504 $pfx .= '/' if length($pfx);
3505 while (<$ls>) {
3506 chomp;
3507 s/\A100644 blob $empty_blob\t//o or next;
3508 unless ($printed_warning) {
3509 print STDERR "Scanning for empty symlinks, ",
3510 "this may take a while if you have ",
3511 "many empty files\n",
3512 "You may disable this with `",
3513 "git config svn.brokenSymlinkWorkaround ",
3514 "false'.\n",
3515 "This may be done in a different ",
3516 "terminal without restarting ",
3517 "git svn\n";
3518 $printed_warning = 1;
3520 my $path = $_;
3521 my (undef, $props) =
3522 $git_svn->ra->get_file($pfx.$path, $rev, undef);
3523 if ($props->{'svn:special'}) {
3524 $ret{$path} = 1;
3527 command_close_pipe($ls, $ctx);
3528 \%ret;
3531 # returns true if a given path is inside a ".git" directory
3532 sub in_dot_git {
3533 $_[0] =~ m{(?:^|/)\.git(?:/|$)};
3536 # return value: 0 -- don't ignore, 1 -- ignore
3537 sub is_path_ignored {
3538 my ($self, $path) = @_;
3539 return 1 if in_dot_git($path);
3540 return 1 if defined($self->{ignore_regex}) &&
3541 $path =~ m!$self->{ignore_regex}!;
3542 return 0 unless defined($_ignore_regex);
3543 return 1 if $path =~ m!$_ignore_regex!o;
3544 return 0;
3547 sub set_path_strip {
3548 my ($self, $path) = @_;
3549 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
3552 sub open_root {
3553 { path => '' };
3556 sub open_directory {
3557 my ($self, $path, $pb, $rev) = @_;
3558 { path => $path };
3561 sub git_path {
3562 my ($self, $path) = @_;
3563 if ($self->{path_strip}) {
3564 $path =~ s!$self->{path_strip}!! or
3565 die "Failed to strip path '$path' ($self->{path_strip})\n";
3567 $path;
3570 sub delete_entry {
3571 my ($self, $path, $rev, $pb) = @_;
3572 return undef if $self->is_path_ignored($path);
3574 my $gpath = $self->git_path($path);
3575 return undef if ($gpath eq '');
3577 # remove entire directories.
3578 my ($tree) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
3579 =~ /\A040000 tree ([a-f\d]{40})\t\Q$gpath\E\0/);
3580 if ($tree) {
3581 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3582 -r --name-only -z/,
3583 $tree);
3584 local $/ = "\0";
3585 while (<$ls>) {
3586 chomp;
3587 my $rmpath = "$gpath/$_";
3588 $self->{gii}->remove($rmpath);
3589 print "\tD\t$rmpath\n" unless $::_q;
3591 print "\tD\t$gpath/\n" unless $::_q;
3592 command_close_pipe($ls, $ctx);
3593 $self->{empty}->{$path} = 0
3594 } else {
3595 $self->{gii}->remove($gpath);
3596 print "\tD\t$gpath\n" unless $::_q;
3598 undef;
3601 sub open_file {
3602 my ($self, $path, $pb, $rev) = @_;
3603 my ($mode, $blob);
3605 goto out if $self->is_path_ignored($path);
3607 my $gpath = $self->git_path($path);
3608 ($mode, $blob) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
3609 =~ /\A(\d{6}) blob ([a-f\d]{40})\t\Q$gpath\E\0/);
3610 unless (defined $mode && defined $blob) {
3611 die "$path was not found in commit $self->{c} (r$rev)\n";
3613 if ($mode eq '100644' && $self->{empty_symlinks}->{$path}) {
3614 $mode = '120000';
3616 out:
3617 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
3618 pool => SVN::Pool->new, action => 'M' };
3621 sub add_file {
3622 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
3623 my $mode;
3625 if (!$self->is_path_ignored($path)) {
3626 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3627 delete $self->{empty}->{$dir};
3628 $mode = '100644';
3630 { path => $path, mode_a => $mode, mode_b => $mode,
3631 pool => SVN::Pool->new, action => 'A' };
3634 sub add_directory {
3635 my ($self, $path, $cp_path, $cp_rev) = @_;
3636 goto out if $self->is_path_ignored($path);
3637 my $gpath = $self->git_path($path);
3638 if ($gpath eq '') {
3639 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3640 -r --name-only -z/,
3641 $self->{c});
3642 local $/ = "\0";
3643 while (<$ls>) {
3644 chomp;
3645 $self->{gii}->remove($_);
3646 print "\tD\t$_\n" unless $::_q;
3648 command_close_pipe($ls, $ctx);
3649 $self->{empty}->{$path} = 0;
3651 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3652 delete $self->{empty}->{$dir};
3653 $self->{empty}->{$path} = 1;
3654 out:
3655 { path => $path };
3658 sub change_dir_prop {
3659 my ($self, $db, $prop, $value) = @_;
3660 return undef if $self->is_path_ignored($db->{path});
3661 $self->{dir_prop}->{$db->{path}} ||= {};
3662 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
3663 undef;
3666 sub absent_directory {
3667 my ($self, $path, $pb) = @_;
3668 return undef if $self->is_path_ignored($path);
3669 $self->{absent_dir}->{$pb->{path}} ||= [];
3670 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
3671 undef;
3674 sub absent_file {
3675 my ($self, $path, $pb) = @_;
3676 return undef if $self->is_path_ignored($path);
3677 $self->{absent_file}->{$pb->{path}} ||= [];
3678 push @{$self->{absent_file}->{$pb->{path}}}, $path;
3679 undef;
3682 sub change_file_prop {
3683 my ($self, $fb, $prop, $value) = @_;
3684 return undef if $self->is_path_ignored($fb->{path});
3685 if ($prop eq 'svn:executable') {
3686 if ($fb->{mode_b} != 120000) {
3687 $fb->{mode_b} = defined $value ? 100755 : 100644;
3689 } elsif ($prop eq 'svn:special') {
3690 $fb->{mode_b} = defined $value ? 120000 : 100644;
3691 } else {
3692 $self->{file_prop}->{$fb->{path}} ||= {};
3693 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
3695 undef;
3698 sub apply_textdelta {
3699 my ($self, $fb, $exp) = @_;
3700 return undef if $self->is_path_ignored($fb->{path});
3701 my $fh = $::_repository->temp_acquire('svn_delta');
3702 # $fh gets auto-closed() by SVN::TxDelta::apply(),
3703 # (but $base does not,) so dup() it for reading in close_file
3704 open my $dup, '<&', $fh or croak $!;
3705 my $base = $::_repository->temp_acquire('git_blob');
3707 if ($fb->{blob}) {
3708 my ($base_is_link, $size);
3710 if ($fb->{mode_a} eq '120000' &&
3711 ! $self->{empty_symlinks}->{$fb->{path}}) {
3712 print $base 'link ' or die "print $!\n";
3713 $base_is_link = 1;
3715 retry:
3716 $size = $::_repository->cat_blob($fb->{blob}, $base);
3717 die "Failed to read object $fb->{blob}" if ($size < 0);
3719 if (defined $exp) {
3720 seek $base, 0, 0 or croak $!;
3721 my $got = ::md5sum($base);
3722 if ($got ne $exp) {
3723 my $err = "Checksum mismatch: ".
3724 "$fb->{path} $fb->{blob}\n" .
3725 "expected: $exp\n" .
3726 " got: $got\n";
3727 if ($base_is_link) {
3728 warn $err,
3729 "Retrying... (possibly ",
3730 "a bad symlink from SVN)\n";
3731 $::_repository->temp_reset($base);
3732 $base_is_link = 0;
3733 goto retry;
3735 die $err;
3739 seek $base, 0, 0 or croak $!;
3740 $fb->{fh} = $fh;
3741 $fb->{base} = $base;
3742 [ SVN::TxDelta::apply($base, $dup, undef, $fb->{path}, $fb->{pool}) ];
3745 sub close_file {
3746 my ($self, $fb, $exp) = @_;
3747 return undef if $self->is_path_ignored($fb->{path});
3749 my $hash;
3750 my $path = $self->git_path($fb->{path});
3751 if (my $fh = $fb->{fh}) {
3752 if (defined $exp) {
3753 seek($fh, 0, 0) or croak $!;
3754 my $got = ::md5sum($fh);
3755 if ($got ne $exp) {
3756 die "Checksum mismatch: $path\n",
3757 "expected: $exp\n got: $got\n";
3760 if ($fb->{mode_b} == 120000) {
3761 sysseek($fh, 0, 0) or croak $!;
3762 my $rd = sysread($fh, my $buf, 5);
3764 if (!defined $rd) {
3765 croak "sysread: $!\n";
3766 } elsif ($rd == 0) {
3767 warn "$path has mode 120000",
3768 " but it points to nothing\n",
3769 "converting to an empty file with mode",
3770 " 100644\n";
3771 $fb->{mode_b} = '100644';
3772 } elsif ($buf ne 'link ') {
3773 warn "$path has mode 120000",
3774 " but is not a link\n";
3775 } else {
3776 my $tmp_fh = $::_repository->temp_acquire(
3777 'svn_hash');
3778 my $res;
3779 while ($res = sysread($fh, my $str, 1024)) {
3780 my $out = syswrite($tmp_fh, $str, $res);
3781 defined($out) && $out == $res
3782 or croak("write ",
3783 Git::temp_path($tmp_fh),
3784 ": $!\n");
3786 defined $res or croak $!;
3788 ($fh, $tmp_fh) = ($tmp_fh, $fh);
3789 Git::temp_release($tmp_fh, 1);
3793 $hash = $::_repository->hash_and_insert_object(
3794 Git::temp_path($fh));
3795 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
3797 Git::temp_release($fb->{base}, 1);
3798 Git::temp_release($fh, 1);
3799 } else {
3800 $hash = $fb->{blob} or die "no blob information\n";
3802 $fb->{pool}->clear;
3803 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
3804 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
3805 undef;
3808 sub abort_edit {
3809 my $self = shift;
3810 $self->{nr} = $self->{gii}->{nr};
3811 delete $self->{gii};
3812 $self->SUPER::abort_edit(@_);
3815 sub close_edit {
3816 my $self = shift;
3817 $self->{git_commit_ok} = 1;
3818 $self->{nr} = $self->{gii}->{nr};
3819 delete $self->{gii};
3820 $self->SUPER::close_edit(@_);
3823 package SVN::Git::Editor;
3824 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
3825 use strict;
3826 use warnings;
3827 use Carp qw/croak/;
3828 use IO::File;
3830 sub new {
3831 my ($class, $opts) = @_;
3832 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
3833 die "$_ required!\n" unless (defined $opts->{$_});
3836 my $pool = SVN::Pool->new;
3837 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
3838 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
3839 $opts->{r}, $mods);
3841 # $opts->{ra} functions should not be used after this:
3842 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
3843 $opts->{editor_cb}, $pool);
3844 my $self = SVN::Delta::Editor->new(@ce, $pool);
3845 bless $self, $class;
3846 foreach (qw/svn_path r tree_a tree_b/) {
3847 $self->{$_} = $opts->{$_};
3849 $self->{url} = $opts->{ra}->{url};
3850 $self->{mods} = $mods;
3851 $self->{types} = $types;
3852 $self->{pool} = $pool;
3853 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
3854 $self->{rm} = { };
3855 $self->{path_prefix} = length $self->{svn_path} ?
3856 "$self->{svn_path}/" : '';
3857 $self->{config} = $opts->{config};
3858 return $self;
3861 sub generate_diff {
3862 my ($tree_a, $tree_b) = @_;
3863 my @diff_tree = qw(diff-tree -z -r);
3864 if ($_cp_similarity) {
3865 push @diff_tree, "-C$_cp_similarity";
3866 } else {
3867 push @diff_tree, '-C';
3869 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
3870 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
3871 push @diff_tree, $tree_a, $tree_b;
3872 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
3873 local $/ = "\0";
3874 my $state = 'meta';
3875 my @mods;
3876 while (<$diff_fh>) {
3877 chomp $_; # this gets rid of the trailing "\0"
3878 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
3879 ($::sha1)\s($::sha1)\s
3880 ([MTCRAD])\d*$/xo) {
3881 push @mods, { mode_a => $1, mode_b => $2,
3882 sha1_a => $3, sha1_b => $4,
3883 chg => $5 };
3884 if ($5 =~ /^(?:C|R)$/) {
3885 $state = 'file_a';
3886 } else {
3887 $state = 'file_b';
3889 } elsif ($state eq 'file_a') {
3890 my $x = $mods[$#mods] or croak "Empty array\n";
3891 if ($x->{chg} !~ /^(?:C|R)$/) {
3892 croak "Error parsing $_, $x->{chg}\n";
3894 $x->{file_a} = $_;
3895 $state = 'file_b';
3896 } elsif ($state eq 'file_b') {
3897 my $x = $mods[$#mods] or croak "Empty array\n";
3898 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
3899 croak "Error parsing $_, $x->{chg}\n";
3901 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
3902 croak "Error parsing $_, $x->{chg}\n";
3904 $x->{file_b} = $_;
3905 $state = 'meta';
3906 } else {
3907 croak "Error parsing $_\n";
3910 command_close_pipe($diff_fh, $ctx);
3911 \@mods;
3914 sub check_diff_paths {
3915 my ($ra, $pfx, $rev, $mods) = @_;
3916 my %types;
3917 $pfx .= '/' if length $pfx;
3919 sub type_diff_paths {
3920 my ($ra, $types, $path, $rev) = @_;
3921 my @p = split m#/+#, $path;
3922 my $c = shift @p;
3923 unless (defined $types->{$c}) {
3924 $types->{$c} = $ra->check_path($c, $rev);
3926 while (@p) {
3927 $c .= '/' . shift @p;
3928 next if defined $types->{$c};
3929 $types->{$c} = $ra->check_path($c, $rev);
3933 foreach my $m (@$mods) {
3934 foreach my $f (qw/file_a file_b/) {
3935 next unless defined $m->{$f};
3936 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
3937 if (length $pfx.$dir && ! defined $types{$dir}) {
3938 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
3942 \%types;
3945 sub split_path {
3946 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
3949 sub repo_path {
3950 my ($self, $path) = @_;
3951 $self->{path_prefix}.(defined $path ? $path : '');
3954 sub url_path {
3955 my ($self, $path) = @_;
3956 if ($self->{url} =~ m#^https?://#) {
3957 $path =~ s/([^~a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
3959 $self->{url} . '/' . $self->repo_path($path);
3962 sub rmdirs {
3963 my ($self) = @_;
3964 my $rm = $self->{rm};
3965 delete $rm->{''}; # we never delete the url we're tracking
3966 return unless %$rm;
3968 foreach (keys %$rm) {
3969 my @d = split m#/#, $_;
3970 my $c = shift @d;
3971 $rm->{$c} = 1;
3972 while (@d) {
3973 $c .= '/' . shift @d;
3974 $rm->{$c} = 1;
3977 delete $rm->{$self->{svn_path}};
3978 delete $rm->{''}; # we never delete the url we're tracking
3979 return unless %$rm;
3981 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
3982 $self->{tree_b});
3983 local $/ = "\0";
3984 while (<$fh>) {
3985 chomp;
3986 my @dn = split m#/#, $_;
3987 while (pop @dn) {
3988 delete $rm->{join '/', @dn};
3990 unless (%$rm) {
3991 close $fh;
3992 return;
3995 command_close_pipe($fh, $ctx);
3997 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
3998 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
3999 $self->close_directory($bat->{$d}, $p);
4000 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
4001 print "\tD+\t$d/\n" unless $::_q;
4002 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
4003 delete $bat->{$d};
4007 sub open_or_add_dir {
4008 my ($self, $full_path, $baton) = @_;
4009 my $t = $self->{types}->{$full_path};
4010 if (!defined $t) {
4011 die "$full_path not known in r$self->{r} or we have a bug!\n";
4014 no warnings 'once';
4015 # SVN::Node::none and SVN::Node::file are used only once,
4016 # so we're shutting up Perl's warnings about them.
4017 if ($t == $SVN::Node::none) {
4018 return $self->add_directory($full_path, $baton,
4019 undef, -1, $self->{pool});
4020 } elsif ($t == $SVN::Node::dir) {
4021 return $self->open_directory($full_path, $baton,
4022 $self->{r}, $self->{pool});
4023 } # no warnings 'once'
4024 print STDERR "$full_path already exists in repository at ",
4025 "r$self->{r} and it is not a directory (",
4026 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
4027 } # no warnings 'once'
4028 exit 1;
4031 sub ensure_path {
4032 my ($self, $path) = @_;
4033 my $bat = $self->{bat};
4034 my $repo_path = $self->repo_path($path);
4035 return $bat->{''} unless (length $repo_path);
4036 my @p = split m#/+#, $repo_path;
4037 my $c = shift @p;
4038 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
4039 while (@p) {
4040 my $c0 = $c;
4041 $c .= '/' . shift @p;
4042 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
4044 return $bat->{$c};
4047 # Subroutine to convert a globbing pattern to a regular expression.
4048 # From perl cookbook.
4049 sub glob2pat {
4050 my $globstr = shift;
4051 my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
4052 $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
4053 return '^' . $globstr . '$';
4056 sub check_autoprop {
4057 my ($self, $pattern, $properties, $file, $fbat) = @_;
4058 # Convert the globbing pattern to a regular expression.
4059 my $regex = glob2pat($pattern);
4060 # Check if the pattern matches the file name.
4061 if($file =~ m/($regex)/) {
4062 # Parse the list of properties to set.
4063 my @props = split(/;/, $properties);
4064 foreach my $prop (@props) {
4065 # Parse 'name=value' syntax and set the property.
4066 if ($prop =~ /([^=]+)=(.*)/) {
4067 my ($n,$v) = ($1,$2);
4068 for ($n, $v) {
4069 s/^\s+//; s/\s+$//;
4071 $self->change_file_prop($fbat, $n, $v);
4077 sub apply_autoprops {
4078 my ($self, $file, $fbat) = @_;
4079 my $conf_t = ${$self->{config}}{'config'};
4080 no warnings 'once';
4081 # Check [miscellany]/enable-auto-props in svn configuration.
4082 if (SVN::_Core::svn_config_get_bool(
4083 $conf_t,
4084 $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
4085 $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
4086 0)) {
4087 # Auto-props are enabled. Enumerate them to look for matches.
4088 my $callback = sub {
4089 $self->check_autoprop($_[0], $_[1], $file, $fbat);
4091 SVN::_Core::svn_config_enumerate(
4092 $conf_t,
4093 $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
4094 $callback);
4098 sub A {
4099 my ($self, $m) = @_;
4100 my ($dir, $file) = split_path($m->{file_b});
4101 my $pbat = $self->ensure_path($dir);
4102 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4103 undef, -1);
4104 print "\tA\t$m->{file_b}\n" unless $::_q;
4105 $self->apply_autoprops($file, $fbat);
4106 $self->chg_file($fbat, $m);
4107 $self->close_file($fbat,undef,$self->{pool});
4110 sub C {
4111 my ($self, $m) = @_;
4112 my ($dir, $file) = split_path($m->{file_b});
4113 my $pbat = $self->ensure_path($dir);
4114 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4115 $self->url_path($m->{file_a}), $self->{r});
4116 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
4117 $self->chg_file($fbat, $m);
4118 $self->close_file($fbat,undef,$self->{pool});
4121 sub delete_entry {
4122 my ($self, $path, $pbat) = @_;
4123 my $rpath = $self->repo_path($path);
4124 my ($dir, $file) = split_path($rpath);
4125 $self->{rm}->{$dir} = 1;
4126 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
4129 sub R {
4130 my ($self, $m) = @_;
4131 my ($dir, $file) = split_path($m->{file_b});
4132 my $pbat = $self->ensure_path($dir);
4133 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4134 $self->url_path($m->{file_a}), $self->{r});
4135 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
4136 $self->apply_autoprops($file, $fbat);
4137 $self->chg_file($fbat, $m);
4138 $self->close_file($fbat,undef,$self->{pool});
4140 ($dir, $file) = split_path($m->{file_a});
4141 $pbat = $self->ensure_path($dir);
4142 $self->delete_entry($m->{file_a}, $pbat);
4145 sub M {
4146 my ($self, $m) = @_;
4147 my ($dir, $file) = split_path($m->{file_b});
4148 my $pbat = $self->ensure_path($dir);
4149 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
4150 $pbat,$self->{r},$self->{pool});
4151 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
4152 $self->chg_file($fbat, $m);
4153 $self->close_file($fbat,undef,$self->{pool});
4156 sub T { shift->M(@_) }
4158 sub change_file_prop {
4159 my ($self, $fbat, $pname, $pval) = @_;
4160 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
4163 sub _chg_file_get_blob ($$$$) {
4164 my ($self, $fbat, $m, $which) = @_;
4165 my $fh = $::_repository->temp_acquire("git_blob_$which");
4166 if ($m->{"mode_$which"} =~ /^120/) {
4167 print $fh 'link ' or croak $!;
4168 $self->change_file_prop($fbat,'svn:special','*');
4169 } elsif ($m->{mode_a} =~ /^120/ && $m->{"mode_$which"} !~ /^120/) {
4170 $self->change_file_prop($fbat,'svn:special',undef);
4172 my $blob = $m->{"sha1_$which"};
4173 return ($fh,) if ($blob =~ /^0{40}$/);
4174 my $size = $::_repository->cat_blob($blob, $fh);
4175 croak "Failed to read object $blob" if ($size < 0);
4176 $fh->flush == 0 or croak $!;
4177 seek $fh, 0, 0 or croak $!;
4179 my $exp = ::md5sum($fh);
4180 seek $fh, 0, 0 or croak $!;
4181 return ($fh, $exp);
4184 sub chg_file {
4185 my ($self, $fbat, $m) = @_;
4186 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
4187 $self->change_file_prop($fbat,'svn:executable','*');
4188 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
4189 $self->change_file_prop($fbat,'svn:executable',undef);
4191 my ($fh_a, $exp_a) = _chg_file_get_blob $self, $fbat, $m, 'a';
4192 my ($fh_b, $exp_b) = _chg_file_get_blob $self, $fbat, $m, 'b';
4193 my $pool = SVN::Pool->new;
4194 my $atd = $self->apply_textdelta($fbat, $exp_a, $pool);
4195 if (-s $fh_a) {
4196 my $txstream = SVN::TxDelta::new ($fh_a, $fh_b, $pool);
4197 my $res = SVN::TxDelta::send_txstream($txstream, @$atd, $pool);
4198 if (defined $res) {
4199 die "Unexpected result from send_txstream: $res\n",
4200 "(SVN::Core::VERSION: $SVN::Core::VERSION)\n";
4202 } else {
4203 my $got = SVN::TxDelta::send_stream($fh_b, @$atd, $pool);
4204 die "Checksum mismatch\nexpected: $exp_b\ngot: $got\n"
4205 if ($got ne $exp_b);
4207 Git::temp_release($fh_b, 1);
4208 Git::temp_release($fh_a, 1);
4209 $pool->clear;
4212 sub D {
4213 my ($self, $m) = @_;
4214 my ($dir, $file) = split_path($m->{file_b});
4215 my $pbat = $self->ensure_path($dir);
4216 print "\tD\t$m->{file_b}\n" unless $::_q;
4217 $self->delete_entry($m->{file_b}, $pbat);
4220 sub close_edit {
4221 my ($self) = @_;
4222 my ($p,$bat) = ($self->{pool}, $self->{bat});
4223 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
4224 next if $_ eq '';
4225 $self->close_directory($bat->{$_}, $p);
4227 $self->close_directory($bat->{''}, $p);
4228 $self->SUPER::close_edit($p);
4229 $p->clear;
4232 sub abort_edit {
4233 my ($self) = @_;
4234 $self->SUPER::abort_edit($self->{pool});
4237 sub DESTROY {
4238 my $self = shift;
4239 $self->SUPER::DESTROY(@_);
4240 $self->{pool}->clear;
4243 # this drives the editor
4244 sub apply_diff {
4245 my ($self) = @_;
4246 my $mods = $self->{mods};
4247 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
4248 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
4249 my $f = $m->{chg};
4250 if (defined $o{$f}) {
4251 $self->$f($m);
4252 } else {
4253 fatal("Invalid change type: $f");
4256 $self->rmdirs if $_rmdir;
4257 if (@$mods == 0) {
4258 $self->abort_edit;
4259 } else {
4260 $self->close_edit;
4262 return scalar @$mods;
4265 package Git::SVN::Ra;
4266 use vars qw/@ISA $config_dir $_log_window_size/;
4267 use strict;
4268 use warnings;
4269 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
4271 BEGIN {
4272 # enforce temporary pool usage for some simple functions
4273 no strict 'refs';
4274 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root
4275 get_file/) {
4276 my $SUPER = "SUPER::$f";
4277 *$f = sub {
4278 my $self = shift;
4279 my $pool = SVN::Pool->new;
4280 my @ret = $self->$SUPER(@_,$pool);
4281 $pool->clear;
4282 wantarray ? @ret : $ret[0];
4287 sub _auth_providers () {
4289 SVN::Client::get_simple_provider(),
4290 SVN::Client::get_ssl_server_trust_file_provider(),
4291 SVN::Client::get_simple_prompt_provider(
4292 \&Git::SVN::Prompt::simple, 2),
4293 SVN::Client::get_ssl_client_cert_file_provider(),
4294 SVN::Client::get_ssl_client_cert_prompt_provider(
4295 \&Git::SVN::Prompt::ssl_client_cert, 2),
4296 SVN::Client::get_ssl_client_cert_pw_file_provider(),
4297 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
4298 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
4299 SVN::Client::get_username_provider(),
4300 SVN::Client::get_ssl_server_trust_prompt_provider(
4301 \&Git::SVN::Prompt::ssl_server_trust),
4302 SVN::Client::get_username_prompt_provider(
4303 \&Git::SVN::Prompt::username, 2)
4307 sub escape_uri_only {
4308 my ($uri) = @_;
4309 my @tmp;
4310 foreach (split m{/}, $uri) {
4311 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
4312 push @tmp, $_;
4314 join('/', @tmp);
4317 sub escape_url {
4318 my ($url) = @_;
4319 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
4320 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
4321 $url = "$scheme://$domain$uri";
4323 $url;
4326 sub new {
4327 my ($class, $url) = @_;
4328 $url =~ s!/+$!!;
4329 return $RA if ($RA && $RA->{url} eq $url);
4331 SVN::_Core::svn_config_ensure($config_dir, undef);
4332 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
4333 my $config = SVN::Core::config_get_config($config_dir);
4334 $RA = undef;
4335 my $dont_store_passwords = 1;
4336 my $conf_t = ${$config}{'config'};
4338 no warnings 'once';
4339 # The usage of $SVN::_Core::SVN_CONFIG_* variables
4340 # produces warnings that variables are used only once.
4341 # I had not found the better way to shut them up, so
4342 # the warnings of type 'once' are disabled in this block.
4343 if (SVN::_Core::svn_config_get_bool($conf_t,
4344 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4345 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
4346 1) == 0) {
4347 SVN::_Core::svn_auth_set_parameter($baton,
4348 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
4349 bless (\$dont_store_passwords, "_p_void"));
4351 if (SVN::_Core::svn_config_get_bool($conf_t,
4352 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4353 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
4354 1) == 0) {
4355 $Git::SVN::Prompt::_no_auth_cache = 1;
4357 } # no warnings 'once'
4358 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
4359 config => $config,
4360 pool => SVN::Pool->new,
4361 auth_provider_callbacks => $callbacks);
4362 $self->{url} = $url;
4363 $self->{svn_path} = $url;
4364 $self->{repos_root} = $self->get_repos_root;
4365 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
4366 $self->{cache} = { check_path => { r => 0, data => {} },
4367 get_dir => { r => 0, data => {} } };
4368 $RA = bless $self, $class;
4371 sub check_path {
4372 my ($self, $path, $r) = @_;
4373 my $cache = $self->{cache}->{check_path};
4374 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
4375 return $cache->{data}->{$path};
4377 my $pool = SVN::Pool->new;
4378 my $t = $self->SUPER::check_path($path, $r, $pool);
4379 $pool->clear;
4380 if ($r != $cache->{r}) {
4381 %{$cache->{data}} = ();
4382 $cache->{r} = $r;
4384 $cache->{data}->{$path} = $t;
4387 sub get_dir {
4388 my ($self, $dir, $r) = @_;
4389 my $cache = $self->{cache}->{get_dir};
4390 if ($r == $cache->{r}) {
4391 if (my $x = $cache->{data}->{$dir}) {
4392 return wantarray ? @$x : $x->[0];
4395 my $pool = SVN::Pool->new;
4396 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
4397 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
4398 $pool->clear;
4399 if ($r != $cache->{r}) {
4400 %{$cache->{data}} = ();
4401 $cache->{r} = $r;
4403 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
4404 wantarray ? (\%dirents, $r, $props) : \%dirents;
4407 sub DESTROY {
4408 # do not call the real DESTROY since we store ourselves in $RA
4411 # get_log(paths, start, end, limit,
4412 # discover_changed_paths, strict_node_history, receiver)
4413 sub get_log {
4414 my ($self, @args) = @_;
4415 my $pool = SVN::Pool->new;
4417 # svn_log_changed_path_t objects passed to get_log are likely to be
4418 # overwritten even if only the refs are copied to an external variable,
4419 # so we should dup the structures in their entirety. Using an
4420 # externally passed pool (instead of our temporary and quickly cleared
4421 # pool in Git::SVN::Ra) does not help matters at all...
4422 my $receiver = pop @args;
4423 my $prefix = "/".$self->{svn_path};
4424 $prefix =~ s#/+($)##;
4425 my $prefix_regex = qr#^\Q$prefix\E#;
4426 push(@args, sub {
4427 my ($paths) = $_[0];
4428 return &$receiver(@_) unless $paths;
4429 $_[0] = ();
4430 foreach my $p (keys %$paths) {
4431 my $i = $paths->{$p};
4432 # Make path relative to our url, not repos_root
4433 $p =~ s/$prefix_regex//;
4434 my %s = map { $_ => $i->$_; }
4435 qw/copyfrom_path copyfrom_rev action/;
4436 if ($s{'copyfrom_path'}) {
4437 $s{'copyfrom_path'} =~ s/$prefix_regex//;
4439 $_[0]{$p} = \%s;
4441 &$receiver(@_);
4445 # the limit parameter was not supported in SVN 1.1.x, so we
4446 # drop it. Therefore, the receiver callback passed to it
4447 # is made aware of this limitation by being wrapped if
4448 # the limit passed to is being wrapped.
4449 if ($SVN::Core::VERSION le '1.2.0') {
4450 my $limit = splice(@args, 3, 1);
4451 if ($limit > 0) {
4452 my $receiver = pop @args;
4453 push(@args, sub { &$receiver(@_) if (--$limit >= 0) });
4456 my $ret = $self->SUPER::get_log(@args, $pool);
4457 $pool->clear;
4458 $ret;
4461 sub trees_match {
4462 my ($self, $url1, $rev1, $url2, $rev2) = @_;
4463 my $ctx = SVN::Client->new(auth => _auth_providers);
4464 my $out = IO::File->new_tmpfile;
4466 # older SVN (1.1.x) doesn't take $pool as the last parameter for
4467 # $ctx->diff(), so we'll create a default one
4468 my $pool = SVN::Pool->new_default_sub;
4470 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
4471 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
4472 $out->flush;
4473 my $ret = (($out->stat)[7] == 0);
4474 close $out or croak $!;
4476 $ret;
4479 sub get_commit_editor {
4480 my ($self, $log, $cb, $pool) = @_;
4481 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
4482 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
4485 sub gs_do_update {
4486 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
4487 my $new = ($rev_a == $rev_b);
4488 my $path = $gs->{path};
4490 if ($new && -e $gs->{index}) {
4491 unlink $gs->{index} or die
4492 "Couldn't unlink index: $gs->{index}: $!\n";
4494 my $pool = SVN::Pool->new;
4495 $editor->set_path_strip($path);
4496 my (@pc) = split m#/#, $path;
4497 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
4498 1, $editor, $pool);
4499 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4501 # Since we can't rely on svn_ra_reparent being available, we'll
4502 # just have to do some magic with set_path to make it so
4503 # we only want a partial path.
4504 my $sp = '';
4505 my $final = join('/', @pc);
4506 while (@pc) {
4507 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
4508 $sp .= '/' if length $sp;
4509 $sp .= shift @pc;
4511 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
4513 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
4515 $reporter->finish_report($pool);
4516 $pool->clear;
4517 $editor->{git_commit_ok};
4520 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
4521 # svn_ra_reparent didn't work before 1.4)
4522 sub gs_do_switch {
4523 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
4524 my $path = $gs->{path};
4525 my $pool = SVN::Pool->new;
4527 my $full_url = $self->{url};
4528 my $old_url = $full_url;
4529 $full_url .= '/' . $path if length $path;
4530 my ($ra, $reparented);
4532 if ($old_url =~ m#^svn(\+ssh)?://# ||
4533 ($full_url =~ m#^https?://# &&
4534 escape_url($full_url) ne $full_url)) {
4535 $_[0] = undef;
4536 $self = undef;
4537 $RA = undef;
4538 $ra = Git::SVN::Ra->new($full_url);
4539 $ra_invalid = 1;
4540 } elsif ($old_url ne $full_url) {
4541 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url, $pool);
4542 $self->{url} = $full_url;
4543 $reparented = 1;
4546 $ra ||= $self;
4547 $url_b = escape_url($url_b);
4548 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
4549 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4550 $reporter->set_path('', $rev_a, 0, @lock, $pool);
4551 $reporter->finish_report($pool);
4553 if ($reparented) {
4554 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
4555 $self->{url} = $old_url;
4558 $pool->clear;
4559 $editor->{git_commit_ok};
4562 sub longest_common_path {
4563 my ($gsv, $globs) = @_;
4564 my %common;
4565 my $common_max = scalar @$gsv;
4567 foreach my $gs (@$gsv) {
4568 my @tmp = split m#/#, $gs->{path};
4569 my $p = '';
4570 foreach (@tmp) {
4571 $p .= length($p) ? "/$_" : $_;
4572 $common{$p} ||= 0;
4573 $common{$p}++;
4576 $globs ||= [];
4577 $common_max += scalar @$globs;
4578 foreach my $glob (@$globs) {
4579 my @tmp = split m#/#, $glob->{path}->{left};
4580 my $p = '';
4581 foreach (@tmp) {
4582 $p .= length($p) ? "/$_" : $_;
4583 $common{$p} ||= 0;
4584 $common{$p}++;
4588 my $longest_path = '';
4589 foreach (sort {length $b <=> length $a} keys %common) {
4590 if ($common{$_} == $common_max) {
4591 $longest_path = $_;
4592 last;
4595 $longest_path;
4598 sub gs_fetch_loop_common {
4599 my ($self, $base, $head, $gsv, $globs) = @_;
4600 return if ($base > $head);
4601 my $inc = $_log_window_size;
4602 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
4603 my $longest_path = longest_common_path($gsv, $globs);
4604 my $ra_url = $self->{url};
4605 my $find_trailing_edge;
4606 while (1) {
4607 my %revs;
4608 my $err;
4609 my $err_handler = $SVN::Error::handler;
4610 $SVN::Error::handler = sub {
4611 ($err) = @_;
4612 skip_unknown_revs($err);
4614 sub _cb {
4615 my ($paths, $r, $author, $date, $log) = @_;
4616 [ $paths,
4617 { author => $author, date => $date, log => $log } ];
4619 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
4620 sub { $revs{$_[1]} = _cb(@_) });
4621 if ($err) {
4622 print "Checked through r$max\r";
4623 } else {
4624 $find_trailing_edge = 1;
4626 if ($err and $find_trailing_edge) {
4627 print STDERR "Path '$longest_path' ",
4628 "was probably deleted:\n",
4629 $err->expanded_message,
4630 "\nWill attempt to follow ",
4631 "revisions r$min .. r$max ",
4632 "committed before the deletion\n";
4633 my $hi = $max;
4634 while (--$hi >= $min) {
4635 my $ok;
4636 $self->get_log([$longest_path], $min, $hi,
4637 0, 1, 1, sub {
4638 $ok = $_[1];
4639 $revs{$_[1]} = _cb(@_) });
4640 if ($ok) {
4641 print STDERR "r$min .. r$ok OK\n";
4642 last;
4645 $find_trailing_edge = 0;
4647 $SVN::Error::handler = $err_handler;
4649 my %exists = map { $_->{path} => $_ } @$gsv;
4650 foreach my $r (sort {$a <=> $b} keys %revs) {
4651 my ($paths, $logged) = @{$revs{$r}};
4653 foreach my $gs ($self->match_globs(\%exists, $paths,
4654 $globs, $r)) {
4655 if ($gs->rev_map_max >= $r) {
4656 next;
4658 next unless $gs->match_paths($paths, $r);
4659 $gs->{logged_rev_props} = $logged;
4660 if (my $last_commit = $gs->last_commit) {
4661 $gs->assert_index_clean($last_commit);
4663 my $log_entry = $gs->do_fetch($paths, $r);
4664 if ($log_entry) {
4665 $gs->do_git_commit($log_entry);
4667 $INDEX_FILES{$gs->{index}} = 1;
4669 foreach my $g (@$globs) {
4670 my $k = "svn-remote.$g->{remote}." .
4671 "$g->{t}-maxRev";
4672 Git::SVN::tmp_config($k, $r);
4674 if ($ra_invalid) {
4675 $_[0] = undef;
4676 $self = undef;
4677 $RA = undef;
4678 $self = Git::SVN::Ra->new($ra_url);
4679 $ra_invalid = undef;
4682 # pre-fill the .rev_db since it'll eventually get filled in
4683 # with '0' x40 if something new gets committed
4684 foreach my $gs (@$gsv) {
4685 next if $gs->rev_map_max >= $max;
4686 next if defined $gs->rev_map_get($max);
4687 $gs->rev_map_set($max, 0 x40);
4689 foreach my $g (@$globs) {
4690 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
4691 Git::SVN::tmp_config($k, $max);
4693 last if $max >= $head;
4694 $min = $max + 1;
4695 $max += $inc;
4696 $max = $head if ($max > $head);
4698 Git::SVN::gc();
4701 sub get_dir_globbed {
4702 my ($self, $left, $depth, $r) = @_;
4704 my @x = eval { $self->get_dir($left, $r) };
4705 return unless scalar @x == 3;
4706 my $dirents = $x[0];
4707 my @finalents;
4708 foreach my $de (keys %$dirents) {
4709 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
4710 if ($depth > 1) {
4711 my @args = ("$left/$de", $depth - 1, $r);
4712 foreach my $dir ($self->get_dir_globbed(@args)) {
4713 push @finalents, "$de/$dir";
4715 } else {
4716 push @finalents, $de;
4719 @finalents;
4722 sub match_globs {
4723 my ($self, $exists, $paths, $globs, $r) = @_;
4725 sub get_dir_check {
4726 my ($self, $exists, $g, $r) = @_;
4728 my @dirs = $self->get_dir_globbed($g->{path}->{left},
4729 $g->{path}->{depth},
4730 $r);
4732 foreach my $de (@dirs) {
4733 my $p = $g->{path}->full_path($de);
4734 next if $exists->{$p};
4735 next if (length $g->{path}->{right} &&
4736 ($self->check_path($p, $r) !=
4737 $SVN::Node::dir));
4738 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
4739 $g->{ref}->full_path($de), 1);
4742 foreach my $g (@$globs) {
4743 if (my $path = $paths->{"/$g->{path}->{left}"}) {
4744 if ($path->{action} =~ /^[AR]$/) {
4745 get_dir_check($self, $exists, $g, $r);
4748 foreach (keys %$paths) {
4749 if (/$g->{path}->{left_regex}/ &&
4750 !/$g->{path}->{regex}/) {
4751 next if $paths->{$_}->{action} !~ /^[AR]$/;
4752 get_dir_check($self, $exists, $g, $r);
4754 next unless /$g->{path}->{regex}/;
4755 my $p = $1;
4756 my $pathname = $g->{path}->full_path($p);
4757 next if $exists->{$pathname};
4758 next if ($self->check_path($pathname, $r) !=
4759 $SVN::Node::dir);
4760 $exists->{$pathname} = Git::SVN->init(
4761 $self->{url}, $pathname, undef,
4762 $g->{ref}->full_path($p), 1);
4764 my $c = '';
4765 foreach (split m#/#, $g->{path}->{left}) {
4766 $c .= "/$_";
4767 next unless ($paths->{$c} &&
4768 ($paths->{$c}->{action} =~ /^[AR]$/));
4769 get_dir_check($self, $exists, $g, $r);
4772 values %$exists;
4775 sub minimize_url {
4776 my ($self) = @_;
4777 return $self->{url} if ($self->{url} eq $self->{repos_root});
4778 my $url = $self->{repos_root};
4779 my @components = split(m!/!, $self->{svn_path});
4780 my $c = '';
4781 do {
4782 $url .= "/$c" if length $c;
4783 eval { (ref $self)->new($url)->get_latest_revnum };
4784 } while ($@ && ($c = shift @components));
4785 $url;
4788 sub can_do_switch {
4789 my $self = shift;
4790 unless (defined $can_do_switch) {
4791 my $pool = SVN::Pool->new;
4792 my $rep = eval {
4793 $self->do_switch(1, '', 0, $self->{url},
4794 SVN::Delta::Editor->new, $pool);
4796 if ($@) {
4797 $can_do_switch = 0;
4798 } else {
4799 $rep->abort_report($pool);
4800 $can_do_switch = 1;
4802 $pool->clear;
4804 $can_do_switch;
4807 sub skip_unknown_revs {
4808 my ($err) = @_;
4809 my $errno = $err->apr_err();
4810 # Maybe the branch we're tracking didn't
4811 # exist when the repo started, so it's
4812 # not an error if it doesn't, just continue
4814 # Wonderfully consistent library, eh?
4815 # 160013 - svn:// and file://
4816 # 175002 - http(s)://
4817 # 175007 - http(s):// (this repo required authorization, too...)
4818 # More codes may be discovered later...
4819 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
4820 my $err_key = $err->expanded_message;
4821 # revision numbers change every time, filter them out
4822 $err_key =~ s/\d+/\0/g;
4823 $err_key = "$errno\0$err_key";
4824 unless ($ignored_err{$err_key}) {
4825 warn "W: Ignoring error from SVN, path probably ",
4826 "does not exist: ($errno): ",
4827 $err->expanded_message,"\n";
4828 warn "W: Do not be alarmed at the above message ",
4829 "git-svn is just searching aggressively for ",
4830 "old history.\n",
4831 "This may take a while on large repositories\n";
4832 $ignored_err{$err_key} = 1;
4834 return;
4836 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
4839 package Git::SVN::Log;
4840 use strict;
4841 use warnings;
4842 use POSIX qw/strftime/;
4843 use Time::Local;
4844 use constant commit_log_separator => ('-' x 72) . "\n";
4845 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
4846 %rusers $show_commit $incremental/;
4847 my $l_fmt;
4849 sub cmt_showable {
4850 my ($c) = @_;
4851 return 1 if defined $c->{r};
4853 # big commit message got truncated by the 16k pretty buffer in rev-list
4854 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
4855 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
4856 @{$c->{l}} = ();
4857 my @log = command(qw/cat-file commit/, $c->{c});
4859 # shift off the headers
4860 shift @log while ($log[0] ne '');
4861 shift @log;
4863 # TODO: make $c->{l} not have a trailing newline in the future
4864 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
4866 (undef, $c->{r}, undef) = ::extract_metadata(
4867 (grep(/^git-svn-id: /, @log))[-1]);
4869 return defined $c->{r};
4872 sub log_use_color {
4873 return $color || Git->repository->get_colorbool('color.diff');
4876 sub git_svn_log_cmd {
4877 my ($r_min, $r_max, @args) = @_;
4878 my $head = 'HEAD';
4879 my (@files, @log_opts);
4880 foreach my $x (@args) {
4881 if ($x eq '--' || @files) {
4882 push @files, $x;
4883 } else {
4884 if (::verify_ref("$x^0")) {
4885 $head = $x;
4886 } else {
4887 push @log_opts, $x;
4892 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
4893 $gs ||= Git::SVN->_new;
4894 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
4895 $gs->refname);
4896 push @cmd, '-r' unless $non_recursive;
4897 push @cmd, qw/--raw --name-status/ if $verbose;
4898 push @cmd, '--color' if log_use_color();
4899 push @cmd, @log_opts;
4900 if (defined $r_max && $r_max == $r_min) {
4901 push @cmd, '--max-count=1';
4902 if (my $c = $gs->rev_map_get($r_max)) {
4903 push @cmd, $c;
4905 } elsif (defined $r_max) {
4906 if ($r_max < $r_min) {
4907 ($r_min, $r_max) = ($r_max, $r_min);
4909 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
4910 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
4911 # If there are no commits in the range, both $c_max and $c_min
4912 # will be undefined. If there is at least 1 commit in the
4913 # range, both will be defined.
4914 return () if !defined $c_min || !defined $c_max;
4915 if ($c_min eq $c_max) {
4916 push @cmd, '--max-count=1', $c_min;
4917 } else {
4918 push @cmd, '--boundary', "$c_min..$c_max";
4921 return (@cmd, @files);
4924 # adapted from pager.c
4925 sub config_pager {
4926 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
4927 if (!defined $pager) {
4928 $pager = 'less';
4929 } elsif (length $pager == 0 || $pager eq 'cat') {
4930 $pager = undef;
4932 $ENV{GIT_PAGER_IN_USE} = defined($pager);
4935 sub run_pager {
4936 return unless -t *STDOUT && defined $pager;
4937 pipe my ($rfd, $wfd) or return;
4938 defined(my $pid = fork) or ::fatal "Can't fork: $!";
4939 if (!$pid) {
4940 open STDOUT, '>&', $wfd or
4941 ::fatal "Can't redirect to stdout: $!";
4942 return;
4944 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
4945 $ENV{LESS} ||= 'FRSX';
4946 exec $pager or ::fatal "Can't run pager: $! ($pager)";
4949 sub format_svn_date {
4950 # some systmes don't handle or mishandle %z, so be creative.
4951 my $t = shift || time;
4952 my $gm = timelocal(gmtime($t));
4953 my $sign = qw( + + - )[ $t <=> $gm ];
4954 my $gmoff = sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
4955 return strftime("%Y-%m-%d %H:%M:%S $gmoff (%a, %d %b %Y)", localtime($t));
4958 sub parse_git_date {
4959 my ($t, $tz) = @_;
4960 # Date::Parse isn't in the standard Perl distro :(
4961 if ($tz =~ s/^\+//) {
4962 $t += tz_to_s_offset($tz);
4963 } elsif ($tz =~ s/^\-//) {
4964 $t -= tz_to_s_offset($tz);
4966 return $t;
4969 sub set_local_timezone {
4970 if (defined $TZ) {
4971 $ENV{TZ} = $TZ;
4972 } else {
4973 delete $ENV{TZ};
4977 sub tz_to_s_offset {
4978 my ($tz) = @_;
4979 $tz =~ s/(\d\d)$//;
4980 return ($1 * 60) + ($tz * 3600);
4983 sub get_author_info {
4984 my ($dest, $author, $t, $tz) = @_;
4985 $author =~ s/(?:^\s*|\s*$)//g;
4986 $dest->{a_raw} = $author;
4987 my $au;
4988 if ($::_authors) {
4989 $au = $rusers{$author} || undef;
4991 if (!$au) {
4992 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
4994 $dest->{t} = $t;
4995 $dest->{tz} = $tz;
4996 $dest->{a} = $au;
4997 $dest->{t_utc} = parse_git_date($t, $tz);
5000 sub process_commit {
5001 my ($c, $r_min, $r_max, $defer) = @_;
5002 if (defined $r_min && defined $r_max) {
5003 if ($r_min == $c->{r} && $r_min == $r_max) {
5004 show_commit($c);
5005 return 0;
5007 return 1 if $r_min == $r_max;
5008 if ($r_min < $r_max) {
5009 # we need to reverse the print order
5010 return 0 if (defined $limit && --$limit < 0);
5011 push @$defer, $c;
5012 return 1;
5014 if ($r_min != $r_max) {
5015 return 1 if ($r_min < $c->{r});
5016 return 1 if ($r_max > $c->{r});
5019 return 0 if (defined $limit && --$limit < 0);
5020 show_commit($c);
5021 return 1;
5024 sub show_commit {
5025 my $c = shift;
5026 if ($oneline) {
5027 my $x = "\n";
5028 if (my $l = $c->{l}) {
5029 while ($l->[0] =~ /^\s*$/) { shift @$l }
5030 $x = $l->[0];
5032 $l_fmt ||= 'A' . length($c->{r});
5033 print 'r',pack($l_fmt, $c->{r}),' | ';
5034 print "$c->{c} | " if $show_commit;
5035 print $x;
5036 } else {
5037 show_commit_normal($c);
5041 sub show_commit_changed_paths {
5042 my ($c) = @_;
5043 return unless $c->{changed};
5044 print "Changed paths:\n", @{$c->{changed}};
5047 sub show_commit_normal {
5048 my ($c) = @_;
5049 print commit_log_separator, "r$c->{r} | ";
5050 print "$c->{c} | " if $show_commit;
5051 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
5052 my $nr_line = 0;
5054 if (my $l = $c->{l}) {
5055 while ($l->[$#$l] eq "\n" && $#$l > 0
5056 && $l->[($#$l - 1)] eq "\n") {
5057 pop @$l;
5059 $nr_line = scalar @$l;
5060 if (!$nr_line) {
5061 print "1 line\n\n\n";
5062 } else {
5063 if ($nr_line == 1) {
5064 $nr_line = '1 line';
5065 } else {
5066 $nr_line .= ' lines';
5068 print $nr_line, "\n";
5069 show_commit_changed_paths($c);
5070 print "\n";
5071 print $_ foreach @$l;
5073 } else {
5074 print "1 line\n";
5075 show_commit_changed_paths($c);
5076 print "\n";
5079 foreach my $x (qw/raw stat diff/) {
5080 if ($c->{$x}) {
5081 print "\n";
5082 print $_ foreach @{$c->{$x}}
5087 sub cmd_show_log {
5088 my (@args) = @_;
5089 my ($r_min, $r_max);
5090 my $r_last = -1; # prevent dupes
5091 set_local_timezone();
5092 if (defined $::_revision) {
5093 if ($::_revision =~ /^(\d+):(\d+)$/) {
5094 ($r_min, $r_max) = ($1, $2);
5095 } elsif ($::_revision =~ /^\d+$/) {
5096 $r_min = $r_max = $::_revision;
5097 } else {
5098 ::fatal "-r$::_revision is not supported, use ",
5099 "standard 'git log' arguments instead";
5103 config_pager();
5104 @args = git_svn_log_cmd($r_min, $r_max, @args);
5105 if (!@args) {
5106 print commit_log_separator unless $incremental || $oneline;
5107 return;
5109 my $log = command_output_pipe(@args);
5110 run_pager();
5111 my (@k, $c, $d, $stat);
5112 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
5113 while (<$log>) {
5114 if (/^${esc_color}commit -?($::sha1_short)/o) {
5115 my $cmt = $1;
5116 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
5117 $r_last = $c->{r};
5118 process_commit($c, $r_min, $r_max, \@k) or
5119 goto out;
5121 $d = undef;
5122 $c = { c => $cmt };
5123 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
5124 get_author_info($c, $1, $2, $3);
5125 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
5126 # ignore
5127 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
5128 push @{$c->{raw}}, $_;
5129 } elsif (/^${esc_color}[ACRMDT]\t/) {
5130 # we could add $SVN->{svn_path} here, but that requires
5131 # remote access at the moment (repo_path_split)...
5132 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
5133 push @{$c->{changed}}, $_;
5134 } elsif (/^${esc_color}diff /o) {
5135 $d = 1;
5136 push @{$c->{diff}}, $_;
5137 } elsif ($d) {
5138 push @{$c->{diff}}, $_;
5139 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
5140 $esc_color*[\+\-]*$esc_color$/x) {
5141 $stat = 1;
5142 push @{$c->{stat}}, $_;
5143 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
5144 push @{$c->{stat}}, $_;
5145 $stat = undef;
5146 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
5147 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
5148 } elsif (s/^${esc_color} //o) {
5149 push @{$c->{l}}, $_;
5152 if ($c && defined $c->{r} && $c->{r} != $r_last) {
5153 $r_last = $c->{r};
5154 process_commit($c, $r_min, $r_max, \@k);
5156 if (@k) {
5157 ($r_min, $r_max) = ($r_max, $r_min);
5158 process_commit($_, $r_min, $r_max) foreach reverse @k;
5160 out:
5161 close $log;
5162 print commit_log_separator unless $incremental || $oneline;
5165 sub cmd_blame {
5166 my $path = pop;
5168 config_pager();
5169 run_pager();
5171 my ($fh, $ctx, $rev);
5173 if ($_git_format) {
5174 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
5175 while (my $line = <$fh>) {
5176 if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
5177 # Uncommitted edits show up as a rev ID of
5178 # all zeros, which we can't look up with
5179 # cmt_metadata
5180 if ($1 !~ /^0+$/) {
5181 (undef, $rev, undef) =
5182 ::cmt_metadata($1);
5183 $rev = '0' if (!$rev);
5184 } else {
5185 $rev = '0';
5187 $rev = sprintf('%-10s', $rev);
5188 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
5190 print $line;
5192 } else {
5193 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
5194 '--', $path);
5195 my ($sha1);
5196 my %authors;
5197 my @buffer;
5198 my %dsha; #distinct sha keys
5200 while (my $line = <$fh>) {
5201 push @buffer, $line;
5202 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5203 $dsha{$1} = 1;
5207 my $s2r = ::cmt_sha2rev_batch([keys %dsha]);
5209 foreach my $line (@buffer) {
5210 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5211 $rev = $s2r->{$1};
5212 $rev = '0' if (!$rev)
5214 elsif ($line =~ /^author (.*)/) {
5215 $authors{$rev} = $1;
5216 $authors{$rev} =~ s/\s/_/g;
5218 elsif ($line =~ /^\t(.*)$/) {
5219 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
5223 command_close_pipe($fh, $ctx);
5226 package Git::SVN::Migration;
5227 # these version numbers do NOT correspond to actual version numbers
5228 # of git nor git-svn. They are just relative.
5230 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
5232 # v1 layout: .git/$id/info/url, refs/remotes/$id
5234 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
5236 # v3 layout: .git/svn/$id, refs/remotes/$id
5237 # - info/url may remain for backwards compatibility
5238 # - this is what we migrate up to this layout automatically,
5239 # - this will be used by git svn init on single branches
5240 # v3.1 layout (auto migrated):
5241 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
5242 # for backwards compatibility
5244 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
5245 # - this is only created for newly multi-init-ed
5246 # repositories. Similar in spirit to the
5247 # --use-separate-remotes option in git-clone (now default)
5248 # - we do not automatically migrate to this (following
5249 # the example set by core git)
5251 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
5252 # - newer, more-efficient format that uses 24-bytes per record
5253 # with no filler space.
5254 # - use xxd -c24 < .rev_map.$UUID to view and debug
5255 # - This is a one-way migration, repositories updated to the
5256 # new format will not be able to use old git-svn without
5257 # rebuilding the .rev_db. Rebuilding the rev_db is not
5258 # possible if noMetadata or useSvmProps are set; but should
5259 # be no problem for users that use the (sensible) defaults.
5260 use strict;
5261 use warnings;
5262 use Carp qw/croak/;
5263 use File::Path qw/mkpath/;
5264 use File::Basename qw/dirname basename/;
5265 use vars qw/$_minimize/;
5267 sub migrate_from_v0 {
5268 my $git_dir = $ENV{GIT_DIR};
5269 return undef unless -d $git_dir;
5270 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5271 my $migrated = 0;
5272 while (<$fh>) {
5273 chomp;
5274 my ($id, $orig_ref) = ($_, $_);
5275 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
5276 next unless -f "$git_dir/$id/info/url";
5277 my $new_ref = "refs/remotes/$id";
5278 if (::verify_ref("$new_ref^0")) {
5279 print STDERR "W: $orig_ref is probably an old ",
5280 "branch used by an ancient version of ",
5281 "git-svn.\n",
5282 "However, $new_ref also exists.\n",
5283 "We will not be able ",
5284 "to use this branch until this ",
5285 "ambiguity is resolved.\n";
5286 next;
5288 print STDERR "Migrating from v0 layout...\n" if !$migrated;
5289 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
5290 command_noisy('update-ref', $new_ref, $orig_ref);
5291 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
5292 $migrated++;
5294 command_close_pipe($fh, $ctx);
5295 print STDERR "Done migrating from v0 layout...\n" if $migrated;
5296 $migrated;
5299 sub migrate_from_v1 {
5300 my $git_dir = $ENV{GIT_DIR};
5301 my $migrated = 0;
5302 return $migrated unless -d $git_dir;
5303 my $svn_dir = "$git_dir/svn";
5305 # just in case somebody used 'svn' as their $id at some point...
5306 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
5308 print STDERR "Migrating from a git-svn v1 layout...\n";
5309 mkpath([$svn_dir]);
5310 print STDERR "Data from a previous version of git-svn exists, but\n\t",
5311 "$svn_dir\n\t(required for this version ",
5312 "($::VERSION) of git-svn) does not exist.\n";
5313 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5314 while (<$fh>) {
5315 my $x = $_;
5316 next unless $x =~ s#^refs/remotes/##;
5317 chomp $x;
5318 next unless -f "$git_dir/$x/info/url";
5319 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
5320 next unless $u;
5321 my $dn = dirname("$git_dir/svn/$x");
5322 mkpath([$dn]) unless -d $dn;
5323 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
5324 mkpath(["$git_dir/svn/svn"]);
5325 print STDERR " - $git_dir/$x/info => ",
5326 "$git_dir/svn/$x/info\n";
5327 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
5328 croak "$!: $x";
5329 # don't worry too much about these, they probably
5330 # don't exist with repos this old (save for index,
5331 # and we can easily regenerate that)
5332 foreach my $f (qw/unhandled.log index .rev_db/) {
5333 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
5335 } else {
5336 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
5337 rename "$git_dir/$x", "$git_dir/svn/$x" or
5338 croak "$!: $x";
5340 $migrated++;
5342 command_close_pipe($fh, $ctx);
5343 print STDERR "Done migrating from a git-svn v1 layout\n";
5344 $migrated;
5347 sub read_old_urls {
5348 my ($l_map, $pfx, $path) = @_;
5349 my @dir;
5350 foreach (<$path/*>) {
5351 if (-r "$_/info/url") {
5352 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
5353 my $ref_id = $pfx . basename $_;
5354 my $url = ::file_to_s("$_/info/url");
5355 $l_map->{$ref_id} = $url;
5356 } elsif (-d $_) {
5357 push @dir, $_;
5360 foreach (@dir) {
5361 my $x = $_;
5362 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
5363 read_old_urls($l_map, $x, $_);
5367 sub migrate_from_v2 {
5368 my @cfg = command(qw/config -l/);
5369 return if grep /^svn-remote\..+\.url=/, @cfg;
5370 my %l_map;
5371 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
5372 my $migrated = 0;
5374 foreach my $ref_id (sort keys %l_map) {
5375 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
5376 if ($@) {
5377 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
5379 $migrated++;
5381 $migrated;
5384 sub minimize_connections {
5385 my $r = Git::SVN::read_all_remotes();
5386 my $new_urls = {};
5387 my $root_repos = {};
5388 foreach my $repo_id (keys %$r) {
5389 my $url = $r->{$repo_id}->{url} or next;
5390 my $fetch = $r->{$repo_id}->{fetch} or next;
5391 my $ra = Git::SVN::Ra->new($url);
5393 # skip existing cases where we already connect to the root
5394 if (($ra->{url} eq $ra->{repos_root}) ||
5395 ($ra->{repos_root} eq $repo_id)) {
5396 $root_repos->{$ra->{url}} = $repo_id;
5397 next;
5400 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
5401 my $root_path = $ra->{url};
5402 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
5403 foreach my $path (keys %$fetch) {
5404 my $ref_id = $fetch->{$path};
5405 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
5407 # make sure we can read when connecting to
5408 # a higher level of a repository
5409 my ($last_rev, undef) = $gs->last_rev_commit;
5410 if (!defined $last_rev) {
5411 $last_rev = eval {
5412 $root_ra->get_latest_revnum;
5414 next if $@;
5416 my $new = $root_path;
5417 $new .= length $path ? "/$path" : '';
5418 eval {
5419 $root_ra->get_log([$new], $last_rev, $last_rev,
5420 0, 0, 1, sub { });
5422 next if $@;
5423 $new_urls->{$ra->{repos_root}}->{$new} =
5424 { ref_id => $ref_id,
5425 old_repo_id => $repo_id,
5426 old_path => $path };
5430 my @emptied;
5431 foreach my $url (keys %$new_urls) {
5432 # see if we can re-use an existing [svn-remote "repo_id"]
5433 # instead of creating a(n ugly) new section:
5434 my $repo_id = $root_repos->{$url} || $url;
5436 my $fetch = $new_urls->{$url};
5437 foreach my $path (keys %$fetch) {
5438 my $x = $fetch->{$path};
5439 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
5440 my $pfx = "svn-remote.$x->{old_repo_id}";
5442 my $old_fetch = quotemeta("$x->{old_path}:".
5443 "refs/remotes/$x->{ref_id}");
5444 command_noisy(qw/config --unset/,
5445 "$pfx.fetch", '^'. $old_fetch . '$');
5446 delete $r->{$x->{old_repo_id}}->
5447 {fetch}->{$x->{old_path}};
5448 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
5449 command_noisy(qw/config --unset/,
5450 "$pfx.url");
5451 push @emptied, $x->{old_repo_id}
5455 if (@emptied) {
5456 my $file = $ENV{GIT_CONFIG} || "$ENV{GIT_DIR}/config";
5457 print STDERR <<EOF;
5458 The following [svn-remote] sections in your config file ($file) are empty
5459 and can be safely removed:
5461 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
5465 sub migration_check {
5466 migrate_from_v0();
5467 migrate_from_v1();
5468 migrate_from_v2();
5469 minimize_connections() if $_minimize;
5472 package Git::IndexInfo;
5473 use strict;
5474 use warnings;
5475 use Git qw/command_input_pipe command_close_pipe/;
5477 sub new {
5478 my ($class) = @_;
5479 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
5480 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
5483 sub remove {
5484 my ($self, $path) = @_;
5485 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
5486 return ++$self->{nr};
5488 undef;
5491 sub update {
5492 my ($self, $mode, $hash, $path) = @_;
5493 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
5494 return ++$self->{nr};
5496 undef;
5499 sub DESTROY {
5500 my ($self) = @_;
5501 command_close_pipe($self->{gui}, $self->{ctx});
5504 package Git::SVN::GlobSpec;
5505 use strict;
5506 use warnings;
5508 sub new {
5509 my ($class, $glob) = @_;
5510 my $re = $glob;
5511 $re =~ s!/+$!!g; # no need for trailing slashes
5512 $re =~ m!^([^*]*)(\*(?:/\*)*)([^*]*)$!;
5513 my $temp = $re;
5514 my ($left, $right) = ($1, $3);
5515 $re = $2;
5516 my $depth = $re =~ tr/*/*/;
5517 if ($depth != $temp =~ tr/*/*/) {
5518 die "Only one set of wildcard directories " .
5519 "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
5521 if ($depth == 0) {
5522 die "One '*' is needed for glob: '$glob'\n";
5524 $re =~ s!\*!\[^/\]*!g;
5525 $re = quotemeta($left) . "($re)" . quotemeta($right);
5526 if (length $left && !($left =~ s!/+$!!g)) {
5527 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
5529 if (length $right && !($right =~ s!^/+!!g)) {
5530 die "Missing leading '/' on right side of: '$glob' ($right)\n";
5532 my $left_re = qr/^\/\Q$left\E(\/|$)/;
5533 bless { left => $left, right => $right, left_regex => $left_re,
5534 regex => qr/$re/, glob => $glob, depth => $depth }, $class;
5537 sub full_path {
5538 my ($self, $path) = @_;
5539 return (length $self->{left} ? "$self->{left}/" : '') .
5540 $path . (length $self->{right} ? "/$self->{right}" : '');
5543 __END__
5545 Data structures:
5548 $remotes = { # returned by read_all_remotes()
5549 'svn' => {
5550 # svn-remote.svn.url=https://svn.musicpd.org
5551 url => 'https://svn.musicpd.org',
5552 # svn-remote.svn.fetch=mpd/trunk:trunk
5553 fetch => {
5554 'mpd/trunk' => 'trunk',
5556 # svn-remote.svn.tags=mpd/tags/*:tags/*
5557 tags => {
5558 path => {
5559 left => 'mpd/tags',
5560 right => '',
5561 regex => qr!mpd/tags/([^/]+)$!,
5562 glob => 'tags/*',
5564 ref => {
5565 left => 'tags',
5566 right => '',
5567 regex => qr!tags/([^/]+)$!,
5568 glob => 'tags/*',
5574 $log_entry hashref as returned by libsvn_log_entry()
5576 log => 'whitespace-formatted log entry
5577 ', # trailing newline is preserved
5578 revision => '8', # integer
5579 date => '2004-02-24T17:01:44.108345Z', # commit date
5580 author => 'committer name'
5584 # this is generated by generate_diff();
5585 @mods = array of diff-index line hashes, each element represents one line
5586 of diff-index output
5588 diff-index line ($m hash)
5590 mode_a => first column of diff-index output, no leading ':',
5591 mode_b => second column of diff-index output,
5592 sha1_b => sha1sum of the final blob,
5593 chg => change type [MCRADT],
5594 file_a => original file name of a file (iff chg is 'C' or 'R')
5595 file_b => new/current file name of a file (any chg)
5599 # retval of read_url_paths{,_all}();
5600 $l_map = {
5601 # repository root url
5602 'https://svn.musicpd.org' => {
5603 # repository path # GIT_SVN_ID
5604 'mpd/trunk' => 'trunk',
5605 'mpd/tags/0.11.5' => 'tags/0.11.5',
5609 Notes:
5610 I don't trust the each() function on unless I created %hash myself
5611 because the internal iterator may not have started at base.