THIS IS A TEST INSTANCE ONLY! REPOSITORIES CAN BE DELETED AT ANY TIME!

Git Source Code Mirror - This is a publish-only repository and all pull requests are ignored. Please follow Documentation/SubmittingPatches procedure for any of your improvements.
git
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2242 lines
63KB

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