Add encode subcommand

Wraps gid.encodeGid, prints the packed-u32 as decimal on stdout,
emits usage on stderr on bad arity, and a labelled error on
out-of-range or non-integer input.
This commit is contained in:
Axel Meyer
2026-05-23 13:46:03 +02:00
parent b1743ad19f
commit 7316ebc7dd
3 changed files with 87 additions and 1 deletions

View File

@@ -30,7 +30,7 @@ function run(argv, { out, err }) {
return 0;
}
const handlers = {
// populated in subsequent tasks
encode: require('./commands/encode'),
};
const handler = handlers[head];
if (!handler) {

32
src/commands/encode.js Normal file
View File

@@ -0,0 +1,32 @@
'use strict';
const { encodeGid } = require('../gid');
const USAGE = 'usage: sporel-mapper encode <atlas_idx> <tile_id> [rotation]\n';
function parseIntStrict(s, field) {
if (!/^-?\d+$/.test(s)) {
throw new RangeError(`${field} '${s}' is not an integer`);
}
return parseInt(s, 10);
}
function run(args, { out, err }) {
if (args.length < 2 || args.length > 3) {
err.write(USAGE);
return 1;
}
try {
const atlas = parseIntStrict(args[0], 'atlas');
const tile = parseIntStrict(args[1], 'tile');
const rotation = args.length === 3 ? parseIntStrict(args[2], 'rotation') : 0;
const gid = encodeGid(atlas, tile, rotation);
out.write(`${gid}\n`);
return 0;
} catch (e) {
err.write(`error: ${e.message}\n`);
return 1;
}
}
module.exports = { run };