PageRenderTime 68ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/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

Large files files are truncated, but you can click here to view the full file

  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: $fi…

Large files files are truncated, but you can click here to view the full file