Passed
Push — master ( dc496c...d8d9f2 )
by Tom
02:40
created

Env::resetStepRunNumber()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
/* this file is part of pipelines */
4
5
namespace Ktomk\Pipelines\Runner;
6
7
use Ktomk\Pipelines\Cli\Args\Args;
8
use Ktomk\Pipelines\Cli\Args\Collector;
9
use Ktomk\Pipelines\Lib;
10
use Ktomk\Pipelines\LibFsPath;
11
12
/**
13
 * Pipeline environment collaborator
14
 */
15
class Env
16
{
17
    /**
18
     * @var array pipelines (bitbucket) environment variables
19
     */
20
    private $vars = array();
21
22
    /**
23
     * collected arguments
24
     *
25
     * @var array
26
     */
27
    private $collected = array();
28
29
    /**
30
     * environment variables to inherit from
31
     *
32
     * @var array
33
     */
34
    private $inherit = array();
35
36
    /**
37
     * @var EnvResolver
38
     */
39
    private $resolver;
40
41
    /**
42
     * create with no default initialization
43
     *
44
     * @param null|array $inherit
45
     *
46
     * @return Env
47
     */
48 3
    public static function create(array $inherit = null)
49
    {
50 3
        $env = new self();
51 3
        $env->initInherit((array)$inherit);
52
53 3
        return $env;
54
    }
55
56
    /**
57
     * @param null|array $inherit
58
     *
59
     * @return Env
60
     */
61 18
    public static function createEx(array $inherit = null)
62
    {
63 18
        $env = new self();
64 18
        $env->initDefaultVars((array)$inherit);
65
66 18
        return $env;
67
    }
68
69
    /**
70
     * @param array $vars
71
     *
72
     * @return array w/ a string variable definition (name=value) per value
73
     */
74 13
    public static function createVarDefinitions(array $vars)
75
    {
76 13
        $array = array();
77
78 13
        foreach ($vars as $name => $value) {
79 11
            if (isset($value)) {
80 11
                $array[] = sprintf('%s=%s', $name, $value);
81
            }
82
        }
83
84 13
        return $array;
85
    }
86
87
    /**
88
     * @param string $option "-e" typically for Docker binary
89
     * @param array $vars variables as hashmap
90
     *
91
     * @return array of options (from $option) and values, ['-e', 'val1', '-e', 'val2', ...]
92
     */
93 13
    public static function createArgVarDefinitions($option, array $vars)
94
    {
95 13
        $args = array();
96
97 13
        foreach (self::createVarDefinitions($vars) as $definition) {
98 11
            $args[] = $option;
99 11
            $args[] = $definition;
100
        }
101
102 13
        return $args;
103
    }
104
105
    /**
106
     * Initialize default environment used in a Bitbucket Pipeline
107
     *
108
     * As the runner mimics some values, defaults are available
109
     *
110
     * @param array $inherit Environment variables to inherit from
111
     *
112
     * @return void
113
     */
114 23
    public function initDefaultVars(array $inherit)
115
    {
116 23
        $this->initInherit($inherit);
117
118
        $inheritable = array(
119 23
            'BITBUCKET_BOOKMARK' => null,
120
            'BITBUCKET_BRANCH' => null,
121 23
            'BITBUCKET_BUILD_NUMBER' => '0',
122 23
            'BITBUCKET_COMMIT' => '0000000000000000000000000000000000000000',
123 23
            'BITBUCKET_REPO_OWNER' => '' . Lib::r($inherit['USER'], 'nobody'),
124 23
            'BITBUCKET_REPO_SLUG' => 'local-has-no-slug',
125 23
            'BITBUCKET_STEP_RUN_NUMBER' => '1',
126
            'BITBUCKET_TAG' => null,
127 23
            'CI' => 'true',
128
            'PIPELINES_CONTAINER_NAME' => null,
129
            'PIPELINES_IDS' => null,
130
            'PIPELINES_PARENT_CONTAINER_NAME' => null,
131
            'PIPELINES_PIP_CONTAINER_NAME' => null,
132
            'PIPELINES_PROJECT_PATH' => null,
133
        );
134
135
        $invariant = array(
136 23
            'PIPELINES_ID' => null,
137
        );
138
139 23
        $var = $invariant + array_intersect_key(array_filter($inherit, 'is_string'), $inheritable) + $inheritable;
140 23
        ksort($var);
141
142 23
        $this->vars = $var;
143 23
    }
144
145
    /**
146
     * Map reference to environment variable setting
147
     *
148
     * Only add the BITBUCKET_BOOKMARK/_BRANCH/_TAG variable
149
     * if not yet set.
150
     *
151
     * @param Reference $ref
152
     *
153
     * @return void
154
     */
155 4
    public function addReference(Reference $ref)
156
    {
157 4
        if (null === $type = $ref->getType()) {
158 2
            return;
159
        }
160
161
        $map = array(
162 4
            'bookmark' => 'BITBUCKET_BOOKMARK',
163
            'branch' => 'BITBUCKET_BRANCH',
164
            'tag' => 'BITBUCKET_TAG',
165
            'pr' => 'BITBUCKET_BRANCH',
166
        );
167
168 4
        if (!isset($map[$type])) {
169 1
            throw new \UnexpectedValueException(sprintf('Unknown reference type: "%s"', $type));
170
        }
171
172 3
        if ($this->addPrReference($ref)) {
173 1
            return;
174
        }
175
176 2
        $this->addVar($map[$type], $ref->getName());
177 2
    }
178
179
    /**
180
     * add a variable if not yet set (real add new)
181
     *
182
     * @param string $name
183
     * @param string $value
184
     *
185
     * @return void
186
     */
187 3
    public function addVar($name, $value)
188
    {
189 3
        if (!isset($this->vars[$name])) {
190 2
            $this->vars[$name] = $value;
191
        }
192 3
    }
193
194
    /**
195
     * @param Reference $reference
196
     *
197
     * @return bool
198
     */
199 3
    public function addPrReference(Reference $reference)
200
    {
201 3
        if ('pr' !== $reference->getType()) {
202 2
            return false;
203
        }
204
205 1
        $var = array_combine(
206 1
            array('BITBUCKET_BRANCH', 'BITBUCKET_PR_DESTINATION_BRANCH'),
207 1
            explode(':', $reference->getName(), 2) + array(null, null)
208
        );
209
210 1
        foreach ($var as $name => $value) {
211 1
            isset($value) && $this->addVar($name, $value);
212
        }
213
214 1
        return true;
215
    }
216
217
    /**
218
     * @param string $name of container
219
     *
220
     * @return void
221
     */
222 2
    public function setContainerName($name)
223
    {
224 2
        if (isset($this->vars['PIPELINES_CONTAINER_NAME'])) {
225 2
            $this->vars['PIPELINES_PARENT_CONTAINER_NAME']
226 2
                = $this->vars['PIPELINES_CONTAINER_NAME'];
227
        }
228
229 2
        $this->vars['PIPELINES_CONTAINER_NAME'] = $name;
230 2
        $this->setFirstPipelineVariable('PIPELINES_PIP_CONTAINER_NAME', $name);
231 2
    }
232
233
    /**
234
     * set the pipelines environment's running pipeline id
235
     *
236
     * @param string $id of pipeline, e.g. "default" or "branch/feature/*"
237
     *
238
     * @return bool whether was used before (endless pipelines in pipelines loop)
239
     */
240 2
    public function setPipelinesId($id)
241
    {
242 2
        $list = (string)$this->getValue('PIPELINES_IDS');
243 2
        $hashes = preg_split('~\s+~', $list, -1, PREG_SPLIT_NO_EMPTY);
244 2
        $hashes = array_map('strtolower', /** @scrutinizer ignore-type */ $hashes);
245
246 2
        $idHash = md5($id);
247 2
        $hasId = in_array($idHash, $hashes, true);
248 2
        $hashes[] = $idHash;
249
250 2
        $this->vars['PIPELINES_ID'] = $id;
251 2
        $this->vars['PIPELINES_IDS'] = implode(' ', $hashes);
252
253 2
        return $hasId;
254
    }
255
256
    /**
257
     * $BITBUCKET_STEP_RUN_NUMBER can be inherited from environment and after
258
     * the first step did run is being reset to 1
259
     *
260
     * allows to test it for steps `BITBUCKET_STEP_RUN_NUMBER=2 pipelines --step 1-`
261
     */
262 1
    public function resetStepRunNumber()
263
    {
264 1
        $this->vars['BITBUCKET_STEP_RUN_NUMBER'] = '1';
265 1
    }
266
267
    /**
268
     * set PIPELINES_PROJECT_PATH
269
     *
270
     * can never be overwritten, must be set by pipelines itself for the
271
     * initial pipeline. will be taken over into each sub-pipeline.
272
     *
273
     * @param string $path absolute path to the project directory (deploy source path)
274
     *
275
     * @return void
276
     */
277 2
    public function setPipelinesProjectPath($path)
278
    {
279 2
        if (!LibFsPath::isAbsolute($path)) {
280 1
            throw new \InvalidArgumentException(sprintf('not an absolute path: "%s"', $path));
281
        }
282
283 1
        $this->setFirstPipelineVariable('PIPELINES_PROJECT_PATH', $path);
284 1
    }
285
286
    /**
287
     * @param string $option "-e" typically for Docker binary
288
     *
289
     * @return array of options (from $option) and values, ['-e', 'val1', '-e', 'val2', ...]
290
     */
291 13
    public function getArgs($option)
292
    {
293 13
        return Lib::merge(
294 13
            $this->collected,
295 13
            self::createArgVarDefinitions($option, $this->vars)
296
        );
297
    }
298
299
    /**
300
     * get a variables' value from the inherited
301
     * environment or null if not set
302
     *
303
     * @param string $name
304
     *
305
     * @return null|string
306
     */
307 1
    public function getInheritValue($name)
308
    {
309 1
        return isset($this->inherit[$name])
310 1
            ? $this->inherit[$name]
311 1
            : null;
312
    }
313
314
    /**
315
     * get a variables value or null if not set
316
     *
317
     * @param string $name
318
     *
319
     * @return null|string
320
     */
321 8
    public function getValue($name)
322
    {
323 8
        return isset($this->vars[$name])
324 7
            ? $this->vars[$name]
325 8
            : null;
326
    }
327
328
    /**
329
     * collect option arguments
330
     *
331
     * those options to be passed to docker client, normally -e,
332
     * --env and --env-file.
333
     *
334
     * @param Args $args
335
     * @param string|string[] $option
336
     *
337
     * @throws \InvalidArgumentException
338
     * @throws \Ktomk\Pipelines\Cli\ArgsException
339
     *
340
     * @return void
341
     */
342 2
    public function collect(Args $args, $option)
343
    {
344 2
        $collector = new Collector($args);
345 2
        $collector->collect($option);
346 2
        $this->collected = array_merge($this->collected, $collector->getArgs());
347
348 2
        $this->getResolver()->addArguments($collector);
349 2
    }
350
351
    /**
352
     * @param array $paths
353
     *
354
     * @throws \InvalidArgumentException
355
     *
356
     * @return void
357
     */
358 2
    public function collectFiles(array $paths)
359
    {
360 2
        $resolver = $this->getResolver();
361 2
        foreach ($paths as $path) {
362 2
            if ($resolver->addFileIfExists($path)) {
363 2
                $this->collected[] = '--env-file';
364 2
                $this->collected[] = $path;
365
            }
366
        }
367 2
    }
368
369
    /**
370
     * @return EnvResolver
371
     */
372 6
    public function getResolver()
373
    {
374 6
        if (null === $this->resolver) {
375 6
            $this->resolver = new EnvResolver($this->inherit);
376
        }
377
378 6
        return $this->resolver;
379
    }
380
381
    /**
382
     * get all variables collected so far
383
     *
384
     * @return array
385
     */
386 2
    public function getVariables()
387
    {
388 2
        return (array)$this->getResolver()->getVariables();
389
    }
390
391
    /**
392
     * @param array $inherit
393
     *
394
     * @return void
395
     */
396 24
    private function initInherit(array $inherit)
397
    {
398 24
        $this->inherit = array_filter($inherit, 'is_string');
399 24
    }
400
401
    /**
402
     * set an environment variable only if not yet set and in the first
403
     * pipeline.
404
     *
405
     * @param string $name
406
     * @param string $value
407
     *
408
     * @return void
409
     */
410 3
    private function setFirstPipelineVariable($name, $value)
411
    {
412 3
        if (isset($this->vars[$name])
413 3
            || !isset($this->vars['PIPELINES_ID'], $this->vars['PIPELINES_IDS'])
414 3
            || $this->vars['PIPELINES_IDS'] !== md5($this->vars['PIPELINES_ID'])
415
        ) {
416 3
            return;
417
        }
418
419 1
        $this->vars[$name] = $value;
420 1
    }
421
}
422