Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 3 additions & 18 deletions bin/new-command
Original file line number Diff line number Diff line change
Expand Up @@ -103,25 +103,10 @@ echo " $CMD"
echo " $CMD_TEST"
echo

# Register the command in src/app.phel. The edit is computed in full before
# anything is written; on an unexpected file shape nothing changes.
# Register the command in src/app.phel; fall back to manual steps if the file
# is not in the expected shape.
APP="src/app.phel"
# shellcheck disable=SC2016 # the PHP program is single-quoted on purpose
if php -d display_errors=stderr -r '
$file = $argv[1];
$name = $argv[2];
$src = file_get_contents($file);
if ($src === false || preg_match("/(?<![\\w-])$name-command(?![\\w-])/", $src)) { exit(1); }
$pattern = "/^ \\(:require cli-skeleton\\.commands\\.\\S+ :refer \\[[^\\]]+\\]\\)\\)$/m";
if (!preg_match_all($pattern, $src, $m, PREG_OFFSET_CAPTURE) || !$m[0]) { exit(1); }
[$last, $offset] = end($m[0]);
$new = " (:require cli-skeleton.commands.$name :refer [$name-command])";
$src = substr($src, 0, $offset) . substr($last, 0, -1) . "\n" . $new . ")" . substr($src, $offset + strlen($last));
$count = 0;
$src = preg_replace("/(\\n\\s+)([\\w?!*-]+)\\]\\}\\)\\)/", "\$1\$2\$1$name-command]}))", $src, 1, $count);
if ($count !== 1) { exit(1); }
if (file_put_contents($file, $src) === false) { exit(1); }
' "$APP" "$NAME" 2>/dev/null; then
if php bin/register-command "$APP" "$NAME" 2>/dev/null; then
[ -x vendor/bin/phel ] && vendor/bin/phel format "$APP" >/dev/null 2>&1 || true
echo "registered $NAME-command in $APP"
else
Expand Down
55 changes: 55 additions & 0 deletions bin/register-command
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
#!/usr/bin/env php
<?php

declare(strict_types=1);

/**
* Register a scaffolded command in the application file.
*
* Usage: bin/register-command <app-file> <name>
*
* Adds the `:require` and the `:commands` entry. The edit is computed in full
* before anything is written, so an unexpected file shape changes nothing.
* Exit 0 on success, 1 when the file could not be edited.
*/

const REQUIRE_LINE = '/^ \(:require cli-skeleton\.commands\.\S+ :refer \[[^\]]+\]\)\)$/m';
const LAST_COMMAND = '/(\n\s+)([\w?!*-]+)\]\}\)\)/';

function register(string $source, string $name): ?string
{
$symbol = $name . '-command';

if (preg_match('/(?<![\w-])' . preg_quote($symbol, '/') . '(?![\w-])/', $source) === 1) {
return null;
}

if (preg_match_all(REQUIRE_LINE, $source, $matches, PREG_OFFSET_CAPTURE) < 1) {
return null;
}

[$lastRequire, $offset] = end($matches[0]);
$newRequire = sprintf(' (:require cli-skeleton.commands.%s :refer [%s])', $name, $symbol);
$withRequire = substr($source, 0, $offset)
. substr($lastRequire, 0, -1) . "\n" . $newRequire . ')'
. substr($source, $offset + strlen($lastRequire));

$count = 0;
$registered = preg_replace(LAST_COMMAND, '$1$2$1' . $symbol . ']}))', $withRequire, 1, $count);

return $count === 1 ? $registered : null;
}

if ($argc !== 3) {
fwrite(STDERR, "usage: bin/register-command <app-file> <name>\n");
exit(2);
}

[, $file, $name] = $argv;

$source = is_readable($file) ? file_get_contents($file) : false;
$updated = $source === false ? null : register($source, $name);

if ($updated === null || @file_put_contents($file, $updated) === false) {
exit(1);
}
28 changes: 11 additions & 17 deletions src/commands/adder.phel
Original file line number Diff line number Diff line change
@@ -1,28 +1,22 @@
(ns cli-skeleton.commands.adder
(:require phel.cli :as cli)
(:require cli-skeleton.core.adder :refer [adder parse-int]))
(:require cli-skeleton.core.adder :refer [sum-tokens]))

;; COMMAND layer = IO boundary: parse args, print results. Math lives in core.

(defn- run-adder [ctx]
(let [tokens (cli/arg ctx "numbers")
invalid (filter (fn [token] (nil? (parse-int token))) tokens)]
(cond
(empty? tokens)
(let [tokens (cli/arg ctx "numbers")]
(if (empty? tokens)
(do (cli/warning ctx "Pass at least one number, e.g. `add 1 2 3`.")
1)

(seq invalid)
(do (cli/error ctx (str "Not an integer: " (php/implode ", " (to-php-array invalid))))
1)

:else
(let [total (apply adder (map parse-int tokens))]
(if (php/is_int total)
(do (cli/success ctx (str "Sum = " total))
0)
(do (cli/error ctx "Sum is too large for an integer.")
1))))))
(let [{:keys [total invalid overflow]} (sum-tokens tokens)]
(cond
invalid (do (cli/error ctx (str "Not an integer: " (php/implode ", " (to-php-array invalid))))
1)
overflow (do (cli/error ctx "Sum is too large for an integer.")
1)
:else (do (cli/success ctx (str "Sum = " total))
0))))))

(def adder-command
{:name "add"
Expand Down
13 changes: 13 additions & 0 deletions src/core/adder.phel
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,16 @@
floats, text, empty input, or a value outside the PHP integer range. Pure."
[s]
(php/filter_var s php/FILTER_VALIDATE_INT php/FILTER_NULL_ON_FAILURE))

(defn sum-tokens
"Sum integer tokens. Returns {:total n}, {:invalid [token ...]} when any token
is not an integer, or {:overflow true} when the sum leaves the integer range. Pure."
[tokens]
(let [parsed (map parse-int tokens)
invalid (filter some? (map (fn [token n] (when (nil? n) token)) tokens parsed))]
(if (seq invalid)
{:invalid (vec invalid)}
(let [total (apply adder parsed)]
(if (php/is_int total)
{:total total}
{:overflow true})))))
8 changes: 7 additions & 1 deletion tests/core/adder-test.phel
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
(ns cli-skeleton-tests.core.adder-test
(:require cli-skeleton.core.adder :refer [adder parse-int])
(:require cli-skeleton.core.adder :refer [adder parse-int sum-tokens])
(:require phel.test :refer [deftest is]))

;; CORE tests: pure logic, literal data in/out. No CLI harness, no mocks.
Expand All @@ -17,3 +17,9 @@
(is (nil? (parse-int "1.5")))
(is (nil? (parse-int "")))
(is (nil? (parse-int "9223372036854775808"))))

(deftest test-sum-tokens
(is (= {:total 6} (sum-tokens ["1" "2" "3"])))
(is (= {:total 1} (sum-tokens ["-1" "2"])))
(is (= {:invalid ["abc" "1.5"]} (sum-tokens ["1" "abc" "2" "1.5"])))
(is (= {:overflow true} (sum-tokens ["9223372036854775807" "1"]))))
Loading