2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
7 use vars qw
/ $AUTHOR $VERSION
8 $sha1 $sha1_short $_revision $_repository
9 $_q $_authors $_authors_prog %users/;
10 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
11 $VERSION = '@@GIT_VERSION@@';
13 # From which subdir have we been invoked?
14 my $cmd_dir_prefix = eval {
15 command_oneline
([qw
/rev-parse --show-prefix/], STDERR
=> 0)
18 my $git_dir_user_set = 1 if defined $ENV{GIT_DIR
};
19 $ENV{GIT_DIR
} ||= '.git';
20 $Git::SVN
::default_repo_id
= 'svn';
21 $Git::SVN
::default_ref_id
= $ENV{GIT_SVN_ID
} || 'git-svn';
22 $Git::SVN
::Ra
::_log_window_size
= 100;
23 $Git::SVN
::_minimize_url
= 'unset';
25 if (! exists $ENV{SVN_SSH
}) {
26 if (exists $ENV{GIT_SSH
}) {
27 $ENV{SVN_SSH
} = $ENV{GIT_SSH
};
29 $ENV{SVN_SSH
} =~ s/\\/\\\\/g;
30 $ENV{SVN_SSH
} =~ s/(.*)/"$1"/;
35 $Git::SVN
::Log
::TZ
= $ENV{TZ
};
37 $| = 1; # unbuffer STDOUT
39 sub fatal
(@
) { print STDERR
"@_\n"; exit 1 }
41 require SVN
::Core
; # use()-ing this causes segfaults for me... *shrug*
44 if ($SVN::Core
::VERSION
lt '1.1.0') {
45 fatal
"Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
48 my $can_compress = eval { require Compress
::Zlib
; 1};
49 push @Git::SVN
::Ra
::ISA
, 'SVN::Ra';
50 push @SVN::Git
::Editor
::ISA
, 'SVN::Delta::Editor';
51 push @SVN::Git
::Fetcher
::ISA
, 'SVN::Delta::Editor';
55 use File
::Basename qw
/dirname basename/;
56 use File
::Path qw
/mkpath/;
59 use Getopt
::Long qw
/:config gnu_getopt no_ignore_case auto_abbrev/;
62 use Memoize
; # core since 5.8.0, Jul 2002
65 # import functions from Git into our packages, en masse
67 foreach (qw
/command command_oneline command_noisy command_output_pipe
68 command_input_pipe command_close_pipe
69 command_bidi_pipe command_close_bidi_pipe
/) {
70 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
71 Git::SVN::Migration Git::SVN::Log Git::SVN),
73 *{"${package}::$_"} = \
&{"Git::$_"};
76 Memoize
::memoize
'Git::config';
77 Memoize
::memoize
'Git::config_bool';
82 $sha1 = qr/[a-f\d]{40}/;
83 $sha1_short = qr/[a-f\d]{4,40}/;
84 my ($_stdin, $_help, $_edit,
85 $_message, $_file, $_branch_dest,
87 $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
88 $_merge, $_strategy, $_dry_run, $_local,
89 $_prefix, $_no_checkout, $_url, $_verbose,
90 $_git_format, $_commit_url, $_tag, $_merge_info);
91 $Git::SVN
::_follow_parent
= 1;
92 $SVN::Git
::Fetcher
::_placeholder_filename
= ".gitignore";
94 my %remote_opts = ( 'username=s' => \
$Git::SVN
::Prompt
::_username
,
95 'config-dir=s' => \
$Git::SVN
::Ra
::config_dir
,
96 'no-auth-cache' => \
$Git::SVN
::Prompt
::_no_auth_cache
,
97 'ignore-paths=s' => \
$SVN::Git
::Fetcher
::_ignore_regex
);
98 my %fc_opts = ( 'follow-parent|follow!' => \
$Git::SVN
::_follow_parent
,
99 'authors-file|A=s' => \
$_authors,
100 'authors-prog=s' => \
$_authors_prog,
101 'repack:i' => \
$Git::SVN
::_repack
,
102 'noMetadata' => \
$Git::SVN
::_no_metadata
,
103 'useSvmProps' => \
$Git::SVN
::_use_svm_props
,
104 'useSvnsyncProps' => \
$Git::SVN
::_use_svnsync_props
,
105 'log-window-size=i' => \
$Git::SVN
::Ra
::_log_window_size
,
106 'no-checkout' => \
$_no_checkout,
108 'repack-flags|repack-args|repack-opts=s' =>
109 \
$Git::SVN
::_repack_flags
,
110 'use-log-author' => \
$Git::SVN
::_use_log_author
,
111 'add-author-from' => \
$Git::SVN
::_add_author_from
,
112 'localtime' => \
$Git::SVN
::_localtime
,
115 my ($_trunk, @_tags, @_branches, $_stdlayout);
117 my %init_opts = ( 'template=s' => \
$_template, 'shared:s' => \
$_shared,
118 'trunk|T=s' => \
$_trunk, 'tags|t=s@' => \
@_tags,
119 'branches|b=s@' => \
@_branches, 'prefix=s' => \
$_prefix,
120 'stdlayout|s' => \
$_stdlayout,
121 'minimize-url|m!' => \
$Git::SVN
::_minimize_url
,
122 'no-metadata' => sub { $icv{noMetadata
} = 1 },
123 'use-svm-props' => sub { $icv{useSvmProps
} = 1 },
124 'use-svnsync-props' => sub { $icv{useSvnsyncProps
} = 1 },
125 'rewrite-root=s' => sub { $icv{rewriteRoot
} = $_[1] },
126 'rewrite-uuid=s' => sub { $icv{rewriteUUID
} = $_[1] },
128 my %cmt_opts = ( 'edit|e' => \
$_edit,
129 'rmdir' => \
$SVN::Git
::Editor
::_rmdir
,
130 'find-copies-harder' => \
$SVN::Git
::Editor
::_find_copies_harder
,
131 'l=i' => \
$SVN::Git
::Editor
::_rename_limit
,
132 'copy-similarity|C=i'=> \
$SVN::Git
::Editor
::_cp_similarity
136 fetch
=> [ \
&cmd_fetch
, "Download new revisions from SVN",
137 { 'revision|r=s' => \
$_revision,
138 'fetch-all|all' => \
$_fetch_all,
139 'parent|p' => \
$_fetch_parent,
141 clone
=> [ \
&cmd_clone
, "Initialize and fetch revisions",
142 { 'revision|r=s' => \
$_revision,
143 'preserve-empty-dirs' =>
144 \
$SVN::Git
::Fetcher
::_preserve_empty_dirs
,
145 'placeholder-filename=s' =>
146 \
$SVN::Git
::Fetcher
::_placeholder_filename
,
147 %fc_opts, %init_opts } ],
148 init
=> [ \
&cmd_init
, "Initialize a repo for tracking" .
149 " (requires URL argument)",
151 'multi-init' => [ \
&cmd_multi_init
,
152 "Deprecated alias for ".
153 "'$0 init -T<trunk> -b<branches> -t<tags>'",
155 dcommit
=> [ \
&cmd_dcommit
,
156 'Commit several diffs to merge with upstream',
157 { 'merge|m|M' => \
$_merge,
158 'strategy|s=s' => \
$_strategy,
159 'verbose|v' => \
$_verbose,
160 'dry-run|n' => \
$_dry_run,
161 'fetch-all|all' => \
$_fetch_all,
162 'commit-url=s' => \
$_commit_url,
163 'revision|r=i' => \
$_revision,
164 'no-rebase' => \
$_no_rebase,
165 'mergeinfo=s' => \
$_merge_info,
166 %cmt_opts, %fc_opts } ],
167 branch
=> [ \
&cmd_branch
,
168 'Create a branch in the SVN repository',
169 { 'message|m=s' => \
$_message,
170 'destination|d=s' => \
$_branch_dest,
171 'dry-run|n' => \
$_dry_run,
173 'username=s' => \
$Git::SVN
::Prompt
::_username
,
174 'commit-url=s' => \
$_commit_url } ],
175 tag
=> [ sub { $_tag = 1; cmd_branch
(@_) },
176 'Create a tag in the SVN repository',
177 { 'message|m=s' => \
$_message,
178 'destination|d=s' => \
$_branch_dest,
179 'dry-run|n' => \
$_dry_run,
180 'username=s' => \
$Git::SVN
::Prompt
::_username
,
181 'commit-url=s' => \
$_commit_url } ],
182 'set-tree' => [ \
&cmd_set_tree
,
183 "Set an SVN repository to a git tree-ish",
184 { 'stdin' => \
$_stdin, %cmt_opts, %fc_opts, } ],
185 'create-ignore' => [ \
&cmd_create_ignore
,
186 'Create a .gitignore per svn:ignore',
187 { 'revision|r=i' => \
$_revision
189 'mkdirs' => [ \
&cmd_mkdirs
,
190 "recreate empty directories after a checkout",
191 { 'revision|r=i' => \
$_revision } ],
192 'propget' => [ \
&cmd_propget
,
193 'Print the value of a property on a file or directory',
194 { 'revision|r=i' => \
$_revision } ],
195 'proplist' => [ \
&cmd_proplist
,
196 'List all properties of a file or directory',
197 { 'revision|r=i' => \
$_revision } ],
198 'show-ignore' => [ \
&cmd_show_ignore
, "Show svn:ignore listings",
199 { 'revision|r=i' => \
$_revision
201 'show-externals' => [ \
&cmd_show_externals
, "Show svn:externals listings",
202 { 'revision|r=i' => \
$_revision
204 'multi-fetch' => [ \
&cmd_multi_fetch
,
205 "Deprecated alias for $0 fetch --all",
206 { 'revision|r=s' => \
$_revision, %fc_opts } ],
207 'migrate' => [ sub { },
208 # no-op, we automatically run this anyways,
209 'Migrate configuration/metadata/layout from
210 previous versions of git-svn',
211 { 'minimize' => \
$Git::SVN
::Migration
::_minimize
,
213 'log' => [ \
&Git
::SVN
::Log
::cmd_show_log
, 'Show commit logs',
214 { 'limit=i' => \
$Git::SVN
::Log
::limit
,
215 'revision|r=s' => \
$_revision,
216 'verbose|v' => \
$Git::SVN
::Log
::verbose
,
217 'incremental' => \
$Git::SVN
::Log
::incremental
,
218 'oneline' => \
$Git::SVN
::Log
::oneline
,
219 'show-commit' => \
$Git::SVN
::Log
::show_commit
,
220 'non-recursive' => \
$Git::SVN
::Log
::non_recursive
,
221 'authors-file|A=s' => \
$_authors,
222 'color' => \
$Git::SVN
::Log
::color
,
223 'pager=s' => \
$Git::SVN
::Log
::pager
225 'find-rev' => [ \
&cmd_find_rev
,
226 "Translate between SVN revision numbers and tree-ish",
228 'rebase' => [ \
&cmd_rebase
, "Fetch and rebase your working directory",
229 { 'merge|m|M' => \
$_merge,
230 'verbose|v' => \
$_verbose,
231 'strategy|s=s' => \
$_strategy,
232 'local|l' => \
$_local,
233 'fetch-all|all' => \
$_fetch_all,
234 'dry-run|n' => \
$_dry_run,
236 'commit-diff' => [ \
&cmd_commit_diff
,
237 'Commit a diff between two trees',
238 { 'message|m=s' => \
$_message,
239 'file|F=s' => \
$_file,
240 'revision|r=s' => \
$_revision,
242 'info' => [ \
&cmd_info
,
243 "Show info about the latest SVN revision
244 on the current branch",
245 { 'url' => \
$_url, } ],
246 'blame' => [ \
&Git
::SVN
::Log
::cmd_blame
,
247 "Show what revision and author last modified each line of a file",
248 { 'git-format' => \
$_git_format } ],
249 'reset' => [ \
&cmd_reset
,
250 "Undo fetches back to the specified SVN revision",
251 { 'revision|r=s' => \
$_revision,
252 'parent|p' => \
$_fetch_parent } ],
254 "Compress unhandled.log files in .git/svn and remove " .
255 "index files in .git/svn",
260 for (my $i = 0; $i < @ARGV; $i++) {
261 if (defined $cmd{$ARGV[$i]}) {
265 } elsif ($ARGV[$i] eq 'help') {
271 # make sure we're always running at the top-level working directory
272 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
273 unless (-d
$ENV{GIT_DIR
}) {
274 if ($git_dir_user_set) {
275 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
276 "but it is not a directory\n";
278 my $git_dir = delete $ENV{GIT_DIR
};
281 $cdup = command_oneline
(qw
/rev-parse --show-cdup/);
282 $git_dir = '.' unless ($cdup);
283 chomp $cdup if ($cdup);
284 $cdup = "." unless ($cdup && length $cdup);
285 } "Already at toplevel, but $git_dir not found\n";
286 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
287 unless (-d
$git_dir) {
288 die "$git_dir still not found after going to ",
291 $ENV{GIT_DIR
} = $git_dir;
293 $_repository = Git
->repository(Repository
=> $ENV{GIT_DIR
});
296 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
298 read_git_config
(\
%opts);
299 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
300 Getopt
::Long
::Configure
('pass_through');
302 my $rv = GetOptions
(%opts, 'help|H|h' => \
$_help, 'version|V' => \
$_version,
303 'minimize-connections' => \
$Git::SVN
::Migration
::_minimize
,
304 'id|i=s' => \
$Git::SVN
::default_ref_id
,
305 'svn-remote|remote|R=s' => sub {
306 $Git::SVN
::no_reuse_existing
= 1;
307 $Git::SVN
::default_repo_id
= $_[1] });
308 exit 1 if (!$rv && $cmd && $cmd ne 'log');
311 version
() if $_version;
312 usage
(1) unless defined $cmd;
313 load_authors
() if $_authors;
314 if (defined $_authors_prog) {
315 $_authors_prog = "'" . File
::Spec
->rel2abs($_authors_prog) . "'";
318 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
319 Git
::SVN
::Migration
::migration_check
();
321 Git
::SVN
::init_vars
();
323 Git
::SVN
::verify_remotes_sanity
();
324 $cmd{$cmd}->[0]->(@ARGV);
327 post_fetch_checkout
();
330 ####################### primary functions ######################
332 my $exit = shift || 0;
333 my $fd = $exit ? \
*STDERR
: \
*STDOUT
;
335 git
-svn
- bidirectional operations between a single Subversion tree
and git
336 Usage
: git svn
<command
> [options
] [arguments
]\n
338 print $fd "Available commands:\n" unless $cmd;
340 foreach (sort keys %cmd) {
341 next if $cmd && $cmd ne $_;
342 next if /^multi-/; # don't show deprecated commands
343 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
344 foreach (sort keys %{$cmd{$_}->[2]}) {
345 # mixed-case options are for .git/config only
346 next if /[A-Z]/ && /^[a-z]+$/i;
347 # prints out arguments as they should be passed:
348 my $x = s
#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
349 print $fd ' ' x
21, join(', ', map { length $_ > 1 ?
351 split /\|/,$_)," $x\n";
355 \nGIT_SVN_ID may be set
in the environment
or via the
--id
/-i switch to an
356 arbitrary identifier
if you
're tracking multiple SVN branches/repositories in
357 one git repository and want to keep them separate. See git-svn(1) for more
365 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
370 unless (-d $ENV{GIT_DIR}) {
371 my @init_db = ('init
');
372 push @init_db, "--template=$_template" if defined $_template;
373 if (defined $_shared) {
374 if ($_shared =~ /[a-z]/) {
375 push @init_db, "--shared=$_shared";
377 push @init_db, "--shared";
380 command_noisy(@init_db);
381 $_repository = Git->repository(Repository => ".git");
384 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
385 foreach my $i (keys %icv) {
386 die "'$set' and '$i' cannot both be set\n" if $set;
387 next unless defined $icv{$i};
388 command_noisy('config
', "$pfx.$i", $icv{$i});
391 my $ignore_regex = \$SVN::Git::Fetcher::_ignore_regex;
392 command_noisy('config
', "$pfx.ignore-paths", $$ignore_regex)
393 if defined $$ignore_regex;
395 if (defined $SVN::Git::Fetcher::_preserve_empty_dirs) {
396 my $fname = \$SVN::Git::Fetcher::_placeholder_filename;
397 command_noisy('config
', "$pfx.preserve-empty-dirs", 'true
');
398 command_noisy('config
', "$pfx.placeholder-filename", $$fname);
403 my $repo_path = shift or return;
404 mkpath([$repo_path]) unless -d $repo_path;
405 chdir $repo_path or die "Couldn't
chdir to
$repo_path: $!\n";
406 $ENV{GIT_DIR} = '.git';
407 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
411 my ($url, $path) = @_;
412 if (!defined $path &&
413 (defined $_trunk || @_branches || @_tags ||
414 defined $_stdlayout) &&
415 $url !~ m#^[a-z\+]+://#) {
418 $path = basename($url) if !defined $path || !length $path;
419 my $authors_absolute = $_authors ? File::Spec->rel2abs($_authors) : "";
420 cmd_init($url, $path);
421 command_oneline('config', 'svn.authorsfile', $authors_absolute)
423 Git::SVN::fetch_all($Git::SVN::default_repo_id);
427 if (defined $_stdlayout) {
428 $_trunk = 'trunk' if (!defined $_trunk);
429 @_tags = 'tags' if (! @_tags);
430 @_branches = 'branches' if (! @_branches);
432 if (defined $_trunk || @_branches || @_tags) {
433 return cmd_multi_init(@_);
435 my $url = shift or die "SVN repository location required
",
436 "as a command
-line argument
\n";
437 $url = canonicalize_url($url);
441 if ($Git::SVN::_minimize_url eq 'unset') {
442 $Git::SVN::_minimize_url = 0;
445 Git::SVN->init($url);
449 if (grep /^\d+=./, @_) {
450 die "'<rev>=<commit>' fetch arguments are
",
451 "no longer supported
.\n";
455 die "Usage
: $0 fetch
[--all
] [--parent
] [svn
-remote
]\n";
457 $Git::SVN::no_reuse_existing = undef;
458 if ($_fetch_parent) {
459 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
461 die "Unable to determine upstream SVN information from
",
462 "working tree history
\n";
464 # just fetch, don't checkout.
465 $_no_checkout = 'true';
466 $_fetch_all ? $gs->fetch_all : $gs->fetch;
467 } elsif ($_fetch_all) {
470 $remote ||= $Git::SVN::default_repo_id;
471 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
477 if ($_stdin || !@commits) {
478 print "Reading from stdin
...\n";
481 if (/\b($sha1_short)\b/o) {
482 unshift @commits, $1;
487 foreach my $c (@commits) {
488 my @tmp = command('rev-parse',$c);
489 if (scalar @tmp == 1) {
491 } elsif (scalar @tmp > 1) {
492 push @revs, reverse(command('rev-list',@tmp));
494 fatal "Failed to rev
-parse
$c";
497 my $gs = Git::SVN->new;
498 my ($r_last, $cmt_last) = $gs->last_rev_commit;
500 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
501 fatal "There are new revisions that were fetched
",
502 "and need to be merged
(or acknowledged
) ",
503 "before committing
.\nlast rev
: $r_last\n",
504 " current
: $gs->{last_rev
}";
506 $gs->set_tree($_) foreach @revs;
507 print "Done committing
",scalar @revs," revisions to SVN
\n";
513 command_noisy(qw/update-index --refresh/);
514 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
515 'Cannot dcommit with a dirty index. Commit your changes first, '
516 . "or stash them with
`git stash'.\n";
520 if ($head ne 'HEAD') {
522 command_oneline([qw/symbolic-ref -q HEAD/])
525 $old_head =~ s{^refs/heads/}{};
527 $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
529 command(['checkout', $head], STDERR => 0);
533 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
535 die "Unable to determine upstream SVN information from ",
536 "$head history.\nPerhaps the repository is empty.";
539 if (defined $_commit_url) {
542 $url = eval { command_oneline('config', '--get',
543 "svn-remote.$gs->{repo_id}.commiturl") };
545 $url = $gs->full_pushurl
549 my $last_rev = $_revision if defined $_revision;
551 print "Committing to $url ...\n";
553 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
554 if ($_no_rebase && scalar(@$linear_refs) > 1) {
555 warn "Attempting to commit more than one change while ",
556 "--no-rebase is enabled.\n",
557 "If these changes depend on each other, re-running ",
558 "without --no-rebase may be required."
560 my $expect_url = $url;
561 Git::SVN::remove_username($expect_url);
562 if (defined($_merge_info)) {
563 $_merge_info =~ tr{ }{\n};
566 my $d = shift @$linear_refs or last;
567 unless (defined $last_rev) {
568 (undef, $last_rev, undef) = cmt_metadata("$d~1");
569 unless (defined $last_rev) {
570 fatal "Unable to extract revision information ",
575 print "diff-tree $d~1 $d\n";
578 my %ed_opts = ( r => $last_rev,
579 log => get_commit_entry($d)->{log},
580 ra => Git::SVN::Ra->new($url),
581 config => SVN::Core::config_get_config(
582 $Git::SVN::Ra::config_dir
587 print "Committed r$_[0]\n";
590 mergeinfo => $_merge_info,
592 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
593 print "No changes\n$d~1 == $d\n";
594 } elsif ($parents->{$d} && @{$parents->{$d}}) {
595 $gs->{inject_parents_dcommit}->{$cmt_rev} =
598 $_fetch_all ? $gs->fetch_all : $gs->fetch;
599 $last_rev = $cmt_rev;
602 # we always want to rebase against the current HEAD,
603 # not any head that was passed to us
604 my @diff = command('diff-tree', $d,
608 @finish = rebase_cmd();
609 print STDERR "W: $d and ", $gs->refname,
610 " differ, using @finish:\n",
611 join("\n", @diff), "\n";
613 print "No changes between current HEAD and ",
615 "\nResetting to the latest ",
617 @finish = qw/reset --mixed/;
619 command_noisy(@finish, $gs->refname);
622 my ($url_, $rev_, $uuid_, $gs_) =
623 working_head_info('HEAD', \@refs);
624 my ($linear_refs_, $parents_) =
625 linearize_history($gs_, \@refs);
626 if (scalar(@$linear_refs) !=
627 scalar(@$linear_refs_)) {
628 fatal "# of revisions changed ",
630 join("\n", @$linear_refs),
632 join("\n", @$linear_refs_), "\n",
633 'If you are attempting to commit ',
634 "merges, try running:\n\t",
635 'git rebase --interactive',
636 '--preserve-merges ',
638 "\nBefore dcommitting";
640 if ($url_ ne $expect_url) {
641 if ($url_ eq $gs->metadata_url) {
643 "Accepting rewritten URL:",
647 "URL mismatch after rebase:",
648 " $url_ != $expect_url";
651 if ($uuid_ ne $uuid) {
652 fatal "uuid mismatch after rebase: ",
657 for ($i = 0; $i < scalar @$linear_refs; $i++) {
658 my $new = $linear_refs_->[$i] or next;
660 $parents->{$linear_refs->[$i]};
670 my $new_head = command_oneline(qw/rev-parse HEAD/);
671 my $new_is_symbolic = eval {
672 command_oneline(qw/symbolic-ref -q HEAD/);
674 if ($new_is_symbolic) {
675 print "dcommitted the branch ", $head, "\n";
677 print "dcommitted on a detached HEAD because you gave ",
678 "a revision argument.\n",
679 "The rewritten commit is: ", $new_head, "\n";
681 command(['checkout', $old_head], STDERR => 0);
688 my ($branch_name, $head) = @_;
690 unless (defined $branch_name && length $branch_name) {
691 die(($_tag ? "tag" : "branch") . " name required\n");
695 my (undef, $rev, undef, $gs) = working_head_info($head);
696 my $src = $gs->full_pushurl;
698 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
699 my $allglobs = $remote->{ $_tag ? 'tags' : 'branches' };
701 if ($#{$allglobs} == 0) {
702 $glob = $allglobs->[0];
704 unless(defined $_branch_dest) {
706 $_tag ? "tag" : "branch",
707 " paths defined for Subversion repository.\n",
708 "You must specify where you want to create the ",
709 $_tag ? "tag" : "branch",
710 " with the --destination argument.\n";
712 foreach my $g (@{$allglobs}) {
713 # SVN::Git::Editor could probably be moved to Git.pm..
714 my $re = SVN::Git::Editor::glob2pat($g->{path}->{left});
715 if ($_branch_dest =~ /$re/) {
720 unless (defined $glob) {
721 my $dest_re = qr/\b\Q$_branch_dest\E\b/;
722 foreach my $g (@{$allglobs}) {
723 $g->{path}->{left} =~ /$dest_re/ or next;
725 die "Ambiguous destination: ",
726 $_branch_dest, "\nmatches both '",
727 $glob->{path}->{left}, "' and '",
728 $g->{path}->{left}, "'\n";
732 unless (defined $glob) {
734 $_tag ? "tag" : "branch",
735 " destination $_branch_dest\n";
739 my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
741 if (defined $_commit_url) {
744 $url = eval { command_oneline('config', '--get',
745 "svn-remote.$gs->{repo_id}.commiturl") };
747 $url = $remote->{pushurl} || $remote->{url};
750 my $dst = join '/', $url, $lft, $branch_name, ($rgt || ());
752 if ($dst =~ /^https:/ && $src =~ /^http:/) {
753 $src=~s/^http:/https:/;
758 my $ctx = SVN::Client->new(
759 auth => Git::SVN::Ra::_auth_providers(),
761 ${ $_[0] } = defined $_message
763 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
769 $ctx->ls($dst, 'HEAD', 0);
770 } and die "branch ${branch_name} already exists\n";
772 print "Copying ${src} at r${rev} to ${dst}...\n";
773 $ctx->copy($src, $rev, $dst)
780 my $revision_or_hash = shift or die "SVN or git revision required ",
781 "as a command-line argument\n";
783 if ($revision_or_hash =~ /^r\d+$/) {
787 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
789 die "Unable to determine upstream SVN information from ",
792 my $desired_revision = substr($revision_or_hash, 1);
793 $result = $gs->rev_map_get($desired_revision, $uuid);
795 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
798 print "$result\n" if $result;
801 sub auto_create_empty_directories {
803 my $var = eval { command_oneline('config', '--get', '--bool',
804 "svn-remote.$gs->{repo_id}.automkdirs") };
805 # By default, create empty directories by consulting the unhandled log,
806 # but allow setting it to 'false' to skip it.
807 return !($var && $var eq 'false');
811 command_noisy(qw/update-index --refresh/);
812 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
814 die "Unable to determine upstream SVN information from ",
815 "working tree history\n";
818 print "Remote Branch: " . $gs->refname . "\n";
819 print "SVN URL: " . $url . "\n";
822 if (command(qw/diff-index HEAD --/)) {
823 print STDERR "Cannot rebase with uncommited changes:\n";
824 command_noisy('status');
828 # rebase will checkout for us, so no need to do it explicitly
829 $_no_checkout = 'true';
830 $_fetch_all ? $gs->fetch_all : $gs->fetch;
832 command_noisy(rebase_cmd(), $gs->refname);
833 if (auto_create_empty_directories($gs)) {
838 sub cmd_show_ignore {
839 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
840 $gs ||= Git::SVN->new;
841 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
842 $gs->prop_walk($gs->{path}, $r, sub {
843 my ($gs, $path, $props) = @_;
844 print STDOUT "\n# $path\n";
845 my $s = $props->{'svn:ignore'} or return;
846 $s =~ s/[\r\n]+/\n/g;
854 sub cmd_show_externals {
855 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
856 $gs ||= Git::SVN->new;
857 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
858 $gs->prop_walk($gs->{path}, $r, sub {
859 my ($gs, $path, $props) = @_;
860 print STDOUT "\n# $path\n";
861 my $s = $props->{'svn:externals'} or return;
862 $s =~ s/[\r\n]+/\n/g;
869 sub cmd_create_ignore {
870 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
871 $gs ||= Git::SVN->new;
872 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
873 $gs->prop_walk($gs->{path}, $r, sub {
874 my ($gs, $path, $props) = @_;
875 # $path is of the form /path/to/dir/
877 # SVN can have attributes on empty directories,
878 # which git won't track
879 mkpath([$path]) unless -d $path;
880 my $ignore = $path . '.gitignore';
881 my $s = $props->{'svn:ignore'} or return;
882 open(GITIGNORE, '>', $ignore)
883 or fatal("Failed to open `$ignore' for writing: $!");
884 $s =~ s/[\r\n]+/\n/g;
887 # Prefix all patterns so that the ignore doesn't apply
888 # to sub-directories.
890 print GITIGNORE
"$s\n";
892 or fatal
("Failed to close `$ignore': $!");
893 command_noisy
('add', '-f', $ignore);
898 my ($url, $rev, $uuid, $gs) = working_head_info
('HEAD');
899 $gs ||= Git
::SVN
->new;
900 $gs->mkemptydirs($_revision);
903 sub canonicalize_path
{
905 my $dot_slash_added = 0;
906 if (substr($path, 0, 1) ne "/") {
907 $path = "./" . $path;
908 $dot_slash_added = 1;
910 # File::Spec->canonpath doesn't collapse x/../y into y (for a
911 # good reason), so let's do this manually.
913 $path =~ s
#/\.(?:/|$)#/#g;
914 $path =~ s
#/[^/]+/\.\.##g;
916 $path =~ s
#^\./## if $dot_slash_added;
922 sub canonicalize_url
{
924 $url =~ s
#^([^:]+://[^/]*/)(.*)$#$1 . canonicalize_path($2)#e;
930 # Helper for cmd_propget and cmd_proplist below.
933 my ($url, $rev, $uuid, $gs) = working_head_info
('HEAD');
934 $gs ||= Git
::SVN
->new;
936 # prefix THE PATH by the sub-directory from which the user
938 $path = $cmd_dir_prefix . $path;
939 fatal
("No such file or directory: $path") unless -e
$path;
940 my $is_dir = -d
$path ?
1 : 0;
941 $path = $gs->{path
} . '/' . $path;
943 # canonicalize the path (otherwise libsvn will abort or fail to
945 $path = canonicalize_path
($path);
947 my $r = (defined $_revision ?
$_revision : $gs->ra->get_latest_revnum);
950 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
953 (undef, $props) = $gs->ra->get_file($path, $r, undef);
958 # cmd_propget (PROP, PATH)
959 # ------------------------
960 # Print the SVN property PROP for PATH.
962 my ($prop, $path) = @_;
963 $path = '.' if not defined $path;
964 usage
(1) if not defined $prop;
965 my $props = get_svnprops
($path);
966 if (not defined $props->{$prop}) {
967 fatal
("`$path' does not have a `$prop' SVN property.");
969 print $props->{$prop} . "\n";
972 # cmd_proplist (PATH)
973 # -------------------
974 # Print the list of SVN properties for PATH.
977 $path = '.' if not defined $path;
978 my $props = get_svnprops
($path);
979 print "Properties on '$path':\n";
980 foreach (sort keys %{$props}) {
987 unless (defined $_trunk || @_branches || @_tags) {
991 $_prefix = '' unless defined $_prefix;
993 $url = canonicalize_url
($url);
997 if (defined $_trunk) {
999 my $trunk_ref = 'refs/remotes/' . $_prefix . 'trunk';
1000 # try both old-style and new-style lookups:
1001 my $gs_trunk = eval { Git
::SVN
->new($trunk_ref) };
1002 unless ($gs_trunk) {
1003 my ($trunk_url, $trunk_path) =
1004 complete_svn_url
($url, $_trunk);
1005 $gs_trunk = Git
::SVN
->init($trunk_url, $trunk_path,
1009 return unless @_branches || @_tags;
1010 my $ra = $url ? Git
::SVN
::Ra
->new($url) : undef;
1011 foreach my $path (@_branches) {
1012 complete_url_ls_init
($ra, $path, '--branches/-b', $_prefix);
1014 foreach my $path (@_tags) {
1015 complete_url_ls_init
($ra, $path, '--tags/-t', $_prefix.'tags/');
1019 sub cmd_multi_fetch
{
1020 $Git::SVN
::no_reuse_existing
= undef;
1021 my $remotes = Git
::SVN
::read_all_remotes
();
1022 foreach my $repo_id (sort keys %$remotes) {
1023 if ($remotes->{$repo_id}->{url
}) {
1024 Git
::SVN
::fetch_all
($repo_id, $remotes);
1029 # this command is special because it requires no metadata
1030 sub cmd_commit_diff
{
1031 my ($ta, $tb, $url) = @_;
1032 my $usage = "Usage: $0 commit-diff -r<revision> ".
1033 "<tree-ish> <tree-ish> [<URL>]";
1034 fatal
($usage) if (!defined $ta || !defined $tb);
1036 if (!defined $url) {
1037 my $gs = eval { Git
::SVN
->new };
1039 fatal
("Needed URL or usable git-svn --id in ",
1040 "the command-line\n", $usage);
1043 $svn_path = $gs->{path
};
1045 unless (defined $_revision) {
1046 fatal
("-r|--revision is a required argument\n", $usage);
1048 if (defined $_message && defined $_file) {
1049 fatal
("Both --message/-m and --file/-F specified ",
1050 "for the commit message.\n",
1051 "I have no idea what you mean");
1053 if (defined $_file) {
1054 $_message = file_to_s
($_file);
1056 $_message ||= get_commit_entry
($tb)->{log};
1058 my $ra ||= Git
::SVN
::Ra
->new($url);
1061 $r = $ra->get_latest_revnum;
1062 } elsif ($r !~ /^\d+$/) {
1063 die "revision argument: $r not understood by git-svn\n";
1065 my %ed_opts = ( r
=> $r,
1070 editor_cb
=> sub { print "Committed r$_[0]\n" },
1071 svn_path
=> $svn_path );
1072 if (!SVN
::Git
::Editor
->new(\
%ed_opts)->apply_diff) {
1073 print "No changes\n$ta == $tb\n";
1077 sub escape_uri_only
{
1080 foreach (split m{/}, $uri) {
1081 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
1089 if ($url =~ m
#^([^:]+)://([^/]*)(.*)$#) {
1090 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only
($3));
1091 $url = "$scheme://$domain$uri";
1097 my $path = canonicalize_path
(defined($_[0]) ?
$_[0] : ".");
1098 my $fullpath = canonicalize_path
($cmd_dir_prefix . $path);
1100 die "Too many arguments specified\n";
1103 my ($file_type, $diff_status) = find_file_type_and_diff_status
($path);
1105 if (!$file_type && !$diff_status) {
1106 print STDERR
"svn: '$path' is not under version control\n";
1110 my ($url, $rev, $uuid, $gs) = working_head_info
('HEAD');
1112 die "Unable to determine upstream SVN information from ",
1113 "working tree history\n";
1116 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
1117 $path = "." if $path eq "";
1119 my $full_url = $url . ($fullpath eq "" ?
"" : "/$fullpath");
1122 print escape_url
($full_url), "\n";
1126 my $result = "Path: $path\n";
1127 $result .= "Name: " . basename
($path) . "\n" if $file_type ne "dir";
1128 $result .= "URL: " . escape_url
($full_url) . "\n";
1131 my $repos_root = $gs->repos_root;
1132 Git
::SVN
::remove_username
($repos_root);
1133 $result .= "Repository Root: " . escape_url
($repos_root) . "\n";
1136 $result .= "Repository Root: (offline)\n";
1139 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
1140 ($SVN::Core
::VERSION
le '1.5.4' || $file_type ne "dir");
1141 $result .= "Revision: " . ($diff_status eq "A" ?
0 : $rev) . "\n";
1143 $result .= "Node Kind: " .
1144 ($file_type eq "dir" ?
"directory" : "file") . "\n";
1146 my $schedule = $diff_status eq "A"
1148 : ($diff_status eq "D" ?
"delete" : "normal");
1149 $result .= "Schedule: $schedule\n";
1151 if ($diff_status eq "A") {
1152 print $result, "\n";
1156 my ($lc_author, $lc_rev, $lc_date_utc);
1157 my @args = Git
::SVN
::Log
::git_svn_log_cmd
($rev, $rev, "--", $fullpath);
1158 my $log = command_output_pipe
(@args);
1159 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
1161 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
1163 $lc_date_utc = Git
::SVN
::Log
::parse_git_date
($2, $3);
1164 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
1165 (undef, $lc_rev, undef) = ::extract_metadata
($1);
1170 Git
::SVN
::Log
::set_local_timezone
();
1172 $result .= "Last Changed Author: $lc_author\n";
1173 $result .= "Last Changed Rev: $lc_rev\n";
1174 $result .= "Last Changed Date: " .
1175 Git
::SVN
::Log
::format_svn_date
($lc_date_utc) . "\n";
1177 if ($file_type ne "dir") {
1178 my $text_last_updated_date =
1179 ($diff_status eq "D" ?
$lc_date_utc : (stat $path)[9]);
1181 "Text Last Updated: " .
1182 Git
::SVN
::Log
::format_svn_date
($text_last_updated_date) .
1185 if ($diff_status eq "D") {
1187 command_output_pipe
(qw(cat-file blob), "HEAD:$path");
1188 if ($file_type eq "link") {
1189 my $file_name = <$fh>;
1190 $checksum = md5sum
("link $file_name");
1192 $checksum = md5sum
($fh);
1194 command_close_pipe
($fh, $ctx);
1195 } elsif ($file_type eq "link") {
1197 command
(qw(cat-file blob), "HEAD:$path");
1199 md5sum
("link " . $file_name);
1201 open FILE
, "<", $path or die $!;
1202 $checksum = md5sum
(\
*FILE
);
1203 close FILE
or die $!;
1205 $result .= "Checksum: " . $checksum . "\n";
1208 print $result, "\n";
1212 my $target = shift || $_revision or die "SVN revision required\n";
1213 $target = $1 if $target =~ /^r(\d+)$/;
1214 $target =~ /^\d+$/ or die "Numeric SVN revision expected\n";
1215 my ($url, $rev, $uuid, $gs) = working_head_info
('HEAD');
1217 die "Unable to determine upstream SVN information from ".
1220 my ($r, $c) = $gs->find_rev_before($target, not $_fetch_parent);
1221 die "Cannot find SVN revision $target\n" unless defined($c);
1222 $gs->rev_map_set($r, $c, 'reset', $uuid);
1223 print "r$r = $c ($gs->{ref_id})\n";
1227 if (!$can_compress) {
1228 warn "Compress::Zlib could not be found; unhandled.log " .
1229 "files will not be compressed.\n";
1231 find
({ wanted
=> \
&gc_directory
, no_chdir
=> 1}, "$ENV{GIT_DIR}/svn");
1234 ########################### utility functions #########################
1237 my @cmd = qw
/rebase/;
1238 push @cmd, '-v' if $_verbose;
1239 push @cmd, qw
/--merge/ if $_merge;
1240 push @cmd, "--strategy=$_strategy" if $_strategy;
1244 sub post_fetch_checkout
{
1245 return if $_no_checkout;
1246 my $gs = $Git::SVN
::_head
or return;
1247 return if verify_ref
('refs/heads/master^0');
1249 # look for "trunk" ref if it exists
1250 my $remote = Git
::SVN
::read_all_remotes
()->{$gs->{repo_id
}};
1251 my $fetch = $remote->{fetch
};
1253 foreach my $p (keys %$fetch) {
1254 basename
($fetch->{$p}) eq 'trunk' or next;
1255 $gs = Git
::SVN
->new($fetch->{$p}, $gs->{repo_id
}, $p);
1260 my $valid_head = verify_ref
('HEAD^0');
1261 command_noisy
(qw(update-ref refs/heads/master), $gs->refname);
1262 return if ($valid_head || !verify_ref
('HEAD^0'));
1264 return if $ENV{GIT_DIR
} !~ m
#^(?:.*/)?\.git$#;
1265 my $index = $ENV{GIT_INDEX_FILE
} || "$ENV{GIT_DIR}/index";
1266 return if -f
$index;
1268 return if command_oneline
(qw
/rev-parse --is-inside-work-tree/) eq 'false';
1269 return if command_oneline
(qw
/rev-parse --is-inside-git-dir/) eq 'true';
1270 command_noisy
(qw
/read-tree -m -u -v HEAD HEAD/);
1271 print STDERR
"Checked out HEAD:\n ",
1272 $gs->full_url, " r", $gs->last_rev, "\n";
1273 if (auto_create_empty_directories
($gs)) {
1274 $gs->mkemptydirs($gs->last_rev);
1278 sub complete_svn_url
{
1279 my ($url, $path) = @_;
1281 if ($path !~ m
#^[a-z\+]+://#) {
1282 if (!defined $url || $url !~ m
#^[a-z\+]+://#) {
1283 fatal
("E: '$path' is not a complete URL ",
1284 "and a separate URL is not specified");
1286 return ($url, $path);
1291 sub complete_url_ls_init
{
1292 my ($ra, $repo_path, $switch, $pfx) = @_;
1293 unless ($repo_path) {
1294 print STDERR
"W: $switch not specified\n";
1297 $repo_path =~ s
#/+$##;
1298 if ($repo_path =~ m
#^[a-z\+]+://#) {
1299 $ra = Git
::SVN
::Ra
->new($repo_path);
1302 $repo_path =~ s
#^/+##;
1304 fatal
("E: '$repo_path' is not a complete URL ",
1305 "and a separate URL is not specified");
1308 my $url = $ra->{url
};
1309 my $gs = Git
::SVN
->init($url, undef, undef, undef, 1);
1310 my $k = "svn-remote.$gs->{repo_id}.url";
1311 my $orig_url = eval { command_oneline
(qw
/config --get/, $k) };
1312 if ($orig_url && ($orig_url ne $gs->{url
})) {
1313 die "$k already set: $orig_url\n",
1314 "wanted to set to: $gs->{url}\n";
1316 command_oneline
('config', $k, $gs->{url
}) unless $orig_url;
1317 my $remote_path = "$gs->{path}/$repo_path";
1318 $remote_path =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
1319 $remote_path =~ s
#/+#/#g;
1320 $remote_path =~ s
#^/##g;
1321 $remote_path .= "/*" if $remote_path !~ /\
*/;
1322 my ($n) = ($switch =~ /^--(\w+)/);
1323 if (length $pfx && $pfx !~ m
#/$#) {
1324 die "--prefix='$pfx' must have a trailing slash '/'\n";
1326 command_noisy
('config',
1328 "svn-remote.$gs->{repo_id}.$n",
1329 "$remote_path:refs/remotes/$pfx*" .
1330 ('/*' x
(($remote_path =~ tr
/*/*/) - 1)) );
1335 eval { command_oneline
([ 'rev-parse', '--verify', $ref ],
1336 { STDERR
=> 0 }); };
1339 sub get_tree_from_treeish
{
1341 # $treeish can be a symbolic ref, too:
1342 my $type = command_oneline
(qw
/cat-file -t/, $treeish);
1344 while ($type eq 'tag') {
1345 ($treeish, $type) = command
(qw
/cat-file tag/, $treeish);
1347 if ($type eq 'commit') {
1348 $expected = (grep /^tree /, command
(qw
/cat-file commit/,
1350 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1351 die "Unable to get tree from $treeish\n" unless $expected;
1352 } elsif ($type eq 'tree') {
1353 $expected = $treeish;
1355 die "$treeish is a $type, expected tree, tag or commit\n";
1360 sub get_commit_entry
{
1361 my ($treeish) = shift;
1362 my %log_entry = ( log => '', tree
=> get_tree_from_treeish
($treeish) );
1363 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1364 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1365 open my $log_fh, '>', $commit_editmsg or croak
$!;
1367 my $type = command_oneline
(qw
/cat-file -t/, $treeish);
1368 if ($type eq 'commit' || $type eq 'tag') {
1369 my ($msg_fh, $ctx) = command_output_pipe
('cat-file',
1377 $in_msg = 1 if (/^\s*$/);
1378 $author = $1 if (/^author (.*>)/);
1379 } elsif (/^git-svn-id: /) {
1380 # skip this for now, we regenerate the
1381 # correct one on re-fetch anyways
1382 # TODO: set *:merge properties or like...
1384 if (/^From:/ || /^Signed-off-by:/) {
1390 $msgbuf =~ s/\s+$//s;
1391 if ($Git::SVN
::_add_author_from
&& defined($author)
1393 $msgbuf .= "\n\nFrom: $author";
1395 print $log_fh $msgbuf or croak
$!;
1396 command_close_pipe
($msg_fh, $ctx);
1398 close $log_fh or croak
$!;
1400 if ($_edit || ($type eq 'tree')) {
1401 chomp(my $editor = command_oneline
(qw(var GIT_EDITOR)));
1402 system('sh', '-c', $editor.' "$@"', $editor, $commit_editmsg);
1404 rename $commit_editmsg, $commit_msg or croak
$!;
1407 # SVN requires messages to be UTF-8 when entering the repo
1409 open $log_fh, '<', $commit_msg or croak
$!;
1411 chomp($log_entry{log} = <$log_fh>);
1413 my $enc = Git
::config
('i18n.commitencoding') || 'UTF-8';
1414 my $msg = $log_entry{log};
1416 eval { $msg = Encode
::decode
($enc, $msg, 1) };
1418 die "Could not decode as $enc:\n", $msg,
1419 "\nPerhaps you need to set i18n.commitencoding\n";
1422 eval { $msg = Encode
::encode
('UTF-8', $msg, 1) };
1423 die "Could not encode as UTF-8:\n$msg\n" if $@
;
1425 $log_entry{log} = $msg;
1427 close $log_fh or croak
$!;
1434 my ($str, $file, $mode) = @_;
1435 open my $fd,'>',$file or croak
$!;
1436 print $fd $str,"\n" or croak
$!;
1437 close $fd or croak
$!;
1438 chmod ($mode &~ umask, $file) if (defined $mode);
1443 open my $fd,'<',$file or croak
"$!: file: $file\n";
1446 close $fd or croak
$!;
1451 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1453 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1454 my $log = $cmd eq 'log';
1455 while (<$authors>) {
1457 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1458 my ($user, $name, $email) = ($1, $2, $3);
1460 $Git::SVN
::Log
::rusers
{"$name <$email>"} = $user;
1462 $users{$user} = [$name, $email];
1465 close $authors or croak
$!;
1468 # convert GetOpt::Long specs for use by git-config
1469 sub read_git_config
{
1472 foreach my $o (keys %$opts) {
1473 # if we have mixedCase and a long option-only, then
1474 # it's a config-only variable that we don't need for
1476 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1477 my $v = $opts->{$o};
1478 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1480 my $arg = 'git config';
1481 $arg .= ' --int' if ($o =~ /[:=]i$/);
1482 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1483 if (ref $v eq 'ARRAY') {
1484 chomp(my @tmp = `$arg --get-all svn.$key`);
1487 chomp(my $tmp = `$arg --get svn.$key`);
1488 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1493 delete @
$opts{@config_only} if @config_only;
1496 sub extract_metadata
{
1497 my $id = shift or return (undef, undef, undef);
1498 my ($url, $rev, $uuid) = ($id =~ /^\s
*git
-svn
-id
:\s
+(.*)\@
(\d
+)
1499 \s
([a
-f\d\
-]+)$/ix
);
1500 if (!defined $rev || !$uuid || !$url) {
1501 # some of the original repositories I made had
1502 # identifiers like this:
1503 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/i);
1505 return ($url, $rev, $uuid);
1509 return extract_metadata
((grep(/^git-svn-id: /,
1510 command
(qw
/cat-file commit/, shift)))[-1]);
1513 sub cmt_sha2rev_batch
{
1515 my ($pid, $in, $out, $ctx) = command_bidi_pipe
(qw
/cat-file --batch/);
1518 foreach my $sha (@
{$list}) {
1521 print $out $sha, "\n";
1523 while (my $line = <$in>) {
1524 if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1527 $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1531 } elsif ($line =~ /^(git-svn-id: )/) {
1532 my (undef, $rev, undef) =
1533 extract_metadata
($line);
1537 $size -= length($line);
1538 last if ($size == 0);
1542 command_close_bidi_pipe
($pid, $in, $out, $ctx);
1547 sub working_head_info
{
1548 my ($head, $refs) = @_;
1549 my @args = qw
/log --no-color
--no-decorate
--first
-parent
1551 my ($fh, $ctx) = command_output_pipe
(@args, $head);
1555 if ( m{^commit ($::sha1)$} ) {
1556 unshift @
$refs, $hash if $hash and $refs;
1560 next unless s{^\s*(git-svn-id:)}{$1};
1561 my ($url, $rev, $uuid) = extract_metadata
($_);
1562 if (defined $url && defined $rev) {
1563 next if $max{$url} and $max{$url} < $rev;
1564 if (my $gs = Git
::SVN
->find_by_url($url)) {
1565 my $c = $gs->rev_map_get($rev, $uuid);
1566 if ($c && $c eq $hash) {
1567 close $fh; # break the pipe
1568 return ($url, $rev, $uuid, $gs);
1570 $max{$url} ||= $gs->rev_map_max;
1575 command_close_pipe
($fh, $ctx);
1576 (undef, undef, undef, undef);
1579 sub read_commit_parents
{
1580 my ($parents, $c) = @_;
1581 chomp(my $p = command_oneline
(qw
/rev-list --parents -1/, $c));
1582 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1583 @
{$parents->{$c}} = split(/ /, $p);
1586 sub linearize_history
{
1587 my ($gs, $refs) = @_;
1589 foreach my $c (@
$refs) {
1590 read_commit_parents
(\
%parents, $c);
1595 my $last_svn_commit = $gs->last_commit;
1596 foreach my $c (reverse @
$refs) {
1597 next if $c eq $last_svn_commit;
1600 unshift @linear_refs, $c;
1603 # we only want the first parent to diff against for linear
1604 # history, we save the rest to inject when we finalize the
1606 my $fp_a = verify_ref
("$c~1");
1607 my $fp_b = shift @
{$parents{$c}} if $parents{$c};
1608 if (!$fp_a || !$fp_b) {
1610 "has no parent commit, and therefore ",
1611 "nothing to diff against.\n",
1612 "You should be working from a repository ",
1613 "originally created by git-svn\n";
1615 if ($fp_a ne $fp_b) {
1616 die "$c~1 = $fp_a, however parsing commit $c ",
1617 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1620 foreach my $p (@
{$parents{$c}}) {
1624 (\
@linear_refs, \
%parents);
1627 sub find_file_type_and_diff_status
{
1629 return ('dir', '') if $path eq '';
1632 command_oneline
(qw(diff --cached --name-status --), $path) || "";
1633 my $diff_status = (split(' ', $diff_output))[0] || "";
1635 my $ls_tree = command_oneline
(qw(ls-tree HEAD), $path) || "";
1637 return (undef, undef) if !$diff_status && !$ls_tree;
1639 if ($diff_status eq "A") {
1640 return ("link", $diff_status) if -l
$path;
1641 return ("dir", $diff_status) if -d
$path;
1642 return ("file", $diff_status);
1645 my $mode = (split(' ', $ls_tree))[0] || "";
1647 return ("link", $diff_status) if $mode eq "120000";
1648 return ("dir", $diff_status) if $mode eq "040000";
1649 return ("file", $diff_status);
1655 my $md5 = Digest
::MD5
->new();
1656 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
1657 $md5->addfile($arg) or croak
$!;
1658 } elsif ($ref eq 'SCALAR') {
1659 $md5->add($$arg) or croak
$!;
1661 $md5->add($arg) or croak
$!;
1663 ::fatal
"Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1665 return $md5->hexdigest();
1669 if ($can_compress && -f
$_ && basename
($_) eq "unhandled.log") {
1670 my $out_filename = $_ . ".gz";
1671 open my $in_fh, "<", $_ or die "Unable to open $_: $!\n";
1673 my $gz = Compress
::Zlib
::gzopen
($out_filename, "ab") or
1674 die "Unable to open $out_filename: $!\n";
1677 while ($res = sysread($in_fh, my $str, 1024)) {
1678 $gz->gzwrite($str) or
1679 die "Unable to write: ".$gz->gzerror()."!\n";
1681 unlink $_ or die "unlink $File::Find::name: $!\n";
1682 } elsif (-f
$_ && basename
($_) eq "index") {
1683 unlink $_ or die "unlink $_: $!\n";
1690 use Fcntl qw
/:DEFAULT :seek/;
1691 use constant rev_map_fmt
=> 'NH40';
1692 use vars qw
/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1693 $_repack $_repack_flags $_use_svm_props $_head
1694 $_use_svnsync_props $no_reuse_existing $_minimize_url
1695 $_use_log_author $_add_author_from $_localtime/;
1697 use File
::Path qw
/mkpath/;
1698 use File
::Copy qw
/copy/;
1700 use Memoize
; # core since 5.8.0, Jul 2002
1701 use Memoize
::Storable
;
1703 my ($_gc_nr, $_gc_period);
1705 # properties that we do not log:
1708 %SKIP_PROP = map { $_ => 1 } qw
/svn
:wc
:ra_dav
:version
-url
1709 svn
:special svn
:executable
1710 svn
:entry
:committed
-rev
1711 svn
:entry
:last-author
1713 svn
:entry
:committed
-date
/;
1715 # some options are read globally, but can be overridden locally
1716 # per [svn-remote "..."] section. Command-line options will *NOT*
1717 # override options set in an [svn-remote "..."] section
1719 for my $option (qw
/follow_parent no_metadata use_svm_props
1720 use_svnsync_props
/) {
1723 my $prop = "-$option";
1726 return $self->{$prop} if exists $self->{$prop};
1727 my $k = "svn-remote.$self->{repo_id}.$key";
1728 eval { command_oneline
(qw
/config --get/, $k) };
1730 $self->{$prop} = ${"Git::SVN::_$option"};
1732 my $v = command_oneline
(qw
/config --bool/,$k);
1733 $self->{$prop} = $v eq 'false' ?
0 : 1;
1735 return $self->{$prop};
1741 my (%LOCKFILES, %INDEX_FILES);
1743 unlink keys %LOCKFILES if %LOCKFILES;
1744 unlink keys %INDEX_FILES if %INDEX_FILES;
1747 sub resolve_local_globs
{
1748 my ($url, $fetch, $glob_spec) = @_;
1749 return unless defined $glob_spec;
1750 my $ref = $glob_spec->{ref};
1751 my $path = $glob_spec->{path
};
1752 foreach (command
(qw
#for-each-ref --format=%(refname) refs/#)) {
1753 next unless m
#^$ref->{regex}$#;
1755 my $pathname = desanitize_refname
($path->full_path($p));
1756 my $refname = desanitize_refname
($ref->full_path($p));
1757 if (my $existing = $fetch->{$pathname}) {
1758 if ($existing ne $refname) {
1759 die "Refspec conflict:\n",
1760 "existing: $existing\n",
1761 " globbed: $refname\n";
1763 my $u = (::cmt_metadata
("$refname"))[0];
1764 $u =~ s!^\Q$url\E(/|$)!! or die
1765 "$refname: '$url' not found in '$u'\n";
1766 if ($pathname ne $u) {
1767 warn "W: Refspec glob conflict ",
1768 "(ref: $refname):\n",
1769 "expected path: $pathname\n",
1771 "Continuing ahead with $u\n";
1775 $fetch->{$pathname} = $refname;
1780 sub parse_revision_argument
{
1781 my ($base, $head) = @_;
1782 if (!defined $::_revision
|| $::_revision
eq 'BASE:HEAD') {
1783 return ($base, $head);
1785 return ($1, $2) if ($::_revision
=~ /^(\d+):(\d+)$/);
1786 return ($::_revision
, $::_revision
) if ($::_revision
=~ /^\d+$/);
1787 return ($head, $head) if ($::_revision
eq 'HEAD');
1788 return ($base, $1) if ($::_revision
=~ /^BASE:(\d+)$/);
1789 return ($1, $head) if ($::_revision
=~ /^(\d+):HEAD$/);
1790 die "revision argument: $::_revision not understood by git-svn\n";
1794 my ($repo_id, $remotes) = @_;
1798 $repo_id = $gs->{repo_id
};
1800 $remotes ||= read_all_remotes
();
1801 my $remote = $remotes->{$repo_id} or
1802 die "[svn-remote \"$repo_id\"] unknown\n";
1803 my $fetch = $remote->{fetch
};
1804 my $url = $remote->{url
} or die "svn-remote.$repo_id.url not defined\n";
1806 my $ra = Git
::SVN
::Ra
->new($url);
1807 my $uuid = $ra->get_uuid;
1808 my $head = $ra->get_latest_revnum;
1810 # ignore errors, $head revision may not even exist anymore
1811 eval { $ra->get_log("", $head, 0, 1, 0, 1, sub { $head = $_[1] }) };
1812 warn "W: $@\n" if $@
;
1814 my $base = defined $fetch ?
$head : 0;
1816 # read the max revs for wildcard expansion (branches/*, tags/*)
1817 foreach my $t (qw
/branches tags/) {
1818 defined $remote->{$t} or next;
1819 push @globs, @
{$remote->{$t}};
1821 my $max_rev = eval { tmp_config
(qw
/--int --get/,
1822 "svn-remote.$repo_id.${t}-maxRev") };
1823 if (defined $max_rev && ($max_rev < $base)) {
1825 } elsif (!defined $max_rev) {
1831 foreach my $p (sort keys %$fetch) {
1832 my $gs = Git
::SVN
->new($fetch->{$p}, $repo_id, $p);
1833 my $lr = $gs->rev_map_max;
1835 $base = $lr if ($lr < $base);
1841 ($base, $head) = parse_revision_argument
($base, $head);
1842 $ra->gs_fetch_loop_common($base, $head, \
@gs, \
@globs);
1845 sub read_all_remotes
{
1847 my $use_svm_props = eval { command_oneline
(qw
/config
--bool
1848 svn
.useSvmProps
/) };
1849 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
1850 my $svn_refspec = qr{\s*(.*?)\s*:\s*(.+?)\s*};
1851 foreach (grep { s/^svn-remote\.// } command
(qw
/config -l/)) {
1852 if (m!^(.+)\.fetch=$svn_refspec$!) {
1853 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
1854 die("svn-remote.$remote: remote ref '$remote_ref' "
1855 . "must start with 'refs/'\n")
1856 unless $remote_ref =~ m{^refs/};
1857 $local_ref = uri_decode
($local_ref);
1858 $r->{$remote}->{fetch
}->{$local_ref} = $remote_ref;
1859 $r->{$remote}->{svm
} = {} if $use_svm_props;
1860 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
1861 $r->{$1}->{svm
} = {};
1862 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1863 $r->{$1}->{url
} = $2;
1864 } elsif (m!^(.+)\.pushurl=\s*(.*)\s*$!) {
1865 $r->{$1}->{pushurl
} = $2;
1866 } elsif (m!^(.+)\.(branches|tags)=$svn_refspec$!) {
1867 my ($remote, $t, $local_ref, $remote_ref) =
1869 die("svn-remote.$remote: remote ref '$remote_ref' ($t) "
1870 . "must start with 'refs/'\n")
1871 unless $remote_ref =~ m{^refs/};
1872 $local_ref = uri_decode
($local_ref);
1876 path
=> Git
::SVN
::GlobSpec
->new($local_ref, 1),
1877 ref => Git
::SVN
::GlobSpec
->new($remote_ref, 0) };
1878 if (length($rs->{ref}->{right
}) != 0) {
1879 die "The '*' glob character must be the last ",
1880 "character of '$remote_ref'\n";
1882 push @
{ $r->{$remote}->{$t} }, $rs;
1887 if (defined $r->{$_}->{svm
}) {
1890 my $section = "svn-remote.$_";
1892 source
=> tmp_config
('--get',
1893 "$section.svm-source"),
1894 replace
=> tmp_config
('--get',
1895 "$section.svm-replace"),
1898 $r->{$_}->{svm
} = $svm;
1906 $_gc_nr = $_gc_period = 1000;
1907 if (defined $_repack || defined $_repack_flags) {
1908 warn "Repack options are obsolete; they have no effect.\n";
1912 sub verify_remotes_sanity
{
1913 return unless -d
$ENV{GIT_DIR
};
1915 foreach (command
(qw
/config -l/)) {
1916 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1918 die "Remote ref refs/remote/$1 is tracked by",
1919 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1920 "Please resolve this ambiguity in ",
1921 "your git configuration file before ",
1929 sub find_existing_remote
{
1930 my ($url, $remotes) = @_;
1931 return undef if $no_reuse_existing;
1933 foreach my $repo_id (keys %$remotes) {
1934 my $u = $remotes->{$repo_id}->{url
} or next;
1936 $existing = $repo_id;
1942 sub init_remote_config
{
1943 my ($self, $url, $no_write) = @_;
1944 $url =~ s!/+$!!; # strip trailing slash
1945 my $r = read_all_remotes
();
1946 my $existing = find_existing_remote
($url, $r);
1948 unless ($no_write) {
1949 print STDERR
"Using existing ",
1950 "[svn-remote \"$existing\"]\n";
1952 $self->{repo_id
} = $existing;
1953 } elsif ($_minimize_url) {
1954 my $min_url = Git
::SVN
::Ra
->new($url)->minimize_url;
1955 $existing = find_existing_remote
($min_url, $r);
1957 unless ($no_write) {
1958 print STDERR
"Using existing ",
1959 "[svn-remote \"$existing\"]\n";
1961 $self->{repo_id
} = $existing;
1963 if ($min_url ne $url) {
1964 unless ($no_write) {
1965 print STDERR
"Using higher level of URL: ",
1966 "$url => $min_url\n";
1968 my $old_path = $self->{path
};
1969 $self->{path
} = $url;
1970 $self->{path
} =~ s!^\Q$min_url\E(/|$)!!;
1971 if (length $old_path) {
1972 $self->{path
} .= "/$old_path";
1979 # verify that we aren't overwriting anything:
1981 command_oneline
('config', '--get',
1982 "svn-remote.$self->{repo_id}.url")
1984 if ($orig_url && ($orig_url ne $url)) {
1985 die "svn-remote.$self->{repo_id}.url already set: ",
1986 "$orig_url\nwanted to set to: $url\n";
1989 my ($xrepo_id, $xpath) = find_ref
($self->refname);
1990 if (!$no_write && defined $xpath) {
1991 die "svn-remote.$xrepo_id.fetch already set to track ",
1992 "$xpath:", $self->refname, "\n";
1994 unless ($no_write) {
1995 command_noisy
('config',
1996 "svn-remote.$self->{repo_id}.url", $url);
1997 $self->{path
} =~ s{^/}{};
1998 $self->{path
} =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
1999 command_noisy
('config', '--add',
2000 "svn-remote.$self->{repo_id}.fetch",
2001 "$self->{path}:".$self->refname);
2003 $self->{url
} = $url;
2006 sub find_by_url
{ # repos_root and, path are optional
2007 my ($class, $full_url, $repos_root, $path) = @_;
2009 return undef unless defined $full_url;
2010 remove_username
($full_url);
2011 remove_username
($repos_root) if defined $repos_root;
2012 my $remotes = read_all_remotes
();
2013 if (defined $full_url && defined $repos_root && !defined $path) {
2015 $path =~ s
#^\Q$repos_root\E(?:/|$)##;
2017 foreach my $repo_id (keys %$remotes) {
2018 my $u = $remotes->{$repo_id}->{url
} or next;
2019 remove_username
($u);
2020 next if defined $repos_root && $repos_root ne $u;
2022 my $fetch = $remotes->{$repo_id}->{fetch
} || {};
2023 foreach my $t (qw
/branches tags/) {
2024 foreach my $globspec (@
{$remotes->{$repo_id}->{$t}}) {
2025 resolve_local_globs
($u, $fetch, $globspec);
2029 my $rwr = rewrite_root
({repo_id
=> $repo_id});
2030 my $svm = $remotes->{$repo_id}->{svm
}
2031 if defined $remotes->{$repo_id}->{svm
};
2032 unless (defined $p) {
2038 remove_username
($z);
2039 } elsif (defined $svm) {
2040 $z = $svm->{source
};
2041 $prefix = $svm->{replace
};
2042 $prefix =~ s
#^\Q$u\E(?:/|$)##;
2045 $p =~ s
#^\Q$z\E(?:/|$)#$prefix# or next;
2047 foreach my $f (keys %$fetch) {
2049 return Git
::SVN
->new($fetch->{$f}, $repo_id, $f);
2056 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
2057 my $self = _new
($class, $repo_id, $ref_id, $path);
2059 $self->init_remote_config($url, $no_write);
2066 foreach (command
(qw
/config -l/)) {
2067 next unless m
!^svn
-remote\
.(.+)\
.fetch
=
2068 \s
*(.*?
)\s
*:\s
*(.+?
)\s
*$!x
;
2069 my ($repo_id, $path, $ref) = ($1, $2, $3);
2070 if ($ref eq $ref_id) {
2071 $path = '' if ($path =~ m
#^\./?#);
2072 return ($repo_id, $path);
2075 (undef, undef, undef);
2079 my ($class, $ref_id, $repo_id, $path) = @_;
2080 if (defined $ref_id && !defined $repo_id && !defined $path) {
2081 ($repo_id, $path) = find_ref
($ref_id);
2082 if (!defined $repo_id) {
2083 die "Could not find a \"svn-remote.*.fetch\" key ",
2084 "in the repository configuration matching: ",
2088 my $self = _new
($class, $repo_id, $ref_id, $path);
2089 if (!defined $self->{path
} || !length $self->{path
}) {
2090 my $fetch = command_oneline
('config', '--get',
2091 "svn-remote.$repo_id.fetch",
2093 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
2094 "\":$ref_id\$\" in config\n";
2095 ($self->{path
}, undef) = split(/\s*:\s*/, $fetch);
2097 $self->{path
} =~ s{/+}{/}g;
2098 $self->{path
} =~ s{\A/}{};
2099 $self->{path
} =~ s{/\z}{};
2100 $self->{url
} = command_oneline
('config', '--get',
2101 "svn-remote.$repo_id.url") or
2102 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
2103 $self->{pushurl
} = eval { command_oneline
('config', '--get',
2104 "svn-remote.$repo_id.pushurl") };
2110 my ($refname) = $_[0]->{ref_id
} ;
2112 # It cannot end with a slash /, we'll throw up on this because
2113 # SVN can't have directories with a slash in their name, either:
2114 if ($refname =~ m{/$}) {
2115 die "ref: '$refname' ends with a trailing slash, this is ",
2116 "not permitted by git nor Subversion\n";
2119 # It cannot have ASCII control character space, tilde ~, caret ^,
2120 # colon :, question-mark ?, asterisk *, space, or open bracket [
2123 # Additionally, % must be escaped because it is used for escaping
2124 # and we want our escaped refname to be reversible
2125 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
2127 # no slash-separated component can begin with a dot .
2129 $refname =~ s{/\.}{/%2E}g;
2131 # It cannot have two consecutive dots .. anywhere
2133 $refname =~ s{\.\.}{%2E%2E}g;
2135 # trailing dots and .lock are not allowed
2136 # .$ becomes %2E and .lock becomes %2Elock
2137 $refname =~ s{\.(?=$|lock$)}{%2E};
2139 # the sequence @{ is used to access the reflog
2141 $refname =~ s{\@\{}{%40\{}g;
2146 sub desanitize_refname
{
2148 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
2154 return $self->{svm
}->{uuid
} if $self->svm;
2156 unless ($self->{svm
}) {
2157 die "SVM UUID not cached, and reading remotely failed\n";
2159 $self->{svm
}->{uuid
};
2164 return $self->{svm
} if $self->{svm
};
2166 # see if we have it in our config, first:
2168 my $section = "svn-remote.$self->{repo_id}";
2170 source
=> tmp_config
('--get', "$section.svm-source"),
2171 uuid
=> tmp_config
('--get', "$section.svm-uuid"),
2172 replace
=> tmp_config
('--get', "$section.svm-replace"),
2175 if ($svm && $svm->{source
} && $svm->{uuid
} && $svm->{replace
}) {
2176 $self->{svm
} = $svm;
2182 my ($self, $ra) = @_;
2183 return $ra if $self->svm;
2185 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
2186 "(svm:source, svm:uuid) ",
2187 "from the following URLs:\n" );
2188 sub read_svm_props
{
2189 my ($self, $ra, $path, $r) = @_;
2190 my $props = ($ra->get_dir($path, $r))[2];
2191 my $src = $props->{'svm:source'};
2192 my $uuid = $props->{'svm:uuid'};
2193 return undef if (!$src || !$uuid);
2197 $uuid =~ m{^[0-9a-f\-]{30,}$}i
2198 or die "doesn't look right - svm:uuid is '$uuid'\n";
2200 # the '!' is used to mark the repos_root!/relative/path
2201 $src =~ s{/?!/?}{/};
2202 $src =~ s{/+$}{}; # no trailing slashes please
2203 # username is of no interest
2204 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
2206 my $replace = $ra->{url
};
2207 $replace .= "/$path" if length $path;
2209 my $section = "svn-remote.$self->{repo_id}";
2210 tmp_config
("$section.svm-source", $src);
2211 tmp_config
("$section.svm-replace", $replace);
2212 tmp_config
("$section.svm-uuid", $uuid);
2220 my $r = $ra->get_latest_revnum;
2221 my $path = $self->{path
};
2223 while (length $path) {
2224 unless ($tried{"$self->{url}/$path"}) {
2225 return $ra if $self->read_svm_props($ra, $path, $r);
2226 $tried{"$self->{url}/$path"} = 1;
2228 $path =~ s
#/?[^/]+$##;
2230 die "Path: '$path' should be ''\n" if $path ne '';
2231 return $ra if $self->read_svm_props($ra, $path, $r);
2232 $tried{"$self->{url}/$path"} = 1;
2234 if ($ra->{repos_root
} eq $self->{url
}) {
2235 die @err, (map { " $_\n" } keys %tried), "\n";
2238 # nope, make sure we're connected to the repository root:
2241 $path = $ra->{svn_path
};
2242 $ra = Git
::SVN
::Ra
->new($ra->{repos_root
});
2243 while (length $path) {
2244 unless ($tried{"$ra->{url}/$path"}) {
2245 $ok = $self->read_svm_props($ra, $path, $r);
2247 $tried{"$ra->{url}/$path"} = 1;
2249 $path =~ s
#/?[^/]+$##;
2251 die "Path: '$path' should be ''\n" if $path ne '';
2252 $ok ||= $self->read_svm_props($ra, $path, $r);
2253 $tried{"$ra->{url}/$path"} = 1;
2255 die @err, (map { " $_\n" } keys %tried), "\n";
2257 Git
::SVN
::Ra
->new($self->{url
});
2262 return $self->{svnsync
} if $self->{svnsync
};
2264 if ($self->no_metadata) {
2265 die "Can't have both 'noMetadata' and ",
2266 "'useSvnsyncProps' options set!\n";
2268 if ($self->rewrite_root) {
2269 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
2272 if ($self->rewrite_uuid) {
2273 die "Can't have both 'useSvnsyncProps' and 'rewriteUUID' ",
2278 # see if we have it in our config, first:
2280 my $section = "svn-remote.$self->{repo_id}";
2282 my $url = tmp_config
('--get', "$section.svnsync-url");
2283 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2284 die "doesn't look right - svn:sync-from-url is '$url'\n";
2286 my $uuid = tmp_config
('--get', "$section.svnsync-uuid");
2287 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i
) or
2288 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2290 $svnsync = { url
=> $url, uuid
=> $uuid }
2292 if ($svnsync && $svnsync->{url
} && $svnsync->{uuid
}) {
2293 return $self->{svnsync
} = $svnsync;
2296 my $err = "useSvnsyncProps set, but failed to read " .
2297 "svnsync property: svn:sync-from-";
2298 my $rp = $self->ra->rev_proplist(0);
2300 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
2301 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2302 die "doesn't look right - svn:sync-from-url is '$url'\n";
2304 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
2305 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i
) or
2306 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2308 my $section = "svn-remote.$self->{repo_id}";
2309 tmp_config
('--add', "$section.svnsync-uuid", $uuid);
2310 tmp_config
('--add', "$section.svnsync-url", $url);
2311 return $self->{svnsync
} = { url
=> $url, uuid
=> $uuid };
2314 # this allows us to memoize our SVN::Ra UUID locally and avoid a
2315 # remote lookup (useful for 'git svn log').
2318 unless ($self->{ra_uuid
}) {
2319 my $key = "svn-remote.$self->{repo_id}.uuid";
2320 my $uuid = eval { tmp_config
('--get', $key) };
2321 if (!$@
&& $uuid && $uuid =~ /^([a-f\d\-]{30,})$/i) {
2322 $self->{ra_uuid
} = $uuid;
2324 die "ra_uuid called without URL\n" unless $self->{url
};
2325 $self->{ra_uuid
} = $self->ra->get_uuid;
2326 tmp_config
('--add', $key, $self->{ra_uuid
});
2332 sub _set_repos_root
{
2333 my ($self, $repos_root) = @_;
2334 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2335 $repos_root ||= $self->ra->{repos_root
};
2336 tmp_config
($k, $repos_root);
2342 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2343 eval { tmp_config
('--get', $k) } || $self->_set_repos_root;
2348 my $ra = Git
::SVN
::Ra
->new($self->{url
});
2349 $self->_set_repos_root($ra->{repos_root
});
2350 if ($self->use_svm_props && !$self->{svm
}) {
2351 if ($self->no_metadata) {
2352 die "Can't have both 'noMetadata' and ",
2353 "'useSvmProps' options set!\n";
2354 } elsif ($self->use_svnsync_props) {
2355 die "Can't have both 'useSvnsyncProps' and ",
2356 "'useSvmProps' options set!\n";
2358 $ra = $self->_set_svm_vars($ra);
2359 $self->{-want_revprops
} = 1;
2364 # prop_walk(PATH, REV, SUB)
2365 # -------------------------
2366 # Recursively traverse PATH at revision REV and invoke SUB for each
2367 # directory that contains a SVN property. SUB will be invoked as
2368 # follows: &SUB(gs, path, props); where `gs' is this instance of
2369 # Git::SVN, `path' the path to the directory where the properties
2370 # `props' were found. The `path' will be relative to point of checkout,
2371 # that is, if url://repo/trunk is the current Git branch, and that
2372 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
2373 # as `path' (note the trailing `/').
2375 my ($self, $path, $rev, $sub) = @_;
2378 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2381 # Strip the irrelevant part of the path.
2382 $p =~ s
#^/+\Q$self->{path}\E(/|$)#/#;
2383 # Ensure the path is terminated by a `/'.
2386 # The properties contain all the internal SVN stuff nobody
2387 # (usually) cares about.
2388 my $interesting_props = 0;
2389 foreach (keys %{$props}) {
2390 # If it doesn't start with `svn:', it must be a
2391 # user-defined property.
2392 ++$interesting_props and next if $_ !~ /^svn:/;
2393 # FIXME: Fragile, if SVN adds new public properties,
2394 # this needs to be updated.
2395 ++$interesting_props if /^svn
:(?
:ignore
|keywords
|executable
2396 |eol
-style
|mime
-type
2397 |externals
|needs
-lock)$/x
;
2399 &$sub($self, $p, $props) if $interesting_props;
2401 foreach (sort keys %$dirent) {
2402 next if $dirent->{$_}->{kind
} != $SVN::Node
::dir
;
2403 $self->prop_walk($self->{path
} . $p . $_, $rev, $sub);
2407 sub last_rev
{ ($_[0]->last_rev_commit)[0] }
2408 sub last_commit
{ ($_[0]->last_rev_commit)[1] }
2410 # returns the newest SVN revision number and newest commit SHA1
2411 sub last_rev_commit
{
2413 if (defined $self->{last_rev
} && defined $self->{last_commit
}) {
2414 return ($self->{last_rev
}, $self->{last_commit
});
2416 my $c = ::verify_ref
($self->refname.'^0');
2417 if ($c && !$self->use_svm_props && !$self->no_metadata) {
2418 my $rev = (::cmt_metadata
($c))[1];
2420 ($self->{last_rev
}, $self->{last_commit
}) = ($rev, $c);
2424 my $map_path = $self->map_path;
2425 unless (-e
$map_path) {
2426 ($self->{last_rev
}, $self->{last_commit
}) = (undef, undef);
2427 return (undef, undef);
2429 my ($rev, $commit) = $self->rev_map_max(1);
2430 ($self->{last_rev
}, $self->{last_commit
}) = ($rev, $commit);
2431 return ($rev, $commit);
2434 sub get_fetch_range
{
2435 my ($self, $min, $max) = @_;
2436 $max ||= $self->ra->get_latest_revnum;
2437 $min ||= $self->rev_map_max;
2443 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2444 my $config = "$ENV{GIT_DIR}/svn/.metadata";
2445 if (! -f
$config && -f
$old_def_config) {
2446 rename $old_def_config, $config or
2447 die "Failed rename $old_def_config => $config: $!\n";
2449 my $old_config = $ENV{GIT_CONFIG
};
2450 $ENV{GIT_CONFIG
} = $config;
2453 unless (-f
$config) {
2455 open my $fh, '>', $config or
2456 die "Can't open $config: $!\n";
2457 print $fh "; This file is used internally by ",
2459 "Couldn't write to $config: $!\n";
2460 print $fh "; You should not have to edit it\n" or
2461 die "Couldn't write to $config: $!\n";
2462 close $fh or die "Couldn't close $config: $!\n";
2464 command
('config', @args);
2467 if (defined $old_config) {
2468 $ENV{GIT_CONFIG
} = $old_config;
2470 delete $ENV{GIT_CONFIG
};
2473 wantarray ?
@ret : $ret[0];
2477 my ($self, $sub) = @_;
2478 my $old_index = $ENV{GIT_INDEX_FILE
};
2479 $ENV{GIT_INDEX_FILE
} = $self->{index};
2482 my ($dir, $base) = ($self->{index} =~ m
#^(.*?)/?([^/]+)$#);
2483 mkpath
([$dir]) unless -d
$dir;
2487 if (defined $old_index) {
2488 $ENV{GIT_INDEX_FILE
} = $old_index;
2490 delete $ENV{GIT_INDEX_FILE
};
2493 wantarray ?
@ret : $ret[0];
2496 sub assert_index_clean
{
2497 my ($self, $treeish) = @_;
2499 $self->tmp_index_do(sub {
2500 command_noisy
('read-tree', $treeish) unless -e
$self->{index};
2501 my $x = command_oneline
('write-tree');
2502 my ($y) = (command
(qw
/cat-file commit/, $treeish) =~
2503 /^tree ($::sha1)/mo);
2506 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2507 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2508 command_noisy
('read-tree', $treeish);
2509 $x = command_oneline
('write-tree');
2511 ::fatal
"trees ($treeish) $y != $x\n",
2512 "Something is seriously wrong...";
2517 sub get_commit_parents
{
2518 my ($self, $log_entry) = @_;
2519 my (%seen, @ret, @tmp);
2520 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2521 if (my $ip = $self->{inject_parents
}) {
2522 if (my $commit = delete $ip->{$log_entry->{revision
}}) {
2526 if (my $cur = ::verify_ref
($self->refname.'^0')) {
2529 if (my $ipd = $self->{inject_parents_dcommit
}) {
2530 if (my $commit = delete $ipd->{$log_entry->{revision
}}) {
2531 push @tmp, @
$commit;
2534 push @tmp, $_ foreach (@
{$log_entry->{parents
}}, @tmp);
2535 while (my $p = shift @tmp) {
2545 return $self->{-rewrite_root
} if exists $self->{-rewrite_root
};
2546 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2547 my $rwr = eval { command_oneline
(qw
/config --get/, $k) };
2550 if ($rwr !~ m
#^[a-z\+]+://#) {
2551 die "$rwr is not a valid URL (key: $k)\n";
2554 $self->{-rewrite_root
} = $rwr;
2559 return $self->{-rewrite_uuid
} if exists $self->{-rewrite_uuid
};
2560 my $k = "svn-remote.$self->{repo_id}.rewriteUUID";
2561 my $rwid = eval { command_oneline
(qw
/config --get/, $k) };
2564 if ($rwid !~ m
#^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$#) {
2565 die "$rwid is not a valid UUID (key: $k)\n";
2568 $self->{-rewrite_uuid
} = $rwid;
2573 ($self->rewrite_root || $self->{url
}) .
2574 (length $self->{path
} ?
'/' . $self->{path
} : '');
2579 $self->{url
} . (length $self->{path
} ?
'/' . $self->{path
} : '');
2584 if ($self->{pushurl
}) {
2585 return $self->{pushurl
} . (length $self->{path
} ?
'/' .
2586 $self->{path
} : '');
2588 return $self->full_url;
2592 sub set_commit_header_env
{
2593 my ($log_entry) = @_;
2595 foreach my $ned (qw
/NAME EMAIL DATE/) {
2596 foreach my $ac (qw
/AUTHOR COMMITTER/) {
2597 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2601 $ENV{GIT_AUTHOR_NAME
} = $log_entry->{name
};
2602 $ENV{GIT_AUTHOR_EMAIL
} = $log_entry->{email
};
2603 $ENV{GIT_AUTHOR_DATE
} = $ENV{GIT_COMMITTER_DATE
} = $log_entry->{date
};
2605 $ENV{GIT_COMMITTER_NAME
} = (defined $log_entry->{commit_name
})
2606 ?
$log_entry->{commit_name
}
2607 : $log_entry->{name
};
2608 $ENV{GIT_COMMITTER_EMAIL
} = (defined $log_entry->{commit_email
})
2609 ?
$log_entry->{commit_email
}
2610 : $log_entry->{email
};
2614 sub restore_commit_header_env
{
2616 foreach my $ned (qw
/NAME EMAIL DATE/) {
2617 foreach my $ac (qw
/AUTHOR COMMITTER/) {
2618 my $k = "GIT_${ac}_${ned}";
2619 if (defined $env->{$k}) {
2620 $ENV{$k} = $env->{$k};
2629 command_noisy
('gc', '--auto');
2633 my ($self, $log_entry) = @_;
2634 my $lr = $self->last_rev;
2635 if (defined $lr && $lr >= $log_entry->{revision
}) {
2636 die "Last fetched revision of ", $self->refname,
2637 " was r$lr, but we are about to fetch: ",
2638 "r$log_entry->{revision}!\n";
2640 if (my $c = $self->rev_map_get($log_entry->{revision
})) {
2641 croak
"$log_entry->{revision} = $c already exists! ",
2642 "Why are we refetching it?\n";
2644 my $old_env = set_commit_header_env
($log_entry);
2645 my $tree = $log_entry->{tree
};
2646 if (!defined $tree) {
2647 $tree = $self->tmp_index_do(sub {
2648 command_oneline
('write-tree') });
2650 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2652 my @exec = ('git', 'commit-tree', $tree);
2653 foreach ($self->get_commit_parents($log_entry)) {
2654 push @exec, '-p', $_;
2656 defined(my $pid = open3
(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2660 # we always get UTF-8 from SVN, but we may want our commits in
2661 # a different encoding.
2662 if (my $enc = Git
::config
('i18n.commitencoding')) {
2664 Encode
::from_to
($log_entry->{log}, 'UTF-8', $enc);
2666 print $msg_fh $log_entry->{log} or croak
$!;
2667 restore_commit_header_env
($old_env);
2668 unless ($self->no_metadata) {
2669 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2672 $msg_fh->flush == 0 or croak
$!;
2673 close $msg_fh or croak
$!;
2674 chomp(my $commit = do { local $/; <$out_fh> });
2675 close $out_fh or croak
$!;
2678 if ($commit !~ /^$::sha1$/o) {
2679 die "Failed to commit, invalid sha1: $commit\n";
2682 $self->rev_map_set($log_entry->{revision
}, $commit, 1);
2684 $self->{last_rev
} = $log_entry->{revision
};
2685 $self->{last_commit
} = $commit;
2686 print "r$log_entry->{revision}" unless $::_q
> 1;
2687 if (defined $log_entry->{svm_revision
}) {
2688 print " (\@$log_entry->{svm_revision})" unless $::_q
> 1;
2689 $self->rev_map_set($log_entry->{svm_revision
}, $commit,
2690 0, $self->svm_uuid);
2692 print " = $commit ($self->{ref_id})\n" unless $::_q
> 1;
2693 if (--$_gc_nr == 0) {
2694 $_gc_nr = $_gc_period;
2701 my ($self, $paths, $r) = @_;
2702 return 1 if $self->{path
} eq '';
2703 if (my $path = $paths->{"/$self->{path}"}) {
2704 return ($path->{action
} eq 'D') ?
0 : 1;
2706 $self->{path_regex
} ||= qr/^\/\Q
$self->{path
}\E\
//;
2707 if (grep /$self->{path_regex}/, keys %$paths) {
2711 foreach (split m
#/#, $self->{path}) {
2713 next unless ($paths->{$c} &&
2714 ($paths->{$c}->{action
} =~ /^[AR]$/));
2715 if ($self->ra->check_path($self->{path
}, $r) ==
2723 sub find_parent_branch
{
2724 my ($self, $paths, $rev) = @_;
2725 return undef unless $self->follow_parent;
2726 unless (defined $paths) {
2727 my $err_handler = $SVN::Error
::handler
;
2728 $SVN::Error
::handler
= \
&Git
::SVN
::Ra
::skip_unknown_revs
;
2729 $self->ra->get_log([$self->{path
}], $rev, $rev, 0, 1, 1,
2730 sub { $paths = $_[0] });
2731 $SVN::Error
::handler
= $err_handler;
2733 return undef unless defined $paths;
2735 # look for a parent from another branch:
2736 my @b_path_components = split m
#/#, $self->{path};
2737 my @a_path_components;
2739 while (@b_path_components) {
2740 $i = $paths->{'/'.join('/', @b_path_components)};
2741 last if $i && defined $i->{copyfrom_path
};
2742 unshift(@a_path_components, pop(@b_path_components));
2744 return undef unless defined $i && defined $i->{copyfrom_path
};
2745 my $branch_from = $i->{copyfrom_path
};
2746 if (@a_path_components) {
2747 print STDERR
"branch_from: $branch_from => ";
2748 $branch_from .= '/'.join('/', @a_path_components);
2749 print STDERR
$branch_from, "\n";
2751 my $r = $i->{copyfrom_rev
};
2752 my $repos_root = $self->ra->{repos_root
};
2753 my $url = $self->ra->{url
};
2754 my $new_url = $url . $branch_from;
2755 print STDERR
"Found possible branch point: ",
2756 "$new_url => ", $self->full_url, ", $r\n"
2758 $branch_from =~ s
#^/##;
2759 my $gs = $self->other_gs($new_url, $url,
2760 $branch_from, $r, $self->{ref_id
});
2761 my ($r0, $parent) = $gs->find_rev_before($r, 1);
2764 if (!defined $r0 || !defined $parent) {
2765 ($base, $head) = parse_revision_argument
(0, $r);
2768 $gs->ra->get_log([$gs->{path
}], $r0 + 1, $r, 1,
2769 0, 1, sub { $base = $_[1] - 1 });
2772 if (defined $base && $base <= $r) {
2773 $gs->fetch($base, $r);
2775 ($r0, $parent) = $gs->find_rev_before($r, 1);
2777 if (defined $r0 && defined $parent) {
2778 print STDERR
"Found branch parent: ($self->{ref_id}) $parent\n"
2781 if ($self->ra->can_do_switch) {
2782 $self->assert_index_clean($parent);
2783 print STDERR
"Following parent with do_switch\n"
2785 # do_switch works with svn/trunk >= r22312, but that
2786 # is not included with SVN 1.4.3 (the latest version
2787 # at the moment), so we can't rely on it
2788 $self->{last_rev
} = $r0;
2789 $self->{last_commit
} = $parent;
2790 $ed = SVN
::Git
::Fetcher
->new($self, $gs->{path
});
2791 $gs->ra->gs_do_switch($r0, $rev, $gs,
2792 $self->full_url, $ed)
2793 or die "SVN connection failed somewhere...\n";
2794 } elsif ($self->ra->trees_match($new_url, $r0,
2795 $self->full_url, $rev)) {
2796 print STDERR
"Trees match:\n",
2798 " ${\$self->full_url}\@$rev\n",
2799 "Following parent with no changes\n"
2801 $self->tmp_index_do(sub {
2802 command_noisy
('read-tree', $parent);
2804 $self->{last_commit
} = $parent;
2806 print STDERR
"Following parent with do_update\n"
2808 $ed = SVN
::Git
::Fetcher
->new($self);
2809 $self->ra->gs_do_update($rev, $rev, $self, $ed)
2810 or die "SVN connection failed somewhere...\n";
2812 print STDERR
"Successfully followed parent\n" unless $::_q
> 1;
2813 return $self->make_log_entry($rev, [$parent], $ed);
2819 my ($self, $paths, $rev) = @_;
2821 my ($last_rev, @parents);
2822 if (my $lc = $self->last_commit) {
2823 # we can have a branch that was deleted, then re-added
2824 # under the same name but copied from another path, in
2825 # which case we'll have multiple parents (we don't
2826 # want to break the original ref, nor lose copypath info):
2827 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2828 push @
{$log_entry->{parents
}}, $lc;
2831 $ed = SVN
::Git
::Fetcher
->new($self);
2832 $last_rev = $self->{last_rev
};
2837 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2840 $ed = SVN
::Git
::Fetcher
->new($self);
2842 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2843 die "SVN connection failed somewhere...\n";
2845 $self->make_log_entry($rev, \
@parents, $ed);
2849 my ($self, $r) = @_;
2852 my ($r, $empty_dirs, $line) = @_;
2853 if (defined $r && $line =~ /^r(\d+)$/) {
2854 return 0 if $1 > $r;
2855 } elsif ($line =~ /^ \+empty_dir: (.+)$/) {
2856 $empty_dirs->{$1} = 1;
2857 } elsif ($line =~ /^ \-empty_dir: (.+)$/) {
2858 my @d = grep {m
[^\Q
$1\E
(/|$)]} (keys %$empty_dirs);
2859 delete @
$empty_dirs{@d};
2864 my %empty_dirs = ();
2865 my $gz_file = "$self->{dir}/unhandled.log.gz";
2867 if (!$can_compress) {
2868 warn "Compress::Zlib could not be found; ",
2869 "empty directories in $gz_file will not be read\n";
2871 my $gz = Compress
::Zlib
::gzopen
($gz_file, "rb") or
2872 die "Unable to open $gz_file: $!\n";
2874 while ($gz->gzreadline($line) > 0) {
2875 scan
($r, \
%empty_dirs, $line) or last;
2881 if (open my $fh, '<', "$self->{dir}/unhandled.log") {
2882 binmode $fh or croak
"binmode: $!";
2884 scan
($r, \
%empty_dirs, $_) or last;
2889 my $strip = qr/\A\Q$self->{path}\E(?:\/|$)/;
2890 foreach my $d (sort keys %empty_dirs) {
2891 $d = uri_decode
($d);
2893 next unless length($d);
2896 warn "$d exists but is not a directory\n";
2898 print "creating empty directory: $d\n";
2905 my ($self, $ed) = @_;
2907 my $h = $ed->{empty
};
2908 foreach (sort keys %$h) {
2909 my $act = $h->{$_} ?
'+empty_dir' : '-empty_dir';
2910 push @out, " $act: " . uri_encode
($_);
2911 warn "W: $act: $_\n";
2913 foreach my $t (qw
/dir_prop file_prop/) {
2914 $h = $ed->{$t} or next;
2915 foreach my $path (sort keys %$h) {
2916 my $ppath = $path eq '' ?
'.' : $path;
2917 foreach my $prop (sort keys %{$h->{$path}}) {
2918 next if $SKIP_PROP{$prop};
2919 my $v = $h->{$path}->{$prop};
2920 my $t_ppath_prop = "$t: " .
2921 uri_encode
($ppath) . ' ' .
2924 push @out, " +$t_ppath_prop " .
2927 push @out, " -$t_ppath_prop";
2932 foreach my $t (qw
/absent_file absent_directory/) {
2933 $h = $ed->{$t} or next;
2934 foreach my $parent (sort keys %$h) {
2935 foreach my $path (sort @
{$h->{$parent}}) {
2936 push @out, " $t: " .
2937 uri_encode
("$parent/$path");
2938 warn "W: $t: $parent/$path ",
2939 "Insufficient permissions?\n";
2946 # parse_svn_date(DATE)
2947 # --------------------
2948 # Given a date (in UTC) from Subversion, return a string in the format
2949 # "<TZ Offset> <local date/time>" that Git will use.
2951 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
2952 # is true we'll convert it to the local timezone instead.
2953 sub parse_svn_date
{
2954 my $date = shift || return '+0000 1970-01-01 00:00:00';
2955 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d
{4})\
-(\d\d
)\
-(\d\d
)T
2956 (\d\d
)\
:(\d\d
)\
:(\d\d
)\
.\d
*Z
$/x
) or
2957 croak
"Unable to parse date: $date\n";
2958 my $parsed_date; # Set next.
2960 if ($Git::SVN
::_localtime
) {
2961 # Translate the Subversion datetime to an epoch time.
2962 # Begin by switching ourselves to $date's timezone, UTC.
2963 my $old_env_TZ = $ENV{TZ
};
2967 POSIX
::strftime
('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
2969 # Determine our local timezone (including DST) at the
2970 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
2971 # value of TZ, if any, at the time we were run.
2972 if (defined $Git::SVN
::Log
::TZ
) {
2973 $ENV{TZ
} = $Git::SVN
::Log
::TZ
;
2979 POSIX
::strftime
('%Z', $S, $M, $H, $d, $m - 1, $Y - 1900);
2981 # This converts $epoch_in_UTC into our local timezone.
2982 my ($sec, $min, $hour, $mday, $mon, $year,
2983 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
2985 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
2986 $our_TZ, $year + 1900, $mon + 1,
2987 $mday, $hour, $min, $sec);
2989 # Reset us to the timezone in effect when we entered
2991 if (defined $old_env_TZ) {
2992 $ENV{TZ
} = $old_env_TZ;
2997 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
3000 return $parsed_date;
3004 my ($self, $new_url, $url,
3005 $branch_from, $r, $old_ref_id) = @_;
3006 my $gs = Git
::SVN
->find_by_url($new_url, $url, $branch_from);
3008 my $ref_id = $old_ref_id;
3009 $ref_id =~ s/\@\d+-*$//;
3011 # just grow a tail if we're not unique enough :x
3012 $ref_id .= '-' while find_ref
($ref_id);
3013 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
3014 if ($u =~ s
#^\Q$url\E(/|$)##) {
3017 $repo_id = $self->{repo_id
};
3020 # It is possible to tag two different subdirectories at
3021 # the same revision. If the url for an existing ref
3022 # does not match, we must either find a ref with a
3023 # matching url or create a new ref by growing a tail.
3024 $gs = Git
::SVN
->init($u, $p, $repo_id, $ref_id, 1);
3025 my (undef, $max_commit) = $gs->rev_map_max(1);
3026 last if (!$max_commit);
3027 my ($url) = ::cmt_metadata
($max_commit);
3028 last if ($url eq $gs->metadata_url);
3031 print STDERR
"Initializing parent: $ref_id\n" unless $::_q
> 1;
3036 sub call_authors_prog
{
3037 my ($orig_author) = @_;
3038 $orig_author = command_oneline
('rev-parse', '--sq-quote', $orig_author);
3039 my $author = `$::_authors_prog $orig_author`;
3041 die "$::_authors_prog failed with exit code $?\n"
3043 if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
3044 my ($name, $email) = ($1, $2);
3045 $email = undef if length $2 == 0;
3046 return [$name, $email];
3048 die "Author: $orig_author: $::_authors_prog returned "
3049 . "invalid author format: $author\n";
3055 if (!defined $author || length $author == 0) {
3056 $author = '(no author)';
3058 if (!defined $::users
{$author}) {
3059 if (defined $::_authors_prog
) {
3060 $::users
{$author} = call_authors_prog
($author);
3061 } elsif (defined $::_authors
) {
3062 die "Author: $author not defined in $::_authors file\n";
3068 sub find_extra_svk_parents
{
3069 my ($self, $ed, $tickets, $parents) = @_;
3070 # aha! svk:merge property changed...
3071 my @tickets = split "\n", $tickets;
3073 for my $ticket ( @tickets ) {
3074 my ($uuid, $path, $rev) = split /:/, $ticket;
3075 if ( $uuid eq $self->ra_uuid ) {
3076 my $url = $self->{url
};
3077 my $repos_root = $url;
3078 my $branch_from = $path;
3079 $branch_from =~ s{^/}{};
3080 my $gs = $self->other_gs($repos_root."/".$branch_from,
3085 if ( my $commit = $gs->rev_map_get($rev, $uuid) ) {
3086 # wahey! we found it, but it might be
3088 push @known_parents, [ $rev, $commit ];
3092 # Ordering matters; highest-numbered commit merge tickets
3093 # first, as they may account for later merge ticket additions
3095 @known_parents = map {$_->[1]} sort {$b->[0] <=> $a->[0]} @known_parents;
3096 for my $parent ( @known_parents ) {
3097 my @cmd = ('rev-list', $parent, map { "^$_" } @
$parents );
3098 my ($msg_fh, $ctx) = command_output_pipe
(@cmd);
3100 while ( <$msg_fh> ) {
3103 command_close_pipe
($msg_fh, $ctx);
3106 "Found merge parent (svk:merge ticket): $parent\n";
3107 push @
$parents, $parent;
3112 sub lookup_svn_merge
{
3117 my ($source, $revs) = split ":", $merge;
3120 my $gs = Git
::SVN
->find_by_url($url.$source, $url, $path);
3122 warn "Couldn't find revmap for $url$source\n";
3125 my @ranges = split ",", $revs;
3126 my ($tip, $tip_commit);
3127 my @merged_commit_ranges;
3129 for my $range ( @ranges ) {
3130 my ($bottom, $top) = split "-", $range;
3132 my $bottom_commit = $gs->find_rev_after( $bottom, 1, $top );
3133 my $top_commit = $gs->find_rev_before( $top, 1, $bottom );
3135 unless ($top_commit and $bottom_commit) {
3136 warn "W:unknown path/rev in svn:mergeinfo "
3137 ."dirprop: $source:$range\n";
3141 if (scalar(command
('rev-parse', "$bottom_commit^@"))) {
3142 push @merged_commit_ranges,
3143 "$bottom_commit^..$top_commit";
3145 push @merged_commit_ranges, "$top_commit";
3148 if ( !defined $tip or $top > $tip ) {
3150 $tip_commit = $top_commit;
3153 return ($tip_commit, @merged_commit_ranges);
3157 my ($msg_fh, $ctx) = command_output_pipe
(
3161 while ( <$msg_fh> ) {
3165 command_close_pipe
($msg_fh, $ctx);
3169 sub check_cherry_pick
{
3172 my $parents = shift;
3174 my %commits = map { $_ => 1 }
3175 _rev_list
("--no-merges", $tip, "--not", $base, @
$parents, "--");
3176 for my $range ( @ranges ) {
3177 delete @commits{_rev_list
($range, "--")};
3179 for my $commit (keys %commits) {
3180 if (has_no_changes
($commit)) {
3181 delete $commits{$commit};
3184 return (keys %commits);
3187 sub has_no_changes
{
3190 my @revs = split / /, command_oneline
(
3191 qw(rev-list --parents -1 -m), $commit);
3193 # Commits with no parents, e.g. the start of a partial branch,
3194 # have changes by definition.
3195 return 1 if (@revs < 2);
3197 # Commits with multiple parents, e.g a merge, have no changes
3199 return 0 if (@revs > 2);
3201 return (command_oneline
("rev-parse", "$commit^{tree}") eq
3202 command_oneline
("rev-parse", "$commit~1^{tree}"));
3205 # The GIT_DIR environment variable is not always set until after the command
3206 # line arguments are processed, so we can't memoize in a BEGIN block.
3210 sub memoize_svn_mergeinfo_functions
{
3211 return if $memoized;
3214 my $cache_path = "$ENV{GIT_DIR}/svn/.caches/";
3215 mkpath
([$cache_path]) unless -d
$cache_path;
3217 tie
my %lookup_svn_merge_cache => 'Memoize::Storable',
3218 "$cache_path/lookup_svn_merge.db", 'nstore';
3219 memoize
'lookup_svn_merge',
3220 SCALAR_CACHE
=> 'FAULT',
3221 LIST_CACHE
=> ['HASH' => \
%lookup_svn_merge_cache],
3224 tie
my %check_cherry_pick_cache => 'Memoize::Storable',
3225 "$cache_path/check_cherry_pick.db", 'nstore';
3226 memoize
'check_cherry_pick',
3227 SCALAR_CACHE
=> 'FAULT',
3228 LIST_CACHE
=> ['HASH' => \
%check_cherry_pick_cache],
3231 tie
my %has_no_changes_cache => 'Memoize::Storable',
3232 "$cache_path/has_no_changes.db", 'nstore';
3233 memoize
'has_no_changes',
3234 SCALAR_CACHE
=> ['HASH' => \
%has_no_changes_cache],
3235 LIST_CACHE
=> 'FAULT',
3239 sub unmemoize_svn_mergeinfo_functions
{
3240 return if not $memoized;
3243 Memoize
::unmemoize
'lookup_svn_merge';
3244 Memoize
::unmemoize
'check_cherry_pick';
3245 Memoize
::unmemoize
'has_no_changes';
3248 Memoize
::memoize
'Git::SVN::repos_root';
3252 # Force cache writeout explicitly instead of waiting for
3253 # global destruction to avoid segfault in Storable:
3254 # http://rt.cpan.org/Public/Bug/Display.html?id=36087
3255 unmemoize_svn_mergeinfo_functions
();
3258 sub parents_exclude
{
3259 my $parents = shift;
3261 return unless @commits;
3266 my @cmd = ('rev-list', "-1", @commits, "--not", @
$parents );
3267 $excluded = command_oneline
(@cmd);
3271 for my $commit ( @commits ) {
3272 if ( $commit eq $excluded ) {
3273 push @excluded, $commit;
3281 die "saw commit '$excluded' in rev-list output, "
3282 ."but we didn't ask for that commit (wanted: @commits --not @$parents)"
3287 while ($excluded and @commits);
3293 # note: this function should only be called if the various dirprops
3294 # have actually changed
3295 sub find_extra_svn_parents
{
3296 my ($self, $ed, $mergeinfo, $parents) = @_;
3297 # aha! svk:merge property changed...
3299 memoize_svn_mergeinfo_functions
();
3301 # We first search for merged tips which are not in our
3302 # history. Then, we figure out which git revisions are in
3303 # that tip, but not this revision. If all of those revisions
3304 # are now marked as merge, we can add the tip as a parent.
3305 my @merges = split "\n", $mergeinfo;
3307 my $url = $self->{url
};
3308 my $uuid = $self->ra_uuid;
3310 for my $merge ( @merges ) {
3311 my ($tip_commit, @ranges) =
3312 lookup_svn_merge
( $uuid, $url, $merge );
3313 unless (!$tip_commit or
3314 grep { $_ eq $tip_commit } @
$parents ) {
3315 push @merge_tips, $tip_commit;
3316 $ranges{$tip_commit} = \
@ranges;
3318 push @merge_tips, undef;
3322 my %excluded = map { $_ => 1 }
3323 parents_exclude
($parents, grep { defined } @merge_tips);
3325 # check merge tips for new parents
3327 for my $merge_tip ( @merge_tips ) {
3328 my $spec = shift @merges;
3329 next unless $merge_tip and $excluded{$merge_tip};
3331 my $ranges = $ranges{$merge_tip};
3333 # check out 'new' tips
3336 $merge_base = command_oneline
(
3338 @
$parents, $merge_tip,
3342 die "An error occurred during merge-base"
3343 unless $@
->isa("Git::Error::Command");
3345 warn "W: Cannot find common ancestor between ".
3346 "@$parents and $merge_tip. Ignoring merge info.\n";
3350 # double check that there are no missing non-merge commits
3351 my (@incomplete) = check_cherry_pick
(
3352 $merge_base, $merge_tip,
3357 if ( @incomplete ) {
3358 warn "W:svn cherry-pick ignored ($spec) - missing "
3359 .@incomplete." commit(s) (eg $incomplete[0])\n";
3362 "Found merge parent (svn:mergeinfo prop): ",
3364 push @new_parents, $merge_tip;
3368 # cater for merges which merge commits from multiple branches
3369 if ( @new_parents > 1 ) {
3370 for ( my $i = 0; $i <= $#new_parents; $i++ ) {
3371 for ( my $j = 0; $j <= $#new_parents; $j++ ) {
3373 next unless $new_parents[$i];
3374 next unless $new_parents[$j];
3375 my $revs = command_oneline
(
3377 "$new_parents[$i]..$new_parents[$j]",
3380 undef($new_parents[$j]);
3385 push @
$parents, grep { defined } @new_parents;
3388 sub make_log_entry
{
3389 my ($self, $rev, $parents, $ed) = @_;
3390 my $untracked = $self->get_untracked($ed);
3392 my @parents = @
$parents;
3393 my $ps = $ed->{path_strip
} || "";
3394 for my $path ( grep { m/$ps/ } %{$ed->{dir_prop
}} ) {
3395 my $props = $ed->{dir_prop
}{$path};
3396 if ( $props->{"svk:merge"} ) {
3397 $self->find_extra_svk_parents
3398 ($ed, $props->{"svk:merge"}, \
@parents);
3400 if ( $props->{"svn:mergeinfo"} ) {
3401 $self->find_extra_svn_parents
3403 $props->{"svn:mergeinfo"},
3408 open my $un, '>>', "$self->{dir}/unhandled.log" or croak
$!;
3409 print $un "r$rev\n" or croak
$!;
3410 print $un $_, "\n" foreach @
$untracked;
3411 my %log_entry = ( parents
=> \
@parents, revision
=> $rev,
3415 my $logged = delete $self->{logged_rev_props
};
3416 if (!$logged || $self->{-want_revprops
}) {
3417 my $rp = $self->ra->rev_proplist($rev);
3418 foreach (sort keys %$rp) {
3420 if (/^svn:(author|date|log)$/) {
3421 $log_entry{$1} = $v;
3422 } elsif ($_ eq 'svm:headrev') {
3425 print $un " rev_prop: ", uri_encode
($_), ' ',
3426 uri_encode
($v), "\n";
3430 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
3432 close $un or croak
$!;
3434 $log_entry{date
} = parse_svn_date
($log_entry{date
});
3435 $log_entry{log} .= "\n";
3436 my $author = $log_entry{author
} = check_author
($log_entry{author
});
3437 my ($name, $email) = defined $::users
{$author} ? @
{$::users
{$author}}
3440 my ($commit_name, $commit_email) = ($name, $email);
3441 if ($_use_log_author) {
3443 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
3445 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
3448 if (!defined $name_field) {
3449 if (!defined $email) {
3452 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
3453 ($name, $email) = ($1, $2);
3454 } elsif ($name_field =~ /(.*)@/) {
3455 ($name, $email) = ($1, $name_field);
3457 ($name, $email) = ($name_field, $name_field);
3460 if (defined $headrev && $self->use_svm_props) {
3461 if ($self->rewrite_root) {
3462 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
3465 if ($self->rewrite_uuid) {
3466 die "Can't have both 'useSvmProps' and 'rewriteUUID' ",
3469 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d
+)$}i
;
3470 # we don't want "SVM: initializing mirror for junk" ...
3471 return undef if $r == 0;
3472 my $svm = $self->svm;
3473 if ($uuid ne $svm->{uuid
}) {
3474 die "UUID mismatch on SVM path:\n",
3475 "expected: $svm->{uuid}\n",
3478 my $full_url = $self->full_url;
3479 $full_url =~ s
#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
3480 die "Failed to replace '$svm->{replace}' with ",
3481 "'$svm->{source}' in $full_url\n";
3482 # throw away username for storing in records
3483 remove_username
($full_url);
3484 $log_entry{metadata
} = "$full_url\@$r $uuid";
3485 $log_entry{svm_revision
} = $r;
3486 $email ||= "$author\@$uuid";
3487 $commit_email ||= "$author\@$uuid";
3488 } elsif ($self->use_svnsync_props) {
3489 my $full_url = $self->svnsync->{url
};
3490 $full_url .= "/$self->{path}" if length $self->{path
};
3491 remove_username
($full_url);
3492 my $uuid = $self->svnsync->{uuid
};
3493 $log_entry{metadata
} = "$full_url\@$rev $uuid";
3494 $email ||= "$author\@$uuid";
3495 $commit_email ||= "$author\@$uuid";
3497 my $url = $self->metadata_url;
3498 remove_username
($url);
3499 my $uuid = $self->rewrite_uuid || $self->ra->get_uuid;
3500 $log_entry{metadata
} = "$url\@$rev " . $uuid;
3501 $email ||= "$author\@" . $uuid;
3502 $commit_email ||= "$author\@" . $uuid;
3504 $log_entry{name
} = $name;
3505 $log_entry{email
} = $email;
3506 $log_entry{commit_name
} = $commit_name;
3507 $log_entry{commit_email
} = $commit_email;
3512 my ($self, $min_rev, $max_rev, @parents) = @_;
3513 my ($last_rev, $last_commit) = $self->last_rev_commit;
3514 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
3515 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
3519 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
3520 $self->{inject_parents
} = { $rev => $tree };
3521 $self->fetch(undef, undef);
3525 my ($self, $tree) = (shift, shift);
3526 my $log_entry = ::get_commit_entry
($tree);
3527 unless ($self->{last_rev
}) {
3528 ::fatal
("Must have an existing revision to commit");
3530 my %ed_opts = ( r
=> $self->{last_rev
},
3531 log => $log_entry->{log},
3533 tree_a
=> $self->{last_commit
},
3536 $self->set_tree_cb($log_entry, $tree, @_) },
3537 svn_path
=> $self->{path
} );
3538 if (!SVN
::Git
::Editor
->new(\
%ed_opts)->apply_diff) {
3539 print "No changes\nr$self->{last_rev} = $tree\n";
3543 sub rebuild_from_rev_db
{
3544 my ($self, $path) = @_;
3546 open my $fh, '<', $path or croak
"open: $!";
3547 binmode $fh or croak
"binmode: $!";
3549 length($_) == 41 or croak
"inconsistent size in ($_) != 41";
3552 next if $_ eq ('0' x
40);
3553 $self->rev_map_set($r, $_);
3556 close $fh or croak
"close: $!";
3557 unlink $path or croak
"unlink: $!";
3562 my $map_path = $self->map_path;
3563 my $partial = (-e
$map_path && ! -z
$map_path);
3564 return unless ::verify_ref
($self->refname.'^0');
3565 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
3566 my $rev_db = $self->rev_db_path;
3567 $self->rebuild_from_rev_db($rev_db);
3568 if ($self->use_svm_props) {
3569 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
3570 $self->rebuild_from_rev_db($svm_rev_db);
3572 $self->unlink_rev_db_symlink;
3575 print "Rebuilding $map_path ...\n" if (!$partial);
3576 my ($base_rev, $head) = ($partial ?
$self->rev_map_max_norebuild(1) :
3579 command_output_pipe
(qw
/rev-list --pretty=raw --no-color --reverse/,
3580 ($head ?
"$head.." : "") . $self->refname,
3582 my $metadata_url = $self->metadata_url;
3583 remove_username
($metadata_url);
3584 my $svn_uuid = $self->rewrite_uuid || $self->ra_uuid;
3587 if ( m{^commit ($::sha1)$} ) {
3591 next unless s{^\s*(git-svn-id:)}{$1};
3592 my ($url, $rev, $uuid) = ::extract_metadata
($_);
3593 remove_username
($url);
3595 # ignore merges (from set-tree)
3596 next if (!defined $rev || !$uuid);
3598 # if we merged or otherwise started elsewhere, this is
3599 # how we break out of it
3600 if (($uuid ne $svn_uuid) ||
3601 ($metadata_url && $url && ($url ne $metadata_url))) {
3604 if ($partial && $head) {
3605 print "Partial-rebuilding $map_path ...\n";
3606 print "Currently at $base_rev = $head\n";
3610 $self->rev_map_set($rev, $c);
3611 print "r$rev = $c\n";
3613 command_close_pipe
($log, $ctx);
3614 print "Done rebuilding $map_path\n" if (!$partial || !$head);
3615 my $rev_db_path = $self->rev_db_path;
3616 if (-f
$self->rev_db_path) {
3617 unlink $self->rev_db_path or croak
"unlink: $!";
3619 $self->unlink_rev_db_symlink;
3623 # Tie::File seems to be prone to offset errors if revisions get sparse,
3624 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
3625 # one of my favorite modules is out :< Next up would be one of the DBM
3626 # modules, but I'm not sure which is most portable...
3628 # This is the replacement for the rev_db format, which was too big
3629 # and inefficient for large repositories with a lot of sparse history
3632 # The format is this:
3633 # - 24 bytes for every record,
3634 # * 4 bytes for the integer representing an SVN revision number
3635 # * 20 bytes representing the sha1 of a git commit
3636 # - No empty padding records like the old format
3637 # (except the last record, which can be overwritten)
3638 # - new records are written append-only since SVN revision numbers
3639 # increase monotonically
3640 # - lookups on SVN revision number are done via a binary search
3641 # - Piping the file to xxd -c24 is a good way of dumping it for
3642 # viewing or editing (piped back through xxd -r), should the need
3644 # - The last record can be padding revision with an all-zero sha1
3645 # This is used to optimize fetch performance when using multiple
3646 # "fetch" directives in .git/config
3648 # These files are disposable unless noMetadata or useSvmProps is set
3651 my ($fh, $rev, $commit) = @_;
3653 binmode $fh or croak
"binmode: $!";
3654 my $size = (stat($fh))[7];
3655 ($size % 24) == 0 or croak
"inconsistent size: $size";
3659 sysseek($fh, -24, SEEK_END
) or croak
"seek: $!";
3660 my $read = sysread($fh, my $buf, 24) or croak
"read: $!";
3661 $read == 24 or croak
"read only $read bytes (!= 24)";
3662 my ($last_rev, $last_commit) = unpack(rev_map_fmt
, $buf);
3663 if ($last_commit eq ('0' x40
)) {
3665 sysseek($fh, -48, SEEK_END
) or croak
"seek: $!";
3666 $read = sysread($fh, $buf, 24) or
3669 croak
"read only $read bytes (!= 24)";
3670 ($last_rev, $last_commit) =
3671 unpack(rev_map_fmt
, $buf);
3672 if ($last_commit eq ('0' x40
)) {
3673 croak
"inconsistent .rev_map\n";
3676 if ($last_rev >= $rev) {
3677 croak
"last_rev is higher!: $last_rev >= $rev";
3682 sysseek($fh, $wr_offset, SEEK_END
) or croak
"seek: $!";
3683 syswrite($fh, pack(rev_map_fmt
, $rev, $commit), 24) == 24 or
3687 sub _rev_map_reset
{
3688 my ($fh, $rev, $commit) = @_;
3689 my $c = _rev_map_get
($fh, $rev);
3690 $c eq $commit or die "_rev_map_reset(@_) commit $c does not match!\n";
3691 my $offset = sysseek($fh, 0, SEEK_CUR
) or croak
"seek: $!";
3692 truncate $fh, $offset or croak
"truncate: $!";
3698 my ($dir, $base) = ($path =~ m
#^(.*?)/?([^/]+)$#);
3699 mkpath
([$dir]) unless -d
$dir;
3700 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
3701 close $fh or die "Couldn't close (create) $path: $!\n";
3706 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
3707 defined $commit or die "missing arg3\n";
3708 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
3709 my $db = $self->map_path($uuid);
3710 my $db_lock = "$db.lock";
3714 $SIG{INT
} = $SIG{HUP
} = $SIG{TERM
} = $SIG{ALRM
} = $SIG{PIPE
} =
3715 $SIG{USR1
} = $SIG{USR2
} = sub { $sig = $_[0] };
3719 $LOCKFILES{$db_lock} = 1;
3721 # both of these options make our .rev_db file very, very important
3722 # and we can't afford to lose it because rebuild() won't work
3723 if ($self->use_svm_props || $self->no_metadata) {
3725 copy
($db, $db_lock) or die "rev_map_set(@_): ",
3727 "$db => $db_lock ($!)\n";
3729 rename $db, $db_lock or die "rev_map_set(@_): ",
3730 "Failed to rename: ",
3731 "$db => $db_lock ($!)\n";
3734 sysopen(my $fh, $db_lock, O_RDWR
| O_CREAT
)
3735 or croak
"Couldn't open $db_lock: $!\n";
3736 $update_ref eq 'reset' ? _rev_map_reset
($fh, $rev, $commit) :
3737 _rev_map_set
($fh, $rev, $commit);
3739 $fh->flush or die "Couldn't flush $db_lock: $!\n";
3740 $fh->sync or die "Couldn't sync $db_lock: $!\n";
3742 close $fh or croak
$!;
3746 $note = " ($update_ref)" if ($update_ref !~ /^\d*$/);
3747 command_noisy
('update-ref', '-m', "r$rev$note",
3748 $self->refname, $commit);
3750 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
3751 "$db_lock => $db ($!)\n";
3752 delete $LOCKFILES{$db_lock};
3754 $SIG{INT
} = $SIG{HUP
} = $SIG{TERM
} = $SIG{ALRM
} = $SIG{PIPE
} =
3755 $SIG{USR1
} = $SIG{USR2
} = 'DEFAULT';
3756 kill $sig, $$ if defined $sig;
3760 # If want_commit, this will return an array of (rev, commit) where
3761 # commit _must_ be a valid commit in the archive.
3762 # Otherwise, it'll return the max revision (whether or not the
3763 # commit is valid or just a 0x40 placeholder).
3765 my ($self, $want_commit) = @_;
3767 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
3768 $want_commit ?
($r, $c) : $r;
3771 sub rev_map_max_norebuild
{
3772 my ($self, $want_commit) = @_;
3773 my $map_path = $self->map_path;
3774 stat $map_path or return $want_commit ?
(0, undef) : 0;
3775 sysopen(my $fh, $map_path, O_RDONLY
) or croak
"open: $!";
3776 binmode $fh or croak
"binmode: $!";
3777 my $size = (stat($fh))[7];
3778 ($size % 24) == 0 or croak
"inconsistent size: $size";
3781 close $fh or croak
"close: $!";
3782 return $want_commit ?
(0, undef) : 0;
3785 sysseek($fh, -24, SEEK_END
) or croak
"seek: $!";
3786 sysread($fh, my $buf, 24) == 24 or croak
"read: $!";
3787 my ($r, $c) = unpack(rev_map_fmt
, $buf);
3788 if ($want_commit && $c eq ('0' x40
)) {
3790 return $want_commit ?
(0, undef) : 0;
3792 sysseek($fh, -48, SEEK_END
) or croak
"seek: $!";
3793 sysread($fh, $buf, 24) == 24 or croak
"read: $!";
3794 ($r, $c) = unpack(rev_map_fmt
, $buf);
3795 if ($c eq ('0'x40
)) {
3796 croak
"Penultimate record is all-zeroes in $map_path";
3799 close $fh or croak
"close: $!";
3800 $want_commit ?
($r, $c) : $r;
3804 my ($self, $rev, $uuid) = @_;
3805 my $map_path = $self->map_path($uuid);
3806 return undef unless -e
$map_path;
3808 sysopen(my $fh, $map_path, O_RDONLY
) or croak
"open: $!";
3809 my $c = _rev_map_get
($fh, $rev);
3810 close($fh) or croak
"close: $!";
3815 my ($fh, $rev) = @_;
3817 binmode $fh or croak
"binmode: $!";
3818 my $size = (stat($fh))[7];
3819 ($size % 24) == 0 or croak
"inconsistent size: $size";
3825 my ($l, $u) = (0, $size - 24);
3829 my $i = int(($l/24 + $u/24) / 2) * 24;
3830 sysseek($fh, $i, SEEK_SET
) or croak
"seek: $!";
3831 sysread($fh, my $buf, 24) == 24 or croak
"read: $!";
3832 my ($r, $c) = unpack(rev_map_fmt
, $buf);
3836 } elsif ($r > $rev) {
3838 } else { # $r == $rev
3839 return $c eq ('0' x
40) ?
undef : $c;
3845 # Finds the first svn revision that exists on (if $eq_ok is true) or
3846 # before $rev for the current branch. It will not search any lower
3847 # than $min_rev. Returns the git commit hash and svn revision number
3848 # if found, else (undef, undef).
3849 sub find_rev_before
{
3850 my ($self, $rev, $eq_ok, $min_rev) = @_;
3851 --$rev unless $eq_ok;
3853 my $max_rev = $self->rev_map_max;
3854 $rev = $max_rev if ($rev > $max_rev);
3855 while ($rev >= $min_rev) {
3856 if (my $c = $self->rev_map_get($rev)) {
3861 return (undef, undef);
3864 # Finds the first svn revision that exists on (if $eq_ok is true) or
3865 # after $rev for the current branch. It will not search any higher
3866 # than $max_rev. Returns the git commit hash and svn revision number
3867 # if found, else (undef, undef).
3868 sub find_rev_after
{
3869 my ($self, $rev, $eq_ok, $max_rev) = @_;
3870 ++$rev unless $eq_ok;
3871 $max_rev ||= $self->rev_map_max;
3872 while ($rev <= $max_rev) {
3873 if (my $c = $self->rev_map_get($rev)) {
3878 return (undef, undef);
3882 my ($class, $repo_id, $ref_id, $path) = @_;
3883 unless (defined $repo_id && length $repo_id) {
3884 $repo_id = $Git::SVN
::default_repo_id
;
3886 unless (defined $ref_id && length $ref_id) {
3887 $_prefix = '' unless defined($_prefix);
3889 "refs/remotes/$_prefix$Git::SVN::default_ref_id";
3892 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
3894 # Older repos imported by us used $GIT_DIR/svn/foo instead of
3895 # $GIT_DIR/svn/refs/remotes/foo when tracking refs/remotes/foo
3896 if ($ref_id =~ m{^refs/remotes/(.*)}) {
3897 my $old_dir = "$ENV{GIT_DIR}/svn/$1";
3898 if (-d
$old_dir && ! -d
$dir) {
3903 $_[3] = $path = '' unless (defined $path);
3906 ref_id
=> $ref_id, dir
=> $dir, index => "$dir/index",
3907 path
=> $path, config
=> "$ENV{GIT_DIR}/svn/config",
3908 map_root
=> "$dir/.rev_map", repo_id
=> $repo_id }, $class;
3911 # for read-only access of old .rev_db formats
3912 sub unlink_rev_db_symlink
{
3914 my $link = $self->rev_db_path;
3915 $link =~ s/\.[\w-]+$// or croak
"missing UUID at the end of $link";
3917 unlink $link or croak
"unlink: $link failed!";
3922 my ($self, $uuid) = @_;
3923 my $db_path = $self->map_path($uuid);
3924 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
3925 or croak
"map_path: $db_path does not contain '/.rev_map.' !";
3929 # the new replacement for .rev_db
3931 my ($self, $uuid) = @_;
3932 $uuid ||= $self->ra_uuid;
3933 "$self->{map_root}.$uuid";
3938 $f =~ s
#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
3944 $f =~ s
#%([0-9a-fA-F]{2})#chr(hex($1))#eg;
3948 sub remove_username
{
3949 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
3952 package Git
::SVN
::Prompt
;
3956 use vars qw
/$_no_auth_cache $_username/;
3959 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
3960 $may_save = undef if $_no_auth_cache;
3961 $default_username = $_username if defined $_username;
3962 if (defined $default_username && length $default_username) {
3963 if (defined $realm && length $realm) {
3964 print STDERR
"Authentication realm: $realm\n";
3967 $cred->username($default_username);
3969 username
($cred, $realm, $may_save, $pool);
3971 $cred->password(_read_password
("Password for '" .
3972 $cred->username . "': ", $realm));
3973 $cred->may_save($may_save);
3974 $SVN::_Core
::SVN_NO_ERROR
;
3977 sub ssl_server_trust
{
3978 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
3979 $may_save = undef if $_no_auth_cache;
3980 print STDERR
"Error validating server certificate for '$realm':\n";
3983 # All variables SVN::Auth::SSL::* are used only once,
3984 # so we're shutting up Perl warnings about this.
3985 if ($failures & $SVN::Auth
::SSL
::UNKNOWNCA
) {
3986 print STDERR
" - The certificate is not issued ",
3987 "by a trusted authority. Use the\n",
3988 " fingerprint to validate ",
3989 "the certificate manually!\n";
3991 if ($failures & $SVN::Auth
::SSL
::CNMISMATCH
) {
3992 print STDERR
" - The certificate hostname ",
3993 "does not match.\n";
3995 if ($failures & $SVN::Auth
::SSL
::NOTYETVALID
) {
3996 print STDERR
" - The certificate is not yet valid.\n";
3998 if ($failures & $SVN::Auth
::SSL
::EXPIRED
) {
3999 print STDERR
" - The certificate has expired.\n";
4001 if ($failures & $SVN::Auth
::SSL
::OTHER
) {
4002 print STDERR
" - The certificate has ",
4003 "an unknown error.\n";
4005 } # no warnings 'once'
4007 "Certificate information:\n".
4008 " - Hostname: %s\n".
4009 " - Valid: from %s until %s\n".
4011 " - Fingerprint: %s\n",
4012 map $cert_info->$_, qw(hostname valid_from valid_until
4013 issuer_dname fingerprint);
4016 print STDERR
$may_save ?
4017 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
4018 "(R)eject or accept (t)emporarily? ";
4020 $choice = lc(substr(<STDIN
> || 'R', 0, 1));
4021 if ($choice =~ /^t$/i) {
4022 $cred->may_save(undef);
4023 } elsif ($choice =~ /^r$/i) {
4025 } elsif ($may_save && $choice =~ /^p$/i) {
4026 $cred->may_save($may_save);
4030 $cred->accepted_failures($failures);
4031 $SVN::_Core
::SVN_NO_ERROR
;
4034 sub ssl_client_cert
{
4035 my ($cred, $realm, $may_save, $pool) = @_;
4036 $may_save = undef if $_no_auth_cache;
4037 print STDERR
"Client certificate filename: ";
4039 chomp(my $filename = <STDIN
>);
4040 $cred->cert_file($filename);
4041 $cred->may_save($may_save);
4042 $SVN::_Core
::SVN_NO_ERROR
;
4045 sub ssl_client_cert_pw
{
4046 my ($cred, $realm, $may_save, $pool) = @_;
4047 $may_save = undef if $_no_auth_cache;
4048 $cred->password(_read_password
("Password: ", $realm));
4049 $cred->may_save($may_save);
4050 $SVN::_Core
::SVN_NO_ERROR
;
4054 my ($cred, $realm, $may_save, $pool) = @_;
4055 $may_save = undef if $_no_auth_cache;
4056 if (defined $realm && length $realm) {
4057 print STDERR
"Authentication realm: $realm\n";
4060 if (defined $_username) {
4061 $username = $_username;
4063 print STDERR
"Username: ";
4065 chomp($username = <STDIN
>);
4067 $cred->username($username);
4068 $cred->may_save($may_save);
4069 $SVN::_Core
::SVN_NO_ERROR
;
4072 sub _read_password
{
4073 my ($prompt, $realm) = @_;
4075 if (exists $ENV{GIT_ASKPASS
}) {
4076 open(PH
, "-|", $ENV{GIT_ASKPASS
}, $prompt);
4078 $password =~ s/[\012\015]//; # \n\r
4081 print STDERR
$prompt;
4083 require Term
::ReadKey
;
4084 Term
::ReadKey
::ReadMode
('noecho');
4085 while (defined(my $key = Term
::ReadKey
::ReadKey
(0))) {
4086 last if $key =~ /[\012\015]/; # \n\r
4089 Term
::ReadKey
::ReadMode
('restore');
4096 package SVN
::Git
::Fetcher
;
4097 use vars qw
/@ISA $_ignore_regex $_preserve_empty_dirs $_placeholder_filename
4098 @deleted_gpath %added_placeholder $repo_id/;
4102 use File
::Basename qw
/dirname/;
4105 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
4107 my ($class, $git_svn, $switch_path) = @_;
4108 my $self = SVN
::Delta
::Editor
->new;
4109 bless $self, $class;
4110 if (exists $git_svn->{last_commit
}) {
4111 $self->{c
} = $git_svn->{last_commit
};
4112 $self->{empty_symlinks
} =
4113 _mark_empty_symlinks
($git_svn, $switch_path);
4116 # some options are read globally, but can be overridden locally
4117 # per [svn-remote "..."] section. Command-line options will *NOT*
4118 # override options set in an [svn-remote "..."] section
4119 $repo_id = $git_svn->{repo_id
};
4120 my $k = "svn-remote.$repo_id.ignore-paths";
4121 my $v = eval { command_oneline
('config', '--get', $k) };
4122 $self->{ignore_regex
} = $v;
4124 $k = "svn-remote.$repo_id.preserve-empty-dirs";
4125 $v = eval { command_oneline
('config', '--get', '--bool', $k) };
4126 if ($v && $v eq 'true') {
4127 $_preserve_empty_dirs = 1;
4128 $k = "svn-remote.$repo_id.placeholder-filename";
4129 $v = eval { command_oneline
('config', '--get', $k) };
4130 $_placeholder_filename = $v;
4133 # Load the list of placeholder files added during previous invocations.
4134 $k = "svn-remote.$repo_id.added-placeholder";
4135 $v = eval { command_oneline
('config', '--get-all', $k) };
4136 if ($_preserve_empty_dirs && $v) {
4137 # command() prints errors to stderr, so we only call it if
4138 # command_oneline() succeeded.
4139 my @v = command
('config', '--get-all', $k);
4140 $added_placeholder{ dirname
($_) } = $_ foreach @v;
4143 $self->{empty
} = {};
4144 $self->{dir_prop
} = {};
4145 $self->{file_prop
} = {};
4146 $self->{absent_dir
} = {};
4147 $self->{absent_file
} = {};
4148 $self->{gii
} = $git_svn->tmp_index_do(sub { Git
::IndexInfo
->new });
4149 $self->{pathnameencoding
} = Git
::config
('svn.pathnameencoding');
4153 # this uses the Ra object, so it must be called before do_{switch,update},
4154 # not inside them (when the Git::SVN::Fetcher object is passed) to
4155 # do_{switch,update}
4156 sub _mark_empty_symlinks
{
4157 my ($git_svn, $switch_path) = @_;
4158 my $bool = Git
::config_bool
('svn.brokenSymlinkWorkaround');
4159 return {} if (!defined($bool)) || (defined($bool) && ! $bool);
4162 my ($rev, $cmt) = $git_svn->last_rev_commit;
4163 return {} unless ($rev && $cmt);
4165 # allow the warning to be printed for each revision we fetch to
4166 # ensure the user sees it. The user can also disable the workaround
4167 # on the repository even while git svn is running and the next
4168 # revision fetched will skip this expensive function.
4169 my $printed_warning;
4170 chomp(my $empty_blob = `git hash-object -t blob --stdin < /dev/null`);
4171 my ($ls, $ctx) = command_output_pipe
(qw
/ls-tree -r -z/, $cmt);
4173 my $pfx = defined($switch_path) ?
$switch_path : $git_svn->{path
};
4174 $pfx .= '/' if length($pfx);
4177 s/\A100644 blob $empty_blob\t//o or next;
4178 unless ($printed_warning) {
4179 print STDERR
"Scanning for empty symlinks, ",
4180 "this may take a while if you have ",
4181 "many empty files\n",
4182 "You may disable this with `",
4183 "git config svn.brokenSymlinkWorkaround ",
4185 "This may be done in a different ",
4186 "terminal without restarting ",
4188 $printed_warning = 1;
4191 my (undef, $props) =
4192 $git_svn->ra->get_file($pfx.$path, $rev, undef);
4193 if ($props->{'svn:special'}) {
4197 command_close_pipe
($ls, $ctx);
4201 # returns true if a given path is inside a ".git" directory
4203 $_[0] =~ m{(?:^|/)\.git(?:/|$)};
4206 # return value: 0 -- don't ignore, 1 -- ignore
4207 sub is_path_ignored
{
4208 my ($self, $path) = @_;
4209 return 1 if in_dot_git
($path);
4210 return 1 if defined($self->{ignore_regex
}) &&
4211 $path =~ m!$self->{ignore_regex}!;
4212 return 0 unless defined($_ignore_regex);
4213 return 1 if $path =~ m!$_ignore_regex!o;
4217 sub set_path_strip
{
4218 my ($self, $path) = @_;
4219 $self->{path_strip
} = qr/^\Q$path\E(\/|$)/ if length $path;
4226 sub open_directory
{
4227 my ($self, $path, $pb, $rev) = @_;
4232 my ($self, $path) = @_;
4233 if (my $enc = $self->{pathnameencoding
}) {
4235 Encode
::from_to
($path, 'UTF-8', $enc);
4237 if ($self->{path_strip
}) {
4238 $path =~ s!$self->{path_strip}!! or
4239 die "Failed to strip path '$path' ($self->{path_strip})\n";
4245 my ($self, $path, $rev, $pb) = @_;
4246 return undef if $self->is_path_ignored($path);
4248 my $gpath = $self->git_path($path);
4249 return undef if ($gpath eq '');
4251 # remove entire directories.
4252 my ($tree) = (command
('ls-tree', '-z', $self->{c
}, "./$gpath")
4253 =~ /\A040000 tree ([a-f\d]{40})\t\Q$gpath\E\0/);
4255 my ($ls, $ctx) = command_output_pipe
(qw
/ls
-tree
4261 my $rmpath = "$gpath/$_";
4262 $self->{gii
}->remove($rmpath);
4263 print "\tD\t$rmpath\n" unless $::_q
;
4265 print "\tD\t$gpath/\n" unless $::_q
;
4266 command_close_pipe
($ls, $ctx);
4268 $self->{gii
}->remove($gpath);
4269 print "\tD\t$gpath\n" unless $::_q
;
4271 # Don't add to @deleted_gpath if we're deleting a placeholder file.
4272 push @deleted_gpath, $gpath unless $added_placeholder{dirname
($path)};
4273 $self->{empty
}->{$path} = 0;
4278 my ($self, $path, $pb, $rev) = @_;
4281 goto out
if $self->is_path_ignored($path);
4283 my $gpath = $self->git_path($path);
4284 ($mode, $blob) = (command
('ls-tree', '-z', $self->{c
}, "./$gpath")
4285 =~ /\A(\d{6}) blob ([a-f\d]{40})\t\Q$gpath\E\0/);
4286 unless (defined $mode && defined $blob) {
4287 die "$path was not found in commit $self->{c} (r$rev)\n";
4289 if ($mode eq '100644' && $self->{empty_symlinks
}->{$path}) {
4293 { path
=> $path, mode_a
=> $mode, mode_b
=> $mode, blob
=> $blob,
4294 pool
=> SVN
::Pool
->new, action
=> 'M' };
4298 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
4301 if (!$self->is_path_ignored($path)) {
4302 my ($dir, $file) = ($path =~ m
#^(.*?)/?([^/]+)$#);
4303 delete $self->{empty
}->{$dir};
4306 if ($added_placeholder{$dir}) {
4307 # Remove our placeholder file, if we created one.
4308 delete_entry
($self, $added_placeholder{$dir})
4309 unless $path eq $added_placeholder{$dir};
4310 delete $added_placeholder{$dir}
4314 { path
=> $path, mode_a
=> $mode, mode_b
=> $mode,
4315 pool
=> SVN
::Pool
->new, action
=> 'A' };
4319 my ($self, $path, $cp_path, $cp_rev) = @_;
4320 goto out
if $self->is_path_ignored($path);
4321 my $gpath = $self->git_path($path);
4323 my ($ls, $ctx) = command_output_pipe
(qw
/ls
-tree
4329 $self->{gii
}->remove($_);
4330 print "\tD\t$_\n" unless $::_q
;
4331 push @deleted_gpath, $gpath;
4333 command_close_pipe
($ls, $ctx);
4334 $self->{empty
}->{$path} = 0;
4336 my ($dir, $file) = ($path =~ m
#^(.*?)/?([^/]+)$#);
4337 delete $self->{empty
}->{$dir};
4338 $self->{empty
}->{$path} = 1;
4340 if ($added_placeholder{$dir}) {
4341 # Remove our placeholder file, if we created one.
4342 delete_entry
($self, $added_placeholder{$dir});
4343 delete $added_placeholder{$dir}
4350 sub change_dir_prop
{
4351 my ($self, $db, $prop, $value) = @_;
4352 return undef if $self->is_path_ignored($db->{path
});
4353 $self->{dir_prop
}->{$db->{path
}} ||= {};
4354 $self->{dir_prop
}->{$db->{path
}}->{$prop} = $value;
4358 sub absent_directory
{
4359 my ($self, $path, $pb) = @_;
4360 return undef if $self->is_path_ignored($path);
4361 $self->{absent_dir
}->{$pb->{path
}} ||= [];
4362 push @
{$self->{absent_dir
}->{$pb->{path
}}}, $path;
4367 my ($self, $path, $pb) = @_;
4368 return undef if $self->is_path_ignored($path);
4369 $self->{absent_file
}->{$pb->{path
}} ||= [];
4370 push @
{$self->{absent_file
}->{$pb->{path
}}}, $path;
4374 sub change_file_prop
{
4375 my ($self, $fb, $prop, $value) = @_;
4376 return undef if $self->is_path_ignored($fb->{path
});
4377 if ($prop eq 'svn:executable') {
4378 if ($fb->{mode_b
} != 120000) {
4379 $fb->{mode_b
} = defined $value ?
100755 : 100644;
4381 } elsif ($prop eq 'svn:special') {
4382 $fb->{mode_b
} = defined $value ?
120000 : 100644;
4384 $self->{file_prop
}->{$fb->{path
}} ||= {};
4385 $self->{file_prop
}->{$fb->{path
}}->{$prop} = $value;
4390 sub apply_textdelta
{
4391 my ($self, $fb, $exp) = @_;
4392 return undef if $self->is_path_ignored($fb->{path
});
4393 my $fh = $::_repository
->temp_acquire('svn_delta');
4394 # $fh gets auto-closed() by SVN::TxDelta::apply(),
4395 # (but $base does not,) so dup() it for reading in close_file
4396 open my $dup, '<&', $fh or croak
$!;
4397 my $base = $::_repository
->temp_acquire('git_blob');
4400 my ($base_is_link, $size);
4402 if ($fb->{mode_a
} eq '120000' &&
4403 ! $self->{empty_symlinks
}->{$fb->{path
}}) {
4404 print $base 'link ' or die "print $!\n";
4408 $size = $::_repository
->cat_blob($fb->{blob
}, $base);
4409 die "Failed to read object $fb->{blob}" if ($size < 0);
4412 seek $base, 0, 0 or croak
$!;
4413 my $got = ::md5sum
($base);
4415 my $err = "Checksum mismatch: ".
4416 "$fb->{path} $fb->{blob}\n" .
4417 "expected: $exp\n" .
4419 if ($base_is_link) {
4421 "Retrying... (possibly ",
4422 "a bad symlink from SVN)\n";
4423 $::_repository
->temp_reset($base);
4431 seek $base, 0, 0 or croak
$!;
4433 $fb->{base
} = $base;
4434 [ SVN
::TxDelta
::apply
($base, $dup, undef, $fb->{path
}, $fb->{pool
}) ];
4438 my ($self, $fb, $exp) = @_;
4439 return undef if $self->is_path_ignored($fb->{path
});
4442 my $path = $self->git_path($fb->{path
});
4443 if (my $fh = $fb->{fh
}) {
4445 seek($fh, 0, 0) or croak
$!;
4446 my $got = ::md5sum
($fh);
4448 die "Checksum mismatch: $path\n",
4449 "expected: $exp\n got: $got\n";
4452 if ($fb->{mode_b
} == 120000) {
4453 sysseek($fh, 0, 0) or croak
$!;
4454 my $rd = sysread($fh, my $buf, 5);
4457 croak
"sysread: $!\n";
4458 } elsif ($rd == 0) {
4459 warn "$path has mode 120000",
4460 " but it points to nothing\n",
4461 "converting to an empty file with mode",
4463 $fb->{mode_b
} = '100644';
4464 } elsif ($buf ne 'link ') {
4465 warn "$path has mode 120000",
4466 " but is not a link\n";
4468 my $tmp_fh = $::_repository
->temp_acquire(
4471 while ($res = sysread($fh, my $str, 1024)) {
4472 my $out = syswrite($tmp_fh, $str, $res);
4473 defined($out) && $out == $res
4475 Git
::temp_path
($tmp_fh),
4478 defined $res or croak
$!;
4480 ($fh, $tmp_fh) = ($tmp_fh, $fh);
4481 Git
::temp_release
($tmp_fh, 1);
4485 $hash = $::_repository
->hash_and_insert_object(
4486 Git
::temp_path
($fh));
4487 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
4489 Git
::temp_release
($fb->{base
}, 1);
4490 Git
::temp_release
($fh, 1);
4492 $hash = $fb->{blob
} or die "no blob information\n";
4495 $self->{gii
}->update($fb->{mode_b
}, $hash, $path) or croak
$!;
4496 print "\t$fb->{action}\t$path\n" if $fb->{action
} && ! $::_q
;
4502 $self->{nr
} = $self->{gii
}->{nr
};
4503 delete $self->{gii
};
4504 $self->SUPER::abort_edit
(@_);
4510 if ($_preserve_empty_dirs) {
4513 # Any entry flagged as empty that also has an associated
4514 # dir_prop represents a newly created empty directory.
4515 foreach my $i (keys %{$self->{empty
}}) {
4516 push @empty_dirs, $i if exists $self->{dir_prop
}->{$i};
4519 # Search for directories that have become empty due subsequent
4521 push @empty_dirs, $self->find_empty_directories();
4523 # Finally, add a placeholder file to each empty directory.
4524 $self->add_placeholder_file($_) foreach (@empty_dirs);
4526 $self->stash_placeholder_list();
4529 $self->{git_commit_ok
} = 1;
4530 $self->{nr
} = $self->{gii
}->{nr
};
4531 delete $self->{gii
};
4532 $self->SUPER::close_edit
(@_);
4535 sub find_empty_directories
{
4538 my %dirs = map { dirname
($_) => 1 } @deleted_gpath;
4540 foreach my $dir (sort keys %dirs) {
4541 next if $dir eq ".";
4543 # If there have been any additions to this directory, there is
4544 # no reason to check if it is empty.
4546 foreach my $t (qw
/dir_prop file_prop/) {
4547 foreach my $path (keys %{ $self->{$t} }) {
4548 if (exists $self->{$t}->{dirname
($path)}) {
4553 last if $skip_added;
4555 next if $skip_added;
4557 # Use `git ls-tree` to get the filenames of this directory
4558 # that existed prior to this particular commit.
4559 my $ls = command
('ls-tree', '-z', '--name-only',
4560 $self->{c
}, "$dir/");
4561 my %files = map { $_ => 1 } split(/\0/, $ls);
4563 # Remove the filenames that were deleted during this commit.
4564 delete $files{$_} foreach (@deleted_gpath);
4566 # Report the directory if there are no filenames left.
4567 push @empty_dirs, $dir unless (scalar %files);
4572 sub add_placeholder_file
{
4573 my ($self, $dir) = @_;
4574 my $path = "$dir/$_placeholder_filename";
4575 my $gpath = $self->git_path($path);
4577 my $fh = $::_repository
->temp_acquire($gpath);
4578 my $hash = $::_repository
->hash_and_insert_object(Git
::temp_path
($fh));
4579 Git
::temp_release
($fh, 1);
4580 $self->{gii
}->update('100644', $hash, $gpath) or croak
$!;
4582 # The directory should no longer be considered empty.
4583 delete $self->{empty
}->{$dir} if exists $self->{empty
}->{$dir};
4585 # Keep track of any placeholder files we create.
4586 $added_placeholder{$dir} = $path;
4589 sub stash_placeholder_list
{
4591 my $k = "svn-remote.$repo_id.added-placeholder";
4592 my $v = eval { command_oneline
('config', '--get-all', $k) };
4593 command_noisy
('config', '--unset-all', $k) if $v;
4594 foreach (values %added_placeholder) {
4595 command_noisy
('config', '--add', $k, $_);
4599 package SVN
::Git
::Editor
;
4600 use vars qw
/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
4607 my ($class, $opts) = @_;
4608 foreach (qw
/svn_path r ra tree_a tree_b log editor_cb/) {
4609 die "$_ required!\n" unless (defined $opts->{$_});
4612 my $pool = SVN
::Pool
->new;
4613 my $mods = generate_diff
($opts->{tree_a
}, $opts->{tree_b
});
4614 my $types = check_diff_paths
($opts->{ra
}, $opts->{svn_path
},
4617 # $opts->{ra} functions should not be used after this:
4618 my @ce = $opts->{ra
}->get_commit_editor($opts->{log},
4619 $opts->{editor_cb
}, $pool);
4620 my $self = SVN
::Delta
::Editor
->new(@ce, $pool);
4621 bless $self, $class;
4622 foreach (qw
/svn_path r tree_a tree_b/) {
4623 $self->{$_} = $opts->{$_};
4625 $self->{url
} = $opts->{ra
}->{url
};
4626 $self->{mods
} = $mods;
4627 $self->{types
} = $types;
4628 $self->{pool
} = $pool;
4629 $self->{bat
} = { '' => $self->open_root($self->{r
}, $self->{pool
}) };
4631 $self->{path_prefix
} = length $self->{svn_path
} ?
4632 "$self->{svn_path}/" : '';
4633 $self->{config
} = $opts->{config
};
4634 $self->{mergeinfo
} = $opts->{mergeinfo
};
4639 my ($tree_a, $tree_b) = @_;
4640 my @diff_tree = qw(diff-tree -z -r);
4641 if ($_cp_similarity) {
4642 push @diff_tree, "-C$_cp_similarity";
4644 push @diff_tree, '-C';
4646 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
4647 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
4648 push @diff_tree, $tree_a, $tree_b;
4649 my ($diff_fh, $ctx) = command_output_pipe
(@diff_tree);
4653 while (<$diff_fh>) {
4654 chomp $_; # this gets rid of the trailing "\0"
4655 if ($state eq 'meta' && /^:(\d
{6})\s
(\d
{6})\s
4656 ($::sha1
)\s
($::sha1
)\s
4657 ([MTCRAD
])\d
*$/xo
) {
4658 push @mods, { mode_a
=> $1, mode_b
=> $2,
4659 sha1_a
=> $3, sha1_b
=> $4,
4661 if ($5 =~ /^(?:C|R)$/) {
4666 } elsif ($state eq 'file_a') {
4667 my $x = $mods[$#mods] or croak
"Empty array\n";
4668 if ($x->{chg
} !~ /^(?:C|R)$/) {
4669 croak
"Error parsing $_, $x->{chg}\n";
4673 } elsif ($state eq 'file_b') {
4674 my $x = $mods[$#mods] or croak
"Empty array\n";
4675 if (exists $x->{file_a
} && $x->{chg
} !~ /^(?:C|R)$/) {
4676 croak
"Error parsing $_, $x->{chg}\n";
4678 if (!exists $x->{file_a
} && $x->{chg
} =~ /^(?:C|R)$/) {
4679 croak
"Error parsing $_, $x->{chg}\n";
4684 croak
"Error parsing $_\n";
4687 command_close_pipe
($diff_fh, $ctx);
4691 sub check_diff_paths
{
4692 my ($ra, $pfx, $rev, $mods) = @_;
4694 $pfx .= '/' if length $pfx;
4696 sub type_diff_paths
{
4697 my ($ra, $types, $path, $rev) = @_;
4698 my @p = split m
#/+#, $path;
4700 unless (defined $types->{$c}) {
4701 $types->{$c} = $ra->check_path($c, $rev);
4704 $c .= '/' . shift @p;
4705 next if defined $types->{$c};
4706 $types->{$c} = $ra->check_path($c, $rev);
4710 foreach my $m (@
$mods) {
4711 foreach my $f (qw
/file_a file_b/) {
4712 next unless defined $m->{$f};
4713 my ($dir) = ($m->{$f} =~ m
#^(.*?)/?(?:[^/]+)$#);
4714 if (length $pfx.$dir && ! defined $types{$dir}) {
4715 type_diff_paths
($ra, \
%types, $pfx.$dir, $rev);
4723 return ($_[0] =~ m
#^(.*?)/?([^/]+)$#);
4727 my ($self, $path) = @_;
4728 if (my $enc = $self->{pathnameencoding
}) {
4730 Encode
::from_to
($path, $enc, 'UTF-8');
4732 $self->{path_prefix
}.(defined $path ?
$path : '');
4736 my ($self, $path) = @_;
4737 if ($self->{url
} =~ m
#^https?://#) {
4738 $path =~ s!([^~a-zA-Z0-9_./-])!uc sprintf("%%%02x",ord($1))!eg;
4740 $self->{url
} . '/' . $self->repo_path($path);
4745 my $rm = $self->{rm
};
4746 delete $rm->{''}; # we never delete the url we're tracking
4749 foreach (keys %$rm) {
4750 my @d = split m
#/#, $_;
4754 $c .= '/' . shift @d;
4758 delete $rm->{$self->{svn_path
}};
4759 delete $rm->{''}; # we never delete the url we're tracking
4762 my ($fh, $ctx) = command_output_pipe
(qw
/ls-tree --name-only -r -z/,
4767 my @dn = split m
#/#, $_;
4769 delete $rm->{join '/', @dn};
4776 command_close_pipe
($fh, $ctx);
4778 my ($r, $p, $bat) = ($self->{r
}, $self->{pool
}, $self->{bat
});
4779 foreach my $d (sort { $b =~ tr
#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
4780 $self->close_directory($bat->{$d}, $p);
4781 my ($dn) = ($d =~ m
#^(.*?)/?(?:[^/]+)$#);
4782 print "\tD+\t$d/\n" unless $::_q
;
4783 $self->SUPER::delete_entry
($d, $r, $bat->{$dn}, $p);
4788 sub open_or_add_dir
{
4789 my ($self, $full_path, $baton) = @_;
4790 my $t = $self->{types
}->{$full_path};
4792 die "$full_path not known in r$self->{r} or we have a bug!\n";
4796 # SVN::Node::none and SVN::Node::file are used only once,
4797 # so we're shutting up Perl's warnings about them.
4798 if ($t == $SVN::Node
::none
) {
4799 return $self->add_directory($full_path, $baton,
4800 undef, -1, $self->{pool
});
4801 } elsif ($t == $SVN::Node
::dir
) {
4802 return $self->open_directory($full_path, $baton,
4803 $self->{r
}, $self->{pool
});
4804 } # no warnings 'once'
4805 print STDERR
"$full_path already exists in repository at ",
4806 "r$self->{r} and it is not a directory (",
4807 ($t == $SVN::Node
::file ?
'file' : 'unknown'),"/$t)\n";
4808 } # no warnings 'once'
4813 my ($self, $path) = @_;
4814 my $bat = $self->{bat
};
4815 my $repo_path = $self->repo_path($path);
4816 return $bat->{''} unless (length $repo_path);
4817 my @p = split m
#/+#, $repo_path;
4819 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
4822 $c .= '/' . shift @p;
4823 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
4828 # Subroutine to convert a globbing pattern to a regular expression.
4829 # From perl cookbook.
4831 my $globstr = shift;
4832 my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
4833 $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
4834 return '^' . $globstr . '$';
4837 sub check_autoprop
{
4838 my ($self, $pattern, $properties, $file, $fbat) = @_;
4839 # Convert the globbing pattern to a regular expression.
4840 my $regex = glob2pat
($pattern);
4841 # Check if the pattern matches the file name.
4842 if($file =~ m/($regex)/) {
4843 # Parse the list of properties to set.
4844 my @props = split(/;/, $properties);
4845 foreach my $prop (@props) {
4846 # Parse 'name=value' syntax and set the property.
4847 if ($prop =~ /([^=]+)=(.*)/) {
4848 my ($n,$v) = ($1,$2);
4852 $self->change_file_prop($fbat, $n, $v);
4858 sub apply_autoprops
{
4859 my ($self, $file, $fbat) = @_;
4860 my $conf_t = ${$self->{config
}}{'config'};
4862 # Check [miscellany]/enable-auto-props in svn configuration.
4863 if (SVN
::_Core
::svn_config_get_bool
(
4865 $SVN::_Core
::SVN_CONFIG_SECTION_MISCELLANY
,
4866 $SVN::_Core
::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS
,
4868 # Auto-props are enabled. Enumerate them to look for matches.
4869 my $callback = sub {
4870 $self->check_autoprop($_[0], $_[1], $file, $fbat);
4872 SVN
::_Core
::svn_config_enumerate
(
4874 $SVN::_Core
::SVN_CONFIG_SECTION_AUTO_PROPS
,
4880 my ($self, $m) = @_;
4881 my ($dir, $file) = split_path
($m->{file_b
});
4882 my $pbat = $self->ensure_path($dir);
4883 my $fbat = $self->add_file($self->repo_path($m->{file_b
}), $pbat,
4885 print "\tA\t$m->{file_b}\n" unless $::_q
;
4886 $self->apply_autoprops($file, $fbat);
4887 $self->chg_file($fbat, $m);
4888 $self->close_file($fbat,undef,$self->{pool
});
4892 my ($self, $m) = @_;
4893 my ($dir, $file) = split_path
($m->{file_b
});
4894 my $pbat = $self->ensure_path($dir);
4895 my $fbat = $self->add_file($self->repo_path($m->{file_b
}), $pbat,
4896 $self->url_path($m->{file_a
}), $self->{r
});
4897 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q
;
4898 $self->chg_file($fbat, $m);
4899 $self->close_file($fbat,undef,$self->{pool
});
4903 my ($self, $path, $pbat) = @_;
4904 my $rpath = $self->repo_path($path);
4905 my ($dir, $file) = split_path
($rpath);
4906 $self->{rm
}->{$dir} = 1;
4907 $self->SUPER::delete_entry
($rpath, $self->{r
}, $pbat, $self->{pool
});
4911 my ($self, $m) = @_;
4912 my ($dir, $file) = split_path
($m->{file_b
});
4913 my $pbat = $self->ensure_path($dir);
4914 my $fbat = $self->add_file($self->repo_path($m->{file_b
}), $pbat,
4915 $self->url_path($m->{file_a
}), $self->{r
});
4916 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q
;
4917 $self->apply_autoprops($file, $fbat);
4918 $self->chg_file($fbat, $m);
4919 $self->close_file($fbat,undef,$self->{pool
});
4921 ($dir, $file) = split_path
($m->{file_a
});
4922 $pbat = $self->ensure_path($dir);
4923 $self->delete_entry($m->{file_a
}, $pbat);
4927 my ($self, $m) = @_;
4928 my ($dir, $file) = split_path
($m->{file_b
});
4929 my $pbat = $self->ensure_path($dir);
4930 my $fbat = $self->open_file($self->repo_path($m->{file_b
}),
4931 $pbat,$self->{r
},$self->{pool
});
4932 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q
;
4933 $self->chg_file($fbat, $m);
4934 $self->close_file($fbat,undef,$self->{pool
});
4937 sub T
{ shift->M(@_) }
4939 sub change_file_prop
{
4940 my ($self, $fbat, $pname, $pval) = @_;
4941 $self->SUPER::change_file_prop
($fbat, $pname, $pval, $self->{pool
});
4944 sub change_dir_prop
{
4945 my ($self, $pbat, $pname, $pval) = @_;
4946 $self->SUPER::change_dir_prop
($pbat, $pname, $pval, $self->{pool
});
4949 sub _chg_file_get_blob
($$$$) {
4950 my ($self, $fbat, $m, $which) = @_;
4951 my $fh = $::_repository
->temp_acquire("git_blob_$which");
4952 if ($m->{"mode_$which"} =~ /^120/) {
4953 print $fh 'link ' or croak
$!;
4954 $self->change_file_prop($fbat,'svn:special','*');
4955 } elsif ($m->{mode_a
} =~ /^120/ && $m->{"mode_$which"} !~ /^120/) {
4956 $self->change_file_prop($fbat,'svn:special',undef);
4958 my $blob = $m->{"sha1_$which"};
4959 return ($fh,) if ($blob =~ /^0{40}$/);
4960 my $size = $::_repository
->cat_blob($blob, $fh);
4961 croak
"Failed to read object $blob" if ($size < 0);
4962 $fh->flush == 0 or croak
$!;
4963 seek $fh, 0, 0 or croak
$!;
4965 my $exp = ::md5sum
($fh);
4966 seek $fh, 0, 0 or croak
$!;
4971 my ($self, $fbat, $m) = @_;
4972 if ($m->{mode_b
} =~ /755$/ && $m->{mode_a
} !~ /755$/) {
4973 $self->change_file_prop($fbat,'svn:executable','*');
4974 } elsif ($m->{mode_b
} !~ /755$/ && $m->{mode_a
} =~ /755$/) {
4975 $self->change_file_prop($fbat,'svn:executable',undef);
4977 my ($fh_a, $exp_a) = _chg_file_get_blob
$self, $fbat, $m, 'a';
4978 my ($fh_b, $exp_b) = _chg_file_get_blob
$self, $fbat, $m, 'b';
4979 my $pool = SVN
::Pool
->new;
4980 my $atd = $self->apply_textdelta($fbat, $exp_a, $pool);
4982 my $txstream = SVN
::TxDelta
::new
($fh_a, $fh_b, $pool);
4983 my $res = SVN
::TxDelta
::send_txstream
($txstream, @
$atd, $pool);
4985 die "Unexpected result from send_txstream: $res\n",
4986 "(SVN::Core::VERSION: $SVN::Core::VERSION)\n";
4989 my $got = SVN
::TxDelta
::send_stream
($fh_b, @
$atd, $pool);
4990 die "Checksum mismatch\nexpected: $exp_b\ngot: $got\n"
4991 if ($got ne $exp_b);
4993 Git
::temp_release
($fh_b, 1);
4994 Git
::temp_release
($fh_a, 1);
4999 my ($self, $m) = @_;
5000 my ($dir, $file) = split_path
($m->{file_b
});
5001 my $pbat = $self->ensure_path($dir);
5002 print "\tD\t$m->{file_b}\n" unless $::_q
;
5003 $self->delete_entry($m->{file_b
}, $pbat);
5008 my ($p,$bat) = ($self->{pool
}, $self->{bat
});
5009 foreach (sort { $b =~ tr
#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
5011 $self->close_directory($bat->{$_}, $p);
5013 $self->close_directory($bat->{''}, $p);
5014 $self->SUPER::close_edit
($p);
5020 $self->SUPER::abort_edit
($self->{pool
});
5025 $self->SUPER::DESTROY
(@_);
5026 $self->{pool
}->clear;
5029 # this drives the editor
5032 my $mods = $self->{mods
};
5033 my %o = ( D
=> 1, R
=> 0, C
=> -1, A
=> 3, M
=> 3, T
=> 3 );
5034 foreach my $m (sort { $o{$a->{chg
}} <=> $o{$b->{chg
}} } @
$mods) {
5036 if (defined $o{$f}) {
5039 fatal
("Invalid change type: $f");
5043 if (defined($self->{mergeinfo
})) {
5044 $self->change_dir_prop($self->{bat
}{''}, "svn:mergeinfo",
5045 $self->{mergeinfo
});
5047 $self->rmdirs if $_rmdir;
5053 return scalar @
$mods;
5056 package Git
::SVN
::Ra
;
5057 use vars qw
/@ISA $config_dir $_log_window_size/;
5060 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
5063 # enforce temporary pool usage for some simple functions
5065 for my $f (qw
/rev_proplist get_latest_revnum get_uuid get_repos_root
5067 my $SUPER = "SUPER::$f";
5070 my $pool = SVN
::Pool
->new;
5071 my @ret = $self->$SUPER(@_,$pool);
5073 wantarray ?
@ret : $ret[0];
5078 sub _auth_providers
() {
5080 SVN
::Client
::get_simple_provider
(),
5081 SVN
::Client
::get_ssl_server_trust_file_provider
(),
5082 SVN
::Client
::get_simple_prompt_provider
(
5083 \
&Git
::SVN
::Prompt
::simple
, 2),
5084 SVN
::Client
::get_ssl_client_cert_file_provider
(),
5085 SVN
::Client
::get_ssl_client_cert_prompt_provider
(
5086 \
&Git
::SVN
::Prompt
::ssl_client_cert
, 2),
5087 SVN
::Client
::get_ssl_client_cert_pw_file_provider
(),
5088 SVN
::Client
::get_ssl_client_cert_pw_prompt_provider
(
5089 \
&Git
::SVN
::Prompt
::ssl_client_cert_pw
, 2),
5090 SVN
::Client
::get_username_provider
(),
5091 SVN
::Client
::get_ssl_server_trust_prompt_provider
(
5092 \
&Git
::SVN
::Prompt
::ssl_server_trust
),
5093 SVN
::Client
::get_username_prompt_provider
(
5094 \
&Git
::SVN
::Prompt
::username
, 2)
5098 sub escape_uri_only
{
5101 foreach (split m{/}, $uri) {
5102 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
5110 if ($url =~ m
#^(https?)://([^/]+)(.*)$#) {
5111 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only
($3));
5112 $url = "$scheme://$domain$uri";
5118 my ($class, $url) = @_;
5120 return $RA if ($RA && $RA->{url
} eq $url);
5124 SVN
::_Core
::svn_config_ensure
($config_dir, undef);
5125 my ($baton, $callbacks) = SVN
::Core
::auth_open_helper
(_auth_providers
);
5126 my $config = SVN
::Core
::config_get_config
($config_dir);
5128 my $dont_store_passwords = 1;
5129 my $conf_t = ${$config}{'config'};
5132 # The usage of $SVN::_Core::SVN_CONFIG_* variables
5133 # produces warnings that variables are used only once.
5134 # I had not found the better way to shut them up, so
5135 # the warnings of type 'once' are disabled in this block.
5136 if (SVN
::_Core
::svn_config_get_bool
($conf_t,
5137 $SVN::_Core
::SVN_CONFIG_SECTION_AUTH
,
5138 $SVN::_Core
::SVN_CONFIG_OPTION_STORE_PASSWORDS
,
5140 SVN
::_Core
::svn_auth_set_parameter
($baton,
5141 $SVN::_Core
::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS
,
5142 bless (\
$dont_store_passwords, "_p_void"));
5144 if (SVN
::_Core
::svn_config_get_bool
($conf_t,
5145 $SVN::_Core
::SVN_CONFIG_SECTION_AUTH
,
5146 $SVN::_Core
::SVN_CONFIG_OPTION_STORE_AUTH_CREDS
,
5148 $Git::SVN
::Prompt
::_no_auth_cache
= 1;
5150 } # no warnings 'once'
5151 my $self = SVN
::Ra
->new(url
=> escape_url
($url), auth
=> $baton,
5153 pool
=> SVN
::Pool
->new,
5154 auth_provider_callbacks
=> $callbacks);
5155 $self->{url
} = $url;
5156 $self->{svn_path
} = $url;
5157 $self->{repos_root
} = $self->get_repos_root;
5158 $self->{svn_path
} =~ s
#^\Q$self->{repos_root}\E(/|$)##;
5159 $self->{cache
} = { check_path
=> { r
=> 0, data
=> {} },
5160 get_dir
=> { r
=> 0, data
=> {} } };
5161 $RA = bless $self, $class;
5165 my ($self, $path, $r) = @_;
5166 my $cache = $self->{cache
}->{check_path
};
5167 if ($r == $cache->{r
} && exists $cache->{data
}->{$path}) {
5168 return $cache->{data
}->{$path};
5170 my $pool = SVN
::Pool
->new;
5171 my $t = $self->SUPER::check_path
($path, $r, $pool);
5173 if ($r != $cache->{r
}) {
5174 %{$cache->{data
}} = ();
5177 $cache->{data
}->{$path} = $t;
5181 my ($self, $dir, $r) = @_;
5182 my $cache = $self->{cache
}->{get_dir
};
5183 if ($r == $cache->{r
}) {
5184 if (my $x = $cache->{data
}->{$dir}) {
5185 return wantarray ? @
$x : $x->[0];
5188 my $pool = SVN
::Pool
->new;
5189 my ($d, undef, $props) = $self->SUPER::get_dir
($dir, $r, $pool);
5190 my %dirents = map { $_ => { kind
=> $d->{$_}->kind } } keys %$d;
5192 if ($r != $cache->{r
}) {
5193 %{$cache->{data
}} = ();
5196 $cache->{data
}->{$dir} = [ \
%dirents, $r, $props ];
5197 wantarray ?
(\
%dirents, $r, $props) : \
%dirents;
5201 # do not call the real DESTROY since we store ourselves in $RA
5204 # get_log(paths, start, end, limit,
5205 # discover_changed_paths, strict_node_history, receiver)
5207 my ($self, @args) = @_;
5208 my $pool = SVN
::Pool
->new;
5210 # svn_log_changed_path_t objects passed to get_log are likely to be
5211 # overwritten even if only the refs are copied to an external variable,
5212 # so we should dup the structures in their entirety. Using an
5213 # externally passed pool (instead of our temporary and quickly cleared
5214 # pool in Git::SVN::Ra) does not help matters at all...
5215 my $receiver = pop @args;
5216 my $prefix = "/".$self->{svn_path
};
5217 $prefix =~ s
#/+($)##;
5218 my $prefix_regex = qr
#^\Q$prefix\E#;
5220 my ($paths) = $_[0];
5221 return &$receiver(@_) unless $paths;
5223 foreach my $p (keys %$paths) {
5224 my $i = $paths->{$p};
5225 # Make path relative to our url, not repos_root
5226 $p =~ s/$prefix_regex//;
5227 my %s = map { $_ => $i->$_; }
5228 qw
/copyfrom_path copyfrom_rev action/;
5229 if ($s{'copyfrom_path'}) {
5230 $s{'copyfrom_path'} =~ s/$prefix_regex//;
5238 # the limit parameter was not supported in SVN 1.1.x, so we
5239 # drop it. Therefore, the receiver callback passed to it
5240 # is made aware of this limitation by being wrapped if
5241 # the limit passed to is being wrapped.
5242 if ($SVN::Core
::VERSION
le '1.2.0') {
5243 my $limit = splice(@args, 3, 1);
5245 my $receiver = pop @args;
5246 push(@args, sub { &$receiver(@_) if (--$limit >= 0) });
5249 my $ret = $self->SUPER::get_log
(@args, $pool);
5255 my ($self, $url1, $rev1, $url2, $rev2) = @_;
5256 my $ctx = SVN
::Client
->new(auth
=> _auth_providers
);
5257 my $out = IO
::File
->new_tmpfile;
5259 # older SVN (1.1.x) doesn't take $pool as the last parameter for
5260 # $ctx->diff(), so we'll create a default one
5261 my $pool = SVN
::Pool
->new_default_sub;
5263 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
5264 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
5266 my $ret = (($out->stat)[7] == 0);
5267 close $out or croak
$!;
5272 sub get_commit_editor
{
5273 my ($self, $log, $cb, $pool) = @_;
5274 my @lock = $SVN::Core
::VERSION
ge '1.2.0' ?
(undef, 0) : ();
5275 $self->SUPER::get_commit_editor
($log, $cb, @lock, $pool);
5279 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
5280 my $new = ($rev_a == $rev_b);
5281 my $path = $gs->{path
};
5283 if ($new && -e
$gs->{index}) {
5284 unlink $gs->{index} or die
5285 "Couldn't unlink index: $gs->{index}: $!\n";
5287 my $pool = SVN
::Pool
->new;
5288 $editor->set_path_strip($path);
5289 my (@pc) = split m
#/#, $path;
5290 my $reporter = $self->do_update($rev_b, (@pc ?
shift @pc : ''),
5292 my @lock = $SVN::Core
::VERSION
ge '1.2.0' ?
(undef) : ();
5294 # Since we can't rely on svn_ra_reparent being available, we'll
5295 # just have to do some magic with set_path to make it so
5296 # we only want a partial path.
5298 my $final = join('/', @pc);
5300 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
5301 $sp .= '/' if length $sp;
5304 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
5306 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
5308 $reporter->finish_report($pool);
5310 $editor->{git_commit_ok
};
5313 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
5314 # svn_ra_reparent didn't work before 1.4)
5316 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
5317 my $path = $gs->{path
};
5318 my $pool = SVN
::Pool
->new;
5320 my $full_url = $self->{url
};
5321 my $old_url = $full_url;
5322 $full_url .= '/' . $path if length $path;
5323 my ($ra, $reparented);
5325 if ($old_url =~ m
#^svn(\+ssh)?://# ||
5326 ($full_url =~ m
#^https?://# &&
5327 escape_url
($full_url) ne $full_url)) {
5331 $ra = Git
::SVN
::Ra
->new($full_url);
5333 } elsif ($old_url ne $full_url) {
5334 SVN
::_Ra
::svn_ra_reparent
($self->{session
}, $full_url, $pool);
5335 $self->{url
} = $full_url;
5340 $url_b = escape_url
($url_b);
5341 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
5342 my @lock = $SVN::Core
::VERSION
ge '1.2.0' ?
(undef) : ();
5343 $reporter->set_path('', $rev_a, 0, @lock, $pool);
5344 $reporter->finish_report($pool);
5347 SVN
::_Ra
::svn_ra_reparent
($self->{session
}, $old_url, $pool);
5348 $self->{url
} = $old_url;
5352 $editor->{git_commit_ok
};
5355 sub longest_common_path
{
5356 my ($gsv, $globs) = @_;
5358 my $common_max = scalar @
$gsv;
5360 foreach my $gs (@
$gsv) {
5361 my @tmp = split m
#/#, $gs->{path};
5364 $p .= length($p) ?
"/$_" : $_;
5370 $common_max += scalar @
$globs;
5371 foreach my $glob (@
$globs) {
5372 my @tmp = split m
#/#, $glob->{path}->{left};
5375 $p .= length($p) ?
"/$_" : $_;
5381 my $longest_path = '';
5382 foreach (sort {length $b <=> length $a} keys %common) {
5383 if ($common{$_} == $common_max) {
5391 sub gs_fetch_loop_common
{
5392 my ($self, $base, $head, $gsv, $globs) = @_;
5393 return if ($base > $head);
5394 my $inc = $_log_window_size;
5395 my ($min, $max) = ($base, $head < $base + $inc ?
$head : $base + $inc);
5396 my $longest_path = longest_common_path
($gsv, $globs);
5397 my $ra_url = $self->{url
};
5398 my $find_trailing_edge;
5402 my $err_handler = $SVN::Error
::handler
;
5403 $SVN::Error
::handler
= sub {
5405 skip_unknown_revs
($err);
5408 my ($paths, $r, $author, $date, $log) = @_;
5410 { author
=> $author, date
=> $date, log => $log } ];
5412 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
5413 sub { $revs{$_[1]} = _cb
(@_) });
5415 print "Checked through r$max\r";
5417 $find_trailing_edge = 1;
5419 if ($err and $find_trailing_edge) {
5420 print STDERR
"Path '$longest_path' ",
5421 "was probably deleted:\n",
5422 $err->expanded_message,
5423 "\nWill attempt to follow ",
5424 "revisions r$min .. r$max ",
5425 "committed before the deletion\n";
5427 while (--$hi >= $min) {
5429 $self->get_log([$longest_path], $min, $hi,
5432 $revs{$_[1]} = _cb
(@_) });
5434 print STDERR
"r$min .. r$ok OK\n";
5438 $find_trailing_edge = 0;
5440 $SVN::Error
::handler
= $err_handler;
5442 my %exists = map { $_->{path
} => $_ } @
$gsv;
5443 foreach my $r (sort {$a <=> $b} keys %revs) {
5444 my ($paths, $logged) = @
{$revs{$r}};
5446 foreach my $gs ($self->match_globs(\
%exists, $paths,
5448 if ($gs->rev_map_max >= $r) {
5451 next unless $gs->match_paths($paths, $r);
5452 $gs->{logged_rev_props
} = $logged;
5453 if (my $last_commit = $gs->last_commit) {
5454 $gs->assert_index_clean($last_commit);
5456 my $log_entry = $gs->do_fetch($paths, $r);
5458 $gs->do_git_commit($log_entry);
5460 $INDEX_FILES{$gs->{index}} = 1;
5462 foreach my $g (@
$globs) {
5463 my $k = "svn-remote.$g->{remote}." .
5465 Git
::SVN
::tmp_config
($k, $r);
5471 $self = Git
::SVN
::Ra
->new($ra_url);
5472 $ra_invalid = undef;
5475 # pre-fill the .rev_db since it'll eventually get filled in
5476 # with '0' x40 if something new gets committed
5477 foreach my $gs (@
$gsv) {
5478 next if $gs->rev_map_max >= $max;
5479 next if defined $gs->rev_map_get($max);
5480 $gs->rev_map_set($max, 0 x40
);
5482 foreach my $g (@
$globs) {
5483 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
5484 Git
::SVN
::tmp_config
($k, $max);
5486 last if $max >= $head;
5489 $max = $head if ($max > $head);
5494 sub get_dir_globbed
{
5495 my ($self, $left, $depth, $r) = @_;
5497 my @x = eval { $self->get_dir($left, $r) };
5498 return unless scalar @x == 3;
5499 my $dirents = $x[0];
5501 foreach my $de (keys %$dirents) {
5502 next if $dirents->{$de}->{kind
} != $SVN::Node
::dir
;
5504 my @args = ("$left/$de", $depth - 1, $r);
5505 foreach my $dir ($self->get_dir_globbed(@args)) {
5506 push @finalents, "$de/$dir";
5509 push @finalents, $de;
5516 my ($self, $exists, $paths, $globs, $r) = @_;
5519 my ($self, $exists, $g, $r) = @_;
5521 my @dirs = $self->get_dir_globbed($g->{path
}->{left
},
5522 $g->{path
}->{depth
},
5525 foreach my $de (@dirs) {
5526 my $p = $g->{path
}->full_path($de);
5527 next if $exists->{$p};
5528 next if (length $g->{path
}->{right
} &&
5529 ($self->check_path($p, $r) !=
5531 next unless $p =~ /$g->{path}->{regex}/;
5532 $exists->{$p} = Git
::SVN
->init($self->{url
}, $p, undef,
5533 $g->{ref}->full_path($de), 1);
5536 foreach my $g (@
$globs) {
5537 if (my $path = $paths->{"/$g->{path}->{left}"}) {
5538 if ($path->{action
} =~ /^[AR]$/) {
5539 get_dir_check
($self, $exists, $g, $r);
5542 foreach (keys %$paths) {
5543 if (/$g->{path}->{left_regex}/ &&
5544 !/$g->{path}->{regex}/) {
5545 next if $paths->{$_}->{action
} !~ /^[AR]$/;
5546 get_dir_check
($self, $exists, $g, $r);
5548 next unless /$g->{path}->{regex}/;
5550 my $pathname = $g->{path
}->full_path($p);
5551 next if $exists->{$pathname};
5552 next if ($self->check_path($pathname, $r) !=
5554 $exists->{$pathname} = Git
::SVN
->init(
5555 $self->{url
}, $pathname, undef,
5556 $g->{ref}->full_path($p), 1);
5559 foreach (split m
#/#, $g->{path}->{left}) {
5561 next unless ($paths->{$c} &&
5562 ($paths->{$c}->{action
} =~ /^[AR]$/));
5563 get_dir_check
($self, $exists, $g, $r);
5571 return $self->{url
} if ($self->{url
} eq $self->{repos_root
});
5572 my $url = $self->{repos_root
};
5573 my @components = split(m!/!, $self->{svn_path
});
5576 $url .= "/$c" if length $c;
5578 my $ra = (ref $self)->new($url);
5579 my $latest = $ra->get_latest_revnum;
5580 $ra->get_log("", $latest, 0, 1, 0, 1, sub {});
5582 } while ($@
&& ($c = shift @components));
5588 unless (defined $can_do_switch) {
5589 my $pool = SVN
::Pool
->new;
5591 $self->do_switch(1, '', 0, $self->{url
},
5592 SVN
::Delta
::Editor
->new, $pool);
5597 $rep->abort_report($pool);
5605 sub skip_unknown_revs
{
5607 my $errno = $err->apr_err();
5608 # Maybe the branch we're tracking didn't
5609 # exist when the repo started, so it's
5610 # not an error if it doesn't, just continue
5612 # Wonderfully consistent library, eh?
5613 # 160013 - svn:// and file://
5614 # 175002 - http(s)://
5615 # 175007 - http(s):// (this repo required authorization, too...)
5616 # More codes may be discovered later...
5617 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
5618 my $err_key = $err->expanded_message;
5619 # revision numbers change every time, filter them out
5620 $err_key =~ s/\d+/\0/g;
5621 $err_key = "$errno\0$err_key";
5622 unless ($ignored_err{$err_key}) {
5623 warn "W: Ignoring error from SVN, path probably ",
5624 "does not exist: ($errno): ",
5625 $err->expanded_message,"\n";
5626 warn "W: Do not be alarmed at the above message ",
5627 "git-svn is just searching aggressively for ",
5629 "This may take a while on large repositories\n";
5630 $ignored_err{$err_key} = 1;
5634 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
5637 package Git
::SVN
::Log
;
5640 use POSIX qw
/strftime/;
5642 use constant commit_log_separator
=> ('-' x
72) . "\n";
5643 use vars qw
/$TZ $limit $color $pager $non_recursive $verbose $oneline
5644 %rusers $show_commit $incremental/;
5649 return 1 if defined $c->{r
};
5651 # big commit message got truncated by the 16k pretty buffer in rev-list
5652 if ($c->{l
} && $c->{l
}->[-1] eq "...\n" &&
5653 $c->{a_raw
} =~ /\@([a-f\d\-]+)>$/) {
5655 my @log = command
(qw
/cat-file commit/, $c->{c
});
5657 # shift off the headers
5658 shift @log while ($log[0] ne '');
5661 # TODO: make $c->{l} not have a trailing newline in the future
5662 @
{$c->{l
}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
5664 (undef, $c->{r
}, undef) = ::extract_metadata
(
5665 (grep(/^git-svn-id: /, @log))[-1]);
5667 return defined $c->{r
};
5671 return $color || Git
->repository->get_colorbool('color.diff');
5674 sub git_svn_log_cmd
{
5675 my ($r_min, $r_max, @args) = @_;
5677 my (@files, @log_opts);
5678 foreach my $x (@args) {
5679 if ($x eq '--' || @files) {
5682 if (::verify_ref
("$x^0")) {
5690 my ($url, $rev, $uuid, $gs) = ::working_head_info
($head);
5691 $gs ||= Git
::SVN
->_new;
5692 my @cmd = (qw
/log --abbrev-commit --pretty=raw --default/,
5694 push @cmd, '-r' unless $non_recursive;
5695 push @cmd, qw
/--raw --name-status/ if $verbose;
5696 push @cmd, '--color' if log_use_color
();
5697 push @cmd, @log_opts;
5698 if (defined $r_max && $r_max == $r_min) {
5699 push @cmd, '--max-count=1';
5700 if (my $c = $gs->rev_map_get($r_max)) {
5703 } elsif (defined $r_max) {
5704 if ($r_max < $r_min) {
5705 ($r_min, $r_max) = ($r_max, $r_min);
5707 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
5708 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
5709 # If there are no commits in the range, both $c_max and $c_min
5710 # will be undefined. If there is at least 1 commit in the
5711 # range, both will be defined.
5712 return () if !defined $c_min || !defined $c_max;
5713 if ($c_min eq $c_max) {
5714 push @cmd, '--max-count=1', $c_min;
5716 push @cmd, '--boundary', "$c_min..$c_max";
5719 return (@cmd, @files);
5722 # adapted from pager.c
5725 $ENV{GIT_PAGER_IN_USE
} = 'false';
5729 chomp($pager = command_oneline
(qw(var GIT_PAGER)));
5730 if ($pager eq 'cat') {
5733 $ENV{GIT_PAGER_IN_USE
} = defined($pager);
5737 return unless defined $pager;
5738 pipe my ($rfd, $wfd) or return;
5739 defined(my $pid = fork) or ::fatal
"Can't fork: $!";
5741 open STDOUT
, '>&', $wfd or
5742 ::fatal
"Can't redirect to stdout: $!";
5745 open STDIN
, '<&', $rfd or ::fatal
"Can't redirect stdin: $!";
5746 $ENV{LESS
} ||= 'FRSX';
5747 exec $pager or ::fatal
"Can't run pager: $! ($pager)";
5750 sub format_svn_date
{
5751 # some systmes don't handle or mishandle %z, so be creative.
5752 my $t = shift || time;
5753 my $gm = timelocal
(gmtime($t));
5754 my $sign = qw( + + - )[ $t <=> $gm ];
5755 my $gmoff = sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
5756 return strftime
("%Y-%m-%d %H:%M:%S $gmoff (%a, %d %b %Y)", localtime($t));
5759 sub parse_git_date
{
5761 # Date::Parse isn't in the standard Perl distro :(
5762 if ($tz =~ s/^\+//) {
5763 $t += tz_to_s_offset
($tz);
5764 } elsif ($tz =~ s/^\-//) {
5765 $t -= tz_to_s_offset
($tz);
5770 sub set_local_timezone
{
5778 sub tz_to_s_offset
{
5781 return ($1 * 60) + ($tz * 3600);
5784 sub get_author_info
{
5785 my ($dest, $author, $t, $tz) = @_;
5786 $author =~ s/(?:^\s*|\s*$)//g;
5787 $dest->{a_raw
} = $author;
5790 $au = $rusers{$author} || undef;
5793 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
5798 $dest->{t_utc
} = parse_git_date
($t, $tz);
5801 sub process_commit
{
5802 my ($c, $r_min, $r_max, $defer) = @_;
5803 if (defined $r_min && defined $r_max) {
5804 if ($r_min == $c->{r
} && $r_min == $r_max) {
5808 return 1 if $r_min == $r_max;
5809 if ($r_min < $r_max) {
5810 # we need to reverse the print order
5811 return 0 if (defined $limit && --$limit < 0);
5815 if ($r_min != $r_max) {
5816 return 1 if ($r_min < $c->{r
});
5817 return 1 if ($r_max > $c->{r
});
5820 return 0 if (defined $limit && --$limit < 0);
5829 if (my $l = $c->{l
}) {
5830 while ($l->[0] =~ /^\s*$/) { shift @
$l }
5833 $l_fmt ||= 'A' . length($c->{r
});
5834 print 'r',pack($l_fmt, $c->{r
}),' | ';
5835 print "$c->{c} | " if $show_commit;
5838 show_commit_normal
($c);
5842 sub show_commit_changed_paths
{
5844 return unless $c->{changed
};
5845 print "Changed paths:\n", @
{$c->{changed
}};
5848 sub show_commit_normal
{
5850 print commit_log_separator
, "r$c->{r} | ";
5851 print "$c->{c} | " if $show_commit;
5852 print "$c->{a} | ", format_svn_date
($c->{t_utc
}), ' | ';
5855 if (my $l = $c->{l
}) {
5856 while ($l->[$#$l] eq "\n" && $#$l > 0
5857 && $l->[($#$l - 1)] eq "\n") {
5860 $nr_line = scalar @
$l;
5862 print "1 line\n\n\n";
5864 if ($nr_line == 1) {
5865 $nr_line = '1 line';
5867 $nr_line .= ' lines';
5869 print $nr_line, "\n";
5870 show_commit_changed_paths
($c);
5872 print $_ foreach @
$l;
5876 show_commit_changed_paths
($c);
5880 foreach my $x (qw
/raw stat diff/) {
5883 print $_ foreach @
{$c->{$x}}
5890 my ($r_min, $r_max);
5891 my $r_last = -1; # prevent dupes
5892 set_local_timezone
();
5893 if (defined $::_revision
) {
5894 if ($::_revision
=~ /^(\d+):(\d+)$/) {
5895 ($r_min, $r_max) = ($1, $2);
5896 } elsif ($::_revision
=~ /^\d+$/) {
5897 $r_min = $r_max = $::_revision
;
5899 ::fatal
"-r$::_revision is not supported, use ",
5900 "standard 'git log' arguments instead";
5905 @args = git_svn_log_cmd
($r_min, $r_max, @args);
5907 print commit_log_separator
unless $incremental || $oneline;
5910 my $log = command_output_pipe
(@args);
5912 my (@k, $c, $d, $stat);
5913 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
5915 if (/^${esc_color}commit (?:- )?($::sha1_short)/o) {
5917 if ($c && cmt_showable
($c) && $c->{r
} != $r_last) {
5919 process_commit
($c, $r_min, $r_max, \
@k) or
5924 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
5925 get_author_info
($c, $1, $2, $3);
5926 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
5928 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
5929 push @
{$c->{raw
}}, $_;
5930 } elsif (/^${esc_color}[ACRMDT]\t/) {
5931 # we could add $SVN->{svn_path} here, but that requires
5932 # remote access at the moment (repo_path_split)...
5933 s
#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
5934 push @
{$c->{changed
}}, $_;
5935 } elsif (/^${esc_color}diff /o) {
5937 push @
{$c->{diff
}}, $_;
5939 push @
{$c->{diff
}}, $_;
5940 } elsif (/^\
.+\ \
|\s
*\d
+\
$esc_color[\
+\
-]*
5941 $esc_color*[\
+\
-]*$esc_color$/x
) {
5943 push @
{$c->{stat}}, $_;
5944 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
5945 push @
{$c->{stat}}, $_;
5947 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
5948 ($c->{url
}, $c->{r
}, undef) = ::extract_metadata
($1);
5949 } elsif (s/^${esc_color} //o) {
5950 push @
{$c->{l
}}, $_;
5953 if ($c && defined $c->{r
} && $c->{r
} != $r_last) {
5955 process_commit
($c, $r_min, $r_max, \
@k);
5958 ($r_min, $r_max) = ($r_max, $r_min);
5959 process_commit
($_, $r_min, $r_max) foreach reverse @k;
5963 print commit_log_separator
unless $incremental || $oneline;
5972 my ($fh, $ctx, $rev);
5975 ($fh, $ctx) = command_output_pipe
('blame', @_, $path);
5976 while (my $line = <$fh>) {
5977 if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
5978 # Uncommitted edits show up as a rev ID of
5979 # all zeros, which we can't look up with
5982 (undef, $rev, undef) =
5984 $rev = '0' if (!$rev);
5988 $rev = sprintf('%-10s', $rev);
5989 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
5994 ($fh, $ctx) = command_output_pipe
('blame', '-p', @_, 'HEAD',
5999 my %dsha; #distinct sha keys
6001 while (my $line = <$fh>) {
6002 push @buffer, $line;
6003 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
6008 my $s2r = ::cmt_sha2rev_batch
([keys %dsha]);
6010 foreach my $line (@buffer) {
6011 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
6013 $rev = '0' if (!$rev)
6015 elsif ($line =~ /^author (.*)/) {
6016 $authors{$rev} = $1;
6017 $authors{$rev} =~ s/\s/_/g;
6019 elsif ($line =~ /^\t(.*)$/) {
6020 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
6024 command_close_pipe
($fh, $ctx);
6027 package Git
::SVN
::Migration
;
6028 # these version numbers do NOT correspond to actual version numbers
6029 # of git nor git-svn. They are just relative.
6031 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
6033 # v1 layout: .git/$id/info/url, refs/remotes/$id
6035 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
6037 # v3 layout: .git/svn/$id, refs/remotes/$id
6038 # - info/url may remain for backwards compatibility
6039 # - this is what we migrate up to this layout automatically,
6040 # - this will be used by git svn init on single branches
6041 # v3.1 layout (auto migrated):
6042 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
6043 # for backwards compatibility
6045 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
6046 # - this is only created for newly multi-init-ed
6047 # repositories. Similar in spirit to the
6048 # --use-separate-remotes option in git-clone (now default)
6049 # - we do not automatically migrate to this (following
6050 # the example set by core git)
6052 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
6053 # - newer, more-efficient format that uses 24-bytes per record
6054 # with no filler space.
6055 # - use xxd -c24 < .rev_map.$UUID to view and debug
6056 # - This is a one-way migration, repositories updated to the
6057 # new format will not be able to use old git-svn without
6058 # rebuilding the .rev_db. Rebuilding the rev_db is not
6059 # possible if noMetadata or useSvmProps are set; but should
6060 # be no problem for users that use the (sensible) defaults.
6064 use File
::Path qw
/mkpath/;
6065 use File
::Basename qw
/dirname basename/;
6066 use vars qw
/$_minimize/;
6068 sub migrate_from_v0
{
6069 my $git_dir = $ENV{GIT_DIR
};
6070 return undef unless -d
$git_dir;
6071 my ($fh, $ctx) = command_output_pipe
(qw
/rev-parse --symbolic --all/);
6075 my ($id, $orig_ref) = ($_, $_);
6076 next unless $id =~ s
#^refs/heads/(.+)-HEAD$#$1#;
6077 next unless -f
"$git_dir/$id/info/url";
6078 my $new_ref = "refs/remotes/$id";
6079 if (::verify_ref
("$new_ref^0")) {
6080 print STDERR
"W: $orig_ref is probably an old ",
6081 "branch used by an ancient version of ",
6083 "However, $new_ref also exists.\n",
6084 "We will not be able ",
6085 "to use this branch until this ",
6086 "ambiguity is resolved.\n";
6089 print STDERR
"Migrating from v0 layout...\n" if !$migrated;
6090 print STDERR
"Renaming ref: $orig_ref => $new_ref\n";
6091 command_noisy
('update-ref', $new_ref, $orig_ref);
6092 command_noisy
('update-ref', '-d', $orig_ref, $orig_ref);
6095 command_close_pipe
($fh, $ctx);
6096 print STDERR
"Done migrating from v0 layout...\n" if $migrated;
6100 sub migrate_from_v1
{
6101 my $git_dir = $ENV{GIT_DIR
};
6103 return $migrated unless -d
$git_dir;
6104 my $svn_dir = "$git_dir/svn";
6106 # just in case somebody used 'svn' as their $id at some point...
6107 return $migrated if -d
$svn_dir && ! -f
"$svn_dir/info/url";
6109 print STDERR
"Migrating from a git-svn v1 layout...\n";
6111 print STDERR
"Data from a previous version of git-svn exists, but\n\t",
6112 "$svn_dir\n\t(required for this version ",
6113 "($::VERSION) of git-svn) does not exist.\n";
6114 my ($fh, $ctx) = command_output_pipe
(qw
/rev-parse --symbolic --all/);
6117 next unless $x =~ s
#^refs/remotes/##;
6119 next unless -f
"$git_dir/$x/info/url";
6120 my $u = eval { ::file_to_s
("$git_dir/$x/info/url") };
6122 my $dn = dirname
("$git_dir/svn/$x");
6123 mkpath
([$dn]) unless -d
$dn;
6124 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
6125 mkpath
(["$git_dir/svn/svn"]);
6126 print STDERR
" - $git_dir/$x/info => ",
6127 "$git_dir/svn/$x/info\n";
6128 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
6130 # don't worry too much about these, they probably
6131 # don't exist with repos this old (save for index,
6132 # and we can easily regenerate that)
6133 foreach my $f (qw
/unhandled.log index .rev_db/) {
6134 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
6137 print STDERR
" - $git_dir/$x => $git_dir/svn/$x\n";
6138 rename "$git_dir/$x", "$git_dir/svn/$x" or
6143 command_close_pipe
($fh, $ctx);
6144 print STDERR
"Done migrating from a git-svn v1 layout\n";
6149 my ($l_map, $pfx, $path) = @_;
6151 foreach (<$path/*>) {
6152 if (-r
"$_/info/url") {
6153 $pfx .= '/' if $pfx && $pfx !~ m
!/$!;
6154 my $ref_id = $pfx . basename
$_;
6155 my $url = ::file_to_s
("$_/info/url");
6156 $l_map->{$ref_id} = $url;
6163 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
6164 read_old_urls
($l_map, $x, $_);
6168 sub migrate_from_v2
{
6169 my @cfg = command
(qw
/config -l/);
6170 return if grep /^svn-remote\..+\.url=/, @cfg;
6172 read_old_urls
(\
%l_map, '', "$ENV{GIT_DIR}/svn");
6175 foreach my $ref_id (sort keys %l_map) {
6176 eval { Git
::SVN
->init($l_map{$ref_id}, '', undef, $ref_id) };
6178 Git
::SVN
->init($l_map{$ref_id}, '', $ref_id, $ref_id);
6185 sub minimize_connections
{
6186 my $r = Git
::SVN
::read_all_remotes
();
6188 my $root_repos = {};
6189 foreach my $repo_id (keys %$r) {
6190 my $url = $r->{$repo_id}->{url
} or next;
6191 my $fetch = $r->{$repo_id}->{fetch
} or next;
6192 my $ra = Git
::SVN
::Ra
->new($url);
6194 # skip existing cases where we already connect to the root
6195 if (($ra->{url
} eq $ra->{repos_root
}) ||
6196 ($ra->{repos_root
} eq $repo_id)) {
6197 $root_repos->{$ra->{url
}} = $repo_id;
6201 my $root_ra = Git
::SVN
::Ra
->new($ra->{repos_root
});
6202 my $root_path = $ra->{url
};
6203 $root_path =~ s
#^\Q$ra->{repos_root}\E(/|$)##;
6204 foreach my $path (keys %$fetch) {
6205 my $ref_id = $fetch->{$path};
6206 my $gs = Git
::SVN
->new($ref_id, $repo_id, $path);
6208 # make sure we can read when connecting to
6209 # a higher level of a repository
6210 my ($last_rev, undef) = $gs->last_rev_commit;
6211 if (!defined $last_rev) {
6213 $root_ra->get_latest_revnum;
6217 my $new = $root_path;
6218 $new .= length $path ?
"/$path" : '';
6220 $root_ra->get_log([$new], $last_rev, $last_rev,
6224 $new_urls->{$ra->{repos_root
}}->{$new} =
6225 { ref_id
=> $ref_id,
6226 old_repo_id
=> $repo_id,
6227 old_path
=> $path };
6232 foreach my $url (keys %$new_urls) {
6233 # see if we can re-use an existing [svn-remote "repo_id"]
6234 # instead of creating a(n ugly) new section:
6235 my $repo_id = $root_repos->{$url} || $url;
6237 my $fetch = $new_urls->{$url};
6238 foreach my $path (keys %$fetch) {
6239 my $x = $fetch->{$path};
6240 Git
::SVN
->init($url, $path, $repo_id, $x->{ref_id
});
6241 my $pfx = "svn-remote.$x->{old_repo_id}";
6243 my $old_fetch = quotemeta("$x->{old_path}:".
6245 command_noisy
(qw
/config --unset/,
6246 "$pfx.fetch", '^'. $old_fetch . '$');
6247 delete $r->{$x->{old_repo_id
}}->
6248 {fetch
}->{$x->{old_path
}};
6249 if (!keys %{$r->{$x->{old_repo_id
}}->{fetch
}}) {
6250 command_noisy
(qw
/config --unset/,
6252 push @emptied, $x->{old_repo_id
}
6257 my $file = $ENV{GIT_CONFIG
} || "$ENV{GIT_DIR}/config";
6259 The following [svn-remote] sections in your config file ($file) are empty
6260 and can be safely removed:
6262 print STDERR
"[svn-remote \"$_\"]\n" foreach @emptied;
6266 sub migration_check
{
6270 minimize_connections
() if $_minimize;
6273 package Git
::IndexInfo
;
6276 use Git qw
/command_input_pipe command_close_pipe/;
6280 my ($gui, $ctx) = command_input_pipe
(qw
/update-index -z --index-info/);
6281 bless { gui
=> $gui, ctx
=> $ctx, nr
=> 0}, $class;
6285 my ($self, $path) = @_;
6286 if (print { $self->{gui
} } '0 ', 0 x
40, "\t", $path, "\0") {
6287 return ++$self->{nr
};
6293 my ($self, $mode, $hash, $path) = @_;
6294 if (print { $self->{gui
} } $mode, ' ', $hash, "\t", $path, "\0") {
6295 return ++$self->{nr
};
6302 command_close_pipe
($self->{gui
}, $self->{ctx
});
6305 package Git
::SVN
::GlobSpec
;
6310 my ($class, $glob, $pattern_ok) = @_;
6312 $re =~ s!/+$!!g; # no need for trailing slashes
6313 my (@left, @right, @patterns);
6315 my $die_msg = "Only one set of wildcard directories " .
6316 "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
6317 for my $part (split(m
|/|, $glob)) {
6318 if ($part =~ /\*/ && $part ne "*") {
6319 die "Invalid pattern in '$glob': $part\n";
6320 } elsif ($pattern_ok && $part =~ /[{}]/ &&
6321 $part !~ /^\{[^{}]+\}/) {
6322 die "Invalid pattern in '$glob': $part\n";
6325 die $die_msg if $state eq "right";
6327 push(@patterns, "[^/]*");
6328 } elsif ($pattern_ok && $part =~ /^\{(.*)\}$/) {
6329 die $die_msg if $state eq "right";
6331 my $p = quotemeta($1);
6333 push(@patterns, "(?:$p)");
6335 if ($state eq "left") {
6338 push(@right, $part);
6343 my $depth = @patterns;
6345 die "One '*' is needed in glob: '$glob'\n";
6347 my $left = join('/', @left);
6348 my $right = join('/', @right);
6349 $re = join('/', @patterns);
6351 grep(length, quotemeta($left), "($re)", quotemeta($right)));
6352 my $left_re = qr/^\/\Q
$left\E
(\
/|$)/;
6353 bless { left
=> $left, right
=> $right, left_regex
=> $left_re,
6354 regex
=> qr/$re/, glob => $glob, depth
=> $depth }, $class;
6358 my ($self, $path) = @_;
6359 return (length $self->{left
} ?
"$self->{left}/" : '') .
6360 $path . (length $self->{right
} ?
"/$self->{right}" : '');
6368 $remotes = { # returned by read_all_remotes()
6370 # svn-remote.svn.url=https://svn.musicpd.org
6371 url
=> 'https://svn.musicpd.org',
6372 # svn-remote.svn.fetch=mpd/trunk:trunk
6374 'mpd/trunk' => 'trunk',
6376 # svn-remote.svn.tags=mpd/tags/*:tags/*
6381 regex
=> qr!mpd/tags/([^/]+)$!,
6387 regex
=> qr!tags/([^/]+)$!,
6394 $log_entry hashref as returned by libsvn_log_entry
()
6396 log => 'whitespace-formatted log entry
6397 ', # trailing newline is preserved
6398 revision
=> '8', # integer
6399 date
=> '2004-02-24T17:01:44.108345Z', # commit date
6400 author
=> 'committer name'
6404 # this is generated by generate_diff();
6405 @mods = array of diff
-index line hashes
, each element represents one line
6406 of diff
-index output
6408 diff
-index line
($m hash
)
6410 mode_a
=> first column of diff
-index output
, no leading
':',
6411 mode_b
=> second column of diff
-index output
,
6412 sha1_b
=> sha1sum of the final blob
,
6413 chg
=> change type
[MCRADT
],
6414 file_a
=> original file name of a file
(iff chg is
'C' or 'R')
6415 file_b
=> new
/current file name of a file
(any chg
)
6419 # retval of read_url_paths{,_all}();
6421 # repository root url
6422 'https://svn.musicpd.org' => {
6423 # repository path # GIT_SVN_ID
6424 'mpd/trunk' => 'trunk',
6425 'mpd/tags/0.11.5' => 'tags/0.11.5',
6430 I don
't trust the each() function on unless I created %hash myself
6431 because the internal iterator may not have started at base.