Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
695 changes: 408 additions & 287 deletions package-lock.json

Large diffs are not rendered by default.

21 changes: 21 additions & 0 deletions tools/cli/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 Backtrace Labs

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
48 changes: 48 additions & 0 deletions tools/cli/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
{
"name": "@backtrace/javascript-cli",
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@backtrace/javascript-cli commands sounds really weird. Shouldn't we think about a different name for CLI? javascript cli definitely sounds odd. In our monorepo it makes sense to keep is as cli, however adding cli in cli sounds weird.

We have concept of morgue, coroner, heracles, etc. How about using naming it in a different way. or at least Backtrace-javascript?

Edit:

based on what I see for example in nest: https://docs.nestjs.com/cli/overview do you know how we can trigger our cli via a different name?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, add:

{
  "bin": {
    "<execName>": "lib/index.js"
  }
}

"version": "0.0.1",
"description": "Backtrace CLI for working with Javascript files.",
"main": "lib/index.js",
"types": "lib/index.d.ts",
"engines": {
"node": ">=14"
},
"scripts": {
"build": "tsc",
"clean": "tsc -b --clean && rimraf \"lib\"",
"format": "prettier --write '**/*.ts'",
"lint": "eslint . --ext .ts",
"watch": "tsc -w",
"start": "node lib/index.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/backtrace-labs/backtrace-javascript.git"
},
"keywords": [
"Error",
"Reporting",
"Diagnostic",
"Tool",
"Bug",
"Bugs",
"StackTrace",
"Source maps",
"Sourcemaps"
],
"author": "Backtrace <team@backtrace.io>",
"license": "MIT",
"bugs": {
"url": "https://github.com/backtrace-labs/backtrace-javascript/issues"
},
"homepage": "https://github.com/backtrace-labs/backtrace-javascript#readme",
"dependencies": {
"@backtrace/sourcemap-tools": "^0.0.1",
"command-line-args": "^5.2.1",
"command-line-usage": "^7.0.1"
},
"devDependencies": {
"@types/command-line-args": "^5.2.0",
"@types/command-line-usage": "^5.0.2"
}
}
168 changes: 168 additions & 0 deletions tools/cli/src/commands/Command.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
import { Err, Ok, Result } from '@backtrace/sourcemap-tools';
import commandLineArgs from 'command-line-args';
import commandLineUsage, { Section } from 'command-line-usage';
import { LoggerOptions, createLogger } from '../logger';
import { CommandError } from '../models/CommandError';
import { ExtendedOptionDefinition } from '../models/OptionDefinition';

const CLI_COMMAND = 'backtrace';

export class Command<T extends object = object> {
public readonly subcommands: Command[] = [];
public readonly options: ExtendedOptionDefinition[] = [];
public readonly helpSections: Section[] = [];
private _execute?: (
this: this,
values: Partial<T>,
stack?: Command[],
) => Result<number, string> | Promise<Result<number, string>>;

constructor(public readonly definition: ExtendedOptionDefinition) {}

public subcommand(command: Command): this {
this.subcommands.push(command);
return this;
}

public option<N extends keyof T & string>(option: ExtendedOptionDefinition<N>): this {
this.options.push(option);
return this;
}

public help(...sections: Section[]): this {
this.helpSections.push(...sections);
return this;
}

public execute(fn: Command<T>['_execute']): this {
this._execute = fn;
return this;
}

public async run(argv: string[], stack?: Command[]): Promise<Result<number, CommandError>> {
const stackOptions = stack?.flatMap((s) => s.options.filter((o) => o.global)) ?? [];
const localOptions = [...this.options, ...stackOptions];
const subcommandOption = {
name: '_subcommand',
defaultOption: true,
};

const subCommandMode = !!this.subcommands.length;
if (subCommandMode) {
localOptions.push(subcommandOption);
}

const values = commandLineArgs(localOptions, {
argv,
stopAtFirstUnknown: subCommandMode,
});

if (subCommandMode && values._subcommand) {
const subcommand = this.subcommands.find((s) => s.definition.name === values._subcommand);
if (subcommand) {
const subcommandValues = commandLineArgs([subcommandOption], { argv, stopAtFirstUnknown: true });
return await subcommand.run(subcommandValues._unknown ?? [], [...(stack ?? []), this]);
}
}

const logger = createLogger(values as LoggerOptions);

if (values.help) {
logger.output(this.getHelpMessage(stack));
return Ok(0);
}

if (this._execute) {
return (await this._execute.call(this, values as T, stack)).mapErr((error) => ({
command: this,
error,
stack,
}));
}

logger.info(this.getHelpMessage(stack));

if (subCommandMode) {
return Err({ command: this, stack, error: 'Unknown command.' });
}

return Err({ command: this, stack, error: 'Unknown option.' });
}

public getHelpMessage(stack?: Command[]) {
const globalOptions = [
...this.options.filter((o) => o.global),
...(stack?.flatMap((o) => o.options.filter((o) => o.global)) ?? []),
];

const nonGlobalOptions = this.options.filter((o) => !o.global);

let cmd = CLI_COMMAND;
const stackCmd = `${
[...(stack ?? []), this]
.map((s) => s.definition.name)
.filter((s) => !!s)
.join(' ') ?? ''
}`;

if (stackCmd) {
cmd += ` ${stackCmd}`;
}

let usage = cmd;
if (this.subcommands.length) {
usage += ' <command>';
}

const defaultOption =
nonGlobalOptions.find((s) => s.defaultOption) ?? globalOptions.find((s) => s.defaultOption);
if (defaultOption) {
usage += ` <${defaultOption.name}>`;
}

if (globalOptions.length + nonGlobalOptions.length) {
usage += ' [options]';
}

const sections: Section[] = [
{
header: cmd,
content: 'Backtrace utility for managing Javascript files.',
},
];

if (this.helpSections.length) {
sections.push(...this.helpSections);
}

sections.push({
content: `Usage: ${usage}`,
});

if (this.subcommands.length) {
sections.push({
header: 'Available commands',
content: this.subcommands.map((s) => ({
name: s.definition.name,
summary: s.definition.description,
})),
});
}

if (nonGlobalOptions.length) {
sections.push({
header: 'Available options',
optionList: nonGlobalOptions,
});
}

if (globalOptions.length) {
sections.push({
header: 'Global options',
optionList: globalOptions,
});
}

return commandLineUsage(sections);
}
}
69 changes: 69 additions & 0 deletions tools/cli/src/helpers/common.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { Err, Ok, Result, ResultPromise } from '@backtrace/sourcemap-tools';
import fs from 'fs';
import { Readable } from 'stream';

export type ContentFile = readonly [content: string, path: string];
export type StreamFile = readonly [stream: Readable, path: string];

export async function readFile(file: string): ResultPromise<string, string> {
try {
return Ok(await fs.promises.readFile(file, 'utf-8'));
} catch (err) {
return Err(`failed to read file: ${err instanceof Error ? err.message : 'unknown error'}`);
}
}

export async function writeFile(file: ContentFile) {
const [content, path] = file;
try {
await fs.promises.writeFile(path, content);
return Ok(file);
} catch (err) {
return Err(`failed to write file: ${err instanceof Error ? err.message : 'unknown error'}`);
}
}

export async function writeStream(file: StreamFile) {
const [stream, path] = file;
try {
const output = fs.createWriteStream(path);
stream.pipe(output);
return new Promise<Result<StreamFile, string>>((resolve) => {
output.on('error', (err) => {
resolve(Err(`failed to write file: ${err.message}`));
});

output.on('finish', () => resolve(Ok(file)));
});
} catch (err) {
return Err(`failed to write file: ${err instanceof Error ? err.message : 'unknown error'}`);
}
}

export function parseJSON<T>(content: string): Result<T, string> {
try {
return Ok(JSON.parse(content));
} catch (err) {
return Err(`failed to parse content: ${err instanceof Error ? err.message : 'unknown error'}`);
}
}

export function pass<T>(t: T): T {
return t;
}

export function passOk<T>(t: T): Result<T, never> {
return Ok(t);
}

export function failIfEmpty<E>(error: E) {
return function failIfEmpty<T>(t: T[]): Result<T[], E> {
return t.length ? Ok(t) : Err(error);
};
}

export function map<T, B>(fn: (t: T) => B) {
return function map(t: T[]) {
return t.map(fn);
};
}
41 changes: 41 additions & 0 deletions tools/cli/src/helpers/find.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { Err, FileFinder, Ok, ResultPromise } from '@backtrace/sourcemap-tools';
import fs from 'fs';
import path from 'path';

/**
* Returns files found in directories matching `regex`. If path is a file, it is returned if it matches `regex`.
* @param regex Regular expression pattern to match.
* @param paths Paths to search in.
* @returns Result with file paths.
*/
export async function find(regex: RegExp, ...paths: string[]): ResultPromise<string[], string> {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hmm can we be more descriptive what we want to find here?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added a doc.

const finder = new FileFinder();
const results = new Map<string, string>();
for (const findPath of paths) {
const stat = await fs.promises.stat(findPath);
if (!stat.isDirectory()) {
if (!findPath.match(regex)) {
return Err(`${findPath} does not match regex: ${regex}`);
}
const fullPath = path.resolve(findPath);
if (!results.has(fullPath)) {
results.set(fullPath, findPath);
}
continue;
}

const findResult = await finder.find(findPath, { match: regex, recursive: true });
if (findResult.isErr()) {
return findResult;
}

for (const result of findResult.data) {
const fullPath = path.resolve(result);
if (!results.has(fullPath)) {
results.set(fullPath, result);
}
}
}

return Ok([...results.values()]);
}
Loading