PageRenderTime 82ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 2ms

/bin/git-folder/git-svn.perl

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