This commit is contained in:
Tomas Mirchev 2025-10-30 09:48:00 +02:00
parent f5e7db5400
commit 11ea01a88f

357
barg.js
View File

@ -11,296 +11,297 @@ function join(...rest) {
return rest.filter((v) => !!v).join("."); return rest.filter((v) => !!v).join(".");
} }
function take_one(list) { function takeOne(list) {
return list.shift(); return list.shift();
} }
function take_all(list) { function takeAll(list) {
const all = [...list]; const all = list.slice();
list.length = 0; list.length = 0;
return all; return all;
} }
function map(key, cases, options = { error: true }) {
const DEFAULT = "_";
const hasKey = key != null && cases.hasOwnProperty(key);
const hasDefault = cases.hasOwnProperty(DEFAULT);
if (!hasKey && !hasDefault) {
if (options.error) {
throw new Error(`Invalid map key "${key}". Valid keys: ${Object.keys(cases).join(", ")}`);
}
return null;
}
return cases[hasKey ? key : DEFAULT];
}
function tokenize(input) { function tokenize(input) {
const raw_tokens = input.trim().split(/\s+/).slice(1); // skip command const args = input.trim().split(/\s+/);
const tokens = []; const root = args.shift();
const tokens = [`root::${root}`];
while (raw_tokens.length) { while (args.length) {
const raw_token = take_one(raw_tokens); const token = takeOne(args);
if (raw_token === "--") { // Rest
tokens.push(`rest::${take_all(raw_tokens).join(" ")}`); if (token === "--") {
tokens.push(`rest::${takeAll(args).join(" ")}`);
break; break;
} }
let key; // Named Argument + Value: Option or Flag (long variant)
let value; if (token.startsWith("--")) {
const [key, value] = token.slice(2).split("=");
if (raw_token.startsWith("--")) {
[key, value] = raw_token.slice(2).split("=");
tokens.push(`narg::${key}`); tokens.push(`narg::${key}`);
} else if (raw_token.startsWith("-")) { if (value) tokens.push(`value::${value}`);
[key, value] = raw_token.slice(1).split("="); continue;
tokens.push(...key.split("").map((k) => `narg::${k}`));
} else {
tokens.push(`unk::${raw_token}`);
} }
if (value !== undefined) { // Named Argument + Value: Option or Flag (short variant)
tokens.push(`value::${value}`); if (token.startsWith("-")) {
const [flags, value] = token.slice(1).split("=");
tokens.push(...flags.split("").map((f) => `narg::${f}`));
if (value) tokens.push(`value::${value}`);
continue;
} }
// Unknown: Command, Positional or Value
tokens.push(`unk::${token}`);
} }
return tokens; return tokens;
} }
function parse_input(spec, input) { function parseInput(spec, input) {
const tokens = tokenize(input); const tokens = tokenize(input);
const s = {};
const a = {};
const schema = {}; let _id = 100;
const alias_map = {}; let level = -1;
let pos = [];
let cmds = [];
let position = [0]; function generateSchema() {
let level = 0;
let commands = [];
function ref(...rest) {
return commands.slice(0, level).concat(rest).join(".");
}
function get_entry_ref(key) {
return alias_map[ref(key)];
}
function get_entry_item(...keys) {
return schema[join(...keys)];
}
function generate_schema() {
for (const entry of spec) { for (const entry of spec) {
const elements = entry.split(";"); const elements = entry.split(";");
const type = elements.shift(); const type = elements.shift();
switch (type) { map(type, {
case "command": { command: () => {
const id = String(_id++);
const aliases = elements.shift().split(","); const aliases = elements.shift().split(",");
const name = aliases[0];
const help = elements.shift(); const help = elements.shift();
// Schema // Schema
schema[ref(name, "type")] = "command"; s[join(id, "entryType")] = "command";
schema[ref(name, "help")] = help; s[join(id, "name")] = aliases[0];
s[join(id, "help")] = help;
s[join(id, "args")] = "";
// Alias // Alias
for (const alias of aliases) { if (cmds.length === 0) {
alias_map[ref(`unk::${alias}`)] = ref(name); a[`cmd::root`] = id;
} else {
aliases.forEach((alias) => (a[join(cmds.at(-1), `cmd::${alias}`)] = id));
} }
// Control // Control
commands.push(name);
level += 1; level += 1;
position.push(0); cmds.push(id);
break; pos.push(0);
} },
case "end": { end: () => {
level -= 1; level -= 1;
commands.pop(); cmds.pop();
position.pop(); pos.pop();
break; },
} argument: () => {
case "argument": { const id = String(_id++);
let aliases = elements.shift().split(","); const aliases = elements.shift().split(",");
let name = aliases[0]; const name = aliases[0];
const entry = { name, dest: name, required: false, kind: "positional" }; // Attributes
const entry = { name, dest: name, required: false, type: "positional" };
for (const element of elements) { for (const element of elements) {
const [attribute, attr_value] = element.split(":"); const [key, value = true] = element.split(":");
entry[key === "default" ? "value" : key] = value;
if (attribute === "required") entry.required = true;
else if (attribute === "repeatable") entry.repeatable = true;
else if (attribute === "help") entry.help = attr_value;
else if (attribute === "dest") entry.dest = attr_value;
else if (attribute === "type") entry.kind = attr_value;
else if (attribute === "default") entry.value = attr_value;
}
// Alias
if (entry.kind === "positional") {
name = String(position[level]++);
aliases = [`pos::${name}`];
} else if (entry.kind === "rest") {
aliases = ["__rest"];
}
for (const alias of aliases) {
if (entry.kind === "option" || entry.kind === "flag") {
alias_map[ref(`narg::${alias}`)] = ref(name);
} else {
alias_map[ref(alias)] = ref(name);
}
} }
// Schema // Schema
schema[ref(name, "type")] = "argument"; s[join(id, "entryType")] = "argument";
for (const [key, value] of Object.entries(entry)) { Object.entries(entry).forEach(([key, value]) => {
schema[ref(name, key)] = value; s[join(id, key)] = value;
} });
// Register arg to command // Register to command
if (schema[ref("args")]) { const cmdArgs = join(cmds.at(-1), "args");
schema[ref("args")] += `,${name}`; s[cmdArgs] += s[cmdArgs] ? `,${id}` : id;
} else {
schema[ref("args")] = `${name}`;
}
break; // Alias
} map(entry.type, {
default: positional: () => [`pos::${pos[level]++}`],
throw new Error(`Invalid entry type: '${type}'`); rest: () => ["rest"],
} option: () => aliases.map((a) => `narg::${a}`),
flag: () => aliases.map((a) => `narg::${a}`),
})().forEach((alias) => (a[join(cmds.at(-1), alias)] = id));
},
_: () => {
throw new Error(`Invalid entry type: "${type}"`);
},
})();
} }
commands = [];
level = 0; level = 0;
position = [0]; pos = [];
cmds = [];
} }
function next_token_value() { generateSchema();
const token = take_one(tokens); // log({ s, a });
const [token_type, token_key] = token.split("::");
if (token_type !== "unk") {
throw new Error(`Expected option value, but got: ${token_type}. Token: '${token_key}'`);
}
return token_key;
}
generate_schema();
log({ schema, alias_map });
while (tokens.length > 0) { while (tokens.length > 0) {
const token = take_one(tokens); const taggedToken = takeOne(tokens);
const [token_type, token_key] = token.split("::"); const [tokenTag, token] = taggedToken.split("::");
// Bubble up arguments -> Loop over all command levels starting by the latest // Bubble up arguments -> Loop over all command levels starting by the latest
let found = false; let found = false;
for (level = position.length - 1; level >= 0; level--) { for (level = Math.max(0, cmds.length - 1); level >= 0; level--) {
let entry_ref = get_entry_ref(token); const entryId = map(tokenTag, {
root: () => a["cmd::root"],
rest: () => a[join(cmds[level], "rest")],
narg: () => a[join(cmds[level], taggedToken)],
unk: () => {
// check: Command
let id = a[join(cmds[level], `cmd::${token}`)];
// Check for rest argument // check: Positionl. Valid only on last command level
if (token_type === "rest") { if (!id && level === pos.length - 1) {
entry_ref = get_entry_ref("__rest"); id = a[join(cmds[level], `pos::${pos[level]}`)];
} if (id) pos[level]++;
}
if (token_type === "narg") { return id;
entry_ref = get_entry_ref(token); },
} })();
if (!entry_ref && level === position.length - 1 && token_type === "unk") {
// Positional arguments are valid only for the latest command
entry_ref = get_entry_ref(`pos::${position[level]}`);
if (entry_ref) {
position[level] += 1;
}
}
// Try with parent command // Try with parent command
if (!entry_ref) { if (!entryId) continue;
continue;
}
const entry_type = get_entry_item(entry_ref, "type"); // Add
if (entry_type === "command") { const entryType = s[join(entryId, "entryType")];
commands.push(token_key); map(entryType, {
position.push(0); command: () => {
} else if (entry_type === "argument") { cmds.push(entryId);
const kind = get_entry_item(entry_ref, "kind"); pos.push(0);
if (tokenTag === "root") {
let value; s[join(entryId, "name")] = token;
if (kind === "flag") value = true; }
else if (kind === "option") value = next_token_value(); },
else if (kind === "positional") value = token_key; argument: () => {
else if (kind === "rest") value = token_key; const attrType = s[join(entryId, "type")];
else throw new Error(`Invalid attribute type: '${kind}'`); const value = map(attrType, {
rest: () => token,
schema[join(entry_ref, "value")] = value; positional: () => token,
} flag: () => true,
option: () => {
const nTaggedToken = tokens[0];
if (!nTaggedToken) {
throw new Error(`No value provided for option argument: "${token}"`);
}
const [nTokenTag, nToken] = nTaggedToken.split("::");
if (nTokenTag !== "value" && nTokenTag !== "unk") {
throw new Error(
`Expected option argument, but got: "${nToken}" (${nTokenTag}). Skipping...`,
);
}
tokens.shift();
return nToken;
},
})();
s[join(entryId, "value")] = value;
},
})();
found = true; found = true;
break; break;
} }
if (!found) { if (!found) {
console.log(`> Skipping invalid argument: (${token_type}) '${token_key}'`); console.log(`Invalid argument: "${token}" (${tokenTag}). Skipping...`);
} }
} }
// Check required // Set values and check required
const commands = [];
const values = {}; const values = {};
let id = ""; for (const cmdId of cmds) {
for (const command of commands) { let cmdName = s[join(cmdId, "name")];
id = join(id, command); let cmdArgs = s[join(cmdId, "args")];
let command_args = schema[join(id, "args")]; if (!cmdArgs) continue;
if (!command_args) {
continue;
}
for (const arg of command_args.split(",")) { for (const argId of cmdArgs.split(",")) {
const name = schema[join(id, arg, "name")]; const name = s[join(argId, "name")];
const dest = schema[join(id, arg, "dest")]; const dest = s[join(argId, "dest")];
const value = schema[join(id, arg, "value")]; const value = s[join(argId, "value")];
const required = schema[join(id, arg, "required")]; const required = s[join(argId, "required")];
if (value === undefined && required) { if (value == null && required) {
throw new Error(`Argument '${name}' is required in command '${command}'`); throw new Error(`Argument "${name}" is required in command "${cmdName}"`);
} }
if (values[dest] !== undefined) { if (values[dest] != null) {
values[`${command}_${dest}`] = value; values[`${cmdName}_${dest}`] = value;
} else { } else {
values[dest] = value; values[dest] = value;
} }
} }
commands.push(cmdName);
} }
log({ commands, values }); log({ commands, values });
return values; return values;
} }
function parse_input_wrap(spec, input) { function parseInputWrap(spec, input) {
try { try {
parse_input(spec, input); parseInput(spec, input);
} catch (error) { } catch (error) {
console.error(`Error: ${error.message}`); console.error(`Error: ${error.message}`);
} }
} }
const SPEC = [ const SPEC = [
"command;barg;Barg - Bash Argument Parser",
"argument;global;type:flag",
"command;build;Build a dev container", "command;build;Build a dev container",
"argument;from;type:option;dest:from_name;help:Name of the base container", "argument;from;type:option;dest:fromName;help:Name of the base container",
"argument;name;type:positional;required;help:Name of the container", "argument;name;type:positional;required;help:Name of the container",
"argument;nametwo;help:Name of the container", "argument;nametwo;help:Name of the container",
"argument;image,i;type:option;required;dest:image_name;help:Base image", "argument;image,i;type:option;required;dest:imageName;help:Base image",
"argument;include,I;type:option;repeatable;dest:include_paths;help:Include paths", "argument;include,I;type:option;repeatable;dest:includePaths;help:Include paths",
"argument;verbose,v;type:flag;repeatable;default:0;help:Increase verbosity (-v, -vv, ...)", "argument;verbose,v;type:flag;repeatable;default:0;help:Increase verbosity (-v, -vv, ...)",
"argument;quiet,q;type:flag;default:false;help:Suppress all output", "argument;quiet,q;type:flag;default:false;help:Suppress all output",
"argument;cmd;type:rest;help:Command and args to run inside the container", "argument;cmd;type:rest;help:Command and args to run inside the container",
"argument;name;dest:name_opt;type:option;help:Building container name", "argument;name;dest:nameOpt;type:option;help:Building container name",
"command;container;Container building", "command;container;Container building",
"argument;dev;type:flag;help:Is dev or not", "argument;dev;type:flag;help:Is dev or not",
"argument;name;required;help:Building container name", "argument;name;required;help:Building container name",
"argument;cmd;type:rest;dest:cmd_rest;help:Command and args to run inside the container", "argument;cmd;type:rest;dest:cmdRest;help:Command and args to run inside the container",
"end", "end",
"end", "end",
"command;stop;Stop a dev container", "command;stop;Stop a dev container",
"argument;name;type:positional;required;help:Name of the container", "argument;name;type:positional;required;help:Name of the container",
"argument;kill,k;type:flag;default:false;help:Force kill the container", "argument;kill,k;type:flag;default:false;help:Force kill the container",
"end", "end",
"end",
]; ];
const INPUTS = [ const INPUTS = [
"dev build -i myimage buildtwo --from base-dev --image node:18 --include src --include test -v -v -q mycontainer -- npm run start", "dev build -i myimage buildtwo --from base-dev --image node:18 --include src --include test -v -v -q mycontainer -- npm run start",
"dev build buildname container -i myimage --dev --name webapp externalContainer", "dev build buildname container -i myimage --dev --name webapp externalContainer",
"dev build --image debian mybox container --dev --name webapp externalContainer -- echo hi", "dev --global build --image debian mybox container --dev --name webapp externalContainer -- echo hi",
"dev stop mycontainer --kill", "dev stop mycontainer --kill",
"dev stop mycontainer --kill -- not specified one", "dev stop mycontainer --kill -- not specified one",
"dev build --from alpine --image node:20 mybox -- echo hi", "dev build --from alpine --image node:20 mybox -- echo hi",
@ -310,5 +311,5 @@ const INPUTS = [
INPUTS.forEach((input) => { INPUTS.forEach((input) => {
console.log("\n\n------------------------\n"); console.log("\n\n------------------------\n");
console.log("> ", input); console.log("> ", input);
parse_input_wrap(SPEC, input); parseInputWrap(SPEC, input);
}); });