Skip to content

Commit

Permalink
chore: using cron-parser package parsing job schedules
Browse files Browse the repository at this point in the history
  • Loading branch information
Johan committed Oct 25, 2019
1 parent 9e49245 commit ae32baa
Show file tree
Hide file tree
Showing 11 changed files with 181 additions and 67 deletions.
34 changes: 31 additions & 3 deletions package-lock.json

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

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
"@types/shelljs": "^0.8.5",
"@types/table": "^4.0.7",
"chalk": "^2.4.2",
"cron-parser": "^2.13.0",
"flexi-path": "^0.1.2-beta.16",
"nordvpn-server-lister": "https://github.com/jaspenlind/nordvpn-server-lister/releases/download/v0.0.1-alpha.3/nordvpn-server-lister-0.0.1-alpha.3.tgz",
"option-parser": "https://github.com/jaspenlind/option-parser/releases/download/v0.0.1-alpha.6/option-parser-0.0.1-alpha.6.tgz",
Expand Down
65 changes: 62 additions & 3 deletions src/lib/arrayHelper.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,67 @@
export const any = <T>(array: ArrayLike<T>) => array.length > 0;
type NullableArray<T> = ArrayLike<T> | null;

export const isEmpty = <T>(array: ArrayLike<T>) => !any(array);
export const indeces = {
empty: 0,
first: 0,
lastIndexSubtrahend: 1
};

export const last = <T>(array: ArrayLike<T>): T => array[array.length - 1];
export const any = <T>(array: NullableArray<T>) =>
(array && array.length > indeces.empty) || false;

export const isEmpty = <T>(array: NullableArray<T>) => !any(array);

export const firstOrDefault = <T>(
array: NullableArray<T>,
defaultValue: T | null = null
): T | null => (array && array[indeces.first]) || defaultValue;

export const first = <T>(array: NullableArray<T>) =>
firstOrDefault(array) || undefined;

export const lastOrDefault = <T>(
array: NullableArray<T>,
defaultValue: T | null = null
): T | null =>
(array && array[array.length - indeces.lastIndexSubtrahend]) || defaultValue;

export const last = <T>(array: NullableArray<T>) =>
lastOrDefault(array) || undefined;

export const takeWhile = <T>(
array: T[],
predicate: (item: T) => boolean
): T[] => {
const items: T[] = [];

for (const item of array) {
if (!predicate(item)) {
break;
}

items.push(item);
}

return items;
};

export const takeWhileAll = <T>(
array: T[],
predicate: (current: T[]) => boolean
): T[] => {
const result: T[] = [];

for (let index = 0; index < array.length; index += 1) {
result.push(array[index]);

if (!predicate(result)) {
result.pop();
break;
}
}

return result;
};

export const distinct = <T>(...items: T[]): T[] =>
items.filter((value: T, index: number, self: T[]) => {
Expand Down
2 changes: 1 addition & 1 deletion src/lib/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ const runCommand = (command: CommandDeclaration, options: OptionMap) => {
const message = [`Excuting: router ${chalk.bold(command.fullName)}`];

if (any(command.args)) {
message.push(`with options ${command.args.join(" ")}`);
message.push(` with options '${command.args.join(" ")}'`);
}

message.push(" ...");
Expand Down
35 changes: 34 additions & 1 deletion src/lib/commands/jobs/list.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,43 @@
import cron from "cron-parser";
import { table } from "table";
import { isEmpty } from "../../arrayHelper";
import { ScheduledItem } from "../../../types";
import { parse } from "../../scheduledItemParser";
import ssh from "../../ssh";
import { create } from "../../../models/command";

const description = "Lists existing cron jobs";

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const asTabular = (data: ScheduledItem[]): any[] => {
if (isEmpty(data)) return [];

const tableValues = data.map(x => {
const values = Object.values(x);
const expression = cron.parseExpression(x.cronExpression);
values.push(expression.hasNext() ? expression.next() : "");
return values;
});

const headings = Object.getOwnPropertyNames(data[0]);
headings.push("next run");

tableValues.unshift(headings);

return tableValues;
};

const run = () => {
ssh.execute("cru l");
const result = ssh.execute("cru l", { silent: true });

const parsed = result.stdout
.split("\n")
.map(x => parse(x))
.filter(x => x.id);

const tabularData = asTabular(parsed);
console.log(parsed);
console.log(table(tabularData));
};

export default create({ description, run });
39 changes: 0 additions & 39 deletions src/lib/cronParser.ts

This file was deleted.

39 changes: 39 additions & 0 deletions src/lib/scheduledItemParser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { ScheduledItem } from "../types";
import { takeWhile, takeWhileAll } from "./arrayHelper";

const idMarker = "#";

const parseCronExpression = (row: string[]): [string, string[]] => {
const result = takeWhileAll(row, x => x.filter(z => z === " ").length < 5);
const remainder = row.slice(result.length + 1);

return [result.join("").trim(), remainder];
};

const parseCommand = (row: string[]): [string, string[]] => {
const result = takeWhile(row, x => x !== idMarker);
const remainder = row.slice(result.length + 1);

return [result.join("").trim(), remainder];
};

const parseId = (row: string[]): string => {
return row
.join("")
.replace(new RegExp(`${idMarker}`, "g"), "")
.trim();
};

export const parse = (row: string): ScheduledItem => {
const [cronExpression, cronRemainder] = parseCronExpression([...row]);
const [command, commandRemainder] = parseCommand(cronRemainder);
const id = parseId(commandRemainder);

const item: ScheduledItem = {
id,
command,
cronExpression
};

return item;
};
7 changes: 7 additions & 0 deletions src/models/scheduledItem.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { ScheduledItem } from "../types";

export const empty: ScheduledItem = {
id: "empty",
cronExpression: "* * * * *",
command: ""
};
5 changes: 5 additions & 0 deletions src/types/ScheduledItem.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export interface ScheduledItem {
id: string;
cronExpression: string;
command: string;
}
1 change: 1 addition & 0 deletions src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,5 @@ export { ParseResult } from "./ParseResult";
export { default as PromptType } from "./PromptType";
export { default as PromptBody } from "./PromptBody";
export { default as SshConfig } from "./SshConfig";
export { ScheduledItem } from "./ScheduledItem";
export { StringComparison } from "./StringComparison";
20 changes: 0 additions & 20 deletions test/cronParser.test.ts

This file was deleted.

0 comments on commit ae32baa

Please sign in to comment.