From 97759229754c7c4bdf411e15043b5e37c06aeff0 Mon Sep 17 00:00:00 2001 From: Thomas Gelf Date: Wed, 20 Jul 2022 06:37:06 +0200 Subject: [PATCH] ObjectCommand: support JSON via STDIN fixes #1570 --- doc/60-CLI.md | 6 ++++++ doc/82-Changelog.md | 1 + library/Director/Cli/ObjectCommand.php | 24 ++++++++++++++++++++++++ 3 files changed, 31 insertions(+) diff --git a/doc/60-CLI.md b/doc/60-CLI.md index 4a3bf31e..59944af0 100644 --- a/doc/60-CLI.md +++ b/doc/60-CLI.md @@ -75,6 +75,12 @@ icingacli director host create localhost \ --json '{ "address": "127.0.0.1", "vars": { "test": [ "one", "two" ] } }' ``` +Passing JSON via STDIN is also possible: + +```shell +icingacli director host create localhost --json < my-host.json +``` + ### Delete a specific object diff --git a/doc/82-Changelog.md b/doc/82-Changelog.md index 72d118ab..ea993fa3 100644 --- a/doc/82-Changelog.md +++ b/doc/82-Changelog.md @@ -27,6 +27,7 @@ v1.10.0 (unreleased) ### CLI * FIX: config deploy doesn't try to wait in case of no deployment (#2522) * FEATURE: improved wording for deployment error messages (#2523) +* FEATURE: JSON can now be shipped via STDIN (#1570) 1.9.1 ----- diff --git a/library/Director/Cli/ObjectCommand.php b/library/Director/Cli/ObjectCommand.php index 401757dc..84c4751b 100644 --- a/library/Director/Cli/ObjectCommand.php +++ b/library/Director/Cli/ObjectCommand.php @@ -441,12 +441,36 @@ class ObjectCommand extends Command protected function remainingParams() { if ($json = $this->params->shift('json')) { + if ($json === true) { + $json = $this->readFromStdin(); + if ($json === null) { + $this->fail('Please pass JSON either via STDIN or via --json'); + } + } return (array) $this->parseJson($json); } else { return $this->params->getParams(); } } + protected function readFromStdin() + { + if (!defined('STDIN')) { + define('STDIN', fopen("php://stdin","r")); + } + $inputIsTty = function_exists('posix_isatty') && posix_isatty(STDIN); + if ($inputIsTty) { + return null; + } + + $stdin = file_get_contents('php://stdin'); + if (strlen($stdin) === 0) { + return null; + } + + return $stdin; + } + protected function exists($name) { return IcingaObject::existsByType(