-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDevkit.php
More file actions
289 lines (229 loc) · 8.85 KB
/
Devkit.php
File metadata and controls
289 lines (229 loc) · 8.85 KB
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
<?php
declare(strict_types=1);
namespace KaririCode\Devkit\Core;
use KaririCode\Devkit\Contract\ConfigGenerator;
use KaririCode\Devkit\Contract\ToolRunner;
use KaririCode\Devkit\Exception\DevkitException;
use KaririCode\Devkit\ValueObject\QualityReport;
use KaririCode\Devkit\ValueObject\ToolResult;
/**
* Top-level orchestrator for all devkit operations.
*
* Wired in `bin/kcode`. Holds config generators, tool runners,
* and the project context. Every public method is a high-level
* operation exposed through the CLI.
*
* @since 1.0.0
*/
final class Devkit
{
private const string VERSION = '1.0.0';
private ?ProjectContext $context = null;
/** @var array<string, ConfigGenerator> */
private array $generators = [];
/** @var array<string, ToolRunner> */
private array $runners = [];
public function __construct(
private readonly ProjectDetector $detector,
private readonly ComposerResolver $composerResolver = new ComposerResolver(),
) {
}
public static function version(): string
{
return self::VERSION;
}
// ── Registration ──────────────────────────────────────────────
public function addGenerator(ConfigGenerator $generator): void
{
$this->generators[$generator->toolName()] = $generator;
}
public function addRunner(ToolRunner $runner): void
{
$this->runners[$runner->toolName()] = $runner;
}
// ── Context ───────────────────────────────────────────────────
public function context(string $workingDirectory = '.'): ProjectContext
{
return $this->context ??= $this->detector->detect(
realpath($workingDirectory) ?: $workingDirectory,
);
}
// ── Init ──────────────────────────────────────────────────────
/** Generate all config files inside `.kcode/`. Returns file count. */
public function init(string $workingDirectory = '.'): int
{
$ctx = $this->context($workingDirectory);
$this->ensureDirectories($ctx);
$count = 0;
foreach ($this->generators as $generator) {
$path = $ctx->configPath($generator->outputPath());
$dir = \dirname($path);
if (! is_dir($dir)) {
mkdir($dir, 0o755, true);
}
file_put_contents($path, $generator->generate($ctx));
++$count;
}
$this->appendGitIgnore($ctx);
return $count;
}
/**
* Install dev tools into `.kcode/vendor/` by running Composer.
*
* Reads the `.kcode/composer.json` manifest generated by `KcodeComposerGenerator`
* and runs `composer install --working-dir=.kcode/` so tools are available
* at `.kcode/vendor/bin/` for Tier-1 binary resolution.
*
* Output streams live to the user's terminal via STDIN/STDOUT/STDERR passthrough.
*
* @return int Composer exit code (0 = success)
*
* @since 1.0.0
*/
public function installTools(string $workingDirectory = '.'): int
{
$context = $this->context($workingDirectory);
$devkitDirectory = $context->devkitDir;
$composerManifestPath = $devkitDirectory . \DIRECTORY_SEPARATOR . 'composer.json';
if (! is_file($composerManifestPath)) {
// KcodeComposerGenerator not registered — nothing to install
return 0;
}
$composerBinary = $this->composerResolver->resolve();
$command = [
$composerBinary,
'install',
'--working-dir=' . $devkitDirectory,
'--no-interaction',
'--prefer-dist',
'--optimize-autoloader',
'--no-scripts',
];
$process = proc_open(
$command,
[0 => \STDIN, 1 => \STDOUT, 2 => \STDERR],
$pipes,
$workingDirectory,
);
if (! \is_resource($process)) {
return 1;
}
return proc_close($process);
}
// ── Run ───────────────────────────────────────────────────────
/** @param list<string> $arguments */
public function run(string $toolName, array $arguments = []): ToolResult
{
$runner = $this->runners[$toolName] ?? null;
if (null === $runner) {
throw new DevkitException(\sprintf(
'Unknown tool "%s". Available: %s',
$toolName,
implode(', ', array_keys($this->runners)),
));
}
return $runner->run($arguments);
}
/** Check if a tool runner is registered and its binary is available. */
public function isToolAvailable(string $toolName): bool
{
return isset($this->runners[$toolName]) && $this->runners[$toolName]->isAvailable();
}
// ── Quality Pipeline ──────────────────────────────────────────
/**
* Full quality pipeline: cs-check → analyse → test.
*
* Skips unavailable tools instead of failing.
*
* @param list<string> $onlyTools Restrict to these tools (empty = all).
*/
public function quality(array $onlyTools = []): QualityReport
{
$pipeline = [] !== $onlyTools
? $onlyTools
: ['cs-fixer', 'phpstan', 'psalm', 'phpunit'];
$results = [];
foreach ($pipeline as $tool) {
if (! $this->isToolAvailable($tool)) {
continue;
}
$extraArgs = match ($tool) {
'cs-fixer' => ['--dry-run', '--diff'],
'rector' => ['--dry-run'],
default => [],
};
$results[] = $this->run($tool, $extraArgs);
}
return new QualityReport($results);
}
// ── Clean ─────────────────────────────────────────────────────
public function clean(string $workingDirectory = '.'): void
{
$buildDir = $this->context($workingDirectory)->buildDir;
if (is_dir($buildDir)) {
$this->removeRecursive($buildDir);
}
mkdir($buildDir, 0o755, true);
}
/** @return list<string> */
public function registeredTools(): array
{
return array_keys($this->runners);
}
// ── Internals ─────────────────────────────────────────────────
private function ensureDirectories(ProjectContext $ctx): void
{
foreach ([$ctx->devkitDir, $ctx->buildDir] as $dir) {
if (! is_dir($dir) && ! mkdir($dir, 0o755, true)) {
throw DevkitException::directoryNotWritable($dir);
}
}
}
private function appendGitIgnore(ProjectContext $ctx): void
{
$gitignore = $ctx->projectRoot . \DIRECTORY_SEPARATOR . '.gitignore';
$entry = '.kcode/';
// Create .gitignore if it doesn't exist
if (! is_file($gitignore)) {
file_put_contents(
$gitignore,
'# KaririCode Devkit — generated configs and build artifacts' . \PHP_EOL
. $entry . \PHP_EOL,
);
return;
}
$content = file_get_contents($gitignore);
if (false === $content) {
return;
}
// Already covered
if (str_contains($content, $entry)) {
return;
}
// Migrate: if old .kcode/build/ entry exists, replace with .kcode/
$legacyEntry = '.kcode/build/';
if (str_contains($content, $legacyEntry)) {
$content = str_replace($legacyEntry, $entry, $content);
file_put_contents($gitignore, $content);
return;
}
file_put_contents(
$gitignore,
\PHP_EOL . '# KaririCode Devkit — generated configs and build artifacts' . \PHP_EOL
. $entry . \PHP_EOL,
\FILE_APPEND,
);
}
private function removeRecursive(string $dir): void
{
$items = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($dir, \FilesystemIterator::SKIP_DOTS),
\RecursiveIteratorIterator::CHILD_FIRST,
);
foreach ($items as $item) {
/** @var \SplFileInfo $item */
$item->isDir() ? rmdir($item->getPathname()) : unlink($item->getPathname());
}
rmdir($dir);
}
}