PageRenderTime 56ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/git-svn.perl

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