Merge branch 'js/bisect-no-checkout'
[git/mingw.git] / git-svn.perl
blobb608bbf95a9c9530af4151c3077f4fe32f3a3340
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, $_interactive);
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 'ignore-refs=s' => \$Git::SVN::Ra::_ignore_refs_regex );
99 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
100 'authors-file|A=s' => \$_authors,
101 'authors-prog=s' => \$_authors_prog,
102 'repack:i' => \$Git::SVN::_repack,
103 'noMetadata' => \$Git::SVN::_no_metadata,
104 'useSvmProps' => \$Git::SVN::_use_svm_props,
105 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
106 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
107 'no-checkout' => \$_no_checkout,
108 'quiet|q+' => \$_q,
109 'repack-flags|repack-args|repack-opts=s' =>
110 \$Git::SVN::_repack_flags,
111 'use-log-author' => \$Git::SVN::_use_log_author,
112 'add-author-from' => \$Git::SVN::_add_author_from,
113 'localtime' => \$Git::SVN::_localtime,
114 %remote_opts );
116 my ($_trunk, @_tags, @_branches, $_stdlayout);
117 my %icv;
118 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
119 'trunk|T=s' => \$_trunk, 'tags|t=s@' => \@_tags,
120 'branches|b=s@' => \@_branches, 'prefix=s' => \$_prefix,
121 'stdlayout|s' => \$_stdlayout,
122 'minimize-url|m!' => \$Git::SVN::_minimize_url,
123 'no-metadata' => sub { $icv{noMetadata} = 1 },
124 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
125 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
126 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
127 'rewrite-uuid=s' => sub { $icv{rewriteUUID} = $_[1] },
128 %remote_opts );
129 my %cmt_opts = ( 'edit|e' => \$_edit,
130 'rmdir' => \$SVN::Git::Editor::_rmdir,
131 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
132 'l=i' => \$SVN::Git::Editor::_rename_limit,
133 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
136 my %cmd = (
137 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
138 { 'revision|r=s' => \$_revision,
139 'fetch-all|all' => \$_fetch_all,
140 'parent|p' => \$_fetch_parent,
141 %fc_opts } ],
142 clone => [ \&cmd_clone, "Initialize and fetch revisions",
143 { 'revision|r=s' => \$_revision,
144 'preserve-empty-dirs' =>
145 \$SVN::Git::Fetcher::_preserve_empty_dirs,
146 'placeholder-filename=s' =>
147 \$SVN::Git::Fetcher::_placeholder_filename,
148 %fc_opts, %init_opts } ],
149 init => [ \&cmd_init, "Initialize a repo for tracking" .
150 " (requires URL argument)",
151 \%init_opts ],
152 'multi-init' => [ \&cmd_multi_init,
153 "Deprecated alias for ".
154 "'$0 init -T<trunk> -b<branches> -t<tags>'",
155 \%init_opts ],
156 dcommit => [ \&cmd_dcommit,
157 'Commit several diffs to merge with upstream',
158 { 'merge|m|M' => \$_merge,
159 'strategy|s=s' => \$_strategy,
160 'verbose|v' => \$_verbose,
161 'dry-run|n' => \$_dry_run,
162 'fetch-all|all' => \$_fetch_all,
163 'commit-url=s' => \$_commit_url,
164 'revision|r=i' => \$_revision,
165 'no-rebase' => \$_no_rebase,
166 'mergeinfo=s' => \$_merge_info,
167 'interactive|i' => \$_interactive,
168 %cmt_opts, %fc_opts } ],
169 branch => [ \&cmd_branch,
170 'Create a branch in the SVN repository',
171 { 'message|m=s' => \$_message,
172 'destination|d=s' => \$_branch_dest,
173 'dry-run|n' => \$_dry_run,
174 'tag|t' => \$_tag,
175 'username=s' => \$Git::SVN::Prompt::_username,
176 'commit-url=s' => \$_commit_url } ],
177 tag => [ sub { $_tag = 1; cmd_branch(@_) },
178 'Create a tag in the SVN repository',
179 { 'message|m=s' => \$_message,
180 'destination|d=s' => \$_branch_dest,
181 'dry-run|n' => \$_dry_run,
182 'username=s' => \$Git::SVN::Prompt::_username,
183 'commit-url=s' => \$_commit_url } ],
184 'set-tree' => [ \&cmd_set_tree,
185 "Set an SVN repository to a git tree-ish",
186 { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
187 'create-ignore' => [ \&cmd_create_ignore,
188 'Create a .gitignore per svn:ignore',
189 { 'revision|r=i' => \$_revision
190 } ],
191 'mkdirs' => [ \&cmd_mkdirs ,
192 "recreate empty directories after a checkout",
193 { 'revision|r=i' => \$_revision } ],
194 'propget' => [ \&cmd_propget,
195 'Print the value of a property on a file or directory',
196 { 'revision|r=i' => \$_revision } ],
197 'proplist' => [ \&cmd_proplist,
198 'List all properties of a file or directory',
199 { 'revision|r=i' => \$_revision } ],
200 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
201 { 'revision|r=i' => \$_revision
202 } ],
203 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
204 { 'revision|r=i' => \$_revision
205 } ],
206 'multi-fetch' => [ \&cmd_multi_fetch,
207 "Deprecated alias for $0 fetch --all",
208 { 'revision|r=s' => \$_revision, %fc_opts } ],
209 'migrate' => [ sub { },
210 # no-op, we automatically run this anyways,
211 'Migrate configuration/metadata/layout from
212 previous versions of git-svn',
213 { 'minimize' => \$Git::SVN::Migration::_minimize,
214 %remote_opts } ],
215 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
216 { 'limit=i' => \$Git::SVN::Log::limit,
217 'revision|r=s' => \$_revision,
218 'verbose|v' => \$Git::SVN::Log::verbose,
219 'incremental' => \$Git::SVN::Log::incremental,
220 'oneline' => \$Git::SVN::Log::oneline,
221 'show-commit' => \$Git::SVN::Log::show_commit,
222 'non-recursive' => \$Git::SVN::Log::non_recursive,
223 'authors-file|A=s' => \$_authors,
224 'color' => \$Git::SVN::Log::color,
225 'pager=s' => \$Git::SVN::Log::pager
226 } ],
227 'find-rev' => [ \&cmd_find_rev,
228 "Translate between SVN revision numbers and tree-ish",
229 {} ],
230 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
231 { 'merge|m|M' => \$_merge,
232 'verbose|v' => \$_verbose,
233 'strategy|s=s' => \$_strategy,
234 'local|l' => \$_local,
235 'fetch-all|all' => \$_fetch_all,
236 'dry-run|n' => \$_dry_run,
237 %fc_opts } ],
238 'commit-diff' => [ \&cmd_commit_diff,
239 'Commit a diff between two trees',
240 { 'message|m=s' => \$_message,
241 'file|F=s' => \$_file,
242 'revision|r=s' => \$_revision,
243 %cmt_opts } ],
244 'info' => [ \&cmd_info,
245 "Show info about the latest SVN revision
246 on the current branch",
247 { 'url' => \$_url, } ],
248 'blame' => [ \&Git::SVN::Log::cmd_blame,
249 "Show what revision and author last modified each line of a file",
250 { 'git-format' => \$_git_format } ],
251 'reset' => [ \&cmd_reset,
252 "Undo fetches back to the specified SVN revision",
253 { 'revision|r=s' => \$_revision,
254 'parent|p' => \$_fetch_parent } ],
255 'gc' => [ \&cmd_gc,
256 "Compress unhandled.log files in .git/svn and remove " .
257 "index files in .git/svn",
258 {} ],
261 use Term::ReadLine;
262 package FakeTerm;
263 sub new {
264 my ($class, $reason) = @_;
265 return bless \$reason, shift;
267 sub readline {
268 my $self = shift;
269 die "Cannot use readline on FakeTerm: $$self";
271 package main;
273 my $term = eval {
274 $ENV{"GIT_SVN_NOTTY"}
275 ? new Term::ReadLine 'git-svn', \*STDIN, \*STDOUT
276 : new Term::ReadLine 'git-svn';
278 if ($@) {
279 $term = new FakeTerm "$@: going non-interactive";
282 my $cmd;
283 for (my $i = 0; $i < @ARGV; $i++) {
284 if (defined $cmd{$ARGV[$i]}) {
285 $cmd = $ARGV[$i];
286 splice @ARGV, $i, 1;
287 last;
288 } elsif ($ARGV[$i] eq 'help') {
289 $cmd = $ARGV[$i+1];
290 usage(0);
294 # make sure we're always running at the top-level working directory
295 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
296 unless (-d $ENV{GIT_DIR}) {
297 if ($git_dir_user_set) {
298 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
299 "but it is not a directory\n";
301 my $git_dir = delete $ENV{GIT_DIR};
302 my $cdup = undef;
303 git_cmd_try {
304 $cdup = command_oneline(qw/rev-parse --show-cdup/);
305 $git_dir = '.' unless ($cdup);
306 chomp $cdup if ($cdup);
307 $cdup = "." unless ($cdup && length $cdup);
308 } "Already at toplevel, but $git_dir not found\n";
309 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
310 unless (-d $git_dir) {
311 die "$git_dir still not found after going to ",
312 "'$cdup'\n";
314 $ENV{GIT_DIR} = $git_dir;
316 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
319 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
321 read_git_config(\%opts);
322 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
323 Getopt::Long::Configure('pass_through');
325 my $rv = GetOptions(%opts, 'h|H' => \$_help, 'version|V' => \$_version,
326 'minimize-connections' => \$Git::SVN::Migration::_minimize,
327 'id|i=s' => \$Git::SVN::default_ref_id,
328 'svn-remote|remote|R=s' => sub {
329 $Git::SVN::no_reuse_existing = 1;
330 $Git::SVN::default_repo_id = $_[1] });
331 exit 1 if (!$rv && $cmd && $cmd ne 'log');
333 usage(0) if $_help;
334 version() if $_version;
335 usage(1) unless defined $cmd;
336 load_authors() if $_authors;
337 if (defined $_authors_prog) {
338 $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
341 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
342 Git::SVN::Migration::migration_check();
344 Git::SVN::init_vars();
345 eval {
346 Git::SVN::verify_remotes_sanity();
347 $cmd{$cmd}->[0]->(@ARGV);
349 fatal $@ if $@;
350 post_fetch_checkout();
351 exit 0;
353 ####################### primary functions ######################
354 sub usage {
355 my $exit = shift || 0;
356 my $fd = $exit ? \*STDERR : \*STDOUT;
357 print $fd <<"";
358 git-svn - bidirectional operations between a single Subversion tree and git
359 Usage: git svn <command> [options] [arguments]\n
361 print $fd "Available commands:\n" unless $cmd;
363 foreach (sort keys %cmd) {
364 next if $cmd && $cmd ne $_;
365 next if /^multi-/; # don't show deprecated commands
366 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
367 foreach (sort keys %{$cmd{$_}->[2]}) {
368 # mixed-case options are for .git/config only
369 next if /[A-Z]/ && /^[a-z]+$/i;
370 # prints out arguments as they should be passed:
371 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
372 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
373 "--$_" : "-$_" }
374 split /\|/,$_)," $x\n";
377 print $fd <<"";
378 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
379 arbitrary identifier if you're tracking multiple SVN branches/repositories in
380 one git repository and want to keep them separate. See git-svn(1) for more
381 information.
383 exit $exit;
386 sub version {
387 ::_req_svn();
388 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
389 exit 0;
392 sub ask {
393 my ($prompt, %arg) = @_;
394 my $valid_re = $arg{valid_re};
395 my $default = $arg{default};
396 my $resp;
397 my $i = 0;
399 if ( !( defined($term->IN)
400 && defined( fileno($term->IN) )
401 && defined( $term->OUT )
402 && defined( fileno($term->OUT) ) ) ){
403 return defined($default) ? $default : undef;
406 while ($i++ < 10) {
407 $resp = $term->readline($prompt);
408 if (!defined $resp) { # EOF
409 print "\n";
410 return defined $default ? $default : undef;
412 if ($resp eq '' and defined $default) {
413 return $default;
415 if (!defined $valid_re or $resp =~ /$valid_re/) {
416 return $resp;
419 return undef;
422 sub do_git_init_db {
423 unless (-d $ENV{GIT_DIR}) {
424 my @init_db = ('init');
425 push @init_db, "--template=$_template" if defined $_template;
426 if (defined $_shared) {
427 if ($_shared =~ /[a-z]/) {
428 push @init_db, "--shared=$_shared";
429 } else {
430 push @init_db, "--shared";
433 command_noisy(@init_db);
434 $_repository = Git->repository(Repository => ".git");
436 my $set;
437 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
438 foreach my $i (keys %icv) {
439 die "'$set' and '$i' cannot both be set\n" if $set;
440 next unless defined $icv{$i};
441 command_noisy('config', "$pfx.$i", $icv{$i});
442 $set = $i;
444 my $ignore_paths_regex = \$SVN::Git::Fetcher::_ignore_regex;
445 command_noisy('config', "$pfx.ignore-paths", $$ignore_paths_regex)
446 if defined $$ignore_paths_regex;
447 my $ignore_refs_regex = \$Git::SVN::Ra::_ignore_refs_regex;
448 command_noisy('config', "$pfx.ignore-refs", $$ignore_refs_regex)
449 if defined $$ignore_refs_regex;
451 if (defined $SVN::Git::Fetcher::_preserve_empty_dirs) {
452 my $fname = \$SVN::Git::Fetcher::_placeholder_filename;
453 command_noisy('config', "$pfx.preserve-empty-dirs", 'true');
454 command_noisy('config', "$pfx.placeholder-filename", $$fname);
458 sub init_subdir {
459 my $repo_path = shift or return;
460 mkpath([$repo_path]) unless -d $repo_path;
461 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
462 $ENV{GIT_DIR} = '.git';
463 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
466 sub cmd_clone {
467 my ($url, $path) = @_;
468 if (!defined $path &&
469 (defined $_trunk || @_branches || @_tags ||
470 defined $_stdlayout) &&
471 $url !~ m#^[a-z\+]+://#) {
472 $path = $url;
474 $path = basename($url) if !defined $path || !length $path;
475 my $authors_absolute = $_authors ? File::Spec->rel2abs($_authors) : "";
476 cmd_init($url, $path);
477 command_oneline('config', 'svn.authorsfile', $authors_absolute)
478 if $_authors;
479 Git::SVN::fetch_all($Git::SVN::default_repo_id);
482 sub cmd_init {
483 if (defined $_stdlayout) {
484 $_trunk = 'trunk' if (!defined $_trunk);
485 @_tags = 'tags' if (! @_tags);
486 @_branches = 'branches' if (! @_branches);
488 if (defined $_trunk || @_branches || @_tags) {
489 return cmd_multi_init(@_);
491 my $url = shift or die "SVN repository location required ",
492 "as a command-line argument\n";
493 $url = canonicalize_url($url);
494 init_subdir(@_);
495 do_git_init_db();
497 if ($Git::SVN::_minimize_url eq 'unset') {
498 $Git::SVN::_minimize_url = 0;
501 Git::SVN->init($url);
504 sub cmd_fetch {
505 if (grep /^\d+=./, @_) {
506 die "'<rev>=<commit>' fetch arguments are ",
507 "no longer supported.\n";
509 my ($remote) = @_;
510 if (@_ > 1) {
511 die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
513 $Git::SVN::no_reuse_existing = undef;
514 if ($_fetch_parent) {
515 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
516 unless ($gs) {
517 die "Unable to determine upstream SVN information from ",
518 "working tree history\n";
520 # just fetch, don't checkout.
521 $_no_checkout = 'true';
522 $_fetch_all ? $gs->fetch_all : $gs->fetch;
523 } elsif ($_fetch_all) {
524 cmd_multi_fetch();
525 } else {
526 $remote ||= $Git::SVN::default_repo_id;
527 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
531 sub cmd_set_tree {
532 my (@commits) = @_;
533 if ($_stdin || !@commits) {
534 print "Reading from stdin...\n";
535 @commits = ();
536 while (<STDIN>) {
537 if (/\b($sha1_short)\b/o) {
538 unshift @commits, $1;
542 my @revs;
543 foreach my $c (@commits) {
544 my @tmp = command('rev-parse',$c);
545 if (scalar @tmp == 1) {
546 push @revs, $tmp[0];
547 } elsif (scalar @tmp > 1) {
548 push @revs, reverse(command('rev-list',@tmp));
549 } else {
550 fatal "Failed to rev-parse $c";
553 my $gs = Git::SVN->new;
554 my ($r_last, $cmt_last) = $gs->last_rev_commit;
555 $gs->fetch;
556 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
557 fatal "There are new revisions that were fetched ",
558 "and need to be merged (or acknowledged) ",
559 "before committing.\nlast rev: $r_last\n",
560 " current: $gs->{last_rev}";
562 $gs->set_tree($_) foreach @revs;
563 print "Done committing ",scalar @revs," revisions to SVN\n";
564 unlink $gs->{index};
567 sub split_merge_info_range {
568 my ($range) = @_;
569 if ($range =~ /(\d+)-(\d+)/) {
570 return (int($1), int($2));
571 } else {
572 return (int($range), int($range));
576 sub combine_ranges {
577 my ($in) = @_;
579 my @fnums = ();
580 my @arr = split(/,/, $in);
581 for my $element (@arr) {
582 my ($start, $end) = split_merge_info_range($element);
583 push @fnums, $start;
586 my @sorted = @arr [ sort {
587 $fnums[$a] <=> $fnums[$b]
588 } 0..$#arr ];
590 my @return = ();
591 my $last = -1;
592 my $first = -1;
593 for my $element (@sorted) {
594 my ($start, $end) = split_merge_info_range($element);
596 if ($last == -1) {
597 $first = $start;
598 $last = $end;
599 next;
601 if ($start <= $last+1) {
602 if ($end > $last) {
603 $last = $end;
605 next;
607 if ($first == $last) {
608 push @return, "$first";
609 } else {
610 push @return, "$first-$last";
612 $first = $start;
613 $last = $end;
616 if ($first != -1) {
617 if ($first == $last) {
618 push @return, "$first";
619 } else {
620 push @return, "$first-$last";
624 return join(',', @return);
627 sub merge_revs_into_hash {
628 my ($hash, $minfo) = @_;
629 my @lines = split(' ', $minfo);
631 for my $line (@lines) {
632 my ($branchpath, $revs) = split(/:/, $line);
634 if (exists($hash->{$branchpath})) {
635 # Merge the two revision sets
636 my $combined = "$hash->{$branchpath},$revs";
637 $hash->{$branchpath} = combine_ranges($combined);
638 } else {
639 # Just do range combining for consolidation
640 $hash->{$branchpath} = combine_ranges($revs);
645 sub merge_merge_info {
646 my ($mergeinfo_one, $mergeinfo_two) = @_;
647 my %result_hash = ();
649 merge_revs_into_hash(\%result_hash, $mergeinfo_one);
650 merge_revs_into_hash(\%result_hash, $mergeinfo_two);
652 my $result = '';
653 # Sort below is for consistency's sake
654 for my $branchname (sort keys(%result_hash)) {
655 my $revlist = $result_hash{$branchname};
656 $result .= "$branchname:$revlist\n"
658 return $result;
661 sub populate_merge_info {
662 my ($d, $gs, $uuid, $linear_refs, $rewritten_parent) = @_;
664 my %parentshash;
665 read_commit_parents(\%parentshash, $d);
666 my @parents = @{$parentshash{$d}};
667 if ($#parents > 0) {
668 # Merge commit
669 my $all_parents_ok = 1;
670 my $aggregate_mergeinfo = '';
671 my $rooturl = $gs->repos_root;
673 if (defined($rewritten_parent)) {
674 # Replace first parent with newly-rewritten version
675 shift @parents;
676 unshift @parents, $rewritten_parent;
679 foreach my $parent (@parents) {
680 my ($branchurl, $svnrev, $paruuid) =
681 cmt_metadata($parent);
683 unless (defined($svnrev)) {
684 # Should have been caught be preflight check
685 fatal "merge commit $d has ancestor $parent, but that change "
686 ."does not have git-svn metadata!";
688 unless ($branchurl =~ /^$rooturl(.*)/) {
689 fatal "commit $parent git-svn metadata changed mid-run!";
691 my $branchpath = $1;
693 my $ra = Git::SVN::Ra->new($branchurl);
694 my (undef, undef, $props) =
695 $ra->get_dir(canonicalize_path("."), $svnrev);
696 my $par_mergeinfo = $props->{'svn:mergeinfo'};
697 unless (defined $par_mergeinfo) {
698 $par_mergeinfo = '';
700 # Merge previous mergeinfo values
701 $aggregate_mergeinfo =
702 merge_merge_info($aggregate_mergeinfo,
703 $par_mergeinfo, 0);
705 next if $parent eq $parents[0]; # Skip first parent
706 # Add new changes being placed in tree by merge
707 my @cmd = (qw/rev-list --reverse/,
708 $parent, qw/--not/);
709 foreach my $par (@parents) {
710 unless ($par eq $parent) {
711 push @cmd, $par;
714 my @revsin = ();
715 my ($revlist, $ctx) = command_output_pipe(@cmd);
716 while (<$revlist>) {
717 my $irev = $_;
718 chomp $irev;
719 my (undef, $csvnrev, undef) =
720 cmt_metadata($irev);
721 unless (defined $csvnrev) {
722 # A child is missing SVN annotations...
723 # this might be OK, or might not be.
724 warn "W:child $irev is merged into revision "
725 ."$d but does not have git-svn metadata. "
726 ."This means git-svn cannot determine the "
727 ."svn revision numbers to place into the "
728 ."svn:mergeinfo property. You must ensure "
729 ."a branch is entirely committed to "
730 ."SVN before merging it in order for "
731 ."svn:mergeinfo population to function "
732 ."properly";
734 push @revsin, $csvnrev;
736 command_close_pipe($revlist, $ctx);
738 last unless $all_parents_ok;
740 # We now have a list of all SVN revnos which are
741 # merged by this particular parent. Integrate them.
742 next if $#revsin == -1;
743 my $newmergeinfo = "$branchpath:" . join(',', @revsin);
744 $aggregate_mergeinfo =
745 merge_merge_info($aggregate_mergeinfo,
746 $newmergeinfo, 1);
748 if ($all_parents_ok and $aggregate_mergeinfo) {
749 return $aggregate_mergeinfo;
753 return undef;
756 sub cmd_dcommit {
757 my $head = shift;
758 command_noisy(qw/update-index --refresh/);
759 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
760 'Cannot dcommit with a dirty index. Commit your changes first, '
761 . "or stash them with `git stash'.\n";
762 $head ||= 'HEAD';
764 my $old_head;
765 if ($head ne 'HEAD') {
766 $old_head = eval {
767 command_oneline([qw/symbolic-ref -q HEAD/])
769 if ($old_head) {
770 $old_head =~ s{^refs/heads/}{};
771 } else {
772 $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
774 command(['checkout', $head], STDERR => 0);
777 my @refs;
778 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
779 unless ($gs) {
780 die "Unable to determine upstream SVN information from ",
781 "$head history.\nPerhaps the repository is empty.";
784 if (defined $_commit_url) {
785 $url = $_commit_url;
786 } else {
787 $url = eval { command_oneline('config', '--get',
788 "svn-remote.$gs->{repo_id}.commiturl") };
789 if (!$url) {
790 $url = $gs->full_pushurl
794 my $last_rev = $_revision if defined $_revision;
795 if ($url) {
796 print "Committing to $url ...\n";
798 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
799 if ($_no_rebase && scalar(@$linear_refs) > 1) {
800 warn "Attempting to commit more than one change while ",
801 "--no-rebase is enabled.\n",
802 "If these changes depend on each other, re-running ",
803 "without --no-rebase may be required."
806 if (defined $_interactive){
807 my $ask_default = "y";
808 foreach my $d (@$linear_refs){
809 my ($fh, $ctx) = command_output_pipe(qw(show --summary), "$d");
810 while (<$fh>){
811 print $_;
813 command_close_pipe($fh, $ctx);
814 $_ = ask("Commit this patch to SVN? ([y]es (default)|[n]o|[q]uit|[a]ll): ",
815 valid_re => qr/^(?:yes|y|no|n|quit|q|all|a)/i,
816 default => $ask_default);
817 die "Commit this patch reply required" unless defined $_;
818 if (/^[nq]/i) {
819 exit(0);
820 } elsif (/^a/i) {
821 last;
826 my $expect_url = $url;
828 my $push_merge_info = eval {
829 command_oneline(qw/config --get svn.pushmergeinfo/)
831 if (not defined($push_merge_info)
832 or $push_merge_info eq "false"
833 or $push_merge_info eq "no"
834 or $push_merge_info eq "never") {
835 $push_merge_info = 0;
838 unless (defined($_merge_info) || ! $push_merge_info) {
839 # Preflight check of changes to ensure no issues with mergeinfo
840 # This includes check for uncommitted-to-SVN parents
841 # (other than the first parent, which we will handle),
842 # information from different SVN repos, and paths
843 # which are not underneath this repository root.
844 my $rooturl = $gs->repos_root;
845 foreach my $d (@$linear_refs) {
846 my %parentshash;
847 read_commit_parents(\%parentshash, $d);
848 my @realparents = @{$parentshash{$d}};
849 if ($#realparents > 0) {
850 # Merge commit
851 shift @realparents; # Remove/ignore first parent
852 foreach my $parent (@realparents) {
853 my ($branchurl, $svnrev, $paruuid) = cmt_metadata($parent);
854 unless (defined $paruuid) {
855 # A parent is missing SVN annotations...
856 # abort the whole operation.
857 fatal "$parent is merged into revision $d, "
858 ."but does not have git-svn metadata. "
859 ."Either dcommit the branch or use a "
860 ."local cherry-pick, FF merge, or rebase "
861 ."instead of an explicit merge commit.";
864 unless ($paruuid eq $uuid) {
865 # Parent has SVN metadata from different repository
866 fatal "merge parent $parent for change $d has "
867 ."git-svn uuid $paruuid, while current change "
868 ."has uuid $uuid!";
871 unless ($branchurl =~ /^$rooturl(.*)/) {
872 # This branch is very strange indeed.
873 fatal "merge parent $parent for $d is on branch "
874 ."$branchurl, which is not under the "
875 ."git-svn root $rooturl!";
882 my $rewritten_parent;
883 Git::SVN::remove_username($expect_url);
884 if (defined($_merge_info)) {
885 $_merge_info =~ tr{ }{\n};
887 while (1) {
888 my $d = shift @$linear_refs or last;
889 unless (defined $last_rev) {
890 (undef, $last_rev, undef) = cmt_metadata("$d~1");
891 unless (defined $last_rev) {
892 fatal "Unable to extract revision information ",
893 "from commit $d~1";
896 if ($_dry_run) {
897 print "diff-tree $d~1 $d\n";
898 } else {
899 my $cmt_rev;
901 unless (defined($_merge_info) || ! $push_merge_info) {
902 $_merge_info = populate_merge_info($d, $gs,
903 $uuid,
904 $linear_refs,
905 $rewritten_parent);
908 my %ed_opts = ( r => $last_rev,
909 log => get_commit_entry($d)->{log},
910 ra => Git::SVN::Ra->new($url),
911 config => SVN::Core::config_get_config(
912 $Git::SVN::Ra::config_dir
914 tree_a => "$d~1",
915 tree_b => $d,
916 editor_cb => sub {
917 print "Committed r$_[0]\n";
918 $cmt_rev = $_[0];
920 mergeinfo => $_merge_info,
921 svn_path => '');
922 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
923 print "No changes\n$d~1 == $d\n";
924 } elsif ($parents->{$d} && @{$parents->{$d}}) {
925 $gs->{inject_parents_dcommit}->{$cmt_rev} =
926 $parents->{$d};
928 $_fetch_all ? $gs->fetch_all : $gs->fetch;
929 $last_rev = $cmt_rev;
930 next if $_no_rebase;
932 # we always want to rebase against the current HEAD,
933 # not any head that was passed to us
934 my @diff = command('diff-tree', $d,
935 $gs->refname, '--');
936 my @finish;
937 if (@diff) {
938 @finish = rebase_cmd();
939 print STDERR "W: $d and ", $gs->refname,
940 " differ, using @finish:\n",
941 join("\n", @diff), "\n";
942 } else {
943 print "No changes between current HEAD and ",
944 $gs->refname,
945 "\nResetting to the latest ",
946 $gs->refname, "\n";
947 @finish = qw/reset --mixed/;
949 command_noisy(@finish, $gs->refname);
951 $rewritten_parent = command_oneline(qw/rev-parse HEAD/);
953 if (@diff) {
954 @refs = ();
955 my ($url_, $rev_, $uuid_, $gs_) =
956 working_head_info('HEAD', \@refs);
957 my ($linear_refs_, $parents_) =
958 linearize_history($gs_, \@refs);
959 if (scalar(@$linear_refs) !=
960 scalar(@$linear_refs_)) {
961 fatal "# of revisions changed ",
962 "\nbefore:\n",
963 join("\n", @$linear_refs),
964 "\n\nafter:\n",
965 join("\n", @$linear_refs_), "\n",
966 'If you are attempting to commit ',
967 "merges, try running:\n\t",
968 'git rebase --interactive',
969 '--preserve-merges ',
970 $gs->refname,
971 "\nBefore dcommitting";
973 if ($url_ ne $expect_url) {
974 if ($url_ eq $gs->metadata_url) {
975 print
976 "Accepting rewritten URL:",
977 " $url_\n";
978 } else {
979 fatal
980 "URL mismatch after rebase:",
981 " $url_ != $expect_url";
984 if ($uuid_ ne $uuid) {
985 fatal "uuid mismatch after rebase: ",
986 "$uuid_ != $uuid";
988 # remap parents
989 my (%p, @l, $i);
990 for ($i = 0; $i < scalar @$linear_refs; $i++) {
991 my $new = $linear_refs_->[$i] or next;
992 $p{$new} =
993 $parents->{$linear_refs->[$i]};
994 push @l, $new;
996 $parents = \%p;
997 $linear_refs = \@l;
1002 if ($old_head) {
1003 my $new_head = command_oneline(qw/rev-parse HEAD/);
1004 my $new_is_symbolic = eval {
1005 command_oneline(qw/symbolic-ref -q HEAD/);
1007 if ($new_is_symbolic) {
1008 print "dcommitted the branch ", $head, "\n";
1009 } else {
1010 print "dcommitted on a detached HEAD because you gave ",
1011 "a revision argument.\n",
1012 "The rewritten commit is: ", $new_head, "\n";
1014 command(['checkout', $old_head], STDERR => 0);
1017 unlink $gs->{index};
1020 sub cmd_branch {
1021 my ($branch_name, $head) = @_;
1023 unless (defined $branch_name && length $branch_name) {
1024 die(($_tag ? "tag" : "branch") . " name required\n");
1026 $head ||= 'HEAD';
1028 my (undef, $rev, undef, $gs) = working_head_info($head);
1029 my $src = $gs->full_pushurl;
1031 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
1032 my $allglobs = $remote->{ $_tag ? 'tags' : 'branches' };
1033 my $glob;
1034 if ($#{$allglobs} == 0) {
1035 $glob = $allglobs->[0];
1036 } else {
1037 unless(defined $_branch_dest) {
1038 die "Multiple ",
1039 $_tag ? "tag" : "branch",
1040 " paths defined for Subversion repository.\n",
1041 "You must specify where you want to create the ",
1042 $_tag ? "tag" : "branch",
1043 " with the --destination argument.\n";
1045 foreach my $g (@{$allglobs}) {
1046 # SVN::Git::Editor could probably be moved to Git.pm..
1047 my $re = SVN::Git::Editor::glob2pat($g->{path}->{left});
1048 if ($_branch_dest =~ /$re/) {
1049 $glob = $g;
1050 last;
1053 unless (defined $glob) {
1054 my $dest_re = qr/\b\Q$_branch_dest\E\b/;
1055 foreach my $g (@{$allglobs}) {
1056 $g->{path}->{left} =~ /$dest_re/ or next;
1057 if (defined $glob) {
1058 die "Ambiguous destination: ",
1059 $_branch_dest, "\nmatches both '",
1060 $glob->{path}->{left}, "' and '",
1061 $g->{path}->{left}, "'\n";
1063 $glob = $g;
1065 unless (defined $glob) {
1066 die "Unknown ",
1067 $_tag ? "tag" : "branch",
1068 " destination $_branch_dest\n";
1072 my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
1073 my $url;
1074 if (defined $_commit_url) {
1075 $url = $_commit_url;
1076 } else {
1077 $url = eval { command_oneline('config', '--get',
1078 "svn-remote.$gs->{repo_id}.commiturl") };
1079 if (!$url) {
1080 $url = $remote->{pushurl} || $remote->{url};
1083 my $dst = join '/', $url, $lft, $branch_name, ($rgt || ());
1085 if ($dst =~ /^https:/ && $src =~ /^http:/) {
1086 $src=~s/^http:/https:/;
1089 ::_req_svn();
1091 my $ctx = SVN::Client->new(
1092 auth => Git::SVN::Ra::_auth_providers(),
1093 log_msg => sub {
1094 ${ $_[0] } = defined $_message
1095 ? $_message
1096 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
1097 . $branch_name;
1101 eval {
1102 $ctx->ls($dst, 'HEAD', 0);
1103 } and die "branch ${branch_name} already exists\n";
1105 print "Copying ${src} at r${rev} to ${dst}...\n";
1106 $ctx->copy($src, $rev, $dst)
1107 unless $_dry_run;
1109 $gs->fetch_all;
1112 sub cmd_find_rev {
1113 my $revision_or_hash = shift or die "SVN or git revision required ",
1114 "as a command-line argument\n";
1115 my $result;
1116 if ($revision_or_hash =~ /^r\d+$/) {
1117 my $head = shift;
1118 $head ||= 'HEAD';
1119 my @refs;
1120 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
1121 unless ($gs) {
1122 die "Unable to determine upstream SVN information from ",
1123 "$head history\n";
1125 my $desired_revision = substr($revision_or_hash, 1);
1126 $result = $gs->rev_map_get($desired_revision, $uuid);
1127 } else {
1128 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
1129 $result = $rev;
1131 print "$result\n" if $result;
1134 sub auto_create_empty_directories {
1135 my ($gs) = @_;
1136 my $var = eval { command_oneline('config', '--get', '--bool',
1137 "svn-remote.$gs->{repo_id}.automkdirs") };
1138 # By default, create empty directories by consulting the unhandled log,
1139 # but allow setting it to 'false' to skip it.
1140 return !($var && $var eq 'false');
1143 sub cmd_rebase {
1144 command_noisy(qw/update-index --refresh/);
1145 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1146 unless ($gs) {
1147 die "Unable to determine upstream SVN information from ",
1148 "working tree history\n";
1150 if ($_dry_run) {
1151 print "Remote Branch: " . $gs->refname . "\n";
1152 print "SVN URL: " . $url . "\n";
1153 return;
1155 if (command(qw/diff-index HEAD --/)) {
1156 print STDERR "Cannot rebase with uncommited changes:\n";
1157 command_noisy('status');
1158 exit 1;
1160 unless ($_local) {
1161 # rebase will checkout for us, so no need to do it explicitly
1162 $_no_checkout = 'true';
1163 $_fetch_all ? $gs->fetch_all : $gs->fetch;
1165 command_noisy(rebase_cmd(), $gs->refname);
1166 if (auto_create_empty_directories($gs)) {
1167 $gs->mkemptydirs;
1171 sub cmd_show_ignore {
1172 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1173 $gs ||= Git::SVN->new;
1174 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1175 $gs->prop_walk($gs->{path}, $r, sub {
1176 my ($gs, $path, $props) = @_;
1177 print STDOUT "\n# $path\n";
1178 my $s = $props->{'svn:ignore'} or return;
1179 $s =~ s/[\r\n]+/\n/g;
1180 $s =~ s/^\n+//;
1181 chomp $s;
1182 $s =~ s#^#$path#gm;
1183 print STDOUT "$s\n";
1187 sub cmd_show_externals {
1188 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1189 $gs ||= Git::SVN->new;
1190 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1191 $gs->prop_walk($gs->{path}, $r, sub {
1192 my ($gs, $path, $props) = @_;
1193 print STDOUT "\n# $path\n";
1194 my $s = $props->{'svn:externals'} or return;
1195 $s =~ s/[\r\n]+/\n/g;
1196 chomp $s;
1197 $s =~ s#^#$path#gm;
1198 print STDOUT "$s\n";
1202 sub cmd_create_ignore {
1203 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1204 $gs ||= Git::SVN->new;
1205 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1206 $gs->prop_walk($gs->{path}, $r, sub {
1207 my ($gs, $path, $props) = @_;
1208 # $path is of the form /path/to/dir/
1209 $path = '.' . $path;
1210 # SVN can have attributes on empty directories,
1211 # which git won't track
1212 mkpath([$path]) unless -d $path;
1213 my $ignore = $path . '.gitignore';
1214 my $s = $props->{'svn:ignore'} or return;
1215 open(GITIGNORE, '>', $ignore)
1216 or fatal("Failed to open `$ignore' for writing: $!");
1217 $s =~ s/[\r\n]+/\n/g;
1218 $s =~ s/^\n+//;
1219 chomp $s;
1220 # Prefix all patterns so that the ignore doesn't apply
1221 # to sub-directories.
1222 $s =~ s#^#/#gm;
1223 print GITIGNORE "$s\n";
1224 close(GITIGNORE)
1225 or fatal("Failed to close `$ignore': $!");
1226 command_noisy('add', '-f', $ignore);
1230 sub cmd_mkdirs {
1231 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1232 $gs ||= Git::SVN->new;
1233 $gs->mkemptydirs($_revision);
1236 sub canonicalize_path {
1237 my ($path) = @_;
1238 my $dot_slash_added = 0;
1239 if (substr($path, 0, 1) ne "/") {
1240 $path = "./" . $path;
1241 $dot_slash_added = 1;
1243 # File::Spec->canonpath doesn't collapse x/../y into y (for a
1244 # good reason), so let's do this manually.
1245 $path =~ s#/+#/#g;
1246 $path =~ s#/\.(?:/|$)#/#g;
1247 $path =~ s#/[^/]+/\.\.##g;
1248 $path =~ s#/$##g;
1249 $path =~ s#^\./## if $dot_slash_added;
1250 $path =~ s#^/##;
1251 $path =~ s#^\.$##;
1252 return $path;
1255 sub canonicalize_url {
1256 my ($url) = @_;
1257 $url =~ s#^([^:]+://[^/]*/)(.*)$#$1 . canonicalize_path($2)#e;
1258 return $url;
1261 # get_svnprops(PATH)
1262 # ------------------
1263 # Helper for cmd_propget and cmd_proplist below.
1264 sub get_svnprops {
1265 my $path = shift;
1266 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1267 $gs ||= Git::SVN->new;
1269 # prefix THE PATH by the sub-directory from which the user
1270 # invoked us.
1271 $path = $cmd_dir_prefix . $path;
1272 fatal("No such file or directory: $path") unless -e $path;
1273 my $is_dir = -d $path ? 1 : 0;
1274 $path = $gs->{path} . '/' . $path;
1276 # canonicalize the path (otherwise libsvn will abort or fail to
1277 # find the file)
1278 $path = canonicalize_path($path);
1280 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1281 my $props;
1282 if ($is_dir) {
1283 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
1285 else {
1286 (undef, $props) = $gs->ra->get_file($path, $r, undef);
1288 return $props;
1291 # cmd_propget (PROP, PATH)
1292 # ------------------------
1293 # Print the SVN property PROP for PATH.
1294 sub cmd_propget {
1295 my ($prop, $path) = @_;
1296 $path = '.' if not defined $path;
1297 usage(1) if not defined $prop;
1298 my $props = get_svnprops($path);
1299 if (not defined $props->{$prop}) {
1300 fatal("`$path' does not have a `$prop' SVN property.");
1302 print $props->{$prop} . "\n";
1305 # cmd_proplist (PATH)
1306 # -------------------
1307 # Print the list of SVN properties for PATH.
1308 sub cmd_proplist {
1309 my $path = shift;
1310 $path = '.' if not defined $path;
1311 my $props = get_svnprops($path);
1312 print "Properties on '$path':\n";
1313 foreach (sort keys %{$props}) {
1314 print " $_\n";
1318 sub cmd_multi_init {
1319 my $url = shift;
1320 unless (defined $_trunk || @_branches || @_tags) {
1321 usage(1);
1324 $_prefix = '' unless defined $_prefix;
1325 if (defined $url) {
1326 $url = canonicalize_url($url);
1327 init_subdir(@_);
1329 do_git_init_db();
1330 if (defined $_trunk) {
1331 $_trunk =~ s#^/+##;
1332 my $trunk_ref = 'refs/remotes/' . $_prefix . 'trunk';
1333 # try both old-style and new-style lookups:
1334 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
1335 unless ($gs_trunk) {
1336 my ($trunk_url, $trunk_path) =
1337 complete_svn_url($url, $_trunk);
1338 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
1339 undef, $trunk_ref);
1342 return unless @_branches || @_tags;
1343 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
1344 foreach my $path (@_branches) {
1345 complete_url_ls_init($ra, $path, '--branches/-b', $_prefix);
1347 foreach my $path (@_tags) {
1348 complete_url_ls_init($ra, $path, '--tags/-t', $_prefix.'tags/');
1352 sub cmd_multi_fetch {
1353 $Git::SVN::no_reuse_existing = undef;
1354 my $remotes = Git::SVN::read_all_remotes();
1355 foreach my $repo_id (sort keys %$remotes) {
1356 if ($remotes->{$repo_id}->{url}) {
1357 Git::SVN::fetch_all($repo_id, $remotes);
1362 # this command is special because it requires no metadata
1363 sub cmd_commit_diff {
1364 my ($ta, $tb, $url) = @_;
1365 my $usage = "Usage: $0 commit-diff -r<revision> ".
1366 "<tree-ish> <tree-ish> [<URL>]";
1367 fatal($usage) if (!defined $ta || !defined $tb);
1368 my $svn_path = '';
1369 if (!defined $url) {
1370 my $gs = eval { Git::SVN->new };
1371 if (!$gs) {
1372 fatal("Needed URL or usable git-svn --id in ",
1373 "the command-line\n", $usage);
1375 $url = $gs->{url};
1376 $svn_path = $gs->{path};
1378 unless (defined $_revision) {
1379 fatal("-r|--revision is a required argument\n", $usage);
1381 if (defined $_message && defined $_file) {
1382 fatal("Both --message/-m and --file/-F specified ",
1383 "for the commit message.\n",
1384 "I have no idea what you mean");
1386 if (defined $_file) {
1387 $_message = file_to_s($_file);
1388 } else {
1389 $_message ||= get_commit_entry($tb)->{log};
1391 my $ra ||= Git::SVN::Ra->new($url);
1392 my $r = $_revision;
1393 if ($r eq 'HEAD') {
1394 $r = $ra->get_latest_revnum;
1395 } elsif ($r !~ /^\d+$/) {
1396 die "revision argument: $r not understood by git-svn\n";
1398 my %ed_opts = ( r => $r,
1399 log => $_message,
1400 ra => $ra,
1401 tree_a => $ta,
1402 tree_b => $tb,
1403 editor_cb => sub { print "Committed r$_[0]\n" },
1404 svn_path => $svn_path );
1405 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
1406 print "No changes\n$ta == $tb\n";
1410 sub escape_uri_only {
1411 my ($uri) = @_;
1412 my @tmp;
1413 foreach (split m{/}, $uri) {
1414 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
1415 push @tmp, $_;
1417 join('/', @tmp);
1420 sub escape_url {
1421 my ($url) = @_;
1422 if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
1423 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
1424 $url = "$scheme://$domain$uri";
1426 $url;
1429 sub cmd_info {
1430 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
1431 my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
1432 if (exists $_[1]) {
1433 die "Too many arguments specified\n";
1436 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
1438 if (!$file_type && !$diff_status) {
1439 print STDERR "svn: '$path' is not under version control\n";
1440 exit 1;
1443 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1444 unless ($gs) {
1445 die "Unable to determine upstream SVN information from ",
1446 "working tree history\n";
1449 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
1450 $path = "." if $path eq "";
1452 my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
1454 if ($_url) {
1455 print escape_url($full_url), "\n";
1456 return;
1459 my $result = "Path: $path\n";
1460 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
1461 $result .= "URL: " . escape_url($full_url) . "\n";
1463 eval {
1464 my $repos_root = $gs->repos_root;
1465 Git::SVN::remove_username($repos_root);
1466 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
1468 if ($@) {
1469 $result .= "Repository Root: (offline)\n";
1471 ::_req_svn();
1472 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
1473 ($SVN::Core::VERSION le '1.5.4' || $file_type ne "dir");
1474 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
1476 $result .= "Node Kind: " .
1477 ($file_type eq "dir" ? "directory" : "file") . "\n";
1479 my $schedule = $diff_status eq "A"
1480 ? "add"
1481 : ($diff_status eq "D" ? "delete" : "normal");
1482 $result .= "Schedule: $schedule\n";
1484 if ($diff_status eq "A") {
1485 print $result, "\n";
1486 return;
1489 my ($lc_author, $lc_rev, $lc_date_utc);
1490 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
1491 my $log = command_output_pipe(@args);
1492 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
1493 while (<$log>) {
1494 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
1495 $lc_author = $1;
1496 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
1497 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
1498 (undef, $lc_rev, undef) = ::extract_metadata($1);
1501 close $log;
1503 Git::SVN::Log::set_local_timezone();
1505 $result .= "Last Changed Author: $lc_author\n";
1506 $result .= "Last Changed Rev: $lc_rev\n";
1507 $result .= "Last Changed Date: " .
1508 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
1510 if ($file_type ne "dir") {
1511 my $text_last_updated_date =
1512 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
1513 $result .=
1514 "Text Last Updated: " .
1515 Git::SVN::Log::format_svn_date($text_last_updated_date) .
1516 "\n";
1517 my $checksum;
1518 if ($diff_status eq "D") {
1519 my ($fh, $ctx) =
1520 command_output_pipe(qw(cat-file blob), "HEAD:$path");
1521 if ($file_type eq "link") {
1522 my $file_name = <$fh>;
1523 $checksum = md5sum("link $file_name");
1524 } else {
1525 $checksum = md5sum($fh);
1527 command_close_pipe($fh, $ctx);
1528 } elsif ($file_type eq "link") {
1529 my $file_name =
1530 command(qw(cat-file blob), "HEAD:$path");
1531 $checksum =
1532 md5sum("link " . $file_name);
1533 } else {
1534 open FILE, "<", $path or die $!;
1535 $checksum = md5sum(\*FILE);
1536 close FILE or die $!;
1538 $result .= "Checksum: " . $checksum . "\n";
1541 print $result, "\n";
1544 sub cmd_reset {
1545 my $target = shift || $_revision or die "SVN revision required\n";
1546 $target = $1 if $target =~ /^r(\d+)$/;
1547 $target =~ /^\d+$/ or die "Numeric SVN revision expected\n";
1548 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1549 unless ($gs) {
1550 die "Unable to determine upstream SVN information from ".
1551 "history\n";
1553 my ($r, $c) = $gs->find_rev_before($target, not $_fetch_parent);
1554 die "Cannot find SVN revision $target\n" unless defined($c);
1555 $gs->rev_map_set($r, $c, 'reset', $uuid);
1556 print "r$r = $c ($gs->{ref_id})\n";
1559 sub cmd_gc {
1560 if (!$can_compress) {
1561 warn "Compress::Zlib could not be found; unhandled.log " .
1562 "files will not be compressed.\n";
1564 find({ wanted => \&gc_directory, no_chdir => 1}, "$ENV{GIT_DIR}/svn");
1567 ########################### utility functions #########################
1569 sub rebase_cmd {
1570 my @cmd = qw/rebase/;
1571 push @cmd, '-v' if $_verbose;
1572 push @cmd, qw/--merge/ if $_merge;
1573 push @cmd, "--strategy=$_strategy" if $_strategy;
1574 @cmd;
1577 sub post_fetch_checkout {
1578 return if $_no_checkout;
1579 my $gs = $Git::SVN::_head or return;
1580 return if verify_ref('refs/heads/master^0');
1582 # look for "trunk" ref if it exists
1583 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
1584 my $fetch = $remote->{fetch};
1585 if ($fetch) {
1586 foreach my $p (keys %$fetch) {
1587 basename($fetch->{$p}) eq 'trunk' or next;
1588 $gs = Git::SVN->new($fetch->{$p}, $gs->{repo_id}, $p);
1589 last;
1593 my $valid_head = verify_ref('HEAD^0');
1594 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1595 return if ($valid_head || !verify_ref('HEAD^0'));
1597 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1598 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1599 return if -f $index;
1601 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1602 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1603 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1604 print STDERR "Checked out HEAD:\n ",
1605 $gs->full_url, " r", $gs->last_rev, "\n";
1606 if (auto_create_empty_directories($gs)) {
1607 $gs->mkemptydirs($gs->last_rev);
1611 sub complete_svn_url {
1612 my ($url, $path) = @_;
1613 $path =~ s#/+$##;
1614 if ($path !~ m#^[a-z\+]+://#) {
1615 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1616 fatal("E: '$path' is not a complete URL ",
1617 "and a separate URL is not specified");
1619 return ($url, $path);
1621 return ($path, '');
1624 sub complete_url_ls_init {
1625 my ($ra, $repo_path, $switch, $pfx) = @_;
1626 unless ($repo_path) {
1627 print STDERR "W: $switch not specified\n";
1628 return;
1630 $repo_path =~ s#/+$##;
1631 if ($repo_path =~ m#^[a-z\+]+://#) {
1632 $ra = Git::SVN::Ra->new($repo_path);
1633 $repo_path = '';
1634 } else {
1635 $repo_path =~ s#^/+##;
1636 unless ($ra) {
1637 fatal("E: '$repo_path' is not a complete URL ",
1638 "and a separate URL is not specified");
1641 my $url = $ra->{url};
1642 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1643 my $k = "svn-remote.$gs->{repo_id}.url";
1644 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1645 if ($orig_url && ($orig_url ne $gs->{url})) {
1646 die "$k already set: $orig_url\n",
1647 "wanted to set to: $gs->{url}\n";
1649 command_oneline('config', $k, $gs->{url}) unless $orig_url;
1650 my $remote_path = "$gs->{path}/$repo_path";
1651 $remote_path =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
1652 $remote_path =~ s#/+#/#g;
1653 $remote_path =~ s#^/##g;
1654 $remote_path .= "/*" if $remote_path !~ /\*/;
1655 my ($n) = ($switch =~ /^--(\w+)/);
1656 if (length $pfx && $pfx !~ m#/$#) {
1657 die "--prefix='$pfx' must have a trailing slash '/'\n";
1659 command_noisy('config',
1660 '--add',
1661 "svn-remote.$gs->{repo_id}.$n",
1662 "$remote_path:refs/remotes/$pfx*" .
1663 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1666 sub verify_ref {
1667 my ($ref) = @_;
1668 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1669 { STDERR => 0 }); };
1672 sub get_tree_from_treeish {
1673 my ($treeish) = @_;
1674 # $treeish can be a symbolic ref, too:
1675 my $type = command_oneline(qw/cat-file -t/, $treeish);
1676 my $expected;
1677 while ($type eq 'tag') {
1678 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1680 if ($type eq 'commit') {
1681 $expected = (grep /^tree /, command(qw/cat-file commit/,
1682 $treeish))[0];
1683 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1684 die "Unable to get tree from $treeish\n" unless $expected;
1685 } elsif ($type eq 'tree') {
1686 $expected = $treeish;
1687 } else {
1688 die "$treeish is a $type, expected tree, tag or commit\n";
1690 return $expected;
1693 sub get_commit_entry {
1694 my ($treeish) = shift;
1695 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1696 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1697 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1698 open my $log_fh, '>', $commit_editmsg or croak $!;
1700 my $type = command_oneline(qw/cat-file -t/, $treeish);
1701 if ($type eq 'commit' || $type eq 'tag') {
1702 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1703 $type, $treeish);
1704 my $in_msg = 0;
1705 my $author;
1706 my $saw_from = 0;
1707 my $msgbuf = "";
1708 while (<$msg_fh>) {
1709 if (!$in_msg) {
1710 $in_msg = 1 if (/^\s*$/);
1711 $author = $1 if (/^author (.*>)/);
1712 } elsif (/^git-svn-id: /) {
1713 # skip this for now, we regenerate the
1714 # correct one on re-fetch anyways
1715 # TODO: set *:merge properties or like...
1716 } else {
1717 if (/^From:/ || /^Signed-off-by:/) {
1718 $saw_from = 1;
1720 $msgbuf .= $_;
1723 $msgbuf =~ s/\s+$//s;
1724 if ($Git::SVN::_add_author_from && defined($author)
1725 && !$saw_from) {
1726 $msgbuf .= "\n\nFrom: $author";
1728 print $log_fh $msgbuf or croak $!;
1729 command_close_pipe($msg_fh, $ctx);
1731 close $log_fh or croak $!;
1733 if ($_edit || ($type eq 'tree')) {
1734 chomp(my $editor = command_oneline(qw(var GIT_EDITOR)));
1735 system('sh', '-c', $editor.' "$@"', $editor, $commit_editmsg);
1737 rename $commit_editmsg, $commit_msg or croak $!;
1739 require Encode;
1740 # SVN requires messages to be UTF-8 when entering the repo
1741 local $/;
1742 open $log_fh, '<', $commit_msg or croak $!;
1743 binmode $log_fh;
1744 chomp($log_entry{log} = <$log_fh>);
1746 my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
1747 my $msg = $log_entry{log};
1749 eval { $msg = Encode::decode($enc, $msg, 1) };
1750 if ($@) {
1751 die "Could not decode as $enc:\n", $msg,
1752 "\nPerhaps you need to set i18n.commitencoding\n";
1755 eval { $msg = Encode::encode('UTF-8', $msg, 1) };
1756 die "Could not encode as UTF-8:\n$msg\n" if $@;
1758 $log_entry{log} = $msg;
1760 close $log_fh or croak $!;
1762 unlink $commit_msg;
1763 \%log_entry;
1766 sub s_to_file {
1767 my ($str, $file, $mode) = @_;
1768 open my $fd,'>',$file or croak $!;
1769 print $fd $str,"\n" or croak $!;
1770 close $fd or croak $!;
1771 chmod ($mode &~ umask, $file) if (defined $mode);
1774 sub file_to_s {
1775 my $file = shift;
1776 open my $fd,'<',$file or croak "$!: file: $file\n";
1777 local $/;
1778 my $ret = <$fd>;
1779 close $fd or croak $!;
1780 $ret =~ s/\s*$//s;
1781 return $ret;
1784 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1785 sub load_authors {
1786 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1787 my $log = $cmd eq 'log';
1788 while (<$authors>) {
1789 chomp;
1790 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1791 my ($user, $name, $email) = ($1, $2, $3);
1792 if ($log) {
1793 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1794 } else {
1795 $users{$user} = [$name, $email];
1798 close $authors or croak $!;
1801 # convert GetOpt::Long specs for use by git-config
1802 sub read_git_config {
1803 my $opts = shift;
1804 my @config_only;
1805 foreach my $o (keys %$opts) {
1806 # if we have mixedCase and a long option-only, then
1807 # it's a config-only variable that we don't need for
1808 # the command-line.
1809 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1810 my $v = $opts->{$o};
1811 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1812 $key =~ s/-//g;
1813 my $arg = 'git config';
1814 $arg .= ' --int' if ($o =~ /[:=]i$/);
1815 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1816 if (ref $v eq 'ARRAY') {
1817 chomp(my @tmp = `$arg --get-all svn.$key`);
1818 @$v = @tmp if @tmp;
1819 } else {
1820 chomp(my $tmp = `$arg --get svn.$key`);
1821 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1822 $$v = $tmp;
1826 delete @$opts{@config_only} if @config_only;
1829 sub extract_metadata {
1830 my $id = shift or return (undef, undef, undef);
1831 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1832 \s([a-f\d\-]+)$/ix);
1833 if (!defined $rev || !$uuid || !$url) {
1834 # some of the original repositories I made had
1835 # identifiers like this:
1836 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/i);
1838 return ($url, $rev, $uuid);
1841 sub cmt_metadata {
1842 return extract_metadata((grep(/^git-svn-id: /,
1843 command(qw/cat-file commit/, shift)))[-1]);
1846 sub cmt_sha2rev_batch {
1847 my %s2r;
1848 my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1849 my $list = shift;
1851 foreach my $sha (@{$list}) {
1852 my $first = 1;
1853 my $size = 0;
1854 print $out $sha, "\n";
1856 while (my $line = <$in>) {
1857 if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1858 last;
1859 } elsif ($first &&
1860 $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1861 $first = 0;
1862 $size = $1;
1863 next;
1864 } elsif ($line =~ /^(git-svn-id: )/) {
1865 my (undef, $rev, undef) =
1866 extract_metadata($line);
1867 $s2r{$sha} = $rev;
1870 $size -= length($line);
1871 last if ($size == 0);
1875 command_close_bidi_pipe($pid, $in, $out, $ctx);
1877 return \%s2r;
1880 sub working_head_info {
1881 my ($head, $refs) = @_;
1882 my @args = qw/log --no-color --no-decorate --first-parent
1883 --pretty=medium/;
1884 my ($fh, $ctx) = command_output_pipe(@args, $head);
1885 my $hash;
1886 my %max;
1887 while (<$fh>) {
1888 if ( m{^commit ($::sha1)$} ) {
1889 unshift @$refs, $hash if $hash and $refs;
1890 $hash = $1;
1891 next;
1893 next unless s{^\s*(git-svn-id:)}{$1};
1894 my ($url, $rev, $uuid) = extract_metadata($_);
1895 if (defined $url && defined $rev) {
1896 next if $max{$url} and $max{$url} < $rev;
1897 if (my $gs = Git::SVN->find_by_url($url)) {
1898 my $c = $gs->rev_map_get($rev, $uuid);
1899 if ($c && $c eq $hash) {
1900 close $fh; # break the pipe
1901 return ($url, $rev, $uuid, $gs);
1902 } else {
1903 $max{$url} ||= $gs->rev_map_max;
1908 command_close_pipe($fh, $ctx);
1909 (undef, undef, undef, undef);
1912 sub read_commit_parents {
1913 my ($parents, $c) = @_;
1914 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1915 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1916 @{$parents->{$c}} = split(/ /, $p);
1919 sub linearize_history {
1920 my ($gs, $refs) = @_;
1921 my %parents;
1922 foreach my $c (@$refs) {
1923 read_commit_parents(\%parents, $c);
1926 my @linear_refs;
1927 my %skip = ();
1928 my $last_svn_commit = $gs->last_commit;
1929 foreach my $c (reverse @$refs) {
1930 next if $c eq $last_svn_commit;
1931 last if $skip{$c};
1933 unshift @linear_refs, $c;
1934 $skip{$c} = 1;
1936 # we only want the first parent to diff against for linear
1937 # history, we save the rest to inject when we finalize the
1938 # svn commit
1939 my $fp_a = verify_ref("$c~1");
1940 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1941 if (!$fp_a || !$fp_b) {
1942 die "Commit $c\n",
1943 "has no parent commit, and therefore ",
1944 "nothing to diff against.\n",
1945 "You should be working from a repository ",
1946 "originally created by git-svn\n";
1948 if ($fp_a ne $fp_b) {
1949 die "$c~1 = $fp_a, however parsing commit $c ",
1950 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1953 foreach my $p (@{$parents{$c}}) {
1954 $skip{$p} = 1;
1957 (\@linear_refs, \%parents);
1960 sub find_file_type_and_diff_status {
1961 my ($path) = @_;
1962 return ('dir', '') if $path eq '';
1964 my $diff_output =
1965 command_oneline(qw(diff --cached --name-status --), $path) || "";
1966 my $diff_status = (split(' ', $diff_output))[0] || "";
1968 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1970 return (undef, undef) if !$diff_status && !$ls_tree;
1972 if ($diff_status eq "A") {
1973 return ("link", $diff_status) if -l $path;
1974 return ("dir", $diff_status) if -d $path;
1975 return ("file", $diff_status);
1978 my $mode = (split(' ', $ls_tree))[0] || "";
1980 return ("link", $diff_status) if $mode eq "120000";
1981 return ("dir", $diff_status) if $mode eq "040000";
1982 return ("file", $diff_status);
1985 sub md5sum {
1986 my $arg = shift;
1987 my $ref = ref $arg;
1988 my $md5 = Digest::MD5->new();
1989 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
1990 $md5->addfile($arg) or croak $!;
1991 } elsif ($ref eq 'SCALAR') {
1992 $md5->add($$arg) or croak $!;
1993 } elsif (!$ref) {
1994 $md5->add($arg) or croak $!;
1995 } else {
1996 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1998 return $md5->hexdigest();
2001 sub gc_directory {
2002 if ($can_compress && -f $_ && basename($_) eq "unhandled.log") {
2003 my $out_filename = $_ . ".gz";
2004 open my $in_fh, "<", $_ or die "Unable to open $_: $!\n";
2005 binmode $in_fh;
2006 my $gz = Compress::Zlib::gzopen($out_filename, "ab") or
2007 die "Unable to open $out_filename: $!\n";
2009 my $res;
2010 while ($res = sysread($in_fh, my $str, 1024)) {
2011 $gz->gzwrite($str) or
2012 die "Unable to write: ".$gz->gzerror()."!\n";
2014 unlink $_ or die "unlink $File::Find::name: $!\n";
2015 } elsif (-f $_ && basename($_) eq "index") {
2016 unlink $_ or die "unlink $_: $!\n";
2020 package Git::SVN;
2021 use strict;
2022 use warnings;
2023 use Fcntl qw/:DEFAULT :seek/;
2024 use constant rev_map_fmt => 'NH40';
2025 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
2026 $_repack $_repack_flags $_use_svm_props $_head
2027 $_use_svnsync_props $no_reuse_existing $_minimize_url
2028 $_use_log_author $_add_author_from $_localtime/;
2029 use Carp qw/croak/;
2030 use File::Path qw/mkpath/;
2031 use File::Copy qw/copy/;
2032 use IPC::Open3;
2033 use Memoize; # core since 5.8.0, Jul 2002
2034 use Memoize::Storable;
2036 my ($_gc_nr, $_gc_period);
2038 # properties that we do not log:
2039 my %SKIP_PROP;
2040 BEGIN {
2041 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
2042 svn:special svn:executable
2043 svn:entry:committed-rev
2044 svn:entry:last-author
2045 svn:entry:uuid
2046 svn:entry:committed-date/;
2048 # some options are read globally, but can be overridden locally
2049 # per [svn-remote "..."] section. Command-line options will *NOT*
2050 # override options set in an [svn-remote "..."] section
2051 no strict 'refs';
2052 for my $option (qw/follow_parent no_metadata use_svm_props
2053 use_svnsync_props/) {
2054 my $key = $option;
2055 $key =~ tr/_//d;
2056 my $prop = "-$option";
2057 *$option = sub {
2058 my ($self) = @_;
2059 return $self->{$prop} if exists $self->{$prop};
2060 my $k = "svn-remote.$self->{repo_id}.$key";
2061 eval { command_oneline(qw/config --get/, $k) };
2062 if ($@) {
2063 $self->{$prop} = ${"Git::SVN::_$option"};
2064 } else {
2065 my $v = command_oneline(qw/config --bool/,$k);
2066 $self->{$prop} = $v eq 'false' ? 0 : 1;
2068 return $self->{$prop};
2074 my (%LOCKFILES, %INDEX_FILES);
2075 END {
2076 unlink keys %LOCKFILES if %LOCKFILES;
2077 unlink keys %INDEX_FILES if %INDEX_FILES;
2080 sub resolve_local_globs {
2081 my ($url, $fetch, $glob_spec) = @_;
2082 return unless defined $glob_spec;
2083 my $ref = $glob_spec->{ref};
2084 my $path = $glob_spec->{path};
2085 foreach (command(qw#for-each-ref --format=%(refname) refs/#)) {
2086 next unless m#^$ref->{regex}$#;
2087 my $p = $1;
2088 my $pathname = desanitize_refname($path->full_path($p));
2089 my $refname = desanitize_refname($ref->full_path($p));
2090 if (my $existing = $fetch->{$pathname}) {
2091 if ($existing ne $refname) {
2092 die "Refspec conflict:\n",
2093 "existing: $existing\n",
2094 " globbed: $refname\n";
2096 my $u = (::cmt_metadata("$refname"))[0];
2097 $u =~ s!^\Q$url\E(/|$)!! or die
2098 "$refname: '$url' not found in '$u'\n";
2099 if ($pathname ne $u) {
2100 warn "W: Refspec glob conflict ",
2101 "(ref: $refname):\n",
2102 "expected path: $pathname\n",
2103 " real path: $u\n",
2104 "Continuing ahead with $u\n";
2105 next;
2107 } else {
2108 $fetch->{$pathname} = $refname;
2113 sub parse_revision_argument {
2114 my ($base, $head) = @_;
2115 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
2116 return ($base, $head);
2118 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
2119 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
2120 return ($head, $head) if ($::_revision eq 'HEAD');
2121 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
2122 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
2123 die "revision argument: $::_revision not understood by git-svn\n";
2126 sub fetch_all {
2127 my ($repo_id, $remotes) = @_;
2128 if (ref $repo_id) {
2129 my $gs = $repo_id;
2130 $repo_id = undef;
2131 $repo_id = $gs->{repo_id};
2133 $remotes ||= read_all_remotes();
2134 my $remote = $remotes->{$repo_id} or
2135 die "[svn-remote \"$repo_id\"] unknown\n";
2136 my $fetch = $remote->{fetch};
2137 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
2138 my (@gs, @globs);
2139 my $ra = Git::SVN::Ra->new($url);
2140 my $uuid = $ra->get_uuid;
2141 my $head = $ra->get_latest_revnum;
2143 # ignore errors, $head revision may not even exist anymore
2144 eval { $ra->get_log("", $head, 0, 1, 0, 1, sub { $head = $_[1] }) };
2145 warn "W: $@\n" if $@;
2147 my $base = defined $fetch ? $head : 0;
2149 # read the max revs for wildcard expansion (branches/*, tags/*)
2150 foreach my $t (qw/branches tags/) {
2151 defined $remote->{$t} or next;
2152 push @globs, @{$remote->{$t}};
2154 my $max_rev = eval { tmp_config(qw/--int --get/,
2155 "svn-remote.$repo_id.${t}-maxRev") };
2156 if (defined $max_rev && ($max_rev < $base)) {
2157 $base = $max_rev;
2158 } elsif (!defined $max_rev) {
2159 $base = 0;
2163 if ($fetch) {
2164 foreach my $p (sort keys %$fetch) {
2165 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
2166 my $lr = $gs->rev_map_max;
2167 if (defined $lr) {
2168 $base = $lr if ($lr < $base);
2170 push @gs, $gs;
2174 ($base, $head) = parse_revision_argument($base, $head);
2175 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
2178 sub read_all_remotes {
2179 my $r = {};
2180 my $use_svm_props = eval { command_oneline(qw/config --bool
2181 svn.useSvmProps/) };
2182 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
2183 my $svn_refspec = qr{\s*(.*?)\s*:\s*(.+?)\s*};
2184 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
2185 if (m!^(.+)\.fetch=$svn_refspec$!) {
2186 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
2187 die("svn-remote.$remote: remote ref '$remote_ref' "
2188 . "must start with 'refs/'\n")
2189 unless $remote_ref =~ m{^refs/};
2190 $local_ref = uri_decode($local_ref);
2191 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
2192 $r->{$remote}->{svm} = {} if $use_svm_props;
2193 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
2194 $r->{$1}->{svm} = {};
2195 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
2196 $r->{$1}->{url} = $2;
2197 } elsif (m!^(.+)\.pushurl=\s*(.*)\s*$!) {
2198 $r->{$1}->{pushurl} = $2;
2199 } elsif (m!^(.+)\.ignore-refs=\s*(.*)\s*$!) {
2200 $r->{$1}->{ignore_refs_regex} = $2;
2201 } elsif (m!^(.+)\.(branches|tags)=$svn_refspec$!) {
2202 my ($remote, $t, $local_ref, $remote_ref) =
2203 ($1, $2, $3, $4);
2204 die("svn-remote.$remote: remote ref '$remote_ref' ($t) "
2205 . "must start with 'refs/'\n")
2206 unless $remote_ref =~ m{^refs/};
2207 $local_ref = uri_decode($local_ref);
2208 my $rs = {
2209 t => $t,
2210 remote => $remote,
2211 path => Git::SVN::GlobSpec->new($local_ref, 1),
2212 ref => Git::SVN::GlobSpec->new($remote_ref, 0) };
2213 if (length($rs->{ref}->{right}) != 0) {
2214 die "The '*' glob character must be the last ",
2215 "character of '$remote_ref'\n";
2217 push @{ $r->{$remote}->{$t} }, $rs;
2221 map {
2222 if (defined $r->{$_}->{svm}) {
2223 my $svm;
2224 eval {
2225 my $section = "svn-remote.$_";
2226 $svm = {
2227 source => tmp_config('--get',
2228 "$section.svm-source"),
2229 replace => tmp_config('--get',
2230 "$section.svm-replace"),
2233 $r->{$_}->{svm} = $svm;
2235 } keys %$r;
2237 foreach my $remote (keys %$r) {
2238 foreach ( grep { defined $_ }
2239 map { $r->{$remote}->{$_} } qw(branches tags) ) {
2240 foreach my $rs ( @$_ ) {
2241 $rs->{ignore_refs_regex} =
2242 $r->{$remote}->{ignore_refs_regex};
2250 sub init_vars {
2251 $_gc_nr = $_gc_period = 1000;
2252 if (defined $_repack || defined $_repack_flags) {
2253 warn "Repack options are obsolete; they have no effect.\n";
2257 sub verify_remotes_sanity {
2258 return unless -d $ENV{GIT_DIR};
2259 my %seen;
2260 foreach (command(qw/config -l/)) {
2261 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
2262 if ($seen{$1}) {
2263 die "Remote ref refs/remote/$1 is tracked by",
2264 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
2265 "Please resolve this ambiguity in ",
2266 "your git configuration file before ",
2267 "continuing\n";
2269 $seen{$1} = $_;
2274 sub find_existing_remote {
2275 my ($url, $remotes) = @_;
2276 return undef if $no_reuse_existing;
2277 my $existing;
2278 foreach my $repo_id (keys %$remotes) {
2279 my $u = $remotes->{$repo_id}->{url} or next;
2280 next if $u ne $url;
2281 $existing = $repo_id;
2282 last;
2284 $existing;
2287 sub init_remote_config {
2288 my ($self, $url, $no_write) = @_;
2289 $url =~ s!/+$!!; # strip trailing slash
2290 my $r = read_all_remotes();
2291 my $existing = find_existing_remote($url, $r);
2292 if ($existing) {
2293 unless ($no_write) {
2294 print STDERR "Using existing ",
2295 "[svn-remote \"$existing\"]\n";
2297 $self->{repo_id} = $existing;
2298 } elsif ($_minimize_url) {
2299 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
2300 $existing = find_existing_remote($min_url, $r);
2301 if ($existing) {
2302 unless ($no_write) {
2303 print STDERR "Using existing ",
2304 "[svn-remote \"$existing\"]\n";
2306 $self->{repo_id} = $existing;
2308 if ($min_url ne $url) {
2309 unless ($no_write) {
2310 print STDERR "Using higher level of URL: ",
2311 "$url => $min_url\n";
2313 my $old_path = $self->{path};
2314 $self->{path} = $url;
2315 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
2316 if (length $old_path) {
2317 $self->{path} .= "/$old_path";
2319 $url = $min_url;
2322 my $orig_url;
2323 if (!$existing) {
2324 # verify that we aren't overwriting anything:
2325 $orig_url = eval {
2326 command_oneline('config', '--get',
2327 "svn-remote.$self->{repo_id}.url")
2329 if ($orig_url && ($orig_url ne $url)) {
2330 die "svn-remote.$self->{repo_id}.url already set: ",
2331 "$orig_url\nwanted to set to: $url\n";
2334 my ($xrepo_id, $xpath) = find_ref($self->refname);
2335 if (!$no_write && defined $xpath) {
2336 die "svn-remote.$xrepo_id.fetch already set to track ",
2337 "$xpath:", $self->refname, "\n";
2339 unless ($no_write) {
2340 command_noisy('config',
2341 "svn-remote.$self->{repo_id}.url", $url);
2342 $self->{path} =~ s{^/}{};
2343 $self->{path} =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
2344 command_noisy('config', '--add',
2345 "svn-remote.$self->{repo_id}.fetch",
2346 "$self->{path}:".$self->refname);
2348 $self->{url} = $url;
2351 sub find_by_url { # repos_root and, path are optional
2352 my ($class, $full_url, $repos_root, $path) = @_;
2354 return undef unless defined $full_url;
2355 remove_username($full_url);
2356 remove_username($repos_root) if defined $repos_root;
2357 my $remotes = read_all_remotes();
2358 if (defined $full_url && defined $repos_root && !defined $path) {
2359 $path = $full_url;
2360 $path =~ s#^\Q$repos_root\E(?:/|$)##;
2362 foreach my $repo_id (keys %$remotes) {
2363 my $u = $remotes->{$repo_id}->{url} or next;
2364 remove_username($u);
2365 next if defined $repos_root && $repos_root ne $u;
2367 my $fetch = $remotes->{$repo_id}->{fetch} || {};
2368 foreach my $t (qw/branches tags/) {
2369 foreach my $globspec (@{$remotes->{$repo_id}->{$t}}) {
2370 resolve_local_globs($u, $fetch, $globspec);
2373 my $p = $path;
2374 my $rwr = rewrite_root({repo_id => $repo_id});
2375 my $svm = $remotes->{$repo_id}->{svm}
2376 if defined $remotes->{$repo_id}->{svm};
2377 unless (defined $p) {
2378 $p = $full_url;
2379 my $z = $u;
2380 my $prefix = '';
2381 if ($rwr) {
2382 $z = $rwr;
2383 remove_username($z);
2384 } elsif (defined $svm) {
2385 $z = $svm->{source};
2386 $prefix = $svm->{replace};
2387 $prefix =~ s#^\Q$u\E(?:/|$)##;
2388 $prefix =~ s#/$##;
2390 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
2392 foreach my $f (keys %$fetch) {
2393 next if $f ne $p;
2394 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
2397 undef;
2400 sub init {
2401 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
2402 my $self = _new($class, $repo_id, $ref_id, $path);
2403 if (defined $url) {
2404 $self->init_remote_config($url, $no_write);
2406 $self;
2409 sub find_ref {
2410 my ($ref_id) = @_;
2411 foreach (command(qw/config -l/)) {
2412 next unless m!^svn-remote\.(.+)\.fetch=
2413 \s*(.*?)\s*:\s*(.+?)\s*$!x;
2414 my ($repo_id, $path, $ref) = ($1, $2, $3);
2415 if ($ref eq $ref_id) {
2416 $path = '' if ($path =~ m#^\./?#);
2417 return ($repo_id, $path);
2420 (undef, undef, undef);
2423 sub new {
2424 my ($class, $ref_id, $repo_id, $path) = @_;
2425 if (defined $ref_id && !defined $repo_id && !defined $path) {
2426 ($repo_id, $path) = find_ref($ref_id);
2427 if (!defined $repo_id) {
2428 die "Could not find a \"svn-remote.*.fetch\" key ",
2429 "in the repository configuration matching: ",
2430 "$ref_id\n";
2433 my $self = _new($class, $repo_id, $ref_id, $path);
2434 if (!defined $self->{path} || !length $self->{path}) {
2435 my $fetch = command_oneline('config', '--get',
2436 "svn-remote.$repo_id.fetch",
2437 ":$ref_id\$") or
2438 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
2439 "\":$ref_id\$\" in config\n";
2440 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
2442 $self->{path} =~ s{/+}{/}g;
2443 $self->{path} =~ s{\A/}{};
2444 $self->{path} =~ s{/\z}{};
2445 $self->{url} = command_oneline('config', '--get',
2446 "svn-remote.$repo_id.url") or
2447 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
2448 $self->{pushurl} = eval { command_oneline('config', '--get',
2449 "svn-remote.$repo_id.pushurl") };
2450 $self->rebuild;
2451 $self;
2454 sub refname {
2455 my ($refname) = $_[0]->{ref_id} ;
2457 # It cannot end with a slash /, we'll throw up on this because
2458 # SVN can't have directories with a slash in their name, either:
2459 if ($refname =~ m{/$}) {
2460 die "ref: '$refname' ends with a trailing slash, this is ",
2461 "not permitted by git nor Subversion\n";
2464 # It cannot have ASCII control character space, tilde ~, caret ^,
2465 # colon :, question-mark ?, asterisk *, space, or open bracket [
2466 # anywhere.
2468 # Additionally, % must be escaped because it is used for escaping
2469 # and we want our escaped refname to be reversible
2470 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
2472 # no slash-separated component can begin with a dot .
2473 # /.* becomes /%2E*
2474 $refname =~ s{/\.}{/%2E}g;
2476 # It cannot have two consecutive dots .. anywhere
2477 # .. becomes %2E%2E
2478 $refname =~ s{\.\.}{%2E%2E}g;
2480 # trailing dots and .lock are not allowed
2481 # .$ becomes %2E and .lock becomes %2Elock
2482 $refname =~ s{\.(?=$|lock$)}{%2E};
2484 # the sequence @{ is used to access the reflog
2485 # @{ becomes %40{
2486 $refname =~ s{\@\{}{%40\{}g;
2488 return $refname;
2491 sub desanitize_refname {
2492 my ($refname) = @_;
2493 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
2494 return $refname;
2497 sub svm_uuid {
2498 my ($self) = @_;
2499 return $self->{svm}->{uuid} if $self->svm;
2500 $self->ra;
2501 unless ($self->{svm}) {
2502 die "SVM UUID not cached, and reading remotely failed\n";
2504 $self->{svm}->{uuid};
2507 sub svm {
2508 my ($self) = @_;
2509 return $self->{svm} if $self->{svm};
2510 my $svm;
2511 # see if we have it in our config, first:
2512 eval {
2513 my $section = "svn-remote.$self->{repo_id}";
2514 $svm = {
2515 source => tmp_config('--get', "$section.svm-source"),
2516 uuid => tmp_config('--get', "$section.svm-uuid"),
2517 replace => tmp_config('--get', "$section.svm-replace"),
2520 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
2521 $self->{svm} = $svm;
2523 $self->{svm};
2526 sub _set_svm_vars {
2527 my ($self, $ra) = @_;
2528 return $ra if $self->svm;
2530 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
2531 "(svm:source, svm:uuid) ",
2532 "from the following URLs:\n" );
2533 sub read_svm_props {
2534 my ($self, $ra, $path, $r) = @_;
2535 my $props = ($ra->get_dir($path, $r))[2];
2536 my $src = $props->{'svm:source'};
2537 my $uuid = $props->{'svm:uuid'};
2538 return undef if (!$src || !$uuid);
2540 chomp($src, $uuid);
2542 $uuid =~ m{^[0-9a-f\-]{30,}$}i
2543 or die "doesn't look right - svm:uuid is '$uuid'\n";
2545 # the '!' is used to mark the repos_root!/relative/path
2546 $src =~ s{/?!/?}{/};
2547 $src =~ s{/+$}{}; # no trailing slashes please
2548 # username is of no interest
2549 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
2551 my $replace = $ra->{url};
2552 $replace .= "/$path" if length $path;
2554 my $section = "svn-remote.$self->{repo_id}";
2555 tmp_config("$section.svm-source", $src);
2556 tmp_config("$section.svm-replace", $replace);
2557 tmp_config("$section.svm-uuid", $uuid);
2558 $self->{svm} = {
2559 source => $src,
2560 uuid => $uuid,
2561 replace => $replace
2565 my $r = $ra->get_latest_revnum;
2566 my $path = $self->{path};
2567 my %tried;
2568 while (length $path) {
2569 unless ($tried{"$self->{url}/$path"}) {
2570 return $ra if $self->read_svm_props($ra, $path, $r);
2571 $tried{"$self->{url}/$path"} = 1;
2573 $path =~ s#/?[^/]+$##;
2575 die "Path: '$path' should be ''\n" if $path ne '';
2576 return $ra if $self->read_svm_props($ra, $path, $r);
2577 $tried{"$self->{url}/$path"} = 1;
2579 if ($ra->{repos_root} eq $self->{url}) {
2580 die @err, (map { " $_\n" } keys %tried), "\n";
2583 # nope, make sure we're connected to the repository root:
2584 my $ok;
2585 my @tried_b;
2586 $path = $ra->{svn_path};
2587 $ra = Git::SVN::Ra->new($ra->{repos_root});
2588 while (length $path) {
2589 unless ($tried{"$ra->{url}/$path"}) {
2590 $ok = $self->read_svm_props($ra, $path, $r);
2591 last if $ok;
2592 $tried{"$ra->{url}/$path"} = 1;
2594 $path =~ s#/?[^/]+$##;
2596 die "Path: '$path' should be ''\n" if $path ne '';
2597 $ok ||= $self->read_svm_props($ra, $path, $r);
2598 $tried{"$ra->{url}/$path"} = 1;
2599 if (!$ok) {
2600 die @err, (map { " $_\n" } keys %tried), "\n";
2602 Git::SVN::Ra->new($self->{url});
2605 sub svnsync {
2606 my ($self) = @_;
2607 return $self->{svnsync} if $self->{svnsync};
2609 if ($self->no_metadata) {
2610 die "Can't have both 'noMetadata' and ",
2611 "'useSvnsyncProps' options set!\n";
2613 if ($self->rewrite_root) {
2614 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
2615 "options set!\n";
2617 if ($self->rewrite_uuid) {
2618 die "Can't have both 'useSvnsyncProps' and 'rewriteUUID' ",
2619 "options set!\n";
2622 my $svnsync;
2623 # see if we have it in our config, first:
2624 eval {
2625 my $section = "svn-remote.$self->{repo_id}";
2627 my $url = tmp_config('--get', "$section.svnsync-url");
2628 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2629 die "doesn't look right - svn:sync-from-url is '$url'\n";
2631 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
2632 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2633 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2635 $svnsync = { url => $url, uuid => $uuid }
2637 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
2638 return $self->{svnsync} = $svnsync;
2641 my $err = "useSvnsyncProps set, but failed to read " .
2642 "svnsync property: svn:sync-from-";
2643 my $rp = $self->ra->rev_proplist(0);
2645 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
2646 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2647 die "doesn't look right - svn:sync-from-url is '$url'\n";
2649 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
2650 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2651 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2653 my $section = "svn-remote.$self->{repo_id}";
2654 tmp_config('--add', "$section.svnsync-uuid", $uuid);
2655 tmp_config('--add', "$section.svnsync-url", $url);
2656 return $self->{svnsync} = { url => $url, uuid => $uuid };
2659 # this allows us to memoize our SVN::Ra UUID locally and avoid a
2660 # remote lookup (useful for 'git svn log').
2661 sub ra_uuid {
2662 my ($self) = @_;
2663 unless ($self->{ra_uuid}) {
2664 my $key = "svn-remote.$self->{repo_id}.uuid";
2665 my $uuid = eval { tmp_config('--get', $key) };
2666 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/i) {
2667 $self->{ra_uuid} = $uuid;
2668 } else {
2669 die "ra_uuid called without URL\n" unless $self->{url};
2670 $self->{ra_uuid} = $self->ra->get_uuid;
2671 tmp_config('--add', $key, $self->{ra_uuid});
2674 $self->{ra_uuid};
2677 sub _set_repos_root {
2678 my ($self, $repos_root) = @_;
2679 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2680 $repos_root ||= $self->ra->{repos_root};
2681 tmp_config($k, $repos_root);
2682 $repos_root;
2685 sub repos_root {
2686 my ($self) = @_;
2687 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2688 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
2691 sub ra {
2692 my ($self) = shift;
2693 my $ra = Git::SVN::Ra->new($self->{url});
2694 $self->_set_repos_root($ra->{repos_root});
2695 if ($self->use_svm_props && !$self->{svm}) {
2696 if ($self->no_metadata) {
2697 die "Can't have both 'noMetadata' and ",
2698 "'useSvmProps' options set!\n";
2699 } elsif ($self->use_svnsync_props) {
2700 die "Can't have both 'useSvnsyncProps' and ",
2701 "'useSvmProps' options set!\n";
2703 $ra = $self->_set_svm_vars($ra);
2704 $self->{-want_revprops} = 1;
2706 $ra;
2709 # prop_walk(PATH, REV, SUB)
2710 # -------------------------
2711 # Recursively traverse PATH at revision REV and invoke SUB for each
2712 # directory that contains a SVN property. SUB will be invoked as
2713 # follows: &SUB(gs, path, props); where `gs' is this instance of
2714 # Git::SVN, `path' the path to the directory where the properties
2715 # `props' were found. The `path' will be relative to point of checkout,
2716 # that is, if url://repo/trunk is the current Git branch, and that
2717 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
2718 # as `path' (note the trailing `/').
2719 sub prop_walk {
2720 my ($self, $path, $rev, $sub) = @_;
2722 $path =~ s#^/##;
2723 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2724 $path =~ s#^/*#/#g;
2725 my $p = $path;
2726 # Strip the irrelevant part of the path.
2727 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2728 # Ensure the path is terminated by a `/'.
2729 $p =~ s#/*$#/#;
2731 # The properties contain all the internal SVN stuff nobody
2732 # (usually) cares about.
2733 my $interesting_props = 0;
2734 foreach (keys %{$props}) {
2735 # If it doesn't start with `svn:', it must be a
2736 # user-defined property.
2737 ++$interesting_props and next if $_ !~ /^svn:/;
2738 # FIXME: Fragile, if SVN adds new public properties,
2739 # this needs to be updated.
2740 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2741 |eol-style|mime-type
2742 |externals|needs-lock)$/x;
2744 &$sub($self, $p, $props) if $interesting_props;
2746 foreach (sort keys %$dirent) {
2747 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
2748 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
2752 sub last_rev { ($_[0]->last_rev_commit)[0] }
2753 sub last_commit { ($_[0]->last_rev_commit)[1] }
2755 # returns the newest SVN revision number and newest commit SHA1
2756 sub last_rev_commit {
2757 my ($self) = @_;
2758 if (defined $self->{last_rev} && defined $self->{last_commit}) {
2759 return ($self->{last_rev}, $self->{last_commit});
2761 my $c = ::verify_ref($self->refname.'^0');
2762 if ($c && !$self->use_svm_props && !$self->no_metadata) {
2763 my $rev = (::cmt_metadata($c))[1];
2764 if (defined $rev) {
2765 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2766 return ($rev, $c);
2769 my $map_path = $self->map_path;
2770 unless (-e $map_path) {
2771 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2772 return (undef, undef);
2774 my ($rev, $commit) = $self->rev_map_max(1);
2775 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2776 return ($rev, $commit);
2779 sub get_fetch_range {
2780 my ($self, $min, $max) = @_;
2781 $max ||= $self->ra->get_latest_revnum;
2782 $min ||= $self->rev_map_max;
2783 (++$min, $max);
2786 sub tmp_config {
2787 my (@args) = @_;
2788 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2789 my $config = "$ENV{GIT_DIR}/svn/.metadata";
2790 if (! -f $config && -f $old_def_config) {
2791 rename $old_def_config, $config or
2792 die "Failed rename $old_def_config => $config: $!\n";
2794 my $old_config = $ENV{GIT_CONFIG};
2795 $ENV{GIT_CONFIG} = $config;
2796 $@ = undef;
2797 my @ret = eval {
2798 unless (-f $config) {
2799 mkfile($config);
2800 open my $fh, '>', $config or
2801 die "Can't open $config: $!\n";
2802 print $fh "; This file is used internally by ",
2803 "git-svn\n" or die
2804 "Couldn't write to $config: $!\n";
2805 print $fh "; You should not have to edit it\n" or
2806 die "Couldn't write to $config: $!\n";
2807 close $fh or die "Couldn't close $config: $!\n";
2809 command('config', @args);
2811 my $err = $@;
2812 if (defined $old_config) {
2813 $ENV{GIT_CONFIG} = $old_config;
2814 } else {
2815 delete $ENV{GIT_CONFIG};
2817 die $err if $err;
2818 wantarray ? @ret : $ret[0];
2821 sub tmp_index_do {
2822 my ($self, $sub) = @_;
2823 my $old_index = $ENV{GIT_INDEX_FILE};
2824 $ENV{GIT_INDEX_FILE} = $self->{index};
2825 $@ = undef;
2826 my @ret = eval {
2827 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2828 mkpath([$dir]) unless -d $dir;
2829 &$sub;
2831 my $err = $@;
2832 if (defined $old_index) {
2833 $ENV{GIT_INDEX_FILE} = $old_index;
2834 } else {
2835 delete $ENV{GIT_INDEX_FILE};
2837 die $err if $err;
2838 wantarray ? @ret : $ret[0];
2841 sub assert_index_clean {
2842 my ($self, $treeish) = @_;
2844 $self->tmp_index_do(sub {
2845 command_noisy('read-tree', $treeish) unless -e $self->{index};
2846 my $x = command_oneline('write-tree');
2847 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2848 /^tree ($::sha1)/mo);
2849 return if $y eq $x;
2851 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2852 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2853 command_noisy('read-tree', $treeish);
2854 $x = command_oneline('write-tree');
2855 if ($y ne $x) {
2856 ::fatal "trees ($treeish) $y != $x\n",
2857 "Something is seriously wrong...";
2862 sub get_commit_parents {
2863 my ($self, $log_entry) = @_;
2864 my (%seen, @ret, @tmp);
2865 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2866 if (my $ip = $self->{inject_parents}) {
2867 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2868 push @tmp, $commit;
2871 if (my $cur = ::verify_ref($self->refname.'^0')) {
2872 push @tmp, $cur;
2874 if (my $ipd = $self->{inject_parents_dcommit}) {
2875 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2876 push @tmp, @$commit;
2879 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2880 while (my $p = shift @tmp) {
2881 next if $seen{$p};
2882 $seen{$p} = 1;
2883 push @ret, $p;
2885 @ret;
2888 sub rewrite_root {
2889 my ($self) = @_;
2890 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2891 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2892 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2893 if ($rwr) {
2894 $rwr =~ s#/+$##;
2895 if ($rwr !~ m#^[a-z\+]+://#) {
2896 die "$rwr is not a valid URL (key: $k)\n";
2899 $self->{-rewrite_root} = $rwr;
2902 sub rewrite_uuid {
2903 my ($self) = @_;
2904 return $self->{-rewrite_uuid} if exists $self->{-rewrite_uuid};
2905 my $k = "svn-remote.$self->{repo_id}.rewriteUUID";
2906 my $rwid = eval { command_oneline(qw/config --get/, $k) };
2907 if ($rwid) {
2908 $rwid =~ s#/+$##;
2909 if ($rwid !~ m#^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$#) {
2910 die "$rwid is not a valid UUID (key: $k)\n";
2913 $self->{-rewrite_uuid} = $rwid;
2916 sub metadata_url {
2917 my ($self) = @_;
2918 ($self->rewrite_root || $self->{url}) .
2919 (length $self->{path} ? '/' . $self->{path} : '');
2922 sub full_url {
2923 my ($self) = @_;
2924 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2927 sub full_pushurl {
2928 my ($self) = @_;
2929 if ($self->{pushurl}) {
2930 return $self->{pushurl} . (length $self->{path} ? '/' .
2931 $self->{path} : '');
2932 } else {
2933 return $self->full_url;
2937 sub set_commit_header_env {
2938 my ($log_entry) = @_;
2939 my %env;
2940 foreach my $ned (qw/NAME EMAIL DATE/) {
2941 foreach my $ac (qw/AUTHOR COMMITTER/) {
2942 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2946 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2947 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2948 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2950 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2951 ? $log_entry->{commit_name}
2952 : $log_entry->{name};
2953 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2954 ? $log_entry->{commit_email}
2955 : $log_entry->{email};
2956 \%env;
2959 sub restore_commit_header_env {
2960 my ($env) = @_;
2961 foreach my $ned (qw/NAME EMAIL DATE/) {
2962 foreach my $ac (qw/AUTHOR COMMITTER/) {
2963 my $k = "GIT_${ac}_${ned}";
2964 if (defined $env->{$k}) {
2965 $ENV{$k} = $env->{$k};
2966 } else {
2967 delete $ENV{$k};
2973 sub gc {
2974 command_noisy('gc', '--auto');
2977 sub do_git_commit {
2978 my ($self, $log_entry) = @_;
2979 my $lr = $self->last_rev;
2980 if (defined $lr && $lr >= $log_entry->{revision}) {
2981 die "Last fetched revision of ", $self->refname,
2982 " was r$lr, but we are about to fetch: ",
2983 "r$log_entry->{revision}!\n";
2985 if (my $c = $self->rev_map_get($log_entry->{revision})) {
2986 croak "$log_entry->{revision} = $c already exists! ",
2987 "Why are we refetching it?\n";
2989 my $old_env = set_commit_header_env($log_entry);
2990 my $tree = $log_entry->{tree};
2991 if (!defined $tree) {
2992 $tree = $self->tmp_index_do(sub {
2993 command_oneline('write-tree') });
2995 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2997 my @exec = ('git', 'commit-tree', $tree);
2998 foreach ($self->get_commit_parents($log_entry)) {
2999 push @exec, '-p', $_;
3001 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
3002 or croak $!;
3003 binmode $msg_fh;
3005 # we always get UTF-8 from SVN, but we may want our commits in
3006 # a different encoding.
3007 if (my $enc = Git::config('i18n.commitencoding')) {
3008 require Encode;
3009 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
3011 print $msg_fh $log_entry->{log} or croak $!;
3012 restore_commit_header_env($old_env);
3013 unless ($self->no_metadata) {
3014 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
3015 or croak $!;
3017 $msg_fh->flush == 0 or croak $!;
3018 close $msg_fh or croak $!;
3019 chomp(my $commit = do { local $/; <$out_fh> });
3020 close $out_fh or croak $!;
3021 waitpid $pid, 0;
3022 croak $? if $?;
3023 if ($commit !~ /^$::sha1$/o) {
3024 die "Failed to commit, invalid sha1: $commit\n";
3027 $self->rev_map_set($log_entry->{revision}, $commit, 1);
3029 $self->{last_rev} = $log_entry->{revision};
3030 $self->{last_commit} = $commit;
3031 print "r$log_entry->{revision}" unless $::_q > 1;
3032 if (defined $log_entry->{svm_revision}) {
3033 print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
3034 $self->rev_map_set($log_entry->{svm_revision}, $commit,
3035 0, $self->svm_uuid);
3037 print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
3038 if (--$_gc_nr == 0) {
3039 $_gc_nr = $_gc_period;
3040 gc();
3042 return $commit;
3045 sub match_paths {
3046 my ($self, $paths, $r) = @_;
3047 return 1 if $self->{path} eq '';
3048 if (my $path = $paths->{"/$self->{path}"}) {
3049 return ($path->{action} eq 'D') ? 0 : 1;
3051 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
3052 if (grep /$self->{path_regex}/, keys %$paths) {
3053 return 1;
3055 my $c = '';
3056 foreach (split m#/#, $self->{path}) {
3057 $c .= "/$_";
3058 next unless ($paths->{$c} &&
3059 ($paths->{$c}->{action} =~ /^[AR]$/));
3060 if ($self->ra->check_path($self->{path}, $r) ==
3061 $SVN::Node::dir) {
3062 return 1;
3065 return 0;
3068 sub find_parent_branch {
3069 my ($self, $paths, $rev) = @_;
3070 return undef unless $self->follow_parent;
3071 unless (defined $paths) {
3072 my $err_handler = $SVN::Error::handler;
3073 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
3074 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1,
3075 sub { $paths = $_[0] });
3076 $SVN::Error::handler = $err_handler;
3078 return undef unless defined $paths;
3080 # look for a parent from another branch:
3081 my @b_path_components = split m#/#, $self->{path};
3082 my @a_path_components;
3083 my $i;
3084 while (@b_path_components) {
3085 $i = $paths->{'/'.join('/', @b_path_components)};
3086 last if $i && defined $i->{copyfrom_path};
3087 unshift(@a_path_components, pop(@b_path_components));
3089 return undef unless defined $i && defined $i->{copyfrom_path};
3090 my $branch_from = $i->{copyfrom_path};
3091 if (@a_path_components) {
3092 print STDERR "branch_from: $branch_from => ";
3093 $branch_from .= '/'.join('/', @a_path_components);
3094 print STDERR $branch_from, "\n";
3096 my $r = $i->{copyfrom_rev};
3097 my $repos_root = $self->ra->{repos_root};
3098 my $url = $self->ra->{url};
3099 my $new_url = $url . $branch_from;
3100 print STDERR "Found possible branch point: ",
3101 "$new_url => ", $self->full_url, ", $r\n"
3102 unless $::_q > 1;
3103 $branch_from =~ s#^/##;
3104 my $gs = $self->other_gs($new_url, $url,
3105 $branch_from, $r, $self->{ref_id});
3106 my ($r0, $parent) = $gs->find_rev_before($r, 1);
3108 my ($base, $head);
3109 if (!defined $r0 || !defined $parent) {
3110 ($base, $head) = parse_revision_argument(0, $r);
3111 } else {
3112 if ($r0 < $r) {
3113 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
3114 0, 1, sub { $base = $_[1] - 1 });
3117 if (defined $base && $base <= $r) {
3118 $gs->fetch($base, $r);
3120 ($r0, $parent) = $gs->find_rev_before($r, 1);
3122 if (defined $r0 && defined $parent) {
3123 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n"
3124 unless $::_q > 1;
3125 my $ed;
3126 if ($self->ra->can_do_switch) {
3127 $self->assert_index_clean($parent);
3128 print STDERR "Following parent with do_switch\n"
3129 unless $::_q > 1;
3130 # do_switch works with svn/trunk >= r22312, but that
3131 # is not included with SVN 1.4.3 (the latest version
3132 # at the moment), so we can't rely on it
3133 $self->{last_rev} = $r0;
3134 $self->{last_commit} = $parent;
3135 $ed = SVN::Git::Fetcher->new($self, $gs->{path});
3136 $gs->ra->gs_do_switch($r0, $rev, $gs,
3137 $self->full_url, $ed)
3138 or die "SVN connection failed somewhere...\n";
3139 } elsif ($self->ra->trees_match($new_url, $r0,
3140 $self->full_url, $rev)) {
3141 print STDERR "Trees match:\n",
3142 " $new_url\@$r0\n",
3143 " ${\$self->full_url}\@$rev\n",
3144 "Following parent with no changes\n"
3145 unless $::_q > 1;
3146 $self->tmp_index_do(sub {
3147 command_noisy('read-tree', $parent);
3149 $self->{last_commit} = $parent;
3150 } else {
3151 print STDERR "Following parent with do_update\n"
3152 unless $::_q > 1;
3153 $ed = SVN::Git::Fetcher->new($self);
3154 $self->ra->gs_do_update($rev, $rev, $self, $ed)
3155 or die "SVN connection failed somewhere...\n";
3157 print STDERR "Successfully followed parent\n" unless $::_q > 1;
3158 return $self->make_log_entry($rev, [$parent], $ed);
3160 return undef;
3163 sub do_fetch {
3164 my ($self, $paths, $rev) = @_;
3165 my $ed;
3166 my ($last_rev, @parents);
3167 if (my $lc = $self->last_commit) {
3168 # we can have a branch that was deleted, then re-added
3169 # under the same name but copied from another path, in
3170 # which case we'll have multiple parents (we don't
3171 # want to break the original ref, nor lose copypath info):
3172 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
3173 push @{$log_entry->{parents}}, $lc;
3174 return $log_entry;
3176 $ed = SVN::Git::Fetcher->new($self);
3177 $last_rev = $self->{last_rev};
3178 $ed->{c} = $lc;
3179 @parents = ($lc);
3180 } else {
3181 $last_rev = $rev;
3182 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
3183 return $log_entry;
3185 $ed = SVN::Git::Fetcher->new($self);
3187 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
3188 die "SVN connection failed somewhere...\n";
3190 $self->make_log_entry($rev, \@parents, $ed);
3193 sub mkemptydirs {
3194 my ($self, $r) = @_;
3196 sub scan {
3197 my ($r, $empty_dirs, $line) = @_;
3198 if (defined $r && $line =~ /^r(\d+)$/) {
3199 return 0 if $1 > $r;
3200 } elsif ($line =~ /^ \+empty_dir: (.+)$/) {
3201 $empty_dirs->{$1} = 1;
3202 } elsif ($line =~ /^ \-empty_dir: (.+)$/) {
3203 my @d = grep {m[^\Q$1\E(/|$)]} (keys %$empty_dirs);
3204 delete @$empty_dirs{@d};
3206 1; # continue
3209 my %empty_dirs = ();
3210 my $gz_file = "$self->{dir}/unhandled.log.gz";
3211 if (-f $gz_file) {
3212 if (!$can_compress) {
3213 warn "Compress::Zlib could not be found; ",
3214 "empty directories in $gz_file will not be read\n";
3215 } else {
3216 my $gz = Compress::Zlib::gzopen($gz_file, "rb") or
3217 die "Unable to open $gz_file: $!\n";
3218 my $line;
3219 while ($gz->gzreadline($line) > 0) {
3220 scan($r, \%empty_dirs, $line) or last;
3222 $gz->gzclose;
3226 if (open my $fh, '<', "$self->{dir}/unhandled.log") {
3227 binmode $fh or croak "binmode: $!";
3228 while (<$fh>) {
3229 scan($r, \%empty_dirs, $_) or last;
3231 close $fh;
3234 my $strip = qr/\A\Q$self->{path}\E(?:\/|$)/;
3235 foreach my $d (sort keys %empty_dirs) {
3236 $d = uri_decode($d);
3237 $d =~ s/$strip//;
3238 next unless length($d);
3239 next if -d $d;
3240 if (-e $d) {
3241 warn "$d exists but is not a directory\n";
3242 } else {
3243 print "creating empty directory: $d\n";
3244 mkpath([$d]);
3249 sub get_untracked {
3250 my ($self, $ed) = @_;
3251 my @out;
3252 my $h = $ed->{empty};
3253 foreach (sort keys %$h) {
3254 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
3255 push @out, " $act: " . uri_encode($_);
3256 warn "W: $act: $_\n";
3258 foreach my $t (qw/dir_prop file_prop/) {
3259 $h = $ed->{$t} or next;
3260 foreach my $path (sort keys %$h) {
3261 my $ppath = $path eq '' ? '.' : $path;
3262 foreach my $prop (sort keys %{$h->{$path}}) {
3263 next if $SKIP_PROP{$prop};
3264 my $v = $h->{$path}->{$prop};
3265 my $t_ppath_prop = "$t: " .
3266 uri_encode($ppath) . ' ' .
3267 uri_encode($prop);
3268 if (defined $v) {
3269 push @out, " +$t_ppath_prop " .
3270 uri_encode($v);
3271 } else {
3272 push @out, " -$t_ppath_prop";
3277 foreach my $t (qw/absent_file absent_directory/) {
3278 $h = $ed->{$t} or next;
3279 foreach my $parent (sort keys %$h) {
3280 foreach my $path (sort @{$h->{$parent}}) {
3281 push @out, " $t: " .
3282 uri_encode("$parent/$path");
3283 warn "W: $t: $parent/$path ",
3284 "Insufficient permissions?\n";
3288 \@out;
3291 # parse_svn_date(DATE)
3292 # --------------------
3293 # Given a date (in UTC) from Subversion, return a string in the format
3294 # "<TZ Offset> <local date/time>" that Git will use.
3296 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
3297 # is true we'll convert it to the local timezone instead.
3298 sub parse_svn_date {
3299 my $date = shift || return '+0000 1970-01-01 00:00:00';
3300 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
3301 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
3302 croak "Unable to parse date: $date\n";
3303 my $parsed_date; # Set next.
3305 if ($Git::SVN::_localtime) {
3306 # Translate the Subversion datetime to an epoch time.
3307 # Begin by switching ourselves to $date's timezone, UTC.
3308 my $old_env_TZ = $ENV{TZ};
3309 $ENV{TZ} = 'UTC';
3311 my $epoch_in_UTC =
3312 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
3314 # Determine our local timezone (including DST) at the
3315 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
3316 # value of TZ, if any, at the time we were run.
3317 if (defined $Git::SVN::Log::TZ) {
3318 $ENV{TZ} = $Git::SVN::Log::TZ;
3319 } else {
3320 delete $ENV{TZ};
3323 my $our_TZ =
3324 POSIX::strftime('%Z', $S, $M, $H, $d, $m - 1, $Y - 1900);
3326 # This converts $epoch_in_UTC into our local timezone.
3327 my ($sec, $min, $hour, $mday, $mon, $year,
3328 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
3330 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
3331 $our_TZ, $year + 1900, $mon + 1,
3332 $mday, $hour, $min, $sec);
3334 # Reset us to the timezone in effect when we entered
3335 # this routine.
3336 if (defined $old_env_TZ) {
3337 $ENV{TZ} = $old_env_TZ;
3338 } else {
3339 delete $ENV{TZ};
3341 } else {
3342 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
3345 return $parsed_date;
3348 sub other_gs {
3349 my ($self, $new_url, $url,
3350 $branch_from, $r, $old_ref_id) = @_;
3351 my $gs = Git::SVN->find_by_url($new_url, $url, $branch_from);
3352 unless ($gs) {
3353 my $ref_id = $old_ref_id;
3354 $ref_id =~ s/\@\d+-*$//;
3355 $ref_id .= "\@$r";
3356 # just grow a tail if we're not unique enough :x
3357 $ref_id .= '-' while find_ref($ref_id);
3358 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
3359 if ($u =~ s#^\Q$url\E(/|$)##) {
3360 $p = $u;
3361 $u = $url;
3362 $repo_id = $self->{repo_id};
3364 while (1) {
3365 # It is possible to tag two different subdirectories at
3366 # the same revision. If the url for an existing ref
3367 # does not match, we must either find a ref with a
3368 # matching url or create a new ref by growing a tail.
3369 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
3370 my (undef, $max_commit) = $gs->rev_map_max(1);
3371 last if (!$max_commit);
3372 my ($url) = ::cmt_metadata($max_commit);
3373 last if ($url eq $gs->metadata_url);
3374 $ref_id .= '-';
3376 print STDERR "Initializing parent: $ref_id\n" unless $::_q > 1;
3381 sub call_authors_prog {
3382 my ($orig_author) = @_;
3383 $orig_author = command_oneline('rev-parse', '--sq-quote', $orig_author);
3384 my $author = `$::_authors_prog $orig_author`;
3385 if ($? != 0) {
3386 die "$::_authors_prog failed with exit code $?\n"
3388 if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
3389 my ($name, $email) = ($1, $2);
3390 $email = undef if length $2 == 0;
3391 return [$name, $email];
3392 } else {
3393 die "Author: $orig_author: $::_authors_prog returned "
3394 . "invalid author format: $author\n";
3398 sub check_author {
3399 my ($author) = @_;
3400 if (!defined $author || length $author == 0) {
3401 $author = '(no author)';
3403 if (!defined $::users{$author}) {
3404 if (defined $::_authors_prog) {
3405 $::users{$author} = call_authors_prog($author);
3406 } elsif (defined $::_authors) {
3407 die "Author: $author not defined in $::_authors file\n";
3410 $author;
3413 sub find_extra_svk_parents {
3414 my ($self, $ed, $tickets, $parents) = @_;
3415 # aha! svk:merge property changed...
3416 my @tickets = split "\n", $tickets;
3417 my @known_parents;
3418 for my $ticket ( @tickets ) {
3419 my ($uuid, $path, $rev) = split /:/, $ticket;
3420 if ( $uuid eq $self->ra_uuid ) {
3421 my $url = $self->{url};
3422 my $repos_root = $url;
3423 my $branch_from = $path;
3424 $branch_from =~ s{^/}{};
3425 my $gs = $self->other_gs($repos_root."/".$branch_from,
3426 $url,
3427 $branch_from,
3428 $rev,
3429 $self->{ref_id});
3430 if ( my $commit = $gs->rev_map_get($rev, $uuid) ) {
3431 # wahey! we found it, but it might be
3432 # an old one (!)
3433 push @known_parents, [ $rev, $commit ];
3437 # Ordering matters; highest-numbered commit merge tickets
3438 # first, as they may account for later merge ticket additions
3439 # or changes.
3440 @known_parents = map {$_->[1]} sort {$b->[0] <=> $a->[0]} @known_parents;
3441 for my $parent ( @known_parents ) {
3442 my @cmd = ('rev-list', $parent, map { "^$_" } @$parents );
3443 my ($msg_fh, $ctx) = command_output_pipe(@cmd);
3444 my $new;
3445 while ( <$msg_fh> ) {
3446 $new=1;last;
3448 command_close_pipe($msg_fh, $ctx);
3449 if ( $new ) {
3450 print STDERR
3451 "Found merge parent (svk:merge ticket): $parent\n";
3452 push @$parents, $parent;
3457 sub lookup_svn_merge {
3458 my $uuid = shift;
3459 my $url = shift;
3460 my $merge = shift;
3462 my ($source, $revs) = split ":", $merge;
3463 my $path = $source;
3464 $path =~ s{^/}{};
3465 my $gs = Git::SVN->find_by_url($url.$source, $url, $path);
3466 if ( !$gs ) {
3467 warn "Couldn't find revmap for $url$source\n";
3468 return;
3470 my @ranges = split ",", $revs;
3471 my ($tip, $tip_commit);
3472 my @merged_commit_ranges;
3473 # find the tip
3474 for my $range ( @ranges ) {
3475 my ($bottom, $top) = split "-", $range;
3476 $top ||= $bottom;
3477 my $bottom_commit = $gs->find_rev_after( $bottom, 1, $top );
3478 my $top_commit = $gs->find_rev_before( $top, 1, $bottom );
3480 unless ($top_commit and $bottom_commit) {
3481 warn "W:unknown path/rev in svn:mergeinfo "
3482 ."dirprop: $source:$range\n";
3483 next;
3486 if (scalar(command('rev-parse', "$bottom_commit^@"))) {
3487 push @merged_commit_ranges,
3488 "$bottom_commit^..$top_commit";
3489 } else {
3490 push @merged_commit_ranges, "$top_commit";
3493 if ( !defined $tip or $top > $tip ) {
3494 $tip = $top;
3495 $tip_commit = $top_commit;
3498 return ($tip_commit, @merged_commit_ranges);
3501 sub _rev_list {
3502 my ($msg_fh, $ctx) = command_output_pipe(
3503 "rev-list", @_,
3505 my @rv;
3506 while ( <$msg_fh> ) {
3507 chomp;
3508 push @rv, $_;
3510 command_close_pipe($msg_fh, $ctx);
3511 @rv;
3514 sub check_cherry_pick {
3515 my $base = shift;
3516 my $tip = shift;
3517 my $parents = shift;
3518 my @ranges = @_;
3519 my %commits = map { $_ => 1 }
3520 _rev_list("--no-merges", $tip, "--not", $base, @$parents, "--");
3521 for my $range ( @ranges ) {
3522 delete @commits{_rev_list($range, "--")};
3524 for my $commit (keys %commits) {
3525 if (has_no_changes($commit)) {
3526 delete $commits{$commit};
3529 return (keys %commits);
3532 sub has_no_changes {
3533 my $commit = shift;
3535 my @revs = split / /, command_oneline(
3536 qw(rev-list --parents -1 -m), $commit);
3538 # Commits with no parents, e.g. the start of a partial branch,
3539 # have changes by definition.
3540 return 1 if (@revs < 2);
3542 # Commits with multiple parents, e.g a merge, have no changes
3543 # by definition.
3544 return 0 if (@revs > 2);
3546 return (command_oneline("rev-parse", "$commit^{tree}") eq
3547 command_oneline("rev-parse", "$commit~1^{tree}"));
3550 # The GIT_DIR environment variable is not always set until after the command
3551 # line arguments are processed, so we can't memoize in a BEGIN block.
3553 my $memoized = 0;
3555 sub memoize_svn_mergeinfo_functions {
3556 return if $memoized;
3557 $memoized = 1;
3559 my $cache_path = "$ENV{GIT_DIR}/svn/.caches/";
3560 mkpath([$cache_path]) unless -d $cache_path;
3562 tie my %lookup_svn_merge_cache => 'Memoize::Storable',
3563 "$cache_path/lookup_svn_merge.db", 'nstore';
3564 memoize 'lookup_svn_merge',
3565 SCALAR_CACHE => 'FAULT',
3566 LIST_CACHE => ['HASH' => \%lookup_svn_merge_cache],
3569 tie my %check_cherry_pick_cache => 'Memoize::Storable',
3570 "$cache_path/check_cherry_pick.db", 'nstore';
3571 memoize 'check_cherry_pick',
3572 SCALAR_CACHE => 'FAULT',
3573 LIST_CACHE => ['HASH' => \%check_cherry_pick_cache],
3576 tie my %has_no_changes_cache => 'Memoize::Storable',
3577 "$cache_path/has_no_changes.db", 'nstore';
3578 memoize 'has_no_changes',
3579 SCALAR_CACHE => ['HASH' => \%has_no_changes_cache],
3580 LIST_CACHE => 'FAULT',
3584 sub unmemoize_svn_mergeinfo_functions {
3585 return if not $memoized;
3586 $memoized = 0;
3588 Memoize::unmemoize 'lookup_svn_merge';
3589 Memoize::unmemoize 'check_cherry_pick';
3590 Memoize::unmemoize 'has_no_changes';
3593 Memoize::memoize 'Git::SVN::repos_root';
3596 END {
3597 # Force cache writeout explicitly instead of waiting for
3598 # global destruction to avoid segfault in Storable:
3599 # http://rt.cpan.org/Public/Bug/Display.html?id=36087
3600 unmemoize_svn_mergeinfo_functions();
3603 sub parents_exclude {
3604 my $parents = shift;
3605 my @commits = @_;
3606 return unless @commits;
3608 my @excluded;
3609 my $excluded;
3610 do {
3611 my @cmd = ('rev-list', "-1", @commits, "--not", @$parents );
3612 $excluded = command_oneline(@cmd);
3613 if ( $excluded ) {
3614 my @new;
3615 my $found;
3616 for my $commit ( @commits ) {
3617 if ( $commit eq $excluded ) {
3618 push @excluded, $commit;
3619 $found++;
3620 last;
3622 else {
3623 push @new, $commit;
3626 die "saw commit '$excluded' in rev-list output, "
3627 ."but we didn't ask for that commit (wanted: @commits --not @$parents)"
3628 unless $found;
3629 @commits = @new;
3632 while ($excluded and @commits);
3634 return @excluded;
3638 # note: this function should only be called if the various dirprops
3639 # have actually changed
3640 sub find_extra_svn_parents {
3641 my ($self, $ed, $mergeinfo, $parents) = @_;
3642 # aha! svk:merge property changed...
3644 memoize_svn_mergeinfo_functions();
3646 # We first search for merged tips which are not in our
3647 # history. Then, we figure out which git revisions are in
3648 # that tip, but not this revision. If all of those revisions
3649 # are now marked as merge, we can add the tip as a parent.
3650 my @merges = split "\n", $mergeinfo;
3651 my @merge_tips;
3652 my $url = $self->{url};
3653 my $uuid = $self->ra_uuid;
3654 my %ranges;
3655 for my $merge ( @merges ) {
3656 my ($tip_commit, @ranges) =
3657 lookup_svn_merge( $uuid, $url, $merge );
3658 unless (!$tip_commit or
3659 grep { $_ eq $tip_commit } @$parents ) {
3660 push @merge_tips, $tip_commit;
3661 $ranges{$tip_commit} = \@ranges;
3662 } else {
3663 push @merge_tips, undef;
3667 my %excluded = map { $_ => 1 }
3668 parents_exclude($parents, grep { defined } @merge_tips);
3670 # check merge tips for new parents
3671 my @new_parents;
3672 for my $merge_tip ( @merge_tips ) {
3673 my $spec = shift @merges;
3674 next unless $merge_tip and $excluded{$merge_tip};
3676 my $ranges = $ranges{$merge_tip};
3678 # check out 'new' tips
3679 my $merge_base;
3680 eval {
3681 $merge_base = command_oneline(
3682 "merge-base",
3683 @$parents, $merge_tip,
3686 if ($@) {
3687 die "An error occurred during merge-base"
3688 unless $@->isa("Git::Error::Command");
3690 warn "W: Cannot find common ancestor between ".
3691 "@$parents and $merge_tip. Ignoring merge info.\n";
3692 next;
3695 # double check that there are no missing non-merge commits
3696 my (@incomplete) = check_cherry_pick(
3697 $merge_base, $merge_tip,
3698 $parents,
3699 @$ranges,
3702 if ( @incomplete ) {
3703 warn "W:svn cherry-pick ignored ($spec) - missing "
3704 .@incomplete." commit(s) (eg $incomplete[0])\n";
3705 } else {
3706 warn
3707 "Found merge parent (svn:mergeinfo prop): ",
3708 $merge_tip, "\n";
3709 push @new_parents, $merge_tip;
3713 # cater for merges which merge commits from multiple branches
3714 if ( @new_parents > 1 ) {
3715 for ( my $i = 0; $i <= $#new_parents; $i++ ) {
3716 for ( my $j = 0; $j <= $#new_parents; $j++ ) {
3717 next if $i == $j;
3718 next unless $new_parents[$i];
3719 next unless $new_parents[$j];
3720 my $revs = command_oneline(
3721 "rev-list", "-1",
3722 "$new_parents[$i]..$new_parents[$j]",
3724 if ( !$revs ) {
3725 undef($new_parents[$j]);
3730 push @$parents, grep { defined } @new_parents;
3733 sub make_log_entry {
3734 my ($self, $rev, $parents, $ed) = @_;
3735 my $untracked = $self->get_untracked($ed);
3737 my @parents = @$parents;
3738 my $ps = $ed->{path_strip} || "";
3739 for my $path ( grep { m/$ps/ } %{$ed->{dir_prop}} ) {
3740 my $props = $ed->{dir_prop}{$path};
3741 if ( $props->{"svk:merge"} ) {
3742 $self->find_extra_svk_parents
3743 ($ed, $props->{"svk:merge"}, \@parents);
3745 if ( $props->{"svn:mergeinfo"} ) {
3746 $self->find_extra_svn_parents
3747 ($ed,
3748 $props->{"svn:mergeinfo"},
3749 \@parents);
3753 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
3754 print $un "r$rev\n" or croak $!;
3755 print $un $_, "\n" foreach @$untracked;
3756 my %log_entry = ( parents => \@parents, revision => $rev,
3757 log => '');
3759 my $headrev;
3760 my $logged = delete $self->{logged_rev_props};
3761 if (!$logged || $self->{-want_revprops}) {
3762 my $rp = $self->ra->rev_proplist($rev);
3763 foreach (sort keys %$rp) {
3764 my $v = $rp->{$_};
3765 if (/^svn:(author|date|log)$/) {
3766 $log_entry{$1} = $v;
3767 } elsif ($_ eq 'svm:headrev') {
3768 $headrev = $v;
3769 } else {
3770 print $un " rev_prop: ", uri_encode($_), ' ',
3771 uri_encode($v), "\n";
3774 } else {
3775 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
3777 close $un or croak $!;
3779 $log_entry{date} = parse_svn_date($log_entry{date});
3780 $log_entry{log} .= "\n";
3781 my $author = $log_entry{author} = check_author($log_entry{author});
3782 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
3783 : ($author, undef);
3785 my ($commit_name, $commit_email) = ($name, $email);
3786 if ($_use_log_author) {
3787 my $name_field;
3788 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
3789 $name_field = $1;
3790 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
3791 $name_field = $1;
3793 if (!defined $name_field) {
3794 if (!defined $email) {
3795 $email = $name;
3797 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
3798 ($name, $email) = ($1, $2);
3799 } elsif ($name_field =~ /(.*)@/) {
3800 ($name, $email) = ($1, $name_field);
3801 } else {
3802 ($name, $email) = ($name_field, $name_field);
3805 if (defined $headrev && $self->use_svm_props) {
3806 if ($self->rewrite_root) {
3807 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
3808 "options set!\n";
3810 if ($self->rewrite_uuid) {
3811 die "Can't have both 'useSvmProps' and 'rewriteUUID' ",
3812 "options set!\n";
3814 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$}i;
3815 # we don't want "SVM: initializing mirror for junk" ...
3816 return undef if $r == 0;
3817 my $svm = $self->svm;
3818 if ($uuid ne $svm->{uuid}) {
3819 die "UUID mismatch on SVM path:\n",
3820 "expected: $svm->{uuid}\n",
3821 " got: $uuid\n";
3823 my $full_url = $self->full_url;
3824 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
3825 die "Failed to replace '$svm->{replace}' with ",
3826 "'$svm->{source}' in $full_url\n";
3827 # throw away username for storing in records
3828 remove_username($full_url);
3829 $log_entry{metadata} = "$full_url\@$r $uuid";
3830 $log_entry{svm_revision} = $r;
3831 $email ||= "$author\@$uuid";
3832 $commit_email ||= "$author\@$uuid";
3833 } elsif ($self->use_svnsync_props) {
3834 my $full_url = $self->svnsync->{url};
3835 $full_url .= "/$self->{path}" if length $self->{path};
3836 remove_username($full_url);
3837 my $uuid = $self->svnsync->{uuid};
3838 $log_entry{metadata} = "$full_url\@$rev $uuid";
3839 $email ||= "$author\@$uuid";
3840 $commit_email ||= "$author\@$uuid";
3841 } else {
3842 my $url = $self->metadata_url;
3843 remove_username($url);
3844 my $uuid = $self->rewrite_uuid || $self->ra->get_uuid;
3845 $log_entry{metadata} = "$url\@$rev " . $uuid;
3846 $email ||= "$author\@" . $uuid;
3847 $commit_email ||= "$author\@" . $uuid;
3849 $log_entry{name} = $name;
3850 $log_entry{email} = $email;
3851 $log_entry{commit_name} = $commit_name;
3852 $log_entry{commit_email} = $commit_email;
3853 \%log_entry;
3856 sub fetch {
3857 my ($self, $min_rev, $max_rev, @parents) = @_;
3858 my ($last_rev, $last_commit) = $self->last_rev_commit;
3859 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
3860 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
3863 sub set_tree_cb {
3864 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
3865 $self->{inject_parents} = { $rev => $tree };
3866 $self->fetch(undef, undef);
3869 sub set_tree {
3870 my ($self, $tree) = (shift, shift);
3871 my $log_entry = ::get_commit_entry($tree);
3872 unless ($self->{last_rev}) {
3873 ::fatal("Must have an existing revision to commit");
3875 my %ed_opts = ( r => $self->{last_rev},
3876 log => $log_entry->{log},
3877 ra => $self->ra,
3878 tree_a => $self->{last_commit},
3879 tree_b => $tree,
3880 editor_cb => sub {
3881 $self->set_tree_cb($log_entry, $tree, @_) },
3882 svn_path => $self->{path} );
3883 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
3884 print "No changes\nr$self->{last_rev} = $tree\n";
3888 sub rebuild_from_rev_db {
3889 my ($self, $path) = @_;
3890 my $r = -1;
3891 open my $fh, '<', $path or croak "open: $!";
3892 binmode $fh or croak "binmode: $!";
3893 while (<$fh>) {
3894 length($_) == 41 or croak "inconsistent size in ($_) != 41";
3895 chomp($_);
3896 ++$r;
3897 next if $_ eq ('0' x 40);
3898 $self->rev_map_set($r, $_);
3899 print "r$r = $_\n";
3901 close $fh or croak "close: $!";
3902 unlink $path or croak "unlink: $!";
3905 sub rebuild {
3906 my ($self) = @_;
3907 my $map_path = $self->map_path;
3908 my $partial = (-e $map_path && ! -z $map_path);
3909 return unless ::verify_ref($self->refname.'^0');
3910 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
3911 my $rev_db = $self->rev_db_path;
3912 $self->rebuild_from_rev_db($rev_db);
3913 if ($self->use_svm_props) {
3914 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
3915 $self->rebuild_from_rev_db($svm_rev_db);
3917 $self->unlink_rev_db_symlink;
3918 return;
3920 print "Rebuilding $map_path ...\n" if (!$partial);
3921 my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
3922 (undef, undef));
3923 my ($log, $ctx) =
3924 command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
3925 ($head ? "$head.." : "") . $self->refname,
3926 '--');
3927 my $metadata_url = $self->metadata_url;
3928 remove_username($metadata_url);
3929 my $svn_uuid = $self->rewrite_uuid || $self->ra_uuid;
3930 my $c;
3931 while (<$log>) {
3932 if ( m{^commit ($::sha1)$} ) {
3933 $c = $1;
3934 next;
3936 next unless s{^\s*(git-svn-id:)}{$1};
3937 my ($url, $rev, $uuid) = ::extract_metadata($_);
3938 remove_username($url);
3940 # ignore merges (from set-tree)
3941 next if (!defined $rev || !$uuid);
3943 # if we merged or otherwise started elsewhere, this is
3944 # how we break out of it
3945 if (($uuid ne $svn_uuid) ||
3946 ($metadata_url && $url && ($url ne $metadata_url))) {
3947 next;
3949 if ($partial && $head) {
3950 print "Partial-rebuilding $map_path ...\n";
3951 print "Currently at $base_rev = $head\n";
3952 $head = undef;
3955 $self->rev_map_set($rev, $c);
3956 print "r$rev = $c\n";
3958 command_close_pipe($log, $ctx);
3959 print "Done rebuilding $map_path\n" if (!$partial || !$head);
3960 my $rev_db_path = $self->rev_db_path;
3961 if (-f $self->rev_db_path) {
3962 unlink $self->rev_db_path or croak "unlink: $!";
3964 $self->unlink_rev_db_symlink;
3967 # rev_map:
3968 # Tie::File seems to be prone to offset errors if revisions get sparse,
3969 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
3970 # one of my favorite modules is out :< Next up would be one of the DBM
3971 # modules, but I'm not sure which is most portable...
3973 # This is the replacement for the rev_db format, which was too big
3974 # and inefficient for large repositories with a lot of sparse history
3975 # (mainly tags)
3977 # The format is this:
3978 # - 24 bytes for every record,
3979 # * 4 bytes for the integer representing an SVN revision number
3980 # * 20 bytes representing the sha1 of a git commit
3981 # - No empty padding records like the old format
3982 # (except the last record, which can be overwritten)
3983 # - new records are written append-only since SVN revision numbers
3984 # increase monotonically
3985 # - lookups on SVN revision number are done via a binary search
3986 # - Piping the file to xxd -c24 is a good way of dumping it for
3987 # viewing or editing (piped back through xxd -r), should the need
3988 # ever arise.
3989 # - The last record can be padding revision with an all-zero sha1
3990 # This is used to optimize fetch performance when using multiple
3991 # "fetch" directives in .git/config
3993 # These files are disposable unless noMetadata or useSvmProps is set
3995 sub _rev_map_set {
3996 my ($fh, $rev, $commit) = @_;
3998 binmode $fh or croak "binmode: $!";
3999 my $size = (stat($fh))[7];
4000 ($size % 24) == 0 or croak "inconsistent size: $size";
4002 my $wr_offset = 0;
4003 if ($size > 0) {
4004 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
4005 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
4006 $read == 24 or croak "read only $read bytes (!= 24)";
4007 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
4008 if ($last_commit eq ('0' x40)) {
4009 if ($size >= 48) {
4010 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
4011 $read = sysread($fh, $buf, 24) or
4012 croak "read: $!";
4013 $read == 24 or
4014 croak "read only $read bytes (!= 24)";
4015 ($last_rev, $last_commit) =
4016 unpack(rev_map_fmt, $buf);
4017 if ($last_commit eq ('0' x40)) {
4018 croak "inconsistent .rev_map\n";
4021 if ($last_rev >= $rev) {
4022 croak "last_rev is higher!: $last_rev >= $rev";
4024 $wr_offset = -24;
4027 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
4028 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
4029 croak "write: $!";
4032 sub _rev_map_reset {
4033 my ($fh, $rev, $commit) = @_;
4034 my $c = _rev_map_get($fh, $rev);
4035 $c eq $commit or die "_rev_map_reset(@_) commit $c does not match!\n";
4036 my $offset = sysseek($fh, 0, SEEK_CUR) or croak "seek: $!";
4037 truncate $fh, $offset or croak "truncate: $!";
4040 sub mkfile {
4041 my ($path) = @_;
4042 unless (-e $path) {
4043 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
4044 mkpath([$dir]) unless -d $dir;
4045 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
4046 close $fh or die "Couldn't close (create) $path: $!\n";
4050 sub rev_map_set {
4051 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
4052 defined $commit or die "missing arg3\n";
4053 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
4054 my $db = $self->map_path($uuid);
4055 my $db_lock = "$db.lock";
4056 my $sig;
4057 $update_ref ||= 0;
4058 if ($update_ref) {
4059 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
4060 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
4062 mkfile($db);
4064 $LOCKFILES{$db_lock} = 1;
4065 my $sync;
4066 # both of these options make our .rev_db file very, very important
4067 # and we can't afford to lose it because rebuild() won't work
4068 if ($self->use_svm_props || $self->no_metadata) {
4069 $sync = 1;
4070 copy($db, $db_lock) or die "rev_map_set(@_): ",
4071 "Failed to copy: ",
4072 "$db => $db_lock ($!)\n";
4073 } else {
4074 rename $db, $db_lock or die "rev_map_set(@_): ",
4075 "Failed to rename: ",
4076 "$db => $db_lock ($!)\n";
4079 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
4080 or croak "Couldn't open $db_lock: $!\n";
4081 $update_ref eq 'reset' ? _rev_map_reset($fh, $rev, $commit) :
4082 _rev_map_set($fh, $rev, $commit);
4083 if ($sync) {
4084 $fh->flush or die "Couldn't flush $db_lock: $!\n";
4085 $fh->sync or die "Couldn't sync $db_lock: $!\n";
4087 close $fh or croak $!;
4088 if ($update_ref) {
4089 $_head = $self;
4090 my $note = "";
4091 $note = " ($update_ref)" if ($update_ref !~ /^\d*$/);
4092 command_noisy('update-ref', '-m', "r$rev$note",
4093 $self->refname, $commit);
4095 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
4096 "$db_lock => $db ($!)\n";
4097 delete $LOCKFILES{$db_lock};
4098 if ($update_ref) {
4099 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
4100 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
4101 kill $sig, $$ if defined $sig;
4105 # If want_commit, this will return an array of (rev, commit) where
4106 # commit _must_ be a valid commit in the archive.
4107 # Otherwise, it'll return the max revision (whether or not the
4108 # commit is valid or just a 0x40 placeholder).
4109 sub rev_map_max {
4110 my ($self, $want_commit) = @_;
4111 $self->rebuild;
4112 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
4113 $want_commit ? ($r, $c) : $r;
4116 sub rev_map_max_norebuild {
4117 my ($self, $want_commit) = @_;
4118 my $map_path = $self->map_path;
4119 stat $map_path or return $want_commit ? (0, undef) : 0;
4120 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
4121 binmode $fh or croak "binmode: $!";
4122 my $size = (stat($fh))[7];
4123 ($size % 24) == 0 or croak "inconsistent size: $size";
4125 if ($size == 0) {
4126 close $fh or croak "close: $!";
4127 return $want_commit ? (0, undef) : 0;
4130 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
4131 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
4132 my ($r, $c) = unpack(rev_map_fmt, $buf);
4133 if ($want_commit && $c eq ('0' x40)) {
4134 if ($size < 48) {
4135 return $want_commit ? (0, undef) : 0;
4137 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
4138 sysread($fh, $buf, 24) == 24 or croak "read: $!";
4139 ($r, $c) = unpack(rev_map_fmt, $buf);
4140 if ($c eq ('0'x40)) {
4141 croak "Penultimate record is all-zeroes in $map_path";
4144 close $fh or croak "close: $!";
4145 $want_commit ? ($r, $c) : $r;
4148 sub rev_map_get {
4149 my ($self, $rev, $uuid) = @_;
4150 my $map_path = $self->map_path($uuid);
4151 return undef unless -e $map_path;
4153 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
4154 my $c = _rev_map_get($fh, $rev);
4155 close($fh) or croak "close: $!";
4159 sub _rev_map_get {
4160 my ($fh, $rev) = @_;
4162 binmode $fh or croak "binmode: $!";
4163 my $size = (stat($fh))[7];
4164 ($size % 24) == 0 or croak "inconsistent size: $size";
4166 if ($size == 0) {
4167 return undef;
4170 my ($l, $u) = (0, $size - 24);
4171 my ($r, $c, $buf);
4173 while ($l <= $u) {
4174 my $i = int(($l/24 + $u/24) / 2) * 24;
4175 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
4176 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
4177 my ($r, $c) = unpack(rev_map_fmt, $buf);
4179 if ($r < $rev) {
4180 $l = $i + 24;
4181 } elsif ($r > $rev) {
4182 $u = $i - 24;
4183 } else { # $r == $rev
4184 return $c eq ('0' x 40) ? undef : $c;
4187 undef;
4190 # Finds the first svn revision that exists on (if $eq_ok is true) or
4191 # before $rev for the current branch. It will not search any lower
4192 # than $min_rev. Returns the git commit hash and svn revision number
4193 # if found, else (undef, undef).
4194 sub find_rev_before {
4195 my ($self, $rev, $eq_ok, $min_rev) = @_;
4196 --$rev unless $eq_ok;
4197 $min_rev ||= 1;
4198 my $max_rev = $self->rev_map_max;
4199 $rev = $max_rev if ($rev > $max_rev);
4200 while ($rev >= $min_rev) {
4201 if (my $c = $self->rev_map_get($rev)) {
4202 return ($rev, $c);
4204 --$rev;
4206 return (undef, undef);
4209 # Finds the first svn revision that exists on (if $eq_ok is true) or
4210 # after $rev for the current branch. It will not search any higher
4211 # than $max_rev. Returns the git commit hash and svn revision number
4212 # if found, else (undef, undef).
4213 sub find_rev_after {
4214 my ($self, $rev, $eq_ok, $max_rev) = @_;
4215 ++$rev unless $eq_ok;
4216 $max_rev ||= $self->rev_map_max;
4217 while ($rev <= $max_rev) {
4218 if (my $c = $self->rev_map_get($rev)) {
4219 return ($rev, $c);
4221 ++$rev;
4223 return (undef, undef);
4226 sub _new {
4227 my ($class, $repo_id, $ref_id, $path) = @_;
4228 unless (defined $repo_id && length $repo_id) {
4229 $repo_id = $Git::SVN::default_repo_id;
4231 unless (defined $ref_id && length $ref_id) {
4232 $_prefix = '' unless defined($_prefix);
4233 $_[2] = $ref_id =
4234 "refs/remotes/$_prefix$Git::SVN::default_ref_id";
4236 $_[1] = $repo_id;
4237 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
4239 # Older repos imported by us used $GIT_DIR/svn/foo instead of
4240 # $GIT_DIR/svn/refs/remotes/foo when tracking refs/remotes/foo
4241 if ($ref_id =~ m{^refs/remotes/(.*)}) {
4242 my $old_dir = "$ENV{GIT_DIR}/svn/$1";
4243 if (-d $old_dir && ! -d $dir) {
4244 $dir = $old_dir;
4248 $_[3] = $path = '' unless (defined $path);
4249 mkpath([$dir]);
4250 bless {
4251 ref_id => $ref_id, dir => $dir, index => "$dir/index",
4252 path => $path, config => "$ENV{GIT_DIR}/svn/config",
4253 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
4256 # for read-only access of old .rev_db formats
4257 sub unlink_rev_db_symlink {
4258 my ($self) = @_;
4259 my $link = $self->rev_db_path;
4260 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
4261 if (-l $link) {
4262 unlink $link or croak "unlink: $link failed!";
4266 sub rev_db_path {
4267 my ($self, $uuid) = @_;
4268 my $db_path = $self->map_path($uuid);
4269 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
4270 or croak "map_path: $db_path does not contain '/.rev_map.' !";
4271 $db_path;
4274 # the new replacement for .rev_db
4275 sub map_path {
4276 my ($self, $uuid) = @_;
4277 $uuid ||= $self->ra_uuid;
4278 "$self->{map_root}.$uuid";
4281 sub uri_encode {
4282 my ($f) = @_;
4283 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
4287 sub uri_decode {
4288 my ($f) = @_;
4289 $f =~ s#%([0-9a-fA-F]{2})#chr(hex($1))#eg;
4293 sub remove_username {
4294 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
4297 package Git::SVN::Prompt;
4298 use strict;
4299 use warnings;
4300 require SVN::Core;
4301 use vars qw/$_no_auth_cache $_username/;
4303 sub simple {
4304 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
4305 $may_save = undef if $_no_auth_cache;
4306 $default_username = $_username if defined $_username;
4307 if (defined $default_username && length $default_username) {
4308 if (defined $realm && length $realm) {
4309 print STDERR "Authentication realm: $realm\n";
4310 STDERR->flush;
4312 $cred->username($default_username);
4313 } else {
4314 username($cred, $realm, $may_save, $pool);
4316 $cred->password(_read_password("Password for '" .
4317 $cred->username . "': ", $realm));
4318 $cred->may_save($may_save);
4319 $SVN::_Core::SVN_NO_ERROR;
4322 sub ssl_server_trust {
4323 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
4324 $may_save = undef if $_no_auth_cache;
4325 print STDERR "Error validating server certificate for '$realm':\n";
4327 no warnings 'once';
4328 # All variables SVN::Auth::SSL::* are used only once,
4329 # so we're shutting up Perl warnings about this.
4330 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
4331 print STDERR " - The certificate is not issued ",
4332 "by a trusted authority. Use the\n",
4333 " fingerprint to validate ",
4334 "the certificate manually!\n";
4336 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
4337 print STDERR " - The certificate hostname ",
4338 "does not match.\n";
4340 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
4341 print STDERR " - The certificate is not yet valid.\n";
4343 if ($failures & $SVN::Auth::SSL::EXPIRED) {
4344 print STDERR " - The certificate has expired.\n";
4346 if ($failures & $SVN::Auth::SSL::OTHER) {
4347 print STDERR " - The certificate has ",
4348 "an unknown error.\n";
4350 } # no warnings 'once'
4351 printf STDERR
4352 "Certificate information:\n".
4353 " - Hostname: %s\n".
4354 " - Valid: from %s until %s\n".
4355 " - Issuer: %s\n".
4356 " - Fingerprint: %s\n",
4357 map $cert_info->$_, qw(hostname valid_from valid_until
4358 issuer_dname fingerprint);
4359 my $choice;
4360 prompt:
4361 print STDERR $may_save ?
4362 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
4363 "(R)eject or accept (t)emporarily? ";
4364 STDERR->flush;
4365 $choice = lc(substr(<STDIN> || 'R', 0, 1));
4366 if ($choice =~ /^t$/i) {
4367 $cred->may_save(undef);
4368 } elsif ($choice =~ /^r$/i) {
4369 return -1;
4370 } elsif ($may_save && $choice =~ /^p$/i) {
4371 $cred->may_save($may_save);
4372 } else {
4373 goto prompt;
4375 $cred->accepted_failures($failures);
4376 $SVN::_Core::SVN_NO_ERROR;
4379 sub ssl_client_cert {
4380 my ($cred, $realm, $may_save, $pool) = @_;
4381 $may_save = undef if $_no_auth_cache;
4382 print STDERR "Client certificate filename: ";
4383 STDERR->flush;
4384 chomp(my $filename = <STDIN>);
4385 $cred->cert_file($filename);
4386 $cred->may_save($may_save);
4387 $SVN::_Core::SVN_NO_ERROR;
4390 sub ssl_client_cert_pw {
4391 my ($cred, $realm, $may_save, $pool) = @_;
4392 $may_save = undef if $_no_auth_cache;
4393 $cred->password(_read_password("Password: ", $realm));
4394 $cred->may_save($may_save);
4395 $SVN::_Core::SVN_NO_ERROR;
4398 sub username {
4399 my ($cred, $realm, $may_save, $pool) = @_;
4400 $may_save = undef if $_no_auth_cache;
4401 if (defined $realm && length $realm) {
4402 print STDERR "Authentication realm: $realm\n";
4404 my $username;
4405 if (defined $_username) {
4406 $username = $_username;
4407 } else {
4408 print STDERR "Username: ";
4409 STDERR->flush;
4410 chomp($username = <STDIN>);
4412 $cred->username($username);
4413 $cred->may_save($may_save);
4414 $SVN::_Core::SVN_NO_ERROR;
4417 sub _read_password {
4418 my ($prompt, $realm) = @_;
4419 my $password = '';
4420 if (exists $ENV{GIT_ASKPASS}) {
4421 open(PH, "-|", $ENV{GIT_ASKPASS}, $prompt);
4422 $password = <PH>;
4423 $password =~ s/[\012\015]//; # \n\r
4424 close(PH);
4425 } else {
4426 print STDERR $prompt;
4427 STDERR->flush;
4428 require Term::ReadKey;
4429 Term::ReadKey::ReadMode('noecho');
4430 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
4431 last if $key =~ /[\012\015]/; # \n\r
4432 $password .= $key;
4434 Term::ReadKey::ReadMode('restore');
4435 print STDERR "\n";
4436 STDERR->flush;
4438 $password;
4441 package SVN::Git::Fetcher;
4442 use vars qw/@ISA $_ignore_regex $_preserve_empty_dirs $_placeholder_filename
4443 @deleted_gpath %added_placeholder $repo_id/;
4444 use strict;
4445 use warnings;
4446 use Carp qw/croak/;
4447 use File::Basename qw/dirname/;
4448 use IO::File qw//;
4450 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
4451 sub new {
4452 my ($class, $git_svn, $switch_path) = @_;
4453 my $self = SVN::Delta::Editor->new;
4454 bless $self, $class;
4455 if (exists $git_svn->{last_commit}) {
4456 $self->{c} = $git_svn->{last_commit};
4457 $self->{empty_symlinks} =
4458 _mark_empty_symlinks($git_svn, $switch_path);
4461 # some options are read globally, but can be overridden locally
4462 # per [svn-remote "..."] section. Command-line options will *NOT*
4463 # override options set in an [svn-remote "..."] section
4464 $repo_id = $git_svn->{repo_id};
4465 my $k = "svn-remote.$repo_id.ignore-paths";
4466 my $v = eval { command_oneline('config', '--get', $k) };
4467 $self->{ignore_regex} = $v;
4469 $k = "svn-remote.$repo_id.preserve-empty-dirs";
4470 $v = eval { command_oneline('config', '--get', '--bool', $k) };
4471 if ($v && $v eq 'true') {
4472 $_preserve_empty_dirs = 1;
4473 $k = "svn-remote.$repo_id.placeholder-filename";
4474 $v = eval { command_oneline('config', '--get', $k) };
4475 $_placeholder_filename = $v;
4478 # Load the list of placeholder files added during previous invocations.
4479 $k = "svn-remote.$repo_id.added-placeholder";
4480 $v = eval { command_oneline('config', '--get-all', $k) };
4481 if ($_preserve_empty_dirs && $v) {
4482 # command() prints errors to stderr, so we only call it if
4483 # command_oneline() succeeded.
4484 my @v = command('config', '--get-all', $k);
4485 $added_placeholder{ dirname($_) } = $_ foreach @v;
4488 $self->{empty} = {};
4489 $self->{dir_prop} = {};
4490 $self->{file_prop} = {};
4491 $self->{absent_dir} = {};
4492 $self->{absent_file} = {};
4493 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
4494 $self->{pathnameencoding} = Git::config('svn.pathnameencoding');
4495 $self;
4498 # this uses the Ra object, so it must be called before do_{switch,update},
4499 # not inside them (when the Git::SVN::Fetcher object is passed) to
4500 # do_{switch,update}
4501 sub _mark_empty_symlinks {
4502 my ($git_svn, $switch_path) = @_;
4503 my $bool = Git::config_bool('svn.brokenSymlinkWorkaround');
4504 return {} if (!defined($bool)) || (defined($bool) && ! $bool);
4506 my %ret;
4507 my ($rev, $cmt) = $git_svn->last_rev_commit;
4508 return {} unless ($rev && $cmt);
4510 # allow the warning to be printed for each revision we fetch to
4511 # ensure the user sees it. The user can also disable the workaround
4512 # on the repository even while git svn is running and the next
4513 # revision fetched will skip this expensive function.
4514 my $printed_warning;
4515 chomp(my $empty_blob = `git hash-object -t blob --stdin < /dev/null`);
4516 my ($ls, $ctx) = command_output_pipe(qw/ls-tree -r -z/, $cmt);
4517 local $/ = "\0";
4518 my $pfx = defined($switch_path) ? $switch_path : $git_svn->{path};
4519 $pfx .= '/' if length($pfx);
4520 while (<$ls>) {
4521 chomp;
4522 s/\A100644 blob $empty_blob\t//o or next;
4523 unless ($printed_warning) {
4524 print STDERR "Scanning for empty symlinks, ",
4525 "this may take a while if you have ",
4526 "many empty files\n",
4527 "You may disable this with `",
4528 "git config svn.brokenSymlinkWorkaround ",
4529 "false'.\n",
4530 "This may be done in a different ",
4531 "terminal without restarting ",
4532 "git svn\n";
4533 $printed_warning = 1;
4535 my $path = $_;
4536 my (undef, $props) =
4537 $git_svn->ra->get_file($pfx.$path, $rev, undef);
4538 if ($props->{'svn:special'}) {
4539 $ret{$path} = 1;
4542 command_close_pipe($ls, $ctx);
4543 \%ret;
4546 # returns true if a given path is inside a ".git" directory
4547 sub in_dot_git {
4548 $_[0] =~ m{(?:^|/)\.git(?:/|$)};
4551 # return value: 0 -- don't ignore, 1 -- ignore
4552 sub is_path_ignored {
4553 my ($self, $path) = @_;
4554 return 1 if in_dot_git($path);
4555 return 1 if defined($self->{ignore_regex}) &&
4556 $path =~ m!$self->{ignore_regex}!;
4557 return 0 unless defined($_ignore_regex);
4558 return 1 if $path =~ m!$_ignore_regex!o;
4559 return 0;
4562 sub set_path_strip {
4563 my ($self, $path) = @_;
4564 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
4567 sub open_root {
4568 { path => '' };
4571 sub open_directory {
4572 my ($self, $path, $pb, $rev) = @_;
4573 { path => $path };
4576 sub git_path {
4577 my ($self, $path) = @_;
4578 if (my $enc = $self->{pathnameencoding}) {
4579 require Encode;
4580 Encode::from_to($path, 'UTF-8', $enc);
4582 if ($self->{path_strip}) {
4583 $path =~ s!$self->{path_strip}!! or
4584 die "Failed to strip path '$path' ($self->{path_strip})\n";
4586 $path;
4589 sub delete_entry {
4590 my ($self, $path, $rev, $pb) = @_;
4591 return undef if $self->is_path_ignored($path);
4593 my $gpath = $self->git_path($path);
4594 return undef if ($gpath eq '');
4596 # remove entire directories.
4597 my ($tree) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
4598 =~ /\A040000 tree ([a-f\d]{40})\t\Q$gpath\E\0/);
4599 if ($tree) {
4600 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
4601 -r --name-only -z/,
4602 $tree);
4603 local $/ = "\0";
4604 while (<$ls>) {
4605 chomp;
4606 my $rmpath = "$gpath/$_";
4607 $self->{gii}->remove($rmpath);
4608 print "\tD\t$rmpath\n" unless $::_q;
4610 print "\tD\t$gpath/\n" unless $::_q;
4611 command_close_pipe($ls, $ctx);
4612 } else {
4613 $self->{gii}->remove($gpath);
4614 print "\tD\t$gpath\n" unless $::_q;
4616 # Don't add to @deleted_gpath if we're deleting a placeholder file.
4617 push @deleted_gpath, $gpath unless $added_placeholder{dirname($path)};
4618 $self->{empty}->{$path} = 0;
4619 undef;
4622 sub open_file {
4623 my ($self, $path, $pb, $rev) = @_;
4624 my ($mode, $blob);
4626 goto out if $self->is_path_ignored($path);
4628 my $gpath = $self->git_path($path);
4629 ($mode, $blob) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
4630 =~ /\A(\d{6}) blob ([a-f\d]{40})\t\Q$gpath\E\0/);
4631 unless (defined $mode && defined $blob) {
4632 die "$path was not found in commit $self->{c} (r$rev)\n";
4634 if ($mode eq '100644' && $self->{empty_symlinks}->{$path}) {
4635 $mode = '120000';
4637 out:
4638 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
4639 pool => SVN::Pool->new, action => 'M' };
4642 sub add_file {
4643 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
4644 my $mode;
4646 if (!$self->is_path_ignored($path)) {
4647 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
4648 delete $self->{empty}->{$dir};
4649 $mode = '100644';
4651 if ($added_placeholder{$dir}) {
4652 # Remove our placeholder file, if we created one.
4653 delete_entry($self, $added_placeholder{$dir})
4654 unless $path eq $added_placeholder{$dir};
4655 delete $added_placeholder{$dir}
4659 { path => $path, mode_a => $mode, mode_b => $mode,
4660 pool => SVN::Pool->new, action => 'A' };
4663 sub add_directory {
4664 my ($self, $path, $cp_path, $cp_rev) = @_;
4665 goto out if $self->is_path_ignored($path);
4666 my $gpath = $self->git_path($path);
4667 if ($gpath eq '') {
4668 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
4669 -r --name-only -z/,
4670 $self->{c});
4671 local $/ = "\0";
4672 while (<$ls>) {
4673 chomp;
4674 $self->{gii}->remove($_);
4675 print "\tD\t$_\n" unless $::_q;
4676 push @deleted_gpath, $gpath;
4678 command_close_pipe($ls, $ctx);
4679 $self->{empty}->{$path} = 0;
4681 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
4682 delete $self->{empty}->{$dir};
4683 $self->{empty}->{$path} = 1;
4685 if ($added_placeholder{$dir}) {
4686 # Remove our placeholder file, if we created one.
4687 delete_entry($self, $added_placeholder{$dir});
4688 delete $added_placeholder{$dir}
4691 out:
4692 { path => $path };
4695 sub change_dir_prop {
4696 my ($self, $db, $prop, $value) = @_;
4697 return undef if $self->is_path_ignored($db->{path});
4698 $self->{dir_prop}->{$db->{path}} ||= {};
4699 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
4700 undef;
4703 sub absent_directory {
4704 my ($self, $path, $pb) = @_;
4705 return undef if $self->is_path_ignored($path);
4706 $self->{absent_dir}->{$pb->{path}} ||= [];
4707 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
4708 undef;
4711 sub absent_file {
4712 my ($self, $path, $pb) = @_;
4713 return undef if $self->is_path_ignored($path);
4714 $self->{absent_file}->{$pb->{path}} ||= [];
4715 push @{$self->{absent_file}->{$pb->{path}}}, $path;
4716 undef;
4719 sub change_file_prop {
4720 my ($self, $fb, $prop, $value) = @_;
4721 return undef if $self->is_path_ignored($fb->{path});
4722 if ($prop eq 'svn:executable') {
4723 if ($fb->{mode_b} != 120000) {
4724 $fb->{mode_b} = defined $value ? 100755 : 100644;
4726 } elsif ($prop eq 'svn:special') {
4727 $fb->{mode_b} = defined $value ? 120000 : 100644;
4728 } else {
4729 $self->{file_prop}->{$fb->{path}} ||= {};
4730 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
4732 undef;
4735 sub apply_textdelta {
4736 my ($self, $fb, $exp) = @_;
4737 return undef if $self->is_path_ignored($fb->{path});
4738 my $fh = $::_repository->temp_acquire('svn_delta');
4739 # $fh gets auto-closed() by SVN::TxDelta::apply(),
4740 # (but $base does not,) so dup() it for reading in close_file
4741 open my $dup, '<&', $fh or croak $!;
4742 my $base = $::_repository->temp_acquire('git_blob');
4744 if ($fb->{blob}) {
4745 my ($base_is_link, $size);
4747 if ($fb->{mode_a} eq '120000' &&
4748 ! $self->{empty_symlinks}->{$fb->{path}}) {
4749 print $base 'link ' or die "print $!\n";
4750 $base_is_link = 1;
4752 retry:
4753 $size = $::_repository->cat_blob($fb->{blob}, $base);
4754 die "Failed to read object $fb->{blob}" if ($size < 0);
4756 if (defined $exp) {
4757 seek $base, 0, 0 or croak $!;
4758 my $got = ::md5sum($base);
4759 if ($got ne $exp) {
4760 my $err = "Checksum mismatch: ".
4761 "$fb->{path} $fb->{blob}\n" .
4762 "expected: $exp\n" .
4763 " got: $got\n";
4764 if ($base_is_link) {
4765 warn $err,
4766 "Retrying... (possibly ",
4767 "a bad symlink from SVN)\n";
4768 $::_repository->temp_reset($base);
4769 $base_is_link = 0;
4770 goto retry;
4772 die $err;
4776 seek $base, 0, 0 or croak $!;
4777 $fb->{fh} = $fh;
4778 $fb->{base} = $base;
4779 [ SVN::TxDelta::apply($base, $dup, undef, $fb->{path}, $fb->{pool}) ];
4782 sub close_file {
4783 my ($self, $fb, $exp) = @_;
4784 return undef if $self->is_path_ignored($fb->{path});
4786 my $hash;
4787 my $path = $self->git_path($fb->{path});
4788 if (my $fh = $fb->{fh}) {
4789 if (defined $exp) {
4790 seek($fh, 0, 0) or croak $!;
4791 my $got = ::md5sum($fh);
4792 if ($got ne $exp) {
4793 die "Checksum mismatch: $path\n",
4794 "expected: $exp\n got: $got\n";
4797 if ($fb->{mode_b} == 120000) {
4798 sysseek($fh, 0, 0) or croak $!;
4799 my $rd = sysread($fh, my $buf, 5);
4801 if (!defined $rd) {
4802 croak "sysread: $!\n";
4803 } elsif ($rd == 0) {
4804 warn "$path has mode 120000",
4805 " but it points to nothing\n",
4806 "converting to an empty file with mode",
4807 " 100644\n";
4808 $fb->{mode_b} = '100644';
4809 } elsif ($buf ne 'link ') {
4810 warn "$path has mode 120000",
4811 " but is not a link\n";
4812 } else {
4813 my $tmp_fh = $::_repository->temp_acquire(
4814 'svn_hash');
4815 my $res;
4816 while ($res = sysread($fh, my $str, 1024)) {
4817 my $out = syswrite($tmp_fh, $str, $res);
4818 defined($out) && $out == $res
4819 or croak("write ",
4820 Git::temp_path($tmp_fh),
4821 ": $!\n");
4823 defined $res or croak $!;
4825 ($fh, $tmp_fh) = ($tmp_fh, $fh);
4826 Git::temp_release($tmp_fh, 1);
4830 $hash = $::_repository->hash_and_insert_object(
4831 Git::temp_path($fh));
4832 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
4834 Git::temp_release($fb->{base}, 1);
4835 Git::temp_release($fh, 1);
4836 } else {
4837 $hash = $fb->{blob} or die "no blob information\n";
4839 $fb->{pool}->clear;
4840 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
4841 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
4842 undef;
4845 sub abort_edit {
4846 my $self = shift;
4847 $self->{nr} = $self->{gii}->{nr};
4848 delete $self->{gii};
4849 $self->SUPER::abort_edit(@_);
4852 sub close_edit {
4853 my $self = shift;
4855 if ($_preserve_empty_dirs) {
4856 my @empty_dirs;
4858 # Any entry flagged as empty that also has an associated
4859 # dir_prop represents a newly created empty directory.
4860 foreach my $i (keys %{$self->{empty}}) {
4861 push @empty_dirs, $i if exists $self->{dir_prop}->{$i};
4864 # Search for directories that have become empty due subsequent
4865 # file deletes.
4866 push @empty_dirs, $self->find_empty_directories();
4868 # Finally, add a placeholder file to each empty directory.
4869 $self->add_placeholder_file($_) foreach (@empty_dirs);
4871 $self->stash_placeholder_list();
4874 $self->{git_commit_ok} = 1;
4875 $self->{nr} = $self->{gii}->{nr};
4876 delete $self->{gii};
4877 $self->SUPER::close_edit(@_);
4880 sub find_empty_directories {
4881 my ($self) = @_;
4882 my @empty_dirs;
4883 my %dirs = map { dirname($_) => 1 } @deleted_gpath;
4885 foreach my $dir (sort keys %dirs) {
4886 next if $dir eq ".";
4888 # If there have been any additions to this directory, there is
4889 # no reason to check if it is empty.
4890 my $skip_added = 0;
4891 foreach my $t (qw/dir_prop file_prop/) {
4892 foreach my $path (keys %{ $self->{$t} }) {
4893 if (exists $self->{$t}->{dirname($path)}) {
4894 $skip_added = 1;
4895 last;
4898 last if $skip_added;
4900 next if $skip_added;
4902 # Use `git ls-tree` to get the filenames of this directory
4903 # that existed prior to this particular commit.
4904 my $ls = command('ls-tree', '-z', '--name-only',
4905 $self->{c}, "$dir/");
4906 my %files = map { $_ => 1 } split(/\0/, $ls);
4908 # Remove the filenames that were deleted during this commit.
4909 delete $files{$_} foreach (@deleted_gpath);
4911 # Report the directory if there are no filenames left.
4912 push @empty_dirs, $dir unless (scalar %files);
4914 @empty_dirs;
4917 sub add_placeholder_file {
4918 my ($self, $dir) = @_;
4919 my $path = "$dir/$_placeholder_filename";
4920 my $gpath = $self->git_path($path);
4922 my $fh = $::_repository->temp_acquire($gpath);
4923 my $hash = $::_repository->hash_and_insert_object(Git::temp_path($fh));
4924 Git::temp_release($fh, 1);
4925 $self->{gii}->update('100644', $hash, $gpath) or croak $!;
4927 # The directory should no longer be considered empty.
4928 delete $self->{empty}->{$dir} if exists $self->{empty}->{$dir};
4930 # Keep track of any placeholder files we create.
4931 $added_placeholder{$dir} = $path;
4934 sub stash_placeholder_list {
4935 my ($self) = @_;
4936 my $k = "svn-remote.$repo_id.added-placeholder";
4937 my $v = eval { command_oneline('config', '--get-all', $k) };
4938 command_noisy('config', '--unset-all', $k) if $v;
4939 foreach (values %added_placeholder) {
4940 command_noisy('config', '--add', $k, $_);
4944 package SVN::Git::Editor;
4945 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
4946 use strict;
4947 use warnings;
4948 use Carp qw/croak/;
4949 use IO::File;
4951 sub new {
4952 my ($class, $opts) = @_;
4953 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
4954 die "$_ required!\n" unless (defined $opts->{$_});
4957 my $pool = SVN::Pool->new;
4958 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
4959 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
4960 $opts->{r}, $mods);
4962 # $opts->{ra} functions should not be used after this:
4963 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
4964 $opts->{editor_cb}, $pool);
4965 my $self = SVN::Delta::Editor->new(@ce, $pool);
4966 bless $self, $class;
4967 foreach (qw/svn_path r tree_a tree_b/) {
4968 $self->{$_} = $opts->{$_};
4970 $self->{url} = $opts->{ra}->{url};
4971 $self->{mods} = $mods;
4972 $self->{types} = $types;
4973 $self->{pool} = $pool;
4974 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
4975 $self->{rm} = { };
4976 $self->{path_prefix} = length $self->{svn_path} ?
4977 "$self->{svn_path}/" : '';
4978 $self->{config} = $opts->{config};
4979 $self->{mergeinfo} = $opts->{mergeinfo};
4980 return $self;
4983 sub generate_diff {
4984 my ($tree_a, $tree_b) = @_;
4985 my @diff_tree = qw(diff-tree -z -r);
4986 if ($_cp_similarity) {
4987 push @diff_tree, "-C$_cp_similarity";
4988 } else {
4989 push @diff_tree, '-C';
4991 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
4992 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
4993 push @diff_tree, $tree_a, $tree_b;
4994 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
4995 local $/ = "\0";
4996 my $state = 'meta';
4997 my @mods;
4998 while (<$diff_fh>) {
4999 chomp $_; # this gets rid of the trailing "\0"
5000 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
5001 ($::sha1)\s($::sha1)\s
5002 ([MTCRAD])\d*$/xo) {
5003 push @mods, { mode_a => $1, mode_b => $2,
5004 sha1_a => $3, sha1_b => $4,
5005 chg => $5 };
5006 if ($5 =~ /^(?:C|R)$/) {
5007 $state = 'file_a';
5008 } else {
5009 $state = 'file_b';
5011 } elsif ($state eq 'file_a') {
5012 my $x = $mods[$#mods] or croak "Empty array\n";
5013 if ($x->{chg} !~ /^(?:C|R)$/) {
5014 croak "Error parsing $_, $x->{chg}\n";
5016 $x->{file_a} = $_;
5017 $state = 'file_b';
5018 } elsif ($state eq 'file_b') {
5019 my $x = $mods[$#mods] or croak "Empty array\n";
5020 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
5021 croak "Error parsing $_, $x->{chg}\n";
5023 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
5024 croak "Error parsing $_, $x->{chg}\n";
5026 $x->{file_b} = $_;
5027 $state = 'meta';
5028 } else {
5029 croak "Error parsing $_\n";
5032 command_close_pipe($diff_fh, $ctx);
5033 \@mods;
5036 sub check_diff_paths {
5037 my ($ra, $pfx, $rev, $mods) = @_;
5038 my %types;
5039 $pfx .= '/' if length $pfx;
5041 sub type_diff_paths {
5042 my ($ra, $types, $path, $rev) = @_;
5043 my @p = split m#/+#, $path;
5044 my $c = shift @p;
5045 unless (defined $types->{$c}) {
5046 $types->{$c} = $ra->check_path($c, $rev);
5048 while (@p) {
5049 $c .= '/' . shift @p;
5050 next if defined $types->{$c};
5051 $types->{$c} = $ra->check_path($c, $rev);
5055 foreach my $m (@$mods) {
5056 foreach my $f (qw/file_a file_b/) {
5057 next unless defined $m->{$f};
5058 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
5059 if (length $pfx.$dir && ! defined $types{$dir}) {
5060 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
5064 \%types;
5067 sub split_path {
5068 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
5071 sub repo_path {
5072 my ($self, $path) = @_;
5073 if (my $enc = $self->{pathnameencoding}) {
5074 require Encode;
5075 Encode::from_to($path, $enc, 'UTF-8');
5077 $self->{path_prefix}.(defined $path ? $path : '');
5080 sub url_path {
5081 my ($self, $path) = @_;
5082 if ($self->{url} =~ m#^https?://#) {
5083 $path =~ s!([^~a-zA-Z0-9_./-])!uc sprintf("%%%02x",ord($1))!eg;
5085 $self->{url} . '/' . $self->repo_path($path);
5088 sub rmdirs {
5089 my ($self) = @_;
5090 my $rm = $self->{rm};
5091 delete $rm->{''}; # we never delete the url we're tracking
5092 return unless %$rm;
5094 foreach (keys %$rm) {
5095 my @d = split m#/#, $_;
5096 my $c = shift @d;
5097 $rm->{$c} = 1;
5098 while (@d) {
5099 $c .= '/' . shift @d;
5100 $rm->{$c} = 1;
5103 delete $rm->{$self->{svn_path}};
5104 delete $rm->{''}; # we never delete the url we're tracking
5105 return unless %$rm;
5107 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
5108 $self->{tree_b});
5109 local $/ = "\0";
5110 while (<$fh>) {
5111 chomp;
5112 my @dn = split m#/#, $_;
5113 while (pop @dn) {
5114 delete $rm->{join '/', @dn};
5116 unless (%$rm) {
5117 close $fh;
5118 return;
5121 command_close_pipe($fh, $ctx);
5123 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
5124 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
5125 $self->close_directory($bat->{$d}, $p);
5126 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
5127 print "\tD+\t$d/\n" unless $::_q;
5128 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
5129 delete $bat->{$d};
5133 sub open_or_add_dir {
5134 my ($self, $full_path, $baton) = @_;
5135 my $t = $self->{types}->{$full_path};
5136 if (!defined $t) {
5137 die "$full_path not known in r$self->{r} or we have a bug!\n";
5140 no warnings 'once';
5141 # SVN::Node::none and SVN::Node::file are used only once,
5142 # so we're shutting up Perl's warnings about them.
5143 if ($t == $SVN::Node::none) {
5144 return $self->add_directory($full_path, $baton,
5145 undef, -1, $self->{pool});
5146 } elsif ($t == $SVN::Node::dir) {
5147 return $self->open_directory($full_path, $baton,
5148 $self->{r}, $self->{pool});
5149 } # no warnings 'once'
5150 print STDERR "$full_path already exists in repository at ",
5151 "r$self->{r} and it is not a directory (",
5152 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
5153 } # no warnings 'once'
5154 exit 1;
5157 sub ensure_path {
5158 my ($self, $path) = @_;
5159 my $bat = $self->{bat};
5160 my $repo_path = $self->repo_path($path);
5161 return $bat->{''} unless (length $repo_path);
5162 my @p = split m#/+#, $repo_path;
5163 my $c = shift @p;
5164 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
5165 while (@p) {
5166 my $c0 = $c;
5167 $c .= '/' . shift @p;
5168 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
5170 return $bat->{$c};
5173 # Subroutine to convert a globbing pattern to a regular expression.
5174 # From perl cookbook.
5175 sub glob2pat {
5176 my $globstr = shift;
5177 my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
5178 $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
5179 return '^' . $globstr . '$';
5182 sub check_autoprop {
5183 my ($self, $pattern, $properties, $file, $fbat) = @_;
5184 # Convert the globbing pattern to a regular expression.
5185 my $regex = glob2pat($pattern);
5186 # Check if the pattern matches the file name.
5187 if($file =~ m/($regex)/) {
5188 # Parse the list of properties to set.
5189 my @props = split(/;/, $properties);
5190 foreach my $prop (@props) {
5191 # Parse 'name=value' syntax and set the property.
5192 if ($prop =~ /([^=]+)=(.*)/) {
5193 my ($n,$v) = ($1,$2);
5194 for ($n, $v) {
5195 s/^\s+//; s/\s+$//;
5197 $self->change_file_prop($fbat, $n, $v);
5203 sub apply_autoprops {
5204 my ($self, $file, $fbat) = @_;
5205 my $conf_t = ${$self->{config}}{'config'};
5206 no warnings 'once';
5207 # Check [miscellany]/enable-auto-props in svn configuration.
5208 if (SVN::_Core::svn_config_get_bool(
5209 $conf_t,
5210 $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
5211 $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
5212 0)) {
5213 # Auto-props are enabled. Enumerate them to look for matches.
5214 my $callback = sub {
5215 $self->check_autoprop($_[0], $_[1], $file, $fbat);
5217 SVN::_Core::svn_config_enumerate(
5218 $conf_t,
5219 $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
5220 $callback);
5224 sub A {
5225 my ($self, $m) = @_;
5226 my ($dir, $file) = split_path($m->{file_b});
5227 my $pbat = $self->ensure_path($dir);
5228 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
5229 undef, -1);
5230 print "\tA\t$m->{file_b}\n" unless $::_q;
5231 $self->apply_autoprops($file, $fbat);
5232 $self->chg_file($fbat, $m);
5233 $self->close_file($fbat,undef,$self->{pool});
5236 sub C {
5237 my ($self, $m) = @_;
5238 my ($dir, $file) = split_path($m->{file_b});
5239 my $pbat = $self->ensure_path($dir);
5240 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
5241 $self->url_path($m->{file_a}), $self->{r});
5242 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
5243 $self->chg_file($fbat, $m);
5244 $self->close_file($fbat,undef,$self->{pool});
5247 sub delete_entry {
5248 my ($self, $path, $pbat) = @_;
5249 my $rpath = $self->repo_path($path);
5250 my ($dir, $file) = split_path($rpath);
5251 $self->{rm}->{$dir} = 1;
5252 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
5255 sub R {
5256 my ($self, $m) = @_;
5257 my ($dir, $file) = split_path($m->{file_b});
5258 my $pbat = $self->ensure_path($dir);
5259 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
5260 $self->url_path($m->{file_a}), $self->{r});
5261 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
5262 $self->apply_autoprops($file, $fbat);
5263 $self->chg_file($fbat, $m);
5264 $self->close_file($fbat,undef,$self->{pool});
5266 ($dir, $file) = split_path($m->{file_a});
5267 $pbat = $self->ensure_path($dir);
5268 $self->delete_entry($m->{file_a}, $pbat);
5271 sub M {
5272 my ($self, $m) = @_;
5273 my ($dir, $file) = split_path($m->{file_b});
5274 my $pbat = $self->ensure_path($dir);
5275 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
5276 $pbat,$self->{r},$self->{pool});
5277 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
5278 $self->chg_file($fbat, $m);
5279 $self->close_file($fbat,undef,$self->{pool});
5282 sub T { shift->M(@_) }
5284 sub change_file_prop {
5285 my ($self, $fbat, $pname, $pval) = @_;
5286 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
5289 sub change_dir_prop {
5290 my ($self, $pbat, $pname, $pval) = @_;
5291 $self->SUPER::change_dir_prop($pbat, $pname, $pval, $self->{pool});
5294 sub _chg_file_get_blob ($$$$) {
5295 my ($self, $fbat, $m, $which) = @_;
5296 my $fh = $::_repository->temp_acquire("git_blob_$which");
5297 if ($m->{"mode_$which"} =~ /^120/) {
5298 print $fh 'link ' or croak $!;
5299 $self->change_file_prop($fbat,'svn:special','*');
5300 } elsif ($m->{mode_a} =~ /^120/ && $m->{"mode_$which"} !~ /^120/) {
5301 $self->change_file_prop($fbat,'svn:special',undef);
5303 my $blob = $m->{"sha1_$which"};
5304 return ($fh,) if ($blob =~ /^0{40}$/);
5305 my $size = $::_repository->cat_blob($blob, $fh);
5306 croak "Failed to read object $blob" if ($size < 0);
5307 $fh->flush == 0 or croak $!;
5308 seek $fh, 0, 0 or croak $!;
5310 my $exp = ::md5sum($fh);
5311 seek $fh, 0, 0 or croak $!;
5312 return ($fh, $exp);
5315 sub chg_file {
5316 my ($self, $fbat, $m) = @_;
5317 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
5318 $self->change_file_prop($fbat,'svn:executable','*');
5319 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
5320 $self->change_file_prop($fbat,'svn:executable',undef);
5322 my ($fh_a, $exp_a) = _chg_file_get_blob $self, $fbat, $m, 'a';
5323 my ($fh_b, $exp_b) = _chg_file_get_blob $self, $fbat, $m, 'b';
5324 my $pool = SVN::Pool->new;
5325 my $atd = $self->apply_textdelta($fbat, $exp_a, $pool);
5326 if (-s $fh_a) {
5327 my $txstream = SVN::TxDelta::new ($fh_a, $fh_b, $pool);
5328 my $res = SVN::TxDelta::send_txstream($txstream, @$atd, $pool);
5329 if (defined $res) {
5330 die "Unexpected result from send_txstream: $res\n",
5331 "(SVN::Core::VERSION: $SVN::Core::VERSION)\n";
5333 } else {
5334 my $got = SVN::TxDelta::send_stream($fh_b, @$atd, $pool);
5335 die "Checksum mismatch\nexpected: $exp_b\ngot: $got\n"
5336 if ($got ne $exp_b);
5338 Git::temp_release($fh_b, 1);
5339 Git::temp_release($fh_a, 1);
5340 $pool->clear;
5343 sub D {
5344 my ($self, $m) = @_;
5345 my ($dir, $file) = split_path($m->{file_b});
5346 my $pbat = $self->ensure_path($dir);
5347 print "\tD\t$m->{file_b}\n" unless $::_q;
5348 $self->delete_entry($m->{file_b}, $pbat);
5351 sub close_edit {
5352 my ($self) = @_;
5353 my ($p,$bat) = ($self->{pool}, $self->{bat});
5354 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
5355 next if $_ eq '';
5356 $self->close_directory($bat->{$_}, $p);
5358 $self->close_directory($bat->{''}, $p);
5359 $self->SUPER::close_edit($p);
5360 $p->clear;
5363 sub abort_edit {
5364 my ($self) = @_;
5365 $self->SUPER::abort_edit($self->{pool});
5368 sub DESTROY {
5369 my $self = shift;
5370 $self->SUPER::DESTROY(@_);
5371 $self->{pool}->clear;
5374 # this drives the editor
5375 sub apply_diff {
5376 my ($self) = @_;
5377 my $mods = $self->{mods};
5378 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
5379 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
5380 my $f = $m->{chg};
5381 if (defined $o{$f}) {
5382 $self->$f($m);
5383 } else {
5384 fatal("Invalid change type: $f");
5388 if (defined($self->{mergeinfo})) {
5389 $self->change_dir_prop($self->{bat}{''}, "svn:mergeinfo",
5390 $self->{mergeinfo});
5392 $self->rmdirs if $_rmdir;
5393 if (@$mods == 0) {
5394 $self->abort_edit;
5395 } else {
5396 $self->close_edit;
5398 return scalar @$mods;
5401 package Git::SVN::Ra;
5402 use vars qw/@ISA $config_dir $_ignore_refs_regex $_log_window_size/;
5403 use strict;
5404 use warnings;
5405 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
5407 BEGIN {
5408 # enforce temporary pool usage for some simple functions
5409 no strict 'refs';
5410 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root
5411 get_file/) {
5412 my $SUPER = "SUPER::$f";
5413 *$f = sub {
5414 my $self = shift;
5415 my $pool = SVN::Pool->new;
5416 my @ret = $self->$SUPER(@_,$pool);
5417 $pool->clear;
5418 wantarray ? @ret : $ret[0];
5423 sub _auth_providers () {
5425 SVN::Client::get_simple_provider(),
5426 SVN::Client::get_ssl_server_trust_file_provider(),
5427 SVN::Client::get_simple_prompt_provider(
5428 \&Git::SVN::Prompt::simple, 2),
5429 SVN::Client::get_ssl_client_cert_file_provider(),
5430 SVN::Client::get_ssl_client_cert_prompt_provider(
5431 \&Git::SVN::Prompt::ssl_client_cert, 2),
5432 SVN::Client::get_ssl_client_cert_pw_file_provider(),
5433 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
5434 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
5435 SVN::Client::get_username_provider(),
5436 SVN::Client::get_ssl_server_trust_prompt_provider(
5437 \&Git::SVN::Prompt::ssl_server_trust),
5438 SVN::Client::get_username_prompt_provider(
5439 \&Git::SVN::Prompt::username, 2)
5443 sub escape_uri_only {
5444 my ($uri) = @_;
5445 my @tmp;
5446 foreach (split m{/}, $uri) {
5447 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
5448 push @tmp, $_;
5450 join('/', @tmp);
5453 sub escape_url {
5454 my ($url) = @_;
5455 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
5456 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
5457 $url = "$scheme://$domain$uri";
5459 $url;
5462 sub new {
5463 my ($class, $url) = @_;
5464 $url =~ s!/+$!!;
5465 return $RA if ($RA && $RA->{url} eq $url);
5467 ::_req_svn();
5469 SVN::_Core::svn_config_ensure($config_dir, undef);
5470 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
5471 my $config = SVN::Core::config_get_config($config_dir);
5472 $RA = undef;
5473 my $dont_store_passwords = 1;
5474 my $conf_t = ${$config}{'config'};
5476 no warnings 'once';
5477 # The usage of $SVN::_Core::SVN_CONFIG_* variables
5478 # produces warnings that variables are used only once.
5479 # I had not found the better way to shut them up, so
5480 # the warnings of type 'once' are disabled in this block.
5481 if (SVN::_Core::svn_config_get_bool($conf_t,
5482 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
5483 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
5484 1) == 0) {
5485 SVN::_Core::svn_auth_set_parameter($baton,
5486 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
5487 bless (\$dont_store_passwords, "_p_void"));
5489 if (SVN::_Core::svn_config_get_bool($conf_t,
5490 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
5491 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
5492 1) == 0) {
5493 $Git::SVN::Prompt::_no_auth_cache = 1;
5495 } # no warnings 'once'
5496 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
5497 config => $config,
5498 pool => SVN::Pool->new,
5499 auth_provider_callbacks => $callbacks);
5500 $self->{url} = $url;
5501 $self->{svn_path} = $url;
5502 $self->{repos_root} = $self->get_repos_root;
5503 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
5504 $self->{cache} = { check_path => { r => 0, data => {} },
5505 get_dir => { r => 0, data => {} } };
5506 $RA = bless $self, $class;
5509 sub check_path {
5510 my ($self, $path, $r) = @_;
5511 my $cache = $self->{cache}->{check_path};
5512 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
5513 return $cache->{data}->{$path};
5515 my $pool = SVN::Pool->new;
5516 my $t = $self->SUPER::check_path($path, $r, $pool);
5517 $pool->clear;
5518 if ($r != $cache->{r}) {
5519 %{$cache->{data}} = ();
5520 $cache->{r} = $r;
5522 $cache->{data}->{$path} = $t;
5525 sub get_dir {
5526 my ($self, $dir, $r) = @_;
5527 my $cache = $self->{cache}->{get_dir};
5528 if ($r == $cache->{r}) {
5529 if (my $x = $cache->{data}->{$dir}) {
5530 return wantarray ? @$x : $x->[0];
5533 my $pool = SVN::Pool->new;
5534 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
5535 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
5536 $pool->clear;
5537 if ($r != $cache->{r}) {
5538 %{$cache->{data}} = ();
5539 $cache->{r} = $r;
5541 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
5542 wantarray ? (\%dirents, $r, $props) : \%dirents;
5545 sub DESTROY {
5546 # do not call the real DESTROY since we store ourselves in $RA
5549 # get_log(paths, start, end, limit,
5550 # discover_changed_paths, strict_node_history, receiver)
5551 sub get_log {
5552 my ($self, @args) = @_;
5553 my $pool = SVN::Pool->new;
5555 # svn_log_changed_path_t objects passed to get_log are likely to be
5556 # overwritten even if only the refs are copied to an external variable,
5557 # so we should dup the structures in their entirety. Using an
5558 # externally passed pool (instead of our temporary and quickly cleared
5559 # pool in Git::SVN::Ra) does not help matters at all...
5560 my $receiver = pop @args;
5561 my $prefix = "/".$self->{svn_path};
5562 $prefix =~ s#/+($)##;
5563 my $prefix_regex = qr#^\Q$prefix\E#;
5564 push(@args, sub {
5565 my ($paths) = $_[0];
5566 return &$receiver(@_) unless $paths;
5567 $_[0] = ();
5568 foreach my $p (keys %$paths) {
5569 my $i = $paths->{$p};
5570 # Make path relative to our url, not repos_root
5571 $p =~ s/$prefix_regex//;
5572 my %s = map { $_ => $i->$_; }
5573 qw/copyfrom_path copyfrom_rev action/;
5574 if ($s{'copyfrom_path'}) {
5575 $s{'copyfrom_path'} =~ s/$prefix_regex//;
5577 $_[0]{$p} = \%s;
5579 &$receiver(@_);
5583 # the limit parameter was not supported in SVN 1.1.x, so we
5584 # drop it. Therefore, the receiver callback passed to it
5585 # is made aware of this limitation by being wrapped if
5586 # the limit passed to is being wrapped.
5587 if ($SVN::Core::VERSION le '1.2.0') {
5588 my $limit = splice(@args, 3, 1);
5589 if ($limit > 0) {
5590 my $receiver = pop @args;
5591 push(@args, sub { &$receiver(@_) if (--$limit >= 0) });
5594 my $ret = $self->SUPER::get_log(@args, $pool);
5595 $pool->clear;
5596 $ret;
5599 sub trees_match {
5600 my ($self, $url1, $rev1, $url2, $rev2) = @_;
5601 my $ctx = SVN::Client->new(auth => _auth_providers);
5602 my $out = IO::File->new_tmpfile;
5604 # older SVN (1.1.x) doesn't take $pool as the last parameter for
5605 # $ctx->diff(), so we'll create a default one
5606 my $pool = SVN::Pool->new_default_sub;
5608 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
5609 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
5610 $out->flush;
5611 my $ret = (($out->stat)[7] == 0);
5612 close $out or croak $!;
5614 $ret;
5617 sub get_commit_editor {
5618 my ($self, $log, $cb, $pool) = @_;
5619 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
5620 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
5623 sub gs_do_update {
5624 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
5625 my $new = ($rev_a == $rev_b);
5626 my $path = $gs->{path};
5628 if ($new && -e $gs->{index}) {
5629 unlink $gs->{index} or die
5630 "Couldn't unlink index: $gs->{index}: $!\n";
5632 my $pool = SVN::Pool->new;
5633 $editor->set_path_strip($path);
5634 my (@pc) = split m#/#, $path;
5635 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
5636 1, $editor, $pool);
5637 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
5639 # Since we can't rely on svn_ra_reparent being available, we'll
5640 # just have to do some magic with set_path to make it so
5641 # we only want a partial path.
5642 my $sp = '';
5643 my $final = join('/', @pc);
5644 while (@pc) {
5645 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
5646 $sp .= '/' if length $sp;
5647 $sp .= shift @pc;
5649 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
5651 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
5653 $reporter->finish_report($pool);
5654 $pool->clear;
5655 $editor->{git_commit_ok};
5658 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
5659 # svn_ra_reparent didn't work before 1.4)
5660 sub gs_do_switch {
5661 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
5662 my $path = $gs->{path};
5663 my $pool = SVN::Pool->new;
5665 my $full_url = $self->{url};
5666 my $old_url = $full_url;
5667 $full_url .= '/' . $path if length $path;
5668 my ($ra, $reparented);
5670 if ($old_url =~ m#^svn(\+ssh)?://# ||
5671 ($full_url =~ m#^https?://# &&
5672 escape_url($full_url) ne $full_url)) {
5673 $_[0] = undef;
5674 $self = undef;
5675 $RA = undef;
5676 $ra = Git::SVN::Ra->new($full_url);
5677 $ra_invalid = 1;
5678 } elsif ($old_url ne $full_url) {
5679 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url, $pool);
5680 $self->{url} = $full_url;
5681 $reparented = 1;
5684 $ra ||= $self;
5685 $url_b = escape_url($url_b);
5686 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
5687 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
5688 $reporter->set_path('', $rev_a, 0, @lock, $pool);
5689 $reporter->finish_report($pool);
5691 if ($reparented) {
5692 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
5693 $self->{url} = $old_url;
5696 $pool->clear;
5697 $editor->{git_commit_ok};
5700 sub longest_common_path {
5701 my ($gsv, $globs) = @_;
5702 my %common;
5703 my $common_max = scalar @$gsv;
5705 foreach my $gs (@$gsv) {
5706 my @tmp = split m#/#, $gs->{path};
5707 my $p = '';
5708 foreach (@tmp) {
5709 $p .= length($p) ? "/$_" : $_;
5710 $common{$p} ||= 0;
5711 $common{$p}++;
5714 $globs ||= [];
5715 $common_max += scalar @$globs;
5716 foreach my $glob (@$globs) {
5717 my @tmp = split m#/#, $glob->{path}->{left};
5718 my $p = '';
5719 foreach (@tmp) {
5720 $p .= length($p) ? "/$_" : $_;
5721 $common{$p} ||= 0;
5722 $common{$p}++;
5726 my $longest_path = '';
5727 foreach (sort {length $b <=> length $a} keys %common) {
5728 if ($common{$_} == $common_max) {
5729 $longest_path = $_;
5730 last;
5733 $longest_path;
5736 sub gs_fetch_loop_common {
5737 my ($self, $base, $head, $gsv, $globs) = @_;
5738 return if ($base > $head);
5739 my $inc = $_log_window_size;
5740 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
5741 my $longest_path = longest_common_path($gsv, $globs);
5742 my $ra_url = $self->{url};
5743 my $find_trailing_edge;
5744 while (1) {
5745 my %revs;
5746 my $err;
5747 my $err_handler = $SVN::Error::handler;
5748 $SVN::Error::handler = sub {
5749 ($err) = @_;
5750 skip_unknown_revs($err);
5752 sub _cb {
5753 my ($paths, $r, $author, $date, $log) = @_;
5754 [ $paths,
5755 { author => $author, date => $date, log => $log } ];
5757 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
5758 sub { $revs{$_[1]} = _cb(@_) });
5759 if ($err) {
5760 print "Checked through r$max\r";
5761 } else {
5762 $find_trailing_edge = 1;
5764 if ($err and $find_trailing_edge) {
5765 print STDERR "Path '$longest_path' ",
5766 "was probably deleted:\n",
5767 $err->expanded_message,
5768 "\nWill attempt to follow ",
5769 "revisions r$min .. r$max ",
5770 "committed before the deletion\n";
5771 my $hi = $max;
5772 while (--$hi >= $min) {
5773 my $ok;
5774 $self->get_log([$longest_path], $min, $hi,
5775 0, 1, 1, sub {
5776 $ok = $_[1];
5777 $revs{$_[1]} = _cb(@_) });
5778 if ($ok) {
5779 print STDERR "r$min .. r$ok OK\n";
5780 last;
5783 $find_trailing_edge = 0;
5785 $SVN::Error::handler = $err_handler;
5787 my %exists = map { $_->{path} => $_ } @$gsv;
5788 foreach my $r (sort {$a <=> $b} keys %revs) {
5789 my ($paths, $logged) = @{$revs{$r}};
5791 foreach my $gs ($self->match_globs(\%exists, $paths,
5792 $globs, $r)) {
5793 if ($gs->rev_map_max >= $r) {
5794 next;
5796 next unless $gs->match_paths($paths, $r);
5797 $gs->{logged_rev_props} = $logged;
5798 if (my $last_commit = $gs->last_commit) {
5799 $gs->assert_index_clean($last_commit);
5801 my $log_entry = $gs->do_fetch($paths, $r);
5802 if ($log_entry) {
5803 $gs->do_git_commit($log_entry);
5805 $INDEX_FILES{$gs->{index}} = 1;
5807 foreach my $g (@$globs) {
5808 my $k = "svn-remote.$g->{remote}." .
5809 "$g->{t}-maxRev";
5810 Git::SVN::tmp_config($k, $r);
5812 if ($ra_invalid) {
5813 $_[0] = undef;
5814 $self = undef;
5815 $RA = undef;
5816 $self = Git::SVN::Ra->new($ra_url);
5817 $ra_invalid = undef;
5820 # pre-fill the .rev_db since it'll eventually get filled in
5821 # with '0' x40 if something new gets committed
5822 foreach my $gs (@$gsv) {
5823 next if $gs->rev_map_max >= $max;
5824 next if defined $gs->rev_map_get($max);
5825 $gs->rev_map_set($max, 0 x40);
5827 foreach my $g (@$globs) {
5828 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
5829 Git::SVN::tmp_config($k, $max);
5831 last if $max >= $head;
5832 $min = $max + 1;
5833 $max += $inc;
5834 $max = $head if ($max > $head);
5836 Git::SVN::gc();
5839 sub get_dir_globbed {
5840 my ($self, $left, $depth, $r) = @_;
5842 my @x = eval { $self->get_dir($left, $r) };
5843 return unless scalar @x == 3;
5844 my $dirents = $x[0];
5845 my @finalents;
5846 foreach my $de (keys %$dirents) {
5847 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
5848 if ($depth > 1) {
5849 my @args = ("$left/$de", $depth - 1, $r);
5850 foreach my $dir ($self->get_dir_globbed(@args)) {
5851 push @finalents, "$de/$dir";
5853 } else {
5854 push @finalents, $de;
5857 @finalents;
5860 # return value: 0 -- don't ignore, 1 -- ignore
5861 sub is_ref_ignored {
5862 my ($g, $p) = @_;
5863 my $refname = $g->{ref}->full_path($p);
5864 return 1 if defined($g->{ignore_refs_regex}) &&
5865 $refname =~ m!$g->{ignore_refs_regex}!;
5866 return 0 unless defined($_ignore_refs_regex);
5867 return 1 if $refname =~ m!$_ignore_refs_regex!o;
5868 return 0;
5871 sub match_globs {
5872 my ($self, $exists, $paths, $globs, $r) = @_;
5874 sub get_dir_check {
5875 my ($self, $exists, $g, $r) = @_;
5877 my @dirs = $self->get_dir_globbed($g->{path}->{left},
5878 $g->{path}->{depth},
5879 $r);
5881 foreach my $de (@dirs) {
5882 my $p = $g->{path}->full_path($de);
5883 next if $exists->{$p};
5884 next if (length $g->{path}->{right} &&
5885 ($self->check_path($p, $r) !=
5886 $SVN::Node::dir));
5887 next unless $p =~ /$g->{path}->{regex}/;
5888 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
5889 $g->{ref}->full_path($de), 1);
5892 foreach my $g (@$globs) {
5893 if (my $path = $paths->{"/$g->{path}->{left}"}) {
5894 if ($path->{action} =~ /^[AR]$/) {
5895 get_dir_check($self, $exists, $g, $r);
5898 foreach (keys %$paths) {
5899 if (/$g->{path}->{left_regex}/ &&
5900 !/$g->{path}->{regex}/) {
5901 next if $paths->{$_}->{action} !~ /^[AR]$/;
5902 get_dir_check($self, $exists, $g, $r);
5904 next unless /$g->{path}->{regex}/;
5905 my $p = $1;
5906 my $pathname = $g->{path}->full_path($p);
5907 next if is_ref_ignored($g, $p);
5908 next if $exists->{$pathname};
5909 next if ($self->check_path($pathname, $r) !=
5910 $SVN::Node::dir);
5911 $exists->{$pathname} = Git::SVN->init(
5912 $self->{url}, $pathname, undef,
5913 $g->{ref}->full_path($p), 1);
5915 my $c = '';
5916 foreach (split m#/#, $g->{path}->{left}) {
5917 $c .= "/$_";
5918 next unless ($paths->{$c} &&
5919 ($paths->{$c}->{action} =~ /^[AR]$/));
5920 get_dir_check($self, $exists, $g, $r);
5923 values %$exists;
5926 sub minimize_url {
5927 my ($self) = @_;
5928 return $self->{url} if ($self->{url} eq $self->{repos_root});
5929 my $url = $self->{repos_root};
5930 my @components = split(m!/!, $self->{svn_path});
5931 my $c = '';
5932 do {
5933 $url .= "/$c" if length $c;
5934 eval {
5935 my $ra = (ref $self)->new($url);
5936 my $latest = $ra->get_latest_revnum;
5937 $ra->get_log("", $latest, 0, 1, 0, 1, sub {});
5939 } while ($@ && ($c = shift @components));
5940 $url;
5943 sub can_do_switch {
5944 my $self = shift;
5945 unless (defined $can_do_switch) {
5946 my $pool = SVN::Pool->new;
5947 my $rep = eval {
5948 $self->do_switch(1, '', 0, $self->{url},
5949 SVN::Delta::Editor->new, $pool);
5951 if ($@) {
5952 $can_do_switch = 0;
5953 } else {
5954 $rep->abort_report($pool);
5955 $can_do_switch = 1;
5957 $pool->clear;
5959 $can_do_switch;
5962 sub skip_unknown_revs {
5963 my ($err) = @_;
5964 my $errno = $err->apr_err();
5965 # Maybe the branch we're tracking didn't
5966 # exist when the repo started, so it's
5967 # not an error if it doesn't, just continue
5969 # Wonderfully consistent library, eh?
5970 # 160013 - svn:// and file://
5971 # 175002 - http(s)://
5972 # 175007 - http(s):// (this repo required authorization, too...)
5973 # More codes may be discovered later...
5974 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
5975 my $err_key = $err->expanded_message;
5976 # revision numbers change every time, filter them out
5977 $err_key =~ s/\d+/\0/g;
5978 $err_key = "$errno\0$err_key";
5979 unless ($ignored_err{$err_key}) {
5980 warn "W: Ignoring error from SVN, path probably ",
5981 "does not exist: ($errno): ",
5982 $err->expanded_message,"\n";
5983 warn "W: Do not be alarmed at the above message ",
5984 "git-svn is just searching aggressively for ",
5985 "old history.\n",
5986 "This may take a while on large repositories\n";
5987 $ignored_err{$err_key} = 1;
5989 return;
5991 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
5994 package Git::SVN::Log;
5995 use strict;
5996 use warnings;
5997 use POSIX qw/strftime/;
5998 use Time::Local;
5999 use constant commit_log_separator => ('-' x 72) . "\n";
6000 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
6001 %rusers $show_commit $incremental/;
6002 my $l_fmt;
6004 sub cmt_showable {
6005 my ($c) = @_;
6006 return 1 if defined $c->{r};
6008 # big commit message got truncated by the 16k pretty buffer in rev-list
6009 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
6010 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
6011 @{$c->{l}} = ();
6012 my @log = command(qw/cat-file commit/, $c->{c});
6014 # shift off the headers
6015 shift @log while ($log[0] ne '');
6016 shift @log;
6018 # TODO: make $c->{l} not have a trailing newline in the future
6019 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
6021 (undef, $c->{r}, undef) = ::extract_metadata(
6022 (grep(/^git-svn-id: /, @log))[-1]);
6024 return defined $c->{r};
6027 sub log_use_color {
6028 return $color || Git->repository->get_colorbool('color.diff');
6031 sub git_svn_log_cmd {
6032 my ($r_min, $r_max, @args) = @_;
6033 my $head = 'HEAD';
6034 my (@files, @log_opts);
6035 foreach my $x (@args) {
6036 if ($x eq '--' || @files) {
6037 push @files, $x;
6038 } else {
6039 if (::verify_ref("$x^0")) {
6040 $head = $x;
6041 } else {
6042 push @log_opts, $x;
6047 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
6048 $gs ||= Git::SVN->_new;
6049 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
6050 $gs->refname);
6051 push @cmd, '-r' unless $non_recursive;
6052 push @cmd, qw/--raw --name-status/ if $verbose;
6053 push @cmd, '--color' if log_use_color();
6054 push @cmd, @log_opts;
6055 if (defined $r_max && $r_max == $r_min) {
6056 push @cmd, '--max-count=1';
6057 if (my $c = $gs->rev_map_get($r_max)) {
6058 push @cmd, $c;
6060 } elsif (defined $r_max) {
6061 if ($r_max < $r_min) {
6062 ($r_min, $r_max) = ($r_max, $r_min);
6064 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
6065 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
6066 # If there are no commits in the range, both $c_max and $c_min
6067 # will be undefined. If there is at least 1 commit in the
6068 # range, both will be defined.
6069 return () if !defined $c_min || !defined $c_max;
6070 if ($c_min eq $c_max) {
6071 push @cmd, '--max-count=1', $c_min;
6072 } else {
6073 push @cmd, '--boundary', "$c_min..$c_max";
6076 return (@cmd, @files);
6079 # adapted from pager.c
6080 sub config_pager {
6081 if (! -t *STDOUT) {
6082 $ENV{GIT_PAGER_IN_USE} = 'false';
6083 $pager = undef;
6084 return;
6086 chomp($pager = command_oneline(qw(var GIT_PAGER)));
6087 if ($pager eq 'cat') {
6088 $pager = undef;
6090 $ENV{GIT_PAGER_IN_USE} = defined($pager);
6093 sub run_pager {
6094 return unless defined $pager;
6095 pipe my ($rfd, $wfd) or return;
6096 defined(my $pid = fork) or ::fatal "Can't fork: $!";
6097 if (!$pid) {
6098 open STDOUT, '>&', $wfd or
6099 ::fatal "Can't redirect to stdout: $!";
6100 return;
6102 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
6103 $ENV{LESS} ||= 'FRSX';
6104 exec $pager or ::fatal "Can't run pager: $! ($pager)";
6107 sub format_svn_date {
6108 # some systmes don't handle or mishandle %z, so be creative.
6109 my $t = shift || time;
6110 my $gm = timelocal(gmtime($t));
6111 my $sign = qw( + + - )[ $t <=> $gm ];
6112 my $gmoff = sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
6113 return strftime("%Y-%m-%d %H:%M:%S $gmoff (%a, %d %b %Y)", localtime($t));
6116 sub parse_git_date {
6117 my ($t, $tz) = @_;
6118 # Date::Parse isn't in the standard Perl distro :(
6119 if ($tz =~ s/^\+//) {
6120 $t += tz_to_s_offset($tz);
6121 } elsif ($tz =~ s/^\-//) {
6122 $t -= tz_to_s_offset($tz);
6124 return $t;
6127 sub set_local_timezone {
6128 if (defined $TZ) {
6129 $ENV{TZ} = $TZ;
6130 } else {
6131 delete $ENV{TZ};
6135 sub tz_to_s_offset {
6136 my ($tz) = @_;
6137 $tz =~ s/(\d\d)$//;
6138 return ($1 * 60) + ($tz * 3600);
6141 sub get_author_info {
6142 my ($dest, $author, $t, $tz) = @_;
6143 $author =~ s/(?:^\s*|\s*$)//g;
6144 $dest->{a_raw} = $author;
6145 my $au;
6146 if ($::_authors) {
6147 $au = $rusers{$author} || undef;
6149 if (!$au) {
6150 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
6152 $dest->{t} = $t;
6153 $dest->{tz} = $tz;
6154 $dest->{a} = $au;
6155 $dest->{t_utc} = parse_git_date($t, $tz);
6158 sub process_commit {
6159 my ($c, $r_min, $r_max, $defer) = @_;
6160 if (defined $r_min && defined $r_max) {
6161 if ($r_min == $c->{r} && $r_min == $r_max) {
6162 show_commit($c);
6163 return 0;
6165 return 1 if $r_min == $r_max;
6166 if ($r_min < $r_max) {
6167 # we need to reverse the print order
6168 return 0 if (defined $limit && --$limit < 0);
6169 push @$defer, $c;
6170 return 1;
6172 if ($r_min != $r_max) {
6173 return 1 if ($r_min < $c->{r});
6174 return 1 if ($r_max > $c->{r});
6177 return 0 if (defined $limit && --$limit < 0);
6178 show_commit($c);
6179 return 1;
6182 sub show_commit {
6183 my $c = shift;
6184 if ($oneline) {
6185 my $x = "\n";
6186 if (my $l = $c->{l}) {
6187 while ($l->[0] =~ /^\s*$/) { shift @$l }
6188 $x = $l->[0];
6190 $l_fmt ||= 'A' . length($c->{r});
6191 print 'r',pack($l_fmt, $c->{r}),' | ';
6192 print "$c->{c} | " if $show_commit;
6193 print $x;
6194 } else {
6195 show_commit_normal($c);
6199 sub show_commit_changed_paths {
6200 my ($c) = @_;
6201 return unless $c->{changed};
6202 print "Changed paths:\n", @{$c->{changed}};
6205 sub show_commit_normal {
6206 my ($c) = @_;
6207 print commit_log_separator, "r$c->{r} | ";
6208 print "$c->{c} | " if $show_commit;
6209 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
6210 my $nr_line = 0;
6212 if (my $l = $c->{l}) {
6213 while ($l->[$#$l] eq "\n" && $#$l > 0
6214 && $l->[($#$l - 1)] eq "\n") {
6215 pop @$l;
6217 $nr_line = scalar @$l;
6218 if (!$nr_line) {
6219 print "1 line\n\n\n";
6220 } else {
6221 if ($nr_line == 1) {
6222 $nr_line = '1 line';
6223 } else {
6224 $nr_line .= ' lines';
6226 print $nr_line, "\n";
6227 show_commit_changed_paths($c);
6228 print "\n";
6229 print $_ foreach @$l;
6231 } else {
6232 print "1 line\n";
6233 show_commit_changed_paths($c);
6234 print "\n";
6237 foreach my $x (qw/raw stat diff/) {
6238 if ($c->{$x}) {
6239 print "\n";
6240 print $_ foreach @{$c->{$x}}
6245 sub cmd_show_log {
6246 my (@args) = @_;
6247 my ($r_min, $r_max);
6248 my $r_last = -1; # prevent dupes
6249 set_local_timezone();
6250 if (defined $::_revision) {
6251 if ($::_revision =~ /^(\d+):(\d+)$/) {
6252 ($r_min, $r_max) = ($1, $2);
6253 } elsif ($::_revision =~ /^\d+$/) {
6254 $r_min = $r_max = $::_revision;
6255 } else {
6256 ::fatal "-r$::_revision is not supported, use ",
6257 "standard 'git log' arguments instead";
6261 config_pager();
6262 @args = git_svn_log_cmd($r_min, $r_max, @args);
6263 if (!@args) {
6264 print commit_log_separator unless $incremental || $oneline;
6265 return;
6267 my $log = command_output_pipe(@args);
6268 run_pager();
6269 my (@k, $c, $d, $stat);
6270 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
6271 while (<$log>) {
6272 if (/^${esc_color}commit (?:- )?($::sha1_short)/o) {
6273 my $cmt = $1;
6274 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
6275 $r_last = $c->{r};
6276 process_commit($c, $r_min, $r_max, \@k) or
6277 goto out;
6279 $d = undef;
6280 $c = { c => $cmt };
6281 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
6282 get_author_info($c, $1, $2, $3);
6283 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
6284 # ignore
6285 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
6286 push @{$c->{raw}}, $_;
6287 } elsif (/^${esc_color}[ACRMDT]\t/) {
6288 # we could add $SVN->{svn_path} here, but that requires
6289 # remote access at the moment (repo_path_split)...
6290 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
6291 push @{$c->{changed}}, $_;
6292 } elsif (/^${esc_color}diff /o) {
6293 $d = 1;
6294 push @{$c->{diff}}, $_;
6295 } elsif ($d) {
6296 push @{$c->{diff}}, $_;
6297 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
6298 $esc_color*[\+\-]*$esc_color$/x) {
6299 $stat = 1;
6300 push @{$c->{stat}}, $_;
6301 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
6302 push @{$c->{stat}}, $_;
6303 $stat = undef;
6304 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
6305 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
6306 } elsif (s/^${esc_color} //o) {
6307 push @{$c->{l}}, $_;
6310 if ($c && defined $c->{r} && $c->{r} != $r_last) {
6311 $r_last = $c->{r};
6312 process_commit($c, $r_min, $r_max, \@k);
6314 if (@k) {
6315 ($r_min, $r_max) = ($r_max, $r_min);
6316 process_commit($_, $r_min, $r_max) foreach reverse @k;
6318 out:
6319 close $log;
6320 print commit_log_separator unless $incremental || $oneline;
6323 sub cmd_blame {
6324 my $path = pop;
6326 config_pager();
6327 run_pager();
6329 my ($fh, $ctx, $rev);
6331 if ($_git_format) {
6332 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
6333 while (my $line = <$fh>) {
6334 if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
6335 # Uncommitted edits show up as a rev ID of
6336 # all zeros, which we can't look up with
6337 # cmt_metadata
6338 if ($1 !~ /^0+$/) {
6339 (undef, $rev, undef) =
6340 ::cmt_metadata($1);
6341 $rev = '0' if (!$rev);
6342 } else {
6343 $rev = '0';
6345 $rev = sprintf('%-10s', $rev);
6346 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
6348 print $line;
6350 } else {
6351 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
6352 '--', $path);
6353 my ($sha1);
6354 my %authors;
6355 my @buffer;
6356 my %dsha; #distinct sha keys
6358 while (my $line = <$fh>) {
6359 push @buffer, $line;
6360 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
6361 $dsha{$1} = 1;
6365 my $s2r = ::cmt_sha2rev_batch([keys %dsha]);
6367 foreach my $line (@buffer) {
6368 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
6369 $rev = $s2r->{$1};
6370 $rev = '0' if (!$rev)
6372 elsif ($line =~ /^author (.*)/) {
6373 $authors{$rev} = $1;
6374 $authors{$rev} =~ s/\s/_/g;
6376 elsif ($line =~ /^\t(.*)$/) {
6377 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
6381 command_close_pipe($fh, $ctx);
6384 package Git::SVN::Migration;
6385 # these version numbers do NOT correspond to actual version numbers
6386 # of git nor git-svn. They are just relative.
6388 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
6390 # v1 layout: .git/$id/info/url, refs/remotes/$id
6392 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
6394 # v3 layout: .git/svn/$id, refs/remotes/$id
6395 # - info/url may remain for backwards compatibility
6396 # - this is what we migrate up to this layout automatically,
6397 # - this will be used by git svn init on single branches
6398 # v3.1 layout (auto migrated):
6399 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
6400 # for backwards compatibility
6402 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
6403 # - this is only created for newly multi-init-ed
6404 # repositories. Similar in spirit to the
6405 # --use-separate-remotes option in git-clone (now default)
6406 # - we do not automatically migrate to this (following
6407 # the example set by core git)
6409 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
6410 # - newer, more-efficient format that uses 24-bytes per record
6411 # with no filler space.
6412 # - use xxd -c24 < .rev_map.$UUID to view and debug
6413 # - This is a one-way migration, repositories updated to the
6414 # new format will not be able to use old git-svn without
6415 # rebuilding the .rev_db. Rebuilding the rev_db is not
6416 # possible if noMetadata or useSvmProps are set; but should
6417 # be no problem for users that use the (sensible) defaults.
6418 use strict;
6419 use warnings;
6420 use Carp qw/croak/;
6421 use File::Path qw/mkpath/;
6422 use File::Basename qw/dirname basename/;
6423 use vars qw/$_minimize/;
6425 sub migrate_from_v0 {
6426 my $git_dir = $ENV{GIT_DIR};
6427 return undef unless -d $git_dir;
6428 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
6429 my $migrated = 0;
6430 while (<$fh>) {
6431 chomp;
6432 my ($id, $orig_ref) = ($_, $_);
6433 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
6434 next unless -f "$git_dir/$id/info/url";
6435 my $new_ref = "refs/remotes/$id";
6436 if (::verify_ref("$new_ref^0")) {
6437 print STDERR "W: $orig_ref is probably an old ",
6438 "branch used by an ancient version of ",
6439 "git-svn.\n",
6440 "However, $new_ref also exists.\n",
6441 "We will not be able ",
6442 "to use this branch until this ",
6443 "ambiguity is resolved.\n";
6444 next;
6446 print STDERR "Migrating from v0 layout...\n" if !$migrated;
6447 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
6448 command_noisy('update-ref', $new_ref, $orig_ref);
6449 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
6450 $migrated++;
6452 command_close_pipe($fh, $ctx);
6453 print STDERR "Done migrating from v0 layout...\n" if $migrated;
6454 $migrated;
6457 sub migrate_from_v1 {
6458 my $git_dir = $ENV{GIT_DIR};
6459 my $migrated = 0;
6460 return $migrated unless -d $git_dir;
6461 my $svn_dir = "$git_dir/svn";
6463 # just in case somebody used 'svn' as their $id at some point...
6464 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
6466 print STDERR "Migrating from a git-svn v1 layout...\n";
6467 mkpath([$svn_dir]);
6468 print STDERR "Data from a previous version of git-svn exists, but\n\t",
6469 "$svn_dir\n\t(required for this version ",
6470 "($::VERSION) of git-svn) does not exist.\n";
6471 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
6472 while (<$fh>) {
6473 my $x = $_;
6474 next unless $x =~ s#^refs/remotes/##;
6475 chomp $x;
6476 next unless -f "$git_dir/$x/info/url";
6477 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
6478 next unless $u;
6479 my $dn = dirname("$git_dir/svn/$x");
6480 mkpath([$dn]) unless -d $dn;
6481 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
6482 mkpath(["$git_dir/svn/svn"]);
6483 print STDERR " - $git_dir/$x/info => ",
6484 "$git_dir/svn/$x/info\n";
6485 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
6486 croak "$!: $x";
6487 # don't worry too much about these, they probably
6488 # don't exist with repos this old (save for index,
6489 # and we can easily regenerate that)
6490 foreach my $f (qw/unhandled.log index .rev_db/) {
6491 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
6493 } else {
6494 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
6495 rename "$git_dir/$x", "$git_dir/svn/$x" or
6496 croak "$!: $x";
6498 $migrated++;
6500 command_close_pipe($fh, $ctx);
6501 print STDERR "Done migrating from a git-svn v1 layout\n";
6502 $migrated;
6505 sub read_old_urls {
6506 my ($l_map, $pfx, $path) = @_;
6507 my @dir;
6508 foreach (<$path/*>) {
6509 if (-r "$_/info/url") {
6510 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
6511 my $ref_id = $pfx . basename $_;
6512 my $url = ::file_to_s("$_/info/url");
6513 $l_map->{$ref_id} = $url;
6514 } elsif (-d $_) {
6515 push @dir, $_;
6518 foreach (@dir) {
6519 my $x = $_;
6520 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
6521 read_old_urls($l_map, $x, $_);
6525 sub migrate_from_v2 {
6526 my @cfg = command(qw/config -l/);
6527 return if grep /^svn-remote\..+\.url=/, @cfg;
6528 my %l_map;
6529 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
6530 my $migrated = 0;
6532 foreach my $ref_id (sort keys %l_map) {
6533 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
6534 if ($@) {
6535 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
6537 $migrated++;
6539 $migrated;
6542 sub minimize_connections {
6543 my $r = Git::SVN::read_all_remotes();
6544 my $new_urls = {};
6545 my $root_repos = {};
6546 foreach my $repo_id (keys %$r) {
6547 my $url = $r->{$repo_id}->{url} or next;
6548 my $fetch = $r->{$repo_id}->{fetch} or next;
6549 my $ra = Git::SVN::Ra->new($url);
6551 # skip existing cases where we already connect to the root
6552 if (($ra->{url} eq $ra->{repos_root}) ||
6553 ($ra->{repos_root} eq $repo_id)) {
6554 $root_repos->{$ra->{url}} = $repo_id;
6555 next;
6558 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
6559 my $root_path = $ra->{url};
6560 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
6561 foreach my $path (keys %$fetch) {
6562 my $ref_id = $fetch->{$path};
6563 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
6565 # make sure we can read when connecting to
6566 # a higher level of a repository
6567 my ($last_rev, undef) = $gs->last_rev_commit;
6568 if (!defined $last_rev) {
6569 $last_rev = eval {
6570 $root_ra->get_latest_revnum;
6572 next if $@;
6574 my $new = $root_path;
6575 $new .= length $path ? "/$path" : '';
6576 eval {
6577 $root_ra->get_log([$new], $last_rev, $last_rev,
6578 0, 0, 1, sub { });
6580 next if $@;
6581 $new_urls->{$ra->{repos_root}}->{$new} =
6582 { ref_id => $ref_id,
6583 old_repo_id => $repo_id,
6584 old_path => $path };
6588 my @emptied;
6589 foreach my $url (keys %$new_urls) {
6590 # see if we can re-use an existing [svn-remote "repo_id"]
6591 # instead of creating a(n ugly) new section:
6592 my $repo_id = $root_repos->{$url} || $url;
6594 my $fetch = $new_urls->{$url};
6595 foreach my $path (keys %$fetch) {
6596 my $x = $fetch->{$path};
6597 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
6598 my $pfx = "svn-remote.$x->{old_repo_id}";
6600 my $old_fetch = quotemeta("$x->{old_path}:".
6601 "$x->{ref_id}");
6602 command_noisy(qw/config --unset/,
6603 "$pfx.fetch", '^'. $old_fetch . '$');
6604 delete $r->{$x->{old_repo_id}}->
6605 {fetch}->{$x->{old_path}};
6606 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
6607 command_noisy(qw/config --unset/,
6608 "$pfx.url");
6609 push @emptied, $x->{old_repo_id}
6613 if (@emptied) {
6614 my $file = $ENV{GIT_CONFIG} || "$ENV{GIT_DIR}/config";
6615 print STDERR <<EOF;
6616 The following [svn-remote] sections in your config file ($file) are empty
6617 and can be safely removed:
6619 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
6623 sub migration_check {
6624 migrate_from_v0();
6625 migrate_from_v1();
6626 migrate_from_v2();
6627 minimize_connections() if $_minimize;
6630 package Git::IndexInfo;
6631 use strict;
6632 use warnings;
6633 use Git qw/command_input_pipe command_close_pipe/;
6635 sub new {
6636 my ($class) = @_;
6637 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
6638 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
6641 sub remove {
6642 my ($self, $path) = @_;
6643 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
6644 return ++$self->{nr};
6646 undef;
6649 sub update {
6650 my ($self, $mode, $hash, $path) = @_;
6651 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
6652 return ++$self->{nr};
6654 undef;
6657 sub DESTROY {
6658 my ($self) = @_;
6659 command_close_pipe($self->{gui}, $self->{ctx});
6662 package Git::SVN::GlobSpec;
6663 use strict;
6664 use warnings;
6666 sub new {
6667 my ($class, $glob, $pattern_ok) = @_;
6668 my $re = $glob;
6669 $re =~ s!/+$!!g; # no need for trailing slashes
6670 my (@left, @right, @patterns);
6671 my $state = "left";
6672 my $die_msg = "Only one set of wildcard directories " .
6673 "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
6674 for my $part (split(m|/|, $glob)) {
6675 if ($part =~ /\*/ && $part ne "*") {
6676 die "Invalid pattern in '$glob': $part\n";
6677 } elsif ($pattern_ok && $part =~ /[{}]/ &&
6678 $part !~ /^\{[^{}]+\}/) {
6679 die "Invalid pattern in '$glob': $part\n";
6681 if ($part eq "*") {
6682 die $die_msg if $state eq "right";
6683 $state = "pattern";
6684 push(@patterns, "[^/]*");
6685 } elsif ($pattern_ok && $part =~ /^\{(.*)\}$/) {
6686 die $die_msg if $state eq "right";
6687 $state = "pattern";
6688 my $p = quotemeta($1);
6689 $p =~ s/\\,/|/g;
6690 push(@patterns, "(?:$p)");
6691 } else {
6692 if ($state eq "left") {
6693 push(@left, $part);
6694 } else {
6695 push(@right, $part);
6696 $state = "right";
6700 my $depth = @patterns;
6701 if ($depth == 0) {
6702 die "One '*' is needed in glob: '$glob'\n";
6704 my $left = join('/', @left);
6705 my $right = join('/', @right);
6706 $re = join('/', @patterns);
6707 $re = join('\/',
6708 grep(length, quotemeta($left), "($re)", quotemeta($right)));
6709 my $left_re = qr/^\/\Q$left\E(\/|$)/;
6710 bless { left => $left, right => $right, left_regex => $left_re,
6711 regex => qr/$re/, glob => $glob, depth => $depth }, $class;
6714 sub full_path {
6715 my ($self, $path) = @_;
6716 return (length $self->{left} ? "$self->{left}/" : '') .
6717 $path . (length $self->{right} ? "/$self->{right}" : '');
6720 __END__
6722 Data structures:
6725 $remotes = { # returned by read_all_remotes()
6726 'svn' => {
6727 # svn-remote.svn.url=https://svn.musicpd.org
6728 url => 'https://svn.musicpd.org',
6729 # svn-remote.svn.fetch=mpd/trunk:trunk
6730 fetch => {
6731 'mpd/trunk' => 'trunk',
6733 # svn-remote.svn.tags=mpd/tags/*:tags/*
6734 tags => {
6735 path => {
6736 left => 'mpd/tags',
6737 right => '',
6738 regex => qr!mpd/tags/([^/]+)$!,
6739 glob => 'tags/*',
6741 ref => {
6742 left => 'tags',
6743 right => '',
6744 regex => qr!tags/([^/]+)$!,
6745 glob => 'tags/*',
6751 $log_entry hashref as returned by libsvn_log_entry()
6753 log => 'whitespace-formatted log entry
6754 ', # trailing newline is preserved
6755 revision => '8', # integer
6756 date => '2004-02-24T17:01:44.108345Z', # commit date
6757 author => 'committer name'
6761 # this is generated by generate_diff();
6762 @mods = array of diff-index line hashes, each element represents one line
6763 of diff-index output
6765 diff-index line ($m hash)
6767 mode_a => first column of diff-index output, no leading ':',
6768 mode_b => second column of diff-index output,
6769 sha1_b => sha1sum of the final blob,
6770 chg => change type [MCRADT],
6771 file_a => original file name of a file (iff chg is 'C' or 'R')
6772 file_b => new/current file name of a file (any chg)
6776 # retval of read_url_paths{,_all}();
6777 $l_map = {
6778 # repository root url
6779 'https://svn.musicpd.org' => {
6780 # repository path # GIT_SVN_ID
6781 'mpd/trunk' => 'trunk',
6782 'mpd/tags/0.11.5' => 'tags/0.11.5',
6786 Notes:
6787 I don't trust the each() function on unless I created %hash myself
6788 because the internal iterator may not have started at base.