git-svn: Remove unnecessary Git::SVN::Util package
[git/mjg.git] / git-svn.perl
blobaf01dac894c34154063723c346884ef8f261d5b4
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
8 $_q $_authors %users/;
9 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
10 $VERSION = '@@GIT_VERSION@@';
12 # From which subdir have we been invoked?
13 my $cmd_dir_prefix = eval {
14 command_oneline([qw/rev-parse --show-prefix/], STDERR => 0)
15 } || '';
17 my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
18 $ENV{GIT_DIR} ||= '.git';
19 $Git::SVN::default_repo_id = 'svn';
20 $Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
21 $Git::SVN::Ra::_log_window_size = 100;
23 $Git::SVN::Log::TZ = $ENV{TZ};
24 $ENV{TZ} = 'UTC';
25 $| = 1; # unbuffer STDOUT
27 sub fatal (@) { print STDERR "@_\n"; exit 1 }
28 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
29 require SVN::Ra;
30 require SVN::Delta;
31 if ($SVN::Core::VERSION lt '1.1.0') {
32 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
34 push @Git::SVN::Ra::ISA, 'SVN::Ra';
35 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
36 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
37 use Carp qw/croak/;
38 use Digest::MD5;
39 use IO::File qw//;
40 use File::Basename qw/dirname basename/;
41 use File::Path qw/mkpath/;
42 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
43 use IPC::Open3;
44 use Git;
46 BEGIN {
47 # import functions from Git into our packages, en masse
48 no strict 'refs';
49 foreach (qw/command command_oneline command_noisy command_output_pipe
50 command_input_pipe command_close_pipe/) {
51 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
52 Git::SVN::Migration Git::SVN::Log Git::SVN),
53 __PACKAGE__) {
54 *{"${package}::$_"} = \&{"Git::$_"};
59 my ($SVN);
61 $sha1 = qr/[a-f\d]{40}/;
62 $sha1_short = qr/[a-f\d]{4,40}/;
63 my ($_stdin, $_help, $_edit,
64 $_message, $_file,
65 $_template, $_shared,
66 $_version, $_fetch_all, $_no_rebase,
67 $_merge, $_strategy, $_dry_run, $_local,
68 $_prefix, $_no_checkout, $_url, $_verbose);
69 $Git::SVN::_follow_parent = 1;
70 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
71 'config-dir=s' => \$Git::SVN::Ra::config_dir,
72 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache );
73 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
74 'authors-file|A=s' => \$_authors,
75 'repack:i' => \$Git::SVN::_repack,
76 'noMetadata' => \$Git::SVN::_no_metadata,
77 'useSvmProps' => \$Git::SVN::_use_svm_props,
78 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
79 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
80 'no-checkout' => \$_no_checkout,
81 'quiet|q' => \$_q,
82 'repack-flags|repack-args|repack-opts=s' =>
83 \$Git::SVN::_repack_flags,
84 'use-log-author' => \$Git::SVN::_use_log_author,
85 %remote_opts );
87 my ($_trunk, $_tags, $_branches, $_stdlayout);
88 my %icv;
89 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
90 'trunk|T=s' => \$_trunk, 'tags|t=s' => \$_tags,
91 'branches|b=s' => \$_branches, 'prefix=s' => \$_prefix,
92 'stdlayout|s' => \$_stdlayout,
93 'minimize-url|m' => \$Git::SVN::_minimize_url,
94 'no-metadata' => sub { $icv{noMetadata} = 1 },
95 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
96 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
97 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
98 %remote_opts );
99 my %cmt_opts = ( 'edit|e' => \$_edit,
100 'rmdir' => \$SVN::Git::Editor::_rmdir,
101 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
102 'l=i' => \$SVN::Git::Editor::_rename_limit,
103 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
106 my %cmd = (
107 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
108 { 'revision|r=s' => \$_revision,
109 'fetch-all|all' => \$_fetch_all,
110 %fc_opts } ],
111 clone => [ \&cmd_clone, "Initialize and fetch revisions",
112 { 'revision|r=s' => \$_revision,
113 %fc_opts, %init_opts } ],
114 init => [ \&cmd_init, "Initialize a repo for tracking" .
115 " (requires URL argument)",
116 \%init_opts ],
117 'multi-init' => [ \&cmd_multi_init,
118 "Deprecated alias for ".
119 "'$0 init -T<trunk> -b<branches> -t<tags>'",
120 \%init_opts ],
121 dcommit => [ \&cmd_dcommit,
122 'Commit several diffs to merge with upstream',
123 { 'merge|m|M' => \$_merge,
124 'strategy|s=s' => \$_strategy,
125 'verbose|v' => \$_verbose,
126 'dry-run|n' => \$_dry_run,
127 'fetch-all|all' => \$_fetch_all,
128 'no-rebase' => \$_no_rebase,
129 %cmt_opts, %fc_opts } ],
130 'set-tree' => [ \&cmd_set_tree,
131 "Set an SVN repository to a git tree-ish",
132 { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
133 'create-ignore' => [ \&cmd_create_ignore,
134 'Create a .gitignore per svn:ignore',
135 { 'revision|r=i' => \$_revision
136 } ],
137 'propget' => [ \&cmd_propget,
138 'Print the value of a property on a file or directory',
139 { 'revision|r=i' => \$_revision } ],
140 'proplist' => [ \&cmd_proplist,
141 'List all properties of a file or directory',
142 { 'revision|r=i' => \$_revision } ],
143 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
144 { 'revision|r=i' => \$_revision
145 } ],
146 'multi-fetch' => [ \&cmd_multi_fetch,
147 "Deprecated alias for $0 fetch --all",
148 { 'revision|r=s' => \$_revision, %fc_opts } ],
149 'migrate' => [ sub { },
150 # no-op, we automatically run this anyways,
151 'Migrate configuration/metadata/layout from
152 previous versions of git-svn',
153 { 'minimize' => \$Git::SVN::Migration::_minimize,
154 %remote_opts } ],
155 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
156 { 'limit=i' => \$Git::SVN::Log::limit,
157 'revision|r=s' => \$_revision,
158 'verbose|v' => \$Git::SVN::Log::verbose,
159 'incremental' => \$Git::SVN::Log::incremental,
160 'oneline' => \$Git::SVN::Log::oneline,
161 'show-commit' => \$Git::SVN::Log::show_commit,
162 'non-recursive' => \$Git::SVN::Log::non_recursive,
163 'authors-file|A=s' => \$_authors,
164 'color' => \$Git::SVN::Log::color,
165 'pager=s' => \$Git::SVN::Log::pager
166 } ],
167 'find-rev' => [ \&cmd_find_rev, "Translate between SVN revision numbers and tree-ish",
168 {} ],
169 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
170 { 'merge|m|M' => \$_merge,
171 'verbose|v' => \$_verbose,
172 'strategy|s=s' => \$_strategy,
173 'local|l' => \$_local,
174 'fetch-all|all' => \$_fetch_all,
175 %fc_opts } ],
176 'commit-diff' => [ \&cmd_commit_diff,
177 'Commit a diff between two trees',
178 { 'message|m=s' => \$_message,
179 'file|F=s' => \$_file,
180 'revision|r=s' => \$_revision,
181 %cmt_opts } ],
182 'info' => [ \&cmd_info,
183 "Show info about the latest SVN revision
184 on the current branch",
185 { 'url' => \$_url, } ],
188 my $cmd;
189 for (my $i = 0; $i < @ARGV; $i++) {
190 if (defined $cmd{$ARGV[$i]}) {
191 $cmd = $ARGV[$i];
192 splice @ARGV, $i, 1;
193 last;
197 # make sure we're always running
198 unless ($cmd =~ /(?:clone|init|multi-init)$/) {
199 unless (-d $ENV{GIT_DIR}) {
200 if ($git_dir_user_set) {
201 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
202 "but it is not a directory\n";
204 my $git_dir = delete $ENV{GIT_DIR};
205 chomp(my $cdup = command_oneline(qw/rev-parse --show-cdup/));
206 unless (length $cdup) {
207 die "Already at toplevel, but $git_dir ",
208 "not found '$cdup'\n";
210 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
211 unless (-d $git_dir) {
212 die "$git_dir still not found after going to ",
213 "'$cdup'\n";
215 $ENV{GIT_DIR} = $git_dir;
219 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
221 read_repo_config(\%opts);
222 Getopt::Long::Configure('pass_through') if ($cmd && $cmd eq 'log');
223 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
224 'minimize-connections' => \$Git::SVN::Migration::_minimize,
225 'id|i=s' => \$Git::SVN::default_ref_id,
226 'svn-remote|remote|R=s' => sub {
227 $Git::SVN::no_reuse_existing = 1;
228 $Git::SVN::default_repo_id = $_[1] });
229 exit 1 if (!$rv && $cmd && $cmd ne 'log');
231 usage(0) if $_help;
232 version() if $_version;
233 usage(1) unless defined $cmd;
234 load_authors() if $_authors;
236 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
237 Git::SVN::Migration::migration_check();
239 Git::SVN::init_vars();
240 eval {
241 Git::SVN::verify_remotes_sanity();
242 $cmd{$cmd}->[0]->(@ARGV);
244 fatal $@ if $@;
245 post_fetch_checkout();
246 exit 0;
248 ####################### primary functions ######################
249 sub usage {
250 my $exit = shift || 0;
251 my $fd = $exit ? \*STDERR : \*STDOUT;
252 print $fd <<"";
253 git-svn - bidirectional operations between a single Subversion tree and git
254 Usage: $0 <command> [options] [arguments]\n
256 print $fd "Available commands:\n" unless $cmd;
258 foreach (sort keys %cmd) {
259 next if $cmd && $cmd ne $_;
260 next if /^multi-/; # don't show deprecated commands
261 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
262 foreach (sort keys %{$cmd{$_}->[2]}) {
263 # mixed-case options are for .git/config only
264 next if /[A-Z]/ && /^[a-z]+$/i;
265 # prints out arguments as they should be passed:
266 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
267 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
268 "--$_" : "-$_" }
269 split /\|/,$_)," $x\n";
272 print $fd <<"";
273 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
274 arbitrary identifier if you're tracking multiple SVN branches/repositories in
275 one git repository and want to keep them separate. See git-svn(1) for more
276 information.
278 exit $exit;
281 sub version {
282 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
283 exit 0;
286 sub do_git_init_db {
287 unless (-d $ENV{GIT_DIR}) {
288 my @init_db = ('init');
289 push @init_db, "--template=$_template" if defined $_template;
290 if (defined $_shared) {
291 if ($_shared =~ /[a-z]/) {
292 push @init_db, "--shared=$_shared";
293 } else {
294 push @init_db, "--shared";
297 command_noisy(@init_db);
299 my $set;
300 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
301 foreach my $i (keys %icv) {
302 die "'$set' and '$i' cannot both be set\n" if $set;
303 next unless defined $icv{$i};
304 command_noisy('config', "$pfx.$i", $icv{$i});
305 $set = $i;
309 sub init_subdir {
310 my $repo_path = shift or return;
311 mkpath([$repo_path]) unless -d $repo_path;
312 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
313 $ENV{GIT_DIR} = '.git';
316 sub cmd_clone {
317 my ($url, $path) = @_;
318 if (!defined $path &&
319 (defined $_trunk || defined $_branches || defined $_tags ||
320 defined $_stdlayout) &&
321 $url !~ m#^[a-z\+]+://#) {
322 $path = $url;
324 $path = basename($url) if !defined $path || !length $path;
325 cmd_init($url, $path);
326 Git::SVN::fetch_all($Git::SVN::default_repo_id);
329 sub cmd_init {
330 if (defined $_stdlayout) {
331 $_trunk = 'trunk' if (!defined $_trunk);
332 $_tags = 'tags' if (!defined $_tags);
333 $_branches = 'branches' if (!defined $_branches);
335 if (defined $_trunk || defined $_branches || defined $_tags) {
336 return cmd_multi_init(@_);
338 my $url = shift or die "SVN repository location required ",
339 "as a command-line argument\n";
340 init_subdir(@_);
341 do_git_init_db();
343 Git::SVN->init($url);
346 sub cmd_fetch {
347 if (grep /^\d+=./, @_) {
348 die "'<rev>=<commit>' fetch arguments are ",
349 "no longer supported.\n";
351 my ($remote) = @_;
352 if (@_ > 1) {
353 die "Usage: $0 fetch [--all] [svn-remote]\n";
355 $remote ||= $Git::SVN::default_repo_id;
356 if ($_fetch_all) {
357 cmd_multi_fetch();
358 } else {
359 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
363 sub cmd_set_tree {
364 my (@commits) = @_;
365 if ($_stdin || !@commits) {
366 print "Reading from stdin...\n";
367 @commits = ();
368 while (<STDIN>) {
369 if (/\b($sha1_short)\b/o) {
370 unshift @commits, $1;
374 my @revs;
375 foreach my $c (@commits) {
376 my @tmp = command('rev-parse',$c);
377 if (scalar @tmp == 1) {
378 push @revs, $tmp[0];
379 } elsif (scalar @tmp > 1) {
380 push @revs, reverse(command('rev-list',@tmp));
381 } else {
382 fatal "Failed to rev-parse $c";
385 my $gs = Git::SVN->new;
386 my ($r_last, $cmt_last) = $gs->last_rev_commit;
387 $gs->fetch;
388 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
389 fatal "There are new revisions that were fetched ",
390 "and need to be merged (or acknowledged) ",
391 "before committing.\nlast rev: $r_last\n",
392 " current: $gs->{last_rev}";
394 $gs->set_tree($_) foreach @revs;
395 print "Done committing ",scalar @revs," revisions to SVN\n";
398 sub cmd_dcommit {
399 my $head = shift;
400 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
401 'Cannot dcommit with a dirty index. Commit your changes first, '
402 . "or stash them with `git stash'.\n";
403 $head ||= 'HEAD';
404 my @refs;
405 my ($url, $rev, $uuid, $gs) = working_head_info($head, \@refs);
406 print "Committing to $url ...\n";
407 unless ($gs) {
408 die "Unable to determine upstream SVN information from ",
409 "$head history\n";
411 my $last_rev;
412 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
413 if ($_no_rebase && scalar(@$linear_refs) > 1) {
414 warn "Attempting to commit more than one change while ",
415 "--no-rebase is enabled.\n",
416 "If these changes depend on each other, re-running ",
417 "without --no-rebase will be required."
419 while (1) {
420 my $d = shift @$linear_refs or last;
421 unless (defined $last_rev) {
422 (undef, $last_rev, undef) = cmt_metadata("$d~1");
423 unless (defined $last_rev) {
424 fatal "Unable to extract revision information ",
425 "from commit $d~1";
428 if ($_dry_run) {
429 print "diff-tree $d~1 $d\n";
430 } else {
431 my $cmt_rev;
432 my %ed_opts = ( r => $last_rev,
433 log => get_commit_entry($d)->{log},
434 ra => Git::SVN::Ra->new($gs->full_url),
435 config => SVN::Core::config_get_config(
436 $Git::SVN::Ra::config_dir
438 tree_a => "$d~1",
439 tree_b => $d,
440 editor_cb => sub {
441 print "Committed r$_[0]\n";
442 $cmt_rev = $_[0];
444 svn_path => '');
445 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
446 print "No changes\n$d~1 == $d\n";
447 } elsif ($parents->{$d} && @{$parents->{$d}}) {
448 $gs->{inject_parents_dcommit}->{$cmt_rev} =
449 $parents->{$d};
451 $_fetch_all ? $gs->fetch_all : $gs->fetch;
452 next if $_no_rebase;
454 # we always want to rebase against the current HEAD,
455 # not any head that was passed to us
456 my @diff = command('diff-tree', $d,
457 $gs->refname, '--');
458 my @finish;
459 if (@diff) {
460 @finish = rebase_cmd();
461 print STDERR "W: $d and ", $gs->refname,
462 " differ, using @finish:\n",
463 join("\n", @diff), "\n";
464 } else {
465 print "No changes between current HEAD and ",
466 $gs->refname,
467 "\nResetting to the latest ",
468 $gs->refname, "\n";
469 @finish = qw/reset --mixed/;
471 command_noisy(@finish, $gs->refname);
472 if (@diff) {
473 @refs = ();
474 my ($url_, $rev_, $uuid_, $gs_) =
475 working_head_info($head, \@refs);
476 my ($linear_refs_, $parents_) =
477 linearize_history($gs_, \@refs);
478 if (scalar(@$linear_refs) !=
479 scalar(@$linear_refs_)) {
480 fatal "# of revisions changed ",
481 "\nbefore:\n",
482 join("\n", @$linear_refs),
483 "\n\nafter:\n",
484 join("\n", @$linear_refs_), "\n",
485 'If you are attempting to commit ',
486 "merges, try running:\n\t",
487 'git rebase --interactive',
488 '--preserve-merges ',
489 $gs->refname,
490 "\nBefore dcommitting";
492 if ($url_ ne $url) {
493 fatal "URL mismatch after rebase: ",
494 "$url_ != $url";
496 if ($uuid_ ne $uuid) {
497 fatal "uuid mismatch after rebase: ",
498 "$uuid_ != $uuid";
500 # remap parents
501 my (%p, @l, $i);
502 for ($i = 0; $i < scalar @$linear_refs; $i++) {
503 my $new = $linear_refs_->[$i] or next;
504 $p{$new} =
505 $parents->{$linear_refs->[$i]};
506 push @l, $new;
508 $parents = \%p;
509 $linear_refs = \@l;
511 $last_rev = $cmt_rev;
516 sub cmd_find_rev {
517 my $revision_or_hash = shift;
518 my $result;
519 if ($revision_or_hash =~ /^r\d+$/) {
520 my $head = shift;
521 $head ||= 'HEAD';
522 my @refs;
523 my (undef, undef, undef, $gs) = working_head_info($head, \@refs);
524 unless ($gs) {
525 die "Unable to determine upstream SVN information from ",
526 "$head history\n";
528 my $desired_revision = substr($revision_or_hash, 1);
529 $result = $gs->rev_db_get($desired_revision);
530 } else {
531 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
532 $result = $rev;
534 print "$result\n" if $result;
537 sub cmd_rebase {
538 command_noisy(qw/update-index --refresh/);
539 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
540 unless ($gs) {
541 die "Unable to determine upstream SVN information from ",
542 "working tree history\n";
544 if (command(qw/diff-index HEAD --/)) {
545 print STDERR "Cannot rebase with uncommited changes:\n";
546 command_noisy('status');
547 exit 1;
549 unless ($_local) {
550 $_fetch_all ? $gs->fetch_all : $gs->fetch;
552 command_noisy(rebase_cmd(), $gs->refname);
555 sub cmd_show_ignore {
556 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
557 $gs ||= Git::SVN->new;
558 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
559 $gs->prop_walk($gs->{path}, $r, sub {
560 my ($gs, $path, $props) = @_;
561 print STDOUT "\n# $path\n";
562 my $s = $props->{'svn:ignore'} or return;
563 $s =~ s/[\r\n]+/\n/g;
564 chomp $s;
565 $s =~ s#^#$path#gm;
566 print STDOUT "$s\n";
570 sub cmd_create_ignore {
571 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
572 $gs ||= Git::SVN->new;
573 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
574 $gs->prop_walk($gs->{path}, $r, sub {
575 my ($gs, $path, $props) = @_;
576 # $path is of the form /path/to/dir/
577 my $ignore = '.' . $path . '.gitignore';
578 my $s = $props->{'svn:ignore'} or return;
579 open(GITIGNORE, '>', $ignore)
580 or fatal("Failed to open `$ignore' for writing: $!");
581 $s =~ s/[\r\n]+/\n/g;
582 chomp $s;
583 # Prefix all patterns so that the ignore doesn't apply
584 # to sub-directories.
585 $s =~ s#^#/#gm;
586 print GITIGNORE "$s\n";
587 close(GITIGNORE)
588 or fatal("Failed to close `$ignore': $!");
589 command_noisy('add', $ignore);
593 sub canonicalize_path {
594 my ($path) = @_;
595 my $dot_slash_added = 0;
596 if (substr($path, 0, 1) ne "/") {
597 $path = "./" . $path;
598 $dot_slash_added = 1;
600 # File::Spec->canonpath doesn't collapse x/../y into y (for a
601 # good reason), so let's do this manually.
602 $path =~ s#/+#/#g;
603 $path =~ s#/\.(?:/|$)#/#g;
604 $path =~ s#/[^/]+/\.\.##g;
605 $path =~ s#/$##g;
606 $path =~ s#^\./## if $dot_slash_added;
607 return $path;
610 # get_svnprops(PATH)
611 # ------------------
612 # Helper for cmd_propget and cmd_proplist below.
613 sub get_svnprops {
614 my $path = shift;
615 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
616 $gs ||= Git::SVN->new;
618 # prefix THE PATH by the sub-directory from which the user
619 # invoked us.
620 $path = $cmd_dir_prefix . $path;
621 fatal("No such file or directory: $path") unless -e $path;
622 my $is_dir = -d $path ? 1 : 0;
623 $path = $gs->{path} . '/' . $path;
625 # canonicalize the path (otherwise libsvn will abort or fail to
626 # find the file)
627 $path = canonicalize_path($path);
629 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
630 my $props;
631 if ($is_dir) {
632 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
634 else {
635 (undef, $props) = $gs->ra->get_file($path, $r, undef);
637 return $props;
640 # cmd_propget (PROP, PATH)
641 # ------------------------
642 # Print the SVN property PROP for PATH.
643 sub cmd_propget {
644 my ($prop, $path) = @_;
645 $path = '.' if not defined $path;
646 usage(1) if not defined $prop;
647 my $props = get_svnprops($path);
648 if (not defined $props->{$prop}) {
649 fatal("`$path' does not have a `$prop' SVN property.");
651 print $props->{$prop} . "\n";
654 # cmd_proplist (PATH)
655 # -------------------
656 # Print the list of SVN properties for PATH.
657 sub cmd_proplist {
658 my $path = shift;
659 $path = '.' if not defined $path;
660 my $props = get_svnprops($path);
661 print "Properties on '$path':\n";
662 foreach (sort keys %{$props}) {
663 print " $_\n";
667 sub cmd_multi_init {
668 my $url = shift;
669 unless (defined $_trunk || defined $_branches || defined $_tags) {
670 usage(1);
673 # there are currently some bugs that prevent multi-init/multi-fetch
674 # setups from working well without this.
675 $Git::SVN::_minimize_url = 1;
677 $_prefix = '' unless defined $_prefix;
678 if (defined $url) {
679 $url =~ s#/+$##;
680 init_subdir(@_);
682 do_git_init_db();
683 if (defined $_trunk) {
684 my $trunk_ref = $_prefix . 'trunk';
685 # try both old-style and new-style lookups:
686 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
687 unless ($gs_trunk) {
688 my ($trunk_url, $trunk_path) =
689 complete_svn_url($url, $_trunk);
690 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
691 undef, $trunk_ref);
694 return unless defined $_branches || defined $_tags;
695 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
696 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
697 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
700 sub cmd_multi_fetch {
701 my $remotes = Git::SVN::read_all_remotes();
702 foreach my $repo_id (sort keys %$remotes) {
703 if ($remotes->{$repo_id}->{url}) {
704 Git::SVN::fetch_all($repo_id, $remotes);
709 # this command is special because it requires no metadata
710 sub cmd_commit_diff {
711 my ($ta, $tb, $url) = @_;
712 my $usage = "Usage: $0 commit-diff -r<revision> ".
713 "<tree-ish> <tree-ish> [<URL>]";
714 fatal($usage) if (!defined $ta || !defined $tb);
715 my $svn_path;
716 if (!defined $url) {
717 my $gs = eval { Git::SVN->new };
718 if (!$gs) {
719 fatal("Needed URL or usable git-svn --id in ",
720 "the command-line\n", $usage);
722 $url = $gs->{url};
723 $svn_path = $gs->{path};
725 unless (defined $_revision) {
726 fatal("-r|--revision is a required argument\n", $usage);
728 if (defined $_message && defined $_file) {
729 fatal("Both --message/-m and --file/-F specified ",
730 "for the commit message.\n",
731 "I have no idea what you mean");
733 if (defined $_file) {
734 $_message = file_to_s($_file);
735 } else {
736 $_message ||= get_commit_entry($tb)->{log};
738 my $ra ||= Git::SVN::Ra->new($url);
739 $svn_path ||= $ra->{svn_path};
740 my $r = $_revision;
741 if ($r eq 'HEAD') {
742 $r = $ra->get_latest_revnum;
743 } elsif ($r !~ /^\d+$/) {
744 die "revision argument: $r not understood by git-svn\n";
746 my %ed_opts = ( r => $r,
747 log => $_message,
748 ra => $ra,
749 tree_a => $ta,
750 tree_b => $tb,
751 editor_cb => sub { print "Committed r$_[0]\n" },
752 svn_path => $svn_path );
753 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
754 print "No changes\n$ta == $tb\n";
758 sub cmd_info {
759 my $path = canonicalize_path(shift or ".");
760 unless (scalar(@_) == 0) {
761 die "Too many arguments specified\n";
764 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
766 if (!$file_type && !$diff_status) {
767 print STDERR "$path: (Not a versioned resource)\n\n";
768 return;
771 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
772 unless ($gs) {
773 die "Unable to determine upstream SVN information from ",
774 "working tree history\n";
776 my $full_url = $url . ($path eq "." ? "" : "/$path");
778 if ($_url) {
779 print $full_url, "\n";
780 return;
783 my $result = "Path: $path\n";
784 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
785 $result .= "URL: " . $full_url . "\n";
787 eval {
788 my $repos_root = $gs->repos_root;
789 Git::SVN::remove_username($repos_root);
790 $result .= "Repository Root: $repos_root\n";
792 if ($@) {
793 $result .= "Repository Root: (offline)\n";
795 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A";
796 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
798 $result .= "Node Kind: " .
799 ($file_type eq "dir" ? "directory" : "file") . "\n";
801 my $schedule = $diff_status eq "A"
802 ? "add"
803 : ($diff_status eq "D" ? "delete" : "normal");
804 $result .= "Schedule: $schedule\n";
806 if ($diff_status eq "A") {
807 print $result, "\n";
808 return;
811 my ($lc_author, $lc_rev, $lc_date_utc);
812 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $path);
813 my $log = command_output_pipe(@args);
814 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
815 while (<$log>) {
816 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
817 $lc_author = $1;
818 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
819 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
820 (undef, $lc_rev, undef) = ::extract_metadata($1);
823 close $log;
825 Git::SVN::Log::set_local_timezone();
827 $result .= "Last Changed Author: $lc_author\n";
828 $result .= "Last Changed Rev: $lc_rev\n";
829 $result .= "Last Changed Date: " .
830 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
832 if ($file_type ne "dir") {
833 my $text_last_updated_date =
834 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
835 $result .=
836 "Text Last Updated: " .
837 Git::SVN::Log::format_svn_date($text_last_updated_date) .
838 "\n";
839 my $checksum;
840 if ($diff_status eq "D") {
841 my ($fh, $ctx) =
842 command_output_pipe(qw(cat-file blob), "HEAD:$path");
843 if ($file_type eq "link") {
844 my $file_name = <$fh>;
845 $checksum = md5sum("link $file_name");
846 } else {
847 $checksum = md5sum($fh);
849 command_close_pipe($fh, $ctx);
850 } elsif ($file_type eq "link") {
851 my $file_name =
852 command(qw(cat-file blob), "HEAD:$path");
853 $checksum =
854 md5sum("link " . $file_name);
855 } else {
856 open FILE, "<", $path or die $!;
857 $checksum = md5sum(\*FILE);
858 close FILE or die $!;
860 $result .= "Checksum: " . $checksum . "\n";
863 print $result, "\n";
866 ########################### utility functions #########################
868 sub rebase_cmd {
869 my @cmd = qw/rebase/;
870 push @cmd, '-v' if $_verbose;
871 push @cmd, qw/--merge/ if $_merge;
872 push @cmd, "--strategy=$_strategy" if $_strategy;
873 @cmd;
876 sub post_fetch_checkout {
877 return if $_no_checkout;
878 my $gs = $Git::SVN::_head or return;
879 return if verify_ref('refs/heads/master^0');
881 my $valid_head = verify_ref('HEAD^0');
882 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
883 return if ($valid_head || !verify_ref('HEAD^0'));
885 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
886 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
887 return if -f $index;
889 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
890 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
891 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
892 print STDERR "Checked out HEAD:\n ",
893 $gs->full_url, " r", $gs->last_rev, "\n";
896 sub complete_svn_url {
897 my ($url, $path) = @_;
898 $path =~ s#/+$##;
899 if ($path !~ m#^[a-z\+]+://#) {
900 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
901 fatal("E: '$path' is not a complete URL ",
902 "and a separate URL is not specified");
904 return ($url, $path);
906 return ($path, '');
909 sub complete_url_ls_init {
910 my ($ra, $repo_path, $switch, $pfx) = @_;
911 unless ($repo_path) {
912 print STDERR "W: $switch not specified\n";
913 return;
915 $repo_path =~ s#/+$##;
916 if ($repo_path =~ m#^[a-z\+]+://#) {
917 $ra = Git::SVN::Ra->new($repo_path);
918 $repo_path = '';
919 } else {
920 $repo_path =~ s#^/+##;
921 unless ($ra) {
922 fatal("E: '$repo_path' is not a complete URL ",
923 "and a separate URL is not specified");
926 my $url = $ra->{url};
927 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
928 my $k = "svn-remote.$gs->{repo_id}.url";
929 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
930 if ($orig_url && ($orig_url ne $gs->{url})) {
931 die "$k already set: $orig_url\n",
932 "wanted to set to: $gs->{url}\n";
934 command_oneline('config', $k, $gs->{url}) unless $orig_url;
935 my $remote_path = "$ra->{svn_path}/$repo_path/*";
936 $remote_path =~ s#/+#/#g;
937 $remote_path =~ s#^/##g;
938 my ($n) = ($switch =~ /^--(\w+)/);
939 if (length $pfx && $pfx !~ m#/$#) {
940 die "--prefix='$pfx' must have a trailing slash '/'\n";
942 command_noisy('config', "svn-remote.$gs->{repo_id}.$n",
943 "$remote_path:refs/remotes/$pfx*");
946 sub verify_ref {
947 my ($ref) = @_;
948 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
949 { STDERR => 0 }); };
952 sub get_tree_from_treeish {
953 my ($treeish) = @_;
954 # $treeish can be a symbolic ref, too:
955 my $type = command_oneline(qw/cat-file -t/, $treeish);
956 my $expected;
957 while ($type eq 'tag') {
958 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
960 if ($type eq 'commit') {
961 $expected = (grep /^tree /, command(qw/cat-file commit/,
962 $treeish))[0];
963 ($expected) = ($expected =~ /^tree ($sha1)$/o);
964 die "Unable to get tree from $treeish\n" unless $expected;
965 } elsif ($type eq 'tree') {
966 $expected = $treeish;
967 } else {
968 die "$treeish is a $type, expected tree, tag or commit\n";
970 return $expected;
973 sub get_commit_entry {
974 my ($treeish) = shift;
975 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
976 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
977 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
978 open my $log_fh, '>', $commit_editmsg or croak $!;
980 my $type = command_oneline(qw/cat-file -t/, $treeish);
981 if ($type eq 'commit' || $type eq 'tag') {
982 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
983 $type, $treeish);
984 my $in_msg = 0;
985 while (<$msg_fh>) {
986 if (!$in_msg) {
987 $in_msg = 1 if (/^\s*$/);
988 } elsif (/^git-svn-id: /) {
989 # skip this for now, we regenerate the
990 # correct one on re-fetch anyways
991 # TODO: set *:merge properties or like...
992 } else {
993 print $log_fh $_ or croak $!;
996 command_close_pipe($msg_fh, $ctx);
998 close $log_fh or croak $!;
1000 if ($_edit || ($type eq 'tree')) {
1001 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1002 # TODO: strip out spaces, comments, like git-commit.sh
1003 system($editor, $commit_editmsg);
1005 rename $commit_editmsg, $commit_msg or croak $!;
1006 open $log_fh, '<', $commit_msg or croak $!;
1007 { local $/; chomp($log_entry{log} = <$log_fh>); }
1008 close $log_fh or croak $!;
1009 unlink $commit_msg;
1010 \%log_entry;
1013 sub s_to_file {
1014 my ($str, $file, $mode) = @_;
1015 open my $fd,'>',$file or croak $!;
1016 print $fd $str,"\n" or croak $!;
1017 close $fd or croak $!;
1018 chmod ($mode &~ umask, $file) if (defined $mode);
1021 sub file_to_s {
1022 my $file = shift;
1023 open my $fd,'<',$file or croak "$!: file: $file\n";
1024 local $/;
1025 my $ret = <$fd>;
1026 close $fd or croak $!;
1027 $ret =~ s/\s*$//s;
1028 return $ret;
1031 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1032 sub load_authors {
1033 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1034 my $log = $cmd eq 'log';
1035 while (<$authors>) {
1036 chomp;
1037 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1038 my ($user, $name, $email) = ($1, $2, $3);
1039 if ($log) {
1040 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1041 } else {
1042 $users{$user} = [$name, $email];
1045 close $authors or croak $!;
1048 # convert GetOpt::Long specs for use by git-config
1049 sub read_repo_config {
1050 return unless -d $ENV{GIT_DIR};
1051 my $opts = shift;
1052 my @config_only;
1053 foreach my $o (keys %$opts) {
1054 # if we have mixedCase and a long option-only, then
1055 # it's a config-only variable that we don't need for
1056 # the command-line.
1057 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1058 my $v = $opts->{$o};
1059 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1060 $key =~ s/-//g;
1061 my $arg = 'git-config';
1062 $arg .= ' --int' if ($o =~ /[:=]i$/);
1063 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1064 if (ref $v eq 'ARRAY') {
1065 chomp(my @tmp = `$arg --get-all svn.$key`);
1066 @$v = @tmp if @tmp;
1067 } else {
1068 chomp(my $tmp = `$arg --get svn.$key`);
1069 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1070 $$v = $tmp;
1074 delete @$opts{@config_only} if @config_only;
1077 sub extract_metadata {
1078 my $id = shift or return (undef, undef, undef);
1079 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1080 \s([a-f\d\-]+)$/x);
1081 if (!defined $rev || !$uuid || !$url) {
1082 # some of the original repositories I made had
1083 # identifiers like this:
1084 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
1086 return ($url, $rev, $uuid);
1089 sub cmt_metadata {
1090 return extract_metadata((grep(/^git-svn-id: /,
1091 command(qw/cat-file commit/, shift)))[-1]);
1094 sub working_head_info {
1095 my ($head, $refs) = @_;
1096 my @args = ('log', '--no-color', '--first-parent');
1097 my ($fh, $ctx) = command_output_pipe(@args, $head);
1098 my $hash;
1099 my %max;
1100 while (<$fh>) {
1101 if ( m{^commit ($::sha1)$} ) {
1102 unshift @$refs, $hash if $hash and $refs;
1103 $hash = $1;
1104 next;
1106 next unless s{^\s*(git-svn-id:)}{$1};
1107 my ($url, $rev, $uuid) = extract_metadata($_);
1108 if (defined $url && defined $rev) {
1109 next if $max{$url} and $max{$url} < $rev;
1110 if (my $gs = Git::SVN->find_by_url($url)) {
1111 my $c = $gs->rev_db_get($rev);
1112 if ($c && $c eq $hash) {
1113 close $fh; # break the pipe
1114 return ($url, $rev, $uuid, $gs);
1115 } else {
1116 $max{$url} ||= $gs->rev_db_max;
1121 command_close_pipe($fh, $ctx);
1122 (undef, undef, undef, undef);
1125 sub read_commit_parents {
1126 my ($parents, $c) = @_;
1127 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1128 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1129 @{$parents->{$c}} = split(/ /, $p);
1132 sub linearize_history {
1133 my ($gs, $refs) = @_;
1134 my %parents;
1135 foreach my $c (@$refs) {
1136 read_commit_parents(\%parents, $c);
1139 my @linear_refs;
1140 my %skip = ();
1141 my $last_svn_commit = $gs->last_commit;
1142 foreach my $c (reverse @$refs) {
1143 next if $c eq $last_svn_commit;
1144 last if $skip{$c};
1146 unshift @linear_refs, $c;
1147 $skip{$c} = 1;
1149 # we only want the first parent to diff against for linear
1150 # history, we save the rest to inject when we finalize the
1151 # svn commit
1152 my $fp_a = verify_ref("$c~1");
1153 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1154 if (!$fp_a || !$fp_b) {
1155 die "Commit $c\n",
1156 "has no parent commit, and therefore ",
1157 "nothing to diff against.\n",
1158 "You should be working from a repository ",
1159 "originally created by git-svn\n";
1161 if ($fp_a ne $fp_b) {
1162 die "$c~1 = $fp_a, however parsing commit $c ",
1163 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1166 foreach my $p (@{$parents{$c}}) {
1167 $skip{$p} = 1;
1170 (\@linear_refs, \%parents);
1173 sub find_file_type_and_diff_status {
1174 my ($path) = @_;
1175 return ('dir', '') if $path eq '.';
1177 my $diff_output =
1178 command_oneline(qw(diff --cached --name-status --), $path) || "";
1179 my $diff_status = (split(' ', $diff_output))[0] || "";
1181 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1183 return (undef, undef) if !$diff_status && !$ls_tree;
1185 if ($diff_status eq "A") {
1186 return ("link", $diff_status) if -l $path;
1187 return ("dir", $diff_status) if -d $path;
1188 return ("file", $diff_status);
1191 my $mode = (split(' ', $ls_tree))[0] || "";
1193 return ("link", $diff_status) if $mode eq "120000";
1194 return ("dir", $diff_status) if $mode eq "040000";
1195 return ("file", $diff_status);
1198 sub md5sum {
1199 my $arg = shift;
1200 my $ref = ref $arg;
1201 my $md5 = Digest::MD5->new();
1202 if ($ref eq 'GLOB' || $ref eq 'IO::File') {
1203 $md5->addfile($arg) or croak $!;
1204 } elsif ($ref eq 'SCALAR') {
1205 $md5->add($$arg) or croak $!;
1206 } elsif (!$ref) {
1207 $md5->add($arg) or croak $!;
1208 } else {
1209 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1211 return $md5->hexdigest();
1214 package Git::SVN;
1215 use strict;
1216 use warnings;
1217 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1218 $_repack $_repack_flags $_use_svm_props $_head
1219 $_use_svnsync_props $no_reuse_existing $_minimize_url
1220 $_use_log_author/;
1221 use Carp qw/croak/;
1222 use File::Path qw/mkpath/;
1223 use File::Copy qw/copy/;
1224 use IPC::Open3;
1226 my $_repack_nr;
1227 # properties that we do not log:
1228 my %SKIP_PROP;
1229 BEGIN {
1230 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1231 svn:special svn:executable
1232 svn:entry:committed-rev
1233 svn:entry:last-author
1234 svn:entry:uuid
1235 svn:entry:committed-date/;
1237 # some options are read globally, but can be overridden locally
1238 # per [svn-remote "..."] section. Command-line options will *NOT*
1239 # override options set in an [svn-remote "..."] section
1240 no strict 'refs';
1241 for my $option (qw/follow_parent no_metadata use_svm_props
1242 use_svnsync_props/) {
1243 my $key = $option;
1244 $key =~ tr/_//d;
1245 my $prop = "-$option";
1246 *$option = sub {
1247 my ($self) = @_;
1248 return $self->{$prop} if exists $self->{$prop};
1249 my $k = "svn-remote.$self->{repo_id}.$key";
1250 eval { command_oneline(qw/config --get/, $k) };
1251 if ($@) {
1252 $self->{$prop} = ${"Git::SVN::_$option"};
1253 } else {
1254 my $v = command_oneline(qw/config --bool/,$k);
1255 $self->{$prop} = $v eq 'false' ? 0 : 1;
1257 return $self->{$prop};
1262 my %LOCKFILES;
1263 END { unlink keys %LOCKFILES if %LOCKFILES }
1265 sub resolve_local_globs {
1266 my ($url, $fetch, $glob_spec) = @_;
1267 return unless defined $glob_spec;
1268 my $ref = $glob_spec->{ref};
1269 my $path = $glob_spec->{path};
1270 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
1271 next unless m#^refs/remotes/$ref->{regex}$#;
1272 my $p = $1;
1273 my $pathname = desanitize_refname($path->full_path($p));
1274 my $refname = desanitize_refname($ref->full_path($p));
1275 if (my $existing = $fetch->{$pathname}) {
1276 if ($existing ne $refname) {
1277 die "Refspec conflict:\n",
1278 "existing: refs/remotes/$existing\n",
1279 " globbed: refs/remotes/$refname\n";
1281 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
1282 $u =~ s!^\Q$url\E(/|$)!! or die
1283 "refs/remotes/$refname: '$url' not found in '$u'\n";
1284 if ($pathname ne $u) {
1285 warn "W: Refspec glob conflict ",
1286 "(ref: refs/remotes/$refname):\n",
1287 "expected path: $pathname\n",
1288 " real path: $u\n",
1289 "Continuing ahead with $u\n";
1290 next;
1292 } else {
1293 $fetch->{$pathname} = $refname;
1298 sub parse_revision_argument {
1299 my ($base, $head) = @_;
1300 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1301 return ($base, $head);
1303 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1304 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1305 return ($head, $head) if ($::_revision eq 'HEAD');
1306 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1307 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1308 die "revision argument: $::_revision not understood by git-svn\n";
1311 sub fetch_all {
1312 my ($repo_id, $remotes) = @_;
1313 if (ref $repo_id) {
1314 my $gs = $repo_id;
1315 $repo_id = undef;
1316 $repo_id = $gs->{repo_id};
1318 $remotes ||= read_all_remotes();
1319 my $remote = $remotes->{$repo_id} or
1320 die "[svn-remote \"$repo_id\"] unknown\n";
1321 my $fetch = $remote->{fetch};
1322 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1323 my (@gs, @globs);
1324 my $ra = Git::SVN::Ra->new($url);
1325 my $uuid = $ra->get_uuid;
1326 my $head = $ra->get_latest_revnum;
1327 my $base = defined $fetch ? $head : 0;
1329 # read the max revs for wildcard expansion (branches/*, tags/*)
1330 foreach my $t (qw/branches tags/) {
1331 defined $remote->{$t} or next;
1332 push @globs, $remote->{$t};
1333 my $max_rev = eval { tmp_config(qw/--int --get/,
1334 "svn-remote.$repo_id.${t}-maxRev") };
1335 if (defined $max_rev && ($max_rev < $base)) {
1336 $base = $max_rev;
1337 } elsif (!defined $max_rev) {
1338 $base = 0;
1342 if ($fetch) {
1343 foreach my $p (sort keys %$fetch) {
1344 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1345 my $lr = $gs->rev_db_max;
1346 if (defined $lr) {
1347 $base = $lr if ($lr < $base);
1349 push @gs, $gs;
1353 ($base, $head) = parse_revision_argument($base, $head);
1354 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1357 sub read_all_remotes {
1358 my $r = {};
1359 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1360 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
1361 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
1362 $local_ref =~ s{^/}{};
1363 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1364 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1365 $r->{$1}->{url} = $2;
1366 } elsif (m!^(.+)\.(branches|tags)=
1367 (.*):refs/remotes/(.+)\s*$/!x) {
1368 my ($p, $g) = ($3, $4);
1369 my $rs = $r->{$1}->{$2} = {
1370 t => $2,
1371 remote => $1,
1372 path => Git::SVN::GlobSpec->new($p),
1373 ref => Git::SVN::GlobSpec->new($g) };
1374 if (length($rs->{ref}->{right}) != 0) {
1375 die "The '*' glob character must be the last ",
1376 "character of '$g'\n";
1383 sub init_vars {
1384 if (defined $_repack) {
1385 $_repack = 1000 if ($_repack <= 0);
1386 $_repack_nr = $_repack;
1387 $_repack_flags ||= '-d';
1391 sub verify_remotes_sanity {
1392 return unless -d $ENV{GIT_DIR};
1393 my %seen;
1394 foreach (command(qw/config -l/)) {
1395 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1396 if ($seen{$1}) {
1397 die "Remote ref refs/remote/$1 is tracked by",
1398 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1399 "Please resolve this ambiguity in ",
1400 "your git configuration file before ",
1401 "continuing\n";
1403 $seen{$1} = $_;
1408 # we allow more chars than remotes2config.sh...
1409 sub sanitize_remote_name {
1410 my ($name) = @_;
1411 $name =~ tr{A-Za-z0-9:,/+-}{.}c;
1412 $name;
1415 sub find_existing_remote {
1416 my ($url, $remotes) = @_;
1417 return undef if $no_reuse_existing;
1418 my $existing;
1419 foreach my $repo_id (keys %$remotes) {
1420 my $u = $remotes->{$repo_id}->{url} or next;
1421 next if $u ne $url;
1422 $existing = $repo_id;
1423 last;
1425 $existing;
1428 sub init_remote_config {
1429 my ($self, $url, $no_write) = @_;
1430 $url =~ s!/+$!!; # strip trailing slash
1431 my $r = read_all_remotes();
1432 my $existing = find_existing_remote($url, $r);
1433 if ($existing) {
1434 unless ($no_write) {
1435 print STDERR "Using existing ",
1436 "[svn-remote \"$existing\"]\n";
1438 $self->{repo_id} = $existing;
1439 } elsif ($_minimize_url) {
1440 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1441 $existing = find_existing_remote($min_url, $r);
1442 if ($existing) {
1443 unless ($no_write) {
1444 print STDERR "Using existing ",
1445 "[svn-remote \"$existing\"]\n";
1447 $self->{repo_id} = $existing;
1449 if ($min_url ne $url) {
1450 unless ($no_write) {
1451 print STDERR "Using higher level of URL: ",
1452 "$url => $min_url\n";
1454 my $old_path = $self->{path};
1455 $self->{path} = $url;
1456 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1457 if (length $old_path) {
1458 $self->{path} .= "/$old_path";
1460 $url = $min_url;
1463 my $orig_url;
1464 if (!$existing) {
1465 # verify that we aren't overwriting anything:
1466 $orig_url = eval {
1467 command_oneline('config', '--get',
1468 "svn-remote.$self->{repo_id}.url")
1470 if ($orig_url && ($orig_url ne $url)) {
1471 die "svn-remote.$self->{repo_id}.url already set: ",
1472 "$orig_url\nwanted to set to: $url\n";
1475 my ($xrepo_id, $xpath) = find_ref($self->refname);
1476 if (defined $xpath) {
1477 die "svn-remote.$xrepo_id.fetch already set to track ",
1478 "$xpath:refs/remotes/", $self->refname, "\n";
1480 unless ($no_write) {
1481 command_noisy('config',
1482 "svn-remote.$self->{repo_id}.url", $url);
1483 $self->{path} =~ s{^/}{};
1484 command_noisy('config', '--add',
1485 "svn-remote.$self->{repo_id}.fetch",
1486 "$self->{path}:".$self->refname);
1488 $self->{url} = $url;
1491 sub find_by_url { # repos_root and, path are optional
1492 my ($class, $full_url, $repos_root, $path) = @_;
1494 return undef unless defined $full_url;
1495 remove_username($full_url);
1496 remove_username($repos_root) if defined $repos_root;
1497 my $remotes = read_all_remotes();
1498 if (defined $full_url && defined $repos_root && !defined $path) {
1499 $path = $full_url;
1500 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1502 foreach my $repo_id (keys %$remotes) {
1503 my $u = $remotes->{$repo_id}->{url} or next;
1504 remove_username($u);
1505 next if defined $repos_root && $repos_root ne $u;
1507 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1508 foreach (qw/branches tags/) {
1509 resolve_local_globs($u, $fetch,
1510 $remotes->{$repo_id}->{$_});
1512 my $p = $path;
1513 unless (defined $p) {
1514 $p = $full_url;
1515 $p =~ s#^\Q$u\E(?:/|$)## or next;
1517 foreach my $f (keys %$fetch) {
1518 next if $f ne $p;
1519 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1522 undef;
1525 sub init {
1526 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1527 my $self = _new($class, $repo_id, $ref_id, $path);
1528 if (defined $url) {
1529 $self->init_remote_config($url, $no_write);
1531 $self;
1534 sub find_ref {
1535 my ($ref_id) = @_;
1536 foreach (command(qw/config -l/)) {
1537 next unless m!^svn-remote\.(.+)\.fetch=
1538 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1539 my ($repo_id, $path, $ref) = ($1, $2, $3);
1540 if ($ref eq $ref_id) {
1541 $path = '' if ($path =~ m#^\./?#);
1542 return ($repo_id, $path);
1545 (undef, undef, undef);
1548 sub new {
1549 my ($class, $ref_id, $repo_id, $path) = @_;
1550 if (defined $ref_id && !defined $repo_id && !defined $path) {
1551 ($repo_id, $path) = find_ref($ref_id);
1552 if (!defined $repo_id) {
1553 die "Could not find a \"svn-remote.*.fetch\" key ",
1554 "in the repository configuration matching: ",
1555 "refs/remotes/$ref_id\n";
1558 my $self = _new($class, $repo_id, $ref_id, $path);
1559 if (!defined $self->{path} || !length $self->{path}) {
1560 my $fetch = command_oneline('config', '--get',
1561 "svn-remote.$repo_id.fetch",
1562 ":refs/remotes/$ref_id\$") or
1563 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1564 "\":refs/remotes/$ref_id\$\" in config\n";
1565 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1567 $self->{url} = command_oneline('config', '--get',
1568 "svn-remote.$repo_id.url") or
1569 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1570 $self->rebuild;
1571 $self;
1574 sub refname {
1575 my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1577 # It cannot end with a slash /, we'll throw up on this because
1578 # SVN can't have directories with a slash in their name, either:
1579 if ($refname =~ m{/$}) {
1580 die "ref: '$refname' ends with a trailing slash, this is ",
1581 "not permitted by git nor Subversion\n";
1584 # It cannot have ASCII control character space, tilde ~, caret ^,
1585 # colon :, question-mark ?, asterisk *, space, or open bracket [
1586 # anywhere.
1588 # Additionally, % must be escaped because it is used for escaping
1589 # and we want our escaped refname to be reversible
1590 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1592 # no slash-separated component can begin with a dot .
1593 # /.* becomes /%2E*
1594 $refname =~ s{/\.}{/%2E}g;
1596 # It cannot have two consecutive dots .. anywhere
1597 # .. becomes %2E%2E
1598 $refname =~ s{\.\.}{%2E%2E}g;
1600 return $refname;
1603 sub desanitize_refname {
1604 my ($refname) = @_;
1605 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1606 return $refname;
1609 sub svm_uuid {
1610 my ($self) = @_;
1611 return $self->{svm}->{uuid} if $self->svm;
1612 $self->ra;
1613 unless ($self->{svm}) {
1614 die "SVM UUID not cached, and reading remotely failed\n";
1616 $self->{svm}->{uuid};
1619 sub svm {
1620 my ($self) = @_;
1621 return $self->{svm} if $self->{svm};
1622 my $svm;
1623 # see if we have it in our config, first:
1624 eval {
1625 my $section = "svn-remote.$self->{repo_id}";
1626 $svm = {
1627 source => tmp_config('--get', "$section.svm-source"),
1628 uuid => tmp_config('--get', "$section.svm-uuid"),
1629 replace => tmp_config('--get', "$section.svm-replace"),
1632 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1633 $self->{svm} = $svm;
1635 $self->{svm};
1638 sub _set_svm_vars {
1639 my ($self, $ra) = @_;
1640 return $ra if $self->svm;
1642 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1643 "(svm:source, svm:uuid) ",
1644 "from the following URLs:\n" );
1645 sub read_svm_props {
1646 my ($self, $ra, $path, $r) = @_;
1647 my $props = ($ra->get_dir($path, $r))[2];
1648 my $src = $props->{'svm:source'};
1649 my $uuid = $props->{'svm:uuid'};
1650 return undef if (!$src || !$uuid);
1652 chomp($src, $uuid);
1654 $uuid =~ m{^[0-9a-f\-]{30,}$}
1655 or die "doesn't look right - svm:uuid is '$uuid'\n";
1657 # the '!' is used to mark the repos_root!/relative/path
1658 $src =~ s{/?!/?}{/};
1659 $src =~ s{/+$}{}; # no trailing slashes please
1660 # username is of no interest
1661 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1663 my $replace = $ra->{url};
1664 $replace .= "/$path" if length $path;
1666 my $section = "svn-remote.$self->{repo_id}";
1667 tmp_config("$section.svm-source", $src);
1668 tmp_config("$section.svm-replace", $replace);
1669 tmp_config("$section.svm-uuid", $uuid);
1670 $self->{svm} = {
1671 source => $src,
1672 uuid => $uuid,
1673 replace => $replace
1677 my $r = $ra->get_latest_revnum;
1678 my $path = $self->{path};
1679 my %tried;
1680 while (length $path) {
1681 unless ($tried{"$self->{url}/$path"}) {
1682 return $ra if $self->read_svm_props($ra, $path, $r);
1683 $tried{"$self->{url}/$path"} = 1;
1685 $path =~ s#/?[^/]+$##;
1687 die "Path: '$path' should be ''\n" if $path ne '';
1688 return $ra if $self->read_svm_props($ra, $path, $r);
1689 $tried{"$self->{url}/$path"} = 1;
1691 if ($ra->{repos_root} eq $self->{url}) {
1692 die @err, (map { " $_\n" } keys %tried), "\n";
1695 # nope, make sure we're connected to the repository root:
1696 my $ok;
1697 my @tried_b;
1698 $path = $ra->{svn_path};
1699 $ra = Git::SVN::Ra->new($ra->{repos_root});
1700 while (length $path) {
1701 unless ($tried{"$ra->{url}/$path"}) {
1702 $ok = $self->read_svm_props($ra, $path, $r);
1703 last if $ok;
1704 $tried{"$ra->{url}/$path"} = 1;
1706 $path =~ s#/?[^/]+$##;
1708 die "Path: '$path' should be ''\n" if $path ne '';
1709 $ok ||= $self->read_svm_props($ra, $path, $r);
1710 $tried{"$ra->{url}/$path"} = 1;
1711 if (!$ok) {
1712 die @err, (map { " $_\n" } keys %tried), "\n";
1714 Git::SVN::Ra->new($self->{url});
1717 sub svnsync {
1718 my ($self) = @_;
1719 return $self->{svnsync} if $self->{svnsync};
1721 if ($self->no_metadata) {
1722 die "Can't have both 'noMetadata' and ",
1723 "'useSvnsyncProps' options set!\n";
1725 if ($self->rewrite_root) {
1726 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1727 "options set!\n";
1730 my $svnsync;
1731 # see if we have it in our config, first:
1732 eval {
1733 my $section = "svn-remote.$self->{repo_id}";
1734 $svnsync = {
1735 url => tmp_config('--get', "$section.svnsync-url"),
1736 uuid => tmp_config('--get', "$section.svnsync-uuid"),
1739 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1740 return $self->{svnsync} = $svnsync;
1743 my $err = "useSvnsyncProps set, but failed to read " .
1744 "svnsync property: svn:sync-from-";
1745 my $rp = $self->ra->rev_proplist(0);
1747 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
1748 $url =~ m{^[a-z\+]+://} or
1749 die "doesn't look right - svn:sync-from-url is '$url'\n";
1751 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
1752 $uuid =~ m{^[0-9a-f\-]{30,}$} or
1753 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1755 my $section = "svn-remote.$self->{repo_id}";
1756 tmp_config('--add', "$section.svnsync-uuid", $uuid);
1757 tmp_config('--add', "$section.svnsync-url", $url);
1758 return $self->{svnsync} = { url => $url, uuid => $uuid };
1761 # this allows us to memoize our SVN::Ra UUID locally and avoid a
1762 # remote lookup (useful for 'git svn log').
1763 sub ra_uuid {
1764 my ($self) = @_;
1765 unless ($self->{ra_uuid}) {
1766 my $key = "svn-remote.$self->{repo_id}.uuid";
1767 my $uuid = eval { tmp_config('--get', $key) };
1768 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1769 $self->{ra_uuid} = $uuid;
1770 } else {
1771 die "ra_uuid called without URL\n" unless $self->{url};
1772 $self->{ra_uuid} = $self->ra->get_uuid;
1773 tmp_config('--add', $key, $self->{ra_uuid});
1776 $self->{ra_uuid};
1779 sub _set_repos_root {
1780 my ($self, $repos_root) = @_;
1781 my $k = "svn-remote.$self->{repo_id}.reposRoot";
1782 $repos_root ||= $self->ra->{repos_root};
1783 tmp_config($k, $repos_root);
1784 $repos_root;
1787 sub repos_root {
1788 my ($self) = @_;
1789 my $k = "svn-remote.$self->{repo_id}.reposRoot";
1790 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
1793 sub ra {
1794 my ($self) = shift;
1795 my $ra = Git::SVN::Ra->new($self->{url});
1796 $self->_set_repos_root($ra->{repos_root});
1797 if ($self->use_svm_props && !$self->{svm}) {
1798 if ($self->no_metadata) {
1799 die "Can't have both 'noMetadata' and ",
1800 "'useSvmProps' options set!\n";
1801 } elsif ($self->use_svnsync_props) {
1802 die "Can't have both 'useSvnsyncProps' and ",
1803 "'useSvmProps' options set!\n";
1805 $ra = $self->_set_svm_vars($ra);
1806 $self->{-want_revprops} = 1;
1808 $ra;
1811 sub rel_path {
1812 my ($self) = @_;
1813 my $repos_root = $self->ra->{repos_root};
1814 return $self->{path} if ($self->{url} eq $repos_root);
1815 my $url = $self->{url} .
1816 (length $self->{path} ? "/$self->{path}" : $self->{path});
1817 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
1818 $url;
1821 # prop_walk(PATH, REV, SUB)
1822 # -------------------------
1823 # Recursively traverse PATH at revision REV and invoke SUB for each
1824 # directory that contains a SVN property. SUB will be invoked as
1825 # follows: &SUB(gs, path, props); where `gs' is this instance of
1826 # Git::SVN, `path' the path to the directory where the properties
1827 # `props' were found. The `path' will be relative to point of checkout,
1828 # that is, if url://repo/trunk is the current Git branch, and that
1829 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
1830 # as `path' (note the trailing `/').
1831 sub prop_walk {
1832 my ($self, $path, $rev, $sub) = @_;
1834 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
1835 $path =~ s#^/*#/#g;
1836 my $p = $path;
1837 # Strip the irrelevant part of the path.
1838 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
1839 # Ensure the path is terminated by a `/'.
1840 $p =~ s#/*$#/#;
1842 # The properties contain all the internal SVN stuff nobody
1843 # (usually) cares about.
1844 my $interesting_props = 0;
1845 foreach (keys %{$props}) {
1846 # If it doesn't start with `svn:', it must be a
1847 # user-defined property.
1848 ++$interesting_props and next if $_ !~ /^svn:/;
1849 # FIXME: Fragile, if SVN adds new public properties,
1850 # this needs to be updated.
1851 ++$interesting_props if /^svn:(?:ignore|keywords|executable
1852 |eol-style|mime-type
1853 |externals|needs-lock)$/x;
1855 &$sub($self, $p, $props) if $interesting_props;
1857 foreach (sort keys %$dirent) {
1858 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
1859 $self->prop_walk($path . '/' . $_, $rev, $sub);
1863 sub last_rev { ($_[0]->last_rev_commit)[0] }
1864 sub last_commit { ($_[0]->last_rev_commit)[1] }
1866 # returns the newest SVN revision number and newest commit SHA1
1867 sub last_rev_commit {
1868 my ($self) = @_;
1869 if (defined $self->{last_rev} && defined $self->{last_commit}) {
1870 return ($self->{last_rev}, $self->{last_commit});
1872 my $c = ::verify_ref($self->refname.'^0');
1873 if ($c && !$self->use_svm_props && !$self->no_metadata) {
1874 my $rev = (::cmt_metadata($c))[1];
1875 if (defined $rev) {
1876 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1877 return ($rev, $c);
1880 my $db_path = $self->db_path;
1881 unless (-e $db_path) {
1882 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
1883 return (undef, undef);
1885 my $offset = -41; # from tail
1886 my $rl;
1887 open my $fh, '<', $db_path or croak "$db_path not readable: $!\n";
1888 sysseek($fh, $offset, 2); # don't care for errors
1889 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1890 chomp $rl;
1891 while (('0' x40) eq $rl && sysseek($fh, 0, 1) != 0) {
1892 $offset -= 41;
1893 sysseek($fh, $offset, 2); # don't care for errors
1894 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1895 chomp $rl;
1897 if ($c && $c ne $rl) {
1898 die "$db_path and ", $self->refname,
1899 " inconsistent!:\n$c != $rl\n";
1901 my $rev = sysseek($fh, 0, 1) or croak $!;
1902 $rev = ($rev - 41) / 41;
1903 close $fh or croak $!;
1904 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1905 return ($rev, $c);
1908 sub get_fetch_range {
1909 my ($self, $min, $max) = @_;
1910 $max ||= $self->ra->get_latest_revnum;
1911 $min ||= $self->rev_db_max;
1912 (++$min, $max);
1915 sub tmp_config {
1916 my (@args) = @_;
1917 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
1918 my $config = "$ENV{GIT_DIR}/svn/.metadata";
1919 if (! -f $config && -f $old_def_config) {
1920 rename $old_def_config, $config or
1921 die "Failed rename $old_def_config => $config: $!\n";
1923 my $old_config = $ENV{GIT_CONFIG};
1924 $ENV{GIT_CONFIG} = $config;
1925 $@ = undef;
1926 my @ret = eval {
1927 unless (-f $config) {
1928 mkfile($config);
1929 open my $fh, '>', $config or
1930 die "Can't open $config: $!\n";
1931 print $fh "; This file is used internally by ",
1932 "git-svn\n" or die
1933 "Couldn't write to $config: $!\n";
1934 print $fh "; You should not have to edit it\n" or
1935 die "Couldn't write to $config: $!\n";
1936 close $fh or die "Couldn't close $config: $!\n";
1938 command('config', @args);
1940 my $err = $@;
1941 if (defined $old_config) {
1942 $ENV{GIT_CONFIG} = $old_config;
1943 } else {
1944 delete $ENV{GIT_CONFIG};
1946 die $err if $err;
1947 wantarray ? @ret : $ret[0];
1950 sub tmp_index_do {
1951 my ($self, $sub) = @_;
1952 my $old_index = $ENV{GIT_INDEX_FILE};
1953 $ENV{GIT_INDEX_FILE} = $self->{index};
1954 $@ = undef;
1955 my @ret = eval {
1956 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
1957 mkpath([$dir]) unless -d $dir;
1958 &$sub;
1960 my $err = $@;
1961 if (defined $old_index) {
1962 $ENV{GIT_INDEX_FILE} = $old_index;
1963 } else {
1964 delete $ENV{GIT_INDEX_FILE};
1966 die $err if $err;
1967 wantarray ? @ret : $ret[0];
1970 sub assert_index_clean {
1971 my ($self, $treeish) = @_;
1973 $self->tmp_index_do(sub {
1974 command_noisy('read-tree', $treeish) unless -e $self->{index};
1975 my $x = command_oneline('write-tree');
1976 my ($y) = (command(qw/cat-file commit/, $treeish) =~
1977 /^tree ($::sha1)/mo);
1978 return if $y eq $x;
1980 warn "Index mismatch: $y != $x\nrereading $treeish\n";
1981 unlink $self->{index} or die "unlink $self->{index}: $!\n";
1982 command_noisy('read-tree', $treeish);
1983 $x = command_oneline('write-tree');
1984 if ($y ne $x) {
1985 ::fatal "trees ($treeish) $y != $x\n",
1986 "Something is seriously wrong...";
1991 sub get_commit_parents {
1992 my ($self, $log_entry) = @_;
1993 my (%seen, @ret, @tmp);
1994 # legacy support for 'set-tree'; this is only used by set_tree_cb:
1995 if (my $ip = $self->{inject_parents}) {
1996 if (my $commit = delete $ip->{$log_entry->{revision}}) {
1997 push @tmp, $commit;
2000 if (my $cur = ::verify_ref($self->refname.'^0')) {
2001 push @tmp, $cur;
2003 if (my $ipd = $self->{inject_parents_dcommit}) {
2004 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2005 push @tmp, @$commit;
2008 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2009 while (my $p = shift @tmp) {
2010 next if $seen{$p};
2011 $seen{$p} = 1;
2012 push @ret, $p;
2013 # MAXPARENT is defined to 16 in commit-tree.c:
2014 last if @ret >= 16;
2016 if (@tmp) {
2017 die "r$log_entry->{revision}: No room for parents:\n\t",
2018 join("\n\t", @tmp), "\n";
2020 @ret;
2023 sub rewrite_root {
2024 my ($self) = @_;
2025 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2026 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2027 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2028 if ($rwr) {
2029 $rwr =~ s#/+$##;
2030 if ($rwr !~ m#^[a-z\+]+://#) {
2031 die "$rwr is not a valid URL (key: $k)\n";
2034 $self->{-rewrite_root} = $rwr;
2037 sub metadata_url {
2038 my ($self) = @_;
2039 ($self->rewrite_root || $self->{url}) .
2040 (length $self->{path} ? '/' . $self->{path} : '');
2043 sub full_url {
2044 my ($self) = @_;
2045 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2048 sub do_git_commit {
2049 my ($self, $log_entry) = @_;
2050 my $lr = $self->last_rev;
2051 if (defined $lr && $lr >= $log_entry->{revision}) {
2052 die "Last fetched revision of ", $self->refname,
2053 " was r$lr, but we are about to fetch: ",
2054 "r$log_entry->{revision}!\n";
2056 if (my $c = $self->rev_db_get($log_entry->{revision})) {
2057 croak "$log_entry->{revision} = $c already exists! ",
2058 "Why are we refetching it?\n";
2060 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2061 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2062 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2064 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2065 ? $log_entry->{commit_name}
2066 : $log_entry->{name};
2067 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2068 ? $log_entry->{commit_email}
2069 : $log_entry->{email};
2071 my $tree = $log_entry->{tree};
2072 if (!defined $tree) {
2073 $tree = $self->tmp_index_do(sub {
2074 command_oneline('write-tree') });
2076 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2078 my @exec = ('git-commit-tree', $tree);
2079 foreach ($self->get_commit_parents($log_entry)) {
2080 push @exec, '-p', $_;
2082 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2083 or croak $!;
2084 print $msg_fh $log_entry->{log} or croak $!;
2085 unless ($self->no_metadata) {
2086 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2087 or croak $!;
2089 $msg_fh->flush == 0 or croak $!;
2090 close $msg_fh or croak $!;
2091 chomp(my $commit = do { local $/; <$out_fh> });
2092 close $out_fh or croak $!;
2093 waitpid $pid, 0;
2094 croak $? if $?;
2095 if ($commit !~ /^$::sha1$/o) {
2096 die "Failed to commit, invalid sha1: $commit\n";
2099 $self->rev_db_set($log_entry->{revision}, $commit, 1);
2101 $self->{last_rev} = $log_entry->{revision};
2102 $self->{last_commit} = $commit;
2103 print "r$log_entry->{revision}";
2104 if (defined $log_entry->{svm_revision}) {
2105 print " (\@$log_entry->{svm_revision})";
2106 $self->rev_db_set($log_entry->{svm_revision}, $commit,
2107 0, $self->svm_uuid);
2109 print " = $commit ($self->{ref_id})\n";
2110 if (defined $_repack && (--$_repack_nr == 0)) {
2111 $_repack_nr = $_repack;
2112 # repack doesn't use any arguments with spaces in them, does it?
2113 print "Running git repack $_repack_flags ...\n";
2114 command_noisy('repack', split(/\s+/, $_repack_flags));
2115 print "Done repacking\n";
2117 return $commit;
2120 sub match_paths {
2121 my ($self, $paths, $r) = @_;
2122 return 1 if $self->{path} eq '';
2123 if (my $path = $paths->{"/$self->{path}"}) {
2124 return ($path->{action} eq 'D') ? 0 : 1;
2126 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
2127 if (grep /$self->{path_regex}/, keys %$paths) {
2128 return 1;
2130 my $c = '';
2131 foreach (split m#/#, $self->{path}) {
2132 $c .= "/$_";
2133 next unless ($paths->{$c} &&
2134 ($paths->{$c}->{action} =~ /^[AR]$/));
2135 if ($self->ra->check_path($self->{path}, $r) ==
2136 $SVN::Node::dir) {
2137 return 1;
2140 return 0;
2143 sub find_parent_branch {
2144 my ($self, $paths, $rev) = @_;
2145 return undef unless $self->follow_parent;
2146 unless (defined $paths) {
2147 my $err_handler = $SVN::Error::handler;
2148 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2149 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
2150 $paths =
2151 Git::SVN::Ra::dup_changed_paths($_[0]) });
2152 $SVN::Error::handler = $err_handler;
2154 return undef unless defined $paths;
2156 # look for a parent from another branch:
2157 my @b_path_components = split m#/#, $self->rel_path;
2158 my @a_path_components;
2159 my $i;
2160 while (@b_path_components) {
2161 $i = $paths->{'/'.join('/', @b_path_components)};
2162 last if $i && defined $i->{copyfrom_path};
2163 unshift(@a_path_components, pop(@b_path_components));
2165 return undef unless defined $i && defined $i->{copyfrom_path};
2166 my $branch_from = $i->{copyfrom_path};
2167 if (@a_path_components) {
2168 print STDERR "branch_from: $branch_from => ";
2169 $branch_from .= '/'.join('/', @a_path_components);
2170 print STDERR $branch_from, "\n";
2172 my $r = $i->{copyfrom_rev};
2173 my $repos_root = $self->ra->{repos_root};
2174 my $url = $self->ra->{url};
2175 my $new_url = $repos_root . $branch_from;
2176 print STDERR "Found possible branch point: ",
2177 "$new_url => ", $self->full_url, ", $r\n";
2178 $branch_from =~ s#^/##;
2179 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
2180 unless ($gs) {
2181 my $ref_id = $self->{ref_id};
2182 $ref_id =~ s/\@\d+$//;
2183 $ref_id .= "\@$r";
2184 # just grow a tail if we're not unique enough :x
2185 $ref_id .= '-' while find_ref($ref_id);
2186 print STDERR "Initializing parent: $ref_id\n";
2187 $gs = Git::SVN->init($new_url, '', $ref_id, $ref_id, 1);
2189 my ($r0, $parent) = $gs->find_rev_before($r, 1);
2190 if (!defined $r0 || !defined $parent) {
2191 my ($base, $head) = parse_revision_argument(0, $r);
2192 if ($base <= $r) {
2193 $gs->fetch($base, $r);
2195 ($r0, $parent) = $gs->last_rev_commit;
2197 if (defined $r0 && defined $parent) {
2198 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
2199 my $ed;
2200 if ($self->ra->can_do_switch) {
2201 $self->assert_index_clean($parent);
2202 print STDERR "Following parent with do_switch\n";
2203 # do_switch works with svn/trunk >= r22312, but that
2204 # is not included with SVN 1.4.3 (the latest version
2205 # at the moment), so we can't rely on it
2206 $self->{last_commit} = $parent;
2207 $ed = SVN::Git::Fetcher->new($self);
2208 $gs->ra->gs_do_switch($r0, $rev, $gs,
2209 $self->full_url, $ed)
2210 or die "SVN connection failed somewhere...\n";
2211 } elsif ($self->ra->trees_match($new_url, $r0,
2212 $self->full_url, $rev)) {
2213 print STDERR "Trees match:\n",
2214 " $new_url\@$r0\n",
2215 " ${\$self->full_url}\@$rev\n",
2216 "Following parent with no changes\n";
2217 $self->tmp_index_do(sub {
2218 command_noisy('read-tree', $parent);
2220 $self->{last_commit} = $parent;
2221 } else {
2222 print STDERR "Following parent with do_update\n";
2223 $ed = SVN::Git::Fetcher->new($self);
2224 $self->ra->gs_do_update($rev, $rev, $self, $ed)
2225 or die "SVN connection failed somewhere...\n";
2227 print STDERR "Successfully followed parent\n";
2228 return $self->make_log_entry($rev, [$parent], $ed);
2230 return undef;
2233 sub do_fetch {
2234 my ($self, $paths, $rev) = @_;
2235 my $ed;
2236 my ($last_rev, @parents);
2237 if (my $lc = $self->last_commit) {
2238 # we can have a branch that was deleted, then re-added
2239 # under the same name but copied from another path, in
2240 # which case we'll have multiple parents (we don't
2241 # want to break the original ref, nor lose copypath info):
2242 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2243 push @{$log_entry->{parents}}, $lc;
2244 return $log_entry;
2246 $ed = SVN::Git::Fetcher->new($self);
2247 $last_rev = $self->{last_rev};
2248 $ed->{c} = $lc;
2249 @parents = ($lc);
2250 } else {
2251 $last_rev = $rev;
2252 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2253 return $log_entry;
2255 $ed = SVN::Git::Fetcher->new($self);
2257 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2258 die "SVN connection failed somewhere...\n";
2260 $self->make_log_entry($rev, \@parents, $ed);
2263 sub get_untracked {
2264 my ($self, $ed) = @_;
2265 my @out;
2266 my $h = $ed->{empty};
2267 foreach (sort keys %$h) {
2268 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2269 push @out, " $act: " . uri_encode($_);
2270 warn "W: $act: $_\n";
2272 foreach my $t (qw/dir_prop file_prop/) {
2273 $h = $ed->{$t} or next;
2274 foreach my $path (sort keys %$h) {
2275 my $ppath = $path eq '' ? '.' : $path;
2276 foreach my $prop (sort keys %{$h->{$path}}) {
2277 next if $SKIP_PROP{$prop};
2278 my $v = $h->{$path}->{$prop};
2279 my $t_ppath_prop = "$t: " .
2280 uri_encode($ppath) . ' ' .
2281 uri_encode($prop);
2282 if (defined $v) {
2283 push @out, " +$t_ppath_prop " .
2284 uri_encode($v);
2285 } else {
2286 push @out, " -$t_ppath_prop";
2291 foreach my $t (qw/absent_file absent_directory/) {
2292 $h = $ed->{$t} or next;
2293 foreach my $parent (sort keys %$h) {
2294 foreach my $path (sort @{$h->{$parent}}) {
2295 push @out, " $t: " .
2296 uri_encode("$parent/$path");
2297 warn "W: $t: $parent/$path ",
2298 "Insufficient permissions?\n";
2302 \@out;
2305 sub parse_svn_date {
2306 my $date = shift || return '+0000 1970-01-01 00:00:00';
2307 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2308 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
2309 croak "Unable to parse date: $date\n";
2310 "+0000 $Y-$m-$d $H:$M:$S";
2313 sub check_author {
2314 my ($author) = @_;
2315 if (!defined $author || length $author == 0) {
2316 $author = '(no author)';
2318 if (defined $::_authors && ! defined $::users{$author}) {
2319 die "Author: $author not defined in $::_authors file\n";
2321 $author;
2324 sub make_log_entry {
2325 my ($self, $rev, $parents, $ed) = @_;
2326 my $untracked = $self->get_untracked($ed);
2328 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
2329 print $un "r$rev\n" or croak $!;
2330 print $un $_, "\n" foreach @$untracked;
2331 my %log_entry = ( parents => $parents || [], revision => $rev,
2332 log => '');
2334 my $headrev;
2335 my $logged = delete $self->{logged_rev_props};
2336 if (!$logged || $self->{-want_revprops}) {
2337 my $rp = $self->ra->rev_proplist($rev);
2338 foreach (sort keys %$rp) {
2339 my $v = $rp->{$_};
2340 if (/^svn:(author|date|log)$/) {
2341 $log_entry{$1} = $v;
2342 } elsif ($_ eq 'svm:headrev') {
2343 $headrev = $v;
2344 } else {
2345 print $un " rev_prop: ", uri_encode($_), ' ',
2346 uri_encode($v), "\n";
2349 } else {
2350 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
2352 close $un or croak $!;
2354 $log_entry{date} = parse_svn_date($log_entry{date});
2355 $log_entry{log} .= "\n";
2356 my $author = $log_entry{author} = check_author($log_entry{author});
2357 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
2358 : ($author, undef);
2360 my ($commit_name, $commit_email) = ($name, $email);
2361 if ($_use_log_author) {
2362 if ($log_entry{log} =~ /From:\s+(.*?)\s+<(.*)>\s*\n/) {
2363 ($name, $email) = ($1, $2);
2364 } elsif ($log_entry{log} =~
2365 /Signed-off-by:\s+(.*?)\s+<(.*)>\s*\n/) {
2366 ($name, $email) = ($1, $2);
2369 if (defined $headrev && $self->use_svm_props) {
2370 if ($self->rewrite_root) {
2371 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2372 "options set!\n";
2374 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
2375 # we don't want "SVM: initializing mirror for junk" ...
2376 return undef if $r == 0;
2377 my $svm = $self->svm;
2378 if ($uuid ne $svm->{uuid}) {
2379 die "UUID mismatch on SVM path:\n",
2380 "expected: $svm->{uuid}\n",
2381 " got: $uuid\n";
2383 my $full_url = $self->full_url;
2384 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2385 die "Failed to replace '$svm->{replace}' with ",
2386 "'$svm->{source}' in $full_url\n";
2387 # throw away username for storing in records
2388 remove_username($full_url);
2389 $log_entry{metadata} = "$full_url\@$r $uuid";
2390 $log_entry{svm_revision} = $r;
2391 $email ||= "$author\@$uuid";
2392 $commit_email ||= "$author\@$uuid";
2393 } elsif ($self->use_svnsync_props) {
2394 my $full_url = $self->svnsync->{url};
2395 $full_url .= "/$self->{path}" if length $self->{path};
2396 remove_username($full_url);
2397 my $uuid = $self->svnsync->{uuid};
2398 $log_entry{metadata} = "$full_url\@$rev $uuid";
2399 $email ||= "$author\@$uuid";
2400 $commit_email ||= "$author\@$uuid";
2401 } else {
2402 my $url = $self->metadata_url;
2403 remove_username($url);
2404 $log_entry{metadata} = "$url\@$rev " .
2405 $self->ra->get_uuid;
2406 $email ||= "$author\@" . $self->ra->get_uuid;
2407 $commit_email ||= "$author\@" . $self->ra->get_uuid;
2409 $log_entry{name} = $name;
2410 $log_entry{email} = $email;
2411 $log_entry{commit_name} = $commit_name;
2412 $log_entry{commit_email} = $commit_email;
2413 \%log_entry;
2416 sub fetch {
2417 my ($self, $min_rev, $max_rev, @parents) = @_;
2418 my ($last_rev, $last_commit) = $self->last_rev_commit;
2419 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2420 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2423 sub set_tree_cb {
2424 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2425 $self->{inject_parents} = { $rev => $tree };
2426 $self->fetch(undef, undef);
2429 sub set_tree {
2430 my ($self, $tree) = (shift, shift);
2431 my $log_entry = ::get_commit_entry($tree);
2432 unless ($self->{last_rev}) {
2433 fatal("Must have an existing revision to commit");
2435 my %ed_opts = ( r => $self->{last_rev},
2436 log => $log_entry->{log},
2437 ra => $self->ra,
2438 tree_a => $self->{last_commit},
2439 tree_b => $tree,
2440 editor_cb => sub {
2441 $self->set_tree_cb($log_entry, $tree, @_) },
2442 svn_path => $self->{path} );
2443 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2444 print "No changes\nr$self->{last_rev} = $tree\n";
2448 sub rebuild {
2449 my ($self) = @_;
2450 my $db_path = $self->db_path;
2451 return if (-e $db_path && ! -z $db_path);
2452 return unless ::verify_ref($self->refname.'^0');
2453 if (-f $self->{db_root}) {
2454 rename $self->{db_root}, $db_path or die
2455 "rename $self->{db_root} => $db_path failed: $!\n";
2456 my ($dir, $base) = ($db_path =~ m#^(.*?)/?([^/]+)$#);
2457 symlink $base, $self->{db_root} or die
2458 "symlink $base => $self->{db_root} failed: $!\n";
2459 return;
2461 print "Rebuilding $db_path ...\n";
2462 my ($log, $ctx) = command_output_pipe("log", '--no-color', $self->refname);
2463 my $latest;
2464 my $full_url = $self->full_url;
2465 remove_username($full_url);
2466 my $svn_uuid;
2467 my $c;
2468 while (<$log>) {
2469 if ( m{^commit ($::sha1)$} ) {
2470 $c = $1;
2471 next;
2473 next unless s{^\s*(git-svn-id:)}{$1};
2474 my ($url, $rev, $uuid) = ::extract_metadata($_);
2475 remove_username($url);
2477 # ignore merges (from set-tree)
2478 next if (!defined $rev || !$uuid);
2480 # if we merged or otherwise started elsewhere, this is
2481 # how we break out of it
2482 if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
2483 ($full_url && $url && ($url ne $full_url))) {
2484 next;
2486 $latest ||= $rev;
2487 $svn_uuid ||= $uuid;
2489 $self->rev_db_set($rev, $c);
2490 print "r$rev = $c\n";
2492 command_close_pipe($log, $ctx);
2493 print "Done rebuilding $db_path\n";
2496 # rev_db:
2497 # Tie::File seems to be prone to offset errors if revisions get sparse,
2498 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2499 # one of my favorite modules is out :< Next up would be one of the DBM
2500 # modules, but I'm not sure which is most portable... So I'll just
2501 # go with something that's plain-text, but still capable of
2502 # being randomly accessed. So here's my ultra-simple fixed-width
2503 # database. All records are 40 characters + "\n", so it's easy to seek
2504 # to a revision: (41 * rev) is the byte offset.
2505 # A record of 40 0s denotes an empty revision.
2506 # And yes, it's still pretty fast (faster than Tie::File).
2507 # These files are disposable unless noMetadata or useSvmProps is set
2509 sub _rev_db_set {
2510 my ($fh, $rev, $commit) = @_;
2511 my $offset = $rev * 41;
2512 # assume that append is the common case:
2513 seek $fh, 0, 2 or croak $!;
2514 my $pos = tell $fh;
2515 if ($pos < $offset) {
2516 for (1 .. (($offset - $pos) / 41)) {
2517 print $fh (('0' x 40),"\n") or croak $!;
2520 seek $fh, $offset, 0 or croak $!;
2521 print $fh $commit,"\n" or croak $!;
2524 sub mkfile {
2525 my ($path) = @_;
2526 unless (-e $path) {
2527 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2528 mkpath([$dir]) unless -d $dir;
2529 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2530 close $fh or die "Couldn't close (create) $path: $!\n";
2534 sub rev_db_set {
2535 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2536 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2537 my $db = $self->db_path($uuid);
2538 my $db_lock = "$db.lock";
2539 my $sig;
2540 if ($update_ref) {
2541 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2542 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2544 mkfile($db);
2546 $LOCKFILES{$db_lock} = 1;
2547 my $sync;
2548 # both of these options make our .rev_db file very, very important
2549 # and we can't afford to lose it because rebuild() won't work
2550 if ($self->use_svm_props || $self->no_metadata) {
2551 $sync = 1;
2552 copy($db, $db_lock) or die "rev_db_set(@_): ",
2553 "Failed to copy: ",
2554 "$db => $db_lock ($!)\n";
2555 } else {
2556 rename $db, $db_lock or die "rev_db_set(@_): ",
2557 "Failed to rename: ",
2558 "$db => $db_lock ($!)\n";
2560 open my $fh, '+<', $db_lock or die "Couldn't open $db_lock: $!\n";
2561 _rev_db_set($fh, $rev, $commit);
2562 if ($sync) {
2563 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2564 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2566 close $fh or croak $!;
2567 if ($update_ref) {
2568 $_head = $self;
2569 command_noisy('update-ref', '-m', "r$rev",
2570 $self->refname, $commit);
2572 rename $db_lock, $db or die "rev_db_set(@_): ", "Failed to rename: ",
2573 "$db_lock => $db ($!)\n";
2574 delete $LOCKFILES{$db_lock};
2575 if ($update_ref) {
2576 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2577 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
2578 kill $sig, $$ if defined $sig;
2582 sub rev_db_max {
2583 my ($self) = @_;
2584 $self->rebuild;
2585 my $db_path = $self->db_path;
2586 my @stat = stat $db_path or return 0;
2587 ($stat[7] % 41) == 0 or die "$db_path inconsistent size: $stat[7]\n";
2588 my $max = $stat[7] / 41;
2589 (($max > 0) ? $max - 1 : 0);
2592 sub rev_db_get {
2593 my ($self, $rev, $uuid) = @_;
2594 my $ret;
2595 my $offset = $rev * 41;
2596 my $db_path = $self->db_path($uuid);
2597 return undef unless -e $db_path;
2598 open my $fh, '<', $db_path or croak $!;
2599 if (sysseek($fh, $offset, 0) == $offset) {
2600 my $read = sysread($fh, $ret, 40);
2601 $ret = undef if ($read != 40 || $ret eq ('0'x40));
2603 close $fh or croak $!;
2604 $ret;
2607 # Finds the first svn revision that exists on (if $eq_ok is true) or
2608 # before $rev for the current branch. It will not search any lower
2609 # than $min_rev. Returns the git commit hash and svn revision number
2610 # if found, else (undef, undef).
2611 sub find_rev_before {
2612 my ($self, $rev, $eq_ok, $min_rev) = @_;
2613 --$rev unless $eq_ok;
2614 $min_rev ||= 1;
2615 while ($rev >= $min_rev) {
2616 if (my $c = $self->rev_db_get($rev)) {
2617 return ($rev, $c);
2619 --$rev;
2621 return (undef, undef);
2624 # Finds the first svn revision that exists on (if $eq_ok is true) or
2625 # after $rev for the current branch. It will not search any higher
2626 # than $max_rev. Returns the git commit hash and svn revision number
2627 # if found, else (undef, undef).
2628 sub find_rev_after {
2629 my ($self, $rev, $eq_ok, $max_rev) = @_;
2630 ++$rev unless $eq_ok;
2631 $max_rev ||= $self->rev_db_max();
2632 while ($rev <= $max_rev) {
2633 if (my $c = $self->rev_db_get($rev)) {
2634 return ($rev, $c);
2636 ++$rev;
2638 return (undef, undef);
2641 sub _new {
2642 my ($class, $repo_id, $ref_id, $path) = @_;
2643 unless (defined $repo_id && length $repo_id) {
2644 $repo_id = $Git::SVN::default_repo_id;
2646 unless (defined $ref_id && length $ref_id) {
2647 $_[2] = $ref_id = $Git::SVN::default_ref_id;
2649 $_[1] = $repo_id = sanitize_remote_name($repo_id);
2650 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2651 $_[3] = $path = '' unless (defined $path);
2652 mkpath(["$ENV{GIT_DIR}/svn"]);
2653 bless {
2654 ref_id => $ref_id, dir => $dir, index => "$dir/index",
2655 path => $path, config => "$ENV{GIT_DIR}/svn/config",
2656 db_root => "$dir/.rev_db", repo_id => $repo_id }, $class;
2659 sub db_path {
2660 my ($self, $uuid) = @_;
2661 $uuid ||= $self->ra_uuid;
2662 "$self->{db_root}.$uuid";
2665 sub uri_encode {
2666 my ($f) = @_;
2667 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2671 sub remove_username {
2672 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
2675 package Git::SVN::Prompt;
2676 use strict;
2677 use warnings;
2678 require SVN::Core;
2679 use vars qw/$_no_auth_cache $_username/;
2681 sub simple {
2682 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
2683 $may_save = undef if $_no_auth_cache;
2684 $default_username = $_username if defined $_username;
2685 if (defined $default_username && length $default_username) {
2686 if (defined $realm && length $realm) {
2687 print STDERR "Authentication realm: $realm\n";
2688 STDERR->flush;
2690 $cred->username($default_username);
2691 } else {
2692 username($cred, $realm, $may_save, $pool);
2694 $cred->password(_read_password("Password for '" .
2695 $cred->username . "': ", $realm));
2696 $cred->may_save($may_save);
2697 $SVN::_Core::SVN_NO_ERROR;
2700 sub ssl_server_trust {
2701 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2702 $may_save = undef if $_no_auth_cache;
2703 print STDERR "Error validating server certificate for '$realm':\n";
2705 no warnings 'once';
2706 # All variables SVN::Auth::SSL::* are used only once,
2707 # so we're shutting up Perl warnings about this.
2708 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
2709 print STDERR " - The certificate is not issued ",
2710 "by a trusted authority. Use the\n",
2711 " fingerprint to validate ",
2712 "the certificate manually!\n";
2714 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
2715 print STDERR " - The certificate hostname ",
2716 "does not match.\n";
2718 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
2719 print STDERR " - The certificate is not yet valid.\n";
2721 if ($failures & $SVN::Auth::SSL::EXPIRED) {
2722 print STDERR " - The certificate has expired.\n";
2724 if ($failures & $SVN::Auth::SSL::OTHER) {
2725 print STDERR " - The certificate has ",
2726 "an unknown error.\n";
2728 } # no warnings 'once'
2729 printf STDERR
2730 "Certificate information:\n".
2731 " - Hostname: %s\n".
2732 " - Valid: from %s until %s\n".
2733 " - Issuer: %s\n".
2734 " - Fingerprint: %s\n",
2735 map $cert_info->$_, qw(hostname valid_from valid_until
2736 issuer_dname fingerprint);
2737 my $choice;
2738 prompt:
2739 print STDERR $may_save ?
2740 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
2741 "(R)eject or accept (t)emporarily? ";
2742 STDERR->flush;
2743 $choice = lc(substr(<STDIN> || 'R', 0, 1));
2744 if ($choice =~ /^t$/i) {
2745 $cred->may_save(undef);
2746 } elsif ($choice =~ /^r$/i) {
2747 return -1;
2748 } elsif ($may_save && $choice =~ /^p$/i) {
2749 $cred->may_save($may_save);
2750 } else {
2751 goto prompt;
2753 $cred->accepted_failures($failures);
2754 $SVN::_Core::SVN_NO_ERROR;
2757 sub ssl_client_cert {
2758 my ($cred, $realm, $may_save, $pool) = @_;
2759 $may_save = undef if $_no_auth_cache;
2760 print STDERR "Client certificate filename: ";
2761 STDERR->flush;
2762 chomp(my $filename = <STDIN>);
2763 $cred->cert_file($filename);
2764 $cred->may_save($may_save);
2765 $SVN::_Core::SVN_NO_ERROR;
2768 sub ssl_client_cert_pw {
2769 my ($cred, $realm, $may_save, $pool) = @_;
2770 $may_save = undef if $_no_auth_cache;
2771 $cred->password(_read_password("Password: ", $realm));
2772 $cred->may_save($may_save);
2773 $SVN::_Core::SVN_NO_ERROR;
2776 sub username {
2777 my ($cred, $realm, $may_save, $pool) = @_;
2778 $may_save = undef if $_no_auth_cache;
2779 if (defined $realm && length $realm) {
2780 print STDERR "Authentication realm: $realm\n";
2782 my $username;
2783 if (defined $_username) {
2784 $username = $_username;
2785 } else {
2786 print STDERR "Username: ";
2787 STDERR->flush;
2788 chomp($username = <STDIN>);
2790 $cred->username($username);
2791 $cred->may_save($may_save);
2792 $SVN::_Core::SVN_NO_ERROR;
2795 sub _read_password {
2796 my ($prompt, $realm) = @_;
2797 print STDERR $prompt;
2798 STDERR->flush;
2799 require Term::ReadKey;
2800 Term::ReadKey::ReadMode('noecho');
2801 my $password = '';
2802 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
2803 last if $key =~ /[\012\015]/; # \n\r
2804 $password .= $key;
2806 Term::ReadKey::ReadMode('restore');
2807 print STDERR "\n";
2808 STDERR->flush;
2809 $password;
2812 package SVN::Git::Fetcher;
2813 use vars qw/@ISA/;
2814 use strict;
2815 use warnings;
2816 use Carp qw/croak/;
2817 use IO::File qw//;
2819 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
2820 sub new {
2821 my ($class, $git_svn) = @_;
2822 my $self = SVN::Delta::Editor->new;
2823 bless $self, $class;
2824 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
2825 $self->{empty} = {};
2826 $self->{dir_prop} = {};
2827 $self->{file_prop} = {};
2828 $self->{absent_dir} = {};
2829 $self->{absent_file} = {};
2830 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
2831 $self;
2834 sub set_path_strip {
2835 my ($self, $path) = @_;
2836 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
2839 sub open_root {
2840 { path => '' };
2843 sub open_directory {
2844 my ($self, $path, $pb, $rev) = @_;
2845 { path => $path };
2848 sub git_path {
2849 my ($self, $path) = @_;
2850 if ($self->{path_strip}) {
2851 $path =~ s!$self->{path_strip}!! or
2852 die "Failed to strip path '$path' ($self->{path_strip})\n";
2854 $path;
2857 sub delete_entry {
2858 my ($self, $path, $rev, $pb) = @_;
2860 my $gpath = $self->git_path($path);
2861 return undef if ($gpath eq '');
2863 # remove entire directories.
2864 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
2865 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
2866 -r --name-only -z/,
2867 $self->{c}, '--', $gpath);
2868 local $/ = "\0";
2869 while (<$ls>) {
2870 chomp;
2871 $self->{gii}->remove($_);
2872 print "\tD\t$_\n" unless $::_q;
2874 print "\tD\t$gpath/\n" unless $::_q;
2875 command_close_pipe($ls, $ctx);
2876 $self->{empty}->{$path} = 0
2877 } else {
2878 $self->{gii}->remove($gpath);
2879 print "\tD\t$gpath\n" unless $::_q;
2881 undef;
2884 sub open_file {
2885 my ($self, $path, $pb, $rev) = @_;
2886 my $gpath = $self->git_path($path);
2887 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
2888 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
2889 unless (defined $mode && defined $blob) {
2890 die "$path was not found in commit $self->{c} (r$rev)\n";
2892 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
2893 pool => SVN::Pool->new, action => 'M' };
2896 sub add_file {
2897 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
2898 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2899 delete $self->{empty}->{$dir};
2900 { path => $path, mode_a => 100644, mode_b => 100644,
2901 pool => SVN::Pool->new, action => 'A' };
2904 sub add_directory {
2905 my ($self, $path, $cp_path, $cp_rev) = @_;
2906 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2907 delete $self->{empty}->{$dir};
2908 $self->{empty}->{$path} = 1;
2909 { path => $path };
2912 sub change_dir_prop {
2913 my ($self, $db, $prop, $value) = @_;
2914 $self->{dir_prop}->{$db->{path}} ||= {};
2915 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
2916 undef;
2919 sub absent_directory {
2920 my ($self, $path, $pb) = @_;
2921 $self->{absent_dir}->{$pb->{path}} ||= [];
2922 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
2923 undef;
2926 sub absent_file {
2927 my ($self, $path, $pb) = @_;
2928 $self->{absent_file}->{$pb->{path}} ||= [];
2929 push @{$self->{absent_file}->{$pb->{path}}}, $path;
2930 undef;
2933 sub change_file_prop {
2934 my ($self, $fb, $prop, $value) = @_;
2935 if ($prop eq 'svn:executable') {
2936 if ($fb->{mode_b} != 120000) {
2937 $fb->{mode_b} = defined $value ? 100755 : 100644;
2939 } elsif ($prop eq 'svn:special') {
2940 $fb->{mode_b} = defined $value ? 120000 : 100644;
2941 } else {
2942 $self->{file_prop}->{$fb->{path}} ||= {};
2943 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
2945 undef;
2948 sub apply_textdelta {
2949 my ($self, $fb, $exp) = @_;
2950 my $fh = IO::File->new_tmpfile;
2951 $fh->autoflush(1);
2952 # $fh gets auto-closed() by SVN::TxDelta::apply(),
2953 # (but $base does not,) so dup() it for reading in close_file
2954 open my $dup, '<&', $fh or croak $!;
2955 my $base = IO::File->new_tmpfile;
2956 $base->autoflush(1);
2957 if ($fb->{blob}) {
2958 defined (my $pid = fork) or croak $!;
2959 if (!$pid) {
2960 open STDOUT, '>&', $base or croak $!;
2961 print STDOUT 'link ' if ($fb->{mode_a} == 120000);
2962 exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
2964 waitpid $pid, 0;
2965 croak $? if $?;
2967 if (defined $exp) {
2968 seek $base, 0, 0 or croak $!;
2969 my $got = ::md5sum($base);
2970 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
2971 "expected: $exp\n",
2972 " got: $got\n" if ($got ne $exp);
2975 seek $base, 0, 0 or croak $!;
2976 $fb->{fh} = $dup;
2977 $fb->{base} = $base;
2978 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
2981 sub close_file {
2982 my ($self, $fb, $exp) = @_;
2983 my $hash;
2984 my $path = $self->git_path($fb->{path});
2985 if (my $fh = $fb->{fh}) {
2986 if (defined $exp) {
2987 seek($fh, 0, 0) or croak $!;
2988 my $got = ::md5sum($fh);
2989 if ($got ne $exp) {
2990 die "Checksum mismatch: $path\n",
2991 "expected: $exp\n got: $got\n";
2994 sysseek($fh, 0, 0) or croak $!;
2995 if ($fb->{mode_b} == 120000) {
2996 sysread($fh, my $buf, 5) == 5 or croak $!;
2997 $buf eq 'link ' or die "$path has mode 120000",
2998 "but is not a link\n";
3000 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
3001 if (!$pid) {
3002 open STDIN, '<&', $fh or croak $!;
3003 exec qw/git-hash-object -w --stdin/ or croak $!;
3005 chomp($hash = do { local $/; <$out> });
3006 close $out or croak $!;
3007 close $fh or croak $!;
3008 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
3009 close $fb->{base} or croak $!;
3010 } else {
3011 $hash = $fb->{blob} or die "no blob information\n";
3013 $fb->{pool}->clear;
3014 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
3015 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
3016 undef;
3019 sub abort_edit {
3020 my $self = shift;
3021 $self->{nr} = $self->{gii}->{nr};
3022 delete $self->{gii};
3023 $self->SUPER::abort_edit(@_);
3026 sub close_edit {
3027 my $self = shift;
3028 $self->{git_commit_ok} = 1;
3029 $self->{nr} = $self->{gii}->{nr};
3030 delete $self->{gii};
3031 $self->SUPER::close_edit(@_);
3034 package SVN::Git::Editor;
3035 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
3036 use strict;
3037 use warnings;
3038 use Carp qw/croak/;
3039 use IO::File;
3041 sub new {
3042 my ($class, $opts) = @_;
3043 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
3044 die "$_ required!\n" unless (defined $opts->{$_});
3047 my $pool = SVN::Pool->new;
3048 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
3049 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
3050 $opts->{r}, $mods);
3052 # $opts->{ra} functions should not be used after this:
3053 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
3054 $opts->{editor_cb}, $pool);
3055 my $self = SVN::Delta::Editor->new(@ce, $pool);
3056 bless $self, $class;
3057 foreach (qw/svn_path r tree_a tree_b/) {
3058 $self->{$_} = $opts->{$_};
3060 $self->{url} = $opts->{ra}->{url};
3061 $self->{mods} = $mods;
3062 $self->{types} = $types;
3063 $self->{pool} = $pool;
3064 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
3065 $self->{rm} = { };
3066 $self->{path_prefix} = length $self->{svn_path} ?
3067 "$self->{svn_path}/" : '';
3068 return $self;
3071 sub generate_diff {
3072 my ($tree_a, $tree_b) = @_;
3073 my @diff_tree = qw(diff-tree -z -r);
3074 if ($_cp_similarity) {
3075 push @diff_tree, "-C$_cp_similarity";
3076 } else {
3077 push @diff_tree, '-C';
3079 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
3080 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
3081 push @diff_tree, $tree_a, $tree_b;
3082 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
3083 local $/ = "\0";
3084 my $state = 'meta';
3085 my @mods;
3086 while (<$diff_fh>) {
3087 chomp $_; # this gets rid of the trailing "\0"
3088 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
3089 $::sha1\s($::sha1)\s
3090 ([MTCRAD])\d*$/xo) {
3091 push @mods, { mode_a => $1, mode_b => $2,
3092 sha1_b => $3, chg => $4 };
3093 if ($4 =~ /^(?:C|R)$/) {
3094 $state = 'file_a';
3095 } else {
3096 $state = 'file_b';
3098 } elsif ($state eq 'file_a') {
3099 my $x = $mods[$#mods] or croak "Empty array\n";
3100 if ($x->{chg} !~ /^(?:C|R)$/) {
3101 croak "Error parsing $_, $x->{chg}\n";
3103 $x->{file_a} = $_;
3104 $state = 'file_b';
3105 } elsif ($state eq 'file_b') {
3106 my $x = $mods[$#mods] or croak "Empty array\n";
3107 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
3108 croak "Error parsing $_, $x->{chg}\n";
3110 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
3111 croak "Error parsing $_, $x->{chg}\n";
3113 $x->{file_b} = $_;
3114 $state = 'meta';
3115 } else {
3116 croak "Error parsing $_\n";
3119 command_close_pipe($diff_fh, $ctx);
3120 \@mods;
3123 sub check_diff_paths {
3124 my ($ra, $pfx, $rev, $mods) = @_;
3125 my %types;
3126 $pfx .= '/' if length $pfx;
3128 sub type_diff_paths {
3129 my ($ra, $types, $path, $rev) = @_;
3130 my @p = split m#/+#, $path;
3131 my $c = shift @p;
3132 unless (defined $types->{$c}) {
3133 $types->{$c} = $ra->check_path($c, $rev);
3135 while (@p) {
3136 $c .= '/' . shift @p;
3137 next if defined $types->{$c};
3138 $types->{$c} = $ra->check_path($c, $rev);
3142 foreach my $m (@$mods) {
3143 foreach my $f (qw/file_a file_b/) {
3144 next unless defined $m->{$f};
3145 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
3146 if (length $pfx.$dir && ! defined $types{$dir}) {
3147 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
3151 \%types;
3154 sub split_path {
3155 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
3158 sub repo_path {
3159 my ($self, $path) = @_;
3160 $self->{path_prefix}.(defined $path ? $path : '');
3163 sub url_path {
3164 my ($self, $path) = @_;
3165 if ($self->{url} =~ m#^https?://#) {
3166 $path =~ s/([^a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
3168 $self->{url} . '/' . $self->repo_path($path);
3171 sub rmdirs {
3172 my ($self) = @_;
3173 my $rm = $self->{rm};
3174 delete $rm->{''}; # we never delete the url we're tracking
3175 return unless %$rm;
3177 foreach (keys %$rm) {
3178 my @d = split m#/#, $_;
3179 my $c = shift @d;
3180 $rm->{$c} = 1;
3181 while (@d) {
3182 $c .= '/' . shift @d;
3183 $rm->{$c} = 1;
3186 delete $rm->{$self->{svn_path}};
3187 delete $rm->{''}; # we never delete the url we're tracking
3188 return unless %$rm;
3190 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
3191 $self->{tree_b});
3192 local $/ = "\0";
3193 while (<$fh>) {
3194 chomp;
3195 my @dn = split m#/#, $_;
3196 while (pop @dn) {
3197 delete $rm->{join '/', @dn};
3199 unless (%$rm) {
3200 close $fh;
3201 return;
3204 command_close_pipe($fh, $ctx);
3206 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
3207 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
3208 $self->close_directory($bat->{$d}, $p);
3209 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
3210 print "\tD+\t$d/\n" unless $::_q;
3211 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
3212 delete $bat->{$d};
3216 sub open_or_add_dir {
3217 my ($self, $full_path, $baton) = @_;
3218 my $t = $self->{types}->{$full_path};
3219 if (!defined $t) {
3220 die "$full_path not known in r$self->{r} or we have a bug!\n";
3223 no warnings 'once';
3224 # SVN::Node::none and SVN::Node::file are used only once,
3225 # so we're shutting up Perl's warnings about them.
3226 if ($t == $SVN::Node::none) {
3227 return $self->add_directory($full_path, $baton,
3228 undef, -1, $self->{pool});
3229 } elsif ($t == $SVN::Node::dir) {
3230 return $self->open_directory($full_path, $baton,
3231 $self->{r}, $self->{pool});
3232 } # no warnings 'once'
3233 print STDERR "$full_path already exists in repository at ",
3234 "r$self->{r} and it is not a directory (",
3235 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
3236 } # no warnings 'once'
3237 exit 1;
3240 sub ensure_path {
3241 my ($self, $path) = @_;
3242 my $bat = $self->{bat};
3243 my $repo_path = $self->repo_path($path);
3244 return $bat->{''} unless (length $repo_path);
3245 my @p = split m#/+#, $repo_path;
3246 my $c = shift @p;
3247 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
3248 while (@p) {
3249 my $c0 = $c;
3250 $c .= '/' . shift @p;
3251 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
3253 return $bat->{$c};
3256 sub A {
3257 my ($self, $m) = @_;
3258 my ($dir, $file) = split_path($m->{file_b});
3259 my $pbat = $self->ensure_path($dir);
3260 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3261 undef, -1);
3262 print "\tA\t$m->{file_b}\n" unless $::_q;
3263 $self->chg_file($fbat, $m);
3264 $self->close_file($fbat,undef,$self->{pool});
3267 sub C {
3268 my ($self, $m) = @_;
3269 my ($dir, $file) = split_path($m->{file_b});
3270 my $pbat = $self->ensure_path($dir);
3271 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3272 $self->url_path($m->{file_a}), $self->{r});
3273 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3274 $self->chg_file($fbat, $m);
3275 $self->close_file($fbat,undef,$self->{pool});
3278 sub delete_entry {
3279 my ($self, $path, $pbat) = @_;
3280 my $rpath = $self->repo_path($path);
3281 my ($dir, $file) = split_path($rpath);
3282 $self->{rm}->{$dir} = 1;
3283 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
3286 sub R {
3287 my ($self, $m) = @_;
3288 my ($dir, $file) = split_path($m->{file_b});
3289 my $pbat = $self->ensure_path($dir);
3290 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3291 $self->url_path($m->{file_a}), $self->{r});
3292 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3293 $self->chg_file($fbat, $m);
3294 $self->close_file($fbat,undef,$self->{pool});
3296 ($dir, $file) = split_path($m->{file_a});
3297 $pbat = $self->ensure_path($dir);
3298 $self->delete_entry($m->{file_a}, $pbat);
3301 sub M {
3302 my ($self, $m) = @_;
3303 my ($dir, $file) = split_path($m->{file_b});
3304 my $pbat = $self->ensure_path($dir);
3305 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
3306 $pbat,$self->{r},$self->{pool});
3307 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
3308 $self->chg_file($fbat, $m);
3309 $self->close_file($fbat,undef,$self->{pool});
3312 sub T { shift->M(@_) }
3314 sub change_file_prop {
3315 my ($self, $fbat, $pname, $pval) = @_;
3316 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
3319 sub chg_file {
3320 my ($self, $fbat, $m) = @_;
3321 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
3322 $self->change_file_prop($fbat,'svn:executable','*');
3323 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
3324 $self->change_file_prop($fbat,'svn:executable',undef);
3326 my $fh = IO::File->new_tmpfile or croak $!;
3327 if ($m->{mode_b} =~ /^120/) {
3328 print $fh 'link ' or croak $!;
3329 $self->change_file_prop($fbat,'svn:special','*');
3330 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
3331 $self->change_file_prop($fbat,'svn:special',undef);
3333 defined(my $pid = fork) or croak $!;
3334 if (!$pid) {
3335 open STDOUT, '>&', $fh or croak $!;
3336 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
3338 waitpid $pid, 0;
3339 croak $? if $?;
3340 $fh->flush == 0 or croak $!;
3341 seek $fh, 0, 0 or croak $!;
3343 my $exp = ::md5sum($fh);
3344 seek $fh, 0, 0 or croak $!;
3346 my $pool = SVN::Pool->new;
3347 my $atd = $self->apply_textdelta($fbat, undef, $pool);
3348 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
3349 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
3350 $pool->clear;
3352 close $fh or croak $!;
3355 sub D {
3356 my ($self, $m) = @_;
3357 my ($dir, $file) = split_path($m->{file_b});
3358 my $pbat = $self->ensure_path($dir);
3359 print "\tD\t$m->{file_b}\n" unless $::_q;
3360 $self->delete_entry($m->{file_b}, $pbat);
3363 sub close_edit {
3364 my ($self) = @_;
3365 my ($p,$bat) = ($self->{pool}, $self->{bat});
3366 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
3367 next if $_ eq '';
3368 $self->close_directory($bat->{$_}, $p);
3370 $self->close_directory($bat->{''}, $p);
3371 $self->SUPER::close_edit($p);
3372 $p->clear;
3375 sub abort_edit {
3376 my ($self) = @_;
3377 $self->SUPER::abort_edit($self->{pool});
3380 sub DESTROY {
3381 my $self = shift;
3382 $self->SUPER::DESTROY(@_);
3383 $self->{pool}->clear;
3386 # this drives the editor
3387 sub apply_diff {
3388 my ($self) = @_;
3389 my $mods = $self->{mods};
3390 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
3391 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
3392 my $f = $m->{chg};
3393 if (defined $o{$f}) {
3394 $self->$f($m);
3395 } else {
3396 fatal("Invalid change type: $f");
3399 $self->rmdirs if $_rmdir;
3400 if (@$mods == 0) {
3401 $self->abort_edit;
3402 } else {
3403 $self->close_edit;
3405 return scalar @$mods;
3408 package Git::SVN::Ra;
3409 use vars qw/@ISA $config_dir $_log_window_size/;
3410 use strict;
3411 use warnings;
3412 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
3414 BEGIN {
3415 # enforce temporary pool usage for some simple functions
3416 no strict 'refs';
3417 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root/) {
3418 my $SUPER = "SUPER::$f";
3419 *$f = sub {
3420 my $self = shift;
3421 my $pool = SVN::Pool->new;
3422 my @ret = $self->$SUPER(@_,$pool);
3423 $pool->clear;
3424 wantarray ? @ret : $ret[0];
3429 sub _auth_providers () {
3431 SVN::Client::get_simple_provider(),
3432 SVN::Client::get_ssl_server_trust_file_provider(),
3433 SVN::Client::get_simple_prompt_provider(
3434 \&Git::SVN::Prompt::simple, 2),
3435 SVN::Client::get_ssl_client_cert_file_provider(),
3436 SVN::Client::get_ssl_client_cert_prompt_provider(
3437 \&Git::SVN::Prompt::ssl_client_cert, 2),
3438 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
3439 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
3440 SVN::Client::get_username_provider(),
3441 SVN::Client::get_ssl_server_trust_prompt_provider(
3442 \&Git::SVN::Prompt::ssl_server_trust),
3443 SVN::Client::get_username_prompt_provider(
3444 \&Git::SVN::Prompt::username, 2)
3448 sub escape_uri_only {
3449 my ($uri) = @_;
3450 my @tmp;
3451 foreach (split m{/}, $uri) {
3452 s/([^\w.-])/sprintf("%%%02X",ord($1))/eg;
3453 push @tmp, $_;
3455 join('/', @tmp);
3458 sub escape_url {
3459 my ($url) = @_;
3460 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
3461 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
3462 $url = "$scheme://$domain$uri";
3464 $url;
3467 sub new {
3468 my ($class, $url) = @_;
3469 $url =~ s!/+$!!;
3470 return $RA if ($RA && $RA->{url} eq $url);
3472 SVN::_Core::svn_config_ensure($config_dir, undef);
3473 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
3474 my $config = SVN::Core::config_get_config($config_dir);
3475 $RA = undef;
3476 my $dont_store_passwords = 1;
3477 my $conf_t = ${$config}{'config'};
3479 no warnings 'once';
3480 # The usage of $SVN::_Core::SVN_CONFIG_* variables
3481 # produces warnings that variables are used only once.
3482 # I had not found the better way to shut them up, so
3483 # the warnings of type 'once' are disabled in this block.
3484 if (SVN::_Core::svn_config_get_bool($conf_t,
3485 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
3486 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
3487 1) == 0) {
3488 SVN::_Core::svn_auth_set_parameter($baton,
3489 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
3490 bless (\$dont_store_passwords, "_p_void"));
3492 if (SVN::_Core::svn_config_get_bool($conf_t,
3493 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
3494 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
3495 1) == 0) {
3496 $Git::SVN::Prompt::_no_auth_cache = 1;
3498 } # no warnings 'once'
3499 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
3500 config => $config,
3501 pool => SVN::Pool->new,
3502 auth_provider_callbacks => $callbacks);
3503 $self->{url} = $url;
3504 $self->{svn_path} = $url;
3505 $self->{repos_root} = $self->get_repos_root;
3506 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
3507 $self->{cache} = { check_path => { r => 0, data => {} },
3508 get_dir => { r => 0, data => {} } };
3509 $RA = bless $self, $class;
3512 sub check_path {
3513 my ($self, $path, $r) = @_;
3514 my $cache = $self->{cache}->{check_path};
3515 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
3516 return $cache->{data}->{$path};
3518 my $pool = SVN::Pool->new;
3519 my $t = $self->SUPER::check_path($path, $r, $pool);
3520 $pool->clear;
3521 if ($r != $cache->{r}) {
3522 %{$cache->{data}} = ();
3523 $cache->{r} = $r;
3525 $cache->{data}->{$path} = $t;
3528 sub get_dir {
3529 my ($self, $dir, $r) = @_;
3530 my $cache = $self->{cache}->{get_dir};
3531 if ($r == $cache->{r}) {
3532 if (my $x = $cache->{data}->{$dir}) {
3533 return wantarray ? @$x : $x->[0];
3536 my $pool = SVN::Pool->new;
3537 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
3538 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
3539 $pool->clear;
3540 if ($r != $cache->{r}) {
3541 %{$cache->{data}} = ();
3542 $cache->{r} = $r;
3544 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
3545 wantarray ? (\%dirents, $r, $props) : \%dirents;
3548 sub DESTROY {
3549 # do not call the real DESTROY since we store ourselves in $RA
3552 sub get_log {
3553 my ($self, @args) = @_;
3554 my $pool = SVN::Pool->new;
3555 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
3556 my $ret = $self->SUPER::get_log(@args, $pool);
3557 $pool->clear;
3558 $ret;
3561 sub trees_match {
3562 my ($self, $url1, $rev1, $url2, $rev2) = @_;
3563 my $ctx = SVN::Client->new(auth => _auth_providers);
3564 my $out = IO::File->new_tmpfile;
3566 # older SVN (1.1.x) doesn't take $pool as the last parameter for
3567 # $ctx->diff(), so we'll create a default one
3568 my $pool = SVN::Pool->new_default_sub;
3570 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
3571 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
3572 $out->flush;
3573 my $ret = (($out->stat)[7] == 0);
3574 close $out or croak $!;
3576 $ret;
3579 sub get_commit_editor {
3580 my ($self, $log, $cb, $pool) = @_;
3581 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
3582 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
3585 sub gs_do_update {
3586 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
3587 my $new = ($rev_a == $rev_b);
3588 my $path = $gs->{path};
3590 if ($new && -e $gs->{index}) {
3591 unlink $gs->{index} or die
3592 "Couldn't unlink index: $gs->{index}: $!\n";
3594 my $pool = SVN::Pool->new;
3595 $editor->set_path_strip($path);
3596 my (@pc) = split m#/#, $path;
3597 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
3598 1, $editor, $pool);
3599 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3601 # Since we can't rely on svn_ra_reparent being available, we'll
3602 # just have to do some magic with set_path to make it so
3603 # we only want a partial path.
3604 my $sp = '';
3605 my $final = join('/', @pc);
3606 while (@pc) {
3607 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
3608 $sp .= '/' if length $sp;
3609 $sp .= shift @pc;
3611 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
3613 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
3615 $reporter->finish_report($pool);
3616 $pool->clear;
3617 $editor->{git_commit_ok};
3620 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
3621 # svn_ra_reparent didn't work before 1.4)
3622 sub gs_do_switch {
3623 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
3624 my $path = $gs->{path};
3625 my $pool = SVN::Pool->new;
3627 my $full_url = $self->{url};
3628 my $old_url = $full_url;
3629 $full_url .= '/' . escape_uri_only($path) if length $path;
3630 my ($ra, $reparented);
3631 if ($old_url ne $full_url) {
3632 if ($old_url !~ m#^svn(\+ssh)?://#) {
3633 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
3634 $pool);
3635 $self->{url} = $full_url;
3636 $reparented = 1;
3637 } else {
3638 $_[0] = undef;
3639 $self = undef;
3640 $RA = undef;
3641 $ra = Git::SVN::Ra->new($full_url);
3642 $ra_invalid = 1;
3645 $ra ||= $self;
3646 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
3647 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3648 $reporter->set_path('', $rev_a, 0, @lock, $pool);
3649 $reporter->finish_report($pool);
3651 if ($reparented) {
3652 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
3653 $self->{url} = $old_url;
3656 $pool->clear;
3657 $editor->{git_commit_ok};
3660 sub longest_common_path {
3661 my ($gsv, $globs) = @_;
3662 my %common;
3663 my $common_max = scalar @$gsv;
3665 foreach my $gs (@$gsv) {
3666 my @tmp = split m#/#, $gs->{path};
3667 my $p = '';
3668 foreach (@tmp) {
3669 $p .= length($p) ? "/$_" : $_;
3670 $common{$p} ||= 0;
3671 $common{$p}++;
3674 $globs ||= [];
3675 $common_max += scalar @$globs;
3676 foreach my $glob (@$globs) {
3677 my @tmp = split m#/#, $glob->{path}->{left};
3678 my $p = '';
3679 foreach (@tmp) {
3680 $p .= length($p) ? "/$_" : $_;
3681 $common{$p} ||= 0;
3682 $common{$p}++;
3686 my $longest_path = '';
3687 foreach (sort {length $b <=> length $a} keys %common) {
3688 if ($common{$_} == $common_max) {
3689 $longest_path = $_;
3690 last;
3693 $longest_path;
3696 sub gs_fetch_loop_common {
3697 my ($self, $base, $head, $gsv, $globs) = @_;
3698 return if ($base > $head);
3699 my $inc = $_log_window_size;
3700 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
3701 my $longest_path = longest_common_path($gsv, $globs);
3702 my $ra_url = $self->{url};
3703 while (1) {
3704 my %revs;
3705 my $err;
3706 my $err_handler = $SVN::Error::handler;
3707 $SVN::Error::handler = sub {
3708 ($err) = @_;
3709 skip_unknown_revs($err);
3711 sub _cb {
3712 my ($paths, $r, $author, $date, $log) = @_;
3713 [ dup_changed_paths($paths),
3714 { author => $author, date => $date, log => $log } ];
3716 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
3717 sub { $revs{$_[1]} = _cb(@_) });
3718 if ($err && $max >= $head) {
3719 print STDERR "Path '$longest_path' ",
3720 "was probably deleted:\n",
3721 $err->expanded_message,
3722 "\nWill attempt to follow ",
3723 "revisions r$min .. r$max ",
3724 "committed before the deletion\n";
3725 my $hi = $max;
3726 while (--$hi >= $min) {
3727 my $ok;
3728 $self->get_log([$longest_path], $min, $hi,
3729 0, 1, 1, sub {
3730 $ok ||= $_[1];
3731 $revs{$_[1]} = _cb(@_) });
3732 if ($ok) {
3733 print STDERR "r$min .. r$ok OK\n";
3734 last;
3738 $SVN::Error::handler = $err_handler;
3740 my %exists = map { $_->{path} => $_ } @$gsv;
3741 foreach my $r (sort {$a <=> $b} keys %revs) {
3742 my ($paths, $logged) = @{$revs{$r}};
3744 foreach my $gs ($self->match_globs(\%exists, $paths,
3745 $globs, $r)) {
3746 if ($gs->rev_db_max >= $r) {
3747 next;
3749 next unless $gs->match_paths($paths, $r);
3750 $gs->{logged_rev_props} = $logged;
3751 if (my $last_commit = $gs->last_commit) {
3752 $gs->assert_index_clean($last_commit);
3754 my $log_entry = $gs->do_fetch($paths, $r);
3755 if ($log_entry) {
3756 $gs->do_git_commit($log_entry);
3759 foreach my $g (@$globs) {
3760 my $k = "svn-remote.$g->{remote}." .
3761 "$g->{t}-maxRev";
3762 Git::SVN::tmp_config($k, $r);
3764 if ($ra_invalid) {
3765 $_[0] = undef;
3766 $self = undef;
3767 $RA = undef;
3768 $self = Git::SVN::Ra->new($ra_url);
3769 $ra_invalid = undef;
3772 # pre-fill the .rev_db since it'll eventually get filled in
3773 # with '0' x40 if something new gets committed
3774 foreach my $gs (@$gsv) {
3775 next if defined $gs->rev_db_get($max);
3776 $gs->rev_db_set($max, 0 x40);
3778 foreach my $g (@$globs) {
3779 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
3780 Git::SVN::tmp_config($k, $max);
3782 last if $max >= $head;
3783 $min = $max + 1;
3784 $max += $inc;
3785 $max = $head if ($max > $head);
3789 sub match_globs {
3790 my ($self, $exists, $paths, $globs, $r) = @_;
3792 sub get_dir_check {
3793 my ($self, $exists, $g, $r) = @_;
3794 my @x = eval { $self->get_dir($g->{path}->{left}, $r) };
3795 return unless scalar @x == 3;
3796 my $dirents = $x[0];
3797 foreach my $de (keys %$dirents) {
3798 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
3799 my $p = $g->{path}->full_path($de);
3800 next if $exists->{$p};
3801 next if (length $g->{path}->{right} &&
3802 ($self->check_path($p, $r) !=
3803 $SVN::Node::dir));
3804 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
3805 $g->{ref}->full_path($de), 1);
3808 foreach my $g (@$globs) {
3809 if (my $path = $paths->{"/$g->{path}->{left}"}) {
3810 if ($path->{action} =~ /^[AR]$/) {
3811 get_dir_check($self, $exists, $g, $r);
3814 foreach (keys %$paths) {
3815 if (/$g->{path}->{left_regex}/ &&
3816 !/$g->{path}->{regex}/) {
3817 next if $paths->{$_}->{action} !~ /^[AR]$/;
3818 get_dir_check($self, $exists, $g, $r);
3820 next unless /$g->{path}->{regex}/;
3821 my $p = $1;
3822 my $pathname = $g->{path}->full_path($p);
3823 next if $exists->{$pathname};
3824 next if ($self->check_path($pathname, $r) !=
3825 $SVN::Node::dir);
3826 $exists->{$pathname} = Git::SVN->init(
3827 $self->{url}, $pathname, undef,
3828 $g->{ref}->full_path($p), 1);
3830 my $c = '';
3831 foreach (split m#/#, $g->{path}->{left}) {
3832 $c .= "/$_";
3833 next unless ($paths->{$c} &&
3834 ($paths->{$c}->{action} =~ /^[AR]$/));
3835 get_dir_check($self, $exists, $g, $r);
3838 values %$exists;
3841 sub minimize_url {
3842 my ($self) = @_;
3843 return $self->{url} if ($self->{url} eq $self->{repos_root});
3844 my $url = $self->{repos_root};
3845 my @components = split(m!/!, $self->{svn_path});
3846 my $c = '';
3847 do {
3848 $url .= "/$c" if length $c;
3849 eval { (ref $self)->new($url)->get_latest_revnum };
3850 } while ($@ && ($c = shift @components));
3851 $url;
3854 sub can_do_switch {
3855 my $self = shift;
3856 unless (defined $can_do_switch) {
3857 my $pool = SVN::Pool->new;
3858 my $rep = eval {
3859 $self->do_switch(1, '', 0, $self->{url},
3860 SVN::Delta::Editor->new, $pool);
3862 if ($@) {
3863 $can_do_switch = 0;
3864 } else {
3865 $rep->abort_report($pool);
3866 $can_do_switch = 1;
3868 $pool->clear;
3870 $can_do_switch;
3873 sub skip_unknown_revs {
3874 my ($err) = @_;
3875 my $errno = $err->apr_err();
3876 # Maybe the branch we're tracking didn't
3877 # exist when the repo started, so it's
3878 # not an error if it doesn't, just continue
3880 # Wonderfully consistent library, eh?
3881 # 160013 - svn:// and file://
3882 # 175002 - http(s)://
3883 # 175007 - http(s):// (this repo required authorization, too...)
3884 # More codes may be discovered later...
3885 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
3886 my $err_key = $err->expanded_message;
3887 # revision numbers change every time, filter them out
3888 $err_key =~ s/\d+/\0/g;
3889 $err_key = "$errno\0$err_key";
3890 unless ($ignored_err{$err_key}) {
3891 warn "W: Ignoring error from SVN, path probably ",
3892 "does not exist: ($errno): ",
3893 $err->expanded_message,"\n";
3894 $ignored_err{$err_key} = 1;
3896 return;
3898 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
3901 # svn_log_changed_path_t objects passed to get_log are likely to be
3902 # overwritten even if only the refs are copied to an external variable,
3903 # so we should dup the structures in their entirety. Using an externally
3904 # passed pool (instead of our temporary and quickly cleared pool in
3905 # Git::SVN::Ra) does not help matters at all...
3906 sub dup_changed_paths {
3907 my ($paths) = @_;
3908 return undef unless $paths;
3909 my %ret;
3910 foreach my $p (keys %$paths) {
3911 my $i = $paths->{$p};
3912 my %s = map { $_ => $i->$_ }
3913 qw/copyfrom_path copyfrom_rev action/;
3914 $ret{$p} = \%s;
3916 \%ret;
3919 package Git::SVN::Log;
3920 use strict;
3921 use warnings;
3922 use POSIX qw/strftime/;
3923 use constant commit_log_separator => ('-' x 72) . "\n";
3924 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
3925 %rusers $show_commit $incremental/;
3926 my $l_fmt;
3928 sub cmt_showable {
3929 my ($c) = @_;
3930 return 1 if defined $c->{r};
3932 # big commit message got truncated by the 16k pretty buffer in rev-list
3933 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
3934 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
3935 @{$c->{l}} = ();
3936 my @log = command(qw/cat-file commit/, $c->{c});
3938 # shift off the headers
3939 shift @log while ($log[0] ne '');
3940 shift @log;
3942 # TODO: make $c->{l} not have a trailing newline in the future
3943 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
3945 (undef, $c->{r}, undef) = ::extract_metadata(
3946 (grep(/^git-svn-id: /, @log))[-1]);
3948 return defined $c->{r};
3951 sub log_use_color {
3952 return 1 if $color;
3953 my ($dc, $dcvar);
3954 $dcvar = 'color.diff';
3955 $dc = `git-config --get $dcvar`;
3956 if ($dc eq '') {
3957 # nothing at all; fallback to "diff.color"
3958 $dcvar = 'diff.color';
3959 $dc = `git-config --get $dcvar`;
3961 chomp($dc);
3962 if ($dc eq 'auto') {
3963 my $pc;
3964 $pc = `git-config --get color.pager`;
3965 if ($pc eq '') {
3966 # does not have it -- fallback to pager.color
3967 $pc = `git-config --bool --get pager.color`;
3969 else {
3970 $pc = `git-config --bool --get color.pager`;
3971 if ($?) {
3972 $pc = 'false';
3975 chomp($pc);
3976 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
3977 return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
3979 return 0;
3981 return 0 if $dc eq 'never';
3982 return 1 if $dc eq 'always';
3983 chomp($dc = `git-config --bool --get $dcvar`);
3984 return ($dc eq 'true');
3987 sub git_svn_log_cmd {
3988 my ($r_min, $r_max, @args) = @_;
3989 my $head = 'HEAD';
3990 my (@files, @log_opts);
3991 foreach my $x (@args) {
3992 if ($x eq '--' || @files) {
3993 push @files, $x;
3994 } else {
3995 if (::verify_ref("$x^0")) {
3996 $head = $x;
3997 } else {
3998 push @log_opts, $x;
4003 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
4004 $gs ||= Git::SVN->_new;
4005 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
4006 $gs->refname);
4007 push @cmd, '-r' unless $non_recursive;
4008 push @cmd, qw/--raw --name-status/ if $verbose;
4009 push @cmd, '--color' if log_use_color();
4010 push @cmd, @log_opts;
4011 if (defined $r_max && $r_max == $r_min) {
4012 push @cmd, '--max-count=1';
4013 if (my $c = $gs->rev_db_get($r_max)) {
4014 push @cmd, $c;
4016 } elsif (defined $r_max) {
4017 if ($r_max < $r_min) {
4018 ($r_min, $r_max) = ($r_max, $r_min);
4020 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
4021 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
4022 # If there are no commits in the range, both $c_max and $c_min
4023 # will be undefined. If there is at least 1 commit in the
4024 # range, both will be defined.
4025 return () if !defined $c_min || !defined $c_max;
4026 if ($c_min eq $c_max) {
4027 push @cmd, '--max-count=1', $c_min;
4028 } else {
4029 push @cmd, '--boundary', "$c_min..$c_max";
4032 return (@cmd, @files);
4035 # adapted from pager.c
4036 sub config_pager {
4037 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
4038 if (!defined $pager) {
4039 $pager = 'less';
4040 } elsif (length $pager == 0 || $pager eq 'cat') {
4041 $pager = undef;
4045 sub run_pager {
4046 return unless -t *STDOUT && defined $pager;
4047 pipe my $rfd, my $wfd or return;
4048 defined(my $pid = fork) or ::fatal "Can't fork: $!";
4049 if (!$pid) {
4050 open STDOUT, '>&', $wfd or
4051 ::fatal "Can't redirect to stdout: $!";
4052 return;
4054 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
4055 $ENV{LESS} ||= 'FRSX';
4056 exec $pager or ::fatal "Can't run pager: $! ($pager)";
4059 sub format_svn_date {
4060 return strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)", localtime(shift));
4063 sub parse_git_date {
4064 my ($t, $tz) = @_;
4065 # Date::Parse isn't in the standard Perl distro :(
4066 if ($tz =~ s/^\+//) {
4067 $t += tz_to_s_offset($tz);
4068 } elsif ($tz =~ s/^\-//) {
4069 $t -= tz_to_s_offset($tz);
4071 return $t;
4074 sub set_local_timezone {
4075 if (defined $TZ) {
4076 $ENV{TZ} = $TZ;
4077 } else {
4078 delete $ENV{TZ};
4082 sub tz_to_s_offset {
4083 my ($tz) = @_;
4084 $tz =~ s/(\d\d)$//;
4085 return ($1 * 60) + ($tz * 3600);
4088 sub get_author_info {
4089 my ($dest, $author, $t, $tz) = @_;
4090 $author =~ s/(?:^\s*|\s*$)//g;
4091 $dest->{a_raw} = $author;
4092 my $au;
4093 if ($::_authors) {
4094 $au = $rusers{$author} || undef;
4096 if (!$au) {
4097 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
4099 $dest->{t} = $t;
4100 $dest->{tz} = $tz;
4101 $dest->{a} = $au;
4102 $dest->{t_utc} = parse_git_date($t, $tz);
4105 sub process_commit {
4106 my ($c, $r_min, $r_max, $defer) = @_;
4107 if (defined $r_min && defined $r_max) {
4108 if ($r_min == $c->{r} && $r_min == $r_max) {
4109 show_commit($c);
4110 return 0;
4112 return 1 if $r_min == $r_max;
4113 if ($r_min < $r_max) {
4114 # we need to reverse the print order
4115 return 0 if (defined $limit && --$limit < 0);
4116 push @$defer, $c;
4117 return 1;
4119 if ($r_min != $r_max) {
4120 return 1 if ($r_min < $c->{r});
4121 return 1 if ($r_max > $c->{r});
4124 return 0 if (defined $limit && --$limit < 0);
4125 show_commit($c);
4126 return 1;
4129 sub show_commit {
4130 my $c = shift;
4131 if ($oneline) {
4132 my $x = "\n";
4133 if (my $l = $c->{l}) {
4134 while ($l->[0] =~ /^\s*$/) { shift @$l }
4135 $x = $l->[0];
4137 $l_fmt ||= 'A' . length($c->{r});
4138 print 'r',pack($l_fmt, $c->{r}),' | ';
4139 print "$c->{c} | " if $show_commit;
4140 print $x;
4141 } else {
4142 show_commit_normal($c);
4146 sub show_commit_changed_paths {
4147 my ($c) = @_;
4148 return unless $c->{changed};
4149 print "Changed paths:\n", @{$c->{changed}};
4152 sub show_commit_normal {
4153 my ($c) = @_;
4154 print commit_log_separator, "r$c->{r} | ";
4155 print "$c->{c} | " if $show_commit;
4156 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
4157 my $nr_line = 0;
4159 if (my $l = $c->{l}) {
4160 while ($l->[$#$l] eq "\n" && $#$l > 0
4161 && $l->[($#$l - 1)] eq "\n") {
4162 pop @$l;
4164 $nr_line = scalar @$l;
4165 if (!$nr_line) {
4166 print "1 line\n\n\n";
4167 } else {
4168 if ($nr_line == 1) {
4169 $nr_line = '1 line';
4170 } else {
4171 $nr_line .= ' lines';
4173 print $nr_line, "\n";
4174 show_commit_changed_paths($c);
4175 print "\n";
4176 print $_ foreach @$l;
4178 } else {
4179 print "1 line\n";
4180 show_commit_changed_paths($c);
4181 print "\n";
4184 foreach my $x (qw/raw stat diff/) {
4185 if ($c->{$x}) {
4186 print "\n";
4187 print $_ foreach @{$c->{$x}}
4192 sub cmd_show_log {
4193 my (@args) = @_;
4194 my ($r_min, $r_max);
4195 my $r_last = -1; # prevent dupes
4196 set_local_timezone();
4197 if (defined $::_revision) {
4198 if ($::_revision =~ /^(\d+):(\d+)$/) {
4199 ($r_min, $r_max) = ($1, $2);
4200 } elsif ($::_revision =~ /^\d+$/) {
4201 $r_min = $r_max = $::_revision;
4202 } else {
4203 ::fatal "-r$::_revision is not supported, use ",
4204 "standard 'git log' arguments instead";
4208 config_pager();
4209 @args = git_svn_log_cmd($r_min, $r_max, @args);
4210 if (!@args) {
4211 print commit_log_separator unless $incremental || $oneline;
4212 return;
4214 my $log = command_output_pipe(@args);
4215 run_pager();
4216 my (@k, $c, $d, $stat);
4217 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
4218 while (<$log>) {
4219 if (/^${esc_color}commit -?($::sha1_short)/o) {
4220 my $cmt = $1;
4221 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
4222 $r_last = $c->{r};
4223 process_commit($c, $r_min, $r_max, \@k) or
4224 goto out;
4226 $d = undef;
4227 $c = { c => $cmt };
4228 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
4229 get_author_info($c, $1, $2, $3);
4230 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
4231 # ignore
4232 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
4233 push @{$c->{raw}}, $_;
4234 } elsif (/^${esc_color}[ACRMDT]\t/) {
4235 # we could add $SVN->{svn_path} here, but that requires
4236 # remote access at the moment (repo_path_split)...
4237 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
4238 push @{$c->{changed}}, $_;
4239 } elsif (/^${esc_color}diff /o) {
4240 $d = 1;
4241 push @{$c->{diff}}, $_;
4242 } elsif ($d) {
4243 push @{$c->{diff}}, $_;
4244 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
4245 $esc_color*[\+\-]*$esc_color$/x) {
4246 $stat = 1;
4247 push @{$c->{stat}}, $_;
4248 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
4249 push @{$c->{stat}}, $_;
4250 $stat = undef;
4251 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
4252 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
4253 } elsif (s/^${esc_color} //o) {
4254 push @{$c->{l}}, $_;
4257 if ($c && defined $c->{r} && $c->{r} != $r_last) {
4258 $r_last = $c->{r};
4259 process_commit($c, $r_min, $r_max, \@k);
4261 if (@k) {
4262 ($r_min, $r_max) = ($r_max, $r_min);
4263 process_commit($_, $r_min, $r_max) foreach reverse @k;
4265 out:
4266 close $log;
4267 print commit_log_separator unless $incremental || $oneline;
4270 package Git::SVN::Migration;
4271 # these version numbers do NOT correspond to actual version numbers
4272 # of git nor git-svn. They are just relative.
4274 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
4276 # v1 layout: .git/$id/info/url, refs/remotes/$id
4278 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
4280 # v3 layout: .git/svn/$id, refs/remotes/$id
4281 # - info/url may remain for backwards compatibility
4282 # - this is what we migrate up to this layout automatically,
4283 # - this will be used by git svn init on single branches
4284 # v3.1 layout (auto migrated):
4285 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
4286 # for backwards compatibility
4288 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
4289 # - this is only created for newly multi-init-ed
4290 # repositories. Similar in spirit to the
4291 # --use-separate-remotes option in git-clone (now default)
4292 # - we do not automatically migrate to this (following
4293 # the example set by core git)
4294 use strict;
4295 use warnings;
4296 use Carp qw/croak/;
4297 use File::Path qw/mkpath/;
4298 use File::Basename qw/dirname basename/;
4299 use vars qw/$_minimize/;
4301 sub migrate_from_v0 {
4302 my $git_dir = $ENV{GIT_DIR};
4303 return undef unless -d $git_dir;
4304 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
4305 my $migrated = 0;
4306 while (<$fh>) {
4307 chomp;
4308 my ($id, $orig_ref) = ($_, $_);
4309 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
4310 next unless -f "$git_dir/$id/info/url";
4311 my $new_ref = "refs/remotes/$id";
4312 if (::verify_ref("$new_ref^0")) {
4313 print STDERR "W: $orig_ref is probably an old ",
4314 "branch used by an ancient version of ",
4315 "git-svn.\n",
4316 "However, $new_ref also exists.\n",
4317 "We will not be able ",
4318 "to use this branch until this ",
4319 "ambiguity is resolved.\n";
4320 next;
4322 print STDERR "Migrating from v0 layout...\n" if !$migrated;
4323 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
4324 command_noisy('update-ref', $new_ref, $orig_ref);
4325 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
4326 $migrated++;
4328 command_close_pipe($fh, $ctx);
4329 print STDERR "Done migrating from v0 layout...\n" if $migrated;
4330 $migrated;
4333 sub migrate_from_v1 {
4334 my $git_dir = $ENV{GIT_DIR};
4335 my $migrated = 0;
4336 return $migrated unless -d $git_dir;
4337 my $svn_dir = "$git_dir/svn";
4339 # just in case somebody used 'svn' as their $id at some point...
4340 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
4342 print STDERR "Migrating from a git-svn v1 layout...\n";
4343 mkpath([$svn_dir]);
4344 print STDERR "Data from a previous version of git-svn exists, but\n\t",
4345 "$svn_dir\n\t(required for this version ",
4346 "($::VERSION) of git-svn) does not. exist\n";
4347 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
4348 while (<$fh>) {
4349 my $x = $_;
4350 next unless $x =~ s#^refs/remotes/##;
4351 chomp $x;
4352 next unless -f "$git_dir/$x/info/url";
4353 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
4354 next unless $u;
4355 my $dn = dirname("$git_dir/svn/$x");
4356 mkpath([$dn]) unless -d $dn;
4357 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
4358 mkpath(["$git_dir/svn/svn"]);
4359 print STDERR " - $git_dir/$x/info => ",
4360 "$git_dir/svn/$x/info\n";
4361 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
4362 croak "$!: $x";
4363 # don't worry too much about these, they probably
4364 # don't exist with repos this old (save for index,
4365 # and we can easily regenerate that)
4366 foreach my $f (qw/unhandled.log index .rev_db/) {
4367 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
4369 } else {
4370 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
4371 rename "$git_dir/$x", "$git_dir/svn/$x" or
4372 croak "$!: $x";
4374 $migrated++;
4376 command_close_pipe($fh, $ctx);
4377 print STDERR "Done migrating from a git-svn v1 layout\n";
4378 $migrated;
4381 sub read_old_urls {
4382 my ($l_map, $pfx, $path) = @_;
4383 my @dir;
4384 foreach (<$path/*>) {
4385 if (-r "$_/info/url") {
4386 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
4387 my $ref_id = $pfx . basename $_;
4388 my $url = ::file_to_s("$_/info/url");
4389 $l_map->{$ref_id} = $url;
4390 } elsif (-d $_) {
4391 push @dir, $_;
4394 foreach (@dir) {
4395 my $x = $_;
4396 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
4397 read_old_urls($l_map, $x, $_);
4401 sub migrate_from_v2 {
4402 my @cfg = command(qw/config -l/);
4403 return if grep /^svn-remote\..+\.url=/, @cfg;
4404 my %l_map;
4405 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
4406 my $migrated = 0;
4408 foreach my $ref_id (sort keys %l_map) {
4409 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
4410 if ($@) {
4411 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
4413 $migrated++;
4415 $migrated;
4418 sub minimize_connections {
4419 my $r = Git::SVN::read_all_remotes();
4420 my $new_urls = {};
4421 my $root_repos = {};
4422 foreach my $repo_id (keys %$r) {
4423 my $url = $r->{$repo_id}->{url} or next;
4424 my $fetch = $r->{$repo_id}->{fetch} or next;
4425 my $ra = Git::SVN::Ra->new($url);
4427 # skip existing cases where we already connect to the root
4428 if (($ra->{url} eq $ra->{repos_root}) ||
4429 (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
4430 $repo_id)) {
4431 $root_repos->{$ra->{url}} = $repo_id;
4432 next;
4435 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
4436 my $root_path = $ra->{url};
4437 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
4438 foreach my $path (keys %$fetch) {
4439 my $ref_id = $fetch->{$path};
4440 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
4442 # make sure we can read when connecting to
4443 # a higher level of a repository
4444 my ($last_rev, undef) = $gs->last_rev_commit;
4445 if (!defined $last_rev) {
4446 $last_rev = eval {
4447 $root_ra->get_latest_revnum;
4449 next if $@;
4451 my $new = $root_path;
4452 $new .= length $path ? "/$path" : '';
4453 eval {
4454 $root_ra->get_log([$new], $last_rev, $last_rev,
4455 0, 0, 1, sub { });
4457 next if $@;
4458 $new_urls->{$ra->{repos_root}}->{$new} =
4459 { ref_id => $ref_id,
4460 old_repo_id => $repo_id,
4461 old_path => $path };
4465 my @emptied;
4466 foreach my $url (keys %$new_urls) {
4467 # see if we can re-use an existing [svn-remote "repo_id"]
4468 # instead of creating a(n ugly) new section:
4469 my $repo_id = $root_repos->{$url} ||
4470 Git::SVN::sanitize_remote_name($url);
4472 my $fetch = $new_urls->{$url};
4473 foreach my $path (keys %$fetch) {
4474 my $x = $fetch->{$path};
4475 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
4476 my $pfx = "svn-remote.$x->{old_repo_id}";
4478 my $old_fetch = quotemeta("$x->{old_path}:".
4479 "refs/remotes/$x->{ref_id}");
4480 command_noisy(qw/config --unset/,
4481 "$pfx.fetch", '^'. $old_fetch . '$');
4482 delete $r->{$x->{old_repo_id}}->
4483 {fetch}->{$x->{old_path}};
4484 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
4485 command_noisy(qw/config --unset/,
4486 "$pfx.url");
4487 push @emptied, $x->{old_repo_id}
4491 if (@emptied) {
4492 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
4493 "$ENV{GIT_DIR}/config";
4494 print STDERR <<EOF;
4495 The following [svn-remote] sections in your config file ($file) are empty
4496 and can be safely removed:
4498 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
4502 sub migration_check {
4503 migrate_from_v0();
4504 migrate_from_v1();
4505 migrate_from_v2();
4506 minimize_connections() if $_minimize;
4509 package Git::IndexInfo;
4510 use strict;
4511 use warnings;
4512 use Git qw/command_input_pipe command_close_pipe/;
4514 sub new {
4515 my ($class) = @_;
4516 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
4517 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
4520 sub remove {
4521 my ($self, $path) = @_;
4522 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
4523 return ++$self->{nr};
4525 undef;
4528 sub update {
4529 my ($self, $mode, $hash, $path) = @_;
4530 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
4531 return ++$self->{nr};
4533 undef;
4536 sub DESTROY {
4537 my ($self) = @_;
4538 command_close_pipe($self->{gui}, $self->{ctx});
4541 package Git::SVN::GlobSpec;
4542 use strict;
4543 use warnings;
4545 sub new {
4546 my ($class, $glob) = @_;
4547 my $re = $glob;
4548 $re =~ s!/+$!!g; # no need for trailing slashes
4549 my $nr = ($re =~ s!^(.*)\*(.*)$!\(\[^/\]+\)!g);
4550 my ($left, $right) = ($1, $2);
4551 if ($nr > 1) {
4552 die "Only one '*' wildcard expansion ",
4553 "is supported (got $nr): '$glob'\n";
4554 } elsif ($nr == 0) {
4555 die "One '*' is needed for glob: '$glob'\n";
4557 $re = quotemeta($left) . $re . quotemeta($right);
4558 if (length $left && !($left =~ s!/+$!!g)) {
4559 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
4561 if (length $right && !($right =~ s!^/+!!g)) {
4562 die "Missing leading '/' on right side of: '$glob' ($right)\n";
4564 my $left_re = qr/^\/\Q$left\E(\/|$)/;
4565 bless { left => $left, right => $right, left_regex => $left_re,
4566 regex => qr/$re/, glob => $glob }, $class;
4569 sub full_path {
4570 my ($self, $path) = @_;
4571 return (length $self->{left} ? "$self->{left}/" : '') .
4572 $path . (length $self->{right} ? "/$self->{right}" : '');
4575 __END__
4577 Data structures:
4580 $remotes = { # returned by read_all_remotes()
4581 'svn' => {
4582 # svn-remote.svn.url=https://svn.musicpd.org
4583 url => 'https://svn.musicpd.org',
4584 # svn-remote.svn.fetch=mpd/trunk:trunk
4585 fetch => {
4586 'mpd/trunk' => 'trunk',
4588 # svn-remote.svn.tags=mpd/tags/*:tags/*
4589 tags => {
4590 path => {
4591 left => 'mpd/tags',
4592 right => '',
4593 regex => qr!mpd/tags/([^/]+)$!,
4594 glob => 'tags/*',
4596 ref => {
4597 left => 'tags',
4598 right => '',
4599 regex => qr!tags/([^/]+)$!,
4600 glob => 'tags/*',
4606 $log_entry hashref as returned by libsvn_log_entry()
4608 log => 'whitespace-formatted log entry
4609 ', # trailing newline is preserved
4610 revision => '8', # integer
4611 date => '2004-02-24T17:01:44.108345Z', # commit date
4612 author => 'committer name'
4616 # this is generated by generate_diff();
4617 @mods = array of diff-index line hashes, each element represents one line
4618 of diff-index output
4620 diff-index line ($m hash)
4622 mode_a => first column of diff-index output, no leading ':',
4623 mode_b => second column of diff-index output,
4624 sha1_b => sha1sum of the final blob,
4625 chg => change type [MCRADT],
4626 file_a => original file name of a file (iff chg is 'C' or 'R')
4627 file_b => new/current file name of a file (any chg)
4631 # retval of read_url_paths{,_all}();
4632 $l_map = {
4633 # repository root url
4634 'https://svn.musicpd.org' => {
4635 # repository path # GIT_SVN_ID
4636 'mpd/trunk' => 'trunk',
4637 'mpd/tags/0.11.5' => 'tags/0.11.5',
4641 Notes:
4642 I don't trust the each() function on unless I created %hash myself
4643 because the internal iterator may not have started at base.