Skip to content
This repository has been archived by the owner on Feb 26, 2024. It is now read-only.

Commit

Permalink
Add test coverage, improve test coverage of process-name, and args
Browse files Browse the repository at this point in the history
  • Loading branch information
jeffsmale90 committed Sep 28, 2022
1 parent 773f21a commit 944b516
Show file tree
Hide file tree
Showing 7 changed files with 331 additions and 29 deletions.
2 changes: 1 addition & 1 deletion src/packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
},
"scripts": {
"tsc": "tsc --build",
"test": "nyc npm run mocha",
"test": "nyc --reporter lcov npm run mocha",
"mocha": "cross-env TS_NODE_FILES=true mocha --exit --check-leaks --throw-deprecation --trace-warnings --require ts-node/register 'tests/**/*.test.ts'",
"start": "cross-env node --require ts-node/register --inspect src/cli.ts"
},
Expand Down
50 changes: 33 additions & 17 deletions src/packages/cli/src/args.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
// `import Yargs from "yargs"` is the Yargs singleton and namespace
// `import yargs from "yargs/yargs"` is the non-singleton interface
// See https://github.com/yargs/yargs/issues/1648
import Yargs, { Options } from "yargs";
import yargs from "yargs/yargs";

import { TruffleColors } from "@ganache/colors";
import yargs, { Options } from "yargs";
import {
DefaultFlavor,
FilecoinFlavorName,
Expand All @@ -26,7 +31,7 @@ marked.setOptions({
})
});

const wrapWidth = Math.min(120, yargs.terminalWidth());
const wrapWidth = Math.min(120, Yargs.terminalWidth());
const NEED_HELP = "Need more help? Reach out to the Truffle community at";
const COMMUNITY_LINK = "https://trfl.io/support";

Expand All @@ -43,7 +48,7 @@ const highlight = (t: string) => unescapeEntities(marked.parseInline(t));
const center = (str: string) =>
" ".repeat(Math.max(0, Math.floor((wrapWidth - str.length) / 2))) + str;

const addAliases = (args: yargs.Argv<{}>, aliases: string[], key: string) => {
const addAliases = (args: Yargs.Argv<{}>, aliases: string[], key: string) => {
const options = { hidden: true, alias: key };
return aliases.reduce((args, a) => args.option(a, options), args);
};
Expand All @@ -54,7 +59,7 @@ function processOption(
group: string,
option: string,
optionObj: Definitions<Base.Config>[string],
argv: yargs.Argv,
argv: Yargs.Argv,
flavor: string
) {
if (optionObj.disableInCLI !== true) {
Expand Down Expand Up @@ -122,7 +127,7 @@ function applyDefaults(
flavorDefaults:
| typeof DefaultOptionsByName[keyof typeof DefaultOptionsByName]
| typeof _DefaultServerOptions,
flavorArgs: yargs.Argv<{}>,
flavorArgs: Yargs.Argv<{}>,
flavor: keyof typeof DefaultOptionsByName
) {
for (const category in flavorDefaults) {
Expand Down Expand Up @@ -160,8 +165,9 @@ export default function (

// disable dot-notation because yargs just can't coerce args properly...
// ...on purpose! https://github.com/yargs/yargs/issues/1021#issuecomment-352324693
yargs
const yargsParser = yargs()
.parserConfiguration({ "dot-notation": false })
.exitProcess(false)
.strict()
.usage(versionUsageOutputText)
.epilogue(
Expand All @@ -188,12 +194,9 @@ export default function (
command = ["$0", flavor];
defaultPort = 8545;
break;
default:
command = flavor;
defaultPort = 8545;
}

yargs.command(
yargsParser.command(
command,
chalk`Use the {bold ${flavor}} flavor of Ganache`,
flavorArgs => {
Expand All @@ -214,14 +217,19 @@ export default function (
description: chalk`Port to listen on.${EOL}{dim deprecated aliases: --port}${EOL}`,
alias: ["p", "port"],
type: "number",
default: defaultPort
default: defaultPort,
// `string: true` to allow raw value to be used in validation below
// (otherwise string values becomes NaN)
string: true,
coerce: port => (isFinite(port) ? +port : port)
})
.check(argv => {
const { "server.port": port, "server.host": host } = argv;
if (port < 1 || port > 65535) {
throw new Error(`Invalid port number '${port}'`);
if (!isFinite(port) || port < 1 || port > 65535) {
throw new Error(
`Port should be >= 0 and < 65536. Received ${port}.`
);
}

if (host.trim() === "") {
throw new Error("Cannot leave host blank; please provide a host");
}
Expand All @@ -244,7 +252,7 @@ export default function (
);
}

yargs
yargsParser
.command(
"instances",
highlight(
Expand Down Expand Up @@ -272,6 +280,14 @@ export default function (
stopArgs.action = "stop";
}
)
.check(instancesArgs => {
if (instancesArgs["_"].length <= 1) {
throw new Error(
"No sub-command given. See `ganache instances --help` for more information."
);
}
return true;
})
.version(false);
}
)
Expand All @@ -280,7 +296,7 @@ export default function (
.wrap(wrapWidth)
.version(version);

const parsedArgs = yargs.parse(rawArgs);
const parsedArgs = yargsParser.parse(rawArgs);

let finalArgs: GanacheArgs;
if (parsedArgs.action === "stop") {
Expand Down Expand Up @@ -308,7 +324,7 @@ export default function (
>)
};
} else {
throw new Error(`Unknown action: ${parsedArgs.action}`);
finalArgs = { action: "help" };
}

return finalArgs;
Expand Down
7 changes: 6 additions & 1 deletion src/packages/cli/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
import { TruffleColors } from "@ganache/colors";
import { table } from "table";
import chalk from "chalk";
import { GanacheArgs } from "./types";

const logAndForceExit = (messages: any[], exitCode = 0) => {
// https://nodejs.org/api/process.html#process_process_exit_code
Expand Down Expand Up @@ -60,7 +61,11 @@ const detailedVersion = `ganache v${version} (@ganache/cli: ${cliVersion}, @gana
const isDocker =
"DOCKER" in process.env && process.env.DOCKER.toLowerCase() === "true";

const argv = args(detailedVersion, isDocker);
let argv: GanacheArgs;
try {
argv = args(detailedVersion, isDocker);
} catch (err: any) {}

if (argv.action === "start") {
const flavor = argv.flavor;
const cliSettings = argv.server;
Expand Down
13 changes: 8 additions & 5 deletions src/packages/cli/src/process-name.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,23 @@
function pick(source: string[]) {
const partIndex = Math.floor(Math.random() * source.length);
function pick(source: string[], random: () => number) {
const partIndex = Math.floor(random() * source.length);
return source[partIndex];
}
/**
* Generates a random name to assign to an instance of Ganache. The name is
* generated from an adjective, a flavor and a type of desert, in the form of
* `<adjective>_<flavor>_<type>`, eg., `salted_caramel_ganache`.
*/
export default function createInstanceName() {
const name = [adjectives, flavors, kinds].map(pick).join("_");
export default function createInstanceName(random: () => number = Math.random) {
const name = [adjectives, flavors, kinds]
.map(source => pick(source, random))
.join("_");
return name;
}

const adjectives = [
"baked",
"candied",
"creamy",
"deepfried",
"frozen",
"hot",
Expand Down Expand Up @@ -48,7 +51,7 @@ const flavors = [
"orange",
"peanut",
"plum",
"poppy-seed",
"poppyseed",
"rhubarb",
"strawberry",
"sugar",
Expand Down
3 changes: 2 additions & 1 deletion src/packages/cli/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ type CliServerOptions = {
port: number;
};

type Action = "start" | "start-detached" | "list" | "stop";
type Action = "start" | "start-detached" | "list" | "stop" | "help";

type AbstractArgs<TAction = Action> = {
action: TAction;
Expand All @@ -21,6 +21,7 @@ export type StartArgs<TFlavorName extends FlavorName> =
export type GanacheArgs =
| (AbstractArgs<"stop"> & { name: string })
| AbstractArgs<"list">
| AbstractArgs<"help">
| StartArgs<FlavorName>;

export type CliSettings = CliServerOptions;
Expand Down
Loading

0 comments on commit 944b516

Please sign in to comment.