mergetools/meld: Use --help output to detect --output support
[alt-git.git] / git-svn.perl
blob351e743a902568c8b6f68ffaf4030f087ba8568d
1 #!/usr/bin/env perl
2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
4 use 5.008;
5 use warnings;
6 use strict;
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)
16 } || '';
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};
28 if ($^O eq 'msys') {
29 $ENV{SVN_SSH} =~ s/\\/\\\\/g;
30 $ENV{SVN_SSH} =~ s/(.*)/"$1"/;
35 $Git::SVN::Log::TZ = $ENV{TZ};
36 $ENV{TZ} = 'UTC';
37 $| = 1; # unbuffer STDOUT
39 sub fatal (@) { print STDERR "@_\n"; exit 1 }
40 sub _req_svn {
41 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
42 require SVN::Ra;
43 require SVN::Delta;
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';
52 use Carp qw/croak/;
53 use Digest::MD5;
54 use IO::File qw//;
55 use File::Basename qw/dirname basename/;
56 use File::Path qw/mkpath/;
57 use File::Spec;
58 use File::Find;
59 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
60 use IPC::Open3;
61 use Git;
62 use Memoize; # core since 5.8.0, Jul 2002
64 BEGIN {
65 # import functions from Git into our packages, en masse
66 no strict 'refs';
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),
72 __PACKAGE__) {
73 *{"${package}::$_"} = \&{"Git::$_"};
76 Memoize::memoize 'Git::config';
77 Memoize::memoize 'Git::config_bool';
80 my ($SVN);
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,
86 $_template, $_shared,
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";
93 $_q ||= 0;
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,
107 'quiet|q+' => \$_q,
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,
113 %remote_opts );
115 my ($_trunk, @_tags, @_branches, $_stdlayout);
116 my %icv;
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] },
127 %remote_opts );
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
135 my %cmd = (
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,
140 %fc_opts } ],
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)",
150 \%init_opts ],
151 'multi-init' => [ \&cmd_multi_init,
152 "Deprecated alias for ".
153 "'$0 init -T<trunk> -b<branches> -t<tags>'",
154 \%init_opts ],
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,
172 'tag|t' => \$_tag,
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
188 } ],
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
200 } ],
201 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
202 { 'revision|r=i' => \$_revision
203 } ],
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,
212 %remote_opts } ],
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
224 } ],
225 'find-rev' => [ \&cmd_find_rev,
226 "Translate between SVN revision numbers and tree-ish",
227 {} ],
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,
235 %fc_opts } ],
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,
241 %cmt_opts } ],
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 } ],
253 'gc' => [ \&cmd_gc,
254 "Compress unhandled.log files in .git/svn and remove " .
255 "index files in .git/svn",
256 {} ],
259 my $cmd;
260 for (my $i = 0; $i < @ARGV; $i++) {
261 if (defined $cmd{$ARGV[$i]}) {
262 $cmd = $ARGV[$i];
263 splice @ARGV, $i, 1;
264 last;
265 } elsif ($ARGV[$i] eq 'help') {
266 $cmd = $ARGV[$i+1];
267 usage(0);
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};
279 my $cdup = undef;
280 git_cmd_try {
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 ",
289 "'$cdup'\n";
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');
310 usage(0) if $_help;
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();
322 eval {
323 Git::SVN::verify_remotes_sanity();
324 $cmd{$cmd}->[0]->(@ARGV);
326 fatal $@ if $@;
327 post_fetch_checkout();
328 exit 0;
330 ####################### primary functions ######################
331 sub usage {
332 my $exit = shift || 0;
333 my $fd = $exit ? \*STDERR : \*STDOUT;
334 print $fd <<"";
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 ?
350 "--$_" : "-$_" }
351 split /\|/,$_)," $x\n";
354 print $fd <<"";
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
358 information.
360 exit $exit;
363 sub version {
364 ::_req_svn();
365 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
366 exit 0;
369 sub do_git_init_db {
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";
376 } else {
377 push @init_db, "--shared";
380 command_noisy(@init_db);
381 $_repository = Git->repository(Repository => ".git");
383 my $set;
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});
389 $set = $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);
402 sub init_subdir {
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});
410 sub cmd_clone {
411 my ($url, $path) = @_;
412 if (!defined $path &&
413 (defined $_trunk || @_branches || @_tags ||
414 defined $_stdlayout) &&
415 $url !~ m#^[a-z\+]+://#) {
416 $path = $url;
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)
422 if $_authors;
423 Git::SVN::fetch_all($Git::SVN::default_repo_id);
426 sub cmd_init {
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);
438 init_subdir(@_);
439 do_git_init_db();
441 if ($Git::SVN::_minimize_url eq 'unset') {
442 $Git::SVN::_minimize_url = 0;
445 Git::SVN->init($url);
448 sub cmd_fetch {
449 if (grep /^\d+=./, @_) {
450 die "'<rev>=<commit>' fetch arguments are ",
451 "no longer supported.\n";
453 my ($remote) = @_;
454 if (@_ > 1) {
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');
460 unless ($gs) {
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) {
468 cmd_multi_fetch();
469 } else {
470 $remote ||= $Git::SVN::default_repo_id;
471 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
475 sub cmd_set_tree {
476 my (@commits) = @_;
477 if ($_stdin || !@commits) {
478 print "Reading from stdin...\n";
479 @commits = ();
480 while (<STDIN>) {
481 if (/\b($sha1_short)\b/o) {
482 unshift @commits, $1;
486 my @revs;
487 foreach my $c (@commits) {
488 my @tmp = command('rev-parse',$c);
489 if (scalar @tmp == 1) {
490 push @revs, $tmp[0];
491 } elsif (scalar @tmp > 1) {
492 push @revs, reverse(command('rev-list',@tmp));
493 } else {
494 fatal "Failed to rev-parse $c";
497 my $gs = Git::SVN->new;
498 my ($r_last, $cmt_last) = $gs->last_rev_commit;
499 $gs->fetch;
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";
508 unlink $gs->{index};
511 sub split_merge_info_range {
512 my ($range) = @_;
513 if ($range =~ /(\d+)-(\d+)/) {
514 return (int($1), int($2));
515 } else {
516 return (int($range), int($range));
520 sub combine_ranges {
521 my ($in) = @_;
523 my @fnums = ();
524 my @arr = split(/,/, $in);
525 for my $element (@arr) {
526 my ($start, $end) = split_merge_info_range($element);
527 push @fnums, $start;
530 my @sorted = @arr [ sort {
531 $fnums[$a] <=> $fnums[$b]
532 } 0..$#arr ];
534 my @return = ();
535 my $last = -1;
536 my $first = -1;
537 for my $element (@sorted) {
538 my ($start, $end) = split_merge_info_range($element);
540 if ($last == -1) {
541 $first = $start;
542 $last = $end;
543 next;
545 if ($start <= $last+1) {
546 if ($end > $last) {
547 $last = $end;
549 next;
551 if ($first == $last) {
552 push @return, "$first";
553 } else {
554 push @return, "$first-$last";
556 $first = $start;
557 $last = $end;
560 if ($first != -1) {
561 if ($first == $last) {
562 push @return, "$first";
563 } else {
564 push @return, "$first-$last";
568 return join(',', @return);
571 sub merge_revs_into_hash {
572 my ($hash, $minfo) = @_;
573 my @lines = split(' ', $minfo);
575 for my $line (@lines) {
576 my ($branchpath, $revs) = split(/:/, $line);
578 if (exists($hash->{$branchpath})) {
579 # Merge the two revision sets
580 my $combined = "$hash->{$branchpath},$revs";
581 $hash->{$branchpath} = combine_ranges($combined);
582 } else {
583 # Just do range combining for consolidation
584 $hash->{$branchpath} = combine_ranges($revs);
589 sub merge_merge_info {
590 my ($mergeinfo_one, $mergeinfo_two) = @_;
591 my %result_hash = ();
593 merge_revs_into_hash(\%result_hash, $mergeinfo_one);
594 merge_revs_into_hash(\%result_hash, $mergeinfo_two);
596 my $result = '';
597 # Sort below is for consistency's sake
598 for my $branchname (sort keys(%result_hash)) {
599 my $revlist = $result_hash{$branchname};
600 $result .= "$branchname:$revlist\n"
602 return $result;
605 sub populate_merge_info {
606 my ($d, $gs, $uuid, $linear_refs, $rewritten_parent) = @_;
608 my %parentshash;
609 read_commit_parents(\%parentshash, $d);
610 my @parents = @{$parentshash{$d}};
611 if ($#parents > 0) {
612 # Merge commit
613 my $all_parents_ok = 1;
614 my $aggregate_mergeinfo = '';
615 my $rooturl = $gs->repos_root;
617 if (defined($rewritten_parent)) {
618 # Replace first parent with newly-rewritten version
619 shift @parents;
620 unshift @parents, $rewritten_parent;
623 foreach my $parent (@parents) {
624 my ($branchurl, $svnrev, $paruuid) =
625 cmt_metadata($parent);
627 unless (defined($svnrev)) {
628 # Should have been caught be preflight check
629 fatal "merge commit $d has ancestor $parent, but that change "
630 ."does not have git-svn metadata!";
632 unless ($branchurl =~ /^$rooturl(.*)/) {
633 fatal "commit $parent git-svn metadata changed mid-run!";
635 my $branchpath = $1;
637 my $ra = Git::SVN::Ra->new($branchurl);
638 my (undef, undef, $props) =
639 $ra->get_dir(canonicalize_path("."), $svnrev);
640 my $par_mergeinfo = $props->{'svn:mergeinfo'};
641 unless (defined $par_mergeinfo) {
642 $par_mergeinfo = '';
644 # Merge previous mergeinfo values
645 $aggregate_mergeinfo =
646 merge_merge_info($aggregate_mergeinfo,
647 $par_mergeinfo, 0);
649 next if $parent eq $parents[0]; # Skip first parent
650 # Add new changes being placed in tree by merge
651 my @cmd = (qw/rev-list --reverse/,
652 $parent, qw/--not/);
653 foreach my $par (@parents) {
654 unless ($par eq $parent) {
655 push @cmd, $par;
658 my @revsin = ();
659 my ($revlist, $ctx) = command_output_pipe(@cmd);
660 while (<$revlist>) {
661 my $irev = $_;
662 chomp $irev;
663 my (undef, $csvnrev, undef) =
664 cmt_metadata($irev);
665 unless (defined $csvnrev) {
666 # A child is missing SVN annotations...
667 # this might be OK, or might not be.
668 warn "W:child $irev is merged into revision "
669 ."$d but does not have git-svn metadata. "
670 ."This means git-svn cannot determine the "
671 ."svn revision numbers to place into the "
672 ."svn:mergeinfo property. You must ensure "
673 ."a branch is entirely committed to "
674 ."SVN before merging it in order for "
675 ."svn:mergeinfo population to function "
676 ."properly";
678 push @revsin, $csvnrev;
680 command_close_pipe($revlist, $ctx);
682 last unless $all_parents_ok;
684 # We now have a list of all SVN revnos which are
685 # merged by this particular parent. Integrate them.
686 next if $#revsin == -1;
687 my $newmergeinfo = "$branchpath:" . join(',', @revsin);
688 $aggregate_mergeinfo =
689 merge_merge_info($aggregate_mergeinfo,
690 $newmergeinfo, 1);
692 if ($all_parents_ok and $aggregate_mergeinfo) {
693 return $aggregate_mergeinfo;
697 return undef;
700 sub cmd_dcommit {
701 my $head = shift;
702 command_noisy(qw/update-index --refresh/);
703 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
704 'Cannot dcommit with a dirty index. Commit your changes first, '
705 . "or stash them with `git stash'.\n";
706 $head ||= 'HEAD';
708 my $old_head;
709 if ($head ne 'HEAD') {
710 $old_head = eval {
711 command_oneline([qw/symbolic-ref -q HEAD/])
713 if ($old_head) {
714 $old_head =~ s{^refs/heads/}{};
715 } else {
716 $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
718 command(['checkout', $head], STDERR => 0);
721 my @refs;
722 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
723 unless ($gs) {
724 die "Unable to determine upstream SVN information from ",
725 "$head history.\nPerhaps the repository is empty.";
728 if (defined $_commit_url) {
729 $url = $_commit_url;
730 } else {
731 $url = eval { command_oneline('config', '--get',
732 "svn-remote.$gs->{repo_id}.commiturl") };
733 if (!$url) {
734 $url = $gs->full_pushurl
738 my $last_rev = $_revision if defined $_revision;
739 if ($url) {
740 print "Committing to $url ...\n";
742 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
743 if ($_no_rebase && scalar(@$linear_refs) > 1) {
744 warn "Attempting to commit more than one change while ",
745 "--no-rebase is enabled.\n",
746 "If these changes depend on each other, re-running ",
747 "without --no-rebase may be required."
749 my $expect_url = $url;
751 my $push_merge_info = eval {
752 command_oneline(qw/config --get svn.pushmergeinfo/)
754 if (not defined($push_merge_info)
755 or $push_merge_info eq "false"
756 or $push_merge_info eq "no"
757 or $push_merge_info eq "never") {
758 $push_merge_info = 0;
761 unless (defined($_merge_info) || ! $push_merge_info) {
762 # Preflight check of changes to ensure no issues with mergeinfo
763 # This includes check for uncommitted-to-SVN parents
764 # (other than the first parent, which we will handle),
765 # information from different SVN repos, and paths
766 # which are not underneath this repository root.
767 my $rooturl = $gs->repos_root;
768 foreach my $d (@$linear_refs) {
769 my %parentshash;
770 read_commit_parents(\%parentshash, $d);
771 my @realparents = @{$parentshash{$d}};
772 if ($#realparents > 0) {
773 # Merge commit
774 shift @realparents; # Remove/ignore first parent
775 foreach my $parent (@realparents) {
776 my ($branchurl, $svnrev, $paruuid) = cmt_metadata($parent);
777 unless (defined $paruuid) {
778 # A parent is missing SVN annotations...
779 # abort the whole operation.
780 fatal "$parent is merged into revision $d, "
781 ."but does not have git-svn metadata. "
782 ."Either dcommit the branch or use a "
783 ."local cherry-pick, FF merge, or rebase "
784 ."instead of an explicit merge commit.";
787 unless ($paruuid eq $uuid) {
788 # Parent has SVN metadata from different repository
789 fatal "merge parent $parent for change $d has "
790 ."git-svn uuid $paruuid, while current change "
791 ."has uuid $uuid!";
794 unless ($branchurl =~ /^$rooturl(.*)/) {
795 # This branch is very strange indeed.
796 fatal "merge parent $parent for $d is on branch "
797 ."$branchurl, which is not under the "
798 ."git-svn root $rooturl!";
805 my $rewritten_parent;
806 Git::SVN::remove_username($expect_url);
807 if (defined($_merge_info)) {
808 $_merge_info =~ tr{ }{\n};
810 while (1) {
811 my $d = shift @$linear_refs or last;
812 unless (defined $last_rev) {
813 (undef, $last_rev, undef) = cmt_metadata("$d~1");
814 unless (defined $last_rev) {
815 fatal "Unable to extract revision information ",
816 "from commit $d~1";
819 if ($_dry_run) {
820 print "diff-tree $d~1 $d\n";
821 } else {
822 my $cmt_rev;
824 unless (defined($_merge_info) || ! $push_merge_info) {
825 $_merge_info = populate_merge_info($d, $gs,
826 $uuid,
827 $linear_refs,
828 $rewritten_parent);
831 my %ed_opts = ( r => $last_rev,
832 log => get_commit_entry($d)->{log},
833 ra => Git::SVN::Ra->new($url),
834 config => SVN::Core::config_get_config(
835 $Git::SVN::Ra::config_dir
837 tree_a => "$d~1",
838 tree_b => $d,
839 editor_cb => sub {
840 print "Committed r$_[0]\n";
841 $cmt_rev = $_[0];
843 mergeinfo => $_merge_info,
844 svn_path => '');
845 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
846 print "No changes\n$d~1 == $d\n";
847 } elsif ($parents->{$d} && @{$parents->{$d}}) {
848 $gs->{inject_parents_dcommit}->{$cmt_rev} =
849 $parents->{$d};
851 $_fetch_all ? $gs->fetch_all : $gs->fetch;
852 $last_rev = $cmt_rev;
853 next if $_no_rebase;
855 # we always want to rebase against the current HEAD,
856 # not any head that was passed to us
857 my @diff = command('diff-tree', $d,
858 $gs->refname, '--');
859 my @finish;
860 if (@diff) {
861 @finish = rebase_cmd();
862 print STDERR "W: $d and ", $gs->refname,
863 " differ, using @finish:\n",
864 join("\n", @diff), "\n";
865 } else {
866 print "No changes between current HEAD and ",
867 $gs->refname,
868 "\nResetting to the latest ",
869 $gs->refname, "\n";
870 @finish = qw/reset --mixed/;
872 command_noisy(@finish, $gs->refname);
874 $rewritten_parent = command_oneline(qw/rev-parse HEAD/);
876 if (@diff) {
877 @refs = ();
878 my ($url_, $rev_, $uuid_, $gs_) =
879 working_head_info('HEAD', \@refs);
880 my ($linear_refs_, $parents_) =
881 linearize_history($gs_, \@refs);
882 if (scalar(@$linear_refs) !=
883 scalar(@$linear_refs_)) {
884 fatal "# of revisions changed ",
885 "\nbefore:\n",
886 join("\n", @$linear_refs),
887 "\n\nafter:\n",
888 join("\n", @$linear_refs_), "\n",
889 'If you are attempting to commit ',
890 "merges, try running:\n\t",
891 'git rebase --interactive',
892 '--preserve-merges ',
893 $gs->refname,
894 "\nBefore dcommitting";
896 if ($url_ ne $expect_url) {
897 if ($url_ eq $gs->metadata_url) {
898 print
899 "Accepting rewritten URL:",
900 " $url_\n";
901 } else {
902 fatal
903 "URL mismatch after rebase:",
904 " $url_ != $expect_url";
907 if ($uuid_ ne $uuid) {
908 fatal "uuid mismatch after rebase: ",
909 "$uuid_ != $uuid";
911 # remap parents
912 my (%p, @l, $i);
913 for ($i = 0; $i < scalar @$linear_refs; $i++) {
914 my $new = $linear_refs_->[$i] or next;
915 $p{$new} =
916 $parents->{$linear_refs->[$i]};
917 push @l, $new;
919 $parents = \%p;
920 $linear_refs = \@l;
925 if ($old_head) {
926 my $new_head = command_oneline(qw/rev-parse HEAD/);
927 my $new_is_symbolic = eval {
928 command_oneline(qw/symbolic-ref -q HEAD/);
930 if ($new_is_symbolic) {
931 print "dcommitted the branch ", $head, "\n";
932 } else {
933 print "dcommitted on a detached HEAD because you gave ",
934 "a revision argument.\n",
935 "The rewritten commit is: ", $new_head, "\n";
937 command(['checkout', $old_head], STDERR => 0);
940 unlink $gs->{index};
943 sub cmd_branch {
944 my ($branch_name, $head) = @_;
946 unless (defined $branch_name && length $branch_name) {
947 die(($_tag ? "tag" : "branch") . " name required\n");
949 $head ||= 'HEAD';
951 my (undef, $rev, undef, $gs) = working_head_info($head);
952 my $src = $gs->full_pushurl;
954 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
955 my $allglobs = $remote->{ $_tag ? 'tags' : 'branches' };
956 my $glob;
957 if ($#{$allglobs} == 0) {
958 $glob = $allglobs->[0];
959 } else {
960 unless(defined $_branch_dest) {
961 die "Multiple ",
962 $_tag ? "tag" : "branch",
963 " paths defined for Subversion repository.\n",
964 "You must specify where you want to create the ",
965 $_tag ? "tag" : "branch",
966 " with the --destination argument.\n";
968 foreach my $g (@{$allglobs}) {
969 # SVN::Git::Editor could probably be moved to Git.pm..
970 my $re = SVN::Git::Editor::glob2pat($g->{path}->{left});
971 if ($_branch_dest =~ /$re/) {
972 $glob = $g;
973 last;
976 unless (defined $glob) {
977 my $dest_re = qr/\b\Q$_branch_dest\E\b/;
978 foreach my $g (@{$allglobs}) {
979 $g->{path}->{left} =~ /$dest_re/ or next;
980 if (defined $glob) {
981 die "Ambiguous destination: ",
982 $_branch_dest, "\nmatches both '",
983 $glob->{path}->{left}, "' and '",
984 $g->{path}->{left}, "'\n";
986 $glob = $g;
988 unless (defined $glob) {
989 die "Unknown ",
990 $_tag ? "tag" : "branch",
991 " destination $_branch_dest\n";
995 my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
996 my $url;
997 if (defined $_commit_url) {
998 $url = $_commit_url;
999 } else {
1000 $url = eval { command_oneline('config', '--get',
1001 "svn-remote.$gs->{repo_id}.commiturl") };
1002 if (!$url) {
1003 $url = $remote->{pushurl} || $remote->{url};
1006 my $dst = join '/', $url, $lft, $branch_name, ($rgt || ());
1008 if ($dst =~ /^https:/ && $src =~ /^http:/) {
1009 $src=~s/^http:/https:/;
1012 ::_req_svn();
1014 my $ctx = SVN::Client->new(
1015 auth => Git::SVN::Ra::_auth_providers(),
1016 log_msg => sub {
1017 ${ $_[0] } = defined $_message
1018 ? $_message
1019 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
1020 . $branch_name;
1024 eval {
1025 $ctx->ls($dst, 'HEAD', 0);
1026 } and die "branch ${branch_name} already exists\n";
1028 print "Copying ${src} at r${rev} to ${dst}...\n";
1029 $ctx->copy($src, $rev, $dst)
1030 unless $_dry_run;
1032 $gs->fetch_all;
1035 sub cmd_find_rev {
1036 my $revision_or_hash = shift or die "SVN or git revision required ",
1037 "as a command-line argument\n";
1038 my $result;
1039 if ($revision_or_hash =~ /^r\d+$/) {
1040 my $head = shift;
1041 $head ||= 'HEAD';
1042 my @refs;
1043 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
1044 unless ($gs) {
1045 die "Unable to determine upstream SVN information from ",
1046 "$head history\n";
1048 my $desired_revision = substr($revision_or_hash, 1);
1049 $result = $gs->rev_map_get($desired_revision, $uuid);
1050 } else {
1051 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
1052 $result = $rev;
1054 print "$result\n" if $result;
1057 sub auto_create_empty_directories {
1058 my ($gs) = @_;
1059 my $var = eval { command_oneline('config', '--get', '--bool',
1060 "svn-remote.$gs->{repo_id}.automkdirs") };
1061 # By default, create empty directories by consulting the unhandled log,
1062 # but allow setting it to 'false' to skip it.
1063 return !($var && $var eq 'false');
1066 sub cmd_rebase {
1067 command_noisy(qw/update-index --refresh/);
1068 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1069 unless ($gs) {
1070 die "Unable to determine upstream SVN information from ",
1071 "working tree history\n";
1073 if ($_dry_run) {
1074 print "Remote Branch: " . $gs->refname . "\n";
1075 print "SVN URL: " . $url . "\n";
1076 return;
1078 if (command(qw/diff-index HEAD --/)) {
1079 print STDERR "Cannot rebase with uncommited changes:\n";
1080 command_noisy('status');
1081 exit 1;
1083 unless ($_local) {
1084 # rebase will checkout for us, so no need to do it explicitly
1085 $_no_checkout = 'true';
1086 $_fetch_all ? $gs->fetch_all : $gs->fetch;
1088 command_noisy(rebase_cmd(), $gs->refname);
1089 if (auto_create_empty_directories($gs)) {
1090 $gs->mkemptydirs;
1094 sub cmd_show_ignore {
1095 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1096 $gs ||= Git::SVN->new;
1097 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1098 $gs->prop_walk($gs->{path}, $r, sub {
1099 my ($gs, $path, $props) = @_;
1100 print STDOUT "\n# $path\n";
1101 my $s = $props->{'svn:ignore'} or return;
1102 $s =~ s/[\r\n]+/\n/g;
1103 $s =~ s/^\n+//;
1104 chomp $s;
1105 $s =~ s#^#$path#gm;
1106 print STDOUT "$s\n";
1110 sub cmd_show_externals {
1111 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1112 $gs ||= Git::SVN->new;
1113 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1114 $gs->prop_walk($gs->{path}, $r, sub {
1115 my ($gs, $path, $props) = @_;
1116 print STDOUT "\n# $path\n";
1117 my $s = $props->{'svn:externals'} or return;
1118 $s =~ s/[\r\n]+/\n/g;
1119 chomp $s;
1120 $s =~ s#^#$path#gm;
1121 print STDOUT "$s\n";
1125 sub cmd_create_ignore {
1126 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1127 $gs ||= Git::SVN->new;
1128 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1129 $gs->prop_walk($gs->{path}, $r, sub {
1130 my ($gs, $path, $props) = @_;
1131 # $path is of the form /path/to/dir/
1132 $path = '.' . $path;
1133 # SVN can have attributes on empty directories,
1134 # which git won't track
1135 mkpath([$path]) unless -d $path;
1136 my $ignore = $path . '.gitignore';
1137 my $s = $props->{'svn:ignore'} or return;
1138 open(GITIGNORE, '>', $ignore)
1139 or fatal("Failed to open `$ignore' for writing: $!");
1140 $s =~ s/[\r\n]+/\n/g;
1141 $s =~ s/^\n+//;
1142 chomp $s;
1143 # Prefix all patterns so that the ignore doesn't apply
1144 # to sub-directories.
1145 $s =~ s#^#/#gm;
1146 print GITIGNORE "$s\n";
1147 close(GITIGNORE)
1148 or fatal("Failed to close `$ignore': $!");
1149 command_noisy('add', '-f', $ignore);
1153 sub cmd_mkdirs {
1154 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1155 $gs ||= Git::SVN->new;
1156 $gs->mkemptydirs($_revision);
1159 sub canonicalize_path {
1160 my ($path) = @_;
1161 my $dot_slash_added = 0;
1162 if (substr($path, 0, 1) ne "/") {
1163 $path = "./" . $path;
1164 $dot_slash_added = 1;
1166 # File::Spec->canonpath doesn't collapse x/../y into y (for a
1167 # good reason), so let's do this manually.
1168 $path =~ s#/+#/#g;
1169 $path =~ s#/\.(?:/|$)#/#g;
1170 $path =~ s#/[^/]+/\.\.##g;
1171 $path =~ s#/$##g;
1172 $path =~ s#^\./## if $dot_slash_added;
1173 $path =~ s#^/##;
1174 $path =~ s#^\.$##;
1175 return $path;
1178 sub canonicalize_url {
1179 my ($url) = @_;
1180 $url =~ s#^([^:]+://[^/]*/)(.*)$#$1 . canonicalize_path($2)#e;
1181 return $url;
1184 # get_svnprops(PATH)
1185 # ------------------
1186 # Helper for cmd_propget and cmd_proplist below.
1187 sub get_svnprops {
1188 my $path = shift;
1189 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1190 $gs ||= Git::SVN->new;
1192 # prefix THE PATH by the sub-directory from which the user
1193 # invoked us.
1194 $path = $cmd_dir_prefix . $path;
1195 fatal("No such file or directory: $path") unless -e $path;
1196 my $is_dir = -d $path ? 1 : 0;
1197 $path = $gs->{path} . '/' . $path;
1199 # canonicalize the path (otherwise libsvn will abort or fail to
1200 # find the file)
1201 $path = canonicalize_path($path);
1203 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1204 my $props;
1205 if ($is_dir) {
1206 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
1208 else {
1209 (undef, $props) = $gs->ra->get_file($path, $r, undef);
1211 return $props;
1214 # cmd_propget (PROP, PATH)
1215 # ------------------------
1216 # Print the SVN property PROP for PATH.
1217 sub cmd_propget {
1218 my ($prop, $path) = @_;
1219 $path = '.' if not defined $path;
1220 usage(1) if not defined $prop;
1221 my $props = get_svnprops($path);
1222 if (not defined $props->{$prop}) {
1223 fatal("`$path' does not have a `$prop' SVN property.");
1225 print $props->{$prop} . "\n";
1228 # cmd_proplist (PATH)
1229 # -------------------
1230 # Print the list of SVN properties for PATH.
1231 sub cmd_proplist {
1232 my $path = shift;
1233 $path = '.' if not defined $path;
1234 my $props = get_svnprops($path);
1235 print "Properties on '$path':\n";
1236 foreach (sort keys %{$props}) {
1237 print " $_\n";
1241 sub cmd_multi_init {
1242 my $url = shift;
1243 unless (defined $_trunk || @_branches || @_tags) {
1244 usage(1);
1247 $_prefix = '' unless defined $_prefix;
1248 if (defined $url) {
1249 $url = canonicalize_url($url);
1250 init_subdir(@_);
1252 do_git_init_db();
1253 if (defined $_trunk) {
1254 $_trunk =~ s#^/+##;
1255 my $trunk_ref = 'refs/remotes/' . $_prefix . 'trunk';
1256 # try both old-style and new-style lookups:
1257 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
1258 unless ($gs_trunk) {
1259 my ($trunk_url, $trunk_path) =
1260 complete_svn_url($url, $_trunk);
1261 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
1262 undef, $trunk_ref);
1265 return unless @_branches || @_tags;
1266 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
1267 foreach my $path (@_branches) {
1268 complete_url_ls_init($ra, $path, '--branches/-b', $_prefix);
1270 foreach my $path (@_tags) {
1271 complete_url_ls_init($ra, $path, '--tags/-t', $_prefix.'tags/');
1275 sub cmd_multi_fetch {
1276 $Git::SVN::no_reuse_existing = undef;
1277 my $remotes = Git::SVN::read_all_remotes();
1278 foreach my $repo_id (sort keys %$remotes) {
1279 if ($remotes->{$repo_id}->{url}) {
1280 Git::SVN::fetch_all($repo_id, $remotes);
1285 # this command is special because it requires no metadata
1286 sub cmd_commit_diff {
1287 my ($ta, $tb, $url) = @_;
1288 my $usage = "Usage: $0 commit-diff -r<revision> ".
1289 "<tree-ish> <tree-ish> [<URL>]";
1290 fatal($usage) if (!defined $ta || !defined $tb);
1291 my $svn_path = '';
1292 if (!defined $url) {
1293 my $gs = eval { Git::SVN->new };
1294 if (!$gs) {
1295 fatal("Needed URL or usable git-svn --id in ",
1296 "the command-line\n", $usage);
1298 $url = $gs->{url};
1299 $svn_path = $gs->{path};
1301 unless (defined $_revision) {
1302 fatal("-r|--revision is a required argument\n", $usage);
1304 if (defined $_message && defined $_file) {
1305 fatal("Both --message/-m and --file/-F specified ",
1306 "for the commit message.\n",
1307 "I have no idea what you mean");
1309 if (defined $_file) {
1310 $_message = file_to_s($_file);
1311 } else {
1312 $_message ||= get_commit_entry($tb)->{log};
1314 my $ra ||= Git::SVN::Ra->new($url);
1315 my $r = $_revision;
1316 if ($r eq 'HEAD') {
1317 $r = $ra->get_latest_revnum;
1318 } elsif ($r !~ /^\d+$/) {
1319 die "revision argument: $r not understood by git-svn\n";
1321 my %ed_opts = ( r => $r,
1322 log => $_message,
1323 ra => $ra,
1324 tree_a => $ta,
1325 tree_b => $tb,
1326 editor_cb => sub { print "Committed r$_[0]\n" },
1327 svn_path => $svn_path );
1328 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
1329 print "No changes\n$ta == $tb\n";
1333 sub escape_uri_only {
1334 my ($uri) = @_;
1335 my @tmp;
1336 foreach (split m{/}, $uri) {
1337 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
1338 push @tmp, $_;
1340 join('/', @tmp);
1343 sub escape_url {
1344 my ($url) = @_;
1345 if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
1346 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
1347 $url = "$scheme://$domain$uri";
1349 $url;
1352 sub cmd_info {
1353 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
1354 my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
1355 if (exists $_[1]) {
1356 die "Too many arguments specified\n";
1359 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
1361 if (!$file_type && !$diff_status) {
1362 print STDERR "svn: '$path' is not under version control\n";
1363 exit 1;
1366 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1367 unless ($gs) {
1368 die "Unable to determine upstream SVN information from ",
1369 "working tree history\n";
1372 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
1373 $path = "." if $path eq "";
1375 my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
1377 if ($_url) {
1378 print escape_url($full_url), "\n";
1379 return;
1382 my $result = "Path: $path\n";
1383 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
1384 $result .= "URL: " . escape_url($full_url) . "\n";
1386 eval {
1387 my $repos_root = $gs->repos_root;
1388 Git::SVN::remove_username($repos_root);
1389 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
1391 if ($@) {
1392 $result .= "Repository Root: (offline)\n";
1394 ::_req_svn();
1395 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
1396 ($SVN::Core::VERSION le '1.5.4' || $file_type ne "dir");
1397 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
1399 $result .= "Node Kind: " .
1400 ($file_type eq "dir" ? "directory" : "file") . "\n";
1402 my $schedule = $diff_status eq "A"
1403 ? "add"
1404 : ($diff_status eq "D" ? "delete" : "normal");
1405 $result .= "Schedule: $schedule\n";
1407 if ($diff_status eq "A") {
1408 print $result, "\n";
1409 return;
1412 my ($lc_author, $lc_rev, $lc_date_utc);
1413 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
1414 my $log = command_output_pipe(@args);
1415 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
1416 while (<$log>) {
1417 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
1418 $lc_author = $1;
1419 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
1420 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
1421 (undef, $lc_rev, undef) = ::extract_metadata($1);
1424 close $log;
1426 Git::SVN::Log::set_local_timezone();
1428 $result .= "Last Changed Author: $lc_author\n";
1429 $result .= "Last Changed Rev: $lc_rev\n";
1430 $result .= "Last Changed Date: " .
1431 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
1433 if ($file_type ne "dir") {
1434 my $text_last_updated_date =
1435 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
1436 $result .=
1437 "Text Last Updated: " .
1438 Git::SVN::Log::format_svn_date($text_last_updated_date) .
1439 "\n";
1440 my $checksum;
1441 if ($diff_status eq "D") {
1442 my ($fh, $ctx) =
1443 command_output_pipe(qw(cat-file blob), "HEAD:$path");
1444 if ($file_type eq "link") {
1445 my $file_name = <$fh>;
1446 $checksum = md5sum("link $file_name");
1447 } else {
1448 $checksum = md5sum($fh);
1450 command_close_pipe($fh, $ctx);
1451 } elsif ($file_type eq "link") {
1452 my $file_name =
1453 command(qw(cat-file blob), "HEAD:$path");
1454 $checksum =
1455 md5sum("link " . $file_name);
1456 } else {
1457 open FILE, "<", $path or die $!;
1458 $checksum = md5sum(\*FILE);
1459 close FILE or die $!;
1461 $result .= "Checksum: " . $checksum . "\n";
1464 print $result, "\n";
1467 sub cmd_reset {
1468 my $target = shift || $_revision or die "SVN revision required\n";
1469 $target = $1 if $target =~ /^r(\d+)$/;
1470 $target =~ /^\d+$/ or die "Numeric SVN revision expected\n";
1471 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1472 unless ($gs) {
1473 die "Unable to determine upstream SVN information from ".
1474 "history\n";
1476 my ($r, $c) = $gs->find_rev_before($target, not $_fetch_parent);
1477 die "Cannot find SVN revision $target\n" unless defined($c);
1478 $gs->rev_map_set($r, $c, 'reset', $uuid);
1479 print "r$r = $c ($gs->{ref_id})\n";
1482 sub cmd_gc {
1483 if (!$can_compress) {
1484 warn "Compress::Zlib could not be found; unhandled.log " .
1485 "files will not be compressed.\n";
1487 find({ wanted => \&gc_directory, no_chdir => 1}, "$ENV{GIT_DIR}/svn");
1490 ########################### utility functions #########################
1492 sub rebase_cmd {
1493 my @cmd = qw/rebase/;
1494 push @cmd, '-v' if $_verbose;
1495 push @cmd, qw/--merge/ if $_merge;
1496 push @cmd, "--strategy=$_strategy" if $_strategy;
1497 @cmd;
1500 sub post_fetch_checkout {
1501 return if $_no_checkout;
1502 my $gs = $Git::SVN::_head or return;
1503 return if verify_ref('refs/heads/master^0');
1505 # look for "trunk" ref if it exists
1506 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
1507 my $fetch = $remote->{fetch};
1508 if ($fetch) {
1509 foreach my $p (keys %$fetch) {
1510 basename($fetch->{$p}) eq 'trunk' or next;
1511 $gs = Git::SVN->new($fetch->{$p}, $gs->{repo_id}, $p);
1512 last;
1516 my $valid_head = verify_ref('HEAD^0');
1517 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1518 return if ($valid_head || !verify_ref('HEAD^0'));
1520 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1521 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1522 return if -f $index;
1524 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1525 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1526 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1527 print STDERR "Checked out HEAD:\n ",
1528 $gs->full_url, " r", $gs->last_rev, "\n";
1529 if (auto_create_empty_directories($gs)) {
1530 $gs->mkemptydirs($gs->last_rev);
1534 sub complete_svn_url {
1535 my ($url, $path) = @_;
1536 $path =~ s#/+$##;
1537 if ($path !~ m#^[a-z\+]+://#) {
1538 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1539 fatal("E: '$path' is not a complete URL ",
1540 "and a separate URL is not specified");
1542 return ($url, $path);
1544 return ($path, '');
1547 sub complete_url_ls_init {
1548 my ($ra, $repo_path, $switch, $pfx) = @_;
1549 unless ($repo_path) {
1550 print STDERR "W: $switch not specified\n";
1551 return;
1553 $repo_path =~ s#/+$##;
1554 if ($repo_path =~ m#^[a-z\+]+://#) {
1555 $ra = Git::SVN::Ra->new($repo_path);
1556 $repo_path = '';
1557 } else {
1558 $repo_path =~ s#^/+##;
1559 unless ($ra) {
1560 fatal("E: '$repo_path' is not a complete URL ",
1561 "and a separate URL is not specified");
1564 my $url = $ra->{url};
1565 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1566 my $k = "svn-remote.$gs->{repo_id}.url";
1567 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1568 if ($orig_url && ($orig_url ne $gs->{url})) {
1569 die "$k already set: $orig_url\n",
1570 "wanted to set to: $gs->{url}\n";
1572 command_oneline('config', $k, $gs->{url}) unless $orig_url;
1573 my $remote_path = "$gs->{path}/$repo_path";
1574 $remote_path =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
1575 $remote_path =~ s#/+#/#g;
1576 $remote_path =~ s#^/##g;
1577 $remote_path .= "/*" if $remote_path !~ /\*/;
1578 my ($n) = ($switch =~ /^--(\w+)/);
1579 if (length $pfx && $pfx !~ m#/$#) {
1580 die "--prefix='$pfx' must have a trailing slash '/'\n";
1582 command_noisy('config',
1583 '--add',
1584 "svn-remote.$gs->{repo_id}.$n",
1585 "$remote_path:refs/remotes/$pfx*" .
1586 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1589 sub verify_ref {
1590 my ($ref) = @_;
1591 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1592 { STDERR => 0 }); };
1595 sub get_tree_from_treeish {
1596 my ($treeish) = @_;
1597 # $treeish can be a symbolic ref, too:
1598 my $type = command_oneline(qw/cat-file -t/, $treeish);
1599 my $expected;
1600 while ($type eq 'tag') {
1601 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1603 if ($type eq 'commit') {
1604 $expected = (grep /^tree /, command(qw/cat-file commit/,
1605 $treeish))[0];
1606 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1607 die "Unable to get tree from $treeish\n" unless $expected;
1608 } elsif ($type eq 'tree') {
1609 $expected = $treeish;
1610 } else {
1611 die "$treeish is a $type, expected tree, tag or commit\n";
1613 return $expected;
1616 sub get_commit_entry {
1617 my ($treeish) = shift;
1618 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1619 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1620 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1621 open my $log_fh, '>', $commit_editmsg or croak $!;
1623 my $type = command_oneline(qw/cat-file -t/, $treeish);
1624 if ($type eq 'commit' || $type eq 'tag') {
1625 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1626 $type, $treeish);
1627 my $in_msg = 0;
1628 my $author;
1629 my $saw_from = 0;
1630 my $msgbuf = "";
1631 while (<$msg_fh>) {
1632 if (!$in_msg) {
1633 $in_msg = 1 if (/^\s*$/);
1634 $author = $1 if (/^author (.*>)/);
1635 } elsif (/^git-svn-id: /) {
1636 # skip this for now, we regenerate the
1637 # correct one on re-fetch anyways
1638 # TODO: set *:merge properties or like...
1639 } else {
1640 if (/^From:/ || /^Signed-off-by:/) {
1641 $saw_from = 1;
1643 $msgbuf .= $_;
1646 $msgbuf =~ s/\s+$//s;
1647 if ($Git::SVN::_add_author_from && defined($author)
1648 && !$saw_from) {
1649 $msgbuf .= "\n\nFrom: $author";
1651 print $log_fh $msgbuf or croak $!;
1652 command_close_pipe($msg_fh, $ctx);
1654 close $log_fh or croak $!;
1656 if ($_edit || ($type eq 'tree')) {
1657 chomp(my $editor = command_oneline(qw(var GIT_EDITOR)));
1658 system('sh', '-c', $editor.' "$@"', $editor, $commit_editmsg);
1660 rename $commit_editmsg, $commit_msg or croak $!;
1662 require Encode;
1663 # SVN requires messages to be UTF-8 when entering the repo
1664 local $/;
1665 open $log_fh, '<', $commit_msg or croak $!;
1666 binmode $log_fh;
1667 chomp($log_entry{log} = <$log_fh>);
1669 my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
1670 my $msg = $log_entry{log};
1672 eval { $msg = Encode::decode($enc, $msg, 1) };
1673 if ($@) {
1674 die "Could not decode as $enc:\n", $msg,
1675 "\nPerhaps you need to set i18n.commitencoding\n";
1678 eval { $msg = Encode::encode('UTF-8', $msg, 1) };
1679 die "Could not encode as UTF-8:\n$msg\n" if $@;
1681 $log_entry{log} = $msg;
1683 close $log_fh or croak $!;
1685 unlink $commit_msg;
1686 \%log_entry;
1689 sub s_to_file {
1690 my ($str, $file, $mode) = @_;
1691 open my $fd,'>',$file or croak $!;
1692 print $fd $str,"\n" or croak $!;
1693 close $fd or croak $!;
1694 chmod ($mode &~ umask, $file) if (defined $mode);
1697 sub file_to_s {
1698 my $file = shift;
1699 open my $fd,'<',$file or croak "$!: file: $file\n";
1700 local $/;
1701 my $ret = <$fd>;
1702 close $fd or croak $!;
1703 $ret =~ s/\s*$//s;
1704 return $ret;
1707 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1708 sub load_authors {
1709 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1710 my $log = $cmd eq 'log';
1711 while (<$authors>) {
1712 chomp;
1713 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1714 my ($user, $name, $email) = ($1, $2, $3);
1715 if ($log) {
1716 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1717 } else {
1718 $users{$user} = [$name, $email];
1721 close $authors or croak $!;
1724 # convert GetOpt::Long specs for use by git-config
1725 sub read_git_config {
1726 my $opts = shift;
1727 my @config_only;
1728 foreach my $o (keys %$opts) {
1729 # if we have mixedCase and a long option-only, then
1730 # it's a config-only variable that we don't need for
1731 # the command-line.
1732 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1733 my $v = $opts->{$o};
1734 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1735 $key =~ s/-//g;
1736 my $arg = 'git config';
1737 $arg .= ' --int' if ($o =~ /[:=]i$/);
1738 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1739 if (ref $v eq 'ARRAY') {
1740 chomp(my @tmp = `$arg --get-all svn.$key`);
1741 @$v = @tmp if @tmp;
1742 } else {
1743 chomp(my $tmp = `$arg --get svn.$key`);
1744 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1745 $$v = $tmp;
1749 delete @$opts{@config_only} if @config_only;
1752 sub extract_metadata {
1753 my $id = shift or return (undef, undef, undef);
1754 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1755 \s([a-f\d\-]+)$/ix);
1756 if (!defined $rev || !$uuid || !$url) {
1757 # some of the original repositories I made had
1758 # identifiers like this:
1759 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/i);
1761 return ($url, $rev, $uuid);
1764 sub cmt_metadata {
1765 return extract_metadata((grep(/^git-svn-id: /,
1766 command(qw/cat-file commit/, shift)))[-1]);
1769 sub cmt_sha2rev_batch {
1770 my %s2r;
1771 my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1772 my $list = shift;
1774 foreach my $sha (@{$list}) {
1775 my $first = 1;
1776 my $size = 0;
1777 print $out $sha, "\n";
1779 while (my $line = <$in>) {
1780 if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1781 last;
1782 } elsif ($first &&
1783 $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1784 $first = 0;
1785 $size = $1;
1786 next;
1787 } elsif ($line =~ /^(git-svn-id: )/) {
1788 my (undef, $rev, undef) =
1789 extract_metadata($line);
1790 $s2r{$sha} = $rev;
1793 $size -= length($line);
1794 last if ($size == 0);
1798 command_close_bidi_pipe($pid, $in, $out, $ctx);
1800 return \%s2r;
1803 sub working_head_info {
1804 my ($head, $refs) = @_;
1805 my @args = qw/log --no-color --no-decorate --first-parent
1806 --pretty=medium/;
1807 my ($fh, $ctx) = command_output_pipe(@args, $head);
1808 my $hash;
1809 my %max;
1810 while (<$fh>) {
1811 if ( m{^commit ($::sha1)$} ) {
1812 unshift @$refs, $hash if $hash and $refs;
1813 $hash = $1;
1814 next;
1816 next unless s{^\s*(git-svn-id:)}{$1};
1817 my ($url, $rev, $uuid) = extract_metadata($_);
1818 if (defined $url && defined $rev) {
1819 next if $max{$url} and $max{$url} < $rev;
1820 if (my $gs = Git::SVN->find_by_url($url)) {
1821 my $c = $gs->rev_map_get($rev, $uuid);
1822 if ($c && $c eq $hash) {
1823 close $fh; # break the pipe
1824 return ($url, $rev, $uuid, $gs);
1825 } else {
1826 $max{$url} ||= $gs->rev_map_max;
1831 command_close_pipe($fh, $ctx);
1832 (undef, undef, undef, undef);
1835 sub read_commit_parents {
1836 my ($parents, $c) = @_;
1837 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1838 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1839 @{$parents->{$c}} = split(/ /, $p);
1842 sub linearize_history {
1843 my ($gs, $refs) = @_;
1844 my %parents;
1845 foreach my $c (@$refs) {
1846 read_commit_parents(\%parents, $c);
1849 my @linear_refs;
1850 my %skip = ();
1851 my $last_svn_commit = $gs->last_commit;
1852 foreach my $c (reverse @$refs) {
1853 next if $c eq $last_svn_commit;
1854 last if $skip{$c};
1856 unshift @linear_refs, $c;
1857 $skip{$c} = 1;
1859 # we only want the first parent to diff against for linear
1860 # history, we save the rest to inject when we finalize the
1861 # svn commit
1862 my $fp_a = verify_ref("$c~1");
1863 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1864 if (!$fp_a || !$fp_b) {
1865 die "Commit $c\n",
1866 "has no parent commit, and therefore ",
1867 "nothing to diff against.\n",
1868 "You should be working from a repository ",
1869 "originally created by git-svn\n";
1871 if ($fp_a ne $fp_b) {
1872 die "$c~1 = $fp_a, however parsing commit $c ",
1873 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1876 foreach my $p (@{$parents{$c}}) {
1877 $skip{$p} = 1;
1880 (\@linear_refs, \%parents);
1883 sub find_file_type_and_diff_status {
1884 my ($path) = @_;
1885 return ('dir', '') if $path eq '';
1887 my $diff_output =
1888 command_oneline(qw(diff --cached --name-status --), $path) || "";
1889 my $diff_status = (split(' ', $diff_output))[0] || "";
1891 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1893 return (undef, undef) if !$diff_status && !$ls_tree;
1895 if ($diff_status eq "A") {
1896 return ("link", $diff_status) if -l $path;
1897 return ("dir", $diff_status) if -d $path;
1898 return ("file", $diff_status);
1901 my $mode = (split(' ', $ls_tree))[0] || "";
1903 return ("link", $diff_status) if $mode eq "120000";
1904 return ("dir", $diff_status) if $mode eq "040000";
1905 return ("file", $diff_status);
1908 sub md5sum {
1909 my $arg = shift;
1910 my $ref = ref $arg;
1911 my $md5 = Digest::MD5->new();
1912 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
1913 $md5->addfile($arg) or croak $!;
1914 } elsif ($ref eq 'SCALAR') {
1915 $md5->add($$arg) or croak $!;
1916 } elsif (!$ref) {
1917 $md5->add($arg) or croak $!;
1918 } else {
1919 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1921 return $md5->hexdigest();
1924 sub gc_directory {
1925 if ($can_compress && -f $_ && basename($_) eq "unhandled.log") {
1926 my $out_filename = $_ . ".gz";
1927 open my $in_fh, "<", $_ or die "Unable to open $_: $!\n";
1928 binmode $in_fh;
1929 my $gz = Compress::Zlib::gzopen($out_filename, "ab") or
1930 die "Unable to open $out_filename: $!\n";
1932 my $res;
1933 while ($res = sysread($in_fh, my $str, 1024)) {
1934 $gz->gzwrite($str) or
1935 die "Unable to write: ".$gz->gzerror()."!\n";
1937 unlink $_ or die "unlink $File::Find::name: $!\n";
1938 } elsif (-f $_ && basename($_) eq "index") {
1939 unlink $_ or die "unlink $_: $!\n";
1943 package Git::SVN;
1944 use strict;
1945 use warnings;
1946 use Fcntl qw/:DEFAULT :seek/;
1947 use constant rev_map_fmt => 'NH40';
1948 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1949 $_repack $_repack_flags $_use_svm_props $_head
1950 $_use_svnsync_props $no_reuse_existing $_minimize_url
1951 $_use_log_author $_add_author_from $_localtime/;
1952 use Carp qw/croak/;
1953 use File::Path qw/mkpath/;
1954 use File::Copy qw/copy/;
1955 use IPC::Open3;
1956 use Memoize; # core since 5.8.0, Jul 2002
1957 use Memoize::Storable;
1959 my ($_gc_nr, $_gc_period);
1961 # properties that we do not log:
1962 my %SKIP_PROP;
1963 BEGIN {
1964 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1965 svn:special svn:executable
1966 svn:entry:committed-rev
1967 svn:entry:last-author
1968 svn:entry:uuid
1969 svn:entry:committed-date/;
1971 # some options are read globally, but can be overridden locally
1972 # per [svn-remote "..."] section. Command-line options will *NOT*
1973 # override options set in an [svn-remote "..."] section
1974 no strict 'refs';
1975 for my $option (qw/follow_parent no_metadata use_svm_props
1976 use_svnsync_props/) {
1977 my $key = $option;
1978 $key =~ tr/_//d;
1979 my $prop = "-$option";
1980 *$option = sub {
1981 my ($self) = @_;
1982 return $self->{$prop} if exists $self->{$prop};
1983 my $k = "svn-remote.$self->{repo_id}.$key";
1984 eval { command_oneline(qw/config --get/, $k) };
1985 if ($@) {
1986 $self->{$prop} = ${"Git::SVN::_$option"};
1987 } else {
1988 my $v = command_oneline(qw/config --bool/,$k);
1989 $self->{$prop} = $v eq 'false' ? 0 : 1;
1991 return $self->{$prop};
1997 my (%LOCKFILES, %INDEX_FILES);
1998 END {
1999 unlink keys %LOCKFILES if %LOCKFILES;
2000 unlink keys %INDEX_FILES if %INDEX_FILES;
2003 sub resolve_local_globs {
2004 my ($url, $fetch, $glob_spec) = @_;
2005 return unless defined $glob_spec;
2006 my $ref = $glob_spec->{ref};
2007 my $path = $glob_spec->{path};
2008 foreach (command(qw#for-each-ref --format=%(refname) refs/#)) {
2009 next unless m#^$ref->{regex}$#;
2010 my $p = $1;
2011 my $pathname = desanitize_refname($path->full_path($p));
2012 my $refname = desanitize_refname($ref->full_path($p));
2013 if (my $existing = $fetch->{$pathname}) {
2014 if ($existing ne $refname) {
2015 die "Refspec conflict:\n",
2016 "existing: $existing\n",
2017 " globbed: $refname\n";
2019 my $u = (::cmt_metadata("$refname"))[0];
2020 $u =~ s!^\Q$url\E(/|$)!! or die
2021 "$refname: '$url' not found in '$u'\n";
2022 if ($pathname ne $u) {
2023 warn "W: Refspec glob conflict ",
2024 "(ref: $refname):\n",
2025 "expected path: $pathname\n",
2026 " real path: $u\n",
2027 "Continuing ahead with $u\n";
2028 next;
2030 } else {
2031 $fetch->{$pathname} = $refname;
2036 sub parse_revision_argument {
2037 my ($base, $head) = @_;
2038 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
2039 return ($base, $head);
2041 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
2042 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
2043 return ($head, $head) if ($::_revision eq 'HEAD');
2044 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
2045 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
2046 die "revision argument: $::_revision not understood by git-svn\n";
2049 sub fetch_all {
2050 my ($repo_id, $remotes) = @_;
2051 if (ref $repo_id) {
2052 my $gs = $repo_id;
2053 $repo_id = undef;
2054 $repo_id = $gs->{repo_id};
2056 $remotes ||= read_all_remotes();
2057 my $remote = $remotes->{$repo_id} or
2058 die "[svn-remote \"$repo_id\"] unknown\n";
2059 my $fetch = $remote->{fetch};
2060 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
2061 my (@gs, @globs);
2062 my $ra = Git::SVN::Ra->new($url);
2063 my $uuid = $ra->get_uuid;
2064 my $head = $ra->get_latest_revnum;
2066 # ignore errors, $head revision may not even exist anymore
2067 eval { $ra->get_log("", $head, 0, 1, 0, 1, sub { $head = $_[1] }) };
2068 warn "W: $@\n" if $@;
2070 my $base = defined $fetch ? $head : 0;
2072 # read the max revs for wildcard expansion (branches/*, tags/*)
2073 foreach my $t (qw/branches tags/) {
2074 defined $remote->{$t} or next;
2075 push @globs, @{$remote->{$t}};
2077 my $max_rev = eval { tmp_config(qw/--int --get/,
2078 "svn-remote.$repo_id.${t}-maxRev") };
2079 if (defined $max_rev && ($max_rev < $base)) {
2080 $base = $max_rev;
2081 } elsif (!defined $max_rev) {
2082 $base = 0;
2086 if ($fetch) {
2087 foreach my $p (sort keys %$fetch) {
2088 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
2089 my $lr = $gs->rev_map_max;
2090 if (defined $lr) {
2091 $base = $lr if ($lr < $base);
2093 push @gs, $gs;
2097 ($base, $head) = parse_revision_argument($base, $head);
2098 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
2101 sub read_all_remotes {
2102 my $r = {};
2103 my $use_svm_props = eval { command_oneline(qw/config --bool
2104 svn.useSvmProps/) };
2105 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
2106 my $svn_refspec = qr{\s*(.*?)\s*:\s*(.+?)\s*};
2107 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
2108 if (m!^(.+)\.fetch=$svn_refspec$!) {
2109 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
2110 die("svn-remote.$remote: remote ref '$remote_ref' "
2111 . "must start with 'refs/'\n")
2112 unless $remote_ref =~ m{^refs/};
2113 $local_ref = uri_decode($local_ref);
2114 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
2115 $r->{$remote}->{svm} = {} if $use_svm_props;
2116 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
2117 $r->{$1}->{svm} = {};
2118 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
2119 $r->{$1}->{url} = $2;
2120 } elsif (m!^(.+)\.pushurl=\s*(.*)\s*$!) {
2121 $r->{$1}->{pushurl} = $2;
2122 } elsif (m!^(.+)\.(branches|tags)=$svn_refspec$!) {
2123 my ($remote, $t, $local_ref, $remote_ref) =
2124 ($1, $2, $3, $4);
2125 die("svn-remote.$remote: remote ref '$remote_ref' ($t) "
2126 . "must start with 'refs/'\n")
2127 unless $remote_ref =~ m{^refs/};
2128 $local_ref = uri_decode($local_ref);
2129 my $rs = {
2130 t => $t,
2131 remote => $remote,
2132 path => Git::SVN::GlobSpec->new($local_ref, 1),
2133 ref => Git::SVN::GlobSpec->new($remote_ref, 0) };
2134 if (length($rs->{ref}->{right}) != 0) {
2135 die "The '*' glob character must be the last ",
2136 "character of '$remote_ref'\n";
2138 push @{ $r->{$remote}->{$t} }, $rs;
2142 map {
2143 if (defined $r->{$_}->{svm}) {
2144 my $svm;
2145 eval {
2146 my $section = "svn-remote.$_";
2147 $svm = {
2148 source => tmp_config('--get',
2149 "$section.svm-source"),
2150 replace => tmp_config('--get',
2151 "$section.svm-replace"),
2154 $r->{$_}->{svm} = $svm;
2156 } keys %$r;
2161 sub init_vars {
2162 $_gc_nr = $_gc_period = 1000;
2163 if (defined $_repack || defined $_repack_flags) {
2164 warn "Repack options are obsolete; they have no effect.\n";
2168 sub verify_remotes_sanity {
2169 return unless -d $ENV{GIT_DIR};
2170 my %seen;
2171 foreach (command(qw/config -l/)) {
2172 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
2173 if ($seen{$1}) {
2174 die "Remote ref refs/remote/$1 is tracked by",
2175 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
2176 "Please resolve this ambiguity in ",
2177 "your git configuration file before ",
2178 "continuing\n";
2180 $seen{$1} = $_;
2185 sub find_existing_remote {
2186 my ($url, $remotes) = @_;
2187 return undef if $no_reuse_existing;
2188 my $existing;
2189 foreach my $repo_id (keys %$remotes) {
2190 my $u = $remotes->{$repo_id}->{url} or next;
2191 next if $u ne $url;
2192 $existing = $repo_id;
2193 last;
2195 $existing;
2198 sub init_remote_config {
2199 my ($self, $url, $no_write) = @_;
2200 $url =~ s!/+$!!; # strip trailing slash
2201 my $r = read_all_remotes();
2202 my $existing = find_existing_remote($url, $r);
2203 if ($existing) {
2204 unless ($no_write) {
2205 print STDERR "Using existing ",
2206 "[svn-remote \"$existing\"]\n";
2208 $self->{repo_id} = $existing;
2209 } elsif ($_minimize_url) {
2210 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
2211 $existing = find_existing_remote($min_url, $r);
2212 if ($existing) {
2213 unless ($no_write) {
2214 print STDERR "Using existing ",
2215 "[svn-remote \"$existing\"]\n";
2217 $self->{repo_id} = $existing;
2219 if ($min_url ne $url) {
2220 unless ($no_write) {
2221 print STDERR "Using higher level of URL: ",
2222 "$url => $min_url\n";
2224 my $old_path = $self->{path};
2225 $self->{path} = $url;
2226 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
2227 if (length $old_path) {
2228 $self->{path} .= "/$old_path";
2230 $url = $min_url;
2233 my $orig_url;
2234 if (!$existing) {
2235 # verify that we aren't overwriting anything:
2236 $orig_url = eval {
2237 command_oneline('config', '--get',
2238 "svn-remote.$self->{repo_id}.url")
2240 if ($orig_url && ($orig_url ne $url)) {
2241 die "svn-remote.$self->{repo_id}.url already set: ",
2242 "$orig_url\nwanted to set to: $url\n";
2245 my ($xrepo_id, $xpath) = find_ref($self->refname);
2246 if (!$no_write && defined $xpath) {
2247 die "svn-remote.$xrepo_id.fetch already set to track ",
2248 "$xpath:", $self->refname, "\n";
2250 unless ($no_write) {
2251 command_noisy('config',
2252 "svn-remote.$self->{repo_id}.url", $url);
2253 $self->{path} =~ s{^/}{};
2254 $self->{path} =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
2255 command_noisy('config', '--add',
2256 "svn-remote.$self->{repo_id}.fetch",
2257 "$self->{path}:".$self->refname);
2259 $self->{url} = $url;
2262 sub find_by_url { # repos_root and, path are optional
2263 my ($class, $full_url, $repos_root, $path) = @_;
2265 return undef unless defined $full_url;
2266 remove_username($full_url);
2267 remove_username($repos_root) if defined $repos_root;
2268 my $remotes = read_all_remotes();
2269 if (defined $full_url && defined $repos_root && !defined $path) {
2270 $path = $full_url;
2271 $path =~ s#^\Q$repos_root\E(?:/|$)##;
2273 foreach my $repo_id (keys %$remotes) {
2274 my $u = $remotes->{$repo_id}->{url} or next;
2275 remove_username($u);
2276 next if defined $repos_root && $repos_root ne $u;
2278 my $fetch = $remotes->{$repo_id}->{fetch} || {};
2279 foreach my $t (qw/branches tags/) {
2280 foreach my $globspec (@{$remotes->{$repo_id}->{$t}}) {
2281 resolve_local_globs($u, $fetch, $globspec);
2284 my $p = $path;
2285 my $rwr = rewrite_root({repo_id => $repo_id});
2286 my $svm = $remotes->{$repo_id}->{svm}
2287 if defined $remotes->{$repo_id}->{svm};
2288 unless (defined $p) {
2289 $p = $full_url;
2290 my $z = $u;
2291 my $prefix = '';
2292 if ($rwr) {
2293 $z = $rwr;
2294 remove_username($z);
2295 } elsif (defined $svm) {
2296 $z = $svm->{source};
2297 $prefix = $svm->{replace};
2298 $prefix =~ s#^\Q$u\E(?:/|$)##;
2299 $prefix =~ s#/$##;
2301 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
2303 foreach my $f (keys %$fetch) {
2304 next if $f ne $p;
2305 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
2308 undef;
2311 sub init {
2312 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
2313 my $self = _new($class, $repo_id, $ref_id, $path);
2314 if (defined $url) {
2315 $self->init_remote_config($url, $no_write);
2317 $self;
2320 sub find_ref {
2321 my ($ref_id) = @_;
2322 foreach (command(qw/config -l/)) {
2323 next unless m!^svn-remote\.(.+)\.fetch=
2324 \s*(.*?)\s*:\s*(.+?)\s*$!x;
2325 my ($repo_id, $path, $ref) = ($1, $2, $3);
2326 if ($ref eq $ref_id) {
2327 $path = '' if ($path =~ m#^\./?#);
2328 return ($repo_id, $path);
2331 (undef, undef, undef);
2334 sub new {
2335 my ($class, $ref_id, $repo_id, $path) = @_;
2336 if (defined $ref_id && !defined $repo_id && !defined $path) {
2337 ($repo_id, $path) = find_ref($ref_id);
2338 if (!defined $repo_id) {
2339 die "Could not find a \"svn-remote.*.fetch\" key ",
2340 "in the repository configuration matching: ",
2341 "$ref_id\n";
2344 my $self = _new($class, $repo_id, $ref_id, $path);
2345 if (!defined $self->{path} || !length $self->{path}) {
2346 my $fetch = command_oneline('config', '--get',
2347 "svn-remote.$repo_id.fetch",
2348 ":$ref_id\$") or
2349 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
2350 "\":$ref_id\$\" in config\n";
2351 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
2353 $self->{path} =~ s{/+}{/}g;
2354 $self->{path} =~ s{\A/}{};
2355 $self->{path} =~ s{/\z}{};
2356 $self->{url} = command_oneline('config', '--get',
2357 "svn-remote.$repo_id.url") or
2358 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
2359 $self->{pushurl} = eval { command_oneline('config', '--get',
2360 "svn-remote.$repo_id.pushurl") };
2361 $self->rebuild;
2362 $self;
2365 sub refname {
2366 my ($refname) = $_[0]->{ref_id} ;
2368 # It cannot end with a slash /, we'll throw up on this because
2369 # SVN can't have directories with a slash in their name, either:
2370 if ($refname =~ m{/$}) {
2371 die "ref: '$refname' ends with a trailing slash, this is ",
2372 "not permitted by git nor Subversion\n";
2375 # It cannot have ASCII control character space, tilde ~, caret ^,
2376 # colon :, question-mark ?, asterisk *, space, or open bracket [
2377 # anywhere.
2379 # Additionally, % must be escaped because it is used for escaping
2380 # and we want our escaped refname to be reversible
2381 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
2383 # no slash-separated component can begin with a dot .
2384 # /.* becomes /%2E*
2385 $refname =~ s{/\.}{/%2E}g;
2387 # It cannot have two consecutive dots .. anywhere
2388 # .. becomes %2E%2E
2389 $refname =~ s{\.\.}{%2E%2E}g;
2391 # trailing dots and .lock are not allowed
2392 # .$ becomes %2E and .lock becomes %2Elock
2393 $refname =~ s{\.(?=$|lock$)}{%2E};
2395 # the sequence @{ is used to access the reflog
2396 # @{ becomes %40{
2397 $refname =~ s{\@\{}{%40\{}g;
2399 return $refname;
2402 sub desanitize_refname {
2403 my ($refname) = @_;
2404 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
2405 return $refname;
2408 sub svm_uuid {
2409 my ($self) = @_;
2410 return $self->{svm}->{uuid} if $self->svm;
2411 $self->ra;
2412 unless ($self->{svm}) {
2413 die "SVM UUID not cached, and reading remotely failed\n";
2415 $self->{svm}->{uuid};
2418 sub svm {
2419 my ($self) = @_;
2420 return $self->{svm} if $self->{svm};
2421 my $svm;
2422 # see if we have it in our config, first:
2423 eval {
2424 my $section = "svn-remote.$self->{repo_id}";
2425 $svm = {
2426 source => tmp_config('--get', "$section.svm-source"),
2427 uuid => tmp_config('--get', "$section.svm-uuid"),
2428 replace => tmp_config('--get', "$section.svm-replace"),
2431 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
2432 $self->{svm} = $svm;
2434 $self->{svm};
2437 sub _set_svm_vars {
2438 my ($self, $ra) = @_;
2439 return $ra if $self->svm;
2441 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
2442 "(svm:source, svm:uuid) ",
2443 "from the following URLs:\n" );
2444 sub read_svm_props {
2445 my ($self, $ra, $path, $r) = @_;
2446 my $props = ($ra->get_dir($path, $r))[2];
2447 my $src = $props->{'svm:source'};
2448 my $uuid = $props->{'svm:uuid'};
2449 return undef if (!$src || !$uuid);
2451 chomp($src, $uuid);
2453 $uuid =~ m{^[0-9a-f\-]{30,}$}i
2454 or die "doesn't look right - svm:uuid is '$uuid'\n";
2456 # the '!' is used to mark the repos_root!/relative/path
2457 $src =~ s{/?!/?}{/};
2458 $src =~ s{/+$}{}; # no trailing slashes please
2459 # username is of no interest
2460 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
2462 my $replace = $ra->{url};
2463 $replace .= "/$path" if length $path;
2465 my $section = "svn-remote.$self->{repo_id}";
2466 tmp_config("$section.svm-source", $src);
2467 tmp_config("$section.svm-replace", $replace);
2468 tmp_config("$section.svm-uuid", $uuid);
2469 $self->{svm} = {
2470 source => $src,
2471 uuid => $uuid,
2472 replace => $replace
2476 my $r = $ra->get_latest_revnum;
2477 my $path = $self->{path};
2478 my %tried;
2479 while (length $path) {
2480 unless ($tried{"$self->{url}/$path"}) {
2481 return $ra if $self->read_svm_props($ra, $path, $r);
2482 $tried{"$self->{url}/$path"} = 1;
2484 $path =~ s#/?[^/]+$##;
2486 die "Path: '$path' should be ''\n" if $path ne '';
2487 return $ra if $self->read_svm_props($ra, $path, $r);
2488 $tried{"$self->{url}/$path"} = 1;
2490 if ($ra->{repos_root} eq $self->{url}) {
2491 die @err, (map { " $_\n" } keys %tried), "\n";
2494 # nope, make sure we're connected to the repository root:
2495 my $ok;
2496 my @tried_b;
2497 $path = $ra->{svn_path};
2498 $ra = Git::SVN::Ra->new($ra->{repos_root});
2499 while (length $path) {
2500 unless ($tried{"$ra->{url}/$path"}) {
2501 $ok = $self->read_svm_props($ra, $path, $r);
2502 last if $ok;
2503 $tried{"$ra->{url}/$path"} = 1;
2505 $path =~ s#/?[^/]+$##;
2507 die "Path: '$path' should be ''\n" if $path ne '';
2508 $ok ||= $self->read_svm_props($ra, $path, $r);
2509 $tried{"$ra->{url}/$path"} = 1;
2510 if (!$ok) {
2511 die @err, (map { " $_\n" } keys %tried), "\n";
2513 Git::SVN::Ra->new($self->{url});
2516 sub svnsync {
2517 my ($self) = @_;
2518 return $self->{svnsync} if $self->{svnsync};
2520 if ($self->no_metadata) {
2521 die "Can't have both 'noMetadata' and ",
2522 "'useSvnsyncProps' options set!\n";
2524 if ($self->rewrite_root) {
2525 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
2526 "options set!\n";
2528 if ($self->rewrite_uuid) {
2529 die "Can't have both 'useSvnsyncProps' and 'rewriteUUID' ",
2530 "options set!\n";
2533 my $svnsync;
2534 # see if we have it in our config, first:
2535 eval {
2536 my $section = "svn-remote.$self->{repo_id}";
2538 my $url = tmp_config('--get', "$section.svnsync-url");
2539 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2540 die "doesn't look right - svn:sync-from-url is '$url'\n";
2542 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
2543 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2544 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2546 $svnsync = { url => $url, uuid => $uuid }
2548 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
2549 return $self->{svnsync} = $svnsync;
2552 my $err = "useSvnsyncProps set, but failed to read " .
2553 "svnsync property: svn:sync-from-";
2554 my $rp = $self->ra->rev_proplist(0);
2556 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
2557 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2558 die "doesn't look right - svn:sync-from-url is '$url'\n";
2560 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
2561 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2562 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2564 my $section = "svn-remote.$self->{repo_id}";
2565 tmp_config('--add', "$section.svnsync-uuid", $uuid);
2566 tmp_config('--add', "$section.svnsync-url", $url);
2567 return $self->{svnsync} = { url => $url, uuid => $uuid };
2570 # this allows us to memoize our SVN::Ra UUID locally and avoid a
2571 # remote lookup (useful for 'git svn log').
2572 sub ra_uuid {
2573 my ($self) = @_;
2574 unless ($self->{ra_uuid}) {
2575 my $key = "svn-remote.$self->{repo_id}.uuid";
2576 my $uuid = eval { tmp_config('--get', $key) };
2577 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/i) {
2578 $self->{ra_uuid} = $uuid;
2579 } else {
2580 die "ra_uuid called without URL\n" unless $self->{url};
2581 $self->{ra_uuid} = $self->ra->get_uuid;
2582 tmp_config('--add', $key, $self->{ra_uuid});
2585 $self->{ra_uuid};
2588 sub _set_repos_root {
2589 my ($self, $repos_root) = @_;
2590 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2591 $repos_root ||= $self->ra->{repos_root};
2592 tmp_config($k, $repos_root);
2593 $repos_root;
2596 sub repos_root {
2597 my ($self) = @_;
2598 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2599 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
2602 sub ra {
2603 my ($self) = shift;
2604 my $ra = Git::SVN::Ra->new($self->{url});
2605 $self->_set_repos_root($ra->{repos_root});
2606 if ($self->use_svm_props && !$self->{svm}) {
2607 if ($self->no_metadata) {
2608 die "Can't have both 'noMetadata' and ",
2609 "'useSvmProps' options set!\n";
2610 } elsif ($self->use_svnsync_props) {
2611 die "Can't have both 'useSvnsyncProps' and ",
2612 "'useSvmProps' options set!\n";
2614 $ra = $self->_set_svm_vars($ra);
2615 $self->{-want_revprops} = 1;
2617 $ra;
2620 # prop_walk(PATH, REV, SUB)
2621 # -------------------------
2622 # Recursively traverse PATH at revision REV and invoke SUB for each
2623 # directory that contains a SVN property. SUB will be invoked as
2624 # follows: &SUB(gs, path, props); where `gs' is this instance of
2625 # Git::SVN, `path' the path to the directory where the properties
2626 # `props' were found. The `path' will be relative to point of checkout,
2627 # that is, if url://repo/trunk is the current Git branch, and that
2628 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
2629 # as `path' (note the trailing `/').
2630 sub prop_walk {
2631 my ($self, $path, $rev, $sub) = @_;
2633 $path =~ s#^/##;
2634 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2635 $path =~ s#^/*#/#g;
2636 my $p = $path;
2637 # Strip the irrelevant part of the path.
2638 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2639 # Ensure the path is terminated by a `/'.
2640 $p =~ s#/*$#/#;
2642 # The properties contain all the internal SVN stuff nobody
2643 # (usually) cares about.
2644 my $interesting_props = 0;
2645 foreach (keys %{$props}) {
2646 # If it doesn't start with `svn:', it must be a
2647 # user-defined property.
2648 ++$interesting_props and next if $_ !~ /^svn:/;
2649 # FIXME: Fragile, if SVN adds new public properties,
2650 # this needs to be updated.
2651 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2652 |eol-style|mime-type
2653 |externals|needs-lock)$/x;
2655 &$sub($self, $p, $props) if $interesting_props;
2657 foreach (sort keys %$dirent) {
2658 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
2659 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
2663 sub last_rev { ($_[0]->last_rev_commit)[0] }
2664 sub last_commit { ($_[0]->last_rev_commit)[1] }
2666 # returns the newest SVN revision number and newest commit SHA1
2667 sub last_rev_commit {
2668 my ($self) = @_;
2669 if (defined $self->{last_rev} && defined $self->{last_commit}) {
2670 return ($self->{last_rev}, $self->{last_commit});
2672 my $c = ::verify_ref($self->refname.'^0');
2673 if ($c && !$self->use_svm_props && !$self->no_metadata) {
2674 my $rev = (::cmt_metadata($c))[1];
2675 if (defined $rev) {
2676 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2677 return ($rev, $c);
2680 my $map_path = $self->map_path;
2681 unless (-e $map_path) {
2682 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2683 return (undef, undef);
2685 my ($rev, $commit) = $self->rev_map_max(1);
2686 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2687 return ($rev, $commit);
2690 sub get_fetch_range {
2691 my ($self, $min, $max) = @_;
2692 $max ||= $self->ra->get_latest_revnum;
2693 $min ||= $self->rev_map_max;
2694 (++$min, $max);
2697 sub tmp_config {
2698 my (@args) = @_;
2699 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2700 my $config = "$ENV{GIT_DIR}/svn/.metadata";
2701 if (! -f $config && -f $old_def_config) {
2702 rename $old_def_config, $config or
2703 die "Failed rename $old_def_config => $config: $!\n";
2705 my $old_config = $ENV{GIT_CONFIG};
2706 $ENV{GIT_CONFIG} = $config;
2707 $@ = undef;
2708 my @ret = eval {
2709 unless (-f $config) {
2710 mkfile($config);
2711 open my $fh, '>', $config or
2712 die "Can't open $config: $!\n";
2713 print $fh "; This file is used internally by ",
2714 "git-svn\n" or die
2715 "Couldn't write to $config: $!\n";
2716 print $fh "; You should not have to edit it\n" or
2717 die "Couldn't write to $config: $!\n";
2718 close $fh or die "Couldn't close $config: $!\n";
2720 command('config', @args);
2722 my $err = $@;
2723 if (defined $old_config) {
2724 $ENV{GIT_CONFIG} = $old_config;
2725 } else {
2726 delete $ENV{GIT_CONFIG};
2728 die $err if $err;
2729 wantarray ? @ret : $ret[0];
2732 sub tmp_index_do {
2733 my ($self, $sub) = @_;
2734 my $old_index = $ENV{GIT_INDEX_FILE};
2735 $ENV{GIT_INDEX_FILE} = $self->{index};
2736 $@ = undef;
2737 my @ret = eval {
2738 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2739 mkpath([$dir]) unless -d $dir;
2740 &$sub;
2742 my $err = $@;
2743 if (defined $old_index) {
2744 $ENV{GIT_INDEX_FILE} = $old_index;
2745 } else {
2746 delete $ENV{GIT_INDEX_FILE};
2748 die $err if $err;
2749 wantarray ? @ret : $ret[0];
2752 sub assert_index_clean {
2753 my ($self, $treeish) = @_;
2755 $self->tmp_index_do(sub {
2756 command_noisy('read-tree', $treeish) unless -e $self->{index};
2757 my $x = command_oneline('write-tree');
2758 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2759 /^tree ($::sha1)/mo);
2760 return if $y eq $x;
2762 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2763 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2764 command_noisy('read-tree', $treeish);
2765 $x = command_oneline('write-tree');
2766 if ($y ne $x) {
2767 ::fatal "trees ($treeish) $y != $x\n",
2768 "Something is seriously wrong...";
2773 sub get_commit_parents {
2774 my ($self, $log_entry) = @_;
2775 my (%seen, @ret, @tmp);
2776 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2777 if (my $ip = $self->{inject_parents}) {
2778 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2779 push @tmp, $commit;
2782 if (my $cur = ::verify_ref($self->refname.'^0')) {
2783 push @tmp, $cur;
2785 if (my $ipd = $self->{inject_parents_dcommit}) {
2786 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2787 push @tmp, @$commit;
2790 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2791 while (my $p = shift @tmp) {
2792 next if $seen{$p};
2793 $seen{$p} = 1;
2794 push @ret, $p;
2796 @ret;
2799 sub rewrite_root {
2800 my ($self) = @_;
2801 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2802 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2803 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2804 if ($rwr) {
2805 $rwr =~ s#/+$##;
2806 if ($rwr !~ m#^[a-z\+]+://#) {
2807 die "$rwr is not a valid URL (key: $k)\n";
2810 $self->{-rewrite_root} = $rwr;
2813 sub rewrite_uuid {
2814 my ($self) = @_;
2815 return $self->{-rewrite_uuid} if exists $self->{-rewrite_uuid};
2816 my $k = "svn-remote.$self->{repo_id}.rewriteUUID";
2817 my $rwid = eval { command_oneline(qw/config --get/, $k) };
2818 if ($rwid) {
2819 $rwid =~ s#/+$##;
2820 if ($rwid !~ m#^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$#) {
2821 die "$rwid is not a valid UUID (key: $k)\n";
2824 $self->{-rewrite_uuid} = $rwid;
2827 sub metadata_url {
2828 my ($self) = @_;
2829 ($self->rewrite_root || $self->{url}) .
2830 (length $self->{path} ? '/' . $self->{path} : '');
2833 sub full_url {
2834 my ($self) = @_;
2835 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2838 sub full_pushurl {
2839 my ($self) = @_;
2840 if ($self->{pushurl}) {
2841 return $self->{pushurl} . (length $self->{path} ? '/' .
2842 $self->{path} : '');
2843 } else {
2844 return $self->full_url;
2848 sub set_commit_header_env {
2849 my ($log_entry) = @_;
2850 my %env;
2851 foreach my $ned (qw/NAME EMAIL DATE/) {
2852 foreach my $ac (qw/AUTHOR COMMITTER/) {
2853 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2857 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2858 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2859 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2861 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2862 ? $log_entry->{commit_name}
2863 : $log_entry->{name};
2864 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2865 ? $log_entry->{commit_email}
2866 : $log_entry->{email};
2867 \%env;
2870 sub restore_commit_header_env {
2871 my ($env) = @_;
2872 foreach my $ned (qw/NAME EMAIL DATE/) {
2873 foreach my $ac (qw/AUTHOR COMMITTER/) {
2874 my $k = "GIT_${ac}_${ned}";
2875 if (defined $env->{$k}) {
2876 $ENV{$k} = $env->{$k};
2877 } else {
2878 delete $ENV{$k};
2884 sub gc {
2885 command_noisy('gc', '--auto');
2888 sub do_git_commit {
2889 my ($self, $log_entry) = @_;
2890 my $lr = $self->last_rev;
2891 if (defined $lr && $lr >= $log_entry->{revision}) {
2892 die "Last fetched revision of ", $self->refname,
2893 " was r$lr, but we are about to fetch: ",
2894 "r$log_entry->{revision}!\n";
2896 if (my $c = $self->rev_map_get($log_entry->{revision})) {
2897 croak "$log_entry->{revision} = $c already exists! ",
2898 "Why are we refetching it?\n";
2900 my $old_env = set_commit_header_env($log_entry);
2901 my $tree = $log_entry->{tree};
2902 if (!defined $tree) {
2903 $tree = $self->tmp_index_do(sub {
2904 command_oneline('write-tree') });
2906 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2908 my @exec = ('git', 'commit-tree', $tree);
2909 foreach ($self->get_commit_parents($log_entry)) {
2910 push @exec, '-p', $_;
2912 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2913 or croak $!;
2914 binmode $msg_fh;
2916 # we always get UTF-8 from SVN, but we may want our commits in
2917 # a different encoding.
2918 if (my $enc = Git::config('i18n.commitencoding')) {
2919 require Encode;
2920 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
2922 print $msg_fh $log_entry->{log} or croak $!;
2923 restore_commit_header_env($old_env);
2924 unless ($self->no_metadata) {
2925 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2926 or croak $!;
2928 $msg_fh->flush == 0 or croak $!;
2929 close $msg_fh or croak $!;
2930 chomp(my $commit = do { local $/; <$out_fh> });
2931 close $out_fh or croak $!;
2932 waitpid $pid, 0;
2933 croak $? if $?;
2934 if ($commit !~ /^$::sha1$/o) {
2935 die "Failed to commit, invalid sha1: $commit\n";
2938 $self->rev_map_set($log_entry->{revision}, $commit, 1);
2940 $self->{last_rev} = $log_entry->{revision};
2941 $self->{last_commit} = $commit;
2942 print "r$log_entry->{revision}" unless $::_q > 1;
2943 if (defined $log_entry->{svm_revision}) {
2944 print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
2945 $self->rev_map_set($log_entry->{svm_revision}, $commit,
2946 0, $self->svm_uuid);
2948 print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
2949 if (--$_gc_nr == 0) {
2950 $_gc_nr = $_gc_period;
2951 gc();
2953 return $commit;
2956 sub match_paths {
2957 my ($self, $paths, $r) = @_;
2958 return 1 if $self->{path} eq '';
2959 if (my $path = $paths->{"/$self->{path}"}) {
2960 return ($path->{action} eq 'D') ? 0 : 1;
2962 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
2963 if (grep /$self->{path_regex}/, keys %$paths) {
2964 return 1;
2966 my $c = '';
2967 foreach (split m#/#, $self->{path}) {
2968 $c .= "/$_";
2969 next unless ($paths->{$c} &&
2970 ($paths->{$c}->{action} =~ /^[AR]$/));
2971 if ($self->ra->check_path($self->{path}, $r) ==
2972 $SVN::Node::dir) {
2973 return 1;
2976 return 0;
2979 sub find_parent_branch {
2980 my ($self, $paths, $rev) = @_;
2981 return undef unless $self->follow_parent;
2982 unless (defined $paths) {
2983 my $err_handler = $SVN::Error::handler;
2984 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2985 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1,
2986 sub { $paths = $_[0] });
2987 $SVN::Error::handler = $err_handler;
2989 return undef unless defined $paths;
2991 # look for a parent from another branch:
2992 my @b_path_components = split m#/#, $self->{path};
2993 my @a_path_components;
2994 my $i;
2995 while (@b_path_components) {
2996 $i = $paths->{'/'.join('/', @b_path_components)};
2997 last if $i && defined $i->{copyfrom_path};
2998 unshift(@a_path_components, pop(@b_path_components));
3000 return undef unless defined $i && defined $i->{copyfrom_path};
3001 my $branch_from = $i->{copyfrom_path};
3002 if (@a_path_components) {
3003 print STDERR "branch_from: $branch_from => ";
3004 $branch_from .= '/'.join('/', @a_path_components);
3005 print STDERR $branch_from, "\n";
3007 my $r = $i->{copyfrom_rev};
3008 my $repos_root = $self->ra->{repos_root};
3009 my $url = $self->ra->{url};
3010 my $new_url = $url . $branch_from;
3011 print STDERR "Found possible branch point: ",
3012 "$new_url => ", $self->full_url, ", $r\n"
3013 unless $::_q > 1;
3014 $branch_from =~ s#^/##;
3015 my $gs = $self->other_gs($new_url, $url,
3016 $branch_from, $r, $self->{ref_id});
3017 my ($r0, $parent) = $gs->find_rev_before($r, 1);
3019 my ($base, $head);
3020 if (!defined $r0 || !defined $parent) {
3021 ($base, $head) = parse_revision_argument(0, $r);
3022 } else {
3023 if ($r0 < $r) {
3024 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
3025 0, 1, sub { $base = $_[1] - 1 });
3028 if (defined $base && $base <= $r) {
3029 $gs->fetch($base, $r);
3031 ($r0, $parent) = $gs->find_rev_before($r, 1);
3033 if (defined $r0 && defined $parent) {
3034 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n"
3035 unless $::_q > 1;
3036 my $ed;
3037 if ($self->ra->can_do_switch) {
3038 $self->assert_index_clean($parent);
3039 print STDERR "Following parent with do_switch\n"
3040 unless $::_q > 1;
3041 # do_switch works with svn/trunk >= r22312, but that
3042 # is not included with SVN 1.4.3 (the latest version
3043 # at the moment), so we can't rely on it
3044 $self->{last_rev} = $r0;
3045 $self->{last_commit} = $parent;
3046 $ed = SVN::Git::Fetcher->new($self, $gs->{path});
3047 $gs->ra->gs_do_switch($r0, $rev, $gs,
3048 $self->full_url, $ed)
3049 or die "SVN connection failed somewhere...\n";
3050 } elsif ($self->ra->trees_match($new_url, $r0,
3051 $self->full_url, $rev)) {
3052 print STDERR "Trees match:\n",
3053 " $new_url\@$r0\n",
3054 " ${\$self->full_url}\@$rev\n",
3055 "Following parent with no changes\n"
3056 unless $::_q > 1;
3057 $self->tmp_index_do(sub {
3058 command_noisy('read-tree', $parent);
3060 $self->{last_commit} = $parent;
3061 } else {
3062 print STDERR "Following parent with do_update\n"
3063 unless $::_q > 1;
3064 $ed = SVN::Git::Fetcher->new($self);
3065 $self->ra->gs_do_update($rev, $rev, $self, $ed)
3066 or die "SVN connection failed somewhere...\n";
3068 print STDERR "Successfully followed parent\n" unless $::_q > 1;
3069 return $self->make_log_entry($rev, [$parent], $ed);
3071 return undef;
3074 sub do_fetch {
3075 my ($self, $paths, $rev) = @_;
3076 my $ed;
3077 my ($last_rev, @parents);
3078 if (my $lc = $self->last_commit) {
3079 # we can have a branch that was deleted, then re-added
3080 # under the same name but copied from another path, in
3081 # which case we'll have multiple parents (we don't
3082 # want to break the original ref, nor lose copypath info):
3083 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
3084 push @{$log_entry->{parents}}, $lc;
3085 return $log_entry;
3087 $ed = SVN::Git::Fetcher->new($self);
3088 $last_rev = $self->{last_rev};
3089 $ed->{c} = $lc;
3090 @parents = ($lc);
3091 } else {
3092 $last_rev = $rev;
3093 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
3094 return $log_entry;
3096 $ed = SVN::Git::Fetcher->new($self);
3098 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
3099 die "SVN connection failed somewhere...\n";
3101 $self->make_log_entry($rev, \@parents, $ed);
3104 sub mkemptydirs {
3105 my ($self, $r) = @_;
3107 sub scan {
3108 my ($r, $empty_dirs, $line) = @_;
3109 if (defined $r && $line =~ /^r(\d+)$/) {
3110 return 0 if $1 > $r;
3111 } elsif ($line =~ /^ \+empty_dir: (.+)$/) {
3112 $empty_dirs->{$1} = 1;
3113 } elsif ($line =~ /^ \-empty_dir: (.+)$/) {
3114 my @d = grep {m[^\Q$1\E(/|$)]} (keys %$empty_dirs);
3115 delete @$empty_dirs{@d};
3117 1; # continue
3120 my %empty_dirs = ();
3121 my $gz_file = "$self->{dir}/unhandled.log.gz";
3122 if (-f $gz_file) {
3123 if (!$can_compress) {
3124 warn "Compress::Zlib could not be found; ",
3125 "empty directories in $gz_file will not be read\n";
3126 } else {
3127 my $gz = Compress::Zlib::gzopen($gz_file, "rb") or
3128 die "Unable to open $gz_file: $!\n";
3129 my $line;
3130 while ($gz->gzreadline($line) > 0) {
3131 scan($r, \%empty_dirs, $line) or last;
3133 $gz->gzclose;
3137 if (open my $fh, '<', "$self->{dir}/unhandled.log") {
3138 binmode $fh or croak "binmode: $!";
3139 while (<$fh>) {
3140 scan($r, \%empty_dirs, $_) or last;
3142 close $fh;
3145 my $strip = qr/\A\Q$self->{path}\E(?:\/|$)/;
3146 foreach my $d (sort keys %empty_dirs) {
3147 $d = uri_decode($d);
3148 $d =~ s/$strip//;
3149 next unless length($d);
3150 next if -d $d;
3151 if (-e $d) {
3152 warn "$d exists but is not a directory\n";
3153 } else {
3154 print "creating empty directory: $d\n";
3155 mkpath([$d]);
3160 sub get_untracked {
3161 my ($self, $ed) = @_;
3162 my @out;
3163 my $h = $ed->{empty};
3164 foreach (sort keys %$h) {
3165 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
3166 push @out, " $act: " . uri_encode($_);
3167 warn "W: $act: $_\n";
3169 foreach my $t (qw/dir_prop file_prop/) {
3170 $h = $ed->{$t} or next;
3171 foreach my $path (sort keys %$h) {
3172 my $ppath = $path eq '' ? '.' : $path;
3173 foreach my $prop (sort keys %{$h->{$path}}) {
3174 next if $SKIP_PROP{$prop};
3175 my $v = $h->{$path}->{$prop};
3176 my $t_ppath_prop = "$t: " .
3177 uri_encode($ppath) . ' ' .
3178 uri_encode($prop);
3179 if (defined $v) {
3180 push @out, " +$t_ppath_prop " .
3181 uri_encode($v);
3182 } else {
3183 push @out, " -$t_ppath_prop";
3188 foreach my $t (qw/absent_file absent_directory/) {
3189 $h = $ed->{$t} or next;
3190 foreach my $parent (sort keys %$h) {
3191 foreach my $path (sort @{$h->{$parent}}) {
3192 push @out, " $t: " .
3193 uri_encode("$parent/$path");
3194 warn "W: $t: $parent/$path ",
3195 "Insufficient permissions?\n";
3199 \@out;
3202 # parse_svn_date(DATE)
3203 # --------------------
3204 # Given a date (in UTC) from Subversion, return a string in the format
3205 # "<TZ Offset> <local date/time>" that Git will use.
3207 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
3208 # is true we'll convert it to the local timezone instead.
3209 sub parse_svn_date {
3210 my $date = shift || return '+0000 1970-01-01 00:00:00';
3211 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
3212 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
3213 croak "Unable to parse date: $date\n";
3214 my $parsed_date; # Set next.
3216 if ($Git::SVN::_localtime) {
3217 # Translate the Subversion datetime to an epoch time.
3218 # Begin by switching ourselves to $date's timezone, UTC.
3219 my $old_env_TZ = $ENV{TZ};
3220 $ENV{TZ} = 'UTC';
3222 my $epoch_in_UTC =
3223 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
3225 # Determine our local timezone (including DST) at the
3226 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
3227 # value of TZ, if any, at the time we were run.
3228 if (defined $Git::SVN::Log::TZ) {
3229 $ENV{TZ} = $Git::SVN::Log::TZ;
3230 } else {
3231 delete $ENV{TZ};
3234 my $our_TZ =
3235 POSIX::strftime('%Z', $S, $M, $H, $d, $m - 1, $Y - 1900);
3237 # This converts $epoch_in_UTC into our local timezone.
3238 my ($sec, $min, $hour, $mday, $mon, $year,
3239 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
3241 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
3242 $our_TZ, $year + 1900, $mon + 1,
3243 $mday, $hour, $min, $sec);
3245 # Reset us to the timezone in effect when we entered
3246 # this routine.
3247 if (defined $old_env_TZ) {
3248 $ENV{TZ} = $old_env_TZ;
3249 } else {
3250 delete $ENV{TZ};
3252 } else {
3253 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
3256 return $parsed_date;
3259 sub other_gs {
3260 my ($self, $new_url, $url,
3261 $branch_from, $r, $old_ref_id) = @_;
3262 my $gs = Git::SVN->find_by_url($new_url, $url, $branch_from);
3263 unless ($gs) {
3264 my $ref_id = $old_ref_id;
3265 $ref_id =~ s/\@\d+-*$//;
3266 $ref_id .= "\@$r";
3267 # just grow a tail if we're not unique enough :x
3268 $ref_id .= '-' while find_ref($ref_id);
3269 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
3270 if ($u =~ s#^\Q$url\E(/|$)##) {
3271 $p = $u;
3272 $u = $url;
3273 $repo_id = $self->{repo_id};
3275 while (1) {
3276 # It is possible to tag two different subdirectories at
3277 # the same revision. If the url for an existing ref
3278 # does not match, we must either find a ref with a
3279 # matching url or create a new ref by growing a tail.
3280 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
3281 my (undef, $max_commit) = $gs->rev_map_max(1);
3282 last if (!$max_commit);
3283 my ($url) = ::cmt_metadata($max_commit);
3284 last if ($url eq $gs->metadata_url);
3285 $ref_id .= '-';
3287 print STDERR "Initializing parent: $ref_id\n" unless $::_q > 1;
3292 sub call_authors_prog {
3293 my ($orig_author) = @_;
3294 $orig_author = command_oneline('rev-parse', '--sq-quote', $orig_author);
3295 my $author = `$::_authors_prog $orig_author`;
3296 if ($? != 0) {
3297 die "$::_authors_prog failed with exit code $?\n"
3299 if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
3300 my ($name, $email) = ($1, $2);
3301 $email = undef if length $2 == 0;
3302 return [$name, $email];
3303 } else {
3304 die "Author: $orig_author: $::_authors_prog returned "
3305 . "invalid author format: $author\n";
3309 sub check_author {
3310 my ($author) = @_;
3311 if (!defined $author || length $author == 0) {
3312 $author = '(no author)';
3314 if (!defined $::users{$author}) {
3315 if (defined $::_authors_prog) {
3316 $::users{$author} = call_authors_prog($author);
3317 } elsif (defined $::_authors) {
3318 die "Author: $author not defined in $::_authors file\n";
3321 $author;
3324 sub find_extra_svk_parents {
3325 my ($self, $ed, $tickets, $parents) = @_;
3326 # aha! svk:merge property changed...
3327 my @tickets = split "\n", $tickets;
3328 my @known_parents;
3329 for my $ticket ( @tickets ) {
3330 my ($uuid, $path, $rev) = split /:/, $ticket;
3331 if ( $uuid eq $self->ra_uuid ) {
3332 my $url = $self->{url};
3333 my $repos_root = $url;
3334 my $branch_from = $path;
3335 $branch_from =~ s{^/}{};
3336 my $gs = $self->other_gs($repos_root."/".$branch_from,
3337 $url,
3338 $branch_from,
3339 $rev,
3340 $self->{ref_id});
3341 if ( my $commit = $gs->rev_map_get($rev, $uuid) ) {
3342 # wahey! we found it, but it might be
3343 # an old one (!)
3344 push @known_parents, [ $rev, $commit ];
3348 # Ordering matters; highest-numbered commit merge tickets
3349 # first, as they may account for later merge ticket additions
3350 # or changes.
3351 @known_parents = map {$_->[1]} sort {$b->[0] <=> $a->[0]} @known_parents;
3352 for my $parent ( @known_parents ) {
3353 my @cmd = ('rev-list', $parent, map { "^$_" } @$parents );
3354 my ($msg_fh, $ctx) = command_output_pipe(@cmd);
3355 my $new;
3356 while ( <$msg_fh> ) {
3357 $new=1;last;
3359 command_close_pipe($msg_fh, $ctx);
3360 if ( $new ) {
3361 print STDERR
3362 "Found merge parent (svk:merge ticket): $parent\n";
3363 push @$parents, $parent;
3368 sub lookup_svn_merge {
3369 my $uuid = shift;
3370 my $url = shift;
3371 my $merge = shift;
3373 my ($source, $revs) = split ":", $merge;
3374 my $path = $source;
3375 $path =~ s{^/}{};
3376 my $gs = Git::SVN->find_by_url($url.$source, $url, $path);
3377 if ( !$gs ) {
3378 warn "Couldn't find revmap for $url$source\n";
3379 return;
3381 my @ranges = split ",", $revs;
3382 my ($tip, $tip_commit);
3383 my @merged_commit_ranges;
3384 # find the tip
3385 for my $range ( @ranges ) {
3386 my ($bottom, $top) = split "-", $range;
3387 $top ||= $bottom;
3388 my $bottom_commit = $gs->find_rev_after( $bottom, 1, $top );
3389 my $top_commit = $gs->find_rev_before( $top, 1, $bottom );
3391 unless ($top_commit and $bottom_commit) {
3392 warn "W:unknown path/rev in svn:mergeinfo "
3393 ."dirprop: $source:$range\n";
3394 next;
3397 if (scalar(command('rev-parse', "$bottom_commit^@"))) {
3398 push @merged_commit_ranges,
3399 "$bottom_commit^..$top_commit";
3400 } else {
3401 push @merged_commit_ranges, "$top_commit";
3404 if ( !defined $tip or $top > $tip ) {
3405 $tip = $top;
3406 $tip_commit = $top_commit;
3409 return ($tip_commit, @merged_commit_ranges);
3412 sub _rev_list {
3413 my ($msg_fh, $ctx) = command_output_pipe(
3414 "rev-list", @_,
3416 my @rv;
3417 while ( <$msg_fh> ) {
3418 chomp;
3419 push @rv, $_;
3421 command_close_pipe($msg_fh, $ctx);
3422 @rv;
3425 sub check_cherry_pick {
3426 my $base = shift;
3427 my $tip = shift;
3428 my $parents = shift;
3429 my @ranges = @_;
3430 my %commits = map { $_ => 1 }
3431 _rev_list("--no-merges", $tip, "--not", $base, @$parents, "--");
3432 for my $range ( @ranges ) {
3433 delete @commits{_rev_list($range, "--")};
3435 for my $commit (keys %commits) {
3436 if (has_no_changes($commit)) {
3437 delete $commits{$commit};
3440 return (keys %commits);
3443 sub has_no_changes {
3444 my $commit = shift;
3446 my @revs = split / /, command_oneline(
3447 qw(rev-list --parents -1 -m), $commit);
3449 # Commits with no parents, e.g. the start of a partial branch,
3450 # have changes by definition.
3451 return 1 if (@revs < 2);
3453 # Commits with multiple parents, e.g a merge, have no changes
3454 # by definition.
3455 return 0 if (@revs > 2);
3457 return (command_oneline("rev-parse", "$commit^{tree}") eq
3458 command_oneline("rev-parse", "$commit~1^{tree}"));
3461 # The GIT_DIR environment variable is not always set until after the command
3462 # line arguments are processed, so we can't memoize in a BEGIN block.
3464 my $memoized = 0;
3466 sub memoize_svn_mergeinfo_functions {
3467 return if $memoized;
3468 $memoized = 1;
3470 my $cache_path = "$ENV{GIT_DIR}/svn/.caches/";
3471 mkpath([$cache_path]) unless -d $cache_path;
3473 tie my %lookup_svn_merge_cache => 'Memoize::Storable',
3474 "$cache_path/lookup_svn_merge.db", 'nstore';
3475 memoize 'lookup_svn_merge',
3476 SCALAR_CACHE => 'FAULT',
3477 LIST_CACHE => ['HASH' => \%lookup_svn_merge_cache],
3480 tie my %check_cherry_pick_cache => 'Memoize::Storable',
3481 "$cache_path/check_cherry_pick.db", 'nstore';
3482 memoize 'check_cherry_pick',
3483 SCALAR_CACHE => 'FAULT',
3484 LIST_CACHE => ['HASH' => \%check_cherry_pick_cache],
3487 tie my %has_no_changes_cache => 'Memoize::Storable',
3488 "$cache_path/has_no_changes.db", 'nstore';
3489 memoize 'has_no_changes',
3490 SCALAR_CACHE => ['HASH' => \%has_no_changes_cache],
3491 LIST_CACHE => 'FAULT',
3495 sub unmemoize_svn_mergeinfo_functions {
3496 return if not $memoized;
3497 $memoized = 0;
3499 Memoize::unmemoize 'lookup_svn_merge';
3500 Memoize::unmemoize 'check_cherry_pick';
3501 Memoize::unmemoize 'has_no_changes';
3504 Memoize::memoize 'Git::SVN::repos_root';
3507 END {
3508 # Force cache writeout explicitly instead of waiting for
3509 # global destruction to avoid segfault in Storable:
3510 # http://rt.cpan.org/Public/Bug/Display.html?id=36087
3511 unmemoize_svn_mergeinfo_functions();
3514 sub parents_exclude {
3515 my $parents = shift;
3516 my @commits = @_;
3517 return unless @commits;
3519 my @excluded;
3520 my $excluded;
3521 do {
3522 my @cmd = ('rev-list', "-1", @commits, "--not", @$parents );
3523 $excluded = command_oneline(@cmd);
3524 if ( $excluded ) {
3525 my @new;
3526 my $found;
3527 for my $commit ( @commits ) {
3528 if ( $commit eq $excluded ) {
3529 push @excluded, $commit;
3530 $found++;
3531 last;
3533 else {
3534 push @new, $commit;
3537 die "saw commit '$excluded' in rev-list output, "
3538 ."but we didn't ask for that commit (wanted: @commits --not @$parents)"
3539 unless $found;
3540 @commits = @new;
3543 while ($excluded and @commits);
3545 return @excluded;
3549 # note: this function should only be called if the various dirprops
3550 # have actually changed
3551 sub find_extra_svn_parents {
3552 my ($self, $ed, $mergeinfo, $parents) = @_;
3553 # aha! svk:merge property changed...
3555 memoize_svn_mergeinfo_functions();
3557 # We first search for merged tips which are not in our
3558 # history. Then, we figure out which git revisions are in
3559 # that tip, but not this revision. If all of those revisions
3560 # are now marked as merge, we can add the tip as a parent.
3561 my @merges = split "\n", $mergeinfo;
3562 my @merge_tips;
3563 my $url = $self->{url};
3564 my $uuid = $self->ra_uuid;
3565 my %ranges;
3566 for my $merge ( @merges ) {
3567 my ($tip_commit, @ranges) =
3568 lookup_svn_merge( $uuid, $url, $merge );
3569 unless (!$tip_commit or
3570 grep { $_ eq $tip_commit } @$parents ) {
3571 push @merge_tips, $tip_commit;
3572 $ranges{$tip_commit} = \@ranges;
3573 } else {
3574 push @merge_tips, undef;
3578 my %excluded = map { $_ => 1 }
3579 parents_exclude($parents, grep { defined } @merge_tips);
3581 # check merge tips for new parents
3582 my @new_parents;
3583 for my $merge_tip ( @merge_tips ) {
3584 my $spec = shift @merges;
3585 next unless $merge_tip and $excluded{$merge_tip};
3587 my $ranges = $ranges{$merge_tip};
3589 # check out 'new' tips
3590 my $merge_base;
3591 eval {
3592 $merge_base = command_oneline(
3593 "merge-base",
3594 @$parents, $merge_tip,
3597 if ($@) {
3598 die "An error occurred during merge-base"
3599 unless $@->isa("Git::Error::Command");
3601 warn "W: Cannot find common ancestor between ".
3602 "@$parents and $merge_tip. Ignoring merge info.\n";
3603 next;
3606 # double check that there are no missing non-merge commits
3607 my (@incomplete) = check_cherry_pick(
3608 $merge_base, $merge_tip,
3609 $parents,
3610 @$ranges,
3613 if ( @incomplete ) {
3614 warn "W:svn cherry-pick ignored ($spec) - missing "
3615 .@incomplete." commit(s) (eg $incomplete[0])\n";
3616 } else {
3617 warn
3618 "Found merge parent (svn:mergeinfo prop): ",
3619 $merge_tip, "\n";
3620 push @new_parents, $merge_tip;
3624 # cater for merges which merge commits from multiple branches
3625 if ( @new_parents > 1 ) {
3626 for ( my $i = 0; $i <= $#new_parents; $i++ ) {
3627 for ( my $j = 0; $j <= $#new_parents; $j++ ) {
3628 next if $i == $j;
3629 next unless $new_parents[$i];
3630 next unless $new_parents[$j];
3631 my $revs = command_oneline(
3632 "rev-list", "-1",
3633 "$new_parents[$i]..$new_parents[$j]",
3635 if ( !$revs ) {
3636 undef($new_parents[$j]);
3641 push @$parents, grep { defined } @new_parents;
3644 sub make_log_entry {
3645 my ($self, $rev, $parents, $ed) = @_;
3646 my $untracked = $self->get_untracked($ed);
3648 my @parents = @$parents;
3649 my $ps = $ed->{path_strip} || "";
3650 for my $path ( grep { m/$ps/ } %{$ed->{dir_prop}} ) {
3651 my $props = $ed->{dir_prop}{$path};
3652 if ( $props->{"svk:merge"} ) {
3653 $self->find_extra_svk_parents
3654 ($ed, $props->{"svk:merge"}, \@parents);
3656 if ( $props->{"svn:mergeinfo"} ) {
3657 $self->find_extra_svn_parents
3658 ($ed,
3659 $props->{"svn:mergeinfo"},
3660 \@parents);
3664 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
3665 print $un "r$rev\n" or croak $!;
3666 print $un $_, "\n" foreach @$untracked;
3667 my %log_entry = ( parents => \@parents, revision => $rev,
3668 log => '');
3670 my $headrev;
3671 my $logged = delete $self->{logged_rev_props};
3672 if (!$logged || $self->{-want_revprops}) {
3673 my $rp = $self->ra->rev_proplist($rev);
3674 foreach (sort keys %$rp) {
3675 my $v = $rp->{$_};
3676 if (/^svn:(author|date|log)$/) {
3677 $log_entry{$1} = $v;
3678 } elsif ($_ eq 'svm:headrev') {
3679 $headrev = $v;
3680 } else {
3681 print $un " rev_prop: ", uri_encode($_), ' ',
3682 uri_encode($v), "\n";
3685 } else {
3686 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
3688 close $un or croak $!;
3690 $log_entry{date} = parse_svn_date($log_entry{date});
3691 $log_entry{log} .= "\n";
3692 my $author = $log_entry{author} = check_author($log_entry{author});
3693 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
3694 : ($author, undef);
3696 my ($commit_name, $commit_email) = ($name, $email);
3697 if ($_use_log_author) {
3698 my $name_field;
3699 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
3700 $name_field = $1;
3701 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
3702 $name_field = $1;
3704 if (!defined $name_field) {
3705 if (!defined $email) {
3706 $email = $name;
3708 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
3709 ($name, $email) = ($1, $2);
3710 } elsif ($name_field =~ /(.*)@/) {
3711 ($name, $email) = ($1, $name_field);
3712 } else {
3713 ($name, $email) = ($name_field, $name_field);
3716 if (defined $headrev && $self->use_svm_props) {
3717 if ($self->rewrite_root) {
3718 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
3719 "options set!\n";
3721 if ($self->rewrite_uuid) {
3722 die "Can't have both 'useSvmProps' and 'rewriteUUID' ",
3723 "options set!\n";
3725 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$}i;
3726 # we don't want "SVM: initializing mirror for junk" ...
3727 return undef if $r == 0;
3728 my $svm = $self->svm;
3729 if ($uuid ne $svm->{uuid}) {
3730 die "UUID mismatch on SVM path:\n",
3731 "expected: $svm->{uuid}\n",
3732 " got: $uuid\n";
3734 my $full_url = $self->full_url;
3735 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
3736 die "Failed to replace '$svm->{replace}' with ",
3737 "'$svm->{source}' in $full_url\n";
3738 # throw away username for storing in records
3739 remove_username($full_url);
3740 $log_entry{metadata} = "$full_url\@$r $uuid";
3741 $log_entry{svm_revision} = $r;
3742 $email ||= "$author\@$uuid";
3743 $commit_email ||= "$author\@$uuid";
3744 } elsif ($self->use_svnsync_props) {
3745 my $full_url = $self->svnsync->{url};
3746 $full_url .= "/$self->{path}" if length $self->{path};
3747 remove_username($full_url);
3748 my $uuid = $self->svnsync->{uuid};
3749 $log_entry{metadata} = "$full_url\@$rev $uuid";
3750 $email ||= "$author\@$uuid";
3751 $commit_email ||= "$author\@$uuid";
3752 } else {
3753 my $url = $self->metadata_url;
3754 remove_username($url);
3755 my $uuid = $self->rewrite_uuid || $self->ra->get_uuid;
3756 $log_entry{metadata} = "$url\@$rev " . $uuid;
3757 $email ||= "$author\@" . $uuid;
3758 $commit_email ||= "$author\@" . $uuid;
3760 $log_entry{name} = $name;
3761 $log_entry{email} = $email;
3762 $log_entry{commit_name} = $commit_name;
3763 $log_entry{commit_email} = $commit_email;
3764 \%log_entry;
3767 sub fetch {
3768 my ($self, $min_rev, $max_rev, @parents) = @_;
3769 my ($last_rev, $last_commit) = $self->last_rev_commit;
3770 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
3771 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
3774 sub set_tree_cb {
3775 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
3776 $self->{inject_parents} = { $rev => $tree };
3777 $self->fetch(undef, undef);
3780 sub set_tree {
3781 my ($self, $tree) = (shift, shift);
3782 my $log_entry = ::get_commit_entry($tree);
3783 unless ($self->{last_rev}) {
3784 ::fatal("Must have an existing revision to commit");
3786 my %ed_opts = ( r => $self->{last_rev},
3787 log => $log_entry->{log},
3788 ra => $self->ra,
3789 tree_a => $self->{last_commit},
3790 tree_b => $tree,
3791 editor_cb => sub {
3792 $self->set_tree_cb($log_entry, $tree, @_) },
3793 svn_path => $self->{path} );
3794 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
3795 print "No changes\nr$self->{last_rev} = $tree\n";
3799 sub rebuild_from_rev_db {
3800 my ($self, $path) = @_;
3801 my $r = -1;
3802 open my $fh, '<', $path or croak "open: $!";
3803 binmode $fh or croak "binmode: $!";
3804 while (<$fh>) {
3805 length($_) == 41 or croak "inconsistent size in ($_) != 41";
3806 chomp($_);
3807 ++$r;
3808 next if $_ eq ('0' x 40);
3809 $self->rev_map_set($r, $_);
3810 print "r$r = $_\n";
3812 close $fh or croak "close: $!";
3813 unlink $path or croak "unlink: $!";
3816 sub rebuild {
3817 my ($self) = @_;
3818 my $map_path = $self->map_path;
3819 my $partial = (-e $map_path && ! -z $map_path);
3820 return unless ::verify_ref($self->refname.'^0');
3821 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
3822 my $rev_db = $self->rev_db_path;
3823 $self->rebuild_from_rev_db($rev_db);
3824 if ($self->use_svm_props) {
3825 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
3826 $self->rebuild_from_rev_db($svm_rev_db);
3828 $self->unlink_rev_db_symlink;
3829 return;
3831 print "Rebuilding $map_path ...\n" if (!$partial);
3832 my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
3833 (undef, undef));
3834 my ($log, $ctx) =
3835 command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
3836 ($head ? "$head.." : "") . $self->refname,
3837 '--');
3838 my $metadata_url = $self->metadata_url;
3839 remove_username($metadata_url);
3840 my $svn_uuid = $self->rewrite_uuid || $self->ra_uuid;
3841 my $c;
3842 while (<$log>) {
3843 if ( m{^commit ($::sha1)$} ) {
3844 $c = $1;
3845 next;
3847 next unless s{^\s*(git-svn-id:)}{$1};
3848 my ($url, $rev, $uuid) = ::extract_metadata($_);
3849 remove_username($url);
3851 # ignore merges (from set-tree)
3852 next if (!defined $rev || !$uuid);
3854 # if we merged or otherwise started elsewhere, this is
3855 # how we break out of it
3856 if (($uuid ne $svn_uuid) ||
3857 ($metadata_url && $url && ($url ne $metadata_url))) {
3858 next;
3860 if ($partial && $head) {
3861 print "Partial-rebuilding $map_path ...\n";
3862 print "Currently at $base_rev = $head\n";
3863 $head = undef;
3866 $self->rev_map_set($rev, $c);
3867 print "r$rev = $c\n";
3869 command_close_pipe($log, $ctx);
3870 print "Done rebuilding $map_path\n" if (!$partial || !$head);
3871 my $rev_db_path = $self->rev_db_path;
3872 if (-f $self->rev_db_path) {
3873 unlink $self->rev_db_path or croak "unlink: $!";
3875 $self->unlink_rev_db_symlink;
3878 # rev_map:
3879 # Tie::File seems to be prone to offset errors if revisions get sparse,
3880 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
3881 # one of my favorite modules is out :< Next up would be one of the DBM
3882 # modules, but I'm not sure which is most portable...
3884 # This is the replacement for the rev_db format, which was too big
3885 # and inefficient for large repositories with a lot of sparse history
3886 # (mainly tags)
3888 # The format is this:
3889 # - 24 bytes for every record,
3890 # * 4 bytes for the integer representing an SVN revision number
3891 # * 20 bytes representing the sha1 of a git commit
3892 # - No empty padding records like the old format
3893 # (except the last record, which can be overwritten)
3894 # - new records are written append-only since SVN revision numbers
3895 # increase monotonically
3896 # - lookups on SVN revision number are done via a binary search
3897 # - Piping the file to xxd -c24 is a good way of dumping it for
3898 # viewing or editing (piped back through xxd -r), should the need
3899 # ever arise.
3900 # - The last record can be padding revision with an all-zero sha1
3901 # This is used to optimize fetch performance when using multiple
3902 # "fetch" directives in .git/config
3904 # These files are disposable unless noMetadata or useSvmProps is set
3906 sub _rev_map_set {
3907 my ($fh, $rev, $commit) = @_;
3909 binmode $fh or croak "binmode: $!";
3910 my $size = (stat($fh))[7];
3911 ($size % 24) == 0 or croak "inconsistent size: $size";
3913 my $wr_offset = 0;
3914 if ($size > 0) {
3915 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3916 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
3917 $read == 24 or croak "read only $read bytes (!= 24)";
3918 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
3919 if ($last_commit eq ('0' x40)) {
3920 if ($size >= 48) {
3921 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3922 $read = sysread($fh, $buf, 24) or
3923 croak "read: $!";
3924 $read == 24 or
3925 croak "read only $read bytes (!= 24)";
3926 ($last_rev, $last_commit) =
3927 unpack(rev_map_fmt, $buf);
3928 if ($last_commit eq ('0' x40)) {
3929 croak "inconsistent .rev_map\n";
3932 if ($last_rev >= $rev) {
3933 croak "last_rev is higher!: $last_rev >= $rev";
3935 $wr_offset = -24;
3938 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
3939 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
3940 croak "write: $!";
3943 sub _rev_map_reset {
3944 my ($fh, $rev, $commit) = @_;
3945 my $c = _rev_map_get($fh, $rev);
3946 $c eq $commit or die "_rev_map_reset(@_) commit $c does not match!\n";
3947 my $offset = sysseek($fh, 0, SEEK_CUR) or croak "seek: $!";
3948 truncate $fh, $offset or croak "truncate: $!";
3951 sub mkfile {
3952 my ($path) = @_;
3953 unless (-e $path) {
3954 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
3955 mkpath([$dir]) unless -d $dir;
3956 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
3957 close $fh or die "Couldn't close (create) $path: $!\n";
3961 sub rev_map_set {
3962 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
3963 defined $commit or die "missing arg3\n";
3964 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
3965 my $db = $self->map_path($uuid);
3966 my $db_lock = "$db.lock";
3967 my $sig;
3968 $update_ref ||= 0;
3969 if ($update_ref) {
3970 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3971 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
3973 mkfile($db);
3975 $LOCKFILES{$db_lock} = 1;
3976 my $sync;
3977 # both of these options make our .rev_db file very, very important
3978 # and we can't afford to lose it because rebuild() won't work
3979 if ($self->use_svm_props || $self->no_metadata) {
3980 $sync = 1;
3981 copy($db, $db_lock) or die "rev_map_set(@_): ",
3982 "Failed to copy: ",
3983 "$db => $db_lock ($!)\n";
3984 } else {
3985 rename $db, $db_lock or die "rev_map_set(@_): ",
3986 "Failed to rename: ",
3987 "$db => $db_lock ($!)\n";
3990 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
3991 or croak "Couldn't open $db_lock: $!\n";
3992 $update_ref eq 'reset' ? _rev_map_reset($fh, $rev, $commit) :
3993 _rev_map_set($fh, $rev, $commit);
3994 if ($sync) {
3995 $fh->flush or die "Couldn't flush $db_lock: $!\n";
3996 $fh->sync or die "Couldn't sync $db_lock: $!\n";
3998 close $fh or croak $!;
3999 if ($update_ref) {
4000 $_head = $self;
4001 my $note = "";
4002 $note = " ($update_ref)" if ($update_ref !~ /^\d*$/);
4003 command_noisy('update-ref', '-m', "r$rev$note",
4004 $self->refname, $commit);
4006 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
4007 "$db_lock => $db ($!)\n";
4008 delete $LOCKFILES{$db_lock};
4009 if ($update_ref) {
4010 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
4011 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
4012 kill $sig, $$ if defined $sig;
4016 # If want_commit, this will return an array of (rev, commit) where
4017 # commit _must_ be a valid commit in the archive.
4018 # Otherwise, it'll return the max revision (whether or not the
4019 # commit is valid or just a 0x40 placeholder).
4020 sub rev_map_max {
4021 my ($self, $want_commit) = @_;
4022 $self->rebuild;
4023 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
4024 $want_commit ? ($r, $c) : $r;
4027 sub rev_map_max_norebuild {
4028 my ($self, $want_commit) = @_;
4029 my $map_path = $self->map_path;
4030 stat $map_path or return $want_commit ? (0, undef) : 0;
4031 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
4032 binmode $fh or croak "binmode: $!";
4033 my $size = (stat($fh))[7];
4034 ($size % 24) == 0 or croak "inconsistent size: $size";
4036 if ($size == 0) {
4037 close $fh or croak "close: $!";
4038 return $want_commit ? (0, undef) : 0;
4041 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
4042 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
4043 my ($r, $c) = unpack(rev_map_fmt, $buf);
4044 if ($want_commit && $c eq ('0' x40)) {
4045 if ($size < 48) {
4046 return $want_commit ? (0, undef) : 0;
4048 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
4049 sysread($fh, $buf, 24) == 24 or croak "read: $!";
4050 ($r, $c) = unpack(rev_map_fmt, $buf);
4051 if ($c eq ('0'x40)) {
4052 croak "Penultimate record is all-zeroes in $map_path";
4055 close $fh or croak "close: $!";
4056 $want_commit ? ($r, $c) : $r;
4059 sub rev_map_get {
4060 my ($self, $rev, $uuid) = @_;
4061 my $map_path = $self->map_path($uuid);
4062 return undef unless -e $map_path;
4064 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
4065 my $c = _rev_map_get($fh, $rev);
4066 close($fh) or croak "close: $!";
4070 sub _rev_map_get {
4071 my ($fh, $rev) = @_;
4073 binmode $fh or croak "binmode: $!";
4074 my $size = (stat($fh))[7];
4075 ($size % 24) == 0 or croak "inconsistent size: $size";
4077 if ($size == 0) {
4078 return undef;
4081 my ($l, $u) = (0, $size - 24);
4082 my ($r, $c, $buf);
4084 while ($l <= $u) {
4085 my $i = int(($l/24 + $u/24) / 2) * 24;
4086 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
4087 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
4088 my ($r, $c) = unpack(rev_map_fmt, $buf);
4090 if ($r < $rev) {
4091 $l = $i + 24;
4092 } elsif ($r > $rev) {
4093 $u = $i - 24;
4094 } else { # $r == $rev
4095 return $c eq ('0' x 40) ? undef : $c;
4098 undef;
4101 # Finds the first svn revision that exists on (if $eq_ok is true) or
4102 # before $rev for the current branch. It will not search any lower
4103 # than $min_rev. Returns the git commit hash and svn revision number
4104 # if found, else (undef, undef).
4105 sub find_rev_before {
4106 my ($self, $rev, $eq_ok, $min_rev) = @_;
4107 --$rev unless $eq_ok;
4108 $min_rev ||= 1;
4109 my $max_rev = $self->rev_map_max;
4110 $rev = $max_rev if ($rev > $max_rev);
4111 while ($rev >= $min_rev) {
4112 if (my $c = $self->rev_map_get($rev)) {
4113 return ($rev, $c);
4115 --$rev;
4117 return (undef, undef);
4120 # Finds the first svn revision that exists on (if $eq_ok is true) or
4121 # after $rev for the current branch. It will not search any higher
4122 # than $max_rev. Returns the git commit hash and svn revision number
4123 # if found, else (undef, undef).
4124 sub find_rev_after {
4125 my ($self, $rev, $eq_ok, $max_rev) = @_;
4126 ++$rev unless $eq_ok;
4127 $max_rev ||= $self->rev_map_max;
4128 while ($rev <= $max_rev) {
4129 if (my $c = $self->rev_map_get($rev)) {
4130 return ($rev, $c);
4132 ++$rev;
4134 return (undef, undef);
4137 sub _new {
4138 my ($class, $repo_id, $ref_id, $path) = @_;
4139 unless (defined $repo_id && length $repo_id) {
4140 $repo_id = $Git::SVN::default_repo_id;
4142 unless (defined $ref_id && length $ref_id) {
4143 $_prefix = '' unless defined($_prefix);
4144 $_[2] = $ref_id =
4145 "refs/remotes/$_prefix$Git::SVN::default_ref_id";
4147 $_[1] = $repo_id;
4148 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
4150 # Older repos imported by us used $GIT_DIR/svn/foo instead of
4151 # $GIT_DIR/svn/refs/remotes/foo when tracking refs/remotes/foo
4152 if ($ref_id =~ m{^refs/remotes/(.*)}) {
4153 my $old_dir = "$ENV{GIT_DIR}/svn/$1";
4154 if (-d $old_dir && ! -d $dir) {
4155 $dir = $old_dir;
4159 $_[3] = $path = '' unless (defined $path);
4160 mkpath([$dir]);
4161 bless {
4162 ref_id => $ref_id, dir => $dir, index => "$dir/index",
4163 path => $path, config => "$ENV{GIT_DIR}/svn/config",
4164 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
4167 # for read-only access of old .rev_db formats
4168 sub unlink_rev_db_symlink {
4169 my ($self) = @_;
4170 my $link = $self->rev_db_path;
4171 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
4172 if (-l $link) {
4173 unlink $link or croak "unlink: $link failed!";
4177 sub rev_db_path {
4178 my ($self, $uuid) = @_;
4179 my $db_path = $self->map_path($uuid);
4180 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
4181 or croak "map_path: $db_path does not contain '/.rev_map.' !";
4182 $db_path;
4185 # the new replacement for .rev_db
4186 sub map_path {
4187 my ($self, $uuid) = @_;
4188 $uuid ||= $self->ra_uuid;
4189 "$self->{map_root}.$uuid";
4192 sub uri_encode {
4193 my ($f) = @_;
4194 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
4198 sub uri_decode {
4199 my ($f) = @_;
4200 $f =~ s#%([0-9a-fA-F]{2})#chr(hex($1))#eg;
4204 sub remove_username {
4205 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
4208 package Git::SVN::Prompt;
4209 use strict;
4210 use warnings;
4211 require SVN::Core;
4212 use vars qw/$_no_auth_cache $_username/;
4214 sub simple {
4215 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
4216 $may_save = undef if $_no_auth_cache;
4217 $default_username = $_username if defined $_username;
4218 if (defined $default_username && length $default_username) {
4219 if (defined $realm && length $realm) {
4220 print STDERR "Authentication realm: $realm\n";
4221 STDERR->flush;
4223 $cred->username($default_username);
4224 } else {
4225 username($cred, $realm, $may_save, $pool);
4227 $cred->password(_read_password("Password for '" .
4228 $cred->username . "': ", $realm));
4229 $cred->may_save($may_save);
4230 $SVN::_Core::SVN_NO_ERROR;
4233 sub ssl_server_trust {
4234 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
4235 $may_save = undef if $_no_auth_cache;
4236 print STDERR "Error validating server certificate for '$realm':\n";
4238 no warnings 'once';
4239 # All variables SVN::Auth::SSL::* are used only once,
4240 # so we're shutting up Perl warnings about this.
4241 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
4242 print STDERR " - The certificate is not issued ",
4243 "by a trusted authority. Use the\n",
4244 " fingerprint to validate ",
4245 "the certificate manually!\n";
4247 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
4248 print STDERR " - The certificate hostname ",
4249 "does not match.\n";
4251 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
4252 print STDERR " - The certificate is not yet valid.\n";
4254 if ($failures & $SVN::Auth::SSL::EXPIRED) {
4255 print STDERR " - The certificate has expired.\n";
4257 if ($failures & $SVN::Auth::SSL::OTHER) {
4258 print STDERR " - The certificate has ",
4259 "an unknown error.\n";
4261 } # no warnings 'once'
4262 printf STDERR
4263 "Certificate information:\n".
4264 " - Hostname: %s\n".
4265 " - Valid: from %s until %s\n".
4266 " - Issuer: %s\n".
4267 " - Fingerprint: %s\n",
4268 map $cert_info->$_, qw(hostname valid_from valid_until
4269 issuer_dname fingerprint);
4270 my $choice;
4271 prompt:
4272 print STDERR $may_save ?
4273 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
4274 "(R)eject or accept (t)emporarily? ";
4275 STDERR->flush;
4276 $choice = lc(substr(<STDIN> || 'R', 0, 1));
4277 if ($choice =~ /^t$/i) {
4278 $cred->may_save(undef);
4279 } elsif ($choice =~ /^r$/i) {
4280 return -1;
4281 } elsif ($may_save && $choice =~ /^p$/i) {
4282 $cred->may_save($may_save);
4283 } else {
4284 goto prompt;
4286 $cred->accepted_failures($failures);
4287 $SVN::_Core::SVN_NO_ERROR;
4290 sub ssl_client_cert {
4291 my ($cred, $realm, $may_save, $pool) = @_;
4292 $may_save = undef if $_no_auth_cache;
4293 print STDERR "Client certificate filename: ";
4294 STDERR->flush;
4295 chomp(my $filename = <STDIN>);
4296 $cred->cert_file($filename);
4297 $cred->may_save($may_save);
4298 $SVN::_Core::SVN_NO_ERROR;
4301 sub ssl_client_cert_pw {
4302 my ($cred, $realm, $may_save, $pool) = @_;
4303 $may_save = undef if $_no_auth_cache;
4304 $cred->password(_read_password("Password: ", $realm));
4305 $cred->may_save($may_save);
4306 $SVN::_Core::SVN_NO_ERROR;
4309 sub username {
4310 my ($cred, $realm, $may_save, $pool) = @_;
4311 $may_save = undef if $_no_auth_cache;
4312 if (defined $realm && length $realm) {
4313 print STDERR "Authentication realm: $realm\n";
4315 my $username;
4316 if (defined $_username) {
4317 $username = $_username;
4318 } else {
4319 print STDERR "Username: ";
4320 STDERR->flush;
4321 chomp($username = <STDIN>);
4323 $cred->username($username);
4324 $cred->may_save($may_save);
4325 $SVN::_Core::SVN_NO_ERROR;
4328 sub _read_password {
4329 my ($prompt, $realm) = @_;
4330 my $password = '';
4331 if (exists $ENV{GIT_ASKPASS}) {
4332 open(PH, "-|", $ENV{GIT_ASKPASS}, $prompt);
4333 $password = <PH>;
4334 $password =~ s/[\012\015]//; # \n\r
4335 close(PH);
4336 } else {
4337 print STDERR $prompt;
4338 STDERR->flush;
4339 require Term::ReadKey;
4340 Term::ReadKey::ReadMode('noecho');
4341 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
4342 last if $key =~ /[\012\015]/; # \n\r
4343 $password .= $key;
4345 Term::ReadKey::ReadMode('restore');
4346 print STDERR "\n";
4347 STDERR->flush;
4349 $password;
4352 package SVN::Git::Fetcher;
4353 use vars qw/@ISA $_ignore_regex $_preserve_empty_dirs $_placeholder_filename
4354 @deleted_gpath %added_placeholder $repo_id/;
4355 use strict;
4356 use warnings;
4357 use Carp qw/croak/;
4358 use File::Basename qw/dirname/;
4359 use IO::File qw//;
4361 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
4362 sub new {
4363 my ($class, $git_svn, $switch_path) = @_;
4364 my $self = SVN::Delta::Editor->new;
4365 bless $self, $class;
4366 if (exists $git_svn->{last_commit}) {
4367 $self->{c} = $git_svn->{last_commit};
4368 $self->{empty_symlinks} =
4369 _mark_empty_symlinks($git_svn, $switch_path);
4372 # some options are read globally, but can be overridden locally
4373 # per [svn-remote "..."] section. Command-line options will *NOT*
4374 # override options set in an [svn-remote "..."] section
4375 $repo_id = $git_svn->{repo_id};
4376 my $k = "svn-remote.$repo_id.ignore-paths";
4377 my $v = eval { command_oneline('config', '--get', $k) };
4378 $self->{ignore_regex} = $v;
4380 $k = "svn-remote.$repo_id.preserve-empty-dirs";
4381 $v = eval { command_oneline('config', '--get', '--bool', $k) };
4382 if ($v && $v eq 'true') {
4383 $_preserve_empty_dirs = 1;
4384 $k = "svn-remote.$repo_id.placeholder-filename";
4385 $v = eval { command_oneline('config', '--get', $k) };
4386 $_placeholder_filename = $v;
4389 # Load the list of placeholder files added during previous invocations.
4390 $k = "svn-remote.$repo_id.added-placeholder";
4391 $v = eval { command_oneline('config', '--get-all', $k) };
4392 if ($_preserve_empty_dirs && $v) {
4393 # command() prints errors to stderr, so we only call it if
4394 # command_oneline() succeeded.
4395 my @v = command('config', '--get-all', $k);
4396 $added_placeholder{ dirname($_) } = $_ foreach @v;
4399 $self->{empty} = {};
4400 $self->{dir_prop} = {};
4401 $self->{file_prop} = {};
4402 $self->{absent_dir} = {};
4403 $self->{absent_file} = {};
4404 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
4405 $self->{pathnameencoding} = Git::config('svn.pathnameencoding');
4406 $self;
4409 # this uses the Ra object, so it must be called before do_{switch,update},
4410 # not inside them (when the Git::SVN::Fetcher object is passed) to
4411 # do_{switch,update}
4412 sub _mark_empty_symlinks {
4413 my ($git_svn, $switch_path) = @_;
4414 my $bool = Git::config_bool('svn.brokenSymlinkWorkaround');
4415 return {} if (!defined($bool)) || (defined($bool) && ! $bool);
4417 my %ret;
4418 my ($rev, $cmt) = $git_svn->last_rev_commit;
4419 return {} unless ($rev && $cmt);
4421 # allow the warning to be printed for each revision we fetch to
4422 # ensure the user sees it. The user can also disable the workaround
4423 # on the repository even while git svn is running and the next
4424 # revision fetched will skip this expensive function.
4425 my $printed_warning;
4426 chomp(my $empty_blob = `git hash-object -t blob --stdin < /dev/null`);
4427 my ($ls, $ctx) = command_output_pipe(qw/ls-tree -r -z/, $cmt);
4428 local $/ = "\0";
4429 my $pfx = defined($switch_path) ? $switch_path : $git_svn->{path};
4430 $pfx .= '/' if length($pfx);
4431 while (<$ls>) {
4432 chomp;
4433 s/\A100644 blob $empty_blob\t//o or next;
4434 unless ($printed_warning) {
4435 print STDERR "Scanning for empty symlinks, ",
4436 "this may take a while if you have ",
4437 "many empty files\n",
4438 "You may disable this with `",
4439 "git config svn.brokenSymlinkWorkaround ",
4440 "false'.\n",
4441 "This may be done in a different ",
4442 "terminal without restarting ",
4443 "git svn\n";
4444 $printed_warning = 1;
4446 my $path = $_;
4447 my (undef, $props) =
4448 $git_svn->ra->get_file($pfx.$path, $rev, undef);
4449 if ($props->{'svn:special'}) {
4450 $ret{$path} = 1;
4453 command_close_pipe($ls, $ctx);
4454 \%ret;
4457 # returns true if a given path is inside a ".git" directory
4458 sub in_dot_git {
4459 $_[0] =~ m{(?:^|/)\.git(?:/|$)};
4462 # return value: 0 -- don't ignore, 1 -- ignore
4463 sub is_path_ignored {
4464 my ($self, $path) = @_;
4465 return 1 if in_dot_git($path);
4466 return 1 if defined($self->{ignore_regex}) &&
4467 $path =~ m!$self->{ignore_regex}!;
4468 return 0 unless defined($_ignore_regex);
4469 return 1 if $path =~ m!$_ignore_regex!o;
4470 return 0;
4473 sub set_path_strip {
4474 my ($self, $path) = @_;
4475 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
4478 sub open_root {
4479 { path => '' };
4482 sub open_directory {
4483 my ($self, $path, $pb, $rev) = @_;
4484 { path => $path };
4487 sub git_path {
4488 my ($self, $path) = @_;
4489 if (my $enc = $self->{pathnameencoding}) {
4490 require Encode;
4491 Encode::from_to($path, 'UTF-8', $enc);
4493 if ($self->{path_strip}) {
4494 $path =~ s!$self->{path_strip}!! or
4495 die "Failed to strip path '$path' ($self->{path_strip})\n";
4497 $path;
4500 sub delete_entry {
4501 my ($self, $path, $rev, $pb) = @_;
4502 return undef if $self->is_path_ignored($path);
4504 my $gpath = $self->git_path($path);
4505 return undef if ($gpath eq '');
4507 # remove entire directories.
4508 my ($tree) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
4509 =~ /\A040000 tree ([a-f\d]{40})\t\Q$gpath\E\0/);
4510 if ($tree) {
4511 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
4512 -r --name-only -z/,
4513 $tree);
4514 local $/ = "\0";
4515 while (<$ls>) {
4516 chomp;
4517 my $rmpath = "$gpath/$_";
4518 $self->{gii}->remove($rmpath);
4519 print "\tD\t$rmpath\n" unless $::_q;
4521 print "\tD\t$gpath/\n" unless $::_q;
4522 command_close_pipe($ls, $ctx);
4523 } else {
4524 $self->{gii}->remove($gpath);
4525 print "\tD\t$gpath\n" unless $::_q;
4527 # Don't add to @deleted_gpath if we're deleting a placeholder file.
4528 push @deleted_gpath, $gpath unless $added_placeholder{dirname($path)};
4529 $self->{empty}->{$path} = 0;
4530 undef;
4533 sub open_file {
4534 my ($self, $path, $pb, $rev) = @_;
4535 my ($mode, $blob);
4537 goto out if $self->is_path_ignored($path);
4539 my $gpath = $self->git_path($path);
4540 ($mode, $blob) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
4541 =~ /\A(\d{6}) blob ([a-f\d]{40})\t\Q$gpath\E\0/);
4542 unless (defined $mode && defined $blob) {
4543 die "$path was not found in commit $self->{c} (r$rev)\n";
4545 if ($mode eq '100644' && $self->{empty_symlinks}->{$path}) {
4546 $mode = '120000';
4548 out:
4549 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
4550 pool => SVN::Pool->new, action => 'M' };
4553 sub add_file {
4554 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
4555 my $mode;
4557 if (!$self->is_path_ignored($path)) {
4558 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
4559 delete $self->{empty}->{$dir};
4560 $mode = '100644';
4562 if ($added_placeholder{$dir}) {
4563 # Remove our placeholder file, if we created one.
4564 delete_entry($self, $added_placeholder{$dir})
4565 unless $path eq $added_placeholder{$dir};
4566 delete $added_placeholder{$dir}
4570 { path => $path, mode_a => $mode, mode_b => $mode,
4571 pool => SVN::Pool->new, action => 'A' };
4574 sub add_directory {
4575 my ($self, $path, $cp_path, $cp_rev) = @_;
4576 goto out if $self->is_path_ignored($path);
4577 my $gpath = $self->git_path($path);
4578 if ($gpath eq '') {
4579 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
4580 -r --name-only -z/,
4581 $self->{c});
4582 local $/ = "\0";
4583 while (<$ls>) {
4584 chomp;
4585 $self->{gii}->remove($_);
4586 print "\tD\t$_\n" unless $::_q;
4587 push @deleted_gpath, $gpath;
4589 command_close_pipe($ls, $ctx);
4590 $self->{empty}->{$path} = 0;
4592 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
4593 delete $self->{empty}->{$dir};
4594 $self->{empty}->{$path} = 1;
4596 if ($added_placeholder{$dir}) {
4597 # Remove our placeholder file, if we created one.
4598 delete_entry($self, $added_placeholder{$dir});
4599 delete $added_placeholder{$dir}
4602 out:
4603 { path => $path };
4606 sub change_dir_prop {
4607 my ($self, $db, $prop, $value) = @_;
4608 return undef if $self->is_path_ignored($db->{path});
4609 $self->{dir_prop}->{$db->{path}} ||= {};
4610 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
4611 undef;
4614 sub absent_directory {
4615 my ($self, $path, $pb) = @_;
4616 return undef if $self->is_path_ignored($path);
4617 $self->{absent_dir}->{$pb->{path}} ||= [];
4618 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
4619 undef;
4622 sub absent_file {
4623 my ($self, $path, $pb) = @_;
4624 return undef if $self->is_path_ignored($path);
4625 $self->{absent_file}->{$pb->{path}} ||= [];
4626 push @{$self->{absent_file}->{$pb->{path}}}, $path;
4627 undef;
4630 sub change_file_prop {
4631 my ($self, $fb, $prop, $value) = @_;
4632 return undef if $self->is_path_ignored($fb->{path});
4633 if ($prop eq 'svn:executable') {
4634 if ($fb->{mode_b} != 120000) {
4635 $fb->{mode_b} = defined $value ? 100755 : 100644;
4637 } elsif ($prop eq 'svn:special') {
4638 $fb->{mode_b} = defined $value ? 120000 : 100644;
4639 } else {
4640 $self->{file_prop}->{$fb->{path}} ||= {};
4641 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
4643 undef;
4646 sub apply_textdelta {
4647 my ($self, $fb, $exp) = @_;
4648 return undef if $self->is_path_ignored($fb->{path});
4649 my $fh = $::_repository->temp_acquire('svn_delta');
4650 # $fh gets auto-closed() by SVN::TxDelta::apply(),
4651 # (but $base does not,) so dup() it for reading in close_file
4652 open my $dup, '<&', $fh or croak $!;
4653 my $base = $::_repository->temp_acquire('git_blob');
4655 if ($fb->{blob}) {
4656 my ($base_is_link, $size);
4658 if ($fb->{mode_a} eq '120000' &&
4659 ! $self->{empty_symlinks}->{$fb->{path}}) {
4660 print $base 'link ' or die "print $!\n";
4661 $base_is_link = 1;
4663 retry:
4664 $size = $::_repository->cat_blob($fb->{blob}, $base);
4665 die "Failed to read object $fb->{blob}" if ($size < 0);
4667 if (defined $exp) {
4668 seek $base, 0, 0 or croak $!;
4669 my $got = ::md5sum($base);
4670 if ($got ne $exp) {
4671 my $err = "Checksum mismatch: ".
4672 "$fb->{path} $fb->{blob}\n" .
4673 "expected: $exp\n" .
4674 " got: $got\n";
4675 if ($base_is_link) {
4676 warn $err,
4677 "Retrying... (possibly ",
4678 "a bad symlink from SVN)\n";
4679 $::_repository->temp_reset($base);
4680 $base_is_link = 0;
4681 goto retry;
4683 die $err;
4687 seek $base, 0, 0 or croak $!;
4688 $fb->{fh} = $fh;
4689 $fb->{base} = $base;
4690 [ SVN::TxDelta::apply($base, $dup, undef, $fb->{path}, $fb->{pool}) ];
4693 sub close_file {
4694 my ($self, $fb, $exp) = @_;
4695 return undef if $self->is_path_ignored($fb->{path});
4697 my $hash;
4698 my $path = $self->git_path($fb->{path});
4699 if (my $fh = $fb->{fh}) {
4700 if (defined $exp) {
4701 seek($fh, 0, 0) or croak $!;
4702 my $got = ::md5sum($fh);
4703 if ($got ne $exp) {
4704 die "Checksum mismatch: $path\n",
4705 "expected: $exp\n got: $got\n";
4708 if ($fb->{mode_b} == 120000) {
4709 sysseek($fh, 0, 0) or croak $!;
4710 my $rd = sysread($fh, my $buf, 5);
4712 if (!defined $rd) {
4713 croak "sysread: $!\n";
4714 } elsif ($rd == 0) {
4715 warn "$path has mode 120000",
4716 " but it points to nothing\n",
4717 "converting to an empty file with mode",
4718 " 100644\n";
4719 $fb->{mode_b} = '100644';
4720 } elsif ($buf ne 'link ') {
4721 warn "$path has mode 120000",
4722 " but is not a link\n";
4723 } else {
4724 my $tmp_fh = $::_repository->temp_acquire(
4725 'svn_hash');
4726 my $res;
4727 while ($res = sysread($fh, my $str, 1024)) {
4728 my $out = syswrite($tmp_fh, $str, $res);
4729 defined($out) && $out == $res
4730 or croak("write ",
4731 Git::temp_path($tmp_fh),
4732 ": $!\n");
4734 defined $res or croak $!;
4736 ($fh, $tmp_fh) = ($tmp_fh, $fh);
4737 Git::temp_release($tmp_fh, 1);
4741 $hash = $::_repository->hash_and_insert_object(
4742 Git::temp_path($fh));
4743 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
4745 Git::temp_release($fb->{base}, 1);
4746 Git::temp_release($fh, 1);
4747 } else {
4748 $hash = $fb->{blob} or die "no blob information\n";
4750 $fb->{pool}->clear;
4751 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
4752 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
4753 undef;
4756 sub abort_edit {
4757 my $self = shift;
4758 $self->{nr} = $self->{gii}->{nr};
4759 delete $self->{gii};
4760 $self->SUPER::abort_edit(@_);
4763 sub close_edit {
4764 my $self = shift;
4766 if ($_preserve_empty_dirs) {
4767 my @empty_dirs;
4769 # Any entry flagged as empty that also has an associated
4770 # dir_prop represents a newly created empty directory.
4771 foreach my $i (keys %{$self->{empty}}) {
4772 push @empty_dirs, $i if exists $self->{dir_prop}->{$i};
4775 # Search for directories that have become empty due subsequent
4776 # file deletes.
4777 push @empty_dirs, $self->find_empty_directories();
4779 # Finally, add a placeholder file to each empty directory.
4780 $self->add_placeholder_file($_) foreach (@empty_dirs);
4782 $self->stash_placeholder_list();
4785 $self->{git_commit_ok} = 1;
4786 $self->{nr} = $self->{gii}->{nr};
4787 delete $self->{gii};
4788 $self->SUPER::close_edit(@_);
4791 sub find_empty_directories {
4792 my ($self) = @_;
4793 my @empty_dirs;
4794 my %dirs = map { dirname($_) => 1 } @deleted_gpath;
4796 foreach my $dir (sort keys %dirs) {
4797 next if $dir eq ".";
4799 # If there have been any additions to this directory, there is
4800 # no reason to check if it is empty.
4801 my $skip_added = 0;
4802 foreach my $t (qw/dir_prop file_prop/) {
4803 foreach my $path (keys %{ $self->{$t} }) {
4804 if (exists $self->{$t}->{dirname($path)}) {
4805 $skip_added = 1;
4806 last;
4809 last if $skip_added;
4811 next if $skip_added;
4813 # Use `git ls-tree` to get the filenames of this directory
4814 # that existed prior to this particular commit.
4815 my $ls = command('ls-tree', '-z', '--name-only',
4816 $self->{c}, "$dir/");
4817 my %files = map { $_ => 1 } split(/\0/, $ls);
4819 # Remove the filenames that were deleted during this commit.
4820 delete $files{$_} foreach (@deleted_gpath);
4822 # Report the directory if there are no filenames left.
4823 push @empty_dirs, $dir unless (scalar %files);
4825 @empty_dirs;
4828 sub add_placeholder_file {
4829 my ($self, $dir) = @_;
4830 my $path = "$dir/$_placeholder_filename";
4831 my $gpath = $self->git_path($path);
4833 my $fh = $::_repository->temp_acquire($gpath);
4834 my $hash = $::_repository->hash_and_insert_object(Git::temp_path($fh));
4835 Git::temp_release($fh, 1);
4836 $self->{gii}->update('100644', $hash, $gpath) or croak $!;
4838 # The directory should no longer be considered empty.
4839 delete $self->{empty}->{$dir} if exists $self->{empty}->{$dir};
4841 # Keep track of any placeholder files we create.
4842 $added_placeholder{$dir} = $path;
4845 sub stash_placeholder_list {
4846 my ($self) = @_;
4847 my $k = "svn-remote.$repo_id.added-placeholder";
4848 my $v = eval { command_oneline('config', '--get-all', $k) };
4849 command_noisy('config', '--unset-all', $k) if $v;
4850 foreach (values %added_placeholder) {
4851 command_noisy('config', '--add', $k, $_);
4855 package SVN::Git::Editor;
4856 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
4857 use strict;
4858 use warnings;
4859 use Carp qw/croak/;
4860 use IO::File;
4862 sub new {
4863 my ($class, $opts) = @_;
4864 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
4865 die "$_ required!\n" unless (defined $opts->{$_});
4868 my $pool = SVN::Pool->new;
4869 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
4870 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
4871 $opts->{r}, $mods);
4873 # $opts->{ra} functions should not be used after this:
4874 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
4875 $opts->{editor_cb}, $pool);
4876 my $self = SVN::Delta::Editor->new(@ce, $pool);
4877 bless $self, $class;
4878 foreach (qw/svn_path r tree_a tree_b/) {
4879 $self->{$_} = $opts->{$_};
4881 $self->{url} = $opts->{ra}->{url};
4882 $self->{mods} = $mods;
4883 $self->{types} = $types;
4884 $self->{pool} = $pool;
4885 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
4886 $self->{rm} = { };
4887 $self->{path_prefix} = length $self->{svn_path} ?
4888 "$self->{svn_path}/" : '';
4889 $self->{config} = $opts->{config};
4890 $self->{mergeinfo} = $opts->{mergeinfo};
4891 return $self;
4894 sub generate_diff {
4895 my ($tree_a, $tree_b) = @_;
4896 my @diff_tree = qw(diff-tree -z -r);
4897 if ($_cp_similarity) {
4898 push @diff_tree, "-C$_cp_similarity";
4899 } else {
4900 push @diff_tree, '-C';
4902 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
4903 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
4904 push @diff_tree, $tree_a, $tree_b;
4905 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
4906 local $/ = "\0";
4907 my $state = 'meta';
4908 my @mods;
4909 while (<$diff_fh>) {
4910 chomp $_; # this gets rid of the trailing "\0"
4911 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
4912 ($::sha1)\s($::sha1)\s
4913 ([MTCRAD])\d*$/xo) {
4914 push @mods, { mode_a => $1, mode_b => $2,
4915 sha1_a => $3, sha1_b => $4,
4916 chg => $5 };
4917 if ($5 =~ /^(?:C|R)$/) {
4918 $state = 'file_a';
4919 } else {
4920 $state = 'file_b';
4922 } elsif ($state eq 'file_a') {
4923 my $x = $mods[$#mods] or croak "Empty array\n";
4924 if ($x->{chg} !~ /^(?:C|R)$/) {
4925 croak "Error parsing $_, $x->{chg}\n";
4927 $x->{file_a} = $_;
4928 $state = 'file_b';
4929 } elsif ($state eq 'file_b') {
4930 my $x = $mods[$#mods] or croak "Empty array\n";
4931 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
4932 croak "Error parsing $_, $x->{chg}\n";
4934 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
4935 croak "Error parsing $_, $x->{chg}\n";
4937 $x->{file_b} = $_;
4938 $state = 'meta';
4939 } else {
4940 croak "Error parsing $_\n";
4943 command_close_pipe($diff_fh, $ctx);
4944 \@mods;
4947 sub check_diff_paths {
4948 my ($ra, $pfx, $rev, $mods) = @_;
4949 my %types;
4950 $pfx .= '/' if length $pfx;
4952 sub type_diff_paths {
4953 my ($ra, $types, $path, $rev) = @_;
4954 my @p = split m#/+#, $path;
4955 my $c = shift @p;
4956 unless (defined $types->{$c}) {
4957 $types->{$c} = $ra->check_path($c, $rev);
4959 while (@p) {
4960 $c .= '/' . shift @p;
4961 next if defined $types->{$c};
4962 $types->{$c} = $ra->check_path($c, $rev);
4966 foreach my $m (@$mods) {
4967 foreach my $f (qw/file_a file_b/) {
4968 next unless defined $m->{$f};
4969 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
4970 if (length $pfx.$dir && ! defined $types{$dir}) {
4971 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
4975 \%types;
4978 sub split_path {
4979 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
4982 sub repo_path {
4983 my ($self, $path) = @_;
4984 if (my $enc = $self->{pathnameencoding}) {
4985 require Encode;
4986 Encode::from_to($path, $enc, 'UTF-8');
4988 $self->{path_prefix}.(defined $path ? $path : '');
4991 sub url_path {
4992 my ($self, $path) = @_;
4993 if ($self->{url} =~ m#^https?://#) {
4994 $path =~ s!([^~a-zA-Z0-9_./-])!uc sprintf("%%%02x",ord($1))!eg;
4996 $self->{url} . '/' . $self->repo_path($path);
4999 sub rmdirs {
5000 my ($self) = @_;
5001 my $rm = $self->{rm};
5002 delete $rm->{''}; # we never delete the url we're tracking
5003 return unless %$rm;
5005 foreach (keys %$rm) {
5006 my @d = split m#/#, $_;
5007 my $c = shift @d;
5008 $rm->{$c} = 1;
5009 while (@d) {
5010 $c .= '/' . shift @d;
5011 $rm->{$c} = 1;
5014 delete $rm->{$self->{svn_path}};
5015 delete $rm->{''}; # we never delete the url we're tracking
5016 return unless %$rm;
5018 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
5019 $self->{tree_b});
5020 local $/ = "\0";
5021 while (<$fh>) {
5022 chomp;
5023 my @dn = split m#/#, $_;
5024 while (pop @dn) {
5025 delete $rm->{join '/', @dn};
5027 unless (%$rm) {
5028 close $fh;
5029 return;
5032 command_close_pipe($fh, $ctx);
5034 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
5035 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
5036 $self->close_directory($bat->{$d}, $p);
5037 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
5038 print "\tD+\t$d/\n" unless $::_q;
5039 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
5040 delete $bat->{$d};
5044 sub open_or_add_dir {
5045 my ($self, $full_path, $baton) = @_;
5046 my $t = $self->{types}->{$full_path};
5047 if (!defined $t) {
5048 die "$full_path not known in r$self->{r} or we have a bug!\n";
5051 no warnings 'once';
5052 # SVN::Node::none and SVN::Node::file are used only once,
5053 # so we're shutting up Perl's warnings about them.
5054 if ($t == $SVN::Node::none) {
5055 return $self->add_directory($full_path, $baton,
5056 undef, -1, $self->{pool});
5057 } elsif ($t == $SVN::Node::dir) {
5058 return $self->open_directory($full_path, $baton,
5059 $self->{r}, $self->{pool});
5060 } # no warnings 'once'
5061 print STDERR "$full_path already exists in repository at ",
5062 "r$self->{r} and it is not a directory (",
5063 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
5064 } # no warnings 'once'
5065 exit 1;
5068 sub ensure_path {
5069 my ($self, $path) = @_;
5070 my $bat = $self->{bat};
5071 my $repo_path = $self->repo_path($path);
5072 return $bat->{''} unless (length $repo_path);
5073 my @p = split m#/+#, $repo_path;
5074 my $c = shift @p;
5075 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
5076 while (@p) {
5077 my $c0 = $c;
5078 $c .= '/' . shift @p;
5079 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
5081 return $bat->{$c};
5084 # Subroutine to convert a globbing pattern to a regular expression.
5085 # From perl cookbook.
5086 sub glob2pat {
5087 my $globstr = shift;
5088 my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
5089 $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
5090 return '^' . $globstr . '$';
5093 sub check_autoprop {
5094 my ($self, $pattern, $properties, $file, $fbat) = @_;
5095 # Convert the globbing pattern to a regular expression.
5096 my $regex = glob2pat($pattern);
5097 # Check if the pattern matches the file name.
5098 if($file =~ m/($regex)/) {
5099 # Parse the list of properties to set.
5100 my @props = split(/;/, $properties);
5101 foreach my $prop (@props) {
5102 # Parse 'name=value' syntax and set the property.
5103 if ($prop =~ /([^=]+)=(.*)/) {
5104 my ($n,$v) = ($1,$2);
5105 for ($n, $v) {
5106 s/^\s+//; s/\s+$//;
5108 $self->change_file_prop($fbat, $n, $v);
5114 sub apply_autoprops {
5115 my ($self, $file, $fbat) = @_;
5116 my $conf_t = ${$self->{config}}{'config'};
5117 no warnings 'once';
5118 # Check [miscellany]/enable-auto-props in svn configuration.
5119 if (SVN::_Core::svn_config_get_bool(
5120 $conf_t,
5121 $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
5122 $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
5123 0)) {
5124 # Auto-props are enabled. Enumerate them to look for matches.
5125 my $callback = sub {
5126 $self->check_autoprop($_[0], $_[1], $file, $fbat);
5128 SVN::_Core::svn_config_enumerate(
5129 $conf_t,
5130 $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
5131 $callback);
5135 sub A {
5136 my ($self, $m) = @_;
5137 my ($dir, $file) = split_path($m->{file_b});
5138 my $pbat = $self->ensure_path($dir);
5139 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
5140 undef, -1);
5141 print "\tA\t$m->{file_b}\n" unless $::_q;
5142 $self->apply_autoprops($file, $fbat);
5143 $self->chg_file($fbat, $m);
5144 $self->close_file($fbat,undef,$self->{pool});
5147 sub C {
5148 my ($self, $m) = @_;
5149 my ($dir, $file) = split_path($m->{file_b});
5150 my $pbat = $self->ensure_path($dir);
5151 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
5152 $self->url_path($m->{file_a}), $self->{r});
5153 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
5154 $self->chg_file($fbat, $m);
5155 $self->close_file($fbat,undef,$self->{pool});
5158 sub delete_entry {
5159 my ($self, $path, $pbat) = @_;
5160 my $rpath = $self->repo_path($path);
5161 my ($dir, $file) = split_path($rpath);
5162 $self->{rm}->{$dir} = 1;
5163 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
5166 sub R {
5167 my ($self, $m) = @_;
5168 my ($dir, $file) = split_path($m->{file_b});
5169 my $pbat = $self->ensure_path($dir);
5170 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
5171 $self->url_path($m->{file_a}), $self->{r});
5172 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
5173 $self->apply_autoprops($file, $fbat);
5174 $self->chg_file($fbat, $m);
5175 $self->close_file($fbat,undef,$self->{pool});
5177 ($dir, $file) = split_path($m->{file_a});
5178 $pbat = $self->ensure_path($dir);
5179 $self->delete_entry($m->{file_a}, $pbat);
5182 sub M {
5183 my ($self, $m) = @_;
5184 my ($dir, $file) = split_path($m->{file_b});
5185 my $pbat = $self->ensure_path($dir);
5186 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
5187 $pbat,$self->{r},$self->{pool});
5188 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
5189 $self->chg_file($fbat, $m);
5190 $self->close_file($fbat,undef,$self->{pool});
5193 sub T { shift->M(@_) }
5195 sub change_file_prop {
5196 my ($self, $fbat, $pname, $pval) = @_;
5197 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
5200 sub change_dir_prop {
5201 my ($self, $pbat, $pname, $pval) = @_;
5202 $self->SUPER::change_dir_prop($pbat, $pname, $pval, $self->{pool});
5205 sub _chg_file_get_blob ($$$$) {
5206 my ($self, $fbat, $m, $which) = @_;
5207 my $fh = $::_repository->temp_acquire("git_blob_$which");
5208 if ($m->{"mode_$which"} =~ /^120/) {
5209 print $fh 'link ' or croak $!;
5210 $self->change_file_prop($fbat,'svn:special','*');
5211 } elsif ($m->{mode_a} =~ /^120/ && $m->{"mode_$which"} !~ /^120/) {
5212 $self->change_file_prop($fbat,'svn:special',undef);
5214 my $blob = $m->{"sha1_$which"};
5215 return ($fh,) if ($blob =~ /^0{40}$/);
5216 my $size = $::_repository->cat_blob($blob, $fh);
5217 croak "Failed to read object $blob" if ($size < 0);
5218 $fh->flush == 0 or croak $!;
5219 seek $fh, 0, 0 or croak $!;
5221 my $exp = ::md5sum($fh);
5222 seek $fh, 0, 0 or croak $!;
5223 return ($fh, $exp);
5226 sub chg_file {
5227 my ($self, $fbat, $m) = @_;
5228 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
5229 $self->change_file_prop($fbat,'svn:executable','*');
5230 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
5231 $self->change_file_prop($fbat,'svn:executable',undef);
5233 my ($fh_a, $exp_a) = _chg_file_get_blob $self, $fbat, $m, 'a';
5234 my ($fh_b, $exp_b) = _chg_file_get_blob $self, $fbat, $m, 'b';
5235 my $pool = SVN::Pool->new;
5236 my $atd = $self->apply_textdelta($fbat, $exp_a, $pool);
5237 if (-s $fh_a) {
5238 my $txstream = SVN::TxDelta::new ($fh_a, $fh_b, $pool);
5239 my $res = SVN::TxDelta::send_txstream($txstream, @$atd, $pool);
5240 if (defined $res) {
5241 die "Unexpected result from send_txstream: $res\n",
5242 "(SVN::Core::VERSION: $SVN::Core::VERSION)\n";
5244 } else {
5245 my $got = SVN::TxDelta::send_stream($fh_b, @$atd, $pool);
5246 die "Checksum mismatch\nexpected: $exp_b\ngot: $got\n"
5247 if ($got ne $exp_b);
5249 Git::temp_release($fh_b, 1);
5250 Git::temp_release($fh_a, 1);
5251 $pool->clear;
5254 sub D {
5255 my ($self, $m) = @_;
5256 my ($dir, $file) = split_path($m->{file_b});
5257 my $pbat = $self->ensure_path($dir);
5258 print "\tD\t$m->{file_b}\n" unless $::_q;
5259 $self->delete_entry($m->{file_b}, $pbat);
5262 sub close_edit {
5263 my ($self) = @_;
5264 my ($p,$bat) = ($self->{pool}, $self->{bat});
5265 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
5266 next if $_ eq '';
5267 $self->close_directory($bat->{$_}, $p);
5269 $self->close_directory($bat->{''}, $p);
5270 $self->SUPER::close_edit($p);
5271 $p->clear;
5274 sub abort_edit {
5275 my ($self) = @_;
5276 $self->SUPER::abort_edit($self->{pool});
5279 sub DESTROY {
5280 my $self = shift;
5281 $self->SUPER::DESTROY(@_);
5282 $self->{pool}->clear;
5285 # this drives the editor
5286 sub apply_diff {
5287 my ($self) = @_;
5288 my $mods = $self->{mods};
5289 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
5290 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
5291 my $f = $m->{chg};
5292 if (defined $o{$f}) {
5293 $self->$f($m);
5294 } else {
5295 fatal("Invalid change type: $f");
5299 if (defined($self->{mergeinfo})) {
5300 $self->change_dir_prop($self->{bat}{''}, "svn:mergeinfo",
5301 $self->{mergeinfo});
5303 $self->rmdirs if $_rmdir;
5304 if (@$mods == 0) {
5305 $self->abort_edit;
5306 } else {
5307 $self->close_edit;
5309 return scalar @$mods;
5312 package Git::SVN::Ra;
5313 use vars qw/@ISA $config_dir $_log_window_size/;
5314 use strict;
5315 use warnings;
5316 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
5318 BEGIN {
5319 # enforce temporary pool usage for some simple functions
5320 no strict 'refs';
5321 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root
5322 get_file/) {
5323 my $SUPER = "SUPER::$f";
5324 *$f = sub {
5325 my $self = shift;
5326 my $pool = SVN::Pool->new;
5327 my @ret = $self->$SUPER(@_,$pool);
5328 $pool->clear;
5329 wantarray ? @ret : $ret[0];
5334 sub _auth_providers () {
5336 SVN::Client::get_simple_provider(),
5337 SVN::Client::get_ssl_server_trust_file_provider(),
5338 SVN::Client::get_simple_prompt_provider(
5339 \&Git::SVN::Prompt::simple, 2),
5340 SVN::Client::get_ssl_client_cert_file_provider(),
5341 SVN::Client::get_ssl_client_cert_prompt_provider(
5342 \&Git::SVN::Prompt::ssl_client_cert, 2),
5343 SVN::Client::get_ssl_client_cert_pw_file_provider(),
5344 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
5345 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
5346 SVN::Client::get_username_provider(),
5347 SVN::Client::get_ssl_server_trust_prompt_provider(
5348 \&Git::SVN::Prompt::ssl_server_trust),
5349 SVN::Client::get_username_prompt_provider(
5350 \&Git::SVN::Prompt::username, 2)
5354 sub escape_uri_only {
5355 my ($uri) = @_;
5356 my @tmp;
5357 foreach (split m{/}, $uri) {
5358 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
5359 push @tmp, $_;
5361 join('/', @tmp);
5364 sub escape_url {
5365 my ($url) = @_;
5366 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
5367 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
5368 $url = "$scheme://$domain$uri";
5370 $url;
5373 sub new {
5374 my ($class, $url) = @_;
5375 $url =~ s!/+$!!;
5376 return $RA if ($RA && $RA->{url} eq $url);
5378 ::_req_svn();
5380 SVN::_Core::svn_config_ensure($config_dir, undef);
5381 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
5382 my $config = SVN::Core::config_get_config($config_dir);
5383 $RA = undef;
5384 my $dont_store_passwords = 1;
5385 my $conf_t = ${$config}{'config'};
5387 no warnings 'once';
5388 # The usage of $SVN::_Core::SVN_CONFIG_* variables
5389 # produces warnings that variables are used only once.
5390 # I had not found the better way to shut them up, so
5391 # the warnings of type 'once' are disabled in this block.
5392 if (SVN::_Core::svn_config_get_bool($conf_t,
5393 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
5394 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
5395 1) == 0) {
5396 SVN::_Core::svn_auth_set_parameter($baton,
5397 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
5398 bless (\$dont_store_passwords, "_p_void"));
5400 if (SVN::_Core::svn_config_get_bool($conf_t,
5401 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
5402 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
5403 1) == 0) {
5404 $Git::SVN::Prompt::_no_auth_cache = 1;
5406 } # no warnings 'once'
5407 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
5408 config => $config,
5409 pool => SVN::Pool->new,
5410 auth_provider_callbacks => $callbacks);
5411 $self->{url} = $url;
5412 $self->{svn_path} = $url;
5413 $self->{repos_root} = $self->get_repos_root;
5414 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
5415 $self->{cache} = { check_path => { r => 0, data => {} },
5416 get_dir => { r => 0, data => {} } };
5417 $RA = bless $self, $class;
5420 sub check_path {
5421 my ($self, $path, $r) = @_;
5422 my $cache = $self->{cache}->{check_path};
5423 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
5424 return $cache->{data}->{$path};
5426 my $pool = SVN::Pool->new;
5427 my $t = $self->SUPER::check_path($path, $r, $pool);
5428 $pool->clear;
5429 if ($r != $cache->{r}) {
5430 %{$cache->{data}} = ();
5431 $cache->{r} = $r;
5433 $cache->{data}->{$path} = $t;
5436 sub get_dir {
5437 my ($self, $dir, $r) = @_;
5438 my $cache = $self->{cache}->{get_dir};
5439 if ($r == $cache->{r}) {
5440 if (my $x = $cache->{data}->{$dir}) {
5441 return wantarray ? @$x : $x->[0];
5444 my $pool = SVN::Pool->new;
5445 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
5446 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
5447 $pool->clear;
5448 if ($r != $cache->{r}) {
5449 %{$cache->{data}} = ();
5450 $cache->{r} = $r;
5452 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
5453 wantarray ? (\%dirents, $r, $props) : \%dirents;
5456 sub DESTROY {
5457 # do not call the real DESTROY since we store ourselves in $RA
5460 # get_log(paths, start, end, limit,
5461 # discover_changed_paths, strict_node_history, receiver)
5462 sub get_log {
5463 my ($self, @args) = @_;
5464 my $pool = SVN::Pool->new;
5466 # svn_log_changed_path_t objects passed to get_log are likely to be
5467 # overwritten even if only the refs are copied to an external variable,
5468 # so we should dup the structures in their entirety. Using an
5469 # externally passed pool (instead of our temporary and quickly cleared
5470 # pool in Git::SVN::Ra) does not help matters at all...
5471 my $receiver = pop @args;
5472 my $prefix = "/".$self->{svn_path};
5473 $prefix =~ s#/+($)##;
5474 my $prefix_regex = qr#^\Q$prefix\E#;
5475 push(@args, sub {
5476 my ($paths) = $_[0];
5477 return &$receiver(@_) unless $paths;
5478 $_[0] = ();
5479 foreach my $p (keys %$paths) {
5480 my $i = $paths->{$p};
5481 # Make path relative to our url, not repos_root
5482 $p =~ s/$prefix_regex//;
5483 my %s = map { $_ => $i->$_; }
5484 qw/copyfrom_path copyfrom_rev action/;
5485 if ($s{'copyfrom_path'}) {
5486 $s{'copyfrom_path'} =~ s/$prefix_regex//;
5488 $_[0]{$p} = \%s;
5490 &$receiver(@_);
5494 # the limit parameter was not supported in SVN 1.1.x, so we
5495 # drop it. Therefore, the receiver callback passed to it
5496 # is made aware of this limitation by being wrapped if
5497 # the limit passed to is being wrapped.
5498 if ($SVN::Core::VERSION le '1.2.0') {
5499 my $limit = splice(@args, 3, 1);
5500 if ($limit > 0) {
5501 my $receiver = pop @args;
5502 push(@args, sub { &$receiver(@_) if (--$limit >= 0) });
5505 my $ret = $self->SUPER::get_log(@args, $pool);
5506 $pool->clear;
5507 $ret;
5510 sub trees_match {
5511 my ($self, $url1, $rev1, $url2, $rev2) = @_;
5512 my $ctx = SVN::Client->new(auth => _auth_providers);
5513 my $out = IO::File->new_tmpfile;
5515 # older SVN (1.1.x) doesn't take $pool as the last parameter for
5516 # $ctx->diff(), so we'll create a default one
5517 my $pool = SVN::Pool->new_default_sub;
5519 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
5520 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
5521 $out->flush;
5522 my $ret = (($out->stat)[7] == 0);
5523 close $out or croak $!;
5525 $ret;
5528 sub get_commit_editor {
5529 my ($self, $log, $cb, $pool) = @_;
5530 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
5531 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
5534 sub gs_do_update {
5535 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
5536 my $new = ($rev_a == $rev_b);
5537 my $path = $gs->{path};
5539 if ($new && -e $gs->{index}) {
5540 unlink $gs->{index} or die
5541 "Couldn't unlink index: $gs->{index}: $!\n";
5543 my $pool = SVN::Pool->new;
5544 $editor->set_path_strip($path);
5545 my (@pc) = split m#/#, $path;
5546 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
5547 1, $editor, $pool);
5548 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
5550 # Since we can't rely on svn_ra_reparent being available, we'll
5551 # just have to do some magic with set_path to make it so
5552 # we only want a partial path.
5553 my $sp = '';
5554 my $final = join('/', @pc);
5555 while (@pc) {
5556 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
5557 $sp .= '/' if length $sp;
5558 $sp .= shift @pc;
5560 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
5562 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
5564 $reporter->finish_report($pool);
5565 $pool->clear;
5566 $editor->{git_commit_ok};
5569 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
5570 # svn_ra_reparent didn't work before 1.4)
5571 sub gs_do_switch {
5572 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
5573 my $path = $gs->{path};
5574 my $pool = SVN::Pool->new;
5576 my $full_url = $self->{url};
5577 my $old_url = $full_url;
5578 $full_url .= '/' . $path if length $path;
5579 my ($ra, $reparented);
5581 if ($old_url =~ m#^svn(\+ssh)?://# ||
5582 ($full_url =~ m#^https?://# &&
5583 escape_url($full_url) ne $full_url)) {
5584 $_[0] = undef;
5585 $self = undef;
5586 $RA = undef;
5587 $ra = Git::SVN::Ra->new($full_url);
5588 $ra_invalid = 1;
5589 } elsif ($old_url ne $full_url) {
5590 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url, $pool);
5591 $self->{url} = $full_url;
5592 $reparented = 1;
5595 $ra ||= $self;
5596 $url_b = escape_url($url_b);
5597 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
5598 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
5599 $reporter->set_path('', $rev_a, 0, @lock, $pool);
5600 $reporter->finish_report($pool);
5602 if ($reparented) {
5603 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
5604 $self->{url} = $old_url;
5607 $pool->clear;
5608 $editor->{git_commit_ok};
5611 sub longest_common_path {
5612 my ($gsv, $globs) = @_;
5613 my %common;
5614 my $common_max = scalar @$gsv;
5616 foreach my $gs (@$gsv) {
5617 my @tmp = split m#/#, $gs->{path};
5618 my $p = '';
5619 foreach (@tmp) {
5620 $p .= length($p) ? "/$_" : $_;
5621 $common{$p} ||= 0;
5622 $common{$p}++;
5625 $globs ||= [];
5626 $common_max += scalar @$globs;
5627 foreach my $glob (@$globs) {
5628 my @tmp = split m#/#, $glob->{path}->{left};
5629 my $p = '';
5630 foreach (@tmp) {
5631 $p .= length($p) ? "/$_" : $_;
5632 $common{$p} ||= 0;
5633 $common{$p}++;
5637 my $longest_path = '';
5638 foreach (sort {length $b <=> length $a} keys %common) {
5639 if ($common{$_} == $common_max) {
5640 $longest_path = $_;
5641 last;
5644 $longest_path;
5647 sub gs_fetch_loop_common {
5648 my ($self, $base, $head, $gsv, $globs) = @_;
5649 return if ($base > $head);
5650 my $inc = $_log_window_size;
5651 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
5652 my $longest_path = longest_common_path($gsv, $globs);
5653 my $ra_url = $self->{url};
5654 my $find_trailing_edge;
5655 while (1) {
5656 my %revs;
5657 my $err;
5658 my $err_handler = $SVN::Error::handler;
5659 $SVN::Error::handler = sub {
5660 ($err) = @_;
5661 skip_unknown_revs($err);
5663 sub _cb {
5664 my ($paths, $r, $author, $date, $log) = @_;
5665 [ $paths,
5666 { author => $author, date => $date, log => $log } ];
5668 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
5669 sub { $revs{$_[1]} = _cb(@_) });
5670 if ($err) {
5671 print "Checked through r$max\r";
5672 } else {
5673 $find_trailing_edge = 1;
5675 if ($err and $find_trailing_edge) {
5676 print STDERR "Path '$longest_path' ",
5677 "was probably deleted:\n",
5678 $err->expanded_message,
5679 "\nWill attempt to follow ",
5680 "revisions r$min .. r$max ",
5681 "committed before the deletion\n";
5682 my $hi = $max;
5683 while (--$hi >= $min) {
5684 my $ok;
5685 $self->get_log([$longest_path], $min, $hi,
5686 0, 1, 1, sub {
5687 $ok = $_[1];
5688 $revs{$_[1]} = _cb(@_) });
5689 if ($ok) {
5690 print STDERR "r$min .. r$ok OK\n";
5691 last;
5694 $find_trailing_edge = 0;
5696 $SVN::Error::handler = $err_handler;
5698 my %exists = map { $_->{path} => $_ } @$gsv;
5699 foreach my $r (sort {$a <=> $b} keys %revs) {
5700 my ($paths, $logged) = @{$revs{$r}};
5702 foreach my $gs ($self->match_globs(\%exists, $paths,
5703 $globs, $r)) {
5704 if ($gs->rev_map_max >= $r) {
5705 next;
5707 next unless $gs->match_paths($paths, $r);
5708 $gs->{logged_rev_props} = $logged;
5709 if (my $last_commit = $gs->last_commit) {
5710 $gs->assert_index_clean($last_commit);
5712 my $log_entry = $gs->do_fetch($paths, $r);
5713 if ($log_entry) {
5714 $gs->do_git_commit($log_entry);
5716 $INDEX_FILES{$gs->{index}} = 1;
5718 foreach my $g (@$globs) {
5719 my $k = "svn-remote.$g->{remote}." .
5720 "$g->{t}-maxRev";
5721 Git::SVN::tmp_config($k, $r);
5723 if ($ra_invalid) {
5724 $_[0] = undef;
5725 $self = undef;
5726 $RA = undef;
5727 $self = Git::SVN::Ra->new($ra_url);
5728 $ra_invalid = undef;
5731 # pre-fill the .rev_db since it'll eventually get filled in
5732 # with '0' x40 if something new gets committed
5733 foreach my $gs (@$gsv) {
5734 next if $gs->rev_map_max >= $max;
5735 next if defined $gs->rev_map_get($max);
5736 $gs->rev_map_set($max, 0 x40);
5738 foreach my $g (@$globs) {
5739 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
5740 Git::SVN::tmp_config($k, $max);
5742 last if $max >= $head;
5743 $min = $max + 1;
5744 $max += $inc;
5745 $max = $head if ($max > $head);
5747 Git::SVN::gc();
5750 sub get_dir_globbed {
5751 my ($self, $left, $depth, $r) = @_;
5753 my @x = eval { $self->get_dir($left, $r) };
5754 return unless scalar @x == 3;
5755 my $dirents = $x[0];
5756 my @finalents;
5757 foreach my $de (keys %$dirents) {
5758 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
5759 if ($depth > 1) {
5760 my @args = ("$left/$de", $depth - 1, $r);
5761 foreach my $dir ($self->get_dir_globbed(@args)) {
5762 push @finalents, "$de/$dir";
5764 } else {
5765 push @finalents, $de;
5768 @finalents;
5771 sub match_globs {
5772 my ($self, $exists, $paths, $globs, $r) = @_;
5774 sub get_dir_check {
5775 my ($self, $exists, $g, $r) = @_;
5777 my @dirs = $self->get_dir_globbed($g->{path}->{left},
5778 $g->{path}->{depth},
5779 $r);
5781 foreach my $de (@dirs) {
5782 my $p = $g->{path}->full_path($de);
5783 next if $exists->{$p};
5784 next if (length $g->{path}->{right} &&
5785 ($self->check_path($p, $r) !=
5786 $SVN::Node::dir));
5787 next unless $p =~ /$g->{path}->{regex}/;
5788 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
5789 $g->{ref}->full_path($de), 1);
5792 foreach my $g (@$globs) {
5793 if (my $path = $paths->{"/$g->{path}->{left}"}) {
5794 if ($path->{action} =~ /^[AR]$/) {
5795 get_dir_check($self, $exists, $g, $r);
5798 foreach (keys %$paths) {
5799 if (/$g->{path}->{left_regex}/ &&
5800 !/$g->{path}->{regex}/) {
5801 next if $paths->{$_}->{action} !~ /^[AR]$/;
5802 get_dir_check($self, $exists, $g, $r);
5804 next unless /$g->{path}->{regex}/;
5805 my $p = $1;
5806 my $pathname = $g->{path}->full_path($p);
5807 next if $exists->{$pathname};
5808 next if ($self->check_path($pathname, $r) !=
5809 $SVN::Node::dir);
5810 $exists->{$pathname} = Git::SVN->init(
5811 $self->{url}, $pathname, undef,
5812 $g->{ref}->full_path($p), 1);
5814 my $c = '';
5815 foreach (split m#/#, $g->{path}->{left}) {
5816 $c .= "/$_";
5817 next unless ($paths->{$c} &&
5818 ($paths->{$c}->{action} =~ /^[AR]$/));
5819 get_dir_check($self, $exists, $g, $r);
5822 values %$exists;
5825 sub minimize_url {
5826 my ($self) = @_;
5827 return $self->{url} if ($self->{url} eq $self->{repos_root});
5828 my $url = $self->{repos_root};
5829 my @components = split(m!/!, $self->{svn_path});
5830 my $c = '';
5831 do {
5832 $url .= "/$c" if length $c;
5833 eval {
5834 my $ra = (ref $self)->new($url);
5835 my $latest = $ra->get_latest_revnum;
5836 $ra->get_log("", $latest, 0, 1, 0, 1, sub {});
5838 } while ($@ && ($c = shift @components));
5839 $url;
5842 sub can_do_switch {
5843 my $self = shift;
5844 unless (defined $can_do_switch) {
5845 my $pool = SVN::Pool->new;
5846 my $rep = eval {
5847 $self->do_switch(1, '', 0, $self->{url},
5848 SVN::Delta::Editor->new, $pool);
5850 if ($@) {
5851 $can_do_switch = 0;
5852 } else {
5853 $rep->abort_report($pool);
5854 $can_do_switch = 1;
5856 $pool->clear;
5858 $can_do_switch;
5861 sub skip_unknown_revs {
5862 my ($err) = @_;
5863 my $errno = $err->apr_err();
5864 # Maybe the branch we're tracking didn't
5865 # exist when the repo started, so it's
5866 # not an error if it doesn't, just continue
5868 # Wonderfully consistent library, eh?
5869 # 160013 - svn:// and file://
5870 # 175002 - http(s)://
5871 # 175007 - http(s):// (this repo required authorization, too...)
5872 # More codes may be discovered later...
5873 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
5874 my $err_key = $err->expanded_message;
5875 # revision numbers change every time, filter them out
5876 $err_key =~ s/\d+/\0/g;
5877 $err_key = "$errno\0$err_key";
5878 unless ($ignored_err{$err_key}) {
5879 warn "W: Ignoring error from SVN, path probably ",
5880 "does not exist: ($errno): ",
5881 $err->expanded_message,"\n";
5882 warn "W: Do not be alarmed at the above message ",
5883 "git-svn is just searching aggressively for ",
5884 "old history.\n",
5885 "This may take a while on large repositories\n";
5886 $ignored_err{$err_key} = 1;
5888 return;
5890 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
5893 package Git::SVN::Log;
5894 use strict;
5895 use warnings;
5896 use POSIX qw/strftime/;
5897 use Time::Local;
5898 use constant commit_log_separator => ('-' x 72) . "\n";
5899 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
5900 %rusers $show_commit $incremental/;
5901 my $l_fmt;
5903 sub cmt_showable {
5904 my ($c) = @_;
5905 return 1 if defined $c->{r};
5907 # big commit message got truncated by the 16k pretty buffer in rev-list
5908 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
5909 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
5910 @{$c->{l}} = ();
5911 my @log = command(qw/cat-file commit/, $c->{c});
5913 # shift off the headers
5914 shift @log while ($log[0] ne '');
5915 shift @log;
5917 # TODO: make $c->{l} not have a trailing newline in the future
5918 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
5920 (undef, $c->{r}, undef) = ::extract_metadata(
5921 (grep(/^git-svn-id: /, @log))[-1]);
5923 return defined $c->{r};
5926 sub log_use_color {
5927 return $color || Git->repository->get_colorbool('color.diff');
5930 sub git_svn_log_cmd {
5931 my ($r_min, $r_max, @args) = @_;
5932 my $head = 'HEAD';
5933 my (@files, @log_opts);
5934 foreach my $x (@args) {
5935 if ($x eq '--' || @files) {
5936 push @files, $x;
5937 } else {
5938 if (::verify_ref("$x^0")) {
5939 $head = $x;
5940 } else {
5941 push @log_opts, $x;
5946 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
5947 $gs ||= Git::SVN->_new;
5948 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
5949 $gs->refname);
5950 push @cmd, '-r' unless $non_recursive;
5951 push @cmd, qw/--raw --name-status/ if $verbose;
5952 push @cmd, '--color' if log_use_color();
5953 push @cmd, @log_opts;
5954 if (defined $r_max && $r_max == $r_min) {
5955 push @cmd, '--max-count=1';
5956 if (my $c = $gs->rev_map_get($r_max)) {
5957 push @cmd, $c;
5959 } elsif (defined $r_max) {
5960 if ($r_max < $r_min) {
5961 ($r_min, $r_max) = ($r_max, $r_min);
5963 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
5964 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
5965 # If there are no commits in the range, both $c_max and $c_min
5966 # will be undefined. If there is at least 1 commit in the
5967 # range, both will be defined.
5968 return () if !defined $c_min || !defined $c_max;
5969 if ($c_min eq $c_max) {
5970 push @cmd, '--max-count=1', $c_min;
5971 } else {
5972 push @cmd, '--boundary', "$c_min..$c_max";
5975 return (@cmd, @files);
5978 # adapted from pager.c
5979 sub config_pager {
5980 if (! -t *STDOUT) {
5981 $ENV{GIT_PAGER_IN_USE} = 'false';
5982 $pager = undef;
5983 return;
5985 chomp($pager = command_oneline(qw(var GIT_PAGER)));
5986 if ($pager eq 'cat') {
5987 $pager = undef;
5989 $ENV{GIT_PAGER_IN_USE} = defined($pager);
5992 sub run_pager {
5993 return unless defined $pager;
5994 pipe my ($rfd, $wfd) or return;
5995 defined(my $pid = fork) or ::fatal "Can't fork: $!";
5996 if (!$pid) {
5997 open STDOUT, '>&', $wfd or
5998 ::fatal "Can't redirect to stdout: $!";
5999 return;
6001 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
6002 $ENV{LESS} ||= 'FRSX';
6003 exec $pager or ::fatal "Can't run pager: $! ($pager)";
6006 sub format_svn_date {
6007 # some systmes don't handle or mishandle %z, so be creative.
6008 my $t = shift || time;
6009 my $gm = timelocal(gmtime($t));
6010 my $sign = qw( + + - )[ $t <=> $gm ];
6011 my $gmoff = sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
6012 return strftime("%Y-%m-%d %H:%M:%S $gmoff (%a, %d %b %Y)", localtime($t));
6015 sub parse_git_date {
6016 my ($t, $tz) = @_;
6017 # Date::Parse isn't in the standard Perl distro :(
6018 if ($tz =~ s/^\+//) {
6019 $t += tz_to_s_offset($tz);
6020 } elsif ($tz =~ s/^\-//) {
6021 $t -= tz_to_s_offset($tz);
6023 return $t;
6026 sub set_local_timezone {
6027 if (defined $TZ) {
6028 $ENV{TZ} = $TZ;
6029 } else {
6030 delete $ENV{TZ};
6034 sub tz_to_s_offset {
6035 my ($tz) = @_;
6036 $tz =~ s/(\d\d)$//;
6037 return ($1 * 60) + ($tz * 3600);
6040 sub get_author_info {
6041 my ($dest, $author, $t, $tz) = @_;
6042 $author =~ s/(?:^\s*|\s*$)//g;
6043 $dest->{a_raw} = $author;
6044 my $au;
6045 if ($::_authors) {
6046 $au = $rusers{$author} || undef;
6048 if (!$au) {
6049 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
6051 $dest->{t} = $t;
6052 $dest->{tz} = $tz;
6053 $dest->{a} = $au;
6054 $dest->{t_utc} = parse_git_date($t, $tz);
6057 sub process_commit {
6058 my ($c, $r_min, $r_max, $defer) = @_;
6059 if (defined $r_min && defined $r_max) {
6060 if ($r_min == $c->{r} && $r_min == $r_max) {
6061 show_commit($c);
6062 return 0;
6064 return 1 if $r_min == $r_max;
6065 if ($r_min < $r_max) {
6066 # we need to reverse the print order
6067 return 0 if (defined $limit && --$limit < 0);
6068 push @$defer, $c;
6069 return 1;
6071 if ($r_min != $r_max) {
6072 return 1 if ($r_min < $c->{r});
6073 return 1 if ($r_max > $c->{r});
6076 return 0 if (defined $limit && --$limit < 0);
6077 show_commit($c);
6078 return 1;
6081 sub show_commit {
6082 my $c = shift;
6083 if ($oneline) {
6084 my $x = "\n";
6085 if (my $l = $c->{l}) {
6086 while ($l->[0] =~ /^\s*$/) { shift @$l }
6087 $x = $l->[0];
6089 $l_fmt ||= 'A' . length($c->{r});
6090 print 'r',pack($l_fmt, $c->{r}),' | ';
6091 print "$c->{c} | " if $show_commit;
6092 print $x;
6093 } else {
6094 show_commit_normal($c);
6098 sub show_commit_changed_paths {
6099 my ($c) = @_;
6100 return unless $c->{changed};
6101 print "Changed paths:\n", @{$c->{changed}};
6104 sub show_commit_normal {
6105 my ($c) = @_;
6106 print commit_log_separator, "r$c->{r} | ";
6107 print "$c->{c} | " if $show_commit;
6108 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
6109 my $nr_line = 0;
6111 if (my $l = $c->{l}) {
6112 while ($l->[$#$l] eq "\n" && $#$l > 0
6113 && $l->[($#$l - 1)] eq "\n") {
6114 pop @$l;
6116 $nr_line = scalar @$l;
6117 if (!$nr_line) {
6118 print "1 line\n\n\n";
6119 } else {
6120 if ($nr_line == 1) {
6121 $nr_line = '1 line';
6122 } else {
6123 $nr_line .= ' lines';
6125 print $nr_line, "\n";
6126 show_commit_changed_paths($c);
6127 print "\n";
6128 print $_ foreach @$l;
6130 } else {
6131 print "1 line\n";
6132 show_commit_changed_paths($c);
6133 print "\n";
6136 foreach my $x (qw/raw stat diff/) {
6137 if ($c->{$x}) {
6138 print "\n";
6139 print $_ foreach @{$c->{$x}}
6144 sub cmd_show_log {
6145 my (@args) = @_;
6146 my ($r_min, $r_max);
6147 my $r_last = -1; # prevent dupes
6148 set_local_timezone();
6149 if (defined $::_revision) {
6150 if ($::_revision =~ /^(\d+):(\d+)$/) {
6151 ($r_min, $r_max) = ($1, $2);
6152 } elsif ($::_revision =~ /^\d+$/) {
6153 $r_min = $r_max = $::_revision;
6154 } else {
6155 ::fatal "-r$::_revision is not supported, use ",
6156 "standard 'git log' arguments instead";
6160 config_pager();
6161 @args = git_svn_log_cmd($r_min, $r_max, @args);
6162 if (!@args) {
6163 print commit_log_separator unless $incremental || $oneline;
6164 return;
6166 my $log = command_output_pipe(@args);
6167 run_pager();
6168 my (@k, $c, $d, $stat);
6169 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
6170 while (<$log>) {
6171 if (/^${esc_color}commit (?:- )?($::sha1_short)/o) {
6172 my $cmt = $1;
6173 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
6174 $r_last = $c->{r};
6175 process_commit($c, $r_min, $r_max, \@k) or
6176 goto out;
6178 $d = undef;
6179 $c = { c => $cmt };
6180 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
6181 get_author_info($c, $1, $2, $3);
6182 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
6183 # ignore
6184 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
6185 push @{$c->{raw}}, $_;
6186 } elsif (/^${esc_color}[ACRMDT]\t/) {
6187 # we could add $SVN->{svn_path} here, but that requires
6188 # remote access at the moment (repo_path_split)...
6189 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
6190 push @{$c->{changed}}, $_;
6191 } elsif (/^${esc_color}diff /o) {
6192 $d = 1;
6193 push @{$c->{diff}}, $_;
6194 } elsif ($d) {
6195 push @{$c->{diff}}, $_;
6196 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
6197 $esc_color*[\+\-]*$esc_color$/x) {
6198 $stat = 1;
6199 push @{$c->{stat}}, $_;
6200 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
6201 push @{$c->{stat}}, $_;
6202 $stat = undef;
6203 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
6204 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
6205 } elsif (s/^${esc_color} //o) {
6206 push @{$c->{l}}, $_;
6209 if ($c && defined $c->{r} && $c->{r} != $r_last) {
6210 $r_last = $c->{r};
6211 process_commit($c, $r_min, $r_max, \@k);
6213 if (@k) {
6214 ($r_min, $r_max) = ($r_max, $r_min);
6215 process_commit($_, $r_min, $r_max) foreach reverse @k;
6217 out:
6218 close $log;
6219 print commit_log_separator unless $incremental || $oneline;
6222 sub cmd_blame {
6223 my $path = pop;
6225 config_pager();
6226 run_pager();
6228 my ($fh, $ctx, $rev);
6230 if ($_git_format) {
6231 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
6232 while (my $line = <$fh>) {
6233 if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
6234 # Uncommitted edits show up as a rev ID of
6235 # all zeros, which we can't look up with
6236 # cmt_metadata
6237 if ($1 !~ /^0+$/) {
6238 (undef, $rev, undef) =
6239 ::cmt_metadata($1);
6240 $rev = '0' if (!$rev);
6241 } else {
6242 $rev = '0';
6244 $rev = sprintf('%-10s', $rev);
6245 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
6247 print $line;
6249 } else {
6250 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
6251 '--', $path);
6252 my ($sha1);
6253 my %authors;
6254 my @buffer;
6255 my %dsha; #distinct sha keys
6257 while (my $line = <$fh>) {
6258 push @buffer, $line;
6259 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
6260 $dsha{$1} = 1;
6264 my $s2r = ::cmt_sha2rev_batch([keys %dsha]);
6266 foreach my $line (@buffer) {
6267 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
6268 $rev = $s2r->{$1};
6269 $rev = '0' if (!$rev)
6271 elsif ($line =~ /^author (.*)/) {
6272 $authors{$rev} = $1;
6273 $authors{$rev} =~ s/\s/_/g;
6275 elsif ($line =~ /^\t(.*)$/) {
6276 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
6280 command_close_pipe($fh, $ctx);
6283 package Git::SVN::Migration;
6284 # these version numbers do NOT correspond to actual version numbers
6285 # of git nor git-svn. They are just relative.
6287 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
6289 # v1 layout: .git/$id/info/url, refs/remotes/$id
6291 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
6293 # v3 layout: .git/svn/$id, refs/remotes/$id
6294 # - info/url may remain for backwards compatibility
6295 # - this is what we migrate up to this layout automatically,
6296 # - this will be used by git svn init on single branches
6297 # v3.1 layout (auto migrated):
6298 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
6299 # for backwards compatibility
6301 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
6302 # - this is only created for newly multi-init-ed
6303 # repositories. Similar in spirit to the
6304 # --use-separate-remotes option in git-clone (now default)
6305 # - we do not automatically migrate to this (following
6306 # the example set by core git)
6308 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
6309 # - newer, more-efficient format that uses 24-bytes per record
6310 # with no filler space.
6311 # - use xxd -c24 < .rev_map.$UUID to view and debug
6312 # - This is a one-way migration, repositories updated to the
6313 # new format will not be able to use old git-svn without
6314 # rebuilding the .rev_db. Rebuilding the rev_db is not
6315 # possible if noMetadata or useSvmProps are set; but should
6316 # be no problem for users that use the (sensible) defaults.
6317 use strict;
6318 use warnings;
6319 use Carp qw/croak/;
6320 use File::Path qw/mkpath/;
6321 use File::Basename qw/dirname basename/;
6322 use vars qw/$_minimize/;
6324 sub migrate_from_v0 {
6325 my $git_dir = $ENV{GIT_DIR};
6326 return undef unless -d $git_dir;
6327 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
6328 my $migrated = 0;
6329 while (<$fh>) {
6330 chomp;
6331 my ($id, $orig_ref) = ($_, $_);
6332 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
6333 next unless -f "$git_dir/$id/info/url";
6334 my $new_ref = "refs/remotes/$id";
6335 if (::verify_ref("$new_ref^0")) {
6336 print STDERR "W: $orig_ref is probably an old ",
6337 "branch used by an ancient version of ",
6338 "git-svn.\n",
6339 "However, $new_ref also exists.\n",
6340 "We will not be able ",
6341 "to use this branch until this ",
6342 "ambiguity is resolved.\n";
6343 next;
6345 print STDERR "Migrating from v0 layout...\n" if !$migrated;
6346 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
6347 command_noisy('update-ref', $new_ref, $orig_ref);
6348 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
6349 $migrated++;
6351 command_close_pipe($fh, $ctx);
6352 print STDERR "Done migrating from v0 layout...\n" if $migrated;
6353 $migrated;
6356 sub migrate_from_v1 {
6357 my $git_dir = $ENV{GIT_DIR};
6358 my $migrated = 0;
6359 return $migrated unless -d $git_dir;
6360 my $svn_dir = "$git_dir/svn";
6362 # just in case somebody used 'svn' as their $id at some point...
6363 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
6365 print STDERR "Migrating from a git-svn v1 layout...\n";
6366 mkpath([$svn_dir]);
6367 print STDERR "Data from a previous version of git-svn exists, but\n\t",
6368 "$svn_dir\n\t(required for this version ",
6369 "($::VERSION) of git-svn) does not exist.\n";
6370 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
6371 while (<$fh>) {
6372 my $x = $_;
6373 next unless $x =~ s#^refs/remotes/##;
6374 chomp $x;
6375 next unless -f "$git_dir/$x/info/url";
6376 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
6377 next unless $u;
6378 my $dn = dirname("$git_dir/svn/$x");
6379 mkpath([$dn]) unless -d $dn;
6380 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
6381 mkpath(["$git_dir/svn/svn"]);
6382 print STDERR " - $git_dir/$x/info => ",
6383 "$git_dir/svn/$x/info\n";
6384 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
6385 croak "$!: $x";
6386 # don't worry too much about these, they probably
6387 # don't exist with repos this old (save for index,
6388 # and we can easily regenerate that)
6389 foreach my $f (qw/unhandled.log index .rev_db/) {
6390 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
6392 } else {
6393 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
6394 rename "$git_dir/$x", "$git_dir/svn/$x" or
6395 croak "$!: $x";
6397 $migrated++;
6399 command_close_pipe($fh, $ctx);
6400 print STDERR "Done migrating from a git-svn v1 layout\n";
6401 $migrated;
6404 sub read_old_urls {
6405 my ($l_map, $pfx, $path) = @_;
6406 my @dir;
6407 foreach (<$path/*>) {
6408 if (-r "$_/info/url") {
6409 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
6410 my $ref_id = $pfx . basename $_;
6411 my $url = ::file_to_s("$_/info/url");
6412 $l_map->{$ref_id} = $url;
6413 } elsif (-d $_) {
6414 push @dir, $_;
6417 foreach (@dir) {
6418 my $x = $_;
6419 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
6420 read_old_urls($l_map, $x, $_);
6424 sub migrate_from_v2 {
6425 my @cfg = command(qw/config -l/);
6426 return if grep /^svn-remote\..+\.url=/, @cfg;
6427 my %l_map;
6428 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
6429 my $migrated = 0;
6431 foreach my $ref_id (sort keys %l_map) {
6432 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
6433 if ($@) {
6434 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
6436 $migrated++;
6438 $migrated;
6441 sub minimize_connections {
6442 my $r = Git::SVN::read_all_remotes();
6443 my $new_urls = {};
6444 my $root_repos = {};
6445 foreach my $repo_id (keys %$r) {
6446 my $url = $r->{$repo_id}->{url} or next;
6447 my $fetch = $r->{$repo_id}->{fetch} or next;
6448 my $ra = Git::SVN::Ra->new($url);
6450 # skip existing cases where we already connect to the root
6451 if (($ra->{url} eq $ra->{repos_root}) ||
6452 ($ra->{repos_root} eq $repo_id)) {
6453 $root_repos->{$ra->{url}} = $repo_id;
6454 next;
6457 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
6458 my $root_path = $ra->{url};
6459 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
6460 foreach my $path (keys %$fetch) {
6461 my $ref_id = $fetch->{$path};
6462 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
6464 # make sure we can read when connecting to
6465 # a higher level of a repository
6466 my ($last_rev, undef) = $gs->last_rev_commit;
6467 if (!defined $last_rev) {
6468 $last_rev = eval {
6469 $root_ra->get_latest_revnum;
6471 next if $@;
6473 my $new = $root_path;
6474 $new .= length $path ? "/$path" : '';
6475 eval {
6476 $root_ra->get_log([$new], $last_rev, $last_rev,
6477 0, 0, 1, sub { });
6479 next if $@;
6480 $new_urls->{$ra->{repos_root}}->{$new} =
6481 { ref_id => $ref_id,
6482 old_repo_id => $repo_id,
6483 old_path => $path };
6487 my @emptied;
6488 foreach my $url (keys %$new_urls) {
6489 # see if we can re-use an existing [svn-remote "repo_id"]
6490 # instead of creating a(n ugly) new section:
6491 my $repo_id = $root_repos->{$url} || $url;
6493 my $fetch = $new_urls->{$url};
6494 foreach my $path (keys %$fetch) {
6495 my $x = $fetch->{$path};
6496 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
6497 my $pfx = "svn-remote.$x->{old_repo_id}";
6499 my $old_fetch = quotemeta("$x->{old_path}:".
6500 "$x->{ref_id}");
6501 command_noisy(qw/config --unset/,
6502 "$pfx.fetch", '^'. $old_fetch . '$');
6503 delete $r->{$x->{old_repo_id}}->
6504 {fetch}->{$x->{old_path}};
6505 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
6506 command_noisy(qw/config --unset/,
6507 "$pfx.url");
6508 push @emptied, $x->{old_repo_id}
6512 if (@emptied) {
6513 my $file = $ENV{GIT_CONFIG} || "$ENV{GIT_DIR}/config";
6514 print STDERR <<EOF;
6515 The following [svn-remote] sections in your config file ($file) are empty
6516 and can be safely removed:
6518 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
6522 sub migration_check {
6523 migrate_from_v0();
6524 migrate_from_v1();
6525 migrate_from_v2();
6526 minimize_connections() if $_minimize;
6529 package Git::IndexInfo;
6530 use strict;
6531 use warnings;
6532 use Git qw/command_input_pipe command_close_pipe/;
6534 sub new {
6535 my ($class) = @_;
6536 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
6537 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
6540 sub remove {
6541 my ($self, $path) = @_;
6542 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
6543 return ++$self->{nr};
6545 undef;
6548 sub update {
6549 my ($self, $mode, $hash, $path) = @_;
6550 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
6551 return ++$self->{nr};
6553 undef;
6556 sub DESTROY {
6557 my ($self) = @_;
6558 command_close_pipe($self->{gui}, $self->{ctx});
6561 package Git::SVN::GlobSpec;
6562 use strict;
6563 use warnings;
6565 sub new {
6566 my ($class, $glob, $pattern_ok) = @_;
6567 my $re = $glob;
6568 $re =~ s!/+$!!g; # no need for trailing slashes
6569 my (@left, @right, @patterns);
6570 my $state = "left";
6571 my $die_msg = "Only one set of wildcard directories " .
6572 "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
6573 for my $part (split(m|/|, $glob)) {
6574 if ($part =~ /\*/ && $part ne "*") {
6575 die "Invalid pattern in '$glob': $part\n";
6576 } elsif ($pattern_ok && $part =~ /[{}]/ &&
6577 $part !~ /^\{[^{}]+\}/) {
6578 die "Invalid pattern in '$glob': $part\n";
6580 if ($part eq "*") {
6581 die $die_msg if $state eq "right";
6582 $state = "pattern";
6583 push(@patterns, "[^/]*");
6584 } elsif ($pattern_ok && $part =~ /^\{(.*)\}$/) {
6585 die $die_msg if $state eq "right";
6586 $state = "pattern";
6587 my $p = quotemeta($1);
6588 $p =~ s/\\,/|/g;
6589 push(@patterns, "(?:$p)");
6590 } else {
6591 if ($state eq "left") {
6592 push(@left, $part);
6593 } else {
6594 push(@right, $part);
6595 $state = "right";
6599 my $depth = @patterns;
6600 if ($depth == 0) {
6601 die "One '*' is needed in glob: '$glob'\n";
6603 my $left = join('/', @left);
6604 my $right = join('/', @right);
6605 $re = join('/', @patterns);
6606 $re = join('\/',
6607 grep(length, quotemeta($left), "($re)", quotemeta($right)));
6608 my $left_re = qr/^\/\Q$left\E(\/|$)/;
6609 bless { left => $left, right => $right, left_regex => $left_re,
6610 regex => qr/$re/, glob => $glob, depth => $depth }, $class;
6613 sub full_path {
6614 my ($self, $path) = @_;
6615 return (length $self->{left} ? "$self->{left}/" : '') .
6616 $path . (length $self->{right} ? "/$self->{right}" : '');
6619 __END__
6621 Data structures:
6624 $remotes = { # returned by read_all_remotes()
6625 'svn' => {
6626 # svn-remote.svn.url=https://svn.musicpd.org
6627 url => 'https://svn.musicpd.org',
6628 # svn-remote.svn.fetch=mpd/trunk:trunk
6629 fetch => {
6630 'mpd/trunk' => 'trunk',
6632 # svn-remote.svn.tags=mpd/tags/*:tags/*
6633 tags => {
6634 path => {
6635 left => 'mpd/tags',
6636 right => '',
6637 regex => qr!mpd/tags/([^/]+)$!,
6638 glob => 'tags/*',
6640 ref => {
6641 left => 'tags',
6642 right => '',
6643 regex => qr!tags/([^/]+)$!,
6644 glob => 'tags/*',
6650 $log_entry hashref as returned by libsvn_log_entry()
6652 log => 'whitespace-formatted log entry
6653 ', # trailing newline is preserved
6654 revision => '8', # integer
6655 date => '2004-02-24T17:01:44.108345Z', # commit date
6656 author => 'committer name'
6660 # this is generated by generate_diff();
6661 @mods = array of diff-index line hashes, each element represents one line
6662 of diff-index output
6664 diff-index line ($m hash)
6666 mode_a => first column of diff-index output, no leading ':',
6667 mode_b => second column of diff-index output,
6668 sha1_b => sha1sum of the final blob,
6669 chg => change type [MCRADT],
6670 file_a => original file name of a file (iff chg is 'C' or 'R')
6671 file_b => new/current file name of a file (any chg)
6675 # retval of read_url_paths{,_all}();
6676 $l_map = {
6677 # repository root url
6678 'https://svn.musicpd.org' => {
6679 # repository path # GIT_SVN_ID
6680 'mpd/trunk' => 'trunk',
6681 'mpd/tags/0.11.5' => 'tags/0.11.5',
6685 Notes:
6686 I don't trust the each() function on unless I created %hash myself
6687 because the internal iterator may not have started at base.