@kaynooo/cli-env 0.8.1 → 0.9.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/README.md +6 -4
- package/dist/ev.js +199 -75
- package/dist/redact.js +90 -27
- package/package.json +6 -3
- package/src/audit.ts +167 -0
- package/src/commands/audit.ts +135 -0
- package/src/commands/compare.ts +77 -0
- package/src/commands/edit.ts +181 -0
- package/src/commands/pins.ts +98 -0
- package/src/commands/read.ts +193 -0
- package/src/dotenv.ts +8 -4
- package/src/ev.ts +31 -0
- package/src/files.ts +242 -0
- package/src/fix.ts +294 -0
- package/src/guard-dumps.ts +114 -0
- package/src/guard-names.ts +107 -0
- package/src/guard-paths.ts +80 -0
- package/src/guard-pipes.ts +76 -0
- package/src/guard-search.ts +181 -0
- package/src/guard.ts +51 -0
- package/src/mask.ts +264 -0
- package/src/pins.ts +268 -0
- package/src/redact.ts +43 -0
- package/src/redactor.ts +166 -0
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import { badUsage, fail, parse, readInput } from '@kaynooo/cli-kit'
|
|
2
|
+
import { entries, lastLine, removeKey, setLine } from '../dotenv'
|
|
3
|
+
import { loadKnown, readEnv, withLocks, writeEnv } from '../files'
|
|
4
|
+
import { maskValue } from '../mask'
|
|
5
|
+
|
|
6
|
+
const DEFAULT_FILE = '.env'
|
|
7
|
+
const TRAILING_NEWLINE = /\r?\n$/
|
|
8
|
+
const KEY_NAME = /^[A-Z_][\w.-]*$/i
|
|
9
|
+
|
|
10
|
+
const setUsage = `ev set KEY [file]
|
|
11
|
+
|
|
12
|
+
Sets KEY in the file (.env by default, created when missing), replacing its line in place or appending one. The value is read from stdin, or from -F <file>, so it never appears in a command line; --empty sets it to an empty value.
|
|
13
|
+
|
|
14
|
+
Exits 0 when it wrote the key, 1 when it could not, 2 on a usage error.`
|
|
15
|
+
|
|
16
|
+
const unsetUsage = `ev unset KEY [file]
|
|
17
|
+
|
|
18
|
+
Removes every line setting KEY from the file (.env by default), leaving comments and other lines as they are.
|
|
19
|
+
|
|
20
|
+
Exits 0 when it removed the key, 1 when the file does not set it, 2 on a usage error.`
|
|
21
|
+
|
|
22
|
+
const mvUsage = `ev mv KEY --from <file> --to <file>
|
|
23
|
+
|
|
24
|
+
Moves KEY's line from one file to another, as written. Refuses to replace a key the target already sets unless --force.
|
|
25
|
+
|
|
26
|
+
Exits 0 when it moved the key, 1 when the source lacks it or the target already sets it, 2 on a usage error.`
|
|
27
|
+
|
|
28
|
+
const cpUsage = `ev cp KEY --from <file> --to <file> [--as NEWKEY]
|
|
29
|
+
|
|
30
|
+
Copies KEY's value from one file to another without printing it, replacing the key's line in the target in place or appending one, and prints the masked result as ev set does. --as stores the copy under another key.
|
|
31
|
+
|
|
32
|
+
Exits 0 when it copied the key, 1 when the source lacks it, 2 on a usage error.`
|
|
33
|
+
|
|
34
|
+
async function readValue(from: string | undefined): Promise<string> {
|
|
35
|
+
const input = await readInput(from ?? '-', { noStdin: 'pipe the value on stdin or give -F <file>, it is never taken from the command line' })
|
|
36
|
+
|
|
37
|
+
if (input === '')
|
|
38
|
+
fail('the value is empty, nothing was written: --empty sets an empty value')
|
|
39
|
+
|
|
40
|
+
return input.replace(TRAILING_NEWLINE, '')
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// A key that is not a plain name could carry a line break or an `=` and write more than one line.
|
|
44
|
+
function checkKey(key: string): void {
|
|
45
|
+
if (!KEY_NAME.test(key))
|
|
46
|
+
badUsage(`${JSON.stringify(key)} is not a valid key: letters, digits, _, . and - only, not starting with a digit`)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async function readOrEmpty(path: string) {
|
|
50
|
+
return await Bun.file(path).exists() ? readEnv(path) : { lines: [] }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export async function set(args: string[]): Promise<number> {
|
|
54
|
+
const parsed = parse(args, setUsage, {
|
|
55
|
+
file: { type: 'string', short: 'F', description: 'read the value from this file instead of stdin' },
|
|
56
|
+
empty: { type: 'boolean', description: 'set an empty value, reading nothing' },
|
|
57
|
+
})
|
|
58
|
+
|
|
59
|
+
const [key, target = DEFAULT_FILE] = parsed.positionals
|
|
60
|
+
|
|
61
|
+
if (key === undefined)
|
|
62
|
+
fail(`missing KEY\n\n${setUsage}`)
|
|
63
|
+
|
|
64
|
+
if (parsed.values.empty === true && parsed.values.file !== undefined)
|
|
65
|
+
fail('--empty and -F exclude each other')
|
|
66
|
+
|
|
67
|
+
checkKey(key)
|
|
68
|
+
|
|
69
|
+
const value = parsed.values.empty === true ? '' : await readValue(parsed.values.file)
|
|
70
|
+
|
|
71
|
+
const file = await withLocks([target], async () => {
|
|
72
|
+
const current = await readOrEmpty(target)
|
|
73
|
+
|
|
74
|
+
setLine(current, key, value)
|
|
75
|
+
await writeEnv(target, current)
|
|
76
|
+
|
|
77
|
+
return current
|
|
78
|
+
})
|
|
79
|
+
|
|
80
|
+
console.log(`${target}: ${key}=${maskValue(key, value, await loadKnown(process.cwd(), [file])).replaceAll('\n', '\\n')}`)
|
|
81
|
+
|
|
82
|
+
return 0
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export async function unset(args: string[]): Promise<number> {
|
|
86
|
+
const parsed = parse(args, unsetUsage, {})
|
|
87
|
+
|
|
88
|
+
const [key, target = DEFAULT_FILE] = parsed.positionals
|
|
89
|
+
|
|
90
|
+
if (key === undefined)
|
|
91
|
+
fail(`missing KEY\n\n${unsetUsage}`)
|
|
92
|
+
|
|
93
|
+
await withLocks([target], async () => {
|
|
94
|
+
const file = await readEnv(target)
|
|
95
|
+
|
|
96
|
+
if (removeKey(file, key) === 0)
|
|
97
|
+
fail(`${key} is not set in ${target}`, 1)
|
|
98
|
+
|
|
99
|
+
await writeEnv(target, file)
|
|
100
|
+
})
|
|
101
|
+
|
|
102
|
+
console.log(`${target}: removed ${key}`)
|
|
103
|
+
|
|
104
|
+
return 0
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// The write path of mv and cp: puts KEY's line from `from` into `to`, as `newKey` when given, and returns both files for the caller to finish.
|
|
108
|
+
async function transfer(key: string, from: string, to: string, newKey: string | undefined, replace: boolean) {
|
|
109
|
+
checkKey(key)
|
|
110
|
+
|
|
111
|
+
if (newKey !== undefined)
|
|
112
|
+
checkKey(newKey)
|
|
113
|
+
|
|
114
|
+
if (from === to && newKey === undefined)
|
|
115
|
+
fail('--from and --to are the same file')
|
|
116
|
+
|
|
117
|
+
const source = await readEnv(from)
|
|
118
|
+
const line = lastLine(source, key)
|
|
119
|
+
|
|
120
|
+
if (line === undefined)
|
|
121
|
+
fail(`${key} is not set in ${from}`, 1)
|
|
122
|
+
|
|
123
|
+
const target = from === to ? source : await readOrEmpty(to)
|
|
124
|
+
const name = newKey ?? key
|
|
125
|
+
|
|
126
|
+
if (!replace && entries(target).has(name))
|
|
127
|
+
fail(`${to} already sets ${name}, --force replaces it`, 1)
|
|
128
|
+
|
|
129
|
+
const value = line.value ?? ''
|
|
130
|
+
|
|
131
|
+
setLine(target, name, value, newKey === undefined && !entries(target).has(name) ? line.raw : undefined)
|
|
132
|
+
await writeEnv(to, target)
|
|
133
|
+
|
|
134
|
+
return { source, target, value, name }
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export async function mv(args: string[]): Promise<number> {
|
|
138
|
+
const parsed = parse(args, mvUsage, {
|
|
139
|
+
from: { type: 'string', description: 'the file to take KEY from' },
|
|
140
|
+
to: { type: 'string', description: 'the file to put KEY in, created when missing' },
|
|
141
|
+
force: { type: 'boolean', description: 'replace KEY when the target already sets it' },
|
|
142
|
+
})
|
|
143
|
+
|
|
144
|
+
const [key] = parsed.positionals
|
|
145
|
+
const { from, to, force } = parsed.values
|
|
146
|
+
|
|
147
|
+
if (key === undefined || from === undefined || to === undefined)
|
|
148
|
+
fail(`needs KEY, --from and --to\n\n${mvUsage}`)
|
|
149
|
+
|
|
150
|
+
await withLocks([from, to], async () => {
|
|
151
|
+
const { source } = await transfer(key, from, to, undefined, force === true)
|
|
152
|
+
|
|
153
|
+
removeKey(source, key)
|
|
154
|
+
await writeEnv(from, source)
|
|
155
|
+
})
|
|
156
|
+
|
|
157
|
+
console.log(`${key}: ${from} -> ${to}`)
|
|
158
|
+
|
|
159
|
+
return 0
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export async function cp(args: string[]): Promise<number> {
|
|
163
|
+
const parsed = parse(args, cpUsage, {
|
|
164
|
+
from: { type: 'string', description: 'the file to take KEY from' },
|
|
165
|
+
to: { type: 'string', description: 'the file to put the copy in, created when missing' },
|
|
166
|
+
as: { type: 'string', description: 'store the copy under this key instead' },
|
|
167
|
+
})
|
|
168
|
+
|
|
169
|
+
const [key] = parsed.positionals
|
|
170
|
+
const { from, to, as } = parsed.values
|
|
171
|
+
|
|
172
|
+
if (key === undefined || from === undefined || to === undefined)
|
|
173
|
+
fail(`needs KEY, --from and --to\n\n${cpUsage}`)
|
|
174
|
+
|
|
175
|
+
const { source, target, value, name } = await withLocks([from, to], async () => transfer(key, from, to, as, true))
|
|
176
|
+
const known = await loadKnown(process.cwd(), [source, target])
|
|
177
|
+
|
|
178
|
+
console.log(`${to}: ${name}=${maskValue(name, value, known).replaceAll('\n', '\\n')}`)
|
|
179
|
+
|
|
180
|
+
return 0
|
|
181
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import type { AppPins } from '../pins'
|
|
2
|
+
import { readdir, stat } from 'node:fs/promises'
|
|
3
|
+
import { join, resolve } from 'node:path'
|
|
4
|
+
import { fail, jsonOption, ok, parse, printJson } from '@kaynooo/cli-kit'
|
|
5
|
+
import { checkApp } from '../pins'
|
|
6
|
+
|
|
7
|
+
const usage = `ev pins [dir] [--except NAME,...]
|
|
8
|
+
|
|
9
|
+
Checks that an app's tests pin the env that reaches outside.
|
|
10
|
+
Reads the app's env schema (the file calling defineEnv, src/env.ts) and lists its optional URL, key, token, secret, password and host variables, then the ones no \`.env.test\` entry, test-level overrideEnv or local bunfig preload dropping what .env sets pins, and each test file that calls testSite or proxyKeyTests without pinning them all.
|
|
11
|
+
A file whose pages reach none of them says so with a \`// ev pins: none reached, <why>\` comment.
|
|
12
|
+
The dir is an app, or a monorepo holding apps one level down (the current folder by default).
|
|
13
|
+
Reads variable names only, never a value.
|
|
14
|
+
Exits 0 when everything is pinned, 1 when something is not, 2 on a usage error.`
|
|
15
|
+
|
|
16
|
+
const options = {
|
|
17
|
+
json: jsonOption('each app with its reaching, unpinned variables and flagged test files'),
|
|
18
|
+
except: { type: 'string', description: 'comma-separated variables to leave out, as ones that only link back to the app' },
|
|
19
|
+
} as const
|
|
20
|
+
|
|
21
|
+
async function isFolder(path: string): Promise<boolean> {
|
|
22
|
+
try {
|
|
23
|
+
return (await stat(path)).isDirectory()
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return false
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
async function apps(dir: string, except: ReadonlySet<string>): Promise<AppPins[]> {
|
|
31
|
+
const own = await checkApp(dir, except)
|
|
32
|
+
|
|
33
|
+
if (own !== undefined)
|
|
34
|
+
return [own]
|
|
35
|
+
|
|
36
|
+
const found: AppPins[] = []
|
|
37
|
+
|
|
38
|
+
for (const entry of (await readdir(dir, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
39
|
+
if (!entry.isDirectory() || entry.name.startsWith('.') || entry.name === 'node_modules')
|
|
40
|
+
continue
|
|
41
|
+
|
|
42
|
+
const app = await checkApp(join(dir, entry.name), except)
|
|
43
|
+
|
|
44
|
+
if (app !== undefined)
|
|
45
|
+
found.push(app)
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
return found
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function failing(app: AppPins): boolean {
|
|
52
|
+
return app.unpinned.length > 0 || app.files.length > 0
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function name(app: AppPins, root: string): string {
|
|
56
|
+
return app.app === root ? app.app.split('/').at(-1) ?? app.app : app.app.slice(root.length + 1)
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export async function pins(args: string[]): Promise<number> {
|
|
60
|
+
const parsed = parse(args, usage, options, { positionals: ['[dir]'] })
|
|
61
|
+
const json = parsed.values.json === true
|
|
62
|
+
const root = resolve(parsed.positionals[0] ?? '.')
|
|
63
|
+
const except = new Set((parsed.values.except ?? '').split(',').map(entry => entry.trim()).filter(entry => entry !== ''))
|
|
64
|
+
|
|
65
|
+
if (!await isFolder(root))
|
|
66
|
+
fail(`${root} is not a folder`)
|
|
67
|
+
|
|
68
|
+
const found = await apps(root, except)
|
|
69
|
+
|
|
70
|
+
if (found.length === 0)
|
|
71
|
+
fail(`no env schema (a defineEnv call in src/env.ts) in ${root} or its folders`)
|
|
72
|
+
|
|
73
|
+
if (json) {
|
|
74
|
+
printJson(found.map(app => ({ ...app, app: name(app, root) })))
|
|
75
|
+
|
|
76
|
+
return found.some(failing) ? 1 : 0
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
for (const app of found) {
|
|
80
|
+
const label = name(app, root)
|
|
81
|
+
|
|
82
|
+
if (!failing(app)) {
|
|
83
|
+
ok(label, app.preload === undefined ? `${app.reaching.length} reaching variables pinned` : `every variable pinned by ${app.preload}`)
|
|
84
|
+
|
|
85
|
+
continue
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
console.log(`${label}: ${app.reaching.length} optional variables reach outside`)
|
|
89
|
+
|
|
90
|
+
if (app.unpinned.length > 0)
|
|
91
|
+
console.log(` unpinned by .env.test or any overrideEnv: ${app.unpinned.join(', ')}`)
|
|
92
|
+
|
|
93
|
+
for (const { file, unpinned } of app.files)
|
|
94
|
+
console.log(` ${file} renders a page without pinning: ${unpinned.join(', ')}`)
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
return found.some(failing) ? 1 : 0
|
|
98
|
+
}
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import type { Dotenv } from '../dotenv'
|
|
2
|
+
import type { KnownSecrets } from '../mask'
|
|
3
|
+
import { fail, jsonOption, parse, printJson, table } from '@kaynooo/cli-kit'
|
|
4
|
+
import { $ } from 'bun'
|
|
5
|
+
import { entries, parseDotenv } from '../dotenv'
|
|
6
|
+
import { envFiles, loadKnown, readEnv } from '../files'
|
|
7
|
+
import { isSecretKey, maskValue } from '../mask'
|
|
8
|
+
|
|
9
|
+
const listUsage = `ev list [file]
|
|
10
|
+
|
|
11
|
+
Prints every key of the folder's .env* files, or of one file, with secret values masked: a few leading characters and the length under a key named like TOKEN, SECRET, PASSWORD, PASS, PWD, KEY, PRIVATE, DSN, AUTH, SALT or COOKIE, any value equal to a secret of the folder's .env* files, and the password and tokens of any URL.
|
|
12
|
+
|
|
13
|
+
--json prints [{file, key, value, secret}], value masked and secret true when a value was.
|
|
14
|
+
|
|
15
|
+
Exits 0 when it printed them, 1 when there is no .env* file, 2 on a usage error.`
|
|
16
|
+
|
|
17
|
+
const getUsage = `ev get KEY [file]
|
|
18
|
+
|
|
19
|
+
Prints the masked value of one key, from every .env* file that sets it or from one file.
|
|
20
|
+
|
|
21
|
+
--json prints [{file, key, value, secret}] for each file that sets it.
|
|
22
|
+
|
|
23
|
+
Exits 0 when the key is set, 1 when it is not set anywhere, 2 on a usage error.`
|
|
24
|
+
|
|
25
|
+
function display(key: string, value: string, known: KnownSecrets): string {
|
|
26
|
+
return maskValue(key, value, known).replaceAll('\n', '\\n').replaceAll('\r', '\\r')
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const jsonFlag = { json: jsonOption() } as const
|
|
30
|
+
|
|
31
|
+
interface Row { file: string, key: string, value: string, secret: boolean }
|
|
32
|
+
|
|
33
|
+
// A value is secret when it is masked, or when its key is named like a secret even with nothing to mask.
|
|
34
|
+
function row(file: string, key: string, value: string, known: KnownSecrets): Row {
|
|
35
|
+
const shown = display(key, value, known)
|
|
36
|
+
|
|
37
|
+
return { file, key, value: shown, secret: shown !== value.replaceAll('\n', '\\n').replaceAll('\r', '\\r') || isSecretKey(key) }
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function printRows(rows: Row[], json: boolean, plain: () => void): void {
|
|
41
|
+
if (json)
|
|
42
|
+
printJson(rows)
|
|
43
|
+
else
|
|
44
|
+
plain()
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// Reads each file once and learns the secrets of the folder and of these files, so a value is masked whatever key holds it.
|
|
48
|
+
async function readAll(names: string[]): Promise<{ files: [name: string, file: Dotenv][], known: KnownSecrets }> {
|
|
49
|
+
const files: [string, Dotenv][] = []
|
|
50
|
+
|
|
51
|
+
for (const name of names)
|
|
52
|
+
files.push([name, await readEnv(name)])
|
|
53
|
+
|
|
54
|
+
return { files, known: await loadKnown(process.cwd(), files.map(([, file]) => file)) }
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export async function list(args: string[]): Promise<number> {
|
|
58
|
+
const parsed = parse(args, listUsage, jsonFlag)
|
|
59
|
+
|
|
60
|
+
const [file] = parsed.positionals
|
|
61
|
+
const names = file === undefined ? await envFiles() : [file]
|
|
62
|
+
|
|
63
|
+
if (names.length === 0)
|
|
64
|
+
fail('no .env* file in this folder', 1)
|
|
65
|
+
|
|
66
|
+
const rows: Row[] = []
|
|
67
|
+
|
|
68
|
+
const { files, known } = await readAll(names)
|
|
69
|
+
|
|
70
|
+
for (const [name, file] of files) {
|
|
71
|
+
for (const [key, value] of entries(file))
|
|
72
|
+
rows.push(row(name, key, value, known))
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
printRows(rows, parsed.values.json === true, () => {
|
|
76
|
+
if (rows.length > 0)
|
|
77
|
+
console.log(table(rows.map(each => [each.file, each.key, each.value])))
|
|
78
|
+
})
|
|
79
|
+
|
|
80
|
+
return 0
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export async function get(args: string[]): Promise<number> {
|
|
84
|
+
const parsed = parse(args, getUsage, jsonFlag)
|
|
85
|
+
|
|
86
|
+
const [key, file] = parsed.positionals
|
|
87
|
+
|
|
88
|
+
if (key === undefined)
|
|
89
|
+
fail(`missing KEY\n\n${getUsage}`)
|
|
90
|
+
|
|
91
|
+
const names = file === undefined ? await envFiles() : [file]
|
|
92
|
+
const rows: Row[] = []
|
|
93
|
+
|
|
94
|
+
const { files, known } = await readAll(names)
|
|
95
|
+
|
|
96
|
+
for (const [name, file] of files) {
|
|
97
|
+
const value = entries(file).get(key)
|
|
98
|
+
|
|
99
|
+
if (value !== undefined)
|
|
100
|
+
rows.push(row(name, key, value, known))
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
if (rows.length === 0)
|
|
104
|
+
fail(`${key} is not set in ${file ?? 'any .env* file'}`, 1)
|
|
105
|
+
|
|
106
|
+
printRows(rows, parsed.values.json === true, () => console.log(file === undefined ? table(rows.map(each => [each.file, each.value])) : rows[0]?.value))
|
|
107
|
+
|
|
108
|
+
return 0
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const grepUsage = `ev grep [-i] <regex> [file...]
|
|
112
|
+
|
|
113
|
+
Prints the keys matching the regular expression, from the folder's .env* files or the files given, with their values masked as ev list does. The regex is matched against the key only, never the value: \`ev grep '^DATABASE_'\` instead of \`grep ^DATABASE_ .env\`.
|
|
114
|
+
|
|
115
|
+
--json prints [{file, key, value, secret}].
|
|
116
|
+
|
|
117
|
+
Exits 0 when a key matches, 1 when none does, 2 on a usage error.`
|
|
118
|
+
|
|
119
|
+
const showUsage = `ev show <rev>:<file>
|
|
120
|
+
|
|
121
|
+
Prints every key of an env file as a git revision holds it, values masked as ev list does: \`ev show HEAD~1:api/.env\` instead of \`git show HEAD~1:api/.env\`.
|
|
122
|
+
|
|
123
|
+
--json prints [{file, key, value, secret}].
|
|
124
|
+
|
|
125
|
+
Exits 0 when it printed them, 1 when git cannot show the file, 2 on a usage error.`
|
|
126
|
+
|
|
127
|
+
const REVISION = /^([^:]+):(.+)$/
|
|
128
|
+
|
|
129
|
+
export async function grep(args: string[]): Promise<number> {
|
|
130
|
+
const parsed = parse(args, grepUsage, { 'ignore-case': { type: 'boolean', short: 'i', description: 'match the key whatever its case' }, ...jsonFlag })
|
|
131
|
+
|
|
132
|
+
const [source, ...given] = parsed.positionals
|
|
133
|
+
|
|
134
|
+
if (source === undefined)
|
|
135
|
+
fail(`missing the regex\n\n${grepUsage}`)
|
|
136
|
+
|
|
137
|
+
let pattern: RegExp
|
|
138
|
+
|
|
139
|
+
try {
|
|
140
|
+
pattern = new RegExp(source, parsed.values['ignore-case'] === true ? 'i' : '')
|
|
141
|
+
}
|
|
142
|
+
catch (error) {
|
|
143
|
+
fail(`${source} is no valid regular expression: ${error instanceof Error ? error.message : String(error)}`)
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const names = given.length === 0 ? await envFiles() : given
|
|
147
|
+
const rows: Row[] = []
|
|
148
|
+
|
|
149
|
+
const { files, known } = await readAll(names)
|
|
150
|
+
|
|
151
|
+
for (const [name, file] of files) {
|
|
152
|
+
for (const [key, value] of entries(file)) {
|
|
153
|
+
if (pattern.test(key))
|
|
154
|
+
rows.push(row(name, key, value, known))
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
if (rows.length === 0)
|
|
159
|
+
fail(`no key matches ${source} in ${names.join(', ') || 'any .env* file'}`, 1)
|
|
160
|
+
|
|
161
|
+
printRows(rows, parsed.values.json === true, () => console.log(table(rows.map(each => [each.file, each.key, each.value]))))
|
|
162
|
+
|
|
163
|
+
return 0
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export async function show(args: string[]): Promise<number> {
|
|
167
|
+
const parsed = parse(args, showUsage, jsonFlag)
|
|
168
|
+
|
|
169
|
+
const [target] = parsed.positionals
|
|
170
|
+
const [, revision, path] = REVISION.exec(target ?? '') ?? []
|
|
171
|
+
|
|
172
|
+
if (revision === undefined || path === undefined)
|
|
173
|
+
fail(`give <rev>:<file>\n\n${showUsage}`)
|
|
174
|
+
|
|
175
|
+
if (revision.startsWith('-'))
|
|
176
|
+
fail(`${revision} is not a revision: it reads as a git option`)
|
|
177
|
+
|
|
178
|
+
const shown = await $`git show --end-of-options ${`${revision}:${path}`}`.quiet().nothrow()
|
|
179
|
+
|
|
180
|
+
if (shown.exitCode !== 0)
|
|
181
|
+
fail(`git show ${revision}:${path} failed: ${shown.stderr.toString().trim()}`, 1)
|
|
182
|
+
|
|
183
|
+
const file = parseDotenv(shown.stdout.toString())
|
|
184
|
+
const known = await loadKnown(process.cwd(), [file])
|
|
185
|
+
const rows = [...entries(file)].map(([key, value]) => row(target ?? '', key, value, known))
|
|
186
|
+
|
|
187
|
+
printRows(rows, parsed.values.json === true, () => {
|
|
188
|
+
if (rows.length > 0)
|
|
189
|
+
console.log(table(rows.map(each => [each.key, each.value])))
|
|
190
|
+
})
|
|
191
|
+
|
|
192
|
+
return 0
|
|
193
|
+
}
|
package/src/dotenv.ts
CHANGED
|
@@ -14,7 +14,8 @@ const EXPORTED = /^\s*export\s/
|
|
|
14
14
|
const INLINE_COMMENT = /\s+#.*$/
|
|
15
15
|
const CARRIAGE_RETURN = /\r$/
|
|
16
16
|
const ESCAPES: Record<string, string> = { 'n': '\n', 'r': '\r', 't': '\t', '"': '"', '\\': '\\', '$': '$' }
|
|
17
|
-
|
|
17
|
+
|
|
18
|
+
export const LINE_BREAK = /[\r\n]/
|
|
18
19
|
// Bun does not unescape these inside double quotes, so a value holding one is written in single quotes.
|
|
19
20
|
const RAW_ONLY = /["\\]/
|
|
20
21
|
const NEEDS_QUOTES = /[\s#"'\\$`]/
|
|
@@ -113,6 +114,11 @@ export function entries(file: Dotenv): Map<string, string> {
|
|
|
113
114
|
return map
|
|
114
115
|
}
|
|
115
116
|
|
|
117
|
+
// A value written between double quotes, each `$` escaped because Bun expands it in every quoting.
|
|
118
|
+
export function escapeDouble(value: string): string {
|
|
119
|
+
return value.replaceAll('\\', '\\\\').replaceAll('"', '\\"').replaceAll('\r', '\\r').replaceAll('\n', '\\n').replaceAll('$', '\\$')
|
|
120
|
+
}
|
|
121
|
+
|
|
116
122
|
export function formatAssignment(key: string, value: string): string {
|
|
117
123
|
if (value === '' || !NEEDS_QUOTES.test(value))
|
|
118
124
|
return `${key}=${value}`
|
|
@@ -121,9 +127,7 @@ export function formatAssignment(key: string, value: string): string {
|
|
|
121
127
|
if (RAW_ONLY.test(value) && !value.includes('\'') && !LINE_BREAK.test(value))
|
|
122
128
|
return `${key}='${value.replaceAll('$', '\\$')}'`
|
|
123
129
|
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
return `${key}="${escaped}"`
|
|
130
|
+
return `${key}="${escapeDouble(value)}"`
|
|
127
131
|
}
|
|
128
132
|
|
|
129
133
|
// Replaces the last assignment of a key keeping its `export`, or appends before the trailing newline. `raw` is the whole line to store when given.
|
package/src/ev.ts
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
|
|
3
|
+
import process from 'node:process'
|
|
4
|
+
import { runCli } from '@kaynooo/cli-kit'
|
|
5
|
+
import { audit } from './commands/audit'
|
|
6
|
+
import { diff, missing } from './commands/compare'
|
|
7
|
+
import { cp, mv, set, unset } from './commands/edit'
|
|
8
|
+
import { pins } from './commands/pins'
|
|
9
|
+
import { get, grep, list, show } from './commands/read'
|
|
10
|
+
|
|
11
|
+
process.exitCode = await runCli({
|
|
12
|
+
name: 'ev',
|
|
13
|
+
about: '.env files listed and edited with secrets masked',
|
|
14
|
+
replaces: 'cat .env, grep on env files and editing them by hand',
|
|
15
|
+
examples: ['ev list', ['ev get DATABASE_URL', 'one key, its value masked']],
|
|
16
|
+
commands: {
|
|
17
|
+
list: { run: list, summary: 'every key of the .env* files, secrets masked' },
|
|
18
|
+
get: { run: get, summary: 'one key\'s masked value' },
|
|
19
|
+
grep: { run: grep, summary: 'the keys matching a regex, values masked' },
|
|
20
|
+
show: { run: show, summary: 'an env file at a git revision, values masked' },
|
|
21
|
+
set: { run: set, summary: 'set a key, the value read from stdin or -F' },
|
|
22
|
+
unset: { run: unset, summary: 'remove a key from a file' },
|
|
23
|
+
cp: { run: cp, summary: 'copy a key from one file to another, the value never printed' },
|
|
24
|
+
mv: { run: mv, summary: 'move a key from one file to another' },
|
|
25
|
+
diff: { run: diff, summary: 'keys set in one file and not the other' },
|
|
26
|
+
missing: { run: missing, summary: 'keys of .env.example that .env lacks' },
|
|
27
|
+
pins: { run: pins, summary: 'the env vars reaching outside that an app\'s tests leave to a developer\'s env' },
|
|
28
|
+
audit: { run: audit, summary: '.env files others can read or git tracks, compose files writing secrets out' },
|
|
29
|
+
},
|
|
30
|
+
aliases: { ls: 'list' },
|
|
31
|
+
})
|