Win32: keep the environment sorted
[git/dscho.git] / git-svn.perl
blobc84842ff0383c6929d8169834944ec1ad2bb7346
1 #!/usr/bin/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} && exists $ENV{GIT_SSH}) {
26 $ENV{SVN_SSH} = $ENV{GIT_SSH};
29 if (exists $ENV{SVN_SSH} && $^O eq 'msys') {
30 $ENV{SVN_SSH} =~ s/\\/\\\\/g;
31 $ENV{SVN_SSH} =~ s/(.*)/"$1"/;
34 $Git::SVN::Log::TZ = $ENV{TZ};
35 $ENV{TZ} = 'UTC';
36 $| = 1; # unbuffer STDOUT
38 sub fatal (@) { print STDERR "@_\n"; exit 1 }
40 # All SVN commands do it. Otherwise we may die on SIGPIPE when the remote
41 # repository decides to close the connection which we expect to be kept alive.
42 $SIG{PIPE} = 'IGNORE';
44 # Given a dot separated version number, "subtract" it from
45 # the SVN::Core::VERSION; non-negaitive return means the SVN::Core
46 # is at least at the version the caller asked for.
47 sub compare_svn_version {
48 my (@ours) = split(/\./, $SVN::Core::VERSION);
49 my (@theirs) = split(/\./, $_[0]);
50 my ($i, $diff);
52 for ($i = 0; $i < @ours && $i < @theirs; $i++) {
53 $diff = $ours[$i] - $theirs[$i];
54 return $diff if ($diff);
56 return 1 if ($i < @ours);
57 return -1 if ($i < @theirs);
58 return 0;
61 sub _req_svn {
62 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
63 require SVN::Ra;
64 require SVN::Delta;
65 if (::compare_svn_version('1.1.0') < 0) {
66 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
69 my $can_compress = eval { require Compress::Zlib; 1};
70 push @Git::SVN::Ra::ISA, 'SVN::Ra';
71 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
72 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
73 use Carp qw/croak/;
74 use Digest::MD5;
75 use IO::File qw//;
76 use File::Basename qw/dirname basename/;
77 use File::Path qw/mkpath/;
78 use File::Spec;
79 use File::Find;
80 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
81 use IPC::Open3;
82 use Git;
83 use Memoize; # core since 5.8.0, Jul 2002
85 BEGIN {
86 # import functions from Git into our packages, en masse
87 no strict 'refs';
88 foreach (qw/command command_oneline command_noisy command_output_pipe
89 command_input_pipe command_close_pipe
90 command_bidi_pipe command_close_bidi_pipe/) {
91 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
92 Git::SVN::Migration Git::SVN::Log Git::SVN),
93 __PACKAGE__) {
94 *{"${package}::$_"} = \&{"Git::$_"};
97 Memoize::memoize 'Git::config';
98 Memoize::memoize 'Git::config_bool';
101 my ($SVN);
103 $sha1 = qr/[a-f\d]{40}/;
104 $sha1_short = qr/[a-f\d]{4,40}/;
105 my ($_stdin, $_help, $_edit,
106 $_message, $_file, $_branch_dest,
107 $_template, $_shared,
108 $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
109 $_merge, $_strategy, $_preserve_merges, $_dry_run, $_local,
110 $_prefix, $_no_checkout, $_url, $_verbose,
111 $_git_format, $_commit_url, $_tag, $_merge_info, $_interactive);
112 $Git::SVN::_follow_parent = 1;
113 $SVN::Git::Fetcher::_placeholder_filename = ".gitignore";
114 $_q ||= 0;
115 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
116 'config-dir=s' => \$Git::SVN::Ra::config_dir,
117 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
118 'ignore-paths=s' => \$SVN::Git::Fetcher::_ignore_regex,
119 'ignore-refs=s' => \$Git::SVN::Ra::_ignore_refs_regex );
120 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
121 'authors-file|A=s' => \$_authors,
122 'authors-prog=s' => \$_authors_prog,
123 'repack:i' => \$Git::SVN::_repack,
124 'noMetadata' => \$Git::SVN::_no_metadata,
125 'useSvmProps' => \$Git::SVN::_use_svm_props,
126 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
127 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
128 'no-checkout' => \$_no_checkout,
129 'quiet|q+' => \$_q,
130 'repack-flags|repack-args|repack-opts=s' =>
131 \$Git::SVN::_repack_flags,
132 'use-log-author' => \$Git::SVN::_use_log_author,
133 'add-author-from' => \$Git::SVN::_add_author_from,
134 'localtime' => \$Git::SVN::_localtime,
135 %remote_opts );
137 my ($_trunk, @_tags, @_branches, $_stdlayout);
138 my %icv;
139 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
140 'trunk|T=s' => \$_trunk, 'tags|t=s@' => \@_tags,
141 'branches|b=s@' => \@_branches, 'prefix=s' => \$_prefix,
142 'stdlayout|s' => \$_stdlayout,
143 'minimize-url|m!' => \$Git::SVN::_minimize_url,
144 'no-metadata' => sub { $icv{noMetadata} = 1 },
145 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
146 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
147 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
148 'rewrite-uuid=s' => sub { $icv{rewriteUUID} = $_[1] },
149 %remote_opts );
150 my %cmt_opts = ( 'edit|e' => \$_edit,
151 'rmdir' => \$SVN::Git::Editor::_rmdir,
152 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
153 'l=i' => \$SVN::Git::Editor::_rename_limit,
154 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
157 my %cmd = (
158 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
159 { 'revision|r=s' => \$_revision,
160 'fetch-all|all' => \$_fetch_all,
161 'parent|p' => \$_fetch_parent,
162 %fc_opts } ],
163 clone => [ \&cmd_clone, "Initialize and fetch revisions",
164 { 'revision|r=s' => \$_revision,
165 'preserve-empty-dirs' =>
166 \$SVN::Git::Fetcher::_preserve_empty_dirs,
167 'placeholder-filename=s' =>
168 \$SVN::Git::Fetcher::_placeholder_filename,
169 %fc_opts, %init_opts } ],
170 init => [ \&cmd_init, "Initialize a repo for tracking" .
171 " (requires URL argument)",
172 \%init_opts ],
173 'multi-init' => [ \&cmd_multi_init,
174 "Deprecated alias for ".
175 "'$0 init -T<trunk> -b<branches> -t<tags>'",
176 \%init_opts ],
177 dcommit => [ \&cmd_dcommit,
178 'Commit several diffs to merge with upstream',
179 { 'merge|m|M' => \$_merge,
180 'strategy|s=s' => \$_strategy,
181 'verbose|v' => \$_verbose,
182 'dry-run|n' => \$_dry_run,
183 'fetch-all|all' => \$_fetch_all,
184 'commit-url=s' => \$_commit_url,
185 'revision|r=i' => \$_revision,
186 'no-rebase' => \$_no_rebase,
187 'mergeinfo=s' => \$_merge_info,
188 'interactive|i' => \$_interactive,
189 %cmt_opts, %fc_opts } ],
190 branch => [ \&cmd_branch,
191 'Create a branch in the SVN repository',
192 { 'message|m=s' => \$_message,
193 'destination|d=s' => \$_branch_dest,
194 'dry-run|n' => \$_dry_run,
195 'tag|t' => \$_tag,
196 'username=s' => \$Git::SVN::Prompt::_username,
197 'commit-url=s' => \$_commit_url } ],
198 tag => [ sub { $_tag = 1; cmd_branch(@_) },
199 'Create a tag in the SVN repository',
200 { 'message|m=s' => \$_message,
201 'destination|d=s' => \$_branch_dest,
202 'dry-run|n' => \$_dry_run,
203 'username=s' => \$Git::SVN::Prompt::_username,
204 'commit-url=s' => \$_commit_url } ],
205 'set-tree' => [ \&cmd_set_tree,
206 "Set an SVN repository to a git tree-ish",
207 { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
208 'create-ignore' => [ \&cmd_create_ignore,
209 'Create a .gitignore per svn:ignore',
210 { 'revision|r=i' => \$_revision
211 } ],
212 'mkdirs' => [ \&cmd_mkdirs ,
213 "recreate empty directories after a checkout",
214 { 'revision|r=i' => \$_revision } ],
215 'propget' => [ \&cmd_propget,
216 'Print the value of a property on a file or directory',
217 { 'revision|r=i' => \$_revision } ],
218 'proplist' => [ \&cmd_proplist,
219 'List all properties of a file or directory',
220 { 'revision|r=i' => \$_revision } ],
221 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
222 { 'revision|r=i' => \$_revision
223 } ],
224 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
225 { 'revision|r=i' => \$_revision
226 } ],
227 'multi-fetch' => [ \&cmd_multi_fetch,
228 "Deprecated alias for $0 fetch --all",
229 { 'revision|r=s' => \$_revision, %fc_opts } ],
230 'migrate' => [ sub { },
231 # no-op, we automatically run this anyways,
232 'Migrate configuration/metadata/layout from
233 previous versions of git-svn',
234 { 'minimize' => \$Git::SVN::Migration::_minimize,
235 %remote_opts } ],
236 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
237 { 'limit=i' => \$Git::SVN::Log::limit,
238 'revision|r=s' => \$_revision,
239 'verbose|v' => \$Git::SVN::Log::verbose,
240 'incremental' => \$Git::SVN::Log::incremental,
241 'oneline' => \$Git::SVN::Log::oneline,
242 'show-commit' => \$Git::SVN::Log::show_commit,
243 'non-recursive' => \$Git::SVN::Log::non_recursive,
244 'authors-file|A=s' => \$_authors,
245 'color' => \$Git::SVN::Log::color,
246 'pager=s' => \$Git::SVN::Log::pager
247 } ],
248 'find-rev' => [ \&cmd_find_rev,
249 "Translate between SVN revision numbers and tree-ish",
250 {} ],
251 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
252 { 'merge|m|M' => \$_merge,
253 'verbose|v' => \$_verbose,
254 'strategy|s=s' => \$_strategy,
255 'local|l' => \$_local,
256 'fetch-all|all' => \$_fetch_all,
257 'dry-run|n' => \$_dry_run,
258 'preserve-merges|p' => \$_preserve_merges,
259 %fc_opts } ],
260 'commit-diff' => [ \&cmd_commit_diff,
261 'Commit a diff between two trees',
262 { 'message|m=s' => \$_message,
263 'file|F=s' => \$_file,
264 'revision|r=s' => \$_revision,
265 %cmt_opts } ],
266 'info' => [ \&cmd_info,
267 "Show info about the latest SVN revision
268 on the current branch",
269 { 'url' => \$_url, } ],
270 'blame' => [ \&Git::SVN::Log::cmd_blame,
271 "Show what revision and author last modified each line of a file",
272 { 'git-format' => \$_git_format } ],
273 'reset' => [ \&cmd_reset,
274 "Undo fetches back to the specified SVN revision",
275 { 'revision|r=s' => \$_revision,
276 'parent|p' => \$_fetch_parent } ],
277 'gc' => [ \&cmd_gc,
278 "Compress unhandled.log files in .git/svn and remove " .
279 "index files in .git/svn",
280 {} ],
283 use Term::ReadLine;
284 package FakeTerm;
285 sub new {
286 my ($class, $reason) = @_;
287 return bless \$reason, shift;
289 sub readline {
290 my $self = shift;
291 die "Cannot use readline on FakeTerm: $$self";
293 package main;
295 my $term = eval {
296 $ENV{"GIT_SVN_NOTTY"}
297 ? new Term::ReadLine 'git-svn', \*STDIN, \*STDOUT
298 : new Term::ReadLine 'git-svn';
300 if ($@) {
301 $term = new FakeTerm "$@: going non-interactive";
304 my $cmd;
305 for (my $i = 0; $i < @ARGV; $i++) {
306 if (defined $cmd{$ARGV[$i]}) {
307 $cmd = $ARGV[$i];
308 splice @ARGV, $i, 1;
309 last;
310 } elsif ($ARGV[$i] eq 'help') {
311 $cmd = $ARGV[$i+1];
312 usage(0);
316 # make sure we're always running at the top-level working directory
317 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
318 unless (-d $ENV{GIT_DIR}) {
319 if ($git_dir_user_set) {
320 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
321 "but it is not a directory\n";
323 my $git_dir = delete $ENV{GIT_DIR};
324 my $cdup = undef;
325 git_cmd_try {
326 $cdup = command_oneline(qw/rev-parse --show-cdup/);
327 $git_dir = '.' unless ($cdup);
328 chomp $cdup if ($cdup);
329 $cdup = "." unless ($cdup && length $cdup);
330 } "Already at toplevel, but $git_dir not found\n";
331 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
332 unless (-d $git_dir) {
333 die "$git_dir still not found after going to ",
334 "'$cdup'\n";
336 $ENV{GIT_DIR} = $git_dir;
338 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
341 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
343 read_git_config(\%opts);
344 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
345 Getopt::Long::Configure('pass_through');
347 my $rv = GetOptions(%opts, 'h|H' => \$_help, 'version|V' => \$_version,
348 'minimize-connections' => \$Git::SVN::Migration::_minimize,
349 'id|i=s' => \$Git::SVN::default_ref_id,
350 'svn-remote|remote|R=s' => sub {
351 $Git::SVN::no_reuse_existing = 1;
352 $Git::SVN::default_repo_id = $_[1] });
353 exit 1 if (!$rv && $cmd && $cmd ne 'log');
355 usage(0) if $_help;
356 version() if $_version;
357 usage(1) unless defined $cmd;
358 load_authors() if $_authors;
359 if (defined $_authors_prog) {
360 $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
363 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
364 Git::SVN::Migration::migration_check();
366 Git::SVN::init_vars();
367 eval {
368 Git::SVN::verify_remotes_sanity();
369 $cmd{$cmd}->[0]->(@ARGV);
371 fatal $@ if $@;
372 post_fetch_checkout();
373 exit 0;
375 ####################### primary functions ######################
376 sub usage {
377 my $exit = shift || 0;
378 my $fd = $exit ? \*STDERR : \*STDOUT;
379 print $fd <<"";
380 git-svn - bidirectional operations between a single Subversion tree and git
381 Usage: git svn <command> [options] [arguments]\n
383 print $fd "Available commands:\n" unless $cmd;
385 foreach (sort keys %cmd) {
386 next if $cmd && $cmd ne $_;
387 next if /^multi-/; # don't show deprecated commands
388 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
389 foreach (sort keys %{$cmd{$_}->[2]}) {
390 # mixed-case options are for .git/config only
391 next if /[A-Z]/ && /^[a-z]+$/i;
392 # prints out arguments as they should be passed:
393 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
394 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
395 "--$_" : "-$_" }
396 split /\|/,$_)," $x\n";
399 print $fd <<"";
400 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
401 arbitrary identifier if you're tracking multiple SVN branches/repositories in
402 one git repository and want to keep them separate. See git-svn(1) for more
403 information.
405 exit $exit;
408 sub version {
409 ::_req_svn();
410 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
411 exit 0;
414 sub ask {
415 my ($prompt, %arg) = @_;
416 my $valid_re = $arg{valid_re};
417 my $default = $arg{default};
418 my $resp;
419 my $i = 0;
421 if ( !( defined($term->IN)
422 && defined( fileno($term->IN) )
423 && defined( $term->OUT )
424 && defined( fileno($term->OUT) ) ) ){
425 return defined($default) ? $default : undef;
428 while ($i++ < 10) {
429 $resp = $term->readline($prompt);
430 if (!defined $resp) { # EOF
431 print "\n";
432 return defined $default ? $default : undef;
434 if ($resp eq '' and defined $default) {
435 return $default;
437 if (!defined $valid_re or $resp =~ /$valid_re/) {
438 return $resp;
441 return undef;
444 sub do_git_init_db {
445 unless (-d $ENV{GIT_DIR}) {
446 my @init_db = ('init');
447 push @init_db, "--template=$_template" if defined $_template;
448 if (defined $_shared) {
449 if ($_shared =~ /[a-z]/) {
450 push @init_db, "--shared=$_shared";
451 } else {
452 push @init_db, "--shared";
455 command_noisy(@init_db);
456 $_repository = Git->repository(Repository => ".git");
458 my $set;
459 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
460 foreach my $i (keys %icv) {
461 die "'$set' and '$i' cannot both be set\n" if $set;
462 next unless defined $icv{$i};
463 command_noisy('config', "$pfx.$i", $icv{$i});
464 $set = $i;
466 my $ignore_paths_regex = \$SVN::Git::Fetcher::_ignore_regex;
467 command_noisy('config', "$pfx.ignore-paths", $$ignore_paths_regex)
468 if defined $$ignore_paths_regex;
469 my $ignore_refs_regex = \$Git::SVN::Ra::_ignore_refs_regex;
470 command_noisy('config', "$pfx.ignore-refs", $$ignore_refs_regex)
471 if defined $$ignore_refs_regex;
473 if (defined $SVN::Git::Fetcher::_preserve_empty_dirs) {
474 my $fname = \$SVN::Git::Fetcher::_placeholder_filename;
475 command_noisy('config', "$pfx.preserve-empty-dirs", 'true');
476 command_noisy('config', "$pfx.placeholder-filename", $$fname);
480 sub init_subdir {
481 my $repo_path = shift or return;
482 mkpath([$repo_path]) unless -d $repo_path;
483 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
484 $ENV{GIT_DIR} = '.git';
485 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
488 sub cmd_clone {
489 my ($url, $path) = @_;
490 if (!defined $path &&
491 (defined $_trunk || @_branches || @_tags ||
492 defined $_stdlayout) &&
493 $url !~ m#^[a-z\+]+://#) {
494 $path = $url;
496 $path = basename($url) if !defined $path || !length $path;
497 my $authors_absolute = $_authors ? File::Spec->rel2abs($_authors) : "";
498 cmd_init($url, $path);
499 command_oneline('config', 'svn.authorsfile', $authors_absolute)
500 if $_authors;
501 Git::SVN::fetch_all($Git::SVN::default_repo_id);
504 sub cmd_init {
505 if (defined $_stdlayout) {
506 $_trunk = 'trunk' if (!defined $_trunk);
507 @_tags = 'tags' if (! @_tags);
508 @_branches = 'branches' if (! @_branches);
510 if (defined $_trunk || @_branches || @_tags) {
511 return cmd_multi_init(@_);
513 my $url = shift or die "SVN repository location required ",
514 "as a command-line argument\n";
515 $url = canonicalize_url($url);
516 init_subdir(@_);
517 do_git_init_db();
519 if ($Git::SVN::_minimize_url eq 'unset') {
520 $Git::SVN::_minimize_url = 0;
523 Git::SVN->init($url);
526 sub cmd_fetch {
527 if (grep /^\d+=./, @_) {
528 die "'<rev>=<commit>' fetch arguments are ",
529 "no longer supported.\n";
531 my ($remote) = @_;
532 if (@_ > 1) {
533 die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
535 $Git::SVN::no_reuse_existing = undef;
536 if ($_fetch_parent) {
537 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
538 unless ($gs) {
539 die "Unable to determine upstream SVN information from ",
540 "working tree history\n";
542 # just fetch, don't checkout.
543 $_no_checkout = 'true';
544 $_fetch_all ? $gs->fetch_all : $gs->fetch;
545 } elsif ($_fetch_all) {
546 cmd_multi_fetch();
547 } else {
548 $remote ||= $Git::SVN::default_repo_id;
549 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
553 sub cmd_set_tree {
554 my (@commits) = @_;
555 if ($_stdin || !@commits) {
556 print "Reading from stdin...\n";
557 @commits = ();
558 while (<STDIN>) {
559 if (/\b($sha1_short)\b/o) {
560 unshift @commits, $1;
564 my @revs;
565 foreach my $c (@commits) {
566 my @tmp = command('rev-parse',$c);
567 if (scalar @tmp == 1) {
568 push @revs, $tmp[0];
569 } elsif (scalar @tmp > 1) {
570 push @revs, reverse(command('rev-list',@tmp));
571 } else {
572 fatal "Failed to rev-parse $c";
575 my $gs = Git::SVN->new;
576 my ($r_last, $cmt_last) = $gs->last_rev_commit;
577 $gs->fetch;
578 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
579 fatal "There are new revisions that were fetched ",
580 "and need to be merged (or acknowledged) ",
581 "before committing.\nlast rev: $r_last\n",
582 " current: $gs->{last_rev}";
584 $gs->set_tree($_) foreach @revs;
585 print "Done committing ",scalar @revs," revisions to SVN\n";
586 unlink $gs->{index};
589 sub split_merge_info_range {
590 my ($range) = @_;
591 if ($range =~ /(\d+)-(\d+)/) {
592 return (int($1), int($2));
593 } else {
594 return (int($range), int($range));
598 sub combine_ranges {
599 my ($in) = @_;
601 my @fnums = ();
602 my @arr = split(/,/, $in);
603 for my $element (@arr) {
604 my ($start, $end) = split_merge_info_range($element);
605 push @fnums, $start;
608 my @sorted = @arr [ sort {
609 $fnums[$a] <=> $fnums[$b]
610 } 0..$#arr ];
612 my @return = ();
613 my $last = -1;
614 my $first = -1;
615 for my $element (@sorted) {
616 my ($start, $end) = split_merge_info_range($element);
618 if ($last == -1) {
619 $first = $start;
620 $last = $end;
621 next;
623 if ($start <= $last+1) {
624 if ($end > $last) {
625 $last = $end;
627 next;
629 if ($first == $last) {
630 push @return, "$first";
631 } else {
632 push @return, "$first-$last";
634 $first = $start;
635 $last = $end;
638 if ($first != -1) {
639 if ($first == $last) {
640 push @return, "$first";
641 } else {
642 push @return, "$first-$last";
646 return join(',', @return);
649 sub merge_revs_into_hash {
650 my ($hash, $minfo) = @_;
651 my @lines = split(' ', $minfo);
653 for my $line (@lines) {
654 my ($branchpath, $revs) = split(/:/, $line);
656 if (exists($hash->{$branchpath})) {
657 # Merge the two revision sets
658 my $combined = "$hash->{$branchpath},$revs";
659 $hash->{$branchpath} = combine_ranges($combined);
660 } else {
661 # Just do range combining for consolidation
662 $hash->{$branchpath} = combine_ranges($revs);
667 sub merge_merge_info {
668 my ($mergeinfo_one, $mergeinfo_two) = @_;
669 my %result_hash = ();
671 merge_revs_into_hash(\%result_hash, $mergeinfo_one);
672 merge_revs_into_hash(\%result_hash, $mergeinfo_two);
674 my $result = '';
675 # Sort below is for consistency's sake
676 for my $branchname (sort keys(%result_hash)) {
677 my $revlist = $result_hash{$branchname};
678 $result .= "$branchname:$revlist\n"
680 return $result;
683 sub populate_merge_info {
684 my ($d, $gs, $uuid, $linear_refs, $rewritten_parent) = @_;
686 my %parentshash;
687 read_commit_parents(\%parentshash, $d);
688 my @parents = @{$parentshash{$d}};
689 if ($#parents > 0) {
690 # Merge commit
691 my $all_parents_ok = 1;
692 my $aggregate_mergeinfo = '';
693 my $rooturl = $gs->repos_root;
695 if (defined($rewritten_parent)) {
696 # Replace first parent with newly-rewritten version
697 shift @parents;
698 unshift @parents, $rewritten_parent;
701 foreach my $parent (@parents) {
702 my ($branchurl, $svnrev, $paruuid) =
703 cmt_metadata($parent);
705 unless (defined($svnrev)) {
706 # Should have been caught be preflight check
707 fatal "merge commit $d has ancestor $parent, but that change "
708 ."does not have git-svn metadata!";
710 unless ($branchurl =~ /^\Q$rooturl\E(.*)/) {
711 fatal "commit $parent git-svn metadata changed mid-run!";
713 my $branchpath = $1;
715 my $ra = Git::SVN::Ra->new($branchurl);
716 my (undef, undef, $props) =
717 $ra->get_dir(canonicalize_path("."), $svnrev);
718 my $par_mergeinfo = $props->{'svn:mergeinfo'};
719 unless (defined $par_mergeinfo) {
720 $par_mergeinfo = '';
722 # Merge previous mergeinfo values
723 $aggregate_mergeinfo =
724 merge_merge_info($aggregate_mergeinfo,
725 $par_mergeinfo, 0);
727 next if $parent eq $parents[0]; # Skip first parent
728 # Add new changes being placed in tree by merge
729 my @cmd = (qw/rev-list --reverse/,
730 $parent, qw/--not/);
731 foreach my $par (@parents) {
732 unless ($par eq $parent) {
733 push @cmd, $par;
736 my @revsin = ();
737 my ($revlist, $ctx) = command_output_pipe(@cmd);
738 while (<$revlist>) {
739 my $irev = $_;
740 chomp $irev;
741 my (undef, $csvnrev, undef) =
742 cmt_metadata($irev);
743 unless (defined $csvnrev) {
744 # A child is missing SVN annotations...
745 # this might be OK, or might not be.
746 warn "W:child $irev is merged into revision "
747 ."$d but does not have git-svn metadata. "
748 ."This means git-svn cannot determine the "
749 ."svn revision numbers to place into the "
750 ."svn:mergeinfo property. You must ensure "
751 ."a branch is entirely committed to "
752 ."SVN before merging it in order for "
753 ."svn:mergeinfo population to function "
754 ."properly";
756 push @revsin, $csvnrev;
758 command_close_pipe($revlist, $ctx);
760 last unless $all_parents_ok;
762 # We now have a list of all SVN revnos which are
763 # merged by this particular parent. Integrate them.
764 next if $#revsin == -1;
765 my $newmergeinfo = "$branchpath:" . join(',', @revsin);
766 $aggregate_mergeinfo =
767 merge_merge_info($aggregate_mergeinfo,
768 $newmergeinfo, 1);
770 if ($all_parents_ok and $aggregate_mergeinfo) {
771 return $aggregate_mergeinfo;
775 return undef;
778 sub cmd_dcommit {
779 my $head = shift;
780 command_noisy(qw/update-index --refresh/);
781 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
782 'Cannot dcommit with a dirty index. Commit your changes first, '
783 . "or stash them with `git stash'.\n";
784 $head ||= 'HEAD';
786 my $old_head;
787 if ($head ne 'HEAD') {
788 $old_head = eval {
789 command_oneline([qw/symbolic-ref -q HEAD/])
791 if ($old_head) {
792 $old_head =~ s{^refs/heads/}{};
793 } else {
794 $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
796 command(['checkout', $head], STDERR => 0);
799 my @refs;
800 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
801 unless ($gs) {
802 die "Unable to determine upstream SVN information from ",
803 "$head history.\nPerhaps the repository is empty.";
806 if (defined $_commit_url) {
807 $url = $_commit_url;
808 } else {
809 $url = eval { command_oneline('config', '--get',
810 "svn-remote.$gs->{repo_id}.commiturl") };
811 if (!$url) {
812 $url = $gs->full_pushurl
816 my $last_rev = $_revision if defined $_revision;
817 if ($url) {
818 print "Committing to $url ...\n";
820 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
821 if ($_no_rebase && scalar(@$linear_refs) > 1) {
822 warn "Attempting to commit more than one change while ",
823 "--no-rebase is enabled.\n",
824 "If these changes depend on each other, re-running ",
825 "without --no-rebase may be required."
828 if (defined $_interactive){
829 my $ask_default = "y";
830 foreach my $d (@$linear_refs){
831 my ($fh, $ctx) = command_output_pipe(qw(show --summary), "$d");
832 while (<$fh>){
833 print $_;
835 command_close_pipe($fh, $ctx);
836 $_ = ask("Commit this patch to SVN? ([y]es (default)|[n]o|[q]uit|[a]ll): ",
837 valid_re => qr/^(?:yes|y|no|n|quit|q|all|a)/i,
838 default => $ask_default);
839 die "Commit this patch reply required" unless defined $_;
840 if (/^[nq]/i) {
841 exit(0);
842 } elsif (/^a/i) {
843 last;
848 my $expect_url = $url;
850 my $push_merge_info = eval {
851 command_oneline(qw/config --get svn.pushmergeinfo/)
853 if (not defined($push_merge_info)
854 or $push_merge_info eq "false"
855 or $push_merge_info eq "no"
856 or $push_merge_info eq "never") {
857 $push_merge_info = 0;
860 unless (defined($_merge_info) || ! $push_merge_info) {
861 # Preflight check of changes to ensure no issues with mergeinfo
862 # This includes check for uncommitted-to-SVN parents
863 # (other than the first parent, which we will handle),
864 # information from different SVN repos, and paths
865 # which are not underneath this repository root.
866 my $rooturl = $gs->repos_root;
867 foreach my $d (@$linear_refs) {
868 my %parentshash;
869 read_commit_parents(\%parentshash, $d);
870 my @realparents = @{$parentshash{$d}};
871 if ($#realparents > 0) {
872 # Merge commit
873 shift @realparents; # Remove/ignore first parent
874 foreach my $parent (@realparents) {
875 my ($branchurl, $svnrev, $paruuid) = cmt_metadata($parent);
876 unless (defined $paruuid) {
877 # A parent is missing SVN annotations...
878 # abort the whole operation.
879 fatal "$parent is merged into revision $d, "
880 ."but does not have git-svn metadata. "
881 ."Either dcommit the branch or use a "
882 ."local cherry-pick, FF merge, or rebase "
883 ."instead of an explicit merge commit.";
886 unless ($paruuid eq $uuid) {
887 # Parent has SVN metadata from different repository
888 fatal "merge parent $parent for change $d has "
889 ."git-svn uuid $paruuid, while current change "
890 ."has uuid $uuid!";
893 unless ($branchurl =~ /^\Q$rooturl\E(.*)/) {
894 # This branch is very strange indeed.
895 fatal "merge parent $parent for $d is on branch "
896 ."$branchurl, which is not under the "
897 ."git-svn root $rooturl!";
904 my $rewritten_parent;
905 Git::SVN::remove_username($expect_url);
906 if (defined($_merge_info)) {
907 $_merge_info =~ tr{ }{\n};
909 while (1) {
910 my $d = shift @$linear_refs or last;
911 unless (defined $last_rev) {
912 (undef, $last_rev, undef) = cmt_metadata("$d~1");
913 unless (defined $last_rev) {
914 fatal "Unable to extract revision information ",
915 "from commit $d~1";
918 if ($_dry_run) {
919 print "diff-tree $d~1 $d\n";
920 } else {
921 my $cmt_rev;
923 unless (defined($_merge_info) || ! $push_merge_info) {
924 $_merge_info = populate_merge_info($d, $gs,
925 $uuid,
926 $linear_refs,
927 $rewritten_parent);
930 my %ed_opts = ( r => $last_rev,
931 log => get_commit_entry($d)->{log},
932 ra => Git::SVN::Ra->new($url),
933 config => SVN::Core::config_get_config(
934 $Git::SVN::Ra::config_dir
936 tree_a => "$d~1",
937 tree_b => $d,
938 editor_cb => sub {
939 print "Committed r$_[0]\n";
940 $cmt_rev = $_[0];
942 mergeinfo => $_merge_info,
943 svn_path => '');
944 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
945 print "No changes\n$d~1 == $d\n";
946 } elsif ($parents->{$d} && @{$parents->{$d}}) {
947 $gs->{inject_parents_dcommit}->{$cmt_rev} =
948 $parents->{$d};
950 $_fetch_all ? $gs->fetch_all : $gs->fetch;
951 $last_rev = $cmt_rev;
952 next if $_no_rebase;
954 # we always want to rebase against the current HEAD,
955 # not any head that was passed to us
956 my @diff = command('diff-tree', $d,
957 $gs->refname, '--');
958 my @finish;
959 if (@diff) {
960 @finish = rebase_cmd();
961 print STDERR "W: $d and ", $gs->refname,
962 " differ, using @finish:\n",
963 join("\n", @diff), "\n";
964 } else {
965 print "No changes between current HEAD and ",
966 $gs->refname,
967 "\nResetting to the latest ",
968 $gs->refname, "\n";
969 @finish = qw/reset --mixed/;
971 command_noisy(@finish, $gs->refname);
973 $rewritten_parent = command_oneline(qw/rev-parse HEAD/);
975 if (@diff) {
976 @refs = ();
977 my ($url_, $rev_, $uuid_, $gs_) =
978 working_head_info('HEAD', \@refs);
979 my ($linear_refs_, $parents_) =
980 linearize_history($gs_, \@refs);
981 if (scalar(@$linear_refs) !=
982 scalar(@$linear_refs_)) {
983 fatal "# of revisions changed ",
984 "\nbefore:\n",
985 join("\n", @$linear_refs),
986 "\n\nafter:\n",
987 join("\n", @$linear_refs_), "\n",
988 'If you are attempting to commit ',
989 "merges, try running:\n\t",
990 'git rebase --interactive',
991 '--preserve-merges ',
992 $gs->refname,
993 "\nBefore dcommitting";
995 if ($url_ ne $expect_url) {
996 if ($url_ eq $gs->metadata_url) {
997 print
998 "Accepting rewritten URL:",
999 " $url_\n";
1000 } else {
1001 fatal
1002 "URL mismatch after rebase:",
1003 " $url_ != $expect_url";
1006 if ($uuid_ ne $uuid) {
1007 fatal "uuid mismatch after rebase: ",
1008 "$uuid_ != $uuid";
1010 # remap parents
1011 my (%p, @l, $i);
1012 for ($i = 0; $i < scalar @$linear_refs; $i++) {
1013 my $new = $linear_refs_->[$i] or next;
1014 $p{$new} =
1015 $parents->{$linear_refs->[$i]};
1016 push @l, $new;
1018 $parents = \%p;
1019 $linear_refs = \@l;
1024 if ($old_head) {
1025 my $new_head = command_oneline(qw/rev-parse HEAD/);
1026 my $new_is_symbolic = eval {
1027 command_oneline(qw/symbolic-ref -q HEAD/);
1029 if ($new_is_symbolic) {
1030 print "dcommitted the branch ", $head, "\n";
1031 } else {
1032 print "dcommitted on a detached HEAD because you gave ",
1033 "a revision argument.\n",
1034 "The rewritten commit is: ", $new_head, "\n";
1036 command(['checkout', $old_head], STDERR => 0);
1039 unlink $gs->{index};
1042 sub cmd_branch {
1043 my ($branch_name, $head) = @_;
1045 unless (defined $branch_name && length $branch_name) {
1046 die(($_tag ? "tag" : "branch") . " name required\n");
1048 $head ||= 'HEAD';
1050 my (undef, $rev, undef, $gs) = working_head_info($head);
1051 my $src = $gs->full_pushurl;
1053 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
1054 my $allglobs = $remote->{ $_tag ? 'tags' : 'branches' };
1055 my $glob;
1056 if ($#{$allglobs} == 0) {
1057 $glob = $allglobs->[0];
1058 } else {
1059 unless(defined $_branch_dest) {
1060 die "Multiple ",
1061 $_tag ? "tag" : "branch",
1062 " paths defined for Subversion repository.\n",
1063 "You must specify where you want to create the ",
1064 $_tag ? "tag" : "branch",
1065 " with the --destination argument.\n";
1067 foreach my $g (@{$allglobs}) {
1068 # SVN::Git::Editor could probably be moved to Git.pm..
1069 my $re = SVN::Git::Editor::glob2pat($g->{path}->{left});
1070 if ($_branch_dest =~ /$re/) {
1071 $glob = $g;
1072 last;
1075 unless (defined $glob) {
1076 my $dest_re = qr/\b\Q$_branch_dest\E\b/;
1077 foreach my $g (@{$allglobs}) {
1078 $g->{path}->{left} =~ /$dest_re/ or next;
1079 if (defined $glob) {
1080 die "Ambiguous destination: ",
1081 $_branch_dest, "\nmatches both '",
1082 $glob->{path}->{left}, "' and '",
1083 $g->{path}->{left}, "'\n";
1085 $glob = $g;
1087 unless (defined $glob) {
1088 die "Unknown ",
1089 $_tag ? "tag" : "branch",
1090 " destination $_branch_dest\n";
1094 my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
1095 my $url;
1096 if (defined $_commit_url) {
1097 $url = $_commit_url;
1098 } else {
1099 $url = eval { command_oneline('config', '--get',
1100 "svn-remote.$gs->{repo_id}.commiturl") };
1101 if (!$url) {
1102 $url = $remote->{pushurl} || $remote->{url};
1105 my $dst = join '/', $url, $lft, $branch_name, ($rgt || ());
1107 if ($dst =~ /^https:/ && $src =~ /^http:/) {
1108 $src=~s/^http:/https:/;
1111 ::_req_svn();
1113 my $ctx = SVN::Client->new(
1114 auth => Git::SVN::Ra::_auth_providers(),
1115 log_msg => sub {
1116 ${ $_[0] } = defined $_message
1117 ? $_message
1118 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
1119 . $branch_name;
1123 eval {
1124 $ctx->ls($dst, 'HEAD', 0);
1125 } and die "branch ${branch_name} already exists\n";
1127 print "Copying ${src} at r${rev} to ${dst}...\n";
1128 $ctx->copy($src, $rev, $dst)
1129 unless $_dry_run;
1131 $gs->fetch_all;
1134 sub cmd_find_rev {
1135 my $revision_or_hash = shift or die "SVN or git revision required ",
1136 "as a command-line argument\n";
1137 my $result;
1138 if ($revision_or_hash =~ /^r\d+$/) {
1139 my $head = shift;
1140 $head ||= 'HEAD';
1141 my @refs;
1142 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
1143 unless ($gs) {
1144 die "Unable to determine upstream SVN information from ",
1145 "$head history\n";
1147 my $desired_revision = substr($revision_or_hash, 1);
1148 $result = $gs->rev_map_get($desired_revision, $uuid);
1149 } else {
1150 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
1151 $result = $rev;
1153 print "$result\n" if $result;
1156 sub auto_create_empty_directories {
1157 my ($gs) = @_;
1158 my $var = eval { command_oneline('config', '--get', '--bool',
1159 "svn-remote.$gs->{repo_id}.automkdirs") };
1160 # By default, create empty directories by consulting the unhandled log,
1161 # but allow setting it to 'false' to skip it.
1162 return !($var && $var eq 'false');
1165 sub cmd_rebase {
1166 command_noisy(qw/update-index --refresh/);
1167 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1168 unless ($gs) {
1169 die "Unable to determine upstream SVN information from ",
1170 "working tree history\n";
1172 if ($_dry_run) {
1173 print "Remote Branch: " . $gs->refname . "\n";
1174 print "SVN URL: " . $url . "\n";
1175 return;
1177 if (command(qw/diff-index HEAD --/)) {
1178 print STDERR "Cannot rebase with uncommited changes:\n";
1179 command_noisy('status');
1180 exit 1;
1182 unless ($_local) {
1183 # rebase will checkout for us, so no need to do it explicitly
1184 $_no_checkout = 'true';
1185 $_fetch_all ? $gs->fetch_all : $gs->fetch;
1187 command_noisy(rebase_cmd(), $gs->refname);
1188 if (auto_create_empty_directories($gs)) {
1189 $gs->mkemptydirs;
1193 sub cmd_show_ignore {
1194 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1195 $gs ||= Git::SVN->new;
1196 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1197 $gs->prop_walk($gs->{path}, $r, sub {
1198 my ($gs, $path, $props) = @_;
1199 print STDOUT "\n# $path\n";
1200 my $s = $props->{'svn:ignore'} or return;
1201 $s =~ s/[\r\n]+/\n/g;
1202 $s =~ s/^\n+//;
1203 chomp $s;
1204 $s =~ s#^#$path#gm;
1205 print STDOUT "$s\n";
1209 sub cmd_show_externals {
1210 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1211 $gs ||= Git::SVN->new;
1212 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1213 $gs->prop_walk($gs->{path}, $r, sub {
1214 my ($gs, $path, $props) = @_;
1215 print STDOUT "\n# $path\n";
1216 my $s = $props->{'svn:externals'} or return;
1217 $s =~ s/[\r\n]+/\n/g;
1218 chomp $s;
1219 $s =~ s#^#$path#gm;
1220 print STDOUT "$s\n";
1224 sub cmd_create_ignore {
1225 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1226 $gs ||= Git::SVN->new;
1227 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1228 $gs->prop_walk($gs->{path}, $r, sub {
1229 my ($gs, $path, $props) = @_;
1230 # $path is of the form /path/to/dir/
1231 $path = '.' . $path;
1232 # SVN can have attributes on empty directories,
1233 # which git won't track
1234 mkpath([$path]) unless -d $path;
1235 my $ignore = $path . '.gitignore';
1236 my $s = $props->{'svn:ignore'} or return;
1237 open(GITIGNORE, '>', $ignore)
1238 or fatal("Failed to open `$ignore' for writing: $!");
1239 $s =~ s/[\r\n]+/\n/g;
1240 $s =~ s/^\n+//;
1241 chomp $s;
1242 # Prefix all patterns so that the ignore doesn't apply
1243 # to sub-directories.
1244 $s =~ s#^#/#gm;
1245 print GITIGNORE "$s\n";
1246 close(GITIGNORE)
1247 or fatal("Failed to close `$ignore': $!");
1248 command_noisy('add', '-f', $ignore);
1252 sub cmd_mkdirs {
1253 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1254 $gs ||= Git::SVN->new;
1255 $gs->mkemptydirs($_revision);
1258 sub canonicalize_path {
1259 my ($path) = @_;
1260 my $dot_slash_added = 0;
1261 if (substr($path, 0, 1) ne "/") {
1262 $path = "./" . $path;
1263 $dot_slash_added = 1;
1265 # File::Spec->canonpath doesn't collapse x/../y into y (for a
1266 # good reason), so let's do this manually.
1267 $path =~ s#/+#/#g;
1268 $path =~ s#/\.(?:/|$)#/#g;
1269 $path =~ s#/[^/]+/\.\.##g;
1270 $path =~ s#/$##g;
1271 $path =~ s#^\./## if $dot_slash_added;
1272 $path =~ s#^/##;
1273 $path =~ s#^\.$##;
1274 return $path;
1277 sub canonicalize_url {
1278 my ($url) = @_;
1279 $url =~ s#^([^:]+://[^/]*/)(.*)$#$1 . canonicalize_path($2)#e;
1280 return $url;
1283 # get_svnprops(PATH)
1284 # ------------------
1285 # Helper for cmd_propget and cmd_proplist below.
1286 sub get_svnprops {
1287 my $path = shift;
1288 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1289 $gs ||= Git::SVN->new;
1291 # prefix THE PATH by the sub-directory from which the user
1292 # invoked us.
1293 $path = $cmd_dir_prefix . $path;
1294 fatal("No such file or directory: $path") unless -e $path;
1295 my $is_dir = -d $path ? 1 : 0;
1296 $path = $gs->{path} . '/' . $path;
1298 # canonicalize the path (otherwise libsvn will abort or fail to
1299 # find the file)
1300 $path = canonicalize_path($path);
1302 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1303 my $props;
1304 if ($is_dir) {
1305 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
1307 else {
1308 (undef, $props) = $gs->ra->get_file($path, $r, undef);
1310 return $props;
1313 # cmd_propget (PROP, PATH)
1314 # ------------------------
1315 # Print the SVN property PROP for PATH.
1316 sub cmd_propget {
1317 my ($prop, $path) = @_;
1318 $path = '.' if not defined $path;
1319 usage(1) if not defined $prop;
1320 my $props = get_svnprops($path);
1321 if (not defined $props->{$prop}) {
1322 fatal("`$path' does not have a `$prop' SVN property.");
1324 print $props->{$prop} . "\n";
1327 # cmd_proplist (PATH)
1328 # -------------------
1329 # Print the list of SVN properties for PATH.
1330 sub cmd_proplist {
1331 my $path = shift;
1332 $path = '.' if not defined $path;
1333 my $props = get_svnprops($path);
1334 print "Properties on '$path':\n";
1335 foreach (sort keys %{$props}) {
1336 print " $_\n";
1340 sub cmd_multi_init {
1341 my $url = shift;
1342 unless (defined $_trunk || @_branches || @_tags) {
1343 usage(1);
1346 $_prefix = '' unless defined $_prefix;
1347 if (defined $url) {
1348 $url = canonicalize_url($url);
1349 init_subdir(@_);
1351 do_git_init_db();
1352 if (defined $_trunk) {
1353 $_trunk =~ s#^/+##;
1354 my $trunk_ref = 'refs/remotes/' . $_prefix . 'trunk';
1355 # try both old-style and new-style lookups:
1356 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
1357 unless ($gs_trunk) {
1358 my ($trunk_url, $trunk_path) =
1359 complete_svn_url($url, $_trunk);
1360 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
1361 undef, $trunk_ref);
1364 return unless @_branches || @_tags;
1365 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
1366 foreach my $path (@_branches) {
1367 complete_url_ls_init($ra, $path, '--branches/-b', $_prefix);
1369 foreach my $path (@_tags) {
1370 complete_url_ls_init($ra, $path, '--tags/-t', $_prefix.'tags/');
1374 sub cmd_multi_fetch {
1375 $Git::SVN::no_reuse_existing = undef;
1376 my $remotes = Git::SVN::read_all_remotes();
1377 foreach my $repo_id (sort keys %$remotes) {
1378 if ($remotes->{$repo_id}->{url}) {
1379 Git::SVN::fetch_all($repo_id, $remotes);
1384 # this command is special because it requires no metadata
1385 sub cmd_commit_diff {
1386 my ($ta, $tb, $url) = @_;
1387 my $usage = "Usage: $0 commit-diff -r<revision> ".
1388 "<tree-ish> <tree-ish> [<URL>]";
1389 fatal($usage) if (!defined $ta || !defined $tb);
1390 my $svn_path = '';
1391 if (!defined $url) {
1392 my $gs = eval { Git::SVN->new };
1393 if (!$gs) {
1394 fatal("Needed URL or usable git-svn --id in ",
1395 "the command-line\n", $usage);
1397 $url = $gs->{url};
1398 $svn_path = $gs->{path};
1400 unless (defined $_revision) {
1401 fatal("-r|--revision is a required argument\n", $usage);
1403 if (defined $_message && defined $_file) {
1404 fatal("Both --message/-m and --file/-F specified ",
1405 "for the commit message.\n",
1406 "I have no idea what you mean");
1408 if (defined $_file) {
1409 $_message = file_to_s($_file);
1410 } else {
1411 $_message ||= get_commit_entry($tb)->{log};
1413 my $ra ||= Git::SVN::Ra->new($url);
1414 my $r = $_revision;
1415 if ($r eq 'HEAD') {
1416 $r = $ra->get_latest_revnum;
1417 } elsif ($r !~ /^\d+$/) {
1418 die "revision argument: $r not understood by git-svn\n";
1420 my %ed_opts = ( r => $r,
1421 log => $_message,
1422 ra => $ra,
1423 tree_a => $ta,
1424 tree_b => $tb,
1425 editor_cb => sub { print "Committed r$_[0]\n" },
1426 svn_path => $svn_path );
1427 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
1428 print "No changes\n$ta == $tb\n";
1432 sub escape_uri_only {
1433 my ($uri) = @_;
1434 my @tmp;
1435 foreach (split m{/}, $uri) {
1436 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
1437 push @tmp, $_;
1439 join('/', @tmp);
1442 sub escape_url {
1443 my ($url) = @_;
1444 if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
1445 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
1446 $url = "$scheme://$domain$uri";
1448 $url;
1451 sub cmd_info {
1452 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
1453 my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
1454 if (exists $_[1]) {
1455 die "Too many arguments specified\n";
1458 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
1460 if (!$file_type && !$diff_status) {
1461 print STDERR "svn: '$path' is not under version control\n";
1462 exit 1;
1465 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1466 unless ($gs) {
1467 die "Unable to determine upstream SVN information from ",
1468 "working tree history\n";
1471 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
1472 $path = "." if $path eq "";
1474 my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
1476 if ($_url) {
1477 print escape_url($full_url), "\n";
1478 return;
1481 my $result = "Path: $path\n";
1482 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
1483 $result .= "URL: " . escape_url($full_url) . "\n";
1485 eval {
1486 my $repos_root = $gs->repos_root;
1487 Git::SVN::remove_username($repos_root);
1488 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
1490 if ($@) {
1491 $result .= "Repository Root: (offline)\n";
1493 ::_req_svn();
1494 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
1495 (::compare_svn_version('1.5.4') <= 0 || $file_type ne "dir");
1496 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
1498 $result .= "Node Kind: " .
1499 ($file_type eq "dir" ? "directory" : "file") . "\n";
1501 my $schedule = $diff_status eq "A"
1502 ? "add"
1503 : ($diff_status eq "D" ? "delete" : "normal");
1504 $result .= "Schedule: $schedule\n";
1506 if ($diff_status eq "A") {
1507 print $result, "\n";
1508 return;
1511 my ($lc_author, $lc_rev, $lc_date_utc);
1512 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
1513 my $log = command_output_pipe(@args);
1514 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
1515 while (<$log>) {
1516 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
1517 $lc_author = $1;
1518 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
1519 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
1520 (undef, $lc_rev, undef) = ::extract_metadata($1);
1523 close $log;
1525 Git::SVN::Log::set_local_timezone();
1527 $result .= "Last Changed Author: $lc_author\n";
1528 $result .= "Last Changed Rev: $lc_rev\n";
1529 $result .= "Last Changed Date: " .
1530 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
1532 if ($file_type ne "dir") {
1533 my $text_last_updated_date =
1534 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
1535 $result .=
1536 "Text Last Updated: " .
1537 Git::SVN::Log::format_svn_date($text_last_updated_date) .
1538 "\n";
1539 my $checksum;
1540 if ($diff_status eq "D") {
1541 my ($fh, $ctx) =
1542 command_output_pipe(qw(cat-file blob), "HEAD:$path");
1543 if ($file_type eq "link") {
1544 my $file_name = <$fh>;
1545 $checksum = md5sum("link $file_name");
1546 } else {
1547 $checksum = md5sum($fh);
1549 command_close_pipe($fh, $ctx);
1550 } elsif ($file_type eq "link") {
1551 my $file_name =
1552 command(qw(cat-file blob), "HEAD:$path");
1553 $checksum =
1554 md5sum("link " . $file_name);
1555 } else {
1556 open FILE, "<", $path or die $!;
1557 $checksum = md5sum(\*FILE);
1558 close FILE or die $!;
1560 $result .= "Checksum: " . $checksum . "\n";
1563 print $result, "\n";
1566 sub cmd_reset {
1567 my $target = shift || $_revision or die "SVN revision required\n";
1568 $target = $1 if $target =~ /^r(\d+)$/;
1569 $target =~ /^\d+$/ or die "Numeric SVN revision expected\n";
1570 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1571 unless ($gs) {
1572 die "Unable to determine upstream SVN information from ".
1573 "history\n";
1575 my ($r, $c) = $gs->find_rev_before($target, not $_fetch_parent);
1576 die "Cannot find SVN revision $target\n" unless defined($c);
1577 $gs->rev_map_set($r, $c, 'reset', $uuid);
1578 print "r$r = $c ($gs->{ref_id})\n";
1581 sub cmd_gc {
1582 if (!$can_compress) {
1583 warn "Compress::Zlib could not be found; unhandled.log " .
1584 "files will not be compressed.\n";
1586 find({ wanted => \&gc_directory, no_chdir => 1}, "$ENV{GIT_DIR}/svn");
1589 ########################### utility functions #########################
1591 sub rebase_cmd {
1592 my @cmd = qw/rebase/;
1593 push @cmd, '-v' if $_verbose;
1594 push @cmd, qw/--merge/ if $_merge;
1595 push @cmd, "--strategy=$_strategy" if $_strategy;
1596 push @cmd, "--preserve-merges" if $_preserve_merges;
1597 @cmd;
1600 sub post_fetch_checkout {
1601 return if $_no_checkout;
1602 my $gs = $Git::SVN::_head or return;
1603 return if verify_ref('refs/heads/master^0');
1605 # look for "trunk" ref if it exists
1606 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
1607 my $fetch = $remote->{fetch};
1608 if ($fetch) {
1609 foreach my $p (keys %$fetch) {
1610 basename($fetch->{$p}) eq 'trunk' or next;
1611 $gs = Git::SVN->new($fetch->{$p}, $gs->{repo_id}, $p);
1612 last;
1616 my $valid_head = verify_ref('HEAD^0');
1617 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1618 return if ($valid_head || !verify_ref('HEAD^0'));
1620 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1621 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1622 return if -f $index;
1624 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1625 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1626 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1627 print STDERR "Checked out HEAD:\n ",
1628 $gs->full_url, " r", $gs->last_rev, "\n";
1629 if (auto_create_empty_directories($gs)) {
1630 $gs->mkemptydirs($gs->last_rev);
1634 sub complete_svn_url {
1635 my ($url, $path) = @_;
1636 $path =~ s#/+$##;
1637 if ($path !~ m#^[a-z\+]+://#) {
1638 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1639 fatal("E: '$path' is not a complete URL ",
1640 "and a separate URL is not specified");
1642 return ($url, $path);
1644 return ($path, '');
1647 sub complete_url_ls_init {
1648 my ($ra, $repo_path, $switch, $pfx) = @_;
1649 unless ($repo_path) {
1650 print STDERR "W: $switch not specified\n";
1651 return;
1653 $repo_path =~ s#/+$##;
1654 if ($repo_path =~ m#^[a-z\+]+://#) {
1655 $ra = Git::SVN::Ra->new($repo_path);
1656 $repo_path = '';
1657 } else {
1658 $repo_path =~ s#^/+##;
1659 unless ($ra) {
1660 fatal("E: '$repo_path' is not a complete URL ",
1661 "and a separate URL is not specified");
1664 my $url = $ra->{url};
1665 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1666 my $k = "svn-remote.$gs->{repo_id}.url";
1667 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1668 if ($orig_url && ($orig_url ne $gs->{url})) {
1669 die "$k already set: $orig_url\n",
1670 "wanted to set to: $gs->{url}\n";
1672 command_oneline('config', $k, $gs->{url}) unless $orig_url;
1673 my $remote_path = "$gs->{path}/$repo_path";
1674 $remote_path =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
1675 $remote_path =~ s#/+#/#g;
1676 $remote_path =~ s#^/##g;
1677 $remote_path .= "/*" if $remote_path !~ /\*/;
1678 my ($n) = ($switch =~ /^--(\w+)/);
1679 if (length $pfx && $pfx !~ m#/$#) {
1680 die "--prefix='$pfx' must have a trailing slash '/'\n";
1682 command_noisy('config',
1683 '--add',
1684 "svn-remote.$gs->{repo_id}.$n",
1685 "$remote_path:refs/remotes/$pfx*" .
1686 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1689 sub verify_ref {
1690 my ($ref) = @_;
1691 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1692 { STDERR => 0 }); };
1695 sub get_tree_from_treeish {
1696 my ($treeish) = @_;
1697 # $treeish can be a symbolic ref, too:
1698 my $type = command_oneline(qw/cat-file -t/, $treeish);
1699 my $expected;
1700 while ($type eq 'tag') {
1701 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1703 if ($type eq 'commit') {
1704 $expected = (grep /^tree /, command(qw/cat-file commit/,
1705 $treeish))[0];
1706 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1707 die "Unable to get tree from $treeish\n" unless $expected;
1708 } elsif ($type eq 'tree') {
1709 $expected = $treeish;
1710 } else {
1711 die "$treeish is a $type, expected tree, tag or commit\n";
1713 return $expected;
1716 sub get_commit_entry {
1717 my ($treeish) = shift;
1718 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1719 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1720 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1721 open my $log_fh, '>', $commit_editmsg or croak $!;
1723 my $type = command_oneline(qw/cat-file -t/, $treeish);
1724 if ($type eq 'commit' || $type eq 'tag') {
1725 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1726 $type, $treeish);
1727 my $in_msg = 0;
1728 my $author;
1729 my $saw_from = 0;
1730 my $msgbuf = "";
1731 while (<$msg_fh>) {
1732 if (!$in_msg) {
1733 $in_msg = 1 if (/^\s*$/);
1734 $author = $1 if (/^author (.*>)/);
1735 } elsif (/^git-svn-id: /) {
1736 # skip this for now, we regenerate the
1737 # correct one on re-fetch anyways
1738 # TODO: set *:merge properties or like...
1739 } else {
1740 if (/^From:/ || /^Signed-off-by:/) {
1741 $saw_from = 1;
1743 $msgbuf .= $_;
1746 $msgbuf =~ s/\s+$//s;
1747 if ($Git::SVN::_add_author_from && defined($author)
1748 && !$saw_from) {
1749 $msgbuf .= "\n\nFrom: $author";
1751 print $log_fh $msgbuf or croak $!;
1752 command_close_pipe($msg_fh, $ctx);
1754 close $log_fh or croak $!;
1756 if ($_edit || ($type eq 'tree')) {
1757 chomp(my $editor = command_oneline(qw(var GIT_EDITOR)));
1758 system('sh', '-c', $editor.' "$@"', $editor, $commit_editmsg);
1760 rename $commit_editmsg, $commit_msg or croak $!;
1762 require Encode;
1763 # SVN requires messages to be UTF-8 when entering the repo
1764 local $/;
1765 open $log_fh, '<', $commit_msg or croak $!;
1766 binmode $log_fh;
1767 chomp($log_entry{log} = <$log_fh>);
1769 my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
1770 my $msg = $log_entry{log};
1772 eval { $msg = Encode::decode($enc, $msg, 1) };
1773 if ($@) {
1774 die "Could not decode as $enc:\n", $msg,
1775 "\nPerhaps you need to set i18n.commitencoding\n";
1778 eval { $msg = Encode::encode('UTF-8', $msg, 1) };
1779 die "Could not encode as UTF-8:\n$msg\n" if $@;
1781 $log_entry{log} = $msg;
1783 close $log_fh or croak $!;
1785 unlink $commit_msg;
1786 \%log_entry;
1789 sub s_to_file {
1790 my ($str, $file, $mode) = @_;
1791 open my $fd,'>',$file or croak $!;
1792 print $fd $str,"\n" or croak $!;
1793 close $fd or croak $!;
1794 chmod ($mode &~ umask, $file) if (defined $mode);
1797 sub file_to_s {
1798 my $file = shift;
1799 open my $fd,'<',$file or croak "$!: file: $file\n";
1800 local $/;
1801 my $ret = <$fd>;
1802 close $fd or croak $!;
1803 $ret =~ s/\s*$//s;
1804 return $ret;
1807 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1808 sub load_authors {
1809 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1810 my $log = $cmd eq 'log';
1811 while (<$authors>) {
1812 chomp;
1813 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1814 my ($user, $name, $email) = ($1, $2, $3);
1815 if ($log) {
1816 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1817 } else {
1818 $users{$user} = [$name, $email];
1821 close $authors or croak $!;
1824 # convert GetOpt::Long specs for use by git-config
1825 sub read_git_config {
1826 my $opts = shift;
1827 my @config_only;
1828 foreach my $o (keys %$opts) {
1829 # if we have mixedCase and a long option-only, then
1830 # it's a config-only variable that we don't need for
1831 # the command-line.
1832 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1833 my $v = $opts->{$o};
1834 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1835 $key =~ s/-//g;
1836 my $arg = 'git config';
1837 $arg .= ' --int' if ($o =~ /[:=]i$/);
1838 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1839 if (ref $v eq 'ARRAY') {
1840 chomp(my @tmp = `$arg --get-all svn.$key`);
1841 @$v = @tmp if @tmp;
1842 } else {
1843 chomp(my $tmp = `$arg --get svn.$key`);
1844 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1845 $$v = $tmp;
1849 delete @$opts{@config_only} if @config_only;
1852 sub extract_metadata {
1853 my $id = shift or return (undef, undef, undef);
1854 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1855 \s([a-f\d\-]+)$/ix);
1856 if (!defined $rev || !$uuid || !$url) {
1857 # some of the original repositories I made had
1858 # identifiers like this:
1859 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/i);
1861 return ($url, $rev, $uuid);
1864 sub cmt_metadata {
1865 return extract_metadata((grep(/^git-svn-id: /,
1866 command(qw/cat-file commit/, shift)))[-1]);
1869 sub cmt_sha2rev_batch {
1870 my %s2r;
1871 my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1872 my $list = shift;
1874 foreach my $sha (@{$list}) {
1875 my $first = 1;
1876 my $size = 0;
1877 print $out $sha, "\n";
1879 while (my $line = <$in>) {
1880 if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1881 last;
1882 } elsif ($first &&
1883 $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1884 $first = 0;
1885 $size = $1;
1886 next;
1887 } elsif ($line =~ /^(git-svn-id: )/) {
1888 my (undef, $rev, undef) =
1889 extract_metadata($line);
1890 $s2r{$sha} = $rev;
1893 $size -= length($line);
1894 last if ($size == 0);
1898 command_close_bidi_pipe($pid, $in, $out, $ctx);
1900 return \%s2r;
1903 sub working_head_info {
1904 my ($head, $refs) = @_;
1905 my @args = qw/rev-list --first-parent --pretty=medium/;
1906 my ($fh, $ctx) = command_output_pipe(@args, $head);
1907 my $hash;
1908 my %max;
1909 while (<$fh>) {
1910 if ( m{^commit ($::sha1)$} ) {
1911 unshift @$refs, $hash if $hash and $refs;
1912 $hash = $1;
1913 next;
1915 next unless s{^\s*(git-svn-id:)}{$1};
1916 my ($url, $rev, $uuid) = extract_metadata($_);
1917 if (defined $url && defined $rev) {
1918 next if $max{$url} and $max{$url} < $rev;
1919 if (my $gs = Git::SVN->find_by_url($url)) {
1920 my $c = $gs->rev_map_get($rev, $uuid);
1921 if ($c && $c eq $hash) {
1922 close $fh; # break the pipe
1923 return ($url, $rev, $uuid, $gs);
1924 } else {
1925 $max{$url} ||= $gs->rev_map_max;
1930 command_close_pipe($fh, $ctx);
1931 (undef, undef, undef, undef);
1934 sub read_commit_parents {
1935 my ($parents, $c) = @_;
1936 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1937 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1938 @{$parents->{$c}} = split(/ /, $p);
1941 sub linearize_history {
1942 my ($gs, $refs) = @_;
1943 my %parents;
1944 foreach my $c (@$refs) {
1945 read_commit_parents(\%parents, $c);
1948 my @linear_refs;
1949 my %skip = ();
1950 my $last_svn_commit = $gs->last_commit;
1951 foreach my $c (reverse @$refs) {
1952 next if $c eq $last_svn_commit;
1953 last if $skip{$c};
1955 unshift @linear_refs, $c;
1956 $skip{$c} = 1;
1958 # we only want the first parent to diff against for linear
1959 # history, we save the rest to inject when we finalize the
1960 # svn commit
1961 my $fp_a = verify_ref("$c~1");
1962 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1963 if (!$fp_a || !$fp_b) {
1964 die "Commit $c\n",
1965 "has no parent commit, and therefore ",
1966 "nothing to diff against.\n",
1967 "You should be working from a repository ",
1968 "originally created by git-svn\n";
1970 if ($fp_a ne $fp_b) {
1971 die "$c~1 = $fp_a, however parsing commit $c ",
1972 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1975 foreach my $p (@{$parents{$c}}) {
1976 $skip{$p} = 1;
1979 (\@linear_refs, \%parents);
1982 sub find_file_type_and_diff_status {
1983 my ($path) = @_;
1984 return ('dir', '') if $path eq '';
1986 my $diff_output =
1987 command_oneline(qw(diff --cached --name-status --), $path) || "";
1988 my $diff_status = (split(' ', $diff_output))[0] || "";
1990 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1992 return (undef, undef) if !$diff_status && !$ls_tree;
1994 if ($diff_status eq "A") {
1995 return ("link", $diff_status) if -l $path;
1996 return ("dir", $diff_status) if -d $path;
1997 return ("file", $diff_status);
2000 my $mode = (split(' ', $ls_tree))[0] || "";
2002 return ("link", $diff_status) if $mode eq "120000";
2003 return ("dir", $diff_status) if $mode eq "040000";
2004 return ("file", $diff_status);
2007 sub md5sum {
2008 my $arg = shift;
2009 my $ref = ref $arg;
2010 my $md5 = Digest::MD5->new();
2011 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
2012 $md5->addfile($arg) or croak $!;
2013 } elsif ($ref eq 'SCALAR') {
2014 $md5->add($$arg) or croak $!;
2015 } elsif (!$ref) {
2016 $md5->add($arg) or croak $!;
2017 } else {
2018 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
2020 return $md5->hexdigest();
2023 sub gc_directory {
2024 if ($can_compress && -f $_ && basename($_) eq "unhandled.log") {
2025 my $out_filename = $_ . ".gz";
2026 open my $in_fh, "<", $_ or die "Unable to open $_: $!\n";
2027 binmode $in_fh;
2028 my $gz = Compress::Zlib::gzopen($out_filename, "ab") or
2029 die "Unable to open $out_filename: $!\n";
2031 my $res;
2032 while ($res = sysread($in_fh, my $str, 1024)) {
2033 $gz->gzwrite($str) or
2034 die "Unable to write: ".$gz->gzerror()."!\n";
2036 unlink $_ or die "unlink $File::Find::name: $!\n";
2037 } elsif (-f $_ && basename($_) eq "index") {
2038 unlink $_ or die "unlink $_: $!\n";
2042 package Git::SVN;
2043 use strict;
2044 use warnings;
2045 use Fcntl qw/:DEFAULT :seek/;
2046 use constant rev_map_fmt => 'NH40';
2047 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
2048 $_repack $_repack_flags $_use_svm_props $_head
2049 $_use_svnsync_props $no_reuse_existing $_minimize_url
2050 $_use_log_author $_add_author_from $_localtime/;
2051 use Carp qw/croak/;
2052 use File::Path qw/mkpath/;
2053 use File::Copy qw/copy/;
2054 use IPC::Open3;
2055 use Time::Local;
2056 use Memoize; # core since 5.8.0, Jul 2002
2057 use Memoize::Storable;
2058 use POSIX qw(:signal_h);
2060 my ($_gc_nr, $_gc_period);
2062 # properties that we do not log:
2063 my %SKIP_PROP;
2064 BEGIN {
2065 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
2066 svn:special svn:executable
2067 svn:entry:committed-rev
2068 svn:entry:last-author
2069 svn:entry:uuid
2070 svn:entry:committed-date/;
2072 # some options are read globally, but can be overridden locally
2073 # per [svn-remote "..."] section. Command-line options will *NOT*
2074 # override options set in an [svn-remote "..."] section
2075 no strict 'refs';
2076 for my $option (qw/follow_parent no_metadata use_svm_props
2077 use_svnsync_props/) {
2078 my $key = $option;
2079 $key =~ tr/_//d;
2080 my $prop = "-$option";
2081 *$option = sub {
2082 my ($self) = @_;
2083 return $self->{$prop} if exists $self->{$prop};
2084 my $k = "svn-remote.$self->{repo_id}.$key";
2085 eval { command_oneline(qw/config --get/, $k) };
2086 if ($@) {
2087 $self->{$prop} = ${"Git::SVN::_$option"};
2088 } else {
2089 my $v = command_oneline(qw/config --bool/,$k);
2090 $self->{$prop} = $v eq 'false' ? 0 : 1;
2092 return $self->{$prop};
2098 my (%LOCKFILES, %INDEX_FILES);
2099 END {
2100 unlink keys %LOCKFILES if %LOCKFILES;
2101 unlink keys %INDEX_FILES if %INDEX_FILES;
2104 sub resolve_local_globs {
2105 my ($url, $fetch, $glob_spec) = @_;
2106 return unless defined $glob_spec;
2107 my $ref = $glob_spec->{ref};
2108 my $path = $glob_spec->{path};
2109 foreach (command(qw#for-each-ref --format=%(refname) refs/#)) {
2110 next unless m#^$ref->{regex}$#;
2111 my $p = $1;
2112 my $pathname = desanitize_refname($path->full_path($p));
2113 my $refname = desanitize_refname($ref->full_path($p));
2114 if (my $existing = $fetch->{$pathname}) {
2115 if ($existing ne $refname) {
2116 die "Refspec conflict:\n",
2117 "existing: $existing\n",
2118 " globbed: $refname\n";
2120 my $u = (::cmt_metadata("$refname"))[0];
2121 $u =~ s!^\Q$url\E(/|$)!! or die
2122 "$refname: '$url' not found in '$u'\n";
2123 if ($pathname ne $u) {
2124 warn "W: Refspec glob conflict ",
2125 "(ref: $refname):\n",
2126 "expected path: $pathname\n",
2127 " real path: $u\n",
2128 "Continuing ahead with $u\n";
2129 next;
2131 } else {
2132 $fetch->{$pathname} = $refname;
2137 sub parse_revision_argument {
2138 my ($base, $head) = @_;
2139 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
2140 return ($base, $head);
2142 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
2143 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
2144 return ($head, $head) if ($::_revision eq 'HEAD');
2145 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
2146 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
2147 die "revision argument: $::_revision not understood by git-svn\n";
2150 sub fetch_all {
2151 my ($repo_id, $remotes) = @_;
2152 if (ref $repo_id) {
2153 my $gs = $repo_id;
2154 $repo_id = undef;
2155 $repo_id = $gs->{repo_id};
2157 $remotes ||= read_all_remotes();
2158 my $remote = $remotes->{$repo_id} or
2159 die "[svn-remote \"$repo_id\"] unknown\n";
2160 my $fetch = $remote->{fetch};
2161 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
2162 my (@gs, @globs);
2163 my $ra = Git::SVN::Ra->new($url);
2164 my $uuid = $ra->get_uuid;
2165 my $head = $ra->get_latest_revnum;
2167 # ignore errors, $head revision may not even exist anymore
2168 eval { $ra->get_log("", $head, 0, 1, 0, 1, sub { $head = $_[1] }) };
2169 warn "W: $@\n" if $@;
2171 my $base = defined $fetch ? $head : 0;
2173 # read the max revs for wildcard expansion (branches/*, tags/*)
2174 foreach my $t (qw/branches tags/) {
2175 defined $remote->{$t} or next;
2176 push @globs, @{$remote->{$t}};
2178 my $max_rev = eval { tmp_config(qw/--int --get/,
2179 "svn-remote.$repo_id.${t}-maxRev") };
2180 if (defined $max_rev && ($max_rev < $base)) {
2181 $base = $max_rev;
2182 } elsif (!defined $max_rev) {
2183 $base = 0;
2187 if ($fetch) {
2188 foreach my $p (sort keys %$fetch) {
2189 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
2190 my $lr = $gs->rev_map_max;
2191 if (defined $lr) {
2192 $base = $lr if ($lr < $base);
2194 push @gs, $gs;
2198 ($base, $head) = parse_revision_argument($base, $head);
2199 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
2202 sub read_all_remotes {
2203 my $r = {};
2204 my $use_svm_props = eval { command_oneline(qw/config --bool
2205 svn.useSvmProps/) };
2206 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
2207 my $svn_refspec = qr{\s*(.*?)\s*:\s*(.+?)\s*};
2208 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
2209 if (m!^(.+)\.fetch=$svn_refspec$!) {
2210 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
2211 die("svn-remote.$remote: remote ref '$remote_ref' "
2212 . "must start with 'refs/'\n")
2213 unless $remote_ref =~ m{^refs/};
2214 $local_ref = uri_decode($local_ref);
2215 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
2216 $r->{$remote}->{svm} = {} if $use_svm_props;
2217 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
2218 $r->{$1}->{svm} = {};
2219 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
2220 $r->{$1}->{url} = $2;
2221 } elsif (m!^(.+)\.pushurl=\s*(.*)\s*$!) {
2222 $r->{$1}->{pushurl} = $2;
2223 } elsif (m!^(.+)\.ignore-refs=\s*(.*)\s*$!) {
2224 $r->{$1}->{ignore_refs_regex} = $2;
2225 } elsif (m!^(.+)\.(branches|tags)=$svn_refspec$!) {
2226 my ($remote, $t, $local_ref, $remote_ref) =
2227 ($1, $2, $3, $4);
2228 die("svn-remote.$remote: remote ref '$remote_ref' ($t) "
2229 . "must start with 'refs/'\n")
2230 unless $remote_ref =~ m{^refs/};
2231 $local_ref = uri_decode($local_ref);
2232 my $rs = {
2233 t => $t,
2234 remote => $remote,
2235 path => Git::SVN::GlobSpec->new($local_ref, 1),
2236 ref => Git::SVN::GlobSpec->new($remote_ref, 0) };
2237 if (length($rs->{ref}->{right}) != 0) {
2238 die "The '*' glob character must be the last ",
2239 "character of '$remote_ref'\n";
2241 push @{ $r->{$remote}->{$t} }, $rs;
2245 map {
2246 if (defined $r->{$_}->{svm}) {
2247 my $svm;
2248 eval {
2249 my $section = "svn-remote.$_";
2250 $svm = {
2251 source => tmp_config('--get',
2252 "$section.svm-source"),
2253 replace => tmp_config('--get',
2254 "$section.svm-replace"),
2257 $r->{$_}->{svm} = $svm;
2259 } keys %$r;
2261 foreach my $remote (keys %$r) {
2262 foreach ( grep { defined $_ }
2263 map { $r->{$remote}->{$_} } qw(branches tags) ) {
2264 foreach my $rs ( @$_ ) {
2265 $rs->{ignore_refs_regex} =
2266 $r->{$remote}->{ignore_refs_regex};
2274 sub init_vars {
2275 $_gc_nr = $_gc_period = 1000;
2276 if (defined $_repack || defined $_repack_flags) {
2277 warn "Repack options are obsolete; they have no effect.\n";
2281 sub verify_remotes_sanity {
2282 return unless -d $ENV{GIT_DIR};
2283 my %seen;
2284 foreach (command(qw/config -l/)) {
2285 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
2286 if ($seen{$1}) {
2287 die "Remote ref refs/remote/$1 is tracked by",
2288 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
2289 "Please resolve this ambiguity in ",
2290 "your git configuration file before ",
2291 "continuing\n";
2293 $seen{$1} = $_;
2298 sub find_existing_remote {
2299 my ($url, $remotes) = @_;
2300 return undef if $no_reuse_existing;
2301 my $existing;
2302 foreach my $repo_id (keys %$remotes) {
2303 my $u = $remotes->{$repo_id}->{url} or next;
2304 next if $u ne $url;
2305 $existing = $repo_id;
2306 last;
2308 $existing;
2311 sub init_remote_config {
2312 my ($self, $url, $no_write) = @_;
2313 $url =~ s!/+$!!; # strip trailing slash
2314 my $r = read_all_remotes();
2315 my $existing = find_existing_remote($url, $r);
2316 if ($existing) {
2317 unless ($no_write) {
2318 print STDERR "Using existing ",
2319 "[svn-remote \"$existing\"]\n";
2321 $self->{repo_id} = $existing;
2322 } elsif ($_minimize_url) {
2323 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
2324 $existing = find_existing_remote($min_url, $r);
2325 if ($existing) {
2326 unless ($no_write) {
2327 print STDERR "Using existing ",
2328 "[svn-remote \"$existing\"]\n";
2330 $self->{repo_id} = $existing;
2332 if ($min_url ne $url) {
2333 unless ($no_write) {
2334 print STDERR "Using higher level of URL: ",
2335 "$url => $min_url\n";
2337 my $old_path = $self->{path};
2338 $self->{path} = $url;
2339 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
2340 if (length $old_path) {
2341 $self->{path} .= "/$old_path";
2343 $url = $min_url;
2346 my $orig_url;
2347 if (!$existing) {
2348 # verify that we aren't overwriting anything:
2349 $orig_url = eval {
2350 command_oneline('config', '--get',
2351 "svn-remote.$self->{repo_id}.url")
2353 if ($orig_url && ($orig_url ne $url)) {
2354 die "svn-remote.$self->{repo_id}.url already set: ",
2355 "$orig_url\nwanted to set to: $url\n";
2358 my ($xrepo_id, $xpath) = find_ref($self->refname);
2359 if (!$no_write && defined $xpath) {
2360 die "svn-remote.$xrepo_id.fetch already set to track ",
2361 "$xpath:", $self->refname, "\n";
2363 unless ($no_write) {
2364 command_noisy('config',
2365 "svn-remote.$self->{repo_id}.url", $url);
2366 $self->{path} =~ s{^/}{};
2367 $self->{path} =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
2368 command_noisy('config', '--add',
2369 "svn-remote.$self->{repo_id}.fetch",
2370 "$self->{path}:".$self->refname);
2372 $self->{url} = $url;
2375 sub find_by_url { # repos_root and, path are optional
2376 my ($class, $full_url, $repos_root, $path) = @_;
2378 return undef unless defined $full_url;
2379 remove_username($full_url);
2380 remove_username($repos_root) if defined $repos_root;
2381 my $remotes = read_all_remotes();
2382 if (defined $full_url && defined $repos_root && !defined $path) {
2383 $path = $full_url;
2384 $path =~ s#^\Q$repos_root\E(?:/|$)##;
2386 foreach my $repo_id (keys %$remotes) {
2387 my $u = $remotes->{$repo_id}->{url} or next;
2388 remove_username($u);
2389 next if defined $repos_root && $repos_root ne $u;
2391 my $fetch = $remotes->{$repo_id}->{fetch} || {};
2392 foreach my $t (qw/branches tags/) {
2393 foreach my $globspec (@{$remotes->{$repo_id}->{$t}}) {
2394 resolve_local_globs($u, $fetch, $globspec);
2397 my $p = $path;
2398 my $rwr = rewrite_root({repo_id => $repo_id});
2399 my $svm = $remotes->{$repo_id}->{svm}
2400 if defined $remotes->{$repo_id}->{svm};
2401 unless (defined $p) {
2402 $p = $full_url;
2403 my $z = $u;
2404 my $prefix = '';
2405 if ($rwr) {
2406 $z = $rwr;
2407 remove_username($z);
2408 } elsif (defined $svm) {
2409 $z = $svm->{source};
2410 $prefix = $svm->{replace};
2411 $prefix =~ s#^\Q$u\E(?:/|$)##;
2412 $prefix =~ s#/$##;
2414 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
2416 foreach my $f (keys %$fetch) {
2417 next if $f ne $p;
2418 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
2421 undef;
2424 sub init {
2425 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
2426 my $self = _new($class, $repo_id, $ref_id, $path);
2427 if (defined $url) {
2428 $self->init_remote_config($url, $no_write);
2430 $self;
2433 sub find_ref {
2434 my ($ref_id) = @_;
2435 foreach (command(qw/config -l/)) {
2436 next unless m!^svn-remote\.(.+)\.fetch=
2437 \s*(.*?)\s*:\s*(.+?)\s*$!x;
2438 my ($repo_id, $path, $ref) = ($1, $2, $3);
2439 if ($ref eq $ref_id) {
2440 $path = '' if ($path =~ m#^\./?#);
2441 return ($repo_id, $path);
2444 (undef, undef, undef);
2447 sub new {
2448 my ($class, $ref_id, $repo_id, $path) = @_;
2449 if (defined $ref_id && !defined $repo_id && !defined $path) {
2450 ($repo_id, $path) = find_ref($ref_id);
2451 if (!defined $repo_id) {
2452 die "Could not find a \"svn-remote.*.fetch\" key ",
2453 "in the repository configuration matching: ",
2454 "$ref_id\n";
2457 my $self = _new($class, $repo_id, $ref_id, $path);
2458 if (!defined $self->{path} || !length $self->{path}) {
2459 my $fetch = command_oneline('config', '--get',
2460 "svn-remote.$repo_id.fetch",
2461 ":$ref_id\$") or
2462 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
2463 "\":$ref_id\$\" in config\n";
2464 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
2466 $self->{path} =~ s{/+}{/}g;
2467 $self->{path} =~ s{\A/}{};
2468 $self->{path} =~ s{/\z}{};
2469 $self->{url} = command_oneline('config', '--get',
2470 "svn-remote.$repo_id.url") or
2471 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
2472 $self->{pushurl} = eval { command_oneline('config', '--get',
2473 "svn-remote.$repo_id.pushurl") };
2474 $self->rebuild;
2475 $self;
2478 sub refname {
2479 my ($refname) = $_[0]->{ref_id} ;
2481 # It cannot end with a slash /, we'll throw up on this because
2482 # SVN can't have directories with a slash in their name, either:
2483 if ($refname =~ m{/$}) {
2484 die "ref: '$refname' ends with a trailing slash, this is ",
2485 "not permitted by git nor Subversion\n";
2488 # It cannot have ASCII control character space, tilde ~, caret ^,
2489 # colon :, question-mark ?, asterisk *, space, or open bracket [
2490 # anywhere.
2492 # Additionally, % must be escaped because it is used for escaping
2493 # and we want our escaped refname to be reversible
2494 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
2496 # no slash-separated component can begin with a dot .
2497 # /.* becomes /%2E*
2498 $refname =~ s{/\.}{/%2E}g;
2500 # It cannot have two consecutive dots .. anywhere
2501 # .. becomes %2E%2E
2502 $refname =~ s{\.\.}{%2E%2E}g;
2504 # trailing dots and .lock are not allowed
2505 # .$ becomes %2E and .lock becomes %2Elock
2506 $refname =~ s{\.(?=$|lock$)}{%2E};
2508 # the sequence @{ is used to access the reflog
2509 # @{ becomes %40{
2510 $refname =~ s{\@\{}{%40\{}g;
2512 return $refname;
2515 sub desanitize_refname {
2516 my ($refname) = @_;
2517 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
2518 return $refname;
2521 sub svm_uuid {
2522 my ($self) = @_;
2523 return $self->{svm}->{uuid} if $self->svm;
2524 $self->ra;
2525 unless ($self->{svm}) {
2526 die "SVM UUID not cached, and reading remotely failed\n";
2528 $self->{svm}->{uuid};
2531 sub svm {
2532 my ($self) = @_;
2533 return $self->{svm} if $self->{svm};
2534 my $svm;
2535 # see if we have it in our config, first:
2536 eval {
2537 my $section = "svn-remote.$self->{repo_id}";
2538 $svm = {
2539 source => tmp_config('--get', "$section.svm-source"),
2540 uuid => tmp_config('--get', "$section.svm-uuid"),
2541 replace => tmp_config('--get', "$section.svm-replace"),
2544 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
2545 $self->{svm} = $svm;
2547 $self->{svm};
2550 sub _set_svm_vars {
2551 my ($self, $ra) = @_;
2552 return $ra if $self->svm;
2554 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
2555 "(svm:source, svm:uuid) ",
2556 "from the following URLs:\n" );
2557 sub read_svm_props {
2558 my ($self, $ra, $path, $r) = @_;
2559 my $props = ($ra->get_dir($path, $r))[2];
2560 my $src = $props->{'svm:source'};
2561 my $uuid = $props->{'svm:uuid'};
2562 return undef if (!$src || !$uuid);
2564 chomp($src, $uuid);
2566 $uuid =~ m{^[0-9a-f\-]{30,}$}i
2567 or die "doesn't look right - svm:uuid is '$uuid'\n";
2569 # the '!' is used to mark the repos_root!/relative/path
2570 $src =~ s{/?!/?}{/};
2571 $src =~ s{/+$}{}; # no trailing slashes please
2572 # username is of no interest
2573 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
2575 my $replace = $ra->{url};
2576 $replace .= "/$path" if length $path;
2578 my $section = "svn-remote.$self->{repo_id}";
2579 tmp_config("$section.svm-source", $src);
2580 tmp_config("$section.svm-replace", $replace);
2581 tmp_config("$section.svm-uuid", $uuid);
2582 $self->{svm} = {
2583 source => $src,
2584 uuid => $uuid,
2585 replace => $replace
2589 my $r = $ra->get_latest_revnum;
2590 my $path = $self->{path};
2591 my %tried;
2592 while (length $path) {
2593 unless ($tried{"$self->{url}/$path"}) {
2594 return $ra if $self->read_svm_props($ra, $path, $r);
2595 $tried{"$self->{url}/$path"} = 1;
2597 $path =~ s#/?[^/]+$##;
2599 die "Path: '$path' should be ''\n" if $path ne '';
2600 return $ra if $self->read_svm_props($ra, $path, $r);
2601 $tried{"$self->{url}/$path"} = 1;
2603 if ($ra->{repos_root} eq $self->{url}) {
2604 die @err, (map { " $_\n" } keys %tried), "\n";
2607 # nope, make sure we're connected to the repository root:
2608 my $ok;
2609 my @tried_b;
2610 $path = $ra->{svn_path};
2611 $ra = Git::SVN::Ra->new($ra->{repos_root});
2612 while (length $path) {
2613 unless ($tried{"$ra->{url}/$path"}) {
2614 $ok = $self->read_svm_props($ra, $path, $r);
2615 last if $ok;
2616 $tried{"$ra->{url}/$path"} = 1;
2618 $path =~ s#/?[^/]+$##;
2620 die "Path: '$path' should be ''\n" if $path ne '';
2621 $ok ||= $self->read_svm_props($ra, $path, $r);
2622 $tried{"$ra->{url}/$path"} = 1;
2623 if (!$ok) {
2624 die @err, (map { " $_\n" } keys %tried), "\n";
2626 Git::SVN::Ra->new($self->{url});
2629 sub svnsync {
2630 my ($self) = @_;
2631 return $self->{svnsync} if $self->{svnsync};
2633 if ($self->no_metadata) {
2634 die "Can't have both 'noMetadata' and ",
2635 "'useSvnsyncProps' options set!\n";
2637 if ($self->rewrite_root) {
2638 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
2639 "options set!\n";
2641 if ($self->rewrite_uuid) {
2642 die "Can't have both 'useSvnsyncProps' and 'rewriteUUID' ",
2643 "options set!\n";
2646 my $svnsync;
2647 # see if we have it in our config, first:
2648 eval {
2649 my $section = "svn-remote.$self->{repo_id}";
2651 my $url = tmp_config('--get', "$section.svnsync-url");
2652 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2653 die "doesn't look right - svn:sync-from-url is '$url'\n";
2655 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
2656 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2657 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2659 $svnsync = { url => $url, uuid => $uuid }
2661 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
2662 return $self->{svnsync} = $svnsync;
2665 my $err = "useSvnsyncProps set, but failed to read " .
2666 "svnsync property: svn:sync-from-";
2667 my $rp = $self->ra->rev_proplist(0);
2669 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
2670 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2671 die "doesn't look right - svn:sync-from-url is '$url'\n";
2673 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
2674 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2675 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2677 my $section = "svn-remote.$self->{repo_id}";
2678 tmp_config('--add', "$section.svnsync-uuid", $uuid);
2679 tmp_config('--add', "$section.svnsync-url", $url);
2680 return $self->{svnsync} = { url => $url, uuid => $uuid };
2683 # this allows us to memoize our SVN::Ra UUID locally and avoid a
2684 # remote lookup (useful for 'git svn log').
2685 sub ra_uuid {
2686 my ($self) = @_;
2687 unless ($self->{ra_uuid}) {
2688 my $key = "svn-remote.$self->{repo_id}.uuid";
2689 my $uuid = eval { tmp_config('--get', $key) };
2690 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/i) {
2691 $self->{ra_uuid} = $uuid;
2692 } else {
2693 die "ra_uuid called without URL\n" unless $self->{url};
2694 $self->{ra_uuid} = $self->ra->get_uuid;
2695 tmp_config('--add', $key, $self->{ra_uuid});
2698 $self->{ra_uuid};
2701 sub _set_repos_root {
2702 my ($self, $repos_root) = @_;
2703 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2704 $repos_root ||= $self->ra->{repos_root};
2705 tmp_config($k, $repos_root);
2706 $repos_root;
2709 sub repos_root {
2710 my ($self) = @_;
2711 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2712 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
2715 sub ra {
2716 my ($self) = shift;
2717 my $ra = Git::SVN::Ra->new($self->{url});
2718 $self->_set_repos_root($ra->{repos_root});
2719 if ($self->use_svm_props && !$self->{svm}) {
2720 if ($self->no_metadata) {
2721 die "Can't have both 'noMetadata' and ",
2722 "'useSvmProps' options set!\n";
2723 } elsif ($self->use_svnsync_props) {
2724 die "Can't have both 'useSvnsyncProps' and ",
2725 "'useSvmProps' options set!\n";
2727 $ra = $self->_set_svm_vars($ra);
2728 $self->{-want_revprops} = 1;
2730 $ra;
2733 # prop_walk(PATH, REV, SUB)
2734 # -------------------------
2735 # Recursively traverse PATH at revision REV and invoke SUB for each
2736 # directory that contains a SVN property. SUB will be invoked as
2737 # follows: &SUB(gs, path, props); where `gs' is this instance of
2738 # Git::SVN, `path' the path to the directory where the properties
2739 # `props' were found. The `path' will be relative to point of checkout,
2740 # that is, if url://repo/trunk is the current Git branch, and that
2741 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
2742 # as `path' (note the trailing `/').
2743 sub prop_walk {
2744 my ($self, $path, $rev, $sub) = @_;
2746 $path =~ s#^/##;
2747 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2748 $path =~ s#^/*#/#g;
2749 my $p = $path;
2750 # Strip the irrelevant part of the path.
2751 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2752 # Ensure the path is terminated by a `/'.
2753 $p =~ s#/*$#/#;
2755 # The properties contain all the internal SVN stuff nobody
2756 # (usually) cares about.
2757 my $interesting_props = 0;
2758 foreach (keys %{$props}) {
2759 # If it doesn't start with `svn:', it must be a
2760 # user-defined property.
2761 ++$interesting_props and next if $_ !~ /^svn:/;
2762 # FIXME: Fragile, if SVN adds new public properties,
2763 # this needs to be updated.
2764 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2765 |eol-style|mime-type
2766 |externals|needs-lock)$/x;
2768 &$sub($self, $p, $props) if $interesting_props;
2770 foreach (sort keys %$dirent) {
2771 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
2772 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
2776 sub last_rev { ($_[0]->last_rev_commit)[0] }
2777 sub last_commit { ($_[0]->last_rev_commit)[1] }
2779 # returns the newest SVN revision number and newest commit SHA1
2780 sub last_rev_commit {
2781 my ($self) = @_;
2782 if (defined $self->{last_rev} && defined $self->{last_commit}) {
2783 return ($self->{last_rev}, $self->{last_commit});
2785 my $c = ::verify_ref($self->refname.'^0');
2786 if ($c && !$self->use_svm_props && !$self->no_metadata) {
2787 my $rev = (::cmt_metadata($c))[1];
2788 if (defined $rev) {
2789 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2790 return ($rev, $c);
2793 my $map_path = $self->map_path;
2794 unless (-e $map_path) {
2795 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2796 return (undef, undef);
2798 my ($rev, $commit) = $self->rev_map_max(1);
2799 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2800 return ($rev, $commit);
2803 sub get_fetch_range {
2804 my ($self, $min, $max) = @_;
2805 $max ||= $self->ra->get_latest_revnum;
2806 $min ||= $self->rev_map_max;
2807 (++$min, $max);
2810 sub tmp_config {
2811 my (@args) = @_;
2812 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2813 my $config = "$ENV{GIT_DIR}/svn/.metadata";
2814 if (! -f $config && -f $old_def_config) {
2815 rename $old_def_config, $config or
2816 die "Failed rename $old_def_config => $config: $!\n";
2818 my $old_config = $ENV{GIT_CONFIG};
2819 $ENV{GIT_CONFIG} = $config;
2820 $@ = undef;
2821 my @ret = eval {
2822 unless (-f $config) {
2823 mkfile($config);
2824 open my $fh, '>', $config or
2825 die "Can't open $config: $!\n";
2826 print $fh "; This file is used internally by ",
2827 "git-svn\n" or die
2828 "Couldn't write to $config: $!\n";
2829 print $fh "; You should not have to edit it\n" or
2830 die "Couldn't write to $config: $!\n";
2831 close $fh or die "Couldn't close $config: $!\n";
2833 command('config', @args);
2835 my $err = $@;
2836 if (defined $old_config) {
2837 $ENV{GIT_CONFIG} = $old_config;
2838 } else {
2839 delete $ENV{GIT_CONFIG};
2841 die $err if $err;
2842 wantarray ? @ret : $ret[0];
2845 sub tmp_index_do {
2846 my ($self, $sub) = @_;
2847 my $old_index = $ENV{GIT_INDEX_FILE};
2848 $ENV{GIT_INDEX_FILE} = $self->{index};
2849 $@ = undef;
2850 my @ret = eval {
2851 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2852 mkpath([$dir]) unless -d $dir;
2853 &$sub;
2855 my $err = $@;
2856 if (defined $old_index) {
2857 $ENV{GIT_INDEX_FILE} = $old_index;
2858 } else {
2859 delete $ENV{GIT_INDEX_FILE};
2861 die $err if $err;
2862 wantarray ? @ret : $ret[0];
2865 sub assert_index_clean {
2866 my ($self, $treeish) = @_;
2868 $self->tmp_index_do(sub {
2869 command_noisy('read-tree', $treeish) unless -e $self->{index};
2870 my $x = command_oneline('write-tree');
2871 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2872 /^tree ($::sha1)/mo);
2873 return if $y eq $x;
2875 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2876 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2877 command_noisy('read-tree', $treeish);
2878 $x = command_oneline('write-tree');
2879 if ($y ne $x) {
2880 ::fatal "trees ($treeish) $y != $x\n",
2881 "Something is seriously wrong...";
2886 sub get_commit_parents {
2887 my ($self, $log_entry) = @_;
2888 my (%seen, @ret, @tmp);
2889 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2890 if (my $ip = $self->{inject_parents}) {
2891 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2892 push @tmp, $commit;
2895 if (my $cur = ::verify_ref($self->refname.'^0')) {
2896 push @tmp, $cur;
2898 if (my $ipd = $self->{inject_parents_dcommit}) {
2899 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2900 push @tmp, @$commit;
2903 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2904 while (my $p = shift @tmp) {
2905 next if $seen{$p};
2906 $seen{$p} = 1;
2907 push @ret, $p;
2909 @ret;
2912 sub rewrite_root {
2913 my ($self) = @_;
2914 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2915 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2916 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2917 if ($rwr) {
2918 $rwr =~ s#/+$##;
2919 if ($rwr !~ m#^[a-z\+]+://#) {
2920 die "$rwr is not a valid URL (key: $k)\n";
2923 $self->{-rewrite_root} = $rwr;
2926 sub rewrite_uuid {
2927 my ($self) = @_;
2928 return $self->{-rewrite_uuid} if exists $self->{-rewrite_uuid};
2929 my $k = "svn-remote.$self->{repo_id}.rewriteUUID";
2930 my $rwid = eval { command_oneline(qw/config --get/, $k) };
2931 if ($rwid) {
2932 $rwid =~ s#/+$##;
2933 if ($rwid !~ m#^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$#) {
2934 die "$rwid is not a valid UUID (key: $k)\n";
2937 $self->{-rewrite_uuid} = $rwid;
2940 sub metadata_url {
2941 my ($self) = @_;
2942 ($self->rewrite_root || $self->{url}) .
2943 (length $self->{path} ? '/' . $self->{path} : '');
2946 sub full_url {
2947 my ($self) = @_;
2948 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2951 sub full_pushurl {
2952 my ($self) = @_;
2953 if ($self->{pushurl}) {
2954 return $self->{pushurl} . (length $self->{path} ? '/' .
2955 $self->{path} : '');
2956 } else {
2957 return $self->full_url;
2961 sub set_commit_header_env {
2962 my ($log_entry) = @_;
2963 my %env;
2964 foreach my $ned (qw/NAME EMAIL DATE/) {
2965 foreach my $ac (qw/AUTHOR COMMITTER/) {
2966 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2970 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2971 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2972 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2974 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2975 ? $log_entry->{commit_name}
2976 : $log_entry->{name};
2977 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2978 ? $log_entry->{commit_email}
2979 : $log_entry->{email};
2980 \%env;
2983 sub restore_commit_header_env {
2984 my ($env) = @_;
2985 foreach my $ned (qw/NAME EMAIL DATE/) {
2986 foreach my $ac (qw/AUTHOR COMMITTER/) {
2987 my $k = "GIT_${ac}_${ned}";
2988 if (defined $env->{$k}) {
2989 $ENV{$k} = $env->{$k};
2990 } else {
2991 delete $ENV{$k};
2997 sub gc {
2998 command_noisy('gc', '--auto');
3001 sub do_git_commit {
3002 my ($self, $log_entry) = @_;
3003 my $lr = $self->last_rev;
3004 if (defined $lr && $lr >= $log_entry->{revision}) {
3005 die "Last fetched revision of ", $self->refname,
3006 " was r$lr, but we are about to fetch: ",
3007 "r$log_entry->{revision}!\n";
3009 if (my $c = $self->rev_map_get($log_entry->{revision})) {
3010 croak "$log_entry->{revision} = $c already exists! ",
3011 "Why are we refetching it?\n";
3013 my $old_env = set_commit_header_env($log_entry);
3014 my $tree = $log_entry->{tree};
3015 if (!defined $tree) {
3016 $tree = $self->tmp_index_do(sub {
3017 command_oneline('write-tree') });
3019 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
3021 my @exec = ('git', 'commit-tree', $tree);
3022 foreach ($self->get_commit_parents($log_entry)) {
3023 push @exec, '-p', $_;
3025 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
3026 or croak $!;
3027 binmode $msg_fh;
3029 # we always get UTF-8 from SVN, but we may want our commits in
3030 # a different encoding.
3031 if (my $enc = Git::config('i18n.commitencoding')) {
3032 require Encode;
3033 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
3035 print $msg_fh $log_entry->{log} or croak $!;
3036 restore_commit_header_env($old_env);
3037 unless ($self->no_metadata) {
3038 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
3039 or croak $!;
3041 $msg_fh->flush == 0 or croak $!;
3042 close $msg_fh or croak $!;
3043 chomp(my $commit = do { local $/; <$out_fh> });
3044 close $out_fh or croak $!;
3045 waitpid $pid, 0;
3046 croak $? if $?;
3047 if ($commit !~ /^$::sha1$/o) {
3048 die "Failed to commit, invalid sha1: $commit\n";
3051 $self->rev_map_set($log_entry->{revision}, $commit, 1);
3053 $self->{last_rev} = $log_entry->{revision};
3054 $self->{last_commit} = $commit;
3055 print "r$log_entry->{revision}" unless $::_q > 1;
3056 if (defined $log_entry->{svm_revision}) {
3057 print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
3058 $self->rev_map_set($log_entry->{svm_revision}, $commit,
3059 0, $self->svm_uuid);
3061 print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
3062 if (--$_gc_nr == 0) {
3063 $_gc_nr = $_gc_period;
3064 gc();
3066 return $commit;
3069 sub match_paths {
3070 my ($self, $paths, $r) = @_;
3071 return 1 if $self->{path} eq '';
3072 if (my $path = $paths->{"/$self->{path}"}) {
3073 return ($path->{action} eq 'D') ? 0 : 1;
3075 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
3076 if (grep /$self->{path_regex}/, keys %$paths) {
3077 return 1;
3079 my $c = '';
3080 foreach (split m#/#, $self->{path}) {
3081 $c .= "/$_";
3082 next unless ($paths->{$c} &&
3083 ($paths->{$c}->{action} =~ /^[AR]$/));
3084 if ($self->ra->check_path($self->{path}, $r) ==
3085 $SVN::Node::dir) {
3086 return 1;
3089 return 0;
3092 sub find_parent_branch {
3093 my ($self, $paths, $rev) = @_;
3094 return undef unless $self->follow_parent;
3095 unless (defined $paths) {
3096 my $err_handler = $SVN::Error::handler;
3097 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
3098 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1,
3099 sub { $paths = $_[0] });
3100 $SVN::Error::handler = $err_handler;
3102 return undef unless defined $paths;
3104 # look for a parent from another branch:
3105 my @b_path_components = split m#/#, $self->{path};
3106 my @a_path_components;
3107 my $i;
3108 while (@b_path_components) {
3109 $i = $paths->{'/'.join('/', @b_path_components)};
3110 last if $i && defined $i->{copyfrom_path};
3111 unshift(@a_path_components, pop(@b_path_components));
3113 return undef unless defined $i && defined $i->{copyfrom_path};
3114 my $branch_from = $i->{copyfrom_path};
3115 if (@a_path_components) {
3116 print STDERR "branch_from: $branch_from => ";
3117 $branch_from .= '/'.join('/', @a_path_components);
3118 print STDERR $branch_from, "\n";
3120 my $r = $i->{copyfrom_rev};
3121 my $repos_root = $self->ra->{repos_root};
3122 my $url = $self->ra->{url};
3123 my $new_url = $url . $branch_from;
3124 print STDERR "Found possible branch point: ",
3125 "$new_url => ", $self->full_url, ", $r\n"
3126 unless $::_q > 1;
3127 $branch_from =~ s#^/##;
3128 my $gs = $self->other_gs($new_url, $url,
3129 $branch_from, $r, $self->{ref_id});
3130 my ($r0, $parent) = $gs->find_rev_before($r, 1);
3132 my ($base, $head);
3133 if (!defined $r0 || !defined $parent) {
3134 ($base, $head) = parse_revision_argument(0, $r);
3135 } else {
3136 if ($r0 < $r) {
3137 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
3138 0, 1, sub { $base = $_[1] - 1 });
3141 if (defined $base && $base <= $r) {
3142 $gs->fetch($base, $r);
3144 ($r0, $parent) = $gs->find_rev_before($r, 1);
3146 if (defined $r0 && defined $parent) {
3147 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n"
3148 unless $::_q > 1;
3149 my $ed;
3150 if ($self->ra->can_do_switch) {
3151 $self->assert_index_clean($parent);
3152 print STDERR "Following parent with do_switch\n"
3153 unless $::_q > 1;
3154 # do_switch works with svn/trunk >= r22312, but that
3155 # is not included with SVN 1.4.3 (the latest version
3156 # at the moment), so we can't rely on it
3157 $self->{last_rev} = $r0;
3158 $self->{last_commit} = $parent;
3159 $ed = SVN::Git::Fetcher->new($self, $gs->{path});
3160 $gs->ra->gs_do_switch($r0, $rev, $gs,
3161 $self->full_url, $ed)
3162 or die "SVN connection failed somewhere...\n";
3163 } elsif ($self->ra->trees_match($new_url, $r0,
3164 $self->full_url, $rev)) {
3165 print STDERR "Trees match:\n",
3166 " $new_url\@$r0\n",
3167 " ${\$self->full_url}\@$rev\n",
3168 "Following parent with no changes\n"
3169 unless $::_q > 1;
3170 $self->tmp_index_do(sub {
3171 command_noisy('read-tree', $parent);
3173 $self->{last_commit} = $parent;
3174 } else {
3175 print STDERR "Following parent with do_update\n"
3176 unless $::_q > 1;
3177 $ed = SVN::Git::Fetcher->new($self);
3178 $self->ra->gs_do_update($rev, $rev, $self, $ed)
3179 or die "SVN connection failed somewhere...\n";
3181 print STDERR "Successfully followed parent\n" unless $::_q > 1;
3182 return $self->make_log_entry($rev, [$parent], $ed);
3184 return undef;
3187 sub do_fetch {
3188 my ($self, $paths, $rev) = @_;
3189 my $ed;
3190 my ($last_rev, @parents);
3191 if (my $lc = $self->last_commit) {
3192 # we can have a branch that was deleted, then re-added
3193 # under the same name but copied from another path, in
3194 # which case we'll have multiple parents (we don't
3195 # want to break the original ref, nor lose copypath info):
3196 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
3197 push @{$log_entry->{parents}}, $lc;
3198 return $log_entry;
3200 $ed = SVN::Git::Fetcher->new($self);
3201 $last_rev = $self->{last_rev};
3202 $ed->{c} = $lc;
3203 @parents = ($lc);
3204 } else {
3205 $last_rev = $rev;
3206 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
3207 return $log_entry;
3209 $ed = SVN::Git::Fetcher->new($self);
3211 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
3212 die "SVN connection failed somewhere...\n";
3214 $self->make_log_entry($rev, \@parents, $ed);
3217 sub mkemptydirs {
3218 my ($self, $r) = @_;
3220 sub scan {
3221 my ($r, $empty_dirs, $line) = @_;
3222 if (defined $r && $line =~ /^r(\d+)$/) {
3223 return 0 if $1 > $r;
3224 } elsif ($line =~ /^ \+empty_dir: (.+)$/) {
3225 $empty_dirs->{$1} = 1;
3226 } elsif ($line =~ /^ \-empty_dir: (.+)$/) {
3227 my @d = grep {m[^\Q$1\E(/|$)]} (keys %$empty_dirs);
3228 delete @$empty_dirs{@d};
3230 1; # continue
3233 my %empty_dirs = ();
3234 my $gz_file = "$self->{dir}/unhandled.log.gz";
3235 if (-f $gz_file) {
3236 if (!$can_compress) {
3237 warn "Compress::Zlib could not be found; ",
3238 "empty directories in $gz_file will not be read\n";
3239 } else {
3240 my $gz = Compress::Zlib::gzopen($gz_file, "rb") or
3241 die "Unable to open $gz_file: $!\n";
3242 my $line;
3243 while ($gz->gzreadline($line) > 0) {
3244 scan($r, \%empty_dirs, $line) or last;
3246 $gz->gzclose;
3250 if (open my $fh, '<', "$self->{dir}/unhandled.log") {
3251 binmode $fh or croak "binmode: $!";
3252 while (<$fh>) {
3253 scan($r, \%empty_dirs, $_) or last;
3255 close $fh;
3258 my $strip = qr/\A\Q$self->{path}\E(?:\/|$)/;
3259 foreach my $d (sort keys %empty_dirs) {
3260 $d = uri_decode($d);
3261 $d =~ s/$strip//;
3262 next unless length($d);
3263 next if -d $d;
3264 if (-e $d) {
3265 warn "$d exists but is not a directory\n";
3266 } else {
3267 print "creating empty directory: $d\n";
3268 mkpath([$d]);
3273 sub get_untracked {
3274 my ($self, $ed) = @_;
3275 my @out;
3276 my $h = $ed->{empty};
3277 foreach (sort keys %$h) {
3278 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
3279 push @out, " $act: " . uri_encode($_);
3280 warn "W: $act: $_\n";
3282 foreach my $t (qw/dir_prop file_prop/) {
3283 $h = $ed->{$t} or next;
3284 foreach my $path (sort keys %$h) {
3285 my $ppath = $path eq '' ? '.' : $path;
3286 foreach my $prop (sort keys %{$h->{$path}}) {
3287 next if $SKIP_PROP{$prop};
3288 my $v = $h->{$path}->{$prop};
3289 my $t_ppath_prop = "$t: " .
3290 uri_encode($ppath) . ' ' .
3291 uri_encode($prop);
3292 if (defined $v) {
3293 push @out, " +$t_ppath_prop " .
3294 uri_encode($v);
3295 } else {
3296 push @out, " -$t_ppath_prop";
3301 foreach my $t (qw/absent_file absent_directory/) {
3302 $h = $ed->{$t} or next;
3303 foreach my $parent (sort keys %$h) {
3304 foreach my $path (sort @{$h->{$parent}}) {
3305 push @out, " $t: " .
3306 uri_encode("$parent/$path");
3307 warn "W: $t: $parent/$path ",
3308 "Insufficient permissions?\n";
3312 \@out;
3315 sub get_tz {
3316 # some systmes don't handle or mishandle %z, so be creative.
3317 my $t = shift || time;
3318 my $gm = timelocal(gmtime($t));
3319 my $sign = qw( + + - )[ $t <=> $gm ];
3320 return sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
3323 # parse_svn_date(DATE)
3324 # --------------------
3325 # Given a date (in UTC) from Subversion, return a string in the format
3326 # "<TZ Offset> <local date/time>" that Git will use.
3328 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
3329 # is true we'll convert it to the local timezone instead.
3330 sub parse_svn_date {
3331 my $date = shift || return '+0000 1970-01-01 00:00:00';
3332 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
3333 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
3334 croak "Unable to parse date: $date\n";
3335 my $parsed_date; # Set next.
3337 if ($Git::SVN::_localtime) {
3338 # Translate the Subversion datetime to an epoch time.
3339 # Begin by switching ourselves to $date's timezone, UTC.
3340 my $old_env_TZ = $ENV{TZ};
3341 $ENV{TZ} = 'UTC';
3343 my $epoch_in_UTC =
3344 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
3346 # Determine our local timezone (including DST) at the
3347 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
3348 # value of TZ, if any, at the time we were run.
3349 if (defined $Git::SVN::Log::TZ) {
3350 $ENV{TZ} = $Git::SVN::Log::TZ;
3351 } else {
3352 delete $ENV{TZ};
3355 my $our_TZ = get_tz();
3357 # This converts $epoch_in_UTC into our local timezone.
3358 my ($sec, $min, $hour, $mday, $mon, $year,
3359 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
3361 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
3362 $our_TZ, $year + 1900, $mon + 1,
3363 $mday, $hour, $min, $sec);
3365 # Reset us to the timezone in effect when we entered
3366 # this routine.
3367 if (defined $old_env_TZ) {
3368 $ENV{TZ} = $old_env_TZ;
3369 } else {
3370 delete $ENV{TZ};
3372 } else {
3373 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
3376 return $parsed_date;
3379 sub other_gs {
3380 my ($self, $new_url, $url,
3381 $branch_from, $r, $old_ref_id) = @_;
3382 my $gs = Git::SVN->find_by_url($new_url, $url, $branch_from);
3383 unless ($gs) {
3384 my $ref_id = $old_ref_id;
3385 $ref_id =~ s/\@\d+-*$//;
3386 $ref_id .= "\@$r";
3387 # just grow a tail if we're not unique enough :x
3388 $ref_id .= '-' while find_ref($ref_id);
3389 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
3390 if ($u =~ s#^\Q$url\E(/|$)##) {
3391 $p = $u;
3392 $u = $url;
3393 $repo_id = $self->{repo_id};
3395 while (1) {
3396 # It is possible to tag two different subdirectories at
3397 # the same revision. If the url for an existing ref
3398 # does not match, we must either find a ref with a
3399 # matching url or create a new ref by growing a tail.
3400 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
3401 my (undef, $max_commit) = $gs->rev_map_max(1);
3402 last if (!$max_commit);
3403 my ($url) = ::cmt_metadata($max_commit);
3404 last if ($url eq $gs->metadata_url);
3405 $ref_id .= '-';
3407 print STDERR "Initializing parent: $ref_id\n" unless $::_q > 1;
3412 sub call_authors_prog {
3413 my ($orig_author) = @_;
3414 $orig_author = command_oneline('rev-parse', '--sq-quote', $orig_author);
3415 my $author = `$::_authors_prog $orig_author`;
3416 if ($? != 0) {
3417 die "$::_authors_prog failed with exit code $?\n"
3419 if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
3420 my ($name, $email) = ($1, $2);
3421 $email = undef if length $2 == 0;
3422 return [$name, $email];
3423 } else {
3424 die "Author: $orig_author: $::_authors_prog returned "
3425 . "invalid author format: $author\n";
3429 sub check_author {
3430 my ($author) = @_;
3431 if (!defined $author || length $author == 0) {
3432 $author = '(no author)';
3434 if (!defined $::users{$author}) {
3435 if (defined $::_authors_prog) {
3436 $::users{$author} = call_authors_prog($author);
3437 } elsif (defined $::_authors) {
3438 die "Author: $author not defined in $::_authors file\n";
3441 $author;
3444 sub find_extra_svk_parents {
3445 my ($self, $ed, $tickets, $parents) = @_;
3446 # aha! svk:merge property changed...
3447 my @tickets = split "\n", $tickets;
3448 my @known_parents;
3449 for my $ticket ( @tickets ) {
3450 my ($uuid, $path, $rev) = split /:/, $ticket;
3451 if ( $uuid eq $self->ra_uuid ) {
3452 my $url = $self->{url};
3453 my $repos_root = $url;
3454 my $branch_from = $path;
3455 $branch_from =~ s{^/}{};
3456 my $gs = $self->other_gs($repos_root."/".$branch_from,
3457 $url,
3458 $branch_from,
3459 $rev,
3460 $self->{ref_id});
3461 if ( my $commit = $gs->rev_map_get($rev, $uuid) ) {
3462 # wahey! we found it, but it might be
3463 # an old one (!)
3464 push @known_parents, [ $rev, $commit ];
3468 # Ordering matters; highest-numbered commit merge tickets
3469 # first, as they may account for later merge ticket additions
3470 # or changes.
3471 @known_parents = map {$_->[1]} sort {$b->[0] <=> $a->[0]} @known_parents;
3472 for my $parent ( @known_parents ) {
3473 my @cmd = ('rev-list', $parent, map { "^$_" } @$parents );
3474 my ($msg_fh, $ctx) = command_output_pipe(@cmd);
3475 my $new;
3476 while ( <$msg_fh> ) {
3477 $new=1;last;
3479 command_close_pipe($msg_fh, $ctx);
3480 if ( $new ) {
3481 print STDERR
3482 "Found merge parent (svk:merge ticket): $parent\n";
3483 push @$parents, $parent;
3488 sub lookup_svn_merge {
3489 my $uuid = shift;
3490 my $url = shift;
3491 my $merge = shift;
3493 my ($source, $revs) = split ":", $merge;
3494 my $path = $source;
3495 $path =~ s{^/}{};
3496 my $gs = Git::SVN->find_by_url($url.$source, $url, $path);
3497 if ( !$gs ) {
3498 warn "Couldn't find revmap for $url$source\n";
3499 return;
3501 my @ranges = split ",", $revs;
3502 my ($tip, $tip_commit);
3503 my @merged_commit_ranges;
3504 # find the tip
3505 for my $range ( @ranges ) {
3506 my ($bottom, $top) = split "-", $range;
3507 $top ||= $bottom;
3508 my $bottom_commit = $gs->find_rev_after( $bottom, 1, $top );
3509 my $top_commit = $gs->find_rev_before( $top, 1, $bottom );
3511 unless ($top_commit and $bottom_commit) {
3512 warn "W:unknown path/rev in svn:mergeinfo "
3513 ."dirprop: $source:$range\n";
3514 next;
3517 if (scalar(command('rev-parse', "$bottom_commit^@"))) {
3518 push @merged_commit_ranges,
3519 "$bottom_commit^..$top_commit";
3520 } else {
3521 push @merged_commit_ranges, "$top_commit";
3524 if ( !defined $tip or $top > $tip ) {
3525 $tip = $top;
3526 $tip_commit = $top_commit;
3529 return ($tip_commit, @merged_commit_ranges);
3532 sub _rev_list {
3533 my ($msg_fh, $ctx) = command_output_pipe(
3534 "rev-list", @_,
3536 my @rv;
3537 while ( <$msg_fh> ) {
3538 chomp;
3539 push @rv, $_;
3541 command_close_pipe($msg_fh, $ctx);
3542 @rv;
3545 sub check_cherry_pick {
3546 my $base = shift;
3547 my $tip = shift;
3548 my $parents = shift;
3549 my @ranges = @_;
3550 my %commits = map { $_ => 1 }
3551 _rev_list("--no-merges", $tip, "--not", $base, @$parents, "--");
3552 for my $range ( @ranges ) {
3553 delete @commits{_rev_list($range, "--")};
3555 for my $commit (keys %commits) {
3556 if (has_no_changes($commit)) {
3557 delete $commits{$commit};
3560 return (keys %commits);
3563 sub has_no_changes {
3564 my $commit = shift;
3566 my @revs = split / /, command_oneline(
3567 qw(rev-list --parents -1 -m), $commit);
3569 # Commits with no parents, e.g. the start of a partial branch,
3570 # have changes by definition.
3571 return 1 if (@revs < 2);
3573 # Commits with multiple parents, e.g a merge, have no changes
3574 # by definition.
3575 return 0 if (@revs > 2);
3577 return (command_oneline("rev-parse", "$commit^{tree}") eq
3578 command_oneline("rev-parse", "$commit~1^{tree}"));
3581 # The GIT_DIR environment variable is not always set until after the command
3582 # line arguments are processed, so we can't memoize in a BEGIN block.
3584 my $memoized = 0;
3586 sub memoize_svn_mergeinfo_functions {
3587 return if $memoized;
3588 $memoized = 1;
3590 my $cache_path = "$ENV{GIT_DIR}/svn/.caches/";
3591 mkpath([$cache_path]) unless -d $cache_path;
3593 tie my %lookup_svn_merge_cache => 'Memoize::Storable',
3594 "$cache_path/lookup_svn_merge.db", 'nstore';
3595 memoize 'lookup_svn_merge',
3596 SCALAR_CACHE => 'FAULT',
3597 LIST_CACHE => ['HASH' => \%lookup_svn_merge_cache],
3600 tie my %check_cherry_pick_cache => 'Memoize::Storable',
3601 "$cache_path/check_cherry_pick.db", 'nstore';
3602 memoize 'check_cherry_pick',
3603 SCALAR_CACHE => 'FAULT',
3604 LIST_CACHE => ['HASH' => \%check_cherry_pick_cache],
3607 tie my %has_no_changes_cache => 'Memoize::Storable',
3608 "$cache_path/has_no_changes.db", 'nstore';
3609 memoize 'has_no_changes',
3610 SCALAR_CACHE => ['HASH' => \%has_no_changes_cache],
3611 LIST_CACHE => 'FAULT',
3615 sub unmemoize_svn_mergeinfo_functions {
3616 return if not $memoized;
3617 $memoized = 0;
3619 Memoize::unmemoize 'lookup_svn_merge';
3620 Memoize::unmemoize 'check_cherry_pick';
3621 Memoize::unmemoize 'has_no_changes';
3624 Memoize::memoize 'Git::SVN::repos_root';
3627 END {
3628 # Force cache writeout explicitly instead of waiting for
3629 # global destruction to avoid segfault in Storable:
3630 # http://rt.cpan.org/Public/Bug/Display.html?id=36087
3631 unmemoize_svn_mergeinfo_functions();
3634 sub parents_exclude {
3635 my $parents = shift;
3636 my @commits = @_;
3637 return unless @commits;
3639 my @excluded;
3640 my $excluded;
3641 do {
3642 my @cmd = ('rev-list', "-1", @commits, "--not", @$parents );
3643 $excluded = command_oneline(@cmd);
3644 if ( $excluded ) {
3645 my @new;
3646 my $found;
3647 for my $commit ( @commits ) {
3648 if ( $commit eq $excluded ) {
3649 push @excluded, $commit;
3650 $found++;
3651 last;
3653 else {
3654 push @new, $commit;
3657 die "saw commit '$excluded' in rev-list output, "
3658 ."but we didn't ask for that commit (wanted: @commits --not @$parents)"
3659 unless $found;
3660 @commits = @new;
3663 while ($excluded and @commits);
3665 return @excluded;
3669 # note: this function should only be called if the various dirprops
3670 # have actually changed
3671 sub find_extra_svn_parents {
3672 my ($self, $ed, $mergeinfo, $parents) = @_;
3673 # aha! svk:merge property changed...
3675 memoize_svn_mergeinfo_functions();
3677 # We first search for merged tips which are not in our
3678 # history. Then, we figure out which git revisions are in
3679 # that tip, but not this revision. If all of those revisions
3680 # are now marked as merge, we can add the tip as a parent.
3681 my @merges = split "\n", $mergeinfo;
3682 my @merge_tips;
3683 my $url = $self->{url};
3684 my $uuid = $self->ra_uuid;
3685 my %ranges;
3686 for my $merge ( @merges ) {
3687 my ($tip_commit, @ranges) =
3688 lookup_svn_merge( $uuid, $url, $merge );
3689 unless (!$tip_commit or
3690 grep { $_ eq $tip_commit } @$parents ) {
3691 push @merge_tips, $tip_commit;
3692 $ranges{$tip_commit} = \@ranges;
3693 } else {
3694 push @merge_tips, undef;
3698 my %excluded = map { $_ => 1 }
3699 parents_exclude($parents, grep { defined } @merge_tips);
3701 # check merge tips for new parents
3702 my @new_parents;
3703 for my $merge_tip ( @merge_tips ) {
3704 my $spec = shift @merges;
3705 next unless $merge_tip and $excluded{$merge_tip};
3707 my $ranges = $ranges{$merge_tip};
3709 # check out 'new' tips
3710 my $merge_base;
3711 eval {
3712 $merge_base = command_oneline(
3713 "merge-base",
3714 @$parents, $merge_tip,
3717 if ($@) {
3718 die "An error occurred during merge-base"
3719 unless $@->isa("Git::Error::Command");
3721 warn "W: Cannot find common ancestor between ".
3722 "@$parents and $merge_tip. Ignoring merge info.\n";
3723 next;
3726 # double check that there are no missing non-merge commits
3727 my (@incomplete) = check_cherry_pick(
3728 $merge_base, $merge_tip,
3729 $parents,
3730 @$ranges,
3733 if ( @incomplete ) {
3734 warn "W:svn cherry-pick ignored ($spec) - missing "
3735 .@incomplete." commit(s) (eg $incomplete[0])\n";
3736 } else {
3737 warn
3738 "Found merge parent (svn:mergeinfo prop): ",
3739 $merge_tip, "\n";
3740 push @new_parents, $merge_tip;
3744 # cater for merges which merge commits from multiple branches
3745 if ( @new_parents > 1 ) {
3746 for ( my $i = 0; $i <= $#new_parents; $i++ ) {
3747 for ( my $j = 0; $j <= $#new_parents; $j++ ) {
3748 next if $i == $j;
3749 next unless $new_parents[$i];
3750 next unless $new_parents[$j];
3751 my $revs = command_oneline(
3752 "rev-list", "-1",
3753 "$new_parents[$i]..$new_parents[$j]",
3755 if ( !$revs ) {
3756 undef($new_parents[$j]);
3761 push @$parents, grep { defined } @new_parents;
3764 sub make_log_entry {
3765 my ($self, $rev, $parents, $ed) = @_;
3766 my $untracked = $self->get_untracked($ed);
3768 my @parents = @$parents;
3769 my $ps = $ed->{path_strip} || "";
3770 for my $path ( grep { m/$ps/ } %{$ed->{dir_prop}} ) {
3771 my $props = $ed->{dir_prop}{$path};
3772 if ( $props->{"svk:merge"} ) {
3773 $self->find_extra_svk_parents
3774 ($ed, $props->{"svk:merge"}, \@parents);
3776 if ( $props->{"svn:mergeinfo"} ) {
3777 $self->find_extra_svn_parents
3778 ($ed,
3779 $props->{"svn:mergeinfo"},
3780 \@parents);
3784 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
3785 print $un "r$rev\n" or croak $!;
3786 print $un $_, "\n" foreach @$untracked;
3787 my %log_entry = ( parents => \@parents, revision => $rev,
3788 log => '');
3790 my $headrev;
3791 my $logged = delete $self->{logged_rev_props};
3792 if (!$logged || $self->{-want_revprops}) {
3793 my $rp = $self->ra->rev_proplist($rev);
3794 foreach (sort keys %$rp) {
3795 my $v = $rp->{$_};
3796 if (/^svn:(author|date|log)$/) {
3797 $log_entry{$1} = $v;
3798 } elsif ($_ eq 'svm:headrev') {
3799 $headrev = $v;
3800 } else {
3801 print $un " rev_prop: ", uri_encode($_), ' ',
3802 uri_encode($v), "\n";
3805 } else {
3806 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
3808 close $un or croak $!;
3810 $log_entry{date} = parse_svn_date($log_entry{date});
3811 $log_entry{log} .= "\n";
3812 my $author = $log_entry{author} = check_author($log_entry{author});
3813 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
3814 : ($author, undef);
3816 my ($commit_name, $commit_email) = ($name, $email);
3817 if ($_use_log_author) {
3818 my $name_field;
3819 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
3820 $name_field = $1;
3821 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
3822 $name_field = $1;
3824 if (!defined $name_field) {
3825 if (!defined $email) {
3826 $email = $name;
3828 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
3829 ($name, $email) = ($1, $2);
3830 } elsif ($name_field =~ /(.*)@/) {
3831 ($name, $email) = ($1, $name_field);
3832 } else {
3833 ($name, $email) = ($name_field, $name_field);
3836 if (defined $headrev && $self->use_svm_props) {
3837 if ($self->rewrite_root) {
3838 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
3839 "options set!\n";
3841 if ($self->rewrite_uuid) {
3842 die "Can't have both 'useSvmProps' and 'rewriteUUID' ",
3843 "options set!\n";
3845 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$}i;
3846 # we don't want "SVM: initializing mirror for junk" ...
3847 return undef if $r == 0;
3848 my $svm = $self->svm;
3849 if ($uuid ne $svm->{uuid}) {
3850 die "UUID mismatch on SVM path:\n",
3851 "expected: $svm->{uuid}\n",
3852 " got: $uuid\n";
3854 my $full_url = $self->full_url;
3855 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
3856 die "Failed to replace '$svm->{replace}' with ",
3857 "'$svm->{source}' in $full_url\n";
3858 # throw away username for storing in records
3859 remove_username($full_url);
3860 $log_entry{metadata} = "$full_url\@$r $uuid";
3861 $log_entry{svm_revision} = $r;
3862 $email ||= "$author\@$uuid";
3863 $commit_email ||= "$author\@$uuid";
3864 } elsif ($self->use_svnsync_props) {
3865 my $full_url = $self->svnsync->{url};
3866 $full_url .= "/$self->{path}" if length $self->{path};
3867 remove_username($full_url);
3868 my $uuid = $self->svnsync->{uuid};
3869 $log_entry{metadata} = "$full_url\@$rev $uuid";
3870 $email ||= "$author\@$uuid";
3871 $commit_email ||= "$author\@$uuid";
3872 } else {
3873 my $url = $self->metadata_url;
3874 remove_username($url);
3875 my $uuid = $self->rewrite_uuid || $self->ra->get_uuid;
3876 $log_entry{metadata} = "$url\@$rev " . $uuid;
3877 $email ||= "$author\@" . $uuid;
3878 $commit_email ||= "$author\@" . $uuid;
3880 $log_entry{name} = $name;
3881 $log_entry{email} = $email;
3882 $log_entry{commit_name} = $commit_name;
3883 $log_entry{commit_email} = $commit_email;
3884 \%log_entry;
3887 sub fetch {
3888 my ($self, $min_rev, $max_rev, @parents) = @_;
3889 my ($last_rev, $last_commit) = $self->last_rev_commit;
3890 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
3891 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
3894 sub set_tree_cb {
3895 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
3896 $self->{inject_parents} = { $rev => $tree };
3897 $self->fetch(undef, undef);
3900 sub set_tree {
3901 my ($self, $tree) = (shift, shift);
3902 my $log_entry = ::get_commit_entry($tree);
3903 unless ($self->{last_rev}) {
3904 ::fatal("Must have an existing revision to commit");
3906 my %ed_opts = ( r => $self->{last_rev},
3907 log => $log_entry->{log},
3908 ra => $self->ra,
3909 tree_a => $self->{last_commit},
3910 tree_b => $tree,
3911 editor_cb => sub {
3912 $self->set_tree_cb($log_entry, $tree, @_) },
3913 svn_path => $self->{path} );
3914 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
3915 print "No changes\nr$self->{last_rev} = $tree\n";
3919 sub rebuild_from_rev_db {
3920 my ($self, $path) = @_;
3921 my $r = -1;
3922 open my $fh, '<', $path or croak "open: $!";
3923 binmode $fh or croak "binmode: $!";
3924 while (<$fh>) {
3925 length($_) == 41 or croak "inconsistent size in ($_) != 41";
3926 chomp($_);
3927 ++$r;
3928 next if $_ eq ('0' x 40);
3929 $self->rev_map_set($r, $_);
3930 print "r$r = $_\n";
3932 close $fh or croak "close: $!";
3933 unlink $path or croak "unlink: $!";
3936 sub rebuild {
3937 my ($self) = @_;
3938 my $map_path = $self->map_path;
3939 my $partial = (-e $map_path && ! -z $map_path);
3940 return unless ::verify_ref($self->refname.'^0');
3941 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
3942 my $rev_db = $self->rev_db_path;
3943 $self->rebuild_from_rev_db($rev_db);
3944 if ($self->use_svm_props) {
3945 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
3946 $self->rebuild_from_rev_db($svm_rev_db);
3948 $self->unlink_rev_db_symlink;
3949 return;
3951 print "Rebuilding $map_path ...\n" if (!$partial);
3952 my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
3953 (undef, undef));
3954 my ($log, $ctx) =
3955 command_output_pipe(qw/rev-list --pretty=raw --reverse/,
3956 ($head ? "$head.." : "") . $self->refname,
3957 '--');
3958 my $metadata_url = $self->metadata_url;
3959 remove_username($metadata_url);
3960 my $svn_uuid = $self->rewrite_uuid || $self->ra_uuid;
3961 my $c;
3962 while (<$log>) {
3963 if ( m{^commit ($::sha1)$} ) {
3964 $c = $1;
3965 next;
3967 next unless s{^\s*(git-svn-id:)}{$1};
3968 my ($url, $rev, $uuid) = ::extract_metadata($_);
3969 remove_username($url);
3971 # ignore merges (from set-tree)
3972 next if (!defined $rev || !$uuid);
3974 # if we merged or otherwise started elsewhere, this is
3975 # how we break out of it
3976 if (($uuid ne $svn_uuid) ||
3977 ($metadata_url && $url && ($url ne $metadata_url))) {
3978 next;
3980 if ($partial && $head) {
3981 print "Partial-rebuilding $map_path ...\n";
3982 print "Currently at $base_rev = $head\n";
3983 $head = undef;
3986 $self->rev_map_set($rev, $c);
3987 print "r$rev = $c\n";
3989 command_close_pipe($log, $ctx);
3990 print "Done rebuilding $map_path\n" if (!$partial || !$head);
3991 my $rev_db_path = $self->rev_db_path;
3992 if (-f $self->rev_db_path) {
3993 unlink $self->rev_db_path or croak "unlink: $!";
3995 $self->unlink_rev_db_symlink;
3998 # rev_map:
3999 # Tie::File seems to be prone to offset errors if revisions get sparse,
4000 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
4001 # one of my favorite modules is out :< Next up would be one of the DBM
4002 # modules, but I'm not sure which is most portable...
4004 # This is the replacement for the rev_db format, which was too big
4005 # and inefficient for large repositories with a lot of sparse history
4006 # (mainly tags)
4008 # The format is this:
4009 # - 24 bytes for every record,
4010 # * 4 bytes for the integer representing an SVN revision number
4011 # * 20 bytes representing the sha1 of a git commit
4012 # - No empty padding records like the old format
4013 # (except the last record, which can be overwritten)
4014 # - new records are written append-only since SVN revision numbers
4015 # increase monotonically
4016 # - lookups on SVN revision number are done via a binary search
4017 # - Piping the file to xxd -c24 is a good way of dumping it for
4018 # viewing or editing (piped back through xxd -r), should the need
4019 # ever arise.
4020 # - The last record can be padding revision with an all-zero sha1
4021 # This is used to optimize fetch performance when using multiple
4022 # "fetch" directives in .git/config
4024 # These files are disposable unless noMetadata or useSvmProps is set
4026 sub _rev_map_set {
4027 my ($fh, $rev, $commit) = @_;
4029 binmode $fh or croak "binmode: $!";
4030 my $size = (stat($fh))[7];
4031 ($size % 24) == 0 or croak "inconsistent size: $size";
4033 my $wr_offset = 0;
4034 if ($size > 0) {
4035 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
4036 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
4037 $read == 24 or croak "read only $read bytes (!= 24)";
4038 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
4039 if ($last_commit eq ('0' x40)) {
4040 if ($size >= 48) {
4041 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
4042 $read = sysread($fh, $buf, 24) or
4043 croak "read: $!";
4044 $read == 24 or
4045 croak "read only $read bytes (!= 24)";
4046 ($last_rev, $last_commit) =
4047 unpack(rev_map_fmt, $buf);
4048 if ($last_commit eq ('0' x40)) {
4049 croak "inconsistent .rev_map\n";
4052 if ($last_rev >= $rev) {
4053 croak "last_rev is higher!: $last_rev >= $rev";
4055 $wr_offset = -24;
4058 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
4059 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
4060 croak "write: $!";
4063 sub _rev_map_reset {
4064 my ($fh, $rev, $commit) = @_;
4065 my $c = _rev_map_get($fh, $rev);
4066 $c eq $commit or die "_rev_map_reset(@_) commit $c does not match!\n";
4067 my $offset = sysseek($fh, 0, SEEK_CUR) or croak "seek: $!";
4068 truncate $fh, $offset or croak "truncate: $!";
4071 sub mkfile {
4072 my ($path) = @_;
4073 unless (-e $path) {
4074 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
4075 mkpath([$dir]) unless -d $dir;
4076 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
4077 close $fh or die "Couldn't close (create) $path: $!\n";
4081 sub rev_map_set {
4082 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
4083 defined $commit or die "missing arg3\n";
4084 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
4085 my $db = $self->map_path($uuid);
4086 my $db_lock = "$db.lock";
4087 my $sigmask;
4088 $update_ref ||= 0;
4089 if ($update_ref) {
4090 $sigmask = POSIX::SigSet->new();
4091 my $signew = POSIX::SigSet->new(SIGINT, SIGHUP, SIGTERM,
4092 SIGALRM, SIGUSR1, SIGUSR2);
4093 sigprocmask(SIG_BLOCK, $signew, $sigmask) or
4094 croak "Can't block signals: $!";
4096 mkfile($db);
4098 $LOCKFILES{$db_lock} = 1;
4099 my $sync;
4100 # both of these options make our .rev_db file very, very important
4101 # and we can't afford to lose it because rebuild() won't work
4102 if ($self->use_svm_props || $self->no_metadata) {
4103 $sync = 1;
4104 copy($db, $db_lock) or die "rev_map_set(@_): ",
4105 "Failed to copy: ",
4106 "$db => $db_lock ($!)\n";
4107 } else {
4108 rename $db, $db_lock or die "rev_map_set(@_): ",
4109 "Failed to rename: ",
4110 "$db => $db_lock ($!)\n";
4113 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
4114 or croak "Couldn't open $db_lock: $!\n";
4115 $update_ref eq 'reset' ? _rev_map_reset($fh, $rev, $commit) :
4116 _rev_map_set($fh, $rev, $commit);
4117 if ($sync) {
4118 $fh->flush or die "Couldn't flush $db_lock: $!\n";
4119 $fh->sync or die "Couldn't sync $db_lock: $!\n";
4121 close $fh or croak $!;
4122 if ($update_ref) {
4123 $_head = $self;
4124 my $note = "";
4125 $note = " ($update_ref)" if ($update_ref !~ /^\d*$/);
4126 command_noisy('update-ref', '-m', "r$rev$note",
4127 $self->refname, $commit);
4129 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
4130 "$db_lock => $db ($!)\n";
4131 delete $LOCKFILES{$db_lock};
4132 if ($update_ref) {
4133 sigprocmask(SIG_SETMASK, $sigmask) or
4134 croak "Can't restore signal mask: $!";
4138 # If want_commit, this will return an array of (rev, commit) where
4139 # commit _must_ be a valid commit in the archive.
4140 # Otherwise, it'll return the max revision (whether or not the
4141 # commit is valid or just a 0x40 placeholder).
4142 sub rev_map_max {
4143 my ($self, $want_commit) = @_;
4144 $self->rebuild;
4145 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
4146 $want_commit ? ($r, $c) : $r;
4149 sub rev_map_max_norebuild {
4150 my ($self, $want_commit) = @_;
4151 my $map_path = $self->map_path;
4152 stat $map_path or return $want_commit ? (0, undef) : 0;
4153 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
4154 binmode $fh or croak "binmode: $!";
4155 my $size = (stat($fh))[7];
4156 ($size % 24) == 0 or croak "inconsistent size: $size";
4158 if ($size == 0) {
4159 close $fh or croak "close: $!";
4160 return $want_commit ? (0, undef) : 0;
4163 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
4164 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
4165 my ($r, $c) = unpack(rev_map_fmt, $buf);
4166 if ($want_commit && $c eq ('0' x40)) {
4167 if ($size < 48) {
4168 return $want_commit ? (0, undef) : 0;
4170 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
4171 sysread($fh, $buf, 24) == 24 or croak "read: $!";
4172 ($r, $c) = unpack(rev_map_fmt, $buf);
4173 if ($c eq ('0'x40)) {
4174 croak "Penultimate record is all-zeroes in $map_path";
4177 close $fh or croak "close: $!";
4178 $want_commit ? ($r, $c) : $r;
4181 sub rev_map_get {
4182 my ($self, $rev, $uuid) = @_;
4183 my $map_path = $self->map_path($uuid);
4184 return undef unless -e $map_path;
4186 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
4187 my $c = _rev_map_get($fh, $rev);
4188 close($fh) or croak "close: $!";
4192 sub _rev_map_get {
4193 my ($fh, $rev) = @_;
4195 binmode $fh or croak "binmode: $!";
4196 my $size = (stat($fh))[7];
4197 ($size % 24) == 0 or croak "inconsistent size: $size";
4199 if ($size == 0) {
4200 return undef;
4203 my ($l, $u) = (0, $size - 24);
4204 my ($r, $c, $buf);
4206 while ($l <= $u) {
4207 my $i = int(($l/24 + $u/24) / 2) * 24;
4208 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
4209 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
4210 my ($r, $c) = unpack(rev_map_fmt, $buf);
4212 if ($r < $rev) {
4213 $l = $i + 24;
4214 } elsif ($r > $rev) {
4215 $u = $i - 24;
4216 } else { # $r == $rev
4217 return $c eq ('0' x 40) ? undef : $c;
4220 undef;
4223 # Finds the first svn revision that exists on (if $eq_ok is true) or
4224 # before $rev for the current branch. It will not search any lower
4225 # than $min_rev. Returns the git commit hash and svn revision number
4226 # if found, else (undef, undef).
4227 sub find_rev_before {
4228 my ($self, $rev, $eq_ok, $min_rev) = @_;
4229 --$rev unless $eq_ok;
4230 $min_rev ||= 1;
4231 my $max_rev = $self->rev_map_max;
4232 $rev = $max_rev if ($rev > $max_rev);
4233 while ($rev >= $min_rev) {
4234 if (my $c = $self->rev_map_get($rev)) {
4235 return ($rev, $c);
4237 --$rev;
4239 return (undef, undef);
4242 # Finds the first svn revision that exists on (if $eq_ok is true) or
4243 # after $rev for the current branch. It will not search any higher
4244 # than $max_rev. Returns the git commit hash and svn revision number
4245 # if found, else (undef, undef).
4246 sub find_rev_after {
4247 my ($self, $rev, $eq_ok, $max_rev) = @_;
4248 ++$rev unless $eq_ok;
4249 $max_rev ||= $self->rev_map_max;
4250 while ($rev <= $max_rev) {
4251 if (my $c = $self->rev_map_get($rev)) {
4252 return ($rev, $c);
4254 ++$rev;
4256 return (undef, undef);
4259 sub _new {
4260 my ($class, $repo_id, $ref_id, $path) = @_;
4261 unless (defined $repo_id && length $repo_id) {
4262 $repo_id = $Git::SVN::default_repo_id;
4264 unless (defined $ref_id && length $ref_id) {
4265 $_prefix = '' unless defined($_prefix);
4266 $_[2] = $ref_id =
4267 "refs/remotes/$_prefix$Git::SVN::default_ref_id";
4269 $_[1] = $repo_id;
4270 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
4272 # Older repos imported by us used $GIT_DIR/svn/foo instead of
4273 # $GIT_DIR/svn/refs/remotes/foo when tracking refs/remotes/foo
4274 if ($ref_id =~ m{^refs/remotes/(.*)}) {
4275 my $old_dir = "$ENV{GIT_DIR}/svn/$1";
4276 if (-d $old_dir && ! -d $dir) {
4277 $dir = $old_dir;
4281 $_[3] = $path = '' unless (defined $path);
4282 mkpath([$dir]);
4283 bless {
4284 ref_id => $ref_id, dir => $dir, index => "$dir/index",
4285 path => $path, config => "$ENV{GIT_DIR}/svn/config",
4286 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
4289 # for read-only access of old .rev_db formats
4290 sub unlink_rev_db_symlink {
4291 my ($self) = @_;
4292 my $link = $self->rev_db_path;
4293 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
4294 if (-l $link) {
4295 unlink $link or croak "unlink: $link failed!";
4299 sub rev_db_path {
4300 my ($self, $uuid) = @_;
4301 my $db_path = $self->map_path($uuid);
4302 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
4303 or croak "map_path: $db_path does not contain '/.rev_map.' !";
4304 $db_path;
4307 # the new replacement for .rev_db
4308 sub map_path {
4309 my ($self, $uuid) = @_;
4310 $uuid ||= $self->ra_uuid;
4311 "$self->{map_root}.$uuid";
4314 sub uri_encode {
4315 my ($f) = @_;
4316 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
4320 sub uri_decode {
4321 my ($f) = @_;
4322 $f =~ s#%([0-9a-fA-F]{2})#chr(hex($1))#eg;
4326 sub remove_username {
4327 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
4330 package Git::SVN::Prompt;
4331 use strict;
4332 use warnings;
4333 require SVN::Core;
4334 use vars qw/$_no_auth_cache $_username/;
4336 sub simple {
4337 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
4338 $may_save = undef if $_no_auth_cache;
4339 $default_username = $_username if defined $_username;
4340 if (defined $default_username && length $default_username) {
4341 if (defined $realm && length $realm) {
4342 print STDERR "Authentication realm: $realm\n";
4343 STDERR->flush;
4345 $cred->username($default_username);
4346 } else {
4347 username($cred, $realm, $may_save, $pool);
4349 $cred->password(_read_password("Password for '" .
4350 $cred->username . "': ", $realm));
4351 $cred->may_save($may_save);
4352 $SVN::_Core::SVN_NO_ERROR;
4355 sub ssl_server_trust {
4356 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
4357 $may_save = undef if $_no_auth_cache;
4358 print STDERR "Error validating server certificate for '$realm':\n";
4360 no warnings 'once';
4361 # All variables SVN::Auth::SSL::* are used only once,
4362 # so we're shutting up Perl warnings about this.
4363 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
4364 print STDERR " - The certificate is not issued ",
4365 "by a trusted authority. Use the\n",
4366 " fingerprint to validate ",
4367 "the certificate manually!\n";
4369 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
4370 print STDERR " - The certificate hostname ",
4371 "does not match.\n";
4373 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
4374 print STDERR " - The certificate is not yet valid.\n";
4376 if ($failures & $SVN::Auth::SSL::EXPIRED) {
4377 print STDERR " - The certificate has expired.\n";
4379 if ($failures & $SVN::Auth::SSL::OTHER) {
4380 print STDERR " - The certificate has ",
4381 "an unknown error.\n";
4383 } # no warnings 'once'
4384 printf STDERR
4385 "Certificate information:\n".
4386 " - Hostname: %s\n".
4387 " - Valid: from %s until %s\n".
4388 " - Issuer: %s\n".
4389 " - Fingerprint: %s\n",
4390 map $cert_info->$_, qw(hostname valid_from valid_until
4391 issuer_dname fingerprint);
4392 my $choice;
4393 prompt:
4394 print STDERR $may_save ?
4395 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
4396 "(R)eject or accept (t)emporarily? ";
4397 STDERR->flush;
4398 $choice = lc(substr(<STDIN> || 'R', 0, 1));
4399 if ($choice =~ /^t$/i) {
4400 $cred->may_save(undef);
4401 } elsif ($choice =~ /^r$/i) {
4402 return -1;
4403 } elsif ($may_save && $choice =~ /^p$/i) {
4404 $cred->may_save($may_save);
4405 } else {
4406 goto prompt;
4408 $cred->accepted_failures($failures);
4409 $SVN::_Core::SVN_NO_ERROR;
4412 sub ssl_client_cert {
4413 my ($cred, $realm, $may_save, $pool) = @_;
4414 $may_save = undef if $_no_auth_cache;
4415 print STDERR "Client certificate filename: ";
4416 STDERR->flush;
4417 chomp(my $filename = <STDIN>);
4418 $cred->cert_file($filename);
4419 $cred->may_save($may_save);
4420 $SVN::_Core::SVN_NO_ERROR;
4423 sub ssl_client_cert_pw {
4424 my ($cred, $realm, $may_save, $pool) = @_;
4425 $may_save = undef if $_no_auth_cache;
4426 $cred->password(_read_password("Password: ", $realm));
4427 $cred->may_save($may_save);
4428 $SVN::_Core::SVN_NO_ERROR;
4431 sub username {
4432 my ($cred, $realm, $may_save, $pool) = @_;
4433 $may_save = undef if $_no_auth_cache;
4434 if (defined $realm && length $realm) {
4435 print STDERR "Authentication realm: $realm\n";
4437 my $username;
4438 if (defined $_username) {
4439 $username = $_username;
4440 } else {
4441 print STDERR "Username: ";
4442 STDERR->flush;
4443 chomp($username = <STDIN>);
4445 $cred->username($username);
4446 $cred->may_save($may_save);
4447 $SVN::_Core::SVN_NO_ERROR;
4450 sub _read_password {
4451 my ($prompt, $realm) = @_;
4452 my $password = '';
4453 if (exists $ENV{GIT_ASKPASS}) {
4454 open(PH, "-|", $ENV{GIT_ASKPASS}, $prompt);
4455 $password = <PH>;
4456 $password =~ s/[\012\015]//; # \n\r
4457 close(PH);
4458 } else {
4459 print STDERR $prompt;
4460 STDERR->flush;
4461 require Term::ReadKey;
4462 Term::ReadKey::ReadMode('noecho');
4463 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
4464 last if $key =~ /[\012\015]/; # \n\r
4465 $password .= $key;
4467 Term::ReadKey::ReadMode('restore');
4468 print STDERR "\n";
4469 STDERR->flush;
4471 $password;
4474 package SVN::Git::Fetcher;
4475 use vars qw/@ISA $_ignore_regex $_preserve_empty_dirs $_placeholder_filename
4476 @deleted_gpath %added_placeholder $repo_id/;
4477 use strict;
4478 use warnings;
4479 use Carp qw/croak/;
4480 use File::Basename qw/dirname/;
4481 use IO::File qw//;
4483 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
4484 sub new {
4485 my ($class, $git_svn, $switch_path) = @_;
4486 my $self = SVN::Delta::Editor->new;
4487 bless $self, $class;
4488 if (exists $git_svn->{last_commit}) {
4489 $self->{c} = $git_svn->{last_commit};
4490 $self->{empty_symlinks} =
4491 _mark_empty_symlinks($git_svn, $switch_path);
4494 # some options are read globally, but can be overridden locally
4495 # per [svn-remote "..."] section. Command-line options will *NOT*
4496 # override options set in an [svn-remote "..."] section
4497 $repo_id = $git_svn->{repo_id};
4498 my $k = "svn-remote.$repo_id.ignore-paths";
4499 my $v = eval { command_oneline('config', '--get', $k) };
4500 $self->{ignore_regex} = $v;
4502 $k = "svn-remote.$repo_id.preserve-empty-dirs";
4503 $v = eval { command_oneline('config', '--get', '--bool', $k) };
4504 if ($v && $v eq 'true') {
4505 $_preserve_empty_dirs = 1;
4506 $k = "svn-remote.$repo_id.placeholder-filename";
4507 $v = eval { command_oneline('config', '--get', $k) };
4508 $_placeholder_filename = $v;
4511 # Load the list of placeholder files added during previous invocations.
4512 $k = "svn-remote.$repo_id.added-placeholder";
4513 $v = eval { command_oneline('config', '--get-all', $k) };
4514 if ($_preserve_empty_dirs && $v) {
4515 # command() prints errors to stderr, so we only call it if
4516 # command_oneline() succeeded.
4517 my @v = command('config', '--get-all', $k);
4518 $added_placeholder{ dirname($_) } = $_ foreach @v;
4521 $self->{empty} = {};
4522 $self->{dir_prop} = {};
4523 $self->{file_prop} = {};
4524 $self->{absent_dir} = {};
4525 $self->{absent_file} = {};
4526 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
4527 $self->{pathnameencoding} = Git::config('svn.pathnameencoding');
4528 $self;
4531 # this uses the Ra object, so it must be called before do_{switch,update},
4532 # not inside them (when the Git::SVN::Fetcher object is passed) to
4533 # do_{switch,update}
4534 sub _mark_empty_symlinks {
4535 my ($git_svn, $switch_path) = @_;
4536 my $bool = Git::config_bool('svn.brokenSymlinkWorkaround');
4537 return {} if (!defined($bool)) || (defined($bool) && ! $bool);
4539 my %ret;
4540 my ($rev, $cmt) = $git_svn->last_rev_commit;
4541 return {} unless ($rev && $cmt);
4543 # allow the warning to be printed for each revision we fetch to
4544 # ensure the user sees it. The user can also disable the workaround
4545 # on the repository even while git svn is running and the next
4546 # revision fetched will skip this expensive function.
4547 my $printed_warning;
4548 chomp(my $empty_blob = `git hash-object -t blob --stdin < /dev/null`);
4549 my ($ls, $ctx) = command_output_pipe(qw/ls-tree -r -z/, $cmt);
4550 local $/ = "\0";
4551 my $pfx = defined($switch_path) ? $switch_path : $git_svn->{path};
4552 $pfx .= '/' if length($pfx);
4553 while (<$ls>) {
4554 chomp;
4555 s/\A100644 blob $empty_blob\t//o or next;
4556 unless ($printed_warning) {
4557 print STDERR "Scanning for empty symlinks, ",
4558 "this may take a while if you have ",
4559 "many empty files\n",
4560 "You may disable this with `",
4561 "git config svn.brokenSymlinkWorkaround ",
4562 "false'.\n",
4563 "This may be done in a different ",
4564 "terminal without restarting ",
4565 "git svn\n";
4566 $printed_warning = 1;
4568 my $path = $_;
4569 my (undef, $props) =
4570 $git_svn->ra->get_file($pfx.$path, $rev, undef);
4571 if ($props->{'svn:special'}) {
4572 $ret{$path} = 1;
4575 command_close_pipe($ls, $ctx);
4576 \%ret;
4579 # returns true if a given path is inside a ".git" directory
4580 sub in_dot_git {
4581 $_[0] =~ m{(?:^|/)\.git(?:/|$)};
4584 # return value: 0 -- don't ignore, 1 -- ignore
4585 sub is_path_ignored {
4586 my ($self, $path) = @_;
4587 return 1 if in_dot_git($path);
4588 return 1 if defined($self->{ignore_regex}) &&
4589 $path =~ m!$self->{ignore_regex}!;
4590 return 0 unless defined($_ignore_regex);
4591 return 1 if $path =~ m!$_ignore_regex!o;
4592 return 0;
4595 sub set_path_strip {
4596 my ($self, $path) = @_;
4597 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
4600 sub open_root {
4601 { path => '' };
4604 sub open_directory {
4605 my ($self, $path, $pb, $rev) = @_;
4606 { path => $path };
4609 sub git_path {
4610 my ($self, $path) = @_;
4611 if (my $enc = $self->{pathnameencoding}) {
4612 require Encode;
4613 Encode::from_to($path, 'UTF-8', $enc);
4615 if ($self->{path_strip}) {
4616 $path =~ s!$self->{path_strip}!! or
4617 die "Failed to strip path '$path' ($self->{path_strip})\n";
4619 $path;
4622 sub delete_entry {
4623 my ($self, $path, $rev, $pb) = @_;
4624 return undef if $self->is_path_ignored($path);
4626 my $gpath = $self->git_path($path);
4627 return undef if ($gpath eq '');
4629 # remove entire directories.
4630 my ($tree) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
4631 =~ /\A040000 tree ([a-f\d]{40})\t\Q$gpath\E\0/);
4632 if ($tree) {
4633 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
4634 -r --name-only -z/,
4635 $tree);
4636 local $/ = "\0";
4637 while (<$ls>) {
4638 chomp;
4639 my $rmpath = "$gpath/$_";
4640 $self->{gii}->remove($rmpath);
4641 print "\tD\t$rmpath\n" unless $::_q;
4643 print "\tD\t$gpath/\n" unless $::_q;
4644 command_close_pipe($ls, $ctx);
4645 } else {
4646 $self->{gii}->remove($gpath);
4647 print "\tD\t$gpath\n" unless $::_q;
4649 # Don't add to @deleted_gpath if we're deleting a placeholder file.
4650 push @deleted_gpath, $gpath unless $added_placeholder{dirname($path)};
4651 $self->{empty}->{$path} = 0;
4652 undef;
4655 sub open_file {
4656 my ($self, $path, $pb, $rev) = @_;
4657 my ($mode, $blob);
4659 goto out if $self->is_path_ignored($path);
4661 my $gpath = $self->git_path($path);
4662 ($mode, $blob) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
4663 =~ /\A(\d{6}) blob ([a-f\d]{40})\t\Q$gpath\E\0/);
4664 unless (defined $mode && defined $blob) {
4665 die "$path was not found in commit $self->{c} (r$rev)\n";
4667 if ($mode eq '100644' && $self->{empty_symlinks}->{$path}) {
4668 $mode = '120000';
4670 out:
4671 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
4672 pool => SVN::Pool->new, action => 'M' };
4675 sub add_file {
4676 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
4677 my $mode;
4679 if (!$self->is_path_ignored($path)) {
4680 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
4681 delete $self->{empty}->{$dir};
4682 $mode = '100644';
4684 if ($added_placeholder{$dir}) {
4685 # Remove our placeholder file, if we created one.
4686 delete_entry($self, $added_placeholder{$dir})
4687 unless $path eq $added_placeholder{$dir};
4688 delete $added_placeholder{$dir}
4692 { path => $path, mode_a => $mode, mode_b => $mode,
4693 pool => SVN::Pool->new, action => 'A' };
4696 sub add_directory {
4697 my ($self, $path, $cp_path, $cp_rev) = @_;
4698 goto out if $self->is_path_ignored($path);
4699 my $gpath = $self->git_path($path);
4700 if ($gpath eq '') {
4701 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
4702 -r --name-only -z/,
4703 $self->{c});
4704 local $/ = "\0";
4705 while (<$ls>) {
4706 chomp;
4707 $self->{gii}->remove($_);
4708 print "\tD\t$_\n" unless $::_q;
4709 push @deleted_gpath, $gpath;
4711 command_close_pipe($ls, $ctx);
4712 $self->{empty}->{$path} = 0;
4714 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
4715 delete $self->{empty}->{$dir};
4716 $self->{empty}->{$path} = 1;
4718 if ($added_placeholder{$dir}) {
4719 # Remove our placeholder file, if we created one.
4720 delete_entry($self, $added_placeholder{$dir});
4721 delete $added_placeholder{$dir}
4724 out:
4725 { path => $path };
4728 sub change_dir_prop {
4729 my ($self, $db, $prop, $value) = @_;
4730 return undef if $self->is_path_ignored($db->{path});
4731 $self->{dir_prop}->{$db->{path}} ||= {};
4732 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
4733 undef;
4736 sub absent_directory {
4737 my ($self, $path, $pb) = @_;
4738 return undef if $self->is_path_ignored($path);
4739 $self->{absent_dir}->{$pb->{path}} ||= [];
4740 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
4741 undef;
4744 sub absent_file {
4745 my ($self, $path, $pb) = @_;
4746 return undef if $self->is_path_ignored($path);
4747 $self->{absent_file}->{$pb->{path}} ||= [];
4748 push @{$self->{absent_file}->{$pb->{path}}}, $path;
4749 undef;
4752 sub change_file_prop {
4753 my ($self, $fb, $prop, $value) = @_;
4754 return undef if $self->is_path_ignored($fb->{path});
4755 if ($prop eq 'svn:executable') {
4756 if ($fb->{mode_b} != 120000) {
4757 $fb->{mode_b} = defined $value ? 100755 : 100644;
4759 } elsif ($prop eq 'svn:special') {
4760 $fb->{mode_b} = defined $value ? 120000 : 100644;
4761 } else {
4762 $self->{file_prop}->{$fb->{path}} ||= {};
4763 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
4765 undef;
4768 sub apply_textdelta {
4769 my ($self, $fb, $exp) = @_;
4770 return undef if $self->is_path_ignored($fb->{path});
4771 my $fh = $::_repository->temp_acquire('svn_delta');
4772 # $fh gets auto-closed() by SVN::TxDelta::apply(),
4773 # (but $base does not,) so dup() it for reading in close_file
4774 open my $dup, '<&', $fh or croak $!;
4775 my $base = $::_repository->temp_acquire('git_blob');
4777 if ($fb->{blob}) {
4778 my ($base_is_link, $size);
4780 if ($fb->{mode_a} eq '120000' &&
4781 ! $self->{empty_symlinks}->{$fb->{path}}) {
4782 print $base 'link ' or die "print $!\n";
4783 $base_is_link = 1;
4785 retry:
4786 $size = $::_repository->cat_blob($fb->{blob}, $base);
4787 die "Failed to read object $fb->{blob}" if ($size < 0);
4789 if (defined $exp) {
4790 seek $base, 0, 0 or croak $!;
4791 my $got = ::md5sum($base);
4792 if ($got ne $exp) {
4793 my $err = "Checksum mismatch: ".
4794 "$fb->{path} $fb->{blob}\n" .
4795 "expected: $exp\n" .
4796 " got: $got\n";
4797 if ($base_is_link) {
4798 warn $err,
4799 "Retrying... (possibly ",
4800 "a bad symlink from SVN)\n";
4801 $::_repository->temp_reset($base);
4802 $base_is_link = 0;
4803 goto retry;
4805 die $err;
4809 seek $base, 0, 0 or croak $!;
4810 $fb->{fh} = $fh;
4811 $fb->{base} = $base;
4812 [ SVN::TxDelta::apply($base, $dup, undef, $fb->{path}, $fb->{pool}) ];
4815 sub close_file {
4816 my ($self, $fb, $exp) = @_;
4817 return undef if $self->is_path_ignored($fb->{path});
4819 my $hash;
4820 my $path = $self->git_path($fb->{path});
4821 if (my $fh = $fb->{fh}) {
4822 if (defined $exp) {
4823 seek($fh, 0, 0) or croak $!;
4824 my $got = ::md5sum($fh);
4825 if ($got ne $exp) {
4826 die "Checksum mismatch: $path\n",
4827 "expected: $exp\n got: $got\n";
4830 if ($fb->{mode_b} == 120000) {
4831 sysseek($fh, 0, 0) or croak $!;
4832 my $rd = sysread($fh, my $buf, 5);
4834 if (!defined $rd) {
4835 croak "sysread: $!\n";
4836 } elsif ($rd == 0) {
4837 warn "$path has mode 120000",
4838 " but it points to nothing\n",
4839 "converting to an empty file with mode",
4840 " 100644\n";
4841 $fb->{mode_b} = '100644';
4842 } elsif ($buf ne 'link ') {
4843 warn "$path has mode 120000",
4844 " but is not a link\n";
4845 } else {
4846 my $tmp_fh = $::_repository->temp_acquire(
4847 'svn_hash');
4848 my $res;
4849 while ($res = sysread($fh, my $str, 1024)) {
4850 my $out = syswrite($tmp_fh, $str, $res);
4851 defined($out) && $out == $res
4852 or croak("write ",
4853 Git::temp_path($tmp_fh),
4854 ": $!\n");
4856 defined $res or croak $!;
4858 ($fh, $tmp_fh) = ($tmp_fh, $fh);
4859 Git::temp_release($tmp_fh, 1);
4863 $hash = $::_repository->hash_and_insert_object(
4864 Git::temp_path($fh));
4865 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
4867 Git::temp_release($fb->{base}, 1);
4868 Git::temp_release($fh, 1);
4869 } else {
4870 $hash = $fb->{blob} or die "no blob information\n";
4872 $fb->{pool}->clear;
4873 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
4874 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
4875 undef;
4878 sub abort_edit {
4879 my $self = shift;
4880 $self->{nr} = $self->{gii}->{nr};
4881 delete $self->{gii};
4882 $self->SUPER::abort_edit(@_);
4885 sub close_edit {
4886 my $self = shift;
4888 if ($_preserve_empty_dirs) {
4889 my @empty_dirs;
4891 # Any entry flagged as empty that also has an associated
4892 # dir_prop represents a newly created empty directory.
4893 foreach my $i (keys %{$self->{empty}}) {
4894 push @empty_dirs, $i if exists $self->{dir_prop}->{$i};
4897 # Search for directories that have become empty due subsequent
4898 # file deletes.
4899 push @empty_dirs, $self->find_empty_directories();
4901 # Finally, add a placeholder file to each empty directory.
4902 $self->add_placeholder_file($_) foreach (@empty_dirs);
4904 $self->stash_placeholder_list();
4907 $self->{git_commit_ok} = 1;
4908 $self->{nr} = $self->{gii}->{nr};
4909 delete $self->{gii};
4910 $self->SUPER::close_edit(@_);
4913 sub find_empty_directories {
4914 my ($self) = @_;
4915 my @empty_dirs;
4916 my %dirs = map { dirname($_) => 1 } @deleted_gpath;
4918 foreach my $dir (sort keys %dirs) {
4919 next if $dir eq ".";
4921 # If there have been any additions to this directory, there is
4922 # no reason to check if it is empty.
4923 my $skip_added = 0;
4924 foreach my $t (qw/dir_prop file_prop/) {
4925 foreach my $path (keys %{ $self->{$t} }) {
4926 if (exists $self->{$t}->{dirname($path)}) {
4927 $skip_added = 1;
4928 last;
4931 last if $skip_added;
4933 next if $skip_added;
4935 # Use `git ls-tree` to get the filenames of this directory
4936 # that existed prior to this particular commit.
4937 my $ls = command('ls-tree', '-z', '--name-only',
4938 $self->{c}, "$dir/");
4939 my %files = map { $_ => 1 } split(/\0/, $ls);
4941 # Remove the filenames that were deleted during this commit.
4942 delete $files{$_} foreach (@deleted_gpath);
4944 # Report the directory if there are no filenames left.
4945 push @empty_dirs, $dir unless (scalar %files);
4947 @empty_dirs;
4950 sub add_placeholder_file {
4951 my ($self, $dir) = @_;
4952 my $path = "$dir/$_placeholder_filename";
4953 my $gpath = $self->git_path($path);
4955 my $fh = $::_repository->temp_acquire($gpath);
4956 my $hash = $::_repository->hash_and_insert_object(Git::temp_path($fh));
4957 Git::temp_release($fh, 1);
4958 $self->{gii}->update('100644', $hash, $gpath) or croak $!;
4960 # The directory should no longer be considered empty.
4961 delete $self->{empty}->{$dir} if exists $self->{empty}->{$dir};
4963 # Keep track of any placeholder files we create.
4964 $added_placeholder{$dir} = $path;
4967 sub stash_placeholder_list {
4968 my ($self) = @_;
4969 my $k = "svn-remote.$repo_id.added-placeholder";
4970 my $v = eval { command_oneline('config', '--get-all', $k) };
4971 command_noisy('config', '--unset-all', $k) if $v;
4972 foreach (values %added_placeholder) {
4973 command_noisy('config', '--add', $k, $_);
4977 package SVN::Git::Editor;
4978 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
4979 use strict;
4980 use warnings;
4981 use Carp qw/croak/;
4982 use IO::File;
4984 sub new {
4985 my ($class, $opts) = @_;
4986 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
4987 die "$_ required!\n" unless (defined $opts->{$_});
4990 my $pool = SVN::Pool->new;
4991 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
4992 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
4993 $opts->{r}, $mods);
4995 # $opts->{ra} functions should not be used after this:
4996 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
4997 $opts->{editor_cb}, $pool);
4998 my $self = SVN::Delta::Editor->new(@ce, $pool);
4999 bless $self, $class;
5000 foreach (qw/svn_path r tree_a tree_b/) {
5001 $self->{$_} = $opts->{$_};
5003 $self->{url} = $opts->{ra}->{url};
5004 $self->{mods} = $mods;
5005 $self->{types} = $types;
5006 $self->{pool} = $pool;
5007 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
5008 $self->{rm} = { };
5009 $self->{path_prefix} = length $self->{svn_path} ?
5010 "$self->{svn_path}/" : '';
5011 $self->{config} = $opts->{config};
5012 $self->{mergeinfo} = $opts->{mergeinfo};
5013 return $self;
5016 sub generate_diff {
5017 my ($tree_a, $tree_b) = @_;
5018 my @diff_tree = qw(diff-tree -z -r);
5019 if ($_cp_similarity) {
5020 push @diff_tree, "-C$_cp_similarity";
5021 } else {
5022 push @diff_tree, '-C';
5024 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
5025 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
5026 push @diff_tree, $tree_a, $tree_b;
5027 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
5028 local $/ = "\0";
5029 my $state = 'meta';
5030 my @mods;
5031 while (<$diff_fh>) {
5032 chomp $_; # this gets rid of the trailing "\0"
5033 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
5034 ($::sha1)\s($::sha1)\s
5035 ([MTCRAD])\d*$/xo) {
5036 push @mods, { mode_a => $1, mode_b => $2,
5037 sha1_a => $3, sha1_b => $4,
5038 chg => $5 };
5039 if ($5 =~ /^(?:C|R)$/) {
5040 $state = 'file_a';
5041 } else {
5042 $state = 'file_b';
5044 } elsif ($state eq 'file_a') {
5045 my $x = $mods[$#mods] or croak "Empty array\n";
5046 if ($x->{chg} !~ /^(?:C|R)$/) {
5047 croak "Error parsing $_, $x->{chg}\n";
5049 $x->{file_a} = $_;
5050 $state = 'file_b';
5051 } elsif ($state eq 'file_b') {
5052 my $x = $mods[$#mods] or croak "Empty array\n";
5053 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
5054 croak "Error parsing $_, $x->{chg}\n";
5056 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
5057 croak "Error parsing $_, $x->{chg}\n";
5059 $x->{file_b} = $_;
5060 $state = 'meta';
5061 } else {
5062 croak "Error parsing $_\n";
5065 command_close_pipe($diff_fh, $ctx);
5066 \@mods;
5069 sub check_diff_paths {
5070 my ($ra, $pfx, $rev, $mods) = @_;
5071 my %types;
5072 $pfx .= '/' if length $pfx;
5074 sub type_diff_paths {
5075 my ($ra, $types, $path, $rev) = @_;
5076 my @p = split m#/+#, $path;
5077 my $c = shift @p;
5078 unless (defined $types->{$c}) {
5079 $types->{$c} = $ra->check_path($c, $rev);
5081 while (@p) {
5082 $c .= '/' . shift @p;
5083 next if defined $types->{$c};
5084 $types->{$c} = $ra->check_path($c, $rev);
5088 foreach my $m (@$mods) {
5089 foreach my $f (qw/file_a file_b/) {
5090 next unless defined $m->{$f};
5091 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
5092 if (length $pfx.$dir && ! defined $types{$dir}) {
5093 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
5097 \%types;
5100 sub split_path {
5101 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
5104 sub repo_path {
5105 my ($self, $path) = @_;
5106 if (my $enc = $self->{pathnameencoding}) {
5107 require Encode;
5108 Encode::from_to($path, $enc, 'UTF-8');
5110 $self->{path_prefix}.(defined $path ? $path : '');
5113 sub url_path {
5114 my ($self, $path) = @_;
5115 if ($self->{url} =~ m#^https?://#) {
5116 $path =~ s!([^~a-zA-Z0-9_./-])!uc sprintf("%%%02x",ord($1))!eg;
5118 $self->{url} . '/' . $self->repo_path($path);
5121 sub rmdirs {
5122 my ($self) = @_;
5123 my $rm = $self->{rm};
5124 delete $rm->{''}; # we never delete the url we're tracking
5125 return unless %$rm;
5127 foreach (keys %$rm) {
5128 my @d = split m#/#, $_;
5129 my $c = shift @d;
5130 $rm->{$c} = 1;
5131 while (@d) {
5132 $c .= '/' . shift @d;
5133 $rm->{$c} = 1;
5136 delete $rm->{$self->{svn_path}};
5137 delete $rm->{''}; # we never delete the url we're tracking
5138 return unless %$rm;
5140 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
5141 $self->{tree_b});
5142 local $/ = "\0";
5143 while (<$fh>) {
5144 chomp;
5145 my @dn = split m#/#, $_;
5146 while (pop @dn) {
5147 delete $rm->{join '/', @dn};
5149 unless (%$rm) {
5150 close $fh;
5151 return;
5154 command_close_pipe($fh, $ctx);
5156 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
5157 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
5158 $self->close_directory($bat->{$d}, $p);
5159 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
5160 print "\tD+\t$d/\n" unless $::_q;
5161 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
5162 delete $bat->{$d};
5166 sub open_or_add_dir {
5167 my ($self, $full_path, $baton, $deletions) = @_;
5168 my $t = $self->{types}->{$full_path};
5169 if (!defined $t) {
5170 die "$full_path not known in r$self->{r} or we have a bug!\n";
5173 no warnings 'once';
5174 # SVN::Node::none and SVN::Node::file are used only once,
5175 # so we're shutting up Perl's warnings about them.
5176 if ($t == $SVN::Node::none || defined($deletions->{$full_path})) {
5177 return $self->add_directory($full_path, $baton,
5178 undef, -1, $self->{pool});
5179 } elsif ($t == $SVN::Node::dir) {
5180 return $self->open_directory($full_path, $baton,
5181 $self->{r}, $self->{pool});
5182 } # no warnings 'once'
5183 print STDERR "$full_path already exists in repository at ",
5184 "r$self->{r} and it is not a directory (",
5185 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
5186 } # no warnings 'once'
5187 exit 1;
5190 sub ensure_path {
5191 my ($self, $path, $deletions) = @_;
5192 my $bat = $self->{bat};
5193 my $repo_path = $self->repo_path($path);
5194 return $bat->{''} unless (length $repo_path);
5196 my @p = split m#/+#, $repo_path;
5197 my $c = shift @p;
5198 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''}, $deletions);
5199 while (@p) {
5200 my $c0 = $c;
5201 $c .= '/' . shift @p;
5202 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0}, $deletions);
5204 return $bat->{$c};
5207 # Subroutine to convert a globbing pattern to a regular expression.
5208 # From perl cookbook.
5209 sub glob2pat {
5210 my $globstr = shift;
5211 my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
5212 $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
5213 return '^' . $globstr . '$';
5216 sub check_autoprop {
5217 my ($self, $pattern, $properties, $file, $fbat) = @_;
5218 # Convert the globbing pattern to a regular expression.
5219 my $regex = glob2pat($pattern);
5220 # Check if the pattern matches the file name.
5221 if($file =~ m/($regex)/) {
5222 # Parse the list of properties to set.
5223 my @props = split(/;/, $properties);
5224 foreach my $prop (@props) {
5225 # Parse 'name=value' syntax and set the property.
5226 if ($prop =~ /([^=]+)=(.*)/) {
5227 my ($n,$v) = ($1,$2);
5228 for ($n, $v) {
5229 s/^\s+//; s/\s+$//;
5231 $self->change_file_prop($fbat, $n, $v);
5237 sub apply_autoprops {
5238 my ($self, $file, $fbat) = @_;
5239 my $conf_t = ${$self->{config}}{'config'};
5240 no warnings 'once';
5241 # Check [miscellany]/enable-auto-props in svn configuration.
5242 if (SVN::_Core::svn_config_get_bool(
5243 $conf_t,
5244 $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
5245 $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
5246 0)) {
5247 # Auto-props are enabled. Enumerate them to look for matches.
5248 my $callback = sub {
5249 $self->check_autoprop($_[0], $_[1], $file, $fbat);
5251 SVN::_Core::svn_config_enumerate(
5252 $conf_t,
5253 $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
5254 $callback);
5258 sub A {
5259 my ($self, $m, $deletions) = @_;
5260 my ($dir, $file) = split_path($m->{file_b});
5261 my $pbat = $self->ensure_path($dir, $deletions);
5262 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
5263 undef, -1);
5264 print "\tA\t$m->{file_b}\n" unless $::_q;
5265 $self->apply_autoprops($file, $fbat);
5266 $self->chg_file($fbat, $m);
5267 $self->close_file($fbat,undef,$self->{pool});
5270 sub C {
5271 my ($self, $m, $deletions) = @_;
5272 my ($dir, $file) = split_path($m->{file_b});
5273 my $pbat = $self->ensure_path($dir, $deletions);
5274 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
5275 $self->url_path($m->{file_a}), $self->{r});
5276 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
5277 $self->chg_file($fbat, $m);
5278 $self->close_file($fbat,undef,$self->{pool});
5281 sub delete_entry {
5282 my ($self, $path, $pbat) = @_;
5283 my $rpath = $self->repo_path($path);
5284 my ($dir, $file) = split_path($rpath);
5285 $self->{rm}->{$dir} = 1;
5286 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
5289 sub R {
5290 my ($self, $m, $deletions) = @_;
5291 my ($dir, $file) = split_path($m->{file_b});
5292 my $pbat = $self->ensure_path($dir, $deletions);
5293 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
5294 $self->url_path($m->{file_a}), $self->{r});
5295 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
5296 $self->apply_autoprops($file, $fbat);
5297 $self->chg_file($fbat, $m);
5298 $self->close_file($fbat,undef,$self->{pool});
5300 ($dir, $file) = split_path($m->{file_a});
5301 $pbat = $self->ensure_path($dir, $deletions);
5302 $self->delete_entry($m->{file_a}, $pbat);
5305 sub M {
5306 my ($self, $m, $deletions) = @_;
5307 my ($dir, $file) = split_path($m->{file_b});
5308 my $pbat = $self->ensure_path($dir, $deletions);
5309 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
5310 $pbat,$self->{r},$self->{pool});
5311 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
5312 $self->chg_file($fbat, $m);
5313 $self->close_file($fbat,undef,$self->{pool});
5316 sub T { shift->M(@_) }
5318 sub change_file_prop {
5319 my ($self, $fbat, $pname, $pval) = @_;
5320 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
5323 sub change_dir_prop {
5324 my ($self, $pbat, $pname, $pval) = @_;
5325 $self->SUPER::change_dir_prop($pbat, $pname, $pval, $self->{pool});
5328 sub _chg_file_get_blob ($$$$) {
5329 my ($self, $fbat, $m, $which) = @_;
5330 my $fh = $::_repository->temp_acquire("git_blob_$which");
5331 if ($m->{"mode_$which"} =~ /^120/) {
5332 print $fh 'link ' or croak $!;
5333 $self->change_file_prop($fbat,'svn:special','*');
5334 } elsif ($m->{mode_a} =~ /^120/ && $m->{"mode_$which"} !~ /^120/) {
5335 $self->change_file_prop($fbat,'svn:special',undef);
5337 my $blob = $m->{"sha1_$which"};
5338 return ($fh,) if ($blob =~ /^0{40}$/);
5339 my $size = $::_repository->cat_blob($blob, $fh);
5340 croak "Failed to read object $blob" if ($size < 0);
5341 $fh->flush == 0 or croak $!;
5342 seek $fh, 0, 0 or croak $!;
5344 my $exp = ::md5sum($fh);
5345 seek $fh, 0, 0 or croak $!;
5346 return ($fh, $exp);
5349 sub chg_file {
5350 my ($self, $fbat, $m) = @_;
5351 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
5352 $self->change_file_prop($fbat,'svn:executable','*');
5353 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
5354 $self->change_file_prop($fbat,'svn:executable',undef);
5356 my ($fh_a, $exp_a) = _chg_file_get_blob $self, $fbat, $m, 'a';
5357 my ($fh_b, $exp_b) = _chg_file_get_blob $self, $fbat, $m, 'b';
5358 my $pool = SVN::Pool->new;
5359 my $atd = $self->apply_textdelta($fbat, $exp_a, $pool);
5360 if (-s $fh_a) {
5361 my $txstream = SVN::TxDelta::new ($fh_a, $fh_b, $pool);
5362 my $res = SVN::TxDelta::send_txstream($txstream, @$atd, $pool);
5363 if (defined $res) {
5364 die "Unexpected result from send_txstream: $res\n",
5365 "(SVN::Core::VERSION: $SVN::Core::VERSION)\n";
5367 } else {
5368 my $got = SVN::TxDelta::send_stream($fh_b, @$atd, $pool);
5369 die "Checksum mismatch\nexpected: $exp_b\ngot: $got\n"
5370 if ($got ne $exp_b);
5372 Git::temp_release($fh_b, 1);
5373 Git::temp_release($fh_a, 1);
5374 $pool->clear;
5377 sub D {
5378 my ($self, $m, $deletions) = @_;
5379 my ($dir, $file) = split_path($m->{file_b});
5380 my $pbat = $self->ensure_path($dir, $deletions);
5381 print "\tD\t$m->{file_b}\n" unless $::_q;
5382 $self->delete_entry($m->{file_b}, $pbat);
5385 sub close_edit {
5386 my ($self) = @_;
5387 my ($p,$bat) = ($self->{pool}, $self->{bat});
5388 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
5389 next if $_ eq '';
5390 $self->close_directory($bat->{$_}, $p);
5392 $self->close_directory($bat->{''}, $p);
5393 $self->SUPER::close_edit($p);
5394 $p->clear;
5397 sub abort_edit {
5398 my ($self) = @_;
5399 $self->SUPER::abort_edit($self->{pool});
5402 sub DESTROY {
5403 my $self = shift;
5404 $self->SUPER::DESTROY(@_);
5405 $self->{pool}->clear;
5408 # this drives the editor
5409 sub apply_diff {
5410 my ($self) = @_;
5411 my $mods = $self->{mods};
5412 my %o = ( D => 0, C => 1, R => 2, A => 3, M => 4, T => 5 );
5413 my %deletions;
5415 foreach my $m (@$mods) {
5416 if ($m->{chg} eq "D") {
5417 $deletions{$m->{file_b}} = 1;
5421 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
5422 my $f = $m->{chg};
5423 if (defined $o{$f}) {
5424 $self->$f($m, \%deletions);
5425 } else {
5426 fatal("Invalid change type: $f");
5430 if (defined($self->{mergeinfo})) {
5431 $self->change_dir_prop($self->{bat}{''}, "svn:mergeinfo",
5432 $self->{mergeinfo});
5434 $self->rmdirs if $_rmdir;
5435 if (@$mods == 0 && !defined($self->{mergeinfo})) {
5436 $self->abort_edit;
5437 } else {
5438 $self->close_edit;
5440 return scalar @$mods;
5443 package Git::SVN::Ra;
5444 use vars qw/@ISA $config_dir $_ignore_refs_regex $_log_window_size/;
5445 use strict;
5446 use warnings;
5447 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
5449 BEGIN {
5450 # enforce temporary pool usage for some simple functions
5451 no strict 'refs';
5452 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root
5453 get_file/) {
5454 my $SUPER = "SUPER::$f";
5455 *$f = sub {
5456 my $self = shift;
5457 my $pool = SVN::Pool->new;
5458 my @ret = $self->$SUPER(@_,$pool);
5459 $pool->clear;
5460 wantarray ? @ret : $ret[0];
5465 sub _auth_providers () {
5466 my @rv = (
5467 SVN::Client::get_simple_provider(),
5468 SVN::Client::get_ssl_server_trust_file_provider(),
5469 SVN::Client::get_simple_prompt_provider(
5470 \&Git::SVN::Prompt::simple, 2),
5471 SVN::Client::get_ssl_client_cert_file_provider(),
5472 SVN::Client::get_ssl_client_cert_prompt_provider(
5473 \&Git::SVN::Prompt::ssl_client_cert, 2),
5474 SVN::Client::get_ssl_client_cert_pw_file_provider(),
5475 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
5476 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
5477 SVN::Client::get_username_provider(),
5478 SVN::Client::get_ssl_server_trust_prompt_provider(
5479 \&Git::SVN::Prompt::ssl_server_trust),
5480 SVN::Client::get_username_prompt_provider(
5481 \&Git::SVN::Prompt::username, 2)
5484 # earlier 1.6.x versions would segfault, and <= 1.5.x didn't have
5485 # this function
5486 if (::compare_svn_version('1.6.12') > 0) {
5487 my $config = SVN::Core::config_get_config($config_dir);
5488 my ($p, @a);
5489 # config_get_config returns all config files from
5490 # ~/.subversion, auth_get_platform_specific_client_providers
5491 # just wants the config "file".
5492 @a = ($config->{'config'}, undef);
5493 $p = SVN::Core::auth_get_platform_specific_client_providers(@a);
5494 # Insert the return value from
5495 # auth_get_platform_specific_providers
5496 unshift @rv, @$p;
5498 \@rv;
5501 sub escape_uri_only {
5502 my ($uri) = @_;
5503 my @tmp;
5504 foreach (split m{/}, $uri) {
5505 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
5506 push @tmp, $_;
5508 join('/', @tmp);
5511 sub escape_url {
5512 my ($url) = @_;
5513 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
5514 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
5515 $url = "$scheme://$domain$uri";
5517 $url;
5520 sub new {
5521 my ($class, $url) = @_;
5522 $url =~ s!/+$!!;
5523 return $RA if ($RA && $RA->{url} eq $url);
5525 ::_req_svn();
5527 SVN::_Core::svn_config_ensure($config_dir, undef);
5528 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
5529 my $config = SVN::Core::config_get_config($config_dir);
5530 $RA = undef;
5531 my $dont_store_passwords = 1;
5532 my $conf_t = ${$config}{'config'};
5534 no warnings 'once';
5535 # The usage of $SVN::_Core::SVN_CONFIG_* variables
5536 # produces warnings that variables are used only once.
5537 # I had not found the better way to shut them up, so
5538 # the warnings of type 'once' are disabled in this block.
5539 if (SVN::_Core::svn_config_get_bool($conf_t,
5540 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
5541 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
5542 1) == 0) {
5543 SVN::_Core::svn_auth_set_parameter($baton,
5544 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
5545 bless (\$dont_store_passwords, "_p_void"));
5547 if (SVN::_Core::svn_config_get_bool($conf_t,
5548 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
5549 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
5550 1) == 0) {
5551 $Git::SVN::Prompt::_no_auth_cache = 1;
5553 } # no warnings 'once'
5554 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
5555 config => $config,
5556 pool => SVN::Pool->new,
5557 auth_provider_callbacks => $callbacks);
5558 $self->{url} = $url;
5559 $self->{svn_path} = $url;
5560 $self->{repos_root} = $self->get_repos_root;
5561 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
5562 $self->{cache} = { check_path => { r => 0, data => {} },
5563 get_dir => { r => 0, data => {} } };
5564 $RA = bless $self, $class;
5567 sub check_path {
5568 my ($self, $path, $r) = @_;
5569 my $cache = $self->{cache}->{check_path};
5570 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
5571 return $cache->{data}->{$path};
5573 my $pool = SVN::Pool->new;
5574 my $t = $self->SUPER::check_path($path, $r, $pool);
5575 $pool->clear;
5576 if ($r != $cache->{r}) {
5577 %{$cache->{data}} = ();
5578 $cache->{r} = $r;
5580 $cache->{data}->{$path} = $t;
5583 sub get_dir {
5584 my ($self, $dir, $r) = @_;
5585 my $cache = $self->{cache}->{get_dir};
5586 if ($r == $cache->{r}) {
5587 if (my $x = $cache->{data}->{$dir}) {
5588 return wantarray ? @$x : $x->[0];
5591 my $pool = SVN::Pool->new;
5592 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
5593 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
5594 $pool->clear;
5595 if ($r != $cache->{r}) {
5596 %{$cache->{data}} = ();
5597 $cache->{r} = $r;
5599 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
5600 wantarray ? (\%dirents, $r, $props) : \%dirents;
5603 sub DESTROY {
5604 # do not call the real DESTROY since we store ourselves in $RA
5607 # get_log(paths, start, end, limit,
5608 # discover_changed_paths, strict_node_history, receiver)
5609 sub get_log {
5610 my ($self, @args) = @_;
5611 my $pool = SVN::Pool->new;
5613 # svn_log_changed_path_t objects passed to get_log are likely to be
5614 # overwritten even if only the refs are copied to an external variable,
5615 # so we should dup the structures in their entirety. Using an
5616 # externally passed pool (instead of our temporary and quickly cleared
5617 # pool in Git::SVN::Ra) does not help matters at all...
5618 my $receiver = pop @args;
5619 my $prefix = "/".$self->{svn_path};
5620 $prefix =~ s#/+($)##;
5621 my $prefix_regex = qr#^\Q$prefix\E#;
5622 push(@args, sub {
5623 my ($paths) = $_[0];
5624 return &$receiver(@_) unless $paths;
5625 $_[0] = ();
5626 foreach my $p (keys %$paths) {
5627 my $i = $paths->{$p};
5628 # Make path relative to our url, not repos_root
5629 $p =~ s/$prefix_regex//;
5630 my %s = map { $_ => $i->$_; }
5631 qw/copyfrom_path copyfrom_rev action/;
5632 if ($s{'copyfrom_path'}) {
5633 $s{'copyfrom_path'} =~ s/$prefix_regex//;
5635 $_[0]{$p} = \%s;
5637 &$receiver(@_);
5641 # the limit parameter was not supported in SVN 1.1.x, so we
5642 # drop it. Therefore, the receiver callback passed to it
5643 # is made aware of this limitation by being wrapped if
5644 # the limit passed to is being wrapped.
5645 if (::compare_svn_version('1.2.0') <= 0) {
5646 my $limit = splice(@args, 3, 1);
5647 if ($limit > 0) {
5648 my $receiver = pop @args;
5649 push(@args, sub { &$receiver(@_) if (--$limit >= 0) });
5652 my $ret = $self->SUPER::get_log(@args, $pool);
5653 $pool->clear;
5654 $ret;
5657 sub trees_match {
5658 my ($self, $url1, $rev1, $url2, $rev2) = @_;
5659 my $ctx = SVN::Client->new(auth => _auth_providers);
5660 my $out = IO::File->new_tmpfile;
5662 # older SVN (1.1.x) doesn't take $pool as the last parameter for
5663 # $ctx->diff(), so we'll create a default one
5664 my $pool = SVN::Pool->new_default_sub;
5666 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
5667 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
5668 $out->flush;
5669 my $ret = (($out->stat)[7] == 0);
5670 close $out or croak $!;
5672 $ret;
5675 sub get_commit_editor {
5676 my ($self, $log, $cb, $pool) = @_;
5678 my @lock = (::compare_svn_version('1.2.0') >= 0) ? (undef, 0) : ();
5679 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
5682 sub gs_do_update {
5683 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
5684 my $new = ($rev_a == $rev_b);
5685 my $path = $gs->{path};
5687 if ($new && -e $gs->{index}) {
5688 unlink $gs->{index} or die
5689 "Couldn't unlink index: $gs->{index}: $!\n";
5691 my $pool = SVN::Pool->new;
5692 $editor->set_path_strip($path);
5693 my (@pc) = split m#/#, $path;
5694 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
5695 1, $editor, $pool);
5696 my @lock = (::compare_svn_version('1.2.0') >= 0) ? (undef) : ();
5698 # Since we can't rely on svn_ra_reparent being available, we'll
5699 # just have to do some magic with set_path to make it so
5700 # we only want a partial path.
5701 my $sp = '';
5702 my $final = join('/', @pc);
5703 while (@pc) {
5704 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
5705 $sp .= '/' if length $sp;
5706 $sp .= shift @pc;
5708 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
5710 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
5712 $reporter->finish_report($pool);
5713 $pool->clear;
5714 $editor->{git_commit_ok};
5717 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
5718 # svn_ra_reparent didn't work before 1.4)
5719 sub gs_do_switch {
5720 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
5721 my $path = $gs->{path};
5722 my $pool = SVN::Pool->new;
5724 my $full_url = $self->{url};
5725 my $old_url = $full_url;
5726 $full_url .= '/' . $path if length $path;
5727 my ($ra, $reparented);
5729 if ($old_url =~ m#^svn(\+ssh)?://# ||
5730 ($full_url =~ m#^https?://# &&
5731 escape_url($full_url) ne $full_url)) {
5732 $_[0] = undef;
5733 $self = undef;
5734 $RA = undef;
5735 $ra = Git::SVN::Ra->new($full_url);
5736 $ra_invalid = 1;
5737 } elsif ($old_url ne $full_url) {
5738 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url, $pool);
5739 $self->{url} = $full_url;
5740 $reparented = 1;
5743 $ra ||= $self;
5744 $url_b = escape_url($url_b);
5745 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
5746 my @lock = (::compare_svn_version('1.2.0') >= 0) ? (undef) : ();
5747 $reporter->set_path('', $rev_a, 0, @lock, $pool);
5748 $reporter->finish_report($pool);
5750 if ($reparented) {
5751 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
5752 $self->{url} = $old_url;
5755 $pool->clear;
5756 $editor->{git_commit_ok};
5759 sub longest_common_path {
5760 my ($gsv, $globs) = @_;
5761 my %common;
5762 my $common_max = scalar @$gsv;
5764 foreach my $gs (@$gsv) {
5765 my @tmp = split m#/#, $gs->{path};
5766 my $p = '';
5767 foreach (@tmp) {
5768 $p .= length($p) ? "/$_" : $_;
5769 $common{$p} ||= 0;
5770 $common{$p}++;
5773 $globs ||= [];
5774 $common_max += scalar @$globs;
5775 foreach my $glob (@$globs) {
5776 my @tmp = split m#/#, $glob->{path}->{left};
5777 my $p = '';
5778 foreach (@tmp) {
5779 $p .= length($p) ? "/$_" : $_;
5780 $common{$p} ||= 0;
5781 $common{$p}++;
5785 my $longest_path = '';
5786 foreach (sort {length $b <=> length $a} keys %common) {
5787 if ($common{$_} == $common_max) {
5788 $longest_path = $_;
5789 last;
5792 $longest_path;
5795 sub gs_fetch_loop_common {
5796 my ($self, $base, $head, $gsv, $globs) = @_;
5797 return if ($base > $head);
5798 my $inc = $_log_window_size;
5799 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
5800 my $longest_path = longest_common_path($gsv, $globs);
5801 my $ra_url = $self->{url};
5802 my $find_trailing_edge;
5803 while (1) {
5804 my %revs;
5805 my $err;
5806 my $err_handler = $SVN::Error::handler;
5807 $SVN::Error::handler = sub {
5808 ($err) = @_;
5809 skip_unknown_revs($err);
5811 sub _cb {
5812 my ($paths, $r, $author, $date, $log) = @_;
5813 [ $paths,
5814 { author => $author, date => $date, log => $log } ];
5816 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
5817 sub { $revs{$_[1]} = _cb(@_) });
5818 if ($err) {
5819 print "Checked through r$max\r";
5820 } else {
5821 $find_trailing_edge = 1;
5823 if ($err and $find_trailing_edge) {
5824 print STDERR "Path '$longest_path' ",
5825 "was probably deleted:\n",
5826 $err->expanded_message,
5827 "\nWill attempt to follow ",
5828 "revisions r$min .. r$max ",
5829 "committed before the deletion\n";
5830 my $hi = $max;
5831 while (--$hi >= $min) {
5832 my $ok;
5833 $self->get_log([$longest_path], $min, $hi,
5834 0, 1, 1, sub {
5835 $ok = $_[1];
5836 $revs{$_[1]} = _cb(@_) });
5837 if ($ok) {
5838 print STDERR "r$min .. r$ok OK\n";
5839 last;
5842 $find_trailing_edge = 0;
5844 $SVN::Error::handler = $err_handler;
5846 my %exists = map { $_->{path} => $_ } @$gsv;
5847 foreach my $r (sort {$a <=> $b} keys %revs) {
5848 my ($paths, $logged) = @{$revs{$r}};
5850 foreach my $gs ($self->match_globs(\%exists, $paths,
5851 $globs, $r)) {
5852 if ($gs->rev_map_max >= $r) {
5853 next;
5855 next unless $gs->match_paths($paths, $r);
5856 $gs->{logged_rev_props} = $logged;
5857 if (my $last_commit = $gs->last_commit) {
5858 $gs->assert_index_clean($last_commit);
5860 my $log_entry = $gs->do_fetch($paths, $r);
5861 if ($log_entry) {
5862 $gs->do_git_commit($log_entry);
5864 $INDEX_FILES{$gs->{index}} = 1;
5866 foreach my $g (@$globs) {
5867 my $k = "svn-remote.$g->{remote}." .
5868 "$g->{t}-maxRev";
5869 Git::SVN::tmp_config($k, $r);
5871 if ($ra_invalid) {
5872 $_[0] = undef;
5873 $self = undef;
5874 $RA = undef;
5875 $self = Git::SVN::Ra->new($ra_url);
5876 $ra_invalid = undef;
5879 # pre-fill the .rev_db since it'll eventually get filled in
5880 # with '0' x40 if something new gets committed
5881 foreach my $gs (@$gsv) {
5882 next if $gs->rev_map_max >= $max;
5883 next if defined $gs->rev_map_get($max);
5884 $gs->rev_map_set($max, 0 x40);
5886 foreach my $g (@$globs) {
5887 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
5888 Git::SVN::tmp_config($k, $max);
5890 last if $max >= $head;
5891 $min = $max + 1;
5892 $max += $inc;
5893 $max = $head if ($max > $head);
5895 Git::SVN::gc();
5898 sub get_dir_globbed {
5899 my ($self, $left, $depth, $r) = @_;
5901 my @x = eval { $self->get_dir($left, $r) };
5902 return unless scalar @x == 3;
5903 my $dirents = $x[0];
5904 my @finalents;
5905 foreach my $de (keys %$dirents) {
5906 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
5907 if ($depth > 1) {
5908 my @args = ("$left/$de", $depth - 1, $r);
5909 foreach my $dir ($self->get_dir_globbed(@args)) {
5910 push @finalents, "$de/$dir";
5912 } else {
5913 push @finalents, $de;
5916 @finalents;
5919 # return value: 0 -- don't ignore, 1 -- ignore
5920 sub is_ref_ignored {
5921 my ($g, $p) = @_;
5922 my $refname = $g->{ref}->full_path($p);
5923 return 1 if defined($g->{ignore_refs_regex}) &&
5924 $refname =~ m!$g->{ignore_refs_regex}!;
5925 return 0 unless defined($_ignore_refs_regex);
5926 return 1 if $refname =~ m!$_ignore_refs_regex!o;
5927 return 0;
5930 sub match_globs {
5931 my ($self, $exists, $paths, $globs, $r) = @_;
5933 sub get_dir_check {
5934 my ($self, $exists, $g, $r) = @_;
5936 my @dirs = $self->get_dir_globbed($g->{path}->{left},
5937 $g->{path}->{depth},
5938 $r);
5940 foreach my $de (@dirs) {
5941 my $p = $g->{path}->full_path($de);
5942 next if $exists->{$p};
5943 next if (length $g->{path}->{right} &&
5944 ($self->check_path($p, $r) !=
5945 $SVN::Node::dir));
5946 next unless $p =~ /$g->{path}->{regex}/;
5947 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
5948 $g->{ref}->full_path($de), 1);
5951 foreach my $g (@$globs) {
5952 if (my $path = $paths->{"/$g->{path}->{left}"}) {
5953 if ($path->{action} =~ /^[AR]$/) {
5954 get_dir_check($self, $exists, $g, $r);
5957 foreach (keys %$paths) {
5958 if (/$g->{path}->{left_regex}/ &&
5959 !/$g->{path}->{regex}/) {
5960 next if $paths->{$_}->{action} !~ /^[AR]$/;
5961 get_dir_check($self, $exists, $g, $r);
5963 next unless /$g->{path}->{regex}/;
5964 my $p = $1;
5965 my $pathname = $g->{path}->full_path($p);
5966 next if is_ref_ignored($g, $p);
5967 next if $exists->{$pathname};
5968 next if ($self->check_path($pathname, $r) !=
5969 $SVN::Node::dir);
5970 $exists->{$pathname} = Git::SVN->init(
5971 $self->{url}, $pathname, undef,
5972 $g->{ref}->full_path($p), 1);
5974 my $c = '';
5975 foreach (split m#/#, $g->{path}->{left}) {
5976 $c .= "/$_";
5977 next unless ($paths->{$c} &&
5978 ($paths->{$c}->{action} =~ /^[AR]$/));
5979 get_dir_check($self, $exists, $g, $r);
5982 values %$exists;
5985 sub minimize_url {
5986 my ($self) = @_;
5987 return $self->{url} if ($self->{url} eq $self->{repos_root});
5988 my $url = $self->{repos_root};
5989 my @components = split(m!/!, $self->{svn_path});
5990 my $c = '';
5991 do {
5992 $url .= "/$c" if length $c;
5993 eval {
5994 my $ra = (ref $self)->new($url);
5995 my $latest = $ra->get_latest_revnum;
5996 $ra->get_log("", $latest, 0, 1, 0, 1, sub {});
5998 } while ($@ && ($c = shift @components));
5999 $url;
6002 sub can_do_switch {
6003 my $self = shift;
6004 unless (defined $can_do_switch) {
6005 my $pool = SVN::Pool->new;
6006 my $rep = eval {
6007 $self->do_switch(1, '', 0, $self->{url},
6008 SVN::Delta::Editor->new, $pool);
6010 if ($@) {
6011 $can_do_switch = 0;
6012 } else {
6013 $rep->abort_report($pool);
6014 $can_do_switch = 1;
6016 $pool->clear;
6018 $can_do_switch;
6021 sub skip_unknown_revs {
6022 my ($err) = @_;
6023 my $errno = $err->apr_err();
6024 # Maybe the branch we're tracking didn't
6025 # exist when the repo started, so it's
6026 # not an error if it doesn't, just continue
6028 # Wonderfully consistent library, eh?
6029 # 160013 - svn:// and file://
6030 # 175002 - http(s)://
6031 # 175007 - http(s):// (this repo required authorization, too...)
6032 # More codes may be discovered later...
6033 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
6034 my $err_key = $err->expanded_message;
6035 # revision numbers change every time, filter them out
6036 $err_key =~ s/\d+/\0/g;
6037 $err_key = "$errno\0$err_key";
6038 unless ($ignored_err{$err_key}) {
6039 warn "W: Ignoring error from SVN, path probably ",
6040 "does not exist: ($errno): ",
6041 $err->expanded_message,"\n";
6042 warn "W: Do not be alarmed at the above message ",
6043 "git-svn is just searching aggressively for ",
6044 "old history.\n",
6045 "This may take a while on large repositories\n";
6046 $ignored_err{$err_key} = 1;
6048 return;
6050 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
6053 package Git::SVN::Log;
6054 use strict;
6055 use warnings;
6056 use POSIX qw/strftime/;
6057 use constant commit_log_separator => ('-' x 72) . "\n";
6058 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
6059 %rusers $show_commit $incremental/;
6060 my $l_fmt;
6062 sub cmt_showable {
6063 my ($c) = @_;
6064 return 1 if defined $c->{r};
6066 # big commit message got truncated by the 16k pretty buffer in rev-list
6067 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
6068 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
6069 @{$c->{l}} = ();
6070 my @log = command(qw/cat-file commit/, $c->{c});
6072 # shift off the headers
6073 shift @log while ($log[0] ne '');
6074 shift @log;
6076 # TODO: make $c->{l} not have a trailing newline in the future
6077 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
6079 (undef, $c->{r}, undef) = ::extract_metadata(
6080 (grep(/^git-svn-id: /, @log))[-1]);
6082 return defined $c->{r};
6085 sub log_use_color {
6086 return $color || Git->repository->get_colorbool('color.diff');
6089 sub git_svn_log_cmd {
6090 my ($r_min, $r_max, @args) = @_;
6091 my $head = 'HEAD';
6092 my (@files, @log_opts);
6093 foreach my $x (@args) {
6094 if ($x eq '--' || @files) {
6095 push @files, $x;
6096 } else {
6097 if (::verify_ref("$x^0")) {
6098 $head = $x;
6099 } else {
6100 push @log_opts, $x;
6105 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
6106 $gs ||= Git::SVN->_new;
6107 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
6108 $gs->refname);
6109 push @cmd, '-r' unless $non_recursive;
6110 push @cmd, qw/--raw --name-status/ if $verbose;
6111 push @cmd, '--color' if log_use_color();
6112 push @cmd, @log_opts;
6113 if (defined $r_max && $r_max == $r_min) {
6114 push @cmd, '--max-count=1';
6115 if (my $c = $gs->rev_map_get($r_max)) {
6116 push @cmd, $c;
6118 } elsif (defined $r_max) {
6119 if ($r_max < $r_min) {
6120 ($r_min, $r_max) = ($r_max, $r_min);
6122 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
6123 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
6124 # If there are no commits in the range, both $c_max and $c_min
6125 # will be undefined. If there is at least 1 commit in the
6126 # range, both will be defined.
6127 return () if !defined $c_min || !defined $c_max;
6128 if ($c_min eq $c_max) {
6129 push @cmd, '--max-count=1', $c_min;
6130 } else {
6131 push @cmd, '--boundary', "$c_min..$c_max";
6134 return (@cmd, @files);
6137 # adapted from pager.c
6138 sub config_pager {
6139 if (! -t *STDOUT) {
6140 $ENV{GIT_PAGER_IN_USE} = 'false';
6141 $pager = undef;
6142 return;
6144 chomp($pager = command_oneline(qw(var GIT_PAGER)));
6145 if ($pager eq 'cat') {
6146 $pager = undef;
6148 $ENV{GIT_PAGER_IN_USE} = defined($pager);
6151 sub run_pager {
6152 return unless defined $pager;
6153 pipe my ($rfd, $wfd) or return;
6154 defined(my $pid = fork) or ::fatal "Can't fork: $!";
6155 if (!$pid) {
6156 open STDOUT, '>&', $wfd or
6157 ::fatal "Can't redirect to stdout: $!";
6158 return;
6160 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
6161 $ENV{LESS} ||= 'FRSX';
6162 exec $pager or ::fatal "Can't run pager: $! ($pager)";
6165 sub format_svn_date {
6166 my $t = shift || time;
6167 my $gmoff = Git::SVN::get_tz($t);
6168 return strftime("%Y-%m-%d %H:%M:%S $gmoff (%a, %d %b %Y)", localtime($t));
6171 sub parse_git_date {
6172 my ($t, $tz) = @_;
6173 # Date::Parse isn't in the standard Perl distro :(
6174 if ($tz =~ s/^\+//) {
6175 $t += tz_to_s_offset($tz);
6176 } elsif ($tz =~ s/^\-//) {
6177 $t -= tz_to_s_offset($tz);
6179 return $t;
6182 sub set_local_timezone {
6183 if (defined $TZ) {
6184 $ENV{TZ} = $TZ;
6185 } else {
6186 delete $ENV{TZ};
6190 sub tz_to_s_offset {
6191 my ($tz) = @_;
6192 $tz =~ s/(\d\d)$//;
6193 return ($1 * 60) + ($tz * 3600);
6196 sub get_author_info {
6197 my ($dest, $author, $t, $tz) = @_;
6198 $author =~ s/(?:^\s*|\s*$)//g;
6199 $dest->{a_raw} = $author;
6200 my $au;
6201 if ($::_authors) {
6202 $au = $rusers{$author} || undef;
6204 if (!$au) {
6205 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
6207 $dest->{t} = $t;
6208 $dest->{tz} = $tz;
6209 $dest->{a} = $au;
6210 $dest->{t_utc} = parse_git_date($t, $tz);
6213 sub process_commit {
6214 my ($c, $r_min, $r_max, $defer) = @_;
6215 if (defined $r_min && defined $r_max) {
6216 if ($r_min == $c->{r} && $r_min == $r_max) {
6217 show_commit($c);
6218 return 0;
6220 return 1 if $r_min == $r_max;
6221 if ($r_min < $r_max) {
6222 # we need to reverse the print order
6223 return 0 if (defined $limit && --$limit < 0);
6224 push @$defer, $c;
6225 return 1;
6227 if ($r_min != $r_max) {
6228 return 1 if ($r_min < $c->{r});
6229 return 1 if ($r_max > $c->{r});
6232 return 0 if (defined $limit && --$limit < 0);
6233 show_commit($c);
6234 return 1;
6237 sub show_commit {
6238 my $c = shift;
6239 if ($oneline) {
6240 my $x = "\n";
6241 if (my $l = $c->{l}) {
6242 while ($l->[0] =~ /^\s*$/) { shift @$l }
6243 $x = $l->[0];
6245 $l_fmt ||= 'A' . length($c->{r});
6246 print 'r',pack($l_fmt, $c->{r}),' | ';
6247 print "$c->{c} | " if $show_commit;
6248 print $x;
6249 } else {
6250 show_commit_normal($c);
6254 sub show_commit_changed_paths {
6255 my ($c) = @_;
6256 return unless $c->{changed};
6257 print "Changed paths:\n", @{$c->{changed}};
6260 sub show_commit_normal {
6261 my ($c) = @_;
6262 print commit_log_separator, "r$c->{r} | ";
6263 print "$c->{c} | " if $show_commit;
6264 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
6265 my $nr_line = 0;
6267 if (my $l = $c->{l}) {
6268 while ($l->[$#$l] eq "\n" && $#$l > 0
6269 && $l->[($#$l - 1)] eq "\n") {
6270 pop @$l;
6272 $nr_line = scalar @$l;
6273 if (!$nr_line) {
6274 print "1 line\n\n\n";
6275 } else {
6276 if ($nr_line == 1) {
6277 $nr_line = '1 line';
6278 } else {
6279 $nr_line .= ' lines';
6281 print $nr_line, "\n";
6282 show_commit_changed_paths($c);
6283 print "\n";
6284 print $_ foreach @$l;
6286 } else {
6287 print "1 line\n";
6288 show_commit_changed_paths($c);
6289 print "\n";
6292 foreach my $x (qw/raw stat diff/) {
6293 if ($c->{$x}) {
6294 print "\n";
6295 print $_ foreach @{$c->{$x}}
6300 sub cmd_show_log {
6301 my (@args) = @_;
6302 my ($r_min, $r_max);
6303 my $r_last = -1; # prevent dupes
6304 set_local_timezone();
6305 if (defined $::_revision) {
6306 if ($::_revision =~ /^(\d+):(\d+)$/) {
6307 ($r_min, $r_max) = ($1, $2);
6308 } elsif ($::_revision =~ /^\d+$/) {
6309 $r_min = $r_max = $::_revision;
6310 } else {
6311 ::fatal "-r$::_revision is not supported, use ",
6312 "standard 'git log' arguments instead";
6316 config_pager();
6317 @args = git_svn_log_cmd($r_min, $r_max, @args);
6318 if (!@args) {
6319 print commit_log_separator unless $incremental || $oneline;
6320 return;
6322 my $log = command_output_pipe(@args);
6323 run_pager();
6324 my (@k, $c, $d, $stat);
6325 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
6326 while (<$log>) {
6327 if (/^${esc_color}commit (?:- )?($::sha1_short)/o) {
6328 my $cmt = $1;
6329 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
6330 $r_last = $c->{r};
6331 process_commit($c, $r_min, $r_max, \@k) or
6332 goto out;
6334 $d = undef;
6335 $c = { c => $cmt };
6336 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
6337 get_author_info($c, $1, $2, $3);
6338 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
6339 # ignore
6340 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
6341 push @{$c->{raw}}, $_;
6342 } elsif (/^${esc_color}[ACRMDT]\t/) {
6343 # we could add $SVN->{svn_path} here, but that requires
6344 # remote access at the moment (repo_path_split)...
6345 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
6346 push @{$c->{changed}}, $_;
6347 } elsif (/^${esc_color}diff /o) {
6348 $d = 1;
6349 push @{$c->{diff}}, $_;
6350 } elsif ($d) {
6351 push @{$c->{diff}}, $_;
6352 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
6353 $esc_color*[\+\-]*$esc_color$/x) {
6354 $stat = 1;
6355 push @{$c->{stat}}, $_;
6356 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
6357 push @{$c->{stat}}, $_;
6358 $stat = undef;
6359 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
6360 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
6361 } elsif (s/^${esc_color} //o) {
6362 push @{$c->{l}}, $_;
6365 if ($c && defined $c->{r} && $c->{r} != $r_last) {
6366 $r_last = $c->{r};
6367 process_commit($c, $r_min, $r_max, \@k);
6369 if (@k) {
6370 ($r_min, $r_max) = ($r_max, $r_min);
6371 process_commit($_, $r_min, $r_max) foreach reverse @k;
6373 out:
6374 close $log;
6375 print commit_log_separator unless $incremental || $oneline;
6378 sub cmd_blame {
6379 my $path = pop;
6381 config_pager();
6382 run_pager();
6384 my ($fh, $ctx, $rev);
6386 if ($_git_format) {
6387 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
6388 while (my $line = <$fh>) {
6389 if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
6390 # Uncommitted edits show up as a rev ID of
6391 # all zeros, which we can't look up with
6392 # cmt_metadata
6393 if ($1 !~ /^0+$/) {
6394 (undef, $rev, undef) =
6395 ::cmt_metadata($1);
6396 $rev = '0' if (!$rev);
6397 } else {
6398 $rev = '0';
6400 $rev = sprintf('%-10s', $rev);
6401 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
6403 print $line;
6405 } else {
6406 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
6407 '--', $path);
6408 my ($sha1);
6409 my %authors;
6410 my @buffer;
6411 my %dsha; #distinct sha keys
6413 while (my $line = <$fh>) {
6414 push @buffer, $line;
6415 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
6416 $dsha{$1} = 1;
6420 my $s2r = ::cmt_sha2rev_batch([keys %dsha]);
6422 foreach my $line (@buffer) {
6423 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
6424 $rev = $s2r->{$1};
6425 $rev = '0' if (!$rev)
6427 elsif ($line =~ /^author (.*)/) {
6428 $authors{$rev} = $1;
6429 $authors{$rev} =~ s/\s/_/g;
6431 elsif ($line =~ /^\t(.*)$/) {
6432 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
6436 command_close_pipe($fh, $ctx);
6439 package Git::SVN::Migration;
6440 # these version numbers do NOT correspond to actual version numbers
6441 # of git nor git-svn. They are just relative.
6443 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
6445 # v1 layout: .git/$id/info/url, refs/remotes/$id
6447 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
6449 # v3 layout: .git/svn/$id, refs/remotes/$id
6450 # - info/url may remain for backwards compatibility
6451 # - this is what we migrate up to this layout automatically,
6452 # - this will be used by git svn init on single branches
6453 # v3.1 layout (auto migrated):
6454 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
6455 # for backwards compatibility
6457 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
6458 # - this is only created for newly multi-init-ed
6459 # repositories. Similar in spirit to the
6460 # --use-separate-remotes option in git-clone (now default)
6461 # - we do not automatically migrate to this (following
6462 # the example set by core git)
6464 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
6465 # - newer, more-efficient format that uses 24-bytes per record
6466 # with no filler space.
6467 # - use xxd -c24 < .rev_map.$UUID to view and debug
6468 # - This is a one-way migration, repositories updated to the
6469 # new format will not be able to use old git-svn without
6470 # rebuilding the .rev_db. Rebuilding the rev_db is not
6471 # possible if noMetadata or useSvmProps are set; but should
6472 # be no problem for users that use the (sensible) defaults.
6473 use strict;
6474 use warnings;
6475 use Carp qw/croak/;
6476 use File::Path qw/mkpath/;
6477 use File::Basename qw/dirname basename/;
6478 use vars qw/$_minimize/;
6480 sub migrate_from_v0 {
6481 my $git_dir = $ENV{GIT_DIR};
6482 return undef unless -d $git_dir;
6483 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
6484 my $migrated = 0;
6485 while (<$fh>) {
6486 chomp;
6487 my ($id, $orig_ref) = ($_, $_);
6488 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
6489 next unless -f "$git_dir/$id/info/url";
6490 my $new_ref = "refs/remotes/$id";
6491 if (::verify_ref("$new_ref^0")) {
6492 print STDERR "W: $orig_ref is probably an old ",
6493 "branch used by an ancient version of ",
6494 "git-svn.\n",
6495 "However, $new_ref also exists.\n",
6496 "We will not be able ",
6497 "to use this branch until this ",
6498 "ambiguity is resolved.\n";
6499 next;
6501 print STDERR "Migrating from v0 layout...\n" if !$migrated;
6502 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
6503 command_noisy('update-ref', $new_ref, $orig_ref);
6504 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
6505 $migrated++;
6507 command_close_pipe($fh, $ctx);
6508 print STDERR "Done migrating from v0 layout...\n" if $migrated;
6509 $migrated;
6512 sub migrate_from_v1 {
6513 my $git_dir = $ENV{GIT_DIR};
6514 my $migrated = 0;
6515 return $migrated unless -d $git_dir;
6516 my $svn_dir = "$git_dir/svn";
6518 # just in case somebody used 'svn' as their $id at some point...
6519 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
6521 print STDERR "Migrating from a git-svn v1 layout...\n";
6522 mkpath([$svn_dir]);
6523 print STDERR "Data from a previous version of git-svn exists, but\n\t",
6524 "$svn_dir\n\t(required for this version ",
6525 "($::VERSION) of git-svn) does not exist.\n";
6526 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
6527 while (<$fh>) {
6528 my $x = $_;
6529 next unless $x =~ s#^refs/remotes/##;
6530 chomp $x;
6531 next unless -f "$git_dir/$x/info/url";
6532 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
6533 next unless $u;
6534 my $dn = dirname("$git_dir/svn/$x");
6535 mkpath([$dn]) unless -d $dn;
6536 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
6537 mkpath(["$git_dir/svn/svn"]);
6538 print STDERR " - $git_dir/$x/info => ",
6539 "$git_dir/svn/$x/info\n";
6540 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
6541 croak "$!: $x";
6542 # don't worry too much about these, they probably
6543 # don't exist with repos this old (save for index,
6544 # and we can easily regenerate that)
6545 foreach my $f (qw/unhandled.log index .rev_db/) {
6546 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
6548 } else {
6549 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
6550 rename "$git_dir/$x", "$git_dir/svn/$x" or
6551 croak "$!: $x";
6553 $migrated++;
6555 command_close_pipe($fh, $ctx);
6556 print STDERR "Done migrating from a git-svn v1 layout\n";
6557 $migrated;
6560 sub read_old_urls {
6561 my ($l_map, $pfx, $path) = @_;
6562 my @dir;
6563 foreach (<$path/*>) {
6564 if (-r "$_/info/url") {
6565 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
6566 my $ref_id = $pfx . basename $_;
6567 my $url = ::file_to_s("$_/info/url");
6568 $l_map->{$ref_id} = $url;
6569 } elsif (-d $_) {
6570 push @dir, $_;
6573 foreach (@dir) {
6574 my $x = $_;
6575 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
6576 read_old_urls($l_map, $x, $_);
6580 sub migrate_from_v2 {
6581 my @cfg = command(qw/config -l/);
6582 return if grep /^svn-remote\..+\.url=/, @cfg;
6583 my %l_map;
6584 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
6585 my $migrated = 0;
6587 foreach my $ref_id (sort keys %l_map) {
6588 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
6589 if ($@) {
6590 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
6592 $migrated++;
6594 $migrated;
6597 sub minimize_connections {
6598 my $r = Git::SVN::read_all_remotes();
6599 my $new_urls = {};
6600 my $root_repos = {};
6601 foreach my $repo_id (keys %$r) {
6602 my $url = $r->{$repo_id}->{url} or next;
6603 my $fetch = $r->{$repo_id}->{fetch} or next;
6604 my $ra = Git::SVN::Ra->new($url);
6606 # skip existing cases where we already connect to the root
6607 if (($ra->{url} eq $ra->{repos_root}) ||
6608 ($ra->{repos_root} eq $repo_id)) {
6609 $root_repos->{$ra->{url}} = $repo_id;
6610 next;
6613 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
6614 my $root_path = $ra->{url};
6615 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
6616 foreach my $path (keys %$fetch) {
6617 my $ref_id = $fetch->{$path};
6618 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
6620 # make sure we can read when connecting to
6621 # a higher level of a repository
6622 my ($last_rev, undef) = $gs->last_rev_commit;
6623 if (!defined $last_rev) {
6624 $last_rev = eval {
6625 $root_ra->get_latest_revnum;
6627 next if $@;
6629 my $new = $root_path;
6630 $new .= length $path ? "/$path" : '';
6631 eval {
6632 $root_ra->get_log([$new], $last_rev, $last_rev,
6633 0, 0, 1, sub { });
6635 next if $@;
6636 $new_urls->{$ra->{repos_root}}->{$new} =
6637 { ref_id => $ref_id,
6638 old_repo_id => $repo_id,
6639 old_path => $path };
6643 my @emptied;
6644 foreach my $url (keys %$new_urls) {
6645 # see if we can re-use an existing [svn-remote "repo_id"]
6646 # instead of creating a(n ugly) new section:
6647 my $repo_id = $root_repos->{$url} || $url;
6649 my $fetch = $new_urls->{$url};
6650 foreach my $path (keys %$fetch) {
6651 my $x = $fetch->{$path};
6652 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
6653 my $pfx = "svn-remote.$x->{old_repo_id}";
6655 my $old_fetch = quotemeta("$x->{old_path}:".
6656 "$x->{ref_id}");
6657 command_noisy(qw/config --unset/,
6658 "$pfx.fetch", '^'. $old_fetch . '$');
6659 delete $r->{$x->{old_repo_id}}->
6660 {fetch}->{$x->{old_path}};
6661 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
6662 command_noisy(qw/config --unset/,
6663 "$pfx.url");
6664 push @emptied, $x->{old_repo_id}
6668 if (@emptied) {
6669 my $file = $ENV{GIT_CONFIG} || "$ENV{GIT_DIR}/config";
6670 print STDERR <<EOF;
6671 The following [svn-remote] sections in your config file ($file) are empty
6672 and can be safely removed:
6674 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
6678 sub migration_check {
6679 migrate_from_v0();
6680 migrate_from_v1();
6681 migrate_from_v2();
6682 minimize_connections() if $_minimize;
6685 package Git::IndexInfo;
6686 use strict;
6687 use warnings;
6688 use Git qw/command_input_pipe command_close_pipe/;
6690 sub new {
6691 my ($class) = @_;
6692 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
6693 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
6696 sub remove {
6697 my ($self, $path) = @_;
6698 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
6699 return ++$self->{nr};
6701 undef;
6704 sub update {
6705 my ($self, $mode, $hash, $path) = @_;
6706 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
6707 return ++$self->{nr};
6709 undef;
6712 sub DESTROY {
6713 my ($self) = @_;
6714 command_close_pipe($self->{gui}, $self->{ctx});
6717 package Git::SVN::GlobSpec;
6718 use strict;
6719 use warnings;
6721 sub new {
6722 my ($class, $glob, $pattern_ok) = @_;
6723 my $re = $glob;
6724 $re =~ s!/+$!!g; # no need for trailing slashes
6725 my (@left, @right, @patterns);
6726 my $state = "left";
6727 my $die_msg = "Only one set of wildcard directories " .
6728 "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
6729 for my $part (split(m|/|, $glob)) {
6730 if ($part =~ /\*/ && $part ne "*") {
6731 die "Invalid pattern in '$glob': $part\n";
6732 } elsif ($pattern_ok && $part =~ /[{}]/ &&
6733 $part !~ /^\{[^{}]+\}/) {
6734 die "Invalid pattern in '$glob': $part\n";
6736 if ($part eq "*") {
6737 die $die_msg if $state eq "right";
6738 $state = "pattern";
6739 push(@patterns, "[^/]*");
6740 } elsif ($pattern_ok && $part =~ /^\{(.*)\}$/) {
6741 die $die_msg if $state eq "right";
6742 $state = "pattern";
6743 my $p = quotemeta($1);
6744 $p =~ s/\\,/|/g;
6745 push(@patterns, "(?:$p)");
6746 } else {
6747 if ($state eq "left") {
6748 push(@left, $part);
6749 } else {
6750 push(@right, $part);
6751 $state = "right";
6755 my $depth = @patterns;
6756 if ($depth == 0) {
6757 die "One '*' is needed in glob: '$glob'\n";
6759 my $left = join('/', @left);
6760 my $right = join('/', @right);
6761 $re = join('/', @patterns);
6762 $re = join('\/',
6763 grep(length, quotemeta($left), "($re)", quotemeta($right)));
6764 my $left_re = qr/^\/\Q$left\E(\/|$)/;
6765 bless { left => $left, right => $right, left_regex => $left_re,
6766 regex => qr/$re/, glob => $glob, depth => $depth }, $class;
6769 sub full_path {
6770 my ($self, $path) = @_;
6771 return (length $self->{left} ? "$self->{left}/" : '') .
6772 $path . (length $self->{right} ? "/$self->{right}" : '');
6775 __END__
6777 Data structures:
6780 $remotes = { # returned by read_all_remotes()
6781 'svn' => {
6782 # svn-remote.svn.url=https://svn.musicpd.org
6783 url => 'https://svn.musicpd.org',
6784 # svn-remote.svn.fetch=mpd/trunk:trunk
6785 fetch => {
6786 'mpd/trunk' => 'trunk',
6788 # svn-remote.svn.tags=mpd/tags/*:tags/*
6789 tags => {
6790 path => {
6791 left => 'mpd/tags',
6792 right => '',
6793 regex => qr!mpd/tags/([^/]+)$!,
6794 glob => 'tags/*',
6796 ref => {
6797 left => 'tags',
6798 right => '',
6799 regex => qr!tags/([^/]+)$!,
6800 glob => 'tags/*',
6806 $log_entry hashref as returned by libsvn_log_entry()
6808 log => 'whitespace-formatted log entry
6809 ', # trailing newline is preserved
6810 revision => '8', # integer
6811 date => '2004-02-24T17:01:44.108345Z', # commit date
6812 author => 'committer name'
6816 # this is generated by generate_diff();
6817 @mods = array of diff-index line hashes, each element represents one line
6818 of diff-index output
6820 diff-index line ($m hash)
6822 mode_a => first column of diff-index output, no leading ':',
6823 mode_b => second column of diff-index output,
6824 sha1_b => sha1sum of the final blob,
6825 chg => change type [MCRADT],
6826 file_a => original file name of a file (iff chg is 'C' or 'R')
6827 file_b => new/current file name of a file (any chg)
6831 # retval of read_url_paths{,_all}();
6832 $l_map = {
6833 # repository root url
6834 'https://svn.musicpd.org' => {
6835 # repository path # GIT_SVN_ID
6836 'mpd/trunk' => 'trunk',
6837 'mpd/tags/0.11.5' => 'tags/0.11.5',
6841 Notes:
6842 I don't trust the each() function on unless I created %hash myself
6843 because the internal iterator may not have started at base.