1#!/usr/bin/perl
2# Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3# License: GPL v2 or later
4use 5.008;
5use warnings;
6use strict;
7use 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@@';
12
13use Carp qw/croak/;
14use Digest::MD5;
15use IO::File qw//;
16use File::Basename qw/dirname basename/;
17use File::Path qw/mkpath/;
18use File::Spec;
19use File::Find;
20use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
21use IPC::Open3;
22use Memoize;
23
24use Git::SVN;
25use Git::SVN::Editor;
26use Git::SVN::Fetcher;
27use Git::SVN::Ra;
28use Git::SVN::Prompt;
29use Git::SVN::Log;
30use Git::SVN::Migration;
31
32use Git::SVN::Utils qw(
33 fatal
34 can_compress
35 canonicalize_path
36 canonicalize_url
37 join_paths
38);
39
40use Git qw(
41 git_cmd_try
42 command
43 command_oneline
44 command_noisy
45 command_output_pipe
46 command_close_pipe
47 command_bidi_pipe
48 command_close_bidi_pipe
49);
50
51BEGIN {
52 Memoize::memoize 'Git::config';
53 Memoize::memoize 'Git::config_bool';
54}
55
56
57# From which subdir have we been invoked?
58my $cmd_dir_prefix = eval {
59 command_oneline([qw/rev-parse --show-prefix/], STDERR => 0)
60} || '';
61
62my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
63$ENV{GIT_DIR} ||= '.git';
64$Git::SVN::Ra::_log_window_size = 100;
65
66if (! exists $ENV{SVN_SSH} && exists $ENV{GIT_SSH}) {
67 $ENV{SVN_SSH} = $ENV{GIT_SSH};
68}
69
70if (exists $ENV{SVN_SSH} && $^O eq 'msys') {
71 $ENV{SVN_SSH} =~ s/\\/\\\\/g;
72 $ENV{SVN_SSH} =~ s/(.*)/"$1"/;
73}
74
75$Git::SVN::Log::TZ = $ENV{TZ};
76$ENV{TZ} = 'UTC';
77$| = 1; # unbuffer STDOUT
78
79# All SVN commands do it. Otherwise we may die on SIGPIPE when the remote
80# repository decides to close the connection which we expect to be kept alive.
81$SIG{PIPE} = 'IGNORE';
82
83# Given a dot separated version number, "subtract" it from
84# the SVN::Core::VERSION; non-negaitive return means the SVN::Core
85# is at least at the version the caller asked for.
86sub compare_svn_version {
87 my (@ours) = split(/\./, $SVN::Core::VERSION);
88 my (@theirs) = split(/\./, $_[0]);
89 my ($i, $diff);
90
91 for ($i = 0; $i < @ours && $i < @theirs; $i++) {
92 $diff = $ours[$i] - $theirs[$i];
93 return $diff if ($diff);
94 }
95 return 1 if ($i < @ours);
96 return -1 if ($i < @theirs);
97 return 0;
98}
99
100sub _req_svn {
101 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
102 require SVN::Ra;
103 require SVN::Delta;
104 if (::compare_svn_version('1.1.0') < 0) {
105 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
106 }
107}
108
109$sha1 = qr/[a-f\d]{40}/;
110$sha1_short = qr/[a-f\d]{4,40}/;
111my ($_stdin, $_help, $_edit,
112 $_message, $_file, $_branch_dest,
113 $_template, $_shared,
114 $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
115 $_merge, $_strategy, $_preserve_merges, $_dry_run, $_local,
116 $_prefix, $_no_checkout, $_url, $_verbose,
117 $_commit_url, $_tag, $_merge_info, $_interactive);
118
119# This is a refactoring artifact so Git::SVN can get at this git-svn switch.
120sub opt_prefix { return $_prefix || '' }
121
122$Git::SVN::Fetcher::_placeholder_filename = ".gitignore";
123$_q ||= 0;
124my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
125 'config-dir=s' => \$Git::SVN::Ra::config_dir,
126 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
127 'ignore-paths=s' => \$Git::SVN::Fetcher::_ignore_regex,
128 'ignore-refs=s' => \$Git::SVN::Ra::_ignore_refs_regex );
129my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
130 'authors-file|A=s' => \$_authors,
131 'authors-prog=s' => \$_authors_prog,
132 'repack:i' => \$Git::SVN::_repack,
133 'noMetadata' => \$Git::SVN::_no_metadata,
134 'useSvmProps' => \$Git::SVN::_use_svm_props,
135 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
136 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
137 'no-checkout' => \$_no_checkout,
138 'quiet|q+' => \$_q,
139 'repack-flags|repack-args|repack-opts=s' =>
140 \$Git::SVN::_repack_flags,
141 'use-log-author' => \$Git::SVN::_use_log_author,
142 'add-author-from' => \$Git::SVN::_add_author_from,
143 'localtime' => \$Git::SVN::_localtime,
144 %remote_opts );
145
146my ($_trunk, @_tags, @_branches, $_stdlayout);
147my %icv;
148my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
149 'trunk|T=s' => \$_trunk, 'tags|t=s@' => \@_tags,
150 'branches|b=s@' => \@_branches, 'prefix=s' => \$_prefix,
151 'stdlayout|s' => \$_stdlayout,
152 'minimize-url|m!' => \$Git::SVN::_minimize_url,
153 'no-metadata' => sub { $icv{noMetadata} = 1 },
154 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
155 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
156 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
157 'rewrite-uuid=s' => sub { $icv{rewriteUUID} = $_[1] },
158 %remote_opts );
159my %cmt_opts = ( 'edit|e' => \$_edit,
160 'rmdir' => \$Git::SVN::Editor::_rmdir,
161 'find-copies-harder' => \$Git::SVN::Editor::_find_copies_harder,
162 'l=i' => \$Git::SVN::Editor::_rename_limit,
163 'copy-similarity|C=i'=> \$Git::SVN::Editor::_cp_similarity
164);
165
166my %cmd = (
167 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
168 { 'revision|r=s' => \$_revision,
169 'fetch-all|all' => \$_fetch_all,
170 'parent|p' => \$_fetch_parent,
171 %fc_opts } ],
172 clone => [ \&cmd_clone, "Initialize and fetch revisions",
173 { 'revision|r=s' => \$_revision,
174 'preserve-empty-dirs' =>
175 \$Git::SVN::Fetcher::_preserve_empty_dirs,
176 'placeholder-filename=s' =>
177 \$Git::SVN::Fetcher::_placeholder_filename,
178 %fc_opts, %init_opts } ],
179 init => [ \&cmd_init, "Initialize a repo for tracking" .
180 " (requires URL argument)",
181 \%init_opts ],
182 'multi-init' => [ \&cmd_multi_init,
183 "Deprecated alias for ".
184 "'$0 init -T<trunk> -b<branches> -t<tags>'",
185 \%init_opts ],
186 dcommit => [ \&cmd_dcommit,
187 'Commit several diffs to merge with upstream',
188 { 'merge|m|M' => \$_merge,
189 'strategy|s=s' => \$_strategy,
190 'verbose|v' => \$_verbose,
191 'dry-run|n' => \$_dry_run,
192 'fetch-all|all' => \$_fetch_all,
193 'commit-url=s' => \$_commit_url,
194 'revision|r=i' => \$_revision,
195 'no-rebase' => \$_no_rebase,
196 'mergeinfo=s' => \$_merge_info,
197 'interactive|i' => \$_interactive,
198 %cmt_opts, %fc_opts } ],
199 branch => [ \&cmd_branch,
200 'Create a branch in the SVN repository',
201 { 'message|m=s' => \$_message,
202 'destination|d=s' => \$_branch_dest,
203 'dry-run|n' => \$_dry_run,
204 'tag|t' => \$_tag,
205 'username=s' => \$Git::SVN::Prompt::_username,
206 'commit-url=s' => \$_commit_url } ],
207 tag => [ sub { $_tag = 1; cmd_branch(@_) },
208 'Create a tag in the SVN repository',
209 { 'message|m=s' => \$_message,
210 'destination|d=s' => \$_branch_dest,
211 'dry-run|n' => \$_dry_run,
212 'username=s' => \$Git::SVN::Prompt::_username,
213 'commit-url=s' => \$_commit_url } ],
214 'set-tree' => [ \&cmd_set_tree,
215 "Set an SVN repository to a git tree-ish",
216 { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
217 'create-ignore' => [ \&cmd_create_ignore,
218 'Create a .gitignore per svn:ignore',
219 { 'revision|r=i' => \$_revision
220 } ],
221 'mkdirs' => [ \&cmd_mkdirs ,
222 "recreate empty directories after a checkout",
223 { 'revision|r=i' => \$_revision } ],
224 'propget' => [ \&cmd_propget,
225 'Print the value of a property on a file or directory',
226 { 'revision|r=i' => \$_revision } ],
227 'proplist' => [ \&cmd_proplist,
228 'List all properties of a file or directory',
229 { 'revision|r=i' => \$_revision } ],
230 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
231 { 'revision|r=i' => \$_revision
232 } ],
233 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
234 { 'revision|r=i' => \$_revision
235 } ],
236 'multi-fetch' => [ \&cmd_multi_fetch,
237 "Deprecated alias for $0 fetch --all",
238 { 'revision|r=s' => \$_revision, %fc_opts } ],
239 'migrate' => [ sub { },
240 # no-op, we automatically run this anyways,
241 'Migrate configuration/metadata/layout from
242 previous versions of git-svn',
243 { 'minimize' => \$Git::SVN::Migration::_minimize,
244 %remote_opts } ],
245 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
246 { 'limit=i' => \$Git::SVN::Log::limit,
247 'revision|r=s' => \$_revision,
248 'verbose|v' => \$Git::SVN::Log::verbose,
249 'incremental' => \$Git::SVN::Log::incremental,
250 'oneline' => \$Git::SVN::Log::oneline,
251 'show-commit' => \$Git::SVN::Log::show_commit,
252 'non-recursive' => \$Git::SVN::Log::non_recursive,
253 'authors-file|A=s' => \$_authors,
254 'color' => \$Git::SVN::Log::color,
255 'pager=s' => \$Git::SVN::Log::pager
256 } ],
257 'find-rev' => [ \&cmd_find_rev,
258 "Translate between SVN revision numbers and tree-ish",
259 {} ],
260 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
261 { 'merge|m|M' => \$_merge,
262 'verbose|v' => \$_verbose,
263 'strategy|s=s' => \$_strategy,
264 'local|l' => \$_local,
265 'fetch-all|all' => \$_fetch_all,
266 'dry-run|n' => \$_dry_run,
267 'preserve-merges|p' => \$_preserve_merges,
268 %fc_opts } ],
269 'commit-diff' => [ \&cmd_commit_diff,
270 'Commit a diff between two trees',
271 { 'message|m=s' => \$_message,
272 'file|F=s' => \$_file,
273 'revision|r=s' => \$_revision,
274 %cmt_opts } ],
275 'info' => [ \&cmd_info,
276 "Show info about the latest SVN revision
277 on the current branch",
278 { 'url' => \$_url, } ],
279 'blame' => [ \&Git::SVN::Log::cmd_blame,
280 "Show what revision and author last modified each line of a file",
281 { 'git-format' => \$Git::SVN::Log::_git_format } ],
282 'reset' => [ \&cmd_reset,
283 "Undo fetches back to the specified SVN revision",
284 { 'revision|r=s' => \$_revision,
285 'parent|p' => \$_fetch_parent } ],
286 'gc' => [ \&cmd_gc,
287 "Compress unhandled.log files in .git/svn and remove " .
288 "index files in .git/svn",
289 {} ],
290);
291
292use Term::ReadLine;
293package FakeTerm;
294sub new {
295 my ($class, $reason) = @_;
296 return bless \$reason, shift;
297}
298sub readline {
299 my $self = shift;
300 die "Cannot use readline on FakeTerm: $$self";
301}
302package main;
303
304my $term = eval {
305 $ENV{"GIT_SVN_NOTTY"}
306 ? new Term::ReadLine 'git-svn', \*STDIN, \*STDOUT
307 : new Term::ReadLine 'git-svn';
308};
309if ($@) {
310 $term = new FakeTerm "$@: going non-interactive";
311}
312
313my $cmd;
314for (my $i = 0; $i < @ARGV; $i++) {
315 if (defined $cmd{$ARGV[$i]}) {
316 $cmd = $ARGV[$i];
317 splice @ARGV, $i, 1;
318 last;
319 } elsif ($ARGV[$i] eq 'help') {
320 $cmd = $ARGV[$i+1];
321 usage(0);
322 }
323};
324
325# make sure we're always running at the top-level working directory
326unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
327 unless (-d $ENV{GIT_DIR}) {
328 if ($git_dir_user_set) {
329 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
330 "but it is not a directory\n";
331 }
332 my $git_dir = delete $ENV{GIT_DIR};
333 my $cdup = undef;
334 git_cmd_try {
335 $cdup = command_oneline(qw/rev-parse --show-cdup/);
336 $git_dir = '.' unless ($cdup);
337 chomp $cdup if ($cdup);
338 $cdup = "." unless ($cdup && length $cdup);
339 } "Already at toplevel, but $git_dir not found\n";
340 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
341 unless (-d $git_dir) {
342 die "$git_dir still not found after going to ",
343 "'$cdup'\n";
344 }
345 $ENV{GIT_DIR} = $git_dir;
346 }
347 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
348}
349
350my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
351
352read_git_config(\%opts);
353if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
354 Getopt::Long::Configure('pass_through');
355}
356my $rv = GetOptions(%opts, 'h|H' => \$_help, 'version|V' => \$_version,
357 'minimize-connections' => \$Git::SVN::Migration::_minimize,
358 'id|i=s' => \$Git::SVN::default_ref_id,
359 'svn-remote|remote|R=s' => sub {
360 $Git::SVN::no_reuse_existing = 1;
361 $Git::SVN::default_repo_id = $_[1] });
362exit 1 if (!$rv && $cmd && $cmd ne 'log');
363
364usage(0) if $_help;
365version() if $_version;
366usage(1) unless defined $cmd;
367load_authors() if $_authors;
368if (defined $_authors_prog) {
369 $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
370}
371
372unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
373 Git::SVN::Migration::migration_check();
374}
375Git::SVN::init_vars();
376eval {
377 Git::SVN::verify_remotes_sanity();
378 $cmd{$cmd}->[0]->(@ARGV);
379 post_fetch_checkout();
380};
381fatal $@ if $@;
382exit 0;
383
384####################### primary functions ######################
385sub usage {
386 my $exit = shift || 0;
387 my $fd = $exit ? \*STDERR : \*STDOUT;
388 print $fd <<"";
389git-svn - bidirectional operations between a single Subversion tree and git
390Usage: git svn <command> [options] [arguments]\n
391
392 print $fd "Available commands:\n" unless $cmd;
393
394 foreach (sort keys %cmd) {
395 next if $cmd && $cmd ne $_;
396 next if /^multi-/; # don't show deprecated commands
397 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
398 foreach (sort keys %{$cmd{$_}->[2]}) {
399 # mixed-case options are for .git/config only
400 next if /[A-Z]/ && /^[a-z]+$/i;
401 # prints out arguments as they should be passed:
402 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
403 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
404 "--$_" : "-$_" }
405 split /\|/,$_)," $x\n";
406 }
407 }
408 print $fd <<"";
409\nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
410arbitrary identifier if you're tracking multiple SVN branches/repositories in
411one git repository and want to keep them separate. See git-svn(1) for more
412information.
413
414 exit $exit;
415}
416
417sub version {
418 ::_req_svn();
419 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
420 exit 0;
421}
422
423sub ask {
424 my ($prompt, %arg) = @_;
425 my $valid_re = $arg{valid_re};
426 my $default = $arg{default};
427 my $resp;
428 my $i = 0;
429
430 if ( !( defined($term->IN)
431 && defined( fileno($term->IN) )
432 && defined( $term->OUT )
433 && defined( fileno($term->OUT) ) ) ){
434 return defined($default) ? $default : undef;
435 }
436
437 while ($i++ < 10) {
438 $resp = $term->readline($prompt);
439 if (!defined $resp) { # EOF
440 print "\n";
441 return defined $default ? $default : undef;
442 }
443 if ($resp eq '' and defined $default) {
444 return $default;
445 }
446 if (!defined $valid_re or $resp =~ /$valid_re/) {
447 return $resp;
448 }
449 }
450 return undef;
451}
452
453sub do_git_init_db {
454 unless (-d $ENV{GIT_DIR}) {
455 my @init_db = ('init');
456 push @init_db, "--template=$_template" if defined $_template;
457 if (defined $_shared) {
458 if ($_shared =~ /[a-z]/) {
459 push @init_db, "--shared=$_shared";
460 } else {
461 push @init_db, "--shared";
462 }
463 }
464 command_noisy(@init_db);
465 $_repository = Git->repository(Repository => ".git");
466 }
467 my $set;
468 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
469 foreach my $i (keys %icv) {
470 die "'$set' and '$i' cannot both be set\n" if $set;
471 next unless defined $icv{$i};
472 command_noisy('config', "$pfx.$i", $icv{$i});
473 $set = $i;
474 }
475 my $ignore_paths_regex = \$Git::SVN::Fetcher::_ignore_regex;
476 command_noisy('config', "$pfx.ignore-paths", $$ignore_paths_regex)
477 if defined $$ignore_paths_regex;
478 my $ignore_refs_regex = \$Git::SVN::Ra::_ignore_refs_regex;
479 command_noisy('config', "$pfx.ignore-refs", $$ignore_refs_regex)
480 if defined $$ignore_refs_regex;
481
482 if (defined $Git::SVN::Fetcher::_preserve_empty_dirs) {
483 my $fname = \$Git::SVN::Fetcher::_placeholder_filename;
484 command_noisy('config', "$pfx.preserve-empty-dirs", 'true');
485 command_noisy('config', "$pfx.placeholder-filename", $$fname);
486 }
487}
488
489sub init_subdir {
490 my $repo_path = shift or return;
491 mkpath([$repo_path]) unless -d $repo_path;
492 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
493 $ENV{GIT_DIR} = '.git';
494 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
495}
496
497sub cmd_clone {
498 my ($url, $path) = @_;
499 if (!defined $path &&
500 (defined $_trunk || @_branches || @_tags ||
501 defined $_stdlayout) &&
502 $url !~ m#^[a-z\+]+://#) {
503 $path = $url;
504 }
505 $path = basename($url) if !defined $path || !length $path;
506 my $authors_absolute = $_authors ? File::Spec->rel2abs($_authors) : "";
507 cmd_init($url, $path);
508 command_oneline('config', 'svn.authorsfile', $authors_absolute)
509 if $_authors;
510 Git::SVN::fetch_all($Git::SVN::default_repo_id);
511}
512
513sub cmd_init {
514 if (defined $_stdlayout) {
515 $_trunk = 'trunk' if (!defined $_trunk);
516 @_tags = 'tags' if (! @_tags);
517 @_branches = 'branches' if (! @_branches);
518 }
519 if (defined $_trunk || @_branches || @_tags) {
520 return cmd_multi_init(@_);
521 }
522 my $url = shift or die "SVN repository location required ",
523 "as a command-line argument\n";
524 $url = canonicalize_url($url);
525 init_subdir(@_);
526 do_git_init_db();
527
528 if ($Git::SVN::_minimize_url eq 'unset') {
529 $Git::SVN::_minimize_url = 0;
530 }
531
532 Git::SVN->init($url);
533}
534
535sub cmd_fetch {
536 if (grep /^\d+=./, @_) {
537 die "'<rev>=<commit>' fetch arguments are ",
538 "no longer supported.\n";
539 }
540 my ($remote) = @_;
541 if (@_ > 1) {
542 die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
543 }
544 $Git::SVN::no_reuse_existing = undef;
545 if ($_fetch_parent) {
546 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
547 unless ($gs) {
548 die "Unable to determine upstream SVN information from ",
549 "working tree history\n";
550 }
551 # just fetch, don't checkout.
552 $_no_checkout = 'true';
553 $_fetch_all ? $gs->fetch_all : $gs->fetch;
554 } elsif ($_fetch_all) {
555 cmd_multi_fetch();
556 } else {
557 $remote ||= $Git::SVN::default_repo_id;
558 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
559 }
560}
561
562sub cmd_set_tree {
563 my (@commits) = @_;
564 if ($_stdin || !@commits) {
565 print "Reading from stdin...\n";
566 @commits = ();
567 while (<STDIN>) {
568 if (/\b($sha1_short)\b/o) {
569 unshift @commits, $1;
570 }
571 }
572 }
573 my @revs;
574 foreach my $c (@commits) {
575 my @tmp = command('rev-parse',$c);
576 if (scalar @tmp == 1) {
577 push @revs, $tmp[0];
578 } elsif (scalar @tmp > 1) {
579 push @revs, reverse(command('rev-list',@tmp));
580 } else {
581 fatal "Failed to rev-parse $c";
582 }
583 }
584 my $gs = Git::SVN->new;
585 my ($r_last, $cmt_last) = $gs->last_rev_commit;
586 $gs->fetch;
587 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
588 fatal "There are new revisions that were fetched ",
589 "and need to be merged (or acknowledged) ",
590 "before committing.\nlast rev: $r_last\n",
591 " current: $gs->{last_rev}";
592 }
593 $gs->set_tree($_) foreach @revs;
594 print "Done committing ",scalar @revs," revisions to SVN\n";
595 unlink $gs->{index};
596}
597
598sub split_merge_info_range {
599 my ($range) = @_;
600 if ($range =~ /(\d+)-(\d+)/) {
601 return (int($1), int($2));
602 } else {
603 return (int($range), int($range));
604 }
605}
606
607sub combine_ranges {
608 my ($in) = @_;
609
610 my @fnums = ();
611 my @arr = split(/,/, $in);
612 for my $element (@arr) {
613 my ($start, $end) = split_merge_info_range($element);
614 push @fnums, $start;
615 }
616
617 my @sorted = @arr [ sort {
618 $fnums[$a] <=> $fnums[$b]
619 } 0..$#arr ];
620
621 my @return = ();
622 my $last = -1;
623 my $first = -1;
624 for my $element (@sorted) {
625 my ($start, $end) = split_merge_info_range($element);
626
627 if ($last == -1) {
628 $first = $start;
629 $last = $end;
630 next;
631 }
632 if ($start <= $last+1) {
633 if ($end > $last) {
634 $last = $end;
635 }
636 next;
637 }
638 if ($first == $last) {
639 push @return, "$first";
640 } else {
641 push @return, "$first-$last";
642 }
643 $first = $start;
644 $last = $end;
645 }
646
647 if ($first != -1) {
648 if ($first == $last) {
649 push @return, "$first";
650 } else {
651 push @return, "$first-$last";
652 }
653 }
654
655 return join(',', @return);
656}
657
658sub merge_revs_into_hash {
659 my ($hash, $minfo) = @_;
660 my @lines = split(' ', $minfo);
661
662 for my $line (@lines) {
663 my ($branchpath, $revs) = split(/:/, $line);
664
665 if (exists($hash->{$branchpath})) {
666 # Merge the two revision sets
667 my $combined = "$hash->{$branchpath},$revs";
668 $hash->{$branchpath} = combine_ranges($combined);
669 } else {
670 # Just do range combining for consolidation
671 $hash->{$branchpath} = combine_ranges($revs);
672 }
673 }
674}
675
676sub merge_merge_info {
677 my ($mergeinfo_one, $mergeinfo_two) = @_;
678 my %result_hash = ();
679
680 merge_revs_into_hash(\%result_hash, $mergeinfo_one);
681 merge_revs_into_hash(\%result_hash, $mergeinfo_two);
682
683 my $result = '';
684 # Sort below is for consistency's sake
685 for my $branchname (sort keys(%result_hash)) {
686 my $revlist = $result_hash{$branchname};
687 $result .= "$branchname:$revlist\n"
688 }
689 return $result;
690}
691
692sub populate_merge_info {
693 my ($d, $gs, $uuid, $linear_refs, $rewritten_parent) = @_;
694
695 my %parentshash;
696 read_commit_parents(\%parentshash, $d);
697 my @parents = @{$parentshash{$d}};
698 if ($#parents > 0) {
699 # Merge commit
700 my $all_parents_ok = 1;
701 my $aggregate_mergeinfo = '';
702 my $rooturl = $gs->repos_root;
703
704 if (defined($rewritten_parent)) {
705 # Replace first parent with newly-rewritten version
706 shift @parents;
707 unshift @parents, $rewritten_parent;
708 }
709
710 foreach my $parent (@parents) {
711 my ($branchurl, $svnrev, $paruuid) =
712 cmt_metadata($parent);
713
714 unless (defined($svnrev)) {
715 # Should have been caught be preflight check
716 fatal "merge commit $d has ancestor $parent, but that change "
717 ."does not have git-svn metadata!";
718 }
719 unless ($branchurl =~ /^\Q$rooturl\E(.*)/) {
720 fatal "commit $parent git-svn metadata changed mid-run!";
721 }
722 my $branchpath = $1;
723
724 my $ra = Git::SVN::Ra->new($branchurl);
725 my (undef, undef, $props) =
726 $ra->get_dir(canonicalize_path("."), $svnrev);
727 my $par_mergeinfo = $props->{'svn:mergeinfo'};
728 unless (defined $par_mergeinfo) {
729 $par_mergeinfo = '';
730 }
731 # Merge previous mergeinfo values
732 $aggregate_mergeinfo =
733 merge_merge_info($aggregate_mergeinfo,
734 $par_mergeinfo, 0);
735
736 next if $parent eq $parents[0]; # Skip first parent
737 # Add new changes being placed in tree by merge
738 my @cmd = (qw/rev-list --reverse/,
739 $parent, qw/--not/);
740 foreach my $par (@parents) {
741 unless ($par eq $parent) {
742 push @cmd, $par;
743 }
744 }
745 my @revsin = ();
746 my ($revlist, $ctx) = command_output_pipe(@cmd);
747 while (<$revlist>) {
748 my $irev = $_;
749 chomp $irev;
750 my (undef, $csvnrev, undef) =
751 cmt_metadata($irev);
752 unless (defined $csvnrev) {
753 # A child is missing SVN annotations...
754 # this might be OK, or might not be.
755 warn "W:child $irev is merged into revision "
756 ."$d but does not have git-svn metadata. "
757 ."This means git-svn cannot determine the "
758 ."svn revision numbers to place into the "
759 ."svn:mergeinfo property. You must ensure "
760 ."a branch is entirely committed to "
761 ."SVN before merging it in order for "
762 ."svn:mergeinfo population to function "
763 ."properly";
764 }
765 push @revsin, $csvnrev;
766 }
767 command_close_pipe($revlist, $ctx);
768
769 last unless $all_parents_ok;
770
771 # We now have a list of all SVN revnos which are
772 # merged by this particular parent. Integrate them.
773 next if $#revsin == -1;
774 my $newmergeinfo = "$branchpath:" . join(',', @revsin);
775 $aggregate_mergeinfo =
776 merge_merge_info($aggregate_mergeinfo,
777 $newmergeinfo, 1);
778 }
779 if ($all_parents_ok and $aggregate_mergeinfo) {
780 return $aggregate_mergeinfo;
781 }
782 }
783
784 return undef;
785}
786
787sub cmd_dcommit {
788 my $head = shift;
789 command_noisy(qw/update-index --refresh/);
790 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
791 'Cannot dcommit with a dirty index. Commit your changes first, '
792 . "or stash them with `git stash'.\n";
793 $head ||= 'HEAD';
794
795 my $old_head;
796 if ($head ne 'HEAD') {
797 $old_head = eval {
798 command_oneline([qw/symbolic-ref -q HEAD/])
799 };
800 if ($old_head) {
801 $old_head =~ s{^refs/heads/}{};
802 } else {
803 $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
804 }
805 command(['checkout', $head], STDERR => 0);
806 }
807
808 my @refs;
809 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
810 unless ($gs) {
811 die "Unable to determine upstream SVN information from ",
812 "$head history.\nPerhaps the repository is empty.";
813 }
814
815 if (defined $_commit_url) {
816 $url = $_commit_url;
817 } else {
818 $url = eval { command_oneline('config', '--get',
819 "svn-remote.$gs->{repo_id}.commiturl") };
820 if (!$url) {
821 $url = $gs->full_pushurl
822 }
823 }
824
825 my $last_rev = $_revision if defined $_revision;
826 if ($url) {
827 print "Committing to $url ...\n";
828 }
829 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
830 if ($_no_rebase && scalar(@$linear_refs) > 1) {
831 warn "Attempting to commit more than one change while ",
832 "--no-rebase is enabled.\n",
833 "If these changes depend on each other, re-running ",
834 "without --no-rebase may be required."
835 }
836
837 if (defined $_interactive){
838 my $ask_default = "y";
839 foreach my $d (@$linear_refs){
840 my ($fh, $ctx) = command_output_pipe(qw(show --summary), "$d");
841 while (<$fh>){
842 print $_;
843 }
844 command_close_pipe($fh, $ctx);
845 $_ = ask("Commit this patch to SVN? ([y]es (default)|[n]o|[q]uit|[a]ll): ",
846 valid_re => qr/^(?:yes|y|no|n|quit|q|all|a)/i,
847 default => $ask_default);
848 die "Commit this patch reply required" unless defined $_;
849 if (/^[nq]/i) {
850 exit(0);
851 } elsif (/^a/i) {
852 last;
853 }
854 }
855 }
856
857 my $expect_url = $url;
858
859 my $push_merge_info = eval {
860 command_oneline(qw/config --get svn.pushmergeinfo/)
861 };
862 if (not defined($push_merge_info)
863 or $push_merge_info eq "false"
864 or $push_merge_info eq "no"
865 or $push_merge_info eq "never") {
866 $push_merge_info = 0;
867 }
868
869 unless (defined($_merge_info) || ! $push_merge_info) {
870 # Preflight check of changes to ensure no issues with mergeinfo
871 # This includes check for uncommitted-to-SVN parents
872 # (other than the first parent, which we will handle),
873 # information from different SVN repos, and paths
874 # which are not underneath this repository root.
875 my $rooturl = $gs->repos_root;
876 foreach my $d (@$linear_refs) {
877 my %parentshash;
878 read_commit_parents(\%parentshash, $d);
879 my @realparents = @{$parentshash{$d}};
880 if ($#realparents > 0) {
881 # Merge commit
882 shift @realparents; # Remove/ignore first parent
883 foreach my $parent (@realparents) {
884 my ($branchurl, $svnrev, $paruuid) = cmt_metadata($parent);
885 unless (defined $paruuid) {
886 # A parent is missing SVN annotations...
887 # abort the whole operation.
888 fatal "$parent is merged into revision $d, "
889 ."but does not have git-svn metadata. "
890 ."Either dcommit the branch or use a "
891 ."local cherry-pick, FF merge, or rebase "
892 ."instead of an explicit merge commit.";
893 }
894
895 unless ($paruuid eq $uuid) {
896 # Parent has SVN metadata from different repository
897 fatal "merge parent $parent for change $d has "
898 ."git-svn uuid $paruuid, while current change "
899 ."has uuid $uuid!";
900 }
901
902 unless ($branchurl =~ /^\Q$rooturl\E(.*)/) {
903 # This branch is very strange indeed.
904 fatal "merge parent $parent for $d is on branch "
905 ."$branchurl, which is not under the "
906 ."git-svn root $rooturl!";
907 }
908 }
909 }
910 }
911 }
912
913 my $rewritten_parent;
914 Git::SVN::remove_username($expect_url);
915 if (defined($_merge_info)) {
916 $_merge_info =~ tr{ }{\n};
917 }
918 while (1) {
919 my $d = shift @$linear_refs or last;
920 unless (defined $last_rev) {
921 (undef, $last_rev, undef) = cmt_metadata("$d~1");
922 unless (defined $last_rev) {
923 fatal "Unable to extract revision information ",
924 "from commit $d~1";
925 }
926 }
927 if ($_dry_run) {
928 print "diff-tree $d~1 $d\n";
929 } else {
930 my $cmt_rev;
931
932 unless (defined($_merge_info) || ! $push_merge_info) {
933 $_merge_info = populate_merge_info($d, $gs,
934 $uuid,
935 $linear_refs,
936 $rewritten_parent);
937 }
938
939 my %ed_opts = ( r => $last_rev,
940 log => get_commit_entry($d)->{log},
941 ra => Git::SVN::Ra->new($url),
942 config => SVN::Core::config_get_config(
943 $Git::SVN::Ra::config_dir
944 ),
945 tree_a => "$d~1",
946 tree_b => $d,
947 editor_cb => sub {
948 print "Committed r$_[0]\n";
949 $cmt_rev = $_[0];
950 },
951 mergeinfo => $_merge_info,
952 svn_path => '');
953 if (!Git::SVN::Editor->new(\%ed_opts)->apply_diff) {
954 print "No changes\n$d~1 == $d\n";
955 } elsif ($parents->{$d} && @{$parents->{$d}}) {
956 $gs->{inject_parents_dcommit}->{$cmt_rev} =
957 $parents->{$d};
958 }
959 $_fetch_all ? $gs->fetch_all : $gs->fetch;
960 $last_rev = $cmt_rev;
961 next if $_no_rebase;
962
963 # we always want to rebase against the current HEAD,
964 # not any head that was passed to us
965 my @diff = command('diff-tree', $d,
966 $gs->refname, '--');
967 my @finish;
968 if (@diff) {
969 @finish = rebase_cmd();
970 print STDERR "W: $d and ", $gs->refname,
971 " differ, using @finish:\n",
972 join("\n", @diff), "\n";
973 } else {
974 print "No changes between current HEAD and ",
975 $gs->refname,
976 "\nResetting to the latest ",
977 $gs->refname, "\n";
978 @finish = qw/reset --mixed/;
979 }
980 command_noisy(@finish, $gs->refname);
981
982 $rewritten_parent = command_oneline(qw/rev-parse HEAD/);
983
984 if (@diff) {
985 @refs = ();
986 my ($url_, $rev_, $uuid_, $gs_) =
987 working_head_info('HEAD', \@refs);
988 my ($linear_refs_, $parents_) =
989 linearize_history($gs_, \@refs);
990 if (scalar(@$linear_refs) !=
991 scalar(@$linear_refs_)) {
992 fatal "# of revisions changed ",
993 "\nbefore:\n",
994 join("\n", @$linear_refs),
995 "\n\nafter:\n",
996 join("\n", @$linear_refs_), "\n",
997 'If you are attempting to commit ',
998 "merges, try running:\n\t",
999 'git rebase --interactive',
1000 '--preserve-merges ',
1001 $gs->refname,
1002 "\nBefore dcommitting";
1003 }
1004 if ($url_ ne $expect_url) {
1005 if ($url_ eq $gs->metadata_url) {
1006 print
1007 "Accepting rewritten URL:",
1008 " $url_\n";
1009 } else {
1010 fatal
1011 "URL mismatch after rebase:",
1012 " $url_ != $expect_url";
1013 }
1014 }
1015 if ($uuid_ ne $uuid) {
1016 fatal "uuid mismatch after rebase: ",
1017 "$uuid_ != $uuid";
1018 }
1019 # remap parents
1020 my (%p, @l, $i);
1021 for ($i = 0; $i < scalar @$linear_refs; $i++) {
1022 my $new = $linear_refs_->[$i] or next;
1023 $p{$new} =
1024 $parents->{$linear_refs->[$i]};
1025 push @l, $new;
1026 }
1027 $parents = \%p;
1028 $linear_refs = \@l;
1029 }
1030 }
1031 }
1032
1033 if ($old_head) {
1034 my $new_head = command_oneline(qw/rev-parse HEAD/);
1035 my $new_is_symbolic = eval {
1036 command_oneline(qw/symbolic-ref -q HEAD/);
1037 };
1038 if ($new_is_symbolic) {
1039 print "dcommitted the branch ", $head, "\n";
1040 } else {
1041 print "dcommitted on a detached HEAD because you gave ",
1042 "a revision argument.\n",
1043 "The rewritten commit is: ", $new_head, "\n";
1044 }
1045 command(['checkout', $old_head], STDERR => 0);
1046 }
1047
1048 unlink $gs->{index};
1049}
1050
1051sub cmd_branch {
1052 my ($branch_name, $head) = @_;
1053
1054 unless (defined $branch_name && length $branch_name) {
1055 die(($_tag ? "tag" : "branch") . " name required\n");
1056 }
1057 $head ||= 'HEAD';
1058
1059 my (undef, $rev, undef, $gs) = working_head_info($head);
1060 my $src = $gs->full_pushurl;
1061
1062 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
1063 my $allglobs = $remote->{ $_tag ? 'tags' : 'branches' };
1064 my $glob;
1065 if ($#{$allglobs} == 0) {
1066 $glob = $allglobs->[0];
1067 } else {
1068 unless(defined $_branch_dest) {
1069 die "Multiple ",
1070 $_tag ? "tag" : "branch",
1071 " paths defined for Subversion repository.\n",
1072 "You must specify where you want to create the ",
1073 $_tag ? "tag" : "branch",
1074 " with the --destination argument.\n";
1075 }
1076 foreach my $g (@{$allglobs}) {
1077 my $re = Git::SVN::Editor::glob2pat($g->{path}->{left});
1078 if ($_branch_dest =~ /$re/) {
1079 $glob = $g;
1080 last;
1081 }
1082 }
1083 unless (defined $glob) {
1084 my $dest_re = qr/\b\Q$_branch_dest\E\b/;
1085 foreach my $g (@{$allglobs}) {
1086 $g->{path}->{left} =~ /$dest_re/ or next;
1087 if (defined $glob) {
1088 die "Ambiguous destination: ",
1089 $_branch_dest, "\nmatches both '",
1090 $glob->{path}->{left}, "' and '",
1091 $g->{path}->{left}, "'\n";
1092 }
1093 $glob = $g;
1094 }
1095 unless (defined $glob) {
1096 die "Unknown ",
1097 $_tag ? "tag" : "branch",
1098 " destination $_branch_dest\n";
1099 }
1100 }
1101 }
1102 my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
1103 my $url;
1104 if (defined $_commit_url) {
1105 $url = $_commit_url;
1106 } else {
1107 $url = eval { command_oneline('config', '--get',
1108 "svn-remote.$gs->{repo_id}.commiturl") };
1109 if (!$url) {
1110 $url = $remote->{pushurl} || $remote->{url};
1111 }
1112 }
1113 my $dst = join '/', $url, $lft, $branch_name, ($rgt || ());
1114
1115 if ($dst =~ /^https:/ && $src =~ /^http:/) {
1116 $src=~s/^http:/https:/;
1117 }
1118
1119 ::_req_svn();
1120
1121 my $ctx = SVN::Client->new(
1122 auth => Git::SVN::Ra::_auth_providers(),
1123 log_msg => sub {
1124 ${ $_[0] } = defined $_message
1125 ? $_message
1126 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
1127 . $branch_name;
1128 },
1129 );
1130
1131 eval {
1132 $ctx->ls($dst, 'HEAD', 0);
1133 } and die "branch ${branch_name} already exists\n";
1134
1135 print "Copying ${src} at r${rev} to ${dst}...\n";
1136 $ctx->copy($src, $rev, $dst)
1137 unless $_dry_run;
1138
1139 $gs->fetch_all;
1140}
1141
1142sub cmd_find_rev {
1143 my $revision_or_hash = shift or die "SVN or git revision required ",
1144 "as a command-line argument\n";
1145 my $result;
1146 if ($revision_or_hash =~ /^r\d+$/) {
1147 my $head = shift;
1148 $head ||= 'HEAD';
1149 my @refs;
1150 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
1151 unless ($gs) {
1152 die "Unable to determine upstream SVN information from ",
1153 "$head history\n";
1154 }
1155 my $desired_revision = substr($revision_or_hash, 1);
1156 $result = $gs->rev_map_get($desired_revision, $uuid);
1157 } else {
1158 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
1159 $result = $rev;
1160 }
1161 print "$result\n" if $result;
1162}
1163
1164sub auto_create_empty_directories {
1165 my ($gs) = @_;
1166 my $var = eval { command_oneline('config', '--get', '--bool',
1167 "svn-remote.$gs->{repo_id}.automkdirs") };
1168 # By default, create empty directories by consulting the unhandled log,
1169 # but allow setting it to 'false' to skip it.
1170 return !($var && $var eq 'false');
1171}
1172
1173sub cmd_rebase {
1174 command_noisy(qw/update-index --refresh/);
1175 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1176 unless ($gs) {
1177 die "Unable to determine upstream SVN information from ",
1178 "working tree history\n";
1179 }
1180 if ($_dry_run) {
1181 print "Remote Branch: " . $gs->refname . "\n";
1182 print "SVN URL: " . $url . "\n";
1183 return;
1184 }
1185 if (command(qw/diff-index HEAD --/)) {
1186 print STDERR "Cannot rebase with uncommited changes:\n";
1187 command_noisy('status');
1188 exit 1;
1189 }
1190 unless ($_local) {
1191 # rebase will checkout for us, so no need to do it explicitly
1192 $_no_checkout = 'true';
1193 $_fetch_all ? $gs->fetch_all : $gs->fetch;
1194 }
1195 command_noisy(rebase_cmd(), $gs->refname);
1196 if (auto_create_empty_directories($gs)) {
1197 $gs->mkemptydirs;
1198 }
1199}
1200
1201sub cmd_show_ignore {
1202 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1203 $gs ||= Git::SVN->new;
1204 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1205 $gs->prop_walk($gs->path, $r, sub {
1206 my ($gs, $path, $props) = @_;
1207 print STDOUT "\n# $path\n";
1208 my $s = $props->{'svn:ignore'} or return;
1209 $s =~ s/[\r\n]+/\n/g;
1210 $s =~ s/^\n+//;
1211 chomp $s;
1212 $s =~ s#^#$path#gm;
1213 print STDOUT "$s\n";
1214 });
1215}
1216
1217sub cmd_show_externals {
1218 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1219 $gs ||= Git::SVN->new;
1220 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1221 $gs->prop_walk($gs->path, $r, sub {
1222 my ($gs, $path, $props) = @_;
1223 print STDOUT "\n# $path\n";
1224 my $s = $props->{'svn:externals'} or return;
1225 $s =~ s/[\r\n]+/\n/g;
1226 chomp $s;
1227 $s =~ s#^#$path#gm;
1228 print STDOUT "$s\n";
1229 });
1230}
1231
1232sub cmd_create_ignore {
1233 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1234 $gs ||= Git::SVN->new;
1235 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1236 $gs->prop_walk($gs->path, $r, sub {
1237 my ($gs, $path, $props) = @_;
1238 # $path is of the form /path/to/dir/
1239 $path = '.' . $path;
1240 # SVN can have attributes on empty directories,
1241 # which git won't track
1242 mkpath([$path]) unless -d $path;
1243 my $ignore = $path . '.gitignore';
1244 my $s = $props->{'svn:ignore'} or return;
1245 open(GITIGNORE, '>', $ignore)
1246 or fatal("Failed to open `$ignore' for writing: $!");
1247 $s =~ s/[\r\n]+/\n/g;
1248 $s =~ s/^\n+//;
1249 chomp $s;
1250 # Prefix all patterns so that the ignore doesn't apply
1251 # to sub-directories.
1252 $s =~ s#^#/#gm;
1253 print GITIGNORE "$s\n";
1254 close(GITIGNORE)
1255 or fatal("Failed to close `$ignore': $!");
1256 command_noisy('add', '-f', $ignore);
1257 });
1258}
1259
1260sub cmd_mkdirs {
1261 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1262 $gs ||= Git::SVN->new;
1263 $gs->mkemptydirs($_revision);
1264}
1265
1266# get_svnprops(PATH)
1267# ------------------
1268# Helper for cmd_propget and cmd_proplist below.
1269sub get_svnprops {
1270 my $path = shift;
1271 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1272 $gs ||= Git::SVN->new;
1273
1274 # prefix THE PATH by the sub-directory from which the user
1275 # invoked us.
1276 $path = $cmd_dir_prefix . $path;
1277 fatal("No such file or directory: $path") unless -e $path;
1278 my $is_dir = -d $path ? 1 : 0;
1279 $path = join_paths($gs->{path}, $path);
1280
1281 # canonicalize the path (otherwise libsvn will abort or fail to
1282 # find the file)
1283 $path = canonicalize_path($path);
1284
1285 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1286 my $props;
1287 if ($is_dir) {
1288 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
1289 }
1290 else {
1291 (undef, $props) = $gs->ra->get_file($path, $r, undef);
1292 }
1293 return $props;
1294}
1295
1296# cmd_propget (PROP, PATH)
1297# ------------------------
1298# Print the SVN property PROP for PATH.
1299sub cmd_propget {
1300 my ($prop, $path) = @_;
1301 $path = '.' if not defined $path;
1302 usage(1) if not defined $prop;
1303 my $props = get_svnprops($path);
1304 if (not defined $props->{$prop}) {
1305 fatal("`$path' does not have a `$prop' SVN property.");
1306 }
1307 print $props->{$prop} . "\n";
1308}
1309
1310# cmd_proplist (PATH)
1311# -------------------
1312# Print the list of SVN properties for PATH.
1313sub cmd_proplist {
1314 my $path = shift;
1315 $path = '.' if not defined $path;
1316 my $props = get_svnprops($path);
1317 print "Properties on '$path':\n";
1318 foreach (sort keys %{$props}) {
1319 print " $_\n";
1320 }
1321}
1322
1323sub cmd_multi_init {
1324 my $url = shift;
1325 unless (defined $_trunk || @_branches || @_tags) {
1326 usage(1);
1327 }
1328
1329 $_prefix = '' unless defined $_prefix;
1330 if (defined $url) {
1331 $url = canonicalize_url($url);
1332 init_subdir(@_);
1333 }
1334 do_git_init_db();
1335 if (defined $_trunk) {
1336 $_trunk =~ s#^/+##;
1337 my $trunk_ref = 'refs/remotes/' . $_prefix . 'trunk';
1338 # try both old-style and new-style lookups:
1339 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
1340 unless ($gs_trunk) {
1341 my ($trunk_url, $trunk_path) =
1342 complete_svn_url($url, $_trunk);
1343 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
1344 undef, $trunk_ref);
1345 }
1346 }
1347 return unless @_branches || @_tags;
1348 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
1349 foreach my $path (@_branches) {
1350 complete_url_ls_init($ra, $path, '--branches/-b', $_prefix);
1351 }
1352 foreach my $path (@_tags) {
1353 complete_url_ls_init($ra, $path, '--tags/-t', $_prefix.'tags/');
1354 }
1355}
1356
1357sub cmd_multi_fetch {
1358 $Git::SVN::no_reuse_existing = undef;
1359 my $remotes = Git::SVN::read_all_remotes();
1360 foreach my $repo_id (sort keys %$remotes) {
1361 if ($remotes->{$repo_id}->{url}) {
1362 Git::SVN::fetch_all($repo_id, $remotes);
1363 }
1364 }
1365}
1366
1367# this command is special because it requires no metadata
1368sub cmd_commit_diff {
1369 my ($ta, $tb, $url) = @_;
1370 my $usage = "Usage: $0 commit-diff -r<revision> ".
1371 "<tree-ish> <tree-ish> [<URL>]";
1372 fatal($usage) if (!defined $ta || !defined $tb);
1373 my $svn_path = '';
1374 if (!defined $url) {
1375 my $gs = eval { Git::SVN->new };
1376 if (!$gs) {
1377 fatal("Needed URL or usable git-svn --id in ",
1378 "the command-line\n", $usage);
1379 }
1380 $url = $gs->url;
1381 $svn_path = $gs->path;
1382 }
1383 unless (defined $_revision) {
1384 fatal("-r|--revision is a required argument\n", $usage);
1385 }
1386 if (defined $_message && defined $_file) {
1387 fatal("Both --message/-m and --file/-F specified ",
1388 "for the commit message.\n",
1389 "I have no idea what you mean");
1390 }
1391 if (defined $_file) {
1392 $_message = file_to_s($_file);
1393 } else {
1394 $_message ||= get_commit_entry($tb)->{log};
1395 }
1396 my $ra ||= Git::SVN::Ra->new($url);
1397 my $r = $_revision;
1398 if ($r eq 'HEAD') {
1399 $r = $ra->get_latest_revnum;
1400 } elsif ($r !~ /^\d+$/) {
1401 die "revision argument: $r not understood by git-svn\n";
1402 }
1403 my %ed_opts = ( r => $r,
1404 log => $_message,
1405 ra => $ra,
1406 tree_a => $ta,
1407 tree_b => $tb,
1408 editor_cb => sub { print "Committed r$_[0]\n" },
1409 svn_path => $svn_path );
1410 if (!Git::SVN::Editor->new(\%ed_opts)->apply_diff) {
1411 print "No changes\n$ta == $tb\n";
1412 }
1413}
1414
1415sub escape_uri_only {
1416 my ($uri) = @_;
1417 my @tmp;
1418 foreach (split m{/}, $uri) {
1419 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
1420 push @tmp, $_;
1421 }
1422 join('/', @tmp);
1423}
1424
1425sub escape_url {
1426 my ($url) = @_;
1427 if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
1428 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
1429 $url = "$scheme://$domain$uri";
1430 }
1431 $url;
1432}
1433
1434sub cmd_info {
1435 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
1436 my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
1437 if (exists $_[1]) {
1438 die "Too many arguments specified\n";
1439 }
1440
1441 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
1442
1443 if (!$file_type && !$diff_status) {
1444 print STDERR "svn: '$path' is not under version control\n";
1445 exit 1;
1446 }
1447
1448 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1449 unless ($gs) {
1450 die "Unable to determine upstream SVN information from ",
1451 "working tree history\n";
1452 }
1453
1454 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
1455 $path = "." if $path eq "";
1456
1457 my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
1458
1459 if ($_url) {
1460 print escape_url($full_url), "\n";
1461 return;
1462 }
1463
1464 my $result = "Path: $path\n";
1465 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
1466 $result .= "URL: " . escape_url($full_url) . "\n";
1467
1468 eval {
1469 my $repos_root = $gs->repos_root;
1470 Git::SVN::remove_username($repos_root);
1471 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
1472 };
1473 if ($@) {
1474 $result .= "Repository Root: (offline)\n";
1475 }
1476 ::_req_svn();
1477 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
1478 (::compare_svn_version('1.5.4') <= 0 || $file_type ne "dir");
1479 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
1480
1481 $result .= "Node Kind: " .
1482 ($file_type eq "dir" ? "directory" : "file") . "\n";
1483
1484 my $schedule = $diff_status eq "A"
1485 ? "add"
1486 : ($diff_status eq "D" ? "delete" : "normal");
1487 $result .= "Schedule: $schedule\n";
1488
1489 if ($diff_status eq "A") {
1490 print $result, "\n";
1491 return;
1492 }
1493
1494 my ($lc_author, $lc_rev, $lc_date_utc);
1495 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
1496 my $log = command_output_pipe(@args);
1497 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
1498 while (<$log>) {
1499 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
1500 $lc_author = $1;
1501 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
1502 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
1503 (undef, $lc_rev, undef) = ::extract_metadata($1);
1504 }
1505 }
1506 close $log;
1507
1508 Git::SVN::Log::set_local_timezone();
1509
1510 $result .= "Last Changed Author: $lc_author\n";
1511 $result .= "Last Changed Rev: $lc_rev\n";
1512 $result .= "Last Changed Date: " .
1513 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
1514
1515 if ($file_type ne "dir") {
1516 my $text_last_updated_date =
1517 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
1518 $result .=
1519 "Text Last Updated: " .
1520 Git::SVN::Log::format_svn_date($text_last_updated_date) .
1521 "\n";
1522 my $checksum;
1523 if ($diff_status eq "D") {
1524 my ($fh, $ctx) =
1525 command_output_pipe(qw(cat-file blob), "HEAD:$path");
1526 if ($file_type eq "link") {
1527 my $file_name = <$fh>;
1528 $checksum = md5sum("link $file_name");
1529 } else {
1530 $checksum = md5sum($fh);
1531 }
1532 command_close_pipe($fh, $ctx);
1533 } elsif ($file_type eq "link") {
1534 my $file_name =
1535 command(qw(cat-file blob), "HEAD:$path");
1536 $checksum =
1537 md5sum("link " . $file_name);
1538 } else {
1539 open FILE, "<", $path or die $!;
1540 $checksum = md5sum(\*FILE);
1541 close FILE or die $!;
1542 }
1543 $result .= "Checksum: " . $checksum . "\n";
1544 }
1545
1546 print $result, "\n";
1547}
1548
1549sub cmd_reset {
1550 my $target = shift || $_revision or die "SVN revision required\n";
1551 $target = $1 if $target =~ /^r(\d+)$/;
1552 $target =~ /^\d+$/ or die "Numeric SVN revision expected\n";
1553 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1554 unless ($gs) {
1555 die "Unable to determine upstream SVN information from ".
1556 "history\n";
1557 }
1558 my ($r, $c) = $gs->find_rev_before($target, not $_fetch_parent);
1559 die "Cannot find SVN revision $target\n" unless defined($c);
1560 $gs->rev_map_set($r, $c, 'reset', $uuid);
1561 print "r$r = $c ($gs->{ref_id})\n";
1562}
1563
1564sub cmd_gc {
1565 if (!can_compress()) {
1566 warn "Compress::Zlib could not be found; unhandled.log " .
1567 "files will not be compressed.\n";
1568 }
1569 find({ wanted => \&gc_directory, no_chdir => 1}, "$ENV{GIT_DIR}/svn");
1570}
1571
1572########################### utility functions #########################
1573
1574sub rebase_cmd {
1575 my @cmd = qw/rebase/;
1576 push @cmd, '-v' if $_verbose;
1577 push @cmd, qw/--merge/ if $_merge;
1578 push @cmd, "--strategy=$_strategy" if $_strategy;
1579 push @cmd, "--preserve-merges" if $_preserve_merges;
1580 @cmd;
1581}
1582
1583sub post_fetch_checkout {
1584 return if $_no_checkout;
1585 return if verify_ref('HEAD^0');
1586 my $gs = $Git::SVN::_head or return;
1587
1588 # look for "trunk" ref if it exists
1589 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
1590 my $fetch = $remote->{fetch};
1591 if ($fetch) {
1592 foreach my $p (keys %$fetch) {
1593 basename($fetch->{$p}) eq 'trunk' or next;
1594 $gs = Git::SVN->new($fetch->{$p}, $gs->{repo_id}, $p);
1595 last;
1596 }
1597 }
1598
1599 command_noisy(qw(update-ref HEAD), $gs->refname);
1600 return unless verify_ref('HEAD^0');
1601
1602 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1603 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1604 return if -f $index;
1605
1606 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1607 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1608 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1609 print STDERR "Checked out HEAD:\n ",
1610 $gs->full_url, " r", $gs->last_rev, "\n";
1611 if (auto_create_empty_directories($gs)) {
1612 $gs->mkemptydirs($gs->last_rev);
1613 }
1614}
1615
1616sub complete_svn_url {
1617 my ($url, $path) = @_;
1618 $path =~ s#/+$##;
1619
1620 # If the path is not a URL...
1621 if ($path !~ m#^[a-z\+]+://#) {
1622 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1623 fatal("E: '$path' is not a complete URL ",
1624 "and a separate URL is not specified");
1625 }
1626 return ($url, $path);
1627 }
1628 return ($path, '');
1629}
1630
1631sub complete_url_ls_init {
1632 my ($ra, $repo_path, $switch, $pfx) = @_;
1633 unless ($repo_path) {
1634 print STDERR "W: $switch not specified\n";
1635 return;
1636 }
1637 $repo_path =~ s#/+$##;
1638 if ($repo_path =~ m#^[a-z\+]+://#) {
1639 $ra = Git::SVN::Ra->new($repo_path);
1640 $repo_path = '';
1641 } else {
1642 $repo_path =~ s#^/+##;
1643 unless ($ra) {
1644 fatal("E: '$repo_path' is not a complete URL ",
1645 "and a separate URL is not specified");
1646 }
1647 }
1648 my $url = $ra->url;
1649 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1650 my $k = "svn-remote.$gs->{repo_id}.url";
1651 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1652 if ($orig_url && ($orig_url ne $gs->url)) {
1653 die "$k already set: $orig_url\n",
1654 "wanted to set to: $gs->url\n";
1655 }
1656 command_oneline('config', $k, $gs->url) unless $orig_url;
1657
1658 my $remote_path = $gs->path . "/$repo_path";
1659 $remote_path =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
1660 $remote_path =~ s#/+#/#g;
1661 $remote_path =~ s#^/##g;
1662 $remote_path .= "/*" if $remote_path !~ /\*/;
1663 my ($n) = ($switch =~ /^--(\w+)/);
1664 if (length $pfx && $pfx !~ m#/$#) {
1665 die "--prefix='$pfx' must have a trailing slash '/'\n";
1666 }
1667 command_noisy('config',
1668 '--add',
1669 "svn-remote.$gs->{repo_id}.$n",
1670 "$remote_path:refs/remotes/$pfx*" .
1671 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1672}
1673
1674sub verify_ref {
1675 my ($ref) = @_;
1676 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1677 { STDERR => 0 }); };
1678}
1679
1680sub get_tree_from_treeish {
1681 my ($treeish) = @_;
1682 # $treeish can be a symbolic ref, too:
1683 my $type = command_oneline(qw/cat-file -t/, $treeish);
1684 my $expected;
1685 while ($type eq 'tag') {
1686 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1687 }
1688 if ($type eq 'commit') {
1689 $expected = (grep /^tree /, command(qw/cat-file commit/,
1690 $treeish))[0];
1691 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1692 die "Unable to get tree from $treeish\n" unless $expected;
1693 } elsif ($type eq 'tree') {
1694 $expected = $treeish;
1695 } else {
1696 die "$treeish is a $type, expected tree, tag or commit\n";
1697 }
1698 return $expected;
1699}
1700
1701sub get_commit_entry {
1702 my ($treeish) = shift;
1703 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1704 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1705 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1706 open my $log_fh, '>', $commit_editmsg or croak $!;
1707
1708 my $type = command_oneline(qw/cat-file -t/, $treeish);
1709 if ($type eq 'commit' || $type eq 'tag') {
1710 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1711 $type, $treeish);
1712 my $in_msg = 0;
1713 my $author;
1714 my $saw_from = 0;
1715 my $msgbuf = "";
1716 while (<$msg_fh>) {
1717 if (!$in_msg) {
1718 $in_msg = 1 if (/^\s*$/);
1719 $author = $1 if (/^author (.*>)/);
1720 } elsif (/^git-svn-id: /) {
1721 # skip this for now, we regenerate the
1722 # correct one on re-fetch anyways
1723 # TODO: set *:merge properties or like...
1724 } else {
1725 if (/^From:/ || /^Signed-off-by:/) {
1726 $saw_from = 1;
1727 }
1728 $msgbuf .= $_;
1729 }
1730 }
1731 $msgbuf =~ s/\s+$//s;
1732 if ($Git::SVN::_add_author_from && defined($author)
1733 && !$saw_from) {
1734 $msgbuf .= "\n\nFrom: $author";
1735 }
1736 print $log_fh $msgbuf or croak $!;
1737 command_close_pipe($msg_fh, $ctx);
1738 }
1739 close $log_fh or croak $!;
1740
1741 if ($_edit || ($type eq 'tree')) {
1742 chomp(my $editor = command_oneline(qw(var GIT_EDITOR)));
1743 system('sh', '-c', $editor.' "$@"', $editor, $commit_editmsg);
1744 }
1745 rename $commit_editmsg, $commit_msg or croak $!;
1746 {
1747 require Encode;
1748 # SVN requires messages to be UTF-8 when entering the repo
1749 local $/;
1750 open $log_fh, '<', $commit_msg or croak $!;
1751 binmode $log_fh;
1752 chomp($log_entry{log} = <$log_fh>);
1753
1754 my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
1755 my $msg = $log_entry{log};
1756
1757 eval { $msg = Encode::decode($enc, $msg, 1) };
1758 if ($@) {
1759 die "Could not decode as $enc:\n", $msg,
1760 "\nPerhaps you need to set i18n.commitencoding\n";
1761 }
1762
1763 eval { $msg = Encode::encode('UTF-8', $msg, 1) };
1764 die "Could not encode as UTF-8:\n$msg\n" if $@;
1765
1766 $log_entry{log} = $msg;
1767
1768 close $log_fh or croak $!;
1769 }
1770 unlink $commit_msg;
1771 \%log_entry;
1772}
1773
1774sub s_to_file {
1775 my ($str, $file, $mode) = @_;
1776 open my $fd,'>',$file or croak $!;
1777 print $fd $str,"\n" or croak $!;
1778 close $fd or croak $!;
1779 chmod ($mode &~ umask, $file) if (defined $mode);
1780}
1781
1782sub file_to_s {
1783 my $file = shift;
1784 open my $fd,'<',$file or croak "$!: file: $file\n";
1785 local $/;
1786 my $ret = <$fd>;
1787 close $fd or croak $!;
1788 $ret =~ s/\s*$//s;
1789 return $ret;
1790}
1791
1792# '<svn username> = real-name <email address>' mapping based on git-svnimport:
1793sub load_authors {
1794 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1795 my $log = $cmd eq 'log';
1796 while (<$authors>) {
1797 chomp;
1798 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1799 my ($user, $name, $email) = ($1, $2, $3);
1800 if ($log) {
1801 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1802 } else {
1803 $users{$user} = [$name, $email];
1804 }
1805 }
1806 close $authors or croak $!;
1807}
1808
1809# convert GetOpt::Long specs for use by git-config
1810sub read_git_config {
1811 my $opts = shift;
1812 my @config_only;
1813 foreach my $o (keys %$opts) {
1814 # if we have mixedCase and a long option-only, then
1815 # it's a config-only variable that we don't need for
1816 # the command-line.
1817 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1818 my $v = $opts->{$o};
1819 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1820 $key =~ s/-//g;
1821 my $arg = 'git config';
1822 $arg .= ' --int' if ($o =~ /[:=]i$/);
1823 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1824 if (ref $v eq 'ARRAY') {
1825 chomp(my @tmp = `$arg --get-all svn.$key`);
1826 @$v = @tmp if @tmp;
1827 } else {
1828 chomp(my $tmp = `$arg --get svn.$key`);
1829 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1830 $$v = $tmp;
1831 }
1832 }
1833 }
1834 delete @$opts{@config_only} if @config_only;
1835}
1836
1837sub extract_metadata {
1838 my $id = shift or return (undef, undef, undef);
1839 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1840 \s([a-f\d\-]+)$/ix);
1841 if (!defined $rev || !$uuid || !$url) {
1842 # some of the original repositories I made had
1843 # identifiers like this:
1844 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/i);
1845 }
1846 return ($url, $rev, $uuid);
1847}
1848
1849sub cmt_metadata {
1850 return extract_metadata((grep(/^git-svn-id: /,
1851 command(qw/cat-file commit/, shift)))[-1]);
1852}
1853
1854sub cmt_sha2rev_batch {
1855 my %s2r;
1856 my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1857 my $list = shift;
1858
1859 foreach my $sha (@{$list}) {
1860 my $first = 1;
1861 my $size = 0;
1862 print $out $sha, "\n";
1863
1864 while (my $line = <$in>) {
1865 if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1866 last;
1867 } elsif ($first &&
1868 $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1869 $first = 0;
1870 $size = $1;
1871 next;
1872 } elsif ($line =~ /^(git-svn-id: )/) {
1873 my (undef, $rev, undef) =
1874 extract_metadata($line);
1875 $s2r{$sha} = $rev;
1876 }
1877
1878 $size -= length($line);
1879 last if ($size == 0);
1880 }
1881 }
1882
1883 command_close_bidi_pipe($pid, $in, $out, $ctx);
1884
1885 return \%s2r;
1886}
1887
1888sub working_head_info {
1889 my ($head, $refs) = @_;
1890 my @args = qw/rev-list --first-parent --pretty=medium/;
1891 my ($fh, $ctx) = command_output_pipe(@args, $head);
1892 my $hash;
1893 my %max;
1894 while (<$fh>) {
1895 if ( m{^commit ($::sha1)$} ) {
1896 unshift @$refs, $hash if $hash and $refs;
1897 $hash = $1;
1898 next;
1899 }
1900 next unless s{^\s*(git-svn-id:)}{$1};
1901 my ($url, $rev, $uuid) = extract_metadata($_);
1902 if (defined $url && defined $rev) {
1903 next if $max{$url} and $max{$url} < $rev;
1904 if (my $gs = Git::SVN->find_by_url($url)) {
1905 my $c = $gs->rev_map_get($rev, $uuid);
1906 if ($c && $c eq $hash) {
1907 close $fh; # break the pipe
1908 return ($url, $rev, $uuid, $gs);
1909 } else {
1910 $max{$url} ||= $gs->rev_map_max;
1911 }
1912 }
1913 }
1914 }
1915 command_close_pipe($fh, $ctx);
1916 (undef, undef, undef, undef);
1917}
1918
1919sub read_commit_parents {
1920 my ($parents, $c) = @_;
1921 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1922 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1923 @{$parents->{$c}} = split(/ /, $p);
1924}
1925
1926sub linearize_history {
1927 my ($gs, $refs) = @_;
1928 my %parents;
1929 foreach my $c (@$refs) {
1930 read_commit_parents(\%parents, $c);
1931 }
1932
1933 my @linear_refs;
1934 my %skip = ();
1935 my $last_svn_commit = $gs->last_commit;
1936 foreach my $c (reverse @$refs) {
1937 next if $c eq $last_svn_commit;
1938 last if $skip{$c};
1939
1940 unshift @linear_refs, $c;
1941 $skip{$c} = 1;
1942
1943 # we only want the first parent to diff against for linear
1944 # history, we save the rest to inject when we finalize the
1945 # svn commit
1946 my $fp_a = verify_ref("$c~1");
1947 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1948 if (!$fp_a || !$fp_b) {
1949 die "Commit $c\n",
1950 "has no parent commit, and therefore ",
1951 "nothing to diff against.\n",
1952 "You should be working from a repository ",
1953 "originally created by git-svn\n";
1954 }
1955 if ($fp_a ne $fp_b) {
1956 die "$c~1 = $fp_a, however parsing commit $c ",
1957 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1958 }
1959
1960 foreach my $p (@{$parents{$c}}) {
1961 $skip{$p} = 1;
1962 }
1963 }
1964 (\@linear_refs, \%parents);
1965}
1966
1967sub find_file_type_and_diff_status {
1968 my ($path) = @_;
1969 return ('dir', '') if $path eq '';
1970
1971 my $diff_output =
1972 command_oneline(qw(diff --cached --name-status --), $path) || "";
1973 my $diff_status = (split(' ', $diff_output))[0] || "";
1974
1975 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1976
1977 return (undef, undef) if !$diff_status && !$ls_tree;
1978
1979 if ($diff_status eq "A") {
1980 return ("link", $diff_status) if -l $path;
1981 return ("dir", $diff_status) if -d $path;
1982 return ("file", $diff_status);
1983 }
1984
1985 my $mode = (split(' ', $ls_tree))[0] || "";
1986
1987 return ("link", $diff_status) if $mode eq "120000";
1988 return ("dir", $diff_status) if $mode eq "040000";
1989 return ("file", $diff_status);
1990}
1991
1992sub md5sum {
1993 my $arg = shift;
1994 my $ref = ref $arg;
1995 my $md5 = Digest::MD5->new();
1996 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
1997 $md5->addfile($arg) or croak $!;
1998 } elsif ($ref eq 'SCALAR') {
1999 $md5->add($$arg) or croak $!;
2000 } elsif (!$ref) {
2001 $md5->add($arg) or croak $!;
2002 } else {
2003 fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
2004 }
2005 return $md5->hexdigest();
2006}
2007
2008sub gc_directory {
2009 if (can_compress() && -f $_ && basename($_) eq "unhandled.log") {
2010 my $out_filename = $_ . ".gz";
2011 open my $in_fh, "<", $_ or die "Unable to open $_: $!\n";
2012 binmode $in_fh;
2013 my $gz = Compress::Zlib::gzopen($out_filename, "ab") or
2014 die "Unable to open $out_filename: $!\n";
2015
2016 my $res;
2017 while ($res = sysread($in_fh, my $str, 1024)) {
2018 $gz->gzwrite($str) or
2019 die "Unable to write: ".$gz->gzerror()."!\n";
2020 }
2021 unlink $_ or die "unlink $File::Find::name: $!\n";
2022 } elsif (-f $_ && basename($_) eq "index") {
2023 unlink $_ or die "unlink $_: $!\n";
2024 }
2025}
2026
2027__END__
2028
2029Data structures:
2030
2031
2032$remotes = { # returned by read_all_remotes()
2033 'svn' => {
2034 # svn-remote.svn.url=https://svn.musicpd.org
2035 url => 'https://svn.musicpd.org',
2036 # svn-remote.svn.fetch=mpd/trunk:trunk
2037 fetch => {
2038 'mpd/trunk' => 'trunk',
2039 },
2040 # svn-remote.svn.tags=mpd/tags/*:tags/*
2041 tags => {
2042 path => {
2043 left => 'mpd/tags',
2044 right => '',
2045 regex => qr!mpd/tags/([^/]+)$!,
2046 glob => 'tags/*',
2047 },
2048 ref => {
2049 left => 'tags',
2050 right => '',
2051 regex => qr!tags/([^/]+)$!,
2052 glob => 'tags/*',
2053 },
2054 }
2055 }
2056};
2057
2058$log_entry hashref as returned by libsvn_log_entry()
2059{
2060 log => 'whitespace-formatted log entry
2061', # trailing newline is preserved
2062 revision => '8', # integer
2063 date => '2004-02-24T17:01:44.108345Z', # commit date
2064 author => 'committer name'
2065};
2066
2067
2068# this is generated by generate_diff();
2069@mods = array of diff-index line hashes, each element represents one line
2070 of diff-index output
2071
2072diff-index line ($m hash)
2073{
2074 mode_a => first column of diff-index output, no leading ':',
2075 mode_b => second column of diff-index output,
2076 sha1_b => sha1sum of the final blob,
2077 chg => change type [MCRADT],
2078 file_a => original file name of a file (iff chg is 'C' or 'R')
2079 file_b => new/current file name of a file (any chg)
2080}
2081;
2082
2083# retval of read_url_paths{,_all}();
2084$l_map = {
2085 # repository root url
2086 'https://svn.musicpd.org' => {
2087 # repository path # GIT_SVN_ID
2088 'mpd/trunk' => 'trunk',
2089 'mpd/tags/0.11.5' => 'tags/0.11.5',
2090 },
2091}
2092
2093Notes:
2094 I don't trust the each() function on unless I created %hash myself
2095 because the internal iterator may not have started at base.