GenerateCommand.php 7.7 KB

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