@stacksjs/cli 0.65.0 → 0.67.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/cli.ts DELETED
@@ -1,30 +0,0 @@
1
- // import type { CliOptions } from '@stacksjs/types'
2
- import { CAC } from 'cac'
3
-
4
- export interface ParsedArgv {
5
- args: ReadonlyArray<string>
6
- options: {
7
- [k: string]: any
8
- }
9
- }
10
-
11
- interface CliOptions {
12
- name?: string
13
- // version: string
14
- // description: string
15
- }
16
-
17
- export function cli(name?: string | CliOptions, options?: CliOptions): CAC {
18
- if (typeof name === 'object') {
19
- options = name
20
- name = options.name
21
- }
22
-
23
- return new CAC(name || 'buddy')
24
- }
25
-
26
- export { CAC }
27
-
28
- // export function command(name: string, description: string, options?: CliOptions) {
29
- // return cli(options).command(name, description)
30
- // }
package/src/command.ts DELETED
@@ -1,54 +0,0 @@
1
- import type { Result } from '@stacksjs/error-handling'
2
- import type { CliOptions, Readable, Subprocess, Writable } from '@stacksjs/types'
3
- import { runCommand } from './run'
4
-
5
- type CommandOptionTuple = [string, string, { default: boolean }]
6
- interface CommandOptionObject {
7
- name: string
8
- description: string
9
- default: boolean | string
10
- }
11
- type CommandOptions = CommandOptionTuple | CommandOptionObject[]
12
- interface Options {
13
- name: string
14
- description: string
15
- active: boolean
16
- options: CommandOptions
17
- run: (options?: CliOptions) => Promise<any>
18
- onFail: (error: Error) => void
19
- onSuccess: () => void
20
- }
21
-
22
- export class Command {
23
- name: Options['name']
24
- description: Options['description']
25
- options: Options['options']
26
- run: Options['run']
27
- onFail: Options['onFail']
28
- onSuccess: Options['onSuccess']
29
-
30
- constructor({ name, description, options, run, onFail, onSuccess }: Options) {
31
- this.name = name
32
- this.description = description
33
- this.options = options
34
- this.run = run
35
- this.onFail = onFail
36
- this.onSuccess = onSuccess
37
- }
38
- }
39
-
40
- export const command = {
41
- run: async (
42
- command: string,
43
- options?: CliOptions,
44
- ): Promise<Result<Subprocess<Writable, Readable, Readable>, Error>> => {
45
- return await runCommand(command, options)
46
- },
47
-
48
- runSync: async (
49
- command: string,
50
- options?: CliOptions,
51
- ): Promise<Result<Subprocess<Writable, Readable, Readable>, Error>> => {
52
- return await runCommand(command, options)
53
- },
54
- }
package/src/console.ts DELETED
@@ -1,4 +0,0 @@
1
- import { log } from '@stacksjs/logging'
2
- import prompts from 'prompts'
3
-
4
- export { log, prompts }
package/src/exec.ts DELETED
@@ -1,140 +0,0 @@
1
- import type { CliOptions, ErrorLike, SpawnOptions, Subprocess } from '@stacksjs/types'
2
- import process from 'node:process'
3
- import { err, handleError, ok, type Result } from '@stacksjs/error-handling'
4
- import { ExitCode } from '@stacksjs/types'
5
- import { italic, log } from './'
6
-
7
- /**
8
- * Execute a command.
9
- *
10
- * @param command The command to execute.
11
- * @param options The options to pass to the command.
12
- * @returns The result of the command.
13
- * @example
14
- * ```ts
15
- * const result = await exec('ls')
16
- *
17
- * if (result.isErr())
18
- * console.error(result.error)
19
- * else
20
- * console.log(result)
21
- * ```
22
- * @example
23
- * ```ts
24
- * const result = await exec('ls', { cwd: '/home' })
25
- * ```
26
- */
27
- export async function exec(command: string | string[], options?: CliOptions): Promise<Result<Subprocess, Error>> {
28
- const cmd = Array.isArray(command) ? command : command.match(/(?:[^\s"]|"[^"]*")+/g)
29
-
30
- if (!cmd)
31
- return err(handleError(`Failed to parse command: ${cmd}`, options))
32
-
33
- log.debug('exec:', Array.isArray(command) ? command.join(' ') : command)
34
- log.debug('cmd:', cmd)
35
- log.debug('exec options:', options)
36
-
37
- const cwd = options?.cwd ?? process.cwd()
38
- const proc = Bun.spawn(cmd, {
39
- ...options,
40
- stdout:
41
- options?.silent || options?.quiet ? 'ignore' : options?.stdin ? options.stdin : options?.stdout || 'inherit',
42
- stderr: options?.silent || options?.quiet ? 'ignore' : options?.stderr || 'inherit',
43
- detached: options?.background || false,
44
- cwd,
45
- // env: { ...e, ...options?.env },
46
- onExit(
47
- subprocess: Subprocess<SpawnOptions.Writable, SpawnOptions.Readable, SpawnOptions.Readable>,
48
- exitCode: number | null,
49
- signalCode: number | null,
50
- error: ErrorLike | undefined,
51
- ) {
52
- exitHandler('spawn', subprocess, exitCode, signalCode, error)
53
- },
54
- })
55
-
56
- // Check if we need to write to stdin
57
- // this is currently only used for `buddy aws:configure`
58
- if (options?.stdin === 'pipe' && options.input) {
59
- if (proc.stdin) {
60
- // @ts-expect-error - this works even though there is a type error
61
- proc.stdin.write(options.input)
62
- // @ts-expect-error - this works even though there is a type error
63
- proc.stdin.end()
64
- }
65
- }
66
-
67
- const exited = await proc.exited
68
- if (exited === ExitCode.Success)
69
- return ok(proc)
70
-
71
- return err(handleError(`Failed to execute command: ${italic(cmd.join(' '))} in ${italic(cwd)}`, options))
72
- }
73
-
74
- /**
75
- * Execute a command and return result.
76
- *
77
- * @param command The command to execute.
78
- * @returns The result of the command.
79
- * @example
80
- * ```ts
81
- * const output = execSync('ls')
82
- *
83
- * console.log(output)
84
- * ```
85
- * @example
86
- * ```ts
87
- * const output = execSync('ls', { cwd: '/home' })
88
- * ```
89
- */
90
- export async function execSync(command: string | string[], options?: CliOptions): Promise<string> {
91
- log.debug('Running ExecSync:', command)
92
- log.debug('ExecSync Options:', options)
93
-
94
- const cmd = Array.isArray(command) ? command : command.match(/(?:[^\s"]|"[^"]*")+/g)
95
-
96
- if (!cmd) {
97
- log.error(`Failed to parse command: ${cmd}`, options)
98
- process.exit(ExitCode.FatalError)
99
- }
100
-
101
- const proc = Bun.spawnSync(cmd, {
102
- ...options,
103
- stdin: options?.stdin ?? 'inherit',
104
- stdout: options?.stdout ?? 'pipe',
105
- stderr: options?.stderr ?? 'inherit',
106
- cwd: options?.cwd ?? process.cwd(),
107
- // env: { ...Bun.env, ...options?.env },
108
- onExit(
109
- subprocess: Subprocess<SpawnOptions.Writable, SpawnOptions.Readable, SpawnOptions.Readable>,
110
- exitCode: number | null,
111
- signalCode: number | null,
112
- error: ErrorLike | undefined,
113
- ) {
114
- exitHandler('spawnSync', subprocess, exitCode, signalCode, error)
115
- },
116
- })
117
-
118
- return proc.stdout?.toString() ?? ''
119
- }
120
-
121
- function exitHandler(
122
- type: 'spawn' | 'spawnSync',
123
- subprocess: Subprocess,
124
- exitCode: number | null,
125
- signalCode: number | null,
126
- error?: Error,
127
- ) {
128
- log.debug(`exitHandler: ${type}`)
129
- log.debug('subprocess', subprocess)
130
- log.debug('exitCode', exitCode)
131
- log.debug('signalCode', signalCode)
132
-
133
- if (error) {
134
- log.error(error)
135
- process.exit(ExitCode.FatalError)
136
- }
137
-
138
- if (exitCode !== ExitCode.Success && exitCode)
139
- process.exit(exitCode)
140
- }
package/src/helpers.ts DELETED
@@ -1,79 +0,0 @@
1
- import type { IntroOptions, OutroOptions } from '@stacksjs/types'
2
- import { handleError } from '@stacksjs/error-handling'
3
- import { log } from '@stacksjs/logging'
4
- import { ExitCode } from '@stacksjs/types'
5
- import { bgCyan, bold, cyan, dim, gray, green, italic } from 'kolorist'
6
- import { version } from '../package.json'
7
-
8
- /**
9
- * Prints the intro message.
10
- */
11
- export async function intro(command: string, options?: IntroOptions): Promise<number> {
12
- return new Promise((resolve) => {
13
- if (options?.quiet === false) {
14
- console.log()
15
- console.log(cyan(bold('Stacks CLI')) + dim(` v${version}`))
16
- console.log()
17
- }
18
-
19
- log.info(`Running ${bgCyan(italic(bold(` ${command} `)))}`)
20
-
21
- if (options?.showPerformance === false || options?.quiet)
22
- return resolve(0)
23
-
24
- return resolve(performance.now())
25
- })
26
- }
27
-
28
- /**
29
- * Prints the outro message.
30
- */
31
- export function outro(text: string, options?: OutroOptions, error?: Error | string): Promise<number> {
32
- const opts = {
33
- type: 'success',
34
- useSeconds: true,
35
- ...options,
36
- }
37
-
38
- opts.message = options?.message || text
39
-
40
- return new Promise((resolve) => {
41
- if (error)
42
- return handleError(error)
43
-
44
- if (opts?.startTime) {
45
- let time = performance.now() - opts.startTime
46
-
47
- if (opts.useSeconds) {
48
- time = time / 1000
49
- time = Math.round(time * 100) / 100 // https://stackoverflow.com/a/11832950/7811162
50
- }
51
-
52
- if (opts.quiet === true)
53
- return resolve(ExitCode.Success)
54
-
55
- if (error) {
56
- log.error(`[${time.toFixed(2)}${opts.useSeconds ? 's' : 'ms'}] Failed`)
57
- }
58
- else if (opts.type === 'info') {
59
- log.info(`${dim(gray(`[${time.toFixed(2)}${opts.useSeconds ? 's' : 'ms'}]`))} ${opts.message ?? 'Complete'}`)
60
- }
61
- else {
62
- log.success(
63
- `${dim(gray(bold(`[${time.toFixed(2)}${opts.useSeconds ? 's' : 'ms'}]`)))} ${bold(
64
- green(opts.message ?? 'Complete'),
65
- )}`,
66
- )
67
- }
68
- }
69
- else {
70
- if (opts?.type === 'info')
71
- log.info(text)
72
- // the following condition triggers in the case of "Cleaned up" messages
73
- else if (opts?.type === 'success' && opts?.quiet !== true)
74
- log.success(text)
75
- }
76
-
77
- return resolve(ExitCode.Success)
78
- })
79
- }
package/src/index.ts DELETED
@@ -1,10 +0,0 @@
1
- export * from './actions'
2
- export * from './cli'
3
- export * from './command'
4
- export * from './console'
5
- export * from './exec'
6
- export * from './helpers'
7
- export * from './parse'
8
- export * from './run'
9
- export * from './spinner'
10
- export * from './utils'
package/src/parse.ts DELETED
@@ -1,182 +0,0 @@
1
- import process from 'node:process'
2
-
3
- interface ParsedArgv {
4
- args: string[]
5
- options: {
6
- [k: string]: string | boolean | number
7
- }
8
- }
9
-
10
- function isLongOption(arg?: string): boolean {
11
- if (!arg)
12
- return false
13
-
14
- return arg.startsWith('--')
15
- }
16
-
17
- function isShortOption(arg: string): boolean {
18
- return arg.startsWith('-') && !isLongOption(arg)
19
- }
20
-
21
- function parseValue(value: string): string | boolean | number {
22
- if (value === 'true')
23
- return true
24
-
25
- if (value === 'false')
26
- return false
27
-
28
- const numberValue = Number.parseFloat(value)
29
- if (!Number.isNaN(numberValue))
30
- return numberValue
31
-
32
- return value.replace(/"/g, '')
33
- }
34
-
35
- function parseLongOption(
36
- arg: string,
37
- argv: string[],
38
- index: number,
39
- options: { [k: string]: string | boolean | number },
40
- ): number {
41
- const [key, value] = arg.slice(2).split('=')
42
- if (value !== undefined) {
43
- options[key as string] = parseValue(value)
44
- }
45
- else if (index + 1 < argv.length && !argv[index + 1]?.startsWith('-')) {
46
- options[key as string] = argv[index + 1] as string
47
- index++
48
- }
49
- else {
50
- options[key as string] = true
51
- }
52
- return index
53
- }
54
-
55
- function parseShortOption(
56
- arg: string,
57
- argv: string[],
58
- index: number,
59
- options: { [k: string]: string | boolean | number },
60
- ): number {
61
- const [key, value] = arg.slice(1).split('=')
62
-
63
- // Check if key is undefined and handle it
64
- if (key === undefined)
65
- return index
66
-
67
- if (value !== undefined && key !== undefined) {
68
- for (let j = 0; j < key.length; j++) options[key[j] as string] = parseValue(value)
69
- }
70
- else {
71
- for (let j = 0; j < key.length; j++) {
72
- if (index + 1 < argv.length && j === key.length - 1 && !argv[index + 1]?.startsWith('-')) {
73
- options[key[j] as string] = parseValue(argv[index + 1] as string)
74
- index++
75
- }
76
- else {
77
- options[key[j] as string] = true
78
- }
79
- }
80
- }
81
-
82
- return index
83
- }
84
-
85
- export function parseArgv(argv?: string[]): ParsedArgv {
86
- if (argv === undefined)
87
- argv = process.argv.slice(2)
88
-
89
- const args: string[] = []
90
- const options: { [k: string]: string | boolean | number } = {}
91
-
92
- for (let i = 0; i < argv.length; i++) {
93
- const arg = argv[i]
94
- if (!arg)
95
- continue
96
- if (isLongOption(arg))
97
- i = parseLongOption(arg, argv, i, options)
98
- else if (isShortOption(arg))
99
- i = parseShortOption(arg, argv, i, options)
100
- else args.push(arg)
101
- }
102
-
103
- return { args, options }
104
- }
105
-
106
- export function parseArgs(argv?: string[]): string[] {
107
- if (argv === undefined)
108
- argv = process.argv.slice(2)
109
-
110
- return parseArgv(argv).args
111
- }
112
-
113
- interface CliOptions {
114
- dryRun?: boolean
115
- quiet?: boolean
116
- verbose?: boolean
117
- [k: string]: string | boolean | number | undefined
118
- }
119
-
120
- export function parseOptions(options?: CliOptions): CliOptions {
121
- options = options || {}
122
- const defaults = { dryRun: false, quiet: false, verbose: false }
123
- const args = process.argv.slice(2)
124
-
125
- for (let i = 0; i < args.length; i++) {
126
- const arg = args[i]
127
- if (arg?.startsWith('--')) {
128
- const key = arg.substring(2) // remove the --
129
- const camelCaseKey = key.replace(
130
- /-([a-z])/gi,
131
- g => (g[1] ? g[1].toUpperCase() : ''), // convert kebab-case to camelCase
132
- )
133
-
134
- if (i + 1 < args.length && !args?.[i + 1]?.startsWith('--')) {
135
- // if the next arg exists and is not an option
136
- if (args?.[i + 1] === 'true' || args?.[i + 1] === 'false') {
137
- // if the next arg is a boolean
138
- options[camelCaseKey] = args[i + 1] === 'true' // set the value to the boolean
139
- i++
140
- }
141
- else {
142
- options[camelCaseKey] = args[i + 1]
143
- i++
144
- }
145
- }
146
- else {
147
- options[camelCaseKey] = true
148
- }
149
- }
150
- }
151
-
152
- if (Object.keys(options).length === 0)
153
- // if options has no keys, return an empty object
154
- return {}
155
-
156
- return { ...defaults, ...options }
157
- }
158
-
159
- // interface BuddyOptions {
160
- // dryRun?: boolean
161
- // verbose?: boolean
162
- // }
163
- export function buddyOptions(options?: string[] | Record<string, any>): string {
164
- if (Array.isArray(options)) {
165
- options = Array.from(new Set(options)) as string[]
166
- if (Array.isArray(options) && options[0] && !options[0].startsWith('-'))
167
- options.shift()
168
- return options.join(' ')
169
- }
170
-
171
- if (typeof options === 'object' && options !== null) {
172
- return Object.entries(options)
173
- .map(([key, value]) => {
174
- if (value === true)
175
- return `--${key}`
176
- return `--${key} ${value}`
177
- })
178
- .join(' ')
179
- }
180
-
181
- return buddyOptions(process.argv.slice(2))
182
- }
package/src/run.ts DELETED
@@ -1,112 +0,0 @@
1
- import type { Ok, Result } from '@stacksjs/error-handling'
2
- import type { CliOptions, CommandError, Readable, Subprocess, Writable } from '@stacksjs/types'
3
- import process from 'node:process'
4
- import { ExitCode } from '@stacksjs/types'
5
- import { log } from './console'
6
- import { exec, execSync } from './exec'
7
- import { italic } from './utils'
8
-
9
- /**
10
- * Run a command.
11
- *
12
- * @param command The command to run.
13
- * @param options The options to pass to the command.
14
- * @returns The result of the command.
15
- * @example
16
- * ```ts
17
- * const result = await runCommand('ls')
18
- *
19
- * if (result.isErr())
20
- * console.error(result.error)
21
- * else
22
- * console.log(result)
23
- * ```
24
- * @example
25
- * ```ts
26
- * const result = await runCommand('ls', { cwd: '/home' })
27
- *
28
- * if (result.isErr())
29
- * console.error(result.error)
30
- * else
31
- * console.log(result)
32
- * ```
33
- */
34
- export async function runCommand(command: string, options?: CliOptions): Promise<Result<Subprocess, CommandError>> {
35
- log.debug('runCommand:', command)
36
- log.debug('options:', options)
37
-
38
- return await exec(command, options)
39
- }
40
-
41
- export async function runProcess(command: string, options?: CliOptions): Promise<Result<Subprocess, CommandError>> {
42
- log.debug('runProcess:', italic(command))
43
- log.debug('runProcess Options:', options)
44
-
45
- return await exec(command, options)
46
- }
47
-
48
- /**
49
- * Run a command.
50
- *
51
- * @param command The command to run.
52
- * @param options The options to pass to the command.
53
- * @returns The result of the command.
54
- * @example
55
- * ```ts
56
- * const result = runCommandSync('ls')
57
- *
58
- * if (result.isErr())
59
- * console.error(result.error)
60
- * else
61
- * console.log(result)
62
- * ```
63
- * @example
64
- * ```ts
65
- * const result = runCommandSync('ls', { cwd: '/home' })
66
- *
67
- * if (result.isErr())
68
- * console.error(result.error)
69
- * else
70
- * console.log(result)
71
- * ```
72
- */
73
- export async function runCommandSync(command: string, options?: CliOptions): Promise<string> {
74
- log.debug('runCommandSync:', italic(command))
75
- log.debug('runCommandSync Options:', options)
76
-
77
- const result = await execSync(command, options)
78
-
79
- // if (result.isErr())
80
- // return err(result.error)
81
-
82
- // return ok(result.value)
83
-
84
- return result
85
- }
86
-
87
- /**
88
- * Run many commands.
89
- *
90
- * @param commands The command to run.
91
- * @param options The options to pass to the command.
92
- * @returns The result of the command.
93
- */
94
- export async function runCommands(
95
- commands: string[],
96
- options?: CliOptions,
97
- ): Promise<Ok<Subprocess<Writable, Readable, Readable>, Error>[]> {
98
- const results = []
99
-
100
- for (const command of commands) {
101
- const result = await runCommand(command, options)
102
-
103
- if (result.isErr()) {
104
- log.error(result.error)
105
- process.exit(ExitCode.FatalError)
106
- }
107
-
108
- results.push(result)
109
- }
110
-
111
- return results
112
- }
package/src/spinner.ts DELETED
@@ -1,3 +0,0 @@
1
- import ora from 'ora'
2
-
3
- export const spinner: typeof ora = ora
package/src/utils.ts DELETED
@@ -1,83 +0,0 @@
1
- import { collect, type Collection } from '@stacksjs/collections'
2
-
3
- export {
4
- align,
5
- box,
6
- centerAlign,
7
- colorize,
8
- colors,
9
- getColor,
10
- leftAlign,
11
- rightAlign,
12
- stripAnsi,
13
- } from 'consola/utils'
14
-
15
- export * as kolorist from 'kolorist'
16
-
17
- export {
18
- ansi256,
19
- ansi256Bg,
20
- bgBlack,
21
- bgBlue,
22
- bgCyan,
23
- bgGray,
24
- bgGreen,
25
- bgLightBlue,
26
- bgLightCyan,
27
- bgLightGray,
28
- bgLightGreen,
29
- bgLightMagenta,
30
- bgLightRed,
31
- bgLightYellow,
32
- bgMagenta,
33
- bgRed,
34
- bgWhite,
35
- bgYellow,
36
- black,
37
- blue,
38
- bold,
39
- cyan,
40
- dim,
41
- gray,
42
- green,
43
- hidden,
44
- inverse,
45
- italic,
46
- lightBlue,
47
- lightCyan,
48
- lightGray,
49
- lightGreen,
50
- lightMagenta,
51
- lightRed,
52
- lightYellow,
53
- link,
54
- magenta,
55
- red,
56
- reset,
57
- strikethrough,
58
- stripColors,
59
- trueColor,
60
- trueColorBg,
61
- underline,
62
- white,
63
- yellow,
64
- } from 'kolorist'
65
-
66
- export const quotes: Collection<string> = collect([
67
- // could be queried from any API or database
68
- 'The best way to get started is to quit talking and begin doing.',
69
- 'The pessimist sees difficulty in every opportunity. The optimist sees opportunity in every difficulty.',
70
- 'Don’t let yesterday take up too much of today.',
71
- 'You learn more from failure than from success. Don’t let it stop you. Failure builds character.',
72
- 'It’s not whether you get knocked down, it’s whether you get up.',
73
- 'If you are working on something that you really care about, you don’t have to be pushed. The vision pulls you.',
74
- 'People who are crazy enough to think they can change the world, are the ones who do.',
75
- 'Failure will never overtake me if my determination to succeed is strong enough.',
76
- 'Entrepreneurs are great at dealing with uncertainty and also very good at minimizing risk. That’s the classic entrepreneur.',
77
- 'We may encounter many defeats but we must not be defeated.',
78
- 'Knowing is not enough; we must apply. Wishing is not enough; we must do.',
79
- 'Imagine your life is perfect in every respect; what would it look like?',
80
- 'We generate fears while we sit. We overcome them by action.',
81
- 'Whether you think you can or think you can’t, you’re right.',
82
- 'Security is mostly a superstition. Life is either a daring adventure or nothing.',
83
- ])