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
2 changes: 1 addition & 1 deletion docs/deeper-dives/shellcode.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ tea integrate --dry-run
Then integrate:

```sh
tea integrate
eval "$(tea integrate)"
```


Expand Down
4 changes: 2 additions & 2 deletions docs/shell-integration.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ will let you know:
```sh
$ tea +node
tea: error: shellcode not loaded
tea: ^^run: source <(tea integrate)
tea: ^^run: eval "$(tea integrate)"
```

Integration is minimal. We write one line to your `.shellrc` that adds a few
Expand All @@ -73,7 +73,7 @@ tea integrate --dry-run
And then finally integrate:

```sh
$ source <(tea integrate)
$ eval "$(tea integrate)"

$ tea +node
(+node) $ node --version
Expand Down
2 changes: 1 addition & 1 deletion entrypoint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ const argstr = Deno.args.join(' ')

if (/--hook(=[a-z]+)?/.test(argstr) || argstr == '--env --keep-going --silent --dry-run=w/trace' || argstr == '-Eds' || argstr == "+tea.xyz/magic -Esk --chaste env") {
perror('deprecated', 'tea magic', [
['type `tea integrate` to use our new integrations']
['type `tea integrate --dry-run` to use our new integrations']
], 'https://help.tea.xyz/v0-migration-guide')
}
if (parseInt(Deno.env.get("TEA_LVL")!) >= 10) {
Expand Down
4 changes: 2 additions & 2 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export default async function({ flags, ...opts }: Args, logger_prefix?: string)
}
} break
case 'integrate':
await integrate('install')
await integrate('install', opts)
break
case 'internal.use': {
await ensure_pantry()
Expand All @@ -69,7 +69,7 @@ export default async function({ flags, ...opts }: Args, logger_prefix?: string)
await install(await Promise.all(opts.args.map(x => parse_pkg_str(x, {latest: 'ok'}))))
break
case 'deintegrate':
await integrate('uninstall')
await integrate('uninstall', opts)
break
case 'shellcode':
console.log(shellcode())
Expand Down
8 changes: 7 additions & 1 deletion src/modes/integrate.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// deno-lint-ignore-file no-explicit-any
import { afterEach, beforeEach, describe, afterAll, it } from "deno/testing/bdd.ts"
import specimen, { _internals } from "./integrate.ts"
import specimen0, { _internals } from "./integrate.ts"
import { assertRejects } from "deno/assert/mod.ts"
import * as mock from "deno/testing/mock.ts"
import { isString } from "is-what"
Expand All @@ -9,6 +10,11 @@ describe("integrate.ts", () => {
let file: Path
let stub1: mock.Stub<typeof _internals>

const specimen = async (op: any) => {
await specimen0(op, {dryrun: false})
await specimen0(op, {dryrun: true})
}

const stub2 = mock.stub(_internals, "stderr", () => {})
const stub3 = mock.stub(_internals, "stdout", x => isString(x))

Expand Down
43 changes: 32 additions & 11 deletions src/modes/integrate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,20 @@ import { readAll } from "deno/streams/read_all.ts"
import { readLines } from "deno/io/read_lines.ts"
import { Path, TeaError, utils } from "tea"
import shellcode from "./shellcode.ts"
import { dim } from "deno/fmt/colors.ts"
const { flatmap, host } = utils

//TODO could be a fun efficiency excercise to maintain a separate write file-pointer
//FIXME assumes unix line-endings

export default async function(op: 'install' | 'uninstall') {
export default async function(op: 'install' | 'uninstall', { dryrun }: { dryrun: boolean }) {
let opd_at_least_once = false
const encode = (e => e.encode.bind(e))(new TextEncoder())

const fopts = { read: true, ...dryrun ? {} : {write: true, create: true} }

here: for (const [file, line] of shells()) {
const fd = await Deno.open(file.string, {read: true, write: true, create: true})
const fd = await Deno.open(file.string, fopts)
try {
let pos = 0
for await (const readline of readLines(fd)) {
Expand All @@ -26,9 +29,9 @@ export default async function(op: 'install' | 'uninstall') {
await fd.seek(pos + readline.length + 1, Deno.SeekMode.Start)
const rest = await readAll(fd)

await fd.truncate(pos) // deno has no way I can find to truncate from the current seek position
if (!dryrun) await fd.truncate(pos) // deno has no way I can find to truncate from the current seek position
await fd.seek(pos, Deno.SeekMode.Start)
await writeAll(fd, rest)
if (!dryrun) await writeAll(fd, rest)

opd_at_least_once = true
_internals.stderr("removed hook:", file)
Expand All @@ -51,30 +54,32 @@ export default async function(op: 'install' | 'uninstall') {
await fd.seek(-1, Deno.SeekMode.Current)
pos -= 1
}
}

await writeAll(fd, encode(`\n\n${line} #docs.tea.xyz/shellcode\n`))

if (!dryrun) await writeAll(fd, encode(`\n\n${line} #docs.tea.xyz/shellcode\n`))
}
opd_at_least_once = true
_internals.stderr(`${file} << \`${line}\``)
}
} finally {
fd.close()
}
}

switch (op) {
if (dryrun && opd_at_least_once) {
const instruction = op == 'install' ? 'eval "$(tea integrate)"' : 'tea deintegrate'
_internals.stderr()
render('this was a dry-run', 'to actually perform the above, run:', [[],[` ${instruction}`],[]], 'https://docs.tea.xyz/shell-integration')
} else switch (op) {
case 'uninstall':
if (!opd_at_least_once) {
_internals.stderr("no hooks to uninstall found")
_internals.stderr("nothing to deintegrate found")
}
break
case 'install':
if (!_internals.isatty(Deno.stdout.rid)) {
// we're being sourced, output the hook
_internals.stdout(shellcode())
} else if (opd_at_least_once) {
_internals.stderr("restart your terminal for `tea` hooks to take effect")
_internals.stderr("%crestart your terminal%c for `tea` hooks to take effect", 'color: #00FFD0', 'color: initial')
}
}
}
Expand Down Expand Up @@ -119,3 +124,19 @@ export const _internals = {
stdout: console.log,
stderr: console.error
}


export function render(title: string, subtitle: string | undefined, body: (string[])[], help: string | undefined) {
const console = { error: _internals.stderr }
if (subtitle) {
console.error('%c┐ %s %c%s', 'color: #00FFD0', title, 'color: initial', subtitle)
} else {
console.error('%c× %s', 'color: #00FFD0', title)
}
for (const [s1, ...ss] of body) {
console.error(`%c│%c ${s1 ?? ''}`, 'color: #00FFD0', 'color: initial', ...ss)
}
help ??= 'unknown-error'
const url = help.startsWith('http') ? help : `https://help.tea.xyz/${help}`
console.error('%c╰─➤%c %s', 'color: #00FFD0', 'color: initial', dim(url))
}
21 changes: 17 additions & 4 deletions src/parse-args.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,23 @@ Deno.test("parse_args.ts", async runner => {
assertEquals(rv.pkgs.plus, args)
})

await runner.step("--shellcode", () => {
const args = faker_args()
const rv = parse_args(['--shellcode', ...args])
assertEquals(rv.mode, 'shellcode')
await runner.step("integrate", async runner => {
await runner.step("--dry-run", () => {
const args = faker_args()
const rv = parse_args(['integrate', '--dry-run', ...args])
if (rv.mode !== 'integrate') fail()
assertEquals(rv.dryrun, true)
})
await runner.step("w/o --dry-run", () => {
const args = faker_args()
const rv = parse_args(['integrate', ...args])
if (rv.mode !== 'integrate') fail()
assertEquals(rv.dryrun, false)
})
await runner.step("--dry-run with other modes throws", () => {
const args = faker_args()
assertThrows(() => parse_args(['--dry-run', '--help', ...args]))
})
})

await runner.step("run", () => {
Expand Down
17 changes: 16 additions & 1 deletion src/parse-args.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,10 @@ export type Args = {
minus: string[]
}
} | {
mode: 'shellcode' | 'integrate' | 'deintegrate' | 'version' | 'help'
mode: 'shellcode' | 'version' | 'help'
} | {
mode: 'integrate' | 'deintegrate'
dryrun: boolean
} | {
mode: 'which' | 'shell-completion'
args: string[]
Expand Down Expand Up @@ -52,6 +55,7 @@ export default function(input: string[]): Args {
update: false
}
let mode: string | undefined
let dryrun: boolean | undefined

switch (input[0]) {
case 'deintegrate':
Expand Down Expand Up @@ -97,6 +101,9 @@ export default function(input: string[]): Args {
case 'quiet':
flags.verbosity = -1
break
case 'dry-run':
dryrun = true
break
case '':
// empty the main loop iterator
for (const arg of it) args.push(arg)
Expand All @@ -117,6 +124,10 @@ export default function(input: string[]): Args {
}
}

if (dryrun !== undefined && !(mode == 'integrate' || mode == 'deintegrate')) {
throw new UsageError({msg: '--dry-run cannot be specified with this mode'})
}

switch (mode) {
case undefined:
if (args.length) {
Expand All @@ -135,6 +146,10 @@ export default function(input: string[]): Args {
return { mode, flags, dir: new Path(args[0]) }
case 'install':
return { mode, flags, args }
case 'integrate':
case 'deintegrate':
dryrun ??= false
return { mode, dryrun, flags }
default:
return { mode: mode as any, flags }
}
Expand Down