Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Abstract cli response logging, and add test coverage. #348

Merged
merged 4 commits into from
Jun 8, 2023
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
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@
"format": "npm run prettier:fix && npm run lint:fix",
"prepublishOnly": "npm run build",
"test": "mocha",
"coverage": "c8 mocha",
"coverage": "TEST_TIMEOUT_FACTOR=3 c8 --100 --exclude test mocha --exit",
"coverage:report": "c8 report --reporter=html",
"clean": "rm -rf dist",
"build": "npx tsc && chmod +x dist/cli.js",
"tableland": "node --experimental-specifier-resolution=node ./dist/cli.js"
Expand Down
8 changes: 4 additions & 4 deletions src/commands/chains.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { Arguments, CommandBuilder } from "yargs";
import { GlobalOptions } from "../cli.js";
import { getChains } from "../utils.js";
import { getChains, logger } from "../utils.js";
import type yargs from "yargs";

export interface Options extends GlobalOptions {
Expand All @@ -24,17 +24,17 @@ export const handler = async (_argv: Arguments<Options>): Promise<void> => {
const { format } = _argv;

if (format === "pretty") {
console.log(JSON.stringify(chains, null, 4));
logger.log(JSON.stringify(chains, null, 4));
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Much of the code changes are simply replacing console.log with logger.log etc...

return;
}
if (format === "jsonl") {
console.log(
logger.log(
Object.entries(chains)
.map((chain) => JSON.stringify(chain[1]))
.join("\n")
);
return;
}
// default is "json"
console.log(JSON.stringify(chains));
logger.log(JSON.stringify(chains));
};
14 changes: 7 additions & 7 deletions src/commands/controller.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type yargs from "yargs";
import type { Arguments, CommandBuilder } from "yargs";
import { Registry } from "@tableland/sdk";
import { getWalletWithProvider, getLink } from "../utils.js";
import { getWalletWithProvider, getLink, logger } from "../utils.js";
import { GlobalOptions } from "../cli.js";

export interface Options extends GlobalOptions {
Expand Down Expand Up @@ -36,10 +36,10 @@ export const builder: CommandBuilder<{}, Options> = (yargs) =>

const res = await reg.getController(name);

console.log(res);
logger.log(res);
/* c8 ignore next 3 */
} catch (err: any) {
console.error(err.message);
logger.error(err.message);
}
}
)
Expand Down Expand Up @@ -71,10 +71,10 @@ export const builder: CommandBuilder<{}, Options> = (yargs) =>

const link = getLink(chain, res.hash);
const out = { ...res, link };
console.log(JSON.stringify(out));
logger.log(JSON.stringify(out));
/* c8 ignore next 3 */
} catch (err: any) {
console.error(err.message);
logger.error(err.message);
}
}
)
Expand Down Expand Up @@ -102,10 +102,10 @@ export const builder: CommandBuilder<{}, Options> = (yargs) =>

const link = getLink(chain, res.hash);
const out = { ...res, link };
console.log(JSON.stringify(out));
logger.log(JSON.stringify(out));
/* c8 ignore next 3 */
} catch (err: any) {
console.error(err.message);
logger.error(err.message);
}
}
);
Expand Down
23 changes: 13 additions & 10 deletions src/commands/create.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type yargs from "yargs";
import type { Arguments, CommandBuilder } from "yargs";
import { getLink } from "../utils.js";
import { getLink, logger } from "../utils.js";
import { createInterface } from "readline";
import { promises } from "fs";
import { GlobalOptions } from "../cli.js";
Expand Down Expand Up @@ -43,11 +43,11 @@ export const handler = async (argv: Arguments<Options>): Promise<void> => {
const { chain, file, prefix, privateKey } = argv;
// enforce that all args required for this command are available
if (!privateKey) {
console.error("missing required flag (`-k` or `--privateKey`)");
logger.error("missing required flag (`-k` or `--privateKey`)");
return;
}
if (!chain) {
console.error("missing required flag (`-c` or `--chain`)");
logger.error("missing required flag (`-c` or `--chain`)");
return;
}
if (file != null) {
Expand All @@ -59,7 +59,7 @@ export const handler = async (argv: Arguments<Options>): Promise<void> => {
schema = value;
}
if (!schema) {
console.error(
logger.error(
"missing input value (`schema`, `file`, or piped input from stdin required)"
);
return;
Expand All @@ -70,7 +70,7 @@ export const handler = async (argv: Arguments<Options>): Promise<void> => {
if (check) {
statement = schema;
} else if (prefix === undefined) {
console.error(
logger.error(
"Must specify --prefix if you do not provide a full Create statement"
);
} else {
Expand Down Expand Up @@ -100,11 +100,11 @@ export const handler = async (argv: Arguments<Options>): Promise<void> => {
);

if (!normalized.every((norm) => norm.type === "create")) {
console.error("the `create` command can only accept create queries");
logger.error("the `create` command can only accept create queries");
return;
}
if (statements.length < 1) {
console.error(
logger.error(
"after normalizing the statement there was no create query, hence nothing to do"
);
return;
Expand All @@ -123,7 +123,7 @@ export const handler = async (argv: Arguments<Options>): Promise<void> => {
out.ensNameRegistered = register;
}

console.log(JSON.stringify(out));
logger.log(JSON.stringify(out));
return;
}

Expand All @@ -135,16 +135,19 @@ export const handler = async (argv: Arguments<Options>): Promise<void> => {
const link = getLink(chain, res.meta.txn?.transactionHash as string);
const out = { ...res, link, ensNameRegistered: false };

// TODO: I'm not sure how `check` would be false and statements.length < 2
// so I didn't write a test for it
/* c8 ignore next 6 */
if (!check && argv.ns && argv.enableEnsExperiment && prefix) {
const register = (await ens?.addTableRecords(argv.ns, [
{ key: prefix, value: out.meta.txn?.name as string },
])) as boolean;
out.ensNameRegistered = register;
}

console.log(JSON.stringify(out));
logger.log(JSON.stringify(out));
/* c8 ignore next 3 */
} catch (err: any) {
console.error(err?.cause?.message || err.message);
logger.error(err?.cause?.message || err.message);
}
};
8 changes: 5 additions & 3 deletions src/commands/info.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type yargs from "yargs";
import type { Arguments, CommandBuilder } from "yargs";
import { GlobalOptions } from "../cli.js";
import { setupCommand } from "../lib/commandSetup.js";
import { logger } from "../utils.js";

export interface Options extends GlobalOptions {
name: string;
Expand All @@ -24,7 +25,7 @@ export const handler = async (argv: Arguments<Options>): Promise<void> => {
const parts = name.split("_");

if (parts.length < 3 && !argv.enableEnsExperiment) {
console.error(
logger.error(
"invalid table name (name format is `{prefix}_{chainId}_{tableId}`)"
);
return;
Expand All @@ -35,6 +36,7 @@ export const handler = async (argv: Arguments<Options>): Promise<void> => {
chain: parseInt(chainId) as any,
});

/* c8 ignore next 3 */
if (argv.enableEnsExperiment && ens) {
name = await ens.resolveTable(name);
}
Expand All @@ -43,9 +45,9 @@ export const handler = async (argv: Arguments<Options>): Promise<void> => {
tableId,
chainId: parseInt(chainId),
});
console.log(JSON.stringify(res));
logger.log(JSON.stringify(res));
/* c8 ignore next 3 */
} catch (err: any) {
console.error(err?.cause?.message || err.message);
logger.error(err?.cause?.message || err.message);
}
};
6 changes: 3 additions & 3 deletions src/commands/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import yaml from "js-yaml";
import { resolve, dirname } from "path";
import { mkdirSync, createWriteStream, WriteStream } from "fs";
import inquirer from "inquirer";
import { getChains } from "../utils.js";
import { getChains, logger } from "../utils.js";
import { GlobalOptions } from "../cli.js";

export interface Options extends GlobalOptions {
Expand Down Expand Up @@ -111,10 +111,10 @@ export const handler = async (argv: Arguments<Options>): Promise<void> => {
break;
}
if (path !== ".") {
console.log(`Config created at ${filePath}`);
logger.log(`Config created at ${filePath}`);
}
} catch (err: any) {
console.error(err.message);
logger.error(err.message);
return;
} finally {
stream.end("\n");
Expand Down
9 changes: 5 additions & 4 deletions src/commands/list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { Arguments, CommandBuilder } from "yargs";
import { Wallet } from "ethers";
import { GlobalOptions } from "../cli.js";
import { setupCommand } from "../lib/commandSetup.js";
import { logger } from "../utils.js";

export interface Options extends GlobalOptions {
address: string;
Expand All @@ -23,14 +24,14 @@ export const handler = async (argv: Arguments<Options>): Promise<void> => {
const { chain, privateKey } = argv;
let { address } = argv;
if (!chain) {
console.error("missing required flag (`-c` or `--chain`)");
logger.error("missing required flag (`-c` or `--chain`)");
return;
}
if (!address) {
if (privateKey) {
address = new Wallet(privateKey).address;
} else {
console.error("must supply `--privateKey` or `address` positional");
logger.error("must supply `--privateKey` or `address` positional");
return;
}
}
Expand All @@ -39,9 +40,9 @@ export const handler = async (argv: Arguments<Options>): Promise<void> => {

const res = await registry.listTables(address);

console.log(JSON.stringify(res));
logger.log(JSON.stringify(res));
/* c8 ignore next 3 */
} catch (err: any) {
console.error(err.message);
logger.error(err.message);
}
};
66 changes: 39 additions & 27 deletions src/commands/namespace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type yargs from "yargs";
import { Arguments, CommandBuilder } from "yargs";
import { GlobalOptions } from "../cli.js";
import { setupCommand } from "../lib/commandSetup.js";
import { logger } from "../utils.js";

export interface Options extends GlobalOptions {
domain: string;
Expand All @@ -16,46 +17,56 @@ async function getHandler(argv: yargs.ArgumentsCamelCase<Options>) {
const { record } = argv;
const { ens } = await setupCommand(argv);
if (!ens) {
console.log(
logger.log(
"To use ENS, ensure you have set the enableEnsExperiment flag to true"
);
return;
}

console.log(JSON.stringify({ value: await ens.resolveTable(record) }));
logger.log(JSON.stringify({ value: await ens.resolveTable(record) }));
}

async function setHandler(argv: yargs.ArgumentsCamelCase<Options>) {
const { domain, mappings } = argv;
const { ens } = await setupCommand(argv);
if (!ens) return;
try {
const { domain, mappings } = argv;
const { ens } = await setupCommand(argv);
if (!ens) {
logger.log(
"To use ENS, ensure you have set the enableEnsExperiment flag to true"
);
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These lines include a change to wrap with a try/catch, but also include an informative message in the case the user is trying to use ens without the required flags

return;
}

const records = mappings.map((entry: any) => {
const [key, value] = entry.split("=");
const records = mappings.map((entry: any) => {
const [key, value] = entry.split("=");

const keyRegex = /^[a-zA-Z0-9_]*$/;
const valueRegex = /^[a-zA-Z_][a-zA-Z0-9_]*_[0-9]+_[0-9]+$/;
const keyRegex = /^[a-zA-Z0-9_]*$/;
const valueRegex = /^[a-zA-Z_][a-zA-Z0-9_]*_[0-9]+_[0-9]+$/;

if (keyRegex.exec(key) === null) {
throw new Error("Only letters or underscores in key name");
}
if (valueRegex.exec(value) === null) {
throw new Error("Tablename is invalid");
}
return {
key,
value,
};
});
if (keyRegex.exec(key) === null) {
throw new Error("Only letters or underscores in key name");
}
if (valueRegex.exec(value) === null) {
throw new Error("Tablename is invalid");
}
return {
key,
value,
};
});

if (await ens.addTableRecords(domain, records)) {
const response = {
domain,
records,
mappings,
};
if (await ens.addTableRecords(domain, records)) {
const response = {
domain,
records,
mappings,
};

console.log(JSON.stringify(response));
logger.log(JSON.stringify(response));
}
/* c8 ignore next 3 */
} catch (err: any) {
logger.error(err?.cause?.message || err?.message);
}
}

Expand Down Expand Up @@ -85,4 +96,5 @@ export const builder: CommandBuilder<{}, Options> = (yargs) =>
)
.usage(``) as yargs.Argv<Options>;

/* c8 ignore next */
export const handler = async (argv: Arguments<Options>): Promise<void> => {};
Loading