Prepare Git::SVN::Migration for extraction from git-svn.
[alt-git.git] / git-svn.perl
blob0266878120c452cac405c3b269797d172733ee6b
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 use Git::SVN;
14 use Git::SVN::Log;
15 use Git::SVN::Utils qw(fatal can_compress);
17 use Git qw(
18 git_cmd_try
19 command
20 command_oneline
21 command_noisy
22 command_output_pipe
23 command_close_pipe
24 command_bidi_pipe
25 command_close_bidi_pipe
29 # From which subdir have we been invoked?
30 my $cmd_dir_prefix = eval {
31 command_oneline([qw/rev-parse --show-prefix/], STDERR => 0)
32 } || '';
34 my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
35 $ENV{GIT_DIR} ||= '.git';
36 $Git::SVN::Ra::_log_window_size = 100;
38 if (! exists $ENV{SVN_SSH} && exists $ENV{GIT_SSH}) {
39 $ENV{SVN_SSH} = $ENV{GIT_SSH};
42 if (exists $ENV{SVN_SSH} && $^O eq 'msys') {
43 $ENV{SVN_SSH} =~ s/\\/\\\\/g;
44 $ENV{SVN_SSH} =~ s/(.*)/"$1"/;
47 $Git::SVN::Log::TZ = $ENV{TZ};
48 $ENV{TZ} = 'UTC';
49 $| = 1; # unbuffer STDOUT
51 # All SVN commands do it. Otherwise we may die on SIGPIPE when the remote
52 # repository decides to close the connection which we expect to be kept alive.
53 $SIG{PIPE} = 'IGNORE';
55 # Given a dot separated version number, "subtract" it from
56 # the SVN::Core::VERSION; non-negaitive return means the SVN::Core
57 # is at least at the version the caller asked for.
58 sub compare_svn_version {
59 my (@ours) = split(/\./, $SVN::Core::VERSION);
60 my (@theirs) = split(/\./, $_[0]);
61 my ($i, $diff);
63 for ($i = 0; $i < @ours && $i < @theirs; $i++) {
64 $diff = $ours[$i] - $theirs[$i];
65 return $diff if ($diff);
67 return 1 if ($i < @ours);
68 return -1 if ($i < @theirs);
69 return 0;
72 sub _req_svn {
73 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
74 require SVN::Ra;
75 require SVN::Delta;
76 if (::compare_svn_version('1.1.0') < 0) {
77 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
81 use Carp qw/croak/;
82 use Digest::MD5;
83 use IO::File qw//;
84 use File::Basename qw/dirname basename/;
85 use File::Path qw/mkpath/;
86 use File::Spec;
87 use File::Find;
88 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
89 use IPC::Open3;
90 use Git::SVN::Editor qw//;
91 use Git::SVN::Fetcher qw//;
92 use Git::SVN::Ra qw//;
93 use Git::SVN::Prompt qw//;
94 use Memoize; # core since 5.8.0, Jul 2002
96 BEGIN {
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 $_commit_url, $_tag, $_merge_info, $_interactive);
113 # This is a refactoring artifact so Git::SVN can get at this git-svn switch.
114 sub opt_prefix { return $_prefix || '' }
116 $Git::SVN::Fetcher::_placeholder_filename = ".gitignore";
117 $_q ||= 0;
118 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
119 'config-dir=s' => \$Git::SVN::Ra::config_dir,
120 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
121 'ignore-paths=s' => \$Git::SVN::Fetcher::_ignore_regex,
122 'ignore-refs=s' => \$Git::SVN::Ra::_ignore_refs_regex );
123 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
124 'authors-file|A=s' => \$_authors,
125 'authors-prog=s' => \$_authors_prog,
126 'repack:i' => \$Git::SVN::_repack,
127 'noMetadata' => \$Git::SVN::_no_metadata,
128 'useSvmProps' => \$Git::SVN::_use_svm_props,
129 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
130 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
131 'no-checkout' => \$_no_checkout,
132 'quiet|q+' => \$_q,
133 'repack-flags|repack-args|repack-opts=s' =>
134 \$Git::SVN::_repack_flags,
135 'use-log-author' => \$Git::SVN::_use_log_author,
136 'add-author-from' => \$Git::SVN::_add_author_from,
137 'localtime' => \$Git::SVN::_localtime,
138 %remote_opts );
140 my ($_trunk, @_tags, @_branches, $_stdlayout);
141 my %icv;
142 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
143 'trunk|T=s' => \$_trunk, 'tags|t=s@' => \@_tags,
144 'branches|b=s@' => \@_branches, 'prefix=s' => \$_prefix,
145 'stdlayout|s' => \$_stdlayout,
146 'minimize-url|m!' => \$Git::SVN::_minimize_url,
147 'no-metadata' => sub { $icv{noMetadata} = 1 },
148 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
149 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
150 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
151 'rewrite-uuid=s' => sub { $icv{rewriteUUID} = $_[1] },
152 %remote_opts );
153 my %cmt_opts = ( 'edit|e' => \$_edit,
154 'rmdir' => \$Git::SVN::Editor::_rmdir,
155 'find-copies-harder' => \$Git::SVN::Editor::_find_copies_harder,
156 'l=i' => \$Git::SVN::Editor::_rename_limit,
157 'copy-similarity|C=i'=> \$Git::SVN::Editor::_cp_similarity
160 my %cmd = (
161 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
162 { 'revision|r=s' => \$_revision,
163 'fetch-all|all' => \$_fetch_all,
164 'parent|p' => \$_fetch_parent,
165 %fc_opts } ],
166 clone => [ \&cmd_clone, "Initialize and fetch revisions",
167 { 'revision|r=s' => \$_revision,
168 'preserve-empty-dirs' =>
169 \$Git::SVN::Fetcher::_preserve_empty_dirs,
170 'placeholder-filename=s' =>
171 \$Git::SVN::Fetcher::_placeholder_filename,
172 %fc_opts, %init_opts } ],
173 init => [ \&cmd_init, "Initialize a repo for tracking" .
174 " (requires URL argument)",
175 \%init_opts ],
176 'multi-init' => [ \&cmd_multi_init,
177 "Deprecated alias for ".
178 "'$0 init -T<trunk> -b<branches> -t<tags>'",
179 \%init_opts ],
180 dcommit => [ \&cmd_dcommit,
181 'Commit several diffs to merge with upstream',
182 { 'merge|m|M' => \$_merge,
183 'strategy|s=s' => \$_strategy,
184 'verbose|v' => \$_verbose,
185 'dry-run|n' => \$_dry_run,
186 'fetch-all|all' => \$_fetch_all,
187 'commit-url=s' => \$_commit_url,
188 'revision|r=i' => \$_revision,
189 'no-rebase' => \$_no_rebase,
190 'mergeinfo=s' => \$_merge_info,
191 'interactive|i' => \$_interactive,
192 %cmt_opts, %fc_opts } ],
193 branch => [ \&cmd_branch,
194 'Create a branch in the SVN repository',
195 { 'message|m=s' => \$_message,
196 'destination|d=s' => \$_branch_dest,
197 'dry-run|n' => \$_dry_run,
198 'tag|t' => \$_tag,
199 'username=s' => \$Git::SVN::Prompt::_username,
200 'commit-url=s' => \$_commit_url } ],
201 tag => [ sub { $_tag = 1; cmd_branch(@_) },
202 'Create a tag in the SVN repository',
203 { 'message|m=s' => \$_message,
204 'destination|d=s' => \$_branch_dest,
205 'dry-run|n' => \$_dry_run,
206 'username=s' => \$Git::SVN::Prompt::_username,
207 'commit-url=s' => \$_commit_url } ],
208 'set-tree' => [ \&cmd_set_tree,
209 "Set an SVN repository to a git tree-ish",
210 { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
211 'create-ignore' => [ \&cmd_create_ignore,
212 'Create a .gitignore per svn:ignore',
213 { 'revision|r=i' => \$_revision
214 } ],
215 'mkdirs' => [ \&cmd_mkdirs ,
216 "recreate empty directories after a checkout",
217 { 'revision|r=i' => \$_revision } ],
218 'propget' => [ \&cmd_propget,
219 'Print the value of a property on a file or directory',
220 { 'revision|r=i' => \$_revision } ],
221 'proplist' => [ \&cmd_proplist,
222 'List all properties of a file or directory',
223 { 'revision|r=i' => \$_revision } ],
224 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
225 { 'revision|r=i' => \$_revision
226 } ],
227 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
228 { 'revision|r=i' => \$_revision
229 } ],
230 'multi-fetch' => [ \&cmd_multi_fetch,
231 "Deprecated alias for $0 fetch --all",
232 { 'revision|r=s' => \$_revision, %fc_opts } ],
233 'migrate' => [ sub { },
234 # no-op, we automatically run this anyways,
235 'Migrate configuration/metadata/layout from
236 previous versions of git-svn',
237 { 'minimize' => \$Git::SVN::Migration::_minimize,
238 %remote_opts } ],
239 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
240 { 'limit=i' => \$Git::SVN::Log::limit,
241 'revision|r=s' => \$_revision,
242 'verbose|v' => \$Git::SVN::Log::verbose,
243 'incremental' => \$Git::SVN::Log::incremental,
244 'oneline' => \$Git::SVN::Log::oneline,
245 'show-commit' => \$Git::SVN::Log::show_commit,
246 'non-recursive' => \$Git::SVN::Log::non_recursive,
247 'authors-file|A=s' => \$_authors,
248 'color' => \$Git::SVN::Log::color,
249 'pager=s' => \$Git::SVN::Log::pager
250 } ],
251 'find-rev' => [ \&cmd_find_rev,
252 "Translate between SVN revision numbers and tree-ish",
253 {} ],
254 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
255 { 'merge|m|M' => \$_merge,
256 'verbose|v' => \$_verbose,
257 'strategy|s=s' => \$_strategy,
258 'local|l' => \$_local,
259 'fetch-all|all' => \$_fetch_all,
260 'dry-run|n' => \$_dry_run,
261 'preserve-merges|p' => \$_preserve_merges,
262 %fc_opts } ],
263 'commit-diff' => [ \&cmd_commit_diff,
264 'Commit a diff between two trees',
265 { 'message|m=s' => \$_message,
266 'file|F=s' => \$_file,
267 'revision|r=s' => \$_revision,
268 %cmt_opts } ],
269 'info' => [ \&cmd_info,
270 "Show info about the latest SVN revision
271 on the current branch",
272 { 'url' => \$_url, } ],
273 'blame' => [ \&Git::SVN::Log::cmd_blame,
274 "Show what revision and author last modified each line of a file",
275 { 'git-format' => \$Git::SVN::Log::_git_format } ],
276 'reset' => [ \&cmd_reset,
277 "Undo fetches back to the specified SVN revision",
278 { 'revision|r=s' => \$_revision,
279 'parent|p' => \$_fetch_parent } ],
280 'gc' => [ \&cmd_gc,
281 "Compress unhandled.log files in .git/svn and remove " .
282 "index files in .git/svn",
283 {} ],
286 use Term::ReadLine;
287 package FakeTerm;
288 sub new {
289 my ($class, $reason) = @_;
290 return bless \$reason, shift;
292 sub readline {
293 my $self = shift;
294 die "Cannot use readline on FakeTerm: $$self";
296 package main;
298 my $term = eval {
299 $ENV{"GIT_SVN_NOTTY"}
300 ? new Term::ReadLine 'git-svn', \*STDIN, \*STDOUT
301 : new Term::ReadLine 'git-svn';
303 if ($@) {
304 $term = new FakeTerm "$@: going non-interactive";
307 my $cmd;
308 for (my $i = 0; $i < @ARGV; $i++) {
309 if (defined $cmd{$ARGV[$i]}) {
310 $cmd = $ARGV[$i];
311 splice @ARGV, $i, 1;
312 last;
313 } elsif ($ARGV[$i] eq 'help') {
314 $cmd = $ARGV[$i+1];
315 usage(0);
319 # make sure we're always running at the top-level working directory
320 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
321 unless (-d $ENV{GIT_DIR}) {
322 if ($git_dir_user_set) {
323 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
324 "but it is not a directory\n";
326 my $git_dir = delete $ENV{GIT_DIR};
327 my $cdup = undef;
328 git_cmd_try {
329 $cdup = command_oneline(qw/rev-parse --show-cdup/);
330 $git_dir = '.' unless ($cdup);
331 chomp $cdup if ($cdup);
332 $cdup = "." unless ($cdup && length $cdup);
333 } "Already at toplevel, but $git_dir not found\n";
334 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
335 unless (-d $git_dir) {
336 die "$git_dir still not found after going to ",
337 "'$cdup'\n";
339 $ENV{GIT_DIR} = $git_dir;
341 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
344 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
346 read_git_config(\%opts);
347 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
348 Getopt::Long::Configure('pass_through');
350 my $rv = GetOptions(%opts, 'h|H' => \$_help, 'version|V' => \$_version,
351 'minimize-connections' => \$Git::SVN::Migration::_minimize,
352 'id|i=s' => \$Git::SVN::default_ref_id,
353 'svn-remote|remote|R=s' => sub {
354 $Git::SVN::no_reuse_existing = 1;
355 $Git::SVN::default_repo_id = $_[1] });
356 exit 1 if (!$rv && $cmd && $cmd ne 'log');
358 usage(0) if $_help;
359 version() if $_version;
360 usage(1) unless defined $cmd;
361 load_authors() if $_authors;
362 if (defined $_authors_prog) {
363 $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
366 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
367 Git::SVN::Migration::migration_check();
369 Git::SVN::init_vars();
370 eval {
371 Git::SVN::verify_remotes_sanity();
372 $cmd{$cmd}->[0]->(@ARGV);
373 post_fetch_checkout();
375 fatal $@ if $@;
376 exit 0;
378 ####################### primary functions ######################
379 sub usage {
380 my $exit = shift || 0;
381 my $fd = $exit ? \*STDERR : \*STDOUT;
382 print $fd <<"";
383 git-svn - bidirectional operations between a single Subversion tree and git
384 Usage: git svn <command> [options] [arguments]\n
386 print $fd "Available commands:\n" unless $cmd;
388 foreach (sort keys %cmd) {
389 next if $cmd && $cmd ne $_;
390 next if /^multi-/; # don't show deprecated commands
391 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
392 foreach (sort keys %{$cmd{$_}->[2]}) {
393 # mixed-case options are for .git/config only
394 next if /[A-Z]/ && /^[a-z]+$/i;
395 # prints out arguments as they should be passed:
396 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
397 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
398 "--$_" : "-$_" }
399 split /\|/,$_)," $x\n";
402 print $fd <<"";
403 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
404 arbitrary identifier if you're tracking multiple SVN branches/repositories in
405 one git repository and want to keep them separate. See git-svn(1) for more
406 information.
408 exit $exit;
411 sub version {
412 ::_req_svn();
413 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
414 exit 0;
417 sub ask {
418 my ($prompt, %arg) = @_;
419 my $valid_re = $arg{valid_re};
420 my $default = $arg{default};
421 my $resp;
422 my $i = 0;
424 if ( !( defined($term->IN)
425 && defined( fileno($term->IN) )
426 && defined( $term->OUT )
427 && defined( fileno($term->OUT) ) ) ){
428 return defined($default) ? $default : undef;
431 while ($i++ < 10) {
432 $resp = $term->readline($prompt);
433 if (!defined $resp) { # EOF
434 print "\n";
435 return defined $default ? $default : undef;
437 if ($resp eq '' and defined $default) {
438 return $default;
440 if (!defined $valid_re or $resp =~ /$valid_re/) {
441 return $resp;
444 return undef;
447 sub do_git_init_db {
448 unless (-d $ENV{GIT_DIR}) {
449 my @init_db = ('init');
450 push @init_db, "--template=$_template" if defined $_template;
451 if (defined $_shared) {
452 if ($_shared =~ /[a-z]/) {
453 push @init_db, "--shared=$_shared";
454 } else {
455 push @init_db, "--shared";
458 command_noisy(@init_db);
459 $_repository = Git->repository(Repository => ".git");
461 my $set;
462 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
463 foreach my $i (keys %icv) {
464 die "'$set' and '$i' cannot both be set\n" if $set;
465 next unless defined $icv{$i};
466 command_noisy('config', "$pfx.$i", $icv{$i});
467 $set = $i;
469 my $ignore_paths_regex = \$Git::SVN::Fetcher::_ignore_regex;
470 command_noisy('config', "$pfx.ignore-paths", $$ignore_paths_regex)
471 if defined $$ignore_paths_regex;
472 my $ignore_refs_regex = \$Git::SVN::Ra::_ignore_refs_regex;
473 command_noisy('config', "$pfx.ignore-refs", $$ignore_refs_regex)
474 if defined $$ignore_refs_regex;
476 if (defined $Git::SVN::Fetcher::_preserve_empty_dirs) {
477 my $fname = \$Git::SVN::Fetcher::_placeholder_filename;
478 command_noisy('config', "$pfx.preserve-empty-dirs", 'true');
479 command_noisy('config', "$pfx.placeholder-filename", $$fname);
483 sub init_subdir {
484 my $repo_path = shift or return;
485 mkpath([$repo_path]) unless -d $repo_path;
486 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
487 $ENV{GIT_DIR} = '.git';
488 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
491 sub cmd_clone {
492 my ($url, $path) = @_;
493 if (!defined $path &&
494 (defined $_trunk || @_branches || @_tags ||
495 defined $_stdlayout) &&
496 $url !~ m#^[a-z\+]+://#) {
497 $path = $url;
499 $path = basename($url) if !defined $path || !length $path;
500 my $authors_absolute = $_authors ? File::Spec->rel2abs($_authors) : "";
501 cmd_init($url, $path);
502 command_oneline('config', 'svn.authorsfile', $authors_absolute)
503 if $_authors;
504 Git::SVN::fetch_all($Git::SVN::default_repo_id);
507 sub cmd_init {
508 if (defined $_stdlayout) {
509 $_trunk = 'trunk' if (!defined $_trunk);
510 @_tags = 'tags' if (! @_tags);
511 @_branches = 'branches' if (! @_branches);
513 if (defined $_trunk || @_branches || @_tags) {
514 return cmd_multi_init(@_);
516 my $url = shift or die "SVN repository location required ",
517 "as a command-line argument\n";
518 $url = canonicalize_url($url);
519 init_subdir(@_);
520 do_git_init_db();
522 if ($Git::SVN::_minimize_url eq 'unset') {
523 $Git::SVN::_minimize_url = 0;
526 Git::SVN->init($url);
529 sub cmd_fetch {
530 if (grep /^\d+=./, @_) {
531 die "'<rev>=<commit>' fetch arguments are ",
532 "no longer supported.\n";
534 my ($remote) = @_;
535 if (@_ > 1) {
536 die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
538 $Git::SVN::no_reuse_existing = undef;
539 if ($_fetch_parent) {
540 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
541 unless ($gs) {
542 die "Unable to determine upstream SVN information from ",
543 "working tree history\n";
545 # just fetch, don't checkout.
546 $_no_checkout = 'true';
547 $_fetch_all ? $gs->fetch_all : $gs->fetch;
548 } elsif ($_fetch_all) {
549 cmd_multi_fetch();
550 } else {
551 $remote ||= $Git::SVN::default_repo_id;
552 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
556 sub cmd_set_tree {
557 my (@commits) = @_;
558 if ($_stdin || !@commits) {
559 print "Reading from stdin...\n";
560 @commits = ();
561 while (<STDIN>) {
562 if (/\b($sha1_short)\b/o) {
563 unshift @commits, $1;
567 my @revs;
568 foreach my $c (@commits) {
569 my @tmp = command('rev-parse',$c);
570 if (scalar @tmp == 1) {
571 push @revs, $tmp[0];
572 } elsif (scalar @tmp > 1) {
573 push @revs, reverse(command('rev-list',@tmp));
574 } else {
575 fatal "Failed to rev-parse $c";
578 my $gs = Git::SVN->new;
579 my ($r_last, $cmt_last) = $gs->last_rev_commit;
580 $gs->fetch;
581 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
582 fatal "There are new revisions that were fetched ",
583 "and need to be merged (or acknowledged) ",
584 "before committing.\nlast rev: $r_last\n",
585 " current: $gs->{last_rev}";
587 $gs->set_tree($_) foreach @revs;
588 print "Done committing ",scalar @revs," revisions to SVN\n";
589 unlink $gs->{index};
592 sub split_merge_info_range {
593 my ($range) = @_;
594 if ($range =~ /(\d+)-(\d+)/) {
595 return (int($1), int($2));
596 } else {
597 return (int($range), int($range));
601 sub combine_ranges {
602 my ($in) = @_;
604 my @fnums = ();
605 my @arr = split(/,/, $in);
606 for my $element (@arr) {
607 my ($start, $end) = split_merge_info_range($element);
608 push @fnums, $start;
611 my @sorted = @arr [ sort {
612 $fnums[$a] <=> $fnums[$b]
613 } 0..$#arr ];
615 my @return = ();
616 my $last = -1;
617 my $first = -1;
618 for my $element (@sorted) {
619 my ($start, $end) = split_merge_info_range($element);
621 if ($last == -1) {
622 $first = $start;
623 $last = $end;
624 next;
626 if ($start <= $last+1) {
627 if ($end > $last) {
628 $last = $end;
630 next;
632 if ($first == $last) {
633 push @return, "$first";
634 } else {
635 push @return, "$first-$last";
637 $first = $start;
638 $last = $end;
641 if ($first != -1) {
642 if ($first == $last) {
643 push @return, "$first";
644 } else {
645 push @return, "$first-$last";
649 return join(',', @return);
652 sub merge_revs_into_hash {
653 my ($hash, $minfo) = @_;
654 my @lines = split(' ', $minfo);
656 for my $line (@lines) {
657 my ($branchpath, $revs) = split(/:/, $line);
659 if (exists($hash->{$branchpath})) {
660 # Merge the two revision sets
661 my $combined = "$hash->{$branchpath},$revs";
662 $hash->{$branchpath} = combine_ranges($combined);
663 } else {
664 # Just do range combining for consolidation
665 $hash->{$branchpath} = combine_ranges($revs);
670 sub merge_merge_info {
671 my ($mergeinfo_one, $mergeinfo_two) = @_;
672 my %result_hash = ();
674 merge_revs_into_hash(\%result_hash, $mergeinfo_one);
675 merge_revs_into_hash(\%result_hash, $mergeinfo_two);
677 my $result = '';
678 # Sort below is for consistency's sake
679 for my $branchname (sort keys(%result_hash)) {
680 my $revlist = $result_hash{$branchname};
681 $result .= "$branchname:$revlist\n"
683 return $result;
686 sub populate_merge_info {
687 my ($d, $gs, $uuid, $linear_refs, $rewritten_parent) = @_;
689 my %parentshash;
690 read_commit_parents(\%parentshash, $d);
691 my @parents = @{$parentshash{$d}};
692 if ($#parents > 0) {
693 # Merge commit
694 my $all_parents_ok = 1;
695 my $aggregate_mergeinfo = '';
696 my $rooturl = $gs->repos_root;
698 if (defined($rewritten_parent)) {
699 # Replace first parent with newly-rewritten version
700 shift @parents;
701 unshift @parents, $rewritten_parent;
704 foreach my $parent (@parents) {
705 my ($branchurl, $svnrev, $paruuid) =
706 cmt_metadata($parent);
708 unless (defined($svnrev)) {
709 # Should have been caught be preflight check
710 fatal "merge commit $d has ancestor $parent, but that change "
711 ."does not have git-svn metadata!";
713 unless ($branchurl =~ /^\Q$rooturl\E(.*)/) {
714 fatal "commit $parent git-svn metadata changed mid-run!";
716 my $branchpath = $1;
718 my $ra = Git::SVN::Ra->new($branchurl);
719 my (undef, undef, $props) =
720 $ra->get_dir(canonicalize_path("."), $svnrev);
721 my $par_mergeinfo = $props->{'svn:mergeinfo'};
722 unless (defined $par_mergeinfo) {
723 $par_mergeinfo = '';
725 # Merge previous mergeinfo values
726 $aggregate_mergeinfo =
727 merge_merge_info($aggregate_mergeinfo,
728 $par_mergeinfo, 0);
730 next if $parent eq $parents[0]; # Skip first parent
731 # Add new changes being placed in tree by merge
732 my @cmd = (qw/rev-list --reverse/,
733 $parent, qw/--not/);
734 foreach my $par (@parents) {
735 unless ($par eq $parent) {
736 push @cmd, $par;
739 my @revsin = ();
740 my ($revlist, $ctx) = command_output_pipe(@cmd);
741 while (<$revlist>) {
742 my $irev = $_;
743 chomp $irev;
744 my (undef, $csvnrev, undef) =
745 cmt_metadata($irev);
746 unless (defined $csvnrev) {
747 # A child is missing SVN annotations...
748 # this might be OK, or might not be.
749 warn "W:child $irev is merged into revision "
750 ."$d but does not have git-svn metadata. "
751 ."This means git-svn cannot determine the "
752 ."svn revision numbers to place into the "
753 ."svn:mergeinfo property. You must ensure "
754 ."a branch is entirely committed to "
755 ."SVN before merging it in order for "
756 ."svn:mergeinfo population to function "
757 ."properly";
759 push @revsin, $csvnrev;
761 command_close_pipe($revlist, $ctx);
763 last unless $all_parents_ok;
765 # We now have a list of all SVN revnos which are
766 # merged by this particular parent. Integrate them.
767 next if $#revsin == -1;
768 my $newmergeinfo = "$branchpath:" . join(',', @revsin);
769 $aggregate_mergeinfo =
770 merge_merge_info($aggregate_mergeinfo,
771 $newmergeinfo, 1);
773 if ($all_parents_ok and $aggregate_mergeinfo) {
774 return $aggregate_mergeinfo;
778 return undef;
781 sub cmd_dcommit {
782 my $head = shift;
783 command_noisy(qw/update-index --refresh/);
784 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
785 'Cannot dcommit with a dirty index. Commit your changes first, '
786 . "or stash them with `git stash'.\n";
787 $head ||= 'HEAD';
789 my $old_head;
790 if ($head ne 'HEAD') {
791 $old_head = eval {
792 command_oneline([qw/symbolic-ref -q HEAD/])
794 if ($old_head) {
795 $old_head =~ s{^refs/heads/}{};
796 } else {
797 $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
799 command(['checkout', $head], STDERR => 0);
802 my @refs;
803 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
804 unless ($gs) {
805 die "Unable to determine upstream SVN information from ",
806 "$head history.\nPerhaps the repository is empty.";
809 if (defined $_commit_url) {
810 $url = $_commit_url;
811 } else {
812 $url = eval { command_oneline('config', '--get',
813 "svn-remote.$gs->{repo_id}.commiturl") };
814 if (!$url) {
815 $url = $gs->full_pushurl
819 my $last_rev = $_revision if defined $_revision;
820 if ($url) {
821 print "Committing to $url ...\n";
823 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
824 if ($_no_rebase && scalar(@$linear_refs) > 1) {
825 warn "Attempting to commit more than one change while ",
826 "--no-rebase is enabled.\n",
827 "If these changes depend on each other, re-running ",
828 "without --no-rebase may be required."
831 if (defined $_interactive){
832 my $ask_default = "y";
833 foreach my $d (@$linear_refs){
834 my ($fh, $ctx) = command_output_pipe(qw(show --summary), "$d");
835 while (<$fh>){
836 print $_;
838 command_close_pipe($fh, $ctx);
839 $_ = ask("Commit this patch to SVN? ([y]es (default)|[n]o|[q]uit|[a]ll): ",
840 valid_re => qr/^(?:yes|y|no|n|quit|q|all|a)/i,
841 default => $ask_default);
842 die "Commit this patch reply required" unless defined $_;
843 if (/^[nq]/i) {
844 exit(0);
845 } elsif (/^a/i) {
846 last;
851 my $expect_url = $url;
853 my $push_merge_info = eval {
854 command_oneline(qw/config --get svn.pushmergeinfo/)
856 if (not defined($push_merge_info)
857 or $push_merge_info eq "false"
858 or $push_merge_info eq "no"
859 or $push_merge_info eq "never") {
860 $push_merge_info = 0;
863 unless (defined($_merge_info) || ! $push_merge_info) {
864 # Preflight check of changes to ensure no issues with mergeinfo
865 # This includes check for uncommitted-to-SVN parents
866 # (other than the first parent, which we will handle),
867 # information from different SVN repos, and paths
868 # which are not underneath this repository root.
869 my $rooturl = $gs->repos_root;
870 foreach my $d (@$linear_refs) {
871 my %parentshash;
872 read_commit_parents(\%parentshash, $d);
873 my @realparents = @{$parentshash{$d}};
874 if ($#realparents > 0) {
875 # Merge commit
876 shift @realparents; # Remove/ignore first parent
877 foreach my $parent (@realparents) {
878 my ($branchurl, $svnrev, $paruuid) = cmt_metadata($parent);
879 unless (defined $paruuid) {
880 # A parent is missing SVN annotations...
881 # abort the whole operation.
882 fatal "$parent is merged into revision $d, "
883 ."but does not have git-svn metadata. "
884 ."Either dcommit the branch or use a "
885 ."local cherry-pick, FF merge, or rebase "
886 ."instead of an explicit merge commit.";
889 unless ($paruuid eq $uuid) {
890 # Parent has SVN metadata from different repository
891 fatal "merge parent $parent for change $d has "
892 ."git-svn uuid $paruuid, while current change "
893 ."has uuid $uuid!";
896 unless ($branchurl =~ /^\Q$rooturl\E(.*)/) {
897 # This branch is very strange indeed.
898 fatal "merge parent $parent for $d is on branch "
899 ."$branchurl, which is not under the "
900 ."git-svn root $rooturl!";
907 my $rewritten_parent;
908 Git::SVN::remove_username($expect_url);
909 if (defined($_merge_info)) {
910 $_merge_info =~ tr{ }{\n};
912 while (1) {
913 my $d = shift @$linear_refs or last;
914 unless (defined $last_rev) {
915 (undef, $last_rev, undef) = cmt_metadata("$d~1");
916 unless (defined $last_rev) {
917 fatal "Unable to extract revision information ",
918 "from commit $d~1";
921 if ($_dry_run) {
922 print "diff-tree $d~1 $d\n";
923 } else {
924 my $cmt_rev;
926 unless (defined($_merge_info) || ! $push_merge_info) {
927 $_merge_info = populate_merge_info($d, $gs,
928 $uuid,
929 $linear_refs,
930 $rewritten_parent);
933 my %ed_opts = ( r => $last_rev,
934 log => get_commit_entry($d)->{log},
935 ra => Git::SVN::Ra->new($url),
936 config => SVN::Core::config_get_config(
937 $Git::SVN::Ra::config_dir
939 tree_a => "$d~1",
940 tree_b => $d,
941 editor_cb => sub {
942 print "Committed r$_[0]\n";
943 $cmt_rev = $_[0];
945 mergeinfo => $_merge_info,
946 svn_path => '');
947 if (!Git::SVN::Editor->new(\%ed_opts)->apply_diff) {
948 print "No changes\n$d~1 == $d\n";
949 } elsif ($parents->{$d} && @{$parents->{$d}}) {
950 $gs->{inject_parents_dcommit}->{$cmt_rev} =
951 $parents->{$d};
953 $_fetch_all ? $gs->fetch_all : $gs->fetch;
954 $last_rev = $cmt_rev;
955 next if $_no_rebase;
957 # we always want to rebase against the current HEAD,
958 # not any head that was passed to us
959 my @diff = command('diff-tree', $d,
960 $gs->refname, '--');
961 my @finish;
962 if (@diff) {
963 @finish = rebase_cmd();
964 print STDERR "W: $d and ", $gs->refname,
965 " differ, using @finish:\n",
966 join("\n", @diff), "\n";
967 } else {
968 print "No changes between current HEAD and ",
969 $gs->refname,
970 "\nResetting to the latest ",
971 $gs->refname, "\n";
972 @finish = qw/reset --mixed/;
974 command_noisy(@finish, $gs->refname);
976 $rewritten_parent = command_oneline(qw/rev-parse HEAD/);
978 if (@diff) {
979 @refs = ();
980 my ($url_, $rev_, $uuid_, $gs_) =
981 working_head_info('HEAD', \@refs);
982 my ($linear_refs_, $parents_) =
983 linearize_history($gs_, \@refs);
984 if (scalar(@$linear_refs) !=
985 scalar(@$linear_refs_)) {
986 fatal "# of revisions changed ",
987 "\nbefore:\n",
988 join("\n", @$linear_refs),
989 "\n\nafter:\n",
990 join("\n", @$linear_refs_), "\n",
991 'If you are attempting to commit ',
992 "merges, try running:\n\t",
993 'git rebase --interactive',
994 '--preserve-merges ',
995 $gs->refname,
996 "\nBefore dcommitting";
998 if ($url_ ne $expect_url) {
999 if ($url_ eq $gs->metadata_url) {
1000 print
1001 "Accepting rewritten URL:",
1002 " $url_\n";
1003 } else {
1004 fatal
1005 "URL mismatch after rebase:",
1006 " $url_ != $expect_url";
1009 if ($uuid_ ne $uuid) {
1010 fatal "uuid mismatch after rebase: ",
1011 "$uuid_ != $uuid";
1013 # remap parents
1014 my (%p, @l, $i);
1015 for ($i = 0; $i < scalar @$linear_refs; $i++) {
1016 my $new = $linear_refs_->[$i] or next;
1017 $p{$new} =
1018 $parents->{$linear_refs->[$i]};
1019 push @l, $new;
1021 $parents = \%p;
1022 $linear_refs = \@l;
1027 if ($old_head) {
1028 my $new_head = command_oneline(qw/rev-parse HEAD/);
1029 my $new_is_symbolic = eval {
1030 command_oneline(qw/symbolic-ref -q HEAD/);
1032 if ($new_is_symbolic) {
1033 print "dcommitted the branch ", $head, "\n";
1034 } else {
1035 print "dcommitted on a detached HEAD because you gave ",
1036 "a revision argument.\n",
1037 "The rewritten commit is: ", $new_head, "\n";
1039 command(['checkout', $old_head], STDERR => 0);
1042 unlink $gs->{index};
1045 sub cmd_branch {
1046 my ($branch_name, $head) = @_;
1048 unless (defined $branch_name && length $branch_name) {
1049 die(($_tag ? "tag" : "branch") . " name required\n");
1051 $head ||= 'HEAD';
1053 my (undef, $rev, undef, $gs) = working_head_info($head);
1054 my $src = $gs->full_pushurl;
1056 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
1057 my $allglobs = $remote->{ $_tag ? 'tags' : 'branches' };
1058 my $glob;
1059 if ($#{$allglobs} == 0) {
1060 $glob = $allglobs->[0];
1061 } else {
1062 unless(defined $_branch_dest) {
1063 die "Multiple ",
1064 $_tag ? "tag" : "branch",
1065 " paths defined for Subversion repository.\n",
1066 "You must specify where you want to create the ",
1067 $_tag ? "tag" : "branch",
1068 " with the --destination argument.\n";
1070 foreach my $g (@{$allglobs}) {
1071 my $re = Git::SVN::Editor::glob2pat($g->{path}->{left});
1072 if ($_branch_dest =~ /$re/) {
1073 $glob = $g;
1074 last;
1077 unless (defined $glob) {
1078 my $dest_re = qr/\b\Q$_branch_dest\E\b/;
1079 foreach my $g (@{$allglobs}) {
1080 $g->{path}->{left} =~ /$dest_re/ or next;
1081 if (defined $glob) {
1082 die "Ambiguous destination: ",
1083 $_branch_dest, "\nmatches both '",
1084 $glob->{path}->{left}, "' and '",
1085 $g->{path}->{left}, "'\n";
1087 $glob = $g;
1089 unless (defined $glob) {
1090 die "Unknown ",
1091 $_tag ? "tag" : "branch",
1092 " destination $_branch_dest\n";
1096 my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
1097 my $url;
1098 if (defined $_commit_url) {
1099 $url = $_commit_url;
1100 } else {
1101 $url = eval { command_oneline('config', '--get',
1102 "svn-remote.$gs->{repo_id}.commiturl") };
1103 if (!$url) {
1104 $url = $remote->{pushurl} || $remote->{url};
1107 my $dst = join '/', $url, $lft, $branch_name, ($rgt || ());
1109 if ($dst =~ /^https:/ && $src =~ /^http:/) {
1110 $src=~s/^http:/https:/;
1113 ::_req_svn();
1115 my $ctx = SVN::Client->new(
1116 auth => Git::SVN::Ra::_auth_providers(),
1117 log_msg => sub {
1118 ${ $_[0] } = defined $_message
1119 ? $_message
1120 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
1121 . $branch_name;
1125 eval {
1126 $ctx->ls($dst, 'HEAD', 0);
1127 } and die "branch ${branch_name} already exists\n";
1129 print "Copying ${src} at r${rev} to ${dst}...\n";
1130 $ctx->copy($src, $rev, $dst)
1131 unless $_dry_run;
1133 $gs->fetch_all;
1136 sub cmd_find_rev {
1137 my $revision_or_hash = shift or die "SVN or git revision required ",
1138 "as a command-line argument\n";
1139 my $result;
1140 if ($revision_or_hash =~ /^r\d+$/) {
1141 my $head = shift;
1142 $head ||= 'HEAD';
1143 my @refs;
1144 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
1145 unless ($gs) {
1146 die "Unable to determine upstream SVN information from ",
1147 "$head history\n";
1149 my $desired_revision = substr($revision_or_hash, 1);
1150 $result = $gs->rev_map_get($desired_revision, $uuid);
1151 } else {
1152 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
1153 $result = $rev;
1155 print "$result\n" if $result;
1158 sub auto_create_empty_directories {
1159 my ($gs) = @_;
1160 my $var = eval { command_oneline('config', '--get', '--bool',
1161 "svn-remote.$gs->{repo_id}.automkdirs") };
1162 # By default, create empty directories by consulting the unhandled log,
1163 # but allow setting it to 'false' to skip it.
1164 return !($var && $var eq 'false');
1167 sub cmd_rebase {
1168 command_noisy(qw/update-index --refresh/);
1169 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1170 unless ($gs) {
1171 die "Unable to determine upstream SVN information from ",
1172 "working tree history\n";
1174 if ($_dry_run) {
1175 print "Remote Branch: " . $gs->refname . "\n";
1176 print "SVN URL: " . $url . "\n";
1177 return;
1179 if (command(qw/diff-index HEAD --/)) {
1180 print STDERR "Cannot rebase with uncommited changes:\n";
1181 command_noisy('status');
1182 exit 1;
1184 unless ($_local) {
1185 # rebase will checkout for us, so no need to do it explicitly
1186 $_no_checkout = 'true';
1187 $_fetch_all ? $gs->fetch_all : $gs->fetch;
1189 command_noisy(rebase_cmd(), $gs->refname);
1190 if (auto_create_empty_directories($gs)) {
1191 $gs->mkemptydirs;
1195 sub cmd_show_ignore {
1196 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1197 $gs ||= Git::SVN->new;
1198 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1199 $gs->prop_walk($gs->{path}, $r, sub {
1200 my ($gs, $path, $props) = @_;
1201 print STDOUT "\n# $path\n";
1202 my $s = $props->{'svn:ignore'} or return;
1203 $s =~ s/[\r\n]+/\n/g;
1204 $s =~ s/^\n+//;
1205 chomp $s;
1206 $s =~ s#^#$path#gm;
1207 print STDOUT "$s\n";
1211 sub cmd_show_externals {
1212 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1213 $gs ||= Git::SVN->new;
1214 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1215 $gs->prop_walk($gs->{path}, $r, sub {
1216 my ($gs, $path, $props) = @_;
1217 print STDOUT "\n# $path\n";
1218 my $s = $props->{'svn:externals'} or return;
1219 $s =~ s/[\r\n]+/\n/g;
1220 chomp $s;
1221 $s =~ s#^#$path#gm;
1222 print STDOUT "$s\n";
1226 sub cmd_create_ignore {
1227 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1228 $gs ||= Git::SVN->new;
1229 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1230 $gs->prop_walk($gs->{path}, $r, sub {
1231 my ($gs, $path, $props) = @_;
1232 # $path is of the form /path/to/dir/
1233 $path = '.' . $path;
1234 # SVN can have attributes on empty directories,
1235 # which git won't track
1236 mkpath([$path]) unless -d $path;
1237 my $ignore = $path . '.gitignore';
1238 my $s = $props->{'svn:ignore'} or return;
1239 open(GITIGNORE, '>', $ignore)
1240 or fatal("Failed to open `$ignore' for writing: $!");
1241 $s =~ s/[\r\n]+/\n/g;
1242 $s =~ s/^\n+//;
1243 chomp $s;
1244 # Prefix all patterns so that the ignore doesn't apply
1245 # to sub-directories.
1246 $s =~ s#^#/#gm;
1247 print GITIGNORE "$s\n";
1248 close(GITIGNORE)
1249 or fatal("Failed to close `$ignore': $!");
1250 command_noisy('add', '-f', $ignore);
1254 sub cmd_mkdirs {
1255 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1256 $gs ||= Git::SVN->new;
1257 $gs->mkemptydirs($_revision);
1260 sub canonicalize_path {
1261 my ($path) = @_;
1262 my $dot_slash_added = 0;
1263 if (substr($path, 0, 1) ne "/") {
1264 $path = "./" . $path;
1265 $dot_slash_added = 1;
1267 # File::Spec->canonpath doesn't collapse x/../y into y (for a
1268 # good reason), so let's do this manually.
1269 $path =~ s#/+#/#g;
1270 $path =~ s#/\.(?:/|$)#/#g;
1271 $path =~ s#/[^/]+/\.\.##g;
1272 $path =~ s#/$##g;
1273 $path =~ s#^\./## if $dot_slash_added;
1274 $path =~ s#^/##;
1275 $path =~ s#^\.$##;
1276 return $path;
1279 sub canonicalize_url {
1280 my ($url) = @_;
1281 $url =~ s#^([^:]+://[^/]*/)(.*)$#$1 . canonicalize_path($2)#e;
1282 return $url;
1285 # get_svnprops(PATH)
1286 # ------------------
1287 # Helper for cmd_propget and cmd_proplist below.
1288 sub get_svnprops {
1289 my $path = shift;
1290 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1291 $gs ||= Git::SVN->new;
1293 # prefix THE PATH by the sub-directory from which the user
1294 # invoked us.
1295 $path = $cmd_dir_prefix . $path;
1296 fatal("No such file or directory: $path") unless -e $path;
1297 my $is_dir = -d $path ? 1 : 0;
1298 $path = $gs->{path} . '/' . $path;
1300 # canonicalize the path (otherwise libsvn will abort or fail to
1301 # find the file)
1302 $path = canonicalize_path($path);
1304 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1305 my $props;
1306 if ($is_dir) {
1307 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
1309 else {
1310 (undef, $props) = $gs->ra->get_file($path, $r, undef);
1312 return $props;
1315 # cmd_propget (PROP, PATH)
1316 # ------------------------
1317 # Print the SVN property PROP for PATH.
1318 sub cmd_propget {
1319 my ($prop, $path) = @_;
1320 $path = '.' if not defined $path;
1321 usage(1) if not defined $prop;
1322 my $props = get_svnprops($path);
1323 if (not defined $props->{$prop}) {
1324 fatal("`$path' does not have a `$prop' SVN property.");
1326 print $props->{$prop} . "\n";
1329 # cmd_proplist (PATH)
1330 # -------------------
1331 # Print the list of SVN properties for PATH.
1332 sub cmd_proplist {
1333 my $path = shift;
1334 $path = '.' if not defined $path;
1335 my $props = get_svnprops($path);
1336 print "Properties on '$path':\n";
1337 foreach (sort keys %{$props}) {
1338 print " $_\n";
1342 sub cmd_multi_init {
1343 my $url = shift;
1344 unless (defined $_trunk || @_branches || @_tags) {
1345 usage(1);
1348 $_prefix = '' unless defined $_prefix;
1349 if (defined $url) {
1350 $url = canonicalize_url($url);
1351 init_subdir(@_);
1353 do_git_init_db();
1354 if (defined $_trunk) {
1355 $_trunk =~ s#^/+##;
1356 my $trunk_ref = 'refs/remotes/' . $_prefix . 'trunk';
1357 # try both old-style and new-style lookups:
1358 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
1359 unless ($gs_trunk) {
1360 my ($trunk_url, $trunk_path) =
1361 complete_svn_url($url, $_trunk);
1362 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
1363 undef, $trunk_ref);
1366 return unless @_branches || @_tags;
1367 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
1368 foreach my $path (@_branches) {
1369 complete_url_ls_init($ra, $path, '--branches/-b', $_prefix);
1371 foreach my $path (@_tags) {
1372 complete_url_ls_init($ra, $path, '--tags/-t', $_prefix.'tags/');
1376 sub cmd_multi_fetch {
1377 $Git::SVN::no_reuse_existing = undef;
1378 my $remotes = Git::SVN::read_all_remotes();
1379 foreach my $repo_id (sort keys %$remotes) {
1380 if ($remotes->{$repo_id}->{url}) {
1381 Git::SVN::fetch_all($repo_id, $remotes);
1386 # this command is special because it requires no metadata
1387 sub cmd_commit_diff {
1388 my ($ta, $tb, $url) = @_;
1389 my $usage = "Usage: $0 commit-diff -r<revision> ".
1390 "<tree-ish> <tree-ish> [<URL>]";
1391 fatal($usage) if (!defined $ta || !defined $tb);
1392 my $svn_path = '';
1393 if (!defined $url) {
1394 my $gs = eval { Git::SVN->new };
1395 if (!$gs) {
1396 fatal("Needed URL or usable git-svn --id in ",
1397 "the command-line\n", $usage);
1399 $url = $gs->{url};
1400 $svn_path = $gs->{path};
1402 unless (defined $_revision) {
1403 fatal("-r|--revision is a required argument\n", $usage);
1405 if (defined $_message && defined $_file) {
1406 fatal("Both --message/-m and --file/-F specified ",
1407 "for the commit message.\n",
1408 "I have no idea what you mean");
1410 if (defined $_file) {
1411 $_message = file_to_s($_file);
1412 } else {
1413 $_message ||= get_commit_entry($tb)->{log};
1415 my $ra ||= Git::SVN::Ra->new($url);
1416 my $r = $_revision;
1417 if ($r eq 'HEAD') {
1418 $r = $ra->get_latest_revnum;
1419 } elsif ($r !~ /^\d+$/) {
1420 die "revision argument: $r not understood by git-svn\n";
1422 my %ed_opts = ( r => $r,
1423 log => $_message,
1424 ra => $ra,
1425 tree_a => $ta,
1426 tree_b => $tb,
1427 editor_cb => sub { print "Committed r$_[0]\n" },
1428 svn_path => $svn_path );
1429 if (!Git::SVN::Editor->new(\%ed_opts)->apply_diff) {
1430 print "No changes\n$ta == $tb\n";
1434 sub escape_uri_only {
1435 my ($uri) = @_;
1436 my @tmp;
1437 foreach (split m{/}, $uri) {
1438 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
1439 push @tmp, $_;
1441 join('/', @tmp);
1444 sub escape_url {
1445 my ($url) = @_;
1446 if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
1447 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
1448 $url = "$scheme://$domain$uri";
1450 $url;
1453 sub cmd_info {
1454 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
1455 my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
1456 if (exists $_[1]) {
1457 die "Too many arguments specified\n";
1460 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
1462 if (!$file_type && !$diff_status) {
1463 print STDERR "svn: '$path' is not under version control\n";
1464 exit 1;
1467 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1468 unless ($gs) {
1469 die "Unable to determine upstream SVN information from ",
1470 "working tree history\n";
1473 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
1474 $path = "." if $path eq "";
1476 my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
1478 if ($_url) {
1479 print escape_url($full_url), "\n";
1480 return;
1483 my $result = "Path: $path\n";
1484 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
1485 $result .= "URL: " . escape_url($full_url) . "\n";
1487 eval {
1488 my $repos_root = $gs->repos_root;
1489 Git::SVN::remove_username($repos_root);
1490 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
1492 if ($@) {
1493 $result .= "Repository Root: (offline)\n";
1495 ::_req_svn();
1496 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
1497 (::compare_svn_version('1.5.4') <= 0 || $file_type ne "dir");
1498 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
1500 $result .= "Node Kind: " .
1501 ($file_type eq "dir" ? "directory" : "file") . "\n";
1503 my $schedule = $diff_status eq "A"
1504 ? "add"
1505 : ($diff_status eq "D" ? "delete" : "normal");
1506 $result .= "Schedule: $schedule\n";
1508 if ($diff_status eq "A") {
1509 print $result, "\n";
1510 return;
1513 my ($lc_author, $lc_rev, $lc_date_utc);
1514 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
1515 my $log = command_output_pipe(@args);
1516 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
1517 while (<$log>) {
1518 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
1519 $lc_author = $1;
1520 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
1521 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
1522 (undef, $lc_rev, undef) = ::extract_metadata($1);
1525 close $log;
1527 Git::SVN::Log::set_local_timezone();
1529 $result .= "Last Changed Author: $lc_author\n";
1530 $result .= "Last Changed Rev: $lc_rev\n";
1531 $result .= "Last Changed Date: " .
1532 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
1534 if ($file_type ne "dir") {
1535 my $text_last_updated_date =
1536 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
1537 $result .=
1538 "Text Last Updated: " .
1539 Git::SVN::Log::format_svn_date($text_last_updated_date) .
1540 "\n";
1541 my $checksum;
1542 if ($diff_status eq "D") {
1543 my ($fh, $ctx) =
1544 command_output_pipe(qw(cat-file blob), "HEAD:$path");
1545 if ($file_type eq "link") {
1546 my $file_name = <$fh>;
1547 $checksum = md5sum("link $file_name");
1548 } else {
1549 $checksum = md5sum($fh);
1551 command_close_pipe($fh, $ctx);
1552 } elsif ($file_type eq "link") {
1553 my $file_name =
1554 command(qw(cat-file blob), "HEAD:$path");
1555 $checksum =
1556 md5sum("link " . $file_name);
1557 } else {
1558 open FILE, "<", $path or die $!;
1559 $checksum = md5sum(\*FILE);
1560 close FILE or die $!;
1562 $result .= "Checksum: " . $checksum . "\n";
1565 print $result, "\n";
1568 sub cmd_reset {
1569 my $target = shift || $_revision or die "SVN revision required\n";
1570 $target = $1 if $target =~ /^r(\d+)$/;
1571 $target =~ /^\d+$/ or die "Numeric SVN revision expected\n";
1572 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1573 unless ($gs) {
1574 die "Unable to determine upstream SVN information from ".
1575 "history\n";
1577 my ($r, $c) = $gs->find_rev_before($target, not $_fetch_parent);
1578 die "Cannot find SVN revision $target\n" unless defined($c);
1579 $gs->rev_map_set($r, $c, 'reset', $uuid);
1580 print "r$r = $c ($gs->{ref_id})\n";
1583 sub cmd_gc {
1584 if (!can_compress()) {
1585 warn "Compress::Zlib could not be found; unhandled.log " .
1586 "files will not be compressed.\n";
1588 find({ wanted => \&gc_directory, no_chdir => 1}, "$ENV{GIT_DIR}/svn");
1591 ########################### utility functions #########################
1593 sub rebase_cmd {
1594 my @cmd = qw/rebase/;
1595 push @cmd, '-v' if $_verbose;
1596 push @cmd, qw/--merge/ if $_merge;
1597 push @cmd, "--strategy=$_strategy" if $_strategy;
1598 push @cmd, "--preserve-merges" if $_preserve_merges;
1599 @cmd;
1602 sub post_fetch_checkout {
1603 return if $_no_checkout;
1604 return if verify_ref('HEAD^0');
1605 my $gs = $Git::SVN::_head or return;
1607 # look for "trunk" ref if it exists
1608 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
1609 my $fetch = $remote->{fetch};
1610 if ($fetch) {
1611 foreach my $p (keys %$fetch) {
1612 basename($fetch->{$p}) eq 'trunk' or next;
1613 $gs = Git::SVN->new($fetch->{$p}, $gs->{repo_id}, $p);
1614 last;
1618 command_noisy(qw(update-ref HEAD), $gs->refname);
1619 return unless verify_ref('HEAD^0');
1621 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1622 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1623 return if -f $index;
1625 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1626 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1627 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1628 print STDERR "Checked out HEAD:\n ",
1629 $gs->full_url, " r", $gs->last_rev, "\n";
1630 if (auto_create_empty_directories($gs)) {
1631 $gs->mkemptydirs($gs->last_rev);
1635 sub complete_svn_url {
1636 my ($url, $path) = @_;
1637 $path =~ s#/+$##;
1638 if ($path !~ m#^[a-z\+]+://#) {
1639 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1640 fatal("E: '$path' is not a complete URL ",
1641 "and a separate URL is not specified");
1643 return ($url, $path);
1645 return ($path, '');
1648 sub complete_url_ls_init {
1649 my ($ra, $repo_path, $switch, $pfx) = @_;
1650 unless ($repo_path) {
1651 print STDERR "W: $switch not specified\n";
1652 return;
1654 $repo_path =~ s#/+$##;
1655 if ($repo_path =~ m#^[a-z\+]+://#) {
1656 $ra = Git::SVN::Ra->new($repo_path);
1657 $repo_path = '';
1658 } else {
1659 $repo_path =~ s#^/+##;
1660 unless ($ra) {
1661 fatal("E: '$repo_path' is not a complete URL ",
1662 "and a separate URL is not specified");
1665 my $url = $ra->{url};
1666 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1667 my $k = "svn-remote.$gs->{repo_id}.url";
1668 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1669 if ($orig_url && ($orig_url ne $gs->{url})) {
1670 die "$k already set: $orig_url\n",
1671 "wanted to set to: $gs->{url}\n";
1673 command_oneline('config', $k, $gs->{url}) unless $orig_url;
1674 my $remote_path = "$gs->{path}/$repo_path";
1675 $remote_path =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
1676 $remote_path =~ s#/+#/#g;
1677 $remote_path =~ s#^/##g;
1678 $remote_path .= "/*" if $remote_path !~ /\*/;
1679 my ($n) = ($switch =~ /^--(\w+)/);
1680 if (length $pfx && $pfx !~ m#/$#) {
1681 die "--prefix='$pfx' must have a trailing slash '/'\n";
1683 command_noisy('config',
1684 '--add',
1685 "svn-remote.$gs->{repo_id}.$n",
1686 "$remote_path:refs/remotes/$pfx*" .
1687 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1690 sub verify_ref {
1691 my ($ref) = @_;
1692 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1693 { STDERR => 0 }); };
1696 sub get_tree_from_treeish {
1697 my ($treeish) = @_;
1698 # $treeish can be a symbolic ref, too:
1699 my $type = command_oneline(qw/cat-file -t/, $treeish);
1700 my $expected;
1701 while ($type eq 'tag') {
1702 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1704 if ($type eq 'commit') {
1705 $expected = (grep /^tree /, command(qw/cat-file commit/,
1706 $treeish))[0];
1707 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1708 die "Unable to get tree from $treeish\n" unless $expected;
1709 } elsif ($type eq 'tree') {
1710 $expected = $treeish;
1711 } else {
1712 die "$treeish is a $type, expected tree, tag or commit\n";
1714 return $expected;
1717 sub get_commit_entry {
1718 my ($treeish) = shift;
1719 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1720 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1721 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1722 open my $log_fh, '>', $commit_editmsg or croak $!;
1724 my $type = command_oneline(qw/cat-file -t/, $treeish);
1725 if ($type eq 'commit' || $type eq 'tag') {
1726 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1727 $type, $treeish);
1728 my $in_msg = 0;
1729 my $author;
1730 my $saw_from = 0;
1731 my $msgbuf = "";
1732 while (<$msg_fh>) {
1733 if (!$in_msg) {
1734 $in_msg = 1 if (/^\s*$/);
1735 $author = $1 if (/^author (.*>)/);
1736 } elsif (/^git-svn-id: /) {
1737 # skip this for now, we regenerate the
1738 # correct one on re-fetch anyways
1739 # TODO: set *:merge properties or like...
1740 } else {
1741 if (/^From:/ || /^Signed-off-by:/) {
1742 $saw_from = 1;
1744 $msgbuf .= $_;
1747 $msgbuf =~ s/\s+$//s;
1748 if ($Git::SVN::_add_author_from && defined($author)
1749 && !$saw_from) {
1750 $msgbuf .= "\n\nFrom: $author";
1752 print $log_fh $msgbuf or croak $!;
1753 command_close_pipe($msg_fh, $ctx);
1755 close $log_fh or croak $!;
1757 if ($_edit || ($type eq 'tree')) {
1758 chomp(my $editor = command_oneline(qw(var GIT_EDITOR)));
1759 system('sh', '-c', $editor.' "$@"', $editor, $commit_editmsg);
1761 rename $commit_editmsg, $commit_msg or croak $!;
1763 require Encode;
1764 # SVN requires messages to be UTF-8 when entering the repo
1765 local $/;
1766 open $log_fh, '<', $commit_msg or croak $!;
1767 binmode $log_fh;
1768 chomp($log_entry{log} = <$log_fh>);
1770 my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
1771 my $msg = $log_entry{log};
1773 eval { $msg = Encode::decode($enc, $msg, 1) };
1774 if ($@) {
1775 die "Could not decode as $enc:\n", $msg,
1776 "\nPerhaps you need to set i18n.commitencoding\n";
1779 eval { $msg = Encode::encode('UTF-8', $msg, 1) };
1780 die "Could not encode as UTF-8:\n$msg\n" if $@;
1782 $log_entry{log} = $msg;
1784 close $log_fh or croak $!;
1786 unlink $commit_msg;
1787 \%log_entry;
1790 sub s_to_file {
1791 my ($str, $file, $mode) = @_;
1792 open my $fd,'>',$file or croak $!;
1793 print $fd $str,"\n" or croak $!;
1794 close $fd or croak $!;
1795 chmod ($mode &~ umask, $file) if (defined $mode);
1798 sub file_to_s {
1799 my $file = shift;
1800 open my $fd,'<',$file or croak "$!: file: $file\n";
1801 local $/;
1802 my $ret = <$fd>;
1803 close $fd or croak $!;
1804 $ret =~ s/\s*$//s;
1805 return $ret;
1808 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1809 sub load_authors {
1810 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1811 my $log = $cmd eq 'log';
1812 while (<$authors>) {
1813 chomp;
1814 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1815 my ($user, $name, $email) = ($1, $2, $3);
1816 if ($log) {
1817 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1818 } else {
1819 $users{$user} = [$name, $email];
1822 close $authors or croak $!;
1825 # convert GetOpt::Long specs for use by git-config
1826 sub read_git_config {
1827 my $opts = shift;
1828 my @config_only;
1829 foreach my $o (keys %$opts) {
1830 # if we have mixedCase and a long option-only, then
1831 # it's a config-only variable that we don't need for
1832 # the command-line.
1833 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1834 my $v = $opts->{$o};
1835 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1836 $key =~ s/-//g;
1837 my $arg = 'git config';
1838 $arg .= ' --int' if ($o =~ /[:=]i$/);
1839 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1840 if (ref $v eq 'ARRAY') {
1841 chomp(my @tmp = `$arg --get-all svn.$key`);
1842 @$v = @tmp if @tmp;
1843 } else {
1844 chomp(my $tmp = `$arg --get svn.$key`);
1845 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1846 $$v = $tmp;
1850 delete @$opts{@config_only} if @config_only;
1853 sub extract_metadata {
1854 my $id = shift or return (undef, undef, undef);
1855 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1856 \s([a-f\d\-]+)$/ix);
1857 if (!defined $rev || !$uuid || !$url) {
1858 # some of the original repositories I made had
1859 # identifiers like this:
1860 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/i);
1862 return ($url, $rev, $uuid);
1865 sub cmt_metadata {
1866 return extract_metadata((grep(/^git-svn-id: /,
1867 command(qw/cat-file commit/, shift)))[-1]);
1870 sub cmt_sha2rev_batch {
1871 my %s2r;
1872 my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1873 my $list = shift;
1875 foreach my $sha (@{$list}) {
1876 my $first = 1;
1877 my $size = 0;
1878 print $out $sha, "\n";
1880 while (my $line = <$in>) {
1881 if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1882 last;
1883 } elsif ($first &&
1884 $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1885 $first = 0;
1886 $size = $1;
1887 next;
1888 } elsif ($line =~ /^(git-svn-id: )/) {
1889 my (undef, $rev, undef) =
1890 extract_metadata($line);
1891 $s2r{$sha} = $rev;
1894 $size -= length($line);
1895 last if ($size == 0);
1899 command_close_bidi_pipe($pid, $in, $out, $ctx);
1901 return \%s2r;
1904 sub working_head_info {
1905 my ($head, $refs) = @_;
1906 my @args = qw/rev-list --first-parent --pretty=medium/;
1907 my ($fh, $ctx) = command_output_pipe(@args, $head);
1908 my $hash;
1909 my %max;
1910 while (<$fh>) {
1911 if ( m{^commit ($::sha1)$} ) {
1912 unshift @$refs, $hash if $hash and $refs;
1913 $hash = $1;
1914 next;
1916 next unless s{^\s*(git-svn-id:)}{$1};
1917 my ($url, $rev, $uuid) = extract_metadata($_);
1918 if (defined $url && defined $rev) {
1919 next if $max{$url} and $max{$url} < $rev;
1920 if (my $gs = Git::SVN->find_by_url($url)) {
1921 my $c = $gs->rev_map_get($rev, $uuid);
1922 if ($c && $c eq $hash) {
1923 close $fh; # break the pipe
1924 return ($url, $rev, $uuid, $gs);
1925 } else {
1926 $max{$url} ||= $gs->rev_map_max;
1931 command_close_pipe($fh, $ctx);
1932 (undef, undef, undef, undef);
1935 sub read_commit_parents {
1936 my ($parents, $c) = @_;
1937 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1938 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1939 @{$parents->{$c}} = split(/ /, $p);
1942 sub linearize_history {
1943 my ($gs, $refs) = @_;
1944 my %parents;
1945 foreach my $c (@$refs) {
1946 read_commit_parents(\%parents, $c);
1949 my @linear_refs;
1950 my %skip = ();
1951 my $last_svn_commit = $gs->last_commit;
1952 foreach my $c (reverse @$refs) {
1953 next if $c eq $last_svn_commit;
1954 last if $skip{$c};
1956 unshift @linear_refs, $c;
1957 $skip{$c} = 1;
1959 # we only want the first parent to diff against for linear
1960 # history, we save the rest to inject when we finalize the
1961 # svn commit
1962 my $fp_a = verify_ref("$c~1");
1963 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1964 if (!$fp_a || !$fp_b) {
1965 die "Commit $c\n",
1966 "has no parent commit, and therefore ",
1967 "nothing to diff against.\n",
1968 "You should be working from a repository ",
1969 "originally created by git-svn\n";
1971 if ($fp_a ne $fp_b) {
1972 die "$c~1 = $fp_a, however parsing commit $c ",
1973 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1976 foreach my $p (@{$parents{$c}}) {
1977 $skip{$p} = 1;
1980 (\@linear_refs, \%parents);
1983 sub find_file_type_and_diff_status {
1984 my ($path) = @_;
1985 return ('dir', '') if $path eq '';
1987 my $diff_output =
1988 command_oneline(qw(diff --cached --name-status --), $path) || "";
1989 my $diff_status = (split(' ', $diff_output))[0] || "";
1991 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1993 return (undef, undef) if !$diff_status && !$ls_tree;
1995 if ($diff_status eq "A") {
1996 return ("link", $diff_status) if -l $path;
1997 return ("dir", $diff_status) if -d $path;
1998 return ("file", $diff_status);
2001 my $mode = (split(' ', $ls_tree))[0] || "";
2003 return ("link", $diff_status) if $mode eq "120000";
2004 return ("dir", $diff_status) if $mode eq "040000";
2005 return ("file", $diff_status);
2008 sub md5sum {
2009 my $arg = shift;
2010 my $ref = ref $arg;
2011 my $md5 = Digest::MD5->new();
2012 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
2013 $md5->addfile($arg) or croak $!;
2014 } elsif ($ref eq 'SCALAR') {
2015 $md5->add($$arg) or croak $!;
2016 } elsif (!$ref) {
2017 $md5->add($arg) or croak $!;
2018 } else {
2019 fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
2021 return $md5->hexdigest();
2024 sub gc_directory {
2025 if (can_compress() && -f $_ && basename($_) eq "unhandled.log") {
2026 my $out_filename = $_ . ".gz";
2027 open my $in_fh, "<", $_ or die "Unable to open $_: $!\n";
2028 binmode $in_fh;
2029 my $gz = Compress::Zlib::gzopen($out_filename, "ab") or
2030 die "Unable to open $out_filename: $!\n";
2032 my $res;
2033 while ($res = sysread($in_fh, my $str, 1024)) {
2034 $gz->gzwrite($str) or
2035 die "Unable to write: ".$gz->gzerror()."!\n";
2037 unlink $_ or die "unlink $File::Find::name: $!\n";
2038 } elsif (-f $_ && basename($_) eq "index") {
2039 unlink $_ or die "unlink $_: $!\n";
2044 package Git::SVN::Migration;
2045 # these version numbers do NOT correspond to actual version numbers
2046 # of git nor git-svn. They are just relative.
2048 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
2050 # v1 layout: .git/$id/info/url, refs/remotes/$id
2052 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
2054 # v3 layout: .git/svn/$id, refs/remotes/$id
2055 # - info/url may remain for backwards compatibility
2056 # - this is what we migrate up to this layout automatically,
2057 # - this will be used by git svn init on single branches
2058 # v3.1 layout (auto migrated):
2059 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
2060 # for backwards compatibility
2062 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
2063 # - this is only created for newly multi-init-ed
2064 # repositories. Similar in spirit to the
2065 # --use-separate-remotes option in git-clone (now default)
2066 # - we do not automatically migrate to this (following
2067 # the example set by core git)
2069 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
2070 # - newer, more-efficient format that uses 24-bytes per record
2071 # with no filler space.
2072 # - use xxd -c24 < .rev_map.$UUID to view and debug
2073 # - This is a one-way migration, repositories updated to the
2074 # new format will not be able to use old git-svn without
2075 # rebuilding the .rev_db. Rebuilding the rev_db is not
2076 # possible if noMetadata or useSvmProps are set; but should
2077 # be no problem for users that use the (sensible) defaults.
2078 use strict;
2079 use warnings;
2080 use Carp qw/croak/;
2081 use File::Path qw/mkpath/;
2082 use File::Basename qw/dirname basename/;
2084 our $_minimize;
2085 use Git qw(
2086 command
2087 command_noisy
2088 command_output_pipe
2089 command_close_pipe
2092 sub migrate_from_v0 {
2093 my $git_dir = $ENV{GIT_DIR};
2094 return undef unless -d $git_dir;
2095 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
2096 my $migrated = 0;
2097 while (<$fh>) {
2098 chomp;
2099 my ($id, $orig_ref) = ($_, $_);
2100 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
2101 next unless -f "$git_dir/$id/info/url";
2102 my $new_ref = "refs/remotes/$id";
2103 if (::verify_ref("$new_ref^0")) {
2104 print STDERR "W: $orig_ref is probably an old ",
2105 "branch used by an ancient version of ",
2106 "git-svn.\n",
2107 "However, $new_ref also exists.\n",
2108 "We will not be able ",
2109 "to use this branch until this ",
2110 "ambiguity is resolved.\n";
2111 next;
2113 print STDERR "Migrating from v0 layout...\n" if !$migrated;
2114 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
2115 command_noisy('update-ref', $new_ref, $orig_ref);
2116 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
2117 $migrated++;
2119 command_close_pipe($fh, $ctx);
2120 print STDERR "Done migrating from v0 layout...\n" if $migrated;
2121 $migrated;
2124 sub migrate_from_v1 {
2125 my $git_dir = $ENV{GIT_DIR};
2126 my $migrated = 0;
2127 return $migrated unless -d $git_dir;
2128 my $svn_dir = "$git_dir/svn";
2130 # just in case somebody used 'svn' as their $id at some point...
2131 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
2133 print STDERR "Migrating from a git-svn v1 layout...\n";
2134 mkpath([$svn_dir]);
2135 print STDERR "Data from a previous version of git-svn exists, but\n\t",
2136 "$svn_dir\n\t(required for this version ",
2137 "($::VERSION) of git-svn) does not exist.\n";
2138 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
2139 while (<$fh>) {
2140 my $x = $_;
2141 next unless $x =~ s#^refs/remotes/##;
2142 chomp $x;
2143 next unless -f "$git_dir/$x/info/url";
2144 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
2145 next unless $u;
2146 my $dn = dirname("$git_dir/svn/$x");
2147 mkpath([$dn]) unless -d $dn;
2148 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
2149 mkpath(["$git_dir/svn/svn"]);
2150 print STDERR " - $git_dir/$x/info => ",
2151 "$git_dir/svn/$x/info\n";
2152 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
2153 croak "$!: $x";
2154 # don't worry too much about these, they probably
2155 # don't exist with repos this old (save for index,
2156 # and we can easily regenerate that)
2157 foreach my $f (qw/unhandled.log index .rev_db/) {
2158 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
2160 } else {
2161 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
2162 rename "$git_dir/$x", "$git_dir/svn/$x" or
2163 croak "$!: $x";
2165 $migrated++;
2167 command_close_pipe($fh, $ctx);
2168 print STDERR "Done migrating from a git-svn v1 layout\n";
2169 $migrated;
2172 sub read_old_urls {
2173 my ($l_map, $pfx, $path) = @_;
2174 my @dir;
2175 foreach (<$path/*>) {
2176 if (-r "$_/info/url") {
2177 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
2178 my $ref_id = $pfx . basename $_;
2179 my $url = ::file_to_s("$_/info/url");
2180 $l_map->{$ref_id} = $url;
2181 } elsif (-d $_) {
2182 push @dir, $_;
2185 foreach (@dir) {
2186 my $x = $_;
2187 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
2188 read_old_urls($l_map, $x, $_);
2192 sub migrate_from_v2 {
2193 my @cfg = command(qw/config -l/);
2194 return if grep /^svn-remote\..+\.url=/, @cfg;
2195 my %l_map;
2196 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
2197 my $migrated = 0;
2199 require Git::SVN;
2200 foreach my $ref_id (sort keys %l_map) {
2201 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
2202 if ($@) {
2203 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
2205 $migrated++;
2207 $migrated;
2210 sub minimize_connections {
2211 require Git::SVN;
2212 require Git::SVN::Ra;
2214 my $r = Git::SVN::read_all_remotes();
2215 my $new_urls = {};
2216 my $root_repos = {};
2217 foreach my $repo_id (keys %$r) {
2218 my $url = $r->{$repo_id}->{url} or next;
2219 my $fetch = $r->{$repo_id}->{fetch} or next;
2220 my $ra = Git::SVN::Ra->new($url);
2222 # skip existing cases where we already connect to the root
2223 if (($ra->{url} eq $ra->{repos_root}) ||
2224 ($ra->{repos_root} eq $repo_id)) {
2225 $root_repos->{$ra->{url}} = $repo_id;
2226 next;
2229 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
2230 my $root_path = $ra->{url};
2231 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
2232 foreach my $path (keys %$fetch) {
2233 my $ref_id = $fetch->{$path};
2234 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
2236 # make sure we can read when connecting to
2237 # a higher level of a repository
2238 my ($last_rev, undef) = $gs->last_rev_commit;
2239 if (!defined $last_rev) {
2240 $last_rev = eval {
2241 $root_ra->get_latest_revnum;
2243 next if $@;
2245 my $new = $root_path;
2246 $new .= length $path ? "/$path" : '';
2247 eval {
2248 $root_ra->get_log([$new], $last_rev, $last_rev,
2249 0, 0, 1, sub { });
2251 next if $@;
2252 $new_urls->{$ra->{repos_root}}->{$new} =
2253 { ref_id => $ref_id,
2254 old_repo_id => $repo_id,
2255 old_path => $path };
2259 my @emptied;
2260 foreach my $url (keys %$new_urls) {
2261 # see if we can re-use an existing [svn-remote "repo_id"]
2262 # instead of creating a(n ugly) new section:
2263 my $repo_id = $root_repos->{$url} || $url;
2265 my $fetch = $new_urls->{$url};
2266 foreach my $path (keys %$fetch) {
2267 my $x = $fetch->{$path};
2268 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
2269 my $pfx = "svn-remote.$x->{old_repo_id}";
2271 my $old_fetch = quotemeta("$x->{old_path}:".
2272 "$x->{ref_id}");
2273 command_noisy(qw/config --unset/,
2274 "$pfx.fetch", '^'. $old_fetch . '$');
2275 delete $r->{$x->{old_repo_id}}->
2276 {fetch}->{$x->{old_path}};
2277 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
2278 command_noisy(qw/config --unset/,
2279 "$pfx.url");
2280 push @emptied, $x->{old_repo_id}
2284 if (@emptied) {
2285 my $file = $ENV{GIT_CONFIG} || "$ENV{GIT_DIR}/config";
2286 print STDERR <<EOF;
2287 The following [svn-remote] sections in your config file ($file) are empty
2288 and can be safely removed:
2290 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
2294 sub migration_check {
2295 migrate_from_v0();
2296 migrate_from_v1();
2297 migrate_from_v2();
2298 minimize_connections() if $_minimize;
2301 package Git::IndexInfo;
2302 use strict;
2303 use warnings;
2304 use Git qw/command_input_pipe command_close_pipe/;
2306 sub new {
2307 my ($class) = @_;
2308 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
2309 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
2312 sub remove {
2313 my ($self, $path) = @_;
2314 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
2315 return ++$self->{nr};
2317 undef;
2320 sub update {
2321 my ($self, $mode, $hash, $path) = @_;
2322 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
2323 return ++$self->{nr};
2325 undef;
2328 sub DESTROY {
2329 my ($self) = @_;
2330 command_close_pipe($self->{gui}, $self->{ctx});
2333 package Git::SVN::GlobSpec;
2334 use strict;
2335 use warnings;
2337 sub new {
2338 my ($class, $glob, $pattern_ok) = @_;
2339 my $re = $glob;
2340 $re =~ s!/+$!!g; # no need for trailing slashes
2341 my (@left, @right, @patterns);
2342 my $state = "left";
2343 my $die_msg = "Only one set of wildcard directories " .
2344 "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
2345 for my $part (split(m|/|, $glob)) {
2346 if ($part =~ /\*/ && $part ne "*") {
2347 die "Invalid pattern in '$glob': $part\n";
2348 } elsif ($pattern_ok && $part =~ /[{}]/ &&
2349 $part !~ /^\{[^{}]+\}/) {
2350 die "Invalid pattern in '$glob': $part\n";
2352 if ($part eq "*") {
2353 die $die_msg if $state eq "right";
2354 $state = "pattern";
2355 push(@patterns, "[^/]*");
2356 } elsif ($pattern_ok && $part =~ /^\{(.*)\}$/) {
2357 die $die_msg if $state eq "right";
2358 $state = "pattern";
2359 my $p = quotemeta($1);
2360 $p =~ s/\\,/|/g;
2361 push(@patterns, "(?:$p)");
2362 } else {
2363 if ($state eq "left") {
2364 push(@left, $part);
2365 } else {
2366 push(@right, $part);
2367 $state = "right";
2371 my $depth = @patterns;
2372 if ($depth == 0) {
2373 die "One '*' is needed in glob: '$glob'\n";
2375 my $left = join('/', @left);
2376 my $right = join('/', @right);
2377 $re = join('/', @patterns);
2378 $re = join('\/',
2379 grep(length, quotemeta($left), "($re)", quotemeta($right)));
2380 my $left_re = qr/^\/\Q$left\E(\/|$)/;
2381 bless { left => $left, right => $right, left_regex => $left_re,
2382 regex => qr/$re/, glob => $glob, depth => $depth }, $class;
2385 sub full_path {
2386 my ($self, $path) = @_;
2387 return (length $self->{left} ? "$self->{left}/" : '') .
2388 $path . (length $self->{right} ? "/$self->{right}" : '');
2391 __END__
2393 Data structures:
2396 $remotes = { # returned by read_all_remotes()
2397 'svn' => {
2398 # svn-remote.svn.url=https://svn.musicpd.org
2399 url => 'https://svn.musicpd.org',
2400 # svn-remote.svn.fetch=mpd/trunk:trunk
2401 fetch => {
2402 'mpd/trunk' => 'trunk',
2404 # svn-remote.svn.tags=mpd/tags/*:tags/*
2405 tags => {
2406 path => {
2407 left => 'mpd/tags',
2408 right => '',
2409 regex => qr!mpd/tags/([^/]+)$!,
2410 glob => 'tags/*',
2412 ref => {
2413 left => 'tags',
2414 right => '',
2415 regex => qr!tags/([^/]+)$!,
2416 glob => 'tags/*',
2422 $log_entry hashref as returned by libsvn_log_entry()
2424 log => 'whitespace-formatted log entry
2425 ', # trailing newline is preserved
2426 revision => '8', # integer
2427 date => '2004-02-24T17:01:44.108345Z', # commit date
2428 author => 'committer name'
2432 # this is generated by generate_diff();
2433 @mods = array of diff-index line hashes, each element represents one line
2434 of diff-index output
2436 diff-index line ($m hash)
2438 mode_a => first column of diff-index output, no leading ':',
2439 mode_b => second column of diff-index output,
2440 sha1_b => sha1sum of the final blob,
2441 chg => change type [MCRADT],
2442 file_a => original file name of a file (iff chg is 'C' or 'R')
2443 file_b => new/current file name of a file (any chg)
2447 # retval of read_url_paths{,_all}();
2448 $l_map = {
2449 # repository root url
2450 'https://svn.musicpd.org' => {
2451 # repository path # GIT_SVN_ID
2452 'mpd/trunk' => 'trunk',
2453 'mpd/tags/0.11.5' => 'tags/0.11.5',
2457 Notes:
2458 I don't trust the each() function on unless I created %hash myself
2459 because the internal iterator may not have started at base.