GenerateCommand.php 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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. * @copyright Copyright (c) {{year}} FIXME Your name <your@email.com>
  27. *
  28. * FIXME @author Your name <your@email.com>
  29. *
  30. * @license GNU AGPL version 3 or any later version
  31. *
  32. * This program is free software: you can redistribute it and/or modify
  33. * it under the terms of the GNU Affero General Public License as
  34. * published by the Free Software Foundation, either version 3 of the
  35. * License, or (at your option) any later version.
  36. *
  37. * This program is distributed in the hope that it will be useful,
  38. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  39. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  40. * GNU Affero General Public License for more details.
  41. *
  42. * You should have received a copy of the GNU Affero General Public License
  43. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  44. *
  45. */
  46. namespace {{namespace}};
  47. use Closure;
  48. use OCP\DB\ISchemaWrapper;
  49. use OCP\Migration\IOutput;
  50. use OCP\Migration\SimpleMigrationStep;
  51. /**
  52. * FIXME Auto-generated migration step: Please modify to your needs!
  53. */
  54. class {{classname}} extends SimpleMigrationStep {
  55. /**
  56. * @param IOutput $output
  57. * @param Closure(): ISchemaWrapper $schemaClosure
  58. * @param array $options
  59. */
  60. public function preSchemaChange(IOutput $output, Closure $schemaClosure, array $options): void {
  61. }
  62. /**
  63. * @param IOutput $output
  64. * @param Closure(): ISchemaWrapper $schemaClosure
  65. * @param array $options
  66. * @return null|ISchemaWrapper
  67. */
  68. public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper {
  69. {{schemabody}}
  70. }
  71. /**
  72. * @param IOutput $output
  73. * @param Closure(): ISchemaWrapper $schemaClosure
  74. * @param array $options
  75. */
  76. public function postSchemaChange(IOutput $output, Closure $schemaClosure, array $options): void {
  77. }
  78. }
  79. ';
  80. protected Connection $connection;
  81. protected IAppManager $appManager;
  82. public function __construct(Connection $connection, IAppManager $appManager) {
  83. $this->connection = $connection;
  84. $this->appManager = $appManager;
  85. parent::__construct();
  86. }
  87. protected function configure() {
  88. $this
  89. ->setName('migrations:generate')
  90. ->addArgument('app', InputArgument::REQUIRED, 'Name of the app this migration command shall work on')
  91. ->addArgument('version', InputArgument::REQUIRED, 'Major version of this app, to allow versions on parallel development branches')
  92. ;
  93. parent::configure();
  94. }
  95. public function execute(InputInterface $input, OutputInterface $output): int {
  96. $appName = $input->getArgument('app');
  97. $version = $input->getArgument('version');
  98. if (!preg_match('/^\d{1,16}$/', $version)) {
  99. $output->writeln('<error>The given version is invalid. Only 0-9 are allowed (max. 16 digits)</error>');
  100. return 1;
  101. }
  102. if ($appName === 'core') {
  103. $fullVersion = implode('.', Util::getVersion());
  104. } else {
  105. try {
  106. $fullVersion = $this->appManager->getAppVersion($appName, false);
  107. } catch (\Throwable $e) {
  108. $fullVersion = '';
  109. }
  110. }
  111. if ($fullVersion) {
  112. [$major, $minor] = explode('.', $fullVersion);
  113. $shouldVersion = (string) ((int)$major * 1000 + (int)$minor);
  114. if ($version !== $shouldVersion) {
  115. $output->writeln('<comment>Unexpected migration version for current version: ' . $fullVersion . '</comment>');
  116. $output->writeln('<comment> - Pattern: XYYY </comment>');
  117. $output->writeln('<comment> - Expected: ' . $shouldVersion . '</comment>');
  118. $output->writeln('<comment> - Actual: ' . $version . '</comment>');
  119. if ($input->isInteractive()) {
  120. $helper = $this->getHelper('question');
  121. $question = new ConfirmationQuestion('Continue with your given version? (y/n) [n] ', false);
  122. if (!$helper->ask($input, $output, $question)) {
  123. return 1;
  124. }
  125. }
  126. }
  127. }
  128. $ms = new MigrationService($appName, $this->connection, new ConsoleOutput($output));
  129. $date = date('YmdHis');
  130. $path = $this->generateMigration($ms, 'Version' . $version . 'Date' . $date);
  131. $output->writeln("New migration class has been generated to <info>$path</info>");
  132. return 0;
  133. }
  134. /**
  135. * @param string $optionName
  136. * @param CompletionContext $context
  137. * @return string[]
  138. */
  139. public function completeOptionValues($optionName, CompletionContext $context) {
  140. return [];
  141. }
  142. /**
  143. * @param string $argumentName
  144. * @param CompletionContext $context
  145. * @return string[]
  146. */
  147. public function completeArgumentValues($argumentName, CompletionContext $context) {
  148. if ($argumentName === 'app') {
  149. $allApps = \OC_App::getAllApps();
  150. return array_diff($allApps, \OC_App::getEnabledApps(true, true));
  151. }
  152. if ($argumentName === 'version') {
  153. $appName = $context->getWordAtIndex($context->getWordIndex() - 1);
  154. $version = explode('.', $this->appManager->getAppVersion($appName));
  155. return [$version[0] . sprintf('%1$03d', $version[1])];
  156. }
  157. return [];
  158. }
  159. /**
  160. * @param MigrationService $ms
  161. * @param string $className
  162. * @param string $schemaBody
  163. * @return string
  164. */
  165. protected function generateMigration(MigrationService $ms, $className, $schemaBody = '') {
  166. if ($schemaBody === '') {
  167. $schemaBody = "\t\t" . 'return null;';
  168. }
  169. $placeHolders = [
  170. '{{namespace}}',
  171. '{{classname}}',
  172. '{{schemabody}}',
  173. '{{year}}',
  174. ];
  175. $replacements = [
  176. $ms->getMigrationsNamespace(),
  177. $className,
  178. $schemaBody,
  179. date('Y')
  180. ];
  181. $code = str_replace($placeHolders, $replacements, self::$_templateSimple);
  182. $dir = $ms->getMigrationsDirectory();
  183. $this->ensureMigrationDirExists($dir);
  184. $path = $dir . '/' . $className . '.php';
  185. if (file_put_contents($path, $code) === false) {
  186. throw new RuntimeException('Failed to generate new migration step. Could not write to ' . $path);
  187. }
  188. return $path;
  189. }
  190. protected function ensureMigrationDirExists($directory) {
  191. if (file_exists($directory) && is_dir($directory)) {
  192. return;
  193. }
  194. if (file_exists($directory)) {
  195. throw new \RuntimeException("Could not create folder \"$directory\"");
  196. }
  197. $this->ensureMigrationDirExists(dirname($directory));
  198. if (!@mkdir($directory) && !is_dir($directory)) {
  199. throw new \RuntimeException("Could not create folder \"$directory\"");
  200. }
  201. }
  202. }