Skip to content

Commit

Permalink
feat: setup cli and helpers
Browse files Browse the repository at this point in the history
  • Loading branch information
lihbr committed May 27, 2021
1 parent a6aa71b commit 85b2da0
Show file tree
Hide file tree
Showing 5 changed files with 77 additions and 0 deletions.
59 changes: 59 additions & 0 deletions src/cli.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import cac from "cac";
import exit from "exit";
import latestVersion from "latest-version";
import semver from "semver";

import * as commands from "./commands";
import { logger, NAME, PACKAGE, ucFirst, VERSION } from "./lib";

const cli = cac(NAME);

cli.command("").action(options => {
commands._default(cli, options);
});

cli.command("login <token>", "Log in to Dico.app").action(async options => {
await commands.signin(cli, options);
});

cli.command("logout", "Log out of Dico.app").action(options => {
commands.signout(cli, options);
});

cli.command("whoami", "Display current user").action(async options => {
await commands.whoami(cli, options);
});

cli.version(VERSION);
cli.help(commands.help);

const run = async (): Promise<void> => {
try {
cli.parse(process.argv, { run: false });
await cli.runMatchedCommand();
} catch (error) {
if (error.message && typeof error.message === "string") {
logger.error(ucFirst(error.message));
} else {
logger.fatal("");
console.log(error);
console.log("");
}
exit(1);
}

const version = await latestVersion(PACKAGE);
if (semver.gt(version, VERSION)) {
console.log("");
logger.info(
`A new version of \`${PACKAGE}\` is available!\n\n Install it with:\n $ npm install --global ${PACKAGE}@${version}\n`
);
}
};

process.on("unhandledRejection", error => {
logger.fatal(error);
exit(2);
});

run();
9 changes: 9 additions & 0 deletions src/lib/const.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import pkg from "../../package.json";

export const NAME = "dico";
export const PACKAGE = pkg.name;
export const DESCRIPTION = pkg.description;
export const VERSION = pkg.version;
export const RC_FILE = ".dicorc";
export const API_ENDPOINT = "http://localhost:3000/v1/cli";
// export const API_ENDPOINT = "https://api.dico.app/v1/cli";
3 changes: 3 additions & 0 deletions src/lib/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export * from "./const";
export * from "./logger";
export * from "./string";
4 changes: 4 additions & 0 deletions src/lib/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import consola from "consola";
import { NAME } from "./const";

export const logger = consola.withScope(NAME);
2 changes: 2 additions & 0 deletions src/lib/string.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export const ucFirst = (str: string): string =>
`${str.charAt(0).toUpperCase()}${str.slice(1)}`;

0 comments on commit 85b2da0

Please sign in to comment.