@stacksjs/cli 0.64.6 → 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) {
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,47 +0,0 @@
1
- import type { CliOptions } from '@stacksjs/types'
2
- import { runCommand } from './run'
3
-
4
- type CommandOptionTuple = [string, string, { default: boolean }]
5
- interface CommandOptionObject {
6
- name: string
7
- description: string
8
- default: boolean | string
9
- }
10
- type CommandOptions = CommandOptionTuple | CommandOptionObject[]
11
- interface Options {
12
- name: string
13
- description: string
14
- active: boolean
15
- options: CommandOptions
16
- run: (options?: CliOptions) => Promise<any>
17
- onFail: (error: Error) => void
18
- onSuccess: () => void
19
- }
20
-
21
- export class Command {
22
- name: Options['name']
23
- description: Options['description']
24
- options: Options['options']
25
- run: Options['run']
26
- onFail: Options['onFail']
27
- onSuccess: Options['onSuccess']
28
-
29
- constructor({ name, description, options, run, onFail, onSuccess }: Options) {
30
- this.name = name
31
- this.description = description
32
- this.options = options
33
- this.run = run
34
- this.onFail = onFail
35
- this.onSuccess = onSuccess
36
- }
37
- }
38
-
39
- export const command = {
40
- run: async (command: string, options?: CliOptions) => {
41
- return await runCommand(command, options)
42
- },
43
-
44
- runSync: async (command: string, options?: CliOptions) => {
45
- return await runCommand(command, options)
46
- },
47
- }
package/src/console.ts DELETED
@@ -1,4 +0,0 @@
1
- import { log } from '@stacksjs/logging'
2
- import prompts from 'prompts'
3
-
4
- export { prompts, log }
package/src/exec.ts DELETED
@@ -1,122 +0,0 @@
1
- import process from 'node:process'
2
- import { type Result, err, handleError, ok } from '@stacksjs/error-handling'
3
- import type { CliOptions, Subprocess } from '@stacksjs/types'
4
- import { ExitCode } from '@stacksjs/types'
5
- import { 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) return err(handleError(`Failed to parse command: ${cmd}`, options))
31
-
32
- log.debug('exec:', Array.isArray(command) ? command.join(' ') : command)
33
- log.debug('cmd:', cmd)
34
- log.debug('exec options:', options)
35
- const cwd = options?.cwd || process.cwd()
36
-
37
- const proc = Bun.spawn(cmd, {
38
- ...options,
39
- stdout:
40
- options?.silent || options?.quiet ? 'ignore' : options?.stdin ? options.stdin : options?.stdout || 'inherit',
41
- stderr: options?.silent || options?.quiet ? 'ignore' : options?.stderr || 'inherit',
42
- detached: options?.background || false,
43
- cwd,
44
- // env: { ...e, ...options?.env },
45
- onExit(subprocess, exitCode, signalCode, error) {
46
- exitHandler('spawn', subprocess, exitCode, signalCode, error)
47
- },
48
- })
49
-
50
- // Check if we need to write to stdin
51
- // this is currently only used for `buddy aws:configure`
52
- if (options?.stdin === 'pipe' && options.input) {
53
- if (proc.stdin) {
54
- // @ts-expect-error - this works even though there is a type error
55
- proc.stdin.write(options.input)
56
- // @ts-expect-error - this works even though there is a type error
57
- proc.stdin.end()
58
- }
59
- }
60
-
61
- const exited = await proc.exited
62
- if (exited === ExitCode.Success) return ok(proc)
63
-
64
- return err(handleError(`Failed to execute command: ${cmd.join(' ')}`))
65
- }
66
-
67
- /**
68
- * Execute a command and return result.
69
- *
70
- * @param command The command to execute.
71
- * @returns The result of the command.
72
- * @example
73
- * ```ts
74
- * const output = execSync('ls')
75
- *
76
- * console.log(output)
77
- * ```
78
- * @example
79
- * ```ts
80
- * const output = execSync('ls', { cwd: '/home' })
81
- * ```
82
- */
83
- export async function execSync(command: string | string[], options?: CliOptions): Promise<string> {
84
- log.debug('Running ExecSync:', command)
85
- log.debug('ExecSync Options:', options)
86
-
87
- const cmd = Array.isArray(command) ? command : command.match(/(?:[^\s"]+|"[^"]*")+/g)
88
-
89
- if (!cmd) {
90
- log.error(`Failed to parse command: ${cmd}`, options)
91
- process.exit(ExitCode.FatalError)
92
- }
93
-
94
- const proc = Bun.spawnSync(cmd, {
95
- ...options,
96
- stdin: options?.stdin ?? 'inherit',
97
- stdout: options?.stdout ?? 'pipe',
98
- stderr: options?.stderr ?? 'inherit',
99
- cwd: options?.cwd ?? process.cwd(),
100
- // env: { ...Bun.env, ...options?.env },
101
- onExit(subprocess, exitCode, signalCode, error) {
102
- exitHandler('spawnSync', subprocess, exitCode, signalCode, error)
103
- },
104
- })
105
-
106
- return proc.stdout.toString()
107
- }
108
-
109
- // @ts-expect-error - missing types is okay here but can be improved later on
110
- function exitHandler(type: 'spawn' | 'spawnSync', subprocess, exitCode, signalCode, error) {
111
- log.debug(`exitHandler: ${type}`)
112
- log.debug('subprocess', subprocess)
113
- log.debug('exitCode', exitCode)
114
- log.debug('signalCode', signalCode)
115
-
116
- if (error) {
117
- log.error(error)
118
- process.exit(ExitCode.FatalError)
119
- }
120
-
121
- if (exitCode !== ExitCode.Success && exitCode) process.exit(exitCode)
122
- }
package/src/helpers.ts DELETED
@@ -1,69 +0,0 @@
1
- import { handleError } from '@stacksjs/error-handling'
2
- import { log } from '@stacksjs/logging'
3
- import type { IntroOptions, OutroOptions } from '@stacksjs/types'
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) return resolve(0)
22
-
23
- return resolve(performance.now())
24
- })
25
- }
26
-
27
- /**
28
- * Prints the outro message.
29
- */
30
- export function outro(text: string, options?: OutroOptions, error?: Error | string) {
31
- const opts = {
32
- type: 'success',
33
- useSeconds: true,
34
- ...options,
35
- }
36
-
37
- opts.message = options?.message || text
38
-
39
- return new Promise((resolve) => {
40
- if (error) return handleError(error)
41
-
42
- if (opts?.startTime) {
43
- let time = performance.now() - opts.startTime
44
-
45
- if (opts.useSeconds) {
46
- time = time / 1000
47
- time = Math.round(time * 100) / 100 // https://stackoverflow.com/a/11832950/7811162
48
- }
49
-
50
- if (opts.quiet === true) return resolve(ExitCode.Success)
51
-
52
- if (error) log.error(`[${time.toFixed(2)}${opts.useSeconds ? 's' : 'ms'}] Failed`)
53
- else if (opts.type === 'info')
54
- log.info(`${dim(gray(`[${time.toFixed(2)}${opts.useSeconds ? 's' : 'ms'}]`))} ${opts.message ?? 'Complete'}`)
55
- else
56
- log.success(
57
- `${dim(gray(bold(`[${time.toFixed(2)}${opts.useSeconds ? 's' : 'ms'}]`)))} ${bold(
58
- green(opts.message ?? 'Complete'),
59
- )}`,
60
- )
61
- } else {
62
- if (opts?.type === 'info') log.info(text)
63
- // the following condition triggers in the case of "Cleaned up" messages
64
- else if (opts?.type === 'success' && opts?.quiet !== true) log.success(text)
65
- }
66
-
67
- return resolve(ExitCode.Success)
68
- })
69
- }
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 './helpers'
6
- export * from './parse'
7
- export * from './exec'
8
- export * from './run'
9
- export * from './spinner'
10
- export * from './utils'
package/src/parse.ts DELETED
@@ -1,170 +0,0 @@
1
- import process from 'node:process'
2
- import { log } from '@stacksjs/logging'
3
-
4
- interface ParsedArgv {
5
- args: string[]
6
- options: {
7
- [k: string]: string | boolean | number
8
- }
9
- }
10
-
11
- function isLongOption(arg?: string): boolean {
12
- if (!arg) 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') return true
23
-
24
- if (value === 'false') return false
25
-
26
- const numberValue = Number.parseFloat(value)
27
- if (!Number.isNaN(numberValue)) return numberValue
28
-
29
- return value.replace(/"/g, '')
30
- }
31
-
32
- function parseLongOption(
33
- arg: string,
34
- argv: string[],
35
- index: number,
36
- options: { [k: string]: string | boolean | number },
37
- ): number {
38
- const [key, value] = arg.slice(2).split('=')
39
- if (value !== undefined) {
40
- options[key as string] = parseValue(value)
41
- } else if (index + 1 < argv.length && !argv[index + 1]?.startsWith('-')) {
42
- options[key as string] = argv[index + 1] as string
43
- index++
44
- } else {
45
- options[key as string] = true
46
- }
47
- return index
48
- }
49
-
50
- function parseShortOption(
51
- arg: string,
52
- argv: string[],
53
- index: number,
54
- options: { [k: string]: string | boolean | number },
55
- ): number {
56
- const [key, value] = arg.slice(1).split('=')
57
-
58
- // Check if key is undefined and handle it
59
- if (key === undefined) return index
60
-
61
- if (value !== undefined && key !== undefined) {
62
- for (let j = 0; j < key.length; j++) options[key[j] as string] = parseValue(value)
63
- } else {
64
- for (let j = 0; j < key.length; j++) {
65
- if (index + 1 < argv.length && j === key.length - 1 && !argv[index + 1]?.startsWith('-')) {
66
- options[key[j] as string] = parseValue(argv[index + 1] as string)
67
- index++
68
- } else {
69
- options[key[j] as string] = true
70
- }
71
- }
72
- }
73
-
74
- return index
75
- }
76
-
77
- export function parseArgv(argv?: string[]): ParsedArgv {
78
- if (argv === undefined) argv = process.argv.slice(2)
79
-
80
- const args: string[] = []
81
- const options: { [k: string]: string | boolean | number } = {}
82
-
83
- for (let i = 0; i < argv.length; i++) {
84
- const arg = argv[i]
85
- if (!arg) continue
86
- if (isLongOption(arg)) i = parseLongOption(arg, argv, i, options)
87
- else if (isShortOption(arg)) i = parseShortOption(arg, argv, i, options)
88
- else args.push(arg)
89
- }
90
-
91
- return { args, options }
92
- }
93
-
94
- export function parseArgs(argv?: string[]): string[] {
95
- if (argv === undefined) argv = process.argv.slice(2)
96
-
97
- return parseArgv(argv).args
98
- }
99
-
100
- interface CliOptions {
101
- dryRun?: boolean
102
- quiet?: boolean
103
- verbose?: boolean
104
- [k: string]: string | boolean | number | undefined
105
- }
106
-
107
- export function parseOptions(options?: CliOptions): CliOptions {
108
- options = options || {}
109
- const args = process.argv.slice(2)
110
-
111
- for (let i = 0; i < args.length; i++) {
112
- const arg = args[i]
113
- if (arg?.startsWith('--')) {
114
- const key = arg.substring(2) // remove the --
115
- const camelCaseKey = key.replace(
116
- /-([a-z])/gi,
117
- (g) => (g[1] ? g[1].toUpperCase() : ''), // convert kebab-case to camelCase
118
- )
119
-
120
- if (i + 1 < args.length) {
121
- // if the next arg exists
122
- if (args[i + 1] === 'true' || args[i + 1] === 'false') {
123
- // if the next arg is a boolean
124
- options[camelCaseKey] = args[i + 1] === 'true' // set the value to the boolean
125
- i++
126
- } else {
127
- options[camelCaseKey] = args[i + 1]
128
- i++
129
- }
130
- } else {
131
- options[camelCaseKey] = true
132
- }
133
- }
134
- }
135
-
136
- // if options has no keys, return undefined, e.g. `buddy release`
137
- if (Object.keys(options).length === 0) return { dryRun: false, quiet: false, verbose: false }
138
-
139
- // convert the string 'true' or 'false' to a boolean
140
- Object.keys(options).forEach((key) => {
141
- if (!options) return { dryRun: false, quiet: false, verbose: false }
142
-
143
- const value = options[key]
144
-
145
- if (value === 'true' || value === 'false') options[key] = value === 'true'
146
- })
147
-
148
- return options
149
- }
150
- // interface BuddyOptions {
151
- // dryRun?: boolean
152
- // verbose?: boolean
153
- // }
154
- export function buddyOptions(options?: any): string {
155
- if (!options) {
156
- options = process.argv.slice(2)
157
- options = Array.from(new Set(options))
158
- // delete the 0 element if it does not start with a -
159
- // e.g. is used when buddy changelog --dry-run is used
160
- if (options[0] && !options[0].startsWith('-')) options.shift()
161
- }
162
-
163
- if (options?.verbose) {
164
- log.debug('process.argv', process.argv)
165
- log.debug('process.argv.slice(2)', process.argv.slice(2))
166
- log.debug('options inside buddyOptions', options)
167
- }
168
-
169
- return options.join(' ')
170
- }
package/src/run.ts DELETED
@@ -1,108 +0,0 @@
1
- import type { Result } from '@stacksjs/error-handling'
2
- import type { CliOptions, CommandError, Subprocess } from '@stacksjs/types'
3
- import { ExitCode } from '@stacksjs/types'
4
- import { log } from './console'
5
- import { exec, execSync } from './exec'
6
- import { italic } from './utils'
7
-
8
- /**
9
- * Run a command.
10
- *
11
- * @param command The command to run.
12
- * @param options The options to pass to the command.
13
- * @returns The result of the command.
14
- * @example
15
- * ```ts
16
- * const result = await runCommand('ls')
17
- *
18
- * if (result.isErr())
19
- * console.error(result.error)
20
- * else
21
- * console.log(result)
22
- * ```
23
- * @example
24
- * ```ts
25
- * const result = await runCommand('ls', { cwd: '/home' })
26
- *
27
- * if (result.isErr())
28
- * console.error(result.error)
29
- * else
30
- * console.log(result)
31
- * ```
32
- */
33
- export async function runCommand(command: string, options?: CliOptions): Promise<Result<Subprocess, CommandError>> {
34
- log.debug('runCommand:', command)
35
- log.debug('options:', options)
36
-
37
- return await exec(command, options)
38
- }
39
-
40
- export async function runProcess(command: string, options?: CliOptions): Promise<Result<Subprocess, CommandError>> {
41
- log.debug('runProcess:', italic(command))
42
- log.debug('runProcess Options:', options)
43
-
44
- return await exec(command, options)
45
- }
46
-
47
- /**
48
- * Run a command.
49
- *
50
- * @param command The command to run.
51
- * @param options The options to pass to the command.
52
- * @returns The result of the command.
53
- * @example
54
- * ```ts
55
- * const result = runCommandSync('ls')
56
- *
57
- * if (result.isErr())
58
- * console.error(result.error)
59
- * else
60
- * console.log(result)
61
- * ```
62
- * @example
63
- * ```ts
64
- * const result = runCommandSync('ls', { cwd: '/home' })
65
- *
66
- * if (result.isErr())
67
- * console.error(result.error)
68
- * else
69
- * console.log(result)
70
- * ```
71
- */
72
- export async function runCommandSync(command: string, options?: CliOptions): Promise<string> {
73
- log.debug('runCommandSync:', italic(command))
74
- log.debug('runCommandSync Options:', options)
75
-
76
- const result = await execSync(command, options)
77
-
78
- // if (result.isErr())
79
- // return err(result.error)
80
-
81
- // return ok(result.value)
82
-
83
- return result
84
- }
85
-
86
- /**
87
- * Run many commands.
88
- *
89
- * @param commands The command to run.
90
- * @param options The options to pass to the command.
91
- * @returns The result of the command.
92
- */
93
- export async function runCommands(commands: string[], options?: CliOptions) {
94
- const results = []
95
-
96
- for (const command of commands) {
97
- const result = await runCommand(command, options)
98
-
99
- if (result.isErr()) {
100
- log.error(result.error)
101
- process.exit(ExitCode.FatalError)
102
- }
103
-
104
- results.push(result)
105
- }
106
-
107
- return results
108
- }
package/src/spinner.ts DELETED
@@ -1,3 +0,0 @@
1
- import ora from 'ora'
2
-
3
- export const spinner = ora
package/src/utils.ts DELETED
@@ -1,83 +0,0 @@
1
- import { collect } from '@stacksjs/collections'
2
-
3
- export * as kolorist from 'kolorist'
4
-
5
- export {
6
- stripAnsi,
7
- centerAlign,
8
- rightAlign,
9
- leftAlign,
10
- align,
11
- box,
12
- colors,
13
- getColor,
14
- colorize,
15
- } from 'consola/utils'
16
-
17
- export {
18
- ansi256Bg,
19
- bgBlack,
20
- bgBlue,
21
- bgCyan,
22
- bgGray,
23
- bgGreen,
24
- bgLightBlue,
25
- bgLightCyan,
26
- bgLightGray,
27
- bgLightGreen,
28
- bgLightMagenta,
29
- bgLightRed,
30
- bgLightYellow,
31
- bgMagenta,
32
- bgRed,
33
- bgWhite,
34
- bgYellow,
35
- black,
36
- blue,
37
- bold,
38
- cyan,
39
- dim,
40
- gray,
41
- green,
42
- hidden,
43
- inverse,
44
- italic,
45
- lightBlue,
46
- lightCyan,
47
- lightGray,
48
- lightGreen,
49
- lightMagenta,
50
- lightRed,
51
- lightYellow,
52
- link,
53
- magenta,
54
- red,
55
- reset,
56
- strikethrough,
57
- underline,
58
- white,
59
- yellow,
60
- ansi256,
61
- trueColor,
62
- trueColorBg,
63
- stripColors,
64
- } from 'kolorist'
65
-
66
- export const quotes = 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
- ])