From 1422d96c80b78882507d1aaafd3a350cfba74f05 Mon Sep 17 00:00:00 2001 From: Sieciech Date: Sat, 28 Aug 2021 19:28:15 +0000 Subject: [PATCH] tools (#31) fix fix fix fix fix fix fix put env tool tools Co-authored-by: Sieciech Reviewed-on: http://git.fufle.net/Community/CureNet/pulls/31 Co-Authored-By: Sieciech Co-Committed-By: Sieciech --- tools/putenv/env | 5 +++ tools/putenv/putenv.php | 80 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 85 insertions(+) create mode 100644 tools/putenv/env create mode 100644 tools/putenv/putenv.php diff --git a/tools/putenv/env b/tools/putenv/env new file mode 100644 index 0000000..d3123e4 --- /dev/null +++ b/tools/putenv/env @@ -0,0 +1,5 @@ +name=value +name2="value 2" +#name3=value3 +name4 = value4 +name5 = "value 5" \ No newline at end of file diff --git a/tools/putenv/putenv.php b/tools/putenv/putenv.php new file mode 100644 index 0000000..ae9698c --- /dev/null +++ b/tools/putenv/putenv.php @@ -0,0 +1,80 @@ +file = $argv[1]; + $this->key = $argv[2]; + $this->value = $argv[3]; + break; + + case 3: + $this->file = $argv[1]; + $this->key = $argv[2]; + $this->value = fgets(STDIN); + break; + + default: + echo "usage: + php8.0 putenv.php filename key value + echo value | php8.0 putenv filename key"; + throw new Exception("invalid params"); + } + if (!file_exists($this->file)) { + throw new Exception('File not found'); + } + $changed = 0; + $lineWasEmpty = false; + $key = $this->key; + $value = $this->value; + if (strpos($value, ' ') !== false) { + $value = '"' . addslashes($value) . '"'; + } + $this->content = file($this->file); + foreach ($this->content as $l => $line) { + if (strlen(trim($line)) < 1) { + if ($lineWasEmpty) { + $this->content[$l] = null; + } else { + $lineWasEmpty = true; + } + continue; + } + $lineWasEmpty = false; + if (!str_starts_with($line, $this->key)) { + continue; + } + $next = trim(substr($line, strlen($this->key))); + if (strlen($next) === 0 || $next[0] !== '=') { + continue; + } + $this->content[$l] = $key . '=' . $value; + $changed++; + } + if ($changed === 0) { + $this->content[] = $key . '=' . $value; + } else if ($changed > 1) { + echo "Key $key changed $changed times\n"; + } + $content = $this->content; + $this->content = []; + foreach ($content as $line) { + if ($line !== null) { + $this->content[] = $line; + } + } + $content = implode('', $this->content); + file_put_contents($this->file, $content); + } +} + +new PutEnv();