From e4839b41bf9c9de475044579caa3546cd443079e Mon Sep 17 00:00:00 2001 From: Misha Medzhytov Date: Sun, 3 Mar 2024 15:07:20 +0200 Subject: [PATCH] add support of multiple values in host label - example of usage: host('prod.example.org') ->set('hostname', 'example.cloud.google.com'); ->setLabel( 'state' => 'prod' 'role' => ['build','web','redis'] ]); host('prod-db.example.org') ->set('hostname', 'example.cloud.google.com'); ->setLabel( 'state' => 'prod' 'role' => ['db'] ]); host('qa.example.org') ->set('hostname', 'example.cloud.google.com'); ->setLabel( 'state' => 'qa' 'role' => ['build','web','redis','db'] ]); host('dev.example.org') ->set('hostname', 'example.cloud.google.com'); ->setLabel( 'state' => 'qa' 'role' => ['build','web','redis','db'] ]); ... desc('Clear pagespeed'); task('pagespeed:clear', function () { run("rm -rf {{deploy_path}}/{{pagespeed_path}}* || true"); })->select('stage=prod|qa & role=web'); // assuming pagespeed is installed only on prod and qa envs --- src/Host/Host.php | 7 +++++++ src/Selector/Selector.php | 14 ++++++++++++-- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/src/Host/Host.php b/src/Host/Host.php index 125c3adcb..6c008f268 100644 --- a/src/Host/Host.php +++ b/src/Host/Host.php @@ -212,6 +212,13 @@ public function setLabels(array $labels): self return $this; } + public function addLabels(array $labels): self + { + $existingLabels = $this->getLabels() ?? []; + $this->setLabels(array_replace_recursive($existingLabels, $labels)); + return $this; + } + public function getLabels(): ?array { return $this->config->get('labels', null); diff --git a/src/Selector/Selector.php b/src/Selector/Selector.php index c9be60472..1a0669e1a 100644 --- a/src/Selector/Selector.php +++ b/src/Selector/Selector.php @@ -57,7 +57,16 @@ public static function apply(?array $conditions, Host $host): bool foreach ($conditions as $hmm) { $ok = []; foreach ($hmm as list($op, $var, $value)) { - $ok[] = self::compare($op, $labels[$var] ?? null, $value); + if (is_array($value)) { + $orOk = []; + foreach ($value as $val) { + $orOk[] = self::compare($op, $labels[$var] ?? null, $val); + } + $ok[] = count(array_filter($orOk, $isTrue)) > 0; + } else { + $ok[] = self::compare($op, $labels[$var] ?? null, $value); + } + } if (count($ok) > 0 && array_all($ok, $isTrue)) { return true; @@ -102,7 +111,8 @@ public static function parse(string $expression): array continue; } if (preg_match('/(?.+?)(?!?=)(?.+)/', $part, $match)) { - $conditions[] = [$match['op'], trim($match['var']), trim($match['value'])]; + $values = array_map('trim', explode('|', trim($match['value']))); + $conditions[] = [$match['op'], trim($match['var']), $values]; } else { $conditions[] = ['=', 'alias', trim($part)]; }