GenerateCommand.php 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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\Input\InputArgument;
  18. use Symfony\Component\Console\Input\InputInterface;
  19. use Symfony\Component\Console\Output\OutputInterface;
  20. use Symfony\Component\Console\Question\ConfirmationQuestion;
  21. class GenerateCommand extends Command implements CompletionAwareInterface {
  22. protected static $_templateSimple =
  23. '<?php
  24. declare(strict_types=1);
  25. /**
  26. * SPDX-FileCopyrightText: {{year}} Nextcloud GmbH and Nextcloud contributors
  27. * SPDX-License-Identifier: AGPL-3.0-or-later
  28. */
  29. namespace {{namespace}};
  30. use Closure;
  31. use OCP\DB\ISchemaWrapper;
  32. use OCP\Migration\IOutput;
  33. use OCP\Migration\SimpleMigrationStep;
  34. /**
  35. * FIXME Auto-generated migration step: Please modify to your needs!
  36. */
  37. class {{classname}} extends SimpleMigrationStep {
  38. /**
  39. * @param IOutput $output
  40. * @param Closure(): ISchemaWrapper $schemaClosure
  41. * @param array $options
  42. */
  43. public function preSchemaChange(IOutput $output, Closure $schemaClosure, array $options): void {
  44. }
  45. /**
  46. * @param IOutput $output
  47. * @param Closure(): ISchemaWrapper $schemaClosure
  48. * @param array $options
  49. * @return null|ISchemaWrapper
  50. */
  51. public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper {
  52. {{schemabody}}
  53. }
  54. /**
  55. * @param IOutput $output
  56. * @param Closure(): ISchemaWrapper $schemaClosure
  57. * @param array $options
  58. */
  59. public function postSchemaChange(IOutput $output, Closure $schemaClosure, array $options): void {
  60. }
  61. }
  62. ';
  63. protected Connection $connection;
  64. protected IAppManager $appManager;
  65. public function __construct(Connection $connection, IAppManager $appManager) {
  66. $this->connection = $connection;
  67. $this->appManager = $appManager;
  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. $helper = $this->getHelper('question');
  104. $question = new ConfirmationQuestion('Continue with your given version? (y/n) [n] ', false);
  105. if (!$helper->ask($input, $output, $question)) {
  106. return 1;
  107. }
  108. }
  109. }
  110. }
  111. $ms = new MigrationService($appName, $this->connection, new ConsoleOutput($output));
  112. $date = date('YmdHis');
  113. $path = $this->generateMigration($ms, 'Version' . $version . 'Date' . $date);
  114. $output->writeln("New migration class has been generated to <info>$path</info>");
  115. return 0;
  116. }
  117. /**
  118. * @param string $optionName
  119. * @param CompletionContext $context
  120. * @return string[]
  121. */
  122. public function completeOptionValues($optionName, CompletionContext $context) {
  123. return [];
  124. }
  125. /**
  126. * @param string $argumentName
  127. * @param CompletionContext $context
  128. * @return string[]
  129. */
  130. public function completeArgumentValues($argumentName, CompletionContext $context) {
  131. if ($argumentName === 'app') {
  132. $allApps = \OC_App::getAllApps();
  133. return array_diff($allApps, \OC_App::getEnabledApps(true, true));
  134. }
  135. if ($argumentName === 'version') {
  136. $appName = $context->getWordAtIndex($context->getWordIndex() - 1);
  137. $version = explode('.', $this->appManager->getAppVersion($appName));
  138. return [$version[0] . sprintf('%1$03d', $version[1])];
  139. }
  140. return [];
  141. }
  142. /**
  143. * @param MigrationService $ms
  144. * @param string $className
  145. * @param string $schemaBody
  146. * @return string
  147. */
  148. protected function generateMigration(MigrationService $ms, $className, $schemaBody = '') {
  149. if ($schemaBody === '') {
  150. $schemaBody = "\t\t" . 'return null;';
  151. }
  152. $placeHolders = [
  153. '{{namespace}}',
  154. '{{classname}}',
  155. '{{schemabody}}',
  156. '{{year}}',
  157. ];
  158. $replacements = [
  159. $ms->getMigrationsNamespace(),
  160. $className,
  161. $schemaBody,
  162. date('Y')
  163. ];
  164. $code = str_replace($placeHolders, $replacements, self::$_templateSimple);
  165. $dir = $ms->getMigrationsDirectory();
  166. $this->ensureMigrationDirExists($dir);
  167. $path = $dir . '/' . $className . '.php';
  168. if (file_put_contents($path, $code) === false) {
  169. throw new RuntimeException('Failed to generate new migration step. Could not write to ' . $path);
  170. }
  171. return $path;
  172. }
  173. protected function ensureMigrationDirExists($directory) {
  174. if (file_exists($directory) && is_dir($directory)) {
  175. return;
  176. }
  177. if (file_exists($directory)) {
  178. throw new \RuntimeException("Could not create folder \"$directory\"");
  179. }
  180. $this->ensureMigrationDirExists(dirname($directory));
  181. if (!@mkdir($directory) && !is_dir($directory)) {
  182. throw new \RuntimeException("Could not create folder \"$directory\"");
  183. }
  184. }
  185. }