git-svn: make Git::SVN::Editor a separate file
[git.git] / git-svn.perl
blobaa14d459f2d8a70f59c12e7b179264a88a5fd74a
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 use Carp qw/croak/;
72 use Digest::MD5;
73 use IO::File qw//;
74 use File::Basename qw/dirname basename/;
75 use File::Path qw/mkpath/;
76 use File::Spec;
77 use File::Find;
78 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
79 use IPC::Open3;
80 use Git;
81 use Git::SVN::Editor qw//;
82 use Git::SVN::Fetcher qw//;
83 use Git::SVN::Prompt qw//;
84 use Memoize; # core since 5.8.0, Jul 2002
86 BEGIN {
87 # import functions from Git into our packages, en masse
88 no strict 'refs';
89 foreach (qw/command command_oneline command_noisy command_output_pipe
90 command_input_pipe command_close_pipe
91 command_bidi_pipe command_close_bidi_pipe/) {
92 for my $package ( qw(Git::SVN::Migration Git::SVN::Log Git::SVN),
93 __PACKAGE__) {
94 *{"${package}::$_"} = \&{"Git::$_"};
97 Memoize::memoize 'Git::config';
98 Memoize::memoize 'Git::config_bool';
101 my ($SVN);
103 $sha1 = qr/[a-f\d]{40}/;
104 $sha1_short = qr/[a-f\d]{4,40}/;
105 my ($_stdin, $_help, $_edit,
106 $_message, $_file, $_branch_dest,
107 $_template, $_shared,
108 $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
109 $_merge, $_strategy, $_preserve_merges, $_dry_run, $_local,
110 $_prefix, $_no_checkout, $_url, $_verbose,
111 $_git_format, $_commit_url, $_tag, $_merge_info, $_interactive);
112 $Git::SVN::_follow_parent = 1;
113 $Git::SVN::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' => \$Git::SVN::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' => \$Git::SVN::Editor::_rmdir,
152 'find-copies-harder' => \$Git::SVN::Editor::_find_copies_harder,
153 'l=i' => \$Git::SVN::Editor::_rename_limit,
154 'copy-similarity|C=i'=> \$Git::SVN::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 \$Git::SVN::Fetcher::_preserve_empty_dirs,
167 'placeholder-filename=s' =>
168 \$Git::SVN::Fetcher::_placeholder_filename,
169 %fc_opts, %init_opts } ],
170 init => [ \&cmd_init, "Initialize a repo for tracking" .
171 " (requires URL argument)",
172 \%init_opts ],
173 'multi-init' => [ \&cmd_multi_init,
174 "Deprecated alias for ".
175 "'$0 init -T<trunk> -b<branches> -t<tags>'",
176 \%init_opts ],
177 dcommit => [ \&cmd_dcommit,
178 'Commit several diffs to merge with upstream',
179 { 'merge|m|M' => \$_merge,
180 'strategy|s=s' => \$_strategy,
181 'verbose|v' => \$_verbose,
182 'dry-run|n' => \$_dry_run,
183 'fetch-all|all' => \$_fetch_all,
184 'commit-url=s' => \$_commit_url,
185 'revision|r=i' => \$_revision,
186 'no-rebase' => \$_no_rebase,
187 'mergeinfo=s' => \$_merge_info,
188 'interactive|i' => \$_interactive,
189 %cmt_opts, %fc_opts } ],
190 branch => [ \&cmd_branch,
191 'Create a branch in the SVN repository',
192 { 'message|m=s' => \$_message,
193 'destination|d=s' => \$_branch_dest,
194 'dry-run|n' => \$_dry_run,
195 'tag|t' => \$_tag,
196 'username=s' => \$Git::SVN::Prompt::_username,
197 'commit-url=s' => \$_commit_url } ],
198 tag => [ sub { $_tag = 1; cmd_branch(@_) },
199 'Create a tag in the SVN repository',
200 { 'message|m=s' => \$_message,
201 'destination|d=s' => \$_branch_dest,
202 'dry-run|n' => \$_dry_run,
203 'username=s' => \$Git::SVN::Prompt::_username,
204 'commit-url=s' => \$_commit_url } ],
205 'set-tree' => [ \&cmd_set_tree,
206 "Set an SVN repository to a git tree-ish",
207 { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
208 'create-ignore' => [ \&cmd_create_ignore,
209 'Create a .gitignore per svn:ignore',
210 { 'revision|r=i' => \$_revision
211 } ],
212 'mkdirs' => [ \&cmd_mkdirs ,
213 "recreate empty directories after a checkout",
214 { 'revision|r=i' => \$_revision } ],
215 'propget' => [ \&cmd_propget,
216 'Print the value of a property on a file or directory',
217 { 'revision|r=i' => \$_revision } ],
218 'proplist' => [ \&cmd_proplist,
219 'List all properties of a file or directory',
220 { 'revision|r=i' => \$_revision } ],
221 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
222 { 'revision|r=i' => \$_revision
223 } ],
224 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
225 { 'revision|r=i' => \$_revision
226 } ],
227 'multi-fetch' => [ \&cmd_multi_fetch,
228 "Deprecated alias for $0 fetch --all",
229 { 'revision|r=s' => \$_revision, %fc_opts } ],
230 'migrate' => [ sub { },
231 # no-op, we automatically run this anyways,
232 'Migrate configuration/metadata/layout from
233 previous versions of git-svn',
234 { 'minimize' => \$Git::SVN::Migration::_minimize,
235 %remote_opts } ],
236 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
237 { 'limit=i' => \$Git::SVN::Log::limit,
238 'revision|r=s' => \$_revision,
239 'verbose|v' => \$Git::SVN::Log::verbose,
240 'incremental' => \$Git::SVN::Log::incremental,
241 'oneline' => \$Git::SVN::Log::oneline,
242 'show-commit' => \$Git::SVN::Log::show_commit,
243 'non-recursive' => \$Git::SVN::Log::non_recursive,
244 'authors-file|A=s' => \$_authors,
245 'color' => \$Git::SVN::Log::color,
246 'pager=s' => \$Git::SVN::Log::pager
247 } ],
248 'find-rev' => [ \&cmd_find_rev,
249 "Translate between SVN revision numbers and tree-ish",
250 {} ],
251 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
252 { 'merge|m|M' => \$_merge,
253 'verbose|v' => \$_verbose,
254 'strategy|s=s' => \$_strategy,
255 'local|l' => \$_local,
256 'fetch-all|all' => \$_fetch_all,
257 'dry-run|n' => \$_dry_run,
258 'preserve-merges|p' => \$_preserve_merges,
259 %fc_opts } ],
260 'commit-diff' => [ \&cmd_commit_diff,
261 'Commit a diff between two trees',
262 { 'message|m=s' => \$_message,
263 'file|F=s' => \$_file,
264 'revision|r=s' => \$_revision,
265 %cmt_opts } ],
266 'info' => [ \&cmd_info,
267 "Show info about the latest SVN revision
268 on the current branch",
269 { 'url' => \$_url, } ],
270 'blame' => [ \&Git::SVN::Log::cmd_blame,
271 "Show what revision and author last modified each line of a file",
272 { 'git-format' => \$_git_format } ],
273 'reset' => [ \&cmd_reset,
274 "Undo fetches back to the specified SVN revision",
275 { 'revision|r=s' => \$_revision,
276 'parent|p' => \$_fetch_parent } ],
277 'gc' => [ \&cmd_gc,
278 "Compress unhandled.log files in .git/svn and remove " .
279 "index files in .git/svn",
280 {} ],
283 use Term::ReadLine;
284 package FakeTerm;
285 sub new {
286 my ($class, $reason) = @_;
287 return bless \$reason, shift;
289 sub readline {
290 my $self = shift;
291 die "Cannot use readline on FakeTerm: $$self";
293 package main;
295 my $term = eval {
296 $ENV{"GIT_SVN_NOTTY"}
297 ? new Term::ReadLine 'git-svn', \*STDIN, \*STDOUT
298 : new Term::ReadLine 'git-svn';
300 if ($@) {
301 $term = new FakeTerm "$@: going non-interactive";
304 my $cmd;
305 for (my $i = 0; $i < @ARGV; $i++) {
306 if (defined $cmd{$ARGV[$i]}) {
307 $cmd = $ARGV[$i];
308 splice @ARGV, $i, 1;
309 last;
310 } elsif ($ARGV[$i] eq 'help') {
311 $cmd = $ARGV[$i+1];
312 usage(0);
316 # make sure we're always running at the top-level working directory
317 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
318 unless (-d $ENV{GIT_DIR}) {
319 if ($git_dir_user_set) {
320 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
321 "but it is not a directory\n";
323 my $git_dir = delete $ENV{GIT_DIR};
324 my $cdup = undef;
325 git_cmd_try {
326 $cdup = command_oneline(qw/rev-parse --show-cdup/);
327 $git_dir = '.' unless ($cdup);
328 chomp $cdup if ($cdup);
329 $cdup = "." unless ($cdup && length $cdup);
330 } "Already at toplevel, but $git_dir not found\n";
331 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
332 unless (-d $git_dir) {
333 die "$git_dir still not found after going to ",
334 "'$cdup'\n";
336 $ENV{GIT_DIR} = $git_dir;
338 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
341 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
343 read_git_config(\%opts);
344 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
345 Getopt::Long::Configure('pass_through');
347 my $rv = GetOptions(%opts, 'h|H' => \$_help, 'version|V' => \$_version,
348 'minimize-connections' => \$Git::SVN::Migration::_minimize,
349 'id|i=s' => \$Git::SVN::default_ref_id,
350 'svn-remote|remote|R=s' => sub {
351 $Git::SVN::no_reuse_existing = 1;
352 $Git::SVN::default_repo_id = $_[1] });
353 exit 1 if (!$rv && $cmd && $cmd ne 'log');
355 usage(0) if $_help;
356 version() if $_version;
357 usage(1) unless defined $cmd;
358 load_authors() if $_authors;
359 if (defined $_authors_prog) {
360 $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
363 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
364 Git::SVN::Migration::migration_check();
366 Git::SVN::init_vars();
367 eval {
368 Git::SVN::verify_remotes_sanity();
369 $cmd{$cmd}->[0]->(@ARGV);
371 fatal $@ if $@;
372 post_fetch_checkout();
373 exit 0;
375 ####################### primary functions ######################
376 sub usage {
377 my $exit = shift || 0;
378 my $fd = $exit ? \*STDERR : \*STDOUT;
379 print $fd <<"";
380 git-svn - bidirectional operations between a single Subversion tree and git
381 Usage: git svn <command> [options] [arguments]\n
383 print $fd "Available commands:\n" unless $cmd;
385 foreach (sort keys %cmd) {
386 next if $cmd && $cmd ne $_;
387 next if /^multi-/; # don't show deprecated commands
388 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
389 foreach (sort keys %{$cmd{$_}->[2]}) {
390 # mixed-case options are for .git/config only
391 next if /[A-Z]/ && /^[a-z]+$/i;
392 # prints out arguments as they should be passed:
393 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
394 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
395 "--$_" : "-$_" }
396 split /\|/,$_)," $x\n";
399 print $fd <<"";
400 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
401 arbitrary identifier if you're tracking multiple SVN branches/repositories in
402 one git repository and want to keep them separate. See git-svn(1) for more
403 information.
405 exit $exit;
408 sub version {
409 ::_req_svn();
410 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
411 exit 0;
414 sub ask {
415 my ($prompt, %arg) = @_;
416 my $valid_re = $arg{valid_re};
417 my $default = $arg{default};
418 my $resp;
419 my $i = 0;
421 if ( !( defined($term->IN)
422 && defined( fileno($term->IN) )
423 && defined( $term->OUT )
424 && defined( fileno($term->OUT) ) ) ){
425 return defined($default) ? $default : undef;
428 while ($i++ < 10) {
429 $resp = $term->readline($prompt);
430 if (!defined $resp) { # EOF
431 print "\n";
432 return defined $default ? $default : undef;
434 if ($resp eq '' and defined $default) {
435 return $default;
437 if (!defined $valid_re or $resp =~ /$valid_re/) {
438 return $resp;
441 return undef;
444 sub do_git_init_db {
445 unless (-d $ENV{GIT_DIR}) {
446 my @init_db = ('init');
447 push @init_db, "--template=$_template" if defined $_template;
448 if (defined $_shared) {
449 if ($_shared =~ /[a-z]/) {
450 push @init_db, "--shared=$_shared";
451 } else {
452 push @init_db, "--shared";
455 command_noisy(@init_db);
456 $_repository = Git->repository(Repository => ".git");
458 my $set;
459 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
460 foreach my $i (keys %icv) {
461 die "'$set' and '$i' cannot both be set\n" if $set;
462 next unless defined $icv{$i};
463 command_noisy('config', "$pfx.$i", $icv{$i});
464 $set = $i;
466 my $ignore_paths_regex = \$Git::SVN::Fetcher::_ignore_regex;
467 command_noisy('config', "$pfx.ignore-paths", $$ignore_paths_regex)
468 if defined $$ignore_paths_regex;
469 my $ignore_refs_regex = \$Git::SVN::Ra::_ignore_refs_regex;
470 command_noisy('config', "$pfx.ignore-refs", $$ignore_refs_regex)
471 if defined $$ignore_refs_regex;
473 if (defined $Git::SVN::Fetcher::_preserve_empty_dirs) {
474 my $fname = \$Git::SVN::Fetcher::_placeholder_filename;
475 command_noisy('config', "$pfx.preserve-empty-dirs", 'true');
476 command_noisy('config', "$pfx.placeholder-filename", $$fname);
480 sub init_subdir {
481 my $repo_path = shift or return;
482 mkpath([$repo_path]) unless -d $repo_path;
483 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
484 $ENV{GIT_DIR} = '.git';
485 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
488 sub cmd_clone {
489 my ($url, $path) = @_;
490 if (!defined $path &&
491 (defined $_trunk || @_branches || @_tags ||
492 defined $_stdlayout) &&
493 $url !~ m#^[a-z\+]+://#) {
494 $path = $url;
496 $path = basename($url) if !defined $path || !length $path;
497 my $authors_absolute = $_authors ? File::Spec->rel2abs($_authors) : "";
498 cmd_init($url, $path);
499 command_oneline('config', 'svn.authorsfile', $authors_absolute)
500 if $_authors;
501 Git::SVN::fetch_all($Git::SVN::default_repo_id);
504 sub cmd_init {
505 if (defined $_stdlayout) {
506 $_trunk = 'trunk' if (!defined $_trunk);
507 @_tags = 'tags' if (! @_tags);
508 @_branches = 'branches' if (! @_branches);
510 if (defined $_trunk || @_branches || @_tags) {
511 return cmd_multi_init(@_);
513 my $url = shift or die "SVN repository location required ",
514 "as a command-line argument\n";
515 $url = canonicalize_url($url);
516 init_subdir(@_);
517 do_git_init_db();
519 if ($Git::SVN::_minimize_url eq 'unset') {
520 $Git::SVN::_minimize_url = 0;
523 Git::SVN->init($url);
526 sub cmd_fetch {
527 if (grep /^\d+=./, @_) {
528 die "'<rev>=<commit>' fetch arguments are ",
529 "no longer supported.\n";
531 my ($remote) = @_;
532 if (@_ > 1) {
533 die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
535 $Git::SVN::no_reuse_existing = undef;
536 if ($_fetch_parent) {
537 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
538 unless ($gs) {
539 die "Unable to determine upstream SVN information from ",
540 "working tree history\n";
542 # just fetch, don't checkout.
543 $_no_checkout = 'true';
544 $_fetch_all ? $gs->fetch_all : $gs->fetch;
545 } elsif ($_fetch_all) {
546 cmd_multi_fetch();
547 } else {
548 $remote ||= $Git::SVN::default_repo_id;
549 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
553 sub cmd_set_tree {
554 my (@commits) = @_;
555 if ($_stdin || !@commits) {
556 print "Reading from stdin...\n";
557 @commits = ();
558 while (<STDIN>) {
559 if (/\b($sha1_short)\b/o) {
560 unshift @commits, $1;
564 my @revs;
565 foreach my $c (@commits) {
566 my @tmp = command('rev-parse',$c);
567 if (scalar @tmp == 1) {
568 push @revs, $tmp[0];
569 } elsif (scalar @tmp > 1) {
570 push @revs, reverse(command('rev-list',@tmp));
571 } else {
572 fatal "Failed to rev-parse $c";
575 my $gs = Git::SVN->new;
576 my ($r_last, $cmt_last) = $gs->last_rev_commit;
577 $gs->fetch;
578 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
579 fatal "There are new revisions that were fetched ",
580 "and need to be merged (or acknowledged) ",
581 "before committing.\nlast rev: $r_last\n",
582 " current: $gs->{last_rev}";
584 $gs->set_tree($_) foreach @revs;
585 print "Done committing ",scalar @revs," revisions to SVN\n";
586 unlink $gs->{index};
589 sub split_merge_info_range {
590 my ($range) = @_;
591 if ($range =~ /(\d+)-(\d+)/) {
592 return (int($1), int($2));
593 } else {
594 return (int($range), int($range));
598 sub combine_ranges {
599 my ($in) = @_;
601 my @fnums = ();
602 my @arr = split(/,/, $in);
603 for my $element (@arr) {
604 my ($start, $end) = split_merge_info_range($element);
605 push @fnums, $start;
608 my @sorted = @arr [ sort {
609 $fnums[$a] <=> $fnums[$b]
610 } 0..$#arr ];
612 my @return = ();
613 my $last = -1;
614 my $first = -1;
615 for my $element (@sorted) {
616 my ($start, $end) = split_merge_info_range($element);
618 if ($last == -1) {
619 $first = $start;
620 $last = $end;
621 next;
623 if ($start <= $last+1) {
624 if ($end > $last) {
625 $last = $end;
627 next;
629 if ($first == $last) {
630 push @return, "$first";
631 } else {
632 push @return, "$first-$last";
634 $first = $start;
635 $last = $end;
638 if ($first != -1) {
639 if ($first == $last) {
640 push @return, "$first";
641 } else {
642 push @return, "$first-$last";
646 return join(',', @return);
649 sub merge_revs_into_hash {
650 my ($hash, $minfo) = @_;
651 my @lines = split(' ', $minfo);
653 for my $line (@lines) {
654 my ($branchpath, $revs) = split(/:/, $line);
656 if (exists($hash->{$branchpath})) {
657 # Merge the two revision sets
658 my $combined = "$hash->{$branchpath},$revs";
659 $hash->{$branchpath} = combine_ranges($combined);
660 } else {
661 # Just do range combining for consolidation
662 $hash->{$branchpath} = combine_ranges($revs);
667 sub merge_merge_info {
668 my ($mergeinfo_one, $mergeinfo_two) = @_;
669 my %result_hash = ();
671 merge_revs_into_hash(\%result_hash, $mergeinfo_one);
672 merge_revs_into_hash(\%result_hash, $mergeinfo_two);
674 my $result = '';
675 # Sort below is for consistency's sake
676 for my $branchname (sort keys(%result_hash)) {
677 my $revlist = $result_hash{$branchname};
678 $result .= "$branchname:$revlist\n"
680 return $result;
683 sub populate_merge_info {
684 my ($d, $gs, $uuid, $linear_refs, $rewritten_parent) = @_;
686 my %parentshash;
687 read_commit_parents(\%parentshash, $d);
688 my @parents = @{$parentshash{$d}};
689 if ($#parents > 0) {
690 # Merge commit
691 my $all_parents_ok = 1;
692 my $aggregate_mergeinfo = '';
693 my $rooturl = $gs->repos_root;
695 if (defined($rewritten_parent)) {
696 # Replace first parent with newly-rewritten version
697 shift @parents;
698 unshift @parents, $rewritten_parent;
701 foreach my $parent (@parents) {
702 my ($branchurl, $svnrev, $paruuid) =
703 cmt_metadata($parent);
705 unless (defined($svnrev)) {
706 # Should have been caught be preflight check
707 fatal "merge commit $d has ancestor $parent, but that change "
708 ."does not have git-svn metadata!";
710 unless ($branchurl =~ /^\Q$rooturl\E(.*)/) {
711 fatal "commit $parent git-svn metadata changed mid-run!";
713 my $branchpath = $1;
715 my $ra = Git::SVN::Ra->new($branchurl);
716 my (undef, undef, $props) =
717 $ra->get_dir(canonicalize_path("."), $svnrev);
718 my $par_mergeinfo = $props->{'svn:mergeinfo'};
719 unless (defined $par_mergeinfo) {
720 $par_mergeinfo = '';
722 # Merge previous mergeinfo values
723 $aggregate_mergeinfo =
724 merge_merge_info($aggregate_mergeinfo,
725 $par_mergeinfo, 0);
727 next if $parent eq $parents[0]; # Skip first parent
728 # Add new changes being placed in tree by merge
729 my @cmd = (qw/rev-list --reverse/,
730 $parent, qw/--not/);
731 foreach my $par (@parents) {
732 unless ($par eq $parent) {
733 push @cmd, $par;
736 my @revsin = ();
737 my ($revlist, $ctx) = command_output_pipe(@cmd);
738 while (<$revlist>) {
739 my $irev = $_;
740 chomp $irev;
741 my (undef, $csvnrev, undef) =
742 cmt_metadata($irev);
743 unless (defined $csvnrev) {
744 # A child is missing SVN annotations...
745 # this might be OK, or might not be.
746 warn "W:child $irev is merged into revision "
747 ."$d but does not have git-svn metadata. "
748 ."This means git-svn cannot determine the "
749 ."svn revision numbers to place into the "
750 ."svn:mergeinfo property. You must ensure "
751 ."a branch is entirely committed to "
752 ."SVN before merging it in order for "
753 ."svn:mergeinfo population to function "
754 ."properly";
756 push @revsin, $csvnrev;
758 command_close_pipe($revlist, $ctx);
760 last unless $all_parents_ok;
762 # We now have a list of all SVN revnos which are
763 # merged by this particular parent. Integrate them.
764 next if $#revsin == -1;
765 my $newmergeinfo = "$branchpath:" . join(',', @revsin);
766 $aggregate_mergeinfo =
767 merge_merge_info($aggregate_mergeinfo,
768 $newmergeinfo, 1);
770 if ($all_parents_ok and $aggregate_mergeinfo) {
771 return $aggregate_mergeinfo;
775 return undef;
778 sub cmd_dcommit {
779 my $head = shift;
780 command_noisy(qw/update-index --refresh/);
781 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
782 'Cannot dcommit with a dirty index. Commit your changes first, '
783 . "or stash them with `git stash'.\n";
784 $head ||= 'HEAD';
786 my $old_head;
787 if ($head ne 'HEAD') {
788 $old_head = eval {
789 command_oneline([qw/symbolic-ref -q HEAD/])
791 if ($old_head) {
792 $old_head =~ s{^refs/heads/}{};
793 } else {
794 $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
796 command(['checkout', $head], STDERR => 0);
799 my @refs;
800 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
801 unless ($gs) {
802 die "Unable to determine upstream SVN information from ",
803 "$head history.\nPerhaps the repository is empty.";
806 if (defined $_commit_url) {
807 $url = $_commit_url;
808 } else {
809 $url = eval { command_oneline('config', '--get',
810 "svn-remote.$gs->{repo_id}.commiturl") };
811 if (!$url) {
812 $url = $gs->full_pushurl
816 my $last_rev = $_revision if defined $_revision;
817 if ($url) {
818 print "Committing to $url ...\n";
820 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
821 if ($_no_rebase && scalar(@$linear_refs) > 1) {
822 warn "Attempting to commit more than one change while ",
823 "--no-rebase is enabled.\n",
824 "If these changes depend on each other, re-running ",
825 "without --no-rebase may be required."
828 if (defined $_interactive){
829 my $ask_default = "y";
830 foreach my $d (@$linear_refs){
831 my ($fh, $ctx) = command_output_pipe(qw(show --summary), "$d");
832 while (<$fh>){
833 print $_;
835 command_close_pipe($fh, $ctx);
836 $_ = ask("Commit this patch to SVN? ([y]es (default)|[n]o|[q]uit|[a]ll): ",
837 valid_re => qr/^(?:yes|y|no|n|quit|q|all|a)/i,
838 default => $ask_default);
839 die "Commit this patch reply required" unless defined $_;
840 if (/^[nq]/i) {
841 exit(0);
842 } elsif (/^a/i) {
843 last;
848 my $expect_url = $url;
850 my $push_merge_info = eval {
851 command_oneline(qw/config --get svn.pushmergeinfo/)
853 if (not defined($push_merge_info)
854 or $push_merge_info eq "false"
855 or $push_merge_info eq "no"
856 or $push_merge_info eq "never") {
857 $push_merge_info = 0;
860 unless (defined($_merge_info) || ! $push_merge_info) {
861 # Preflight check of changes to ensure no issues with mergeinfo
862 # This includes check for uncommitted-to-SVN parents
863 # (other than the first parent, which we will handle),
864 # information from different SVN repos, and paths
865 # which are not underneath this repository root.
866 my $rooturl = $gs->repos_root;
867 foreach my $d (@$linear_refs) {
868 my %parentshash;
869 read_commit_parents(\%parentshash, $d);
870 my @realparents = @{$parentshash{$d}};
871 if ($#realparents > 0) {
872 # Merge commit
873 shift @realparents; # Remove/ignore first parent
874 foreach my $parent (@realparents) {
875 my ($branchurl, $svnrev, $paruuid) = cmt_metadata($parent);
876 unless (defined $paruuid) {
877 # A parent is missing SVN annotations...
878 # abort the whole operation.
879 fatal "$parent is merged into revision $d, "
880 ."but does not have git-svn metadata. "
881 ."Either dcommit the branch or use a "
882 ."local cherry-pick, FF merge, or rebase "
883 ."instead of an explicit merge commit.";
886 unless ($paruuid eq $uuid) {
887 # Parent has SVN metadata from different repository
888 fatal "merge parent $parent for change $d has "
889 ."git-svn uuid $paruuid, while current change "
890 ."has uuid $uuid!";
893 unless ($branchurl =~ /^\Q$rooturl\E(.*)/) {
894 # This branch is very strange indeed.
895 fatal "merge parent $parent for $d is on branch "
896 ."$branchurl, which is not under the "
897 ."git-svn root $rooturl!";
904 my $rewritten_parent;
905 Git::SVN::remove_username($expect_url);
906 if (defined($_merge_info)) {
907 $_merge_info =~ tr{ }{\n};
909 while (1) {
910 my $d = shift @$linear_refs or last;
911 unless (defined $last_rev) {
912 (undef, $last_rev, undef) = cmt_metadata("$d~1");
913 unless (defined $last_rev) {
914 fatal "Unable to extract revision information ",
915 "from commit $d~1";
918 if ($_dry_run) {
919 print "diff-tree $d~1 $d\n";
920 } else {
921 my $cmt_rev;
923 unless (defined($_merge_info) || ! $push_merge_info) {
924 $_merge_info = populate_merge_info($d, $gs,
925 $uuid,
926 $linear_refs,
927 $rewritten_parent);
930 my %ed_opts = ( r => $last_rev,
931 log => get_commit_entry($d)->{log},
932 ra => Git::SVN::Ra->new($url),
933 config => SVN::Core::config_get_config(
934 $Git::SVN::Ra::config_dir
936 tree_a => "$d~1",
937 tree_b => $d,
938 editor_cb => sub {
939 print "Committed r$_[0]\n";
940 $cmt_rev = $_[0];
942 mergeinfo => $_merge_info,
943 svn_path => '');
944 if (!Git::SVN::Editor->new(\%ed_opts)->apply_diff) {
945 print "No changes\n$d~1 == $d\n";
946 } elsif ($parents->{$d} && @{$parents->{$d}}) {
947 $gs->{inject_parents_dcommit}->{$cmt_rev} =
948 $parents->{$d};
950 $_fetch_all ? $gs->fetch_all : $gs->fetch;
951 $last_rev = $cmt_rev;
952 next if $_no_rebase;
954 # we always want to rebase against the current HEAD,
955 # not any head that was passed to us
956 my @diff = command('diff-tree', $d,
957 $gs->refname, '--');
958 my @finish;
959 if (@diff) {
960 @finish = rebase_cmd();
961 print STDERR "W: $d and ", $gs->refname,
962 " differ, using @finish:\n",
963 join("\n", @diff), "\n";
964 } else {
965 print "No changes between current HEAD and ",
966 $gs->refname,
967 "\nResetting to the latest ",
968 $gs->refname, "\n";
969 @finish = qw/reset --mixed/;
971 command_noisy(@finish, $gs->refname);
973 $rewritten_parent = command_oneline(qw/rev-parse HEAD/);
975 if (@diff) {
976 @refs = ();
977 my ($url_, $rev_, $uuid_, $gs_) =
978 working_head_info('HEAD', \@refs);
979 my ($linear_refs_, $parents_) =
980 linearize_history($gs_, \@refs);
981 if (scalar(@$linear_refs) !=
982 scalar(@$linear_refs_)) {
983 fatal "# of revisions changed ",
984 "\nbefore:\n",
985 join("\n", @$linear_refs),
986 "\n\nafter:\n",
987 join("\n", @$linear_refs_), "\n",
988 'If you are attempting to commit ',
989 "merges, try running:\n\t",
990 'git rebase --interactive',
991 '--preserve-merges ',
992 $gs->refname,
993 "\nBefore dcommitting";
995 if ($url_ ne $expect_url) {
996 if ($url_ eq $gs->metadata_url) {
997 print
998 "Accepting rewritten URL:",
999 " $url_\n";
1000 } else {
1001 fatal
1002 "URL mismatch after rebase:",
1003 " $url_ != $expect_url";
1006 if ($uuid_ ne $uuid) {
1007 fatal "uuid mismatch after rebase: ",
1008 "$uuid_ != $uuid";
1010 # remap parents
1011 my (%p, @l, $i);
1012 for ($i = 0; $i < scalar @$linear_refs; $i++) {
1013 my $new = $linear_refs_->[$i] or next;
1014 $p{$new} =
1015 $parents->{$linear_refs->[$i]};
1016 push @l, $new;
1018 $parents = \%p;
1019 $linear_refs = \@l;
1024 if ($old_head) {
1025 my $new_head = command_oneline(qw/rev-parse HEAD/);
1026 my $new_is_symbolic = eval {
1027 command_oneline(qw/symbolic-ref -q HEAD/);
1029 if ($new_is_symbolic) {
1030 print "dcommitted the branch ", $head, "\n";
1031 } else {
1032 print "dcommitted on a detached HEAD because you gave ",
1033 "a revision argument.\n",
1034 "The rewritten commit is: ", $new_head, "\n";
1036 command(['checkout', $old_head], STDERR => 0);
1039 unlink $gs->{index};
1042 sub cmd_branch {
1043 my ($branch_name, $head) = @_;
1045 unless (defined $branch_name && length $branch_name) {
1046 die(($_tag ? "tag" : "branch") . " name required\n");
1048 $head ||= 'HEAD';
1050 my (undef, $rev, undef, $gs) = working_head_info($head);
1051 my $src = $gs->full_pushurl;
1053 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
1054 my $allglobs = $remote->{ $_tag ? 'tags' : 'branches' };
1055 my $glob;
1056 if ($#{$allglobs} == 0) {
1057 $glob = $allglobs->[0];
1058 } else {
1059 unless(defined $_branch_dest) {
1060 die "Multiple ",
1061 $_tag ? "tag" : "branch",
1062 " paths defined for Subversion repository.\n",
1063 "You must specify where you want to create the ",
1064 $_tag ? "tag" : "branch",
1065 " with the --destination argument.\n";
1067 foreach my $g (@{$allglobs}) {
1068 my $re = Git::SVN::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 (!Git::SVN::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 push @cmd, "--preserve-merges" if $_preserve_merges;
1596 @cmd;
1599 sub post_fetch_checkout {
1600 return if $_no_checkout;
1601 my $gs = $Git::SVN::_head or return;
1602 return if verify_ref('refs/heads/master^0');
1604 # look for "trunk" ref if it exists
1605 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
1606 my $fetch = $remote->{fetch};
1607 if ($fetch) {
1608 foreach my $p (keys %$fetch) {
1609 basename($fetch->{$p}) eq 'trunk' or next;
1610 $gs = Git::SVN->new($fetch->{$p}, $gs->{repo_id}, $p);
1611 last;
1615 my $valid_head = verify_ref('HEAD^0');
1616 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1617 return if ($valid_head || !verify_ref('HEAD^0'));
1619 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1620 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1621 return if -f $index;
1623 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1624 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1625 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1626 print STDERR "Checked out HEAD:\n ",
1627 $gs->full_url, " r", $gs->last_rev, "\n";
1628 if (auto_create_empty_directories($gs)) {
1629 $gs->mkemptydirs($gs->last_rev);
1633 sub complete_svn_url {
1634 my ($url, $path) = @_;
1635 $path =~ s#/+$##;
1636 if ($path !~ m#^[a-z\+]+://#) {
1637 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1638 fatal("E: '$path' is not a complete URL ",
1639 "and a separate URL is not specified");
1641 return ($url, $path);
1643 return ($path, '');
1646 sub complete_url_ls_init {
1647 my ($ra, $repo_path, $switch, $pfx) = @_;
1648 unless ($repo_path) {
1649 print STDERR "W: $switch not specified\n";
1650 return;
1652 $repo_path =~ s#/+$##;
1653 if ($repo_path =~ m#^[a-z\+]+://#) {
1654 $ra = Git::SVN::Ra->new($repo_path);
1655 $repo_path = '';
1656 } else {
1657 $repo_path =~ s#^/+##;
1658 unless ($ra) {
1659 fatal("E: '$repo_path' is not a complete URL ",
1660 "and a separate URL is not specified");
1663 my $url = $ra->{url};
1664 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1665 my $k = "svn-remote.$gs->{repo_id}.url";
1666 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1667 if ($orig_url && ($orig_url ne $gs->{url})) {
1668 die "$k already set: $orig_url\n",
1669 "wanted to set to: $gs->{url}\n";
1671 command_oneline('config', $k, $gs->{url}) unless $orig_url;
1672 my $remote_path = "$gs->{path}/$repo_path";
1673 $remote_path =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
1674 $remote_path =~ s#/+#/#g;
1675 $remote_path =~ s#^/##g;
1676 $remote_path .= "/*" if $remote_path !~ /\*/;
1677 my ($n) = ($switch =~ /^--(\w+)/);
1678 if (length $pfx && $pfx !~ m#/$#) {
1679 die "--prefix='$pfx' must have a trailing slash '/'\n";
1681 command_noisy('config',
1682 '--add',
1683 "svn-remote.$gs->{repo_id}.$n",
1684 "$remote_path:refs/remotes/$pfx*" .
1685 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1688 sub verify_ref {
1689 my ($ref) = @_;
1690 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1691 { STDERR => 0 }); };
1694 sub get_tree_from_treeish {
1695 my ($treeish) = @_;
1696 # $treeish can be a symbolic ref, too:
1697 my $type = command_oneline(qw/cat-file -t/, $treeish);
1698 my $expected;
1699 while ($type eq 'tag') {
1700 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1702 if ($type eq 'commit') {
1703 $expected = (grep /^tree /, command(qw/cat-file commit/,
1704 $treeish))[0];
1705 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1706 die "Unable to get tree from $treeish\n" unless $expected;
1707 } elsif ($type eq 'tree') {
1708 $expected = $treeish;
1709 } else {
1710 die "$treeish is a $type, expected tree, tag or commit\n";
1712 return $expected;
1715 sub get_commit_entry {
1716 my ($treeish) = shift;
1717 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1718 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1719 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1720 open my $log_fh, '>', $commit_editmsg or croak $!;
1722 my $type = command_oneline(qw/cat-file -t/, $treeish);
1723 if ($type eq 'commit' || $type eq 'tag') {
1724 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1725 $type, $treeish);
1726 my $in_msg = 0;
1727 my $author;
1728 my $saw_from = 0;
1729 my $msgbuf = "";
1730 while (<$msg_fh>) {
1731 if (!$in_msg) {
1732 $in_msg = 1 if (/^\s*$/);
1733 $author = $1 if (/^author (.*>)/);
1734 } elsif (/^git-svn-id: /) {
1735 # skip this for now, we regenerate the
1736 # correct one on re-fetch anyways
1737 # TODO: set *:merge properties or like...
1738 } else {
1739 if (/^From:/ || /^Signed-off-by:/) {
1740 $saw_from = 1;
1742 $msgbuf .= $_;
1745 $msgbuf =~ s/\s+$//s;
1746 if ($Git::SVN::_add_author_from && defined($author)
1747 && !$saw_from) {
1748 $msgbuf .= "\n\nFrom: $author";
1750 print $log_fh $msgbuf or croak $!;
1751 command_close_pipe($msg_fh, $ctx);
1753 close $log_fh or croak $!;
1755 if ($_edit || ($type eq 'tree')) {
1756 chomp(my $editor = command_oneline(qw(var GIT_EDITOR)));
1757 system('sh', '-c', $editor.' "$@"', $editor, $commit_editmsg);
1759 rename $commit_editmsg, $commit_msg or croak $!;
1761 require Encode;
1762 # SVN requires messages to be UTF-8 when entering the repo
1763 local $/;
1764 open $log_fh, '<', $commit_msg or croak $!;
1765 binmode $log_fh;
1766 chomp($log_entry{log} = <$log_fh>);
1768 my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
1769 my $msg = $log_entry{log};
1771 eval { $msg = Encode::decode($enc, $msg, 1) };
1772 if ($@) {
1773 die "Could not decode as $enc:\n", $msg,
1774 "\nPerhaps you need to set i18n.commitencoding\n";
1777 eval { $msg = Encode::encode('UTF-8', $msg, 1) };
1778 die "Could not encode as UTF-8:\n$msg\n" if $@;
1780 $log_entry{log} = $msg;
1782 close $log_fh or croak $!;
1784 unlink $commit_msg;
1785 \%log_entry;
1788 sub s_to_file {
1789 my ($str, $file, $mode) = @_;
1790 open my $fd,'>',$file or croak $!;
1791 print $fd $str,"\n" or croak $!;
1792 close $fd or croak $!;
1793 chmod ($mode &~ umask, $file) if (defined $mode);
1796 sub file_to_s {
1797 my $file = shift;
1798 open my $fd,'<',$file or croak "$!: file: $file\n";
1799 local $/;
1800 my $ret = <$fd>;
1801 close $fd or croak $!;
1802 $ret =~ s/\s*$//s;
1803 return $ret;
1806 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1807 sub load_authors {
1808 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1809 my $log = $cmd eq 'log';
1810 while (<$authors>) {
1811 chomp;
1812 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1813 my ($user, $name, $email) = ($1, $2, $3);
1814 if ($log) {
1815 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1816 } else {
1817 $users{$user} = [$name, $email];
1820 close $authors or croak $!;
1823 # convert GetOpt::Long specs for use by git-config
1824 sub read_git_config {
1825 my $opts = shift;
1826 my @config_only;
1827 foreach my $o (keys %$opts) {
1828 # if we have mixedCase and a long option-only, then
1829 # it's a config-only variable that we don't need for
1830 # the command-line.
1831 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1832 my $v = $opts->{$o};
1833 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1834 $key =~ s/-//g;
1835 my $arg = 'git config';
1836 $arg .= ' --int' if ($o =~ /[:=]i$/);
1837 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1838 if (ref $v eq 'ARRAY') {
1839 chomp(my @tmp = `$arg --get-all svn.$key`);
1840 @$v = @tmp if @tmp;
1841 } else {
1842 chomp(my $tmp = `$arg --get svn.$key`);
1843 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1844 $$v = $tmp;
1848 delete @$opts{@config_only} if @config_only;
1851 sub extract_metadata {
1852 my $id = shift or return (undef, undef, undef);
1853 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1854 \s([a-f\d\-]+)$/ix);
1855 if (!defined $rev || !$uuid || !$url) {
1856 # some of the original repositories I made had
1857 # identifiers like this:
1858 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/i);
1860 return ($url, $rev, $uuid);
1863 sub cmt_metadata {
1864 return extract_metadata((grep(/^git-svn-id: /,
1865 command(qw/cat-file commit/, shift)))[-1]);
1868 sub cmt_sha2rev_batch {
1869 my %s2r;
1870 my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1871 my $list = shift;
1873 foreach my $sha (@{$list}) {
1874 my $first = 1;
1875 my $size = 0;
1876 print $out $sha, "\n";
1878 while (my $line = <$in>) {
1879 if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1880 last;
1881 } elsif ($first &&
1882 $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1883 $first = 0;
1884 $size = $1;
1885 next;
1886 } elsif ($line =~ /^(git-svn-id: )/) {
1887 my (undef, $rev, undef) =
1888 extract_metadata($line);
1889 $s2r{$sha} = $rev;
1892 $size -= length($line);
1893 last if ($size == 0);
1897 command_close_bidi_pipe($pid, $in, $out, $ctx);
1899 return \%s2r;
1902 sub working_head_info {
1903 my ($head, $refs) = @_;
1904 my @args = qw/rev-list --first-parent --pretty=medium/;
1905 my ($fh, $ctx) = command_output_pipe(@args, $head);
1906 my $hash;
1907 my %max;
1908 while (<$fh>) {
1909 if ( m{^commit ($::sha1)$} ) {
1910 unshift @$refs, $hash if $hash and $refs;
1911 $hash = $1;
1912 next;
1914 next unless s{^\s*(git-svn-id:)}{$1};
1915 my ($url, $rev, $uuid) = extract_metadata($_);
1916 if (defined $url && defined $rev) {
1917 next if $max{$url} and $max{$url} < $rev;
1918 if (my $gs = Git::SVN->find_by_url($url)) {
1919 my $c = $gs->rev_map_get($rev, $uuid);
1920 if ($c && $c eq $hash) {
1921 close $fh; # break the pipe
1922 return ($url, $rev, $uuid, $gs);
1923 } else {
1924 $max{$url} ||= $gs->rev_map_max;
1929 command_close_pipe($fh, $ctx);
1930 (undef, undef, undef, undef);
1933 sub read_commit_parents {
1934 my ($parents, $c) = @_;
1935 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1936 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1937 @{$parents->{$c}} = split(/ /, $p);
1940 sub linearize_history {
1941 my ($gs, $refs) = @_;
1942 my %parents;
1943 foreach my $c (@$refs) {
1944 read_commit_parents(\%parents, $c);
1947 my @linear_refs;
1948 my %skip = ();
1949 my $last_svn_commit = $gs->last_commit;
1950 foreach my $c (reverse @$refs) {
1951 next if $c eq $last_svn_commit;
1952 last if $skip{$c};
1954 unshift @linear_refs, $c;
1955 $skip{$c} = 1;
1957 # we only want the first parent to diff against for linear
1958 # history, we save the rest to inject when we finalize the
1959 # svn commit
1960 my $fp_a = verify_ref("$c~1");
1961 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1962 if (!$fp_a || !$fp_b) {
1963 die "Commit $c\n",
1964 "has no parent commit, and therefore ",
1965 "nothing to diff against.\n",
1966 "You should be working from a repository ",
1967 "originally created by git-svn\n";
1969 if ($fp_a ne $fp_b) {
1970 die "$c~1 = $fp_a, however parsing commit $c ",
1971 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1974 foreach my $p (@{$parents{$c}}) {
1975 $skip{$p} = 1;
1978 (\@linear_refs, \%parents);
1981 sub find_file_type_and_diff_status {
1982 my ($path) = @_;
1983 return ('dir', '') if $path eq '';
1985 my $diff_output =
1986 command_oneline(qw(diff --cached --name-status --), $path) || "";
1987 my $diff_status = (split(' ', $diff_output))[0] || "";
1989 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1991 return (undef, undef) if !$diff_status && !$ls_tree;
1993 if ($diff_status eq "A") {
1994 return ("link", $diff_status) if -l $path;
1995 return ("dir", $diff_status) if -d $path;
1996 return ("file", $diff_status);
1999 my $mode = (split(' ', $ls_tree))[0] || "";
2001 return ("link", $diff_status) if $mode eq "120000";
2002 return ("dir", $diff_status) if $mode eq "040000";
2003 return ("file", $diff_status);
2006 sub md5sum {
2007 my $arg = shift;
2008 my $ref = ref $arg;
2009 my $md5 = Digest::MD5->new();
2010 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
2011 $md5->addfile($arg) or croak $!;
2012 } elsif ($ref eq 'SCALAR') {
2013 $md5->add($$arg) or croak $!;
2014 } elsif (!$ref) {
2015 $md5->add($arg) or croak $!;
2016 } else {
2017 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
2019 return $md5->hexdigest();
2022 sub gc_directory {
2023 if ($can_compress && -f $_ && basename($_) eq "unhandled.log") {
2024 my $out_filename = $_ . ".gz";
2025 open my $in_fh, "<", $_ or die "Unable to open $_: $!\n";
2026 binmode $in_fh;
2027 my $gz = Compress::Zlib::gzopen($out_filename, "ab") or
2028 die "Unable to open $out_filename: $!\n";
2030 my $res;
2031 while ($res = sysread($in_fh, my $str, 1024)) {
2032 $gz->gzwrite($str) or
2033 die "Unable to write: ".$gz->gzerror()."!\n";
2035 unlink $_ or die "unlink $File::Find::name: $!\n";
2036 } elsif (-f $_ && basename($_) eq "index") {
2037 unlink $_ or die "unlink $_: $!\n";
2041 package Git::SVN;
2042 use strict;
2043 use warnings;
2044 use Fcntl qw/:DEFAULT :seek/;
2045 use constant rev_map_fmt => 'NH40';
2046 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
2047 $_repack $_repack_flags $_use_svm_props $_head
2048 $_use_svnsync_props $no_reuse_existing $_minimize_url
2049 $_use_log_author $_add_author_from $_localtime/;
2050 use Carp qw/croak/;
2051 use File::Path qw/mkpath/;
2052 use File::Copy qw/copy/;
2053 use IPC::Open3;
2054 use Time::Local;
2055 use Memoize; # core since 5.8.0, Jul 2002
2056 use Memoize::Storable;
2057 use POSIX qw(:signal_h);
2059 my ($_gc_nr, $_gc_period);
2061 # properties that we do not log:
2062 my %SKIP_PROP;
2063 BEGIN {
2064 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
2065 svn:special svn:executable
2066 svn:entry:committed-rev
2067 svn:entry:last-author
2068 svn:entry:uuid
2069 svn:entry:committed-date/;
2071 # some options are read globally, but can be overridden locally
2072 # per [svn-remote "..."] section. Command-line options will *NOT*
2073 # override options set in an [svn-remote "..."] section
2074 no strict 'refs';
2075 for my $option (qw/follow_parent no_metadata use_svm_props
2076 use_svnsync_props/) {
2077 my $key = $option;
2078 $key =~ tr/_//d;
2079 my $prop = "-$option";
2080 *$option = sub {
2081 my ($self) = @_;
2082 return $self->{$prop} if exists $self->{$prop};
2083 my $k = "svn-remote.$self->{repo_id}.$key";
2084 eval { command_oneline(qw/config --get/, $k) };
2085 if ($@) {
2086 $self->{$prop} = ${"Git::SVN::_$option"};
2087 } else {
2088 my $v = command_oneline(qw/config --bool/,$k);
2089 $self->{$prop} = $v eq 'false' ? 0 : 1;
2091 return $self->{$prop};
2097 my (%LOCKFILES, %INDEX_FILES);
2098 END {
2099 unlink keys %LOCKFILES if %LOCKFILES;
2100 unlink keys %INDEX_FILES if %INDEX_FILES;
2103 sub resolve_local_globs {
2104 my ($url, $fetch, $glob_spec) = @_;
2105 return unless defined $glob_spec;
2106 my $ref = $glob_spec->{ref};
2107 my $path = $glob_spec->{path};
2108 foreach (command(qw#for-each-ref --format=%(refname) refs/#)) {
2109 next unless m#^$ref->{regex}$#;
2110 my $p = $1;
2111 my $pathname = desanitize_refname($path->full_path($p));
2112 my $refname = desanitize_refname($ref->full_path($p));
2113 if (my $existing = $fetch->{$pathname}) {
2114 if ($existing ne $refname) {
2115 die "Refspec conflict:\n",
2116 "existing: $existing\n",
2117 " globbed: $refname\n";
2119 my $u = (::cmt_metadata("$refname"))[0];
2120 $u =~ s!^\Q$url\E(/|$)!! or die
2121 "$refname: '$url' not found in '$u'\n";
2122 if ($pathname ne $u) {
2123 warn "W: Refspec glob conflict ",
2124 "(ref: $refname):\n",
2125 "expected path: $pathname\n",
2126 " real path: $u\n",
2127 "Continuing ahead with $u\n";
2128 next;
2130 } else {
2131 $fetch->{$pathname} = $refname;
2136 sub parse_revision_argument {
2137 my ($base, $head) = @_;
2138 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
2139 return ($base, $head);
2141 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
2142 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
2143 return ($head, $head) if ($::_revision eq 'HEAD');
2144 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
2145 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
2146 die "revision argument: $::_revision not understood by git-svn\n";
2149 sub fetch_all {
2150 my ($repo_id, $remotes) = @_;
2151 if (ref $repo_id) {
2152 my $gs = $repo_id;
2153 $repo_id = undef;
2154 $repo_id = $gs->{repo_id};
2156 $remotes ||= read_all_remotes();
2157 my $remote = $remotes->{$repo_id} or
2158 die "[svn-remote \"$repo_id\"] unknown\n";
2159 my $fetch = $remote->{fetch};
2160 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
2161 my (@gs, @globs);
2162 my $ra = Git::SVN::Ra->new($url);
2163 my $uuid = $ra->get_uuid;
2164 my $head = $ra->get_latest_revnum;
2166 # ignore errors, $head revision may not even exist anymore
2167 eval { $ra->get_log("", $head, 0, 1, 0, 1, sub { $head = $_[1] }) };
2168 warn "W: $@\n" if $@;
2170 my $base = defined $fetch ? $head : 0;
2172 # read the max revs for wildcard expansion (branches/*, tags/*)
2173 foreach my $t (qw/branches tags/) {
2174 defined $remote->{$t} or next;
2175 push @globs, @{$remote->{$t}};
2177 my $max_rev = eval { tmp_config(qw/--int --get/,
2178 "svn-remote.$repo_id.${t}-maxRev") };
2179 if (defined $max_rev && ($max_rev < $base)) {
2180 $base = $max_rev;
2181 } elsif (!defined $max_rev) {
2182 $base = 0;
2186 if ($fetch) {
2187 foreach my $p (sort keys %$fetch) {
2188 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
2189 my $lr = $gs->rev_map_max;
2190 if (defined $lr) {
2191 $base = $lr if ($lr < $base);
2193 push @gs, $gs;
2197 ($base, $head) = parse_revision_argument($base, $head);
2198 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
2201 sub read_all_remotes {
2202 my $r = {};
2203 my $use_svm_props = eval { command_oneline(qw/config --bool
2204 svn.useSvmProps/) };
2205 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
2206 my $svn_refspec = qr{\s*(.*?)\s*:\s*(.+?)\s*};
2207 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
2208 if (m!^(.+)\.fetch=$svn_refspec$!) {
2209 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
2210 die("svn-remote.$remote: remote ref '$remote_ref' "
2211 . "must start with 'refs/'\n")
2212 unless $remote_ref =~ m{^refs/};
2213 $local_ref = uri_decode($local_ref);
2214 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
2215 $r->{$remote}->{svm} = {} if $use_svm_props;
2216 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
2217 $r->{$1}->{svm} = {};
2218 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
2219 $r->{$1}->{url} = $2;
2220 } elsif (m!^(.+)\.pushurl=\s*(.*)\s*$!) {
2221 $r->{$1}->{pushurl} = $2;
2222 } elsif (m!^(.+)\.ignore-refs=\s*(.*)\s*$!) {
2223 $r->{$1}->{ignore_refs_regex} = $2;
2224 } elsif (m!^(.+)\.(branches|tags)=$svn_refspec$!) {
2225 my ($remote, $t, $local_ref, $remote_ref) =
2226 ($1, $2, $3, $4);
2227 die("svn-remote.$remote: remote ref '$remote_ref' ($t) "
2228 . "must start with 'refs/'\n")
2229 unless $remote_ref =~ m{^refs/};
2230 $local_ref = uri_decode($local_ref);
2231 my $rs = {
2232 t => $t,
2233 remote => $remote,
2234 path => Git::SVN::GlobSpec->new($local_ref, 1),
2235 ref => Git::SVN::GlobSpec->new($remote_ref, 0) };
2236 if (length($rs->{ref}->{right}) != 0) {
2237 die "The '*' glob character must be the last ",
2238 "character of '$remote_ref'\n";
2240 push @{ $r->{$remote}->{$t} }, $rs;
2244 map {
2245 if (defined $r->{$_}->{svm}) {
2246 my $svm;
2247 eval {
2248 my $section = "svn-remote.$_";
2249 $svm = {
2250 source => tmp_config('--get',
2251 "$section.svm-source"),
2252 replace => tmp_config('--get',
2253 "$section.svm-replace"),
2256 $r->{$_}->{svm} = $svm;
2258 } keys %$r;
2260 foreach my $remote (keys %$r) {
2261 foreach ( grep { defined $_ }
2262 map { $r->{$remote}->{$_} } qw(branches tags) ) {
2263 foreach my $rs ( @$_ ) {
2264 $rs->{ignore_refs_regex} =
2265 $r->{$remote}->{ignore_refs_regex};
2273 sub init_vars {
2274 $_gc_nr = $_gc_period = 1000;
2275 if (defined $_repack || defined $_repack_flags) {
2276 warn "Repack options are obsolete; they have no effect.\n";
2280 sub verify_remotes_sanity {
2281 return unless -d $ENV{GIT_DIR};
2282 my %seen;
2283 foreach (command(qw/config -l/)) {
2284 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
2285 if ($seen{$1}) {
2286 die "Remote ref refs/remote/$1 is tracked by",
2287 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
2288 "Please resolve this ambiguity in ",
2289 "your git configuration file before ",
2290 "continuing\n";
2292 $seen{$1} = $_;
2297 sub find_existing_remote {
2298 my ($url, $remotes) = @_;
2299 return undef if $no_reuse_existing;
2300 my $existing;
2301 foreach my $repo_id (keys %$remotes) {
2302 my $u = $remotes->{$repo_id}->{url} or next;
2303 next if $u ne $url;
2304 $existing = $repo_id;
2305 last;
2307 $existing;
2310 sub init_remote_config {
2311 my ($self, $url, $no_write) = @_;
2312 $url =~ s!/+$!!; # strip trailing slash
2313 my $r = read_all_remotes();
2314 my $existing = find_existing_remote($url, $r);
2315 if ($existing) {
2316 unless ($no_write) {
2317 print STDERR "Using existing ",
2318 "[svn-remote \"$existing\"]\n";
2320 $self->{repo_id} = $existing;
2321 } elsif ($_minimize_url) {
2322 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
2323 $existing = find_existing_remote($min_url, $r);
2324 if ($existing) {
2325 unless ($no_write) {
2326 print STDERR "Using existing ",
2327 "[svn-remote \"$existing\"]\n";
2329 $self->{repo_id} = $existing;
2331 if ($min_url ne $url) {
2332 unless ($no_write) {
2333 print STDERR "Using higher level of URL: ",
2334 "$url => $min_url\n";
2336 my $old_path = $self->{path};
2337 $self->{path} = $url;
2338 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
2339 if (length $old_path) {
2340 $self->{path} .= "/$old_path";
2342 $url = $min_url;
2345 my $orig_url;
2346 if (!$existing) {
2347 # verify that we aren't overwriting anything:
2348 $orig_url = eval {
2349 command_oneline('config', '--get',
2350 "svn-remote.$self->{repo_id}.url")
2352 if ($orig_url && ($orig_url ne $url)) {
2353 die "svn-remote.$self->{repo_id}.url already set: ",
2354 "$orig_url\nwanted to set to: $url\n";
2357 my ($xrepo_id, $xpath) = find_ref($self->refname);
2358 if (!$no_write && defined $xpath) {
2359 die "svn-remote.$xrepo_id.fetch already set to track ",
2360 "$xpath:", $self->refname, "\n";
2362 unless ($no_write) {
2363 command_noisy('config',
2364 "svn-remote.$self->{repo_id}.url", $url);
2365 $self->{path} =~ s{^/}{};
2366 $self->{path} =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
2367 command_noisy('config', '--add',
2368 "svn-remote.$self->{repo_id}.fetch",
2369 "$self->{path}:".$self->refname);
2371 $self->{url} = $url;
2374 sub find_by_url { # repos_root and, path are optional
2375 my ($class, $full_url, $repos_root, $path) = @_;
2377 return undef unless defined $full_url;
2378 remove_username($full_url);
2379 remove_username($repos_root) if defined $repos_root;
2380 my $remotes = read_all_remotes();
2381 if (defined $full_url && defined $repos_root && !defined $path) {
2382 $path = $full_url;
2383 $path =~ s#^\Q$repos_root\E(?:/|$)##;
2385 foreach my $repo_id (keys %$remotes) {
2386 my $u = $remotes->{$repo_id}->{url} or next;
2387 remove_username($u);
2388 next if defined $repos_root && $repos_root ne $u;
2390 my $fetch = $remotes->{$repo_id}->{fetch} || {};
2391 foreach my $t (qw/branches tags/) {
2392 foreach my $globspec (@{$remotes->{$repo_id}->{$t}}) {
2393 resolve_local_globs($u, $fetch, $globspec);
2396 my $p = $path;
2397 my $rwr = rewrite_root({repo_id => $repo_id});
2398 my $svm = $remotes->{$repo_id}->{svm}
2399 if defined $remotes->{$repo_id}->{svm};
2400 unless (defined $p) {
2401 $p = $full_url;
2402 my $z = $u;
2403 my $prefix = '';
2404 if ($rwr) {
2405 $z = $rwr;
2406 remove_username($z);
2407 } elsif (defined $svm) {
2408 $z = $svm->{source};
2409 $prefix = $svm->{replace};
2410 $prefix =~ s#^\Q$u\E(?:/|$)##;
2411 $prefix =~ s#/$##;
2413 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
2415 foreach my $f (keys %$fetch) {
2416 next if $f ne $p;
2417 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
2420 undef;
2423 sub init {
2424 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
2425 my $self = _new($class, $repo_id, $ref_id, $path);
2426 if (defined $url) {
2427 $self->init_remote_config($url, $no_write);
2429 $self;
2432 sub find_ref {
2433 my ($ref_id) = @_;
2434 foreach (command(qw/config -l/)) {
2435 next unless m!^svn-remote\.(.+)\.fetch=
2436 \s*(.*?)\s*:\s*(.+?)\s*$!x;
2437 my ($repo_id, $path, $ref) = ($1, $2, $3);
2438 if ($ref eq $ref_id) {
2439 $path = '' if ($path =~ m#^\./?#);
2440 return ($repo_id, $path);
2443 (undef, undef, undef);
2446 sub new {
2447 my ($class, $ref_id, $repo_id, $path) = @_;
2448 if (defined $ref_id && !defined $repo_id && !defined $path) {
2449 ($repo_id, $path) = find_ref($ref_id);
2450 if (!defined $repo_id) {
2451 die "Could not find a \"svn-remote.*.fetch\" key ",
2452 "in the repository configuration matching: ",
2453 "$ref_id\n";
2456 my $self = _new($class, $repo_id, $ref_id, $path);
2457 if (!defined $self->{path} || !length $self->{path}) {
2458 my $fetch = command_oneline('config', '--get',
2459 "svn-remote.$repo_id.fetch",
2460 ":$ref_id\$") or
2461 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
2462 "\":$ref_id\$\" in config\n";
2463 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
2465 $self->{path} =~ s{/+}{/}g;
2466 $self->{path} =~ s{\A/}{};
2467 $self->{path} =~ s{/\z}{};
2468 $self->{url} = command_oneline('config', '--get',
2469 "svn-remote.$repo_id.url") or
2470 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
2471 $self->{pushurl} = eval { command_oneline('config', '--get',
2472 "svn-remote.$repo_id.pushurl") };
2473 $self->rebuild;
2474 $self;
2477 sub refname {
2478 my ($refname) = $_[0]->{ref_id} ;
2480 # It cannot end with a slash /, we'll throw up on this because
2481 # SVN can't have directories with a slash in their name, either:
2482 if ($refname =~ m{/$}) {
2483 die "ref: '$refname' ends with a trailing slash, this is ",
2484 "not permitted by git nor Subversion\n";
2487 # It cannot have ASCII control character space, tilde ~, caret ^,
2488 # colon :, question-mark ?, asterisk *, space, or open bracket [
2489 # anywhere.
2491 # Additionally, % must be escaped because it is used for escaping
2492 # and we want our escaped refname to be reversible
2493 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
2495 # no slash-separated component can begin with a dot .
2496 # /.* becomes /%2E*
2497 $refname =~ s{/\.}{/%2E}g;
2499 # It cannot have two consecutive dots .. anywhere
2500 # .. becomes %2E%2E
2501 $refname =~ s{\.\.}{%2E%2E}g;
2503 # trailing dots and .lock are not allowed
2504 # .$ becomes %2E and .lock becomes %2Elock
2505 $refname =~ s{\.(?=$|lock$)}{%2E};
2507 # the sequence @{ is used to access the reflog
2508 # @{ becomes %40{
2509 $refname =~ s{\@\{}{%40\{}g;
2511 return $refname;
2514 sub desanitize_refname {
2515 my ($refname) = @_;
2516 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
2517 return $refname;
2520 sub svm_uuid {
2521 my ($self) = @_;
2522 return $self->{svm}->{uuid} if $self->svm;
2523 $self->ra;
2524 unless ($self->{svm}) {
2525 die "SVM UUID not cached, and reading remotely failed\n";
2527 $self->{svm}->{uuid};
2530 sub svm {
2531 my ($self) = @_;
2532 return $self->{svm} if $self->{svm};
2533 my $svm;
2534 # see if we have it in our config, first:
2535 eval {
2536 my $section = "svn-remote.$self->{repo_id}";
2537 $svm = {
2538 source => tmp_config('--get', "$section.svm-source"),
2539 uuid => tmp_config('--get', "$section.svm-uuid"),
2540 replace => tmp_config('--get', "$section.svm-replace"),
2543 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
2544 $self->{svm} = $svm;
2546 $self->{svm};
2549 sub _set_svm_vars {
2550 my ($self, $ra) = @_;
2551 return $ra if $self->svm;
2553 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
2554 "(svm:source, svm:uuid) ",
2555 "from the following URLs:\n" );
2556 sub read_svm_props {
2557 my ($self, $ra, $path, $r) = @_;
2558 my $props = ($ra->get_dir($path, $r))[2];
2559 my $src = $props->{'svm:source'};
2560 my $uuid = $props->{'svm:uuid'};
2561 return undef if (!$src || !$uuid);
2563 chomp($src, $uuid);
2565 $uuid =~ m{^[0-9a-f\-]{30,}$}i
2566 or die "doesn't look right - svm:uuid is '$uuid'\n";
2568 # the '!' is used to mark the repos_root!/relative/path
2569 $src =~ s{/?!/?}{/};
2570 $src =~ s{/+$}{}; # no trailing slashes please
2571 # username is of no interest
2572 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
2574 my $replace = $ra->{url};
2575 $replace .= "/$path" if length $path;
2577 my $section = "svn-remote.$self->{repo_id}";
2578 tmp_config("$section.svm-source", $src);
2579 tmp_config("$section.svm-replace", $replace);
2580 tmp_config("$section.svm-uuid", $uuid);
2581 $self->{svm} = {
2582 source => $src,
2583 uuid => $uuid,
2584 replace => $replace
2588 my $r = $ra->get_latest_revnum;
2589 my $path = $self->{path};
2590 my %tried;
2591 while (length $path) {
2592 unless ($tried{"$self->{url}/$path"}) {
2593 return $ra if $self->read_svm_props($ra, $path, $r);
2594 $tried{"$self->{url}/$path"} = 1;
2596 $path =~ s#/?[^/]+$##;
2598 die "Path: '$path' should be ''\n" if $path ne '';
2599 return $ra if $self->read_svm_props($ra, $path, $r);
2600 $tried{"$self->{url}/$path"} = 1;
2602 if ($ra->{repos_root} eq $self->{url}) {
2603 die @err, (map { " $_\n" } keys %tried), "\n";
2606 # nope, make sure we're connected to the repository root:
2607 my $ok;
2608 my @tried_b;
2609 $path = $ra->{svn_path};
2610 $ra = Git::SVN::Ra->new($ra->{repos_root});
2611 while (length $path) {
2612 unless ($tried{"$ra->{url}/$path"}) {
2613 $ok = $self->read_svm_props($ra, $path, $r);
2614 last if $ok;
2615 $tried{"$ra->{url}/$path"} = 1;
2617 $path =~ s#/?[^/]+$##;
2619 die "Path: '$path' should be ''\n" if $path ne '';
2620 $ok ||= $self->read_svm_props($ra, $path, $r);
2621 $tried{"$ra->{url}/$path"} = 1;
2622 if (!$ok) {
2623 die @err, (map { " $_\n" } keys %tried), "\n";
2625 Git::SVN::Ra->new($self->{url});
2628 sub svnsync {
2629 my ($self) = @_;
2630 return $self->{svnsync} if $self->{svnsync};
2632 if ($self->no_metadata) {
2633 die "Can't have both 'noMetadata' and ",
2634 "'useSvnsyncProps' options set!\n";
2636 if ($self->rewrite_root) {
2637 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
2638 "options set!\n";
2640 if ($self->rewrite_uuid) {
2641 die "Can't have both 'useSvnsyncProps' and 'rewriteUUID' ",
2642 "options set!\n";
2645 my $svnsync;
2646 # see if we have it in our config, first:
2647 eval {
2648 my $section = "svn-remote.$self->{repo_id}";
2650 my $url = tmp_config('--get', "$section.svnsync-url");
2651 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2652 die "doesn't look right - svn:sync-from-url is '$url'\n";
2654 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
2655 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2656 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2658 $svnsync = { url => $url, uuid => $uuid }
2660 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
2661 return $self->{svnsync} = $svnsync;
2664 my $err = "useSvnsyncProps set, but failed to read " .
2665 "svnsync property: svn:sync-from-";
2666 my $rp = $self->ra->rev_proplist(0);
2668 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
2669 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2670 die "doesn't look right - svn:sync-from-url is '$url'\n";
2672 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
2673 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2674 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2676 my $section = "svn-remote.$self->{repo_id}";
2677 tmp_config('--add', "$section.svnsync-uuid", $uuid);
2678 tmp_config('--add', "$section.svnsync-url", $url);
2679 return $self->{svnsync} = { url => $url, uuid => $uuid };
2682 # this allows us to memoize our SVN::Ra UUID locally and avoid a
2683 # remote lookup (useful for 'git svn log').
2684 sub ra_uuid {
2685 my ($self) = @_;
2686 unless ($self->{ra_uuid}) {
2687 my $key = "svn-remote.$self->{repo_id}.uuid";
2688 my $uuid = eval { tmp_config('--get', $key) };
2689 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/i) {
2690 $self->{ra_uuid} = $uuid;
2691 } else {
2692 die "ra_uuid called without URL\n" unless $self->{url};
2693 $self->{ra_uuid} = $self->ra->get_uuid;
2694 tmp_config('--add', $key, $self->{ra_uuid});
2697 $self->{ra_uuid};
2700 sub _set_repos_root {
2701 my ($self, $repos_root) = @_;
2702 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2703 $repos_root ||= $self->ra->{repos_root};
2704 tmp_config($k, $repos_root);
2705 $repos_root;
2708 sub repos_root {
2709 my ($self) = @_;
2710 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2711 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
2714 sub ra {
2715 my ($self) = shift;
2716 my $ra = Git::SVN::Ra->new($self->{url});
2717 $self->_set_repos_root($ra->{repos_root});
2718 if ($self->use_svm_props && !$self->{svm}) {
2719 if ($self->no_metadata) {
2720 die "Can't have both 'noMetadata' and ",
2721 "'useSvmProps' options set!\n";
2722 } elsif ($self->use_svnsync_props) {
2723 die "Can't have both 'useSvnsyncProps' and ",
2724 "'useSvmProps' options set!\n";
2726 $ra = $self->_set_svm_vars($ra);
2727 $self->{-want_revprops} = 1;
2729 $ra;
2732 # prop_walk(PATH, REV, SUB)
2733 # -------------------------
2734 # Recursively traverse PATH at revision REV and invoke SUB for each
2735 # directory that contains a SVN property. SUB will be invoked as
2736 # follows: &SUB(gs, path, props); where `gs' is this instance of
2737 # Git::SVN, `path' the path to the directory where the properties
2738 # `props' were found. The `path' will be relative to point of checkout,
2739 # that is, if url://repo/trunk is the current Git branch, and that
2740 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
2741 # as `path' (note the trailing `/').
2742 sub prop_walk {
2743 my ($self, $path, $rev, $sub) = @_;
2745 $path =~ s#^/##;
2746 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2747 $path =~ s#^/*#/#g;
2748 my $p = $path;
2749 # Strip the irrelevant part of the path.
2750 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2751 # Ensure the path is terminated by a `/'.
2752 $p =~ s#/*$#/#;
2754 # The properties contain all the internal SVN stuff nobody
2755 # (usually) cares about.
2756 my $interesting_props = 0;
2757 foreach (keys %{$props}) {
2758 # If it doesn't start with `svn:', it must be a
2759 # user-defined property.
2760 ++$interesting_props and next if $_ !~ /^svn:/;
2761 # FIXME: Fragile, if SVN adds new public properties,
2762 # this needs to be updated.
2763 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2764 |eol-style|mime-type
2765 |externals|needs-lock)$/x;
2767 &$sub($self, $p, $props) if $interesting_props;
2769 foreach (sort keys %$dirent) {
2770 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
2771 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
2775 sub last_rev { ($_[0]->last_rev_commit)[0] }
2776 sub last_commit { ($_[0]->last_rev_commit)[1] }
2778 # returns the newest SVN revision number and newest commit SHA1
2779 sub last_rev_commit {
2780 my ($self) = @_;
2781 if (defined $self->{last_rev} && defined $self->{last_commit}) {
2782 return ($self->{last_rev}, $self->{last_commit});
2784 my $c = ::verify_ref($self->refname.'^0');
2785 if ($c && !$self->use_svm_props && !$self->no_metadata) {
2786 my $rev = (::cmt_metadata($c))[1];
2787 if (defined $rev) {
2788 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2789 return ($rev, $c);
2792 my $map_path = $self->map_path;
2793 unless (-e $map_path) {
2794 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2795 return (undef, undef);
2797 my ($rev, $commit) = $self->rev_map_max(1);
2798 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2799 return ($rev, $commit);
2802 sub get_fetch_range {
2803 my ($self, $min, $max) = @_;
2804 $max ||= $self->ra->get_latest_revnum;
2805 $min ||= $self->rev_map_max;
2806 (++$min, $max);
2809 sub tmp_config {
2810 my (@args) = @_;
2811 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2812 my $config = "$ENV{GIT_DIR}/svn/.metadata";
2813 if (! -f $config && -f $old_def_config) {
2814 rename $old_def_config, $config or
2815 die "Failed rename $old_def_config => $config: $!\n";
2817 my $old_config = $ENV{GIT_CONFIG};
2818 $ENV{GIT_CONFIG} = $config;
2819 $@ = undef;
2820 my @ret = eval {
2821 unless (-f $config) {
2822 mkfile($config);
2823 open my $fh, '>', $config or
2824 die "Can't open $config: $!\n";
2825 print $fh "; This file is used internally by ",
2826 "git-svn\n" or die
2827 "Couldn't write to $config: $!\n";
2828 print $fh "; You should not have to edit it\n" or
2829 die "Couldn't write to $config: $!\n";
2830 close $fh or die "Couldn't close $config: $!\n";
2832 command('config', @args);
2834 my $err = $@;
2835 if (defined $old_config) {
2836 $ENV{GIT_CONFIG} = $old_config;
2837 } else {
2838 delete $ENV{GIT_CONFIG};
2840 die $err if $err;
2841 wantarray ? @ret : $ret[0];
2844 sub tmp_index_do {
2845 my ($self, $sub) = @_;
2846 my $old_index = $ENV{GIT_INDEX_FILE};
2847 $ENV{GIT_INDEX_FILE} = $self->{index};
2848 $@ = undef;
2849 my @ret = eval {
2850 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2851 mkpath([$dir]) unless -d $dir;
2852 &$sub;
2854 my $err = $@;
2855 if (defined $old_index) {
2856 $ENV{GIT_INDEX_FILE} = $old_index;
2857 } else {
2858 delete $ENV{GIT_INDEX_FILE};
2860 die $err if $err;
2861 wantarray ? @ret : $ret[0];
2864 sub assert_index_clean {
2865 my ($self, $treeish) = @_;
2867 $self->tmp_index_do(sub {
2868 command_noisy('read-tree', $treeish) unless -e $self->{index};
2869 my $x = command_oneline('write-tree');
2870 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2871 /^tree ($::sha1)/mo);
2872 return if $y eq $x;
2874 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2875 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2876 command_noisy('read-tree', $treeish);
2877 $x = command_oneline('write-tree');
2878 if ($y ne $x) {
2879 ::fatal "trees ($treeish) $y != $x\n",
2880 "Something is seriously wrong...";
2885 sub get_commit_parents {
2886 my ($self, $log_entry) = @_;
2887 my (%seen, @ret, @tmp);
2888 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2889 if (my $ip = $self->{inject_parents}) {
2890 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2891 push @tmp, $commit;
2894 if (my $cur = ::verify_ref($self->refname.'^0')) {
2895 push @tmp, $cur;
2897 if (my $ipd = $self->{inject_parents_dcommit}) {
2898 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2899 push @tmp, @$commit;
2902 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2903 while (my $p = shift @tmp) {
2904 next if $seen{$p};
2905 $seen{$p} = 1;
2906 push @ret, $p;
2908 @ret;
2911 sub rewrite_root {
2912 my ($self) = @_;
2913 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2914 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2915 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2916 if ($rwr) {
2917 $rwr =~ s#/+$##;
2918 if ($rwr !~ m#^[a-z\+]+://#) {
2919 die "$rwr is not a valid URL (key: $k)\n";
2922 $self->{-rewrite_root} = $rwr;
2925 sub rewrite_uuid {
2926 my ($self) = @_;
2927 return $self->{-rewrite_uuid} if exists $self->{-rewrite_uuid};
2928 my $k = "svn-remote.$self->{repo_id}.rewriteUUID";
2929 my $rwid = eval { command_oneline(qw/config --get/, $k) };
2930 if ($rwid) {
2931 $rwid =~ s#/+$##;
2932 if ($rwid !~ m#^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$#) {
2933 die "$rwid is not a valid UUID (key: $k)\n";
2936 $self->{-rewrite_uuid} = $rwid;
2939 sub metadata_url {
2940 my ($self) = @_;
2941 ($self->rewrite_root || $self->{url}) .
2942 (length $self->{path} ? '/' . $self->{path} : '');
2945 sub full_url {
2946 my ($self) = @_;
2947 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2950 sub full_pushurl {
2951 my ($self) = @_;
2952 if ($self->{pushurl}) {
2953 return $self->{pushurl} . (length $self->{path} ? '/' .
2954 $self->{path} : '');
2955 } else {
2956 return $self->full_url;
2960 sub set_commit_header_env {
2961 my ($log_entry) = @_;
2962 my %env;
2963 foreach my $ned (qw/NAME EMAIL DATE/) {
2964 foreach my $ac (qw/AUTHOR COMMITTER/) {
2965 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2969 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2970 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2971 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2973 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2974 ? $log_entry->{commit_name}
2975 : $log_entry->{name};
2976 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2977 ? $log_entry->{commit_email}
2978 : $log_entry->{email};
2979 \%env;
2982 sub restore_commit_header_env {
2983 my ($env) = @_;
2984 foreach my $ned (qw/NAME EMAIL DATE/) {
2985 foreach my $ac (qw/AUTHOR COMMITTER/) {
2986 my $k = "GIT_${ac}_${ned}";
2987 if (defined $env->{$k}) {
2988 $ENV{$k} = $env->{$k};
2989 } else {
2990 delete $ENV{$k};
2996 sub gc {
2997 command_noisy('gc', '--auto');
3000 sub do_git_commit {
3001 my ($self, $log_entry) = @_;
3002 my $lr = $self->last_rev;
3003 if (defined $lr && $lr >= $log_entry->{revision}) {
3004 die "Last fetched revision of ", $self->refname,
3005 " was r$lr, but we are about to fetch: ",
3006 "r$log_entry->{revision}!\n";
3008 if (my $c = $self->rev_map_get($log_entry->{revision})) {
3009 croak "$log_entry->{revision} = $c already exists! ",
3010 "Why are we refetching it?\n";
3012 my $old_env = set_commit_header_env($log_entry);
3013 my $tree = $log_entry->{tree};
3014 if (!defined $tree) {
3015 $tree = $self->tmp_index_do(sub {
3016 command_oneline('write-tree') });
3018 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
3020 my @exec = ('git', 'commit-tree', $tree);
3021 foreach ($self->get_commit_parents($log_entry)) {
3022 push @exec, '-p', $_;
3024 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
3025 or croak $!;
3026 binmode $msg_fh;
3028 # we always get UTF-8 from SVN, but we may want our commits in
3029 # a different encoding.
3030 if (my $enc = Git::config('i18n.commitencoding')) {
3031 require Encode;
3032 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
3034 print $msg_fh $log_entry->{log} or croak $!;
3035 restore_commit_header_env($old_env);
3036 unless ($self->no_metadata) {
3037 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
3038 or croak $!;
3040 $msg_fh->flush == 0 or croak $!;
3041 close $msg_fh or croak $!;
3042 chomp(my $commit = do { local $/; <$out_fh> });
3043 close $out_fh or croak $!;
3044 waitpid $pid, 0;
3045 croak $? if $?;
3046 if ($commit !~ /^$::sha1$/o) {
3047 die "Failed to commit, invalid sha1: $commit\n";
3050 $self->rev_map_set($log_entry->{revision}, $commit, 1);
3052 $self->{last_rev} = $log_entry->{revision};
3053 $self->{last_commit} = $commit;
3054 print "r$log_entry->{revision}" unless $::_q > 1;
3055 if (defined $log_entry->{svm_revision}) {
3056 print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
3057 $self->rev_map_set($log_entry->{svm_revision}, $commit,
3058 0, $self->svm_uuid);
3060 print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
3061 if (--$_gc_nr == 0) {
3062 $_gc_nr = $_gc_period;
3063 gc();
3065 return $commit;
3068 sub match_paths {
3069 my ($self, $paths, $r) = @_;
3070 return 1 if $self->{path} eq '';
3071 if (my $path = $paths->{"/$self->{path}"}) {
3072 return ($path->{action} eq 'D') ? 0 : 1;
3074 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
3075 if (grep /$self->{path_regex}/, keys %$paths) {
3076 return 1;
3078 my $c = '';
3079 foreach (split m#/#, $self->{path}) {
3080 $c .= "/$_";
3081 next unless ($paths->{$c} &&
3082 ($paths->{$c}->{action} =~ /^[AR]$/));
3083 if ($self->ra->check_path($self->{path}, $r) ==
3084 $SVN::Node::dir) {
3085 return 1;
3088 return 0;
3091 sub find_parent_branch {
3092 my ($self, $paths, $rev) = @_;
3093 return undef unless $self->follow_parent;
3094 unless (defined $paths) {
3095 my $err_handler = $SVN::Error::handler;
3096 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
3097 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1,
3098 sub { $paths = $_[0] });
3099 $SVN::Error::handler = $err_handler;
3101 return undef unless defined $paths;
3103 # look for a parent from another branch:
3104 my @b_path_components = split m#/#, $self->{path};
3105 my @a_path_components;
3106 my $i;
3107 while (@b_path_components) {
3108 $i = $paths->{'/'.join('/', @b_path_components)};
3109 last if $i && defined $i->{copyfrom_path};
3110 unshift(@a_path_components, pop(@b_path_components));
3112 return undef unless defined $i && defined $i->{copyfrom_path};
3113 my $branch_from = $i->{copyfrom_path};
3114 if (@a_path_components) {
3115 print STDERR "branch_from: $branch_from => ";
3116 $branch_from .= '/'.join('/', @a_path_components);
3117 print STDERR $branch_from, "\n";
3119 my $r = $i->{copyfrom_rev};
3120 my $repos_root = $self->ra->{repos_root};
3121 my $url = $self->ra->{url};
3122 my $new_url = $url . $branch_from;
3123 print STDERR "Found possible branch point: ",
3124 "$new_url => ", $self->full_url, ", $r\n"
3125 unless $::_q > 1;
3126 $branch_from =~ s#^/##;
3127 my $gs = $self->other_gs($new_url, $url,
3128 $branch_from, $r, $self->{ref_id});
3129 my ($r0, $parent) = $gs->find_rev_before($r, 1);
3131 my ($base, $head);
3132 if (!defined $r0 || !defined $parent) {
3133 ($base, $head) = parse_revision_argument(0, $r);
3134 } else {
3135 if ($r0 < $r) {
3136 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
3137 0, 1, sub { $base = $_[1] - 1 });
3140 if (defined $base && $base <= $r) {
3141 $gs->fetch($base, $r);
3143 ($r0, $parent) = $gs->find_rev_before($r, 1);
3145 if (defined $r0 && defined $parent) {
3146 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n"
3147 unless $::_q > 1;
3148 my $ed;
3149 if ($self->ra->can_do_switch) {
3150 $self->assert_index_clean($parent);
3151 print STDERR "Following parent with do_switch\n"
3152 unless $::_q > 1;
3153 # do_switch works with svn/trunk >= r22312, but that
3154 # is not included with SVN 1.4.3 (the latest version
3155 # at the moment), so we can't rely on it
3156 $self->{last_rev} = $r0;
3157 $self->{last_commit} = $parent;
3158 $ed = Git::SVN::Fetcher->new($self, $gs->{path});
3159 $gs->ra->gs_do_switch($r0, $rev, $gs,
3160 $self->full_url, $ed)
3161 or die "SVN connection failed somewhere...\n";
3162 } elsif ($self->ra->trees_match($new_url, $r0,
3163 $self->full_url, $rev)) {
3164 print STDERR "Trees match:\n",
3165 " $new_url\@$r0\n",
3166 " ${\$self->full_url}\@$rev\n",
3167 "Following parent with no changes\n"
3168 unless $::_q > 1;
3169 $self->tmp_index_do(sub {
3170 command_noisy('read-tree', $parent);
3172 $self->{last_commit} = $parent;
3173 } else {
3174 print STDERR "Following parent with do_update\n"
3175 unless $::_q > 1;
3176 $ed = Git::SVN::Fetcher->new($self);
3177 $self->ra->gs_do_update($rev, $rev, $self, $ed)
3178 or die "SVN connection failed somewhere...\n";
3180 print STDERR "Successfully followed parent\n" unless $::_q > 1;
3181 return $self->make_log_entry($rev, [$parent], $ed);
3183 return undef;
3186 sub do_fetch {
3187 my ($self, $paths, $rev) = @_;
3188 my $ed;
3189 my ($last_rev, @parents);
3190 if (my $lc = $self->last_commit) {
3191 # we can have a branch that was deleted, then re-added
3192 # under the same name but copied from another path, in
3193 # which case we'll have multiple parents (we don't
3194 # want to break the original ref, nor lose copypath info):
3195 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
3196 push @{$log_entry->{parents}}, $lc;
3197 return $log_entry;
3199 $ed = Git::SVN::Fetcher->new($self);
3200 $last_rev = $self->{last_rev};
3201 $ed->{c} = $lc;
3202 @parents = ($lc);
3203 } else {
3204 $last_rev = $rev;
3205 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
3206 return $log_entry;
3208 $ed = Git::SVN::Fetcher->new($self);
3210 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
3211 die "SVN connection failed somewhere...\n";
3213 $self->make_log_entry($rev, \@parents, $ed);
3216 sub mkemptydirs {
3217 my ($self, $r) = @_;
3219 sub scan {
3220 my ($r, $empty_dirs, $line) = @_;
3221 if (defined $r && $line =~ /^r(\d+)$/) {
3222 return 0 if $1 > $r;
3223 } elsif ($line =~ /^ \+empty_dir: (.+)$/) {
3224 $empty_dirs->{$1} = 1;
3225 } elsif ($line =~ /^ \-empty_dir: (.+)$/) {
3226 my @d = grep {m[^\Q$1\E(/|$)]} (keys %$empty_dirs);
3227 delete @$empty_dirs{@d};
3229 1; # continue
3232 my %empty_dirs = ();
3233 my $gz_file = "$self->{dir}/unhandled.log.gz";
3234 if (-f $gz_file) {
3235 if (!$can_compress) {
3236 warn "Compress::Zlib could not be found; ",
3237 "empty directories in $gz_file will not be read\n";
3238 } else {
3239 my $gz = Compress::Zlib::gzopen($gz_file, "rb") or
3240 die "Unable to open $gz_file: $!\n";
3241 my $line;
3242 while ($gz->gzreadline($line) > 0) {
3243 scan($r, \%empty_dirs, $line) or last;
3245 $gz->gzclose;
3249 if (open my $fh, '<', "$self->{dir}/unhandled.log") {
3250 binmode $fh or croak "binmode: $!";
3251 while (<$fh>) {
3252 scan($r, \%empty_dirs, $_) or last;
3254 close $fh;
3257 my $strip = qr/\A\Q$self->{path}\E(?:\/|$)/;
3258 foreach my $d (sort keys %empty_dirs) {
3259 $d = uri_decode($d);
3260 $d =~ s/$strip//;
3261 next unless length($d);
3262 next if -d $d;
3263 if (-e $d) {
3264 warn "$d exists but is not a directory\n";
3265 } else {
3266 print "creating empty directory: $d\n";
3267 mkpath([$d]);
3272 sub get_untracked {
3273 my ($self, $ed) = @_;
3274 my @out;
3275 my $h = $ed->{empty};
3276 foreach (sort keys %$h) {
3277 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
3278 push @out, " $act: " . uri_encode($_);
3279 warn "W: $act: $_\n";
3281 foreach my $t (qw/dir_prop file_prop/) {
3282 $h = $ed->{$t} or next;
3283 foreach my $path (sort keys %$h) {
3284 my $ppath = $path eq '' ? '.' : $path;
3285 foreach my $prop (sort keys %{$h->{$path}}) {
3286 next if $SKIP_PROP{$prop};
3287 my $v = $h->{$path}->{$prop};
3288 my $t_ppath_prop = "$t: " .
3289 uri_encode($ppath) . ' ' .
3290 uri_encode($prop);
3291 if (defined $v) {
3292 push @out, " +$t_ppath_prop " .
3293 uri_encode($v);
3294 } else {
3295 push @out, " -$t_ppath_prop";
3300 foreach my $t (qw/absent_file absent_directory/) {
3301 $h = $ed->{$t} or next;
3302 foreach my $parent (sort keys %$h) {
3303 foreach my $path (sort @{$h->{$parent}}) {
3304 push @out, " $t: " .
3305 uri_encode("$parent/$path");
3306 warn "W: $t: $parent/$path ",
3307 "Insufficient permissions?\n";
3311 \@out;
3314 sub get_tz {
3315 # some systmes don't handle or mishandle %z, so be creative.
3316 my $t = shift || time;
3317 my $gm = timelocal(gmtime($t));
3318 my $sign = qw( + + - )[ $t <=> $gm ];
3319 return sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
3322 # parse_svn_date(DATE)
3323 # --------------------
3324 # Given a date (in UTC) from Subversion, return a string in the format
3325 # "<TZ Offset> <local date/time>" that Git will use.
3327 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
3328 # is true we'll convert it to the local timezone instead.
3329 sub parse_svn_date {
3330 my $date = shift || return '+0000 1970-01-01 00:00:00';
3331 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
3332 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
3333 croak "Unable to parse date: $date\n";
3334 my $parsed_date; # Set next.
3336 if ($Git::SVN::_localtime) {
3337 # Translate the Subversion datetime to an epoch time.
3338 # Begin by switching ourselves to $date's timezone, UTC.
3339 my $old_env_TZ = $ENV{TZ};
3340 $ENV{TZ} = 'UTC';
3342 my $epoch_in_UTC =
3343 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
3345 # Determine our local timezone (including DST) at the
3346 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
3347 # value of TZ, if any, at the time we were run.
3348 if (defined $Git::SVN::Log::TZ) {
3349 $ENV{TZ} = $Git::SVN::Log::TZ;
3350 } else {
3351 delete $ENV{TZ};
3354 my $our_TZ = get_tz();
3356 # This converts $epoch_in_UTC into our local timezone.
3357 my ($sec, $min, $hour, $mday, $mon, $year,
3358 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
3360 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
3361 $our_TZ, $year + 1900, $mon + 1,
3362 $mday, $hour, $min, $sec);
3364 # Reset us to the timezone in effect when we entered
3365 # this routine.
3366 if (defined $old_env_TZ) {
3367 $ENV{TZ} = $old_env_TZ;
3368 } else {
3369 delete $ENV{TZ};
3371 } else {
3372 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
3375 return $parsed_date;
3378 sub other_gs {
3379 my ($self, $new_url, $url,
3380 $branch_from, $r, $old_ref_id) = @_;
3381 my $gs = Git::SVN->find_by_url($new_url, $url, $branch_from);
3382 unless ($gs) {
3383 my $ref_id = $old_ref_id;
3384 $ref_id =~ s/\@\d+-*$//;
3385 $ref_id .= "\@$r";
3386 # just grow a tail if we're not unique enough :x
3387 $ref_id .= '-' while find_ref($ref_id);
3388 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
3389 if ($u =~ s#^\Q$url\E(/|$)##) {
3390 $p = $u;
3391 $u = $url;
3392 $repo_id = $self->{repo_id};
3394 while (1) {
3395 # It is possible to tag two different subdirectories at
3396 # the same revision. If the url for an existing ref
3397 # does not match, we must either find a ref with a
3398 # matching url or create a new ref by growing a tail.
3399 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
3400 my (undef, $max_commit) = $gs->rev_map_max(1);
3401 last if (!$max_commit);
3402 my ($url) = ::cmt_metadata($max_commit);
3403 last if ($url eq $gs->metadata_url);
3404 $ref_id .= '-';
3406 print STDERR "Initializing parent: $ref_id\n" unless $::_q > 1;
3411 sub call_authors_prog {
3412 my ($orig_author) = @_;
3413 $orig_author = command_oneline('rev-parse', '--sq-quote', $orig_author);
3414 my $author = `$::_authors_prog $orig_author`;
3415 if ($? != 0) {
3416 die "$::_authors_prog failed with exit code $?\n"
3418 if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
3419 my ($name, $email) = ($1, $2);
3420 $email = undef if length $2 == 0;
3421 return [$name, $email];
3422 } else {
3423 die "Author: $orig_author: $::_authors_prog returned "
3424 . "invalid author format: $author\n";
3428 sub check_author {
3429 my ($author) = @_;
3430 if (!defined $author || length $author == 0) {
3431 $author = '(no author)';
3433 if (!defined $::users{$author}) {
3434 if (defined $::_authors_prog) {
3435 $::users{$author} = call_authors_prog($author);
3436 } elsif (defined $::_authors) {
3437 die "Author: $author not defined in $::_authors file\n";
3440 $author;
3443 sub find_extra_svk_parents {
3444 my ($self, $ed, $tickets, $parents) = @_;
3445 # aha! svk:merge property changed...
3446 my @tickets = split "\n", $tickets;
3447 my @known_parents;
3448 for my $ticket ( @tickets ) {
3449 my ($uuid, $path, $rev) = split /:/, $ticket;
3450 if ( $uuid eq $self->ra_uuid ) {
3451 my $url = $self->{url};
3452 my $repos_root = $url;
3453 my $branch_from = $path;
3454 $branch_from =~ s{^/}{};
3455 my $gs = $self->other_gs($repos_root."/".$branch_from,
3456 $url,
3457 $branch_from,
3458 $rev,
3459 $self->{ref_id});
3460 if ( my $commit = $gs->rev_map_get($rev, $uuid) ) {
3461 # wahey! we found it, but it might be
3462 # an old one (!)
3463 push @known_parents, [ $rev, $commit ];
3467 # Ordering matters; highest-numbered commit merge tickets
3468 # first, as they may account for later merge ticket additions
3469 # or changes.
3470 @known_parents = map {$_->[1]} sort {$b->[0] <=> $a->[0]} @known_parents;
3471 for my $parent ( @known_parents ) {
3472 my @cmd = ('rev-list', $parent, map { "^$_" } @$parents );
3473 my ($msg_fh, $ctx) = command_output_pipe(@cmd);
3474 my $new;
3475 while ( <$msg_fh> ) {
3476 $new=1;last;
3478 command_close_pipe($msg_fh, $ctx);
3479 if ( $new ) {
3480 print STDERR
3481 "Found merge parent (svk:merge ticket): $parent\n";
3482 push @$parents, $parent;
3487 sub lookup_svn_merge {
3488 my $uuid = shift;
3489 my $url = shift;
3490 my $merge = shift;
3492 my ($source, $revs) = split ":", $merge;
3493 my $path = $source;
3494 $path =~ s{^/}{};
3495 my $gs = Git::SVN->find_by_url($url.$source, $url, $path);
3496 if ( !$gs ) {
3497 warn "Couldn't find revmap for $url$source\n";
3498 return;
3500 my @ranges = split ",", $revs;
3501 my ($tip, $tip_commit);
3502 my @merged_commit_ranges;
3503 # find the tip
3504 for my $range ( @ranges ) {
3505 my ($bottom, $top) = split "-", $range;
3506 $top ||= $bottom;
3507 my $bottom_commit = $gs->find_rev_after( $bottom, 1, $top );
3508 my $top_commit = $gs->find_rev_before( $top, 1, $bottom );
3510 unless ($top_commit and $bottom_commit) {
3511 warn "W:unknown path/rev in svn:mergeinfo "
3512 ."dirprop: $source:$range\n";
3513 next;
3516 if (scalar(command('rev-parse', "$bottom_commit^@"))) {
3517 push @merged_commit_ranges,
3518 "$bottom_commit^..$top_commit";
3519 } else {
3520 push @merged_commit_ranges, "$top_commit";
3523 if ( !defined $tip or $top > $tip ) {
3524 $tip = $top;
3525 $tip_commit = $top_commit;
3528 return ($tip_commit, @merged_commit_ranges);
3531 sub _rev_list {
3532 my ($msg_fh, $ctx) = command_output_pipe(
3533 "rev-list", @_,
3535 my @rv;
3536 while ( <$msg_fh> ) {
3537 chomp;
3538 push @rv, $_;
3540 command_close_pipe($msg_fh, $ctx);
3541 @rv;
3544 sub check_cherry_pick {
3545 my $base = shift;
3546 my $tip = shift;
3547 my $parents = shift;
3548 my @ranges = @_;
3549 my %commits = map { $_ => 1 }
3550 _rev_list("--no-merges", $tip, "--not", $base, @$parents, "--");
3551 for my $range ( @ranges ) {
3552 delete @commits{_rev_list($range, "--")};
3554 for my $commit (keys %commits) {
3555 if (has_no_changes($commit)) {
3556 delete $commits{$commit};
3559 return (keys %commits);
3562 sub has_no_changes {
3563 my $commit = shift;
3565 my @revs = split / /, command_oneline(
3566 qw(rev-list --parents -1 -m), $commit);
3568 # Commits with no parents, e.g. the start of a partial branch,
3569 # have changes by definition.
3570 return 1 if (@revs < 2);
3572 # Commits with multiple parents, e.g a merge, have no changes
3573 # by definition.
3574 return 0 if (@revs > 2);
3576 return (command_oneline("rev-parse", "$commit^{tree}") eq
3577 command_oneline("rev-parse", "$commit~1^{tree}"));
3580 # The GIT_DIR environment variable is not always set until after the command
3581 # line arguments are processed, so we can't memoize in a BEGIN block.
3583 my $memoized = 0;
3585 sub memoize_svn_mergeinfo_functions {
3586 return if $memoized;
3587 $memoized = 1;
3589 my $cache_path = "$ENV{GIT_DIR}/svn/.caches/";
3590 mkpath([$cache_path]) unless -d $cache_path;
3592 tie my %lookup_svn_merge_cache => 'Memoize::Storable',
3593 "$cache_path/lookup_svn_merge.db", 'nstore';
3594 memoize 'lookup_svn_merge',
3595 SCALAR_CACHE => 'FAULT',
3596 LIST_CACHE => ['HASH' => \%lookup_svn_merge_cache],
3599 tie my %check_cherry_pick_cache => 'Memoize::Storable',
3600 "$cache_path/check_cherry_pick.db", 'nstore';
3601 memoize 'check_cherry_pick',
3602 SCALAR_CACHE => 'FAULT',
3603 LIST_CACHE => ['HASH' => \%check_cherry_pick_cache],
3606 tie my %has_no_changes_cache => 'Memoize::Storable',
3607 "$cache_path/has_no_changes.db", 'nstore';
3608 memoize 'has_no_changes',
3609 SCALAR_CACHE => ['HASH' => \%has_no_changes_cache],
3610 LIST_CACHE => 'FAULT',
3614 sub unmemoize_svn_mergeinfo_functions {
3615 return if not $memoized;
3616 $memoized = 0;
3618 Memoize::unmemoize 'lookup_svn_merge';
3619 Memoize::unmemoize 'check_cherry_pick';
3620 Memoize::unmemoize 'has_no_changes';
3623 Memoize::memoize 'Git::SVN::repos_root';
3626 END {
3627 # Force cache writeout explicitly instead of waiting for
3628 # global destruction to avoid segfault in Storable:
3629 # http://rt.cpan.org/Public/Bug/Display.html?id=36087
3630 unmemoize_svn_mergeinfo_functions();
3633 sub parents_exclude {
3634 my $parents = shift;
3635 my @commits = @_;
3636 return unless @commits;
3638 my @excluded;
3639 my $excluded;
3640 do {
3641 my @cmd = ('rev-list', "-1", @commits, "--not", @$parents );
3642 $excluded = command_oneline(@cmd);
3643 if ( $excluded ) {
3644 my @new;
3645 my $found;
3646 for my $commit ( @commits ) {
3647 if ( $commit eq $excluded ) {
3648 push @excluded, $commit;
3649 $found++;
3650 last;
3652 else {
3653 push @new, $commit;
3656 die "saw commit '$excluded' in rev-list output, "
3657 ."but we didn't ask for that commit (wanted: @commits --not @$parents)"
3658 unless $found;
3659 @commits = @new;
3662 while ($excluded and @commits);
3664 return @excluded;
3668 # note: this function should only be called if the various dirprops
3669 # have actually changed
3670 sub find_extra_svn_parents {
3671 my ($self, $ed, $mergeinfo, $parents) = @_;
3672 # aha! svk:merge property changed...
3674 memoize_svn_mergeinfo_functions();
3676 # We first search for merged tips which are not in our
3677 # history. Then, we figure out which git revisions are in
3678 # that tip, but not this revision. If all of those revisions
3679 # are now marked as merge, we can add the tip as a parent.
3680 my @merges = split "\n", $mergeinfo;
3681 my @merge_tips;
3682 my $url = $self->{url};
3683 my $uuid = $self->ra_uuid;
3684 my %ranges;
3685 for my $merge ( @merges ) {
3686 my ($tip_commit, @ranges) =
3687 lookup_svn_merge( $uuid, $url, $merge );
3688 unless (!$tip_commit or
3689 grep { $_ eq $tip_commit } @$parents ) {
3690 push @merge_tips, $tip_commit;
3691 $ranges{$tip_commit} = \@ranges;
3692 } else {
3693 push @merge_tips, undef;
3697 my %excluded = map { $_ => 1 }
3698 parents_exclude($parents, grep { defined } @merge_tips);
3700 # check merge tips for new parents
3701 my @new_parents;
3702 for my $merge_tip ( @merge_tips ) {
3703 my $spec = shift @merges;
3704 next unless $merge_tip and $excluded{$merge_tip};
3706 my $ranges = $ranges{$merge_tip};
3708 # check out 'new' tips
3709 my $merge_base;
3710 eval {
3711 $merge_base = command_oneline(
3712 "merge-base",
3713 @$parents, $merge_tip,
3716 if ($@) {
3717 die "An error occurred during merge-base"
3718 unless $@->isa("Git::Error::Command");
3720 warn "W: Cannot find common ancestor between ".
3721 "@$parents and $merge_tip. Ignoring merge info.\n";
3722 next;
3725 # double check that there are no missing non-merge commits
3726 my (@incomplete) = check_cherry_pick(
3727 $merge_base, $merge_tip,
3728 $parents,
3729 @$ranges,
3732 if ( @incomplete ) {
3733 warn "W:svn cherry-pick ignored ($spec) - missing "
3734 .@incomplete." commit(s) (eg $incomplete[0])\n";
3735 } else {
3736 warn
3737 "Found merge parent (svn:mergeinfo prop): ",
3738 $merge_tip, "\n";
3739 push @new_parents, $merge_tip;
3743 # cater for merges which merge commits from multiple branches
3744 if ( @new_parents > 1 ) {
3745 for ( my $i = 0; $i <= $#new_parents; $i++ ) {
3746 for ( my $j = 0; $j <= $#new_parents; $j++ ) {
3747 next if $i == $j;
3748 next unless $new_parents[$i];
3749 next unless $new_parents[$j];
3750 my $revs = command_oneline(
3751 "rev-list", "-1",
3752 "$new_parents[$i]..$new_parents[$j]",
3754 if ( !$revs ) {
3755 undef($new_parents[$j]);
3760 push @$parents, grep { defined } @new_parents;
3763 sub make_log_entry {
3764 my ($self, $rev, $parents, $ed) = @_;
3765 my $untracked = $self->get_untracked($ed);
3767 my @parents = @$parents;
3768 my $ps = $ed->{path_strip} || "";
3769 for my $path ( grep { m/$ps/ } %{$ed->{dir_prop}} ) {
3770 my $props = $ed->{dir_prop}{$path};
3771 if ( $props->{"svk:merge"} ) {
3772 $self->find_extra_svk_parents
3773 ($ed, $props->{"svk:merge"}, \@parents);
3775 if ( $props->{"svn:mergeinfo"} ) {
3776 $self->find_extra_svn_parents
3777 ($ed,
3778 $props->{"svn:mergeinfo"},
3779 \@parents);
3783 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
3784 print $un "r$rev\n" or croak $!;
3785 print $un $_, "\n" foreach @$untracked;
3786 my %log_entry = ( parents => \@parents, revision => $rev,
3787 log => '');
3789 my $headrev;
3790 my $logged = delete $self->{logged_rev_props};
3791 if (!$logged || $self->{-want_revprops}) {
3792 my $rp = $self->ra->rev_proplist($rev);
3793 foreach (sort keys %$rp) {
3794 my $v = $rp->{$_};
3795 if (/^svn:(author|date|log)$/) {
3796 $log_entry{$1} = $v;
3797 } elsif ($_ eq 'svm:headrev') {
3798 $headrev = $v;
3799 } else {
3800 print $un " rev_prop: ", uri_encode($_), ' ',
3801 uri_encode($v), "\n";
3804 } else {
3805 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
3807 close $un or croak $!;
3809 $log_entry{date} = parse_svn_date($log_entry{date});
3810 $log_entry{log} .= "\n";
3811 my $author = $log_entry{author} = check_author($log_entry{author});
3812 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
3813 : ($author, undef);
3815 my ($commit_name, $commit_email) = ($name, $email);
3816 if ($_use_log_author) {
3817 my $name_field;
3818 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
3819 $name_field = $1;
3820 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
3821 $name_field = $1;
3823 if (!defined $name_field) {
3824 if (!defined $email) {
3825 $email = $name;
3827 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
3828 ($name, $email) = ($1, $2);
3829 } elsif ($name_field =~ /(.*)@/) {
3830 ($name, $email) = ($1, $name_field);
3831 } else {
3832 ($name, $email) = ($name_field, $name_field);
3835 if (defined $headrev && $self->use_svm_props) {
3836 if ($self->rewrite_root) {
3837 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
3838 "options set!\n";
3840 if ($self->rewrite_uuid) {
3841 die "Can't have both 'useSvmProps' and 'rewriteUUID' ",
3842 "options set!\n";
3844 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$}i;
3845 # we don't want "SVM: initializing mirror for junk" ...
3846 return undef if $r == 0;
3847 my $svm = $self->svm;
3848 if ($uuid ne $svm->{uuid}) {
3849 die "UUID mismatch on SVM path:\n",
3850 "expected: $svm->{uuid}\n",
3851 " got: $uuid\n";
3853 my $full_url = $self->full_url;
3854 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
3855 die "Failed to replace '$svm->{replace}' with ",
3856 "'$svm->{source}' in $full_url\n";
3857 # throw away username for storing in records
3858 remove_username($full_url);
3859 $log_entry{metadata} = "$full_url\@$r $uuid";
3860 $log_entry{svm_revision} = $r;
3861 $email ||= "$author\@$uuid";
3862 $commit_email ||= "$author\@$uuid";
3863 } elsif ($self->use_svnsync_props) {
3864 my $full_url = $self->svnsync->{url};
3865 $full_url .= "/$self->{path}" if length $self->{path};
3866 remove_username($full_url);
3867 my $uuid = $self->svnsync->{uuid};
3868 $log_entry{metadata} = "$full_url\@$rev $uuid";
3869 $email ||= "$author\@$uuid";
3870 $commit_email ||= "$author\@$uuid";
3871 } else {
3872 my $url = $self->metadata_url;
3873 remove_username($url);
3874 my $uuid = $self->rewrite_uuid || $self->ra->get_uuid;
3875 $log_entry{metadata} = "$url\@$rev " . $uuid;
3876 $email ||= "$author\@" . $uuid;
3877 $commit_email ||= "$author\@" . $uuid;
3879 $log_entry{name} = $name;
3880 $log_entry{email} = $email;
3881 $log_entry{commit_name} = $commit_name;
3882 $log_entry{commit_email} = $commit_email;
3883 \%log_entry;
3886 sub fetch {
3887 my ($self, $min_rev, $max_rev, @parents) = @_;
3888 my ($last_rev, $last_commit) = $self->last_rev_commit;
3889 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
3890 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
3893 sub set_tree_cb {
3894 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
3895 $self->{inject_parents} = { $rev => $tree };
3896 $self->fetch(undef, undef);
3899 sub set_tree {
3900 my ($self, $tree) = (shift, shift);
3901 my $log_entry = ::get_commit_entry($tree);
3902 unless ($self->{last_rev}) {
3903 ::fatal("Must have an existing revision to commit");
3905 my %ed_opts = ( r => $self->{last_rev},
3906 log => $log_entry->{log},
3907 ra => $self->ra,
3908 tree_a => $self->{last_commit},
3909 tree_b => $tree,
3910 editor_cb => sub {
3911 $self->set_tree_cb($log_entry, $tree, @_) },
3912 svn_path => $self->{path} );
3913 if (!Git::SVN::Editor->new(\%ed_opts)->apply_diff) {
3914 print "No changes\nr$self->{last_rev} = $tree\n";
3918 sub rebuild_from_rev_db {
3919 my ($self, $path) = @_;
3920 my $r = -1;
3921 open my $fh, '<', $path or croak "open: $!";
3922 binmode $fh or croak "binmode: $!";
3923 while (<$fh>) {
3924 length($_) == 41 or croak "inconsistent size in ($_) != 41";
3925 chomp($_);
3926 ++$r;
3927 next if $_ eq ('0' x 40);
3928 $self->rev_map_set($r, $_);
3929 print "r$r = $_\n";
3931 close $fh or croak "close: $!";
3932 unlink $path or croak "unlink: $!";
3935 sub rebuild {
3936 my ($self) = @_;
3937 my $map_path = $self->map_path;
3938 my $partial = (-e $map_path && ! -z $map_path);
3939 return unless ::verify_ref($self->refname.'^0');
3940 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
3941 my $rev_db = $self->rev_db_path;
3942 $self->rebuild_from_rev_db($rev_db);
3943 if ($self->use_svm_props) {
3944 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
3945 $self->rebuild_from_rev_db($svm_rev_db);
3947 $self->unlink_rev_db_symlink;
3948 return;
3950 print "Rebuilding $map_path ...\n" if (!$partial);
3951 my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
3952 (undef, undef));
3953 my ($log, $ctx) =
3954 command_output_pipe(qw/rev-list --pretty=raw --reverse/,
3955 ($head ? "$head.." : "") . $self->refname,
3956 '--');
3957 my $metadata_url = $self->metadata_url;
3958 remove_username($metadata_url);
3959 my $svn_uuid = $self->rewrite_uuid || $self->ra_uuid;
3960 my $c;
3961 while (<$log>) {
3962 if ( m{^commit ($::sha1)$} ) {
3963 $c = $1;
3964 next;
3966 next unless s{^\s*(git-svn-id:)}{$1};
3967 my ($url, $rev, $uuid) = ::extract_metadata($_);
3968 remove_username($url);
3970 # ignore merges (from set-tree)
3971 next if (!defined $rev || !$uuid);
3973 # if we merged or otherwise started elsewhere, this is
3974 # how we break out of it
3975 if (($uuid ne $svn_uuid) ||
3976 ($metadata_url && $url && ($url ne $metadata_url))) {
3977 next;
3979 if ($partial && $head) {
3980 print "Partial-rebuilding $map_path ...\n";
3981 print "Currently at $base_rev = $head\n";
3982 $head = undef;
3985 $self->rev_map_set($rev, $c);
3986 print "r$rev = $c\n";
3988 command_close_pipe($log, $ctx);
3989 print "Done rebuilding $map_path\n" if (!$partial || !$head);
3990 my $rev_db_path = $self->rev_db_path;
3991 if (-f $self->rev_db_path) {
3992 unlink $self->rev_db_path or croak "unlink: $!";
3994 $self->unlink_rev_db_symlink;
3997 # rev_map:
3998 # Tie::File seems to be prone to offset errors if revisions get sparse,
3999 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
4000 # one of my favorite modules is out :< Next up would be one of the DBM
4001 # modules, but I'm not sure which is most portable...
4003 # This is the replacement for the rev_db format, which was too big
4004 # and inefficient for large repositories with a lot of sparse history
4005 # (mainly tags)
4007 # The format is this:
4008 # - 24 bytes for every record,
4009 # * 4 bytes for the integer representing an SVN revision number
4010 # * 20 bytes representing the sha1 of a git commit
4011 # - No empty padding records like the old format
4012 # (except the last record, which can be overwritten)
4013 # - new records are written append-only since SVN revision numbers
4014 # increase monotonically
4015 # - lookups on SVN revision number are done via a binary search
4016 # - Piping the file to xxd -c24 is a good way of dumping it for
4017 # viewing or editing (piped back through xxd -r), should the need
4018 # ever arise.
4019 # - The last record can be padding revision with an all-zero sha1
4020 # This is used to optimize fetch performance when using multiple
4021 # "fetch" directives in .git/config
4023 # These files are disposable unless noMetadata or useSvmProps is set
4025 sub _rev_map_set {
4026 my ($fh, $rev, $commit) = @_;
4028 binmode $fh or croak "binmode: $!";
4029 my $size = (stat($fh))[7];
4030 ($size % 24) == 0 or croak "inconsistent size: $size";
4032 my $wr_offset = 0;
4033 if ($size > 0) {
4034 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
4035 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
4036 $read == 24 or croak "read only $read bytes (!= 24)";
4037 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
4038 if ($last_commit eq ('0' x40)) {
4039 if ($size >= 48) {
4040 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
4041 $read = sysread($fh, $buf, 24) or
4042 croak "read: $!";
4043 $read == 24 or
4044 croak "read only $read bytes (!= 24)";
4045 ($last_rev, $last_commit) =
4046 unpack(rev_map_fmt, $buf);
4047 if ($last_commit eq ('0' x40)) {
4048 croak "inconsistent .rev_map\n";
4051 if ($last_rev >= $rev) {
4052 croak "last_rev is higher!: $last_rev >= $rev";
4054 $wr_offset = -24;
4057 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
4058 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
4059 croak "write: $!";
4062 sub _rev_map_reset {
4063 my ($fh, $rev, $commit) = @_;
4064 my $c = _rev_map_get($fh, $rev);
4065 $c eq $commit or die "_rev_map_reset(@_) commit $c does not match!\n";
4066 my $offset = sysseek($fh, 0, SEEK_CUR) or croak "seek: $!";
4067 truncate $fh, $offset or croak "truncate: $!";
4070 sub mkfile {
4071 my ($path) = @_;
4072 unless (-e $path) {
4073 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
4074 mkpath([$dir]) unless -d $dir;
4075 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
4076 close $fh or die "Couldn't close (create) $path: $!\n";
4080 sub rev_map_set {
4081 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
4082 defined $commit or die "missing arg3\n";
4083 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
4084 my $db = $self->map_path($uuid);
4085 my $db_lock = "$db.lock";
4086 my $sigmask;
4087 $update_ref ||= 0;
4088 if ($update_ref) {
4089 $sigmask = POSIX::SigSet->new();
4090 my $signew = POSIX::SigSet->new(SIGINT, SIGHUP, SIGTERM,
4091 SIGALRM, SIGUSR1, SIGUSR2);
4092 sigprocmask(SIG_BLOCK, $signew, $sigmask) or
4093 croak "Can't block signals: $!";
4095 mkfile($db);
4097 $LOCKFILES{$db_lock} = 1;
4098 my $sync;
4099 # both of these options make our .rev_db file very, very important
4100 # and we can't afford to lose it because rebuild() won't work
4101 if ($self->use_svm_props || $self->no_metadata) {
4102 $sync = 1;
4103 copy($db, $db_lock) or die "rev_map_set(@_): ",
4104 "Failed to copy: ",
4105 "$db => $db_lock ($!)\n";
4106 } else {
4107 rename $db, $db_lock or die "rev_map_set(@_): ",
4108 "Failed to rename: ",
4109 "$db => $db_lock ($!)\n";
4112 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
4113 or croak "Couldn't open $db_lock: $!\n";
4114 $update_ref eq 'reset' ? _rev_map_reset($fh, $rev, $commit) :
4115 _rev_map_set($fh, $rev, $commit);
4116 if ($sync) {
4117 $fh->flush or die "Couldn't flush $db_lock: $!\n";
4118 $fh->sync or die "Couldn't sync $db_lock: $!\n";
4120 close $fh or croak $!;
4121 if ($update_ref) {
4122 $_head = $self;
4123 my $note = "";
4124 $note = " ($update_ref)" if ($update_ref !~ /^\d*$/);
4125 command_noisy('update-ref', '-m', "r$rev$note",
4126 $self->refname, $commit);
4128 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
4129 "$db_lock => $db ($!)\n";
4130 delete $LOCKFILES{$db_lock};
4131 if ($update_ref) {
4132 sigprocmask(SIG_SETMASK, $sigmask) or
4133 croak "Can't restore signal mask: $!";
4137 # If want_commit, this will return an array of (rev, commit) where
4138 # commit _must_ be a valid commit in the archive.
4139 # Otherwise, it'll return the max revision (whether or not the
4140 # commit is valid or just a 0x40 placeholder).
4141 sub rev_map_max {
4142 my ($self, $want_commit) = @_;
4143 $self->rebuild;
4144 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
4145 $want_commit ? ($r, $c) : $r;
4148 sub rev_map_max_norebuild {
4149 my ($self, $want_commit) = @_;
4150 my $map_path = $self->map_path;
4151 stat $map_path or return $want_commit ? (0, undef) : 0;
4152 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
4153 binmode $fh or croak "binmode: $!";
4154 my $size = (stat($fh))[7];
4155 ($size % 24) == 0 or croak "inconsistent size: $size";
4157 if ($size == 0) {
4158 close $fh or croak "close: $!";
4159 return $want_commit ? (0, undef) : 0;
4162 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
4163 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
4164 my ($r, $c) = unpack(rev_map_fmt, $buf);
4165 if ($want_commit && $c eq ('0' x40)) {
4166 if ($size < 48) {
4167 return $want_commit ? (0, undef) : 0;
4169 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
4170 sysread($fh, $buf, 24) == 24 or croak "read: $!";
4171 ($r, $c) = unpack(rev_map_fmt, $buf);
4172 if ($c eq ('0'x40)) {
4173 croak "Penultimate record is all-zeroes in $map_path";
4176 close $fh or croak "close: $!";
4177 $want_commit ? ($r, $c) : $r;
4180 sub rev_map_get {
4181 my ($self, $rev, $uuid) = @_;
4182 my $map_path = $self->map_path($uuid);
4183 return undef unless -e $map_path;
4185 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
4186 my $c = _rev_map_get($fh, $rev);
4187 close($fh) or croak "close: $!";
4191 sub _rev_map_get {
4192 my ($fh, $rev) = @_;
4194 binmode $fh or croak "binmode: $!";
4195 my $size = (stat($fh))[7];
4196 ($size % 24) == 0 or croak "inconsistent size: $size";
4198 if ($size == 0) {
4199 return undef;
4202 my ($l, $u) = (0, $size - 24);
4203 my ($r, $c, $buf);
4205 while ($l <= $u) {
4206 my $i = int(($l/24 + $u/24) / 2) * 24;
4207 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
4208 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
4209 my ($r, $c) = unpack(rev_map_fmt, $buf);
4211 if ($r < $rev) {
4212 $l = $i + 24;
4213 } elsif ($r > $rev) {
4214 $u = $i - 24;
4215 } else { # $r == $rev
4216 return $c eq ('0' x 40) ? undef : $c;
4219 undef;
4222 # Finds the first svn revision that exists on (if $eq_ok is true) or
4223 # before $rev for the current branch. It will not search any lower
4224 # than $min_rev. Returns the git commit hash and svn revision number
4225 # if found, else (undef, undef).
4226 sub find_rev_before {
4227 my ($self, $rev, $eq_ok, $min_rev) = @_;
4228 --$rev unless $eq_ok;
4229 $min_rev ||= 1;
4230 my $max_rev = $self->rev_map_max;
4231 $rev = $max_rev if ($rev > $max_rev);
4232 while ($rev >= $min_rev) {
4233 if (my $c = $self->rev_map_get($rev)) {
4234 return ($rev, $c);
4236 --$rev;
4238 return (undef, undef);
4241 # Finds the first svn revision that exists on (if $eq_ok is true) or
4242 # after $rev for the current branch. It will not search any higher
4243 # than $max_rev. Returns the git commit hash and svn revision number
4244 # if found, else (undef, undef).
4245 sub find_rev_after {
4246 my ($self, $rev, $eq_ok, $max_rev) = @_;
4247 ++$rev unless $eq_ok;
4248 $max_rev ||= $self->rev_map_max;
4249 while ($rev <= $max_rev) {
4250 if (my $c = $self->rev_map_get($rev)) {
4251 return ($rev, $c);
4253 ++$rev;
4255 return (undef, undef);
4258 sub _new {
4259 my ($class, $repo_id, $ref_id, $path) = @_;
4260 unless (defined $repo_id && length $repo_id) {
4261 $repo_id = $Git::SVN::default_repo_id;
4263 unless (defined $ref_id && length $ref_id) {
4264 $_prefix = '' unless defined($_prefix);
4265 $_[2] = $ref_id =
4266 "refs/remotes/$_prefix$Git::SVN::default_ref_id";
4268 $_[1] = $repo_id;
4269 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
4271 # Older repos imported by us used $GIT_DIR/svn/foo instead of
4272 # $GIT_DIR/svn/refs/remotes/foo when tracking refs/remotes/foo
4273 if ($ref_id =~ m{^refs/remotes/(.*)}) {
4274 my $old_dir = "$ENV{GIT_DIR}/svn/$1";
4275 if (-d $old_dir && ! -d $dir) {
4276 $dir = $old_dir;
4280 $_[3] = $path = '' unless (defined $path);
4281 mkpath([$dir]);
4282 bless {
4283 ref_id => $ref_id, dir => $dir, index => "$dir/index",
4284 path => $path, config => "$ENV{GIT_DIR}/svn/config",
4285 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
4288 # for read-only access of old .rev_db formats
4289 sub unlink_rev_db_symlink {
4290 my ($self) = @_;
4291 my $link = $self->rev_db_path;
4292 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
4293 if (-l $link) {
4294 unlink $link or croak "unlink: $link failed!";
4298 sub rev_db_path {
4299 my ($self, $uuid) = @_;
4300 my $db_path = $self->map_path($uuid);
4301 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
4302 or croak "map_path: $db_path does not contain '/.rev_map.' !";
4303 $db_path;
4306 # the new replacement for .rev_db
4307 sub map_path {
4308 my ($self, $uuid) = @_;
4309 $uuid ||= $self->ra_uuid;
4310 "$self->{map_root}.$uuid";
4313 sub uri_encode {
4314 my ($f) = @_;
4315 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
4319 sub uri_decode {
4320 my ($f) = @_;
4321 $f =~ s#%([0-9a-fA-F]{2})#chr(hex($1))#eg;
4325 sub remove_username {
4326 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
4329 package Git::SVN::Ra;
4330 use vars qw/@ISA $config_dir $_ignore_refs_regex $_log_window_size/;
4331 use strict;
4332 use warnings;
4333 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
4335 BEGIN {
4336 # enforce temporary pool usage for some simple functions
4337 no strict 'refs';
4338 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root
4339 get_file/) {
4340 my $SUPER = "SUPER::$f";
4341 *$f = sub {
4342 my $self = shift;
4343 my $pool = SVN::Pool->new;
4344 my @ret = $self->$SUPER(@_,$pool);
4345 $pool->clear;
4346 wantarray ? @ret : $ret[0];
4351 sub _auth_providers () {
4352 my @rv = (
4353 SVN::Client::get_simple_provider(),
4354 SVN::Client::get_ssl_server_trust_file_provider(),
4355 SVN::Client::get_simple_prompt_provider(
4356 \&Git::SVN::Prompt::simple, 2),
4357 SVN::Client::get_ssl_client_cert_file_provider(),
4358 SVN::Client::get_ssl_client_cert_prompt_provider(
4359 \&Git::SVN::Prompt::ssl_client_cert, 2),
4360 SVN::Client::get_ssl_client_cert_pw_file_provider(),
4361 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
4362 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
4363 SVN::Client::get_username_provider(),
4364 SVN::Client::get_ssl_server_trust_prompt_provider(
4365 \&Git::SVN::Prompt::ssl_server_trust),
4366 SVN::Client::get_username_prompt_provider(
4367 \&Git::SVN::Prompt::username, 2)
4370 # earlier 1.6.x versions would segfault, and <= 1.5.x didn't have
4371 # this function
4372 if (::compare_svn_version('1.6.15') >= 0) {
4373 my $config = SVN::Core::config_get_config($config_dir);
4374 my ($p, @a);
4375 # config_get_config returns all config files from
4376 # ~/.subversion, auth_get_platform_specific_client_providers
4377 # just wants the config "file".
4378 @a = ($config->{'config'}, undef);
4379 $p = SVN::Core::auth_get_platform_specific_client_providers(@a);
4380 # Insert the return value from
4381 # auth_get_platform_specific_providers
4382 unshift @rv, @$p;
4384 \@rv;
4387 sub escape_uri_only {
4388 my ($uri) = @_;
4389 my @tmp;
4390 foreach (split m{/}, $uri) {
4391 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
4392 push @tmp, $_;
4394 join('/', @tmp);
4397 sub escape_url {
4398 my ($url) = @_;
4399 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
4400 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
4401 $url = "$scheme://$domain$uri";
4403 $url;
4406 sub new {
4407 my ($class, $url) = @_;
4408 $url =~ s!/+$!!;
4409 return $RA if ($RA && $RA->{url} eq $url);
4411 ::_req_svn();
4413 SVN::_Core::svn_config_ensure($config_dir, undef);
4414 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
4415 my $config = SVN::Core::config_get_config($config_dir);
4416 $RA = undef;
4417 my $dont_store_passwords = 1;
4418 my $conf_t = ${$config}{'config'};
4420 no warnings 'once';
4421 # The usage of $SVN::_Core::SVN_CONFIG_* variables
4422 # produces warnings that variables are used only once.
4423 # I had not found the better way to shut them up, so
4424 # the warnings of type 'once' are disabled in this block.
4425 if (SVN::_Core::svn_config_get_bool($conf_t,
4426 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4427 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
4428 1) == 0) {
4429 SVN::_Core::svn_auth_set_parameter($baton,
4430 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
4431 bless (\$dont_store_passwords, "_p_void"));
4433 if (SVN::_Core::svn_config_get_bool($conf_t,
4434 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4435 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
4436 1) == 0) {
4437 $Git::SVN::Prompt::_no_auth_cache = 1;
4439 } # no warnings 'once'
4440 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
4441 config => $config,
4442 pool => SVN::Pool->new,
4443 auth_provider_callbacks => $callbacks);
4444 $self->{url} = $url;
4445 $self->{svn_path} = $url;
4446 $self->{repos_root} = $self->get_repos_root;
4447 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
4448 $self->{cache} = { check_path => { r => 0, data => {} },
4449 get_dir => { r => 0, data => {} } };
4450 $RA = bless $self, $class;
4453 sub check_path {
4454 my ($self, $path, $r) = @_;
4455 my $cache = $self->{cache}->{check_path};
4456 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
4457 return $cache->{data}->{$path};
4459 my $pool = SVN::Pool->new;
4460 my $t = $self->SUPER::check_path($path, $r, $pool);
4461 $pool->clear;
4462 if ($r != $cache->{r}) {
4463 %{$cache->{data}} = ();
4464 $cache->{r} = $r;
4466 $cache->{data}->{$path} = $t;
4469 sub get_dir {
4470 my ($self, $dir, $r) = @_;
4471 my $cache = $self->{cache}->{get_dir};
4472 if ($r == $cache->{r}) {
4473 if (my $x = $cache->{data}->{$dir}) {
4474 return wantarray ? @$x : $x->[0];
4477 my $pool = SVN::Pool->new;
4478 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
4479 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
4480 $pool->clear;
4481 if ($r != $cache->{r}) {
4482 %{$cache->{data}} = ();
4483 $cache->{r} = $r;
4485 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
4486 wantarray ? (\%dirents, $r, $props) : \%dirents;
4489 sub DESTROY {
4490 # do not call the real DESTROY since we store ourselves in $RA
4493 # get_log(paths, start, end, limit,
4494 # discover_changed_paths, strict_node_history, receiver)
4495 sub get_log {
4496 my ($self, @args) = @_;
4497 my $pool = SVN::Pool->new;
4499 # svn_log_changed_path_t objects passed to get_log are likely to be
4500 # overwritten even if only the refs are copied to an external variable,
4501 # so we should dup the structures in their entirety. Using an
4502 # externally passed pool (instead of our temporary and quickly cleared
4503 # pool in Git::SVN::Ra) does not help matters at all...
4504 my $receiver = pop @args;
4505 my $prefix = "/".$self->{svn_path};
4506 $prefix =~ s#/+($)##;
4507 my $prefix_regex = qr#^\Q$prefix\E#;
4508 push(@args, sub {
4509 my ($paths) = $_[0];
4510 return &$receiver(@_) unless $paths;
4511 $_[0] = ();
4512 foreach my $p (keys %$paths) {
4513 my $i = $paths->{$p};
4514 # Make path relative to our url, not repos_root
4515 $p =~ s/$prefix_regex//;
4516 my %s = map { $_ => $i->$_; }
4517 qw/copyfrom_path copyfrom_rev action/;
4518 if ($s{'copyfrom_path'}) {
4519 $s{'copyfrom_path'} =~ s/$prefix_regex//;
4521 $_[0]{$p} = \%s;
4523 &$receiver(@_);
4527 # the limit parameter was not supported in SVN 1.1.x, so we
4528 # drop it. Therefore, the receiver callback passed to it
4529 # is made aware of this limitation by being wrapped if
4530 # the limit passed to is being wrapped.
4531 if (::compare_svn_version('1.2.0') <= 0) {
4532 my $limit = splice(@args, 3, 1);
4533 if ($limit > 0) {
4534 my $receiver = pop @args;
4535 push(@args, sub { &$receiver(@_) if (--$limit >= 0) });
4538 my $ret = $self->SUPER::get_log(@args, $pool);
4539 $pool->clear;
4540 $ret;
4543 sub trees_match {
4544 my ($self, $url1, $rev1, $url2, $rev2) = @_;
4545 my $ctx = SVN::Client->new(auth => _auth_providers);
4546 my $out = IO::File->new_tmpfile;
4548 # older SVN (1.1.x) doesn't take $pool as the last parameter for
4549 # $ctx->diff(), so we'll create a default one
4550 my $pool = SVN::Pool->new_default_sub;
4552 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
4553 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
4554 $out->flush;
4555 my $ret = (($out->stat)[7] == 0);
4556 close $out or croak $!;
4558 $ret;
4561 sub get_commit_editor {
4562 my ($self, $log, $cb, $pool) = @_;
4564 my @lock = (::compare_svn_version('1.2.0') >= 0) ? (undef, 0) : ();
4565 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
4568 sub gs_do_update {
4569 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
4570 my $new = ($rev_a == $rev_b);
4571 my $path = $gs->{path};
4573 if ($new && -e $gs->{index}) {
4574 unlink $gs->{index} or die
4575 "Couldn't unlink index: $gs->{index}: $!\n";
4577 my $pool = SVN::Pool->new;
4578 $editor->set_path_strip($path);
4579 my (@pc) = split m#/#, $path;
4580 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
4581 1, $editor, $pool);
4582 my @lock = (::compare_svn_version('1.2.0') >= 0) ? (undef) : ();
4584 # Since we can't rely on svn_ra_reparent being available, we'll
4585 # just have to do some magic with set_path to make it so
4586 # we only want a partial path.
4587 my $sp = '';
4588 my $final = join('/', @pc);
4589 while (@pc) {
4590 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
4591 $sp .= '/' if length $sp;
4592 $sp .= shift @pc;
4594 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
4596 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
4598 $reporter->finish_report($pool);
4599 $pool->clear;
4600 $editor->{git_commit_ok};
4603 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
4604 # svn_ra_reparent didn't work before 1.4)
4605 sub gs_do_switch {
4606 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
4607 my $path = $gs->{path};
4608 my $pool = SVN::Pool->new;
4610 my $full_url = $self->{url};
4611 my $old_url = $full_url;
4612 $full_url .= '/' . $path if length $path;
4613 my ($ra, $reparented);
4615 if ($old_url =~ m#^svn(\+ssh)?://# ||
4616 ($full_url =~ m#^https?://# &&
4617 escape_url($full_url) ne $full_url)) {
4618 $_[0] = undef;
4619 $self = undef;
4620 $RA = undef;
4621 $ra = Git::SVN::Ra->new($full_url);
4622 $ra_invalid = 1;
4623 } elsif ($old_url ne $full_url) {
4624 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url, $pool);
4625 $self->{url} = $full_url;
4626 $reparented = 1;
4629 $ra ||= $self;
4630 $url_b = escape_url($url_b);
4631 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
4632 my @lock = (::compare_svn_version('1.2.0') >= 0) ? (undef) : ();
4633 $reporter->set_path('', $rev_a, 0, @lock, $pool);
4634 $reporter->finish_report($pool);
4636 if ($reparented) {
4637 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
4638 $self->{url} = $old_url;
4641 $pool->clear;
4642 $editor->{git_commit_ok};
4645 sub longest_common_path {
4646 my ($gsv, $globs) = @_;
4647 my %common;
4648 my $common_max = scalar @$gsv;
4650 foreach my $gs (@$gsv) {
4651 my @tmp = split m#/#, $gs->{path};
4652 my $p = '';
4653 foreach (@tmp) {
4654 $p .= length($p) ? "/$_" : $_;
4655 $common{$p} ||= 0;
4656 $common{$p}++;
4659 $globs ||= [];
4660 $common_max += scalar @$globs;
4661 foreach my $glob (@$globs) {
4662 my @tmp = split m#/#, $glob->{path}->{left};
4663 my $p = '';
4664 foreach (@tmp) {
4665 $p .= length($p) ? "/$_" : $_;
4666 $common{$p} ||= 0;
4667 $common{$p}++;
4671 my $longest_path = '';
4672 foreach (sort {length $b <=> length $a} keys %common) {
4673 if ($common{$_} == $common_max) {
4674 $longest_path = $_;
4675 last;
4678 $longest_path;
4681 sub gs_fetch_loop_common {
4682 my ($self, $base, $head, $gsv, $globs) = @_;
4683 return if ($base > $head);
4684 my $inc = $_log_window_size;
4685 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
4686 my $longest_path = longest_common_path($gsv, $globs);
4687 my $ra_url = $self->{url};
4688 my $find_trailing_edge;
4689 while (1) {
4690 my %revs;
4691 my $err;
4692 my $err_handler = $SVN::Error::handler;
4693 $SVN::Error::handler = sub {
4694 ($err) = @_;
4695 skip_unknown_revs($err);
4697 sub _cb {
4698 my ($paths, $r, $author, $date, $log) = @_;
4699 [ $paths,
4700 { author => $author, date => $date, log => $log } ];
4702 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
4703 sub { $revs{$_[1]} = _cb(@_) });
4704 if ($err) {
4705 print "Checked through r$max\r";
4706 } else {
4707 $find_trailing_edge = 1;
4709 if ($err and $find_trailing_edge) {
4710 print STDERR "Path '$longest_path' ",
4711 "was probably deleted:\n",
4712 $err->expanded_message,
4713 "\nWill attempt to follow ",
4714 "revisions r$min .. r$max ",
4715 "committed before the deletion\n";
4716 my $hi = $max;
4717 while (--$hi >= $min) {
4718 my $ok;
4719 $self->get_log([$longest_path], $min, $hi,
4720 0, 1, 1, sub {
4721 $ok = $_[1];
4722 $revs{$_[1]} = _cb(@_) });
4723 if ($ok) {
4724 print STDERR "r$min .. r$ok OK\n";
4725 last;
4728 $find_trailing_edge = 0;
4730 $SVN::Error::handler = $err_handler;
4732 my %exists = map { $_->{path} => $_ } @$gsv;
4733 foreach my $r (sort {$a <=> $b} keys %revs) {
4734 my ($paths, $logged) = @{$revs{$r}};
4736 foreach my $gs ($self->match_globs(\%exists, $paths,
4737 $globs, $r)) {
4738 if ($gs->rev_map_max >= $r) {
4739 next;
4741 next unless $gs->match_paths($paths, $r);
4742 $gs->{logged_rev_props} = $logged;
4743 if (my $last_commit = $gs->last_commit) {
4744 $gs->assert_index_clean($last_commit);
4746 my $log_entry = $gs->do_fetch($paths, $r);
4747 if ($log_entry) {
4748 $gs->do_git_commit($log_entry);
4750 $INDEX_FILES{$gs->{index}} = 1;
4752 foreach my $g (@$globs) {
4753 my $k = "svn-remote.$g->{remote}." .
4754 "$g->{t}-maxRev";
4755 Git::SVN::tmp_config($k, $r);
4757 if ($ra_invalid) {
4758 $_[0] = undef;
4759 $self = undef;
4760 $RA = undef;
4761 $self = Git::SVN::Ra->new($ra_url);
4762 $ra_invalid = undef;
4765 # pre-fill the .rev_db since it'll eventually get filled in
4766 # with '0' x40 if something new gets committed
4767 foreach my $gs (@$gsv) {
4768 next if $gs->rev_map_max >= $max;
4769 next if defined $gs->rev_map_get($max);
4770 $gs->rev_map_set($max, 0 x40);
4772 foreach my $g (@$globs) {
4773 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
4774 Git::SVN::tmp_config($k, $max);
4776 last if $max >= $head;
4777 $min = $max + 1;
4778 $max += $inc;
4779 $max = $head if ($max > $head);
4781 Git::SVN::gc();
4784 sub get_dir_globbed {
4785 my ($self, $left, $depth, $r) = @_;
4787 my @x = eval { $self->get_dir($left, $r) };
4788 return unless scalar @x == 3;
4789 my $dirents = $x[0];
4790 my @finalents;
4791 foreach my $de (keys %$dirents) {
4792 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
4793 if ($depth > 1) {
4794 my @args = ("$left/$de", $depth - 1, $r);
4795 foreach my $dir ($self->get_dir_globbed(@args)) {
4796 push @finalents, "$de/$dir";
4798 } else {
4799 push @finalents, $de;
4802 @finalents;
4805 # return value: 0 -- don't ignore, 1 -- ignore
4806 sub is_ref_ignored {
4807 my ($g, $p) = @_;
4808 my $refname = $g->{ref}->full_path($p);
4809 return 1 if defined($g->{ignore_refs_regex}) &&
4810 $refname =~ m!$g->{ignore_refs_regex}!;
4811 return 0 unless defined($_ignore_refs_regex);
4812 return 1 if $refname =~ m!$_ignore_refs_regex!o;
4813 return 0;
4816 sub match_globs {
4817 my ($self, $exists, $paths, $globs, $r) = @_;
4819 sub get_dir_check {
4820 my ($self, $exists, $g, $r) = @_;
4822 my @dirs = $self->get_dir_globbed($g->{path}->{left},
4823 $g->{path}->{depth},
4824 $r);
4826 foreach my $de (@dirs) {
4827 my $p = $g->{path}->full_path($de);
4828 next if $exists->{$p};
4829 next if (length $g->{path}->{right} &&
4830 ($self->check_path($p, $r) !=
4831 $SVN::Node::dir));
4832 next unless $p =~ /$g->{path}->{regex}/;
4833 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
4834 $g->{ref}->full_path($de), 1);
4837 foreach my $g (@$globs) {
4838 if (my $path = $paths->{"/$g->{path}->{left}"}) {
4839 if ($path->{action} =~ /^[AR]$/) {
4840 get_dir_check($self, $exists, $g, $r);
4843 foreach (keys %$paths) {
4844 if (/$g->{path}->{left_regex}/ &&
4845 !/$g->{path}->{regex}/) {
4846 next if $paths->{$_}->{action} !~ /^[AR]$/;
4847 get_dir_check($self, $exists, $g, $r);
4849 next unless /$g->{path}->{regex}/;
4850 my $p = $1;
4851 my $pathname = $g->{path}->full_path($p);
4852 next if is_ref_ignored($g, $p);
4853 next if $exists->{$pathname};
4854 next if ($self->check_path($pathname, $r) !=
4855 $SVN::Node::dir);
4856 $exists->{$pathname} = Git::SVN->init(
4857 $self->{url}, $pathname, undef,
4858 $g->{ref}->full_path($p), 1);
4860 my $c = '';
4861 foreach (split m#/#, $g->{path}->{left}) {
4862 $c .= "/$_";
4863 next unless ($paths->{$c} &&
4864 ($paths->{$c}->{action} =~ /^[AR]$/));
4865 get_dir_check($self, $exists, $g, $r);
4868 values %$exists;
4871 sub minimize_url {
4872 my ($self) = @_;
4873 return $self->{url} if ($self->{url} eq $self->{repos_root});
4874 my $url = $self->{repos_root};
4875 my @components = split(m!/!, $self->{svn_path});
4876 my $c = '';
4877 do {
4878 $url .= "/$c" if length $c;
4879 eval {
4880 my $ra = (ref $self)->new($url);
4881 my $latest = $ra->get_latest_revnum;
4882 $ra->get_log("", $latest, 0, 1, 0, 1, sub {});
4884 } while ($@ && ($c = shift @components));
4885 $url;
4888 sub can_do_switch {
4889 my $self = shift;
4890 unless (defined $can_do_switch) {
4891 my $pool = SVN::Pool->new;
4892 my $rep = eval {
4893 $self->do_switch(1, '', 0, $self->{url},
4894 SVN::Delta::Editor->new, $pool);
4896 if ($@) {
4897 $can_do_switch = 0;
4898 } else {
4899 $rep->abort_report($pool);
4900 $can_do_switch = 1;
4902 $pool->clear;
4904 $can_do_switch;
4907 sub skip_unknown_revs {
4908 my ($err) = @_;
4909 my $errno = $err->apr_err();
4910 # Maybe the branch we're tracking didn't
4911 # exist when the repo started, so it's
4912 # not an error if it doesn't, just continue
4914 # Wonderfully consistent library, eh?
4915 # 160013 - svn:// and file://
4916 # 175002 - http(s)://
4917 # 175007 - http(s):// (this repo required authorization, too...)
4918 # More codes may be discovered later...
4919 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
4920 my $err_key = $err->expanded_message;
4921 # revision numbers change every time, filter them out
4922 $err_key =~ s/\d+/\0/g;
4923 $err_key = "$errno\0$err_key";
4924 unless ($ignored_err{$err_key}) {
4925 warn "W: Ignoring error from SVN, path probably ",
4926 "does not exist: ($errno): ",
4927 $err->expanded_message,"\n";
4928 warn "W: Do not be alarmed at the above message ",
4929 "git-svn is just searching aggressively for ",
4930 "old history.\n",
4931 "This may take a while on large repositories\n";
4932 $ignored_err{$err_key} = 1;
4934 return;
4936 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
4939 package Git::SVN::Log;
4940 use strict;
4941 use warnings;
4942 use POSIX qw/strftime/;
4943 use constant commit_log_separator => ('-' x 72) . "\n";
4944 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
4945 %rusers $show_commit $incremental/;
4946 my $l_fmt;
4948 sub cmt_showable {
4949 my ($c) = @_;
4950 return 1 if defined $c->{r};
4952 # big commit message got truncated by the 16k pretty buffer in rev-list
4953 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
4954 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
4955 @{$c->{l}} = ();
4956 my @log = command(qw/cat-file commit/, $c->{c});
4958 # shift off the headers
4959 shift @log while ($log[0] ne '');
4960 shift @log;
4962 # TODO: make $c->{l} not have a trailing newline in the future
4963 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
4965 (undef, $c->{r}, undef) = ::extract_metadata(
4966 (grep(/^git-svn-id: /, @log))[-1]);
4968 return defined $c->{r};
4971 sub log_use_color {
4972 return $color || Git->repository->get_colorbool('color.diff');
4975 sub git_svn_log_cmd {
4976 my ($r_min, $r_max, @args) = @_;
4977 my $head = 'HEAD';
4978 my (@files, @log_opts);
4979 foreach my $x (@args) {
4980 if ($x eq '--' || @files) {
4981 push @files, $x;
4982 } else {
4983 if (::verify_ref("$x^0")) {
4984 $head = $x;
4985 } else {
4986 push @log_opts, $x;
4991 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
4992 $gs ||= Git::SVN->_new;
4993 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
4994 $gs->refname);
4995 push @cmd, '-r' unless $non_recursive;
4996 push @cmd, qw/--raw --name-status/ if $verbose;
4997 push @cmd, '--color' if log_use_color();
4998 push @cmd, @log_opts;
4999 if (defined $r_max && $r_max == $r_min) {
5000 push @cmd, '--max-count=1';
5001 if (my $c = $gs->rev_map_get($r_max)) {
5002 push @cmd, $c;
5004 } elsif (defined $r_max) {
5005 if ($r_max < $r_min) {
5006 ($r_min, $r_max) = ($r_max, $r_min);
5008 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
5009 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
5010 # If there are no commits in the range, both $c_max and $c_min
5011 # will be undefined. If there is at least 1 commit in the
5012 # range, both will be defined.
5013 return () if !defined $c_min || !defined $c_max;
5014 if ($c_min eq $c_max) {
5015 push @cmd, '--max-count=1', $c_min;
5016 } else {
5017 push @cmd, '--boundary', "$c_min..$c_max";
5020 return (@cmd, @files);
5023 # adapted from pager.c
5024 sub config_pager {
5025 if (! -t *STDOUT) {
5026 $ENV{GIT_PAGER_IN_USE} = 'false';
5027 $pager = undef;
5028 return;
5030 chomp($pager = command_oneline(qw(var GIT_PAGER)));
5031 if ($pager eq 'cat') {
5032 $pager = undef;
5034 $ENV{GIT_PAGER_IN_USE} = defined($pager);
5037 sub run_pager {
5038 return unless defined $pager;
5039 pipe my ($rfd, $wfd) or return;
5040 defined(my $pid = fork) or ::fatal "Can't fork: $!";
5041 if (!$pid) {
5042 open STDOUT, '>&', $wfd or
5043 ::fatal "Can't redirect to stdout: $!";
5044 return;
5046 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
5047 $ENV{LESS} ||= 'FRSX';
5048 exec $pager or ::fatal "Can't run pager: $! ($pager)";
5051 sub format_svn_date {
5052 my $t = shift || time;
5053 my $gmoff = Git::SVN::get_tz($t);
5054 return strftime("%Y-%m-%d %H:%M:%S $gmoff (%a, %d %b %Y)", localtime($t));
5057 sub parse_git_date {
5058 my ($t, $tz) = @_;
5059 # Date::Parse isn't in the standard Perl distro :(
5060 if ($tz =~ s/^\+//) {
5061 $t += tz_to_s_offset($tz);
5062 } elsif ($tz =~ s/^\-//) {
5063 $t -= tz_to_s_offset($tz);
5065 return $t;
5068 sub set_local_timezone {
5069 if (defined $TZ) {
5070 $ENV{TZ} = $TZ;
5071 } else {
5072 delete $ENV{TZ};
5076 sub tz_to_s_offset {
5077 my ($tz) = @_;
5078 $tz =~ s/(\d\d)$//;
5079 return ($1 * 60) + ($tz * 3600);
5082 sub get_author_info {
5083 my ($dest, $author, $t, $tz) = @_;
5084 $author =~ s/(?:^\s*|\s*$)//g;
5085 $dest->{a_raw} = $author;
5086 my $au;
5087 if ($::_authors) {
5088 $au = $rusers{$author} || undef;
5090 if (!$au) {
5091 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
5093 $dest->{t} = $t;
5094 $dest->{tz} = $tz;
5095 $dest->{a} = $au;
5096 $dest->{t_utc} = parse_git_date($t, $tz);
5099 sub process_commit {
5100 my ($c, $r_min, $r_max, $defer) = @_;
5101 if (defined $r_min && defined $r_max) {
5102 if ($r_min == $c->{r} && $r_min == $r_max) {
5103 show_commit($c);
5104 return 0;
5106 return 1 if $r_min == $r_max;
5107 if ($r_min < $r_max) {
5108 # we need to reverse the print order
5109 return 0 if (defined $limit && --$limit < 0);
5110 push @$defer, $c;
5111 return 1;
5113 if ($r_min != $r_max) {
5114 return 1 if ($r_min < $c->{r});
5115 return 1 if ($r_max > $c->{r});
5118 return 0 if (defined $limit && --$limit < 0);
5119 show_commit($c);
5120 return 1;
5123 sub show_commit {
5124 my $c = shift;
5125 if ($oneline) {
5126 my $x = "\n";
5127 if (my $l = $c->{l}) {
5128 while ($l->[0] =~ /^\s*$/) { shift @$l }
5129 $x = $l->[0];
5131 $l_fmt ||= 'A' . length($c->{r});
5132 print 'r',pack($l_fmt, $c->{r}),' | ';
5133 print "$c->{c} | " if $show_commit;
5134 print $x;
5135 } else {
5136 show_commit_normal($c);
5140 sub show_commit_changed_paths {
5141 my ($c) = @_;
5142 return unless $c->{changed};
5143 print "Changed paths:\n", @{$c->{changed}};
5146 sub show_commit_normal {
5147 my ($c) = @_;
5148 print commit_log_separator, "r$c->{r} | ";
5149 print "$c->{c} | " if $show_commit;
5150 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
5151 my $nr_line = 0;
5153 if (my $l = $c->{l}) {
5154 while ($l->[$#$l] eq "\n" && $#$l > 0
5155 && $l->[($#$l - 1)] eq "\n") {
5156 pop @$l;
5158 $nr_line = scalar @$l;
5159 if (!$nr_line) {
5160 print "1 line\n\n\n";
5161 } else {
5162 if ($nr_line == 1) {
5163 $nr_line = '1 line';
5164 } else {
5165 $nr_line .= ' lines';
5167 print $nr_line, "\n";
5168 show_commit_changed_paths($c);
5169 print "\n";
5170 print $_ foreach @$l;
5172 } else {
5173 print "1 line\n";
5174 show_commit_changed_paths($c);
5175 print "\n";
5178 foreach my $x (qw/raw stat diff/) {
5179 if ($c->{$x}) {
5180 print "\n";
5181 print $_ foreach @{$c->{$x}}
5186 sub cmd_show_log {
5187 my (@args) = @_;
5188 my ($r_min, $r_max);
5189 my $r_last = -1; # prevent dupes
5190 set_local_timezone();
5191 if (defined $::_revision) {
5192 if ($::_revision =~ /^(\d+):(\d+)$/) {
5193 ($r_min, $r_max) = ($1, $2);
5194 } elsif ($::_revision =~ /^\d+$/) {
5195 $r_min = $r_max = $::_revision;
5196 } else {
5197 ::fatal "-r$::_revision is not supported, use ",
5198 "standard 'git log' arguments instead";
5202 config_pager();
5203 @args = git_svn_log_cmd($r_min, $r_max, @args);
5204 if (!@args) {
5205 print commit_log_separator unless $incremental || $oneline;
5206 return;
5208 my $log = command_output_pipe(@args);
5209 run_pager();
5210 my (@k, $c, $d, $stat);
5211 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
5212 while (<$log>) {
5213 if (/^${esc_color}commit (?:- )?($::sha1_short)/o) {
5214 my $cmt = $1;
5215 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
5216 $r_last = $c->{r};
5217 process_commit($c, $r_min, $r_max, \@k) or
5218 goto out;
5220 $d = undef;
5221 $c = { c => $cmt };
5222 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
5223 get_author_info($c, $1, $2, $3);
5224 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
5225 # ignore
5226 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
5227 push @{$c->{raw}}, $_;
5228 } elsif (/^${esc_color}[ACRMDT]\t/) {
5229 # we could add $SVN->{svn_path} here, but that requires
5230 # remote access at the moment (repo_path_split)...
5231 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
5232 push @{$c->{changed}}, $_;
5233 } elsif (/^${esc_color}diff /o) {
5234 $d = 1;
5235 push @{$c->{diff}}, $_;
5236 } elsif ($d) {
5237 push @{$c->{diff}}, $_;
5238 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
5239 $esc_color*[\+\-]*$esc_color$/x) {
5240 $stat = 1;
5241 push @{$c->{stat}}, $_;
5242 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
5243 push @{$c->{stat}}, $_;
5244 $stat = undef;
5245 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
5246 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
5247 } elsif (s/^${esc_color} //o) {
5248 push @{$c->{l}}, $_;
5251 if ($c && defined $c->{r} && $c->{r} != $r_last) {
5252 $r_last = $c->{r};
5253 process_commit($c, $r_min, $r_max, \@k);
5255 if (@k) {
5256 ($r_min, $r_max) = ($r_max, $r_min);
5257 process_commit($_, $r_min, $r_max) foreach reverse @k;
5259 out:
5260 close $log;
5261 print commit_log_separator unless $incremental || $oneline;
5264 sub cmd_blame {
5265 my $path = pop;
5267 config_pager();
5268 run_pager();
5270 my ($fh, $ctx, $rev);
5272 if ($_git_format) {
5273 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
5274 while (my $line = <$fh>) {
5275 if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
5276 # Uncommitted edits show up as a rev ID of
5277 # all zeros, which we can't look up with
5278 # cmt_metadata
5279 if ($1 !~ /^0+$/) {
5280 (undef, $rev, undef) =
5281 ::cmt_metadata($1);
5282 $rev = '0' if (!$rev);
5283 } else {
5284 $rev = '0';
5286 $rev = sprintf('%-10s', $rev);
5287 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
5289 print $line;
5291 } else {
5292 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
5293 '--', $path);
5294 my ($sha1);
5295 my %authors;
5296 my @buffer;
5297 my %dsha; #distinct sha keys
5299 while (my $line = <$fh>) {
5300 push @buffer, $line;
5301 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5302 $dsha{$1} = 1;
5306 my $s2r = ::cmt_sha2rev_batch([keys %dsha]);
5308 foreach my $line (@buffer) {
5309 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5310 $rev = $s2r->{$1};
5311 $rev = '0' if (!$rev)
5313 elsif ($line =~ /^author (.*)/) {
5314 $authors{$rev} = $1;
5315 $authors{$rev} =~ s/\s/_/g;
5317 elsif ($line =~ /^\t(.*)$/) {
5318 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
5322 command_close_pipe($fh, $ctx);
5325 package Git::SVN::Migration;
5326 # these version numbers do NOT correspond to actual version numbers
5327 # of git nor git-svn. They are just relative.
5329 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
5331 # v1 layout: .git/$id/info/url, refs/remotes/$id
5333 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
5335 # v3 layout: .git/svn/$id, refs/remotes/$id
5336 # - info/url may remain for backwards compatibility
5337 # - this is what we migrate up to this layout automatically,
5338 # - this will be used by git svn init on single branches
5339 # v3.1 layout (auto migrated):
5340 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
5341 # for backwards compatibility
5343 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
5344 # - this is only created for newly multi-init-ed
5345 # repositories. Similar in spirit to the
5346 # --use-separate-remotes option in git-clone (now default)
5347 # - we do not automatically migrate to this (following
5348 # the example set by core git)
5350 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
5351 # - newer, more-efficient format that uses 24-bytes per record
5352 # with no filler space.
5353 # - use xxd -c24 < .rev_map.$UUID to view and debug
5354 # - This is a one-way migration, repositories updated to the
5355 # new format will not be able to use old git-svn without
5356 # rebuilding the .rev_db. Rebuilding the rev_db is not
5357 # possible if noMetadata or useSvmProps are set; but should
5358 # be no problem for users that use the (sensible) defaults.
5359 use strict;
5360 use warnings;
5361 use Carp qw/croak/;
5362 use File::Path qw/mkpath/;
5363 use File::Basename qw/dirname basename/;
5364 use vars qw/$_minimize/;
5366 sub migrate_from_v0 {
5367 my $git_dir = $ENV{GIT_DIR};
5368 return undef unless -d $git_dir;
5369 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5370 my $migrated = 0;
5371 while (<$fh>) {
5372 chomp;
5373 my ($id, $orig_ref) = ($_, $_);
5374 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
5375 next unless -f "$git_dir/$id/info/url";
5376 my $new_ref = "refs/remotes/$id";
5377 if (::verify_ref("$new_ref^0")) {
5378 print STDERR "W: $orig_ref is probably an old ",
5379 "branch used by an ancient version of ",
5380 "git-svn.\n",
5381 "However, $new_ref also exists.\n",
5382 "We will not be able ",
5383 "to use this branch until this ",
5384 "ambiguity is resolved.\n";
5385 next;
5387 print STDERR "Migrating from v0 layout...\n" if !$migrated;
5388 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
5389 command_noisy('update-ref', $new_ref, $orig_ref);
5390 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
5391 $migrated++;
5393 command_close_pipe($fh, $ctx);
5394 print STDERR "Done migrating from v0 layout...\n" if $migrated;
5395 $migrated;
5398 sub migrate_from_v1 {
5399 my $git_dir = $ENV{GIT_DIR};
5400 my $migrated = 0;
5401 return $migrated unless -d $git_dir;
5402 my $svn_dir = "$git_dir/svn";
5404 # just in case somebody used 'svn' as their $id at some point...
5405 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
5407 print STDERR "Migrating from a git-svn v1 layout...\n";
5408 mkpath([$svn_dir]);
5409 print STDERR "Data from a previous version of git-svn exists, but\n\t",
5410 "$svn_dir\n\t(required for this version ",
5411 "($::VERSION) of git-svn) does not exist.\n";
5412 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5413 while (<$fh>) {
5414 my $x = $_;
5415 next unless $x =~ s#^refs/remotes/##;
5416 chomp $x;
5417 next unless -f "$git_dir/$x/info/url";
5418 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
5419 next unless $u;
5420 my $dn = dirname("$git_dir/svn/$x");
5421 mkpath([$dn]) unless -d $dn;
5422 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
5423 mkpath(["$git_dir/svn/svn"]);
5424 print STDERR " - $git_dir/$x/info => ",
5425 "$git_dir/svn/$x/info\n";
5426 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
5427 croak "$!: $x";
5428 # don't worry too much about these, they probably
5429 # don't exist with repos this old (save for index,
5430 # and we can easily regenerate that)
5431 foreach my $f (qw/unhandled.log index .rev_db/) {
5432 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
5434 } else {
5435 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
5436 rename "$git_dir/$x", "$git_dir/svn/$x" or
5437 croak "$!: $x";
5439 $migrated++;
5441 command_close_pipe($fh, $ctx);
5442 print STDERR "Done migrating from a git-svn v1 layout\n";
5443 $migrated;
5446 sub read_old_urls {
5447 my ($l_map, $pfx, $path) = @_;
5448 my @dir;
5449 foreach (<$path/*>) {
5450 if (-r "$_/info/url") {
5451 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
5452 my $ref_id = $pfx . basename $_;
5453 my $url = ::file_to_s("$_/info/url");
5454 $l_map->{$ref_id} = $url;
5455 } elsif (-d $_) {
5456 push @dir, $_;
5459 foreach (@dir) {
5460 my $x = $_;
5461 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
5462 read_old_urls($l_map, $x, $_);
5466 sub migrate_from_v2 {
5467 my @cfg = command(qw/config -l/);
5468 return if grep /^svn-remote\..+\.url=/, @cfg;
5469 my %l_map;
5470 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
5471 my $migrated = 0;
5473 foreach my $ref_id (sort keys %l_map) {
5474 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
5475 if ($@) {
5476 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
5478 $migrated++;
5480 $migrated;
5483 sub minimize_connections {
5484 my $r = Git::SVN::read_all_remotes();
5485 my $new_urls = {};
5486 my $root_repos = {};
5487 foreach my $repo_id (keys %$r) {
5488 my $url = $r->{$repo_id}->{url} or next;
5489 my $fetch = $r->{$repo_id}->{fetch} or next;
5490 my $ra = Git::SVN::Ra->new($url);
5492 # skip existing cases where we already connect to the root
5493 if (($ra->{url} eq $ra->{repos_root}) ||
5494 ($ra->{repos_root} eq $repo_id)) {
5495 $root_repos->{$ra->{url}} = $repo_id;
5496 next;
5499 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
5500 my $root_path = $ra->{url};
5501 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
5502 foreach my $path (keys %$fetch) {
5503 my $ref_id = $fetch->{$path};
5504 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
5506 # make sure we can read when connecting to
5507 # a higher level of a repository
5508 my ($last_rev, undef) = $gs->last_rev_commit;
5509 if (!defined $last_rev) {
5510 $last_rev = eval {
5511 $root_ra->get_latest_revnum;
5513 next if $@;
5515 my $new = $root_path;
5516 $new .= length $path ? "/$path" : '';
5517 eval {
5518 $root_ra->get_log([$new], $last_rev, $last_rev,
5519 0, 0, 1, sub { });
5521 next if $@;
5522 $new_urls->{$ra->{repos_root}}->{$new} =
5523 { ref_id => $ref_id,
5524 old_repo_id => $repo_id,
5525 old_path => $path };
5529 my @emptied;
5530 foreach my $url (keys %$new_urls) {
5531 # see if we can re-use an existing [svn-remote "repo_id"]
5532 # instead of creating a(n ugly) new section:
5533 my $repo_id = $root_repos->{$url} || $url;
5535 my $fetch = $new_urls->{$url};
5536 foreach my $path (keys %$fetch) {
5537 my $x = $fetch->{$path};
5538 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
5539 my $pfx = "svn-remote.$x->{old_repo_id}";
5541 my $old_fetch = quotemeta("$x->{old_path}:".
5542 "$x->{ref_id}");
5543 command_noisy(qw/config --unset/,
5544 "$pfx.fetch", '^'. $old_fetch . '$');
5545 delete $r->{$x->{old_repo_id}}->
5546 {fetch}->{$x->{old_path}};
5547 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
5548 command_noisy(qw/config --unset/,
5549 "$pfx.url");
5550 push @emptied, $x->{old_repo_id}
5554 if (@emptied) {
5555 my $file = $ENV{GIT_CONFIG} || "$ENV{GIT_DIR}/config";
5556 print STDERR <<EOF;
5557 The following [svn-remote] sections in your config file ($file) are empty
5558 and can be safely removed:
5560 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
5564 sub migration_check {
5565 migrate_from_v0();
5566 migrate_from_v1();
5567 migrate_from_v2();
5568 minimize_connections() if $_minimize;
5571 package Git::IndexInfo;
5572 use strict;
5573 use warnings;
5574 use Git qw/command_input_pipe command_close_pipe/;
5576 sub new {
5577 my ($class) = @_;
5578 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
5579 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
5582 sub remove {
5583 my ($self, $path) = @_;
5584 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
5585 return ++$self->{nr};
5587 undef;
5590 sub update {
5591 my ($self, $mode, $hash, $path) = @_;
5592 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
5593 return ++$self->{nr};
5595 undef;
5598 sub DESTROY {
5599 my ($self) = @_;
5600 command_close_pipe($self->{gui}, $self->{ctx});
5603 package Git::SVN::GlobSpec;
5604 use strict;
5605 use warnings;
5607 sub new {
5608 my ($class, $glob, $pattern_ok) = @_;
5609 my $re = $glob;
5610 $re =~ s!/+$!!g; # no need for trailing slashes
5611 my (@left, @right, @patterns);
5612 my $state = "left";
5613 my $die_msg = "Only one set of wildcard directories " .
5614 "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
5615 for my $part (split(m|/|, $glob)) {
5616 if ($part =~ /\*/ && $part ne "*") {
5617 die "Invalid pattern in '$glob': $part\n";
5618 } elsif ($pattern_ok && $part =~ /[{}]/ &&
5619 $part !~ /^\{[^{}]+\}/) {
5620 die "Invalid pattern in '$glob': $part\n";
5622 if ($part eq "*") {
5623 die $die_msg if $state eq "right";
5624 $state = "pattern";
5625 push(@patterns, "[^/]*");
5626 } elsif ($pattern_ok && $part =~ /^\{(.*)\}$/) {
5627 die $die_msg if $state eq "right";
5628 $state = "pattern";
5629 my $p = quotemeta($1);
5630 $p =~ s/\\,/|/g;
5631 push(@patterns, "(?:$p)");
5632 } else {
5633 if ($state eq "left") {
5634 push(@left, $part);
5635 } else {
5636 push(@right, $part);
5637 $state = "right";
5641 my $depth = @patterns;
5642 if ($depth == 0) {
5643 die "One '*' is needed in glob: '$glob'\n";
5645 my $left = join('/', @left);
5646 my $right = join('/', @right);
5647 $re = join('/', @patterns);
5648 $re = join('\/',
5649 grep(length, quotemeta($left), "($re)", quotemeta($right)));
5650 my $left_re = qr/^\/\Q$left\E(\/|$)/;
5651 bless { left => $left, right => $right, left_regex => $left_re,
5652 regex => qr/$re/, glob => $glob, depth => $depth }, $class;
5655 sub full_path {
5656 my ($self, $path) = @_;
5657 return (length $self->{left} ? "$self->{left}/" : '') .
5658 $path . (length $self->{right} ? "/$self->{right}" : '');
5661 __END__
5663 Data structures:
5666 $remotes = { # returned by read_all_remotes()
5667 'svn' => {
5668 # svn-remote.svn.url=https://svn.musicpd.org
5669 url => 'https://svn.musicpd.org',
5670 # svn-remote.svn.fetch=mpd/trunk:trunk
5671 fetch => {
5672 'mpd/trunk' => 'trunk',
5674 # svn-remote.svn.tags=mpd/tags/*:tags/*
5675 tags => {
5676 path => {
5677 left => 'mpd/tags',
5678 right => '',
5679 regex => qr!mpd/tags/([^/]+)$!,
5680 glob => 'tags/*',
5682 ref => {
5683 left => 'tags',
5684 right => '',
5685 regex => qr!tags/([^/]+)$!,
5686 glob => 'tags/*',
5692 $log_entry hashref as returned by libsvn_log_entry()
5694 log => 'whitespace-formatted log entry
5695 ', # trailing newline is preserved
5696 revision => '8', # integer
5697 date => '2004-02-24T17:01:44.108345Z', # commit date
5698 author => 'committer name'
5702 # this is generated by generate_diff();
5703 @mods = array of diff-index line hashes, each element represents one line
5704 of diff-index output
5706 diff-index line ($m hash)
5708 mode_a => first column of diff-index output, no leading ':',
5709 mode_b => second column of diff-index output,
5710 sha1_b => sha1sum of the final blob,
5711 chg => change type [MCRADT],
5712 file_a => original file name of a file (iff chg is 'C' or 'R')
5713 file_b => new/current file name of a file (any chg)
5717 # retval of read_url_paths{,_all}();
5718 $l_map = {
5719 # repository root url
5720 'https://svn.musicpd.org' => {
5721 # repository path # GIT_SVN_ID
5722 'mpd/trunk' => 'trunk',
5723 'mpd/tags/0.11.5' => 'tags/0.11.5',
5727 Notes:
5728 I don't trust the each() function on unless I created %hash myself
5729 because the internal iterator may not have started at base.