GenerateCommand.php 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2017 ownCloud GmbH
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC\Core\Command\Db\Migrations;
  8. use OC\DB\Connection;
  9. use OC\DB\MigrationService;
  10. use OC\Migration\ConsoleOutput;
  11. use OCP\App\IAppManager;
  12. use OCP\Util;
  13. use Stecman\Component\Symfony\Console\BashCompletion\Completion\CompletionAwareInterface;
  14. use Stecman\Component\Symfony\Console\BashCompletion\CompletionContext;
  15. use Symfony\Component\Console\Command\Command;
  16. use Symfony\Component\Console\Exception\RuntimeException;
  17. use Symfony\Component\Console\Helper\QuestionHelper;
  18. use Symfony\Component\Console\Input\InputArgument;
  19. use Symfony\Component\Console\Input\InputInterface;
  20. use Symfony\Component\Console\Output\OutputInterface;
  21. use Symfony\Component\Console\Question\ConfirmationQuestion;
  22. class GenerateCommand extends Command implements CompletionAwareInterface {
  23. protected static $_templateSimple =
  24. '<?php
  25. declare(strict_types=1);
  26. /**
  27. * SPDX-FileCopyrightText: {{year}} Nextcloud GmbH and Nextcloud contributors
  28. * SPDX-License-Identifier: AGPL-3.0-or-later
  29. */
  30. namespace {{namespace}};
  31. use Closure;
  32. use OCP\DB\ISchemaWrapper;
  33. use OCP\Migration\IOutput;
  34. use OCP\Migration\SimpleMigrationStep;
  35. /**
  36. * FIXME Auto-generated migration step: Please modify to your needs!
  37. */
  38. class {{classname}} extends SimpleMigrationStep {
  39. /**
  40. * @param IOutput $output
  41. * @param Closure(): ISchemaWrapper $schemaClosure
  42. * @param array $options
  43. */
  44. public function preSchemaChange(IOutput $output, Closure $schemaClosure, array $options): void {
  45. }
  46. /**
  47. * @param IOutput $output
  48. * @param Closure(): ISchemaWrapper $schemaClosure
  49. * @param array $options
  50. * @return null|ISchemaWrapper
  51. */
  52. public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper {
  53. {{schemabody}}
  54. }
  55. /**
  56. * @param IOutput $output
  57. * @param Closure(): ISchemaWrapper $schemaClosure
  58. * @param array $options
  59. */
  60. public function postSchemaChange(IOutput $output, Closure $schemaClosure, array $options): void {
  61. }
  62. }
  63. ';
  64. public function __construct(
  65. protected Connection $connection,
  66. protected IAppManager $appManager,
  67. ) {
  68. parent::__construct();
  69. }
  70. protected function configure() {
  71. $this
  72. ->setName('migrations:generate')
  73. ->addArgument('app', InputArgument::REQUIRED, 'Name of the app this migration command shall work on')
  74. ->addArgument('version', InputArgument::REQUIRED, 'Major version of this app, to allow versions on parallel development branches')
  75. ;
  76. parent::configure();
  77. }
  78. public function execute(InputInterface $input, OutputInterface $output): int {
  79. $appName = $input->getArgument('app');
  80. $version = $input->getArgument('version');
  81. if (!preg_match('/^\d{1,16}$/', $version)) {
  82. $output->writeln('<error>The given version is invalid. Only 0-9 are allowed (max. 16 digits)</error>');
  83. return 1;
  84. }
  85. if ($appName === 'core') {
  86. $fullVersion = implode('.', Util::getVersion());
  87. } else {
  88. try {
  89. $fullVersion = $this->appManager->getAppVersion($appName, false);
  90. } catch (\Throwable $e) {
  91. $fullVersion = '';
  92. }
  93. }
  94. if ($fullVersion) {
  95. [$major, $minor] = explode('.', $fullVersion);
  96. $shouldVersion = (string)((int)$major * 1000 + (int)$minor);
  97. if ($version !== $shouldVersion) {
  98. $output->writeln('<comment>Unexpected migration version for current version: ' . $fullVersion . '</comment>');
  99. $output->writeln('<comment> - Pattern: XYYY </comment>');
  100. $output->writeln('<comment> - Expected: ' . $shouldVersion . '</comment>');
  101. $output->writeln('<comment> - Actual: ' . $version . '</comment>');
  102. if ($input->isInteractive()) {
  103. /** @var QuestionHelper $helper */
  104. $helper = $this->getHelper('question');
  105. $question = new ConfirmationQuestion('Continue with your given version? (y/n) [n] ', false);
  106. if (!$helper->ask($input, $output, $question)) {
  107. return 1;
  108. }
  109. }
  110. }
  111. }
  112. $ms = new MigrationService($appName, $this->connection, new ConsoleOutput($output));
  113. $date = date('YmdHis');
  114. $path = $this->generateMigration($ms, 'Version' . $version . 'Date' . $date);
  115. $output->writeln("New migration class has been generated to <info>$path</info>");
  116. return 0;
  117. }
  118. /**
  119. * @param string $optionName
  120. * @param CompletionContext $context
  121. * @return string[]
  122. */
  123. public function completeOptionValues($optionName, CompletionContext $context) {
  124. return [];
  125. }
  126. /**
  127. * @param string $argumentName
  128. * @param CompletionContext $context
  129. * @return string[]
  130. */
  131. public function completeArgumentValues($argumentName, CompletionContext $context) {
  132. if ($argumentName === 'app') {
  133. $allApps = $this->appManager->getAllAppsInAppsFolders();
  134. return array_diff($allApps, \OC_App::getEnabledApps(true, true));
  135. }
  136. if ($argumentName === 'version') {
  137. $appName = $context->getWordAtIndex($context->getWordIndex() - 1);
  138. $version = explode('.', $this->appManager->getAppVersion($appName));
  139. return [$version[0] . sprintf('%1$03d', $version[1])];
  140. }
  141. return [];
  142. }
  143. /**
  144. * @param MigrationService $ms
  145. * @param string $className
  146. * @param string $schemaBody
  147. * @return string
  148. */
  149. protected function generateMigration(MigrationService $ms, $className, $schemaBody = '') {
  150. if ($schemaBody === '') {
  151. $schemaBody = "\t\t" . 'return null;';
  152. }
  153. $placeHolders = [
  154. '{{namespace}}',
  155. '{{classname}}',
  156. '{{schemabody}}',
  157. '{{year}}',
  158. ];
  159. $replacements = [
  160. $ms->getMigrationsNamespace(),
  161. $className,
  162. $schemaBody,
  163. date('Y')
  164. ];
  165. $code = str_replace($placeHolders, $replacements, self::$_templateSimple);
  166. $dir = $ms->getMigrationsDirectory();
  167. $this->ensureMigrationDirExists($dir);
  168. $path = $dir . '/' . $className . '.php';
  169. if (file_put_contents($path, $code) === false) {
  170. throw new RuntimeException('Failed to generate new migration step. Could not write to ' . $path);
  171. }
  172. return $path;
  173. }
  174. protected function ensureMigrationDirExists($directory) {
  175. if (file_exists($directory) && is_dir($directory)) {
  176. return;
  177. }
  178. if (file_exists($directory)) {
  179. throw new \RuntimeException("Could not create folder \"$directory\"");
  180. }
  181. $this->ensureMigrationDirExists(dirname($directory));
  182. if (!@mkdir($directory) && !is_dir($directory)) {
  183. throw new \RuntimeException("Could not create folder \"$directory\"");
  184. }
  185. }
  186. }