-
Notifications
You must be signed in to change notification settings - Fork 4
Add CLI for manipulating source and sourcemap files. #40
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
0d1b21a
cli: add initial @backtrace/cli project
perf2711 381584a
cli: add command-line-args and command-line-usage package
perf2711 b7daa13
cli: add commands support
perf2711 76351de
cli: add logger implementation and usage
perf2711 4f17e11
cli: add reference to @backtrace/sourcemap-tools
perf2711 ac3df9c
cli: add common functions
perf2711 c0ae4da
cli: add process command
perf2711 b42befc
cli: add upload command
perf2711 185fd52
cli: add addSources command
perf2711 ef539e4
cli: add archive output feature
perf2711 c18dfc1
cli: change verbosity levels
perf2711 d47bc17
cli: add doc to find
perf2711 6cffee7
cli: extract 'backtrace' command name to a const
perf2711 04ce448
cli: fix file collisions in uploaded zip archive
perf2711 8180cfb
cli: change default Command generic param to object
perf2711 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
| { | ||
| "name": "@backtrace/javascript-cli", | ||
| "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" | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| }; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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> { | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. hmm can we be more descriptive what we want to find here?
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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()]); | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@backtrace/javascript-cli commandssounds 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?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes, add: