barg-parser/barg.js

315 lines
8.8 KiB
JavaScript

/**
* TODO:
* - Add logic for repeatable attribute
*/
function log(text) {
console.log(JSON.stringify(text, null, 2));
}
function join(...rest) {
return rest.filter((v) => !!v).join(".");
}
function take_one(list) {
return list.shift();
}
function take_all(list) {
const all = [...list];
list.length = 0;
return all;
}
function tokenize(input) {
const raw_tokens = input.trim().split(/\s+/).slice(1); // skip command
const tokens = [];
while (raw_tokens.length) {
const raw_token = take_one(raw_tokens);
if (raw_token === "--") {
tokens.push(`rest::${take_all(raw_tokens).join(" ")}`);
break;
}
let key;
let value;
if (raw_token.startsWith("--")) {
[key, value] = raw_token.slice(2).split("=");
tokens.push(`narg::${key}`);
} else if (raw_token.startsWith("-")) {
[key, value] = raw_token.slice(1).split("=");
tokens.push(...key.split("").map((k) => `narg::${k}`));
} else {
tokens.push(`unk::${raw_token}`);
}
if (value !== undefined) {
tokens.push(`value::${value}`);
}
}
return tokens;
}
function parse_input(spec, input) {
const tokens = tokenize(input);
const schema = {};
const alias_map = {};
let position = [0];
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) {
const elements = entry.split(";");
const type = elements.shift();
switch (type) {
case "command": {
const aliases = elements.shift().split(",");
const name = aliases[0];
const help = elements.shift();
// Schema
schema[ref(name, "type")] = "command";
schema[ref(name, "help")] = help;
// Alias
for (const alias of aliases) {
alias_map[ref(`unk::${alias}`)] = ref(name);
}
// Control
commands.push(name);
level += 1;
position.push(0);
break;
}
case "end": {
level -= 1;
commands.pop();
position.pop();
break;
}
case "argument": {
let aliases = elements.shift().split(",");
let name = aliases[0];
const entry = { name, dest: name, required: false, kind: "positional" };
for (const element of elements) {
const [attribute, attr_value] = element.split(":");
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[ref(name, "type")] = "argument";
for (const [key, value] of Object.entries(entry)) {
schema[ref(name, key)] = value;
}
// Register arg to command
if (schema[ref("args")]) {
schema[ref("args")] += `,${name}`;
} else {
schema[ref("args")] = `${name}`;
}
break;
}
default:
throw new Error(`Invalid entry type: '${type}'`);
}
}
commands = [];
level = 0;
position = [0];
}
function next_token_value() {
const token = take_one(tokens);
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) {
const token = take_one(tokens);
const [token_type, token_key] = token.split("::");
// Bubble up arguments -> Loop over all command levels starting by the latest
let found = false;
for (level = position.length - 1; level >= 0; level--) {
let entry_ref = get_entry_ref(token);
// Check for rest argument
if (token_type === "rest") {
entry_ref = get_entry_ref("__rest");
}
if (token_type === "narg") {
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
if (!entry_ref) {
continue;
}
const entry_type = get_entry_item(entry_ref, "type");
if (entry_type === "command") {
commands.push(token_key);
position.push(0);
} else if (entry_type === "argument") {
const kind = get_entry_item(entry_ref, "kind");
let value;
if (kind === "flag") value = true;
else if (kind === "option") value = next_token_value();
else if (kind === "positional") value = token_key;
else if (kind === "rest") value = token_key;
else throw new Error(`Invalid attribute type: '${kind}'`);
schema[join(entry_ref, "value")] = value;
}
found = true;
break;
}
if (!found) {
console.log(`> Skipping invalid argument: (${token_type}) '${token_key}'`);
}
}
// Check required
const values = {};
let id = "";
for (const command of commands) {
id = join(id, command);
let command_args = schema[join(id, "args")];
if (!command_args) {
continue;
}
for (const arg of command_args.split(",")) {
const name = schema[join(id, arg, "name")];
const dest = schema[join(id, arg, "dest")];
const value = schema[join(id, arg, "value")];
const required = schema[join(id, arg, "required")];
if (value === undefined && required) {
throw new Error(`Argument '${name}' is required in command '${command}'`);
}
if (values[dest] !== undefined) {
values[`${command}_${dest}`] = value;
} else {
values[dest] = value;
}
}
}
log({ commands, values });
return values;
}
function parse_input_wrap(spec, input) {
try {
parse_input(spec, input);
} catch (error) {
console.error(`Error: ${error.message}`);
}
}
const SPEC = [
"command;build;Build a dev container",
"argument;from;type:option;dest:from_name;help:Name of the base container",
"argument;name;type:positional;required;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;include,I;type:option;repeatable;dest:include_paths;help:Include paths",
"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;cmd;type:rest;help:Command and args to run inside the container",
"argument;name;dest:name_opt;type:option;help:Building container name",
"command;container;Container building",
"argument;dev;type:flag;help:Is dev or not",
"argument;name;required;help:Building container name",
"argument;cmd;type:rest;dest:cmd_rest;help:Command and args to run inside the container",
"end",
"end",
"command;stop;Stop a dev container",
"argument;name;type:positional;required;help:Name of the container",
"argument;kill,k;type:flag;default:false;help:Force kill the container",
"end",
];
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 buildname container -i myimage --dev --name webapp externalContainer",
"dev build --image debian mybox container --dev --name webapp externalContainer -- echo hi",
"dev stop mycontainer --kill",
"dev stop mycontainer --kill -- not specified one",
"dev build --from alpine --image node:20 mybox -- echo hi",
"dev build --aaaaa --from alpine --image node:20 --bbbbb orb mybox ccccc -- echo hi",
];
INPUTS.forEach((input) => {
console.log("\n\n------------------------\n");
console.log("> ", input);
parse_input_wrap(SPEC, input);
});