completion: respect $GIT_DIR
[git/mjg.git] / git-svn.perl
blob31d02b5f70f553e27e0bdc760355909cb535f813
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, $_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 %fc_opts } ],
259 'commit-diff' => [ \&cmd_commit_diff,
260 'Commit a diff between two trees',
261 { 'message|m=s' => \$_message,
262 'file|F=s' => \$_file,
263 'revision|r=s' => \$_revision,
264 %cmt_opts } ],
265 'info' => [ \&cmd_info,
266 "Show info about the latest SVN revision
267 on the current branch",
268 { 'url' => \$_url, } ],
269 'blame' => [ \&Git::SVN::Log::cmd_blame,
270 "Show what revision and author last modified each line of a file",
271 { 'git-format' => \$_git_format } ],
272 'reset' => [ \&cmd_reset,
273 "Undo fetches back to the specified SVN revision",
274 { 'revision|r=s' => \$_revision,
275 'parent|p' => \$_fetch_parent } ],
276 'gc' => [ \&cmd_gc,
277 "Compress unhandled.log files in .git/svn and remove " .
278 "index files in .git/svn",
279 {} ],
282 use Term::ReadLine;
283 package FakeTerm;
284 sub new {
285 my ($class, $reason) = @_;
286 return bless \$reason, shift;
288 sub readline {
289 my $self = shift;
290 die "Cannot use readline on FakeTerm: $$self";
292 package main;
294 my $term = eval {
295 $ENV{"GIT_SVN_NOTTY"}
296 ? new Term::ReadLine 'git-svn', \*STDIN, \*STDOUT
297 : new Term::ReadLine 'git-svn';
299 if ($@) {
300 $term = new FakeTerm "$@: going non-interactive";
303 my $cmd;
304 for (my $i = 0; $i < @ARGV; $i++) {
305 if (defined $cmd{$ARGV[$i]}) {
306 $cmd = $ARGV[$i];
307 splice @ARGV, $i, 1;
308 last;
309 } elsif ($ARGV[$i] eq 'help') {
310 $cmd = $ARGV[$i+1];
311 usage(0);
315 # make sure we're always running at the top-level working directory
316 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
317 unless (-d $ENV{GIT_DIR}) {
318 if ($git_dir_user_set) {
319 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
320 "but it is not a directory\n";
322 my $git_dir = delete $ENV{GIT_DIR};
323 my $cdup = undef;
324 git_cmd_try {
325 $cdup = command_oneline(qw/rev-parse --show-cdup/);
326 $git_dir = '.' unless ($cdup);
327 chomp $cdup if ($cdup);
328 $cdup = "." unless ($cdup && length $cdup);
329 } "Already at toplevel, but $git_dir not found\n";
330 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
331 unless (-d $git_dir) {
332 die "$git_dir still not found after going to ",
333 "'$cdup'\n";
335 $ENV{GIT_DIR} = $git_dir;
337 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
340 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
342 read_git_config(\%opts);
343 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
344 Getopt::Long::Configure('pass_through');
346 my $rv = GetOptions(%opts, 'h|H' => \$_help, 'version|V' => \$_version,
347 'minimize-connections' => \$Git::SVN::Migration::_minimize,
348 'id|i=s' => \$Git::SVN::default_ref_id,
349 'svn-remote|remote|R=s' => sub {
350 $Git::SVN::no_reuse_existing = 1;
351 $Git::SVN::default_repo_id = $_[1] });
352 exit 1 if (!$rv && $cmd && $cmd ne 'log');
354 usage(0) if $_help;
355 version() if $_version;
356 usage(1) unless defined $cmd;
357 load_authors() if $_authors;
358 if (defined $_authors_prog) {
359 $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
362 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
363 Git::SVN::Migration::migration_check();
365 Git::SVN::init_vars();
366 eval {
367 Git::SVN::verify_remotes_sanity();
368 $cmd{$cmd}->[0]->(@ARGV);
370 fatal $@ if $@;
371 post_fetch_checkout();
372 exit 0;
374 ####################### primary functions ######################
375 sub usage {
376 my $exit = shift || 0;
377 my $fd = $exit ? \*STDERR : \*STDOUT;
378 print $fd <<"";
379 git-svn - bidirectional operations between a single Subversion tree and git
380 Usage: git svn <command> [options] [arguments]\n
382 print $fd "Available commands:\n" unless $cmd;
384 foreach (sort keys %cmd) {
385 next if $cmd && $cmd ne $_;
386 next if /^multi-/; # don't show deprecated commands
387 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
388 foreach (sort keys %{$cmd{$_}->[2]}) {
389 # mixed-case options are for .git/config only
390 next if /[A-Z]/ && /^[a-z]+$/i;
391 # prints out arguments as they should be passed:
392 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
393 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
394 "--$_" : "-$_" }
395 split /\|/,$_)," $x\n";
398 print $fd <<"";
399 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
400 arbitrary identifier if you're tracking multiple SVN branches/repositories in
401 one git repository and want to keep them separate. See git-svn(1) for more
402 information.
404 exit $exit;
407 sub version {
408 ::_req_svn();
409 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
410 exit 0;
413 sub ask {
414 my ($prompt, %arg) = @_;
415 my $valid_re = $arg{valid_re};
416 my $default = $arg{default};
417 my $resp;
418 my $i = 0;
420 if ( !( defined($term->IN)
421 && defined( fileno($term->IN) )
422 && defined( $term->OUT )
423 && defined( fileno($term->OUT) ) ) ){
424 return defined($default) ? $default : undef;
427 while ($i++ < 10) {
428 $resp = $term->readline($prompt);
429 if (!defined $resp) { # EOF
430 print "\n";
431 return defined $default ? $default : undef;
433 if ($resp eq '' and defined $default) {
434 return $default;
436 if (!defined $valid_re or $resp =~ /$valid_re/) {
437 return $resp;
440 return undef;
443 sub do_git_init_db {
444 unless (-d $ENV{GIT_DIR}) {
445 my @init_db = ('init');
446 push @init_db, "--template=$_template" if defined $_template;
447 if (defined $_shared) {
448 if ($_shared =~ /[a-z]/) {
449 push @init_db, "--shared=$_shared";
450 } else {
451 push @init_db, "--shared";
454 command_noisy(@init_db);
455 $_repository = Git->repository(Repository => ".git");
457 my $set;
458 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
459 foreach my $i (keys %icv) {
460 die "'$set' and '$i' cannot both be set\n" if $set;
461 next unless defined $icv{$i};
462 command_noisy('config', "$pfx.$i", $icv{$i});
463 $set = $i;
465 my $ignore_paths_regex = \$SVN::Git::Fetcher::_ignore_regex;
466 command_noisy('config', "$pfx.ignore-paths", $$ignore_paths_regex)
467 if defined $$ignore_paths_regex;
468 my $ignore_refs_regex = \$Git::SVN::Ra::_ignore_refs_regex;
469 command_noisy('config', "$pfx.ignore-refs", $$ignore_refs_regex)
470 if defined $$ignore_refs_regex;
472 if (defined $SVN::Git::Fetcher::_preserve_empty_dirs) {
473 my $fname = \$SVN::Git::Fetcher::_placeholder_filename;
474 command_noisy('config', "$pfx.preserve-empty-dirs", 'true');
475 command_noisy('config', "$pfx.placeholder-filename", $$fname);
479 sub init_subdir {
480 my $repo_path = shift or return;
481 mkpath([$repo_path]) unless -d $repo_path;
482 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
483 $ENV{GIT_DIR} = '.git';
484 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
487 sub cmd_clone {
488 my ($url, $path) = @_;
489 if (!defined $path &&
490 (defined $_trunk || @_branches || @_tags ||
491 defined $_stdlayout) &&
492 $url !~ m#^[a-z\+]+://#) {
493 $path = $url;
495 $path = basename($url) if !defined $path || !length $path;
496 my $authors_absolute = $_authors ? File::Spec->rel2abs($_authors) : "";
497 cmd_init($url, $path);
498 command_oneline('config', 'svn.authorsfile', $authors_absolute)
499 if $_authors;
500 Git::SVN::fetch_all($Git::SVN::default_repo_id);
503 sub cmd_init {
504 if (defined $_stdlayout) {
505 $_trunk = 'trunk' if (!defined $_trunk);
506 @_tags = 'tags' if (! @_tags);
507 @_branches = 'branches' if (! @_branches);
509 if (defined $_trunk || @_branches || @_tags) {
510 return cmd_multi_init(@_);
512 my $url = shift or die "SVN repository location required ",
513 "as a command-line argument\n";
514 $url = canonicalize_url($url);
515 init_subdir(@_);
516 do_git_init_db();
518 if ($Git::SVN::_minimize_url eq 'unset') {
519 $Git::SVN::_minimize_url = 0;
522 Git::SVN->init($url);
525 sub cmd_fetch {
526 if (grep /^\d+=./, @_) {
527 die "'<rev>=<commit>' fetch arguments are ",
528 "no longer supported.\n";
530 my ($remote) = @_;
531 if (@_ > 1) {
532 die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
534 $Git::SVN::no_reuse_existing = undef;
535 if ($_fetch_parent) {
536 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
537 unless ($gs) {
538 die "Unable to determine upstream SVN information from ",
539 "working tree history\n";
541 # just fetch, don't checkout.
542 $_no_checkout = 'true';
543 $_fetch_all ? $gs->fetch_all : $gs->fetch;
544 } elsif ($_fetch_all) {
545 cmd_multi_fetch();
546 } else {
547 $remote ||= $Git::SVN::default_repo_id;
548 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
552 sub cmd_set_tree {
553 my (@commits) = @_;
554 if ($_stdin || !@commits) {
555 print "Reading from stdin...\n";
556 @commits = ();
557 while (<STDIN>) {
558 if (/\b($sha1_short)\b/o) {
559 unshift @commits, $1;
563 my @revs;
564 foreach my $c (@commits) {
565 my @tmp = command('rev-parse',$c);
566 if (scalar @tmp == 1) {
567 push @revs, $tmp[0];
568 } elsif (scalar @tmp > 1) {
569 push @revs, reverse(command('rev-list',@tmp));
570 } else {
571 fatal "Failed to rev-parse $c";
574 my $gs = Git::SVN->new;
575 my ($r_last, $cmt_last) = $gs->last_rev_commit;
576 $gs->fetch;
577 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
578 fatal "There are new revisions that were fetched ",
579 "and need to be merged (or acknowledged) ",
580 "before committing.\nlast rev: $r_last\n",
581 " current: $gs->{last_rev}";
583 $gs->set_tree($_) foreach @revs;
584 print "Done committing ",scalar @revs," revisions to SVN\n";
585 unlink $gs->{index};
588 sub split_merge_info_range {
589 my ($range) = @_;
590 if ($range =~ /(\d+)-(\d+)/) {
591 return (int($1), int($2));
592 } else {
593 return (int($range), int($range));
597 sub combine_ranges {
598 my ($in) = @_;
600 my @fnums = ();
601 my @arr = split(/,/, $in);
602 for my $element (@arr) {
603 my ($start, $end) = split_merge_info_range($element);
604 push @fnums, $start;
607 my @sorted = @arr [ sort {
608 $fnums[$a] <=> $fnums[$b]
609 } 0..$#arr ];
611 my @return = ();
612 my $last = -1;
613 my $first = -1;
614 for my $element (@sorted) {
615 my ($start, $end) = split_merge_info_range($element);
617 if ($last == -1) {
618 $first = $start;
619 $last = $end;
620 next;
622 if ($start <= $last+1) {
623 if ($end > $last) {
624 $last = $end;
626 next;
628 if ($first == $last) {
629 push @return, "$first";
630 } else {
631 push @return, "$first-$last";
633 $first = $start;
634 $last = $end;
637 if ($first != -1) {
638 if ($first == $last) {
639 push @return, "$first";
640 } else {
641 push @return, "$first-$last";
645 return join(',', @return);
648 sub merge_revs_into_hash {
649 my ($hash, $minfo) = @_;
650 my @lines = split(' ', $minfo);
652 for my $line (@lines) {
653 my ($branchpath, $revs) = split(/:/, $line);
655 if (exists($hash->{$branchpath})) {
656 # Merge the two revision sets
657 my $combined = "$hash->{$branchpath},$revs";
658 $hash->{$branchpath} = combine_ranges($combined);
659 } else {
660 # Just do range combining for consolidation
661 $hash->{$branchpath} = combine_ranges($revs);
666 sub merge_merge_info {
667 my ($mergeinfo_one, $mergeinfo_two) = @_;
668 my %result_hash = ();
670 merge_revs_into_hash(\%result_hash, $mergeinfo_one);
671 merge_revs_into_hash(\%result_hash, $mergeinfo_two);
673 my $result = '';
674 # Sort below is for consistency's sake
675 for my $branchname (sort keys(%result_hash)) {
676 my $revlist = $result_hash{$branchname};
677 $result .= "$branchname:$revlist\n"
679 return $result;
682 sub populate_merge_info {
683 my ($d, $gs, $uuid, $linear_refs, $rewritten_parent) = @_;
685 my %parentshash;
686 read_commit_parents(\%parentshash, $d);
687 my @parents = @{$parentshash{$d}};
688 if ($#parents > 0) {
689 # Merge commit
690 my $all_parents_ok = 1;
691 my $aggregate_mergeinfo = '';
692 my $rooturl = $gs->repos_root;
694 if (defined($rewritten_parent)) {
695 # Replace first parent with newly-rewritten version
696 shift @parents;
697 unshift @parents, $rewritten_parent;
700 foreach my $parent (@parents) {
701 my ($branchurl, $svnrev, $paruuid) =
702 cmt_metadata($parent);
704 unless (defined($svnrev)) {
705 # Should have been caught be preflight check
706 fatal "merge commit $d has ancestor $parent, but that change "
707 ."does not have git-svn metadata!";
709 unless ($branchurl =~ /^\Q$rooturl\E(.*)/) {
710 fatal "commit $parent git-svn metadata changed mid-run!";
712 my $branchpath = $1;
714 my $ra = Git::SVN::Ra->new($branchurl);
715 my (undef, undef, $props) =
716 $ra->get_dir(canonicalize_path("."), $svnrev);
717 my $par_mergeinfo = $props->{'svn:mergeinfo'};
718 unless (defined $par_mergeinfo) {
719 $par_mergeinfo = '';
721 # Merge previous mergeinfo values
722 $aggregate_mergeinfo =
723 merge_merge_info($aggregate_mergeinfo,
724 $par_mergeinfo, 0);
726 next if $parent eq $parents[0]; # Skip first parent
727 # Add new changes being placed in tree by merge
728 my @cmd = (qw/rev-list --reverse/,
729 $parent, qw/--not/);
730 foreach my $par (@parents) {
731 unless ($par eq $parent) {
732 push @cmd, $par;
735 my @revsin = ();
736 my ($revlist, $ctx) = command_output_pipe(@cmd);
737 while (<$revlist>) {
738 my $irev = $_;
739 chomp $irev;
740 my (undef, $csvnrev, undef) =
741 cmt_metadata($irev);
742 unless (defined $csvnrev) {
743 # A child is missing SVN annotations...
744 # this might be OK, or might not be.
745 warn "W:child $irev is merged into revision "
746 ."$d but does not have git-svn metadata. "
747 ."This means git-svn cannot determine the "
748 ."svn revision numbers to place into the "
749 ."svn:mergeinfo property. You must ensure "
750 ."a branch is entirely committed to "
751 ."SVN before merging it in order for "
752 ."svn:mergeinfo population to function "
753 ."properly";
755 push @revsin, $csvnrev;
757 command_close_pipe($revlist, $ctx);
759 last unless $all_parents_ok;
761 # We now have a list of all SVN revnos which are
762 # merged by this particular parent. Integrate them.
763 next if $#revsin == -1;
764 my $newmergeinfo = "$branchpath:" . join(',', @revsin);
765 $aggregate_mergeinfo =
766 merge_merge_info($aggregate_mergeinfo,
767 $newmergeinfo, 1);
769 if ($all_parents_ok and $aggregate_mergeinfo) {
770 return $aggregate_mergeinfo;
774 return undef;
777 sub cmd_dcommit {
778 my $head = shift;
779 command_noisy(qw/update-index --refresh/);
780 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
781 'Cannot dcommit with a dirty index. Commit your changes first, '
782 . "or stash them with `git stash'.\n";
783 $head ||= 'HEAD';
785 my $old_head;
786 if ($head ne 'HEAD') {
787 $old_head = eval {
788 command_oneline([qw/symbolic-ref -q HEAD/])
790 if ($old_head) {
791 $old_head =~ s{^refs/heads/}{};
792 } else {
793 $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
795 command(['checkout', $head], STDERR => 0);
798 my @refs;
799 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
800 unless ($gs) {
801 die "Unable to determine upstream SVN information from ",
802 "$head history.\nPerhaps the repository is empty.";
805 if (defined $_commit_url) {
806 $url = $_commit_url;
807 } else {
808 $url = eval { command_oneline('config', '--get',
809 "svn-remote.$gs->{repo_id}.commiturl") };
810 if (!$url) {
811 $url = $gs->full_pushurl
815 my $last_rev = $_revision if defined $_revision;
816 if ($url) {
817 print "Committing to $url ...\n";
819 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
820 if ($_no_rebase && scalar(@$linear_refs) > 1) {
821 warn "Attempting to commit more than one change while ",
822 "--no-rebase is enabled.\n",
823 "If these changes depend on each other, re-running ",
824 "without --no-rebase may be required."
827 if (defined $_interactive){
828 my $ask_default = "y";
829 foreach my $d (@$linear_refs){
830 my ($fh, $ctx) = command_output_pipe(qw(show --summary), "$d");
831 while (<$fh>){
832 print $_;
834 command_close_pipe($fh, $ctx);
835 $_ = ask("Commit this patch to SVN? ([y]es (default)|[n]o|[q]uit|[a]ll): ",
836 valid_re => qr/^(?:yes|y|no|n|quit|q|all|a)/i,
837 default => $ask_default);
838 die "Commit this patch reply required" unless defined $_;
839 if (/^[nq]/i) {
840 exit(0);
841 } elsif (/^a/i) {
842 last;
847 my $expect_url = $url;
849 my $push_merge_info = eval {
850 command_oneline(qw/config --get svn.pushmergeinfo/)
852 if (not defined($push_merge_info)
853 or $push_merge_info eq "false"
854 or $push_merge_info eq "no"
855 or $push_merge_info eq "never") {
856 $push_merge_info = 0;
859 unless (defined($_merge_info) || ! $push_merge_info) {
860 # Preflight check of changes to ensure no issues with mergeinfo
861 # This includes check for uncommitted-to-SVN parents
862 # (other than the first parent, which we will handle),
863 # information from different SVN repos, and paths
864 # which are not underneath this repository root.
865 my $rooturl = $gs->repos_root;
866 foreach my $d (@$linear_refs) {
867 my %parentshash;
868 read_commit_parents(\%parentshash, $d);
869 my @realparents = @{$parentshash{$d}};
870 if ($#realparents > 0) {
871 # Merge commit
872 shift @realparents; # Remove/ignore first parent
873 foreach my $parent (@realparents) {
874 my ($branchurl, $svnrev, $paruuid) = cmt_metadata($parent);
875 unless (defined $paruuid) {
876 # A parent is missing SVN annotations...
877 # abort the whole operation.
878 fatal "$parent is merged into revision $d, "
879 ."but does not have git-svn metadata. "
880 ."Either dcommit the branch or use a "
881 ."local cherry-pick, FF merge, or rebase "
882 ."instead of an explicit merge commit.";
885 unless ($paruuid eq $uuid) {
886 # Parent has SVN metadata from different repository
887 fatal "merge parent $parent for change $d has "
888 ."git-svn uuid $paruuid, while current change "
889 ."has uuid $uuid!";
892 unless ($branchurl =~ /^\Q$rooturl\E(.*)/) {
893 # This branch is very strange indeed.
894 fatal "merge parent $parent for $d is on branch "
895 ."$branchurl, which is not under the "
896 ."git-svn root $rooturl!";
903 my $rewritten_parent;
904 Git::SVN::remove_username($expect_url);
905 if (defined($_merge_info)) {
906 $_merge_info =~ tr{ }{\n};
908 while (1) {
909 my $d = shift @$linear_refs or last;
910 unless (defined $last_rev) {
911 (undef, $last_rev, undef) = cmt_metadata("$d~1");
912 unless (defined $last_rev) {
913 fatal "Unable to extract revision information ",
914 "from commit $d~1";
917 if ($_dry_run) {
918 print "diff-tree $d~1 $d\n";
919 } else {
920 my $cmt_rev;
922 unless (defined($_merge_info) || ! $push_merge_info) {
923 $_merge_info = populate_merge_info($d, $gs,
924 $uuid,
925 $linear_refs,
926 $rewritten_parent);
929 my %ed_opts = ( r => $last_rev,
930 log => get_commit_entry($d)->{log},
931 ra => Git::SVN::Ra->new($url),
932 config => SVN::Core::config_get_config(
933 $Git::SVN::Ra::config_dir
935 tree_a => "$d~1",
936 tree_b => $d,
937 editor_cb => sub {
938 print "Committed r$_[0]\n";
939 $cmt_rev = $_[0];
941 mergeinfo => $_merge_info,
942 svn_path => '');
943 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
944 print "No changes\n$d~1 == $d\n";
945 } elsif ($parents->{$d} && @{$parents->{$d}}) {
946 $gs->{inject_parents_dcommit}->{$cmt_rev} =
947 $parents->{$d};
949 $_fetch_all ? $gs->fetch_all : $gs->fetch;
950 $last_rev = $cmt_rev;
951 next if $_no_rebase;
953 # we always want to rebase against the current HEAD,
954 # not any head that was passed to us
955 my @diff = command('diff-tree', $d,
956 $gs->refname, '--');
957 my @finish;
958 if (@diff) {
959 @finish = rebase_cmd();
960 print STDERR "W: $d and ", $gs->refname,
961 " differ, using @finish:\n",
962 join("\n", @diff), "\n";
963 } else {
964 print "No changes between current HEAD and ",
965 $gs->refname,
966 "\nResetting to the latest ",
967 $gs->refname, "\n";
968 @finish = qw/reset --mixed/;
970 command_noisy(@finish, $gs->refname);
972 $rewritten_parent = command_oneline(qw/rev-parse HEAD/);
974 if (@diff) {
975 @refs = ();
976 my ($url_, $rev_, $uuid_, $gs_) =
977 working_head_info('HEAD', \@refs);
978 my ($linear_refs_, $parents_) =
979 linearize_history($gs_, \@refs);
980 if (scalar(@$linear_refs) !=
981 scalar(@$linear_refs_)) {
982 fatal "# of revisions changed ",
983 "\nbefore:\n",
984 join("\n", @$linear_refs),
985 "\n\nafter:\n",
986 join("\n", @$linear_refs_), "\n",
987 'If you are attempting to commit ',
988 "merges, try running:\n\t",
989 'git rebase --interactive',
990 '--preserve-merges ',
991 $gs->refname,
992 "\nBefore dcommitting";
994 if ($url_ ne $expect_url) {
995 if ($url_ eq $gs->metadata_url) {
996 print
997 "Accepting rewritten URL:",
998 " $url_\n";
999 } else {
1000 fatal
1001 "URL mismatch after rebase:",
1002 " $url_ != $expect_url";
1005 if ($uuid_ ne $uuid) {
1006 fatal "uuid mismatch after rebase: ",
1007 "$uuid_ != $uuid";
1009 # remap parents
1010 my (%p, @l, $i);
1011 for ($i = 0; $i < scalar @$linear_refs; $i++) {
1012 my $new = $linear_refs_->[$i] or next;
1013 $p{$new} =
1014 $parents->{$linear_refs->[$i]};
1015 push @l, $new;
1017 $parents = \%p;
1018 $linear_refs = \@l;
1023 if ($old_head) {
1024 my $new_head = command_oneline(qw/rev-parse HEAD/);
1025 my $new_is_symbolic = eval {
1026 command_oneline(qw/symbolic-ref -q HEAD/);
1028 if ($new_is_symbolic) {
1029 print "dcommitted the branch ", $head, "\n";
1030 } else {
1031 print "dcommitted on a detached HEAD because you gave ",
1032 "a revision argument.\n",
1033 "The rewritten commit is: ", $new_head, "\n";
1035 command(['checkout', $old_head], STDERR => 0);
1038 unlink $gs->{index};
1041 sub cmd_branch {
1042 my ($branch_name, $head) = @_;
1044 unless (defined $branch_name && length $branch_name) {
1045 die(($_tag ? "tag" : "branch") . " name required\n");
1047 $head ||= 'HEAD';
1049 my (undef, $rev, undef, $gs) = working_head_info($head);
1050 my $src = $gs->full_pushurl;
1052 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
1053 my $allglobs = $remote->{ $_tag ? 'tags' : 'branches' };
1054 my $glob;
1055 if ($#{$allglobs} == 0) {
1056 $glob = $allglobs->[0];
1057 } else {
1058 unless(defined $_branch_dest) {
1059 die "Multiple ",
1060 $_tag ? "tag" : "branch",
1061 " paths defined for Subversion repository.\n",
1062 "You must specify where you want to create the ",
1063 $_tag ? "tag" : "branch",
1064 " with the --destination argument.\n";
1066 foreach my $g (@{$allglobs}) {
1067 # SVN::Git::Editor could probably be moved to Git.pm..
1068 my $re = SVN::Git::Editor::glob2pat($g->{path}->{left});
1069 if ($_branch_dest =~ /$re/) {
1070 $glob = $g;
1071 last;
1074 unless (defined $glob) {
1075 my $dest_re = qr/\b\Q$_branch_dest\E\b/;
1076 foreach my $g (@{$allglobs}) {
1077 $g->{path}->{left} =~ /$dest_re/ or next;
1078 if (defined $glob) {
1079 die "Ambiguous destination: ",
1080 $_branch_dest, "\nmatches both '",
1081 $glob->{path}->{left}, "' and '",
1082 $g->{path}->{left}, "'\n";
1084 $glob = $g;
1086 unless (defined $glob) {
1087 die "Unknown ",
1088 $_tag ? "tag" : "branch",
1089 " destination $_branch_dest\n";
1093 my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
1094 my $url;
1095 if (defined $_commit_url) {
1096 $url = $_commit_url;
1097 } else {
1098 $url = eval { command_oneline('config', '--get',
1099 "svn-remote.$gs->{repo_id}.commiturl") };
1100 if (!$url) {
1101 $url = $remote->{pushurl} || $remote->{url};
1104 my $dst = join '/', $url, $lft, $branch_name, ($rgt || ());
1106 if ($dst =~ /^https:/ && $src =~ /^http:/) {
1107 $src=~s/^http:/https:/;
1110 ::_req_svn();
1112 my $ctx = SVN::Client->new(
1113 auth => Git::SVN::Ra::_auth_providers(),
1114 log_msg => sub {
1115 ${ $_[0] } = defined $_message
1116 ? $_message
1117 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
1118 . $branch_name;
1122 eval {
1123 $ctx->ls($dst, 'HEAD', 0);
1124 } and die "branch ${branch_name} already exists\n";
1126 print "Copying ${src} at r${rev} to ${dst}...\n";
1127 $ctx->copy($src, $rev, $dst)
1128 unless $_dry_run;
1130 $gs->fetch_all;
1133 sub cmd_find_rev {
1134 my $revision_or_hash = shift or die "SVN or git revision required ",
1135 "as a command-line argument\n";
1136 my $result;
1137 if ($revision_or_hash =~ /^r\d+$/) {
1138 my $head = shift;
1139 $head ||= 'HEAD';
1140 my @refs;
1141 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
1142 unless ($gs) {
1143 die "Unable to determine upstream SVN information from ",
1144 "$head history\n";
1146 my $desired_revision = substr($revision_or_hash, 1);
1147 $result = $gs->rev_map_get($desired_revision, $uuid);
1148 } else {
1149 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
1150 $result = $rev;
1152 print "$result\n" if $result;
1155 sub auto_create_empty_directories {
1156 my ($gs) = @_;
1157 my $var = eval { command_oneline('config', '--get', '--bool',
1158 "svn-remote.$gs->{repo_id}.automkdirs") };
1159 # By default, create empty directories by consulting the unhandled log,
1160 # but allow setting it to 'false' to skip it.
1161 return !($var && $var eq 'false');
1164 sub cmd_rebase {
1165 command_noisy(qw/update-index --refresh/);
1166 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1167 unless ($gs) {
1168 die "Unable to determine upstream SVN information from ",
1169 "working tree history\n";
1171 if ($_dry_run) {
1172 print "Remote Branch: " . $gs->refname . "\n";
1173 print "SVN URL: " . $url . "\n";
1174 return;
1176 if (command(qw/diff-index HEAD --/)) {
1177 print STDERR "Cannot rebase with uncommited changes:\n";
1178 command_noisy('status');
1179 exit 1;
1181 unless ($_local) {
1182 # rebase will checkout for us, so no need to do it explicitly
1183 $_no_checkout = 'true';
1184 $_fetch_all ? $gs->fetch_all : $gs->fetch;
1186 command_noisy(rebase_cmd(), $gs->refname);
1187 if (auto_create_empty_directories($gs)) {
1188 $gs->mkemptydirs;
1192 sub cmd_show_ignore {
1193 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1194 $gs ||= Git::SVN->new;
1195 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1196 $gs->prop_walk($gs->{path}, $r, sub {
1197 my ($gs, $path, $props) = @_;
1198 print STDOUT "\n# $path\n";
1199 my $s = $props->{'svn:ignore'} or return;
1200 $s =~ s/[\r\n]+/\n/g;
1201 $s =~ s/^\n+//;
1202 chomp $s;
1203 $s =~ s#^#$path#gm;
1204 print STDOUT "$s\n";
1208 sub cmd_show_externals {
1209 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1210 $gs ||= Git::SVN->new;
1211 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1212 $gs->prop_walk($gs->{path}, $r, sub {
1213 my ($gs, $path, $props) = @_;
1214 print STDOUT "\n# $path\n";
1215 my $s = $props->{'svn:externals'} or return;
1216 $s =~ s/[\r\n]+/\n/g;
1217 chomp $s;
1218 $s =~ s#^#$path#gm;
1219 print STDOUT "$s\n";
1223 sub cmd_create_ignore {
1224 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1225 $gs ||= Git::SVN->new;
1226 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1227 $gs->prop_walk($gs->{path}, $r, sub {
1228 my ($gs, $path, $props) = @_;
1229 # $path is of the form /path/to/dir/
1230 $path = '.' . $path;
1231 # SVN can have attributes on empty directories,
1232 # which git won't track
1233 mkpath([$path]) unless -d $path;
1234 my $ignore = $path . '.gitignore';
1235 my $s = $props->{'svn:ignore'} or return;
1236 open(GITIGNORE, '>', $ignore)
1237 or fatal("Failed to open `$ignore' for writing: $!");
1238 $s =~ s/[\r\n]+/\n/g;
1239 $s =~ s/^\n+//;
1240 chomp $s;
1241 # Prefix all patterns so that the ignore doesn't apply
1242 # to sub-directories.
1243 $s =~ s#^#/#gm;
1244 print GITIGNORE "$s\n";
1245 close(GITIGNORE)
1246 or fatal("Failed to close `$ignore': $!");
1247 command_noisy('add', '-f', $ignore);
1251 sub cmd_mkdirs {
1252 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1253 $gs ||= Git::SVN->new;
1254 $gs->mkemptydirs($_revision);
1257 sub canonicalize_path {
1258 my ($path) = @_;
1259 my $dot_slash_added = 0;
1260 if (substr($path, 0, 1) ne "/") {
1261 $path = "./" . $path;
1262 $dot_slash_added = 1;
1264 # File::Spec->canonpath doesn't collapse x/../y into y (for a
1265 # good reason), so let's do this manually.
1266 $path =~ s#/+#/#g;
1267 $path =~ s#/\.(?:/|$)#/#g;
1268 $path =~ s#/[^/]+/\.\.##g;
1269 $path =~ s#/$##g;
1270 $path =~ s#^\./## if $dot_slash_added;
1271 $path =~ s#^/##;
1272 $path =~ s#^\.$##;
1273 return $path;
1276 sub canonicalize_url {
1277 my ($url) = @_;
1278 $url =~ s#^([^:]+://[^/]*/)(.*)$#$1 . canonicalize_path($2)#e;
1279 return $url;
1282 # get_svnprops(PATH)
1283 # ------------------
1284 # Helper for cmd_propget and cmd_proplist below.
1285 sub get_svnprops {
1286 my $path = shift;
1287 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1288 $gs ||= Git::SVN->new;
1290 # prefix THE PATH by the sub-directory from which the user
1291 # invoked us.
1292 $path = $cmd_dir_prefix . $path;
1293 fatal("No such file or directory: $path") unless -e $path;
1294 my $is_dir = -d $path ? 1 : 0;
1295 $path = $gs->{path} . '/' . $path;
1297 # canonicalize the path (otherwise libsvn will abort or fail to
1298 # find the file)
1299 $path = canonicalize_path($path);
1301 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1302 my $props;
1303 if ($is_dir) {
1304 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
1306 else {
1307 (undef, $props) = $gs->ra->get_file($path, $r, undef);
1309 return $props;
1312 # cmd_propget (PROP, PATH)
1313 # ------------------------
1314 # Print the SVN property PROP for PATH.
1315 sub cmd_propget {
1316 my ($prop, $path) = @_;
1317 $path = '.' if not defined $path;
1318 usage(1) if not defined $prop;
1319 my $props = get_svnprops($path);
1320 if (not defined $props->{$prop}) {
1321 fatal("`$path' does not have a `$prop' SVN property.");
1323 print $props->{$prop} . "\n";
1326 # cmd_proplist (PATH)
1327 # -------------------
1328 # Print the list of SVN properties for PATH.
1329 sub cmd_proplist {
1330 my $path = shift;
1331 $path = '.' if not defined $path;
1332 my $props = get_svnprops($path);
1333 print "Properties on '$path':\n";
1334 foreach (sort keys %{$props}) {
1335 print " $_\n";
1339 sub cmd_multi_init {
1340 my $url = shift;
1341 unless (defined $_trunk || @_branches || @_tags) {
1342 usage(1);
1345 $_prefix = '' unless defined $_prefix;
1346 if (defined $url) {
1347 $url = canonicalize_url($url);
1348 init_subdir(@_);
1350 do_git_init_db();
1351 if (defined $_trunk) {
1352 $_trunk =~ s#^/+##;
1353 my $trunk_ref = 'refs/remotes/' . $_prefix . 'trunk';
1354 # try both old-style and new-style lookups:
1355 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
1356 unless ($gs_trunk) {
1357 my ($trunk_url, $trunk_path) =
1358 complete_svn_url($url, $_trunk);
1359 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
1360 undef, $trunk_ref);
1363 return unless @_branches || @_tags;
1364 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
1365 foreach my $path (@_branches) {
1366 complete_url_ls_init($ra, $path, '--branches/-b', $_prefix);
1368 foreach my $path (@_tags) {
1369 complete_url_ls_init($ra, $path, '--tags/-t', $_prefix.'tags/');
1373 sub cmd_multi_fetch {
1374 $Git::SVN::no_reuse_existing = undef;
1375 my $remotes = Git::SVN::read_all_remotes();
1376 foreach my $repo_id (sort keys %$remotes) {
1377 if ($remotes->{$repo_id}->{url}) {
1378 Git::SVN::fetch_all($repo_id, $remotes);
1383 # this command is special because it requires no metadata
1384 sub cmd_commit_diff {
1385 my ($ta, $tb, $url) = @_;
1386 my $usage = "Usage: $0 commit-diff -r<revision> ".
1387 "<tree-ish> <tree-ish> [<URL>]";
1388 fatal($usage) if (!defined $ta || !defined $tb);
1389 my $svn_path = '';
1390 if (!defined $url) {
1391 my $gs = eval { Git::SVN->new };
1392 if (!$gs) {
1393 fatal("Needed URL or usable git-svn --id in ",
1394 "the command-line\n", $usage);
1396 $url = $gs->{url};
1397 $svn_path = $gs->{path};
1399 unless (defined $_revision) {
1400 fatal("-r|--revision is a required argument\n", $usage);
1402 if (defined $_message && defined $_file) {
1403 fatal("Both --message/-m and --file/-F specified ",
1404 "for the commit message.\n",
1405 "I have no idea what you mean");
1407 if (defined $_file) {
1408 $_message = file_to_s($_file);
1409 } else {
1410 $_message ||= get_commit_entry($tb)->{log};
1412 my $ra ||= Git::SVN::Ra->new($url);
1413 my $r = $_revision;
1414 if ($r eq 'HEAD') {
1415 $r = $ra->get_latest_revnum;
1416 } elsif ($r !~ /^\d+$/) {
1417 die "revision argument: $r not understood by git-svn\n";
1419 my %ed_opts = ( r => $r,
1420 log => $_message,
1421 ra => $ra,
1422 tree_a => $ta,
1423 tree_b => $tb,
1424 editor_cb => sub { print "Committed r$_[0]\n" },
1425 svn_path => $svn_path );
1426 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
1427 print "No changes\n$ta == $tb\n";
1431 sub escape_uri_only {
1432 my ($uri) = @_;
1433 my @tmp;
1434 foreach (split m{/}, $uri) {
1435 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
1436 push @tmp, $_;
1438 join('/', @tmp);
1441 sub escape_url {
1442 my ($url) = @_;
1443 if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
1444 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
1445 $url = "$scheme://$domain$uri";
1447 $url;
1450 sub cmd_info {
1451 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
1452 my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
1453 if (exists $_[1]) {
1454 die "Too many arguments specified\n";
1457 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
1459 if (!$file_type && !$diff_status) {
1460 print STDERR "svn: '$path' is not under version control\n";
1461 exit 1;
1464 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1465 unless ($gs) {
1466 die "Unable to determine upstream SVN information from ",
1467 "working tree history\n";
1470 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
1471 $path = "." if $path eq "";
1473 my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
1475 if ($_url) {
1476 print escape_url($full_url), "\n";
1477 return;
1480 my $result = "Path: $path\n";
1481 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
1482 $result .= "URL: " . escape_url($full_url) . "\n";
1484 eval {
1485 my $repos_root = $gs->repos_root;
1486 Git::SVN::remove_username($repos_root);
1487 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
1489 if ($@) {
1490 $result .= "Repository Root: (offline)\n";
1492 ::_req_svn();
1493 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
1494 (::compare_svn_version('1.5.4') <= 0 || $file_type ne "dir");
1495 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
1497 $result .= "Node Kind: " .
1498 ($file_type eq "dir" ? "directory" : "file") . "\n";
1500 my $schedule = $diff_status eq "A"
1501 ? "add"
1502 : ($diff_status eq "D" ? "delete" : "normal");
1503 $result .= "Schedule: $schedule\n";
1505 if ($diff_status eq "A") {
1506 print $result, "\n";
1507 return;
1510 my ($lc_author, $lc_rev, $lc_date_utc);
1511 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
1512 my $log = command_output_pipe(@args);
1513 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
1514 while (<$log>) {
1515 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
1516 $lc_author = $1;
1517 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
1518 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
1519 (undef, $lc_rev, undef) = ::extract_metadata($1);
1522 close $log;
1524 Git::SVN::Log::set_local_timezone();
1526 $result .= "Last Changed Author: $lc_author\n";
1527 $result .= "Last Changed Rev: $lc_rev\n";
1528 $result .= "Last Changed Date: " .
1529 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
1531 if ($file_type ne "dir") {
1532 my $text_last_updated_date =
1533 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
1534 $result .=
1535 "Text Last Updated: " .
1536 Git::SVN::Log::format_svn_date($text_last_updated_date) .
1537 "\n";
1538 my $checksum;
1539 if ($diff_status eq "D") {
1540 my ($fh, $ctx) =
1541 command_output_pipe(qw(cat-file blob), "HEAD:$path");
1542 if ($file_type eq "link") {
1543 my $file_name = <$fh>;
1544 $checksum = md5sum("link $file_name");
1545 } else {
1546 $checksum = md5sum($fh);
1548 command_close_pipe($fh, $ctx);
1549 } elsif ($file_type eq "link") {
1550 my $file_name =
1551 command(qw(cat-file blob), "HEAD:$path");
1552 $checksum =
1553 md5sum("link " . $file_name);
1554 } else {
1555 open FILE, "<", $path or die $!;
1556 $checksum = md5sum(\*FILE);
1557 close FILE or die $!;
1559 $result .= "Checksum: " . $checksum . "\n";
1562 print $result, "\n";
1565 sub cmd_reset {
1566 my $target = shift || $_revision or die "SVN revision required\n";
1567 $target = $1 if $target =~ /^r(\d+)$/;
1568 $target =~ /^\d+$/ or die "Numeric SVN revision expected\n";
1569 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1570 unless ($gs) {
1571 die "Unable to determine upstream SVN information from ".
1572 "history\n";
1574 my ($r, $c) = $gs->find_rev_before($target, not $_fetch_parent);
1575 die "Cannot find SVN revision $target\n" unless defined($c);
1576 $gs->rev_map_set($r, $c, 'reset', $uuid);
1577 print "r$r = $c ($gs->{ref_id})\n";
1580 sub cmd_gc {
1581 if (!$can_compress) {
1582 warn "Compress::Zlib could not be found; unhandled.log " .
1583 "files will not be compressed.\n";
1585 find({ wanted => \&gc_directory, no_chdir => 1}, "$ENV{GIT_DIR}/svn");
1588 ########################### utility functions #########################
1590 sub rebase_cmd {
1591 my @cmd = qw/rebase/;
1592 push @cmd, '-v' if $_verbose;
1593 push @cmd, qw/--merge/ if $_merge;
1594 push @cmd, "--strategy=$_strategy" if $_strategy;
1595 @cmd;
1598 sub post_fetch_checkout {
1599 return if $_no_checkout;
1600 my $gs = $Git::SVN::_head or return;
1601 return if verify_ref('refs/heads/master^0');
1603 # look for "trunk" ref if it exists
1604 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
1605 my $fetch = $remote->{fetch};
1606 if ($fetch) {
1607 foreach my $p (keys %$fetch) {
1608 basename($fetch->{$p}) eq 'trunk' or next;
1609 $gs = Git::SVN->new($fetch->{$p}, $gs->{repo_id}, $p);
1610 last;
1614 my $valid_head = verify_ref('HEAD^0');
1615 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1616 return if ($valid_head || !verify_ref('HEAD^0'));
1618 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1619 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1620 return if -f $index;
1622 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1623 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1624 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1625 print STDERR "Checked out HEAD:\n ",
1626 $gs->full_url, " r", $gs->last_rev, "\n";
1627 if (auto_create_empty_directories($gs)) {
1628 $gs->mkemptydirs($gs->last_rev);
1632 sub complete_svn_url {
1633 my ($url, $path) = @_;
1634 $path =~ s#/+$##;
1635 if ($path !~ m#^[a-z\+]+://#) {
1636 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1637 fatal("E: '$path' is not a complete URL ",
1638 "and a separate URL is not specified");
1640 return ($url, $path);
1642 return ($path, '');
1645 sub complete_url_ls_init {
1646 my ($ra, $repo_path, $switch, $pfx) = @_;
1647 unless ($repo_path) {
1648 print STDERR "W: $switch not specified\n";
1649 return;
1651 $repo_path =~ s#/+$##;
1652 if ($repo_path =~ m#^[a-z\+]+://#) {
1653 $ra = Git::SVN::Ra->new($repo_path);
1654 $repo_path = '';
1655 } else {
1656 $repo_path =~ s#^/+##;
1657 unless ($ra) {
1658 fatal("E: '$repo_path' is not a complete URL ",
1659 "and a separate URL is not specified");
1662 my $url = $ra->{url};
1663 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1664 my $k = "svn-remote.$gs->{repo_id}.url";
1665 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1666 if ($orig_url && ($orig_url ne $gs->{url})) {
1667 die "$k already set: $orig_url\n",
1668 "wanted to set to: $gs->{url}\n";
1670 command_oneline('config', $k, $gs->{url}) unless $orig_url;
1671 my $remote_path = "$gs->{path}/$repo_path";
1672 $remote_path =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
1673 $remote_path =~ s#/+#/#g;
1674 $remote_path =~ s#^/##g;
1675 $remote_path .= "/*" if $remote_path !~ /\*/;
1676 my ($n) = ($switch =~ /^--(\w+)/);
1677 if (length $pfx && $pfx !~ m#/$#) {
1678 die "--prefix='$pfx' must have a trailing slash '/'\n";
1680 command_noisy('config',
1681 '--add',
1682 "svn-remote.$gs->{repo_id}.$n",
1683 "$remote_path:refs/remotes/$pfx*" .
1684 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1687 sub verify_ref {
1688 my ($ref) = @_;
1689 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1690 { STDERR => 0 }); };
1693 sub get_tree_from_treeish {
1694 my ($treeish) = @_;
1695 # $treeish can be a symbolic ref, too:
1696 my $type = command_oneline(qw/cat-file -t/, $treeish);
1697 my $expected;
1698 while ($type eq 'tag') {
1699 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1701 if ($type eq 'commit') {
1702 $expected = (grep /^tree /, command(qw/cat-file commit/,
1703 $treeish))[0];
1704 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1705 die "Unable to get tree from $treeish\n" unless $expected;
1706 } elsif ($type eq 'tree') {
1707 $expected = $treeish;
1708 } else {
1709 die "$treeish is a $type, expected tree, tag or commit\n";
1711 return $expected;
1714 sub get_commit_entry {
1715 my ($treeish) = shift;
1716 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1717 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1718 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1719 open my $log_fh, '>', $commit_editmsg or croak $!;
1721 my $type = command_oneline(qw/cat-file -t/, $treeish);
1722 if ($type eq 'commit' || $type eq 'tag') {
1723 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1724 $type, $treeish);
1725 my $in_msg = 0;
1726 my $author;
1727 my $saw_from = 0;
1728 my $msgbuf = "";
1729 while (<$msg_fh>) {
1730 if (!$in_msg) {
1731 $in_msg = 1 if (/^\s*$/);
1732 $author = $1 if (/^author (.*>)/);
1733 } elsif (/^git-svn-id: /) {
1734 # skip this for now, we regenerate the
1735 # correct one on re-fetch anyways
1736 # TODO: set *:merge properties or like...
1737 } else {
1738 if (/^From:/ || /^Signed-off-by:/) {
1739 $saw_from = 1;
1741 $msgbuf .= $_;
1744 $msgbuf =~ s/\s+$//s;
1745 if ($Git::SVN::_add_author_from && defined($author)
1746 && !$saw_from) {
1747 $msgbuf .= "\n\nFrom: $author";
1749 print $log_fh $msgbuf or croak $!;
1750 command_close_pipe($msg_fh, $ctx);
1752 close $log_fh or croak $!;
1754 if ($_edit || ($type eq 'tree')) {
1755 chomp(my $editor = command_oneline(qw(var GIT_EDITOR)));
1756 system('sh', '-c', $editor.' "$@"', $editor, $commit_editmsg);
1758 rename $commit_editmsg, $commit_msg or croak $!;
1760 require Encode;
1761 # SVN requires messages to be UTF-8 when entering the repo
1762 local $/;
1763 open $log_fh, '<', $commit_msg or croak $!;
1764 binmode $log_fh;
1765 chomp($log_entry{log} = <$log_fh>);
1767 my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
1768 my $msg = $log_entry{log};
1770 eval { $msg = Encode::decode($enc, $msg, 1) };
1771 if ($@) {
1772 die "Could not decode as $enc:\n", $msg,
1773 "\nPerhaps you need to set i18n.commitencoding\n";
1776 eval { $msg = Encode::encode('UTF-8', $msg, 1) };
1777 die "Could not encode as UTF-8:\n$msg\n" if $@;
1779 $log_entry{log} = $msg;
1781 close $log_fh or croak $!;
1783 unlink $commit_msg;
1784 \%log_entry;
1787 sub s_to_file {
1788 my ($str, $file, $mode) = @_;
1789 open my $fd,'>',$file or croak $!;
1790 print $fd $str,"\n" or croak $!;
1791 close $fd or croak $!;
1792 chmod ($mode &~ umask, $file) if (defined $mode);
1795 sub file_to_s {
1796 my $file = shift;
1797 open my $fd,'<',$file or croak "$!: file: $file\n";
1798 local $/;
1799 my $ret = <$fd>;
1800 close $fd or croak $!;
1801 $ret =~ s/\s*$//s;
1802 return $ret;
1805 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1806 sub load_authors {
1807 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1808 my $log = $cmd eq 'log';
1809 while (<$authors>) {
1810 chomp;
1811 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1812 my ($user, $name, $email) = ($1, $2, $3);
1813 if ($log) {
1814 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1815 } else {
1816 $users{$user} = [$name, $email];
1819 close $authors or croak $!;
1822 # convert GetOpt::Long specs for use by git-config
1823 sub read_git_config {
1824 my $opts = shift;
1825 my @config_only;
1826 foreach my $o (keys %$opts) {
1827 # if we have mixedCase and a long option-only, then
1828 # it's a config-only variable that we don't need for
1829 # the command-line.
1830 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1831 my $v = $opts->{$o};
1832 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1833 $key =~ s/-//g;
1834 my $arg = 'git config';
1835 $arg .= ' --int' if ($o =~ /[:=]i$/);
1836 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1837 if (ref $v eq 'ARRAY') {
1838 chomp(my @tmp = `$arg --get-all svn.$key`);
1839 @$v = @tmp if @tmp;
1840 } else {
1841 chomp(my $tmp = `$arg --get svn.$key`);
1842 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1843 $$v = $tmp;
1847 delete @$opts{@config_only} if @config_only;
1850 sub extract_metadata {
1851 my $id = shift or return (undef, undef, undef);
1852 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1853 \s([a-f\d\-]+)$/ix);
1854 if (!defined $rev || !$uuid || !$url) {
1855 # some of the original repositories I made had
1856 # identifiers like this:
1857 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/i);
1859 return ($url, $rev, $uuid);
1862 sub cmt_metadata {
1863 return extract_metadata((grep(/^git-svn-id: /,
1864 command(qw/cat-file commit/, shift)))[-1]);
1867 sub cmt_sha2rev_batch {
1868 my %s2r;
1869 my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1870 my $list = shift;
1872 foreach my $sha (@{$list}) {
1873 my $first = 1;
1874 my $size = 0;
1875 print $out $sha, "\n";
1877 while (my $line = <$in>) {
1878 if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1879 last;
1880 } elsif ($first &&
1881 $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1882 $first = 0;
1883 $size = $1;
1884 next;
1885 } elsif ($line =~ /^(git-svn-id: )/) {
1886 my (undef, $rev, undef) =
1887 extract_metadata($line);
1888 $s2r{$sha} = $rev;
1891 $size -= length($line);
1892 last if ($size == 0);
1896 command_close_bidi_pipe($pid, $in, $out, $ctx);
1898 return \%s2r;
1901 sub working_head_info {
1902 my ($head, $refs) = @_;
1903 my @args = qw/rev-list --first-parent --pretty=medium/;
1904 my ($fh, $ctx) = command_output_pipe(@args, $head);
1905 my $hash;
1906 my %max;
1907 while (<$fh>) {
1908 if ( m{^commit ($::sha1)$} ) {
1909 unshift @$refs, $hash if $hash and $refs;
1910 $hash = $1;
1911 next;
1913 next unless s{^\s*(git-svn-id:)}{$1};
1914 my ($url, $rev, $uuid) = extract_metadata($_);
1915 if (defined $url && defined $rev) {
1916 next if $max{$url} and $max{$url} < $rev;
1917 if (my $gs = Git::SVN->find_by_url($url)) {
1918 my $c = $gs->rev_map_get($rev, $uuid);
1919 if ($c && $c eq $hash) {
1920 close $fh; # break the pipe
1921 return ($url, $rev, $uuid, $gs);
1922 } else {
1923 $max{$url} ||= $gs->rev_map_max;
1928 command_close_pipe($fh, $ctx);
1929 (undef, undef, undef, undef);
1932 sub read_commit_parents {
1933 my ($parents, $c) = @_;
1934 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1935 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1936 @{$parents->{$c}} = split(/ /, $p);
1939 sub linearize_history {
1940 my ($gs, $refs) = @_;
1941 my %parents;
1942 foreach my $c (@$refs) {
1943 read_commit_parents(\%parents, $c);
1946 my @linear_refs;
1947 my %skip = ();
1948 my $last_svn_commit = $gs->last_commit;
1949 foreach my $c (reverse @$refs) {
1950 next if $c eq $last_svn_commit;
1951 last if $skip{$c};
1953 unshift @linear_refs, $c;
1954 $skip{$c} = 1;
1956 # we only want the first parent to diff against for linear
1957 # history, we save the rest to inject when we finalize the
1958 # svn commit
1959 my $fp_a = verify_ref("$c~1");
1960 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1961 if (!$fp_a || !$fp_b) {
1962 die "Commit $c\n",
1963 "has no parent commit, and therefore ",
1964 "nothing to diff against.\n",
1965 "You should be working from a repository ",
1966 "originally created by git-svn\n";
1968 if ($fp_a ne $fp_b) {
1969 die "$c~1 = $fp_a, however parsing commit $c ",
1970 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1973 foreach my $p (@{$parents{$c}}) {
1974 $skip{$p} = 1;
1977 (\@linear_refs, \%parents);
1980 sub find_file_type_and_diff_status {
1981 my ($path) = @_;
1982 return ('dir', '') if $path eq '';
1984 my $diff_output =
1985 command_oneline(qw(diff --cached --name-status --), $path) || "";
1986 my $diff_status = (split(' ', $diff_output))[0] || "";
1988 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1990 return (undef, undef) if !$diff_status && !$ls_tree;
1992 if ($diff_status eq "A") {
1993 return ("link", $diff_status) if -l $path;
1994 return ("dir", $diff_status) if -d $path;
1995 return ("file", $diff_status);
1998 my $mode = (split(' ', $ls_tree))[0] || "";
2000 return ("link", $diff_status) if $mode eq "120000";
2001 return ("dir", $diff_status) if $mode eq "040000";
2002 return ("file", $diff_status);
2005 sub md5sum {
2006 my $arg = shift;
2007 my $ref = ref $arg;
2008 my $md5 = Digest::MD5->new();
2009 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
2010 $md5->addfile($arg) or croak $!;
2011 } elsif ($ref eq 'SCALAR') {
2012 $md5->add($$arg) or croak $!;
2013 } elsif (!$ref) {
2014 $md5->add($arg) or croak $!;
2015 } else {
2016 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
2018 return $md5->hexdigest();
2021 sub gc_directory {
2022 if ($can_compress && -f $_ && basename($_) eq "unhandled.log") {
2023 my $out_filename = $_ . ".gz";
2024 open my $in_fh, "<", $_ or die "Unable to open $_: $!\n";
2025 binmode $in_fh;
2026 my $gz = Compress::Zlib::gzopen($out_filename, "ab") or
2027 die "Unable to open $out_filename: $!\n";
2029 my $res;
2030 while ($res = sysread($in_fh, my $str, 1024)) {
2031 $gz->gzwrite($str) or
2032 die "Unable to write: ".$gz->gzerror()."!\n";
2034 unlink $_ or die "unlink $File::Find::name: $!\n";
2035 } elsif (-f $_ && basename($_) eq "index") {
2036 unlink $_ or die "unlink $_: $!\n";
2040 package Git::SVN;
2041 use strict;
2042 use warnings;
2043 use Fcntl qw/:DEFAULT :seek/;
2044 use constant rev_map_fmt => 'NH40';
2045 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
2046 $_repack $_repack_flags $_use_svm_props $_head
2047 $_use_svnsync_props $no_reuse_existing $_minimize_url
2048 $_use_log_author $_add_author_from $_localtime/;
2049 use Carp qw/croak/;
2050 use File::Path qw/mkpath/;
2051 use File::Copy qw/copy/;
2052 use IPC::Open3;
2053 use Time::Local;
2054 use Memoize; # core since 5.8.0, Jul 2002
2055 use Memoize::Storable;
2056 use POSIX qw(:signal_h);
2058 my ($_gc_nr, $_gc_period);
2060 # properties that we do not log:
2061 my %SKIP_PROP;
2062 BEGIN {
2063 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
2064 svn:special svn:executable
2065 svn:entry:committed-rev
2066 svn:entry:last-author
2067 svn:entry:uuid
2068 svn:entry:committed-date/;
2070 # some options are read globally, but can be overridden locally
2071 # per [svn-remote "..."] section. Command-line options will *NOT*
2072 # override options set in an [svn-remote "..."] section
2073 no strict 'refs';
2074 for my $option (qw/follow_parent no_metadata use_svm_props
2075 use_svnsync_props/) {
2076 my $key = $option;
2077 $key =~ tr/_//d;
2078 my $prop = "-$option";
2079 *$option = sub {
2080 my ($self) = @_;
2081 return $self->{$prop} if exists $self->{$prop};
2082 my $k = "svn-remote.$self->{repo_id}.$key";
2083 eval { command_oneline(qw/config --get/, $k) };
2084 if ($@) {
2085 $self->{$prop} = ${"Git::SVN::_$option"};
2086 } else {
2087 my $v = command_oneline(qw/config --bool/,$k);
2088 $self->{$prop} = $v eq 'false' ? 0 : 1;
2090 return $self->{$prop};
2096 my (%LOCKFILES, %INDEX_FILES);
2097 END {
2098 unlink keys %LOCKFILES if %LOCKFILES;
2099 unlink keys %INDEX_FILES if %INDEX_FILES;
2102 sub resolve_local_globs {
2103 my ($url, $fetch, $glob_spec) = @_;
2104 return unless defined $glob_spec;
2105 my $ref = $glob_spec->{ref};
2106 my $path = $glob_spec->{path};
2107 foreach (command(qw#for-each-ref --format=%(refname) refs/#)) {
2108 next unless m#^$ref->{regex}$#;
2109 my $p = $1;
2110 my $pathname = desanitize_refname($path->full_path($p));
2111 my $refname = desanitize_refname($ref->full_path($p));
2112 if (my $existing = $fetch->{$pathname}) {
2113 if ($existing ne $refname) {
2114 die "Refspec conflict:\n",
2115 "existing: $existing\n",
2116 " globbed: $refname\n";
2118 my $u = (::cmt_metadata("$refname"))[0];
2119 $u =~ s!^\Q$url\E(/|$)!! or die
2120 "$refname: '$url' not found in '$u'\n";
2121 if ($pathname ne $u) {
2122 warn "W: Refspec glob conflict ",
2123 "(ref: $refname):\n",
2124 "expected path: $pathname\n",
2125 " real path: $u\n",
2126 "Continuing ahead with $u\n";
2127 next;
2129 } else {
2130 $fetch->{$pathname} = $refname;
2135 sub parse_revision_argument {
2136 my ($base, $head) = @_;
2137 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
2138 return ($base, $head);
2140 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
2141 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
2142 return ($head, $head) if ($::_revision eq 'HEAD');
2143 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
2144 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
2145 die "revision argument: $::_revision not understood by git-svn\n";
2148 sub fetch_all {
2149 my ($repo_id, $remotes) = @_;
2150 if (ref $repo_id) {
2151 my $gs = $repo_id;
2152 $repo_id = undef;
2153 $repo_id = $gs->{repo_id};
2155 $remotes ||= read_all_remotes();
2156 my $remote = $remotes->{$repo_id} or
2157 die "[svn-remote \"$repo_id\"] unknown\n";
2158 my $fetch = $remote->{fetch};
2159 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
2160 my (@gs, @globs);
2161 my $ra = Git::SVN::Ra->new($url);
2162 my $uuid = $ra->get_uuid;
2163 my $head = $ra->get_latest_revnum;
2165 # ignore errors, $head revision may not even exist anymore
2166 eval { $ra->get_log("", $head, 0, 1, 0, 1, sub { $head = $_[1] }) };
2167 warn "W: $@\n" if $@;
2169 my $base = defined $fetch ? $head : 0;
2171 # read the max revs for wildcard expansion (branches/*, tags/*)
2172 foreach my $t (qw/branches tags/) {
2173 defined $remote->{$t} or next;
2174 push @globs, @{$remote->{$t}};
2176 my $max_rev = eval { tmp_config(qw/--int --get/,
2177 "svn-remote.$repo_id.${t}-maxRev") };
2178 if (defined $max_rev && ($max_rev < $base)) {
2179 $base = $max_rev;
2180 } elsif (!defined $max_rev) {
2181 $base = 0;
2185 if ($fetch) {
2186 foreach my $p (sort keys %$fetch) {
2187 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
2188 my $lr = $gs->rev_map_max;
2189 if (defined $lr) {
2190 $base = $lr if ($lr < $base);
2192 push @gs, $gs;
2196 ($base, $head) = parse_revision_argument($base, $head);
2197 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
2200 sub read_all_remotes {
2201 my $r = {};
2202 my $use_svm_props = eval { command_oneline(qw/config --bool
2203 svn.useSvmProps/) };
2204 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
2205 my $svn_refspec = qr{\s*(.*?)\s*:\s*(.+?)\s*};
2206 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
2207 if (m!^(.+)\.fetch=$svn_refspec$!) {
2208 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
2209 die("svn-remote.$remote: remote ref '$remote_ref' "
2210 . "must start with 'refs/'\n")
2211 unless $remote_ref =~ m{^refs/};
2212 $local_ref = uri_decode($local_ref);
2213 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
2214 $r->{$remote}->{svm} = {} if $use_svm_props;
2215 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
2216 $r->{$1}->{svm} = {};
2217 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
2218 $r->{$1}->{url} = $2;
2219 } elsif (m!^(.+)\.pushurl=\s*(.*)\s*$!) {
2220 $r->{$1}->{pushurl} = $2;
2221 } elsif (m!^(.+)\.ignore-refs=\s*(.*)\s*$!) {
2222 $r->{$1}->{ignore_refs_regex} = $2;
2223 } elsif (m!^(.+)\.(branches|tags)=$svn_refspec$!) {
2224 my ($remote, $t, $local_ref, $remote_ref) =
2225 ($1, $2, $3, $4);
2226 die("svn-remote.$remote: remote ref '$remote_ref' ($t) "
2227 . "must start with 'refs/'\n")
2228 unless $remote_ref =~ m{^refs/};
2229 $local_ref = uri_decode($local_ref);
2230 my $rs = {
2231 t => $t,
2232 remote => $remote,
2233 path => Git::SVN::GlobSpec->new($local_ref, 1),
2234 ref => Git::SVN::GlobSpec->new($remote_ref, 0) };
2235 if (length($rs->{ref}->{right}) != 0) {
2236 die "The '*' glob character must be the last ",
2237 "character of '$remote_ref'\n";
2239 push @{ $r->{$remote}->{$t} }, $rs;
2243 map {
2244 if (defined $r->{$_}->{svm}) {
2245 my $svm;
2246 eval {
2247 my $section = "svn-remote.$_";
2248 $svm = {
2249 source => tmp_config('--get',
2250 "$section.svm-source"),
2251 replace => tmp_config('--get',
2252 "$section.svm-replace"),
2255 $r->{$_}->{svm} = $svm;
2257 } keys %$r;
2259 foreach my $remote (keys %$r) {
2260 foreach ( grep { defined $_ }
2261 map { $r->{$remote}->{$_} } qw(branches tags) ) {
2262 foreach my $rs ( @$_ ) {
2263 $rs->{ignore_refs_regex} =
2264 $r->{$remote}->{ignore_refs_regex};
2272 sub init_vars {
2273 $_gc_nr = $_gc_period = 1000;
2274 if (defined $_repack || defined $_repack_flags) {
2275 warn "Repack options are obsolete; they have no effect.\n";
2279 sub verify_remotes_sanity {
2280 return unless -d $ENV{GIT_DIR};
2281 my %seen;
2282 foreach (command(qw/config -l/)) {
2283 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
2284 if ($seen{$1}) {
2285 die "Remote ref refs/remote/$1 is tracked by",
2286 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
2287 "Please resolve this ambiguity in ",
2288 "your git configuration file before ",
2289 "continuing\n";
2291 $seen{$1} = $_;
2296 sub find_existing_remote {
2297 my ($url, $remotes) = @_;
2298 return undef if $no_reuse_existing;
2299 my $existing;
2300 foreach my $repo_id (keys %$remotes) {
2301 my $u = $remotes->{$repo_id}->{url} or next;
2302 next if $u ne $url;
2303 $existing = $repo_id;
2304 last;
2306 $existing;
2309 sub init_remote_config {
2310 my ($self, $url, $no_write) = @_;
2311 $url =~ s!/+$!!; # strip trailing slash
2312 my $r = read_all_remotes();
2313 my $existing = find_existing_remote($url, $r);
2314 if ($existing) {
2315 unless ($no_write) {
2316 print STDERR "Using existing ",
2317 "[svn-remote \"$existing\"]\n";
2319 $self->{repo_id} = $existing;
2320 } elsif ($_minimize_url) {
2321 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
2322 $existing = find_existing_remote($min_url, $r);
2323 if ($existing) {
2324 unless ($no_write) {
2325 print STDERR "Using existing ",
2326 "[svn-remote \"$existing\"]\n";
2328 $self->{repo_id} = $existing;
2330 if ($min_url ne $url) {
2331 unless ($no_write) {
2332 print STDERR "Using higher level of URL: ",
2333 "$url => $min_url\n";
2335 my $old_path = $self->{path};
2336 $self->{path} = $url;
2337 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
2338 if (length $old_path) {
2339 $self->{path} .= "/$old_path";
2341 $url = $min_url;
2344 my $orig_url;
2345 if (!$existing) {
2346 # verify that we aren't overwriting anything:
2347 $orig_url = eval {
2348 command_oneline('config', '--get',
2349 "svn-remote.$self->{repo_id}.url")
2351 if ($orig_url && ($orig_url ne $url)) {
2352 die "svn-remote.$self->{repo_id}.url already set: ",
2353 "$orig_url\nwanted to set to: $url\n";
2356 my ($xrepo_id, $xpath) = find_ref($self->refname);
2357 if (!$no_write && defined $xpath) {
2358 die "svn-remote.$xrepo_id.fetch already set to track ",
2359 "$xpath:", $self->refname, "\n";
2361 unless ($no_write) {
2362 command_noisy('config',
2363 "svn-remote.$self->{repo_id}.url", $url);
2364 $self->{path} =~ s{^/}{};
2365 $self->{path} =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
2366 command_noisy('config', '--add',
2367 "svn-remote.$self->{repo_id}.fetch",
2368 "$self->{path}:".$self->refname);
2370 $self->{url} = $url;
2373 sub find_by_url { # repos_root and, path are optional
2374 my ($class, $full_url, $repos_root, $path) = @_;
2376 return undef unless defined $full_url;
2377 remove_username($full_url);
2378 remove_username($repos_root) if defined $repos_root;
2379 my $remotes = read_all_remotes();
2380 if (defined $full_url && defined $repos_root && !defined $path) {
2381 $path = $full_url;
2382 $path =~ s#^\Q$repos_root\E(?:/|$)##;
2384 foreach my $repo_id (keys %$remotes) {
2385 my $u = $remotes->{$repo_id}->{url} or next;
2386 remove_username($u);
2387 next if defined $repos_root && $repos_root ne $u;
2389 my $fetch = $remotes->{$repo_id}->{fetch} || {};
2390 foreach my $t (qw/branches tags/) {
2391 foreach my $globspec (@{$remotes->{$repo_id}->{$t}}) {
2392 resolve_local_globs($u, $fetch, $globspec);
2395 my $p = $path;
2396 my $rwr = rewrite_root({repo_id => $repo_id});
2397 my $svm = $remotes->{$repo_id}->{svm}
2398 if defined $remotes->{$repo_id}->{svm};
2399 unless (defined $p) {
2400 $p = $full_url;
2401 my $z = $u;
2402 my $prefix = '';
2403 if ($rwr) {
2404 $z = $rwr;
2405 remove_username($z);
2406 } elsif (defined $svm) {
2407 $z = $svm->{source};
2408 $prefix = $svm->{replace};
2409 $prefix =~ s#^\Q$u\E(?:/|$)##;
2410 $prefix =~ s#/$##;
2412 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
2414 foreach my $f (keys %$fetch) {
2415 next if $f ne $p;
2416 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
2419 undef;
2422 sub init {
2423 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
2424 my $self = _new($class, $repo_id, $ref_id, $path);
2425 if (defined $url) {
2426 $self->init_remote_config($url, $no_write);
2428 $self;
2431 sub find_ref {
2432 my ($ref_id) = @_;
2433 foreach (command(qw/config -l/)) {
2434 next unless m!^svn-remote\.(.+)\.fetch=
2435 \s*(.*?)\s*:\s*(.+?)\s*$!x;
2436 my ($repo_id, $path, $ref) = ($1, $2, $3);
2437 if ($ref eq $ref_id) {
2438 $path = '' if ($path =~ m#^\./?#);
2439 return ($repo_id, $path);
2442 (undef, undef, undef);
2445 sub new {
2446 my ($class, $ref_id, $repo_id, $path) = @_;
2447 if (defined $ref_id && !defined $repo_id && !defined $path) {
2448 ($repo_id, $path) = find_ref($ref_id);
2449 if (!defined $repo_id) {
2450 die "Could not find a \"svn-remote.*.fetch\" key ",
2451 "in the repository configuration matching: ",
2452 "$ref_id\n";
2455 my $self = _new($class, $repo_id, $ref_id, $path);
2456 if (!defined $self->{path} || !length $self->{path}) {
2457 my $fetch = command_oneline('config', '--get',
2458 "svn-remote.$repo_id.fetch",
2459 ":$ref_id\$") or
2460 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
2461 "\":$ref_id\$\" in config\n";
2462 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
2464 $self->{path} =~ s{/+}{/}g;
2465 $self->{path} =~ s{\A/}{};
2466 $self->{path} =~ s{/\z}{};
2467 $self->{url} = command_oneline('config', '--get',
2468 "svn-remote.$repo_id.url") or
2469 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
2470 $self->{pushurl} = eval { command_oneline('config', '--get',
2471 "svn-remote.$repo_id.pushurl") };
2472 $self->rebuild;
2473 $self;
2476 sub refname {
2477 my ($refname) = $_[0]->{ref_id} ;
2479 # It cannot end with a slash /, we'll throw up on this because
2480 # SVN can't have directories with a slash in their name, either:
2481 if ($refname =~ m{/$}) {
2482 die "ref: '$refname' ends with a trailing slash, this is ",
2483 "not permitted by git nor Subversion\n";
2486 # It cannot have ASCII control character space, tilde ~, caret ^,
2487 # colon :, question-mark ?, asterisk *, space, or open bracket [
2488 # anywhere.
2490 # Additionally, % must be escaped because it is used for escaping
2491 # and we want our escaped refname to be reversible
2492 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
2494 # no slash-separated component can begin with a dot .
2495 # /.* becomes /%2E*
2496 $refname =~ s{/\.}{/%2E}g;
2498 # It cannot have two consecutive dots .. anywhere
2499 # .. becomes %2E%2E
2500 $refname =~ s{\.\.}{%2E%2E}g;
2502 # trailing dots and .lock are not allowed
2503 # .$ becomes %2E and .lock becomes %2Elock
2504 $refname =~ s{\.(?=$|lock$)}{%2E};
2506 # the sequence @{ is used to access the reflog
2507 # @{ becomes %40{
2508 $refname =~ s{\@\{}{%40\{}g;
2510 return $refname;
2513 sub desanitize_refname {
2514 my ($refname) = @_;
2515 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
2516 return $refname;
2519 sub svm_uuid {
2520 my ($self) = @_;
2521 return $self->{svm}->{uuid} if $self->svm;
2522 $self->ra;
2523 unless ($self->{svm}) {
2524 die "SVM UUID not cached, and reading remotely failed\n";
2526 $self->{svm}->{uuid};
2529 sub svm {
2530 my ($self) = @_;
2531 return $self->{svm} if $self->{svm};
2532 my $svm;
2533 # see if we have it in our config, first:
2534 eval {
2535 my $section = "svn-remote.$self->{repo_id}";
2536 $svm = {
2537 source => tmp_config('--get', "$section.svm-source"),
2538 uuid => tmp_config('--get', "$section.svm-uuid"),
2539 replace => tmp_config('--get', "$section.svm-replace"),
2542 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
2543 $self->{svm} = $svm;
2545 $self->{svm};
2548 sub _set_svm_vars {
2549 my ($self, $ra) = @_;
2550 return $ra if $self->svm;
2552 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
2553 "(svm:source, svm:uuid) ",
2554 "from the following URLs:\n" );
2555 sub read_svm_props {
2556 my ($self, $ra, $path, $r) = @_;
2557 my $props = ($ra->get_dir($path, $r))[2];
2558 my $src = $props->{'svm:source'};
2559 my $uuid = $props->{'svm:uuid'};
2560 return undef if (!$src || !$uuid);
2562 chomp($src, $uuid);
2564 $uuid =~ m{^[0-9a-f\-]{30,}$}i
2565 or die "doesn't look right - svm:uuid is '$uuid'\n";
2567 # the '!' is used to mark the repos_root!/relative/path
2568 $src =~ s{/?!/?}{/};
2569 $src =~ s{/+$}{}; # no trailing slashes please
2570 # username is of no interest
2571 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
2573 my $replace = $ra->{url};
2574 $replace .= "/$path" if length $path;
2576 my $section = "svn-remote.$self->{repo_id}";
2577 tmp_config("$section.svm-source", $src);
2578 tmp_config("$section.svm-replace", $replace);
2579 tmp_config("$section.svm-uuid", $uuid);
2580 $self->{svm} = {
2581 source => $src,
2582 uuid => $uuid,
2583 replace => $replace
2587 my $r = $ra->get_latest_revnum;
2588 my $path = $self->{path};
2589 my %tried;
2590 while (length $path) {
2591 unless ($tried{"$self->{url}/$path"}) {
2592 return $ra if $self->read_svm_props($ra, $path, $r);
2593 $tried{"$self->{url}/$path"} = 1;
2595 $path =~ s#/?[^/]+$##;
2597 die "Path: '$path' should be ''\n" if $path ne '';
2598 return $ra if $self->read_svm_props($ra, $path, $r);
2599 $tried{"$self->{url}/$path"} = 1;
2601 if ($ra->{repos_root} eq $self->{url}) {
2602 die @err, (map { " $_\n" } keys %tried), "\n";
2605 # nope, make sure we're connected to the repository root:
2606 my $ok;
2607 my @tried_b;
2608 $path = $ra->{svn_path};
2609 $ra = Git::SVN::Ra->new($ra->{repos_root});
2610 while (length $path) {
2611 unless ($tried{"$ra->{url}/$path"}) {
2612 $ok = $self->read_svm_props($ra, $path, $r);
2613 last if $ok;
2614 $tried{"$ra->{url}/$path"} = 1;
2616 $path =~ s#/?[^/]+$##;
2618 die "Path: '$path' should be ''\n" if $path ne '';
2619 $ok ||= $self->read_svm_props($ra, $path, $r);
2620 $tried{"$ra->{url}/$path"} = 1;
2621 if (!$ok) {
2622 die @err, (map { " $_\n" } keys %tried), "\n";
2624 Git::SVN::Ra->new($self->{url});
2627 sub svnsync {
2628 my ($self) = @_;
2629 return $self->{svnsync} if $self->{svnsync};
2631 if ($self->no_metadata) {
2632 die "Can't have both 'noMetadata' and ",
2633 "'useSvnsyncProps' options set!\n";
2635 if ($self->rewrite_root) {
2636 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
2637 "options set!\n";
2639 if ($self->rewrite_uuid) {
2640 die "Can't have both 'useSvnsyncProps' and 'rewriteUUID' ",
2641 "options set!\n";
2644 my $svnsync;
2645 # see if we have it in our config, first:
2646 eval {
2647 my $section = "svn-remote.$self->{repo_id}";
2649 my $url = tmp_config('--get', "$section.svnsync-url");
2650 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2651 die "doesn't look right - svn:sync-from-url is '$url'\n";
2653 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
2654 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2655 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2657 $svnsync = { url => $url, uuid => $uuid }
2659 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
2660 return $self->{svnsync} = $svnsync;
2663 my $err = "useSvnsyncProps set, but failed to read " .
2664 "svnsync property: svn:sync-from-";
2665 my $rp = $self->ra->rev_proplist(0);
2667 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
2668 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2669 die "doesn't look right - svn:sync-from-url is '$url'\n";
2671 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
2672 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2673 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2675 my $section = "svn-remote.$self->{repo_id}";
2676 tmp_config('--add', "$section.svnsync-uuid", $uuid);
2677 tmp_config('--add', "$section.svnsync-url", $url);
2678 return $self->{svnsync} = { url => $url, uuid => $uuid };
2681 # this allows us to memoize our SVN::Ra UUID locally and avoid a
2682 # remote lookup (useful for 'git svn log').
2683 sub ra_uuid {
2684 my ($self) = @_;
2685 unless ($self->{ra_uuid}) {
2686 my $key = "svn-remote.$self->{repo_id}.uuid";
2687 my $uuid = eval { tmp_config('--get', $key) };
2688 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/i) {
2689 $self->{ra_uuid} = $uuid;
2690 } else {
2691 die "ra_uuid called without URL\n" unless $self->{url};
2692 $self->{ra_uuid} = $self->ra->get_uuid;
2693 tmp_config('--add', $key, $self->{ra_uuid});
2696 $self->{ra_uuid};
2699 sub _set_repos_root {
2700 my ($self, $repos_root) = @_;
2701 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2702 $repos_root ||= $self->ra->{repos_root};
2703 tmp_config($k, $repos_root);
2704 $repos_root;
2707 sub repos_root {
2708 my ($self) = @_;
2709 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2710 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
2713 sub ra {
2714 my ($self) = shift;
2715 my $ra = Git::SVN::Ra->new($self->{url});
2716 $self->_set_repos_root($ra->{repos_root});
2717 if ($self->use_svm_props && !$self->{svm}) {
2718 if ($self->no_metadata) {
2719 die "Can't have both 'noMetadata' and ",
2720 "'useSvmProps' options set!\n";
2721 } elsif ($self->use_svnsync_props) {
2722 die "Can't have both 'useSvnsyncProps' and ",
2723 "'useSvmProps' options set!\n";
2725 $ra = $self->_set_svm_vars($ra);
2726 $self->{-want_revprops} = 1;
2728 $ra;
2731 # prop_walk(PATH, REV, SUB)
2732 # -------------------------
2733 # Recursively traverse PATH at revision REV and invoke SUB for each
2734 # directory that contains a SVN property. SUB will be invoked as
2735 # follows: &SUB(gs, path, props); where `gs' is this instance of
2736 # Git::SVN, `path' the path to the directory where the properties
2737 # `props' were found. The `path' will be relative to point of checkout,
2738 # that is, if url://repo/trunk is the current Git branch, and that
2739 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
2740 # as `path' (note the trailing `/').
2741 sub prop_walk {
2742 my ($self, $path, $rev, $sub) = @_;
2744 $path =~ s#^/##;
2745 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2746 $path =~ s#^/*#/#g;
2747 my $p = $path;
2748 # Strip the irrelevant part of the path.
2749 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2750 # Ensure the path is terminated by a `/'.
2751 $p =~ s#/*$#/#;
2753 # The properties contain all the internal SVN stuff nobody
2754 # (usually) cares about.
2755 my $interesting_props = 0;
2756 foreach (keys %{$props}) {
2757 # If it doesn't start with `svn:', it must be a
2758 # user-defined property.
2759 ++$interesting_props and next if $_ !~ /^svn:/;
2760 # FIXME: Fragile, if SVN adds new public properties,
2761 # this needs to be updated.
2762 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2763 |eol-style|mime-type
2764 |externals|needs-lock)$/x;
2766 &$sub($self, $p, $props) if $interesting_props;
2768 foreach (sort keys %$dirent) {
2769 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
2770 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
2774 sub last_rev { ($_[0]->last_rev_commit)[0] }
2775 sub last_commit { ($_[0]->last_rev_commit)[1] }
2777 # returns the newest SVN revision number and newest commit SHA1
2778 sub last_rev_commit {
2779 my ($self) = @_;
2780 if (defined $self->{last_rev} && defined $self->{last_commit}) {
2781 return ($self->{last_rev}, $self->{last_commit});
2783 my $c = ::verify_ref($self->refname.'^0');
2784 if ($c && !$self->use_svm_props && !$self->no_metadata) {
2785 my $rev = (::cmt_metadata($c))[1];
2786 if (defined $rev) {
2787 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2788 return ($rev, $c);
2791 my $map_path = $self->map_path;
2792 unless (-e $map_path) {
2793 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2794 return (undef, undef);
2796 my ($rev, $commit) = $self->rev_map_max(1);
2797 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2798 return ($rev, $commit);
2801 sub get_fetch_range {
2802 my ($self, $min, $max) = @_;
2803 $max ||= $self->ra->get_latest_revnum;
2804 $min ||= $self->rev_map_max;
2805 (++$min, $max);
2808 sub tmp_config {
2809 my (@args) = @_;
2810 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2811 my $config = "$ENV{GIT_DIR}/svn/.metadata";
2812 if (! -f $config && -f $old_def_config) {
2813 rename $old_def_config, $config or
2814 die "Failed rename $old_def_config => $config: $!\n";
2816 my $old_config = $ENV{GIT_CONFIG};
2817 $ENV{GIT_CONFIG} = $config;
2818 $@ = undef;
2819 my @ret = eval {
2820 unless (-f $config) {
2821 mkfile($config);
2822 open my $fh, '>', $config or
2823 die "Can't open $config: $!\n";
2824 print $fh "; This file is used internally by ",
2825 "git-svn\n" or die
2826 "Couldn't write to $config: $!\n";
2827 print $fh "; You should not have to edit it\n" or
2828 die "Couldn't write to $config: $!\n";
2829 close $fh or die "Couldn't close $config: $!\n";
2831 command('config', @args);
2833 my $err = $@;
2834 if (defined $old_config) {
2835 $ENV{GIT_CONFIG} = $old_config;
2836 } else {
2837 delete $ENV{GIT_CONFIG};
2839 die $err if $err;
2840 wantarray ? @ret : $ret[0];
2843 sub tmp_index_do {
2844 my ($self, $sub) = @_;
2845 my $old_index = $ENV{GIT_INDEX_FILE};
2846 $ENV{GIT_INDEX_FILE} = $self->{index};
2847 $@ = undef;
2848 my @ret = eval {
2849 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2850 mkpath([$dir]) unless -d $dir;
2851 &$sub;
2853 my $err = $@;
2854 if (defined $old_index) {
2855 $ENV{GIT_INDEX_FILE} = $old_index;
2856 } else {
2857 delete $ENV{GIT_INDEX_FILE};
2859 die $err if $err;
2860 wantarray ? @ret : $ret[0];
2863 sub assert_index_clean {
2864 my ($self, $treeish) = @_;
2866 $self->tmp_index_do(sub {
2867 command_noisy('read-tree', $treeish) unless -e $self->{index};
2868 my $x = command_oneline('write-tree');
2869 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2870 /^tree ($::sha1)/mo);
2871 return if $y eq $x;
2873 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2874 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2875 command_noisy('read-tree', $treeish);
2876 $x = command_oneline('write-tree');
2877 if ($y ne $x) {
2878 ::fatal "trees ($treeish) $y != $x\n",
2879 "Something is seriously wrong...";
2884 sub get_commit_parents {
2885 my ($self, $log_entry) = @_;
2886 my (%seen, @ret, @tmp);
2887 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2888 if (my $ip = $self->{inject_parents}) {
2889 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2890 push @tmp, $commit;
2893 if (my $cur = ::verify_ref($self->refname.'^0')) {
2894 push @tmp, $cur;
2896 if (my $ipd = $self->{inject_parents_dcommit}) {
2897 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2898 push @tmp, @$commit;
2901 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2902 while (my $p = shift @tmp) {
2903 next if $seen{$p};
2904 $seen{$p} = 1;
2905 push @ret, $p;
2907 @ret;
2910 sub rewrite_root {
2911 my ($self) = @_;
2912 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2913 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2914 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2915 if ($rwr) {
2916 $rwr =~ s#/+$##;
2917 if ($rwr !~ m#^[a-z\+]+://#) {
2918 die "$rwr is not a valid URL (key: $k)\n";
2921 $self->{-rewrite_root} = $rwr;
2924 sub rewrite_uuid {
2925 my ($self) = @_;
2926 return $self->{-rewrite_uuid} if exists $self->{-rewrite_uuid};
2927 my $k = "svn-remote.$self->{repo_id}.rewriteUUID";
2928 my $rwid = eval { command_oneline(qw/config --get/, $k) };
2929 if ($rwid) {
2930 $rwid =~ s#/+$##;
2931 if ($rwid !~ m#^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$#) {
2932 die "$rwid is not a valid UUID (key: $k)\n";
2935 $self->{-rewrite_uuid} = $rwid;
2938 sub metadata_url {
2939 my ($self) = @_;
2940 ($self->rewrite_root || $self->{url}) .
2941 (length $self->{path} ? '/' . $self->{path} : '');
2944 sub full_url {
2945 my ($self) = @_;
2946 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2949 sub full_pushurl {
2950 my ($self) = @_;
2951 if ($self->{pushurl}) {
2952 return $self->{pushurl} . (length $self->{path} ? '/' .
2953 $self->{path} : '');
2954 } else {
2955 return $self->full_url;
2959 sub set_commit_header_env {
2960 my ($log_entry) = @_;
2961 my %env;
2962 foreach my $ned (qw/NAME EMAIL DATE/) {
2963 foreach my $ac (qw/AUTHOR COMMITTER/) {
2964 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2968 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2969 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2970 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2972 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2973 ? $log_entry->{commit_name}
2974 : $log_entry->{name};
2975 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2976 ? $log_entry->{commit_email}
2977 : $log_entry->{email};
2978 \%env;
2981 sub restore_commit_header_env {
2982 my ($env) = @_;
2983 foreach my $ned (qw/NAME EMAIL DATE/) {
2984 foreach my $ac (qw/AUTHOR COMMITTER/) {
2985 my $k = "GIT_${ac}_${ned}";
2986 if (defined $env->{$k}) {
2987 $ENV{$k} = $env->{$k};
2988 } else {
2989 delete $ENV{$k};
2995 sub gc {
2996 command_noisy('gc', '--auto');
2999 sub do_git_commit {
3000 my ($self, $log_entry) = @_;
3001 my $lr = $self->last_rev;
3002 if (defined $lr && $lr >= $log_entry->{revision}) {
3003 die "Last fetched revision of ", $self->refname,
3004 " was r$lr, but we are about to fetch: ",
3005 "r$log_entry->{revision}!\n";
3007 if (my $c = $self->rev_map_get($log_entry->{revision})) {
3008 croak "$log_entry->{revision} = $c already exists! ",
3009 "Why are we refetching it?\n";
3011 my $old_env = set_commit_header_env($log_entry);
3012 my $tree = $log_entry->{tree};
3013 if (!defined $tree) {
3014 $tree = $self->tmp_index_do(sub {
3015 command_oneline('write-tree') });
3017 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
3019 my @exec = ('git', 'commit-tree', $tree);
3020 foreach ($self->get_commit_parents($log_entry)) {
3021 push @exec, '-p', $_;
3023 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
3024 or croak $!;
3025 binmode $msg_fh;
3027 # we always get UTF-8 from SVN, but we may want our commits in
3028 # a different encoding.
3029 if (my $enc = Git::config('i18n.commitencoding')) {
3030 require Encode;
3031 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
3033 print $msg_fh $log_entry->{log} or croak $!;
3034 restore_commit_header_env($old_env);
3035 unless ($self->no_metadata) {
3036 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
3037 or croak $!;
3039 $msg_fh->flush == 0 or croak $!;
3040 close $msg_fh or croak $!;
3041 chomp(my $commit = do { local $/; <$out_fh> });
3042 close $out_fh or croak $!;
3043 waitpid $pid, 0;
3044 croak $? if $?;
3045 if ($commit !~ /^$::sha1$/o) {
3046 die "Failed to commit, invalid sha1: $commit\n";
3049 $self->rev_map_set($log_entry->{revision}, $commit, 1);
3051 $self->{last_rev} = $log_entry->{revision};
3052 $self->{last_commit} = $commit;
3053 print "r$log_entry->{revision}" unless $::_q > 1;
3054 if (defined $log_entry->{svm_revision}) {
3055 print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
3056 $self->rev_map_set($log_entry->{svm_revision}, $commit,
3057 0, $self->svm_uuid);
3059 print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
3060 if (--$_gc_nr == 0) {
3061 $_gc_nr = $_gc_period;
3062 gc();
3064 return $commit;
3067 sub match_paths {
3068 my ($self, $paths, $r) = @_;
3069 return 1 if $self->{path} eq '';
3070 if (my $path = $paths->{"/$self->{path}"}) {
3071 return ($path->{action} eq 'D') ? 0 : 1;
3073 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
3074 if (grep /$self->{path_regex}/, keys %$paths) {
3075 return 1;
3077 my $c = '';
3078 foreach (split m#/#, $self->{path}) {
3079 $c .= "/$_";
3080 next unless ($paths->{$c} &&
3081 ($paths->{$c}->{action} =~ /^[AR]$/));
3082 if ($self->ra->check_path($self->{path}, $r) ==
3083 $SVN::Node::dir) {
3084 return 1;
3087 return 0;
3090 sub find_parent_branch {
3091 my ($self, $paths, $rev) = @_;
3092 return undef unless $self->follow_parent;
3093 unless (defined $paths) {
3094 my $err_handler = $SVN::Error::handler;
3095 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
3096 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1,
3097 sub { $paths = $_[0] });
3098 $SVN::Error::handler = $err_handler;
3100 return undef unless defined $paths;
3102 # look for a parent from another branch:
3103 my @b_path_components = split m#/#, $self->{path};
3104 my @a_path_components;
3105 my $i;
3106 while (@b_path_components) {
3107 $i = $paths->{'/'.join('/', @b_path_components)};
3108 last if $i && defined $i->{copyfrom_path};
3109 unshift(@a_path_components, pop(@b_path_components));
3111 return undef unless defined $i && defined $i->{copyfrom_path};
3112 my $branch_from = $i->{copyfrom_path};
3113 if (@a_path_components) {
3114 print STDERR "branch_from: $branch_from => ";
3115 $branch_from .= '/'.join('/', @a_path_components);
3116 print STDERR $branch_from, "\n";
3118 my $r = $i->{copyfrom_rev};
3119 my $repos_root = $self->ra->{repos_root};
3120 my $url = $self->ra->{url};
3121 my $new_url = $url . $branch_from;
3122 print STDERR "Found possible branch point: ",
3123 "$new_url => ", $self->full_url, ", $r\n"
3124 unless $::_q > 1;
3125 $branch_from =~ s#^/##;
3126 my $gs = $self->other_gs($new_url, $url,
3127 $branch_from, $r, $self->{ref_id});
3128 my ($r0, $parent) = $gs->find_rev_before($r, 1);
3130 my ($base, $head);
3131 if (!defined $r0 || !defined $parent) {
3132 ($base, $head) = parse_revision_argument(0, $r);
3133 } else {
3134 if ($r0 < $r) {
3135 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
3136 0, 1, sub { $base = $_[1] - 1 });
3139 if (defined $base && $base <= $r) {
3140 $gs->fetch($base, $r);
3142 ($r0, $parent) = $gs->find_rev_before($r, 1);
3144 if (defined $r0 && defined $parent) {
3145 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n"
3146 unless $::_q > 1;
3147 my $ed;
3148 if ($self->ra->can_do_switch) {
3149 $self->assert_index_clean($parent);
3150 print STDERR "Following parent with do_switch\n"
3151 unless $::_q > 1;
3152 # do_switch works with svn/trunk >= r22312, but that
3153 # is not included with SVN 1.4.3 (the latest version
3154 # at the moment), so we can't rely on it
3155 $self->{last_rev} = $r0;
3156 $self->{last_commit} = $parent;
3157 $ed = SVN::Git::Fetcher->new($self, $gs->{path});
3158 $gs->ra->gs_do_switch($r0, $rev, $gs,
3159 $self->full_url, $ed)
3160 or die "SVN connection failed somewhere...\n";
3161 } elsif ($self->ra->trees_match($new_url, $r0,
3162 $self->full_url, $rev)) {
3163 print STDERR "Trees match:\n",
3164 " $new_url\@$r0\n",
3165 " ${\$self->full_url}\@$rev\n",
3166 "Following parent with no changes\n"
3167 unless $::_q > 1;
3168 $self->tmp_index_do(sub {
3169 command_noisy('read-tree', $parent);
3171 $self->{last_commit} = $parent;
3172 } else {
3173 print STDERR "Following parent with do_update\n"
3174 unless $::_q > 1;
3175 $ed = SVN::Git::Fetcher->new($self);
3176 $self->ra->gs_do_update($rev, $rev, $self, $ed)
3177 or die "SVN connection failed somewhere...\n";
3179 print STDERR "Successfully followed parent\n" unless $::_q > 1;
3180 return $self->make_log_entry($rev, [$parent], $ed);
3182 return undef;
3185 sub do_fetch {
3186 my ($self, $paths, $rev) = @_;
3187 my $ed;
3188 my ($last_rev, @parents);
3189 if (my $lc = $self->last_commit) {
3190 # we can have a branch that was deleted, then re-added
3191 # under the same name but copied from another path, in
3192 # which case we'll have multiple parents (we don't
3193 # want to break the original ref, nor lose copypath info):
3194 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
3195 push @{$log_entry->{parents}}, $lc;
3196 return $log_entry;
3198 $ed = SVN::Git::Fetcher->new($self);
3199 $last_rev = $self->{last_rev};
3200 $ed->{c} = $lc;
3201 @parents = ($lc);
3202 } else {
3203 $last_rev = $rev;
3204 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
3205 return $log_entry;
3207 $ed = SVN::Git::Fetcher->new($self);
3209 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
3210 die "SVN connection failed somewhere...\n";
3212 $self->make_log_entry($rev, \@parents, $ed);
3215 sub mkemptydirs {
3216 my ($self, $r) = @_;
3218 sub scan {
3219 my ($r, $empty_dirs, $line) = @_;
3220 if (defined $r && $line =~ /^r(\d+)$/) {
3221 return 0 if $1 > $r;
3222 } elsif ($line =~ /^ \+empty_dir: (.+)$/) {
3223 $empty_dirs->{$1} = 1;
3224 } elsif ($line =~ /^ \-empty_dir: (.+)$/) {
3225 my @d = grep {m[^\Q$1\E(/|$)]} (keys %$empty_dirs);
3226 delete @$empty_dirs{@d};
3228 1; # continue
3231 my %empty_dirs = ();
3232 my $gz_file = "$self->{dir}/unhandled.log.gz";
3233 if (-f $gz_file) {
3234 if (!$can_compress) {
3235 warn "Compress::Zlib could not be found; ",
3236 "empty directories in $gz_file will not be read\n";
3237 } else {
3238 my $gz = Compress::Zlib::gzopen($gz_file, "rb") or
3239 die "Unable to open $gz_file: $!\n";
3240 my $line;
3241 while ($gz->gzreadline($line) > 0) {
3242 scan($r, \%empty_dirs, $line) or last;
3244 $gz->gzclose;
3248 if (open my $fh, '<', "$self->{dir}/unhandled.log") {
3249 binmode $fh or croak "binmode: $!";
3250 while (<$fh>) {
3251 scan($r, \%empty_dirs, $_) or last;
3253 close $fh;
3256 my $strip = qr/\A\Q$self->{path}\E(?:\/|$)/;
3257 foreach my $d (sort keys %empty_dirs) {
3258 $d = uri_decode($d);
3259 $d =~ s/$strip//;
3260 next unless length($d);
3261 next if -d $d;
3262 if (-e $d) {
3263 warn "$d exists but is not a directory\n";
3264 } else {
3265 print "creating empty directory: $d\n";
3266 mkpath([$d]);
3271 sub get_untracked {
3272 my ($self, $ed) = @_;
3273 my @out;
3274 my $h = $ed->{empty};
3275 foreach (sort keys %$h) {
3276 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
3277 push @out, " $act: " . uri_encode($_);
3278 warn "W: $act: $_\n";
3280 foreach my $t (qw/dir_prop file_prop/) {
3281 $h = $ed->{$t} or next;
3282 foreach my $path (sort keys %$h) {
3283 my $ppath = $path eq '' ? '.' : $path;
3284 foreach my $prop (sort keys %{$h->{$path}}) {
3285 next if $SKIP_PROP{$prop};
3286 my $v = $h->{$path}->{$prop};
3287 my $t_ppath_prop = "$t: " .
3288 uri_encode($ppath) . ' ' .
3289 uri_encode($prop);
3290 if (defined $v) {
3291 push @out, " +$t_ppath_prop " .
3292 uri_encode($v);
3293 } else {
3294 push @out, " -$t_ppath_prop";
3299 foreach my $t (qw/absent_file absent_directory/) {
3300 $h = $ed->{$t} or next;
3301 foreach my $parent (sort keys %$h) {
3302 foreach my $path (sort @{$h->{$parent}}) {
3303 push @out, " $t: " .
3304 uri_encode("$parent/$path");
3305 warn "W: $t: $parent/$path ",
3306 "Insufficient permissions?\n";
3310 \@out;
3313 sub get_tz {
3314 # some systmes don't handle or mishandle %z, so be creative.
3315 my $t = shift || time;
3316 my $gm = timelocal(gmtime($t));
3317 my $sign = qw( + + - )[ $t <=> $gm ];
3318 return sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
3321 # parse_svn_date(DATE)
3322 # --------------------
3323 # Given a date (in UTC) from Subversion, return a string in the format
3324 # "<TZ Offset> <local date/time>" that Git will use.
3326 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
3327 # is true we'll convert it to the local timezone instead.
3328 sub parse_svn_date {
3329 my $date = shift || return '+0000 1970-01-01 00:00:00';
3330 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
3331 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
3332 croak "Unable to parse date: $date\n";
3333 my $parsed_date; # Set next.
3335 if ($Git::SVN::_localtime) {
3336 # Translate the Subversion datetime to an epoch time.
3337 # Begin by switching ourselves to $date's timezone, UTC.
3338 my $old_env_TZ = $ENV{TZ};
3339 $ENV{TZ} = 'UTC';
3341 my $epoch_in_UTC =
3342 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
3344 # Determine our local timezone (including DST) at the
3345 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
3346 # value of TZ, if any, at the time we were run.
3347 if (defined $Git::SVN::Log::TZ) {
3348 $ENV{TZ} = $Git::SVN::Log::TZ;
3349 } else {
3350 delete $ENV{TZ};
3353 my $our_TZ = get_tz();
3355 # This converts $epoch_in_UTC into our local timezone.
3356 my ($sec, $min, $hour, $mday, $mon, $year,
3357 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
3359 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
3360 $our_TZ, $year + 1900, $mon + 1,
3361 $mday, $hour, $min, $sec);
3363 # Reset us to the timezone in effect when we entered
3364 # this routine.
3365 if (defined $old_env_TZ) {
3366 $ENV{TZ} = $old_env_TZ;
3367 } else {
3368 delete $ENV{TZ};
3370 } else {
3371 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
3374 return $parsed_date;
3377 sub other_gs {
3378 my ($self, $new_url, $url,
3379 $branch_from, $r, $old_ref_id) = @_;
3380 my $gs = Git::SVN->find_by_url($new_url, $url, $branch_from);
3381 unless ($gs) {
3382 my $ref_id = $old_ref_id;
3383 $ref_id =~ s/\@\d+-*$//;
3384 $ref_id .= "\@$r";
3385 # just grow a tail if we're not unique enough :x
3386 $ref_id .= '-' while find_ref($ref_id);
3387 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
3388 if ($u =~ s#^\Q$url\E(/|$)##) {
3389 $p = $u;
3390 $u = $url;
3391 $repo_id = $self->{repo_id};
3393 while (1) {
3394 # It is possible to tag two different subdirectories at
3395 # the same revision. If the url for an existing ref
3396 # does not match, we must either find a ref with a
3397 # matching url or create a new ref by growing a tail.
3398 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
3399 my (undef, $max_commit) = $gs->rev_map_max(1);
3400 last if (!$max_commit);
3401 my ($url) = ::cmt_metadata($max_commit);
3402 last if ($url eq $gs->metadata_url);
3403 $ref_id .= '-';
3405 print STDERR "Initializing parent: $ref_id\n" unless $::_q > 1;
3410 sub call_authors_prog {
3411 my ($orig_author) = @_;
3412 $orig_author = command_oneline('rev-parse', '--sq-quote', $orig_author);
3413 my $author = `$::_authors_prog $orig_author`;
3414 if ($? != 0) {
3415 die "$::_authors_prog failed with exit code $?\n"
3417 if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
3418 my ($name, $email) = ($1, $2);
3419 $email = undef if length $2 == 0;
3420 return [$name, $email];
3421 } else {
3422 die "Author: $orig_author: $::_authors_prog returned "
3423 . "invalid author format: $author\n";
3427 sub check_author {
3428 my ($author) = @_;
3429 if (!defined $author || length $author == 0) {
3430 $author = '(no author)';
3432 if (!defined $::users{$author}) {
3433 if (defined $::_authors_prog) {
3434 $::users{$author} = call_authors_prog($author);
3435 } elsif (defined $::_authors) {
3436 die "Author: $author not defined in $::_authors file\n";
3439 $author;
3442 sub find_extra_svk_parents {
3443 my ($self, $ed, $tickets, $parents) = @_;
3444 # aha! svk:merge property changed...
3445 my @tickets = split "\n", $tickets;
3446 my @known_parents;
3447 for my $ticket ( @tickets ) {
3448 my ($uuid, $path, $rev) = split /:/, $ticket;
3449 if ( $uuid eq $self->ra_uuid ) {
3450 my $url = $self->{url};
3451 my $repos_root = $url;
3452 my $branch_from = $path;
3453 $branch_from =~ s{^/}{};
3454 my $gs = $self->other_gs($repos_root."/".$branch_from,
3455 $url,
3456 $branch_from,
3457 $rev,
3458 $self->{ref_id});
3459 if ( my $commit = $gs->rev_map_get($rev, $uuid) ) {
3460 # wahey! we found it, but it might be
3461 # an old one (!)
3462 push @known_parents, [ $rev, $commit ];
3466 # Ordering matters; highest-numbered commit merge tickets
3467 # first, as they may account for later merge ticket additions
3468 # or changes.
3469 @known_parents = map {$_->[1]} sort {$b->[0] <=> $a->[0]} @known_parents;
3470 for my $parent ( @known_parents ) {
3471 my @cmd = ('rev-list', $parent, map { "^$_" } @$parents );
3472 my ($msg_fh, $ctx) = command_output_pipe(@cmd);
3473 my $new;
3474 while ( <$msg_fh> ) {
3475 $new=1;last;
3477 command_close_pipe($msg_fh, $ctx);
3478 if ( $new ) {
3479 print STDERR
3480 "Found merge parent (svk:merge ticket): $parent\n";
3481 push @$parents, $parent;
3486 sub lookup_svn_merge {
3487 my $uuid = shift;
3488 my $url = shift;
3489 my $merge = shift;
3491 my ($source, $revs) = split ":", $merge;
3492 my $path = $source;
3493 $path =~ s{^/}{};
3494 my $gs = Git::SVN->find_by_url($url.$source, $url, $path);
3495 if ( !$gs ) {
3496 warn "Couldn't find revmap for $url$source\n";
3497 return;
3499 my @ranges = split ",", $revs;
3500 my ($tip, $tip_commit);
3501 my @merged_commit_ranges;
3502 # find the tip
3503 for my $range ( @ranges ) {
3504 my ($bottom, $top) = split "-", $range;
3505 $top ||= $bottom;
3506 my $bottom_commit = $gs->find_rev_after( $bottom, 1, $top );
3507 my $top_commit = $gs->find_rev_before( $top, 1, $bottom );
3509 unless ($top_commit and $bottom_commit) {
3510 warn "W:unknown path/rev in svn:mergeinfo "
3511 ."dirprop: $source:$range\n";
3512 next;
3515 if (scalar(command('rev-parse', "$bottom_commit^@"))) {
3516 push @merged_commit_ranges,
3517 "$bottom_commit^..$top_commit";
3518 } else {
3519 push @merged_commit_ranges, "$top_commit";
3522 if ( !defined $tip or $top > $tip ) {
3523 $tip = $top;
3524 $tip_commit = $top_commit;
3527 return ($tip_commit, @merged_commit_ranges);
3530 sub _rev_list {
3531 my ($msg_fh, $ctx) = command_output_pipe(
3532 "rev-list", @_,
3534 my @rv;
3535 while ( <$msg_fh> ) {
3536 chomp;
3537 push @rv, $_;
3539 command_close_pipe($msg_fh, $ctx);
3540 @rv;
3543 sub check_cherry_pick {
3544 my $base = shift;
3545 my $tip = shift;
3546 my $parents = shift;
3547 my @ranges = @_;
3548 my %commits = map { $_ => 1 }
3549 _rev_list("--no-merges", $tip, "--not", $base, @$parents, "--");
3550 for my $range ( @ranges ) {
3551 delete @commits{_rev_list($range, "--")};
3553 for my $commit (keys %commits) {
3554 if (has_no_changes($commit)) {
3555 delete $commits{$commit};
3558 return (keys %commits);
3561 sub has_no_changes {
3562 my $commit = shift;
3564 my @revs = split / /, command_oneline(
3565 qw(rev-list --parents -1 -m), $commit);
3567 # Commits with no parents, e.g. the start of a partial branch,
3568 # have changes by definition.
3569 return 1 if (@revs < 2);
3571 # Commits with multiple parents, e.g a merge, have no changes
3572 # by definition.
3573 return 0 if (@revs > 2);
3575 return (command_oneline("rev-parse", "$commit^{tree}") eq
3576 command_oneline("rev-parse", "$commit~1^{tree}"));
3579 # The GIT_DIR environment variable is not always set until after the command
3580 # line arguments are processed, so we can't memoize in a BEGIN block.
3582 my $memoized = 0;
3584 sub memoize_svn_mergeinfo_functions {
3585 return if $memoized;
3586 $memoized = 1;
3588 my $cache_path = "$ENV{GIT_DIR}/svn/.caches/";
3589 mkpath([$cache_path]) unless -d $cache_path;
3591 tie my %lookup_svn_merge_cache => 'Memoize::Storable',
3592 "$cache_path/lookup_svn_merge.db", 'nstore';
3593 memoize 'lookup_svn_merge',
3594 SCALAR_CACHE => 'FAULT',
3595 LIST_CACHE => ['HASH' => \%lookup_svn_merge_cache],
3598 tie my %check_cherry_pick_cache => 'Memoize::Storable',
3599 "$cache_path/check_cherry_pick.db", 'nstore';
3600 memoize 'check_cherry_pick',
3601 SCALAR_CACHE => 'FAULT',
3602 LIST_CACHE => ['HASH' => \%check_cherry_pick_cache],
3605 tie my %has_no_changes_cache => 'Memoize::Storable',
3606 "$cache_path/has_no_changes.db", 'nstore';
3607 memoize 'has_no_changes',
3608 SCALAR_CACHE => ['HASH' => \%has_no_changes_cache],
3609 LIST_CACHE => 'FAULT',
3613 sub unmemoize_svn_mergeinfo_functions {
3614 return if not $memoized;
3615 $memoized = 0;
3617 Memoize::unmemoize 'lookup_svn_merge';
3618 Memoize::unmemoize 'check_cherry_pick';
3619 Memoize::unmemoize 'has_no_changes';
3622 Memoize::memoize 'Git::SVN::repos_root';
3625 END {
3626 # Force cache writeout explicitly instead of waiting for
3627 # global destruction to avoid segfault in Storable:
3628 # http://rt.cpan.org/Public/Bug/Display.html?id=36087
3629 unmemoize_svn_mergeinfo_functions();
3632 sub parents_exclude {
3633 my $parents = shift;
3634 my @commits = @_;
3635 return unless @commits;
3637 my @excluded;
3638 my $excluded;
3639 do {
3640 my @cmd = ('rev-list', "-1", @commits, "--not", @$parents );
3641 $excluded = command_oneline(@cmd);
3642 if ( $excluded ) {
3643 my @new;
3644 my $found;
3645 for my $commit ( @commits ) {
3646 if ( $commit eq $excluded ) {
3647 push @excluded, $commit;
3648 $found++;
3649 last;
3651 else {
3652 push @new, $commit;
3655 die "saw commit '$excluded' in rev-list output, "
3656 ."but we didn't ask for that commit (wanted: @commits --not @$parents)"
3657 unless $found;
3658 @commits = @new;
3661 while ($excluded and @commits);
3663 return @excluded;
3667 # note: this function should only be called if the various dirprops
3668 # have actually changed
3669 sub find_extra_svn_parents {
3670 my ($self, $ed, $mergeinfo, $parents) = @_;
3671 # aha! svk:merge property changed...
3673 memoize_svn_mergeinfo_functions();
3675 # We first search for merged tips which are not in our
3676 # history. Then, we figure out which git revisions are in
3677 # that tip, but not this revision. If all of those revisions
3678 # are now marked as merge, we can add the tip as a parent.
3679 my @merges = split "\n", $mergeinfo;
3680 my @merge_tips;
3681 my $url = $self->{url};
3682 my $uuid = $self->ra_uuid;
3683 my %ranges;
3684 for my $merge ( @merges ) {
3685 my ($tip_commit, @ranges) =
3686 lookup_svn_merge( $uuid, $url, $merge );
3687 unless (!$tip_commit or
3688 grep { $_ eq $tip_commit } @$parents ) {
3689 push @merge_tips, $tip_commit;
3690 $ranges{$tip_commit} = \@ranges;
3691 } else {
3692 push @merge_tips, undef;
3696 my %excluded = map { $_ => 1 }
3697 parents_exclude($parents, grep { defined } @merge_tips);
3699 # check merge tips for new parents
3700 my @new_parents;
3701 for my $merge_tip ( @merge_tips ) {
3702 my $spec = shift @merges;
3703 next unless $merge_tip and $excluded{$merge_tip};
3705 my $ranges = $ranges{$merge_tip};
3707 # check out 'new' tips
3708 my $merge_base;
3709 eval {
3710 $merge_base = command_oneline(
3711 "merge-base",
3712 @$parents, $merge_tip,
3715 if ($@) {
3716 die "An error occurred during merge-base"
3717 unless $@->isa("Git::Error::Command");
3719 warn "W: Cannot find common ancestor between ".
3720 "@$parents and $merge_tip. Ignoring merge info.\n";
3721 next;
3724 # double check that there are no missing non-merge commits
3725 my (@incomplete) = check_cherry_pick(
3726 $merge_base, $merge_tip,
3727 $parents,
3728 @$ranges,
3731 if ( @incomplete ) {
3732 warn "W:svn cherry-pick ignored ($spec) - missing "
3733 .@incomplete." commit(s) (eg $incomplete[0])\n";
3734 } else {
3735 warn
3736 "Found merge parent (svn:mergeinfo prop): ",
3737 $merge_tip, "\n";
3738 push @new_parents, $merge_tip;
3742 # cater for merges which merge commits from multiple branches
3743 if ( @new_parents > 1 ) {
3744 for ( my $i = 0; $i <= $#new_parents; $i++ ) {
3745 for ( my $j = 0; $j <= $#new_parents; $j++ ) {
3746 next if $i == $j;
3747 next unless $new_parents[$i];
3748 next unless $new_parents[$j];
3749 my $revs = command_oneline(
3750 "rev-list", "-1",
3751 "$new_parents[$i]..$new_parents[$j]",
3753 if ( !$revs ) {
3754 undef($new_parents[$j]);
3759 push @$parents, grep { defined } @new_parents;
3762 sub make_log_entry {
3763 my ($self, $rev, $parents, $ed) = @_;
3764 my $untracked = $self->get_untracked($ed);
3766 my @parents = @$parents;
3767 my $ps = $ed->{path_strip} || "";
3768 for my $path ( grep { m/$ps/ } %{$ed->{dir_prop}} ) {
3769 my $props = $ed->{dir_prop}{$path};
3770 if ( $props->{"svk:merge"} ) {
3771 $self->find_extra_svk_parents
3772 ($ed, $props->{"svk:merge"}, \@parents);
3774 if ( $props->{"svn:mergeinfo"} ) {
3775 $self->find_extra_svn_parents
3776 ($ed,
3777 $props->{"svn:mergeinfo"},
3778 \@parents);
3782 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
3783 print $un "r$rev\n" or croak $!;
3784 print $un $_, "\n" foreach @$untracked;
3785 my %log_entry = ( parents => \@parents, revision => $rev,
3786 log => '');
3788 my $headrev;
3789 my $logged = delete $self->{logged_rev_props};
3790 if (!$logged || $self->{-want_revprops}) {
3791 my $rp = $self->ra->rev_proplist($rev);
3792 foreach (sort keys %$rp) {
3793 my $v = $rp->{$_};
3794 if (/^svn:(author|date|log)$/) {
3795 $log_entry{$1} = $v;
3796 } elsif ($_ eq 'svm:headrev') {
3797 $headrev = $v;
3798 } else {
3799 print $un " rev_prop: ", uri_encode($_), ' ',
3800 uri_encode($v), "\n";
3803 } else {
3804 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
3806 close $un or croak $!;
3808 $log_entry{date} = parse_svn_date($log_entry{date});
3809 $log_entry{log} .= "\n";
3810 my $author = $log_entry{author} = check_author($log_entry{author});
3811 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
3812 : ($author, undef);
3814 my ($commit_name, $commit_email) = ($name, $email);
3815 if ($_use_log_author) {
3816 my $name_field;
3817 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
3818 $name_field = $1;
3819 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
3820 $name_field = $1;
3822 if (!defined $name_field) {
3823 if (!defined $email) {
3824 $email = $name;
3826 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
3827 ($name, $email) = ($1, $2);
3828 } elsif ($name_field =~ /(.*)@/) {
3829 ($name, $email) = ($1, $name_field);
3830 } else {
3831 ($name, $email) = ($name_field, $name_field);
3834 if (defined $headrev && $self->use_svm_props) {
3835 if ($self->rewrite_root) {
3836 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
3837 "options set!\n";
3839 if ($self->rewrite_uuid) {
3840 die "Can't have both 'useSvmProps' and 'rewriteUUID' ",
3841 "options set!\n";
3843 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$}i;
3844 # we don't want "SVM: initializing mirror for junk" ...
3845 return undef if $r == 0;
3846 my $svm = $self->svm;
3847 if ($uuid ne $svm->{uuid}) {
3848 die "UUID mismatch on SVM path:\n",
3849 "expected: $svm->{uuid}\n",
3850 " got: $uuid\n";
3852 my $full_url = $self->full_url;
3853 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
3854 die "Failed to replace '$svm->{replace}' with ",
3855 "'$svm->{source}' in $full_url\n";
3856 # throw away username for storing in records
3857 remove_username($full_url);
3858 $log_entry{metadata} = "$full_url\@$r $uuid";
3859 $log_entry{svm_revision} = $r;
3860 $email ||= "$author\@$uuid";
3861 $commit_email ||= "$author\@$uuid";
3862 } elsif ($self->use_svnsync_props) {
3863 my $full_url = $self->svnsync->{url};
3864 $full_url .= "/$self->{path}" if length $self->{path};
3865 remove_username($full_url);
3866 my $uuid = $self->svnsync->{uuid};
3867 $log_entry{metadata} = "$full_url\@$rev $uuid";
3868 $email ||= "$author\@$uuid";
3869 $commit_email ||= "$author\@$uuid";
3870 } else {
3871 my $url = $self->metadata_url;
3872 remove_username($url);
3873 my $uuid = $self->rewrite_uuid || $self->ra->get_uuid;
3874 $log_entry{metadata} = "$url\@$rev " . $uuid;
3875 $email ||= "$author\@" . $uuid;
3876 $commit_email ||= "$author\@" . $uuid;
3878 $log_entry{name} = $name;
3879 $log_entry{email} = $email;
3880 $log_entry{commit_name} = $commit_name;
3881 $log_entry{commit_email} = $commit_email;
3882 \%log_entry;
3885 sub fetch {
3886 my ($self, $min_rev, $max_rev, @parents) = @_;
3887 my ($last_rev, $last_commit) = $self->last_rev_commit;
3888 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
3889 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
3892 sub set_tree_cb {
3893 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
3894 $self->{inject_parents} = { $rev => $tree };
3895 $self->fetch(undef, undef);
3898 sub set_tree {
3899 my ($self, $tree) = (shift, shift);
3900 my $log_entry = ::get_commit_entry($tree);
3901 unless ($self->{last_rev}) {
3902 ::fatal("Must have an existing revision to commit");
3904 my %ed_opts = ( r => $self->{last_rev},
3905 log => $log_entry->{log},
3906 ra => $self->ra,
3907 tree_a => $self->{last_commit},
3908 tree_b => $tree,
3909 editor_cb => sub {
3910 $self->set_tree_cb($log_entry, $tree, @_) },
3911 svn_path => $self->{path} );
3912 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
3913 print "No changes\nr$self->{last_rev} = $tree\n";
3917 sub rebuild_from_rev_db {
3918 my ($self, $path) = @_;
3919 my $r = -1;
3920 open my $fh, '<', $path or croak "open: $!";
3921 binmode $fh or croak "binmode: $!";
3922 while (<$fh>) {
3923 length($_) == 41 or croak "inconsistent size in ($_) != 41";
3924 chomp($_);
3925 ++$r;
3926 next if $_ eq ('0' x 40);
3927 $self->rev_map_set($r, $_);
3928 print "r$r = $_\n";
3930 close $fh or croak "close: $!";
3931 unlink $path or croak "unlink: $!";
3934 sub rebuild {
3935 my ($self) = @_;
3936 my $map_path = $self->map_path;
3937 my $partial = (-e $map_path && ! -z $map_path);
3938 return unless ::verify_ref($self->refname.'^0');
3939 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
3940 my $rev_db = $self->rev_db_path;
3941 $self->rebuild_from_rev_db($rev_db);
3942 if ($self->use_svm_props) {
3943 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
3944 $self->rebuild_from_rev_db($svm_rev_db);
3946 $self->unlink_rev_db_symlink;
3947 return;
3949 print "Rebuilding $map_path ...\n" if (!$partial);
3950 my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
3951 (undef, undef));
3952 my ($log, $ctx) =
3953 command_output_pipe(qw/rev-list --pretty=raw --reverse/,
3954 ($head ? "$head.." : "") . $self->refname,
3955 '--');
3956 my $metadata_url = $self->metadata_url;
3957 remove_username($metadata_url);
3958 my $svn_uuid = $self->rewrite_uuid || $self->ra_uuid;
3959 my $c;
3960 while (<$log>) {
3961 if ( m{^commit ($::sha1)$} ) {
3962 $c = $1;
3963 next;
3965 next unless s{^\s*(git-svn-id:)}{$1};
3966 my ($url, $rev, $uuid) = ::extract_metadata($_);
3967 remove_username($url);
3969 # ignore merges (from set-tree)
3970 next if (!defined $rev || !$uuid);
3972 # if we merged or otherwise started elsewhere, this is
3973 # how we break out of it
3974 if (($uuid ne $svn_uuid) ||
3975 ($metadata_url && $url && ($url ne $metadata_url))) {
3976 next;
3978 if ($partial && $head) {
3979 print "Partial-rebuilding $map_path ...\n";
3980 print "Currently at $base_rev = $head\n";
3981 $head = undef;
3984 $self->rev_map_set($rev, $c);
3985 print "r$rev = $c\n";
3987 command_close_pipe($log, $ctx);
3988 print "Done rebuilding $map_path\n" if (!$partial || !$head);
3989 my $rev_db_path = $self->rev_db_path;
3990 if (-f $self->rev_db_path) {
3991 unlink $self->rev_db_path or croak "unlink: $!";
3993 $self->unlink_rev_db_symlink;
3996 # rev_map:
3997 # Tie::File seems to be prone to offset errors if revisions get sparse,
3998 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
3999 # one of my favorite modules is out :< Next up would be one of the DBM
4000 # modules, but I'm not sure which is most portable...
4002 # This is the replacement for the rev_db format, which was too big
4003 # and inefficient for large repositories with a lot of sparse history
4004 # (mainly tags)
4006 # The format is this:
4007 # - 24 bytes for every record,
4008 # * 4 bytes for the integer representing an SVN revision number
4009 # * 20 bytes representing the sha1 of a git commit
4010 # - No empty padding records like the old format
4011 # (except the last record, which can be overwritten)
4012 # - new records are written append-only since SVN revision numbers
4013 # increase monotonically
4014 # - lookups on SVN revision number are done via a binary search
4015 # - Piping the file to xxd -c24 is a good way of dumping it for
4016 # viewing or editing (piped back through xxd -r), should the need
4017 # ever arise.
4018 # - The last record can be padding revision with an all-zero sha1
4019 # This is used to optimize fetch performance when using multiple
4020 # "fetch" directives in .git/config
4022 # These files are disposable unless noMetadata or useSvmProps is set
4024 sub _rev_map_set {
4025 my ($fh, $rev, $commit) = @_;
4027 binmode $fh or croak "binmode: $!";
4028 my $size = (stat($fh))[7];
4029 ($size % 24) == 0 or croak "inconsistent size: $size";
4031 my $wr_offset = 0;
4032 if ($size > 0) {
4033 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
4034 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
4035 $read == 24 or croak "read only $read bytes (!= 24)";
4036 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
4037 if ($last_commit eq ('0' x40)) {
4038 if ($size >= 48) {
4039 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
4040 $read = sysread($fh, $buf, 24) or
4041 croak "read: $!";
4042 $read == 24 or
4043 croak "read only $read bytes (!= 24)";
4044 ($last_rev, $last_commit) =
4045 unpack(rev_map_fmt, $buf);
4046 if ($last_commit eq ('0' x40)) {
4047 croak "inconsistent .rev_map\n";
4050 if ($last_rev >= $rev) {
4051 croak "last_rev is higher!: $last_rev >= $rev";
4053 $wr_offset = -24;
4056 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
4057 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
4058 croak "write: $!";
4061 sub _rev_map_reset {
4062 my ($fh, $rev, $commit) = @_;
4063 my $c = _rev_map_get($fh, $rev);
4064 $c eq $commit or die "_rev_map_reset(@_) commit $c does not match!\n";
4065 my $offset = sysseek($fh, 0, SEEK_CUR) or croak "seek: $!";
4066 truncate $fh, $offset or croak "truncate: $!";
4069 sub mkfile {
4070 my ($path) = @_;
4071 unless (-e $path) {
4072 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
4073 mkpath([$dir]) unless -d $dir;
4074 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
4075 close $fh or die "Couldn't close (create) $path: $!\n";
4079 sub rev_map_set {
4080 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
4081 defined $commit or die "missing arg3\n";
4082 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
4083 my $db = $self->map_path($uuid);
4084 my $db_lock = "$db.lock";
4085 my $sigmask;
4086 $update_ref ||= 0;
4087 if ($update_ref) {
4088 $sigmask = POSIX::SigSet->new();
4089 my $signew = POSIX::SigSet->new(SIGINT, SIGHUP, SIGTERM,
4090 SIGALRM, SIGUSR1, SIGUSR2);
4091 sigprocmask(SIG_BLOCK, $signew, $sigmask) or
4092 croak "Can't block signals: $!";
4094 mkfile($db);
4096 $LOCKFILES{$db_lock} = 1;
4097 my $sync;
4098 # both of these options make our .rev_db file very, very important
4099 # and we can't afford to lose it because rebuild() won't work
4100 if ($self->use_svm_props || $self->no_metadata) {
4101 $sync = 1;
4102 copy($db, $db_lock) or die "rev_map_set(@_): ",
4103 "Failed to copy: ",
4104 "$db => $db_lock ($!)\n";
4105 } else {
4106 rename $db, $db_lock or die "rev_map_set(@_): ",
4107 "Failed to rename: ",
4108 "$db => $db_lock ($!)\n";
4111 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
4112 or croak "Couldn't open $db_lock: $!\n";
4113 $update_ref eq 'reset' ? _rev_map_reset($fh, $rev, $commit) :
4114 _rev_map_set($fh, $rev, $commit);
4115 if ($sync) {
4116 $fh->flush or die "Couldn't flush $db_lock: $!\n";
4117 $fh->sync or die "Couldn't sync $db_lock: $!\n";
4119 close $fh or croak $!;
4120 if ($update_ref) {
4121 $_head = $self;
4122 my $note = "";
4123 $note = " ($update_ref)" if ($update_ref !~ /^\d*$/);
4124 command_noisy('update-ref', '-m', "r$rev$note",
4125 $self->refname, $commit);
4127 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
4128 "$db_lock => $db ($!)\n";
4129 delete $LOCKFILES{$db_lock};
4130 if ($update_ref) {
4131 sigprocmask(SIG_SETMASK, $sigmask) or
4132 croak "Can't restore signal mask: $!";
4136 # If want_commit, this will return an array of (rev, commit) where
4137 # commit _must_ be a valid commit in the archive.
4138 # Otherwise, it'll return the max revision (whether or not the
4139 # commit is valid or just a 0x40 placeholder).
4140 sub rev_map_max {
4141 my ($self, $want_commit) = @_;
4142 $self->rebuild;
4143 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
4144 $want_commit ? ($r, $c) : $r;
4147 sub rev_map_max_norebuild {
4148 my ($self, $want_commit) = @_;
4149 my $map_path = $self->map_path;
4150 stat $map_path or return $want_commit ? (0, undef) : 0;
4151 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
4152 binmode $fh or croak "binmode: $!";
4153 my $size = (stat($fh))[7];
4154 ($size % 24) == 0 or croak "inconsistent size: $size";
4156 if ($size == 0) {
4157 close $fh or croak "close: $!";
4158 return $want_commit ? (0, undef) : 0;
4161 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
4162 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
4163 my ($r, $c) = unpack(rev_map_fmt, $buf);
4164 if ($want_commit && $c eq ('0' x40)) {
4165 if ($size < 48) {
4166 return $want_commit ? (0, undef) : 0;
4168 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
4169 sysread($fh, $buf, 24) == 24 or croak "read: $!";
4170 ($r, $c) = unpack(rev_map_fmt, $buf);
4171 if ($c eq ('0'x40)) {
4172 croak "Penultimate record is all-zeroes in $map_path";
4175 close $fh or croak "close: $!";
4176 $want_commit ? ($r, $c) : $r;
4179 sub rev_map_get {
4180 my ($self, $rev, $uuid) = @_;
4181 my $map_path = $self->map_path($uuid);
4182 return undef unless -e $map_path;
4184 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
4185 my $c = _rev_map_get($fh, $rev);
4186 close($fh) or croak "close: $!";
4190 sub _rev_map_get {
4191 my ($fh, $rev) = @_;
4193 binmode $fh or croak "binmode: $!";
4194 my $size = (stat($fh))[7];
4195 ($size % 24) == 0 or croak "inconsistent size: $size";
4197 if ($size == 0) {
4198 return undef;
4201 my ($l, $u) = (0, $size - 24);
4202 my ($r, $c, $buf);
4204 while ($l <= $u) {
4205 my $i = int(($l/24 + $u/24) / 2) * 24;
4206 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
4207 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
4208 my ($r, $c) = unpack(rev_map_fmt, $buf);
4210 if ($r < $rev) {
4211 $l = $i + 24;
4212 } elsif ($r > $rev) {
4213 $u = $i - 24;
4214 } else { # $r == $rev
4215 return $c eq ('0' x 40) ? undef : $c;
4218 undef;
4221 # Finds the first svn revision that exists on (if $eq_ok is true) or
4222 # before $rev for the current branch. It will not search any lower
4223 # than $min_rev. Returns the git commit hash and svn revision number
4224 # if found, else (undef, undef).
4225 sub find_rev_before {
4226 my ($self, $rev, $eq_ok, $min_rev) = @_;
4227 --$rev unless $eq_ok;
4228 $min_rev ||= 1;
4229 my $max_rev = $self->rev_map_max;
4230 $rev = $max_rev if ($rev > $max_rev);
4231 while ($rev >= $min_rev) {
4232 if (my $c = $self->rev_map_get($rev)) {
4233 return ($rev, $c);
4235 --$rev;
4237 return (undef, undef);
4240 # Finds the first svn revision that exists on (if $eq_ok is true) or
4241 # after $rev for the current branch. It will not search any higher
4242 # than $max_rev. Returns the git commit hash and svn revision number
4243 # if found, else (undef, undef).
4244 sub find_rev_after {
4245 my ($self, $rev, $eq_ok, $max_rev) = @_;
4246 ++$rev unless $eq_ok;
4247 $max_rev ||= $self->rev_map_max;
4248 while ($rev <= $max_rev) {
4249 if (my $c = $self->rev_map_get($rev)) {
4250 return ($rev, $c);
4252 ++$rev;
4254 return (undef, undef);
4257 sub _new {
4258 my ($class, $repo_id, $ref_id, $path) = @_;
4259 unless (defined $repo_id && length $repo_id) {
4260 $repo_id = $Git::SVN::default_repo_id;
4262 unless (defined $ref_id && length $ref_id) {
4263 $_prefix = '' unless defined($_prefix);
4264 $_[2] = $ref_id =
4265 "refs/remotes/$_prefix$Git::SVN::default_ref_id";
4267 $_[1] = $repo_id;
4268 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
4270 # Older repos imported by us used $GIT_DIR/svn/foo instead of
4271 # $GIT_DIR/svn/refs/remotes/foo when tracking refs/remotes/foo
4272 if ($ref_id =~ m{^refs/remotes/(.*)}) {
4273 my $old_dir = "$ENV{GIT_DIR}/svn/$1";
4274 if (-d $old_dir && ! -d $dir) {
4275 $dir = $old_dir;
4279 $_[3] = $path = '' unless (defined $path);
4280 mkpath([$dir]);
4281 bless {
4282 ref_id => $ref_id, dir => $dir, index => "$dir/index",
4283 path => $path, config => "$ENV{GIT_DIR}/svn/config",
4284 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
4287 # for read-only access of old .rev_db formats
4288 sub unlink_rev_db_symlink {
4289 my ($self) = @_;
4290 my $link = $self->rev_db_path;
4291 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
4292 if (-l $link) {
4293 unlink $link or croak "unlink: $link failed!";
4297 sub rev_db_path {
4298 my ($self, $uuid) = @_;
4299 my $db_path = $self->map_path($uuid);
4300 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
4301 or croak "map_path: $db_path does not contain '/.rev_map.' !";
4302 $db_path;
4305 # the new replacement for .rev_db
4306 sub map_path {
4307 my ($self, $uuid) = @_;
4308 $uuid ||= $self->ra_uuid;
4309 "$self->{map_root}.$uuid";
4312 sub uri_encode {
4313 my ($f) = @_;
4314 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
4318 sub uri_decode {
4319 my ($f) = @_;
4320 $f =~ s#%([0-9a-fA-F]{2})#chr(hex($1))#eg;
4324 sub remove_username {
4325 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
4328 package Git::SVN::Prompt;
4329 use strict;
4330 use warnings;
4331 require SVN::Core;
4332 use vars qw/$_no_auth_cache $_username/;
4334 sub simple {
4335 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
4336 $may_save = undef if $_no_auth_cache;
4337 $default_username = $_username if defined $_username;
4338 if (defined $default_username && length $default_username) {
4339 if (defined $realm && length $realm) {
4340 print STDERR "Authentication realm: $realm\n";
4341 STDERR->flush;
4343 $cred->username($default_username);
4344 } else {
4345 username($cred, $realm, $may_save, $pool);
4347 $cred->password(_read_password("Password for '" .
4348 $cred->username . "': ", $realm));
4349 $cred->may_save($may_save);
4350 $SVN::_Core::SVN_NO_ERROR;
4353 sub ssl_server_trust {
4354 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
4355 $may_save = undef if $_no_auth_cache;
4356 print STDERR "Error validating server certificate for '$realm':\n";
4358 no warnings 'once';
4359 # All variables SVN::Auth::SSL::* are used only once,
4360 # so we're shutting up Perl warnings about this.
4361 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
4362 print STDERR " - The certificate is not issued ",
4363 "by a trusted authority. Use the\n",
4364 " fingerprint to validate ",
4365 "the certificate manually!\n";
4367 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
4368 print STDERR " - The certificate hostname ",
4369 "does not match.\n";
4371 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
4372 print STDERR " - The certificate is not yet valid.\n";
4374 if ($failures & $SVN::Auth::SSL::EXPIRED) {
4375 print STDERR " - The certificate has expired.\n";
4377 if ($failures & $SVN::Auth::SSL::OTHER) {
4378 print STDERR " - The certificate has ",
4379 "an unknown error.\n";
4381 } # no warnings 'once'
4382 printf STDERR
4383 "Certificate information:\n".
4384 " - Hostname: %s\n".
4385 " - Valid: from %s until %s\n".
4386 " - Issuer: %s\n".
4387 " - Fingerprint: %s\n",
4388 map $cert_info->$_, qw(hostname valid_from valid_until
4389 issuer_dname fingerprint);
4390 my $choice;
4391 prompt:
4392 print STDERR $may_save ?
4393 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
4394 "(R)eject or accept (t)emporarily? ";
4395 STDERR->flush;
4396 $choice = lc(substr(<STDIN> || 'R', 0, 1));
4397 if ($choice =~ /^t$/i) {
4398 $cred->may_save(undef);
4399 } elsif ($choice =~ /^r$/i) {
4400 return -1;
4401 } elsif ($may_save && $choice =~ /^p$/i) {
4402 $cred->may_save($may_save);
4403 } else {
4404 goto prompt;
4406 $cred->accepted_failures($failures);
4407 $SVN::_Core::SVN_NO_ERROR;
4410 sub ssl_client_cert {
4411 my ($cred, $realm, $may_save, $pool) = @_;
4412 $may_save = undef if $_no_auth_cache;
4413 print STDERR "Client certificate filename: ";
4414 STDERR->flush;
4415 chomp(my $filename = <STDIN>);
4416 $cred->cert_file($filename);
4417 $cred->may_save($may_save);
4418 $SVN::_Core::SVN_NO_ERROR;
4421 sub ssl_client_cert_pw {
4422 my ($cred, $realm, $may_save, $pool) = @_;
4423 $may_save = undef if $_no_auth_cache;
4424 $cred->password(_read_password("Password: ", $realm));
4425 $cred->may_save($may_save);
4426 $SVN::_Core::SVN_NO_ERROR;
4429 sub username {
4430 my ($cred, $realm, $may_save, $pool) = @_;
4431 $may_save = undef if $_no_auth_cache;
4432 if (defined $realm && length $realm) {
4433 print STDERR "Authentication realm: $realm\n";
4435 my $username;
4436 if (defined $_username) {
4437 $username = $_username;
4438 } else {
4439 print STDERR "Username: ";
4440 STDERR->flush;
4441 chomp($username = <STDIN>);
4443 $cred->username($username);
4444 $cred->may_save($may_save);
4445 $SVN::_Core::SVN_NO_ERROR;
4448 sub _read_password {
4449 my ($prompt, $realm) = @_;
4450 my $password = '';
4451 if (exists $ENV{GIT_ASKPASS}) {
4452 open(PH, "-|", $ENV{GIT_ASKPASS}, $prompt);
4453 $password = <PH>;
4454 $password =~ s/[\012\015]//; # \n\r
4455 close(PH);
4456 } else {
4457 print STDERR $prompt;
4458 STDERR->flush;
4459 require Term::ReadKey;
4460 Term::ReadKey::ReadMode('noecho');
4461 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
4462 last if $key =~ /[\012\015]/; # \n\r
4463 $password .= $key;
4465 Term::ReadKey::ReadMode('restore');
4466 print STDERR "\n";
4467 STDERR->flush;
4469 $password;
4472 package SVN::Git::Fetcher;
4473 use vars qw/@ISA $_ignore_regex $_preserve_empty_dirs $_placeholder_filename
4474 @deleted_gpath %added_placeholder $repo_id/;
4475 use strict;
4476 use warnings;
4477 use Carp qw/croak/;
4478 use File::Basename qw/dirname/;
4479 use IO::File qw//;
4481 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
4482 sub new {
4483 my ($class, $git_svn, $switch_path) = @_;
4484 my $self = SVN::Delta::Editor->new;
4485 bless $self, $class;
4486 if (exists $git_svn->{last_commit}) {
4487 $self->{c} = $git_svn->{last_commit};
4488 $self->{empty_symlinks} =
4489 _mark_empty_symlinks($git_svn, $switch_path);
4492 # some options are read globally, but can be overridden locally
4493 # per [svn-remote "..."] section. Command-line options will *NOT*
4494 # override options set in an [svn-remote "..."] section
4495 $repo_id = $git_svn->{repo_id};
4496 my $k = "svn-remote.$repo_id.ignore-paths";
4497 my $v = eval { command_oneline('config', '--get', $k) };
4498 $self->{ignore_regex} = $v;
4500 $k = "svn-remote.$repo_id.preserve-empty-dirs";
4501 $v = eval { command_oneline('config', '--get', '--bool', $k) };
4502 if ($v && $v eq 'true') {
4503 $_preserve_empty_dirs = 1;
4504 $k = "svn-remote.$repo_id.placeholder-filename";
4505 $v = eval { command_oneline('config', '--get', $k) };
4506 $_placeholder_filename = $v;
4509 # Load the list of placeholder files added during previous invocations.
4510 $k = "svn-remote.$repo_id.added-placeholder";
4511 $v = eval { command_oneline('config', '--get-all', $k) };
4512 if ($_preserve_empty_dirs && $v) {
4513 # command() prints errors to stderr, so we only call it if
4514 # command_oneline() succeeded.
4515 my @v = command('config', '--get-all', $k);
4516 $added_placeholder{ dirname($_) } = $_ foreach @v;
4519 $self->{empty} = {};
4520 $self->{dir_prop} = {};
4521 $self->{file_prop} = {};
4522 $self->{absent_dir} = {};
4523 $self->{absent_file} = {};
4524 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
4525 $self->{pathnameencoding} = Git::config('svn.pathnameencoding');
4526 $self;
4529 # this uses the Ra object, so it must be called before do_{switch,update},
4530 # not inside them (when the Git::SVN::Fetcher object is passed) to
4531 # do_{switch,update}
4532 sub _mark_empty_symlinks {
4533 my ($git_svn, $switch_path) = @_;
4534 my $bool = Git::config_bool('svn.brokenSymlinkWorkaround');
4535 return {} if (!defined($bool)) || (defined($bool) && ! $bool);
4537 my %ret;
4538 my ($rev, $cmt) = $git_svn->last_rev_commit;
4539 return {} unless ($rev && $cmt);
4541 # allow the warning to be printed for each revision we fetch to
4542 # ensure the user sees it. The user can also disable the workaround
4543 # on the repository even while git svn is running and the next
4544 # revision fetched will skip this expensive function.
4545 my $printed_warning;
4546 chomp(my $empty_blob = `git hash-object -t blob --stdin < /dev/null`);
4547 my ($ls, $ctx) = command_output_pipe(qw/ls-tree -r -z/, $cmt);
4548 local $/ = "\0";
4549 my $pfx = defined($switch_path) ? $switch_path : $git_svn->{path};
4550 $pfx .= '/' if length($pfx);
4551 while (<$ls>) {
4552 chomp;
4553 s/\A100644 blob $empty_blob\t//o or next;
4554 unless ($printed_warning) {
4555 print STDERR "Scanning for empty symlinks, ",
4556 "this may take a while if you have ",
4557 "many empty files\n",
4558 "You may disable this with `",
4559 "git config svn.brokenSymlinkWorkaround ",
4560 "false'.\n",
4561 "This may be done in a different ",
4562 "terminal without restarting ",
4563 "git svn\n";
4564 $printed_warning = 1;
4566 my $path = $_;
4567 my (undef, $props) =
4568 $git_svn->ra->get_file($pfx.$path, $rev, undef);
4569 if ($props->{'svn:special'}) {
4570 $ret{$path} = 1;
4573 command_close_pipe($ls, $ctx);
4574 \%ret;
4577 # returns true if a given path is inside a ".git" directory
4578 sub in_dot_git {
4579 $_[0] =~ m{(?:^|/)\.git(?:/|$)};
4582 # return value: 0 -- don't ignore, 1 -- ignore
4583 sub is_path_ignored {
4584 my ($self, $path) = @_;
4585 return 1 if in_dot_git($path);
4586 return 1 if defined($self->{ignore_regex}) &&
4587 $path =~ m!$self->{ignore_regex}!;
4588 return 0 unless defined($_ignore_regex);
4589 return 1 if $path =~ m!$_ignore_regex!o;
4590 return 0;
4593 sub set_path_strip {
4594 my ($self, $path) = @_;
4595 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
4598 sub open_root {
4599 { path => '' };
4602 sub open_directory {
4603 my ($self, $path, $pb, $rev) = @_;
4604 { path => $path };
4607 sub git_path {
4608 my ($self, $path) = @_;
4609 if (my $enc = $self->{pathnameencoding}) {
4610 require Encode;
4611 Encode::from_to($path, 'UTF-8', $enc);
4613 if ($self->{path_strip}) {
4614 $path =~ s!$self->{path_strip}!! or
4615 die "Failed to strip path '$path' ($self->{path_strip})\n";
4617 $path;
4620 sub delete_entry {
4621 my ($self, $path, $rev, $pb) = @_;
4622 return undef if $self->is_path_ignored($path);
4624 my $gpath = $self->git_path($path);
4625 return undef if ($gpath eq '');
4627 # remove entire directories.
4628 my ($tree) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
4629 =~ /\A040000 tree ([a-f\d]{40})\t\Q$gpath\E\0/);
4630 if ($tree) {
4631 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
4632 -r --name-only -z/,
4633 $tree);
4634 local $/ = "\0";
4635 while (<$ls>) {
4636 chomp;
4637 my $rmpath = "$gpath/$_";
4638 $self->{gii}->remove($rmpath);
4639 print "\tD\t$rmpath\n" unless $::_q;
4641 print "\tD\t$gpath/\n" unless $::_q;
4642 command_close_pipe($ls, $ctx);
4643 } else {
4644 $self->{gii}->remove($gpath);
4645 print "\tD\t$gpath\n" unless $::_q;
4647 # Don't add to @deleted_gpath if we're deleting a placeholder file.
4648 push @deleted_gpath, $gpath unless $added_placeholder{dirname($path)};
4649 $self->{empty}->{$path} = 0;
4650 undef;
4653 sub open_file {
4654 my ($self, $path, $pb, $rev) = @_;
4655 my ($mode, $blob);
4657 goto out if $self->is_path_ignored($path);
4659 my $gpath = $self->git_path($path);
4660 ($mode, $blob) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
4661 =~ /\A(\d{6}) blob ([a-f\d]{40})\t\Q$gpath\E\0/);
4662 unless (defined $mode && defined $blob) {
4663 die "$path was not found in commit $self->{c} (r$rev)\n";
4665 if ($mode eq '100644' && $self->{empty_symlinks}->{$path}) {
4666 $mode = '120000';
4668 out:
4669 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
4670 pool => SVN::Pool->new, action => 'M' };
4673 sub add_file {
4674 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
4675 my $mode;
4677 if (!$self->is_path_ignored($path)) {
4678 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
4679 delete $self->{empty}->{$dir};
4680 $mode = '100644';
4682 if ($added_placeholder{$dir}) {
4683 # Remove our placeholder file, if we created one.
4684 delete_entry($self, $added_placeholder{$dir})
4685 unless $path eq $added_placeholder{$dir};
4686 delete $added_placeholder{$dir}
4690 { path => $path, mode_a => $mode, mode_b => $mode,
4691 pool => SVN::Pool->new, action => 'A' };
4694 sub add_directory {
4695 my ($self, $path, $cp_path, $cp_rev) = @_;
4696 goto out if $self->is_path_ignored($path);
4697 my $gpath = $self->git_path($path);
4698 if ($gpath eq '') {
4699 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
4700 -r --name-only -z/,
4701 $self->{c});
4702 local $/ = "\0";
4703 while (<$ls>) {
4704 chomp;
4705 $self->{gii}->remove($_);
4706 print "\tD\t$_\n" unless $::_q;
4707 push @deleted_gpath, $gpath;
4709 command_close_pipe($ls, $ctx);
4710 $self->{empty}->{$path} = 0;
4712 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
4713 delete $self->{empty}->{$dir};
4714 $self->{empty}->{$path} = 1;
4716 if ($added_placeholder{$dir}) {
4717 # Remove our placeholder file, if we created one.
4718 delete_entry($self, $added_placeholder{$dir});
4719 delete $added_placeholder{$dir}
4722 out:
4723 { path => $path };
4726 sub change_dir_prop {
4727 my ($self, $db, $prop, $value) = @_;
4728 return undef if $self->is_path_ignored($db->{path});
4729 $self->{dir_prop}->{$db->{path}} ||= {};
4730 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
4731 undef;
4734 sub absent_directory {
4735 my ($self, $path, $pb) = @_;
4736 return undef if $self->is_path_ignored($path);
4737 $self->{absent_dir}->{$pb->{path}} ||= [];
4738 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
4739 undef;
4742 sub absent_file {
4743 my ($self, $path, $pb) = @_;
4744 return undef if $self->is_path_ignored($path);
4745 $self->{absent_file}->{$pb->{path}} ||= [];
4746 push @{$self->{absent_file}->{$pb->{path}}}, $path;
4747 undef;
4750 sub change_file_prop {
4751 my ($self, $fb, $prop, $value) = @_;
4752 return undef if $self->is_path_ignored($fb->{path});
4753 if ($prop eq 'svn:executable') {
4754 if ($fb->{mode_b} != 120000) {
4755 $fb->{mode_b} = defined $value ? 100755 : 100644;
4757 } elsif ($prop eq 'svn:special') {
4758 $fb->{mode_b} = defined $value ? 120000 : 100644;
4759 } else {
4760 $self->{file_prop}->{$fb->{path}} ||= {};
4761 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
4763 undef;
4766 sub apply_textdelta {
4767 my ($self, $fb, $exp) = @_;
4768 return undef if $self->is_path_ignored($fb->{path});
4769 my $fh = $::_repository->temp_acquire('svn_delta');
4770 # $fh gets auto-closed() by SVN::TxDelta::apply(),
4771 # (but $base does not,) so dup() it for reading in close_file
4772 open my $dup, '<&', $fh or croak $!;
4773 my $base = $::_repository->temp_acquire('git_blob');
4775 if ($fb->{blob}) {
4776 my ($base_is_link, $size);
4778 if ($fb->{mode_a} eq '120000' &&
4779 ! $self->{empty_symlinks}->{$fb->{path}}) {
4780 print $base 'link ' or die "print $!\n";
4781 $base_is_link = 1;
4783 retry:
4784 $size = $::_repository->cat_blob($fb->{blob}, $base);
4785 die "Failed to read object $fb->{blob}" if ($size < 0);
4787 if (defined $exp) {
4788 seek $base, 0, 0 or croak $!;
4789 my $got = ::md5sum($base);
4790 if ($got ne $exp) {
4791 my $err = "Checksum mismatch: ".
4792 "$fb->{path} $fb->{blob}\n" .
4793 "expected: $exp\n" .
4794 " got: $got\n";
4795 if ($base_is_link) {
4796 warn $err,
4797 "Retrying... (possibly ",
4798 "a bad symlink from SVN)\n";
4799 $::_repository->temp_reset($base);
4800 $base_is_link = 0;
4801 goto retry;
4803 die $err;
4807 seek $base, 0, 0 or croak $!;
4808 $fb->{fh} = $fh;
4809 $fb->{base} = $base;
4810 [ SVN::TxDelta::apply($base, $dup, undef, $fb->{path}, $fb->{pool}) ];
4813 sub close_file {
4814 my ($self, $fb, $exp) = @_;
4815 return undef if $self->is_path_ignored($fb->{path});
4817 my $hash;
4818 my $path = $self->git_path($fb->{path});
4819 if (my $fh = $fb->{fh}) {
4820 if (defined $exp) {
4821 seek($fh, 0, 0) or croak $!;
4822 my $got = ::md5sum($fh);
4823 if ($got ne $exp) {
4824 die "Checksum mismatch: $path\n",
4825 "expected: $exp\n got: $got\n";
4828 if ($fb->{mode_b} == 120000) {
4829 sysseek($fh, 0, 0) or croak $!;
4830 my $rd = sysread($fh, my $buf, 5);
4832 if (!defined $rd) {
4833 croak "sysread: $!\n";
4834 } elsif ($rd == 0) {
4835 warn "$path has mode 120000",
4836 " but it points to nothing\n",
4837 "converting to an empty file with mode",
4838 " 100644\n";
4839 $fb->{mode_b} = '100644';
4840 } elsif ($buf ne 'link ') {
4841 warn "$path has mode 120000",
4842 " but is not a link\n";
4843 } else {
4844 my $tmp_fh = $::_repository->temp_acquire(
4845 'svn_hash');
4846 my $res;
4847 while ($res = sysread($fh, my $str, 1024)) {
4848 my $out = syswrite($tmp_fh, $str, $res);
4849 defined($out) && $out == $res
4850 or croak("write ",
4851 Git::temp_path($tmp_fh),
4852 ": $!\n");
4854 defined $res or croak $!;
4856 ($fh, $tmp_fh) = ($tmp_fh, $fh);
4857 Git::temp_release($tmp_fh, 1);
4861 $hash = $::_repository->hash_and_insert_object(
4862 Git::temp_path($fh));
4863 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
4865 Git::temp_release($fb->{base}, 1);
4866 Git::temp_release($fh, 1);
4867 } else {
4868 $hash = $fb->{blob} or die "no blob information\n";
4870 $fb->{pool}->clear;
4871 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
4872 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
4873 undef;
4876 sub abort_edit {
4877 my $self = shift;
4878 $self->{nr} = $self->{gii}->{nr};
4879 delete $self->{gii};
4880 $self->SUPER::abort_edit(@_);
4883 sub close_edit {
4884 my $self = shift;
4886 if ($_preserve_empty_dirs) {
4887 my @empty_dirs;
4889 # Any entry flagged as empty that also has an associated
4890 # dir_prop represents a newly created empty directory.
4891 foreach my $i (keys %{$self->{empty}}) {
4892 push @empty_dirs, $i if exists $self->{dir_prop}->{$i};
4895 # Search for directories that have become empty due subsequent
4896 # file deletes.
4897 push @empty_dirs, $self->find_empty_directories();
4899 # Finally, add a placeholder file to each empty directory.
4900 $self->add_placeholder_file($_) foreach (@empty_dirs);
4902 $self->stash_placeholder_list();
4905 $self->{git_commit_ok} = 1;
4906 $self->{nr} = $self->{gii}->{nr};
4907 delete $self->{gii};
4908 $self->SUPER::close_edit(@_);
4911 sub find_empty_directories {
4912 my ($self) = @_;
4913 my @empty_dirs;
4914 my %dirs = map { dirname($_) => 1 } @deleted_gpath;
4916 foreach my $dir (sort keys %dirs) {
4917 next if $dir eq ".";
4919 # If there have been any additions to this directory, there is
4920 # no reason to check if it is empty.
4921 my $skip_added = 0;
4922 foreach my $t (qw/dir_prop file_prop/) {
4923 foreach my $path (keys %{ $self->{$t} }) {
4924 if (exists $self->{$t}->{dirname($path)}) {
4925 $skip_added = 1;
4926 last;
4929 last if $skip_added;
4931 next if $skip_added;
4933 # Use `git ls-tree` to get the filenames of this directory
4934 # that existed prior to this particular commit.
4935 my $ls = command('ls-tree', '-z', '--name-only',
4936 $self->{c}, "$dir/");
4937 my %files = map { $_ => 1 } split(/\0/, $ls);
4939 # Remove the filenames that were deleted during this commit.
4940 delete $files{$_} foreach (@deleted_gpath);
4942 # Report the directory if there are no filenames left.
4943 push @empty_dirs, $dir unless (scalar %files);
4945 @empty_dirs;
4948 sub add_placeholder_file {
4949 my ($self, $dir) = @_;
4950 my $path = "$dir/$_placeholder_filename";
4951 my $gpath = $self->git_path($path);
4953 my $fh = $::_repository->temp_acquire($gpath);
4954 my $hash = $::_repository->hash_and_insert_object(Git::temp_path($fh));
4955 Git::temp_release($fh, 1);
4956 $self->{gii}->update('100644', $hash, $gpath) or croak $!;
4958 # The directory should no longer be considered empty.
4959 delete $self->{empty}->{$dir} if exists $self->{empty}->{$dir};
4961 # Keep track of any placeholder files we create.
4962 $added_placeholder{$dir} = $path;
4965 sub stash_placeholder_list {
4966 my ($self) = @_;
4967 my $k = "svn-remote.$repo_id.added-placeholder";
4968 my $v = eval { command_oneline('config', '--get-all', $k) };
4969 command_noisy('config', '--unset-all', $k) if $v;
4970 foreach (values %added_placeholder) {
4971 command_noisy('config', '--add', $k, $_);
4975 package SVN::Git::Editor;
4976 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
4977 use strict;
4978 use warnings;
4979 use Carp qw/croak/;
4980 use IO::File;
4982 sub new {
4983 my ($class, $opts) = @_;
4984 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
4985 die "$_ required!\n" unless (defined $opts->{$_});
4988 my $pool = SVN::Pool->new;
4989 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
4990 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
4991 $opts->{r}, $mods);
4993 # $opts->{ra} functions should not be used after this:
4994 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
4995 $opts->{editor_cb}, $pool);
4996 my $self = SVN::Delta::Editor->new(@ce, $pool);
4997 bless $self, $class;
4998 foreach (qw/svn_path r tree_a tree_b/) {
4999 $self->{$_} = $opts->{$_};
5001 $self->{url} = $opts->{ra}->{url};
5002 $self->{mods} = $mods;
5003 $self->{types} = $types;
5004 $self->{pool} = $pool;
5005 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
5006 $self->{rm} = { };
5007 $self->{path_prefix} = length $self->{svn_path} ?
5008 "$self->{svn_path}/" : '';
5009 $self->{config} = $opts->{config};
5010 $self->{mergeinfo} = $opts->{mergeinfo};
5011 return $self;
5014 sub generate_diff {
5015 my ($tree_a, $tree_b) = @_;
5016 my @diff_tree = qw(diff-tree -z -r);
5017 if ($_cp_similarity) {
5018 push @diff_tree, "-C$_cp_similarity";
5019 } else {
5020 push @diff_tree, '-C';
5022 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
5023 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
5024 push @diff_tree, $tree_a, $tree_b;
5025 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
5026 local $/ = "\0";
5027 my $state = 'meta';
5028 my @mods;
5029 while (<$diff_fh>) {
5030 chomp $_; # this gets rid of the trailing "\0"
5031 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
5032 ($::sha1)\s($::sha1)\s
5033 ([MTCRAD])\d*$/xo) {
5034 push @mods, { mode_a => $1, mode_b => $2,
5035 sha1_a => $3, sha1_b => $4,
5036 chg => $5 };
5037 if ($5 =~ /^(?:C|R)$/) {
5038 $state = 'file_a';
5039 } else {
5040 $state = 'file_b';
5042 } elsif ($state eq 'file_a') {
5043 my $x = $mods[$#mods] or croak "Empty array\n";
5044 if ($x->{chg} !~ /^(?:C|R)$/) {
5045 croak "Error parsing $_, $x->{chg}\n";
5047 $x->{file_a} = $_;
5048 $state = 'file_b';
5049 } elsif ($state eq 'file_b') {
5050 my $x = $mods[$#mods] or croak "Empty array\n";
5051 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
5052 croak "Error parsing $_, $x->{chg}\n";
5054 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
5055 croak "Error parsing $_, $x->{chg}\n";
5057 $x->{file_b} = $_;
5058 $state = 'meta';
5059 } else {
5060 croak "Error parsing $_\n";
5063 command_close_pipe($diff_fh, $ctx);
5064 \@mods;
5067 sub check_diff_paths {
5068 my ($ra, $pfx, $rev, $mods) = @_;
5069 my %types;
5070 $pfx .= '/' if length $pfx;
5072 sub type_diff_paths {
5073 my ($ra, $types, $path, $rev) = @_;
5074 my @p = split m#/+#, $path;
5075 my $c = shift @p;
5076 unless (defined $types->{$c}) {
5077 $types->{$c} = $ra->check_path($c, $rev);
5079 while (@p) {
5080 $c .= '/' . shift @p;
5081 next if defined $types->{$c};
5082 $types->{$c} = $ra->check_path($c, $rev);
5086 foreach my $m (@$mods) {
5087 foreach my $f (qw/file_a file_b/) {
5088 next unless defined $m->{$f};
5089 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
5090 if (length $pfx.$dir && ! defined $types{$dir}) {
5091 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
5095 \%types;
5098 sub split_path {
5099 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
5102 sub repo_path {
5103 my ($self, $path) = @_;
5104 if (my $enc = $self->{pathnameencoding}) {
5105 require Encode;
5106 Encode::from_to($path, $enc, 'UTF-8');
5108 $self->{path_prefix}.(defined $path ? $path : '');
5111 sub url_path {
5112 my ($self, $path) = @_;
5113 if ($self->{url} =~ m#^https?://#) {
5114 $path =~ s!([^~a-zA-Z0-9_./-])!uc sprintf("%%%02x",ord($1))!eg;
5116 $self->{url} . '/' . $self->repo_path($path);
5119 sub rmdirs {
5120 my ($self) = @_;
5121 my $rm = $self->{rm};
5122 delete $rm->{''}; # we never delete the url we're tracking
5123 return unless %$rm;
5125 foreach (keys %$rm) {
5126 my @d = split m#/#, $_;
5127 my $c = shift @d;
5128 $rm->{$c} = 1;
5129 while (@d) {
5130 $c .= '/' . shift @d;
5131 $rm->{$c} = 1;
5134 delete $rm->{$self->{svn_path}};
5135 delete $rm->{''}; # we never delete the url we're tracking
5136 return unless %$rm;
5138 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
5139 $self->{tree_b});
5140 local $/ = "\0";
5141 while (<$fh>) {
5142 chomp;
5143 my @dn = split m#/#, $_;
5144 while (pop @dn) {
5145 delete $rm->{join '/', @dn};
5147 unless (%$rm) {
5148 close $fh;
5149 return;
5152 command_close_pipe($fh, $ctx);
5154 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
5155 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
5156 $self->close_directory($bat->{$d}, $p);
5157 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
5158 print "\tD+\t$d/\n" unless $::_q;
5159 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
5160 delete $bat->{$d};
5164 sub open_or_add_dir {
5165 my ($self, $full_path, $baton, $deletions) = @_;
5166 my $t = $self->{types}->{$full_path};
5167 if (!defined $t) {
5168 die "$full_path not known in r$self->{r} or we have a bug!\n";
5171 no warnings 'once';
5172 # SVN::Node::none and SVN::Node::file are used only once,
5173 # so we're shutting up Perl's warnings about them.
5174 if ($t == $SVN::Node::none || defined($deletions->{$full_path})) {
5175 return $self->add_directory($full_path, $baton,
5176 undef, -1, $self->{pool});
5177 } elsif ($t == $SVN::Node::dir) {
5178 return $self->open_directory($full_path, $baton,
5179 $self->{r}, $self->{pool});
5180 } # no warnings 'once'
5181 print STDERR "$full_path already exists in repository at ",
5182 "r$self->{r} and it is not a directory (",
5183 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
5184 } # no warnings 'once'
5185 exit 1;
5188 sub ensure_path {
5189 my ($self, $path, $deletions) = @_;
5190 my $bat = $self->{bat};
5191 my $repo_path = $self->repo_path($path);
5192 return $bat->{''} unless (length $repo_path);
5194 my @p = split m#/+#, $repo_path;
5195 my $c = shift @p;
5196 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''}, $deletions);
5197 while (@p) {
5198 my $c0 = $c;
5199 $c .= '/' . shift @p;
5200 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0}, $deletions);
5202 return $bat->{$c};
5205 # Subroutine to convert a globbing pattern to a regular expression.
5206 # From perl cookbook.
5207 sub glob2pat {
5208 my $globstr = shift;
5209 my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
5210 $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
5211 return '^' . $globstr . '$';
5214 sub check_autoprop {
5215 my ($self, $pattern, $properties, $file, $fbat) = @_;
5216 # Convert the globbing pattern to a regular expression.
5217 my $regex = glob2pat($pattern);
5218 # Check if the pattern matches the file name.
5219 if($file =~ m/($regex)/) {
5220 # Parse the list of properties to set.
5221 my @props = split(/;/, $properties);
5222 foreach my $prop (@props) {
5223 # Parse 'name=value' syntax and set the property.
5224 if ($prop =~ /([^=]+)=(.*)/) {
5225 my ($n,$v) = ($1,$2);
5226 for ($n, $v) {
5227 s/^\s+//; s/\s+$//;
5229 $self->change_file_prop($fbat, $n, $v);
5235 sub apply_autoprops {
5236 my ($self, $file, $fbat) = @_;
5237 my $conf_t = ${$self->{config}}{'config'};
5238 no warnings 'once';
5239 # Check [miscellany]/enable-auto-props in svn configuration.
5240 if (SVN::_Core::svn_config_get_bool(
5241 $conf_t,
5242 $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
5243 $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
5244 0)) {
5245 # Auto-props are enabled. Enumerate them to look for matches.
5246 my $callback = sub {
5247 $self->check_autoprop($_[0], $_[1], $file, $fbat);
5249 SVN::_Core::svn_config_enumerate(
5250 $conf_t,
5251 $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
5252 $callback);
5256 sub A {
5257 my ($self, $m, $deletions) = @_;
5258 my ($dir, $file) = split_path($m->{file_b});
5259 my $pbat = $self->ensure_path($dir, $deletions);
5260 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
5261 undef, -1);
5262 print "\tA\t$m->{file_b}\n" unless $::_q;
5263 $self->apply_autoprops($file, $fbat);
5264 $self->chg_file($fbat, $m);
5265 $self->close_file($fbat,undef,$self->{pool});
5268 sub C {
5269 my ($self, $m, $deletions) = @_;
5270 my ($dir, $file) = split_path($m->{file_b});
5271 my $pbat = $self->ensure_path($dir, $deletions);
5272 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
5273 $self->url_path($m->{file_a}), $self->{r});
5274 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
5275 $self->chg_file($fbat, $m);
5276 $self->close_file($fbat,undef,$self->{pool});
5279 sub delete_entry {
5280 my ($self, $path, $pbat) = @_;
5281 my $rpath = $self->repo_path($path);
5282 my ($dir, $file) = split_path($rpath);
5283 $self->{rm}->{$dir} = 1;
5284 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
5287 sub R {
5288 my ($self, $m, $deletions) = @_;
5289 my ($dir, $file) = split_path($m->{file_b});
5290 my $pbat = $self->ensure_path($dir, $deletions);
5291 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
5292 $self->url_path($m->{file_a}), $self->{r});
5293 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
5294 $self->apply_autoprops($file, $fbat);
5295 $self->chg_file($fbat, $m);
5296 $self->close_file($fbat,undef,$self->{pool});
5298 ($dir, $file) = split_path($m->{file_a});
5299 $pbat = $self->ensure_path($dir, $deletions);
5300 $self->delete_entry($m->{file_a}, $pbat);
5303 sub M {
5304 my ($self, $m, $deletions) = @_;
5305 my ($dir, $file) = split_path($m->{file_b});
5306 my $pbat = $self->ensure_path($dir, $deletions);
5307 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
5308 $pbat,$self->{r},$self->{pool});
5309 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
5310 $self->chg_file($fbat, $m);
5311 $self->close_file($fbat,undef,$self->{pool});
5314 sub T { shift->M(@_) }
5316 sub change_file_prop {
5317 my ($self, $fbat, $pname, $pval) = @_;
5318 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
5321 sub change_dir_prop {
5322 my ($self, $pbat, $pname, $pval) = @_;
5323 $self->SUPER::change_dir_prop($pbat, $pname, $pval, $self->{pool});
5326 sub _chg_file_get_blob ($$$$) {
5327 my ($self, $fbat, $m, $which) = @_;
5328 my $fh = $::_repository->temp_acquire("git_blob_$which");
5329 if ($m->{"mode_$which"} =~ /^120/) {
5330 print $fh 'link ' or croak $!;
5331 $self->change_file_prop($fbat,'svn:special','*');
5332 } elsif ($m->{mode_a} =~ /^120/ && $m->{"mode_$which"} !~ /^120/) {
5333 $self->change_file_prop($fbat,'svn:special',undef);
5335 my $blob = $m->{"sha1_$which"};
5336 return ($fh,) if ($blob =~ /^0{40}$/);
5337 my $size = $::_repository->cat_blob($blob, $fh);
5338 croak "Failed to read object $blob" if ($size < 0);
5339 $fh->flush == 0 or croak $!;
5340 seek $fh, 0, 0 or croak $!;
5342 my $exp = ::md5sum($fh);
5343 seek $fh, 0, 0 or croak $!;
5344 return ($fh, $exp);
5347 sub chg_file {
5348 my ($self, $fbat, $m) = @_;
5349 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
5350 $self->change_file_prop($fbat,'svn:executable','*');
5351 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
5352 $self->change_file_prop($fbat,'svn:executable',undef);
5354 my ($fh_a, $exp_a) = _chg_file_get_blob $self, $fbat, $m, 'a';
5355 my ($fh_b, $exp_b) = _chg_file_get_blob $self, $fbat, $m, 'b';
5356 my $pool = SVN::Pool->new;
5357 my $atd = $self->apply_textdelta($fbat, $exp_a, $pool);
5358 if (-s $fh_a) {
5359 my $txstream = SVN::TxDelta::new ($fh_a, $fh_b, $pool);
5360 my $res = SVN::TxDelta::send_txstream($txstream, @$atd, $pool);
5361 if (defined $res) {
5362 die "Unexpected result from send_txstream: $res\n",
5363 "(SVN::Core::VERSION: $SVN::Core::VERSION)\n";
5365 } else {
5366 my $got = SVN::TxDelta::send_stream($fh_b, @$atd, $pool);
5367 die "Checksum mismatch\nexpected: $exp_b\ngot: $got\n"
5368 if ($got ne $exp_b);
5370 Git::temp_release($fh_b, 1);
5371 Git::temp_release($fh_a, 1);
5372 $pool->clear;
5375 sub D {
5376 my ($self, $m, $deletions) = @_;
5377 my ($dir, $file) = split_path($m->{file_b});
5378 my $pbat = $self->ensure_path($dir, $deletions);
5379 print "\tD\t$m->{file_b}\n" unless $::_q;
5380 $self->delete_entry($m->{file_b}, $pbat);
5383 sub close_edit {
5384 my ($self) = @_;
5385 my ($p,$bat) = ($self->{pool}, $self->{bat});
5386 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
5387 next if $_ eq '';
5388 $self->close_directory($bat->{$_}, $p);
5390 $self->close_directory($bat->{''}, $p);
5391 $self->SUPER::close_edit($p);
5392 $p->clear;
5395 sub abort_edit {
5396 my ($self) = @_;
5397 $self->SUPER::abort_edit($self->{pool});
5400 sub DESTROY {
5401 my $self = shift;
5402 $self->SUPER::DESTROY(@_);
5403 $self->{pool}->clear;
5406 # this drives the editor
5407 sub apply_diff {
5408 my ($self) = @_;
5409 my $mods = $self->{mods};
5410 my %o = ( D => 0, C => 1, R => 2, A => 3, M => 4, T => 5 );
5411 my %deletions;
5413 foreach my $m (@$mods) {
5414 if ($m->{chg} eq "D") {
5415 $deletions{$m->{file_b}} = 1;
5419 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
5420 my $f = $m->{chg};
5421 if (defined $o{$f}) {
5422 $self->$f($m, \%deletions);
5423 } else {
5424 fatal("Invalid change type: $f");
5428 if (defined($self->{mergeinfo})) {
5429 $self->change_dir_prop($self->{bat}{''}, "svn:mergeinfo",
5430 $self->{mergeinfo});
5432 $self->rmdirs if $_rmdir;
5433 if (@$mods == 0 && !defined($self->{mergeinfo})) {
5434 $self->abort_edit;
5435 } else {
5436 $self->close_edit;
5438 return scalar @$mods;
5441 package Git::SVN::Ra;
5442 use vars qw/@ISA $config_dir $_ignore_refs_regex $_log_window_size/;
5443 use strict;
5444 use warnings;
5445 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
5447 BEGIN {
5448 # enforce temporary pool usage for some simple functions
5449 no strict 'refs';
5450 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root
5451 get_file/) {
5452 my $SUPER = "SUPER::$f";
5453 *$f = sub {
5454 my $self = shift;
5455 my $pool = SVN::Pool->new;
5456 my @ret = $self->$SUPER(@_,$pool);
5457 $pool->clear;
5458 wantarray ? @ret : $ret[0];
5463 sub _auth_providers () {
5464 my @rv = (
5465 SVN::Client::get_simple_provider(),
5466 SVN::Client::get_ssl_server_trust_file_provider(),
5467 SVN::Client::get_simple_prompt_provider(
5468 \&Git::SVN::Prompt::simple, 2),
5469 SVN::Client::get_ssl_client_cert_file_provider(),
5470 SVN::Client::get_ssl_client_cert_prompt_provider(
5471 \&Git::SVN::Prompt::ssl_client_cert, 2),
5472 SVN::Client::get_ssl_client_cert_pw_file_provider(),
5473 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
5474 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
5475 SVN::Client::get_username_provider(),
5476 SVN::Client::get_ssl_server_trust_prompt_provider(
5477 \&Git::SVN::Prompt::ssl_server_trust),
5478 SVN::Client::get_username_prompt_provider(
5479 \&Git::SVN::Prompt::username, 2)
5482 # earlier 1.6.x versions would segfault, and <= 1.5.x didn't have
5483 # this function
5484 if (::compare_svn_version('1.6.12') > 0) {
5485 my $config = SVN::Core::config_get_config($config_dir);
5486 my ($p, @a);
5487 # config_get_config returns all config files from
5488 # ~/.subversion, auth_get_platform_specific_client_providers
5489 # just wants the config "file".
5490 @a = ($config->{'config'}, undef);
5491 $p = SVN::Core::auth_get_platform_specific_client_providers(@a);
5492 # Insert the return value from
5493 # auth_get_platform_specific_providers
5494 unshift @rv, @$p;
5496 \@rv;
5499 sub escape_uri_only {
5500 my ($uri) = @_;
5501 my @tmp;
5502 foreach (split m{/}, $uri) {
5503 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
5504 push @tmp, $_;
5506 join('/', @tmp);
5509 sub escape_url {
5510 my ($url) = @_;
5511 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
5512 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
5513 $url = "$scheme://$domain$uri";
5515 $url;
5518 sub new {
5519 my ($class, $url) = @_;
5520 $url =~ s!/+$!!;
5521 return $RA if ($RA && $RA->{url} eq $url);
5523 ::_req_svn();
5525 SVN::_Core::svn_config_ensure($config_dir, undef);
5526 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
5527 my $config = SVN::Core::config_get_config($config_dir);
5528 $RA = undef;
5529 my $dont_store_passwords = 1;
5530 my $conf_t = ${$config}{'config'};
5532 no warnings 'once';
5533 # The usage of $SVN::_Core::SVN_CONFIG_* variables
5534 # produces warnings that variables are used only once.
5535 # I had not found the better way to shut them up, so
5536 # the warnings of type 'once' are disabled in this block.
5537 if (SVN::_Core::svn_config_get_bool($conf_t,
5538 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
5539 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
5540 1) == 0) {
5541 SVN::_Core::svn_auth_set_parameter($baton,
5542 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
5543 bless (\$dont_store_passwords, "_p_void"));
5545 if (SVN::_Core::svn_config_get_bool($conf_t,
5546 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
5547 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
5548 1) == 0) {
5549 $Git::SVN::Prompt::_no_auth_cache = 1;
5551 } # no warnings 'once'
5552 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
5553 config => $config,
5554 pool => SVN::Pool->new,
5555 auth_provider_callbacks => $callbacks);
5556 $self->{url} = $url;
5557 $self->{svn_path} = $url;
5558 $self->{repos_root} = $self->get_repos_root;
5559 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
5560 $self->{cache} = { check_path => { r => 0, data => {} },
5561 get_dir => { r => 0, data => {} } };
5562 $RA = bless $self, $class;
5565 sub check_path {
5566 my ($self, $path, $r) = @_;
5567 my $cache = $self->{cache}->{check_path};
5568 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
5569 return $cache->{data}->{$path};
5571 my $pool = SVN::Pool->new;
5572 my $t = $self->SUPER::check_path($path, $r, $pool);
5573 $pool->clear;
5574 if ($r != $cache->{r}) {
5575 %{$cache->{data}} = ();
5576 $cache->{r} = $r;
5578 $cache->{data}->{$path} = $t;
5581 sub get_dir {
5582 my ($self, $dir, $r) = @_;
5583 my $cache = $self->{cache}->{get_dir};
5584 if ($r == $cache->{r}) {
5585 if (my $x = $cache->{data}->{$dir}) {
5586 return wantarray ? @$x : $x->[0];
5589 my $pool = SVN::Pool->new;
5590 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
5591 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
5592 $pool->clear;
5593 if ($r != $cache->{r}) {
5594 %{$cache->{data}} = ();
5595 $cache->{r} = $r;
5597 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
5598 wantarray ? (\%dirents, $r, $props) : \%dirents;
5601 sub DESTROY {
5602 # do not call the real DESTROY since we store ourselves in $RA
5605 # get_log(paths, start, end, limit,
5606 # discover_changed_paths, strict_node_history, receiver)
5607 sub get_log {
5608 my ($self, @args) = @_;
5609 my $pool = SVN::Pool->new;
5611 # svn_log_changed_path_t objects passed to get_log are likely to be
5612 # overwritten even if only the refs are copied to an external variable,
5613 # so we should dup the structures in their entirety. Using an
5614 # externally passed pool (instead of our temporary and quickly cleared
5615 # pool in Git::SVN::Ra) does not help matters at all...
5616 my $receiver = pop @args;
5617 my $prefix = "/".$self->{svn_path};
5618 $prefix =~ s#/+($)##;
5619 my $prefix_regex = qr#^\Q$prefix\E#;
5620 push(@args, sub {
5621 my ($paths) = $_[0];
5622 return &$receiver(@_) unless $paths;
5623 $_[0] = ();
5624 foreach my $p (keys %$paths) {
5625 my $i = $paths->{$p};
5626 # Make path relative to our url, not repos_root
5627 $p =~ s/$prefix_regex//;
5628 my %s = map { $_ => $i->$_; }
5629 qw/copyfrom_path copyfrom_rev action/;
5630 if ($s{'copyfrom_path'}) {
5631 $s{'copyfrom_path'} =~ s/$prefix_regex//;
5633 $_[0]{$p} = \%s;
5635 &$receiver(@_);
5639 # the limit parameter was not supported in SVN 1.1.x, so we
5640 # drop it. Therefore, the receiver callback passed to it
5641 # is made aware of this limitation by being wrapped if
5642 # the limit passed to is being wrapped.
5643 if (::compare_svn_version('1.2.0') <= 0) {
5644 my $limit = splice(@args, 3, 1);
5645 if ($limit > 0) {
5646 my $receiver = pop @args;
5647 push(@args, sub { &$receiver(@_) if (--$limit >= 0) });
5650 my $ret = $self->SUPER::get_log(@args, $pool);
5651 $pool->clear;
5652 $ret;
5655 sub trees_match {
5656 my ($self, $url1, $rev1, $url2, $rev2) = @_;
5657 my $ctx = SVN::Client->new(auth => _auth_providers);
5658 my $out = IO::File->new_tmpfile;
5660 # older SVN (1.1.x) doesn't take $pool as the last parameter for
5661 # $ctx->diff(), so we'll create a default one
5662 my $pool = SVN::Pool->new_default_sub;
5664 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
5665 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
5666 $out->flush;
5667 my $ret = (($out->stat)[7] == 0);
5668 close $out or croak $!;
5670 $ret;
5673 sub get_commit_editor {
5674 my ($self, $log, $cb, $pool) = @_;
5676 my @lock = (::compare_svn_version('1.2.0') >= 0) ? (undef, 0) : ();
5677 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
5680 sub gs_do_update {
5681 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
5682 my $new = ($rev_a == $rev_b);
5683 my $path = $gs->{path};
5685 if ($new && -e $gs->{index}) {
5686 unlink $gs->{index} or die
5687 "Couldn't unlink index: $gs->{index}: $!\n";
5689 my $pool = SVN::Pool->new;
5690 $editor->set_path_strip($path);
5691 my (@pc) = split m#/#, $path;
5692 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
5693 1, $editor, $pool);
5694 my @lock = (::compare_svn_version('1.2.0') >= 0) ? (undef) : ();
5696 # Since we can't rely on svn_ra_reparent being available, we'll
5697 # just have to do some magic with set_path to make it so
5698 # we only want a partial path.
5699 my $sp = '';
5700 my $final = join('/', @pc);
5701 while (@pc) {
5702 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
5703 $sp .= '/' if length $sp;
5704 $sp .= shift @pc;
5706 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
5708 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
5710 $reporter->finish_report($pool);
5711 $pool->clear;
5712 $editor->{git_commit_ok};
5715 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
5716 # svn_ra_reparent didn't work before 1.4)
5717 sub gs_do_switch {
5718 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
5719 my $path = $gs->{path};
5720 my $pool = SVN::Pool->new;
5722 my $full_url = $self->{url};
5723 my $old_url = $full_url;
5724 $full_url .= '/' . $path if length $path;
5725 my ($ra, $reparented);
5727 if ($old_url =~ m#^svn(\+ssh)?://# ||
5728 ($full_url =~ m#^https?://# &&
5729 escape_url($full_url) ne $full_url)) {
5730 $_[0] = undef;
5731 $self = undef;
5732 $RA = undef;
5733 $ra = Git::SVN::Ra->new($full_url);
5734 $ra_invalid = 1;
5735 } elsif ($old_url ne $full_url) {
5736 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url, $pool);
5737 $self->{url} = $full_url;
5738 $reparented = 1;
5741 $ra ||= $self;
5742 $url_b = escape_url($url_b);
5743 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
5744 my @lock = (::compare_svn_version('1.2.0') >= 0) ? (undef) : ();
5745 $reporter->set_path('', $rev_a, 0, @lock, $pool);
5746 $reporter->finish_report($pool);
5748 if ($reparented) {
5749 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
5750 $self->{url} = $old_url;
5753 $pool->clear;
5754 $editor->{git_commit_ok};
5757 sub longest_common_path {
5758 my ($gsv, $globs) = @_;
5759 my %common;
5760 my $common_max = scalar @$gsv;
5762 foreach my $gs (@$gsv) {
5763 my @tmp = split m#/#, $gs->{path};
5764 my $p = '';
5765 foreach (@tmp) {
5766 $p .= length($p) ? "/$_" : $_;
5767 $common{$p} ||= 0;
5768 $common{$p}++;
5771 $globs ||= [];
5772 $common_max += scalar @$globs;
5773 foreach my $glob (@$globs) {
5774 my @tmp = split m#/#, $glob->{path}->{left};
5775 my $p = '';
5776 foreach (@tmp) {
5777 $p .= length($p) ? "/$_" : $_;
5778 $common{$p} ||= 0;
5779 $common{$p}++;
5783 my $longest_path = '';
5784 foreach (sort {length $b <=> length $a} keys %common) {
5785 if ($common{$_} == $common_max) {
5786 $longest_path = $_;
5787 last;
5790 $longest_path;
5793 sub gs_fetch_loop_common {
5794 my ($self, $base, $head, $gsv, $globs) = @_;
5795 return if ($base > $head);
5796 my $inc = $_log_window_size;
5797 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
5798 my $longest_path = longest_common_path($gsv, $globs);
5799 my $ra_url = $self->{url};
5800 my $find_trailing_edge;
5801 while (1) {
5802 my %revs;
5803 my $err;
5804 my $err_handler = $SVN::Error::handler;
5805 $SVN::Error::handler = sub {
5806 ($err) = @_;
5807 skip_unknown_revs($err);
5809 sub _cb {
5810 my ($paths, $r, $author, $date, $log) = @_;
5811 [ $paths,
5812 { author => $author, date => $date, log => $log } ];
5814 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
5815 sub { $revs{$_[1]} = _cb(@_) });
5816 if ($err) {
5817 print "Checked through r$max\r";
5818 } else {
5819 $find_trailing_edge = 1;
5821 if ($err and $find_trailing_edge) {
5822 print STDERR "Path '$longest_path' ",
5823 "was probably deleted:\n",
5824 $err->expanded_message,
5825 "\nWill attempt to follow ",
5826 "revisions r$min .. r$max ",
5827 "committed before the deletion\n";
5828 my $hi = $max;
5829 while (--$hi >= $min) {
5830 my $ok;
5831 $self->get_log([$longest_path], $min, $hi,
5832 0, 1, 1, sub {
5833 $ok = $_[1];
5834 $revs{$_[1]} = _cb(@_) });
5835 if ($ok) {
5836 print STDERR "r$min .. r$ok OK\n";
5837 last;
5840 $find_trailing_edge = 0;
5842 $SVN::Error::handler = $err_handler;
5844 my %exists = map { $_->{path} => $_ } @$gsv;
5845 foreach my $r (sort {$a <=> $b} keys %revs) {
5846 my ($paths, $logged) = @{$revs{$r}};
5848 foreach my $gs ($self->match_globs(\%exists, $paths,
5849 $globs, $r)) {
5850 if ($gs->rev_map_max >= $r) {
5851 next;
5853 next unless $gs->match_paths($paths, $r);
5854 $gs->{logged_rev_props} = $logged;
5855 if (my $last_commit = $gs->last_commit) {
5856 $gs->assert_index_clean($last_commit);
5858 my $log_entry = $gs->do_fetch($paths, $r);
5859 if ($log_entry) {
5860 $gs->do_git_commit($log_entry);
5862 $INDEX_FILES{$gs->{index}} = 1;
5864 foreach my $g (@$globs) {
5865 my $k = "svn-remote.$g->{remote}." .
5866 "$g->{t}-maxRev";
5867 Git::SVN::tmp_config($k, $r);
5869 if ($ra_invalid) {
5870 $_[0] = undef;
5871 $self = undef;
5872 $RA = undef;
5873 $self = Git::SVN::Ra->new($ra_url);
5874 $ra_invalid = undef;
5877 # pre-fill the .rev_db since it'll eventually get filled in
5878 # with '0' x40 if something new gets committed
5879 foreach my $gs (@$gsv) {
5880 next if $gs->rev_map_max >= $max;
5881 next if defined $gs->rev_map_get($max);
5882 $gs->rev_map_set($max, 0 x40);
5884 foreach my $g (@$globs) {
5885 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
5886 Git::SVN::tmp_config($k, $max);
5888 last if $max >= $head;
5889 $min = $max + 1;
5890 $max += $inc;
5891 $max = $head if ($max > $head);
5893 Git::SVN::gc();
5896 sub get_dir_globbed {
5897 my ($self, $left, $depth, $r) = @_;
5899 my @x = eval { $self->get_dir($left, $r) };
5900 return unless scalar @x == 3;
5901 my $dirents = $x[0];
5902 my @finalents;
5903 foreach my $de (keys %$dirents) {
5904 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
5905 if ($depth > 1) {
5906 my @args = ("$left/$de", $depth - 1, $r);
5907 foreach my $dir ($self->get_dir_globbed(@args)) {
5908 push @finalents, "$de/$dir";
5910 } else {
5911 push @finalents, $de;
5914 @finalents;
5917 # return value: 0 -- don't ignore, 1 -- ignore
5918 sub is_ref_ignored {
5919 my ($g, $p) = @_;
5920 my $refname = $g->{ref}->full_path($p);
5921 return 1 if defined($g->{ignore_refs_regex}) &&
5922 $refname =~ m!$g->{ignore_refs_regex}!;
5923 return 0 unless defined($_ignore_refs_regex);
5924 return 1 if $refname =~ m!$_ignore_refs_regex!o;
5925 return 0;
5928 sub match_globs {
5929 my ($self, $exists, $paths, $globs, $r) = @_;
5931 sub get_dir_check {
5932 my ($self, $exists, $g, $r) = @_;
5934 my @dirs = $self->get_dir_globbed($g->{path}->{left},
5935 $g->{path}->{depth},
5936 $r);
5938 foreach my $de (@dirs) {
5939 my $p = $g->{path}->full_path($de);
5940 next if $exists->{$p};
5941 next if (length $g->{path}->{right} &&
5942 ($self->check_path($p, $r) !=
5943 $SVN::Node::dir));
5944 next unless $p =~ /$g->{path}->{regex}/;
5945 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
5946 $g->{ref}->full_path($de), 1);
5949 foreach my $g (@$globs) {
5950 if (my $path = $paths->{"/$g->{path}->{left}"}) {
5951 if ($path->{action} =~ /^[AR]$/) {
5952 get_dir_check($self, $exists, $g, $r);
5955 foreach (keys %$paths) {
5956 if (/$g->{path}->{left_regex}/ &&
5957 !/$g->{path}->{regex}/) {
5958 next if $paths->{$_}->{action} !~ /^[AR]$/;
5959 get_dir_check($self, $exists, $g, $r);
5961 next unless /$g->{path}->{regex}/;
5962 my $p = $1;
5963 my $pathname = $g->{path}->full_path($p);
5964 next if is_ref_ignored($g, $p);
5965 next if $exists->{$pathname};
5966 next if ($self->check_path($pathname, $r) !=
5967 $SVN::Node::dir);
5968 $exists->{$pathname} = Git::SVN->init(
5969 $self->{url}, $pathname, undef,
5970 $g->{ref}->full_path($p), 1);
5972 my $c = '';
5973 foreach (split m#/#, $g->{path}->{left}) {
5974 $c .= "/$_";
5975 next unless ($paths->{$c} &&
5976 ($paths->{$c}->{action} =~ /^[AR]$/));
5977 get_dir_check($self, $exists, $g, $r);
5980 values %$exists;
5983 sub minimize_url {
5984 my ($self) = @_;
5985 return $self->{url} if ($self->{url} eq $self->{repos_root});
5986 my $url = $self->{repos_root};
5987 my @components = split(m!/!, $self->{svn_path});
5988 my $c = '';
5989 do {
5990 $url .= "/$c" if length $c;
5991 eval {
5992 my $ra = (ref $self)->new($url);
5993 my $latest = $ra->get_latest_revnum;
5994 $ra->get_log("", $latest, 0, 1, 0, 1, sub {});
5996 } while ($@ && ($c = shift @components));
5997 $url;
6000 sub can_do_switch {
6001 my $self = shift;
6002 unless (defined $can_do_switch) {
6003 my $pool = SVN::Pool->new;
6004 my $rep = eval {
6005 $self->do_switch(1, '', 0, $self->{url},
6006 SVN::Delta::Editor->new, $pool);
6008 if ($@) {
6009 $can_do_switch = 0;
6010 } else {
6011 $rep->abort_report($pool);
6012 $can_do_switch = 1;
6014 $pool->clear;
6016 $can_do_switch;
6019 sub skip_unknown_revs {
6020 my ($err) = @_;
6021 my $errno = $err->apr_err();
6022 # Maybe the branch we're tracking didn't
6023 # exist when the repo started, so it's
6024 # not an error if it doesn't, just continue
6026 # Wonderfully consistent library, eh?
6027 # 160013 - svn:// and file://
6028 # 175002 - http(s)://
6029 # 175007 - http(s):// (this repo required authorization, too...)
6030 # More codes may be discovered later...
6031 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
6032 my $err_key = $err->expanded_message;
6033 # revision numbers change every time, filter them out
6034 $err_key =~ s/\d+/\0/g;
6035 $err_key = "$errno\0$err_key";
6036 unless ($ignored_err{$err_key}) {
6037 warn "W: Ignoring error from SVN, path probably ",
6038 "does not exist: ($errno): ",
6039 $err->expanded_message,"\n";
6040 warn "W: Do not be alarmed at the above message ",
6041 "git-svn is just searching aggressively for ",
6042 "old history.\n",
6043 "This may take a while on large repositories\n";
6044 $ignored_err{$err_key} = 1;
6046 return;
6048 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
6051 package Git::SVN::Log;
6052 use strict;
6053 use warnings;
6054 use POSIX qw/strftime/;
6055 use constant commit_log_separator => ('-' x 72) . "\n";
6056 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
6057 %rusers $show_commit $incremental/;
6058 my $l_fmt;
6060 sub cmt_showable {
6061 my ($c) = @_;
6062 return 1 if defined $c->{r};
6064 # big commit message got truncated by the 16k pretty buffer in rev-list
6065 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
6066 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
6067 @{$c->{l}} = ();
6068 my @log = command(qw/cat-file commit/, $c->{c});
6070 # shift off the headers
6071 shift @log while ($log[0] ne '');
6072 shift @log;
6074 # TODO: make $c->{l} not have a trailing newline in the future
6075 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
6077 (undef, $c->{r}, undef) = ::extract_metadata(
6078 (grep(/^git-svn-id: /, @log))[-1]);
6080 return defined $c->{r};
6083 sub log_use_color {
6084 return $color || Git->repository->get_colorbool('color.diff');
6087 sub git_svn_log_cmd {
6088 my ($r_min, $r_max, @args) = @_;
6089 my $head = 'HEAD';
6090 my (@files, @log_opts);
6091 foreach my $x (@args) {
6092 if ($x eq '--' || @files) {
6093 push @files, $x;
6094 } else {
6095 if (::verify_ref("$x^0")) {
6096 $head = $x;
6097 } else {
6098 push @log_opts, $x;
6103 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
6104 $gs ||= Git::SVN->_new;
6105 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
6106 $gs->refname);
6107 push @cmd, '-r' unless $non_recursive;
6108 push @cmd, qw/--raw --name-status/ if $verbose;
6109 push @cmd, '--color' if log_use_color();
6110 push @cmd, @log_opts;
6111 if (defined $r_max && $r_max == $r_min) {
6112 push @cmd, '--max-count=1';
6113 if (my $c = $gs->rev_map_get($r_max)) {
6114 push @cmd, $c;
6116 } elsif (defined $r_max) {
6117 if ($r_max < $r_min) {
6118 ($r_min, $r_max) = ($r_max, $r_min);
6120 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
6121 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
6122 # If there are no commits in the range, both $c_max and $c_min
6123 # will be undefined. If there is at least 1 commit in the
6124 # range, both will be defined.
6125 return () if !defined $c_min || !defined $c_max;
6126 if ($c_min eq $c_max) {
6127 push @cmd, '--max-count=1', $c_min;
6128 } else {
6129 push @cmd, '--boundary', "$c_min..$c_max";
6132 return (@cmd, @files);
6135 # adapted from pager.c
6136 sub config_pager {
6137 if (! -t *STDOUT) {
6138 $ENV{GIT_PAGER_IN_USE} = 'false';
6139 $pager = undef;
6140 return;
6142 chomp($pager = command_oneline(qw(var GIT_PAGER)));
6143 if ($pager eq 'cat') {
6144 $pager = undef;
6146 $ENV{GIT_PAGER_IN_USE} = defined($pager);
6149 sub run_pager {
6150 return unless defined $pager;
6151 pipe my ($rfd, $wfd) or return;
6152 defined(my $pid = fork) or ::fatal "Can't fork: $!";
6153 if (!$pid) {
6154 open STDOUT, '>&', $wfd or
6155 ::fatal "Can't redirect to stdout: $!";
6156 return;
6158 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
6159 $ENV{LESS} ||= 'FRSX';
6160 exec $pager or ::fatal "Can't run pager: $! ($pager)";
6163 sub format_svn_date {
6164 my $t = shift || time;
6165 my $gmoff = Git::SVN::get_tz($t);
6166 return strftime("%Y-%m-%d %H:%M:%S $gmoff (%a, %d %b %Y)", localtime($t));
6169 sub parse_git_date {
6170 my ($t, $tz) = @_;
6171 # Date::Parse isn't in the standard Perl distro :(
6172 if ($tz =~ s/^\+//) {
6173 $t += tz_to_s_offset($tz);
6174 } elsif ($tz =~ s/^\-//) {
6175 $t -= tz_to_s_offset($tz);
6177 return $t;
6180 sub set_local_timezone {
6181 if (defined $TZ) {
6182 $ENV{TZ} = $TZ;
6183 } else {
6184 delete $ENV{TZ};
6188 sub tz_to_s_offset {
6189 my ($tz) = @_;
6190 $tz =~ s/(\d\d)$//;
6191 return ($1 * 60) + ($tz * 3600);
6194 sub get_author_info {
6195 my ($dest, $author, $t, $tz) = @_;
6196 $author =~ s/(?:^\s*|\s*$)//g;
6197 $dest->{a_raw} = $author;
6198 my $au;
6199 if ($::_authors) {
6200 $au = $rusers{$author} || undef;
6202 if (!$au) {
6203 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
6205 $dest->{t} = $t;
6206 $dest->{tz} = $tz;
6207 $dest->{a} = $au;
6208 $dest->{t_utc} = parse_git_date($t, $tz);
6211 sub process_commit {
6212 my ($c, $r_min, $r_max, $defer) = @_;
6213 if (defined $r_min && defined $r_max) {
6214 if ($r_min == $c->{r} && $r_min == $r_max) {
6215 show_commit($c);
6216 return 0;
6218 return 1 if $r_min == $r_max;
6219 if ($r_min < $r_max) {
6220 # we need to reverse the print order
6221 return 0 if (defined $limit && --$limit < 0);
6222 push @$defer, $c;
6223 return 1;
6225 if ($r_min != $r_max) {
6226 return 1 if ($r_min < $c->{r});
6227 return 1 if ($r_max > $c->{r});
6230 return 0 if (defined $limit && --$limit < 0);
6231 show_commit($c);
6232 return 1;
6235 sub show_commit {
6236 my $c = shift;
6237 if ($oneline) {
6238 my $x = "\n";
6239 if (my $l = $c->{l}) {
6240 while ($l->[0] =~ /^\s*$/) { shift @$l }
6241 $x = $l->[0];
6243 $l_fmt ||= 'A' . length($c->{r});
6244 print 'r',pack($l_fmt, $c->{r}),' | ';
6245 print "$c->{c} | " if $show_commit;
6246 print $x;
6247 } else {
6248 show_commit_normal($c);
6252 sub show_commit_changed_paths {
6253 my ($c) = @_;
6254 return unless $c->{changed};
6255 print "Changed paths:\n", @{$c->{changed}};
6258 sub show_commit_normal {
6259 my ($c) = @_;
6260 print commit_log_separator, "r$c->{r} | ";
6261 print "$c->{c} | " if $show_commit;
6262 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
6263 my $nr_line = 0;
6265 if (my $l = $c->{l}) {
6266 while ($l->[$#$l] eq "\n" && $#$l > 0
6267 && $l->[($#$l - 1)] eq "\n") {
6268 pop @$l;
6270 $nr_line = scalar @$l;
6271 if (!$nr_line) {
6272 print "1 line\n\n\n";
6273 } else {
6274 if ($nr_line == 1) {
6275 $nr_line = '1 line';
6276 } else {
6277 $nr_line .= ' lines';
6279 print $nr_line, "\n";
6280 show_commit_changed_paths($c);
6281 print "\n";
6282 print $_ foreach @$l;
6284 } else {
6285 print "1 line\n";
6286 show_commit_changed_paths($c);
6287 print "\n";
6290 foreach my $x (qw/raw stat diff/) {
6291 if ($c->{$x}) {
6292 print "\n";
6293 print $_ foreach @{$c->{$x}}
6298 sub cmd_show_log {
6299 my (@args) = @_;
6300 my ($r_min, $r_max);
6301 my $r_last = -1; # prevent dupes
6302 set_local_timezone();
6303 if (defined $::_revision) {
6304 if ($::_revision =~ /^(\d+):(\d+)$/) {
6305 ($r_min, $r_max) = ($1, $2);
6306 } elsif ($::_revision =~ /^\d+$/) {
6307 $r_min = $r_max = $::_revision;
6308 } else {
6309 ::fatal "-r$::_revision is not supported, use ",
6310 "standard 'git log' arguments instead";
6314 config_pager();
6315 @args = git_svn_log_cmd($r_min, $r_max, @args);
6316 if (!@args) {
6317 print commit_log_separator unless $incremental || $oneline;
6318 return;
6320 my $log = command_output_pipe(@args);
6321 run_pager();
6322 my (@k, $c, $d, $stat);
6323 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
6324 while (<$log>) {
6325 if (/^${esc_color}commit (?:- )?($::sha1_short)/o) {
6326 my $cmt = $1;
6327 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
6328 $r_last = $c->{r};
6329 process_commit($c, $r_min, $r_max, \@k) or
6330 goto out;
6332 $d = undef;
6333 $c = { c => $cmt };
6334 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
6335 get_author_info($c, $1, $2, $3);
6336 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
6337 # ignore
6338 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
6339 push @{$c->{raw}}, $_;
6340 } elsif (/^${esc_color}[ACRMDT]\t/) {
6341 # we could add $SVN->{svn_path} here, but that requires
6342 # remote access at the moment (repo_path_split)...
6343 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
6344 push @{$c->{changed}}, $_;
6345 } elsif (/^${esc_color}diff /o) {
6346 $d = 1;
6347 push @{$c->{diff}}, $_;
6348 } elsif ($d) {
6349 push @{$c->{diff}}, $_;
6350 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
6351 $esc_color*[\+\-]*$esc_color$/x) {
6352 $stat = 1;
6353 push @{$c->{stat}}, $_;
6354 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
6355 push @{$c->{stat}}, $_;
6356 $stat = undef;
6357 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
6358 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
6359 } elsif (s/^${esc_color} //o) {
6360 push @{$c->{l}}, $_;
6363 if ($c && defined $c->{r} && $c->{r} != $r_last) {
6364 $r_last = $c->{r};
6365 process_commit($c, $r_min, $r_max, \@k);
6367 if (@k) {
6368 ($r_min, $r_max) = ($r_max, $r_min);
6369 process_commit($_, $r_min, $r_max) foreach reverse @k;
6371 out:
6372 close $log;
6373 print commit_log_separator unless $incremental || $oneline;
6376 sub cmd_blame {
6377 my $path = pop;
6379 config_pager();
6380 run_pager();
6382 my ($fh, $ctx, $rev);
6384 if ($_git_format) {
6385 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
6386 while (my $line = <$fh>) {
6387 if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
6388 # Uncommitted edits show up as a rev ID of
6389 # all zeros, which we can't look up with
6390 # cmt_metadata
6391 if ($1 !~ /^0+$/) {
6392 (undef, $rev, undef) =
6393 ::cmt_metadata($1);
6394 $rev = '0' if (!$rev);
6395 } else {
6396 $rev = '0';
6398 $rev = sprintf('%-10s', $rev);
6399 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
6401 print $line;
6403 } else {
6404 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
6405 '--', $path);
6406 my ($sha1);
6407 my %authors;
6408 my @buffer;
6409 my %dsha; #distinct sha keys
6411 while (my $line = <$fh>) {
6412 push @buffer, $line;
6413 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
6414 $dsha{$1} = 1;
6418 my $s2r = ::cmt_sha2rev_batch([keys %dsha]);
6420 foreach my $line (@buffer) {
6421 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
6422 $rev = $s2r->{$1};
6423 $rev = '0' if (!$rev)
6425 elsif ($line =~ /^author (.*)/) {
6426 $authors{$rev} = $1;
6427 $authors{$rev} =~ s/\s/_/g;
6429 elsif ($line =~ /^\t(.*)$/) {
6430 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
6434 command_close_pipe($fh, $ctx);
6437 package Git::SVN::Migration;
6438 # these version numbers do NOT correspond to actual version numbers
6439 # of git nor git-svn. They are just relative.
6441 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
6443 # v1 layout: .git/$id/info/url, refs/remotes/$id
6445 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
6447 # v3 layout: .git/svn/$id, refs/remotes/$id
6448 # - info/url may remain for backwards compatibility
6449 # - this is what we migrate up to this layout automatically,
6450 # - this will be used by git svn init on single branches
6451 # v3.1 layout (auto migrated):
6452 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
6453 # for backwards compatibility
6455 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
6456 # - this is only created for newly multi-init-ed
6457 # repositories. Similar in spirit to the
6458 # --use-separate-remotes option in git-clone (now default)
6459 # - we do not automatically migrate to this (following
6460 # the example set by core git)
6462 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
6463 # - newer, more-efficient format that uses 24-bytes per record
6464 # with no filler space.
6465 # - use xxd -c24 < .rev_map.$UUID to view and debug
6466 # - This is a one-way migration, repositories updated to the
6467 # new format will not be able to use old git-svn without
6468 # rebuilding the .rev_db. Rebuilding the rev_db is not
6469 # possible if noMetadata or useSvmProps are set; but should
6470 # be no problem for users that use the (sensible) defaults.
6471 use strict;
6472 use warnings;
6473 use Carp qw/croak/;
6474 use File::Path qw/mkpath/;
6475 use File::Basename qw/dirname basename/;
6476 use vars qw/$_minimize/;
6478 sub migrate_from_v0 {
6479 my $git_dir = $ENV{GIT_DIR};
6480 return undef unless -d $git_dir;
6481 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
6482 my $migrated = 0;
6483 while (<$fh>) {
6484 chomp;
6485 my ($id, $orig_ref) = ($_, $_);
6486 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
6487 next unless -f "$git_dir/$id/info/url";
6488 my $new_ref = "refs/remotes/$id";
6489 if (::verify_ref("$new_ref^0")) {
6490 print STDERR "W: $orig_ref is probably an old ",
6491 "branch used by an ancient version of ",
6492 "git-svn.\n",
6493 "However, $new_ref also exists.\n",
6494 "We will not be able ",
6495 "to use this branch until this ",
6496 "ambiguity is resolved.\n";
6497 next;
6499 print STDERR "Migrating from v0 layout...\n" if !$migrated;
6500 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
6501 command_noisy('update-ref', $new_ref, $orig_ref);
6502 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
6503 $migrated++;
6505 command_close_pipe($fh, $ctx);
6506 print STDERR "Done migrating from v0 layout...\n" if $migrated;
6507 $migrated;
6510 sub migrate_from_v1 {
6511 my $git_dir = $ENV{GIT_DIR};
6512 my $migrated = 0;
6513 return $migrated unless -d $git_dir;
6514 my $svn_dir = "$git_dir/svn";
6516 # just in case somebody used 'svn' as their $id at some point...
6517 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
6519 print STDERR "Migrating from a git-svn v1 layout...\n";
6520 mkpath([$svn_dir]);
6521 print STDERR "Data from a previous version of git-svn exists, but\n\t",
6522 "$svn_dir\n\t(required for this version ",
6523 "($::VERSION) of git-svn) does not exist.\n";
6524 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
6525 while (<$fh>) {
6526 my $x = $_;
6527 next unless $x =~ s#^refs/remotes/##;
6528 chomp $x;
6529 next unless -f "$git_dir/$x/info/url";
6530 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
6531 next unless $u;
6532 my $dn = dirname("$git_dir/svn/$x");
6533 mkpath([$dn]) unless -d $dn;
6534 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
6535 mkpath(["$git_dir/svn/svn"]);
6536 print STDERR " - $git_dir/$x/info => ",
6537 "$git_dir/svn/$x/info\n";
6538 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
6539 croak "$!: $x";
6540 # don't worry too much about these, they probably
6541 # don't exist with repos this old (save for index,
6542 # and we can easily regenerate that)
6543 foreach my $f (qw/unhandled.log index .rev_db/) {
6544 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
6546 } else {
6547 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
6548 rename "$git_dir/$x", "$git_dir/svn/$x" or
6549 croak "$!: $x";
6551 $migrated++;
6553 command_close_pipe($fh, $ctx);
6554 print STDERR "Done migrating from a git-svn v1 layout\n";
6555 $migrated;
6558 sub read_old_urls {
6559 my ($l_map, $pfx, $path) = @_;
6560 my @dir;
6561 foreach (<$path/*>) {
6562 if (-r "$_/info/url") {
6563 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
6564 my $ref_id = $pfx . basename $_;
6565 my $url = ::file_to_s("$_/info/url");
6566 $l_map->{$ref_id} = $url;
6567 } elsif (-d $_) {
6568 push @dir, $_;
6571 foreach (@dir) {
6572 my $x = $_;
6573 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
6574 read_old_urls($l_map, $x, $_);
6578 sub migrate_from_v2 {
6579 my @cfg = command(qw/config -l/);
6580 return if grep /^svn-remote\..+\.url=/, @cfg;
6581 my %l_map;
6582 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
6583 my $migrated = 0;
6585 foreach my $ref_id (sort keys %l_map) {
6586 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
6587 if ($@) {
6588 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
6590 $migrated++;
6592 $migrated;
6595 sub minimize_connections {
6596 my $r = Git::SVN::read_all_remotes();
6597 my $new_urls = {};
6598 my $root_repos = {};
6599 foreach my $repo_id (keys %$r) {
6600 my $url = $r->{$repo_id}->{url} or next;
6601 my $fetch = $r->{$repo_id}->{fetch} or next;
6602 my $ra = Git::SVN::Ra->new($url);
6604 # skip existing cases where we already connect to the root
6605 if (($ra->{url} eq $ra->{repos_root}) ||
6606 ($ra->{repos_root} eq $repo_id)) {
6607 $root_repos->{$ra->{url}} = $repo_id;
6608 next;
6611 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
6612 my $root_path = $ra->{url};
6613 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
6614 foreach my $path (keys %$fetch) {
6615 my $ref_id = $fetch->{$path};
6616 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
6618 # make sure we can read when connecting to
6619 # a higher level of a repository
6620 my ($last_rev, undef) = $gs->last_rev_commit;
6621 if (!defined $last_rev) {
6622 $last_rev = eval {
6623 $root_ra->get_latest_revnum;
6625 next if $@;
6627 my $new = $root_path;
6628 $new .= length $path ? "/$path" : '';
6629 eval {
6630 $root_ra->get_log([$new], $last_rev, $last_rev,
6631 0, 0, 1, sub { });
6633 next if $@;
6634 $new_urls->{$ra->{repos_root}}->{$new} =
6635 { ref_id => $ref_id,
6636 old_repo_id => $repo_id,
6637 old_path => $path };
6641 my @emptied;
6642 foreach my $url (keys %$new_urls) {
6643 # see if we can re-use an existing [svn-remote "repo_id"]
6644 # instead of creating a(n ugly) new section:
6645 my $repo_id = $root_repos->{$url} || $url;
6647 my $fetch = $new_urls->{$url};
6648 foreach my $path (keys %$fetch) {
6649 my $x = $fetch->{$path};
6650 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
6651 my $pfx = "svn-remote.$x->{old_repo_id}";
6653 my $old_fetch = quotemeta("$x->{old_path}:".
6654 "$x->{ref_id}");
6655 command_noisy(qw/config --unset/,
6656 "$pfx.fetch", '^'. $old_fetch . '$');
6657 delete $r->{$x->{old_repo_id}}->
6658 {fetch}->{$x->{old_path}};
6659 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
6660 command_noisy(qw/config --unset/,
6661 "$pfx.url");
6662 push @emptied, $x->{old_repo_id}
6666 if (@emptied) {
6667 my $file = $ENV{GIT_CONFIG} || "$ENV{GIT_DIR}/config";
6668 print STDERR <<EOF;
6669 The following [svn-remote] sections in your config file ($file) are empty
6670 and can be safely removed:
6672 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
6676 sub migration_check {
6677 migrate_from_v0();
6678 migrate_from_v1();
6679 migrate_from_v2();
6680 minimize_connections() if $_minimize;
6683 package Git::IndexInfo;
6684 use strict;
6685 use warnings;
6686 use Git qw/command_input_pipe command_close_pipe/;
6688 sub new {
6689 my ($class) = @_;
6690 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
6691 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
6694 sub remove {
6695 my ($self, $path) = @_;
6696 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
6697 return ++$self->{nr};
6699 undef;
6702 sub update {
6703 my ($self, $mode, $hash, $path) = @_;
6704 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
6705 return ++$self->{nr};
6707 undef;
6710 sub DESTROY {
6711 my ($self) = @_;
6712 command_close_pipe($self->{gui}, $self->{ctx});
6715 package Git::SVN::GlobSpec;
6716 use strict;
6717 use warnings;
6719 sub new {
6720 my ($class, $glob, $pattern_ok) = @_;
6721 my $re = $glob;
6722 $re =~ s!/+$!!g; # no need for trailing slashes
6723 my (@left, @right, @patterns);
6724 my $state = "left";
6725 my $die_msg = "Only one set of wildcard directories " .
6726 "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
6727 for my $part (split(m|/|, $glob)) {
6728 if ($part =~ /\*/ && $part ne "*") {
6729 die "Invalid pattern in '$glob': $part\n";
6730 } elsif ($pattern_ok && $part =~ /[{}]/ &&
6731 $part !~ /^\{[^{}]+\}/) {
6732 die "Invalid pattern in '$glob': $part\n";
6734 if ($part eq "*") {
6735 die $die_msg if $state eq "right";
6736 $state = "pattern";
6737 push(@patterns, "[^/]*");
6738 } elsif ($pattern_ok && $part =~ /^\{(.*)\}$/) {
6739 die $die_msg if $state eq "right";
6740 $state = "pattern";
6741 my $p = quotemeta($1);
6742 $p =~ s/\\,/|/g;
6743 push(@patterns, "(?:$p)");
6744 } else {
6745 if ($state eq "left") {
6746 push(@left, $part);
6747 } else {
6748 push(@right, $part);
6749 $state = "right";
6753 my $depth = @patterns;
6754 if ($depth == 0) {
6755 die "One '*' is needed in glob: '$glob'\n";
6757 my $left = join('/', @left);
6758 my $right = join('/', @right);
6759 $re = join('/', @patterns);
6760 $re = join('\/',
6761 grep(length, quotemeta($left), "($re)", quotemeta($right)));
6762 my $left_re = qr/^\/\Q$left\E(\/|$)/;
6763 bless { left => $left, right => $right, left_regex => $left_re,
6764 regex => qr/$re/, glob => $glob, depth => $depth }, $class;
6767 sub full_path {
6768 my ($self, $path) = @_;
6769 return (length $self->{left} ? "$self->{left}/" : '') .
6770 $path . (length $self->{right} ? "/$self->{right}" : '');
6773 __END__
6775 Data structures:
6778 $remotes = { # returned by read_all_remotes()
6779 'svn' => {
6780 # svn-remote.svn.url=https://svn.musicpd.org
6781 url => 'https://svn.musicpd.org',
6782 # svn-remote.svn.fetch=mpd/trunk:trunk
6783 fetch => {
6784 'mpd/trunk' => 'trunk',
6786 # svn-remote.svn.tags=mpd/tags/*:tags/*
6787 tags => {
6788 path => {
6789 left => 'mpd/tags',
6790 right => '',
6791 regex => qr!mpd/tags/([^/]+)$!,
6792 glob => 'tags/*',
6794 ref => {
6795 left => 'tags',
6796 right => '',
6797 regex => qr!tags/([^/]+)$!,
6798 glob => 'tags/*',
6804 $log_entry hashref as returned by libsvn_log_entry()
6806 log => 'whitespace-formatted log entry
6807 ', # trailing newline is preserved
6808 revision => '8', # integer
6809 date => '2004-02-24T17:01:44.108345Z', # commit date
6810 author => 'committer name'
6814 # this is generated by generate_diff();
6815 @mods = array of diff-index line hashes, each element represents one line
6816 of diff-index output
6818 diff-index line ($m hash)
6820 mode_a => first column of diff-index output, no leading ':',
6821 mode_b => second column of diff-index output,
6822 sha1_b => sha1sum of the final blob,
6823 chg => change type [MCRADT],
6824 file_a => original file name of a file (iff chg is 'C' or 'R')
6825 file_b => new/current file name of a file (any chg)
6829 # retval of read_url_paths{,_all}();
6830 $l_map = {
6831 # repository root url
6832 'https://svn.musicpd.org' => {
6833 # repository path # GIT_SVN_ID
6834 'mpd/trunk' => 'trunk',
6835 'mpd/tags/0.11.5' => 'tags/0.11.5',
6839 Notes:
6840 I don't trust the each() function on unless I created %hash myself
6841 because the internal iterator may not have started at base.