Skip to content

Commit

Permalink
Use yargs to make CLI commands
Browse files Browse the repository at this point in the history
  • Loading branch information
Netfloex committed May 8, 2022
1 parent 9f5ffb9 commit 39c354d
Show file tree
Hide file tree
Showing 6 changed files with 73 additions and 9 deletions.
2 changes: 1 addition & 1 deletion entrypoint.sh
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ PREFIX="[NCM] (entrypoint.sh)"

start() {
echo "$PREFIX Generating configs"
node index.js
node index.js run
}

reload() {
Expand Down
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@
"main": "dist/index.js",
"scripts": {
"build": "rollup -c",
"start": "node .",
"start": "node . run",
"typescript": "tsc --noEmit",
"test": "jest",
"lint": "eslint .",
"ts": "ts-node -T src",
"dev": "tsnd --respawn -T --rs --cls -r tsconfig-paths/register --experimental-modules -- src",
"prepare": "husky install"
},
Expand Down Expand Up @@ -53,6 +54,7 @@
"ts-node-dev": "^1.1.8",
"tslib": "^2.4.0",
"typescript": "^4.6.4",
"yargs": "^17.4.1",
"yn": "^4",
"zod": "3.8"
},
Expand Down
69 changes: 65 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
import chalk from "chalk";
import type { FSWatcher } from "chokidar";
import chokidar from "chokidar";
import { pathExists, readdir, remove } from "fs-extra";
import { version } from "package.json";
import { join } from "path";
import yargs from "yargs";
import { hideBin } from "yargs/helpers";

import { certbot } from "@lib/certbot";
import { logger, resetStarted, started } from "@lib/logger";
import parseServers from "@lib/parseServers";
import validateConfig from "@lib/validateConfig";
import { cloudflare } from "@utils/cloudflare";
import { htpasswd } from "@utils/createAuthFile";
import { createConfigFiles } from "@utils/createConfigFiles";
import { createDHPemIfNotExists } from "@utils/createDHPemIfNotExists";
import { editNginxConfig } from "@utils/editNginxConfig";
Expand All @@ -30,7 +35,11 @@ const createWatcherOnce = async (path: string): Promise<FSWatcher> => {
return watcher;
};

const main = async (): Promise<ExitCode> => {
const main = async ({
justLogConfig
}: {
justLogConfig?: boolean;
} = {}): Promise<ExitCode> => {
let stopping = false;

let configFilePath = settings.configFile;
Expand Down Expand Up @@ -90,6 +99,13 @@ const main = async (): Promise<ExitCode> => {

const validatedConfig = await validateConfig(results);

if (justLogConfig) {
console.log(
chalk.bold("\nParsed Config"),
chalk.dim("\n" + JSON.stringify(results, null, "\t"))
);
}

if (validatedConfig == null) {
return ExitCode.failure;
}
Expand All @@ -101,6 +117,14 @@ const main = async (): Promise<ExitCode> => {
servers: await parseServers(validatedConfig.servers)
};

if (justLogConfig) {
console.log(
chalk.bold("\nValidated Config"),
chalk.dim("\n" + JSON.stringify(validatedConfig, null, "\t"))
);
return ExitCode.success;
}

if (!(await pathExists(settings.nginxConfigPath))) {
logger.noOldConfigs();
logger.configsLocationHint();
Expand Down Expand Up @@ -177,10 +201,10 @@ const main = async (): Promise<ExitCode> => {
return ExitCode.success;
};

export const startMain = (): void => {
export const startMain = (...params: Parameters<typeof main>): void => {
resetStarted();
logger.start();
main()
main(...params)
.then((exitCode) => {
if (exitCode == ExitCode.success) {
logger.done({ started });
Expand All @@ -197,4 +221,41 @@ export const startMain = (): void => {
});
};

startMain();
yargs(hideBin(process.argv))
.scriptName("ncm")
.version(version)
// .help()
.alias("h", "help")
.alias("v", "version")
.command("run", "Runs ncm", {}, () => startMain())
.command(
"htpasswd",
"Creates an apache md5 hashed password",
(yargs) =>
yargs.options({
username: {
type: "string",
alias: "u",
default: "username"
},
password: {
type: "string",
alias: "p",
requiresArg: true,
required: true
}
}),
({ username, password }) => {
console.log("Created a htpasswd string");
console.log(chalk.dim(htpasswd({ username, password })));
}
)
.command("debug-config", "Outputs the parsed config", {}, () => {
startMain({ justLogConfig: true });
})
.command("settings", "Shows a lists of the current settings", {}, () => {
console.log(settings);
})
.strict()
.demandCommand()
.parse();
2 changes: 1 addition & 1 deletion src/utils/createAuthFile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { Auth } from "@models/ParsedConfig";
* @returns
*/

const htpasswd = ({ username, password }: Auth): string =>
export const htpasswd = ({ username, password }: Auth): string =>
`${username}:${md5(password)}`;

/**
Expand Down
3 changes: 2 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
"ts-node": {
"compilerOptions": {
"module": "commonjs"
}
},
"require": ["tsconfig-paths/register"]
}
}
2 changes: 1 addition & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -4360,7 +4360,7 @@ yargs-parser@^21.0.0:
resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-21.0.1.tgz#0267f286c877a4f0f728fceb6f8a3e4cb95c6e35"
integrity sha512-9BK1jFpLzJROCI5TzwZL/TU4gqjK5xiHV/RfWLOahrjAko/e4DJkRDZQXfvqAsiZzzYhgAzbgz6lg48jcm4GLg==

yargs@^17.3.1:
yargs@^17.3.1, yargs@^17.4.1:
version "17.4.1"
resolved "https://registry.yarnpkg.com/yargs/-/yargs-17.4.1.tgz#ebe23284207bb75cee7c408c33e722bfb27b5284"
integrity sha512-WSZD9jgobAg3ZKuCQZSa3g9QOJeCCqLoLAykiWgmXnDo9EPnn4RPf5qVTtzgOx66o6/oqhcA5tHtJXpG8pMt3g==
Expand Down

0 comments on commit 39c354d

Please sign in to comment.