1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
|
<?php
declare(strict_types=1);
namespace Drupal\Core\Command;
use Composer\Autoload\ClassLoader;
use Composer\Semver\VersionParser;
use Drupal\Component\Serialization\Yaml;
use Drupal\Core\Extension\Extension;
use Drupal\Core\Extension\ExtensionDiscovery;
use Drupal\Core\Extension\InfoParser;
use Drupal\Core\Theme\StarterKitInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ConfirmationQuestion;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\Finder\Glob;
use Symfony\Component\Process\Process;
use function Symfony\Component\String\u;
/**
* Generates a new theme based on latest default markup.
*/
class GenerateTheme extends Command {
/**
* The path for the Drupal root.
*
* @var string
*/
private $root;
/**
* GenerateTheme constructor.
*
* @param string|null $name
* The name of the command; passing null means it must be set in
* configure().
* @param string|null $root
* The path for the Drupal root.
*/
public function __construct(?string $name = NULL, ?string $root = NULL) {
parent::__construct($name);
$this->root = $root ?? dirname(__DIR__, 5);
}
/**
* {@inheritdoc}
*/
protected function configure(): void {
$this->setName('generate-theme')
->setDescription('Generates a new theme based on latest default markup.')
->addArgument('machine-name', InputArgument::REQUIRED, 'The machine name of the generated theme')
->addOption('name', NULL, InputOption::VALUE_OPTIONAL, 'A name for the theme.')
->addOption('description', NULL, InputOption::VALUE_OPTIONAL, 'A description of your theme.', '')
->addOption('path', NULL, InputOption::VALUE_OPTIONAL, 'The path where your theme will be created. Defaults to: themes', 'themes')
->addOption('starterkit', NULL, InputOption::VALUE_OPTIONAL, 'The theme to use as the starterkit', 'starterkit_theme')
->addUsage('custom_theme --name "Custom Theme" --description "Custom theme generated from a starterkit theme" --path themes')
->addUsage('custom_theme --name "Custom Theme" --starterkit mystarterkit');
}
protected function initialize(InputInterface $input, OutputInterface $output): void {
if ($input->getOption('name') === NULL) {
$input->setOption('name', $input->getArgument('machine-name'));
}
// Change the directory to the Drupal root.
chdir($this->root);
}
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output): int {
$io = new SymfonyStyle($input, $output);
$filesystem = new Filesystem();
$tmpDir = $this->getUniqueTmpDirPath();
$destination_theme = $input->getArgument('machine-name');
$starterkit_id = $input->getOption('starterkit');
$theme_label = $input->getOption('name');
$io->writeln("<info>Generating theme $theme_label ($destination_theme) from $starterkit_id starterkit.</info>");
$destination = trim($input->getOption('path'), '/') . '/' . $destination_theme;
if (is_dir($destination)) {
$io->getErrorStyle()->error("Theme could not be generated because the destination directory $destination exists already.");
return 1;
}
$starterkit = $this->getThemeInfo($starterkit_id);
if ($starterkit === NULL) {
$io->getErrorStyle()->error("Theme source theme $starterkit_id cannot be found.");
return 1;
}
$io->writeln("Trying to parse version for $starterkit_id starterkit.", OutputInterface::VERBOSITY_DEBUG);
try {
$starterkit_version = self::getStarterKitVersion(
$starterkit,
$io
);
}
catch (\Exception $e) {
$io->getErrorStyle()->error($e->getMessage());
return 1;
}
$io->writeln("Using version $starterkit_version for $starterkit_id starterkit.", OutputInterface::VERBOSITY_DEBUG);
$io->writeln("Loading starterkit config from $starterkit_id.starterkit.yml.", OutputInterface::VERBOSITY_DEBUG);
try {
$starterkit_config = self::loadStarterKitConfig(
$starterkit,
$starterkit_version,
$theme_label,
$input->getOption('description')
);
}
catch (\Exception $e) {
$io->getErrorStyle()->error($e->getMessage());
return 1;
}
$filesystem->mkdir($tmpDir);
$io->writeln("Copying starterkit to temporary directory for processing.", OutputInterface::VERBOSITY_DEBUG);
$mirror_iterator = (new Finder)
->in($starterkit->getPath())
->files()
->ignoreDotFiles(FALSE)
->notName($starterkit_config['ignore'])
->notPath($starterkit_config['ignore']);
$filesystem->mirror($starterkit->getPath(), $tmpDir, $mirror_iterator);
$io->writeln("Modifying and renaming files from starterkit.", OutputInterface::VERBOSITY_DEBUG);
$patterns = [
'old' => self::namePatterns($starterkit->getName(), $starterkit->info['name']),
'new' => self::namePatterns($destination_theme, $theme_label),
];
$filesToEdit = self::createFilesFinder($tmpDir)
->contains(array_values($patterns['old']))
->notPath($starterkit_config['no_edit']);
foreach ($filesToEdit as $file) {
$contents = file_get_contents($file->getRealPath());
$contents = str_replace($patterns['old'], $patterns['new'], $contents);
file_put_contents($file->getRealPath(), $contents);
}
$filesToRename = self::createFilesFinder($tmpDir)
->name(array_map(static fn (string $pattern) => "*$pattern*", array_values($patterns['old'])))
->notPath($starterkit_config['no_rename']);
foreach ($filesToRename as $file) {
$filepath_segments = explode('/', $file->getRealPath());
$filename = array_pop($filepath_segments);
$filename = str_replace($patterns['old'], $patterns['new'], $filename);
$filepath_segments[] = $filename;
$filesystem->rename($file->getRealPath(), implode('/', $filepath_segments));
}
$io->writeln("Updating $destination_theme.info.yml.", OutputInterface::VERBOSITY_DEBUG);
$info_file = "$tmpDir/$destination_theme.info.yml";
$info = Yaml::decode(file_get_contents($info_file));
$info = array_filter(
array_merge($info, $starterkit_config['info']),
static fn (mixed $value) => $value !== NULL,
);
// Ensure the generated theme is not hidden.
unset($info['hidden']);
file_put_contents($info_file, Yaml::encode($info));
$loader = new ClassLoader();
$loader->addPsr4("Drupal\\{$starterkit->getName()}\\", "{$starterkit->getPath()}/src");
$loader->register();
$generator_classname = "Drupal\\{$starterkit->getName()}\\StarterKit";
if (class_exists($generator_classname)) {
if (is_a($generator_classname, StarterKitInterface::class, TRUE)) {
$io->writeln("Running post processing.", OutputInterface::VERBOSITY_DEBUG);
$generator_classname::postProcess($tmpDir, $destination_theme, $theme_label);
}
else {
$io->getErrorStyle()->error("The $generator_classname does not implement \Drupal\Core\Theme\StarterKitInterface and cannot perform post-processing.");
return 1;
}
}
else {
$io->writeln("Skipping post processing, $generator_classname not defined.", OutputInterface::VERBOSITY_DEBUG);
}
// Move altered theme to final destination.
$io->writeln("Copying $destination_theme to $destination.", OutputInterface::VERBOSITY_DEBUG);
$filesystem->mirror($tmpDir, $destination);
$io->writeln(sprintf('Theme generated successfully to %s', $destination));
return 0;
}
/**
* Generates a path to a temporary location.
*
* @return string
* A temporary path.
*/
private function getUniqueTmpDirPath(): string {
return sys_get_temp_dir() . '/drupal-starterkit-theme-' . uniqid(md5(microtime()), TRUE);
}
/**
* Gets theme info using the theme name.
*
* @param string $theme_name
* The machine name of the theme.
*
* @return \Drupal\Core\Extension\Extension|null
* The extension info array. NULL if the theme_name is not discovered.
*/
private function getThemeInfo(string $theme_name): ? Extension {
$extension_discovery = new ExtensionDiscovery($this->root, FALSE, []);
$themes = $extension_discovery->scan('theme');
$theme = $themes[$theme_name] ?? NULL;
if ($theme !== NULL) {
$theme->info = (new InfoParser($this->root))->parse($theme->getPathname());
}
return $theme;
}
private static function createFilesFinder(string $dir): Finder {
return (new Finder)->in($dir)->files();
}
private static function loadStarterKitConfig(
Extension $theme,
string $version,
string $name,
string $description,
): array {
$starterkit_config_file = $theme->getPath() . '/' . $theme->getName() . '.starterkit.yml';
if (!file_exists($starterkit_config_file)) {
throw new \RuntimeException("Theme source theme {$theme->getName()} is not a valid starter kit.");
}
$starterkit_config_defaults = [
'info' => [
'name' => $name,
'description' => $description,
'core_version_requirement' => '^' . explode('.', \Drupal::VERSION)[0],
'version' => '1.0.0',
'generator' => "{$theme->getName()}:$version",
],
'ignore' => [
'/src/StarterKit.php',
'/*.starterkit.yml',
],
'no_edit' => [],
'no_rename' => [],
];
$starterkit_config = Yaml::decode(file_get_contents($starterkit_config_file));
if (!is_array($starterkit_config)) {
throw new \RuntimeException('Starterkit config is was not able to be parsed.');
}
if (!isset($starterkit_config['info'])) {
$starterkit_config['info'] = [];
}
$starterkit_config['info'] = array_merge($starterkit_config_defaults['info'], $starterkit_config['info']);
foreach (['ignore', 'no_edit', 'no_rename'] as $key) {
if (!isset($starterkit_config[$key])) {
$starterkit_config[$key] = $starterkit_config_defaults[$key];
}
if (!is_array($starterkit_config[$key])) {
throw new \RuntimeException("$key in starterkit.yml must be an array");
}
$starterkit_config[$key] = array_map(
static fn (string $path) => Glob::toRegex(trim($path, '/')),
$starterkit_config[$key]
);
if (count($starterkit_config[$key]) > 0) {
$files = self::createFilesFinder($theme->getPath())->path($starterkit_config[$key]);
$starterkit_config[$key] = array_map(static fn ($file) => $file->getRelativePathname(), iterator_to_array($files));
if (count($starterkit_config[$key]) === 0) {
throw new \RuntimeException("Paths were defined `$key` but no files found.");
}
}
}
return $starterkit_config;
}
private static function getStarterKitVersion(
Extension $theme,
SymfonyStyle $io,
): string {
$source_version = $theme->info['version'] ?? '';
if ($source_version === '') {
$confirm = new ConfirmationQuestion(sprintf(
'The source theme %s does not have a version specified. This makes tracking changes in the source theme difficult. Are you sure you want to continue?',
$theme->getName()
));
if (!$io->askQuestion($confirm)) {
throw new \RuntimeException('source version could not be determined');
}
$source_version = 'unknown-version';
}
if ($source_version === 'VERSION') {
$source_version = \Drupal::VERSION;
}
// A version in the generator string like "9.4.0-dev" is not very helpful.
// When this occurs, generate a version string that points to a commit.
if (VersionParser::parseStability($source_version) === 'dev') {
$git_check = Process::fromShellCommandline('git --help');
$git_check->run();
if ($git_check->getExitCode()) {
throw new \RuntimeException(
sprintf(
'The source theme %s has a development version number (%s). Determining a specific commit is not possible because git is not installed. Either install git or use a tagged release to generate a theme.',
$theme->getName(),
$source_version
)
);
}
// Get the git commit for the source theme.
$git_get_commit = Process::fromShellCommandline("git rev-list --max-count=1 --abbrev-commit HEAD -C {$theme->getPath()}");
$git_get_commit->run();
if (!$git_get_commit->isSuccessful() || $git_get_commit->getOutput() === '') {
$confirm = new ConfirmationQuestion(sprintf(
'The source theme %s has a development version number (%s). Because it is not a git checkout, a specific commit could not be identified. This makes tracking changes in the source theme difficult. Are you sure you want to continue?',
$theme->getName(),
$source_version
));
if (!$io->askQuestion($confirm)) {
throw new \RuntimeException('source version could not be determined');
}
$source_version .= '#unknown-commit';
}
else {
$source_version .= '#' . trim($git_get_commit->getOutput());
}
}
return $source_version;
}
private static function namePatterns(string $machine_name, string $label): array {
return [
'machine_name' => $machine_name,
'machine_name_camel' => u($machine_name)->camel(),
'machine_name_pascal' => u($machine_name)->camel()->title(),
'machine_name_title' => u($machine_name)->title(),
'label' => $label,
'label_camel' => u($label)->camel(),
'label_pascal' => u($label)->camel()->title(),
'label_title' => u($label)->title(),
];
}
}
|