-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDockerPipeFormatter.php
More file actions
197 lines (180 loc) · 5.31 KB
/
Copy pathDockerPipeFormatter.php
File metadata and controls
197 lines (180 loc) · 5.31 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
<?php declare(strict_types=1);
namespace uuf6429\PhpCsFixerBlockstring\Formatter;
use InvalidArgumentException;
use RuntimeException;
use uuf6429\PhpCsFixerBlockstring\InterpolationCodec\CodecInterface;
use uuf6429\PhpCsFixerBlockstring\LineEndingNormalizer\DefaultNormalizer;
use uuf6429\PhpCsFixerBlockstring\LineEndingNormalizer\NormalizerInterface;
use uuf6429\PhpCsFixerBlockstring\Process\ProcessFactoryInterface;
use uuf6429\PhpCsFixerBlockstring\Process\ProcessFailedException;
use uuf6429\PhpCsFixerBlockstring\Process\SymfonyProcessFactory;
/**
* The minimal setup, stable repeatability, and a rich ecosystem make Docker images an ideal source of formatting
* tools. This formatter exists to take advantage of that.
*
* Example:
*
* ```php
* return (new PhpCsFixer\Config())
* ->registerCustomFixers([new BlockStringFixer()])
* ->setRules([
* BlockStringFixer::NAME => BlockStringFixer::config([
* 'JSON' => new DockerPipeFormatter(
* // The docker image; might contain url, tag or even the digest.
* image: 'ghcr.io/jqlang/jq',
* // Optional docker arguments, such as for setting env vars.
* options: ['-e', 'SOME_ENV=value'],
* // The command to run within the container, including any arguments.
* command: ['bin/tool', '--dry-run', '-'],
* // How/when the image should be pulled: 'never', 'always' or 'missing'.
* pullMode: 'always',
* // A codec for handling interpolations; depends on the content being formatted.
* interpolationCodec: new PlainStringCodec(),
* // A normalizer for handling end-of-line characters.
* lineEndingNormalizer: null,
* // Factory for creating processes. Defaults to Symfony process factory.
* processFactory: null,
* )
* ]),
* ]);
* ```
*
* @phpstan-type TDockerImageDetails array{platform: string, digest: string}
*/
class DockerPipeFormatter extends AbstractStringFormatter
{
/**
* @readonly
*/
private string $image;
/**
* @readonly
* @var 'never'|'missing'|'always'
*/
private string $pullMode;
/**
* @readonly
* @var list<string>
*/
private array $options;
/**
* @readonly
* @var list<string>
*/
private array $command;
/**
* @readonly
* @var TDockerImageDetails
*/
private array $imageDetails;
/**
* @readonly
*/
private ProcessFactoryInterface $processFactory;
/**
* @param list<string> $options
* @param list<string> $command
* @param 'never'|'missing'|'always' $pullMode
*/
public function __construct(
string $image,
array $options = [],
array $command = [],
string $pullMode = 'never',
?CodecInterface $interpolationCodec = null,
?NormalizerInterface $lineEndingNormalizer = null,
?ProcessFactoryInterface $processFactory = null
) {
$this->image = $image;
$this->options = $options;
$this->command = $command;
$this->pullMode = $pullMode;
$this->processFactory = $processFactory ?? new SymfonyProcessFactory();
$this->imageDetails = $this->resolveImageDetails();
parent::__construct(
sprintf(
'%s: %s',
static::class,
implode(
' ',
array_merge(
["{$this->imageDetails['platform']};{$this->imageDetails['digest']}"],
$this->options,
$this->command
)
)
),
$interpolationCodec,
$lineEndingNormalizer ?? new DefaultNormalizer(DefaultNormalizer::LF, DefaultNormalizer::STRIP)
);
}
/**
* @return TDockerImageDetails
*/
private function resolveImageDetails(): array
{
switch ($this->pullMode) {
case 'never':
return $this->inspectImage(true);
case 'missing':
// @codeCoverageIgnoreStart
if (($result = $this->inspectImage(false)) !== null) {
return $result;
}
$this->pullImage();
return $this->inspectImage(true);
// @codeCoverageIgnoreEnd
case 'always':
$this->pullImage();
return $this->inspectImage(true);
default:
throw new InvalidArgumentException("Unsupported Pull Mode: {$this->pullMode}");
}
}
/**
* @return ($throwOnFailure is true ? TDockerImageDetails : null|TDockerImageDetails)
*/
private function inspectImage(bool $throwOnFailure): ?array
{
$process = $this->processFactory->create(
['docker', 'image', 'inspect', $this->image, '--format={{.Os}}/{{.Architecture}} {{.Id}}']
);
try {
$result = $process->mustRun()->getOutput();
$result = explode(' ', trim($result), 2);
return ['platform' => $result[0], 'digest' => $result[1]];
} catch (ProcessFailedException $ex) {
if (!$throwOnFailure) {
return null;
}
throw new RuntimeException(
"Could not inspect docker image \"$this->image\":\n{$process->getErrorOutput()}"
);
}
}
private function pullImage(): void
{
$this->processFactory
->create(['docker', 'image', 'pull', $this->image])
->mustRun();
}
protected function formatContent(string $original): string
{
return $this->processFactory
->create(
[
'docker',
'run',
'--rm',
'--interactive',
...$this->options,
$this->imageDetails['digest'],
...$this->command,
],
null,
null,
$original
)->mustRun()
->getOutput();
}
}