Skip to content

Commit

Permalink
chore: code restructure & commandParser tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Johan committed Sep 16, 2019
1 parent 803afbe commit f09ec80
Show file tree
Hide file tree
Showing 25 changed files with 239 additions and 124 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
dist
src/common/ssh/.ssh.config.json
src/lib/ssh/.ssh.config.json
package
.DS_STORE

# Logs
Expand Down
2 changes: 1 addition & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
{
"debug.node.autoAttach": "on"
"debug.node.autoAttach": "off"
}
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

36 changes: 22 additions & 14 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,11 +1,28 @@
{
"name": "asuswrt-cli",
"version": "0.0.1",
"bin": {
"router": "dist/src/bin/router.js"
},
"description": "ASUS Router CLI",
"main": "src/router.ts",
"types": "dist/index.d.ts",
"files": [
"dist/src/*"
],
"keywords": [
"firewall",
"vpn",
"asuswrt",
"cli",
"tools"
],
"main": "dist/src/bin/router.js",
"name": "asuswrt-cli",
"version": "0.0.1-beta.1",
"types": "dist/src/types/index.d.ts",
"repository": "github:jaspenlind/asuswrt-cli",
"readme": "https://github.com/jaspenlind/asuswrt-cli#readme",
"author": "jaspenlind",
"license": "MIT",
"scripts": {
"start": "ts-node src/router.ts",
"start": "ts-node src/bin/router.ts",
"commit": "npm run lint-check && npm run test",
"push": "npm run test",
"pretest": "npm run lint && npm run build",
Expand All @@ -21,15 +38,6 @@
"coveralls": "cat ./coverage/lcov.info | ./node_modules/.bin/coveralls",
"debug": "node --nolazy --inspect-brk=9229 node_modules/jest/bin/jest.js -i"
},
"repository": {
"type": "git",
"url": "https://github.com/jaspenlind/asuswrt-cli.git"
},
"keywords": [
""
],
"author": "jaspenlind",
"license": "MIT",
"dependencies": {
"@types/shelljs": "^0.8.5",
"chalk": "^2.4.2",
Expand Down
9 changes: 9 additions & 0 deletions src/bin/router.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import cli from "../lib/cli";

process.once("uncaughtException", err => {
console.error(err.stack);

process.exitCode = 2;
});

cli.run();
12 changes: 0 additions & 12 deletions src/commands/firewall/index.ts

This file was deleted.

29 changes: 0 additions & 29 deletions src/common/ssh/index.ts

This file was deleted.

74 changes: 39 additions & 35 deletions src/router.ts → src/lib/cli.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
#!/usr/bin/env node
import chalk from "chalk";
import help from "./common/help";
import parser from "./common/commandParser";
import moduleLogger from "./common/logger";
import help from "./help";
import parser from "./commandParser";
import moduleLogger from "./logger";

/* eslint-disable no-useless-escape */
const header = `
Expand All @@ -23,36 +23,40 @@ const header = `
###########################################################################`;
/* eslint-enable no-useless-escape */

const logger = moduleLogger.createLogger(module);

const args = process.argv.slice(2);

const commands = parser(...args);

console.log(commands.all().map(x => x.name));

const command = commands.find(args);

logger.debug(undefined, { meta: { args, command } });

if (!commands.isDebug) {
console.clear();
console.log(header);
}

if (commands.isHelp || args.length < 1) {
if (command) {
help(command);
} else {
help();
const cli = {
run: () => {
const logger = moduleLogger.createLogger(module);

const args = process.argv.slice(2);

const commands = parser(...args);

const command = commands.find();

logger.debug(undefined, { meta: { args, command } });

if (!commands.isDebug) {
console.clear();
console.log(header);
}

if (commands.isHelp || args.length < 1) {
if (command) {
help(command);
} else {
help();
}
} else if (command !== null && command.run) {
command.run(command.args);
} else {
if (command) {
help(command);
} else {
help();
}
console.error(chalk.red("\nUnknown command\n"));
}
}
} else if (command !== null && command.run) {
command.run(command.args);
} else {
if (command) {
help(command);
} else {
help();
}
console.error(chalk.red("\nUnknown command\n"));
}
};

export default cli;
18 changes: 9 additions & 9 deletions src/common/commandParser.ts → src/lib/commandParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,7 @@ import extensionless from "extensionless";
import { Command, CommandParser } from "../types";
import moduleLogger from "./logger";

const rootCommandPath = flexi
.path(__dirname)
.parent(x => x.name === "src")
.append("commands/");
const rootCommandPath = flexi.path(__dirname).append("commands/");

const logger = moduleLogger.createLogger(module);

Expand All @@ -25,11 +22,10 @@ const isHelp = (...args: string[]): boolean => {
const isDebug = (...args: string[]): boolean =>
args.filter(x => x === "--debug").length > 0;

const mostSpecificCommand = (args: Path): WalkedPath<FlexiPath> => {
return flexi.walk.back(args, {
const mostSpecificCommand = (args: Path): WalkedPath<FlexiPath> =>
flexi.walk.back(args, {
until: until.exists({ ignoreFileExtensions: true })
});
};

const commandName = (args: Path): string => {
const { result } = mostSpecificCommand(args);
Expand Down Expand Up @@ -79,14 +75,16 @@ const isCommand = (path: FlexiPath) => {
const createCommand = (path: FlexiPath): Command => {
const { result, diff } = mostSpecificCommand(path);

const args = diff.isEmpty() ? [] : diff.path.split(" ");

const content = requireContent(result);
return {
name: commandName(result),
fullname: commandFullName(result),
run: content.run,
helpname: content.helpname,
description: content.description,
args: diff.path.split(" "),
args,
subCommands: result
.children()
.filter(x => isCommand(x))
Expand All @@ -107,7 +105,9 @@ const withoutOptions = (...args: string[]): string[] =>
const parse = (...args: string[]): Command | null => {
const path = rootCommandPath.append(args);

return isCommand(path) ? createCommand(path) : null;
const command = isCommand(path) ? createCommand(path) : null;

return command;
};

const commandParser = (...args: string[]): CommandParser => {
Expand Down
21 changes: 21 additions & 0 deletions src/lib/commands/firewall/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
#!/usr/bin/env node
import ssh from "../../ssh";

const firewall = (args: string[]): void => {
const firewallArgs = (args || []).join(" ");
const interactive = firewallArgs === "";

const command = "sh /jffs/scripts/firewall";

if (interactive) {
ssh.executeInTerminal(command);
} else {
ssh.execute(`${command} ${firewallArgs}`);
}
};

export default {
run: firewall,
helpname: "firewall [args]",
description: "Opens the Skynet firewall with the passes args (optional)"
};
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#!/usr/bin/env node
import ssh from "../../../common/ssh";
import ssh from "../../../ssh";

const transfer = (): void => {
// TODO
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#!/usr/bin/env node
import ssh from "../../common/ssh";
import ssh from "../../ssh";

const commands = (): void => {
ssh.execute("ls -1 /usr/bin/ | grep -v '^d'");
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
#!/usr/bin/env node
import ssh from "../../common/ssh";
import ssh from "../../ssh";

const uptime = (): void => {
ssh.execute(["uptime"]);
ssh.execute("uptime");
};

export default {
Expand Down
4 changes: 2 additions & 2 deletions src/commands/terminal.ts → src/lib/commands/terminal.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
#!/usr/bin/env node
import ssh from "../common/ssh";
import ssh from "../ssh";

const terminal = (args: string[]): void => {
ssh.execute(args);
ssh.executeInTerminal(args);
};

export default {
Expand Down
File renamed without changes.
2 changes: 1 addition & 1 deletion src/common/logger.ts → src/lib/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ const createMeta = (meta: any): string => {
};

const rootLogger = createLogger({
level: isDebug ? "debug" : "info",
level: isDebug ? "debug" : "warn",
format: combine(
format.timestamp({ format: "YYYY-MM-DD HH:mm:ss" }),
align(),
Expand Down
File renamed without changes.
42 changes: 42 additions & 0 deletions src/lib/ssh/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#!/usr/bin/env node
import { existsSync, readFileSync } from "fs";
import { join } from "path";

import sh from "shelljs";

const getConfig = () => {
const sshConfigFile = join(__dirname, ".ssh.config.json");

let config = {
host: "n/a",
username: "n/a",
privateKey: "n/a"
};

if (existsSync(sshConfigFile)) {
config = JSON.parse(readFileSync(sshConfigFile, "utf8"));
}

return config;
};

const execute = (...args: string[]): void => {
const config = getConfig();

const ssh = `ssh -i '${config.privateKey}' ${config.username}@${config.host}`;

sh.exec(`${ssh} "${args.join(" ")}"`);
};

const executeInTerminal = (args: any) => {
const config = getConfig();

const ssh = `ssh -i '${config.privateKey}' ${config.username}@${config.host}`;

sh.exec(`osascript -e 'tell app "Terminal"
activate
do script "${ssh} ${args}"
end tell'`);
};

export default { execute, executeInTerminal };
2 changes: 1 addition & 1 deletion src/types/CommandParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Command } from ".";

export interface CommandParser {
all(): Command[];
find(args: string[]): Command | null;
find(): Command | null;
isHelp: boolean;
isDebug: boolean;
}
Loading

0 comments on commit f09ec80

Please sign in to comment.