PageRenderTime 92ms CodeModel.GetById 41ms RepoModel.GetById 1ms app.codeStats 1ms

/git-svn.perl

https://bitbucket.org/evzijst/git
Perl | 6288 lines | 5587 code | 417 blank | 284 comment | 789 complexity | f11e5e65e8f23a0fedb5c48fccfa2674 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. $_q ||= 0;
  85. my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
  86. 'config-dir=s' => \$Git::SVN::Ra::config_dir,
  87. 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
  88. 'ignore-paths=s' => \$SVN::Git::Fetcher::_ignore_regex );
  89. my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
  90. 'authors-file|A=s' => \$_authors,
  91. 'authors-prog=s' => \$_authors_prog,
  92. 'repack:i' => \$Git::SVN::_repack,
  93. 'noMetadata' => \$Git::SVN::_no_metadata,
  94. 'useSvmProps' => \$Git::SVN::_use_svm_props,
  95. 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
  96. 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
  97. 'no-checkout' => \$_no_checkout,
  98. 'quiet|q+' => \$_q,
  99. 'repack-flags|repack-args|repack-opts=s' =>
  100. \$Git::SVN::_repack_flags,
  101. 'use-log-author' => \$Git::SVN::_use_log_author,
  102. 'add-author-from' => \$Git::SVN::_add_author_from,
  103. 'localtime' => \$Git::SVN::_localtime,
  104. %remote_opts );
  105. my ($_trunk, @_tags, @_branches, $_stdlayout);
  106. my %icv;
  107. my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
  108. 'trunk|T=s' => \$_trunk, 'tags|t=s@' => \@_tags,
  109. 'branches|b=s@' => \@_branches, 'prefix=s' => \$_prefix,
  110. 'stdlayout|s' => \$_stdlayout,
  111. 'minimize-url|m!' => \$Git::SVN::_minimize_url,
  112. 'no-metadata' => sub { $icv{noMetadata} = 1 },
  113. 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
  114. 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
  115. 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
  116. 'rewrite-uuid=s' => sub { $icv{rewriteUUID} = $_[1] },
  117. %remote_opts );
  118. my %cmt_opts = ( 'edit|e' => \$_edit,
  119. 'rmdir' => \$SVN::Git::Editor::_rmdir,
  120. 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
  121. 'l=i' => \$SVN::Git::Editor::_rename_limit,
  122. 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
  123. );
  124. my %cmd = (
  125. fetch => [ \&cmd_fetch, "Download new revisions from SVN",
  126. { 'revision|r=s' => \$_revision,
  127. 'fetch-all|all' => \$_fetch_all,
  128. 'parent|p' => \$_fetch_parent,
  129. %fc_opts } ],
  130. clone => [ \&cmd_clone, "Initialize and fetch revisions",
  131. { 'revision|r=s' => \$_revision,
  132. %fc_opts, %init_opts } ],
  133. init => [ \&cmd_init, "Initialize a repo for tracking" .
  134. " (requires URL argument)",
  135. \%init_opts ],
  136. 'multi-init' => [ \&cmd_multi_init,
  137. "Deprecated alias for ".
  138. "'$0 init -T<trunk> -b<branches> -t<tags>'",
  139. \%init_opts ],
  140. dcommit => [ \&cmd_dcommit,
  141. 'Commit several diffs to merge with upstream',
  142. { 'merge|m|M' => \$_merge,
  143. 'strategy|s=s' => \$_strategy,
  144. 'verbose|v' => \$_verbose,
  145. 'dry-run|n' => \$_dry_run,
  146. 'fetch-all|all' => \$_fetch_all,
  147. 'commit-url=s' => \$_commit_url,
  148. 'revision|r=i' => \$_revision,
  149. 'no-rebase' => \$_no_rebase,
  150. 'mergeinfo=s' => \$_merge_info,
  151. %cmt_opts, %fc_opts } ],
  152. branch => [ \&cmd_branch,
  153. 'Create a branch in the SVN repository',
  154. { 'message|m=s' => \$_message,
  155. 'destination|d=s' => \$_branch_dest,
  156. 'dry-run|n' => \$_dry_run,
  157. 'tag|t' => \$_tag,
  158. 'username=s' => \$Git::SVN::Prompt::_username,
  159. 'commit-url=s' => \$_commit_url } ],
  160. tag => [ sub { $_tag = 1; cmd_branch(@_) },
  161. 'Create a tag in the SVN repository',
  162. { 'message|m=s' => \$_message,
  163. 'destination|d=s' => \$_branch_dest,
  164. 'dry-run|n' => \$_dry_run,
  165. 'username=s' => \$Git::SVN::Prompt::_username,
  166. 'commit-url=s' => \$_commit_url } ],
  167. 'set-tree' => [ \&cmd_set_tree,
  168. "Set an SVN repository to a git tree-ish",
  169. { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
  170. 'create-ignore' => [ \&cmd_create_ignore,
  171. 'Create a .gitignore per svn:ignore',
  172. { 'revision|r=i' => \$_revision
  173. } ],
  174. 'mkdirs' => [ \&cmd_mkdirs ,
  175. "recreate empty directories after a checkout",
  176. { 'revision|r=i' => \$_revision } ],
  177. 'propget' => [ \&cmd_propget,
  178. 'Print the value of a property on a file or directory',
  179. { 'revision|r=i' => \$_revision } ],
  180. 'proplist' => [ \&cmd_proplist,
  181. 'List all properties of a file or directory',
  182. { 'revision|r=i' => \$_revision } ],
  183. 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
  184. { 'revision|r=i' => \$_revision
  185. } ],
  186. 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
  187. { 'revision|r=i' => \$_revision
  188. } ],
  189. 'multi-fetch' => [ \&cmd_multi_fetch,
  190. "Deprecated alias for $0 fetch --all",
  191. { 'revision|r=s' => \$_revision, %fc_opts } ],
  192. 'migrate' => [ sub { },
  193. # no-op, we automatically run this anyways,
  194. 'Migrate configuration/metadata/layout from
  195. previous versions of git-svn',
  196. { 'minimize' => \$Git::SVN::Migration::_minimize,
  197. %remote_opts } ],
  198. 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
  199. { 'limit=i' => \$Git::SVN::Log::limit,
  200. 'revision|r=s' => \$_revision,
  201. 'verbose|v' => \$Git::SVN::Log::verbose,
  202. 'incremental' => \$Git::SVN::Log::incremental,
  203. 'oneline' => \$Git::SVN::Log::oneline,
  204. 'show-commit' => \$Git::SVN::Log::show_commit,
  205. 'non-recursive' => \$Git::SVN::Log::non_recursive,
  206. 'authors-file|A=s' => \$_authors,
  207. 'color' => \$Git::SVN::Log::color,
  208. 'pager=s' => \$Git::SVN::Log::pager
  209. } ],
  210. 'find-rev' => [ \&cmd_find_rev,
  211. "Translate between SVN revision numbers and tree-ish",
  212. {} ],
  213. 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
  214. { 'merge|m|M' => \$_merge,
  215. 'verbose|v' => \$_verbose,
  216. 'strategy|s=s' => \$_strategy,
  217. 'local|l' => \$_local,
  218. 'fetch-all|all' => \$_fetch_all,
  219. 'dry-run|n' => \$_dry_run,
  220. %fc_opts } ],
  221. 'commit-diff' => [ \&cmd_commit_diff,
  222. 'Commit a diff between two trees',
  223. { 'message|m=s' => \$_message,
  224. 'file|F=s' => \$_file,
  225. 'revision|r=s' => \$_revision,
  226. %cmt_opts } ],
  227. 'info' => [ \&cmd_info,
  228. "Show info about the latest SVN revision
  229. on the current branch",
  230. { 'url' => \$_url, } ],
  231. 'blame' => [ \&Git::SVN::Log::cmd_blame,
  232. "Show what revision and author last modified each line of a file",
  233. { 'git-format' => \$_git_format } ],
  234. 'reset' => [ \&cmd_reset,
  235. "Undo fetches back to the specified SVN revision",
  236. { 'revision|r=s' => \$_revision,
  237. 'parent|p' => \$_fetch_parent } ],
  238. 'gc' => [ \&cmd_gc,
  239. "Compress unhandled.log files in .git/svn and remove " .
  240. "index files in .git/svn",
  241. {} ],
  242. );
  243. my $cmd;
  244. for (my $i = 0; $i < @ARGV; $i++) {
  245. if (defined $cmd{$ARGV[$i]}) {
  246. $cmd = $ARGV[$i];
  247. splice @ARGV, $i, 1;
  248. last;
  249. } elsif ($ARGV[$i] eq 'help') {
  250. $cmd = $ARGV[$i+1];
  251. usage(0);
  252. }
  253. };
  254. # make sure we're always running at the top-level working directory
  255. unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
  256. unless (-d $ENV{GIT_DIR}) {
  257. if ($git_dir_user_set) {
  258. die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
  259. "but it is not a directory\n";
  260. }
  261. my $git_dir = delete $ENV{GIT_DIR};
  262. my $cdup = undef;
  263. git_cmd_try {
  264. $cdup = command_oneline(qw/rev-parse --show-cdup/);
  265. $git_dir = '.' unless ($cdup);
  266. chomp $cdup if ($cdup);
  267. $cdup = "." unless ($cdup && length $cdup);
  268. } "Already at toplevel, but $git_dir not found\n";
  269. chdir $cdup or die "Unable to chdir up to '$cdup'\n";
  270. unless (-d $git_dir) {
  271. die "$git_dir still not found after going to ",
  272. "'$cdup'\n";
  273. }
  274. $ENV{GIT_DIR} = $git_dir;
  275. }
  276. $_repository = Git->repository(Repository => $ENV{GIT_DIR});
  277. }
  278. my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
  279. read_git_config(\%opts);
  280. if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
  281. Getopt::Long::Configure('pass_through');
  282. }
  283. my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
  284. 'minimize-connections' => \$Git::SVN::Migration::_minimize,
  285. 'id|i=s' => \$Git::SVN::default_ref_id,
  286. 'svn-remote|remote|R=s' => sub {
  287. $Git::SVN::no_reuse_existing = 1;
  288. $Git::SVN::default_repo_id = $_[1] });
  289. exit 1 if (!$rv && $cmd && $cmd ne 'log');
  290. usage(0) if $_help;
  291. version() if $_version;
  292. usage(1) unless defined $cmd;
  293. load_authors() if $_authors;
  294. if (defined $_authors_prog) {
  295. $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
  296. }
  297. unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
  298. Git::SVN::Migration::migration_check();
  299. }
  300. Git::SVN::init_vars();
  301. eval {
  302. Git::SVN::verify_remotes_sanity();
  303. $cmd{$cmd}->[0]->(@ARGV);
  304. };
  305. fatal $@ if $@;
  306. post_fetch_checkout();
  307. exit 0;
  308. ####################### primary functions ######################
  309. sub usage {
  310. my $exit = shift || 0;
  311. my $fd = $exit ? \*STDERR : \*STDOUT;
  312. print $fd <<"";
  313. git-svn - bidirectional operations between a single Subversion tree and git
  314. Usage: git svn <command> [options] [arguments]\n
  315. print $fd "Available commands:\n" unless $cmd;
  316. foreach (sort keys %cmd) {
  317. next if $cmd && $cmd ne $_;
  318. next if /^multi-/; # don't show deprecated commands
  319. print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
  320. foreach (sort keys %{$cmd{$_}->[2]}) {
  321. # mixed-case options are for .git/config only
  322. next if /[A-Z]/ && /^[a-z]+$/i;
  323. # prints out arguments as they should be passed:
  324. my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
  325. print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
  326. "--$_" : "-$_" }
  327. split /\|/,$_)," $x\n";
  328. }
  329. }
  330. print $fd <<"";
  331. \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
  332. arbitrary identifier if you're tracking multiple SVN branches/repositories in
  333. one git repository and want to keep them separate. See git-svn(1) for more
  334. information.
  335. exit $exit;
  336. }
  337. sub version {
  338. ::_req_svn();
  339. print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
  340. exit 0;
  341. }
  342. sub do_git_init_db {
  343. unless (-d $ENV{GIT_DIR}) {
  344. my @init_db = ('init');
  345. push @init_db, "--template=$_template" if defined $_template;
  346. if (defined $_shared) {
  347. if ($_shared =~ /[a-z]/) {
  348. push @init_db, "--shared=$_shared";
  349. } else {
  350. push @init_db, "--shared";
  351. }
  352. }
  353. command_noisy(@init_db);
  354. $_repository = Git->repository(Repository => ".git");
  355. }
  356. my $set;
  357. my $pfx = "svn-remote.$Git::SVN::default_repo_id";
  358. foreach my $i (keys %icv) {
  359. die "'$set' and '$i' cannot both be set\n" if $set;
  360. next unless defined $icv{$i};
  361. command_noisy('config', "$pfx.$i", $icv{$i});
  362. $set = $i;
  363. }
  364. my $ignore_regex = \$SVN::Git::Fetcher::_ignore_regex;
  365. command_noisy('config', "$pfx.ignore-paths", $$ignore_regex)
  366. if defined $$ignore_regex;
  367. }
  368. sub init_subdir {
  369. my $repo_path = shift or return;
  370. mkpath([$repo_path]) unless -d $repo_path;
  371. chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
  372. $ENV{GIT_DIR} = '.git';
  373. $_repository = Git->repository(Repository => $ENV{GIT_DIR});
  374. }
  375. sub cmd_clone {
  376. my ($url, $path) = @_;
  377. if (!defined $path &&
  378. (defined $_trunk || @_branches || @_tags ||
  379. defined $_stdlayout) &&
  380. $url !~ m#^[a-z\+]+://#) {
  381. $path = $url;
  382. }
  383. $path = basename($url) if !defined $path || !length $path;
  384. my $authors_absolute = $_authors ? File::Spec->rel2abs($_authors) : "";
  385. cmd_init($url, $path);
  386. command_oneline('config', 'svn.authorsfile', $authors_absolute)
  387. if $_authors;
  388. Git::SVN::fetch_all($Git::SVN::default_repo_id);
  389. }
  390. sub cmd_init {
  391. if (defined $_stdlayout) {
  392. $_trunk = 'trunk' if (!defined $_trunk);
  393. @_tags = 'tags' if (! @_tags);
  394. @_branches = 'branches' if (! @_branches);
  395. }
  396. if (defined $_trunk || @_branches || @_tags) {
  397. return cmd_multi_init(@_);
  398. }
  399. my $url = shift or die "SVN repository location required ",
  400. "as a command-line argument\n";
  401. $url = canonicalize_url($url);
  402. init_subdir(@_);
  403. do_git_init_db();
  404. if ($Git::SVN::_minimize_url eq 'unset') {
  405. $Git::SVN::_minimize_url = 0;
  406. }
  407. Git::SVN->init($url);
  408. }
  409. sub cmd_fetch {
  410. if (grep /^\d+=./, @_) {
  411. die "'<rev>=<commit>' fetch arguments are ",
  412. "no longer supported.\n";
  413. }
  414. my ($remote) = @_;
  415. if (@_ > 1) {
  416. die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
  417. }
  418. $Git::SVN::no_reuse_existing = undef;
  419. if ($_fetch_parent) {
  420. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  421. unless ($gs) {
  422. die "Unable to determine upstream SVN information from ",
  423. "working tree history\n";
  424. }
  425. # just fetch, don't checkout.
  426. $_no_checkout = 'true';
  427. $_fetch_all ? $gs->fetch_all : $gs->fetch;
  428. } elsif ($_fetch_all) {
  429. cmd_multi_fetch();
  430. } else {
  431. $remote ||= $Git::SVN::default_repo_id;
  432. Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
  433. }
  434. }
  435. sub cmd_set_tree {
  436. my (@commits) = @_;
  437. if ($_stdin || !@commits) {
  438. print "Reading from stdin...\n";
  439. @commits = ();
  440. while (<STDIN>) {
  441. if (/\b($sha1_short)\b/o) {
  442. unshift @commits, $1;
  443. }
  444. }
  445. }
  446. my @revs;
  447. foreach my $c (@commits) {
  448. my @tmp = command('rev-parse',$c);
  449. if (scalar @tmp == 1) {
  450. push @revs, $tmp[0];
  451. } elsif (scalar @tmp > 1) {
  452. push @revs, reverse(command('rev-list',@tmp));
  453. } else {
  454. fatal "Failed to rev-parse $c";
  455. }
  456. }
  457. my $gs = Git::SVN->new;
  458. my ($r_last, $cmt_last) = $gs->last_rev_commit;
  459. $gs->fetch;
  460. if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
  461. fatal "There are new revisions that were fetched ",
  462. "and need to be merged (or acknowledged) ",
  463. "before committing.\nlast rev: $r_last\n",
  464. " current: $gs->{last_rev}";
  465. }
  466. $gs->set_tree($_) foreach @revs;
  467. print "Done committing ",scalar @revs," revisions to SVN\n";
  468. unlink $gs->{index};
  469. }
  470. sub cmd_dcommit {
  471. my $head = shift;
  472. command_noisy(qw/update-index --refresh/);
  473. git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
  474. 'Cannot dcommit with a dirty index. Commit your changes first, '
  475. . "or stash them with `git stash'.\n";
  476. $head ||= 'HEAD';
  477. my $old_head;
  478. if ($head ne 'HEAD') {
  479. $old_head = eval {
  480. command_oneline([qw/symbolic-ref -q HEAD/])
  481. };
  482. if ($old_head) {
  483. $old_head =~ s{^refs/heads/}{};
  484. } else {
  485. $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
  486. }
  487. command(['checkout', $head], STDERR => 0);
  488. }
  489. my @refs;
  490. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
  491. unless ($gs) {
  492. die "Unable to determine upstream SVN information from ",
  493. "$head history.\nPerhaps the repository is empty.";
  494. }
  495. if (defined $_commit_url) {
  496. $url = $_commit_url;
  497. } else {
  498. $url = eval { command_oneline('config', '--get',
  499. "svn-remote.$gs->{repo_id}.commiturl") };
  500. if (!$url) {
  501. $url = $gs->full_pushurl
  502. }
  503. }
  504. my $last_rev = $_revision if defined $_revision;
  505. if ($url) {
  506. print "Committing to $url ...\n";
  507. }
  508. my ($linear_refs, $parents) = linearize_history($gs, \@refs);
  509. if ($_no_rebase && scalar(@$linear_refs) > 1) {
  510. warn "Attempting to commit more than one change while ",
  511. "--no-rebase is enabled.\n",
  512. "If these changes depend on each other, re-running ",
  513. "without --no-rebase may be required."
  514. }
  515. my $expect_url = $url;
  516. Git::SVN::remove_username($expect_url);
  517. while (1) {
  518. my $d = shift @$linear_refs or last;
  519. unless (defined $last_rev) {
  520. (undef, $last_rev, undef) = cmt_metadata("$d~1");
  521. unless (defined $last_rev) {
  522. fatal "Unable to extract revision information ",
  523. "from commit $d~1";
  524. }
  525. }
  526. if ($_dry_run) {
  527. print "diff-tree $d~1 $d\n";
  528. } else {
  529. my $cmt_rev;
  530. my %ed_opts = ( r => $last_rev,
  531. log => get_commit_entry($d)->{log},
  532. ra => Git::SVN::Ra->new($url),
  533. config => SVN::Core::config_get_config(
  534. $Git::SVN::Ra::config_dir
  535. ),
  536. tree_a => "$d~1",
  537. tree_b => $d,
  538. editor_cb => sub {
  539. print "Committed r$_[0]\n";
  540. $cmt_rev = $_[0];
  541. },
  542. mergeinfo => $_merge_info,
  543. svn_path => '');
  544. if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
  545. print "No changes\n$d~1 == $d\n";
  546. } elsif ($parents->{$d} && @{$parents->{$d}}) {
  547. $gs->{inject_parents_dcommit}->{$cmt_rev} =
  548. $parents->{$d};
  549. }
  550. $_fetch_all ? $gs->fetch_all : $gs->fetch;
  551. $last_rev = $cmt_rev;
  552. next if $_no_rebase;
  553. # we always want to rebase against the current HEAD,
  554. # not any head that was passed to us
  555. my @diff = command('diff-tree', $d,
  556. $gs->refname, '--');
  557. my @finish;
  558. if (@diff) {
  559. @finish = rebase_cmd();
  560. print STDERR "W: $d and ", $gs->refname,
  561. " differ, using @finish:\n",
  562. join("\n", @diff), "\n";
  563. } else {
  564. print "No changes between current HEAD and ",
  565. $gs->refname,
  566. "\nResetting to the latest ",
  567. $gs->refname, "\n";
  568. @finish = qw/reset --mixed/;
  569. }
  570. command_noisy(@finish, $gs->refname);
  571. if (@diff) {
  572. @refs = ();
  573. my ($url_, $rev_, $uuid_, $gs_) =
  574. working_head_info('HEAD', \@refs);
  575. my ($linear_refs_, $parents_) =
  576. linearize_history($gs_, \@refs);
  577. if (scalar(@$linear_refs) !=
  578. scalar(@$linear_refs_)) {
  579. fatal "# of revisions changed ",
  580. "\nbefore:\n",
  581. join("\n", @$linear_refs),
  582. "\n\nafter:\n",
  583. join("\n", @$linear_refs_), "\n",
  584. 'If you are attempting to commit ',
  585. "merges, try running:\n\t",
  586. 'git rebase --interactive',
  587. '--preserve-merges ',
  588. $gs->refname,
  589. "\nBefore dcommitting";
  590. }
  591. if ($url_ ne $expect_url) {
  592. if ($url_ eq $gs->metadata_url) {
  593. print
  594. "Accepting rewritten URL:",
  595. " $url_\n";
  596. } else {
  597. fatal
  598. "URL mismatch after rebase:",
  599. " $url_ != $expect_url";
  600. }
  601. }
  602. if ($uuid_ ne $uuid) {
  603. fatal "uuid mismatch after rebase: ",
  604. "$uuid_ != $uuid";
  605. }
  606. # remap parents
  607. my (%p, @l, $i);
  608. for ($i = 0; $i < scalar @$linear_refs; $i++) {
  609. my $new = $linear_refs_->[$i] or next;
  610. $p{$new} =
  611. $parents->{$linear_refs->[$i]};
  612. push @l, $new;
  613. }
  614. $parents = \%p;
  615. $linear_refs = \@l;
  616. }
  617. }
  618. }
  619. if ($old_head) {
  620. my $new_head = command_oneline(qw/rev-parse HEAD/);
  621. my $new_is_symbolic = eval {
  622. command_oneline(qw/symbolic-ref -q HEAD/);
  623. };
  624. if ($new_is_symbolic) {
  625. print "dcommitted the branch ", $head, "\n";
  626. } else {
  627. print "dcommitted on a detached HEAD because you gave ",
  628. "a revision argument.\n",
  629. "The rewritten commit is: ", $new_head, "\n";
  630. }
  631. command(['checkout', $old_head], STDERR => 0);
  632. }
  633. unlink $gs->{index};
  634. }
  635. sub cmd_branch {
  636. my ($branch_name, $head) = @_;
  637. unless (defined $branch_name && length $branch_name) {
  638. die(($_tag ? "tag" : "branch") . " name required\n");
  639. }
  640. $head ||= 'HEAD';
  641. my (undef, $rev, undef, $gs) = working_head_info($head);
  642. my $src = $gs->full_pushurl;
  643. my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
  644. my $allglobs = $remote->{ $_tag ? 'tags' : 'branches' };
  645. my $glob;
  646. if ($#{$allglobs} == 0) {
  647. $glob = $allglobs->[0];
  648. } else {
  649. unless(defined $_branch_dest) {
  650. die "Multiple ",
  651. $_tag ? "tag" : "branch",
  652. " paths defined for Subversion repository.\n",
  653. "You must specify where you want to create the ",
  654. $_tag ? "tag" : "branch",
  655. " with the --destination argument.\n";
  656. }
  657. foreach my $g (@{$allglobs}) {
  658. # SVN::Git::Editor could probably be moved to Git.pm..
  659. my $re = SVN::Git::Editor::glob2pat($g->{path}->{left});
  660. if ($_branch_dest =~ /$re/) {
  661. $glob = $g;
  662. last;
  663. }
  664. }
  665. unless (defined $glob) {
  666. my $dest_re = qr/\b\Q$_branch_dest\E\b/;
  667. foreach my $g (@{$allglobs}) {
  668. $g->{path}->{left} =~ /$dest_re/ or next;
  669. if (defined $glob) {
  670. die "Ambiguous destination: ",
  671. $_branch_dest, "\nmatches both '",
  672. $glob->{path}->{left}, "' and '",
  673. $g->{path}->{left}, "'\n";
  674. }
  675. $glob = $g;
  676. }
  677. unless (defined $glob) {
  678. die "Unknown ",
  679. $_tag ? "tag" : "branch",
  680. " destination $_branch_dest\n";
  681. }
  682. }
  683. }
  684. my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
  685. my $url;
  686. if (defined $_commit_url) {
  687. $url = $_commit_url;
  688. } else {
  689. $url = eval { command_oneline('config', '--get',
  690. "svn-remote.$gs->{repo_id}.commiturl") };
  691. if (!$url) {
  692. $url = $remote->{pushurl} || $remote->{url};
  693. }
  694. }
  695. my $dst = join '/', $url, $lft, $branch_name, ($rgt || ());
  696. if ($dst =~ /^https:/ && $src =~ /^http:/) {
  697. $src=~s/^http:/https:/;
  698. }
  699. ::_req_svn();
  700. my $ctx = SVN::Client->new(
  701. auth => Git::SVN::Ra::_auth_providers(),
  702. log_msg => sub {
  703. ${ $_[0] } = defined $_message
  704. ? $_message
  705. : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
  706. . $branch_name;
  707. },
  708. );
  709. eval {
  710. $ctx->ls($dst, 'HEAD', 0);
  711. } and die "branch ${branch_name} already exists\n";
  712. print "Copying ${src} at r${rev} to ${dst}...\n";
  713. $ctx->copy($src, $rev, $dst)
  714. unless $_dry_run;
  715. $gs->fetch_all;
  716. }
  717. sub cmd_find_rev {
  718. my $revision_or_hash = shift or die "SVN or git revision required ",
  719. "as a command-line argument\n";
  720. my $result;
  721. if ($revision_or_hash =~ /^r\d+$/) {
  722. my $head = shift;
  723. $head ||= 'HEAD';
  724. my @refs;
  725. my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
  726. unless ($gs) {
  727. die "Unable to determine upstream SVN information from ",
  728. "$head history\n";
  729. }
  730. my $desired_revision = substr($revision_or_hash, 1);
  731. $result = $gs->rev_map_get($desired_revision, $uuid);
  732. } else {
  733. my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
  734. $result = $rev;
  735. }
  736. print "$result\n" if $result;
  737. }
  738. sub auto_create_empty_directories {
  739. my ($gs) = @_;
  740. my $var = eval { command_oneline('config', '--get', '--bool',
  741. "svn-remote.$gs->{repo_id}.automkdirs") };
  742. # By default, create empty directories by consulting the unhandled log,
  743. # but allow setting it to 'false' to skip it.
  744. return !($var && $var eq 'false');
  745. }
  746. sub cmd_rebase {
  747. command_noisy(qw/update-index --refresh/);
  748. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  749. unless ($gs) {
  750. die "Unable to determine upstream SVN information from ",
  751. "working tree history\n";
  752. }
  753. if ($_dry_run) {
  754. print "Remote Branch: " . $gs->refname . "\n";
  755. print "SVN URL: " . $url . "\n";
  756. return;
  757. }
  758. if (command(qw/diff-index HEAD --/)) {
  759. print STDERR "Cannot rebase with uncommited changes:\n";
  760. command_noisy('status');
  761. exit 1;
  762. }
  763. unless ($_local) {
  764. # rebase will checkout for us, so no need to do it explicitly
  765. $_no_checkout = 'true';
  766. $_fetch_all ? $gs->fetch_all : $gs->fetch;
  767. }
  768. command_noisy(rebase_cmd(), $gs->refname);
  769. if (auto_create_empty_directories($gs)) {
  770. $gs->mkemptydirs;
  771. }
  772. }
  773. sub cmd_show_ignore {
  774. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  775. $gs ||= Git::SVN->new;
  776. my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
  777. $gs->prop_walk($gs->{path}, $r, sub {
  778. my ($gs, $path, $props) = @_;
  779. print STDOUT "\n# $path\n";
  780. my $s = $props->{'svn:ignore'} or return;
  781. $s =~ s/[\r\n]+/\n/g;
  782. $s =~ s/^\n+//;
  783. chomp $s;
  784. $s =~ s#^#$path#gm;
  785. print STDOUT "$s\n";
  786. });
  787. }
  788. sub cmd_show_externals {
  789. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  790. $gs ||= Git::SVN->new;
  791. my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
  792. $gs->prop_walk($gs->{path}, $r, sub {
  793. my ($gs, $path, $props) = @_;
  794. print STDOUT "\n# $path\n";
  795. my $s = $props->{'svn:externals'} or return;
  796. $s =~ s/[\r\n]+/\n/g;
  797. chomp $s;
  798. $s =~ s#^#$path#gm;
  799. print STDOUT "$s\n";
  800. });
  801. }
  802. sub cmd_create_ignore {
  803. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  804. $gs ||= Git::SVN->new;
  805. my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
  806. $gs->prop_walk($gs->{path}, $r, sub {
  807. my ($gs, $path, $props) = @_;
  808. # $path is of the form /path/to/dir/
  809. $path = '.' . $path;
  810. # SVN can have attributes on empty directories,
  811. # which git won't track
  812. mkpath([$path]) unless -d $path;
  813. my $ignore = $path . '.gitignore';
  814. my $s = $props->{'svn:ignore'} or return;
  815. open(GITIGNORE, '>', $ignore)
  816. or fatal("Failed to open `$ignore' for writing: $!");
  817. $s =~ s/[\r\n]+/\n/g;
  818. $s =~ s/^\n+//;
  819. chomp $s;
  820. # Prefix all patterns so that the ignore doesn't apply
  821. # to sub-directories.
  822. $s =~ s#^#/#gm;
  823. print GITIGNORE "$s\n";
  824. close(GITIGNORE)
  825. or fatal("Failed to close `$ignore': $!");
  826. command_noisy('add', '-f', $ignore);
  827. });
  828. }
  829. sub cmd_mkdirs {
  830. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  831. $gs ||= Git::SVN->new;
  832. $gs->mkemptydirs($_revision);
  833. }
  834. sub canonicalize_path {
  835. my ($path) = @_;
  836. my $dot_slash_added = 0;
  837. if (substr($path, 0, 1) ne "/") {
  838. $path = "./" . $path;
  839. $dot_slash_added = 1;
  840. }
  841. # File::Spec->canonpath doesn't collapse x/../y into y (for a
  842. # good reason), so let's do this manually.
  843. $path =~ s#/+#/#g;
  844. $path =~ s#/\.(?:/|$)#/#g;
  845. $path =~ s#/[^/]+/\.\.##g;
  846. $path =~ s#/$##g;
  847. $path =~ s#^\./## if $dot_slash_added;
  848. $path =~ s#^/##;
  849. $path =~ s#^\.$##;
  850. return $path;
  851. }
  852. sub canonicalize_url {
  853. my ($url) = @_;
  854. $url =~ s#^([^:]+://[^/]*/)(.*)$#$1 . canonicalize_path($2)#e;
  855. return $url;
  856. }
  857. # get_svnprops(PATH)
  858. # ------------------
  859. # Helper for cmd_propget and cmd_proplist below.
  860. sub get_svnprops {
  861. my $path = shift;
  862. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  863. $gs ||= Git::SVN->new;
  864. # prefix THE PATH by the sub-directory from which the user
  865. # invoked us.
  866. $path = $cmd_dir_prefix . $path;
  867. fatal("No such file or directory: $path") unless -e $path;
  868. my $is_dir = -d $path ? 1 : 0;
  869. $path = $gs->{path} . '/' . $path;
  870. # canonicalize the path (otherwise libsvn will abort or fail to
  871. # find the file)
  872. $path = canonicalize_path($path);
  873. my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
  874. my $props;
  875. if ($is_dir) {
  876. (undef, undef, $props) = $gs->ra->get_dir($path, $r);
  877. }
  878. else {
  879. (undef, $props) = $gs->ra->get_file($path, $r, undef);
  880. }
  881. return $props;
  882. }
  883. # cmd_propget (PROP, PATH)
  884. # ------------------------
  885. # Print the SVN property PROP for PATH.
  886. sub cmd_propget {
  887. my ($prop, $path) = @_;
  888. $path = '.' if not defined $path;
  889. usage(1) if not defined $prop;
  890. my $props = get_svnprops($path);
  891. if (not defined $props->{$prop}) {
  892. fatal("`$path' does not have a `$prop' SVN property.");
  893. }
  894. print $props->{$prop} . "\n";
  895. }
  896. # cmd_proplist (PATH)
  897. # -------------------
  898. # Print the list of SVN properties for PATH.
  899. sub cmd_proplist {
  900. my $path = shift;
  901. $path = '.' if not defined $path;
  902. my $props = get_svnprops($path);
  903. print "Properties on '$path':\n";
  904. foreach (sort keys %{$props}) {
  905. print " $_\n";
  906. }
  907. }
  908. sub cmd_multi_init {
  909. my $url = shift;
  910. unless (defined $_trunk || @_branches || @_tags) {
  911. usage(1);
  912. }
  913. $_prefix = '' unless defined $_prefix;
  914. if (defined $url) {
  915. $url = canonicalize_url($url);
  916. init_subdir(@_);
  917. }
  918. do_git_init_db();
  919. if (defined $_trunk) {
  920. $_trunk =~ s#^/+##;
  921. my $trunk_ref = 'refs/remotes/' . $_prefix . 'trunk';
  922. # try both old-style and new-style lookups:
  923. my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
  924. unless ($gs_trunk) {
  925. my ($trunk_url, $trunk_path) =
  926. complete_svn_url($url, $_trunk);
  927. $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
  928. undef, $trunk_ref);
  929. }
  930. }
  931. return unless @_branches || @_tags;
  932. my $ra = $url ? Git::SVN::Ra->new($url) : undef;
  933. foreach my $path (@_branches) {
  934. complete_url_ls_init($ra, $path, '--branches/-b', $_prefix);
  935. }
  936. foreach my $path (@_tags) {
  937. complete_url_ls_init($ra, $path, '--tags/-t', $_prefix.'tags/');
  938. }
  939. }
  940. sub cmd_multi_fetch {
  941. $Git::SVN::no_reuse_existing = undef;
  942. my $remotes = Git::SVN::read_all_remotes();
  943. foreach my $repo_id (sort keys %$remotes) {
  944. if ($remotes->{$repo_id}->{url}) {
  945. Git::SVN::fetch_all($repo_id, $remotes);
  946. }
  947. }
  948. }
  949. # this command is special because it requires no metadata
  950. sub cmd_commit_diff {
  951. my ($ta, $tb, $url) = @_;
  952. my $usage = "Usage: $0 commit-diff -r<revision> ".
  953. "<tree-ish> <tree-ish> [<URL>]";
  954. fatal($usage) if (!defined $ta || !defined $tb);
  955. my $svn_path = '';
  956. if (!defined $url) {
  957. my $gs = eval { Git::SVN->new };
  958. if (!$gs) {
  959. fatal("Needed URL or usable git-svn --id in ",
  960. "the command-line\n", $usage);
  961. }
  962. $url = $gs->{url};
  963. $svn_path = $gs->{path};
  964. }
  965. unless (defined $_revision) {
  966. fatal("-r|--revision is a required argument\n", $usage);
  967. }
  968. if (defined $_message && defined $_file) {
  969. fatal("Both --message/-m and --file/-F specified ",
  970. "for the commit message.\n",
  971. "I have no idea what you mean");
  972. }
  973. if (defined $_file) {
  974. $_message = file_to_s($_file);
  975. } else {
  976. $_message ||= get_commit_entry($tb)->{log};
  977. }
  978. my $ra ||= Git::SVN::Ra->new($url);
  979. my $r = $_revision;
  980. if ($r eq 'HEAD') {
  981. $r = $ra->get_latest_revnum;
  982. } elsif ($r !~ /^\d+$/) {
  983. die "revision argument: $r not understood by git-svn\n";
  984. }
  985. my %ed_opts = ( r => $r,
  986. log => $_message,
  987. ra => $ra,
  988. tree_a => $ta,
  989. tree_b => $tb,
  990. editor_cb => sub { print "Committed r$_[0]\n" },
  991. svn_path => $svn_path );
  992. if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
  993. print "No changes\n$ta == $tb\n";
  994. }
  995. }
  996. sub escape_uri_only {
  997. my ($uri) = @_;
  998. my @tmp;
  999. foreach (split m{/}, $uri) {
  1000. s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
  1001. push @tmp, $_;
  1002. }
  1003. join('/', @tmp);
  1004. }
  1005. sub escape_url {
  1006. my ($url) = @_;
  1007. if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
  1008. my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
  1009. $url = "$scheme://$domain$uri";
  1010. }
  1011. $url;
  1012. }
  1013. sub cmd_info {
  1014. my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
  1015. my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
  1016. if (exists $_[1]) {
  1017. die "Too many arguments specified\n";
  1018. }
  1019. my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
  1020. if (!$file_type && !$diff_status) {
  1021. print STDERR "svn: '$path' is not under version control\n";
  1022. exit 1;
  1023. }
  1024. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  1025. unless ($gs) {
  1026. die "Unable to determine upstream SVN information from ",
  1027. "working tree history\n";
  1028. }
  1029. # canonicalize_path() will return "" to make libsvn 1.5.x happy,
  1030. $path = "." if $path eq "";
  1031. my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
  1032. if ($_url) {
  1033. print escape_url($full_url), "\n";
  1034. return;
  1035. }
  1036. my $result = "Path: $path\n";
  1037. $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
  1038. $result .= "URL: " . escape_url($full_url) . "\n";
  1039. eval {
  1040. my $repos_root = $gs->repos_root;
  1041. Git::SVN::remove_username($repos_root);
  1042. $result .= "Repository Root: " . escape_url($repos_root) . "\n";
  1043. };
  1044. if ($@) {
  1045. $result .= "Repository Root: (offline)\n";
  1046. }
  1047. ::_req_svn();
  1048. $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
  1049. ($SVN::Core::VERSION le '1.5.4' || $file_type ne "dir");
  1050. $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
  1051. $result .= "Node Kind: " .
  1052. ($file_type eq "dir" ? "directory" : "file") . "\n";
  1053. my $schedule = $diff_status eq "A"
  1054. ? "add"
  1055. : ($diff_status eq "D" ? "delete" : "normal");
  1056. $result .= "Schedule: $schedule\n";
  1057. if ($diff_status eq "A") {
  1058. print $result, "\n";
  1059. return;
  1060. }
  1061. my ($lc_author, $lc_rev, $lc_date_utc);
  1062. my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
  1063. my $log = command_output_pipe(@args);
  1064. my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
  1065. while (<$log>) {
  1066. if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
  1067. $lc_author = $1;
  1068. $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
  1069. } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
  1070. (undef, $lc_rev, undef) = ::extract_metadata($1);
  1071. }
  1072. }
  1073. close $log;
  1074. Git::SVN::Log::set_local_timezone();
  1075. $result .= "Last Changed Author: $lc_author\n";
  1076. $result .= "Last Changed Rev: $lc_rev\n";
  1077. $result .= "Last Changed Date: " .
  1078. Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
  1079. if ($file_type ne "dir") {
  1080. my $text_last_updated_date =
  1081. ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
  1082. $result .=
  1083. "Text Last Updated: " .
  1084. Git::SVN::Log::format_svn_date($text_last_updated_date) .
  1085. "\n";
  1086. my $checksum;
  1087. if ($diff_status eq "D") {
  1088. my ($fh, $ctx) =
  1089. command_output_pipe(qw(cat-file blob), "HEAD:$path");
  1090. if ($file_type eq "link") {
  1091. my $file_name = <$fh>;
  1092. $checksum = md5sum("link $file_name");
  1093. } else {
  1094. $checksum = md5sum($fh);
  1095. }
  1096. command_close_pipe($fh, $ctx);
  1097. } elsif ($file_type eq "link") {
  1098. my $file_name =
  1099. command(qw(cat-file blob), "HEAD:$path");
  1100. $checksum =
  1101. md5sum("link " . $file_name);
  1102. } else {
  1103. open FILE, "<", $path or die $!;
  1104. $checksum = md5sum(\*FILE);
  1105. close FILE or die $!;
  1106. }
  1107. $result .= "Checksum: " . $checksum . "\n";
  1108. }
  1109. print $result, "\n";
  1110. }
  1111. sub cmd_reset {
  1112. my $target = shift || $_revision or die "SVN revision required\n";
  1113. $target = $1 if $target =~ /^r(\d+)$/;
  1114. $target =~ /^\d+$/ or die "Numeric SVN revision expected\n";
  1115. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  1116. unless ($gs) {
  1117. die "Unable to determine upstream SVN information from ".
  1118. "history\n";
  1119. }
  1120. my ($r, $c) = $gs->find_rev_before($target, not $_fetch_parent);
  1121. die "Cannot find SVN revision $target\n" unless defined($c);
  1122. $gs->rev_map_set($r, $c, 'reset', $uuid);
  1123. print "r$r = $c ($gs->{ref_id})\n";
  1124. }
  1125. sub cmd_gc {
  1126. if (!$can_compress) {
  1127. warn "Compress::Zlib could not be found; unhandled.log " .
  1128. "files will not be compressed.\n";
  1129. }
  1130. find({ wanted => \&gc_directory, no_chdir => 1}, "$ENV{GIT_DIR}/svn");
  1131. }
  1132. ########################### utility functions #########################
  1133. sub rebase_cmd {
  1134. my @cmd = qw/rebase/;
  1135. push @cmd, '-v' if $_verbose;
  1136. push @cmd, qw/--merge/ if $_merge;
  1137. push @cmd, "--strategy=$_strategy" if $_strategy;
  1138. @cmd;
  1139. }
  1140. sub post_fetch_checkout {
  1141. return if $_no_checkout;
  1142. my $gs = $Git::SVN::_head or return;
  1143. return if verify_ref('refs/heads/master^0');
  1144. # look for "trunk" ref if it exists
  1145. my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
  1146. my $fetch = $remote->{fetch};
  1147. if ($fetch) {
  1148. foreach my $p (keys %$fetch) {
  1149. basename($fetch->{$p}) eq 'trunk' or next;
  1150. $gs = Git::SVN->new($fetch->{$p}, $gs->{repo_id}, $p);
  1151. last;
  1152. }
  1153. }
  1154. my $valid_head = verify_ref('HEAD^0');
  1155. command_noisy(qw(update-ref refs/heads/master), $gs->refname);
  1156. return if ($valid_head || !verify_ref('HEAD^0'));
  1157. return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
  1158. my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
  1159. return if -f $index;
  1160. return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
  1161. return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
  1162. command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
  1163. print STDERR "Checked out HEAD:\n ",
  1164. $gs->full_url, " r", $gs->last_rev, "\n";
  1165. if (auto_create_empty_directories($gs)) {
  1166. $gs->mkemptydirs($gs->last_rev);
  1167. }
  1168. }
  1169. sub complete_svn_url {
  1170. my ($url, $path) = @_;
  1171. $path =~ s#/+$##;
  1172. if ($path !~ m#^[a-z\+]+://#) {
  1173. if (!defined $url || $url !~ m#^[a-z\+]+://#) {
  1174. fatal("E: '$path' is not a complete URL ",
  1175. "and a separate URL is not specified");
  1176. }
  1177. return ($url, $path);
  1178. }
  1179. return ($path, '');
  1180. }
  1181. sub complete_url_ls_init {
  1182. my ($ra, $repo_path, $switch, $pfx) = @_;
  1183. unless ($repo_path) {
  1184. print STDERR "W: $switch not specified\n";
  1185. return;
  1186. }
  1187. $repo_path =~ s#/+$##;
  1188. if ($repo_path =~ m#^[a-z\+]+://#) {
  1189. $ra = Git::SVN::Ra->new($repo_path);
  1190. $repo_path = '';
  1191. } else {
  1192. $repo_path =~ s#^/+##;
  1193. unless ($ra) {
  1194. fatal("E: '$repo_path' is not a complete URL ",
  1195. "and a separate URL is not specified");
  1196. }
  1197. }
  1198. my $url = $ra->{url};
  1199. my $gs = Git::SVN->init($url, undef, undef, undef, 1);
  1200. my $k = "svn-remote.$gs->{repo_id}.url";
  1201. my $orig_url = eval { command_oneline(qw/config --get/, $k) };
  1202. if ($orig_url && ($orig_url ne $gs->{url})) {
  1203. die "$k already set: $orig_url\n",
  1204. "wanted to set to: $gs->{url}\n";
  1205. }
  1206. command_oneline('config', $k, $gs->{url}) unless $orig_url;
  1207. my $remote_path = "$gs->{path}/$repo_path";
  1208. $remote_path =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
  1209. $remote_path =~ s#/+#/#g;
  1210. $remote_path =~ s#^/##g;
  1211. $remote_path .= "/*" if $remote_path !~ /\*/;
  1212. my ($n) = ($switch =~ /^--(\w+)/);
  1213. if (length $pfx && $pfx !~ m#/$#) {
  1214. die "--prefix='$pfx' must have a trailing slash '/'\n";
  1215. }
  1216. command_noisy('config',
  1217. '--add',
  1218. "svn-remote.$gs->{repo_id}.$n",
  1219. "$remote_path:refs/remotes/$pfx*" .
  1220. ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
  1221. }
  1222. sub verify_ref {
  1223. my ($ref) = @_;
  1224. eval { command_oneline([ 'rev-parse', '--verify', $ref ],
  1225. { STDERR => 0 }); };
  1226. }
  1227. sub get_tree_from_treeish {
  1228. my ($treeish) = @_;
  1229. # $treeish can be a symbolic ref, too:
  1230. my $type = command_oneline(qw/cat-file -t/, $treeish);
  1231. my $expected;
  1232. while ($type eq 'tag') {
  1233. ($treeish, $type) = command(qw/cat-file tag/, $treeish);
  1234. }
  1235. if ($type eq 'commit') {
  1236. $expected = (grep /^tree /, command(qw/cat-file commit/,
  1237. $treeish))[0];
  1238. ($expected) = ($expected =~ /^tree ($sha1)$/o);
  1239. die "Unable to get tree from $treeish\n" unless $expected;
  1240. } elsif ($type eq 'tree') {
  1241. $expected = $treeish;
  1242. } else {
  1243. die "$treeish is a $type, expected tree, tag or commit\n";
  1244. }
  1245. return $expected;
  1246. }
  1247. sub get_commit_entry {
  1248. my ($treeish) = shift;
  1249. my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
  1250. my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
  1251. my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
  1252. open my $log_fh, '>', $commit_editmsg or croak $!;
  1253. my $type = command_oneline(qw/cat-file -t/, $treeish);
  1254. if ($type eq 'commit' || $type eq 'tag') {
  1255. my ($msg_fh, $ctx) = command_output_pipe('cat-file',
  1256. $type, $treeish);
  1257. my $in_msg = 0;
  1258. my $author;
  1259. my $saw_from = 0;
  1260. my $msgbuf = "";
  1261. while (<$msg_fh>) {
  1262. if (!$in_msg) {
  1263. $in_msg = 1 if (/^\s*$/);
  1264. $author = $1 if (/^author (.*>)/);
  1265. } elsif (/^git-svn-id: /) {
  1266. # skip this for now, we regenerate the
  1267. # correct one on re-fetch anyways
  1268. # TODO: set *:merge properties or like...
  1269. } else {
  1270. if (/^From:/ || /^Signed-off-by:/) {
  1271. $saw_from = 1;
  1272. }
  1273. $msgbuf .= $_;
  1274. }
  1275. }
  1276. $msgbuf =~ s/\s+$//s;
  1277. if ($Git::SVN::_add_author_from && defined($author)
  1278. && !$saw_from) {
  1279. $msgbuf .= "\n\nFrom: $author";
  1280. }
  1281. print $log_fh $msgbuf or croak $!;
  1282. command_close_pipe($msg_fh, $ctx);
  1283. }
  1284. close $log_fh or croak $!;
  1285. if ($_edit || ($type eq 'tree')) {
  1286. chomp(my $editor = command_oneline(qw(var GIT_EDITOR)));
  1287. system('sh', '-c', $editor.' "$@"', $editor, $commit_editmsg);
  1288. }
  1289. rename $commit_editmsg, $commit_msg or croak $!;
  1290. {
  1291. require Encode;
  1292. # SVN requires messages to be UTF-8 when entering the repo
  1293. local $/;
  1294. open $log_fh, '<', $commit_msg or croak $!;
  1295. binmode $log_fh;
  1296. chomp($log_entry{log} = <$log_fh>);
  1297. my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
  1298. my $msg = $log_entry{log};
  1299. eval { $msg = Encode::decode($enc, $msg, 1) };
  1300. if ($@) {
  1301. die "Could not decode as $enc:\n", $msg,
  1302. "\nPerhaps you need to set i18n.commitencoding\n";
  1303. }
  1304. eval { $msg = Encode::encode('UTF-8', $msg, 1) };
  1305. die "Could not encode as UTF-8:\n$msg\n" if $@;
  1306. $log_entry{log} = $msg;
  1307. close $log_fh or croak $!;
  1308. }
  1309. unlink $commit_msg;
  1310. \%log_entry;
  1311. }
  1312. sub s_to_file {
  1313. my ($str, $file, $mode) = @_;
  1314. open my $fd,'>',$file or croak $!;
  1315. print $fd $str,"\n" or croak $!;
  1316. close $fd or croak $!;
  1317. chmod ($mode &~ umask, $file) if (defined $mode);
  1318. }
  1319. sub file_to_s {
  1320. my $file = shift;
  1321. open my $fd,'<',$file or croak "$!: file: $file\n";
  1322. local $/;
  1323. my $ret = <$fd>;
  1324. close $fd or croak $!;
  1325. $ret =~ s/\s*$//s;
  1326. return $ret;
  1327. }
  1328. # '<svn username> = real-name <email address>' mapping based on git-svnimport:
  1329. sub load_authors {
  1330. open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
  1331. my $log = $cmd eq 'log';
  1332. while (<$authors>) {
  1333. chomp;
  1334. next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
  1335. my ($user, $name, $email) = ($1, $2, $3);
  1336. if ($log) {
  1337. $Git::SVN::Log::rusers{"$name <$email>"} = $user;
  1338. } else {
  1339. $users{$user} = [$name, $email];
  1340. }
  1341. }
  1342. close $authors or croak $!;
  1343. }
  1344. # convert GetOpt::Long specs for use by git-config
  1345. sub read_git_config {
  1346. my $opts = shift;
  1347. my @config_only;
  1348. foreach my $o (keys %$opts) {
  1349. # if we have mixedCase and a long option-only, then
  1350. # it's a config-only variable that we don't need for
  1351. # the command-line.
  1352. push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
  1353. my $v = $opts->{$o};
  1354. my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
  1355. $key =~ s/-//g;
  1356. my $arg = 'git config';
  1357. $arg .= ' --int' if ($o =~ /[:=]i$/);
  1358. $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
  1359. if (ref $v eq 'ARRAY') {
  1360. chomp(my @tmp = `$arg --get-all svn.$key`);
  1361. @$v = @tmp if @tmp;
  1362. } else {
  1363. chomp(my $tmp = `$arg --get svn.$key`);
  1364. if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
  1365. $$v = $tmp;
  1366. }
  1367. }
  1368. }
  1369. delete @$opts{@config_only} if @config_only;
  1370. }
  1371. sub extract_metadata {
  1372. my $id = shift or return (undef, undef, undef);
  1373. my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
  1374. \s([a-f\d\-]+)$/ix);
  1375. if (!defined $rev || !$uuid || !$url) {
  1376. # some of the original repositories I made had
  1377. # identifiers like this:
  1378. ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/i);
  1379. }
  1380. return ($url, $rev, $uuid);
  1381. }
  1382. sub cmt_metadata {
  1383. return extract_metadata((grep(/^git-svn-id: /,
  1384. command(qw/cat-file commit/, shift)))[-1]);
  1385. }
  1386. sub cmt_sha2rev_batch {
  1387. my %s2r;
  1388. my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
  1389. my $list = shift;
  1390. foreach my $sha (@{$list}) {
  1391. my $first = 1;
  1392. my $size = 0;
  1393. print $out $sha, "\n";
  1394. while (my $line = <$in>) {
  1395. if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
  1396. last;
  1397. } elsif ($first &&
  1398. $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
  1399. $first = 0;
  1400. $size = $1;
  1401. next;
  1402. } elsif ($line =~ /^(git-svn-id: )/) {
  1403. my (undef, $rev, undef) =
  1404. extract_metadata($line);
  1405. $s2r{$sha} = $rev;
  1406. }
  1407. $size -= length($line);
  1408. last if ($size == 0);
  1409. }
  1410. }
  1411. command_close_bidi_pipe($pid, $in, $out, $ctx);
  1412. return \%s2r;
  1413. }
  1414. sub working_head_info {
  1415. my ($head, $refs) = @_;
  1416. my @args = qw/log --no-color --no-decorate --first-parent
  1417. --pretty=medium/;
  1418. my ($fh, $ctx) = command_output_pipe(@args, $head);
  1419. my $hash;
  1420. my %max;
  1421. while (<$fh>) {
  1422. if ( m{^commit ($::sha1)$} ) {
  1423. unshift @$refs, $hash if $hash and $refs;
  1424. $hash = $1;
  1425. next;
  1426. }
  1427. next unless s{^\s*(git-svn-id:)}{$1};
  1428. my ($url, $rev, $uuid) = extract_metadata($_);
  1429. if (defined $url && defined $rev) {
  1430. next if $max{$url} and $max{$url} < $rev;
  1431. if (my $gs = Git::SVN->find_by_url($url)) {
  1432. my $c = $gs->rev_map_get($rev, $uuid);
  1433. if ($c && $c eq $hash) {
  1434. close $fh; # break the pipe
  1435. return ($url, $rev, $uuid, $gs);
  1436. } else {
  1437. $max{$url} ||= $gs->rev_map_max;
  1438. }
  1439. }
  1440. }
  1441. }
  1442. command_close_pipe($fh, $ctx);
  1443. (undef, undef, undef, undef);
  1444. }
  1445. sub read_commit_parents {
  1446. my ($parents, $c) = @_;
  1447. chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
  1448. $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
  1449. @{$parents->{$c}} = split(/ /, $p);
  1450. }
  1451. sub linearize_history {
  1452. my ($gs, $refs) = @_;
  1453. my %parents;
  1454. foreach my $c (@$refs) {
  1455. read_commit_parents(\%parents, $c);
  1456. }
  1457. my @linear_refs;
  1458. my %skip = ();
  1459. my $last_svn_commit = $gs->last_commit;
  1460. foreach my $c (reverse @$refs) {
  1461. next if $c eq $last_svn_commit;
  1462. last if $skip{$c};
  1463. unshift @linear_refs, $c;
  1464. $skip{$c} = 1;
  1465. # we only want the first parent to diff against for linear
  1466. # history, we save the rest to inject when we finalize the
  1467. # svn commit
  1468. my $fp_a = verify_ref("$c~1");
  1469. my $fp_b = shift @{$parents{$c}} if $parents{$c};
  1470. if (!$fp_a || !$fp_b) {
  1471. die "Commit $c\n",
  1472. "has no parent commit, and therefore ",
  1473. "nothing to diff against.\n",
  1474. "You should be working from a repository ",
  1475. "originally created by git-svn\n";
  1476. }
  1477. if ($fp_a ne $fp_b) {
  1478. die "$c~1 = $fp_a, however parsing commit $c ",
  1479. "revealed that:\n$c~1 = $fp_b\nBUG!\n";
  1480. }
  1481. foreach my $p (@{$parents{$c}}) {
  1482. $skip{$p} = 1;
  1483. }
  1484. }
  1485. (\@linear_refs, \%parents);
  1486. }
  1487. sub find_file_type_and_diff_status {
  1488. my ($path) = @_;
  1489. return ('dir', '') if $path eq '';
  1490. my $diff_output =
  1491. command_oneline(qw(diff --cached --name-status --), $path) || "";
  1492. my $diff_status = (split(' ', $diff_output))[0] || "";
  1493. my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
  1494. return (undef, undef) if !$diff_status && !$ls_tree;
  1495. if ($diff_status eq "A") {
  1496. return ("link", $diff_status) if -l $path;
  1497. return ("dir", $diff_status) if -d $path;
  1498. return ("file", $diff_status);
  1499. }
  1500. my $mode = (split(' ', $ls_tree))[0] || "";
  1501. return ("link", $diff_status) if $mode eq "120000";
  1502. return ("dir", $diff_status) if $mode eq "040000";
  1503. return ("file", $diff_status);
  1504. }
  1505. sub md5sum {
  1506. my $arg = shift;
  1507. my $ref = ref $arg;
  1508. my $md5 = Digest::MD5->new();
  1509. if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
  1510. $md5->addfile($arg) or croak $!;
  1511. } elsif ($ref eq 'SCALAR') {
  1512. $md5->add($$arg) or croak $!;
  1513. } elsif (!$ref) {
  1514. $md5->add($arg) or croak $!;
  1515. } else {
  1516. ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
  1517. }
  1518. return $md5->hexdigest();
  1519. }
  1520. sub gc_directory {
  1521. if ($can_compress && -f $_ && basename($_) eq "unhandled.log") {
  1522. my $out_filename = $_ . ".gz";
  1523. open my $in_fh, "<", $_ or die "Unable to open $_: $!\n";
  1524. binmode $in_fh;
  1525. my $gz = Compress::Zlib::gzopen($out_filename, "ab") or
  1526. die "Unable to open $out_filename: $!\n";
  1527. my $res;
  1528. while ($res = sysread($in_fh, my $str, 1024)) {
  1529. $gz->gzwrite($str) or
  1530. die "Unable to write: ".$gz->gzerror()."!\n";
  1531. }
  1532. unlink $_ or die "unlink $File::Find::name: $!\n";
  1533. } elsif (-f $_ && basename($_) eq "index") {
  1534. unlink $_ or die "unlink $_: $!\n";
  1535. }
  1536. }
  1537. package Git::SVN;
  1538. use strict;
  1539. use warnings;
  1540. use Fcntl qw/:DEFAULT :seek/;
  1541. use constant rev_map_fmt => 'NH40';
  1542. use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
  1543. $_repack $_repack_flags $_use_svm_props $_head
  1544. $_use_svnsync_props $no_reuse_existing $_minimize_url
  1545. $_use_log_author $_add_author_from $_localtime/;
  1546. use Carp qw/croak/;
  1547. use File::Path qw/mkpath/;
  1548. use File::Copy qw/copy/;
  1549. use IPC::Open3;
  1550. use Memoize; # core since 5.8.0, Jul 2002
  1551. use Memoize::Storable;
  1552. my ($_gc_nr, $_gc_period);
  1553. # properties that we do not log:
  1554. my %SKIP_PROP;
  1555. BEGIN {
  1556. %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
  1557. svn:special svn:executable
  1558. svn:entry:committed-rev
  1559. svn:entry:last-author
  1560. svn:entry:uuid
  1561. svn:entry:committed-date/;
  1562. # some options are read globally, but can

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