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
32 changes: 27 additions & 5 deletions src/commands.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -36,20 +36,42 @@ async function deliver(type, data) {
}

export function defaultCommands() {
const expectNoArgs = (name, args) => {
if (args.length > 0) {
throw new Error(`moshscript: ${name}() does not take arguments`);
}
};

return {
code: (ctx) => ctx.out(" ⌨ code() → compiling features (no bugs)…"),
mosh: (ctx) => ctx.out(" 🤘 mosh() → opening the pit"),
code: (ctx, args) => {
expectNoArgs("code", args);
ctx.out(" ⌨ code() → compiling features (no bugs)…");
},
mosh: (ctx, args) => {
expectNoArgs("mosh", args);
ctx.out(" 🤘 mosh() → opening the pit");
},
notify: async (ctx, args) => {
const msg = args.length ? args.join(" ") : "moshcode ping 🤘";
ctx.out(` 🔔 notify() → ${msg}`);
if (ctx.dryRun) return;
const res = await deliver("moshscript.notify", { message: msg, iter: ctx.iter });
for (const r of res) if (!r.ok) ctx.out(` ! notify ${r.target} failed (${r.status || r.error})`);
},
repeat: (ctx) => ctx.out(" ↻ repeat() → back to the top"),
repeat: (ctx, args) => {
expectNoArgs("repeat", args);
ctx.out(" ↻ repeat() → back to the top");
},
// handy extras
say: (ctx, args) => ctx.out(` 💬 ${args.join(" ")}`),
sleep: async (_ctx, args) => { const ms = Number(args[0] || 0); if (ms > 0) await new Promise((r) => setTimeout(r, ms)); },
stop: (ctx) => { ctx.vars.alive = false; ctx.out(" ⏹ stop() → alive = false"); },
sleep: async (_ctx, args) => {
const ms = Number(args[0] || 0);
if (ms > 0) await new Promise((r) => setTimeout(r, ms));
},
stop: (ctx, args) => {
expectNoArgs("stop", args);
ctx.vars.alive = false;
ctx.out(" ⏹ stop() → alive = false");
},
};
}
36 changes: 36 additions & 0 deletions test/commands.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import assert from "node:assert/strict";
import test from "node:test";

import { defaultCommands } from "../src/commands.mjs";

function createCtx() {
return {
dryRun: true,
iter: 0,
vars: { alive: true },
lines: [],
out(line) {
this.lines.push(line);
},
};
}

for (const name of ["code", "mosh", "repeat", "stop"]) {
test(`${name}() rejects unexpected arguments`, async () => {
const commands = defaultCommands();
await assert.rejects(
async () => commands[name](createCtx(), ["extra"]),
new RegExp(`moshscript: ${name}\\(\\) does not take arguments`)
);
});
}

test("notify() still accepts message arguments", async () => {
const commands = defaultCommands();
const ctx = createCtx();

await commands.notify(ctx, ["hello", "there"]);

assert.equal(ctx.lines.length, 1);
assert.match(ctx.lines[0], /hello there/);
});
Loading