Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
vCaisim committed Sep 13, 2024
1 parent 71552d5 commit 5f89717
Show file tree
Hide file tree
Showing 10 changed files with 163 additions and 57 deletions.
10 changes: 2 additions & 8 deletions packages/cmd/src/bin/cli-config.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,17 @@
import fs from "fs";
import { CLIOptions, CurrentsConfig, cliOptionsToConfig } from "../config";
import { debug as _debug } from "../debug";
import { getProgram, getCurrentsReporterCommand } from "./program";
import { createTempFile } from "./tmp-file";

const debug = _debug.extend("cli");

export type CurrentsProgram = ReturnType<typeof getProgram>;

export class CLIManager {
program: CurrentsProgram;
cliOptions: CLIOptions;
parsedConfig: Partial<CurrentsConfig>;
configFilePath: string | null = null;

constructor() {
this.program = getProgram(getCurrentsReporterCommand());

this.cliOptions = this.program.parse().opts();
constructor(opts: CLIOptions) {
this.cliOptions = opts;
debug("CLI options: %o", this.cliOptions);

this.parsedConfig = cliOptionsToConfig(this.cliOptions);
Expand Down
7 changes: 7 additions & 0 deletions packages/cmd/src/bin/handlers/api/api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { getCurrentsAPICommand } from "../../program";

export async function apiHandler(
options: ReturnType<ReturnType<typeof getCurrentsAPICommand>["opts"]>
) {
console.log('api', { options });
}
7 changes: 7 additions & 0 deletions packages/cmd/src/bin/handlers/api/get-last-run.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { getLastRunCommand } from "../../program";

export async function getLastRunHandler(
options: ReturnType<ReturnType<typeof getLastRunCommand>["opts"]>
) {
console.log('get-last-run', { options });
}
4 changes: 4 additions & 0 deletions packages/cmd/src/bin/handlers/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export { uploadHandler } from "./upload";
export { apiHandler } from "./api/api";
export { getLastRunHandler } from "./api/get-last-run";

40 changes: 40 additions & 0 deletions packages/cmd/src/bin/handlers/upload.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { CommanderError } from "@commander-js/extra-typings";
import { currentsReporter } from "../..";
import { getCurrentsConfig, setCurrentsConfig } from "../../config";
import { ValidationError } from "../../lib";
import { error, info, success } from "../../logger";
import { CLIManager } from "../cli-config";
import { getCurrentsUploadCommand } from "../program";

export async function uploadHandler(
options: ReturnType<ReturnType<typeof getCurrentsUploadCommand>["opts"]>
) {
const cliManager = new CLIManager(options);
setCurrentsConfig(cliManager.parsedConfig);
const config = getCurrentsConfig();

info("Currents config: %o", {
...config,
recordKey: config?.recordKey ? "*****" : undefined,
});

return currentsReporter()
.then(() => {
success("Script execution finished");
process.exit(0);
})
.catch((e) => {
if (e instanceof CommanderError) {
error(e.message);
process.exit(e.exitCode);
}

if (e instanceof ValidationError) {
error(e.message);
process.exit(1);
}

error("Script execution failed:", e);
process.exit(1);
});
}
39 changes: 4 additions & 35 deletions packages/cmd/src/bin/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,41 +4,10 @@ import "source-map-support/register";

import("dotenv/config");

import { CommanderError } from "commander";
import { getCurrentsConfig, setCurrentsConfig } from "../config";
import { currentsReporter } from "../index";
import { ValidationError } from "../lib";
import { error, info, success } from "../logger";
import { CLIManager } from "./cli-config";
import { getProgram } from "./program";

async function runScript() {
const cliManager = new CLIManager();
setCurrentsConfig(cliManager.parsedConfig);
const config = getCurrentsConfig();

info("Currents config: %o", {
...config,
recordKey: config?.recordKey ? "*****" : undefined,
});
return currentsReporter();
function runScript() {
getProgram().parse();
}

runScript()
.then(() => {
success("Script execution finished");
process.exit(0);
})
.catch((e) => {
if (e instanceof CommanderError) {
error(e.message);
process.exit(e.exitCode);
}

if (e instanceof ValidationError) {
error(e.message);
process.exit(1);
}

error("Script execution failed:", e);
process.exit(1);
});
runScript();
12 changes: 11 additions & 1 deletion packages/cmd/src/bin/options.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Option } from "@commander-js/extra-typings";

import { getEnvironmentVariableName } from "../config";
import { apiCommandConfigKey, getEnvironmentVariableName } from "../config";

export const ciBuildIdOption = new Option(
"--ci-build-id <id>",
Expand Down Expand Up @@ -46,6 +46,16 @@ export const debugOption = new Option("--debug", "enable debug logs")
.env(getEnvironmentVariableName("debug"))
.default(false);

export const apiKeyOption = new Option(
"--api-key <api-key>",
"your API Key obtained from Currents dashboard"
).env(apiCommandConfigKey["apiKey"].env);

export const branchOption = new Option(
"--b, --branch <branch>",
"branch name of the recorded run"
);

function parseCommaSeparatedList(value: string, previous: string[] = []) {
if (value) {
return previous.concat(value.split(",").map((t) => t.trim()));
Expand Down
66 changes: 55 additions & 11 deletions packages/cmd/src/bin/program.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { Command } from "@commander-js/extra-typings";
import chalk from "chalk";

import { reporterVersion } from "../env/versions";
import { dim } from "../logger";
import { apiHandler, getLastRunHandler, uploadHandler } from "./handlers";
import {
apiKeyOption,
branchOption,
ciBuildIdOption,
debugOption,
disableTitleTagsOption,
Expand All @@ -15,14 +17,12 @@ import {
tagOption,
} from "./options";

type CurrentsReporterCommand = Partial<
ReturnType<ReturnType<typeof getCurrentsReporterCommand>["opts"]>
>;

const NAME = "currents";
export const getProgram = (
command: Command<[], CurrentsReporterCommand> = getCurrentsReporterCommand()
) => command.version(reporterVersion);
export const getProgram = () =>
new Command(NAME)
.version(reporterVersion)
.addCommand(getCurrentsUploadCommand(), { isDefault: true })
.addCommand(getCurrentsAPICommand());

const currentsReporterExample = `
----------------------------------------------------
Expand All @@ -46,9 +46,9 @@ ${dim(
)}
`;

export const getCurrentsReporterCommand = () => {
export const getCurrentsUploadCommand = () => {
const command = new Command()
.name(NAME)
.name("upload")
.command("upload")
.showHelpAfterError("(add --help for additional information)")
.allowUnknownOption()
Expand All @@ -64,7 +64,51 @@ ${currentsReporterExample}`
.addOption(disableTitleTagsOption)
.addOption(machineIdOption)
.addOption(debugOption)
.addOption(reportDirOption);
.addOption(reportDirOption)
.action((options) => uploadHandler(options));

return command;
};

const currentsAPIExample = `
----------------------------------------------------
📖 Documentation: https://docs.currents.dev
🤙 Support: [email protected]
----------------------------------------------------
${chalk.bold("Examples")}
Obtain last run data by --ci-build-id:
${dim(`${NAME} api get-last-run --api-key <api-key> --ci-build-id --provider <provider>`)}
Obtain last run data using filters:
${dim(`${NAME} api get-last-run --api-key <api-key> --project-id <project-id> --branch <branch> --tag tagA --tag tagB`)}
`;

export const getLastRunCommand = () => {
const command = new Command()
.name("get-last-run")
.allowUnknownOption()
.addOption(ciBuildIdOption)
.addOption(projectOption)
.addOption(branchOption)
.addOption(tagOption)
.addOption(debugOption)
.action(getLastRunHandler);

return command;
};

export const getCurrentsAPICommand = () => {
const command = new Command()
.command("api")
.description(`Receive information from Currents API ${currentsAPIExample}`)
.showHelpAfterError("(add --help for additional information)")
.allowUnknownOption()
.addCommand(getLastRunCommand())
.addOption(apiKeyOption)
.addOption(debugOption)
.action(apiHandler);

return command;
};
29 changes: 29 additions & 0 deletions packages/cmd/src/config/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,35 @@ export const configKey = {
},
} as const;

export const apiCommandConfigKey = {
apiKey: {
name: "Api Key",
env: "CURRENTS_API_KEY",
cli: "--apiKey",
},
branch: {
name: "Run Branch",
cli: "--branch",
},
debug: {
name: "Debug",
env: "CURRENTS_DEBUG",
cli: "--debug",
},
ciBuildId: {
name: "CI Build ID",
cli: "--ci-build-id",
},
projectId: {
name: "Project ID",
cli: "--project-id",
},
tag: {
name: "Currents Tag",
cli: "--tag",
},
} as const;

export function getEnvironmentVariableName(variable: keyof typeof configKey) {
return configKey[variable].env;
}
Expand Down
6 changes: 4 additions & 2 deletions packages/cmd/src/config/options.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import { Command } from "@commander-js/extra-typings";
import fs from "fs";
import { getProgram } from "../bin/program";
import { getCurrentsUploadCommand } from "../bin/program";
import { debug } from "../debug";

import { CurrentsConfig } from "./config";

type ExtractSecondTags<T> = T extends Command<any, infer U> ? U : never;
export type CLIOptions = ExtractSecondTags<ReturnType<typeof getProgram>>;
export type CLIOptions = ExtractSecondTags<
ReturnType<typeof getCurrentsUploadCommand>
>;

/**
* Converts CLI options to Currents config.
Expand Down

0 comments on commit 5f89717

Please sign in to comment.