git-svn: reuse open SVN::Ra connections by URL
[git/git.git] / git-svn.perl
CommitLineData
3397f9df 1#!/usr/bin/env perl
551ce28f
EW
2# Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3# License: GPL v2 or later
3397f9df
EW
4use warnings;
5use strict;
6use vars qw/ $AUTHOR $VERSION
d81bf827 7 $SVN_URL
3397f9df 8 $GIT_SVN_INDEX $GIT_SVN
f8c9d1d2 9 $GIT_DIR $GIT_SVN_DIR $REVDB
e7f023c8 10 $_follow_parent $sha1 $sha1_short $_revision
44320b9e 11 $_cp_remote $_upgrade $_rmdir $_q $_cp_similarity
1c8443b0 12 $_find_copies_harder $_l $_authors %users/;
3397f9df 13$AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
60d02ccc 14$VERSION = '@@GIT_VERSION@@';
13ccd6d4 15
706587fc
EW
16$ENV{GIT_DIR} ||= '.git';
17$Git::SVN::default_repo_id = $ENV{GIT_SVN_ID} || 'git-svn';
13ccd6d4 18
ce475dfc 19my $LC_ALL = $ENV{LC_ALL};
f8c9d1d2 20$Git::SVN::Log::TZ = $ENV{TZ};
3397f9df
EW
21# make sure the svn binary gives consistent output between locales and TZs:
22$ENV{TZ} = 'UTC';
23$ENV{LC_ALL} = 'C';
a00439ac 24$| = 1; # unbuffer STDOUT
3397f9df 25
6fda05ae 26sub fatal (@) { print STDERR @_; exit 1 }
b9c85187
EW
27require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
28require SVN::Ra;
29require SVN::Delta;
30if ($SVN::Core::VERSION lt '1.1.0') {
31 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)\n";
32}
d81bf827 33push @Git::SVN::Ra::ISA, 'SVN::Ra';
b9c85187
EW
34push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
35push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
3397f9df
EW
36use Carp qw/croak/;
37use IO::File qw//;
38use File::Basename qw/dirname basename/;
39use File::Path qw/mkpath/;
79bb8d88 40use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev pass_through/;
968bdf1f 41use IPC::Open3;
336f1714 42use Git;
a5e0cedc 43
336f1714
EW
44BEGIN {
45 my $s;
46 foreach (qw/command command_oneline command_noisy command_output_pipe
47 command_input_pipe command_close_pipe/) {
48 $s .= "*SVN::Git::Editor::$_ = *SVN::Git::Fetcher::$_ = ".
706587fc 49 "*Git::SVN::Migration::$_ = ".
f8c9d1d2 50 "*Git::SVN::Log::$_ = *Git::SVN::$_ = *$_ = *Git::$_; ";
336f1714
EW
51 }
52 eval $s;
53}
54
b9c85187 55my ($SVN);
83e9940a 56
42d32870 57my $_optimize_commits = 1 unless $ENV{GIT_SVN_NO_OPTIMIZE_COMMITS};
f8c9d1d2
EW
58$sha1 = qr/[a-f\d]{40}/;
59$sha1_short = qr/[a-f\d]{4,40}/;
44320b9e
EW
60my ($_stdin, $_help, $_edit,
61 $_repack, $_repack_nr, $_repack_flags,
d81bf827 62 $_message, $_file, $_no_metadata,
d05d72e0
EW
63 $_template, $_shared,
64 $_version, $_upgrade,
f8c9d1d2
EW
65 $_merge, $_strategy, $_dry_run,
66 $_prefix);
3397f9df 67
706587fc
EW
68my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
69 'config-dir=s' => \$Git::SVN::Ra::config_dir,
70 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache );
d05d72e0 71my %fc_opts = ( 'follow-parent|follow' => \$_follow_parent,
dc5869c0
EW
72 'authors-file|A=s' => \$_authors,
73 'repack:i' => \$_repack,
a00439ac 74 'no-metadata' => \$_no_metadata,
80f50749 75 'quiet|q' => \$_q,
706587fc
EW
76 'repack-flags|repack-args|repack-opts=s' => \$_repack_flags,
77 %remote_opts );
36f5b1f0 78
9d55b41a
EW
79my ($_trunk, $_tags, $_branches);
80my %multi_opts = ( 'trunk|T=s' => \$_trunk,
81 'tags|t=s' => \$_tags,
82 'branches|b=s' => \$_branches );
83my %init_opts = ( 'template=s' => \$_template, 'shared' => \$_shared );
27e9fb8d
EW
84my %cmt_opts = ( 'edit|e' => \$_edit,
85 'rmdir' => \$_rmdir,
86 'find-copies-harder' => \$_find_copies_harder,
87 'l=i' => \$_l,
88 'copy-similarity|C=i'=> \$_cp_similarity
89);
9d55b41a 90
3397f9df 91my %cmd = (
2a3240be 92 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
eeb0abe0 93 { 'revision|r=s' => \$_revision, %fc_opts } ],
d2866f9e 94 init => [ \&cmd_init, "Initialize a repo for tracking" .
f8ab6b73 95 " (requires URL argument)",
9d55b41a 96 \%init_opts ],
d7ad3bed
EW
97 dcommit => [ \&cmd_dcommit,
98 'Commit several diffs to merge with upstream',
3289e86e
EW
99 { 'merge|m|M' => \$_merge,
100 'strategy|s=s' => \$_strategy,
101 'dry-run|n' => \$_dry_run,
4b155223 102 %cmt_opts, %fc_opts } ],
1ce255dc
EW
103 'set-tree' => [ \&cmd_set_tree,
104 "Set an SVN repository to a git tree-ish",
105 { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
5969cbe1 106 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
a5e0cedc 107 { 'revision|r=i' => \$_revision } ],
e7f023c8 108 rebuild => [ \&cmd_rebuild, "Rebuild git-svn metadata (after git clone)",
336f1714 109 { 'copy-remote|remote=s' => \$_cp_remote,
eeb0abe0 110 'upgrade' => \$_upgrade } ],
8164b652 111 'multi-init' => [ \&cmd_multi_init,
9d55b41a 112 'Initialize multiple trees (like git-svnimport)',
706587fc 113 { %multi_opts, %init_opts, %remote_opts,
1ca7558d 114 'revision|r=i' => \$_revision,
ae410987 115 'prefix=s' => \$_prefix,
1ca7558d 116 } ],
1c8443b0 117 'multi-fetch' => [ \&cmd_multi_fetch,
9d55b41a
EW
118 'Fetch multiple trees (like git-svnimport)',
119 \%fc_opts ],
706587fc
EW
120 'migrate' => [ sub { },
121 # no-op, we automatically run this anyways,
122 # we may add a flag to automatically optimize the
123 # configuration to avoid reconnects in the future
124 'Migrate configuration/metadata/layout from
125 previous versions of git-svn',
126 \%remote_opts ],
f8c9d1d2
EW
127 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
128 { 'limit=i' => \$Git::SVN::Log::limit,
79bb8d88 129 'revision|r=s' => \$_revision,
f8c9d1d2
EW
130 'verbose|v' => \$Git::SVN::Log::verbose,
131 'incremental' => \$Git::SVN::Log::incremental,
132 'oneline' => \$Git::SVN::Log::oneline,
133 'show-commit' => \$Git::SVN::Log::show_commit,
134 'non-recursive' => \$Git::SVN::Log::non_recursive,
79bb8d88 135 'authors-file|A=s' => \$_authors,
f8c9d1d2
EW
136 'color' => \$Git::SVN::Log::color,
137 'pager=s' => \$Git::SVN::Log::pager,
79bb8d88 138 } ],
44320b9e
EW
139 'commit-diff' => [ \&cmd_commit_diff,
140 'Commit a diff between two trees',
27e9fb8d
EW
141 { 'message|m=s' => \$_message,
142 'file|F=s' => \$_file,
45bf473a 143 'revision|r=s' => \$_revision,
27e9fb8d 144 %cmt_opts } ],
3397f9df 145);
9d55b41a 146
3397f9df
EW
147my $cmd;
148for (my $i = 0; $i < @ARGV; $i++) {
149 if (defined $cmd{$ARGV[$i]}) {
150 $cmd = $ARGV[$i];
151 splice @ARGV, $i, 1;
152 last;
153 }
154};
155
448c81b4 156my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
a9612be2 157
b8c92cad 158read_repo_config(\%opts);
79bb8d88
EW
159my $rv = GetOptions(%opts, 'help|H|h' => \$_help,
160 'version|V' => \$_version,
706587fc 161 'id|i=s' => \$Git::SVN::default_repo_id);
79bb8d88 162exit 1 if (!$rv && $cmd ne 'log');
6f0783cf 163
3397f9df 164usage(0) if $_help;
551ce28f 165version() if $_version;
eeb0abe0
EW
166usage(1) unless defined $cmd;
167load_authors() if $_authors;
706587fc
EW
168unless ($cmd =~ /^(?:init|rebuild|multi-init|commit-diff)$/) {
169 Git::SVN::Migration::migration_check();
170}
3397f9df
EW
171$cmd{$cmd}->[0]->(@ARGV);
172exit 0;
173
174####################### primary functions ######################
175sub usage {
176 my $exit = shift || 0;
177 my $fd = $exit ? \*STDERR : \*STDOUT;
178 print $fd <<"";
179git-svn - bidirectional operations between a single Subversion tree and git
180Usage: $0 <command> [options] [arguments]\n
448c81b4
EW
181
182 print $fd "Available commands:\n" unless $cmd;
3397f9df
EW
183
184 foreach (sort keys %cmd) {
448c81b4 185 next if $cmd && $cmd ne $_;
b203b769 186 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
448c81b4
EW
187 foreach (keys %{$cmd{$_}->[2]}) {
188 # prints out arguments as they should be passed:
b8c92cad 189 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
b203b769 190 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
448c81b4
EW
191 "--$_" : "-$_" }
192 split /\|/,$_)," $x\n";
193 }
3397f9df
EW
194 }
195 print $fd <<"";
448c81b4
EW
196\nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
197arbitrary identifier if you're tracking multiple SVN branches/repositories in
198one git repository and want to keep them separate. See git-svn(1) for more
199information.
3397f9df
EW
200
201 exit $exit;
202}
203
551ce28f 204sub version {
7d60ab2c 205 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
551ce28f
EW
206 exit 0;
207}
208
e7f023c8
EW
209sub cmd_rebuild {
210 my $url = shift;
706587fc 211 my $gs = $url ? Git::SVN->init($url)
e7f023c8
EW
212 : eval { Git::SVN->new };
213 $gs ||= Git::SVN->_new;
214 if (!verify_ref($gs->refname.'^0')) {
215 $gs->copy_remote_ref;
1a82e793 216 }
3397f9df 217
e7f023c8 218 my ($rev_list, $ctx) = command_output_pipe("rev-list", $gs->refname);
2beb3cdd 219 my $latest;
d81bf827 220 my $svn_uuid;
3397f9df
EW
221 while (<$rev_list>) {
222 chomp;
223 my $c = $_;
e7f023c8
EW
224 fatal "Non-SHA1: $c\n" unless $c =~ /^$sha1$/o;
225 my ($url, $rev, $uuid) = cmt_metadata($c);
226
227 # ignore merges (from set-tree)
228 next if (!defined $rev || !$uuid);
2beb3cdd
EW
229
230 # if we merged or otherwise started elsewhere, this is
231 # how we break out of it
e7f023c8
EW
232 if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
233 ($gs->{url} && $url && ($url ne $gs->{url}))) {
234 next;
235 }
2beb3cdd 236
2beb3cdd 237 unless (defined $latest) {
e7f023c8
EW
238 if (!$gs->{url} && !$url) {
239 fatal "SVN repository location required\n";
3397f9df 240 }
706587fc 241 $gs = Git::SVN->init($url);
2beb3cdd 242 $latest = $rev;
3397f9df 243 }
e7f023c8 244 $gs->rev_db_set($rev, $c);
42d32870 245 print "r$rev = $c\n";
3397f9df 246 }
aef4e921 247 command_close_pipe($rev_list, $ctx);
3397f9df
EW
248}
249
8164b652
EW
250sub do_git_init_db {
251 unless (-d $ENV{GIT_DIR}) {
252 my @init_db = ('init');
253 push @init_db, "--template=$_template" if defined $_template;
254 push @init_db, "--shared" if defined $_shared;
255 command_noisy(@init_db);
256 }
257}
258
d2866f9e 259sub cmd_init {
03e0ea87 260 my $url = shift or die "SVN repository location required " .
81c5a0e6 261 "as a command-line argument\n";
03e0ea87
EW
262 if (my $repo_path = shift) {
263 unless (-d $repo_path) {
264 mkpath([$repo_path]);
265 }
d2866f9e
EW
266 chdir $repo_path or croak $!;
267 $ENV{GIT_DIR} = $repo_path . "/.git";
03e0ea87 268 }
8164b652 269 do_git_init_db();
03e0ea87 270
706587fc 271 Git::SVN->init($url);
3397f9df
EW
272}
273
2a3240be 274sub cmd_fetch {
1c8443b0
EW
275 my $gs = Git::SVN->new;
276 $gs->fetch(@_);
277 if ($gs->{last_commit} && !verify_ref('refs/heads/master^0')) {
278 command_noisy(qw(update-ref refs/heads/master),
279 $gs->{last_commit});
280 }
2a3240be
EW
281}
282
1ce255dc 283sub cmd_set_tree {
3397f9df
EW
284 my (@commits) = @_;
285 if ($_stdin || !@commits) {
286 print "Reading from stdin...\n";
287 @commits = ();
288 while (<STDIN>) {
1ca72aef 289 if (/\b($sha1_short)\b/o) {
3397f9df
EW
290 unshift @commits, $1;
291 }
292 }
293 }
294 my @revs;
8de010ad 295 foreach my $c (@commits) {
aef4e921 296 my @tmp = command('rev-parse',$c);
8de010ad
EW
297 if (scalar @tmp == 1) {
298 push @revs, $tmp[0];
299 } elsif (scalar @tmp > 1) {
aef4e921 300 push @revs, reverse(command('rev-list',@tmp));
8de010ad 301 } else {
1ce255dc 302 fatal "Failed to rev-parse $c\n";
8de010ad 303 }
3397f9df 304 }
1ce255dc
EW
305 my $gs = Git::SVN->new;
306 my ($r_last, $cmt_last) = $gs->last_rev_commit;
307 $gs->fetch;
308 if ($r_last != $gs->{last_rev}) {
309 fatal "There are new revisions that were fetched ",
310 "and need to be merged (or acknowledged) ",
311 "before committing.\nlast rev: $r_last\n",
312 " current: $gs->{last_rev}\n";
a5e0cedc 313 }
1ce255dc
EW
314 $gs->set_tree($_) foreach @revs;
315 print "Done committing ",scalar @revs," revisions to SVN\n";
a5e0cedc 316}
8f22562c 317
d7ad3bed
EW
318sub cmd_dcommit {
319 my $head = shift;
320 my $gs = Git::SVN->new;
321 $head ||= 'HEAD';
322 my @refs = command(qw/rev-list --no-merges/, $gs->refname."..$head");
45bf473a 323 my $last_rev;
b22d4497 324 foreach my $d (reverse @refs) {
aef4e921 325 if (!verify_ref("$d~1")) {
d7ad3bed
EW
326 fatal "Commit $d\n",
327 "has no parent commit, and therefore ",
328 "nothing to diff against.\n",
329 "You should be working from a repository ",
330 "originally created by git-svn\n";
48d044b5 331 }
45bf473a
EW
332 unless (defined $last_rev) {
333 (undef, $last_rev, undef) = cmt_metadata("$d~1");
334 unless (defined $last_rev) {
d7ad3bed
EW
335 fatal "Unable to extract revision information ",
336 "from commit $d~1\n";
45bf473a
EW
337 }
338 }
b22d4497
EW
339 if ($_dry_run) {
340 print "diff-tree $d~1 $d\n";
341 } else {
780a2f58 342 my $log = get_commit_entry($d)->{log};
d7ad3bed
EW
343 my $ra = $gs->ra;
344 my $pool = SVN::Pool->new;
345 my %ed_opts = ( r => $last_rev,
346 ra => $ra->dup,
347 svn_path => $ra->{svn_path} );
348 my $ed = SVN::Git::Editor->new(\%ed_opts,
780a2f58 349 $ra->get_commit_editor($log,
d7ad3bed
EW
350 sub { print "Committed r$_[0]\n";
351 $last_rev = $_[0]; }),
352 $pool);
353 my $mods = $ed->apply_diff("$d~1", $d);
354 if (@$mods == 0) {
355 print "No changes\n$d~1 == $d\n";
356 }
b22d4497
EW
357 }
358 }
359 return if $_dry_run;
d7ad3bed
EW
360 $gs->fetch;
361 # we always want to rebase against the current HEAD, not any
362 # head that was passed to us
363 my @diff = command('diff-tree', 'HEAD', $gs->refname, '--');
b22d4497
EW
364 my @finish;
365 if (@diff) {
366 @finish = qw/rebase/;
367 push @finish, qw/--merge/ if $_merge;
368 push @finish, "--strategy=$_strategy" if $_strategy;
d7ad3bed
EW
369 print STDERR "W: HEAD and ", $gs->refname, " differ, ",
370 "using @finish:\n", "@diff";
b22d4497 371 } else {
d7ad3bed
EW
372 print "No changes between current HEAD and ",
373 $gs->refname, "\nResetting to the latest ",
374 $gs->refname, "\n";
4769489a 375 @finish = qw/reset --mixed/;
b22d4497 376 }
d7ad3bed 377 command_noisy(@finish, $gs->refname);
b22d4497
EW
378}
379
5969cbe1
EW
380sub cmd_show_ignore {
381 my $gs = Git::SVN->new;
382 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
383 $gs->traverse_ignore(\*STDOUT, '', $r);
a5e0cedc
EW
384}
385
8164b652 386sub cmd_multi_init {
9d55b41a 387 my $url = shift;
98327e58
EW
388 unless (defined $_trunk || defined $_branches || defined $_tags) {
389 usage(1);
9d55b41a 390 }
8164b652
EW
391 do_git_init_db();
392 $_prefix = '' unless defined $_prefix;
706587fc 393 $url =~ s#/+$## if defined $url;
98327e58 394 if (defined $_trunk) {
706587fc
EW
395 my $trunk_ref = $_prefix . 'trunk';
396 # try both old-style and new-style lookups:
397 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
8164b652 398 unless ($gs_trunk) {
706587fc
EW
399 my ($trunk_url, $trunk_path) =
400 complete_svn_url($url, $_trunk);
401 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
402 undef, $trunk_ref);
98327e58 403 }
c35b96e7 404 }
706587fc 405 return unless defined $_branches || defined $_tags;
e7db67e6
EW
406 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
407 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
408 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
9d55b41a
EW
409}
410
1c8443b0 411sub cmd_multi_fetch {
706587fc
EW
412 my @gs;
413 foreach (command(qw/config -l/)) {
414 next unless m!^svn-remote\.(.+)\.fetch=
415 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
416 my ($repo_id, $path, $ref_id) = ($1, $2, $3);
417 push @gs, Git::SVN->new($ref_id, $repo_id, $path);
418 }
419 foreach (@gs) {
420 $_->fetch;
9d55b41a 421 }
9d55b41a
EW
422}
423
44320b9e
EW
424# this command is special because it requires no metadata
425sub cmd_commit_diff {
426 my ($ta, $tb, $url) = @_;
427 my $usage = "Usage: $0 commit-diff -r<revision> ".
428 "<tree-ish> <tree-ish> [<URL>]\n";
429 fatal($usage) if (!defined $ta || !defined $tb);
430 if (!defined $url) {
431 my $gs = eval { Git::SVN->new };
432 if (!$gs) {
433 fatal("Needed URL or usable git-svn --id in ",
434 "the command-line\n", $usage);
435 }
436 $url = $gs->{url};
437 }
438 unless (defined $_revision) {
439 fatal("-r|--revision is a required argument\n", $usage);
440 }
441 if (defined $_message && defined $_file) {
442 fatal("Both --message/-m and --file/-F specified ",
443 "for the commit message.\n",
444 "I have no idea what you mean\n");
445 }
446 if (defined $_file) {
447 $_message = file_to_s($_file);
448 } else {
449 $_message ||= get_commit_entry($tb)->{log};
450 }
451 my $ra ||= Git::SVN::Ra->new($url);
452 my $r = $_revision;
453 if ($r eq 'HEAD') {
454 $r = $ra->get_latest_revnum;
455 } elsif ($r !~ /^\d+$/) {
456 die "revision argument: $r not understood by git-svn\n";
457 }
458 my $pool = SVN::Pool->new;
459 my %ed_opts = ( r => $r,
460 ra => $ra->dup,
461 svn_path => $ra->{svn_path} );
462 my $ed = SVN::Git::Editor->new(\%ed_opts,
463 $ra->get_commit_editor($_message,
464 sub { print "Committed r$_[0]\n" }),
465 $pool);
466 my $mods = $ed->apply_diff($ta, $tb);
467 if (@$mods == 0) {
468 print "No changes\n$ta == $tb\n";
469 }
470 $pool->clear;
471}
472
3397f9df
EW
473########################### utility functions #########################
474
98327e58
EW
475sub complete_svn_url {
476 my ($url, $path) = @_;
477 $path =~ s#/+$##;
98327e58 478 if ($path !~ m#^[a-z\+]+://#) {
98327e58
EW
479 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
480 fatal("E: '$path' is not a complete URL ",
481 "and a separate URL is not specified\n");
482 }
706587fc 483 return ($url, $path);
98327e58 484 }
706587fc 485 return ($path, '');
98327e58
EW
486}
487
9d55b41a 488sub complete_url_ls_init {
706587fc
EW
489 my ($ra, $repo_path, $switch, $pfx) = @_;
490 unless ($repo_path) {
9d55b41a
EW
491 print STDERR "W: $switch not specified\n";
492 return;
493 }
706587fc
EW
494 $repo_path =~ s#/+$##;
495 if ($repo_path =~ m#^[a-z\+]+://#) {
496 $ra = Git::SVN::Ra->new($repo_path);
497 $repo_path = '';
e7db67e6 498 } else {
706587fc 499 $repo_path =~ s#^/+##;
e7db67e6 500 unless ($ra) {
706587fc 501 fatal("E: '$repo_path' is not a complete URL ",
e7db67e6 502 "and a separate URL is not specified\n");
8164b652 503 }
e7db67e6
EW
504 }
505 my $r = defined $_revision ? $_revision : $ra->get_latest_revnum;
706587fc
EW
506 my ($dirent, undef, undef) = $ra->get_dir($repo_path, $r);
507 my $url = $ra->{url};
e7db67e6
EW
508 foreach my $d (sort keys %$dirent) {
509 next if ($dirent->{$d}->kind != $SVN::Node::dir);
706587fc
EW
510 my $path = "$repo_path/$d";
511 my $ref = "$pfx$d";
512 my $gs = eval { Git::SVN->new($ref) };
e7db67e6 513 # don't try to init already existing refs
8164b652 514 unless ($gs) {
706587fc
EW
515 print "init $url/$path => $ref\n";
516 Git::SVN->init($url, $path, undef, $ref);
9d55b41a 517 }
9d55b41a 518 }
9d55b41a
EW
519}
520
aef4e921
EW
521sub verify_ref {
522 my ($ref) = @_;
2c5c1d53
EW
523 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
524 { STDERR => 0 }); };
aef4e921
EW
525}
526
a5e0cedc 527sub get_tree_from_treeish {
cf52b8f0 528 my ($treeish) = @_;
44320b9e 529 # $treeish can be a symbolic ref, too:
aef4e921 530 my $type = command_oneline(qw/cat-file -t/, $treeish);
cf52b8f0
EW
531 my $expected;
532 while ($type eq 'tag') {
aef4e921 533 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
cf52b8f0
EW
534 }
535 if ($type eq 'commit') {
aef4e921
EW
536 $expected = (grep /^tree /, command(qw/cat-file commit/,
537 $treeish))[0];
44320b9e 538 ($expected) = ($expected =~ /^tree ($sha1)$/o);
cf52b8f0
EW
539 die "Unable to get tree from $treeish\n" unless $expected;
540 } elsif ($type eq 'tree') {
541 $expected = $treeish;
542 } else {
543 die "$treeish is a $type, expected tree, tag or commit\n";
544 }
a5e0cedc
EW
545 return $expected;
546}
547
44320b9e
EW
548sub get_commit_entry {
549 my ($treeish) = shift;
550 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
551 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
552 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
553 open my $log_fh, '>', $commit_editmsg or croak $!;
3397f9df 554
44320b9e 555 my $type = command_oneline(qw/cat-file -t/, $treeish);
4ad4515d 556 if ($type eq 'commit' || $type eq 'tag') {
aef4e921 557 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
44320b9e 558 $type, $treeish);
3397f9df
EW
559 my $in_msg = 0;
560 while (<$msg_fh>) {
561 if (!$in_msg) {
562 $in_msg = 1 if (/^\s*$/);
df746c5a 563 } elsif (/^git-svn-id: /) {
44320b9e
EW
564 # skip this for now, we regenerate the
565 # correct one on re-fetch anyways
566 # TODO: set *:merge properties or like...
3397f9df 567 } else {
44320b9e 568 print $log_fh $_ or croak $!;
3397f9df
EW
569 }
570 }
aef4e921 571 command_close_pipe($msg_fh, $ctx);
3397f9df 572 }
44320b9e 573 close $log_fh or croak $!;
3397f9df
EW
574
575 if ($_edit || ($type eq 'tree')) {
576 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
44320b9e
EW
577 # TODO: strip out spaces, comments, like git-commit.sh
578 system($editor, $commit_editmsg);
3397f9df 579 }
44320b9e
EW
580 rename $commit_editmsg, $commit_msg or croak $!;
581 open $log_fh, '<', $commit_msg or croak $!;
582 { local $/; chomp($log_entry{log} = <$log_fh>); }
583 close $log_fh or croak $!;
584 unlink $commit_msg;
585 \%log_entry;
a5e0cedc
EW
586}
587
3397f9df
EW
588sub s_to_file {
589 my ($str, $file, $mode) = @_;
590 open my $fd,'>',$file or croak $!;
591 print $fd $str,"\n" or croak $!;
592 close $fd or croak $!;
593 chmod ($mode &~ umask, $file) if (defined $mode);
594}
595
596sub file_to_s {
597 my $file = shift;
598 open my $fd,'<',$file or croak "$!: file: $file\n";
599 local $/;
600 my $ret = <$fd>;
601 close $fd or croak $!;
602 $ret =~ s/\s*$//s;
603 return $ret;
604}
605
eeb0abe0
EW
606# '<svn username> = real-name <email address>' mapping based on git-svnimport:
607sub load_authors {
608 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
f8c9d1d2 609 my $log = $cmd eq 'log';
eeb0abe0
EW
610 while (<$authors>) {
611 chomp;
8815788e 612 next unless /^(\S+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
eeb0abe0 613 my ($user, $name, $email) = ($1, $2, $3);
f8c9d1d2
EW
614 if ($log) {
615 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
616 } else {
617 $users{$user} = [$name, $email];
618 }
79bb8d88
EW
619 }
620 close $authors or croak $!;
621}
622
e0d10e1c 623# convert GetOpt::Long specs for use by git-config
b8c92cad 624sub read_repo_config {
706587fc 625 return unless -d $ENV{GIT_DIR};
b8c92cad
EW
626 my $opts = shift;
627 foreach my $o (keys %$opts) {
628 my $v = $opts->{$o};
629 my ($key) = ($o =~ /^([a-z\-]+)/);
630 $key =~ s/-//g;
e0d10e1c 631 my $arg = 'git-config';
b8c92cad
EW
632 $arg .= ' --int' if ($o =~ /[:=]i$/);
633 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
634 if (ref $v eq 'ARRAY') {
635 chomp(my @tmp = `$arg --get-all svn.$key`);
636 @$v = @tmp if @tmp;
637 } else {
638 chomp(my $tmp = `$arg --get svn.$key`);
7774284a 639 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
b8c92cad
EW
640 $$v = $tmp;
641 }
642 }
643 }
644}
645
79bb8d88 646sub extract_metadata {
c1927a85 647 my $id = shift or return (undef, undef, undef);
79bb8d88
EW
648 my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
649 \s([a-f\d\-]+)$/x);
e70dc780 650 if (!defined $rev || !$uuid || !$url) {
79bb8d88 651 # some of the original repositories I made had
82e5a82f 652 # identifiers like this:
79bb8d88
EW
653 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
654 }
655 return ($url, $rev, $uuid);
656}
657
c1927a85
EW
658sub cmt_metadata {
659 return extract_metadata((grep(/^git-svn-id: /,
aef4e921 660 command(qw/cat-file commit/, shift)))[-1]);
c1927a85
EW
661}
662
663sub get_commit_time {
664 my $cmt = shift;
aef4e921 665 my $fh = command_output_pipe(qw/rev-list --pretty=raw -n1/, $cmt);
c1927a85
EW
666 while (<$fh>) {
667 /^committer\s(?:.+) (\d+) ([\-\+]?\d+)$/ or next;
668 my ($s, $tz) = ($1, $2);
669 if ($tz =~ s/^\+//) {
670 $s += tz_to_s_offset($tz);
671 } elsif ($tz =~ s/^\-//) {
672 $s -= tz_to_s_offset($tz);
673 }
22600a25 674 close $fh;
c1927a85
EW
675 return $s;
676 }
677 die "Can't get commit time for commit: $cmt\n";
678}
679
79bb8d88
EW
680sub tz_to_s_offset {
681 my ($tz) = @_;
682 $tz =~ s/(\d\d)$//;
683 return ($1 * 60) + ($tz * 3600);
684}
685
9b981fc6
EW
686package Git::SVN;
687use strict;
688use warnings;
706587fc 689use vars qw/$default_repo_id/;
9b981fc6
EW
690use Carp qw/croak/;
691use File::Path qw/mkpath/;
692use IPC::Open3;
693
694# properties that we do not log:
695my %SKIP_PROP;
696BEGIN {
697 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
698 svn:special svn:executable
699 svn:entry:committed-rev
700 svn:entry:last-author
701 svn:entry:uuid
702 svn:entry:committed-date/;
703}
704
706587fc
EW
705# we allow dashes, unlike remotes2config.sh
706sub sanitize_remote_name {
707 my ($name) = @_;
708 $name =~ tr/A-Za-z0-9-/./c;
709 $name;
710}
711
9b981fc6 712sub init {
706587fc
EW
713 my ($class, $url, $path, $repo_id, $ref_id) = @_;
714 my $self = _new($class, $repo_id, $ref_id, $path);
715 mkpath([$self->{dir}]);
9b981fc6
EW
716 if (defined $url) {
717 $url =~ s!/+$!!; # strip trailing slash
706587fc
EW
718 my $orig_url = eval {
719 command_oneline('config', '--get',
720 "svn-remote.$repo_id.url")
721 };
722 if ($orig_url) {
723 if ($orig_url ne $url) {
724 die "svn-remote.$repo_id.url already set: ",
725 "$orig_url\nwanted to set to: $url\n";
726 }
727 } else {
728 command_noisy('config',
729 "svn-remote.$repo_id.url", $url);
730 }
731 command_noisy('config', '--add',
732 "svn-remote.$repo_id.fetch",
733 "$path:".$self->refname);
9b981fc6
EW
734 }
735 $self->{url} = $url;
706587fc
EW
736 unless (-f $self->{db_path}) {
737 open my $fh, '>>', $self->{db_path} or croak $!;
738 close $fh or croak $!;
739 }
9b981fc6
EW
740 $self;
741}
742
706587fc
EW
743sub find_ref {
744 my ($ref_id) = @_;
745 foreach (command(qw/config -l/)) {
746 next unless m!^svn-remote\.(.+)\.fetch=
747 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
748 my ($repo_id, $path, $ref) = ($1, $2, $3);
749 if ($ref eq $ref_id) {
750 $path = '' if ($path =~ m#^\./?#);
751 return ($repo_id, $path);
752 }
753 }
754 (undef, undef, undef);
755}
756
9b981fc6 757sub new {
706587fc
EW
758 my ($class, $ref_id, $repo_id, $path) = @_;
759 if (defined $ref_id && !defined $repo_id && !defined $path) {
760 ($repo_id, $path) = find_ref($ref_id);
761 if (!defined $repo_id) {
762 die "Could not find a \"svn-remote.*.fetch\" key ",
763 "in the repository configuration matching: ",
764 "refs/remotes/$ref_id\n";
765 }
766 }
767 my $self = _new($class, $repo_id, $ref_id, $path);
768 $self->{url} = command_oneline('config', '--get',
769 "svn-remote.$repo_id.url") or
770 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
9b981fc6
EW
771 $self;
772}
773
706587fc 774sub refname { "refs/remotes/$_[0]->{ref_id}" }
9b981fc6
EW
775
776sub ra {
777 my ($self) = shift;
778 $self->{ra} ||= Git::SVN::Ra->new($self->{url});
779}
780
781sub copy_remote_ref {
782 my ($self) = @_;
783 my $origin = $::_cp_remote ? $::_cp_remote : 'origin';
784 my $ref = $self->refname;
785 if (command('ls-remote', $origin, $ref)) {
786 command_noisy('fetch', $origin, "$ref:$ref");
787 } elsif ($::_cp_remote && !$::_upgrade) {
788 die "Unable to find remote reference: $ref on $origin\n";
789 }
790}
791
792sub traverse_ignore {
793 my ($self, $fh, $path, $r) = @_;
794 $path =~ s#^/+##g;
795 my ($dirent, undef, $props) = $self->ra->get_dir($path, $r);
796 my $p = $path;
797 $p =~ s#^\Q$self->{ra}->{svn_path}\E/##;
798 print $fh length $p ? "\n# $p\n" : "\n# /\n";
799 if (my $s = $props->{'svn:ignore'}) {
800 $s =~ s/[\r\n]+/\n/g;
801 chomp $s;
802 if (length $p == 0) {
803 $s =~ s#\n#\n/$p#g;
804 print $fh "/$s\n";
805 } else {
806 $s =~ s#\n#\n/$p/#g;
807 print $fh "/$p/$s\n";
808 }
809 }
810 foreach (sort keys %$dirent) {
811 next if $dirent->{$_}->kind != $SVN::Node::dir;
812 $self->traverse_ignore($fh, "$path/$_", $r);
813 }
814}
815
816# returns the newest SVN revision number and newest commit SHA1
817sub last_rev_commit {
818 my ($self) = @_;
819 if (defined $self->{last_rev} && defined $self->{last_commit}) {
820 return ($self->{last_rev}, $self->{last_commit});
821 }
d2866f9e 822 my $c = ::verify_ref($self->refname.'^0');
706587fc 823 if ($c) {
d2866f9e 824 my $rev = (::cmt_metadata($c))[1];
9b981fc6
EW
825 if (defined $rev) {
826 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
827 return ($rev, $c);
828 }
829 }
830 my $offset = -41; # from tail
831 my $rl;
832 open my $fh, '<', $self->{db_path} or
833 croak "$self->{db_path} not readable: $!\n";
834 seek $fh, $offset, 2;
835 $rl = readline $fh;
836 defined $rl or return (undef, undef);
837 chomp $rl;
838 while ($c ne $rl && tell $fh != 0) {
839 $offset -= 41;
840 seek $fh, $offset, 2;
841 $rl = readline $fh;
842 defined $rl or return (undef, undef);
843 chomp $rl;
844 }
845 my $rev = tell $fh;
846 croak $! if ($rev < 0);
847 $rev = ($rev - 41) / 41;
848 close $fh or croak $!;
849 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
850 return ($rev, $c);
851}
852
853sub parse_revision {
854 my ($self, $base) = @_;
855 my $head = $self->ra->get_latest_revnum;
856 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
857 return ($base + 1, $head) if (defined $base);
858 return (0, $head);
859 }
860 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
861 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
862 if ($::_revision =~ /^BASE:(\d+)$/) {
863 return ($base + 1, $1) if (defined $base);
864 return (0, $head);
865 }
866 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
867 die "revision argument: $::_revision not understood by git-svn\n",
868 "Try using the command-line svn client instead\n";
869}
870
871sub tmp_index_do {
872 my ($self, $sub) = @_;
873 my $old_index = $ENV{GIT_INDEX_FILE};
874 $ENV{GIT_INDEX_FILE} = $self->{index};
875 my @ret = &$sub;
876 if ($old_index) {
877 $ENV{GIT_INDEX_FILE} = $old_index;
878 } else {
879 delete $ENV{GIT_INDEX_FILE};
880 }
881 wantarray ? @ret : $ret[0];
882}
883
884sub assert_index_clean {
885 my ($self, $treeish) = @_;
886
887 $self->tmp_index_do(sub {
888 command_noisy('read-tree', $treeish) unless -e $self->{index};
889 my $x = command_oneline('write-tree');
890 my ($y) = (command(qw/cat-file commit/, $treeish) =~
891 /^tree ($::sha1)/mo);
892 if ($y ne $x) {
893 unlink $self->{index} or croak $!;
894 command_noisy('read-tree', $treeish);
895 }
896 $x = command_oneline('write-tree');
897 if ($y ne $x) {
898 ::fatal "trees ($treeish) $y != $x\n",
899 "Something is seriously wrong...\n";
900 }
901 });
902}
903
904sub get_commit_parents {
44320b9e 905 my ($self, $log_entry, @parents) = @_;
9b981fc6
EW
906 my (%seen, @ret, @tmp);
907 # commit parents can be conditionally bound to a particular
908 # svn revision via: "svn_revno=commit_sha1", filter them out here:
909 foreach my $p (@parents) {
910 next unless defined $p;
911 if ($p =~ /^(\d+)=($::sha1_short)$/o) {
44320b9e 912 push @tmp, $2 if $1 == $log_entry->{revision};
9b981fc6
EW
913 } else {
914 push @tmp, $p if $p =~ /^$::sha1_short$/o;
915 }
916 }
d2866f9e 917 if (my $cur = ::verify_ref($self->refname.'^0')) {
9b981fc6
EW
918 push @tmp, $cur;
919 }
44320b9e 920 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
9b981fc6
EW
921 while (my $p = shift @tmp) {
922 next if $seen{$p};
923 $seen{$p} = 1;
924 push @ret, $p;
925 # MAXPARENT is defined to 16 in commit-tree.c:
926 last if @ret >= 16;
927 }
928 if (@tmp) {
44320b9e 929 die "r$log_entry->{revision}: No room for parents:\n\t",
9b981fc6
EW
930 join("\n\t", @tmp), "\n";
931 }
932 @ret;
933}
934
706587fc 935sub full_url {
9b981fc6 936 my ($self) = @_;
706587fc 937 $self->ra->{url} . (length $self->{path} ? '/' . $self->{path} : '');
9b981fc6
EW
938}
939
940sub do_git_commit {
44320b9e
EW
941 my ($self, $log_entry, @parents) = @_;
942 if (my $c = $self->rev_db_get($log_entry->{revision})) {
943 croak "$log_entry->{revision} = $c already exists! ",
9b981fc6
EW
944 "Why are we refetching it?\n";
945 }
1c8443b0
EW
946 my $author = $log_entry->{author};
947 my ($name, $email) = (defined $::users{$author} ? @{$::users{$author}}
948 : ($author, "$author\@".$self->ra->uuid));
9b981fc6
EW
949 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
950 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
44320b9e 951 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
9b981fc6 952
44320b9e 953 my $tree = $log_entry->{tree};
9b981fc6
EW
954 if (!defined $tree) {
955 $tree = $self->tmp_index_do(sub {
956 command_oneline('write-tree') });
957 }
958 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
959
960 my @exec = ('git-commit-tree', $tree);
44320b9e 961 foreach ($self->get_commit_parents($log_entry, @parents)) {
9b981fc6
EW
962 push @exec, '-p', $_;
963 }
964 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
965 or croak $!;
44320b9e 966 print $msg_fh $log_entry->{log} or croak $!;
706587fc 967 print $msg_fh "\ngit-svn-id: ", $self->full_url, '@',
44320b9e
EW
968 $log_entry->{revision}, ' ',
969 $self->ra->uuid, "\n" or croak $!;
9b981fc6
EW
970 $msg_fh->flush == 0 or croak $!;
971 close $msg_fh or croak $!;
972 chomp(my $commit = do { local $/; <$out_fh> });
973 close $out_fh or croak $!;
974 waitpid $pid, 0;
975 croak $? if $?;
976 if ($commit !~ /^$::sha1$/o) {
977 die "Failed to commit, invalid sha1: $commit\n";
978 }
979
980 command_noisy('update-ref',$self->refname, $commit);
44320b9e 981 $self->rev_db_set($log_entry->{revision}, $commit);
9b981fc6 982
44320b9e 983 $self->{last_rev} = $log_entry->{revision};
9b981fc6 984 $self->{last_commit} = $commit;
44320b9e 985 print "r$log_entry->{revision} = $commit\n";
9b981fc6
EW
986 return $commit;
987}
988
989sub do_fetch {
706587fc 990 my ($self, $paths, $rev) = @_;
9b981fc6
EW
991 my $ed = SVN::Git::Fetcher->new($self);
992 my ($last_rev, @parents);
993 if ($self->{last_commit}) {
994 $last_rev = $self->{last_rev};
995 $ed->{c} = $self->{last_commit};
996 @parents = ($self->{last_commit});
997 } else {
998 $last_rev = $rev;
999 }
706587fc
EW
1000 unless ($self->ra->gs_do_update($last_rev, $rev,
1001 $self->{path}, 1, $ed)) {
9b981fc6
EW
1002 die "SVN connection failed somewhere...\n";
1003 }
1004 $self->make_log_entry($rev, \@parents, $ed);
1005}
1006
1007sub write_untracked {
1008 my ($self, $rev, $fh, $untracked) = @_;
1009 my $h;
1010 print $fh "r$rev\n" or croak $!;
1011 $h = $untracked->{empty};
1012 foreach (sort keys %$h) {
1013 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
1014 print $fh " $act: ", uri_encode($_), "\n" or croak $!;
1015 warn "W: $act: $_\n";
1016 }
1017 foreach my $t (qw/dir_prop file_prop/) {
1018 $h = $untracked->{$t} or next;
1019 foreach my $path (sort keys %$h) {
1020 my $ppath = $path eq '' ? '.' : $path;
1021 foreach my $prop (sort keys %{$h->{$path}}) {
1ce255dc 1022 next if $SKIP_PROP{$prop};
9b981fc6
EW
1023 my $v = $h->{$path}->{$prop};
1024 if (defined $v) {
1025 print $fh " +$t: ",
1026 uri_encode($ppath), ' ',
1027 uri_encode($prop), ' ',
1028 uri_encode($v), "\n"
1029 or croak $!;
1030 } else {
1031 print $fh " -$t: ",
1032 uri_encode($ppath), ' ',
1033 uri_encode($prop), "\n"
1034 or croak $!;
1035 }
1036 }
1037 }
1038 }
1039 foreach my $t (qw/absent_file absent_directory/) {
1040 $h = $untracked->{$t} or next;
1041 foreach my $parent (sort keys %$h) {
1042 foreach my $path (sort @{$h->{$parent}}) {
1043 print $fh " $t: ",
1044 uri_encode("$parent/$path"), "\n"
1045 or croak $!;
1046 warn "W: $t: $parent/$path ",
1047 "Insufficient permissions?\n";
1048 }
1049 }
1050 }
1051}
1052
1c8443b0
EW
1053sub parse_svn_date {
1054 my $date = shift || return '+0000 1970-01-01 00:00:00';
1055 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1056 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
1057 croak "Unable to parse date: $date\n";
1058 "+0000 $Y-$m-$d $H:$M:$S";
1059}
1060
1061sub check_author {
1062 my ($author) = @_;
1063 if (!defined $author || length $author == 0) {
1064 $author = '(no author)';
1065 }
1066 if (defined $::_authors && ! defined $::users{$author}) {
1067 die "Author: $author not defined in $::_authors file\n";
1068 }
1069 $author;
1070}
1071
9b981fc6
EW
1072sub make_log_entry {
1073 my ($self, $rev, $parents, $untracked) = @_;
1074 my $rp = $self->ra->rev_proplist($rev);
1075 my %log_entry = ( parents => $parents || [], revision => $rev,
1076 revprops => $rp, log => '');
1077 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
1078 $self->write_untracked($rev, $un, $untracked);
1079 foreach (sort keys %$rp) {
1080 my $v = $rp->{$_};
1081 if (/^svn:(author|date|log)$/) {
1082 $log_entry{$1} = $v;
1083 } else {
1084 print $un " rev_prop: ", uri_encode($_), ' ',
1085 uri_encode($v), "\n";
1086 }
1087 }
1088 close $un or croak $!;
1089 $log_entry{date} = parse_svn_date($log_entry{date});
1090 $log_entry{author} = check_author($log_entry{author});
1091 $log_entry{log} .= "\n";
1092 \%log_entry;
1093}
1094
1095sub fetch {
1096 my ($self, @parents) = @_;
1097 my ($last_rev, $last_commit) = $self->last_rev_commit;
1098 my ($base, $head) = $self->parse_revision($last_rev);
1099 return if ($base > $head);
1100 if (defined $last_commit) {
1101 $self->assert_index_clean($last_commit);
1102 }
1103 my $inc = 1000;
1104 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
1105 my $err_handler = $SVN::Error::handler;
1106 $SVN::Error::handler = \&skip_unknown_revs;
1107 while (1) {
1108 my @revs;
1109 $self->ra->get_log([''], $min, $max, 0, 1, 1, sub {
44320b9e 1110 my ($paths, $rev, $author, $date, $log) = @_;
9b981fc6
EW
1111 push @revs, $rev });
1112 foreach (@revs) {
1113 my $log_entry = $self->do_fetch(undef, $_);
1114 $self->do_git_commit($log_entry, @parents);
1115 }
1116 last if $max >= $head;
1117 $min = $max + 1;
1118 $max += $inc;
1119 $max = $head if ($max > $head);
1120 }
1121 $SVN::Error::handler = $err_handler;
1122}
1123
1124sub set_tree_cb {
1125 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
1126 # TODO: enable and test optimized commits:
1127 if (0 && $rev == ($self->{last_rev} + 1)) {
1128 $log_entry->{revision} = $rev;
1129 $log_entry->{author} = $author;
1130 $self->do_git_commit($log_entry, "$rev=$tree");
1131 } else {
1132 $self->fetch("$rev=$tree");
1133 }
1134}
1135
1136sub set_tree {
1137 my ($self, $tree) = (shift, shift);
1ce255dc 1138 my $log_entry = ::get_commit_entry($tree);
9b981fc6
EW
1139 unless ($self->{last_rev}) {
1140 fatal("Must have an existing revision to commit\n");
1141 }
1142 my $pool = SVN::Pool->new;
1143 my $ed = SVN::Git::Editor->new({ r => $self->{last_rev},
1144 ra => $self->ra->dup,
9b981fc6
EW
1145 svn_path => $self->ra->{svn_path}
1146 },
1147 $self->ra->get_commit_editor(
1148 $log_entry->{log}, sub {
1149 $self->set_tree_cb($log_entry,
1150 $tree, @_);
1151 }),
1152 $pool);
1153 my $mods = $ed->apply_diff($self->{last_commit}, $tree);
1154 if (@$mods == 0) {
1155 print "No changes\nr$self->{last_rev} = $tree\n";
1156 }
1157 $pool->clear;
1158}
1159
1160sub skip_unknown_revs {
1161 my ($err) = @_;
1162 my $errno = $err->apr_err();
1163 # Maybe the branch we're tracking didn't
1164 # exist when the repo started, so it's
1165 # not an error if it doesn't, just continue
1166 #
1167 # Wonderfully consistent library, eh?
1168 # 160013 - svn:// and file://
1169 # 175002 - http(s)://
1170 # 175007 - http(s):// (this repo required authorization, too...)
1171 # More codes may be discovered later...
1172 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
1173 return;
1174 }
1175 croak "Error from SVN, ($errno): ", $err->expanded_message,"\n";
1176}
1177
1178# rev_db:
1179# Tie::File seems to be prone to offset errors if revisions get sparse,
1180# it's not that fast, either. Tie::File is also not in Perl 5.6. So
1181# one of my favorite modules is out :< Next up would be one of the DBM
1182# modules, but I'm not sure which is most portable... So I'll just
1183# go with something that's plain-text, but still capable of
1184# being randomly accessed. So here's my ultra-simple fixed-width
1185# database. All records are 40 characters + "\n", so it's easy to seek
1186# to a revision: (41 * rev) is the byte offset.
1187# A record of 40 0s denotes an empty revision.
1188# And yes, it's still pretty fast (faster than Tie::File).
1189
1190sub rev_db_set {
1191 my ($self, $rev, $commit) = @_;
1192 length $commit == 40 or croak "arg3 must be a full SHA1 hexsum\n";
1193 open my $fh, '+<', $self->{db_path} or croak $!;
1194 my $offset = $rev * 41;
1195 # assume that append is the common case:
1196 seek $fh, 0, 2 or croak $!;
1197 my $pos = tell $fh;
1198 if ($pos < $offset) {
1199 print $fh (('0' x 40),"\n") x (($offset - $pos) / 41)
1200 or croak $!;
1201 }
1202 seek $fh, $offset, 0 or croak $!;
1203 print $fh $commit,"\n" or croak $!;
1204 close $fh or croak $!;
1205}
1206
1207sub rev_db_get {
1208 my ($self, $rev) = @_;
1209 my $ret;
1210 my $offset = $rev * 41;
1211 open my $fh, '<', $self->{db_path} or croak $!;
1212 if (seek $fh, $offset, 0) {
1213 $ret = readline $fh;
1214 if (defined $ret) {
1215 chomp $ret;
1216 $ret = undef if ($ret =~ /^0{40}$/);
1217 }
1218 }
1219 close $fh or croak $!;
1220 $ret;
1221}
1222
1223sub _new {
706587fc
EW
1224 my ($class, $repo_id, $ref_id, $path) = @_;
1225 unless (defined $repo_id && length $repo_id) {
1226 $repo_id = $Git::SVN::default_repo_id;
1227 }
1228 unless (defined $ref_id && length $ref_id) {
1229 $_[2] = $ref_id = $repo_id;
1230 }
1231 $_[1] = $repo_id = sanitize_remote_name($repo_id);
1232 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
1233 $_[3] = $path = '' unless (defined $path);
1234 bless { ref_id => $ref_id, dir => $dir, index => "$dir/index",
1235 path => $path,
1236 db_path => "$dir/.rev_db", repo_id => $repo_id }, $class;
9b981fc6
EW
1237}
1238
1c8443b0
EW
1239sub uri_encode {
1240 my ($f) = @_;
1241 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
1242 $f
1243}
9b981fc6 1244
d976acfd
EW
1245package Git::SVN::Prompt;
1246use strict;
1247use warnings;
1248require SVN::Core;
1249use vars qw/$_no_auth_cache $_username/;
1250
1251sub simple {
30d055aa
EW
1252 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
1253 $may_save = undef if $_no_auth_cache;
1254 $default_username = $_username if defined $_username;
1255 if (defined $default_username && length $default_username) {
1256 if (defined $realm && length $realm) {
6f729591
EW
1257 print STDERR "Authentication realm: $realm\n";
1258 STDERR->flush;
30d055aa
EW
1259 }
1260 $cred->username($default_username);
1261 } else {
d976acfd 1262 username($cred, $realm, $may_save, $pool);
30d055aa
EW
1263 }
1264 $cred->password(_read_password("Password for '" .
1265 $cred->username . "': ", $realm));
1266 $cred->may_save($may_save);
1267 $SVN::_Core::SVN_NO_ERROR;
1268}
1269
d976acfd 1270sub ssl_server_trust {
30d055aa
EW
1271 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
1272 $may_save = undef if $_no_auth_cache;
6f729591 1273 print STDERR "Error validating server certificate for '$realm':\n";
30d055aa 1274 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
6f729591 1275 print STDERR " - The certificate is not issued by a trusted ",
30d055aa
EW
1276 "authority. Use the\n",
1277 " fingerprint to validate the certificate manually!\n";
1278 }
1279 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
6f729591 1280 print STDERR " - The certificate hostname does not match.\n";
30d055aa
EW
1281 }
1282 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
6f729591 1283 print STDERR " - The certificate is not yet valid.\n";
30d055aa
EW
1284 }
1285 if ($failures & $SVN::Auth::SSL::EXPIRED) {
6f729591 1286 print STDERR " - The certificate has expired.\n";
30d055aa
EW
1287 }
1288 if ($failures & $SVN::Auth::SSL::OTHER) {
6f729591 1289 print STDERR " - The certificate has an unknown error.\n";
30d055aa 1290 }
6f729591
EW
1291 printf STDERR
1292 "Certificate information:\n".
30d055aa
EW
1293 " - Hostname: %s\n".
1294 " - Valid: from %s until %s\n".
1295 " - Issuer: %s\n".
1296 " - Fingerprint: %s\n",
1297 map $cert_info->$_, qw(hostname valid_from valid_until
6f729591 1298 issuer_dname fingerprint);
30d055aa
EW
1299 my $choice;
1300prompt:
6f729591 1301 print STDERR $may_save ?
30d055aa
EW
1302 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
1303 "(R)eject or accept (t)emporarily? ";
6f729591 1304 STDERR->flush;
30d055aa
EW
1305 $choice = lc(substr(<STDIN> || 'R', 0, 1));
1306 if ($choice =~ /^t$/i) {
1307 $cred->may_save(undef);
1308 } elsif ($choice =~ /^r$/i) {
1309 return -1;
1310 } elsif ($may_save && $choice =~ /^p$/i) {
1311 $cred->may_save($may_save);
1312 } else {
1313 goto prompt;
1314 }
1315 $cred->accepted_failures($failures);
1316 $SVN::_Core::SVN_NO_ERROR;
1317}
1318
d976acfd 1319sub ssl_client_cert {
30d055aa
EW
1320 my ($cred, $realm, $may_save, $pool) = @_;
1321 $may_save = undef if $_no_auth_cache;
6f729591
EW
1322 print STDERR "Client certificate filename: ";
1323 STDERR->flush;
30d055aa
EW
1324 chomp(my $filename = <STDIN>);
1325 $cred->cert_file($filename);
1326 $cred->may_save($may_save);
1327 $SVN::_Core::SVN_NO_ERROR;
1328}
1329
d976acfd 1330sub ssl_client_cert_pw {
30d055aa
EW
1331 my ($cred, $realm, $may_save, $pool) = @_;
1332 $may_save = undef if $_no_auth_cache;
1333 $cred->password(_read_password("Password: ", $realm));
1334 $cred->may_save($may_save);
1335 $SVN::_Core::SVN_NO_ERROR;
1336}
1337
d976acfd 1338sub username {
30d055aa
EW
1339 my ($cred, $realm, $may_save, $pool) = @_;
1340 $may_save = undef if $_no_auth_cache;
1341 if (defined $realm && length $realm) {
6f729591 1342 print STDERR "Authentication realm: $realm\n";
30d055aa
EW
1343 }
1344 my $username;
1345 if (defined $_username) {
1346 $username = $_username;
1347 } else {
6f729591
EW
1348 print STDERR "Username: ";
1349 STDERR->flush;
30d055aa
EW
1350 chomp($username = <STDIN>);
1351 }
1352 $cred->username($username);
1353 $cred->may_save($may_save);
1354 $SVN::_Core::SVN_NO_ERROR;
1355}
1356
1357sub _read_password {
1358 my ($prompt, $realm) = @_;
6f729591
EW
1359 print STDERR $prompt;
1360 STDERR->flush;
30d055aa
EW
1361 require Term::ReadKey;
1362 Term::ReadKey::ReadMode('noecho');
1363 my $password = '';
1364 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
1365 last if $key =~ /[\012\015]/; # \n\r
1366 $password .= $key;
1367 }
1368 Term::ReadKey::ReadMode('restore');
6f729591
EW
1369 print STDERR "\n";
1370 STDERR->flush;
30d055aa
EW
1371 $password;
1372}
1373
d976acfd
EW
1374package main;
1375
d2a9a87b
EW
1376sub uri_encode {
1377 my ($f) = @_;
1378 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
1379 $f
1380}
1381
1382sub uri_decode {
1383 my ($f) = @_;
1384 $f =~ tr/+/ /;
1385 $f =~ s/%([A-F0-9]{2})/chr hex($1)/ge;
1386 $f
1387}
1388
42d32870
EW
1389sub revisions_eq {
1390 my ($path, $r0, $r1) = @_;
1391 return 1 if $r0 == $r1;
1392 my $nr = 0;
b9c85187 1393 # should be OK to use Pool here (r1 - r0) should be small
d81bf827 1394 $SVN->get_log([$path], $r0, $r1, 0, 0, 1, sub {$nr++});
42d32870
EW
1395 return 0 if ($nr > 1);
1396 return 1;
1397}
1398
1399sub libsvn_find_parent_branch {
44320b9e 1400 my ($paths, $rev, $author, $date, $log) = @_;
747fa12c 1401 my $svn_path = '/'.$SVN->{svn_path};
a5e0cedc
EW
1402
1403 # look for a parent from another branch:
cf7424b0
EW
1404 my $i = $paths->{$svn_path} or return;
1405 my $branch_from = $i->copyfrom_path or return;
1406 my $r = $i->copyfrom_rev;
1407 print STDERR "Found possible branch point: ",
1408 "$branch_from => $svn_path, $r\n";
1409 $branch_from =~ s#^/##;
a00439ac
EW
1410 my $l_map = {};
1411 read_url_paths_all($l_map, '', "$GIT_DIR/svn");
747fa12c 1412 my $url = $SVN->{repos_root};
cf7424b0 1413 defined $l_map->{$url} or return;
a00439ac
EW
1414 my $id = $l_map->{$url}->{$branch_from};
1415 if (!defined $id && $_follow_parent) {
1416 print STDERR "Following parent: $branch_from\@$r\n";
1417 # auto create a new branch and follow it
1418 $id = basename($branch_from);
1419 $id .= '@'.$r if -r "$GIT_DIR/svn/$id";
1420 while (-r "$GIT_DIR/svn/$id") {
1421 # just grow a tail if we're not unique enough :x
1422 $id .= '-';
1423 }
1424 }
1425 return unless defined $id;
1426
cf7424b0 1427 my ($r0, $parent) = find_rev_before($r,$id,1);
a00439ac
EW
1428 if ($_follow_parent && (!defined $r0 || !defined $parent)) {
1429 defined(my $pid = fork) or croak $!;
1430 if (!$pid) {
1431 $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
1432 init_vars();
1433 $SVN_URL = "$url/$branch_from";
747fa12c 1434 $SVN = undef;
a00439ac
EW
1435 setup_git_svn();
1436 # we can't assume SVN_URL exists at r+1:
1437 $_revision = "0:$r";
1438 fetch_lib();
1439 exit 0;
1440 }
1441 waitpid $pid, 0;
1442 croak $? if $?;
1443 ($r0, $parent) = find_rev_before($r,$id,1);
1444 }
cf7424b0
EW
1445 return unless (defined $r0 && defined $parent);
1446 if (revisions_eq($branch_from, $r0, $r)) {
1447 unlink $GIT_SVN_INDEX;
a00439ac 1448 print STDERR "Found branch parent: ($GIT_SVN) $parent\n";
aef4e921 1449 command_noisy('read-tree', $parent);
d81bf827 1450 unless ($SVN->can_do_switch) {
ed92f170 1451 return _libsvn_new_tree($paths, $rev, $author, $date,
44320b9e 1452 $log, [$parent]);
a552db3a
EW
1453 }
1454 # do_switch works with svn/trunk >= r22312, but that is not
1455 # included with SVN 1.4.2 (the latest version at the moment),
1456 # so we can't rely on it.
d81bf827 1457 my $ra = Git::SVN::Ra->new("$url/$branch_from");
aef4e921 1458 my $ed = SVN::Git::Fetcher->new({c => $parent, q => $_q });
d81bf827
EW
1459 $ra->gs_do_switch($r0, $rev, '', 1, $SVN->{url}, $ed) or
1460 die "SVN connection failed somewhere...\n";
44320b9e 1461 return libsvn_log_entry($rev, $author, $date, $log, [$parent]);
cf7424b0
EW
1462 }
1463 print STDERR "Nope, branch point not imported or unknown\n";
42d32870
EW
1464 return undef;
1465}
1466
ed92f170 1467sub _libsvn_new_tree {
44320b9e 1468 my ($paths, $rev, $author, $date, $log, $parents) = @_;
ed92f170 1469 my $ed = SVN::Git::Fetcher->new({q => $_q});
d81bf827 1470 unless ($SVN->gs_do_update($rev, $rev, '', 1, $ed)) {
ed92f170 1471 die "SVN connection failed somewhere...\n";
27a1a801 1472 }
44320b9e 1473 libsvn_log_entry($rev, $author, $date, $log, $parents, $ed);
a5e0cedc
EW
1474}
1475
b9c85187
EW
1476{
1477 my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
1478 $SVN::Node::dir.$SVN::Node::unknown.
1479 $SVN::Node::none.$SVN::Node::file.
1480 $SVN::Node::dir.$SVN::Node::unknown.
1481 $SVN::Auth::SSL::CNMISMATCH.
1482 $SVN::Auth::SSL::NOTYETVALID.
1483 $SVN::Auth::SSL::EXPIRED.
1484 $SVN::Auth::SSL::UNKNOWNCA.
1485 $SVN::Auth::SSL::OTHER;
1486}
1487
27a1a801
EW
1488package SVN::Git::Fetcher;
1489use vars qw/@ISA/;
1490use strict;
1491use warnings;
1492use Carp qw/croak/;
1493use IO::File qw//;
1494
1495# file baton members: path, mode_a, mode_b, pool, fh, blob, base
1496sub new {
1497 my ($class, $git_svn) = @_;
1498 my $self = SVN::Delta::Editor->new;
1499 bless $self, $class;
1c8443b0 1500 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
706587fc
EW
1501 if (length $git_svn->{path}) {
1502 $self->{path_strip} = qr/\Q$git_svn->{path}\E\/?/;
1503 }
d2a9a87b
EW
1504 $self->{empty} = {};
1505 $self->{dir_prop} = {};
1506 $self->{file_prop} = {};
1507 $self->{absent_dir} = {};
1508 $self->{absent_file} = {};
1c8443b0
EW
1509 ($self->{gui}, $self->{ctx}) = $git_svn->tmp_index_do(
1510 sub { command_input_pipe(qw/update-index -z --index-info/) } );
27a1a801
EW
1511 require Digest::MD5;
1512 $self;
1513}
1514
d2a9a87b
EW
1515sub open_root {
1516 { path => '' };
1517}
1518
1519sub open_directory {
1520 my ($self, $path, $pb, $rev) = @_;
1521 { path => $path };
1522}
1523
706587fc
EW
1524sub git_path {
1525 my ($self, $path) = @_;
1526 $path =~ s!$self->{path_strip}!! if $self->{path_strip};
1527 $path;
1528}
1529
27a1a801
EW
1530sub delete_entry {
1531 my ($self, $path, $rev, $pb) = @_;
4a87db0e
EW
1532 my $gui = $self->{gui};
1533
706587fc 1534 my $gpath = $self->git_path($path);
4a87db0e 1535 # remove entire directories.
706587fc 1536 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
4a87db0e
EW
1537 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
1538 -r --name-only -z/,
706587fc 1539 $self->{c}, '--', $gpath);
4a87db0e
EW
1540 local $/ = "\0";
1541 while (<$ls>) {
1542 print $gui '0 ',0 x 40,"\t",$_ or croak $!;
1543 print "\tD\t$_\n" unless $self->{q};
1544 }
706587fc 1545 print "\tD\t$gpath/\n" unless $self->{q};
4a87db0e
EW
1546 command_close_pipe($ls, $ctx);
1547 $self->{empty}->{$path} = 0
1548 } else {
706587fc
EW
1549 print $gui '0 ',0 x 40,"\t",$gpath,"\0" or croak $!;
1550 print "\tD\t$gpath\n" unless $self->{q};
4a87db0e 1551 }
27a1a801
EW
1552 undef;
1553}
1554
1555sub open_file {
1556 my ($self, $path, $pb, $rev) = @_;
706587fc
EW
1557 my $gpath = $self->git_path($path);
1558 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
27a1a801 1559 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
006ede5e
EW
1560 unless (defined $mode && defined $blob) {
1561 die "$path was not found in commit $self->{c} (r$rev)\n";
1562 }
27a1a801 1563 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
0864e3ba 1564 pool => SVN::Pool->new, action => 'M' };
27a1a801
EW
1565}
1566
1567sub add_file {
1568 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
d2a9a87b
EW
1569 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
1570 delete $self->{empty}->{$dir};
27a1a801 1571 { path => $path, mode_a => 100644, mode_b => 100644,
0864e3ba 1572 pool => SVN::Pool->new, action => 'A' };
27a1a801
EW
1573}
1574
d2a9a87b
EW
1575sub add_directory {
1576 my ($self, $path, $cp_path, $cp_rev) = @_;
1577 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
1578 delete $self->{empty}->{$dir};
1579 $self->{empty}->{$path} = 1;
1580 { path => $path };
1581}
1582
1583sub change_dir_prop {
1584 my ($self, $db, $prop, $value) = @_;
1585 $self->{dir_prop}->{$db->{path}} ||= {};
1586 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
1587 undef;
1588}
1589
1590sub absent_directory {
1591 my ($self, $path, $pb) = @_;
1592 $self->{absent_dir}->{$pb->{path}} ||= [];
1593 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
1594 undef;
1595}
1596
1597sub absent_file {
1598 my ($self, $path, $pb) = @_;
1599 $self->{absent_file}->{$pb->{path}} ||= [];
1600 push @{$self->{absent_file}->{$pb->{path}}}, $path;
1601 undef;
1602}
1603
27a1a801
EW
1604sub change_file_prop {
1605 my ($self, $fb, $prop, $value) = @_;
1606 if ($prop eq 'svn:executable') {
1607 if ($fb->{mode_b} != 120000) {
1608 $fb->{mode_b} = defined $value ? 100755 : 100644;
1609 }
1610 } elsif ($prop eq 'svn:special') {
1611 $fb->{mode_b} = defined $value ? 120000 : 100644;
d2a9a87b
EW
1612 } else {
1613 $self->{file_prop}->{$fb->{path}} ||= {};
1614 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
27a1a801
EW
1615 }
1616 undef;
1617}
1618
1619sub apply_textdelta {
1620 my ($self, $fb, $exp) = @_;
1621 my $fh = IO::File->new_tmpfile;
1622 $fh->autoflush(1);
1623 # $fh gets auto-closed() by SVN::TxDelta::apply(),
1624 # (but $base does not,) so dup() it for reading in close_file
1625 open my $dup, '<&', $fh or croak $!;
1626 my $base = IO::File->new_tmpfile;
1627 $base->autoflush(1);
1628 if ($fb->{blob}) {
1629 defined (my $pid = fork) or croak $!;
1630 if (!$pid) {
1631 open STDOUT, '>&', $base or croak $!;
1632 print STDOUT 'link ' if ($fb->{mode_a} == 120000);
1633 exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
1634 }
1635 waitpid $pid, 0;
1636 croak $? if $?;
1637
1638 if (defined $exp) {
1639 seek $base, 0, 0 or croak $!;
1640 my $md5 = Digest::MD5->new;
1641 $md5->addfile($base);
1642 my $got = $md5->hexdigest;
1643 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
1644 "expected: $exp\n",
1645 " got: $got\n" if ($got ne $exp);
1646 }
1647 }
1648 seek $base, 0, 0 or croak $!;
1649 $fb->{fh} = $dup;
1650 $fb->{base} = $base;
1651 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
1652}
1653
1654sub close_file {
1655 my ($self, $fb, $exp) = @_;
1656 my $hash;
706587fc 1657 my $path = $self->git_path($fb->{path});
27a1a801
EW
1658 if (my $fh = $fb->{fh}) {
1659 seek($fh, 0, 0) or croak $!;
1660 my $md5 = Digest::MD5->new;
1661 $md5->addfile($fh);
1662 my $got = $md5->hexdigest;
1663 die "Checksum mismatch: $path\n",
1664 "expected: $exp\n got: $got\n" if ($got ne $exp);
1665 seek($fh, 0, 0) or croak $!;
1666 if ($fb->{mode_b} == 120000) {
1667 read($fh, my $buf, 5) == 5 or croak $!;
1668 $buf eq 'link ' or die "$path has mode 120000",
1669 "but is not a link\n";
1670 }
1671 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
1672 if (!$pid) {
1673 open STDIN, '<&', $fh or croak $!;
1674 exec qw/git-hash-object -w --stdin/ or croak $!;
1675 }
1676 chomp($hash = do { local $/; <$out> });
1677 close $out or croak $!;
1678 close $fh or croak $!;
1679 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
1680 close $fb->{base} or croak $!;
1681 } else {
1682 $hash = $fb->{blob} or die "no blob information\n";
1683 }
1684 $fb->{pool}->clear;
1685 my $gui = $self->{gui};
1686 print $gui "$fb->{mode_b} $hash\t$path\0" or croak $!;
0864e3ba 1687 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $self->{q};
27a1a801
EW
1688 undef;
1689}
1690
1691sub abort_edit {
1692 my $self = shift;
aef4e921 1693 eval { command_close_pipe($self->{gui}, $self->{ctx}) };
27a1a801
EW
1694 $self->SUPER::abort_edit(@_);
1695}
1696
1697sub close_edit {
1698 my $self = shift;
aef4e921 1699 command_close_pipe($self->{gui}, $self->{ctx});
dad73c0b 1700 $self->{git_commit_ok} = 1;
27a1a801
EW
1701 $self->SUPER::close_edit(@_);
1702}
1a82e793 1703
a5e0cedc
EW
1704package SVN::Git::Editor;
1705use vars qw/@ISA/;
1706use strict;
1707use warnings;
1708use Carp qw/croak/;
1709use IO::File;
1710
1711sub new {
1712 my $class = shift;
1713 my $git_svn = shift;
1714 my $self = SVN::Delta::Editor->new(@_);
1715 bless $self, $class;
44320b9e 1716 foreach (qw/svn_path r ra/) {
a5e0cedc
EW
1717 die "$_ required!\n" unless (defined $git_svn->{$_});
1718 $self->{$_} = $git_svn->{$_};
1719 }
1720 $self->{pool} = SVN::Pool->new;
1721 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
1722 $self->{rm} = { };
1723 require Digest::MD5;
1724 return $self;
1725}
1726
1727sub split_path {
1728 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
1729}
1730
1731sub repo_path {
747fa12c 1732 (defined $_[1] && length $_[1]) ? $_[1] : ''
a5e0cedc
EW
1733}
1734
1735sub url_path {
1736 my ($self, $path) = @_;
1737 $self->{ra}->{url} . '/' . $self->repo_path($path);
1738}
1739
1740sub rmdirs {
44320b9e 1741 my ($self, $tree_b) = @_;
a5e0cedc
EW
1742 my $rm = $self->{rm};
1743 delete $rm->{''}; # we never delete the url we're tracking
1744 return unless %$rm;
1745
1746 foreach (keys %$rm) {
1747 my @d = split m#/#, $_;
1748 my $c = shift @d;
1749 $rm->{$c} = 1;
1750 while (@d) {
1751 $c .= '/' . shift @d;
1752 $rm->{$c} = 1;
1753 }
1754 }
1755 delete $rm->{$self->{svn_path}};
1756 delete $rm->{''}; # we never delete the url we're tracking
1757 return unless %$rm;
1758
aef4e921 1759 my ($fh, $ctx) = command_output_pipe(
44320b9e 1760 qw/ls-tree --name-only -r -z/, $tree_b);
a5e0cedc
EW
1761 local $/ = "\0";
1762 while (<$fh>) {
1763 chomp;
747fa12c 1764 my @dn = split m#/#, $_;
c07eee1f
EW
1765 while (pop @dn) {
1766 delete $rm->{join '/', @dn};
1767 }
1768 unless (%$rm) {
22600a25 1769 close $fh;
c07eee1f
EW
1770 return;
1771 }
a5e0cedc 1772 }
aef4e921 1773 command_close_pipe($fh, $ctx);
c07eee1f 1774
a5e0cedc
EW
1775 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
1776 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
1777 $self->close_directory($bat->{$d}, $p);
1778 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
44320b9e 1779 print "\tD+\t$d/\n" unless $::_q;
a5e0cedc
EW
1780 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
1781 delete $bat->{$d};
1782 }
1783}
1784
1785sub open_or_add_dir {
1786 my ($self, $full_path, $baton) = @_;
d81bf827 1787 my $t = $self->{ra}->check_path($full_path, $self->{r});
a5e0cedc
EW
1788 if ($t == $SVN::Node::none) {
1789 return $self->add_directory($full_path, $baton,
1790 undef, -1, $self->{pool});
1791 } elsif ($t == $SVN::Node::dir) {
1792 return $self->open_directory($full_path, $baton,
1793 $self->{r}, $self->{pool});
1794 }
1795 print STDERR "$full_path already exists in repository at ",
1796 "r$self->{r} and it is not a directory (",
1797 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
1798 exit 1;
1799}
1800
1801sub ensure_path {
1802 my ($self, $path) = @_;
1803 my $bat = $self->{bat};
1804 $path = $self->repo_path($path);
1805 return $bat->{''} unless (length $path);
1806 my @p = split m#/+#, $path;
1807 my $c = shift @p;
1808 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
1809 while (@p) {
1810 my $c0 = $c;
1811 $c .= '/' . shift @p;
1812 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
1813 }
1814 return $bat->{$c};
1815}
1816
1817sub A {
44320b9e 1818 my ($self, $m) = @_;
a5e0cedc
EW
1819 my ($dir, $file) = split_path($m->{file_b});
1820 my $pbat = $self->ensure_path($dir);
1821 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
1822 undef, -1);
44320b9e 1823 print "\tA\t$m->{file_b}\n" unless $::_q;
a5e0cedc
EW
1824 $self->chg_file($fbat, $m);
1825 $self->close_file($fbat,undef,$self->{pool});
1826}
1827
1828sub C {
44320b9e 1829 my ($self, $m) = @_;
a5e0cedc
EW
1830 my ($dir, $file) = split_path($m->{file_b});
1831 my $pbat = $self->ensure_path($dir);
1832 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
1833 $self->url_path($m->{file_a}), $self->{r});
44320b9e 1834 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
a5e0cedc
EW
1835 $self->chg_file($fbat, $m);
1836 $self->close_file($fbat,undef,$self->{pool});
1837}
1838
1839sub delete_entry {
1840 my ($self, $path, $pbat) = @_;
1841 my $rpath = $self->repo_path($path);
1842 my ($dir, $file) = split_path($rpath);
1843 $self->{rm}->{$dir} = 1;
1844 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
1845}
1846
1847sub R {
44320b9e 1848 my ($self, $m) = @_;
a5e0cedc
EW
1849 my ($dir, $file) = split_path($m->{file_b});
1850 my $pbat = $self->ensure_path($dir);
1851 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
1852 $self->url_path($m->{file_a}), $self->{r});
44320b9e 1853 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
a5e0cedc
EW
1854 $self->chg_file($fbat, $m);
1855 $self->close_file($fbat,undef,$self->{pool});
1856
1857 ($dir, $file) = split_path($m->{file_a});
1858 $pbat = $self->ensure_path($dir);
1859 $self->delete_entry($m->{file_a}, $pbat);
1860}
1861
1862sub M {
44320b9e 1863 my ($self, $m) = @_;
a5e0cedc
EW
1864 my ($dir, $file) = split_path($m->{file_b});
1865 my $pbat = $self->ensure_path($dir);
1866 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
1867 $pbat,$self->{r},$self->{pool});
44320b9e 1868 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
a5e0cedc
EW
1869 $self->chg_file($fbat, $m);
1870 $self->close_file($fbat,undef,$self->{pool});
1871}
1872
1873sub T { shift->M(@_) }
1874
1875sub change_file_prop {
1876 my ($self, $fbat, $pname, $pval) = @_;
1877 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
1878}
1879
1880sub chg_file {
1881 my ($self, $fbat, $m) = @_;
1882 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
1883 $self->change_file_prop($fbat,'svn:executable','*');
1884 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
1885 $self->change_file_prop($fbat,'svn:executable',undef);
1886 }
1887 my $fh = IO::File->new_tmpfile or croak $!;
1888 if ($m->{mode_b} =~ /^120/) {
1889 print $fh 'link ' or croak $!;
1890 $self->change_file_prop($fbat,'svn:special','*');
1891 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
1892 $self->change_file_prop($fbat,'svn:special',undef);
1893 }
1894 defined(my $pid = fork) or croak $!;
1895 if (!$pid) {
1896 open STDOUT, '>&', $fh or croak $!;
1897 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
1898 }
1899 waitpid $pid, 0;
1900 croak $? if $?;
1901 $fh->flush == 0 or croak $!;
1902 seek $fh, 0, 0 or croak $!;
1903
1904 my $md5 = Digest::MD5->new;
1905 $md5->addfile($fh) or croak $!;
1906 seek $fh, 0, 0 or croak $!;
1907
1908 my $exp = $md5->hexdigest;
f7197dff
EW
1909 my $pool = SVN::Pool->new;
1910 my $atd = $self->apply_textdelta($fbat, undef, $pool);
1911 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
a5e0cedc 1912 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
f7197dff 1913 $pool->clear;
a5e0cedc
EW
1914
1915 close $fh or croak $!;
1916}
1917
1918sub D {
44320b9e 1919 my ($self, $m) = @_;
a5e0cedc
EW
1920 my ($dir, $file) = split_path($m->{file_b});
1921 my $pbat = $self->ensure_path($dir);
44320b9e 1922 print "\tD\t$m->{file_b}\n" unless $::_q;
a5e0cedc
EW
1923 $self->delete_entry($m->{file_b}, $pbat);
1924}
1925
1926sub close_edit {
1927 my ($self) = @_;
1928 my ($p,$bat) = ($self->{pool}, $self->{bat});
1929 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
1930 $self->close_directory($bat->{$_}, $p);
1931 }
1932 $self->SUPER::close_edit($p);
1933 $p->clear;
1934}
1935
1936sub abort_edit {
1937 my ($self) = @_;
1938 $self->SUPER::abort_edit($self->{pool});
1939 $self->{pool}->clear;
1940}
1941
44320b9e
EW
1942# this drives the editor
1943sub apply_diff {
1944 my ($self, $tree_a, $tree_b) = @_;
1945 my @diff_tree = qw(diff-tree -z -r);
1946 if ($::_cp_similarity) {
1947 push @diff_tree, "-C$::_cp_similarity";
1948 } else {
1949 push @diff_tree, '-C';
1950 }
1951 push @diff_tree, '--find-copies-harder' if $::_find_copies_harder;
1952 push @diff_tree, "-l$::_l" if defined $::_l;
1953 push @diff_tree, $tree_a, $tree_b;
1954 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
1955 my $nl = $/;
1956 local $/ = "\0";
1957 my $state = 'meta';
1958 my @mods;
1959 while (<$diff_fh>) {
1960 chomp $_; # this gets rid of the trailing "\0"
1961 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
1962 $::sha1\s($::sha1)\s
1963 ([MTCRAD])\d*$/xo) {
1964 push @mods, { mode_a => $1, mode_b => $2,
1965 sha1_b => $3, chg => $4 };
1966 if ($4 =~ /^(?:C|R)$/) {
1967 $state = 'file_a';
1968 } else {
1969 $state = 'file_b';
1970 }
1971 } elsif ($state eq 'file_a') {
1972 my $x = $mods[$#mods] or croak "Empty array\n";
1973 if ($x->{chg} !~ /^(?:C|R)$/) {
1974 croak "Error parsing $_, $x->{chg}\n";
1975 }
1976 $x->{file_a} = $_;
1977 $state = 'file_b';
1978 } elsif ($state eq 'file_b') {
1979 my $x = $mods[$#mods] or croak "Empty array\n";
1980 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
1981 croak "Error parsing $_, $x->{chg}\n";
1982 }
1983 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
1984 croak "Error parsing $_, $x->{chg}\n";
1985 }
1986 $x->{file_b} = $_;
1987 $state = 'meta';
1988 } else {
1989 croak "Error parsing $_\n";
1990 }
1991 }
1992 command_close_pipe($diff_fh, $ctx);
1993 $/ = $nl;
1994
1995 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
1996 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @mods) {
1997 my $f = $m->{chg};
1998 if (defined $o{$f}) {
1999 $self->$f($m);
2000 } else {
2001 fatal("Invalid change type: $f\n");
2002 }
2003 }
2004 $self->rmdirs($tree_b) if $::_rmdir;
2005 if (@mods == 0) {
2006 $self->abort_edit;
2007 } else {
2008 $self->close_edit;
2009 }
2010 \@mods;
2011}
2012
d81bf827
EW
2013package Git::SVN::Ra;
2014use vars qw/@ISA $config_dir/;
2015use strict;
2016use warnings;
2017my ($can_do_switch);
f6f09876 2018my %RA;
d81bf827
EW
2019
2020BEGIN {
2021 # enforce temporary pool usage for some simple functions
2022 my $e;
2023 foreach (qw/get_latest_revnum rev_proplist get_file
2024 check_path get_dir get_uuid get_repos_root/) {
2025 $e .= "sub $_ {
2026 my \$self = shift;
2027 my \$pool = SVN::Pool->new;
2028 my \@ret = \$self->SUPER::$_(\@_,\$pool);
2029 \$pool->clear;
2030 wantarray ? \@ret : \$ret[0]; }\n";
2031 }
2032 eval $e;
2033}
2034
2035sub new {
2036 my ($class, $url) = @_;
f6f09876
EW
2037 $url =~ s!/+$!!;
2038 return $RA{$url} if $RA{$url};
2039
d81bf827
EW
2040 SVN::_Core::svn_config_ensure($config_dir, undef);
2041 my ($baton, $callbacks) = SVN::Core::auth_open_helper([
2042 SVN::Client::get_simple_provider(),
2043 SVN::Client::get_ssl_server_trust_file_provider(),
2044 SVN::Client::get_simple_prompt_provider(
2045 \&Git::SVN::Prompt::simple, 2),
2046 SVN::Client::get_ssl_client_cert_prompt_provider(
2047 \&Git::SVN::Prompt::ssl_client_cert, 2),
2048 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
2049 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
2050 SVN::Client::get_username_provider(),
2051 SVN::Client::get_ssl_server_trust_prompt_provider(
2052 \&Git::SVN::Prompt::ssl_server_trust),
2053 SVN::Client::get_username_prompt_provider(
2054 \&Git::SVN::Prompt::username, 2),
2055 ]);
2056 my $config = SVN::Core::config_get_config($config_dir);
2057 my $self = SVN::Ra->new(url => $url, auth => $baton,
2058 config => $config,
2059 pool => SVN::Pool->new,
2060 auth_provider_callbacks => $callbacks);
2061 $self->{svn_path} = $url;
2062 $self->{repos_root} = $self->get_repos_root;
2063 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E/*##;
f6f09876 2064 $RA{$url} = bless $self, $class;
d81bf827
EW
2065}
2066
2067sub DESTROY {
f6f09876 2068 # do not call the real DESTROY since we store ourselves in %RA
d81bf827
EW
2069}
2070
2071sub dup {
2072 my ($self) = @_;
2073 my $dup = SVN::Ra->new(pool => SVN::Pool->new,
2074 map { $_ => $self->{$_} } qw/config url
2075 auth auth_provider_callbacks repos_root svn_path/);
2076 bless $dup, ref $self;
2077}
2078
2079sub get_log {
2080 my ($self, @args) = @_;
2081 my $pool = SVN::Pool->new;
2082 $args[4]-- if $args[4] && ! $::_follow_parent;
2083 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
2084 my $ret = $self->SUPER::get_log(@args, $pool);
2085 $pool->clear;
2086 $ret;
2087}
2088
2089sub get_commit_editor {
44320b9e 2090 my ($self, $log, $cb, $pool) = @_;
d81bf827 2091 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
44320b9e 2092 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
d81bf827
EW
2093}
2094
2095sub uuid {
2096 my ($self) = @_;
2097 $self->{uuid} ||= $self->get_uuid;
2098}
2099
2100sub gs_do_update {
2101 my ($self, $rev_a, $rev_b, $path, $recurse, $editor) = @_;
2102 my $pool = SVN::Pool->new;
2103 my $reporter = $self->do_update($rev_b, $path, $recurse,
2104 $editor, $pool);
2105 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2106 my $new = ($rev_a == $rev_b);
706587fc 2107 $reporter->set_path('', $rev_a, $new, @lock, $pool);
d81bf827
EW
2108 $reporter->finish_report($pool);
2109 $pool->clear;
2110 $editor->{git_commit_ok};
2111}
2112
2113sub gs_do_switch {
2114 my ($self, $rev_a, $rev_b, $path, $recurse, $url_b, $editor) = @_;
2115 my $pool = SVN::Pool->new;
2116 my $reporter = $self->do_switch($rev_b, $path, $recurse,
2117 $url_b, $editor, $pool);
2118 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2119 $reporter->set_path($path, $rev_a, 0, @lock, $pool);
2120 $reporter->finish_report($pool);
2121 $pool->clear;
2122 $editor->{git_commit_ok};
2123}
2124
2125sub can_do_switch {
2126 my $self = shift;
2127 unless (defined $can_do_switch) {
2128 my $pool = SVN::Pool->new;
2129 my $rep = eval {
2130 $self->do_switch(1, '', 0, $self->{url},
2131 SVN::Delta::Editor->new, $pool);
2132 };
2133 if ($@) {
2134 $can_do_switch = 0;
2135 } else {
2136 $rep->abort_report($pool);
2137 $can_do_switch = 1;
2138 }
2139 $pool->clear;
2140 }
2141 $can_do_switch;
2142}
2143
f8c9d1d2
EW
2144package Git::SVN::Log;
2145use strict;
2146use warnings;
2147use POSIX qw/strftime/;
2148use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
2149 %rusers $show_commit $incremental/;
2150my $l_fmt;
2151
2152sub cmt_showable {
2153 my ($c) = @_;
2154 return 1 if defined $c->{r};
2155 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
2156 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
44320b9e
EW
2157 my @log = command(qw/cat-file commit/, $c->{c});
2158 shift @log while ($log[0] ne "\n");
2159 shift @log;
2160 @{$c->{l}} = grep !/^git-svn-id: /, @log;
f8c9d1d2
EW
2161
2162 (undef, $c->{r}, undef) = ::extract_metadata(
44320b9e 2163 (grep(/^git-svn-id: /, @log))[-1]);
f8c9d1d2
EW
2164 }
2165 return defined $c->{r};
2166}
2167
2168sub log_use_color {
2169 return 1 if $color;
2170 my ($dc, $dcvar);
2171 $dcvar = 'color.diff';
2172 $dc = `git-config --get $dcvar`;
2173 if ($dc eq '') {
2174 # nothing at all; fallback to "diff.color"
2175 $dcvar = 'diff.color';
2176 $dc = `git-config --get $dcvar`;
2177 }
2178 chomp($dc);
2179 if ($dc eq 'auto') {
2180 my $pc;
2181 $pc = `git-config --get color.pager`;
2182 if ($pc eq '') {
2183 # does not have it -- fallback to pager.color
2184 $pc = `git-config --bool --get pager.color`;
2185 }
2186 else {
2187 $pc = `git-config --bool --get color.pager`;
2188 if ($?) {
2189 $pc = 'false';
2190 }
2191 }
2192 chomp($pc);
2193 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
2194 return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
2195 }
2196 return 0;
2197 }
2198 return 0 if $dc eq 'never';
2199 return 1 if $dc eq 'always';
2200 chomp($dc = `git-config --bool --get $dcvar`);
2201 return ($dc eq 'true');
2202}
2203
2204sub git_svn_log_cmd {
2205 my ($r_min, $r_max) = @_;
2206 my $gs = Git::SVN->_new;
2207 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
2208 $gs->refname);
2209 push @cmd, '-r' unless $non_recursive;
2210 push @cmd, qw/--raw --name-status/ if $verbose;
2211 push @cmd, '--color' if log_use_color();
2212 return @cmd unless defined $r_max;
2213 if ($r_max == $r_min) {
2214 push @cmd, '--max-count=1';
2215 if (my $c = $gs->rev_db_get($r_max)) {
2216 push @cmd, $c;
2217 }
2218 } else {
2219 my ($c_min, $c_max);
2220 $c_max = $gs->rev_db_get($r_max);
2221 $c_min = $gs->rev_db_get($r_min);
2222 if (defined $c_min && defined $c_max) {
2223 if ($r_max > $r_max) {
2224 push @cmd, "$c_min..$c_max";
2225 } else {
2226 push @cmd, "$c_max..$c_min";
2227 }
2228 } elsif ($r_max > $r_min) {
2229 push @cmd, $c_max;
2230 } else {
2231 push @cmd, $c_min;
2232 }
2233 }
2234 return @cmd;
2235}
2236
2237# adapted from pager.c
2238sub config_pager {
2239 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
2240 if (!defined $pager) {
2241 $pager = 'less';
2242 } elsif (length $pager == 0 || $pager eq 'cat') {
2243 $pager = undef;
2244 }
2245}
2246
2247sub run_pager {
2248 return unless -t *STDOUT;
2249 pipe my $rfd, my $wfd or return;
2250 defined(my $pid = fork) or ::fatal "Can't fork: $!\n";
2251 if (!$pid) {
2252 open STDOUT, '>&', $wfd or
2253 ::fatal "Can't redirect to stdout: $!\n";
2254 return;
2255 }
2256 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!\n";
2257 $ENV{LESS} ||= 'FRSX';
2258 exec $pager or ::fatal "Can't run pager: $! ($pager)\n";
2259}
2260
2261sub get_author_info {
2262 my ($dest, $author, $t, $tz) = @_;
2263 $author =~ s/(?:^\s*|\s*$)//g;
2264 $dest->{a_raw} = $author;
2265 my $au;
1c8443b0 2266 if ($::_authors) {
f8c9d1d2
EW
2267 $au = $rusers{$author} || undef;
2268 }
2269 if (!$au) {
2270 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
2271 }
2272 $dest->{t} = $t;
2273 $dest->{tz} = $tz;
2274 $dest->{a} = $au;
2275 # Date::Parse isn't in the standard Perl distro :(
2276 if ($tz =~ s/^\+//) {
2277 $t += ::tz_to_s_offset($tz);
2278 } elsif ($tz =~ s/^\-//) {
2279 $t -= ::tz_to_s_offset($tz);
2280 }
2281 $dest->{t_utc} = $t;
2282}
2283
2284sub process_commit {
2285 my ($c, $r_min, $r_max, $defer) = @_;
2286 if (defined $r_min && defined $r_max) {
2287 if ($r_min == $c->{r} && $r_min == $r_max) {
2288 show_commit($c);
2289 return 0;
2290 }
2291 return 1 if $r_min == $r_max;
2292 if ($r_min < $r_max) {
2293 # we need to reverse the print order
2294 return 0 if (defined $limit && --$limit < 0);
2295 push @$defer, $c;
2296 return 1;
2297 }
2298 if ($r_min != $r_max) {
2299 return 1 if ($r_min < $c->{r});
2300 return 1 if ($r_max > $c->{r});
2301 }
2302 }
2303 return 0 if (defined $limit && --$limit < 0);
2304 show_commit($c);
2305 return 1;
2306}
2307
2308sub show_commit {
2309 my $c = shift;
2310 if ($oneline) {
2311 my $x = "\n";
2312 if (my $l = $c->{l}) {
2313 while ($l->[0] =~ /^\s*$/) { shift @$l }
2314 $x = $l->[0];
2315 }
2316 $l_fmt ||= 'A' . length($c->{r});
2317 print 'r',pack($l_fmt, $c->{r}),' | ';
2318 print "$c->{c} | " if $show_commit;
2319 print $x;
2320 } else {
2321 show_commit_normal($c);
2322 }
2323}
2324
2325sub show_commit_changed_paths {
2326 my ($c) = @_;
2327 return unless $c->{changed};
2328 print "Changed paths:\n", @{$c->{changed}};
2329}
2330
2331sub show_commit_normal {
2332 my ($c) = @_;
2333 print '-' x72, "\nr$c->{r} | ";
2334 print "$c->{c} | " if $show_commit;
2335 print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
2336 localtime($c->{t_utc})), ' | ';
2337 my $nr_line = 0;
2338
2339 if (my $l = $c->{l}) {
2340 while ($l->[$#$l] eq "\n" && $#$l > 0
2341 && $l->[($#$l - 1)] eq "\n") {
2342 pop @$l;
2343 }
2344 $nr_line = scalar @$l;
2345 if (!$nr_line) {
2346 print "1 line\n\n\n";
2347 } else {
2348 if ($nr_line == 1) {
2349 $nr_line = '1 line';
2350 } else {
2351 $nr_line .= ' lines';
2352 }
2353 print $nr_line, "\n";
2354 show_commit_changed_paths($c);
2355 print "\n";
2356 print $_ foreach @$l;
2357 }
2358 } else {
2359 print "1 line\n";
2360 show_commit_changed_paths($c);
2361 print "\n";
2362
2363 }
2364 foreach my $x (qw/raw diff/) {
2365 if ($c->{$x}) {
2366 print "\n";
2367 print $_ foreach @{$c->{$x}}
2368 }
2369 }
2370}
2371
2372sub cmd_show_log {
2373 my (@args) = @_;
2374 my ($r_min, $r_max);
2375 my $r_last = -1; # prevent dupes
2376 if (defined $TZ) {
2377 $ENV{TZ} = $TZ;
2378 } else {
2379 delete $ENV{TZ};
2380 }
2381 if (defined $::_revision) {
2382 if ($::_revision =~ /^(\d+):(\d+)$/) {
2383 ($r_min, $r_max) = ($1, $2);
2384 } elsif ($::_revision =~ /^\d+$/) {
2385 $r_min = $r_max = $::_revision;
2386 } else {
2387 ::fatal "-r$::_revision is not supported, use ",
2388 "standard \'git log\' arguments instead\n";
2389 }
2390 }
2391
2392 config_pager();
2393 @args = (git_svn_log_cmd($r_min, $r_max), @args);
2394 my $log = command_output_pipe(@args);
2395 run_pager();
2396 my (@k, $c, $d);
2397 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
2398 while (<$log>) {
2399 if (/^${esc_color}commit ($::sha1_short)/o) {
2400 my $cmt = $1;
2401 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
2402 $r_last = $c->{r};
2403 process_commit($c, $r_min, $r_max, \@k) or
2404 goto out;
2405 }
2406 $d = undef;
2407 $c = { c => $cmt };
2408 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
2409 get_author_info($c, $1, $2, $3);
2410 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
2411 # ignore
2412 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
2413 push @{$c->{raw}}, $_;
2414 } elsif (/^${esc_color}[ACRMDT]\t/) {
2415 # we could add $SVN->{svn_path} here, but that requires
2416 # remote access at the moment (repo_path_split)...
2417 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
2418 push @{$c->{changed}}, $_;
2419 } elsif (/^${esc_color}diff /o) {
2420 $d = 1;
2421 push @{$c->{diff}}, $_;
2422 } elsif ($d) {
2423 push @{$c->{diff}}, $_;
2424 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
2425 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
2426 } elsif (s/^${esc_color} //o) {
2427 push @{$c->{l}}, $_;
2428 }
2429 }
2430 if ($c && defined $c->{r} && $c->{r} != $r_last) {
2431 $r_last = $c->{r};
2432 process_commit($c, $r_min, $r_max, \@k);
2433 }
2434 if (@k) {
2435 my $swap = $r_max;
2436 $r_max = $r_min;
2437 $r_min = $swap;
2438 process_commit($_, $r_min, $r_max) foreach reverse @k;
2439 }
2440out:
c843c464 2441 close $log;
f8c9d1d2
EW
2442 print '-' x72,"\n" unless $incremental || $oneline;
2443}
2444
706587fc
EW
2445package Git::SVN::Migration;
2446# these version numbers do NOT correspond to actual version numbers
2447# of git nor git-svn. They are just relative.
2448#
2449# v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
2450#
2451# v1 layout: .git/$id/info/url, refs/remotes/$id
2452#
2453# v2 layout: .git/svn/$id/info/url, refs/remotes/$id
2454#
2455# v3 layout: .git/svn/$id, refs/remotes/$id
2456# - info/url may remain for backwards compatibility
2457# - this is what we migrate up to this layout automatically,
2458# - this will be used by git svn init on single branches
2459#
2460# v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
2461# - this is only created for newly multi-init-ed
2462# repositories. Similar in spirit to the
2463# --use-separate-remotes option in git-clone (now default)
2464# - we do not automatically migrate to this (following
2465# the example set by core git)
2466use strict;
2467use warnings;
2468use Carp qw/croak/;
2469use File::Path qw/mkpath/;
2470use File::Basename qw/dirname/;
2471
2472sub migrate_from_v0 {
2473 my $git_dir = $ENV{GIT_DIR};
2474 return undef unless -d $git_dir;
2475 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
2476 my $migrated = 0;
2477 while (<$fh>) {
2478 chomp;
2479 my ($id, $orig_ref) = ($_, $_);
2480 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
2481 next unless -f "$git_dir/$id/info/url";
2482 my $new_ref = "refs/remotes/$id";
2483 if (::verify_ref("$new_ref^0")) {
2484 print STDERR "W: $orig_ref is probably an old ",
2485 "branch used by an ancient version of ",
2486 "git-svn.\n",
2487 "However, $new_ref also exists.\n",
2488 "We will not be able ",
2489 "to use this branch until this ",
2490 "ambiguity is resolved.\n";
2491 next;
2492 }
2493 print STDERR "Migrating from v0 layout...\n" if !$migrated;
2494 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
2495 command_noisy('update-ref', $new_ref, $orig_ref);
2496 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
2497 $migrated++;
2498 }
2499 command_close_pipe($fh, $ctx);
2500 print STDERR "Done migrating from v0 layout...\n" if $migrated;
2501 $migrated;
2502}
2503
2504sub migrate_from_v1 {
2505 my $git_dir = $ENV{GIT_DIR};
2506 my $migrated = 0;
2507 return $migrated unless -d $git_dir;
2508 my $svn_dir = "$git_dir/svn";
2509
2510 # just in case somebody used 'svn' as their $id at some point...
2511 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
2512
2513 print STDERR "Migrating from a git-svn v1 layout...\n";
2514 mkpath([$svn_dir]);
2515 print STDERR "Data from a previous version of git-svn exists, but\n\t",
2516 "$svn_dir\n\t(required for this version ",
2517 "($::VERSION) of git-svn) does not. exist\n";
2518 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
2519 while (<$fh>) {
2520 my $x = $_;
2521 next unless $x =~ s#^refs/remotes/##;
2522 chomp $x;
2523 next unless -f "$git_dir/$x/info/url";
2524 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
2525 next unless $u;
2526 my $dn = dirname("$git_dir/svn/$x");
2527 mkpath([$dn]) unless -d $dn;
2528 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
2529 mkpath(["$git_dir/svn/svn"]);
2530 print STDERR " - $git_dir/$x/info => ",
2531 "$git_dir/svn/$x/info\n";
2532 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
2533 croak "$!: $x";
2534 # don't worry too much about these, they probably
2535 # don't exist with repos this old (save for index,
2536 # and we can easily regenerate that)
2537 foreach my $f (qw/unhandled.log index .rev_db/) {
2538 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
2539 }
2540 } else {
2541 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
2542 rename "$git_dir/$x", "$git_dir/svn/$x" or
2543 croak "$!: $x";
2544 }
2545 $migrated++;
2546 }
2547 command_close_pipe($fh, $ctx);
2548 print STDERR "Done migrating from a git-svn v1 layout\n";
2549 $migrated;
2550}
2551
2552sub read_old_urls {
2553 my ($l_map, $pfx, $path) = @_;
2554 my @dir;
2555 foreach (<$path/*>) {
2556 if (-r "$_/info/url") {
2557 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
2558 my $ref_id = $pfx . basename $_;
2559 my $url = ::file_to_s("$_/info/url");
2560 $l_map->{$ref_id} = $url;
2561 } elsif (-d $_) {
2562 push @dir, $_;
2563 }
2564 }
2565 foreach (@dir) {
2566 my $x = $_;
2567 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
2568 read_old_urls($l_map, $x, $_);
2569 }
2570}
2571
2572sub migrate_from_v2 {
2573 my @cfg = command(qw/config -l/);
2574 return if grep /^svn-remote\..+\.url=/, @cfg;
2575 my %l_map;
2576 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
2577 my $migrated = 0;
2578
2579 foreach my $ref_id (sort keys %l_map) {
2580 Git::SVN->init($l_map{$ref_id}, $ref_id);
2581 $migrated++;
2582 }
2583 $migrated;
2584}
2585
2586sub migration_check {
2587 migrate_from_v0();
2588 migrate_from_v1();
2589 migrate_from_v2();
2590}
2591
3397f9df
EW
2592__END__
2593
2594Data structures:
2595
44320b9e 2596$log_entry hashref as returned by libsvn_log_entry()
3397f9df 2597{
44320b9e 2598 log => 'whitespace-formatted log entry
3397f9df
EW
2599', # trailing newline is preserved
2600 revision => '8', # integer
2601 date => '2004-02-24T17:01:44.108345Z', # commit date
2602 author => 'committer name'
2603};
2604
3397f9df
EW
2605@mods = array of diff-index line hashes, each element represents one line
2606 of diff-index output
2607
2608diff-index line ($m hash)
2609{
2610 mode_a => first column of diff-index output, no leading ':',
2611 mode_b => second column of diff-index output,
2612 sha1_b => sha1sum of the final blob,
ac8e0b91 2613 chg => change type [MCRADT],
3397f9df
EW
2614 file_a => original file name of a file (iff chg is 'C' or 'R')
2615 file_b => new/current file name of a file (any chg)
2616}
2617;
a5e0cedc 2618
a00439ac
EW
2619# retval of read_url_paths{,_all}();
2620$l_map = {
2621 # repository root url
2622 'https://svn.musicpd.org' => {
2623 # repository path # GIT_SVN_ID
2624 'mpd/trunk' => 'trunk',
2625 'mpd/tags/0.11.5' => 'tags/0.11.5',
2626 },
2627}
2628
a5e0cedc
EW
2629Notes:
2630 I don't trust the each() function on unless I created %hash myself
2631 because the internal iterator may not have started at base.