1#!/usr/bin/env 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
13# From which subdir have we been invoked?
14my $cmd_dir_prefix = eval {
15 command_oneline([qw/rev-parse --show-prefix/], STDERR => 0)
16} || '';
17
18my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
19$ENV{GIT_DIR} ||= '.git';
20$Git::SVN::default_repo_id = 'svn';
21$Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
22$Git::SVN::Ra::_log_window_size = 100;
23$Git::SVN::_minimize_url = 'unset';
24
25if (! exists $ENV{SVN_SSH}) {
26 if (exists $ENV{GIT_SSH}) {
27 $ENV{SVN_SSH} = $ENV{GIT_SSH};
28 if ($^O eq 'msys') {
29 $ENV{SVN_SSH} =~ s/\\/\\\\/g;
30 $ENV{SVN_SSH} =~ s/(.*)/"$1"/;
31 }
32 }
33}
34
35$Git::SVN::Log::TZ = $ENV{TZ};
36$ENV{TZ} = 'UTC';
37$| = 1; # unbuffer STDOUT
38
39sub fatal (@) { print STDERR "@_\n"; exit 1 }
40sub _req_svn {
41 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
42 require SVN::Ra;
43 require SVN::Delta;
44 if ($SVN::Core::VERSION lt '1.1.0') {
45 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
46 }
47}
48my $can_compress = eval { require Compress::Zlib; 1};
49push @Git::SVN::Ra::ISA, 'SVN::Ra';
50push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
51push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
52use Carp qw/croak/;
53use Digest::MD5;
54use IO::File qw//;
55use File::Basename qw/dirname basename/;
56use File::Path qw/mkpath/;
57use File::Spec;
58use File::Find;
59use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
60use IPC::Open3;
61use Git;
62use Memoize; # core since 5.8.0, Jul 2002
63
64BEGIN {
65 # import functions from Git into our packages, en masse
66 no strict 'refs';
67 foreach (qw/command command_oneline command_noisy command_output_pipe
68 command_input_pipe command_close_pipe
69 command_bidi_pipe command_close_bidi_pipe/) {
70 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
71 Git::SVN::Migration Git::SVN::Log Git::SVN),
72 __PACKAGE__) {
73 *{"${package}::$_"} = \&{"Git::$_"};
74 }
75 }
76 Memoize::memoize 'Git::config';
77 Memoize::memoize 'Git::config_bool';
78}
79
80my ($SVN);
81
82$sha1 = qr/[a-f\d]{40}/;
83$sha1_short = qr/[a-f\d]{4,40}/;
84my ($_stdin, $_help, $_edit,
85 $_message, $_file, $_branch_dest,
86 $_template, $_shared,
87 $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
88 $_merge, $_strategy, $_dry_run, $_local,
89 $_prefix, $_no_checkout, $_url, $_verbose,
90 $_git_format, $_commit_url, $_tag, $_merge_info);
91$Git::SVN::_follow_parent = 1;
92$SVN::Git::Fetcher::_placeholder_filename = ".gitignore";
93$_q ||= 0;
94my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
95 'config-dir=s' => \$Git::SVN::Ra::config_dir,
96 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
97 'ignore-paths=s' => \$SVN::Git::Fetcher::_ignore_regex );
98my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
99 'authors-file|A=s' => \$_authors,
100 'authors-prog=s' => \$_authors_prog,
101 'repack:i' => \$Git::SVN::_repack,
102 'noMetadata' => \$Git::SVN::_no_metadata,
103 'useSvmProps' => \$Git::SVN::_use_svm_props,
104 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
105 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
106 'no-checkout' => \$_no_checkout,
107 'quiet|q+' => \$_q,
108 'repack-flags|repack-args|repack-opts=s' =>
109 \$Git::SVN::_repack_flags,
110 'use-log-author' => \$Git::SVN::_use_log_author,
111 'add-author-from' => \$Git::SVN::_add_author_from,
112 'localtime' => \$Git::SVN::_localtime,
113 %remote_opts );
114
115my ($_trunk, @_tags, @_branches, $_stdlayout);
116my %icv;
117my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
118 'trunk|T=s' => \$_trunk, 'tags|t=s@' => \@_tags,
119 'branches|b=s@' => \@_branches, 'prefix=s' => \$_prefix,
120 'stdlayout|s' => \$_stdlayout,
121 'minimize-url|m!' => \$Git::SVN::_minimize_url,
122 'no-metadata' => sub { $icv{noMetadata} = 1 },
123 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
124 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
125 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
126 'rewrite-uuid=s' => sub { $icv{rewriteUUID} = $_[1] },
127 %remote_opts );
128my %cmt_opts = ( 'edit|e' => \$_edit,
129 'rmdir' => \$SVN::Git::Editor::_rmdir,
130 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
131 'l=i' => \$SVN::Git::Editor::_rename_limit,
132 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
133);
134
135my %cmd = (
136 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
137 { 'revision|r=s' => \$_revision,
138 'fetch-all|all' => \$_fetch_all,
139 'parent|p' => \$_fetch_parent,
140 %fc_opts } ],
141 clone => [ \&cmd_clone, "Initialize and fetch revisions",
142 { 'revision|r=s' => \$_revision,
143 'preserve-empty-dirs' =>
144 \$SVN::Git::Fetcher::_preserve_empty_dirs,
145 'placeholder-filename=s' =>
146 \$SVN::Git::Fetcher::_placeholder_filename,
147 %fc_opts, %init_opts } ],
148 init => [ \&cmd_init, "Initialize a repo for tracking" .
149 " (requires URL argument)",
150 \%init_opts ],
151 'multi-init' => [ \&cmd_multi_init,
152 "Deprecated alias for ".
153 "'$0 init -T<trunk> -b<branches> -t<tags>'",
154 \%init_opts ],
155 dcommit => [ \&cmd_dcommit,
156 'Commit several diffs to merge with upstream',
157 { 'merge|m|M' => \$_merge,
158 'strategy|s=s' => \$_strategy,
159 'verbose|v' => \$_verbose,
160 'dry-run|n' => \$_dry_run,
161 'fetch-all|all' => \$_fetch_all,
162 'commit-url=s' => \$_commit_url,
163 'revision|r=i' => \$_revision,
164 'no-rebase' => \$_no_rebase,
165 'mergeinfo=s' => \$_merge_info,
166 %cmt_opts, %fc_opts } ],
167 branch => [ \&cmd_branch,
168 'Create a branch in the SVN repository',
169 { 'message|m=s' => \$_message,
170 'destination|d=s' => \$_branch_dest,
171 'dry-run|n' => \$_dry_run,
172 'tag|t' => \$_tag,
173 'username=s' => \$Git::SVN::Prompt::_username,
174 'commit-url=s' => \$_commit_url } ],
175 tag => [ sub { $_tag = 1; cmd_branch(@_) },
176 'Create a tag in the SVN repository',
177 { 'message|m=s' => \$_message,
178 'destination|d=s' => \$_branch_dest,
179 'dry-run|n' => \$_dry_run,
180 'username=s' => \$Git::SVN::Prompt::_username,
181 'commit-url=s' => \$_commit_url } ],
182 'set-tree' => [ \&cmd_set_tree,
183 "Set an SVN repository to a git tree-ish",
184 { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
185 'create-ignore' => [ \&cmd_create_ignore,
186 'Create a .gitignore per svn:ignore',
187 { 'revision|r=i' => \$_revision
188 } ],
189 'mkdirs' => [ \&cmd_mkdirs ,
190 "recreate empty directories after a checkout",
191 { 'revision|r=i' => \$_revision } ],
192 'propget' => [ \&cmd_propget,
193 'Print the value of a property on a file or directory',
194 { 'revision|r=i' => \$_revision } ],
195 'proplist' => [ \&cmd_proplist,
196 'List all properties of a file or directory',
197 { 'revision|r=i' => \$_revision } ],
198 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
199 { 'revision|r=i' => \$_revision
200 } ],
201 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
202 { 'revision|r=i' => \$_revision
203 } ],
204 'multi-fetch' => [ \&cmd_multi_fetch,
205 "Deprecated alias for $0 fetch --all",
206 { 'revision|r=s' => \$_revision, %fc_opts } ],
207 'migrate' => [ sub { },
208 # no-op, we automatically run this anyways,
209 'Migrate configuration/metadata/layout from
210 previous versions of git-svn',
211 { 'minimize' => \$Git::SVN::Migration::_minimize,
212 %remote_opts } ],
213 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
214 { 'limit=i' => \$Git::SVN::Log::limit,
215 'revision|r=s' => \$_revision,
216 'verbose|v' => \$Git::SVN::Log::verbose,
217 'incremental' => \$Git::SVN::Log::incremental,
218 'oneline' => \$Git::SVN::Log::oneline,
219 'show-commit' => \$Git::SVN::Log::show_commit,
220 'non-recursive' => \$Git::SVN::Log::non_recursive,
221 'authors-file|A=s' => \$_authors,
222 'color' => \$Git::SVN::Log::color,
223 'pager=s' => \$Git::SVN::Log::pager
224 } ],
225 'find-rev' => [ \&cmd_find_rev,
226 "Translate between SVN revision numbers and tree-ish",
227 {} ],
228 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
229 { 'merge|m|M' => \$_merge,
230 'verbose|v' => \$_verbose,
231 'strategy|s=s' => \$_strategy,
232 'local|l' => \$_local,
233 'fetch-all|all' => \$_fetch_all,
234 'dry-run|n' => \$_dry_run,
235 %fc_opts } ],
236 'commit-diff' => [ \&cmd_commit_diff,
237 'Commit a diff between two trees',
238 { 'message|m=s' => \$_message,
239 'file|F=s' => \$_file,
240 'revision|r=s' => \$_revision,
241 %cmt_opts } ],
242 'info' => [ \&cmd_info,
243 "Show info about the latest SVN revision
244 on the current branch",
245 { 'url' => \$_url, } ],
246 'blame' => [ \&Git::SVN::Log::cmd_blame,
247 "Show what revision and author last modified each line of a file",
248 { 'git-format' => \$_git_format } ],
249 'reset' => [ \&cmd_reset,
250 "Undo fetches back to the specified SVN revision",
251 { 'revision|r=s' => \$_revision,
252 'parent|p' => \$_fetch_parent } ],
253 'gc' => [ \&cmd_gc,
254 "Compress unhandled.log files in .git/svn and remove " .
255 "index files in .git/svn",
256 {} ],
257);
258
259my $cmd;
260for (my $i = 0; $i < @ARGV; $i++) {
261 if (defined $cmd{$ARGV[$i]}) {
262 $cmd = $ARGV[$i];
263 splice @ARGV, $i, 1;
264 last;
265 } elsif ($ARGV[$i] eq 'help') {
266 $cmd = $ARGV[$i+1];
267 usage(0);
268 }
269};
270
271# make sure we're always running at the top-level working directory
272unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
273 unless (-d $ENV{GIT_DIR}) {
274 if ($git_dir_user_set) {
275 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
276 "but it is not a directory\n";
277 }
278 my $git_dir = delete $ENV{GIT_DIR};
279 my $cdup = undef;
280 git_cmd_try {
281 $cdup = command_oneline(qw/rev-parse --show-cdup/);
282 $git_dir = '.' unless ($cdup);
283 chomp $cdup if ($cdup);
284 $cdup = "." unless ($cdup && length $cdup);
285 } "Already at toplevel, but $git_dir not found\n";
286 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
287 unless (-d $git_dir) {
288 die "$git_dir still not found after going to ",
289 "'$cdup'\n";
290 }
291 $ENV{GIT_DIR} = $git_dir;
292 }
293 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
294}
295
296my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
297
298read_git_config(\%opts);
299if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
300 Getopt::Long::Configure('pass_through');
301}
302my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
303 'minimize-connections' => \$Git::SVN::Migration::_minimize,
304 'id|i=s' => \$Git::SVN::default_ref_id,
305 'svn-remote|remote|R=s' => sub {
306 $Git::SVN::no_reuse_existing = 1;
307 $Git::SVN::default_repo_id = $_[1] });
308exit 1 if (!$rv && $cmd && $cmd ne 'log');
309
310usage(0) if $_help;
311version() if $_version;
312usage(1) unless defined $cmd;
313load_authors() if $_authors;
314if (defined $_authors_prog) {
315 $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
316}
317
318unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
319 Git::SVN::Migration::migration_check();
320}
321Git::SVN::init_vars();
322eval {
323 Git::SVN::verify_remotes_sanity();
324 $cmd{$cmd}->[0]->(@ARGV);
325};
326fatal $@ if $@;
327post_fetch_checkout();
328exit 0;
329
330####################### primary functions ######################
331sub usage {
332 my $exit = shift || 0;
333 my $fd = $exit ? \*STDERR : \*STDOUT;
334 print $fd <<"";
335git-svn - bidirectional operations between a single Subversion tree and git
336Usage: git svn <command> [options] [arguments]\n
337
338 print $fd "Available commands:\n" unless $cmd;
339
340 foreach (sort keys %cmd) {
341 next if $cmd && $cmd ne $_;
342 next if /^multi-/; # don't show deprecated commands
343 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
344 foreach (sort keys %{$cmd{$_}->[2]}) {
345 # mixed-case options are for .git/config only
346 next if /[A-Z]/ && /^[a-z]+$/i;
347 # prints out arguments as they should be passed:
348 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
349 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
350 "--$_" : "-$_" }
351 split /\|/,$_)," $x\n";
352 }
353 }
354 print $fd <<"";
355\nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
356arbitrary identifier if you're tracking multiple SVN branches/repositories in
357one git repository and want to keep them separate. See git-svn(1) for more
358information.
359
360 exit $exit;
361}
362
363sub version {
364 ::_req_svn();
365 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
366 exit 0;
367}
368
369sub do_git_init_db {
370 unless (-d $ENV{GIT_DIR}) {
371 my @init_db = ('init');
372 push @init_db, "--template=$_template" if defined $_template;
373 if (defined $_shared) {
374 if ($_shared =~ /[a-z]/) {
375 push @init_db, "--shared=$_shared";
376 } else {
377 push @init_db, "--shared";
378 }
379 }
380 command_noisy(@init_db);
381 $_repository = Git->repository(Repository => ".git");
382 }
383 my $set;
384 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
385 foreach my $i (keys %icv) {
386 die "'$set' and '$i' cannot both be set\n" if $set;
387 next unless defined $icv{$i};
388 command_noisy('config', "$pfx.$i", $icv{$i});
389 $set = $i;
390 }
391 my $ignore_regex = \$SVN::Git::Fetcher::_ignore_regex;
392 command_noisy('config', "$pfx.ignore-paths", $$ignore_regex)
393 if defined $$ignore_regex;
394
395 if (defined $SVN::Git::Fetcher::_preserve_empty_dirs) {
396 my $fname = \$SVN::Git::Fetcher::_placeholder_filename;
397 command_noisy('config', "$pfx.preserve-empty-dirs", 'true');
398 command_noisy('config', "$pfx.placeholder-filename", $$fname);
399 }
400}
401
402sub init_subdir {
403 my $repo_path = shift or return;
404 mkpath([$repo_path]) unless -d $repo_path;
405 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
406 $ENV{GIT_DIR} = '.git';
407 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
408}
409
410sub cmd_clone {
411 my ($url, $path) = @_;
412 if (!defined $path &&
413 (defined $_trunk || @_branches || @_tags ||
414 defined $_stdlayout) &&
415 $url !~ m#^[a-z\+]+://#) {
416 $path = $url;
417 }
418 $path = basename($url) if !defined $path || !length $path;
419 my $authors_absolute = $_authors ? File::Spec->rel2abs($_authors) : "";
420 cmd_init($url, $path);
421 command_oneline('config', 'svn.authorsfile', $authors_absolute)
422 if $_authors;
423 Git::SVN::fetch_all($Git::SVN::default_repo_id);
424}
425
426sub cmd_init {
427 if (defined $_stdlayout) {
428 $_trunk = 'trunk' if (!defined $_trunk);
429 @_tags = 'tags' if (! @_tags);
430 @_branches = 'branches' if (! @_branches);
431 }
432 if (defined $_trunk || @_branches || @_tags) {
433 return cmd_multi_init(@_);
434 }
435 my $url = shift or die "SVN repository location required ",
436 "as a command-line argument\n";
437 $url = canonicalize_url($url);
438 init_subdir(@_);
439 do_git_init_db();
440
441 if ($Git::SVN::_minimize_url eq 'unset') {
442 $Git::SVN::_minimize_url = 0;
443 }
444
445 Git::SVN->init($url);
446}
447
448sub cmd_fetch {
449 if (grep /^\d+=./, @_) {
450 die "'<rev>=<commit>' fetch arguments are ",
451 "no longer supported.\n";
452 }
453 my ($remote) = @_;
454 if (@_ > 1) {
455 die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
456 }
457 $Git::SVN::no_reuse_existing = undef;
458 if ($_fetch_parent) {
459 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
460 unless ($gs) {
461 die "Unable to determine upstream SVN information from ",
462 "working tree history\n";
463 }
464 # just fetch, don't checkout.
465 $_no_checkout = 'true';
466 $_fetch_all ? $gs->fetch_all : $gs->fetch;
467 } elsif ($_fetch_all) {
468 cmd_multi_fetch();
469 } else {
470 $remote ||= $Git::SVN::default_repo_id;
471 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
472 }
473}
474
475sub cmd_set_tree {
476 my (@commits) = @_;
477 if ($_stdin || !@commits) {
478 print "Reading from stdin...\n";
479 @commits = ();
480 while (<STDIN>) {
481 if (/\b($sha1_short)\b/o) {
482 unshift @commits, $1;
483 }
484 }
485 }
486 my @revs;
487 foreach my $c (@commits) {
488 my @tmp = command('rev-parse',$c);
489 if (scalar @tmp == 1) {
490 push @revs, $tmp[0];
491 } elsif (scalar @tmp > 1) {
492 push @revs, reverse(command('rev-list',@tmp));
493 } else {
494 fatal "Failed to rev-parse $c";
495 }
496 }
497 my $gs = Git::SVN->new;
498 my ($r_last, $cmt_last) = $gs->last_rev_commit;
499 $gs->fetch;
500 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
501 fatal "There are new revisions that were fetched ",
502 "and need to be merged (or acknowledged) ",
503 "before committing.\nlast rev: $r_last\n",
504 " current: $gs->{last_rev}";
505 }
506 $gs->set_tree($_) foreach @revs;
507 print "Done committing ",scalar @revs," revisions to SVN\n";
508 unlink $gs->{index};
509}
510
511sub cmd_dcommit {
512 my $head = shift;
513 command_noisy(qw/update-index --refresh/);
514 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
515 'Cannot dcommit with a dirty index. Commit your changes first, '
516 . "or stash them with `git stash'.\n";
517 $head ||= 'HEAD';
518
519 my $old_head;
520 if ($head ne 'HEAD') {
521 $old_head = eval {
522 command_oneline([qw/symbolic-ref -q HEAD/])
523 };
524 if ($old_head) {
525 $old_head =~ s{^refs/heads/}{};
526 } else {
527 $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
528 }
529 command(['checkout', $head], STDERR => 0);
530 }
531
532 my @refs;
533 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
534 unless ($gs) {
535 die "Unable to determine upstream SVN information from ",
536 "$head history.\nPerhaps the repository is empty.";
537 }
538
539 if (defined $_commit_url) {
540 $url = $_commit_url;
541 } else {
542 $url = eval { command_oneline('config', '--get',
543 "svn-remote.$gs->{repo_id}.commiturl") };
544 if (!$url) {
545 $url = $gs->full_pushurl
546 }
547 }
548
549 my $last_rev = $_revision if defined $_revision;
550 if ($url) {
551 print "Committing to $url ...\n";
552 }
553 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
554 if ($_no_rebase && scalar(@$linear_refs) > 1) {
555 warn "Attempting to commit more than one change while ",
556 "--no-rebase is enabled.\n",
557 "If these changes depend on each other, re-running ",
558 "without --no-rebase may be required."
559 }
560 my $expect_url = $url;
561 Git::SVN::remove_username($expect_url);
562 if (defined($_merge_info)) {
563 $_merge_info =~ tr{ }{\n};
564 }
565 while (1) {
566 my $d = shift @$linear_refs or last;
567 unless (defined $last_rev) {
568 (undef, $last_rev, undef) = cmt_metadata("$d~1");
569 unless (defined $last_rev) {
570 fatal "Unable to extract revision information ",
571 "from commit $d~1";
572 }
573 }
574 if ($_dry_run) {
575 print "diff-tree $d~1 $d\n";
576 } else {
577 my $cmt_rev;
578 my %ed_opts = ( r => $last_rev,
579 log => get_commit_entry($d)->{log},
580 ra => Git::SVN::Ra->new($url),
581 config => SVN::Core::config_get_config(
582 $Git::SVN::Ra::config_dir
583 ),
584 tree_a => "$d~1",
585 tree_b => $d,
586 editor_cb => sub {
587 print "Committed r$_[0]\n";
588 $cmt_rev = $_[0];
589 },
590 mergeinfo => $_merge_info,
591 svn_path => '');
592 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
593 print "No changes\n$d~1 == $d\n";
594 } elsif ($parents->{$d} && @{$parents->{$d}}) {
595 $gs->{inject_parents_dcommit}->{$cmt_rev} =
596 $parents->{$d};
597 }
598 $_fetch_all ? $gs->fetch_all : $gs->fetch;
599 $last_rev = $cmt_rev;
600 next if $_no_rebase;
601
602 # we always want to rebase against the current HEAD,
603 # not any head that was passed to us
604 my @diff = command('diff-tree', $d,
605 $gs->refname, '--');
606 my @finish;
607 if (@diff) {
608 @finish = rebase_cmd();
609 print STDERR "W: $d and ", $gs->refname,
610 " differ, using @finish:\n",
611 join("\n", @diff), "\n";
612 } else {
613 print "No changes between current HEAD and ",
614 $gs->refname,
615 "\nResetting to the latest ",
616 $gs->refname, "\n";
617 @finish = qw/reset --mixed/;
618 }
619 command_noisy(@finish, $gs->refname);
620 if (@diff) {
621 @refs = ();
622 my ($url_, $rev_, $uuid_, $gs_) =
623 working_head_info('HEAD', \@refs);
624 my ($linear_refs_, $parents_) =
625 linearize_history($gs_, \@refs);
626 if (scalar(@$linear_refs) !=
627 scalar(@$linear_refs_)) {
628 fatal "# of revisions changed ",
629 "\nbefore:\n",
630 join("\n", @$linear_refs),
631 "\n\nafter:\n",
632 join("\n", @$linear_refs_), "\n",
633 'If you are attempting to commit ',
634 "merges, try running:\n\t",
635 'git rebase --interactive',
636 '--preserve-merges ',
637 $gs->refname,
638 "\nBefore dcommitting";
639 }
640 if ($url_ ne $expect_url) {
641 if ($url_ eq $gs->metadata_url) {
642 print
643 "Accepting rewritten URL:",
644 " $url_\n";
645 } else {
646 fatal
647 "URL mismatch after rebase:",
648 " $url_ != $expect_url";
649 }
650 }
651 if ($uuid_ ne $uuid) {
652 fatal "uuid mismatch after rebase: ",
653 "$uuid_ != $uuid";
654 }
655 # remap parents
656 my (%p, @l, $i);
657 for ($i = 0; $i < scalar @$linear_refs; $i++) {
658 my $new = $linear_refs_->[$i] or next;
659 $p{$new} =
660 $parents->{$linear_refs->[$i]};
661 push @l, $new;
662 }
663 $parents = \%p;
664 $linear_refs = \@l;
665 }
666 }
667 }
668
669 if ($old_head) {
670 my $new_head = command_oneline(qw/rev-parse HEAD/);
671 my $new_is_symbolic = eval {
672 command_oneline(qw/symbolic-ref -q HEAD/);
673 };
674 if ($new_is_symbolic) {
675 print "dcommitted the branch ", $head, "\n";
676 } else {
677 print "dcommitted on a detached HEAD because you gave ",
678 "a revision argument.\n",
679 "The rewritten commit is: ", $new_head, "\n";
680 }
681 command(['checkout', $old_head], STDERR => 0);
682 }
683
684 unlink $gs->{index};
685}
686
687sub cmd_branch {
688 my ($branch_name, $head) = @_;
689
690 unless (defined $branch_name && length $branch_name) {
691 die(($_tag ? "tag" : "branch") . " name required\n");
692 }
693 $head ||= 'HEAD';
694
695 my (undef, $rev, undef, $gs) = working_head_info($head);
696 my $src = $gs->full_pushurl;
697
698 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
699 my $allglobs = $remote->{ $_tag ? 'tags' : 'branches' };
700 my $glob;
701 if ($#{$allglobs} == 0) {
702 $glob = $allglobs->[0];
703 } else {
704 unless(defined $_branch_dest) {
705 die "Multiple ",
706 $_tag ? "tag" : "branch",
707 " paths defined for Subversion repository.\n",
708 "You must specify where you want to create the ",
709 $_tag ? "tag" : "branch",
710 " with the --destination argument.\n";
711 }
712 foreach my $g (@{$allglobs}) {
713 # SVN::Git::Editor could probably be moved to Git.pm..
714 my $re = SVN::Git::Editor::glob2pat($g->{path}->{left});
715 if ($_branch_dest =~ /$re/) {
716 $glob = $g;
717 last;
718 }
719 }
720 unless (defined $glob) {
721 my $dest_re = qr/\b\Q$_branch_dest\E\b/;
722 foreach my $g (@{$allglobs}) {
723 $g->{path}->{left} =~ /$dest_re/ or next;
724 if (defined $glob) {
725 die "Ambiguous destination: ",
726 $_branch_dest, "\nmatches both '",
727 $glob->{path}->{left}, "' and '",
728 $g->{path}->{left}, "'\n";
729 }
730 $glob = $g;
731 }
732 unless (defined $glob) {
733 die "Unknown ",
734 $_tag ? "tag" : "branch",
735 " destination $_branch_dest\n";
736 }
737 }
738 }
739 my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
740 my $url;
741 if (defined $_commit_url) {
742 $url = $_commit_url;
743 } else {
744 $url = eval { command_oneline('config', '--get',
745 "svn-remote.$gs->{repo_id}.commiturl") };
746 if (!$url) {
747 $url = $remote->{pushurl} || $remote->{url};
748 }
749 }
750 my $dst = join '/', $url, $lft, $branch_name, ($rgt || ());
751
752 if ($dst =~ /^https:/ && $src =~ /^http:/) {
753 $src=~s/^http:/https:/;
754 }
755
756 ::_req_svn();
757
758 my $ctx = SVN::Client->new(
759 auth => Git::SVN::Ra::_auth_providers(),
760 log_msg => sub {
761 ${ $_[0] } = defined $_message
762 ? $_message
763 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
764 . $branch_name;
765 },
766 );
767
768 eval {
769 $ctx->ls($dst, 'HEAD', 0);
770 } and die "branch ${branch_name} already exists\n";
771
772 print "Copying ${src} at r${rev} to ${dst}...\n";
773 $ctx->copy($src, $rev, $dst)
774 unless $_dry_run;
775
776 $gs->fetch_all;
777}
778
779sub cmd_find_rev {
780 my $revision_or_hash = shift or die "SVN or git revision required ",
781 "as a command-line argument\n";
782 my $result;
783 if ($revision_or_hash =~ /^r\d+$/) {
784 my $head = shift;
785 $head ||= 'HEAD';
786 my @refs;
787 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
788 unless ($gs) {
789 die "Unable to determine upstream SVN information from ",
790 "$head history\n";
791 }
792 my $desired_revision = substr($revision_or_hash, 1);
793 $result = $gs->rev_map_get($desired_revision, $uuid);
794 } else {
795 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
796 $result = $rev;
797 }
798 print "$result\n" if $result;
799}
800
801sub auto_create_empty_directories {
802 my ($gs) = @_;
803 my $var = eval { command_oneline('config', '--get', '--bool',
804 "svn-remote.$gs->{repo_id}.automkdirs") };
805 # By default, create empty directories by consulting the unhandled log,
806 # but allow setting it to 'false' to skip it.
807 return !($var && $var eq 'false');
808}
809
810sub cmd_rebase {
811 command_noisy(qw/update-index --refresh/);
812 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
813 unless ($gs) {
814 die "Unable to determine upstream SVN information from ",
815 "working tree history\n";
816 }
817 if ($_dry_run) {
818 print "Remote Branch: " . $gs->refname . "\n";
819 print "SVN URL: " . $url . "\n";
820 return;
821 }
822 if (command(qw/diff-index HEAD --/)) {
823 print STDERR "Cannot rebase with uncommited changes:\n";
824 command_noisy('status');
825 exit 1;
826 }
827 unless ($_local) {
828 # rebase will checkout for us, so no need to do it explicitly
829 $_no_checkout = 'true';
830 $_fetch_all ? $gs->fetch_all : $gs->fetch;
831 }
832 command_noisy(rebase_cmd(), $gs->refname);
833 if (auto_create_empty_directories($gs)) {
834 $gs->mkemptydirs;
835 }
836}
837
838sub cmd_show_ignore {
839 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
840 $gs ||= Git::SVN->new;
841 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
842 $gs->prop_walk($gs->{path}, $r, sub {
843 my ($gs, $path, $props) = @_;
844 print STDOUT "\n# $path\n";
845 my $s = $props->{'svn:ignore'} or return;
846 $s =~ s/[\r\n]+/\n/g;
847 $s =~ s/^\n+//;
848 chomp $s;
849 $s =~ s#^#$path#gm;
850 print STDOUT "$s\n";
851 });
852}
853
854sub cmd_show_externals {
855 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
856 $gs ||= Git::SVN->new;
857 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
858 $gs->prop_walk($gs->{path}, $r, sub {
859 my ($gs, $path, $props) = @_;
860 print STDOUT "\n# $path\n";
861 my $s = $props->{'svn:externals'} or return;
862 $s =~ s/[\r\n]+/\n/g;
863 chomp $s;
864 $s =~ s#^#$path#gm;
865 print STDOUT "$s\n";
866 });
867}
868
869sub cmd_create_ignore {
870 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
871 $gs ||= Git::SVN->new;
872 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
873 $gs->prop_walk($gs->{path}, $r, sub {
874 my ($gs, $path, $props) = @_;
875 # $path is of the form /path/to/dir/
876 $path = '.' . $path;
877 # SVN can have attributes on empty directories,
878 # which git won't track
879 mkpath([$path]) unless -d $path;
880 my $ignore = $path . '.gitignore';
881 my $s = $props->{'svn:ignore'} or return;
882 open(GITIGNORE, '>', $ignore)
883 or fatal("Failed to open `$ignore' for writing: $!");
884 $s =~ s/[\r\n]+/\n/g;
885 $s =~ s/^\n+//;
886 chomp $s;
887 # Prefix all patterns so that the ignore doesn't apply
888 # to sub-directories.
889 $s =~ s#^#/#gm;
890 print GITIGNORE "$s\n";
891 close(GITIGNORE)
892 or fatal("Failed to close `$ignore': $!");
893 command_noisy('add', '-f', $ignore);
894 });
895}
896
897sub cmd_mkdirs {
898 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
899 $gs ||= Git::SVN->new;
900 $gs->mkemptydirs($_revision);
901}
902
903sub canonicalize_path {
904 my ($path) = @_;
905 my $dot_slash_added = 0;
906 if (substr($path, 0, 1) ne "/") {
907 $path = "./" . $path;
908 $dot_slash_added = 1;
909 }
910 # File::Spec->canonpath doesn't collapse x/../y into y (for a
911 # good reason), so let's do this manually.
912 $path =~ s#/+#/#g;
913 $path =~ s#/\.(?:/|$)#/#g;
914 $path =~ s#/[^/]+/\.\.##g;
915 $path =~ s#/$##g;
916 $path =~ s#^\./## if $dot_slash_added;
917 $path =~ s#^/##;
918 $path =~ s#^\.$##;
919 return $path;
920}
921
922sub canonicalize_url {
923 my ($url) = @_;
924 $url =~ s#^([^:]+://[^/]*/)(.*)$#$1 . canonicalize_path($2)#e;
925 return $url;
926}
927
928# get_svnprops(PATH)
929# ------------------
930# Helper for cmd_propget and cmd_proplist below.
931sub get_svnprops {
932 my $path = shift;
933 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
934 $gs ||= Git::SVN->new;
935
936 # prefix THE PATH by the sub-directory from which the user
937 # invoked us.
938 $path = $cmd_dir_prefix . $path;
939 fatal("No such file or directory: $path") unless -e $path;
940 my $is_dir = -d $path ? 1 : 0;
941 $path = $gs->{path} . '/' . $path;
942
943 # canonicalize the path (otherwise libsvn will abort or fail to
944 # find the file)
945 $path = canonicalize_path($path);
946
947 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
948 my $props;
949 if ($is_dir) {
950 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
951 }
952 else {
953 (undef, $props) = $gs->ra->get_file($path, $r, undef);
954 }
955 return $props;
956}
957
958# cmd_propget (PROP, PATH)
959# ------------------------
960# Print the SVN property PROP for PATH.
961sub cmd_propget {
962 my ($prop, $path) = @_;
963 $path = '.' if not defined $path;
964 usage(1) if not defined $prop;
965 my $props = get_svnprops($path);
966 if (not defined $props->{$prop}) {
967 fatal("`$path' does not have a `$prop' SVN property.");
968 }
969 print $props->{$prop} . "\n";
970}
971
972# cmd_proplist (PATH)
973# -------------------
974# Print the list of SVN properties for PATH.
975sub cmd_proplist {
976 my $path = shift;
977 $path = '.' if not defined $path;
978 my $props = get_svnprops($path);
979 print "Properties on '$path':\n";
980 foreach (sort keys %{$props}) {
981 print " $_\n";
982 }
983}
984
985sub cmd_multi_init {
986 my $url = shift;
987 unless (defined $_trunk || @_branches || @_tags) {
988 usage(1);
989 }
990
991 $_prefix = '' unless defined $_prefix;
992 if (defined $url) {
993 $url = canonicalize_url($url);
994 init_subdir(@_);
995 }
996 do_git_init_db();
997 if (defined $_trunk) {
998 $_trunk =~ s#^/+##;
999 my $trunk_ref = 'refs/remotes/' . $_prefix . 'trunk';
1000 # try both old-style and new-style lookups:
1001 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
1002 unless ($gs_trunk) {
1003 my ($trunk_url, $trunk_path) =
1004 complete_svn_url($url, $_trunk);
1005 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
1006 undef, $trunk_ref);
1007 }
1008 }
1009 return unless @_branches || @_tags;
1010 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
1011 foreach my $path (@_branches) {
1012 complete_url_ls_init($ra, $path, '--branches/-b', $_prefix);
1013 }
1014 foreach my $path (@_tags) {
1015 complete_url_ls_init($ra, $path, '--tags/-t', $_prefix.'tags/');
1016 }
1017}
1018
1019sub cmd_multi_fetch {
1020 $Git::SVN::no_reuse_existing = undef;
1021 my $remotes = Git::SVN::read_all_remotes();
1022 foreach my $repo_id (sort keys %$remotes) {
1023 if ($remotes->{$repo_id}->{url}) {
1024 Git::SVN::fetch_all($repo_id, $remotes);
1025 }
1026 }
1027}
1028
1029# this command is special because it requires no metadata
1030sub cmd_commit_diff {
1031 my ($ta, $tb, $url) = @_;
1032 my $usage = "Usage: $0 commit-diff -r<revision> ".
1033 "<tree-ish> <tree-ish> [<URL>]";
1034 fatal($usage) if (!defined $ta || !defined $tb);
1035 my $svn_path = '';
1036 if (!defined $url) {
1037 my $gs = eval { Git::SVN->new };
1038 if (!$gs) {
1039 fatal("Needed URL or usable git-svn --id in ",
1040 "the command-line\n", $usage);
1041 }
1042 $url = $gs->{url};
1043 $svn_path = $gs->{path};
1044 }
1045 unless (defined $_revision) {
1046 fatal("-r|--revision is a required argument\n", $usage);
1047 }
1048 if (defined $_message && defined $_file) {
1049 fatal("Both --message/-m and --file/-F specified ",
1050 "for the commit message.\n",
1051 "I have no idea what you mean");
1052 }
1053 if (defined $_file) {
1054 $_message = file_to_s($_file);
1055 } else {
1056 $_message ||= get_commit_entry($tb)->{log};
1057 }
1058 my $ra ||= Git::SVN::Ra->new($url);
1059 my $r = $_revision;
1060 if ($r eq 'HEAD') {
1061 $r = $ra->get_latest_revnum;
1062 } elsif ($r !~ /^\d+$/) {
1063 die "revision argument: $r not understood by git-svn\n";
1064 }
1065 my %ed_opts = ( r => $r,
1066 log => $_message,
1067 ra => $ra,
1068 tree_a => $ta,
1069 tree_b => $tb,
1070 editor_cb => sub { print "Committed r$_[0]\n" },
1071 svn_path => $svn_path );
1072 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
1073 print "No changes\n$ta == $tb\n";
1074 }
1075}
1076
1077sub escape_uri_only {
1078 my ($uri) = @_;
1079 my @tmp;
1080 foreach (split m{/}, $uri) {
1081 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
1082 push @tmp, $_;
1083 }
1084 join('/', @tmp);
1085}
1086
1087sub escape_url {
1088 my ($url) = @_;
1089 if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
1090 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
1091 $url = "$scheme://$domain$uri";
1092 }
1093 $url;
1094}
1095
1096sub cmd_info {
1097 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
1098 my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
1099 if (exists $_[1]) {
1100 die "Too many arguments specified\n";
1101 }
1102
1103 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
1104
1105 if (!$file_type && !$diff_status) {
1106 print STDERR "svn: '$path' is not under version control\n";
1107 exit 1;
1108 }
1109
1110 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1111 unless ($gs) {
1112 die "Unable to determine upstream SVN information from ",
1113 "working tree history\n";
1114 }
1115
1116 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
1117 $path = "." if $path eq "";
1118
1119 my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
1120
1121 if ($_url) {
1122 print escape_url($full_url), "\n";
1123 return;
1124 }
1125
1126 my $result = "Path: $path\n";
1127 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
1128 $result .= "URL: " . escape_url($full_url) . "\n";
1129
1130 eval {
1131 my $repos_root = $gs->repos_root;
1132 Git::SVN::remove_username($repos_root);
1133 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
1134 };
1135 if ($@) {
1136 $result .= "Repository Root: (offline)\n";
1137 }
1138 ::_req_svn();
1139 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
1140 ($SVN::Core::VERSION le '1.5.4' || $file_type ne "dir");
1141 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
1142
1143 $result .= "Node Kind: " .
1144 ($file_type eq "dir" ? "directory" : "file") . "\n";
1145
1146 my $schedule = $diff_status eq "A"
1147 ? "add"
1148 : ($diff_status eq "D" ? "delete" : "normal");
1149 $result .= "Schedule: $schedule\n";
1150
1151 if ($diff_status eq "A") {
1152 print $result, "\n";
1153 return;
1154 }
1155
1156 my ($lc_author, $lc_rev, $lc_date_utc);
1157 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
1158 my $log = command_output_pipe(@args);
1159 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
1160 while (<$log>) {
1161 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
1162 $lc_author = $1;
1163 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
1164 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
1165 (undef, $lc_rev, undef) = ::extract_metadata($1);
1166 }
1167 }
1168 close $log;
1169
1170 Git::SVN::Log::set_local_timezone();
1171
1172 $result .= "Last Changed Author: $lc_author\n";
1173 $result .= "Last Changed Rev: $lc_rev\n";
1174 $result .= "Last Changed Date: " .
1175 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
1176
1177 if ($file_type ne "dir") {
1178 my $text_last_updated_date =
1179 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
1180 $result .=
1181 "Text Last Updated: " .
1182 Git::SVN::Log::format_svn_date($text_last_updated_date) .
1183 "\n";
1184 my $checksum;
1185 if ($diff_status eq "D") {
1186 my ($fh, $ctx) =
1187 command_output_pipe(qw(cat-file blob), "HEAD:$path");
1188 if ($file_type eq "link") {
1189 my $file_name = <$fh>;
1190 $checksum = md5sum("link $file_name");
1191 } else {
1192 $checksum = md5sum($fh);
1193 }
1194 command_close_pipe($fh, $ctx);
1195 } elsif ($file_type eq "link") {
1196 my $file_name =
1197 command(qw(cat-file blob), "HEAD:$path");
1198 $checksum =
1199 md5sum("link " . $file_name);
1200 } else {
1201 open FILE, "<", $path or die $!;
1202 $checksum = md5sum(\*FILE);
1203 close FILE or die $!;
1204 }
1205 $result .= "Checksum: " . $checksum . "\n";
1206 }
1207
1208 print $result, "\n";
1209}
1210
1211sub cmd_reset {
1212 my $target = shift || $_revision or die "SVN revision required\n";
1213 $target = $1 if $target =~ /^r(\d+)$/;
1214 $target =~ /^\d+$/ or die "Numeric SVN revision expected\n";
1215 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1216 unless ($gs) {
1217 die "Unable to determine upstream SVN information from ".
1218 "history\n";
1219 }
1220 my ($r, $c) = $gs->find_rev_before($target, not $_fetch_parent);
1221 die "Cannot find SVN revision $target\n" unless defined($c);
1222 $gs->rev_map_set($r, $c, 'reset', $uuid);
1223 print "r$r = $c ($gs->{ref_id})\n";
1224}
1225
1226sub cmd_gc {
1227 if (!$can_compress) {
1228 warn "Compress::Zlib could not be found; unhandled.log " .
1229 "files will not be compressed.\n";
1230 }
1231 find({ wanted => \&gc_directory, no_chdir => 1}, "$ENV{GIT_DIR}/svn");
1232}
1233
1234########################### utility functions #########################
1235
1236sub rebase_cmd {
1237 my @cmd = qw/rebase/;
1238 push @cmd, '-v' if $_verbose;
1239 push @cmd, qw/--merge/ if $_merge;
1240 push @cmd, "--strategy=$_strategy" if $_strategy;
1241 @cmd;
1242}
1243
1244sub post_fetch_checkout {
1245 return if $_no_checkout;
1246 my $gs = $Git::SVN::_head or return;
1247 return if verify_ref('refs/heads/master^0');
1248
1249 # look for "trunk" ref if it exists
1250 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
1251 my $fetch = $remote->{fetch};
1252 if ($fetch) {
1253 foreach my $p (keys %$fetch) {
1254 basename($fetch->{$p}) eq 'trunk' or next;
1255 $gs = Git::SVN->new($fetch->{$p}, $gs->{repo_id}, $p);
1256 last;
1257 }
1258 }
1259
1260 my $valid_head = verify_ref('HEAD^0');
1261 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1262 return if ($valid_head || !verify_ref('HEAD^0'));
1263
1264 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1265 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1266 return if -f $index;
1267
1268 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1269 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1270 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1271 print STDERR "Checked out HEAD:\n ",
1272 $gs->full_url, " r", $gs->last_rev, "\n";
1273 if (auto_create_empty_directories($gs)) {
1274 $gs->mkemptydirs($gs->last_rev);
1275 }
1276}
1277
1278sub complete_svn_url {
1279 my ($url, $path) = @_;
1280 $path =~ s#/+$##;
1281 if ($path !~ m#^[a-z\+]+://#) {
1282 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1283 fatal("E: '$path' is not a complete URL ",
1284 "and a separate URL is not specified");
1285 }
1286 return ($url, $path);
1287 }
1288 return ($path, '');
1289}
1290
1291sub complete_url_ls_init {
1292 my ($ra, $repo_path, $switch, $pfx) = @_;
1293 unless ($repo_path) {
1294 print STDERR "W: $switch not specified\n";
1295 return;
1296 }
1297 $repo_path =~ s#/+$##;
1298 if ($repo_path =~ m#^[a-z\+]+://#) {
1299 $ra = Git::SVN::Ra->new($repo_path);
1300 $repo_path = '';
1301 } else {
1302 $repo_path =~ s#^/+##;
1303 unless ($ra) {
1304 fatal("E: '$repo_path' is not a complete URL ",
1305 "and a separate URL is not specified");
1306 }
1307 }
1308 my $url = $ra->{url};
1309 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1310 my $k = "svn-remote.$gs->{repo_id}.url";
1311 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1312 if ($orig_url && ($orig_url ne $gs->{url})) {
1313 die "$k already set: $orig_url\n",
1314 "wanted to set to: $gs->{url}\n";
1315 }
1316 command_oneline('config', $k, $gs->{url}) unless $orig_url;
1317 my $remote_path = "$gs->{path}/$repo_path";
1318 $remote_path =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
1319 $remote_path =~ s#/+#/#g;
1320 $remote_path =~ s#^/##g;
1321 $remote_path .= "/*" if $remote_path !~ /\*/;
1322 my ($n) = ($switch =~ /^--(\w+)/);
1323 if (length $pfx && $pfx !~ m#/$#) {
1324 die "--prefix='$pfx' must have a trailing slash '/'\n";
1325 }
1326 command_noisy('config',
1327 '--add',
1328 "svn-remote.$gs->{repo_id}.$n",
1329 "$remote_path:refs/remotes/$pfx*" .
1330 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1331}
1332
1333sub verify_ref {
1334 my ($ref) = @_;
1335 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1336 { STDERR => 0 }); };
1337}
1338
1339sub get_tree_from_treeish {
1340 my ($treeish) = @_;
1341 # $treeish can be a symbolic ref, too:
1342 my $type = command_oneline(qw/cat-file -t/, $treeish);
1343 my $expected;
1344 while ($type eq 'tag') {
1345 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1346 }
1347 if ($type eq 'commit') {
1348 $expected = (grep /^tree /, command(qw/cat-file commit/,
1349 $treeish))[0];
1350 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1351 die "Unable to get tree from $treeish\n" unless $expected;
1352 } elsif ($type eq 'tree') {
1353 $expected = $treeish;
1354 } else {
1355 die "$treeish is a $type, expected tree, tag or commit\n";
1356 }
1357 return $expected;
1358}
1359
1360sub get_commit_entry {
1361 my ($treeish) = shift;
1362 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1363 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1364 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1365 open my $log_fh, '>', $commit_editmsg or croak $!;
1366
1367 my $type = command_oneline(qw/cat-file -t/, $treeish);
1368 if ($type eq 'commit' || $type eq 'tag') {
1369 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1370 $type, $treeish);
1371 my $in_msg = 0;
1372 my $author;
1373 my $saw_from = 0;
1374 my $msgbuf = "";
1375 while (<$msg_fh>) {
1376 if (!$in_msg) {
1377 $in_msg = 1 if (/^\s*$/);
1378 $author = $1 if (/^author (.*>)/);
1379 } elsif (/^git-svn-id: /) {
1380 # skip this for now, we regenerate the
1381 # correct one on re-fetch anyways
1382 # TODO: set *:merge properties or like...
1383 } else {
1384 if (/^From:/ || /^Signed-off-by:/) {
1385 $saw_from = 1;
1386 }
1387 $msgbuf .= $_;
1388 }
1389 }
1390 $msgbuf =~ s/\s+$//s;
1391 if ($Git::SVN::_add_author_from && defined($author)
1392 && !$saw_from) {
1393 $msgbuf .= "\n\nFrom: $author";
1394 }
1395 print $log_fh $msgbuf or croak $!;
1396 command_close_pipe($msg_fh, $ctx);
1397 }
1398 close $log_fh or croak $!;
1399
1400 if ($_edit || ($type eq 'tree')) {
1401 chomp(my $editor = command_oneline(qw(var GIT_EDITOR)));
1402 system('sh', '-c', $editor.' "$@"', $editor, $commit_editmsg);
1403 }
1404 rename $commit_editmsg, $commit_msg or croak $!;
1405 {
1406 require Encode;
1407 # SVN requires messages to be UTF-8 when entering the repo
1408 local $/;
1409 open $log_fh, '<', $commit_msg or croak $!;
1410 binmode $log_fh;
1411 chomp($log_entry{log} = <$log_fh>);
1412
1413 my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
1414 my $msg = $log_entry{log};
1415
1416 eval { $msg = Encode::decode($enc, $msg, 1) };
1417 if ($@) {
1418 die "Could not decode as $enc:\n", $msg,
1419 "\nPerhaps you need to set i18n.commitencoding\n";
1420 }
1421
1422 eval { $msg = Encode::encode('UTF-8', $msg, 1) };
1423 die "Could not encode as UTF-8:\n$msg\n" if $@;
1424
1425 $log_entry{log} = $msg;
1426
1427 close $log_fh or croak $!;
1428 }
1429 unlink $commit_msg;
1430 \%log_entry;
1431}
1432
1433sub s_to_file {
1434 my ($str, $file, $mode) = @_;
1435 open my $fd,'>',$file or croak $!;
1436 print $fd $str,"\n" or croak $!;
1437 close $fd or croak $!;
1438 chmod ($mode &~ umask, $file) if (defined $mode);
1439}
1440
1441sub file_to_s {
1442 my $file = shift;
1443 open my $fd,'<',$file or croak "$!: file: $file\n";
1444 local $/;
1445 my $ret = <$fd>;
1446 close $fd or croak $!;
1447 $ret =~ s/\s*$//s;
1448 return $ret;
1449}
1450
1451# '<svn username> = real-name <email address>' mapping based on git-svnimport:
1452sub load_authors {
1453 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1454 my $log = $cmd eq 'log';
1455 while (<$authors>) {
1456 chomp;
1457 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1458 my ($user, $name, $email) = ($1, $2, $3);
1459 if ($log) {
1460 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1461 } else {
1462 $users{$user} = [$name, $email];
1463 }
1464 }
1465 close $authors or croak $!;
1466}
1467
1468# convert GetOpt::Long specs for use by git-config
1469sub read_git_config {
1470 my $opts = shift;
1471 my @config_only;
1472 foreach my $o (keys %$opts) {
1473 # if we have mixedCase and a long option-only, then
1474 # it's a config-only variable that we don't need for
1475 # the command-line.
1476 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1477 my $v = $opts->{$o};
1478 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1479 $key =~ s/-//g;
1480 my $arg = 'git config';
1481 $arg .= ' --int' if ($o =~ /[:=]i$/);
1482 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1483 if (ref $v eq 'ARRAY') {
1484 chomp(my @tmp = `$arg --get-all svn.$key`);
1485 @$v = @tmp if @tmp;
1486 } else {
1487 chomp(my $tmp = `$arg --get svn.$key`);
1488 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1489 $$v = $tmp;
1490 }
1491 }
1492 }
1493 delete @$opts{@config_only} if @config_only;
1494}
1495
1496sub extract_metadata {
1497 my $id = shift or return (undef, undef, undef);
1498 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1499 \s([a-f\d\-]+)$/ix);
1500 if (!defined $rev || !$uuid || !$url) {
1501 # some of the original repositories I made had
1502 # identifiers like this:
1503 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/i);
1504 }
1505 return ($url, $rev, $uuid);
1506}
1507
1508sub cmt_metadata {
1509 return extract_metadata((grep(/^git-svn-id: /,
1510 command(qw/cat-file commit/, shift)))[-1]);
1511}
1512
1513sub cmt_sha2rev_batch {
1514 my %s2r;
1515 my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1516 my $list = shift;
1517
1518 foreach my $sha (@{$list}) {
1519 my $first = 1;
1520 my $size = 0;
1521 print $out $sha, "\n";
1522
1523 while (my $line = <$in>) {
1524 if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1525 last;
1526 } elsif ($first &&
1527 $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1528 $first = 0;
1529 $size = $1;
1530 next;
1531 } elsif ($line =~ /^(git-svn-id: )/) {
1532 my (undef, $rev, undef) =
1533 extract_metadata($line);
1534 $s2r{$sha} = $rev;
1535 }
1536
1537 $size -= length($line);
1538 last if ($size == 0);
1539 }
1540 }
1541
1542 command_close_bidi_pipe($pid, $in, $out, $ctx);
1543
1544 return \%s2r;
1545}
1546
1547sub working_head_info {
1548 my ($head, $refs) = @_;
1549 my @args = qw/log --no-color --no-decorate --first-parent
1550 --pretty=medium/;
1551 my ($fh, $ctx) = command_output_pipe(@args, $head);
1552 my $hash;
1553 my %max;
1554 while (<$fh>) {
1555 if ( m{^commit ($::sha1)$} ) {
1556 unshift @$refs, $hash if $hash and $refs;
1557 $hash = $1;
1558 next;
1559 }
1560 next unless s{^\s*(git-svn-id:)}{$1};
1561 my ($url, $rev, $uuid) = extract_metadata($_);
1562 if (defined $url && defined $rev) {
1563 next if $max{$url} and $max{$url} < $rev;
1564 if (my $gs = Git::SVN->find_by_url($url)) {
1565 my $c = $gs->rev_map_get($rev, $uuid);
1566 if ($c && $c eq $hash) {
1567 close $fh; # break the pipe
1568 return ($url, $rev, $uuid, $gs);
1569 } else {
1570 $max{$url} ||= $gs->rev_map_max;
1571 }
1572 }
1573 }
1574 }
1575 command_close_pipe($fh, $ctx);
1576 (undef, undef, undef, undef);
1577}
1578
1579sub read_commit_parents {
1580 my ($parents, $c) = @_;
1581 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1582 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1583 @{$parents->{$c}} = split(/ /, $p);
1584}
1585
1586sub linearize_history {
1587 my ($gs, $refs) = @_;
1588 my %parents;
1589 foreach my $c (@$refs) {
1590 read_commit_parents(\%parents, $c);
1591 }
1592
1593 my @linear_refs;
1594 my %skip = ();
1595 my $last_svn_commit = $gs->last_commit;
1596 foreach my $c (reverse @$refs) {
1597 next if $c eq $last_svn_commit;
1598 last if $skip{$c};
1599
1600 unshift @linear_refs, $c;
1601 $skip{$c} = 1;
1602
1603 # we only want the first parent to diff against for linear
1604 # history, we save the rest to inject when we finalize the
1605 # svn commit
1606 my $fp_a = verify_ref("$c~1");
1607 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1608 if (!$fp_a || !$fp_b) {
1609 die "Commit $c\n",
1610 "has no parent commit, and therefore ",
1611 "nothing to diff against.\n",
1612 "You should be working from a repository ",
1613 "originally created by git-svn\n";
1614 }
1615 if ($fp_a ne $fp_b) {
1616 die "$c~1 = $fp_a, however parsing commit $c ",
1617 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1618 }
1619
1620 foreach my $p (@{$parents{$c}}) {
1621 $skip{$p} = 1;
1622 }
1623 }
1624 (\@linear_refs, \%parents);
1625}
1626
1627sub find_file_type_and_diff_status {
1628 my ($path) = @_;
1629 return ('dir', '') if $path eq '';
1630
1631 my $diff_output =
1632 command_oneline(qw(diff --cached --name-status --), $path) || "";
1633 my $diff_status = (split(' ', $diff_output))[0] || "";
1634
1635 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1636
1637 return (undef, undef) if !$diff_status && !$ls_tree;
1638
1639 if ($diff_status eq "A") {
1640 return ("link", $diff_status) if -l $path;
1641 return ("dir", $diff_status) if -d $path;
1642 return ("file", $diff_status);
1643 }
1644
1645 my $mode = (split(' ', $ls_tree))[0] || "";
1646
1647 return ("link", $diff_status) if $mode eq "120000";
1648 return ("dir", $diff_status) if $mode eq "040000";
1649 return ("file", $diff_status);
1650}
1651
1652sub md5sum {
1653 my $arg = shift;
1654 my $ref = ref $arg;
1655 my $md5 = Digest::MD5->new();
1656 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
1657 $md5->addfile($arg) or croak $!;
1658 } elsif ($ref eq 'SCALAR') {
1659 $md5->add($$arg) or croak $!;
1660 } elsif (!$ref) {
1661 $md5->add($arg) or croak $!;
1662 } else {
1663 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1664 }
1665 return $md5->hexdigest();
1666}
1667
1668sub gc_directory {
1669 if ($can_compress && -f $_ && basename($_) eq "unhandled.log") {
1670 my $out_filename = $_ . ".gz";
1671 open my $in_fh, "<", $_ or die "Unable to open $_: $!\n";
1672 binmode $in_fh;
1673 my $gz = Compress::Zlib::gzopen($out_filename, "ab") or
1674 die "Unable to open $out_filename: $!\n";
1675
1676 my $res;
1677 while ($res = sysread($in_fh, my $str, 1024)) {
1678 $gz->gzwrite($str) or
1679 die "Unable to write: ".$gz->gzerror()."!\n";
1680 }
1681 unlink $_ or die "unlink $File::Find::name: $!\n";
1682 } elsif (-f $_ && basename($_) eq "index") {
1683 unlink $_ or die "unlink $_: $!\n";
1684 }
1685}
1686
1687package Git::SVN;
1688use strict;
1689use warnings;
1690use Fcntl qw/:DEFAULT :seek/;
1691use constant rev_map_fmt => 'NH40';
1692use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1693 $_repack $_repack_flags $_use_svm_props $_head
1694 $_use_svnsync_props $no_reuse_existing $_minimize_url
1695 $_use_log_author $_add_author_from $_localtime/;
1696use Carp qw/croak/;
1697use File::Path qw/mkpath/;
1698use File::Copy qw/copy/;
1699use IPC::Open3;
1700use Memoize; # core since 5.8.0, Jul 2002
1701use Memoize::Storable;
1702
1703my ($_gc_nr, $_gc_period);
1704
1705# properties that we do not log:
1706my %SKIP_PROP;
1707BEGIN {
1708 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1709 svn:special svn:executable
1710 svn:entry:committed-rev
1711 svn:entry:last-author
1712 svn:entry:uuid
1713 svn:entry:committed-date/;
1714
1715 # some options are read globally, but can be overridden locally
1716 # per [svn-remote "..."] section. Command-line options will *NOT*
1717 # override options set in an [svn-remote "..."] section
1718 no strict 'refs';
1719 for my $option (qw/follow_parent no_metadata use_svm_props
1720 use_svnsync_props/) {
1721 my $key = $option;
1722 $key =~ tr/_//d;
1723 my $prop = "-$option";
1724 *$option = sub {
1725 my ($self) = @_;
1726 return $self->{$prop} if exists $self->{$prop};
1727 my $k = "svn-remote.$self->{repo_id}.$key";
1728 eval { command_oneline(qw/config --get/, $k) };
1729 if ($@) {
1730 $self->{$prop} = ${"Git::SVN::_$option"};
1731 } else {
1732 my $v = command_oneline(qw/config --bool/,$k);
1733 $self->{$prop} = $v eq 'false' ? 0 : 1;
1734 }
1735 return $self->{$prop};
1736 }
1737 }
1738}
1739
1740
1741my (%LOCKFILES, %INDEX_FILES);
1742END {
1743 unlink keys %LOCKFILES if %LOCKFILES;
1744 unlink keys %INDEX_FILES if %INDEX_FILES;
1745}
1746
1747sub resolve_local_globs {
1748 my ($url, $fetch, $glob_spec) = @_;
1749 return unless defined $glob_spec;
1750 my $ref = $glob_spec->{ref};
1751 my $path = $glob_spec->{path};
1752 foreach (command(qw#for-each-ref --format=%(refname) refs/#)) {
1753 next unless m#^$ref->{regex}$#;
1754 my $p = $1;
1755 my $pathname = desanitize_refname($path->full_path($p));
1756 my $refname = desanitize_refname($ref->full_path($p));
1757 if (my $existing = $fetch->{$pathname}) {
1758 if ($existing ne $refname) {
1759 die "Refspec conflict:\n",
1760 "existing: $existing\n",
1761 " globbed: $refname\n";
1762 }
1763 my $u = (::cmt_metadata("$refname"))[0];
1764 $u =~ s!^\Q$url\E(/|$)!! or die
1765 "$refname: '$url' not found in '$u'\n";
1766 if ($pathname ne $u) {
1767 warn "W: Refspec glob conflict ",
1768 "(ref: $refname):\n",
1769 "expected path: $pathname\n",
1770 " real path: $u\n",
1771 "Continuing ahead with $u\n";
1772 next;
1773 }
1774 } else {
1775 $fetch->{$pathname} = $refname;
1776 }
1777 }
1778}
1779
1780sub parse_revision_argument {
1781 my ($base, $head) = @_;
1782 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1783 return ($base, $head);
1784 }
1785 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1786 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1787 return ($head, $head) if ($::_revision eq 'HEAD');
1788 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1789 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1790 die "revision argument: $::_revision not understood by git-svn\n";
1791}
1792
1793sub fetch_all {
1794 my ($repo_id, $remotes) = @_;
1795 if (ref $repo_id) {
1796 my $gs = $repo_id;
1797 $repo_id = undef;
1798 $repo_id = $gs->{repo_id};
1799 }
1800 $remotes ||= read_all_remotes();
1801 my $remote = $remotes->{$repo_id} or
1802 die "[svn-remote \"$repo_id\"] unknown\n";
1803 my $fetch = $remote->{fetch};
1804 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1805 my (@gs, @globs);
1806 my $ra = Git::SVN::Ra->new($url);
1807 my $uuid = $ra->get_uuid;
1808 my $head = $ra->get_latest_revnum;
1809
1810 # ignore errors, $head revision may not even exist anymore
1811 eval { $ra->get_log("", $head, 0, 1, 0, 1, sub { $head = $_[1] }) };
1812 warn "W: $@\n" if $@;
1813
1814 my $base = defined $fetch ? $head : 0;
1815
1816 # read the max revs for wildcard expansion (branches/*, tags/*)
1817 foreach my $t (qw/branches tags/) {
1818 defined $remote->{$t} or next;
1819 push @globs, @{$remote->{$t}};
1820
1821 my $max_rev = eval { tmp_config(qw/--int --get/,
1822 "svn-remote.$repo_id.${t}-maxRev") };
1823 if (defined $max_rev && ($max_rev < $base)) {
1824 $base = $max_rev;
1825 } elsif (!defined $max_rev) {
1826 $base = 0;
1827 }
1828 }
1829
1830 if ($fetch) {
1831 foreach my $p (sort keys %$fetch) {
1832 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1833 my $lr = $gs->rev_map_max;
1834 if (defined $lr) {
1835 $base = $lr if ($lr < $base);
1836 }
1837 push @gs, $gs;
1838 }
1839 }
1840
1841 ($base, $head) = parse_revision_argument($base, $head);
1842 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1843}
1844
1845sub read_all_remotes {
1846 my $r = {};
1847 my $use_svm_props = eval { command_oneline(qw/config --bool
1848 svn.useSvmProps/) };
1849 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
1850 my $svn_refspec = qr{\s*(.*?)\s*:\s*(.+?)\s*};
1851 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1852 if (m!^(.+)\.fetch=$svn_refspec$!) {
1853 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
1854 die("svn-remote.$remote: remote ref '$remote_ref' "
1855 . "must start with 'refs/'\n")
1856 unless $remote_ref =~ m{^refs/};
1857 $local_ref = uri_decode($local_ref);
1858 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1859 $r->{$remote}->{svm} = {} if $use_svm_props;
1860 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
1861 $r->{$1}->{svm} = {};
1862 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1863 $r->{$1}->{url} = $2;
1864 } elsif (m!^(.+)\.pushurl=\s*(.*)\s*$!) {
1865 $r->{$1}->{pushurl} = $2;
1866 } elsif (m!^(.+)\.(branches|tags)=$svn_refspec$!) {
1867 my ($remote, $t, $local_ref, $remote_ref) =
1868 ($1, $2, $3, $4);
1869 die("svn-remote.$remote: remote ref '$remote_ref' ($t) "
1870 . "must start with 'refs/'\n")
1871 unless $remote_ref =~ m{^refs/};
1872 $local_ref = uri_decode($local_ref);
1873 my $rs = {
1874 t => $t,
1875 remote => $remote,
1876 path => Git::SVN::GlobSpec->new($local_ref, 1),
1877 ref => Git::SVN::GlobSpec->new($remote_ref, 0) };
1878 if (length($rs->{ref}->{right}) != 0) {
1879 die "The '*' glob character must be the last ",
1880 "character of '$remote_ref'\n";
1881 }
1882 push @{ $r->{$remote}->{$t} }, $rs;
1883 }
1884 }
1885
1886 map {
1887 if (defined $r->{$_}->{svm}) {
1888 my $svm;
1889 eval {
1890 my $section = "svn-remote.$_";
1891 $svm = {
1892 source => tmp_config('--get',
1893 "$section.svm-source"),
1894 replace => tmp_config('--get',
1895 "$section.svm-replace"),
1896 }
1897 };
1898 $r->{$_}->{svm} = $svm;
1899 }
1900 } keys %$r;
1901
1902 $r;
1903}
1904
1905sub init_vars {
1906 $_gc_nr = $_gc_period = 1000;
1907 if (defined $_repack || defined $_repack_flags) {
1908 warn "Repack options are obsolete; they have no effect.\n";
1909 }
1910}
1911
1912sub verify_remotes_sanity {
1913 return unless -d $ENV{GIT_DIR};
1914 my %seen;
1915 foreach (command(qw/config -l/)) {
1916 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1917 if ($seen{$1}) {
1918 die "Remote ref refs/remote/$1 is tracked by",
1919 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1920 "Please resolve this ambiguity in ",
1921 "your git configuration file before ",
1922 "continuing\n";
1923 }
1924 $seen{$1} = $_;
1925 }
1926 }
1927}
1928
1929sub find_existing_remote {
1930 my ($url, $remotes) = @_;
1931 return undef if $no_reuse_existing;
1932 my $existing;
1933 foreach my $repo_id (keys %$remotes) {
1934 my $u = $remotes->{$repo_id}->{url} or next;
1935 next if $u ne $url;
1936 $existing = $repo_id;
1937 last;
1938 }
1939 $existing;
1940}
1941
1942sub init_remote_config {
1943 my ($self, $url, $no_write) = @_;
1944 $url =~ s!/+$!!; # strip trailing slash
1945 my $r = read_all_remotes();
1946 my $existing = find_existing_remote($url, $r);
1947 if ($existing) {
1948 unless ($no_write) {
1949 print STDERR "Using existing ",
1950 "[svn-remote \"$existing\"]\n";
1951 }
1952 $self->{repo_id} = $existing;
1953 } elsif ($_minimize_url) {
1954 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1955 $existing = find_existing_remote($min_url, $r);
1956 if ($existing) {
1957 unless ($no_write) {
1958 print STDERR "Using existing ",
1959 "[svn-remote \"$existing\"]\n";
1960 }
1961 $self->{repo_id} = $existing;
1962 }
1963 if ($min_url ne $url) {
1964 unless ($no_write) {
1965 print STDERR "Using higher level of URL: ",
1966 "$url => $min_url\n";
1967 }
1968 my $old_path = $self->{path};
1969 $self->{path} = $url;
1970 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1971 if (length $old_path) {
1972 $self->{path} .= "/$old_path";
1973 }
1974 $url = $min_url;
1975 }
1976 }
1977 my $orig_url;
1978 if (!$existing) {
1979 # verify that we aren't overwriting anything:
1980 $orig_url = eval {
1981 command_oneline('config', '--get',
1982 "svn-remote.$self->{repo_id}.url")
1983 };
1984 if ($orig_url && ($orig_url ne $url)) {
1985 die "svn-remote.$self->{repo_id}.url already set: ",
1986 "$orig_url\nwanted to set to: $url\n";
1987 }
1988 }
1989 my ($xrepo_id, $xpath) = find_ref($self->refname);
1990 if (!$no_write && defined $xpath) {
1991 die "svn-remote.$xrepo_id.fetch already set to track ",
1992 "$xpath:", $self->refname, "\n";
1993 }
1994 unless ($no_write) {
1995 command_noisy('config',
1996 "svn-remote.$self->{repo_id}.url", $url);
1997 $self->{path} =~ s{^/}{};
1998 $self->{path} =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
1999 command_noisy('config', '--add',
2000 "svn-remote.$self->{repo_id}.fetch",
2001 "$self->{path}:".$self->refname);
2002 }
2003 $self->{url} = $url;
2004}
2005
2006sub find_by_url { # repos_root and, path are optional
2007 my ($class, $full_url, $repos_root, $path) = @_;
2008
2009 return undef unless defined $full_url;
2010 remove_username($full_url);
2011 remove_username($repos_root) if defined $repos_root;
2012 my $remotes = read_all_remotes();
2013 if (defined $full_url && defined $repos_root && !defined $path) {
2014 $path = $full_url;
2015 $path =~ s#^\Q$repos_root\E(?:/|$)##;
2016 }
2017 foreach my $repo_id (keys %$remotes) {
2018 my $u = $remotes->{$repo_id}->{url} or next;
2019 remove_username($u);
2020 next if defined $repos_root && $repos_root ne $u;
2021
2022 my $fetch = $remotes->{$repo_id}->{fetch} || {};
2023 foreach my $t (qw/branches tags/) {
2024 foreach my $globspec (@{$remotes->{$repo_id}->{$t}}) {
2025 resolve_local_globs($u, $fetch, $globspec);
2026 }
2027 }
2028 my $p = $path;
2029 my $rwr = rewrite_root({repo_id => $repo_id});
2030 my $svm = $remotes->{$repo_id}->{svm}
2031 if defined $remotes->{$repo_id}->{svm};
2032 unless (defined $p) {
2033 $p = $full_url;
2034 my $z = $u;
2035 my $prefix = '';
2036 if ($rwr) {
2037 $z = $rwr;
2038 remove_username($z);
2039 } elsif (defined $svm) {
2040 $z = $svm->{source};
2041 $prefix = $svm->{replace};
2042 $prefix =~ s#^\Q$u\E(?:/|$)##;
2043 $prefix =~ s#/$##;
2044 }
2045 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
2046 }
2047 foreach my $f (keys %$fetch) {
2048 next if $f ne $p;
2049 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
2050 }
2051 }
2052 undef;
2053}
2054
2055sub init {
2056 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
2057 my $self = _new($class, $repo_id, $ref_id, $path);
2058 if (defined $url) {
2059 $self->init_remote_config($url, $no_write);
2060 }
2061 $self;
2062}
2063
2064sub find_ref {
2065 my ($ref_id) = @_;
2066 foreach (command(qw/config -l/)) {
2067 next unless m!^svn-remote\.(.+)\.fetch=
2068 \s*(.*?)\s*:\s*(.+?)\s*$!x;
2069 my ($repo_id, $path, $ref) = ($1, $2, $3);
2070 if ($ref eq $ref_id) {
2071 $path = '' if ($path =~ m#^\./?#);
2072 return ($repo_id, $path);
2073 }
2074 }
2075 (undef, undef, undef);
2076}
2077
2078sub new {
2079 my ($class, $ref_id, $repo_id, $path) = @_;
2080 if (defined $ref_id && !defined $repo_id && !defined $path) {
2081 ($repo_id, $path) = find_ref($ref_id);
2082 if (!defined $repo_id) {
2083 die "Could not find a \"svn-remote.*.fetch\" key ",
2084 "in the repository configuration matching: ",
2085 "$ref_id\n";
2086 }
2087 }
2088 my $self = _new($class, $repo_id, $ref_id, $path);
2089 if (!defined $self->{path} || !length $self->{path}) {
2090 my $fetch = command_oneline('config', '--get',
2091 "svn-remote.$repo_id.fetch",
2092 ":$ref_id\$") or
2093 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
2094 "\":$ref_id\$\" in config\n";
2095 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
2096 }
2097 $self->{path} =~ s{/+}{/}g;
2098 $self->{path} =~ s{\A/}{};
2099 $self->{path} =~ s{/\z}{};
2100 $self->{url} = command_oneline('config', '--get',
2101 "svn-remote.$repo_id.url") or
2102 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
2103 $self->{pushurl} = eval { command_oneline('config', '--get',
2104 "svn-remote.$repo_id.pushurl") };
2105 $self->rebuild;
2106 $self;
2107}
2108
2109sub refname {
2110 my ($refname) = $_[0]->{ref_id} ;
2111
2112 # It cannot end with a slash /, we'll throw up on this because
2113 # SVN can't have directories with a slash in their name, either:
2114 if ($refname =~ m{/$}) {
2115 die "ref: '$refname' ends with a trailing slash, this is ",
2116 "not permitted by git nor Subversion\n";
2117 }
2118
2119 # It cannot have ASCII control character space, tilde ~, caret ^,
2120 # colon :, question-mark ?, asterisk *, space, or open bracket [
2121 # anywhere.
2122 #
2123 # Additionally, % must be escaped because it is used for escaping
2124 # and we want our escaped refname to be reversible
2125 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
2126
2127 # no slash-separated component can begin with a dot .
2128 # /.* becomes /%2E*
2129 $refname =~ s{/\.}{/%2E}g;
2130
2131 # It cannot have two consecutive dots .. anywhere
2132 # .. becomes %2E%2E
2133 $refname =~ s{\.\.}{%2E%2E}g;
2134
2135 # trailing dots and .lock are not allowed
2136 # .$ becomes %2E and .lock becomes %2Elock
2137 $refname =~ s{\.(?=$|lock$)}{%2E};
2138
2139 # the sequence @{ is used to access the reflog
2140 # @{ becomes %40{
2141 $refname =~ s{\@\{}{%40\{}g;
2142
2143 return $refname;
2144}
2145
2146sub desanitize_refname {
2147 my ($refname) = @_;
2148 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
2149 return $refname;
2150}
2151
2152sub svm_uuid {
2153 my ($self) = @_;
2154 return $self->{svm}->{uuid} if $self->svm;
2155 $self->ra;
2156 unless ($self->{svm}) {
2157 die "SVM UUID not cached, and reading remotely failed\n";
2158 }
2159 $self->{svm}->{uuid};
2160}
2161
2162sub svm {
2163 my ($self) = @_;
2164 return $self->{svm} if $self->{svm};
2165 my $svm;
2166 # see if we have it in our config, first:
2167 eval {
2168 my $section = "svn-remote.$self->{repo_id}";
2169 $svm = {
2170 source => tmp_config('--get', "$section.svm-source"),
2171 uuid => tmp_config('--get', "$section.svm-uuid"),
2172 replace => tmp_config('--get', "$section.svm-replace"),
2173 }
2174 };
2175 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
2176 $self->{svm} = $svm;
2177 }
2178 $self->{svm};
2179}
2180
2181sub _set_svm_vars {
2182 my ($self, $ra) = @_;
2183 return $ra if $self->svm;
2184
2185 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
2186 "(svm:source, svm:uuid) ",
2187 "from the following URLs:\n" );
2188 sub read_svm_props {
2189 my ($self, $ra, $path, $r) = @_;
2190 my $props = ($ra->get_dir($path, $r))[2];
2191 my $src = $props->{'svm:source'};
2192 my $uuid = $props->{'svm:uuid'};
2193 return undef if (!$src || !$uuid);
2194
2195 chomp($src, $uuid);
2196
2197 $uuid =~ m{^[0-9a-f\-]{30,}$}i
2198 or die "doesn't look right - svm:uuid is '$uuid'\n";
2199
2200 # the '!' is used to mark the repos_root!/relative/path
2201 $src =~ s{/?!/?}{/};
2202 $src =~ s{/+$}{}; # no trailing slashes please
2203 # username is of no interest
2204 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
2205
2206 my $replace = $ra->{url};
2207 $replace .= "/$path" if length $path;
2208
2209 my $section = "svn-remote.$self->{repo_id}";
2210 tmp_config("$section.svm-source", $src);
2211 tmp_config("$section.svm-replace", $replace);
2212 tmp_config("$section.svm-uuid", $uuid);
2213 $self->{svm} = {
2214 source => $src,
2215 uuid => $uuid,
2216 replace => $replace
2217 };
2218 }
2219
2220 my $r = $ra->get_latest_revnum;
2221 my $path = $self->{path};
2222 my %tried;
2223 while (length $path) {
2224 unless ($tried{"$self->{url}/$path"}) {
2225 return $ra if $self->read_svm_props($ra, $path, $r);
2226 $tried{"$self->{url}/$path"} = 1;
2227 }
2228 $path =~ s#/?[^/]+$##;
2229 }
2230 die "Path: '$path' should be ''\n" if $path ne '';
2231 return $ra if $self->read_svm_props($ra, $path, $r);
2232 $tried{"$self->{url}/$path"} = 1;
2233
2234 if ($ra->{repos_root} eq $self->{url}) {
2235 die @err, (map { " $_\n" } keys %tried), "\n";
2236 }
2237
2238 # nope, make sure we're connected to the repository root:
2239 my $ok;
2240 my @tried_b;
2241 $path = $ra->{svn_path};
2242 $ra = Git::SVN::Ra->new($ra->{repos_root});
2243 while (length $path) {
2244 unless ($tried{"$ra->{url}/$path"}) {
2245 $ok = $self->read_svm_props($ra, $path, $r);
2246 last if $ok;
2247 $tried{"$ra->{url}/$path"} = 1;
2248 }
2249 $path =~ s#/?[^/]+$##;
2250 }
2251 die "Path: '$path' should be ''\n" if $path ne '';
2252 $ok ||= $self->read_svm_props($ra, $path, $r);
2253 $tried{"$ra->{url}/$path"} = 1;
2254 if (!$ok) {
2255 die @err, (map { " $_\n" } keys %tried), "\n";
2256 }
2257 Git::SVN::Ra->new($self->{url});
2258}
2259
2260sub svnsync {
2261 my ($self) = @_;
2262 return $self->{svnsync} if $self->{svnsync};
2263
2264 if ($self->no_metadata) {
2265 die "Can't have both 'noMetadata' and ",
2266 "'useSvnsyncProps' options set!\n";
2267 }
2268 if ($self->rewrite_root) {
2269 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
2270 "options set!\n";
2271 }
2272 if ($self->rewrite_uuid) {
2273 die "Can't have both 'useSvnsyncProps' and 'rewriteUUID' ",
2274 "options set!\n";
2275 }
2276
2277 my $svnsync;
2278 # see if we have it in our config, first:
2279 eval {
2280 my $section = "svn-remote.$self->{repo_id}";
2281
2282 my $url = tmp_config('--get', "$section.svnsync-url");
2283 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2284 die "doesn't look right - svn:sync-from-url is '$url'\n";
2285
2286 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
2287 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2288 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2289
2290 $svnsync = { url => $url, uuid => $uuid }
2291 };
2292 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
2293 return $self->{svnsync} = $svnsync;
2294 }
2295
2296 my $err = "useSvnsyncProps set, but failed to read " .
2297 "svnsync property: svn:sync-from-";
2298 my $rp = $self->ra->rev_proplist(0);
2299
2300 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
2301 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2302 die "doesn't look right - svn:sync-from-url is '$url'\n";
2303
2304 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
2305 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2306 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2307
2308 my $section = "svn-remote.$self->{repo_id}";
2309 tmp_config('--add', "$section.svnsync-uuid", $uuid);
2310 tmp_config('--add', "$section.svnsync-url", $url);
2311 return $self->{svnsync} = { url => $url, uuid => $uuid };
2312}
2313
2314# this allows us to memoize our SVN::Ra UUID locally and avoid a
2315# remote lookup (useful for 'git svn log').
2316sub ra_uuid {
2317 my ($self) = @_;
2318 unless ($self->{ra_uuid}) {
2319 my $key = "svn-remote.$self->{repo_id}.uuid";
2320 my $uuid = eval { tmp_config('--get', $key) };
2321 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/i) {
2322 $self->{ra_uuid} = $uuid;
2323 } else {
2324 die "ra_uuid called without URL\n" unless $self->{url};
2325 $self->{ra_uuid} = $self->ra->get_uuid;
2326 tmp_config('--add', $key, $self->{ra_uuid});
2327 }
2328 }
2329 $self->{ra_uuid};
2330}
2331
2332sub _set_repos_root {
2333 my ($self, $repos_root) = @_;
2334 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2335 $repos_root ||= $self->ra->{repos_root};
2336 tmp_config($k, $repos_root);
2337 $repos_root;
2338}
2339
2340sub repos_root {
2341 my ($self) = @_;
2342 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2343 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
2344}
2345
2346sub ra {
2347 my ($self) = shift;
2348 my $ra = Git::SVN::Ra->new($self->{url});
2349 $self->_set_repos_root($ra->{repos_root});
2350 if ($self->use_svm_props && !$self->{svm}) {
2351 if ($self->no_metadata) {
2352 die "Can't have both 'noMetadata' and ",
2353 "'useSvmProps' options set!\n";
2354 } elsif ($self->use_svnsync_props) {
2355 die "Can't have both 'useSvnsyncProps' and ",
2356 "'useSvmProps' options set!\n";
2357 }
2358 $ra = $self->_set_svm_vars($ra);
2359 $self->{-want_revprops} = 1;
2360 }
2361 $ra;
2362}
2363
2364# prop_walk(PATH, REV, SUB)
2365# -------------------------
2366# Recursively traverse PATH at revision REV and invoke SUB for each
2367# directory that contains a SVN property. SUB will be invoked as
2368# follows: &SUB(gs, path, props); where `gs' is this instance of
2369# Git::SVN, `path' the path to the directory where the properties
2370# `props' were found. The `path' will be relative to point of checkout,
2371# that is, if url://repo/trunk is the current Git branch, and that
2372# directory contains a sub-directory `d', SUB will be invoked with `/d/'
2373# as `path' (note the trailing `/').
2374sub prop_walk {
2375 my ($self, $path, $rev, $sub) = @_;
2376
2377 $path =~ s#^/##;
2378 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2379 $path =~ s#^/*#/#g;
2380 my $p = $path;
2381 # Strip the irrelevant part of the path.
2382 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2383 # Ensure the path is terminated by a `/'.
2384 $p =~ s#/*$#/#;
2385
2386 # The properties contain all the internal SVN stuff nobody
2387 # (usually) cares about.
2388 my $interesting_props = 0;
2389 foreach (keys %{$props}) {
2390 # If it doesn't start with `svn:', it must be a
2391 # user-defined property.
2392 ++$interesting_props and next if $_ !~ /^svn:/;
2393 # FIXME: Fragile, if SVN adds new public properties,
2394 # this needs to be updated.
2395 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2396 |eol-style|mime-type
2397 |externals|needs-lock)$/x;
2398 }
2399 &$sub($self, $p, $props) if $interesting_props;
2400
2401 foreach (sort keys %$dirent) {
2402 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
2403 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
2404 }
2405}
2406
2407sub last_rev { ($_[0]->last_rev_commit)[0] }
2408sub last_commit { ($_[0]->last_rev_commit)[1] }
2409
2410# returns the newest SVN revision number and newest commit SHA1
2411sub last_rev_commit {
2412 my ($self) = @_;
2413 if (defined $self->{last_rev} && defined $self->{last_commit}) {
2414 return ($self->{last_rev}, $self->{last_commit});
2415 }
2416 my $c = ::verify_ref($self->refname.'^0');
2417 if ($c && !$self->use_svm_props && !$self->no_metadata) {
2418 my $rev = (::cmt_metadata($c))[1];
2419 if (defined $rev) {
2420 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2421 return ($rev, $c);
2422 }
2423 }
2424 my $map_path = $self->map_path;
2425 unless (-e $map_path) {
2426 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2427 return (undef, undef);
2428 }
2429 my ($rev, $commit) = $self->rev_map_max(1);
2430 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2431 return ($rev, $commit);
2432}
2433
2434sub get_fetch_range {
2435 my ($self, $min, $max) = @_;
2436 $max ||= $self->ra->get_latest_revnum;
2437 $min ||= $self->rev_map_max;
2438 (++$min, $max);
2439}
2440
2441sub tmp_config {
2442 my (@args) = @_;
2443 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2444 my $config = "$ENV{GIT_DIR}/svn/.metadata";
2445 if (! -f $config && -f $old_def_config) {
2446 rename $old_def_config, $config or
2447 die "Failed rename $old_def_config => $config: $!\n";
2448 }
2449 my $old_config = $ENV{GIT_CONFIG};
2450 $ENV{GIT_CONFIG} = $config;
2451 $@ = undef;
2452 my @ret = eval {
2453 unless (-f $config) {
2454 mkfile($config);
2455 open my $fh, '>', $config or
2456 die "Can't open $config: $!\n";
2457 print $fh "; This file is used internally by ",
2458 "git-svn\n" or die
2459 "Couldn't write to $config: $!\n";
2460 print $fh "; You should not have to edit it\n" or
2461 die "Couldn't write to $config: $!\n";
2462 close $fh or die "Couldn't close $config: $!\n";
2463 }
2464 command('config', @args);
2465 };
2466 my $err = $@;
2467 if (defined $old_config) {
2468 $ENV{GIT_CONFIG} = $old_config;
2469 } else {
2470 delete $ENV{GIT_CONFIG};
2471 }
2472 die $err if $err;
2473 wantarray ? @ret : $ret[0];
2474}
2475
2476sub tmp_index_do {
2477 my ($self, $sub) = @_;
2478 my $old_index = $ENV{GIT_INDEX_FILE};
2479 $ENV{GIT_INDEX_FILE} = $self->{index};
2480 $@ = undef;
2481 my @ret = eval {
2482 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2483 mkpath([$dir]) unless -d $dir;
2484 &$sub;
2485 };
2486 my $err = $@;
2487 if (defined $old_index) {
2488 $ENV{GIT_INDEX_FILE} = $old_index;
2489 } else {
2490 delete $ENV{GIT_INDEX_FILE};
2491 }
2492 die $err if $err;
2493 wantarray ? @ret : $ret[0];
2494}
2495
2496sub assert_index_clean {
2497 my ($self, $treeish) = @_;
2498
2499 $self->tmp_index_do(sub {
2500 command_noisy('read-tree', $treeish) unless -e $self->{index};
2501 my $x = command_oneline('write-tree');
2502 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2503 /^tree ($::sha1)/mo);
2504 return if $y eq $x;
2505
2506 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2507 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2508 command_noisy('read-tree', $treeish);
2509 $x = command_oneline('write-tree');
2510 if ($y ne $x) {
2511 ::fatal "trees ($treeish) $y != $x\n",
2512 "Something is seriously wrong...";
2513 }
2514 });
2515}
2516
2517sub get_commit_parents {
2518 my ($self, $log_entry) = @_;
2519 my (%seen, @ret, @tmp);
2520 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2521 if (my $ip = $self->{inject_parents}) {
2522 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2523 push @tmp, $commit;
2524 }
2525 }
2526 if (my $cur = ::verify_ref($self->refname.'^0')) {
2527 push @tmp, $cur;
2528 }
2529 if (my $ipd = $self->{inject_parents_dcommit}) {
2530 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2531 push @tmp, @$commit;
2532 }
2533 }
2534 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2535 while (my $p = shift @tmp) {
2536 next if $seen{$p};
2537 $seen{$p} = 1;
2538 push @ret, $p;
2539 }
2540 @ret;
2541}
2542
2543sub rewrite_root {
2544 my ($self) = @_;
2545 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2546 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2547 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2548 if ($rwr) {
2549 $rwr =~ s#/+$##;
2550 if ($rwr !~ m#^[a-z\+]+://#) {
2551 die "$rwr is not a valid URL (key: $k)\n";
2552 }
2553 }
2554 $self->{-rewrite_root} = $rwr;
2555}
2556
2557sub rewrite_uuid {
2558 my ($self) = @_;
2559 return $self->{-rewrite_uuid} if exists $self->{-rewrite_uuid};
2560 my $k = "svn-remote.$self->{repo_id}.rewriteUUID";
2561 my $rwid = eval { command_oneline(qw/config --get/, $k) };
2562 if ($rwid) {
2563 $rwid =~ s#/+$##;
2564 if ($rwid !~ m#^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$#) {
2565 die "$rwid is not a valid UUID (key: $k)\n";
2566 }
2567 }
2568 $self->{-rewrite_uuid} = $rwid;
2569}
2570
2571sub metadata_url {
2572 my ($self) = @_;
2573 ($self->rewrite_root || $self->{url}) .
2574 (length $self->{path} ? '/' . $self->{path} : '');
2575}
2576
2577sub full_url {
2578 my ($self) = @_;
2579 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2580}
2581
2582sub full_pushurl {
2583 my ($self) = @_;
2584 if ($self->{pushurl}) {
2585 return $self->{pushurl} . (length $self->{path} ? '/' .
2586 $self->{path} : '');
2587 } else {
2588 return $self->full_url;
2589 }
2590}
2591
2592sub set_commit_header_env {
2593 my ($log_entry) = @_;
2594 my %env;
2595 foreach my $ned (qw/NAME EMAIL DATE/) {
2596 foreach my $ac (qw/AUTHOR COMMITTER/) {
2597 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2598 }
2599 }
2600
2601 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2602 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2603 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2604
2605 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2606 ? $log_entry->{commit_name}
2607 : $log_entry->{name};
2608 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2609 ? $log_entry->{commit_email}
2610 : $log_entry->{email};
2611 \%env;
2612}
2613
2614sub restore_commit_header_env {
2615 my ($env) = @_;
2616 foreach my $ned (qw/NAME EMAIL DATE/) {
2617 foreach my $ac (qw/AUTHOR COMMITTER/) {
2618 my $k = "GIT_${ac}_${ned}";
2619 if (defined $env->{$k}) {
2620 $ENV{$k} = $env->{$k};
2621 } else {
2622 delete $ENV{$k};
2623 }
2624 }
2625 }
2626}
2627
2628sub gc {
2629 command_noisy('gc', '--auto');
2630};
2631
2632sub do_git_commit {
2633 my ($self, $log_entry) = @_;
2634 my $lr = $self->last_rev;
2635 if (defined $lr && $lr >= $log_entry->{revision}) {
2636 die "Last fetched revision of ", $self->refname,
2637 " was r$lr, but we are about to fetch: ",
2638 "r$log_entry->{revision}!\n";
2639 }
2640 if (my $c = $self->rev_map_get($log_entry->{revision})) {
2641 croak "$log_entry->{revision} = $c already exists! ",
2642 "Why are we refetching it?\n";
2643 }
2644 my $old_env = set_commit_header_env($log_entry);
2645 my $tree = $log_entry->{tree};
2646 if (!defined $tree) {
2647 $tree = $self->tmp_index_do(sub {
2648 command_oneline('write-tree') });
2649 }
2650 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2651
2652 my @exec = ('git', 'commit-tree', $tree);
2653 foreach ($self->get_commit_parents($log_entry)) {
2654 push @exec, '-p', $_;
2655 }
2656 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2657 or croak $!;
2658 binmode $msg_fh;
2659
2660 # we always get UTF-8 from SVN, but we may want our commits in
2661 # a different encoding.
2662 if (my $enc = Git::config('i18n.commitencoding')) {
2663 require Encode;
2664 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
2665 }
2666 print $msg_fh $log_entry->{log} or croak $!;
2667 restore_commit_header_env($old_env);
2668 unless ($self->no_metadata) {
2669 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2670 or croak $!;
2671 }
2672 $msg_fh->flush == 0 or croak $!;
2673 close $msg_fh or croak $!;
2674 chomp(my $commit = do { local $/; <$out_fh> });
2675 close $out_fh or croak $!;
2676 waitpid $pid, 0;
2677 croak $? if $?;
2678 if ($commit !~ /^$::sha1$/o) {
2679 die "Failed to commit, invalid sha1: $commit\n";
2680 }
2681
2682 $self->rev_map_set($log_entry->{revision}, $commit, 1);
2683
2684 $self->{last_rev} = $log_entry->{revision};
2685 $self->{last_commit} = $commit;
2686 print "r$log_entry->{revision}" unless $::_q > 1;
2687 if (defined $log_entry->{svm_revision}) {
2688 print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
2689 $self->rev_map_set($log_entry->{svm_revision}, $commit,
2690 0, $self->svm_uuid);
2691 }
2692 print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
2693 if (--$_gc_nr == 0) {
2694 $_gc_nr = $_gc_period;
2695 gc();
2696 }
2697 return $commit;
2698}
2699
2700sub match_paths {
2701 my ($self, $paths, $r) = @_;
2702 return 1 if $self->{path} eq '';
2703 if (my $path = $paths->{"/$self->{path}"}) {
2704 return ($path->{action} eq 'D') ? 0 : 1;
2705 }
2706 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
2707 if (grep /$self->{path_regex}/, keys %$paths) {
2708 return 1;
2709 }
2710 my $c = '';
2711 foreach (split m#/#, $self->{path}) {
2712 $c .= "/$_";
2713 next unless ($paths->{$c} &&
2714 ($paths->{$c}->{action} =~ /^[AR]$/));
2715 if ($self->ra->check_path($self->{path}, $r) ==
2716 $SVN::Node::dir) {
2717 return 1;
2718 }
2719 }
2720 return 0;
2721}
2722
2723sub find_parent_branch {
2724 my ($self, $paths, $rev) = @_;
2725 return undef unless $self->follow_parent;
2726 unless (defined $paths) {
2727 my $err_handler = $SVN::Error::handler;
2728 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2729 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1,
2730 sub { $paths = $_[0] });
2731 $SVN::Error::handler = $err_handler;
2732 }
2733 return undef unless defined $paths;
2734
2735 # look for a parent from another branch:
2736 my @b_path_components = split m#/#, $self->{path};
2737 my @a_path_components;
2738 my $i;
2739 while (@b_path_components) {
2740 $i = $paths->{'/'.join('/', @b_path_components)};
2741 last if $i && defined $i->{copyfrom_path};
2742 unshift(@a_path_components, pop(@b_path_components));
2743 }
2744 return undef unless defined $i && defined $i->{copyfrom_path};
2745 my $branch_from = $i->{copyfrom_path};
2746 if (@a_path_components) {
2747 print STDERR "branch_from: $branch_from => ";
2748 $branch_from .= '/'.join('/', @a_path_components);
2749 print STDERR $branch_from, "\n";
2750 }
2751 my $r = $i->{copyfrom_rev};
2752 my $repos_root = $self->ra->{repos_root};
2753 my $url = $self->ra->{url};
2754 my $new_url = $url . $branch_from;
2755 print STDERR "Found possible branch point: ",
2756 "$new_url => ", $self->full_url, ", $r\n"
2757 unless $::_q > 1;
2758 $branch_from =~ s#^/##;
2759 my $gs = $self->other_gs($new_url, $url,
2760 $branch_from, $r, $self->{ref_id});
2761 my ($r0, $parent) = $gs->find_rev_before($r, 1);
2762 {
2763 my ($base, $head);
2764 if (!defined $r0 || !defined $parent) {
2765 ($base, $head) = parse_revision_argument(0, $r);
2766 } else {
2767 if ($r0 < $r) {
2768 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
2769 0, 1, sub { $base = $_[1] - 1 });
2770 }
2771 }
2772 if (defined $base && $base <= $r) {
2773 $gs->fetch($base, $r);
2774 }
2775 ($r0, $parent) = $gs->find_rev_before($r, 1);
2776 }
2777 if (defined $r0 && defined $parent) {
2778 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n"
2779 unless $::_q > 1;
2780 my $ed;
2781 if ($self->ra->can_do_switch) {
2782 $self->assert_index_clean($parent);
2783 print STDERR "Following parent with do_switch\n"
2784 unless $::_q > 1;
2785 # do_switch works with svn/trunk >= r22312, but that
2786 # is not included with SVN 1.4.3 (the latest version
2787 # at the moment), so we can't rely on it
2788 $self->{last_rev} = $r0;
2789 $self->{last_commit} = $parent;
2790 $ed = SVN::Git::Fetcher->new($self, $gs->{path});
2791 $gs->ra->gs_do_switch($r0, $rev, $gs,
2792 $self->full_url, $ed)
2793 or die "SVN connection failed somewhere...\n";
2794 } elsif ($self->ra->trees_match($new_url, $r0,
2795 $self->full_url, $rev)) {
2796 print STDERR "Trees match:\n",
2797 " $new_url\@$r0\n",
2798 " ${\$self->full_url}\@$rev\n",
2799 "Following parent with no changes\n"
2800 unless $::_q > 1;
2801 $self->tmp_index_do(sub {
2802 command_noisy('read-tree', $parent);
2803 });
2804 $self->{last_commit} = $parent;
2805 } else {
2806 print STDERR "Following parent with do_update\n"
2807 unless $::_q > 1;
2808 $ed = SVN::Git::Fetcher->new($self);
2809 $self->ra->gs_do_update($rev, $rev, $self, $ed)
2810 or die "SVN connection failed somewhere...\n";
2811 }
2812 print STDERR "Successfully followed parent\n" unless $::_q > 1;
2813 return $self->make_log_entry($rev, [$parent], $ed);
2814 }
2815 return undef;
2816}
2817
2818sub do_fetch {
2819 my ($self, $paths, $rev) = @_;
2820 my $ed;
2821 my ($last_rev, @parents);
2822 if (my $lc = $self->last_commit) {
2823 # we can have a branch that was deleted, then re-added
2824 # under the same name but copied from another path, in
2825 # which case we'll have multiple parents (we don't
2826 # want to break the original ref, nor lose copypath info):
2827 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2828 push @{$log_entry->{parents}}, $lc;
2829 return $log_entry;
2830 }
2831 $ed = SVN::Git::Fetcher->new($self);
2832 $last_rev = $self->{last_rev};
2833 $ed->{c} = $lc;
2834 @parents = ($lc);
2835 } else {
2836 $last_rev = $rev;
2837 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2838 return $log_entry;
2839 }
2840 $ed = SVN::Git::Fetcher->new($self);
2841 }
2842 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2843 die "SVN connection failed somewhere...\n";
2844 }
2845 $self->make_log_entry($rev, \@parents, $ed);
2846}
2847
2848sub mkemptydirs {
2849 my ($self, $r) = @_;
2850
2851 sub scan {
2852 my ($r, $empty_dirs, $line) = @_;
2853 if (defined $r && $line =~ /^r(\d+)$/) {
2854 return 0 if $1 > $r;
2855 } elsif ($line =~ /^ \+empty_dir: (.+)$/) {
2856 $empty_dirs->{$1} = 1;
2857 } elsif ($line =~ /^ \-empty_dir: (.+)$/) {
2858 my @d = grep {m[^\Q$1\E(/|$)]} (keys %$empty_dirs);
2859 delete @$empty_dirs{@d};
2860 }
2861 1; # continue
2862 };
2863
2864 my %empty_dirs = ();
2865 my $gz_file = "$self->{dir}/unhandled.log.gz";
2866 if (-f $gz_file) {
2867 if (!$can_compress) {
2868 warn "Compress::Zlib could not be found; ",
2869 "empty directories in $gz_file will not be read\n";
2870 } else {
2871 my $gz = Compress::Zlib::gzopen($gz_file, "rb") or
2872 die "Unable to open $gz_file: $!\n";
2873 my $line;
2874 while ($gz->gzreadline($line) > 0) {
2875 scan($r, \%empty_dirs, $line) or last;
2876 }
2877 $gz->gzclose;
2878 }
2879 }
2880
2881 if (open my $fh, '<', "$self->{dir}/unhandled.log") {
2882 binmode $fh or croak "binmode: $!";
2883 while (<$fh>) {
2884 scan($r, \%empty_dirs, $_) or last;
2885 }
2886 close $fh;
2887 }
2888
2889 my $strip = qr/\A\Q$self->{path}\E(?:\/|$)/;
2890 foreach my $d (sort keys %empty_dirs) {
2891 $d = uri_decode($d);
2892 $d =~ s/$strip//;
2893 next unless length($d);
2894 next if -d $d;
2895 if (-e $d) {
2896 warn "$d exists but is not a directory\n";
2897 } else {
2898 print "creating empty directory: $d\n";
2899 mkpath([$d]);
2900 }
2901 }
2902}
2903
2904sub get_untracked {
2905 my ($self, $ed) = @_;
2906 my @out;
2907 my $h = $ed->{empty};
2908 foreach (sort keys %$h) {
2909 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2910 push @out, " $act: " . uri_encode($_);
2911 warn "W: $act: $_\n";
2912 }
2913 foreach my $t (qw/dir_prop file_prop/) {
2914 $h = $ed->{$t} or next;
2915 foreach my $path (sort keys %$h) {
2916 my $ppath = $path eq '' ? '.' : $path;
2917 foreach my $prop (sort keys %{$h->{$path}}) {
2918 next if $SKIP_PROP{$prop};
2919 my $v = $h->{$path}->{$prop};
2920 my $t_ppath_prop = "$t: " .
2921 uri_encode($ppath) . ' ' .
2922 uri_encode($prop);
2923 if (defined $v) {
2924 push @out, " +$t_ppath_prop " .
2925 uri_encode($v);
2926 } else {
2927 push @out, " -$t_ppath_prop";
2928 }
2929 }
2930 }
2931 }
2932 foreach my $t (qw/absent_file absent_directory/) {
2933 $h = $ed->{$t} or next;
2934 foreach my $parent (sort keys %$h) {
2935 foreach my $path (sort @{$h->{$parent}}) {
2936 push @out, " $t: " .
2937 uri_encode("$parent/$path");
2938 warn "W: $t: $parent/$path ",
2939 "Insufficient permissions?\n";
2940 }
2941 }
2942 }
2943 \@out;
2944}
2945
2946# parse_svn_date(DATE)
2947# --------------------
2948# Given a date (in UTC) from Subversion, return a string in the format
2949# "<TZ Offset> <local date/time>" that Git will use.
2950#
2951# By default the parsed date will be in UTC; if $Git::SVN::_localtime
2952# is true we'll convert it to the local timezone instead.
2953sub parse_svn_date {
2954 my $date = shift || return '+0000 1970-01-01 00:00:00';
2955 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2956 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
2957 croak "Unable to parse date: $date\n";
2958 my $parsed_date; # Set next.
2959
2960 if ($Git::SVN::_localtime) {
2961 # Translate the Subversion datetime to an epoch time.
2962 # Begin by switching ourselves to $date's timezone, UTC.
2963 my $old_env_TZ = $ENV{TZ};
2964 $ENV{TZ} = 'UTC';
2965
2966 my $epoch_in_UTC =
2967 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
2968
2969 # Determine our local timezone (including DST) at the
2970 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
2971 # value of TZ, if any, at the time we were run.
2972 if (defined $Git::SVN::Log::TZ) {
2973 $ENV{TZ} = $Git::SVN::Log::TZ;
2974 } else {
2975 delete $ENV{TZ};
2976 }
2977
2978 my $our_TZ =
2979 POSIX::strftime('%Z', $S, $M, $H, $d, $m - 1, $Y - 1900);
2980
2981 # This converts $epoch_in_UTC into our local timezone.
2982 my ($sec, $min, $hour, $mday, $mon, $year,
2983 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
2984
2985 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
2986 $our_TZ, $year + 1900, $mon + 1,
2987 $mday, $hour, $min, $sec);
2988
2989 # Reset us to the timezone in effect when we entered
2990 # this routine.
2991 if (defined $old_env_TZ) {
2992 $ENV{TZ} = $old_env_TZ;
2993 } else {
2994 delete $ENV{TZ};
2995 }
2996 } else {
2997 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
2998 }
2999
3000 return $parsed_date;
3001}
3002
3003sub other_gs {
3004 my ($self, $new_url, $url,
3005 $branch_from, $r, $old_ref_id) = @_;
3006 my $gs = Git::SVN->find_by_url($new_url, $url, $branch_from);
3007 unless ($gs) {
3008 my $ref_id = $old_ref_id;
3009 $ref_id =~ s/\@\d+-*$//;
3010 $ref_id .= "\@$r";
3011 # just grow a tail if we're not unique enough :x
3012 $ref_id .= '-' while find_ref($ref_id);
3013 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
3014 if ($u =~ s#^\Q$url\E(/|$)##) {
3015 $p = $u;
3016 $u = $url;
3017 $repo_id = $self->{repo_id};
3018 }
3019 while (1) {
3020 # It is possible to tag two different subdirectories at
3021 # the same revision. If the url for an existing ref
3022 # does not match, we must either find a ref with a
3023 # matching url or create a new ref by growing a tail.
3024 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
3025 my (undef, $max_commit) = $gs->rev_map_max(1);
3026 last if (!$max_commit);
3027 my ($url) = ::cmt_metadata($max_commit);
3028 last if ($url eq $gs->metadata_url);
3029 $ref_id .= '-';
3030 }
3031 print STDERR "Initializing parent: $ref_id\n" unless $::_q > 1;
3032 }
3033 $gs
3034}
3035
3036sub call_authors_prog {
3037 my ($orig_author) = @_;
3038 $orig_author = command_oneline('rev-parse', '--sq-quote', $orig_author);
3039 my $author = `$::_authors_prog $orig_author`;
3040 if ($? != 0) {
3041 die "$::_authors_prog failed with exit code $?\n"
3042 }
3043 if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
3044 my ($name, $email) = ($1, $2);
3045 $email = undef if length $2 == 0;
3046 return [$name, $email];
3047 } else {
3048 die "Author: $orig_author: $::_authors_prog returned "
3049 . "invalid author format: $author\n";
3050 }
3051}
3052
3053sub check_author {
3054 my ($author) = @_;
3055 if (!defined $author || length $author == 0) {
3056 $author = '(no author)';
3057 }
3058 if (!defined $::users{$author}) {
3059 if (defined $::_authors_prog) {
3060 $::users{$author} = call_authors_prog($author);
3061 } elsif (defined $::_authors) {
3062 die "Author: $author not defined in $::_authors file\n";
3063 }
3064 }
3065 $author;
3066}
3067
3068sub find_extra_svk_parents {
3069 my ($self, $ed, $tickets, $parents) = @_;
3070 # aha! svk:merge property changed...
3071 my @tickets = split "\n", $tickets;
3072 my @known_parents;
3073 for my $ticket ( @tickets ) {
3074 my ($uuid, $path, $rev) = split /:/, $ticket;
3075 if ( $uuid eq $self->ra_uuid ) {
3076 my $url = $self->{url};
3077 my $repos_root = $url;
3078 my $branch_from = $path;
3079 $branch_from =~ s{^/}{};
3080 my $gs = $self->other_gs($repos_root."/".$branch_from,
3081 $url,
3082 $branch_from,
3083 $rev,
3084 $self->{ref_id});
3085 if ( my $commit = $gs->rev_map_get($rev, $uuid) ) {
3086 # wahey! we found it, but it might be
3087 # an old one (!)
3088 push @known_parents, [ $rev, $commit ];
3089 }
3090 }
3091 }
3092 # Ordering matters; highest-numbered commit merge tickets
3093 # first, as they may account for later merge ticket additions
3094 # or changes.
3095 @known_parents = map {$_->[1]} sort {$b->[0] <=> $a->[0]} @known_parents;
3096 for my $parent ( @known_parents ) {
3097 my @cmd = ('rev-list', $parent, map { "^$_" } @$parents );
3098 my ($msg_fh, $ctx) = command_output_pipe(@cmd);
3099 my $new;
3100 while ( <$msg_fh> ) {
3101 $new=1;last;
3102 }
3103 command_close_pipe($msg_fh, $ctx);
3104 if ( $new ) {
3105 print STDERR
3106 "Found merge parent (svk:merge ticket): $parent\n";
3107 push @$parents, $parent;
3108 }
3109 }
3110}
3111
3112sub lookup_svn_merge {
3113 my $uuid = shift;
3114 my $url = shift;
3115 my $merge = shift;
3116
3117 my ($source, $revs) = split ":", $merge;
3118 my $path = $source;
3119 $path =~ s{^/}{};
3120 my $gs = Git::SVN->find_by_url($url.$source, $url, $path);
3121 if ( !$gs ) {
3122 warn "Couldn't find revmap for $url$source\n";
3123 return;
3124 }
3125 my @ranges = split ",", $revs;
3126 my ($tip, $tip_commit);
3127 my @merged_commit_ranges;
3128 # find the tip
3129 for my $range ( @ranges ) {
3130 my ($bottom, $top) = split "-", $range;
3131 $top ||= $bottom;
3132 my $bottom_commit = $gs->find_rev_after( $bottom, 1, $top );
3133 my $top_commit = $gs->find_rev_before( $top, 1, $bottom );
3134
3135 unless ($top_commit and $bottom_commit) {
3136 warn "W:unknown path/rev in svn:mergeinfo "
3137 ."dirprop: $source:$range\n";
3138 next;
3139 }
3140
3141 if (scalar(command('rev-parse', "$bottom_commit^@"))) {
3142 push @merged_commit_ranges,
3143 "$bottom_commit^..$top_commit";
3144 } else {
3145 push @merged_commit_ranges, "$top_commit";
3146 }
3147
3148 if ( !defined $tip or $top > $tip ) {
3149 $tip = $top;
3150 $tip_commit = $top_commit;
3151 }
3152 }
3153 return ($tip_commit, @merged_commit_ranges);
3154}
3155
3156sub _rev_list {
3157 my ($msg_fh, $ctx) = command_output_pipe(
3158 "rev-list", @_,
3159 );
3160 my @rv;
3161 while ( <$msg_fh> ) {
3162 chomp;
3163 push @rv, $_;
3164 }
3165 command_close_pipe($msg_fh, $ctx);
3166 @rv;
3167}
3168
3169sub check_cherry_pick {
3170 my $base = shift;
3171 my $tip = shift;
3172 my $parents = shift;
3173 my @ranges = @_;
3174 my %commits = map { $_ => 1 }
3175 _rev_list("--no-merges", $tip, "--not", $base, @$parents, "--");
3176 for my $range ( @ranges ) {
3177 delete @commits{_rev_list($range, "--")};
3178 }
3179 for my $commit (keys %commits) {
3180 if (has_no_changes($commit)) {
3181 delete $commits{$commit};
3182 }
3183 }
3184 return (keys %commits);
3185}
3186
3187sub has_no_changes {
3188 my $commit = shift;
3189
3190 my @revs = split / /, command_oneline(
3191 qw(rev-list --parents -1 -m), $commit);
3192
3193 # Commits with no parents, e.g. the start of a partial branch,
3194 # have changes by definition.
3195 return 1 if (@revs < 2);
3196
3197 # Commits with multiple parents, e.g a merge, have no changes
3198 # by definition.
3199 return 0 if (@revs > 2);
3200
3201 return (command_oneline("rev-parse", "$commit^{tree}") eq
3202 command_oneline("rev-parse", "$commit~1^{tree}"));
3203}
3204
3205# The GIT_DIR environment variable is not always set until after the command
3206# line arguments are processed, so we can't memoize in a BEGIN block.
3207{
3208 my $memoized = 0;
3209
3210 sub memoize_svn_mergeinfo_functions {
3211 return if $memoized;
3212 $memoized = 1;
3213
3214 my $cache_path = "$ENV{GIT_DIR}/svn/.caches/";
3215 mkpath([$cache_path]) unless -d $cache_path;
3216
3217 tie my %lookup_svn_merge_cache => 'Memoize::Storable',
3218 "$cache_path/lookup_svn_merge.db", 'nstore';
3219 memoize 'lookup_svn_merge',
3220 SCALAR_CACHE => 'FAULT',
3221 LIST_CACHE => ['HASH' => \%lookup_svn_merge_cache],
3222 ;
3223
3224 tie my %check_cherry_pick_cache => 'Memoize::Storable',
3225 "$cache_path/check_cherry_pick.db", 'nstore';
3226 memoize 'check_cherry_pick',
3227 SCALAR_CACHE => 'FAULT',
3228 LIST_CACHE => ['HASH' => \%check_cherry_pick_cache],
3229 ;
3230
3231 tie my %has_no_changes_cache => 'Memoize::Storable',
3232 "$cache_path/has_no_changes.db", 'nstore';
3233 memoize 'has_no_changes',
3234 SCALAR_CACHE => ['HASH' => \%has_no_changes_cache],
3235 LIST_CACHE => 'FAULT',
3236 ;
3237 }
3238
3239 sub unmemoize_svn_mergeinfo_functions {
3240 return if not $memoized;
3241 $memoized = 0;
3242
3243 Memoize::unmemoize 'lookup_svn_merge';
3244 Memoize::unmemoize 'check_cherry_pick';
3245 Memoize::unmemoize 'has_no_changes';
3246 }
3247
3248 Memoize::memoize 'Git::SVN::repos_root';
3249}
3250
3251END {
3252 # Force cache writeout explicitly instead of waiting for
3253 # global destruction to avoid segfault in Storable:
3254 # http://rt.cpan.org/Public/Bug/Display.html?id=36087
3255 unmemoize_svn_mergeinfo_functions();
3256}
3257
3258sub parents_exclude {
3259 my $parents = shift;
3260 my @commits = @_;
3261 return unless @commits;
3262
3263 my @excluded;
3264 my $excluded;
3265 do {
3266 my @cmd = ('rev-list', "-1", @commits, "--not", @$parents );
3267 $excluded = command_oneline(@cmd);
3268 if ( $excluded ) {
3269 my @new;
3270 my $found;
3271 for my $commit ( @commits ) {
3272 if ( $commit eq $excluded ) {
3273 push @excluded, $commit;
3274 $found++;
3275 last;
3276 }
3277 else {
3278 push @new, $commit;
3279 }
3280 }
3281 die "saw commit '$excluded' in rev-list output, "
3282 ."but we didn't ask for that commit (wanted: @commits --not @$parents)"
3283 unless $found;
3284 @commits = @new;
3285 }
3286 }
3287 while ($excluded and @commits);
3288
3289 return @excluded;
3290}
3291
3292
3293# note: this function should only be called if the various dirprops
3294# have actually changed
3295sub find_extra_svn_parents {
3296 my ($self, $ed, $mergeinfo, $parents) = @_;
3297 # aha! svk:merge property changed...
3298
3299 memoize_svn_mergeinfo_functions();
3300
3301 # We first search for merged tips which are not in our
3302 # history. Then, we figure out which git revisions are in
3303 # that tip, but not this revision. If all of those revisions
3304 # are now marked as merge, we can add the tip as a parent.
3305 my @merges = split "\n", $mergeinfo;
3306 my @merge_tips;
3307 my $url = $self->{url};
3308 my $uuid = $self->ra_uuid;
3309 my %ranges;
3310 for my $merge ( @merges ) {
3311 my ($tip_commit, @ranges) =
3312 lookup_svn_merge( $uuid, $url, $merge );
3313 unless (!$tip_commit or
3314 grep { $_ eq $tip_commit } @$parents ) {
3315 push @merge_tips, $tip_commit;
3316 $ranges{$tip_commit} = \@ranges;
3317 } else {
3318 push @merge_tips, undef;
3319 }
3320 }
3321
3322 my %excluded = map { $_ => 1 }
3323 parents_exclude($parents, grep { defined } @merge_tips);
3324
3325 # check merge tips for new parents
3326 my @new_parents;
3327 for my $merge_tip ( @merge_tips ) {
3328 my $spec = shift @merges;
3329 next unless $merge_tip and $excluded{$merge_tip};
3330
3331 my $ranges = $ranges{$merge_tip};
3332
3333 # check out 'new' tips
3334 my $merge_base;
3335 eval {
3336 $merge_base = command_oneline(
3337 "merge-base",
3338 @$parents, $merge_tip,
3339 );
3340 };
3341 if ($@) {
3342 die "An error occurred during merge-base"
3343 unless $@->isa("Git::Error::Command");
3344
3345 warn "W: Cannot find common ancestor between ".
3346 "@$parents and $merge_tip. Ignoring merge info.\n";
3347 next;
3348 }
3349
3350 # double check that there are no missing non-merge commits
3351 my (@incomplete) = check_cherry_pick(
3352 $merge_base, $merge_tip,
3353 $parents,
3354 @$ranges,
3355 );
3356
3357 if ( @incomplete ) {
3358 warn "W:svn cherry-pick ignored ($spec) - missing "
3359 .@incomplete." commit(s) (eg $incomplete[0])\n";
3360 } else {
3361 warn
3362 "Found merge parent (svn:mergeinfo prop): ",
3363 $merge_tip, "\n";
3364 push @new_parents, $merge_tip;
3365 }
3366 }
3367
3368 # cater for merges which merge commits from multiple branches
3369 if ( @new_parents > 1 ) {
3370 for ( my $i = 0; $i <= $#new_parents; $i++ ) {
3371 for ( my $j = 0; $j <= $#new_parents; $j++ ) {
3372 next if $i == $j;
3373 next unless $new_parents[$i];
3374 next unless $new_parents[$j];
3375 my $revs = command_oneline(
3376 "rev-list", "-1",
3377 "$new_parents[$i]..$new_parents[$j]",
3378 );
3379 if ( !$revs ) {
3380 undef($new_parents[$j]);
3381 }
3382 }
3383 }
3384 }
3385 push @$parents, grep { defined } @new_parents;
3386}
3387
3388sub make_log_entry {
3389 my ($self, $rev, $parents, $ed) = @_;
3390 my $untracked = $self->get_untracked($ed);
3391
3392 my @parents = @$parents;
3393 my $ps = $ed->{path_strip} || "";
3394 for my $path ( grep { m/$ps/ } %{$ed->{dir_prop}} ) {
3395 my $props = $ed->{dir_prop}{$path};
3396 if ( $props->{"svk:merge"} ) {
3397 $self->find_extra_svk_parents
3398 ($ed, $props->{"svk:merge"}, \@parents);
3399 }
3400 if ( $props->{"svn:mergeinfo"} ) {
3401 $self->find_extra_svn_parents
3402 ($ed,
3403 $props->{"svn:mergeinfo"},
3404 \@parents);
3405 }
3406 }
3407
3408 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
3409 print $un "r$rev\n" or croak $!;
3410 print $un $_, "\n" foreach @$untracked;
3411 my %log_entry = ( parents => \@parents, revision => $rev,
3412 log => '');
3413
3414 my $headrev;
3415 my $logged = delete $self->{logged_rev_props};
3416 if (!$logged || $self->{-want_revprops}) {
3417 my $rp = $self->ra->rev_proplist($rev);
3418 foreach (sort keys %$rp) {
3419 my $v = $rp->{$_};
3420 if (/^svn:(author|date|log)$/) {
3421 $log_entry{$1} = $v;
3422 } elsif ($_ eq 'svm:headrev') {
3423 $headrev = $v;
3424 } else {
3425 print $un " rev_prop: ", uri_encode($_), ' ',
3426 uri_encode($v), "\n";
3427 }
3428 }
3429 } else {
3430 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
3431 }
3432 close $un or croak $!;
3433
3434 $log_entry{date} = parse_svn_date($log_entry{date});
3435 $log_entry{log} .= "\n";
3436 my $author = $log_entry{author} = check_author($log_entry{author});
3437 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
3438 : ($author, undef);
3439
3440 my ($commit_name, $commit_email) = ($name, $email);
3441 if ($_use_log_author) {
3442 my $name_field;
3443 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
3444 $name_field = $1;
3445 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
3446 $name_field = $1;
3447 }
3448 if (!defined $name_field) {
3449 if (!defined $email) {
3450 $email = $name;
3451 }
3452 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
3453 ($name, $email) = ($1, $2);
3454 } elsif ($name_field =~ /(.*)@/) {
3455 ($name, $email) = ($1, $name_field);
3456 } else {
3457 ($name, $email) = ($name_field, $name_field);
3458 }
3459 }
3460 if (defined $headrev && $self->use_svm_props) {
3461 if ($self->rewrite_root) {
3462 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
3463 "options set!\n";
3464 }
3465 if ($self->rewrite_uuid) {
3466 die "Can't have both 'useSvmProps' and 'rewriteUUID' ",
3467 "options set!\n";
3468 }
3469 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$}i;
3470 # we don't want "SVM: initializing mirror for junk" ...
3471 return undef if $r == 0;
3472 my $svm = $self->svm;
3473 if ($uuid ne $svm->{uuid}) {
3474 die "UUID mismatch on SVM path:\n",
3475 "expected: $svm->{uuid}\n",
3476 " got: $uuid\n";
3477 }
3478 my $full_url = $self->full_url;
3479 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
3480 die "Failed to replace '$svm->{replace}' with ",
3481 "'$svm->{source}' in $full_url\n";
3482 # throw away username for storing in records
3483 remove_username($full_url);
3484 $log_entry{metadata} = "$full_url\@$r $uuid";
3485 $log_entry{svm_revision} = $r;
3486 $email ||= "$author\@$uuid";
3487 $commit_email ||= "$author\@$uuid";
3488 } elsif ($self->use_svnsync_props) {
3489 my $full_url = $self->svnsync->{url};
3490 $full_url .= "/$self->{path}" if length $self->{path};
3491 remove_username($full_url);
3492 my $uuid = $self->svnsync->{uuid};
3493 $log_entry{metadata} = "$full_url\@$rev $uuid";
3494 $email ||= "$author\@$uuid";
3495 $commit_email ||= "$author\@$uuid";
3496 } else {
3497 my $url = $self->metadata_url;
3498 remove_username($url);
3499 my $uuid = $self->rewrite_uuid || $self->ra->get_uuid;
3500 $log_entry{metadata} = "$url\@$rev " . $uuid;
3501 $email ||= "$author\@" . $uuid;
3502 $commit_email ||= "$author\@" . $uuid;
3503 }
3504 $log_entry{name} = $name;
3505 $log_entry{email} = $email;
3506 $log_entry{commit_name} = $commit_name;
3507 $log_entry{commit_email} = $commit_email;
3508 \%log_entry;
3509}
3510
3511sub fetch {
3512 my ($self, $min_rev, $max_rev, @parents) = @_;
3513 my ($last_rev, $last_commit) = $self->last_rev_commit;
3514 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
3515 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
3516}
3517
3518sub set_tree_cb {
3519 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
3520 $self->{inject_parents} = { $rev => $tree };
3521 $self->fetch(undef, undef);
3522}
3523
3524sub set_tree {
3525 my ($self, $tree) = (shift, shift);
3526 my $log_entry = ::get_commit_entry($tree);
3527 unless ($self->{last_rev}) {
3528 ::fatal("Must have an existing revision to commit");
3529 }
3530 my %ed_opts = ( r => $self->{last_rev},
3531 log => $log_entry->{log},
3532 ra => $self->ra,
3533 tree_a => $self->{last_commit},
3534 tree_b => $tree,
3535 editor_cb => sub {
3536 $self->set_tree_cb($log_entry, $tree, @_) },
3537 svn_path => $self->{path} );
3538 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
3539 print "No changes\nr$self->{last_rev} = $tree\n";
3540 }
3541}
3542
3543sub rebuild_from_rev_db {
3544 my ($self, $path) = @_;
3545 my $r = -1;
3546 open my $fh, '<', $path or croak "open: $!";
3547 binmode $fh or croak "binmode: $!";
3548 while (<$fh>) {
3549 length($_) == 41 or croak "inconsistent size in ($_) != 41";
3550 chomp($_);
3551 ++$r;
3552 next if $_ eq ('0' x 40);
3553 $self->rev_map_set($r, $_);
3554 print "r$r = $_\n";
3555 }
3556 close $fh or croak "close: $!";
3557 unlink $path or croak "unlink: $!";
3558}
3559
3560sub rebuild {
3561 my ($self) = @_;
3562 my $map_path = $self->map_path;
3563 my $partial = (-e $map_path && ! -z $map_path);
3564 return unless ::verify_ref($self->refname.'^0');
3565 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
3566 my $rev_db = $self->rev_db_path;
3567 $self->rebuild_from_rev_db($rev_db);
3568 if ($self->use_svm_props) {
3569 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
3570 $self->rebuild_from_rev_db($svm_rev_db);
3571 }
3572 $self->unlink_rev_db_symlink;
3573 return;
3574 }
3575 print "Rebuilding $map_path ...\n" if (!$partial);
3576 my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
3577 (undef, undef));
3578 my ($log, $ctx) =
3579 command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
3580 ($head ? "$head.." : "") . $self->refname,
3581 '--');
3582 my $metadata_url = $self->metadata_url;
3583 remove_username($metadata_url);
3584 my $svn_uuid = $self->rewrite_uuid || $self->ra_uuid;
3585 my $c;
3586 while (<$log>) {
3587 if ( m{^commit ($::sha1)$} ) {
3588 $c = $1;
3589 next;
3590 }
3591 next unless s{^\s*(git-svn-id:)}{$1};
3592 my ($url, $rev, $uuid) = ::extract_metadata($_);
3593 remove_username($url);
3594
3595 # ignore merges (from set-tree)
3596 next if (!defined $rev || !$uuid);
3597
3598 # if we merged or otherwise started elsewhere, this is
3599 # how we break out of it
3600 if (($uuid ne $svn_uuid) ||
3601 ($metadata_url && $url && ($url ne $metadata_url))) {
3602 next;
3603 }
3604 if ($partial && $head) {
3605 print "Partial-rebuilding $map_path ...\n";
3606 print "Currently at $base_rev = $head\n";
3607 $head = undef;
3608 }
3609
3610 $self->rev_map_set($rev, $c);
3611 print "r$rev = $c\n";
3612 }
3613 command_close_pipe($log, $ctx);
3614 print "Done rebuilding $map_path\n" if (!$partial || !$head);
3615 my $rev_db_path = $self->rev_db_path;
3616 if (-f $self->rev_db_path) {
3617 unlink $self->rev_db_path or croak "unlink: $!";
3618 }
3619 $self->unlink_rev_db_symlink;
3620}
3621
3622# rev_map:
3623# Tie::File seems to be prone to offset errors if revisions get sparse,
3624# it's not that fast, either. Tie::File is also not in Perl 5.6. So
3625# one of my favorite modules is out :< Next up would be one of the DBM
3626# modules, but I'm not sure which is most portable...
3627#
3628# This is the replacement for the rev_db format, which was too big
3629# and inefficient for large repositories with a lot of sparse history
3630# (mainly tags)
3631#
3632# The format is this:
3633# - 24 bytes for every record,
3634# * 4 bytes for the integer representing an SVN revision number
3635# * 20 bytes representing the sha1 of a git commit
3636# - No empty padding records like the old format
3637# (except the last record, which can be overwritten)
3638# - new records are written append-only since SVN revision numbers
3639# increase monotonically
3640# - lookups on SVN revision number are done via a binary search
3641# - Piping the file to xxd -c24 is a good way of dumping it for
3642# viewing or editing (piped back through xxd -r), should the need
3643# ever arise.
3644# - The last record can be padding revision with an all-zero sha1
3645# This is used to optimize fetch performance when using multiple
3646# "fetch" directives in .git/config
3647#
3648# These files are disposable unless noMetadata or useSvmProps is set
3649
3650sub _rev_map_set {
3651 my ($fh, $rev, $commit) = @_;
3652
3653 binmode $fh or croak "binmode: $!";
3654 my $size = (stat($fh))[7];
3655 ($size % 24) == 0 or croak "inconsistent size: $size";
3656
3657 my $wr_offset = 0;
3658 if ($size > 0) {
3659 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3660 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
3661 $read == 24 or croak "read only $read bytes (!= 24)";
3662 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
3663 if ($last_commit eq ('0' x40)) {
3664 if ($size >= 48) {
3665 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3666 $read = sysread($fh, $buf, 24) or
3667 croak "read: $!";
3668 $read == 24 or
3669 croak "read only $read bytes (!= 24)";
3670 ($last_rev, $last_commit) =
3671 unpack(rev_map_fmt, $buf);
3672 if ($last_commit eq ('0' x40)) {
3673 croak "inconsistent .rev_map\n";
3674 }
3675 }
3676 if ($last_rev >= $rev) {
3677 croak "last_rev is higher!: $last_rev >= $rev";
3678 }
3679 $wr_offset = -24;
3680 }
3681 }
3682 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
3683 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
3684 croak "write: $!";
3685}
3686
3687sub _rev_map_reset {
3688 my ($fh, $rev, $commit) = @_;
3689 my $c = _rev_map_get($fh, $rev);
3690 $c eq $commit or die "_rev_map_reset(@_) commit $c does not match!\n";
3691 my $offset = sysseek($fh, 0, SEEK_CUR) or croak "seek: $!";
3692 truncate $fh, $offset or croak "truncate: $!";
3693}
3694
3695sub mkfile {
3696 my ($path) = @_;
3697 unless (-e $path) {
3698 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
3699 mkpath([$dir]) unless -d $dir;
3700 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
3701 close $fh or die "Couldn't close (create) $path: $!\n";
3702 }
3703}
3704
3705sub rev_map_set {
3706 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
3707 defined $commit or die "missing arg3\n";
3708 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
3709 my $db = $self->map_path($uuid);
3710 my $db_lock = "$db.lock";
3711 my $sig;
3712 $update_ref ||= 0;
3713 if ($update_ref) {
3714 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3715 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
3716 }
3717 mkfile($db);
3718
3719 $LOCKFILES{$db_lock} = 1;
3720 my $sync;
3721 # both of these options make our .rev_db file very, very important
3722 # and we can't afford to lose it because rebuild() won't work
3723 if ($self->use_svm_props || $self->no_metadata) {
3724 $sync = 1;
3725 copy($db, $db_lock) or die "rev_map_set(@_): ",
3726 "Failed to copy: ",
3727 "$db => $db_lock ($!)\n";
3728 } else {
3729 rename $db, $db_lock or die "rev_map_set(@_): ",
3730 "Failed to rename: ",
3731 "$db => $db_lock ($!)\n";
3732 }
3733
3734 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
3735 or croak "Couldn't open $db_lock: $!\n";
3736 $update_ref eq 'reset' ? _rev_map_reset($fh, $rev, $commit) :
3737 _rev_map_set($fh, $rev, $commit);
3738 if ($sync) {
3739 $fh->flush or die "Couldn't flush $db_lock: $!\n";
3740 $fh->sync or die "Couldn't sync $db_lock: $!\n";
3741 }
3742 close $fh or croak $!;
3743 if ($update_ref) {
3744 $_head = $self;
3745 my $note = "";
3746 $note = " ($update_ref)" if ($update_ref !~ /^\d*$/);
3747 command_noisy('update-ref', '-m', "r$rev$note",
3748 $self->refname, $commit);
3749 }
3750 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
3751 "$db_lock => $db ($!)\n";
3752 delete $LOCKFILES{$db_lock};
3753 if ($update_ref) {
3754 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3755 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
3756 kill $sig, $$ if defined $sig;
3757 }
3758}
3759
3760# If want_commit, this will return an array of (rev, commit) where
3761# commit _must_ be a valid commit in the archive.
3762# Otherwise, it'll return the max revision (whether or not the
3763# commit is valid or just a 0x40 placeholder).
3764sub rev_map_max {
3765 my ($self, $want_commit) = @_;
3766 $self->rebuild;
3767 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
3768 $want_commit ? ($r, $c) : $r;
3769}
3770
3771sub rev_map_max_norebuild {
3772 my ($self, $want_commit) = @_;
3773 my $map_path = $self->map_path;
3774 stat $map_path or return $want_commit ? (0, undef) : 0;
3775 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3776 binmode $fh or croak "binmode: $!";
3777 my $size = (stat($fh))[7];
3778 ($size % 24) == 0 or croak "inconsistent size: $size";
3779
3780 if ($size == 0) {
3781 close $fh or croak "close: $!";
3782 return $want_commit ? (0, undef) : 0;
3783 }
3784
3785 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3786 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3787 my ($r, $c) = unpack(rev_map_fmt, $buf);
3788 if ($want_commit && $c eq ('0' x40)) {
3789 if ($size < 48) {
3790 return $want_commit ? (0, undef) : 0;
3791 }
3792 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3793 sysread($fh, $buf, 24) == 24 or croak "read: $!";
3794 ($r, $c) = unpack(rev_map_fmt, $buf);
3795 if ($c eq ('0'x40)) {
3796 croak "Penultimate record is all-zeroes in $map_path";
3797 }
3798 }
3799 close $fh or croak "close: $!";
3800 $want_commit ? ($r, $c) : $r;
3801}
3802
3803sub rev_map_get {
3804 my ($self, $rev, $uuid) = @_;
3805 my $map_path = $self->map_path($uuid);
3806 return undef unless -e $map_path;
3807
3808 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3809 my $c = _rev_map_get($fh, $rev);
3810 close($fh) or croak "close: $!";
3811 $c
3812}
3813
3814sub _rev_map_get {
3815 my ($fh, $rev) = @_;
3816
3817 binmode $fh or croak "binmode: $!";
3818 my $size = (stat($fh))[7];
3819 ($size % 24) == 0 or croak "inconsistent size: $size";
3820
3821 if ($size == 0) {
3822 return undef;
3823 }
3824
3825 my ($l, $u) = (0, $size - 24);
3826 my ($r, $c, $buf);
3827
3828 while ($l <= $u) {
3829 my $i = int(($l/24 + $u/24) / 2) * 24;
3830 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
3831 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3832 my ($r, $c) = unpack(rev_map_fmt, $buf);
3833
3834 if ($r < $rev) {
3835 $l = $i + 24;
3836 } elsif ($r > $rev) {
3837 $u = $i - 24;
3838 } else { # $r == $rev
3839 return $c eq ('0' x 40) ? undef : $c;
3840 }
3841 }
3842 undef;
3843}
3844
3845# Finds the first svn revision that exists on (if $eq_ok is true) or
3846# before $rev for the current branch. It will not search any lower
3847# than $min_rev. Returns the git commit hash and svn revision number
3848# if found, else (undef, undef).
3849sub find_rev_before {
3850 my ($self, $rev, $eq_ok, $min_rev) = @_;
3851 --$rev unless $eq_ok;
3852 $min_rev ||= 1;
3853 my $max_rev = $self->rev_map_max;
3854 $rev = $max_rev if ($rev > $max_rev);
3855 while ($rev >= $min_rev) {
3856 if (my $c = $self->rev_map_get($rev)) {
3857 return ($rev, $c);
3858 }
3859 --$rev;
3860 }
3861 return (undef, undef);
3862}
3863
3864# Finds the first svn revision that exists on (if $eq_ok is true) or
3865# after $rev for the current branch. It will not search any higher
3866# than $max_rev. Returns the git commit hash and svn revision number
3867# if found, else (undef, undef).
3868sub find_rev_after {
3869 my ($self, $rev, $eq_ok, $max_rev) = @_;
3870 ++$rev unless $eq_ok;
3871 $max_rev ||= $self->rev_map_max;
3872 while ($rev <= $max_rev) {
3873 if (my $c = $self->rev_map_get($rev)) {
3874 return ($rev, $c);
3875 }
3876 ++$rev;
3877 }
3878 return (undef, undef);
3879}
3880
3881sub _new {
3882 my ($class, $repo_id, $ref_id, $path) = @_;
3883 unless (defined $repo_id && length $repo_id) {
3884 $repo_id = $Git::SVN::default_repo_id;
3885 }
3886 unless (defined $ref_id && length $ref_id) {
3887 $_prefix = '' unless defined($_prefix);
3888 $_[2] = $ref_id =
3889 "refs/remotes/$_prefix$Git::SVN::default_ref_id";
3890 }
3891 $_[1] = $repo_id;
3892 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
3893
3894 # Older repos imported by us used $GIT_DIR/svn/foo instead of
3895 # $GIT_DIR/svn/refs/remotes/foo when tracking refs/remotes/foo
3896 if ($ref_id =~ m{^refs/remotes/(.*)}) {
3897 my $old_dir = "$ENV{GIT_DIR}/svn/$1";
3898 if (-d $old_dir && ! -d $dir) {
3899 $dir = $old_dir;
3900 }
3901 }
3902
3903 $_[3] = $path = '' unless (defined $path);
3904 mkpath([$dir]);
3905 bless {
3906 ref_id => $ref_id, dir => $dir, index => "$dir/index",
3907 path => $path, config => "$ENV{GIT_DIR}/svn/config",
3908 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
3909}
3910
3911# for read-only access of old .rev_db formats
3912sub unlink_rev_db_symlink {
3913 my ($self) = @_;
3914 my $link = $self->rev_db_path;
3915 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
3916 if (-l $link) {
3917 unlink $link or croak "unlink: $link failed!";
3918 }
3919}
3920
3921sub rev_db_path {
3922 my ($self, $uuid) = @_;
3923 my $db_path = $self->map_path($uuid);
3924 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
3925 or croak "map_path: $db_path does not contain '/.rev_map.' !";
3926 $db_path;
3927}
3928
3929# the new replacement for .rev_db
3930sub map_path {
3931 my ($self, $uuid) = @_;
3932 $uuid ||= $self->ra_uuid;
3933 "$self->{map_root}.$uuid";
3934}
3935
3936sub uri_encode {
3937 my ($f) = @_;
3938 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
3939 $f
3940}
3941
3942sub uri_decode {
3943 my ($f) = @_;
3944 $f =~ s#%([0-9a-fA-F]{2})#chr(hex($1))#eg;
3945 $f
3946}
3947
3948sub remove_username {
3949 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
3950}
3951
3952package Git::SVN::Prompt;
3953use strict;
3954use warnings;
3955require SVN::Core;
3956use vars qw/$_no_auth_cache $_username/;
3957
3958sub simple {
3959 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
3960 $may_save = undef if $_no_auth_cache;
3961 $default_username = $_username if defined $_username;
3962 if (defined $default_username && length $default_username) {
3963 if (defined $realm && length $realm) {
3964 print STDERR "Authentication realm: $realm\n";
3965 STDERR->flush;
3966 }
3967 $cred->username($default_username);
3968 } else {
3969 username($cred, $realm, $may_save, $pool);
3970 }
3971 $cred->password(_read_password("Password for '" .
3972 $cred->username . "': ", $realm));
3973 $cred->may_save($may_save);
3974 $SVN::_Core::SVN_NO_ERROR;
3975}
3976
3977sub ssl_server_trust {
3978 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
3979 $may_save = undef if $_no_auth_cache;
3980 print STDERR "Error validating server certificate for '$realm':\n";
3981 {
3982 no warnings 'once';
3983 # All variables SVN::Auth::SSL::* are used only once,
3984 # so we're shutting up Perl warnings about this.
3985 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
3986 print STDERR " - The certificate is not issued ",
3987 "by a trusted authority. Use the\n",
3988 " fingerprint to validate ",
3989 "the certificate manually!\n";
3990 }
3991 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
3992 print STDERR " - The certificate hostname ",
3993 "does not match.\n";
3994 }
3995 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
3996 print STDERR " - The certificate is not yet valid.\n";
3997 }
3998 if ($failures & $SVN::Auth::SSL::EXPIRED) {
3999 print STDERR " - The certificate has expired.\n";
4000 }
4001 if ($failures & $SVN::Auth::SSL::OTHER) {
4002 print STDERR " - The certificate has ",
4003 "an unknown error.\n";
4004 }
4005 } # no warnings 'once'
4006 printf STDERR
4007 "Certificate information:\n".
4008 " - Hostname: %s\n".
4009 " - Valid: from %s until %s\n".
4010 " - Issuer: %s\n".
4011 " - Fingerprint: %s\n",
4012 map $cert_info->$_, qw(hostname valid_from valid_until
4013 issuer_dname fingerprint);
4014 my $choice;
4015prompt:
4016 print STDERR $may_save ?
4017 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
4018 "(R)eject or accept (t)emporarily? ";
4019 STDERR->flush;
4020 $choice = lc(substr(<STDIN> || 'R', 0, 1));
4021 if ($choice =~ /^t$/i) {
4022 $cred->may_save(undef);
4023 } elsif ($choice =~ /^r$/i) {
4024 return -1;
4025 } elsif ($may_save && $choice =~ /^p$/i) {
4026 $cred->may_save($may_save);
4027 } else {
4028 goto prompt;
4029 }
4030 $cred->accepted_failures($failures);
4031 $SVN::_Core::SVN_NO_ERROR;
4032}
4033
4034sub ssl_client_cert {
4035 my ($cred, $realm, $may_save, $pool) = @_;
4036 $may_save = undef if $_no_auth_cache;
4037 print STDERR "Client certificate filename: ";
4038 STDERR->flush;
4039 chomp(my $filename = <STDIN>);
4040 $cred->cert_file($filename);
4041 $cred->may_save($may_save);
4042 $SVN::_Core::SVN_NO_ERROR;
4043}
4044
4045sub ssl_client_cert_pw {
4046 my ($cred, $realm, $may_save, $pool) = @_;
4047 $may_save = undef if $_no_auth_cache;
4048 $cred->password(_read_password("Password: ", $realm));
4049 $cred->may_save($may_save);
4050 $SVN::_Core::SVN_NO_ERROR;
4051}
4052
4053sub username {
4054 my ($cred, $realm, $may_save, $pool) = @_;
4055 $may_save = undef if $_no_auth_cache;
4056 if (defined $realm && length $realm) {
4057 print STDERR "Authentication realm: $realm\n";
4058 }
4059 my $username;
4060 if (defined $_username) {
4061 $username = $_username;
4062 } else {
4063 print STDERR "Username: ";
4064 STDERR->flush;
4065 chomp($username = <STDIN>);
4066 }
4067 $cred->username($username);
4068 $cred->may_save($may_save);
4069 $SVN::_Core::SVN_NO_ERROR;
4070}
4071
4072sub _read_password {
4073 my ($prompt, $realm) = @_;
4074 my $password = '';
4075 if (exists $ENV{GIT_ASKPASS}) {
4076 open(PH, "-|", $ENV{GIT_ASKPASS}, $prompt);
4077 $password = <PH>;
4078 $password =~ s/[\012\015]//; # \n\r
4079 close(PH);
4080 } else {
4081 print STDERR $prompt;
4082 STDERR->flush;
4083 require Term::ReadKey;
4084 Term::ReadKey::ReadMode('noecho');
4085 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
4086 last if $key =~ /[\012\015]/; # \n\r
4087 $password .= $key;
4088 }
4089 Term::ReadKey::ReadMode('restore');
4090 print STDERR "\n";
4091 STDERR->flush;
4092 }
4093 $password;
4094}
4095
4096package SVN::Git::Fetcher;
4097use vars qw/@ISA $_ignore_regex $_preserve_empty_dirs $_placeholder_filename
4098 @deleted_gpath %added_placeholder $repo_id/;
4099use strict;
4100use warnings;
4101use Carp qw/croak/;
4102use File::Basename qw/dirname/;
4103use IO::File qw//;
4104
4105# file baton members: path, mode_a, mode_b, pool, fh, blob, base
4106sub new {
4107 my ($class, $git_svn, $switch_path) = @_;
4108 my $self = SVN::Delta::Editor->new;
4109 bless $self, $class;
4110 if (exists $git_svn->{last_commit}) {
4111 $self->{c} = $git_svn->{last_commit};
4112 $self->{empty_symlinks} =
4113 _mark_empty_symlinks($git_svn, $switch_path);
4114 }
4115
4116 # some options are read globally, but can be overridden locally
4117 # per [svn-remote "..."] section. Command-line options will *NOT*
4118 # override options set in an [svn-remote "..."] section
4119 $repo_id = $git_svn->{repo_id};
4120 my $k = "svn-remote.$repo_id.ignore-paths";
4121 my $v = eval { command_oneline('config', '--get', $k) };
4122 $self->{ignore_regex} = $v;
4123
4124 $k = "svn-remote.$repo_id.preserve-empty-dirs";
4125 $v = eval { command_oneline('config', '--get', '--bool', $k) };
4126 if ($v && $v eq 'true') {
4127 $_preserve_empty_dirs = 1;
4128 $k = "svn-remote.$repo_id.placeholder-filename";
4129 $v = eval { command_oneline('config', '--get', $k) };
4130 $_placeholder_filename = $v;
4131 }
4132
4133 # Load the list of placeholder files added during previous invocations.
4134 $k = "svn-remote.$repo_id.added-placeholder";
4135 $v = eval { command_oneline('config', '--get-all', $k) };
4136 if ($_preserve_empty_dirs && $v) {
4137 # command() prints errors to stderr, so we only call it if
4138 # command_oneline() succeeded.
4139 my @v = command('config', '--get-all', $k);
4140 $added_placeholder{ dirname($_) } = $_ foreach @v;
4141 }
4142
4143 $self->{empty} = {};
4144 $self->{dir_prop} = {};
4145 $self->{file_prop} = {};
4146 $self->{absent_dir} = {};
4147 $self->{absent_file} = {};
4148 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
4149 $self->{pathnameencoding} = Git::config('svn.pathnameencoding');
4150 $self;
4151}
4152
4153# this uses the Ra object, so it must be called before do_{switch,update},
4154# not inside them (when the Git::SVN::Fetcher object is passed) to
4155# do_{switch,update}
4156sub _mark_empty_symlinks {
4157 my ($git_svn, $switch_path) = @_;
4158 my $bool = Git::config_bool('svn.brokenSymlinkWorkaround');
4159 return {} if (!defined($bool)) || (defined($bool) && ! $bool);
4160
4161 my %ret;
4162 my ($rev, $cmt) = $git_svn->last_rev_commit;
4163 return {} unless ($rev && $cmt);
4164
4165 # allow the warning to be printed for each revision we fetch to
4166 # ensure the user sees it. The user can also disable the workaround
4167 # on the repository even while git svn is running and the next
4168 # revision fetched will skip this expensive function.
4169 my $printed_warning;
4170 chomp(my $empty_blob = `git hash-object -t blob --stdin < /dev/null`);
4171 my ($ls, $ctx) = command_output_pipe(qw/ls-tree -r -z/, $cmt);
4172 local $/ = "\0";
4173 my $pfx = defined($switch_path) ? $switch_path : $git_svn->{path};
4174 $pfx .= '/' if length($pfx);
4175 while (<$ls>) {
4176 chomp;
4177 s/\A100644 blob $empty_blob\t//o or next;
4178 unless ($printed_warning) {
4179 print STDERR "Scanning for empty symlinks, ",
4180 "this may take a while if you have ",
4181 "many empty files\n",
4182 "You may disable this with `",
4183 "git config svn.brokenSymlinkWorkaround ",
4184 "false'.\n",
4185 "This may be done in a different ",
4186 "terminal without restarting ",
4187 "git svn\n";
4188 $printed_warning = 1;
4189 }
4190 my $path = $_;
4191 my (undef, $props) =
4192 $git_svn->ra->get_file($pfx.$path, $rev, undef);
4193 if ($props->{'svn:special'}) {
4194 $ret{$path} = 1;
4195 }
4196 }
4197 command_close_pipe($ls, $ctx);
4198 \%ret;
4199}
4200
4201# returns true if a given path is inside a ".git" directory
4202sub in_dot_git {
4203 $_[0] =~ m{(?:^|/)\.git(?:/|$)};
4204}
4205
4206# return value: 0 -- don't ignore, 1 -- ignore
4207sub is_path_ignored {
4208 my ($self, $path) = @_;
4209 return 1 if in_dot_git($path);
4210 return 1 if defined($self->{ignore_regex}) &&
4211 $path =~ m!$self->{ignore_regex}!;
4212 return 0 unless defined($_ignore_regex);
4213 return 1 if $path =~ m!$_ignore_regex!o;
4214 return 0;
4215}
4216
4217sub set_path_strip {
4218 my ($self, $path) = @_;
4219 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
4220}
4221
4222sub open_root {
4223 { path => '' };
4224}
4225
4226sub open_directory {
4227 my ($self, $path, $pb, $rev) = @_;
4228 { path => $path };
4229}
4230
4231sub git_path {
4232 my ($self, $path) = @_;
4233 if (my $enc = $self->{pathnameencoding}) {
4234 require Encode;
4235 Encode::from_to($path, 'UTF-8', $enc);
4236 }
4237 if ($self->{path_strip}) {
4238 $path =~ s!$self->{path_strip}!! or
4239 die "Failed to strip path '$path' ($self->{path_strip})\n";
4240 }
4241 $path;
4242}
4243
4244sub delete_entry {
4245 my ($self, $path, $rev, $pb) = @_;
4246 return undef if $self->is_path_ignored($path);
4247
4248 my $gpath = $self->git_path($path);
4249 return undef if ($gpath eq '');
4250
4251 # remove entire directories.
4252 my ($tree) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
4253 =~ /\A040000 tree ([a-f\d]{40})\t\Q$gpath\E\0/);
4254 if ($tree) {
4255 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
4256 -r --name-only -z/,
4257 $tree);
4258 local $/ = "\0";
4259 while (<$ls>) {
4260 chomp;
4261 my $rmpath = "$gpath/$_";
4262 $self->{gii}->remove($rmpath);
4263 print "\tD\t$rmpath\n" unless $::_q;
4264 }
4265 print "\tD\t$gpath/\n" unless $::_q;
4266 command_close_pipe($ls, $ctx);
4267 } else {
4268 $self->{gii}->remove($gpath);
4269 print "\tD\t$gpath\n" unless $::_q;
4270 }
4271 # Don't add to @deleted_gpath if we're deleting a placeholder file.
4272 push @deleted_gpath, $gpath unless $added_placeholder{dirname($path)};
4273 $self->{empty}->{$path} = 0;
4274 undef;
4275}
4276
4277sub open_file {
4278 my ($self, $path, $pb, $rev) = @_;
4279 my ($mode, $blob);
4280
4281 goto out if $self->is_path_ignored($path);
4282
4283 my $gpath = $self->git_path($path);
4284 ($mode, $blob) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
4285 =~ /\A(\d{6}) blob ([a-f\d]{40})\t\Q$gpath\E\0/);
4286 unless (defined $mode && defined $blob) {
4287 die "$path was not found in commit $self->{c} (r$rev)\n";
4288 }
4289 if ($mode eq '100644' && $self->{empty_symlinks}->{$path}) {
4290 $mode = '120000';
4291 }
4292out:
4293 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
4294 pool => SVN::Pool->new, action => 'M' };
4295}
4296
4297sub add_file {
4298 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
4299 my $mode;
4300
4301 if (!$self->is_path_ignored($path)) {
4302 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
4303 delete $self->{empty}->{$dir};
4304 $mode = '100644';
4305
4306 if ($added_placeholder{$dir}) {
4307 # Remove our placeholder file, if we created one.
4308 delete_entry($self, $added_placeholder{$dir})
4309 unless $path eq $added_placeholder{$dir};
4310 delete $added_placeholder{$dir}
4311 }
4312 }
4313
4314 { path => $path, mode_a => $mode, mode_b => $mode,
4315 pool => SVN::Pool->new, action => 'A' };
4316}
4317
4318sub add_directory {
4319 my ($self, $path, $cp_path, $cp_rev) = @_;
4320 goto out if $self->is_path_ignored($path);
4321 my $gpath = $self->git_path($path);
4322 if ($gpath eq '') {
4323 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
4324 -r --name-only -z/,
4325 $self->{c});
4326 local $/ = "\0";
4327 while (<$ls>) {
4328 chomp;
4329 $self->{gii}->remove($_);
4330 print "\tD\t$_\n" unless $::_q;
4331 push @deleted_gpath, $gpath;
4332 }
4333 command_close_pipe($ls, $ctx);
4334 $self->{empty}->{$path} = 0;
4335 }
4336 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
4337 delete $self->{empty}->{$dir};
4338 $self->{empty}->{$path} = 1;
4339
4340 if ($added_placeholder{$dir}) {
4341 # Remove our placeholder file, if we created one.
4342 delete_entry($self, $added_placeholder{$dir});
4343 delete $added_placeholder{$dir}
4344 }
4345
4346out:
4347 { path => $path };
4348}
4349
4350sub change_dir_prop {
4351 my ($self, $db, $prop, $value) = @_;
4352 return undef if $self->is_path_ignored($db->{path});
4353 $self->{dir_prop}->{$db->{path}} ||= {};
4354 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
4355 undef;
4356}
4357
4358sub absent_directory {
4359 my ($self, $path, $pb) = @_;
4360 return undef if $self->is_path_ignored($path);
4361 $self->{absent_dir}->{$pb->{path}} ||= [];
4362 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
4363 undef;
4364}
4365
4366sub absent_file {
4367 my ($self, $path, $pb) = @_;
4368 return undef if $self->is_path_ignored($path);
4369 $self->{absent_file}->{$pb->{path}} ||= [];
4370 push @{$self->{absent_file}->{$pb->{path}}}, $path;
4371 undef;
4372}
4373
4374sub change_file_prop {
4375 my ($self, $fb, $prop, $value) = @_;
4376 return undef if $self->is_path_ignored($fb->{path});
4377 if ($prop eq 'svn:executable') {
4378 if ($fb->{mode_b} != 120000) {
4379 $fb->{mode_b} = defined $value ? 100755 : 100644;
4380 }
4381 } elsif ($prop eq 'svn:special') {
4382 $fb->{mode_b} = defined $value ? 120000 : 100644;
4383 } else {
4384 $self->{file_prop}->{$fb->{path}} ||= {};
4385 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
4386 }
4387 undef;
4388}
4389
4390sub apply_textdelta {
4391 my ($self, $fb, $exp) = @_;
4392 return undef if $self->is_path_ignored($fb->{path});
4393 my $fh = $::_repository->temp_acquire('svn_delta');
4394 # $fh gets auto-closed() by SVN::TxDelta::apply(),
4395 # (but $base does not,) so dup() it for reading in close_file
4396 open my $dup, '<&', $fh or croak $!;
4397 my $base = $::_repository->temp_acquire('git_blob');
4398
4399 if ($fb->{blob}) {
4400 my ($base_is_link, $size);
4401
4402 if ($fb->{mode_a} eq '120000' &&
4403 ! $self->{empty_symlinks}->{$fb->{path}}) {
4404 print $base 'link ' or die "print $!\n";
4405 $base_is_link = 1;
4406 }
4407 retry:
4408 $size = $::_repository->cat_blob($fb->{blob}, $base);
4409 die "Failed to read object $fb->{blob}" if ($size < 0);
4410
4411 if (defined $exp) {
4412 seek $base, 0, 0 or croak $!;
4413 my $got = ::md5sum($base);
4414 if ($got ne $exp) {
4415 my $err = "Checksum mismatch: ".
4416 "$fb->{path} $fb->{blob}\n" .
4417 "expected: $exp\n" .
4418 " got: $got\n";
4419 if ($base_is_link) {
4420 warn $err,
4421 "Retrying... (possibly ",
4422 "a bad symlink from SVN)\n";
4423 $::_repository->temp_reset($base);
4424 $base_is_link = 0;
4425 goto retry;
4426 }
4427 die $err;
4428 }
4429 }
4430 }
4431 seek $base, 0, 0 or croak $!;
4432 $fb->{fh} = $fh;
4433 $fb->{base} = $base;
4434 [ SVN::TxDelta::apply($base, $dup, undef, $fb->{path}, $fb->{pool}) ];
4435}
4436
4437sub close_file {
4438 my ($self, $fb, $exp) = @_;
4439 return undef if $self->is_path_ignored($fb->{path});
4440
4441 my $hash;
4442 my $path = $self->git_path($fb->{path});
4443 if (my $fh = $fb->{fh}) {
4444 if (defined $exp) {
4445 seek($fh, 0, 0) or croak $!;
4446 my $got = ::md5sum($fh);
4447 if ($got ne $exp) {
4448 die "Checksum mismatch: $path\n",
4449 "expected: $exp\n got: $got\n";
4450 }
4451 }
4452 if ($fb->{mode_b} == 120000) {
4453 sysseek($fh, 0, 0) or croak $!;
4454 my $rd = sysread($fh, my $buf, 5);
4455
4456 if (!defined $rd) {
4457 croak "sysread: $!\n";
4458 } elsif ($rd == 0) {
4459 warn "$path has mode 120000",
4460 " but it points to nothing\n",
4461 "converting to an empty file with mode",
4462 " 100644\n";
4463 $fb->{mode_b} = '100644';
4464 } elsif ($buf ne 'link ') {
4465 warn "$path has mode 120000",
4466 " but is not a link\n";
4467 } else {
4468 my $tmp_fh = $::_repository->temp_acquire(
4469 'svn_hash');
4470 my $res;
4471 while ($res = sysread($fh, my $str, 1024)) {
4472 my $out = syswrite($tmp_fh, $str, $res);
4473 defined($out) && $out == $res
4474 or croak("write ",
4475 Git::temp_path($tmp_fh),
4476 ": $!\n");
4477 }
4478 defined $res or croak $!;
4479
4480 ($fh, $tmp_fh) = ($tmp_fh, $fh);
4481 Git::temp_release($tmp_fh, 1);
4482 }
4483 }
4484
4485 $hash = $::_repository->hash_and_insert_object(
4486 Git::temp_path($fh));
4487 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
4488
4489 Git::temp_release($fb->{base}, 1);
4490 Git::temp_release($fh, 1);
4491 } else {
4492 $hash = $fb->{blob} or die "no blob information\n";
4493 }
4494 $fb->{pool}->clear;
4495 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
4496 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
4497 undef;
4498}
4499
4500sub abort_edit {
4501 my $self = shift;
4502 $self->{nr} = $self->{gii}->{nr};
4503 delete $self->{gii};
4504 $self->SUPER::abort_edit(@_);
4505}
4506
4507sub close_edit {
4508 my $self = shift;
4509
4510 if ($_preserve_empty_dirs) {
4511 my @empty_dirs;
4512
4513 # Any entry flagged as empty that also has an associated
4514 # dir_prop represents a newly created empty directory.
4515 foreach my $i (keys %{$self->{empty}}) {
4516 push @empty_dirs, $i if exists $self->{dir_prop}->{$i};
4517 }
4518
4519 # Search for directories that have become empty due subsequent
4520 # file deletes.
4521 push @empty_dirs, $self->find_empty_directories();
4522
4523 # Finally, add a placeholder file to each empty directory.
4524 $self->add_placeholder_file($_) foreach (@empty_dirs);
4525
4526 $self->stash_placeholder_list();
4527 }
4528
4529 $self->{git_commit_ok} = 1;
4530 $self->{nr} = $self->{gii}->{nr};
4531 delete $self->{gii};
4532 $self->SUPER::close_edit(@_);
4533}
4534
4535sub find_empty_directories {
4536 my ($self) = @_;
4537 my @empty_dirs;
4538 my %dirs = map { dirname($_) => 1 } @deleted_gpath;
4539
4540 foreach my $dir (sort keys %dirs) {
4541 next if $dir eq ".";
4542
4543 # If there have been any additions to this directory, there is
4544 # no reason to check if it is empty.
4545 my $skip_added = 0;
4546 foreach my $t (qw/dir_prop file_prop/) {
4547 foreach my $path (keys %{ $self->{$t} }) {
4548 if (exists $self->{$t}->{dirname($path)}) {
4549 $skip_added = 1;
4550 last;
4551 }
4552 }
4553 last if $skip_added;
4554 }
4555 next if $skip_added;
4556
4557 # Use `git ls-tree` to get the filenames of this directory
4558 # that existed prior to this particular commit.
4559 my $ls = command('ls-tree', '-z', '--name-only',
4560 $self->{c}, "$dir/");
4561 my %files = map { $_ => 1 } split(/\0/, $ls);
4562
4563 # Remove the filenames that were deleted during this commit.
4564 delete $files{$_} foreach (@deleted_gpath);
4565
4566 # Report the directory if there are no filenames left.
4567 push @empty_dirs, $dir unless (scalar %files);
4568 }
4569 @empty_dirs;
4570}
4571
4572sub add_placeholder_file {
4573 my ($self, $dir) = @_;
4574 my $path = "$dir/$_placeholder_filename";
4575 my $gpath = $self->git_path($path);
4576
4577 my $fh = $::_repository->temp_acquire($gpath);
4578 my $hash = $::_repository->hash_and_insert_object(Git::temp_path($fh));
4579 Git::temp_release($fh, 1);
4580 $self->{gii}->update('100644', $hash, $gpath) or croak $!;
4581
4582 # The directory should no longer be considered empty.
4583 delete $self->{empty}->{$dir} if exists $self->{empty}->{$dir};
4584
4585 # Keep track of any placeholder files we create.
4586 $added_placeholder{$dir} = $path;
4587}
4588
4589sub stash_placeholder_list {
4590 my ($self) = @_;
4591 my $k = "svn-remote.$repo_id.added-placeholder";
4592 my $v = eval { command_oneline('config', '--get-all', $k) };
4593 command_noisy('config', '--unset-all', $k) if $v;
4594 foreach (values %added_placeholder) {
4595 command_noisy('config', '--add', $k, $_);
4596 }
4597}
4598
4599package SVN::Git::Editor;
4600use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
4601use strict;
4602use warnings;
4603use Carp qw/croak/;
4604use IO::File;
4605
4606sub new {
4607 my ($class, $opts) = @_;
4608 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
4609 die "$_ required!\n" unless (defined $opts->{$_});
4610 }
4611
4612 my $pool = SVN::Pool->new;
4613 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
4614 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
4615 $opts->{r}, $mods);
4616
4617 # $opts->{ra} functions should not be used after this:
4618 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
4619 $opts->{editor_cb}, $pool);
4620 my $self = SVN::Delta::Editor->new(@ce, $pool);
4621 bless $self, $class;
4622 foreach (qw/svn_path r tree_a tree_b/) {
4623 $self->{$_} = $opts->{$_};
4624 }
4625 $self->{url} = $opts->{ra}->{url};
4626 $self->{mods} = $mods;
4627 $self->{types} = $types;
4628 $self->{pool} = $pool;
4629 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
4630 $self->{rm} = { };
4631 $self->{path_prefix} = length $self->{svn_path} ?
4632 "$self->{svn_path}/" : '';
4633 $self->{config} = $opts->{config};
4634 $self->{mergeinfo} = $opts->{mergeinfo};
4635 return $self;
4636}
4637
4638sub generate_diff {
4639 my ($tree_a, $tree_b) = @_;
4640 my @diff_tree = qw(diff-tree -z -r);
4641 if ($_cp_similarity) {
4642 push @diff_tree, "-C$_cp_similarity";
4643 } else {
4644 push @diff_tree, '-C';
4645 }
4646 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
4647 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
4648 push @diff_tree, $tree_a, $tree_b;
4649 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
4650 local $/ = "\0";
4651 my $state = 'meta';
4652 my @mods;
4653 while (<$diff_fh>) {
4654 chomp $_; # this gets rid of the trailing "\0"
4655 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
4656 ($::sha1)\s($::sha1)\s
4657 ([MTCRAD])\d*$/xo) {
4658 push @mods, { mode_a => $1, mode_b => $2,
4659 sha1_a => $3, sha1_b => $4,
4660 chg => $5 };
4661 if ($5 =~ /^(?:C|R)$/) {
4662 $state = 'file_a';
4663 } else {
4664 $state = 'file_b';
4665 }
4666 } elsif ($state eq 'file_a') {
4667 my $x = $mods[$#mods] or croak "Empty array\n";
4668 if ($x->{chg} !~ /^(?:C|R)$/) {
4669 croak "Error parsing $_, $x->{chg}\n";
4670 }
4671 $x->{file_a} = $_;
4672 $state = 'file_b';
4673 } elsif ($state eq 'file_b') {
4674 my $x = $mods[$#mods] or croak "Empty array\n";
4675 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
4676 croak "Error parsing $_, $x->{chg}\n";
4677 }
4678 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
4679 croak "Error parsing $_, $x->{chg}\n";
4680 }
4681 $x->{file_b} = $_;
4682 $state = 'meta';
4683 } else {
4684 croak "Error parsing $_\n";
4685 }
4686 }
4687 command_close_pipe($diff_fh, $ctx);
4688 \@mods;
4689}
4690
4691sub check_diff_paths {
4692 my ($ra, $pfx, $rev, $mods) = @_;
4693 my %types;
4694 $pfx .= '/' if length $pfx;
4695
4696 sub type_diff_paths {
4697 my ($ra, $types, $path, $rev) = @_;
4698 my @p = split m#/+#, $path;
4699 my $c = shift @p;
4700 unless (defined $types->{$c}) {
4701 $types->{$c} = $ra->check_path($c, $rev);
4702 }
4703 while (@p) {
4704 $c .= '/' . shift @p;
4705 next if defined $types->{$c};
4706 $types->{$c} = $ra->check_path($c, $rev);
4707 }
4708 }
4709
4710 foreach my $m (@$mods) {
4711 foreach my $f (qw/file_a file_b/) {
4712 next unless defined $m->{$f};
4713 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
4714 if (length $pfx.$dir && ! defined $types{$dir}) {
4715 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
4716 }
4717 }
4718 }
4719 \%types;
4720}
4721
4722sub split_path {
4723 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
4724}
4725
4726sub repo_path {
4727 my ($self, $path) = @_;
4728 if (my $enc = $self->{pathnameencoding}) {
4729 require Encode;
4730 Encode::from_to($path, $enc, 'UTF-8');
4731 }
4732 $self->{path_prefix}.(defined $path ? $path : '');
4733}
4734
4735sub url_path {
4736 my ($self, $path) = @_;
4737 if ($self->{url} =~ m#^https?://#) {
4738 $path =~ s!([^~a-zA-Z0-9_./-])!uc sprintf("%%%02x",ord($1))!eg;
4739 }
4740 $self->{url} . '/' . $self->repo_path($path);
4741}
4742
4743sub rmdirs {
4744 my ($self) = @_;
4745 my $rm = $self->{rm};
4746 delete $rm->{''}; # we never delete the url we're tracking
4747 return unless %$rm;
4748
4749 foreach (keys %$rm) {
4750 my @d = split m#/#, $_;
4751 my $c = shift @d;
4752 $rm->{$c} = 1;
4753 while (@d) {
4754 $c .= '/' . shift @d;
4755 $rm->{$c} = 1;
4756 }
4757 }
4758 delete $rm->{$self->{svn_path}};
4759 delete $rm->{''}; # we never delete the url we're tracking
4760 return unless %$rm;
4761
4762 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
4763 $self->{tree_b});
4764 local $/ = "\0";
4765 while (<$fh>) {
4766 chomp;
4767 my @dn = split m#/#, $_;
4768 while (pop @dn) {
4769 delete $rm->{join '/', @dn};
4770 }
4771 unless (%$rm) {
4772 close $fh;
4773 return;
4774 }
4775 }
4776 command_close_pipe($fh, $ctx);
4777
4778 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
4779 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
4780 $self->close_directory($bat->{$d}, $p);
4781 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
4782 print "\tD+\t$d/\n" unless $::_q;
4783 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
4784 delete $bat->{$d};
4785 }
4786}
4787
4788sub open_or_add_dir {
4789 my ($self, $full_path, $baton) = @_;
4790 my $t = $self->{types}->{$full_path};
4791 if (!defined $t) {
4792 die "$full_path not known in r$self->{r} or we have a bug!\n";
4793 }
4794 {
4795 no warnings 'once';
4796 # SVN::Node::none and SVN::Node::file are used only once,
4797 # so we're shutting up Perl's warnings about them.
4798 if ($t == $SVN::Node::none) {
4799 return $self->add_directory($full_path, $baton,
4800 undef, -1, $self->{pool});
4801 } elsif ($t == $SVN::Node::dir) {
4802 return $self->open_directory($full_path, $baton,
4803 $self->{r}, $self->{pool});
4804 } # no warnings 'once'
4805 print STDERR "$full_path already exists in repository at ",
4806 "r$self->{r} and it is not a directory (",
4807 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
4808 } # no warnings 'once'
4809 exit 1;
4810}
4811
4812sub ensure_path {
4813 my ($self, $path) = @_;
4814 my $bat = $self->{bat};
4815 my $repo_path = $self->repo_path($path);
4816 return $bat->{''} unless (length $repo_path);
4817 my @p = split m#/+#, $repo_path;
4818 my $c = shift @p;
4819 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
4820 while (@p) {
4821 my $c0 = $c;
4822 $c .= '/' . shift @p;
4823 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
4824 }
4825 return $bat->{$c};
4826}
4827
4828# Subroutine to convert a globbing pattern to a regular expression.
4829# From perl cookbook.
4830sub glob2pat {
4831 my $globstr = shift;
4832 my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
4833 $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
4834 return '^' . $globstr . '$';
4835}
4836
4837sub check_autoprop {
4838 my ($self, $pattern, $properties, $file, $fbat) = @_;
4839 # Convert the globbing pattern to a regular expression.
4840 my $regex = glob2pat($pattern);
4841 # Check if the pattern matches the file name.
4842 if($file =~ m/($regex)/) {
4843 # Parse the list of properties to set.
4844 my @props = split(/;/, $properties);
4845 foreach my $prop (@props) {
4846 # Parse 'name=value' syntax and set the property.
4847 if ($prop =~ /([^=]+)=(.*)/) {
4848 my ($n,$v) = ($1,$2);
4849 for ($n, $v) {
4850 s/^\s+//; s/\s+$//;
4851 }
4852 $self->change_file_prop($fbat, $n, $v);
4853 }
4854 }
4855 }
4856}
4857
4858sub apply_autoprops {
4859 my ($self, $file, $fbat) = @_;
4860 my $conf_t = ${$self->{config}}{'config'};
4861 no warnings 'once';
4862 # Check [miscellany]/enable-auto-props in svn configuration.
4863 if (SVN::_Core::svn_config_get_bool(
4864 $conf_t,
4865 $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
4866 $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
4867 0)) {
4868 # Auto-props are enabled. Enumerate them to look for matches.
4869 my $callback = sub {
4870 $self->check_autoprop($_[0], $_[1], $file, $fbat);
4871 };
4872 SVN::_Core::svn_config_enumerate(
4873 $conf_t,
4874 $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
4875 $callback);
4876 }
4877}
4878
4879sub A {
4880 my ($self, $m) = @_;
4881 my ($dir, $file) = split_path($m->{file_b});
4882 my $pbat = $self->ensure_path($dir);
4883 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4884 undef, -1);
4885 print "\tA\t$m->{file_b}\n" unless $::_q;
4886 $self->apply_autoprops($file, $fbat);
4887 $self->chg_file($fbat, $m);
4888 $self->close_file($fbat,undef,$self->{pool});
4889}
4890
4891sub C {
4892 my ($self, $m) = @_;
4893 my ($dir, $file) = split_path($m->{file_b});
4894 my $pbat = $self->ensure_path($dir);
4895 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4896 $self->url_path($m->{file_a}), $self->{r});
4897 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
4898 $self->chg_file($fbat, $m);
4899 $self->close_file($fbat,undef,$self->{pool});
4900}
4901
4902sub delete_entry {
4903 my ($self, $path, $pbat) = @_;
4904 my $rpath = $self->repo_path($path);
4905 my ($dir, $file) = split_path($rpath);
4906 $self->{rm}->{$dir} = 1;
4907 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
4908}
4909
4910sub R {
4911 my ($self, $m) = @_;
4912 my ($dir, $file) = split_path($m->{file_b});
4913 my $pbat = $self->ensure_path($dir);
4914 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4915 $self->url_path($m->{file_a}), $self->{r});
4916 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
4917 $self->apply_autoprops($file, $fbat);
4918 $self->chg_file($fbat, $m);
4919 $self->close_file($fbat,undef,$self->{pool});
4920
4921 ($dir, $file) = split_path($m->{file_a});
4922 $pbat = $self->ensure_path($dir);
4923 $self->delete_entry($m->{file_a}, $pbat);
4924}
4925
4926sub M {
4927 my ($self, $m) = @_;
4928 my ($dir, $file) = split_path($m->{file_b});
4929 my $pbat = $self->ensure_path($dir);
4930 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
4931 $pbat,$self->{r},$self->{pool});
4932 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
4933 $self->chg_file($fbat, $m);
4934 $self->close_file($fbat,undef,$self->{pool});
4935}
4936
4937sub T { shift->M(@_) }
4938
4939sub change_file_prop {
4940 my ($self, $fbat, $pname, $pval) = @_;
4941 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
4942}
4943
4944sub change_dir_prop {
4945 my ($self, $pbat, $pname, $pval) = @_;
4946 $self->SUPER::change_dir_prop($pbat, $pname, $pval, $self->{pool});
4947}
4948
4949sub _chg_file_get_blob ($$$$) {
4950 my ($self, $fbat, $m, $which) = @_;
4951 my $fh = $::_repository->temp_acquire("git_blob_$which");
4952 if ($m->{"mode_$which"} =~ /^120/) {
4953 print $fh 'link ' or croak $!;
4954 $self->change_file_prop($fbat,'svn:special','*');
4955 } elsif ($m->{mode_a} =~ /^120/ && $m->{"mode_$which"} !~ /^120/) {
4956 $self->change_file_prop($fbat,'svn:special',undef);
4957 }
4958 my $blob = $m->{"sha1_$which"};
4959 return ($fh,) if ($blob =~ /^0{40}$/);
4960 my $size = $::_repository->cat_blob($blob, $fh);
4961 croak "Failed to read object $blob" if ($size < 0);
4962 $fh->flush == 0 or croak $!;
4963 seek $fh, 0, 0 or croak $!;
4964
4965 my $exp = ::md5sum($fh);
4966 seek $fh, 0, 0 or croak $!;
4967 return ($fh, $exp);
4968}
4969
4970sub chg_file {
4971 my ($self, $fbat, $m) = @_;
4972 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
4973 $self->change_file_prop($fbat,'svn:executable','*');
4974 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
4975 $self->change_file_prop($fbat,'svn:executable',undef);
4976 }
4977 my ($fh_a, $exp_a) = _chg_file_get_blob $self, $fbat, $m, 'a';
4978 my ($fh_b, $exp_b) = _chg_file_get_blob $self, $fbat, $m, 'b';
4979 my $pool = SVN::Pool->new;
4980 my $atd = $self->apply_textdelta($fbat, $exp_a, $pool);
4981 if (-s $fh_a) {
4982 my $txstream = SVN::TxDelta::new ($fh_a, $fh_b, $pool);
4983 my $res = SVN::TxDelta::send_txstream($txstream, @$atd, $pool);
4984 if (defined $res) {
4985 die "Unexpected result from send_txstream: $res\n",
4986 "(SVN::Core::VERSION: $SVN::Core::VERSION)\n";
4987 }
4988 } else {
4989 my $got = SVN::TxDelta::send_stream($fh_b, @$atd, $pool);
4990 die "Checksum mismatch\nexpected: $exp_b\ngot: $got\n"
4991 if ($got ne $exp_b);
4992 }
4993 Git::temp_release($fh_b, 1);
4994 Git::temp_release($fh_a, 1);
4995 $pool->clear;
4996}
4997
4998sub D {
4999 my ($self, $m) = @_;
5000 my ($dir, $file) = split_path($m->{file_b});
5001 my $pbat = $self->ensure_path($dir);
5002 print "\tD\t$m->{file_b}\n" unless $::_q;
5003 $self->delete_entry($m->{file_b}, $pbat);
5004}
5005
5006sub close_edit {
5007 my ($self) = @_;
5008 my ($p,$bat) = ($self->{pool}, $self->{bat});
5009 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
5010 next if $_ eq '';
5011 $self->close_directory($bat->{$_}, $p);
5012 }
5013 $self->close_directory($bat->{''}, $p);
5014 $self->SUPER::close_edit($p);
5015 $p->clear;
5016}
5017
5018sub abort_edit {
5019 my ($self) = @_;
5020 $self->SUPER::abort_edit($self->{pool});
5021}
5022
5023sub DESTROY {
5024 my $self = shift;
5025 $self->SUPER::DESTROY(@_);
5026 $self->{pool}->clear;
5027}
5028
5029# this drives the editor
5030sub apply_diff {
5031 my ($self) = @_;
5032 my $mods = $self->{mods};
5033 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
5034 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
5035 my $f = $m->{chg};
5036 if (defined $o{$f}) {
5037 $self->$f($m);
5038 } else {
5039 fatal("Invalid change type: $f");
5040 }
5041 }
5042
5043 if (defined($self->{mergeinfo})) {
5044 $self->change_dir_prop($self->{bat}{''}, "svn:mergeinfo",
5045 $self->{mergeinfo});
5046 }
5047 $self->rmdirs if $_rmdir;
5048 if (@$mods == 0) {
5049 $self->abort_edit;
5050 } else {
5051 $self->close_edit;
5052 }
5053 return scalar @$mods;
5054}
5055
5056package Git::SVN::Ra;
5057use vars qw/@ISA $config_dir $_log_window_size/;
5058use strict;
5059use warnings;
5060my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
5061
5062BEGIN {
5063 # enforce temporary pool usage for some simple functions
5064 no strict 'refs';
5065 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root
5066 get_file/) {
5067 my $SUPER = "SUPER::$f";
5068 *$f = sub {
5069 my $self = shift;
5070 my $pool = SVN::Pool->new;
5071 my @ret = $self->$SUPER(@_,$pool);
5072 $pool->clear;
5073 wantarray ? @ret : $ret[0];
5074 };
5075 }
5076}
5077
5078sub _auth_providers () {
5079 [
5080 SVN::Client::get_simple_provider(),
5081 SVN::Client::get_ssl_server_trust_file_provider(),
5082 SVN::Client::get_simple_prompt_provider(
5083 \&Git::SVN::Prompt::simple, 2),
5084 SVN::Client::get_ssl_client_cert_file_provider(),
5085 SVN::Client::get_ssl_client_cert_prompt_provider(
5086 \&Git::SVN::Prompt::ssl_client_cert, 2),
5087 SVN::Client::get_ssl_client_cert_pw_file_provider(),
5088 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
5089 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
5090 SVN::Client::get_username_provider(),
5091 SVN::Client::get_ssl_server_trust_prompt_provider(
5092 \&Git::SVN::Prompt::ssl_server_trust),
5093 SVN::Client::get_username_prompt_provider(
5094 \&Git::SVN::Prompt::username, 2)
5095 ]
5096}
5097
5098sub escape_uri_only {
5099 my ($uri) = @_;
5100 my @tmp;
5101 foreach (split m{/}, $uri) {
5102 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
5103 push @tmp, $_;
5104 }
5105 join('/', @tmp);
5106}
5107
5108sub escape_url {
5109 my ($url) = @_;
5110 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
5111 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
5112 $url = "$scheme://$domain$uri";
5113 }
5114 $url;
5115}
5116
5117sub new {
5118 my ($class, $url) = @_;
5119 $url =~ s!/+$!!;
5120 return $RA if ($RA && $RA->{url} eq $url);
5121
5122 ::_req_svn();
5123
5124 SVN::_Core::svn_config_ensure($config_dir, undef);
5125 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
5126 my $config = SVN::Core::config_get_config($config_dir);
5127 $RA = undef;
5128 my $dont_store_passwords = 1;
5129 my $conf_t = ${$config}{'config'};
5130 {
5131 no warnings 'once';
5132 # The usage of $SVN::_Core::SVN_CONFIG_* variables
5133 # produces warnings that variables are used only once.
5134 # I had not found the better way to shut them up, so
5135 # the warnings of type 'once' are disabled in this block.
5136 if (SVN::_Core::svn_config_get_bool($conf_t,
5137 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
5138 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
5139 1) == 0) {
5140 SVN::_Core::svn_auth_set_parameter($baton,
5141 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
5142 bless (\$dont_store_passwords, "_p_void"));
5143 }
5144 if (SVN::_Core::svn_config_get_bool($conf_t,
5145 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
5146 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
5147 1) == 0) {
5148 $Git::SVN::Prompt::_no_auth_cache = 1;
5149 }
5150 } # no warnings 'once'
5151 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
5152 config => $config,
5153 pool => SVN::Pool->new,
5154 auth_provider_callbacks => $callbacks);
5155 $self->{url} = $url;
5156 $self->{svn_path} = $url;
5157 $self->{repos_root} = $self->get_repos_root;
5158 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
5159 $self->{cache} = { check_path => { r => 0, data => {} },
5160 get_dir => { r => 0, data => {} } };
5161 $RA = bless $self, $class;
5162}
5163
5164sub check_path {
5165 my ($self, $path, $r) = @_;
5166 my $cache = $self->{cache}->{check_path};
5167 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
5168 return $cache->{data}->{$path};
5169 }
5170 my $pool = SVN::Pool->new;
5171 my $t = $self->SUPER::check_path($path, $r, $pool);
5172 $pool->clear;
5173 if ($r != $cache->{r}) {
5174 %{$cache->{data}} = ();
5175 $cache->{r} = $r;
5176 }
5177 $cache->{data}->{$path} = $t;
5178}
5179
5180sub get_dir {
5181 my ($self, $dir, $r) = @_;
5182 my $cache = $self->{cache}->{get_dir};
5183 if ($r == $cache->{r}) {
5184 if (my $x = $cache->{data}->{$dir}) {
5185 return wantarray ? @$x : $x->[0];
5186 }
5187 }
5188 my $pool = SVN::Pool->new;
5189 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
5190 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
5191 $pool->clear;
5192 if ($r != $cache->{r}) {
5193 %{$cache->{data}} = ();
5194 $cache->{r} = $r;
5195 }
5196 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
5197 wantarray ? (\%dirents, $r, $props) : \%dirents;
5198}
5199
5200sub DESTROY {
5201 # do not call the real DESTROY since we store ourselves in $RA
5202}
5203
5204# get_log(paths, start, end, limit,
5205# discover_changed_paths, strict_node_history, receiver)
5206sub get_log {
5207 my ($self, @args) = @_;
5208 my $pool = SVN::Pool->new;
5209
5210 # svn_log_changed_path_t objects passed to get_log are likely to be
5211 # overwritten even if only the refs are copied to an external variable,
5212 # so we should dup the structures in their entirety. Using an
5213 # externally passed pool (instead of our temporary and quickly cleared
5214 # pool in Git::SVN::Ra) does not help matters at all...
5215 my $receiver = pop @args;
5216 my $prefix = "/".$self->{svn_path};
5217 $prefix =~ s#/+($)##;
5218 my $prefix_regex = qr#^\Q$prefix\E#;
5219 push(@args, sub {
5220 my ($paths) = $_[0];
5221 return &$receiver(@_) unless $paths;
5222 $_[0] = ();
5223 foreach my $p (keys %$paths) {
5224 my $i = $paths->{$p};
5225 # Make path relative to our url, not repos_root
5226 $p =~ s/$prefix_regex//;
5227 my %s = map { $_ => $i->$_; }
5228 qw/copyfrom_path copyfrom_rev action/;
5229 if ($s{'copyfrom_path'}) {
5230 $s{'copyfrom_path'} =~ s/$prefix_regex//;
5231 }
5232 $_[0]{$p} = \%s;
5233 }
5234 &$receiver(@_);
5235 });
5236
5237
5238 # the limit parameter was not supported in SVN 1.1.x, so we
5239 # drop it. Therefore, the receiver callback passed to it
5240 # is made aware of this limitation by being wrapped if
5241 # the limit passed to is being wrapped.
5242 if ($SVN::Core::VERSION le '1.2.0') {
5243 my $limit = splice(@args, 3, 1);
5244 if ($limit > 0) {
5245 my $receiver = pop @args;
5246 push(@args, sub { &$receiver(@_) if (--$limit >= 0) });
5247 }
5248 }
5249 my $ret = $self->SUPER::get_log(@args, $pool);
5250 $pool->clear;
5251 $ret;
5252}
5253
5254sub trees_match {
5255 my ($self, $url1, $rev1, $url2, $rev2) = @_;
5256 my $ctx = SVN::Client->new(auth => _auth_providers);
5257 my $out = IO::File->new_tmpfile;
5258
5259 # older SVN (1.1.x) doesn't take $pool as the last parameter for
5260 # $ctx->diff(), so we'll create a default one
5261 my $pool = SVN::Pool->new_default_sub;
5262
5263 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
5264 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
5265 $out->flush;
5266 my $ret = (($out->stat)[7] == 0);
5267 close $out or croak $!;
5268
5269 $ret;
5270}
5271
5272sub get_commit_editor {
5273 my ($self, $log, $cb, $pool) = @_;
5274 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
5275 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
5276}
5277
5278sub gs_do_update {
5279 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
5280 my $new = ($rev_a == $rev_b);
5281 my $path = $gs->{path};
5282
5283 if ($new && -e $gs->{index}) {
5284 unlink $gs->{index} or die
5285 "Couldn't unlink index: $gs->{index}: $!\n";
5286 }
5287 my $pool = SVN::Pool->new;
5288 $editor->set_path_strip($path);
5289 my (@pc) = split m#/#, $path;
5290 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
5291 1, $editor, $pool);
5292 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
5293
5294 # Since we can't rely on svn_ra_reparent being available, we'll
5295 # just have to do some magic with set_path to make it so
5296 # we only want a partial path.
5297 my $sp = '';
5298 my $final = join('/', @pc);
5299 while (@pc) {
5300 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
5301 $sp .= '/' if length $sp;
5302 $sp .= shift @pc;
5303 }
5304 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
5305
5306 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
5307
5308 $reporter->finish_report($pool);
5309 $pool->clear;
5310 $editor->{git_commit_ok};
5311}
5312
5313# this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
5314# svn_ra_reparent didn't work before 1.4)
5315sub gs_do_switch {
5316 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
5317 my $path = $gs->{path};
5318 my $pool = SVN::Pool->new;
5319
5320 my $full_url = $self->{url};
5321 my $old_url = $full_url;
5322 $full_url .= '/' . $path if length $path;
5323 my ($ra, $reparented);
5324
5325 if ($old_url =~ m#^svn(\+ssh)?://# ||
5326 ($full_url =~ m#^https?://# &&
5327 escape_url($full_url) ne $full_url)) {
5328 $_[0] = undef;
5329 $self = undef;
5330 $RA = undef;
5331 $ra = Git::SVN::Ra->new($full_url);
5332 $ra_invalid = 1;
5333 } elsif ($old_url ne $full_url) {
5334 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url, $pool);
5335 $self->{url} = $full_url;
5336 $reparented = 1;
5337 }
5338
5339 $ra ||= $self;
5340 $url_b = escape_url($url_b);
5341 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
5342 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
5343 $reporter->set_path('', $rev_a, 0, @lock, $pool);
5344 $reporter->finish_report($pool);
5345
5346 if ($reparented) {
5347 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
5348 $self->{url} = $old_url;
5349 }
5350
5351 $pool->clear;
5352 $editor->{git_commit_ok};
5353}
5354
5355sub longest_common_path {
5356 my ($gsv, $globs) = @_;
5357 my %common;
5358 my $common_max = scalar @$gsv;
5359
5360 foreach my $gs (@$gsv) {
5361 my @tmp = split m#/#, $gs->{path};
5362 my $p = '';
5363 foreach (@tmp) {
5364 $p .= length($p) ? "/$_" : $_;
5365 $common{$p} ||= 0;
5366 $common{$p}++;
5367 }
5368 }
5369 $globs ||= [];
5370 $common_max += scalar @$globs;
5371 foreach my $glob (@$globs) {
5372 my @tmp = split m#/#, $glob->{path}->{left};
5373 my $p = '';
5374 foreach (@tmp) {
5375 $p .= length($p) ? "/$_" : $_;
5376 $common{$p} ||= 0;
5377 $common{$p}++;
5378 }
5379 }
5380
5381 my $longest_path = '';
5382 foreach (sort {length $b <=> length $a} keys %common) {
5383 if ($common{$_} == $common_max) {
5384 $longest_path = $_;
5385 last;
5386 }
5387 }
5388 $longest_path;
5389}
5390
5391sub gs_fetch_loop_common {
5392 my ($self, $base, $head, $gsv, $globs) = @_;
5393 return if ($base > $head);
5394 my $inc = $_log_window_size;
5395 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
5396 my $longest_path = longest_common_path($gsv, $globs);
5397 my $ra_url = $self->{url};
5398 my $find_trailing_edge;
5399 while (1) {
5400 my %revs;
5401 my $err;
5402 my $err_handler = $SVN::Error::handler;
5403 $SVN::Error::handler = sub {
5404 ($err) = @_;
5405 skip_unknown_revs($err);
5406 };
5407 sub _cb {
5408 my ($paths, $r, $author, $date, $log) = @_;
5409 [ $paths,
5410 { author => $author, date => $date, log => $log } ];
5411 }
5412 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
5413 sub { $revs{$_[1]} = _cb(@_) });
5414 if ($err) {
5415 print "Checked through r$max\r";
5416 } else {
5417 $find_trailing_edge = 1;
5418 }
5419 if ($err and $find_trailing_edge) {
5420 print STDERR "Path '$longest_path' ",
5421 "was probably deleted:\n",
5422 $err->expanded_message,
5423 "\nWill attempt to follow ",
5424 "revisions r$min .. r$max ",
5425 "committed before the deletion\n";
5426 my $hi = $max;
5427 while (--$hi >= $min) {
5428 my $ok;
5429 $self->get_log([$longest_path], $min, $hi,
5430 0, 1, 1, sub {
5431 $ok = $_[1];
5432 $revs{$_[1]} = _cb(@_) });
5433 if ($ok) {
5434 print STDERR "r$min .. r$ok OK\n";
5435 last;
5436 }
5437 }
5438 $find_trailing_edge = 0;
5439 }
5440 $SVN::Error::handler = $err_handler;
5441
5442 my %exists = map { $_->{path} => $_ } @$gsv;
5443 foreach my $r (sort {$a <=> $b} keys %revs) {
5444 my ($paths, $logged) = @{$revs{$r}};
5445
5446 foreach my $gs ($self->match_globs(\%exists, $paths,
5447 $globs, $r)) {
5448 if ($gs->rev_map_max >= $r) {
5449 next;
5450 }
5451 next unless $gs->match_paths($paths, $r);
5452 $gs->{logged_rev_props} = $logged;
5453 if (my $last_commit = $gs->last_commit) {
5454 $gs->assert_index_clean($last_commit);
5455 }
5456 my $log_entry = $gs->do_fetch($paths, $r);
5457 if ($log_entry) {
5458 $gs->do_git_commit($log_entry);
5459 }
5460 $INDEX_FILES{$gs->{index}} = 1;
5461 }
5462 foreach my $g (@$globs) {
5463 my $k = "svn-remote.$g->{remote}." .
5464 "$g->{t}-maxRev";
5465 Git::SVN::tmp_config($k, $r);
5466 }
5467 if ($ra_invalid) {
5468 $_[0] = undef;
5469 $self = undef;
5470 $RA = undef;
5471 $self = Git::SVN::Ra->new($ra_url);
5472 $ra_invalid = undef;
5473 }
5474 }
5475 # pre-fill the .rev_db since it'll eventually get filled in
5476 # with '0' x40 if something new gets committed
5477 foreach my $gs (@$gsv) {
5478 next if $gs->rev_map_max >= $max;
5479 next if defined $gs->rev_map_get($max);
5480 $gs->rev_map_set($max, 0 x40);
5481 }
5482 foreach my $g (@$globs) {
5483 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
5484 Git::SVN::tmp_config($k, $max);
5485 }
5486 last if $max >= $head;
5487 $min = $max + 1;
5488 $max += $inc;
5489 $max = $head if ($max > $head);
5490 }
5491 Git::SVN::gc();
5492}
5493
5494sub get_dir_globbed {
5495 my ($self, $left, $depth, $r) = @_;
5496
5497 my @x = eval { $self->get_dir($left, $r) };
5498 return unless scalar @x == 3;
5499 my $dirents = $x[0];
5500 my @finalents;
5501 foreach my $de (keys %$dirents) {
5502 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
5503 if ($depth > 1) {
5504 my @args = ("$left/$de", $depth - 1, $r);
5505 foreach my $dir ($self->get_dir_globbed(@args)) {
5506 push @finalents, "$de/$dir";
5507 }
5508 } else {
5509 push @finalents, $de;
5510 }
5511 }
5512 @finalents;
5513}
5514
5515sub match_globs {
5516 my ($self, $exists, $paths, $globs, $r) = @_;
5517
5518 sub get_dir_check {
5519 my ($self, $exists, $g, $r) = @_;
5520
5521 my @dirs = $self->get_dir_globbed($g->{path}->{left},
5522 $g->{path}->{depth},
5523 $r);
5524
5525 foreach my $de (@dirs) {
5526 my $p = $g->{path}->full_path($de);
5527 next if $exists->{$p};
5528 next if (length $g->{path}->{right} &&
5529 ($self->check_path($p, $r) !=
5530 $SVN::Node::dir));
5531 next unless $p =~ /$g->{path}->{regex}/;
5532 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
5533 $g->{ref}->full_path($de), 1);
5534 }
5535 }
5536 foreach my $g (@$globs) {
5537 if (my $path = $paths->{"/$g->{path}->{left}"}) {
5538 if ($path->{action} =~ /^[AR]$/) {
5539 get_dir_check($self, $exists, $g, $r);
5540 }
5541 }
5542 foreach (keys %$paths) {
5543 if (/$g->{path}->{left_regex}/ &&
5544 !/$g->{path}->{regex}/) {
5545 next if $paths->{$_}->{action} !~ /^[AR]$/;
5546 get_dir_check($self, $exists, $g, $r);
5547 }
5548 next unless /$g->{path}->{regex}/;
5549 my $p = $1;
5550 my $pathname = $g->{path}->full_path($p);
5551 next if $exists->{$pathname};
5552 next if ($self->check_path($pathname, $r) !=
5553 $SVN::Node::dir);
5554 $exists->{$pathname} = Git::SVN->init(
5555 $self->{url}, $pathname, undef,
5556 $g->{ref}->full_path($p), 1);
5557 }
5558 my $c = '';
5559 foreach (split m#/#, $g->{path}->{left}) {
5560 $c .= "/$_";
5561 next unless ($paths->{$c} &&
5562 ($paths->{$c}->{action} =~ /^[AR]$/));
5563 get_dir_check($self, $exists, $g, $r);
5564 }
5565 }
5566 values %$exists;
5567}
5568
5569sub minimize_url {
5570 my ($self) = @_;
5571 return $self->{url} if ($self->{url} eq $self->{repos_root});
5572 my $url = $self->{repos_root};
5573 my @components = split(m!/!, $self->{svn_path});
5574 my $c = '';
5575 do {
5576 $url .= "/$c" if length $c;
5577 eval {
5578 my $ra = (ref $self)->new($url);
5579 my $latest = $ra->get_latest_revnum;
5580 $ra->get_log("", $latest, 0, 1, 0, 1, sub {});
5581 };
5582 } while ($@ && ($c = shift @components));
5583 $url;
5584}
5585
5586sub can_do_switch {
5587 my $self = shift;
5588 unless (defined $can_do_switch) {
5589 my $pool = SVN::Pool->new;
5590 my $rep = eval {
5591 $self->do_switch(1, '', 0, $self->{url},
5592 SVN::Delta::Editor->new, $pool);
5593 };
5594 if ($@) {
5595 $can_do_switch = 0;
5596 } else {
5597 $rep->abort_report($pool);
5598 $can_do_switch = 1;
5599 }
5600 $pool->clear;
5601 }
5602 $can_do_switch;
5603}
5604
5605sub skip_unknown_revs {
5606 my ($err) = @_;
5607 my $errno = $err->apr_err();
5608 # Maybe the branch we're tracking didn't
5609 # exist when the repo started, so it's
5610 # not an error if it doesn't, just continue
5611 #
5612 # Wonderfully consistent library, eh?
5613 # 160013 - svn:// and file://
5614 # 175002 - http(s)://
5615 # 175007 - http(s):// (this repo required authorization, too...)
5616 # More codes may be discovered later...
5617 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
5618 my $err_key = $err->expanded_message;
5619 # revision numbers change every time, filter them out
5620 $err_key =~ s/\d+/\0/g;
5621 $err_key = "$errno\0$err_key";
5622 unless ($ignored_err{$err_key}) {
5623 warn "W: Ignoring error from SVN, path probably ",
5624 "does not exist: ($errno): ",
5625 $err->expanded_message,"\n";
5626 warn "W: Do not be alarmed at the above message ",
5627 "git-svn is just searching aggressively for ",
5628 "old history.\n",
5629 "This may take a while on large repositories\n";
5630 $ignored_err{$err_key} = 1;
5631 }
5632 return;
5633 }
5634 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
5635}
5636
5637package Git::SVN::Log;
5638use strict;
5639use warnings;
5640use POSIX qw/strftime/;
5641use Time::Local;
5642use constant commit_log_separator => ('-' x 72) . "\n";
5643use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
5644 %rusers $show_commit $incremental/;
5645my $l_fmt;
5646
5647sub cmt_showable {
5648 my ($c) = @_;
5649 return 1 if defined $c->{r};
5650
5651 # big commit message got truncated by the 16k pretty buffer in rev-list
5652 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
5653 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
5654 @{$c->{l}} = ();
5655 my @log = command(qw/cat-file commit/, $c->{c});
5656
5657 # shift off the headers
5658 shift @log while ($log[0] ne '');
5659 shift @log;
5660
5661 # TODO: make $c->{l} not have a trailing newline in the future
5662 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
5663
5664 (undef, $c->{r}, undef) = ::extract_metadata(
5665 (grep(/^git-svn-id: /, @log))[-1]);
5666 }
5667 return defined $c->{r};
5668}
5669
5670sub log_use_color {
5671 return $color || Git->repository->get_colorbool('color.diff');
5672}
5673
5674sub git_svn_log_cmd {
5675 my ($r_min, $r_max, @args) = @_;
5676 my $head = 'HEAD';
5677 my (@files, @log_opts);
5678 foreach my $x (@args) {
5679 if ($x eq '--' || @files) {
5680 push @files, $x;
5681 } else {
5682 if (::verify_ref("$x^0")) {
5683 $head = $x;
5684 } else {
5685 push @log_opts, $x;
5686 }
5687 }
5688 }
5689
5690 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
5691 $gs ||= Git::SVN->_new;
5692 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
5693 $gs->refname);
5694 push @cmd, '-r' unless $non_recursive;
5695 push @cmd, qw/--raw --name-status/ if $verbose;
5696 push @cmd, '--color' if log_use_color();
5697 push @cmd, @log_opts;
5698 if (defined $r_max && $r_max == $r_min) {
5699 push @cmd, '--max-count=1';
5700 if (my $c = $gs->rev_map_get($r_max)) {
5701 push @cmd, $c;
5702 }
5703 } elsif (defined $r_max) {
5704 if ($r_max < $r_min) {
5705 ($r_min, $r_max) = ($r_max, $r_min);
5706 }
5707 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
5708 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
5709 # If there are no commits in the range, both $c_max and $c_min
5710 # will be undefined. If there is at least 1 commit in the
5711 # range, both will be defined.
5712 return () if !defined $c_min || !defined $c_max;
5713 if ($c_min eq $c_max) {
5714 push @cmd, '--max-count=1', $c_min;
5715 } else {
5716 push @cmd, '--boundary', "$c_min..$c_max";
5717 }
5718 }
5719 return (@cmd, @files);
5720}
5721
5722# adapted from pager.c
5723sub config_pager {
5724 if (! -t *STDOUT) {
5725 $ENV{GIT_PAGER_IN_USE} = 'false';
5726 $pager = undef;
5727 return;
5728 }
5729 chomp($pager = command_oneline(qw(var GIT_PAGER)));
5730 if ($pager eq 'cat') {
5731 $pager = undef;
5732 }
5733 $ENV{GIT_PAGER_IN_USE} = defined($pager);
5734}
5735
5736sub run_pager {
5737 return unless defined $pager;
5738 pipe my ($rfd, $wfd) or return;
5739 defined(my $pid = fork) or ::fatal "Can't fork: $!";
5740 if (!$pid) {
5741 open STDOUT, '>&', $wfd or
5742 ::fatal "Can't redirect to stdout: $!";
5743 return;
5744 }
5745 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
5746 $ENV{LESS} ||= 'FRSX';
5747 exec $pager or ::fatal "Can't run pager: $! ($pager)";
5748}
5749
5750sub format_svn_date {
5751 # some systmes don't handle or mishandle %z, so be creative.
5752 my $t = shift || time;
5753 my $gm = timelocal(gmtime($t));
5754 my $sign = qw( + + - )[ $t <=> $gm ];
5755 my $gmoff = sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
5756 return strftime("%Y-%m-%d %H:%M:%S $gmoff (%a, %d %b %Y)", localtime($t));
5757}
5758
5759sub parse_git_date {
5760 my ($t, $tz) = @_;
5761 # Date::Parse isn't in the standard Perl distro :(
5762 if ($tz =~ s/^\+//) {
5763 $t += tz_to_s_offset($tz);
5764 } elsif ($tz =~ s/^\-//) {
5765 $t -= tz_to_s_offset($tz);
5766 }
5767 return $t;
5768}
5769
5770sub set_local_timezone {
5771 if (defined $TZ) {
5772 $ENV{TZ} = $TZ;
5773 } else {
5774 delete $ENV{TZ};
5775 }
5776}
5777
5778sub tz_to_s_offset {
5779 my ($tz) = @_;
5780 $tz =~ s/(\d\d)$//;
5781 return ($1 * 60) + ($tz * 3600);
5782}
5783
5784sub get_author_info {
5785 my ($dest, $author, $t, $tz) = @_;
5786 $author =~ s/(?:^\s*|\s*$)//g;
5787 $dest->{a_raw} = $author;
5788 my $au;
5789 if ($::_authors) {
5790 $au = $rusers{$author} || undef;
5791 }
5792 if (!$au) {
5793 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
5794 }
5795 $dest->{t} = $t;
5796 $dest->{tz} = $tz;
5797 $dest->{a} = $au;
5798 $dest->{t_utc} = parse_git_date($t, $tz);
5799}
5800
5801sub process_commit {
5802 my ($c, $r_min, $r_max, $defer) = @_;
5803 if (defined $r_min && defined $r_max) {
5804 if ($r_min == $c->{r} && $r_min == $r_max) {
5805 show_commit($c);
5806 return 0;
5807 }
5808 return 1 if $r_min == $r_max;
5809 if ($r_min < $r_max) {
5810 # we need to reverse the print order
5811 return 0 if (defined $limit && --$limit < 0);
5812 push @$defer, $c;
5813 return 1;
5814 }
5815 if ($r_min != $r_max) {
5816 return 1 if ($r_min < $c->{r});
5817 return 1 if ($r_max > $c->{r});
5818 }
5819 }
5820 return 0 if (defined $limit && --$limit < 0);
5821 show_commit($c);
5822 return 1;
5823}
5824
5825sub show_commit {
5826 my $c = shift;
5827 if ($oneline) {
5828 my $x = "\n";
5829 if (my $l = $c->{l}) {
5830 while ($l->[0] =~ /^\s*$/) { shift @$l }
5831 $x = $l->[0];
5832 }
5833 $l_fmt ||= 'A' . length($c->{r});
5834 print 'r',pack($l_fmt, $c->{r}),' | ';
5835 print "$c->{c} | " if $show_commit;
5836 print $x;
5837 } else {
5838 show_commit_normal($c);
5839 }
5840}
5841
5842sub show_commit_changed_paths {
5843 my ($c) = @_;
5844 return unless $c->{changed};
5845 print "Changed paths:\n", @{$c->{changed}};
5846}
5847
5848sub show_commit_normal {
5849 my ($c) = @_;
5850 print commit_log_separator, "r$c->{r} | ";
5851 print "$c->{c} | " if $show_commit;
5852 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
5853 my $nr_line = 0;
5854
5855 if (my $l = $c->{l}) {
5856 while ($l->[$#$l] eq "\n" && $#$l > 0
5857 && $l->[($#$l - 1)] eq "\n") {
5858 pop @$l;
5859 }
5860 $nr_line = scalar @$l;
5861 if (!$nr_line) {
5862 print "1 line\n\n\n";
5863 } else {
5864 if ($nr_line == 1) {
5865 $nr_line = '1 line';
5866 } else {
5867 $nr_line .= ' lines';
5868 }
5869 print $nr_line, "\n";
5870 show_commit_changed_paths($c);
5871 print "\n";
5872 print $_ foreach @$l;
5873 }
5874 } else {
5875 print "1 line\n";
5876 show_commit_changed_paths($c);
5877 print "\n";
5878
5879 }
5880 foreach my $x (qw/raw stat diff/) {
5881 if ($c->{$x}) {
5882 print "\n";
5883 print $_ foreach @{$c->{$x}}
5884 }
5885 }
5886}
5887
5888sub cmd_show_log {
5889 my (@args) = @_;
5890 my ($r_min, $r_max);
5891 my $r_last = -1; # prevent dupes
5892 set_local_timezone();
5893 if (defined $::_revision) {
5894 if ($::_revision =~ /^(\d+):(\d+)$/) {
5895 ($r_min, $r_max) = ($1, $2);
5896 } elsif ($::_revision =~ /^\d+$/) {
5897 $r_min = $r_max = $::_revision;
5898 } else {
5899 ::fatal "-r$::_revision is not supported, use ",
5900 "standard 'git log' arguments instead";
5901 }
5902 }
5903
5904 config_pager();
5905 @args = git_svn_log_cmd($r_min, $r_max, @args);
5906 if (!@args) {
5907 print commit_log_separator unless $incremental || $oneline;
5908 return;
5909 }
5910 my $log = command_output_pipe(@args);
5911 run_pager();
5912 my (@k, $c, $d, $stat);
5913 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
5914 while (<$log>) {
5915 if (/^${esc_color}commit (?:- )?($::sha1_short)/o) {
5916 my $cmt = $1;
5917 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
5918 $r_last = $c->{r};
5919 process_commit($c, $r_min, $r_max, \@k) or
5920 goto out;
5921 }
5922 $d = undef;
5923 $c = { c => $cmt };
5924 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
5925 get_author_info($c, $1, $2, $3);
5926 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
5927 # ignore
5928 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
5929 push @{$c->{raw}}, $_;
5930 } elsif (/^${esc_color}[ACRMDT]\t/) {
5931 # we could add $SVN->{svn_path} here, but that requires
5932 # remote access at the moment (repo_path_split)...
5933 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
5934 push @{$c->{changed}}, $_;
5935 } elsif (/^${esc_color}diff /o) {
5936 $d = 1;
5937 push @{$c->{diff}}, $_;
5938 } elsif ($d) {
5939 push @{$c->{diff}}, $_;
5940 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
5941 $esc_color*[\+\-]*$esc_color$/x) {
5942 $stat = 1;
5943 push @{$c->{stat}}, $_;
5944 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
5945 push @{$c->{stat}}, $_;
5946 $stat = undef;
5947 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
5948 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
5949 } elsif (s/^${esc_color} //o) {
5950 push @{$c->{l}}, $_;
5951 }
5952 }
5953 if ($c && defined $c->{r} && $c->{r} != $r_last) {
5954 $r_last = $c->{r};
5955 process_commit($c, $r_min, $r_max, \@k);
5956 }
5957 if (@k) {
5958 ($r_min, $r_max) = ($r_max, $r_min);
5959 process_commit($_, $r_min, $r_max) foreach reverse @k;
5960 }
5961out:
5962 close $log;
5963 print commit_log_separator unless $incremental || $oneline;
5964}
5965
5966sub cmd_blame {
5967 my $path = pop;
5968
5969 config_pager();
5970 run_pager();
5971
5972 my ($fh, $ctx, $rev);
5973
5974 if ($_git_format) {
5975 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
5976 while (my $line = <$fh>) {
5977 if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
5978 # Uncommitted edits show up as a rev ID of
5979 # all zeros, which we can't look up with
5980 # cmt_metadata
5981 if ($1 !~ /^0+$/) {
5982 (undef, $rev, undef) =
5983 ::cmt_metadata($1);
5984 $rev = '0' if (!$rev);
5985 } else {
5986 $rev = '0';
5987 }
5988 $rev = sprintf('%-10s', $rev);
5989 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
5990 }
5991 print $line;
5992 }
5993 } else {
5994 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
5995 '--', $path);
5996 my ($sha1);
5997 my %authors;
5998 my @buffer;
5999 my %dsha; #distinct sha keys
6000
6001 while (my $line = <$fh>) {
6002 push @buffer, $line;
6003 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
6004 $dsha{$1} = 1;
6005 }
6006 }
6007
6008 my $s2r = ::cmt_sha2rev_batch([keys %dsha]);
6009
6010 foreach my $line (@buffer) {
6011 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
6012 $rev = $s2r->{$1};
6013 $rev = '0' if (!$rev)
6014 }
6015 elsif ($line =~ /^author (.*)/) {
6016 $authors{$rev} = $1;
6017 $authors{$rev} =~ s/\s/_/g;
6018 }
6019 elsif ($line =~ /^\t(.*)$/) {
6020 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
6021 }
6022 }
6023 }
6024 command_close_pipe($fh, $ctx);
6025}
6026
6027package Git::SVN::Migration;
6028# these version numbers do NOT correspond to actual version numbers
6029# of git nor git-svn. They are just relative.
6030#
6031# v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
6032#
6033# v1 layout: .git/$id/info/url, refs/remotes/$id
6034#
6035# v2 layout: .git/svn/$id/info/url, refs/remotes/$id
6036#
6037# v3 layout: .git/svn/$id, refs/remotes/$id
6038# - info/url may remain for backwards compatibility
6039# - this is what we migrate up to this layout automatically,
6040# - this will be used by git svn init on single branches
6041# v3.1 layout (auto migrated):
6042# - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
6043# for backwards compatibility
6044#
6045# v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
6046# - this is only created for newly multi-init-ed
6047# repositories. Similar in spirit to the
6048# --use-separate-remotes option in git-clone (now default)
6049# - we do not automatically migrate to this (following
6050# the example set by core git)
6051#
6052# v5 layout: .rev_db.$UUID => .rev_map.$UUID
6053# - newer, more-efficient format that uses 24-bytes per record
6054# with no filler space.
6055# - use xxd -c24 < .rev_map.$UUID to view and debug
6056# - This is a one-way migration, repositories updated to the
6057# new format will not be able to use old git-svn without
6058# rebuilding the .rev_db. Rebuilding the rev_db is not
6059# possible if noMetadata or useSvmProps are set; but should
6060# be no problem for users that use the (sensible) defaults.
6061use strict;
6062use warnings;
6063use Carp qw/croak/;
6064use File::Path qw/mkpath/;
6065use File::Basename qw/dirname basename/;
6066use vars qw/$_minimize/;
6067
6068sub migrate_from_v0 {
6069 my $git_dir = $ENV{GIT_DIR};
6070 return undef unless -d $git_dir;
6071 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
6072 my $migrated = 0;
6073 while (<$fh>) {
6074 chomp;
6075 my ($id, $orig_ref) = ($_, $_);
6076 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
6077 next unless -f "$git_dir/$id/info/url";
6078 my $new_ref = "refs/remotes/$id";
6079 if (::verify_ref("$new_ref^0")) {
6080 print STDERR "W: $orig_ref is probably an old ",
6081 "branch used by an ancient version of ",
6082 "git-svn.\n",
6083 "However, $new_ref also exists.\n",
6084 "We will not be able ",
6085 "to use this branch until this ",
6086 "ambiguity is resolved.\n";
6087 next;
6088 }
6089 print STDERR "Migrating from v0 layout...\n" if !$migrated;
6090 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
6091 command_noisy('update-ref', $new_ref, $orig_ref);
6092 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
6093 $migrated++;
6094 }
6095 command_close_pipe($fh, $ctx);
6096 print STDERR "Done migrating from v0 layout...\n" if $migrated;
6097 $migrated;
6098}
6099
6100sub migrate_from_v1 {
6101 my $git_dir = $ENV{GIT_DIR};
6102 my $migrated = 0;
6103 return $migrated unless -d $git_dir;
6104 my $svn_dir = "$git_dir/svn";
6105
6106 # just in case somebody used 'svn' as their $id at some point...
6107 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
6108
6109 print STDERR "Migrating from a git-svn v1 layout...\n";
6110 mkpath([$svn_dir]);
6111 print STDERR "Data from a previous version of git-svn exists, but\n\t",
6112 "$svn_dir\n\t(required for this version ",
6113 "($::VERSION) of git-svn) does not exist.\n";
6114 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
6115 while (<$fh>) {
6116 my $x = $_;
6117 next unless $x =~ s#^refs/remotes/##;
6118 chomp $x;
6119 next unless -f "$git_dir/$x/info/url";
6120 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
6121 next unless $u;
6122 my $dn = dirname("$git_dir/svn/$x");
6123 mkpath([$dn]) unless -d $dn;
6124 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
6125 mkpath(["$git_dir/svn/svn"]);
6126 print STDERR " - $git_dir/$x/info => ",
6127 "$git_dir/svn/$x/info\n";
6128 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
6129 croak "$!: $x";
6130 # don't worry too much about these, they probably
6131 # don't exist with repos this old (save for index,
6132 # and we can easily regenerate that)
6133 foreach my $f (qw/unhandled.log index .rev_db/) {
6134 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
6135 }
6136 } else {
6137 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
6138 rename "$git_dir/$x", "$git_dir/svn/$x" or
6139 croak "$!: $x";
6140 }
6141 $migrated++;
6142 }
6143 command_close_pipe($fh, $ctx);
6144 print STDERR "Done migrating from a git-svn v1 layout\n";
6145 $migrated;
6146}
6147
6148sub read_old_urls {
6149 my ($l_map, $pfx, $path) = @_;
6150 my @dir;
6151 foreach (<$path/*>) {
6152 if (-r "$_/info/url") {
6153 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
6154 my $ref_id = $pfx . basename $_;
6155 my $url = ::file_to_s("$_/info/url");
6156 $l_map->{$ref_id} = $url;
6157 } elsif (-d $_) {
6158 push @dir, $_;
6159 }
6160 }
6161 foreach (@dir) {
6162 my $x = $_;
6163 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
6164 read_old_urls($l_map, $x, $_);
6165 }
6166}
6167
6168sub migrate_from_v2 {
6169 my @cfg = command(qw/config -l/);
6170 return if grep /^svn-remote\..+\.url=/, @cfg;
6171 my %l_map;
6172 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
6173 my $migrated = 0;
6174
6175 foreach my $ref_id (sort keys %l_map) {
6176 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
6177 if ($@) {
6178 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
6179 }
6180 $migrated++;
6181 }
6182 $migrated;
6183}
6184
6185sub minimize_connections {
6186 my $r = Git::SVN::read_all_remotes();
6187 my $new_urls = {};
6188 my $root_repos = {};
6189 foreach my $repo_id (keys %$r) {
6190 my $url = $r->{$repo_id}->{url} or next;
6191 my $fetch = $r->{$repo_id}->{fetch} or next;
6192 my $ra = Git::SVN::Ra->new($url);
6193
6194 # skip existing cases where we already connect to the root
6195 if (($ra->{url} eq $ra->{repos_root}) ||
6196 ($ra->{repos_root} eq $repo_id)) {
6197 $root_repos->{$ra->{url}} = $repo_id;
6198 next;
6199 }
6200
6201 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
6202 my $root_path = $ra->{url};
6203 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
6204 foreach my $path (keys %$fetch) {
6205 my $ref_id = $fetch->{$path};
6206 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
6207
6208 # make sure we can read when connecting to
6209 # a higher level of a repository
6210 my ($last_rev, undef) = $gs->last_rev_commit;
6211 if (!defined $last_rev) {
6212 $last_rev = eval {
6213 $root_ra->get_latest_revnum;
6214 };
6215 next if $@;
6216 }
6217 my $new = $root_path;
6218 $new .= length $path ? "/$path" : '';
6219 eval {
6220 $root_ra->get_log([$new], $last_rev, $last_rev,
6221 0, 0, 1, sub { });
6222 };
6223 next if $@;
6224 $new_urls->{$ra->{repos_root}}->{$new} =
6225 { ref_id => $ref_id,
6226 old_repo_id => $repo_id,
6227 old_path => $path };
6228 }
6229 }
6230
6231 my @emptied;
6232 foreach my $url (keys %$new_urls) {
6233 # see if we can re-use an existing [svn-remote "repo_id"]
6234 # instead of creating a(n ugly) new section:
6235 my $repo_id = $root_repos->{$url} || $url;
6236
6237 my $fetch = $new_urls->{$url};
6238 foreach my $path (keys %$fetch) {
6239 my $x = $fetch->{$path};
6240 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
6241 my $pfx = "svn-remote.$x->{old_repo_id}";
6242
6243 my $old_fetch = quotemeta("$x->{old_path}:".
6244 "$x->{ref_id}");
6245 command_noisy(qw/config --unset/,
6246 "$pfx.fetch", '^'. $old_fetch . '$');
6247 delete $r->{$x->{old_repo_id}}->
6248 {fetch}->{$x->{old_path}};
6249 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
6250 command_noisy(qw/config --unset/,
6251 "$pfx.url");
6252 push @emptied, $x->{old_repo_id}
6253 }
6254 }
6255 }
6256 if (@emptied) {
6257 my $file = $ENV{GIT_CONFIG} || "$ENV{GIT_DIR}/config";
6258 print STDERR <<EOF;
6259The following [svn-remote] sections in your config file ($file) are empty
6260and can be safely removed:
6261EOF
6262 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
6263 }
6264}
6265
6266sub migration_check {
6267 migrate_from_v0();
6268 migrate_from_v1();
6269 migrate_from_v2();
6270 minimize_connections() if $_minimize;
6271}
6272
6273package Git::IndexInfo;
6274use strict;
6275use warnings;
6276use Git qw/command_input_pipe command_close_pipe/;
6277
6278sub new {
6279 my ($class) = @_;
6280 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
6281 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
6282}
6283
6284sub remove {
6285 my ($self, $path) = @_;
6286 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
6287 return ++$self->{nr};
6288 }
6289 undef;
6290}
6291
6292sub update {
6293 my ($self, $mode, $hash, $path) = @_;
6294 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
6295 return ++$self->{nr};
6296 }
6297 undef;
6298}
6299
6300sub DESTROY {
6301 my ($self) = @_;
6302 command_close_pipe($self->{gui}, $self->{ctx});
6303}
6304
6305package Git::SVN::GlobSpec;
6306use strict;
6307use warnings;
6308
6309sub new {
6310 my ($class, $glob, $pattern_ok) = @_;
6311 my $re = $glob;
6312 $re =~ s!/+$!!g; # no need for trailing slashes
6313 my (@left, @right, @patterns);
6314 my $state = "left";
6315 my $die_msg = "Only one set of wildcard directories " .
6316 "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
6317 for my $part (split(m|/|, $glob)) {
6318 if ($part =~ /\*/ && $part ne "*") {
6319 die "Invalid pattern in '$glob': $part\n";
6320 } elsif ($pattern_ok && $part =~ /[{}]/ &&
6321 $part !~ /^\{[^{}]+\}/) {
6322 die "Invalid pattern in '$glob': $part\n";
6323 }
6324 if ($part eq "*") {
6325 die $die_msg if $state eq "right";
6326 $state = "pattern";
6327 push(@patterns, "[^/]*");
6328 } elsif ($pattern_ok && $part =~ /^\{(.*)\}$/) {
6329 die $die_msg if $state eq "right";
6330 $state = "pattern";
6331 my $p = quotemeta($1);
6332 $p =~ s/\\,/|/g;
6333 push(@patterns, "(?:$p)");
6334 } else {
6335 if ($state eq "left") {
6336 push(@left, $part);
6337 } else {
6338 push(@right, $part);
6339 $state = "right";
6340 }
6341 }
6342 }
6343 my $depth = @patterns;
6344 if ($depth == 0) {
6345 die "One '*' is needed in glob: '$glob'\n";
6346 }
6347 my $left = join('/', @left);
6348 my $right = join('/', @right);
6349 $re = join('/', @patterns);
6350 $re = join('\/',
6351 grep(length, quotemeta($left), "($re)", quotemeta($right)));
6352 my $left_re = qr/^\/\Q$left\E(\/|$)/;
6353 bless { left => $left, right => $right, left_regex => $left_re,
6354 regex => qr/$re/, glob => $glob, depth => $depth }, $class;
6355}
6356
6357sub full_path {
6358 my ($self, $path) = @_;
6359 return (length $self->{left} ? "$self->{left}/" : '') .
6360 $path . (length $self->{right} ? "/$self->{right}" : '');
6361}
6362
6363__END__
6364
6365Data structures:
6366
6367
6368$remotes = { # returned by read_all_remotes()
6369 'svn' => {
6370 # svn-remote.svn.url=https://svn.musicpd.org
6371 url => 'https://svn.musicpd.org',
6372 # svn-remote.svn.fetch=mpd/trunk:trunk
6373 fetch => {
6374 'mpd/trunk' => 'trunk',
6375 },
6376 # svn-remote.svn.tags=mpd/tags/*:tags/*
6377 tags => {
6378 path => {
6379 left => 'mpd/tags',
6380 right => '',
6381 regex => qr!mpd/tags/([^/]+)$!,
6382 glob => 'tags/*',
6383 },
6384 ref => {
6385 left => 'tags',
6386 right => '',
6387 regex => qr!tags/([^/]+)$!,
6388 glob => 'tags/*',
6389 },
6390 }
6391 }
6392};
6393
6394$log_entry hashref as returned by libsvn_log_entry()
6395{
6396 log => 'whitespace-formatted log entry
6397', # trailing newline is preserved
6398 revision => '8', # integer
6399 date => '2004-02-24T17:01:44.108345Z', # commit date
6400 author => 'committer name'
6401};
6402
6403
6404# this is generated by generate_diff();
6405@mods = array of diff-index line hashes, each element represents one line
6406 of diff-index output
6407
6408diff-index line ($m hash)
6409{
6410 mode_a => first column of diff-index output, no leading ':',
6411 mode_b => second column of diff-index output,
6412 sha1_b => sha1sum of the final blob,
6413 chg => change type [MCRADT],
6414 file_a => original file name of a file (iff chg is 'C' or 'R')
6415 file_b => new/current file name of a file (any chg)
6416}
6417;
6418
6419# retval of read_url_paths{,_all}();
6420$l_map = {
6421 # repository root url
6422 'https://svn.musicpd.org' => {
6423 # repository path # GIT_SVN_ID
6424 'mpd/trunk' => 'trunk',
6425 'mpd/tags/0.11.5' => 'tags/0.11.5',
6426 },
6427}
6428
6429Notes:
6430 I don't trust the each() function on unless I created %hash myself
6431 because the internal iterator may not have started at base.