@kaynooo/cli-wt 0.0.0-stage → 0.1.1
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/LICENSE +21 -0
- package/README.md +93 -2
- package/dist/cli.js +2768 -0
- package/package.json +37 -4
- package/src/cli.ts +319 -0
- package/src/commands.ts +169 -0
- package/src/compose.ts +212 -0
- package/src/config.ts +83 -0
- package/src/env_file.ts +7 -0
- package/src/errors.ts +36 -0
- package/src/files.ts +333 -0
- package/src/git.ts +102 -0
- package/src/index.ts +16 -0
- package/src/init.ts +149 -0
- package/src/jobs.ts +425 -0
- package/src/list.ts +98 -0
- package/src/port.ts +11 -0
- package/src/project.ts +196 -0
- package/src/proxy.ts +51 -0
- package/src/queue.ts +69 -0
- package/src/routes.ts +42 -0
- package/src/run.ts +251 -0
- package/src/shell.ts +28 -0
- package/src/stack.ts +105 -0
- package/src/sync.ts +28 -0
package/src/list.ts
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import type { GlobalOptions } from './commands'
|
|
2
|
+
import type { Project } from './project'
|
|
3
|
+
import { basename, join } from 'node:path'
|
|
4
|
+
import { runningProjects } from './compose'
|
|
5
|
+
import { currentBranch, git, unreachableCount } from './git'
|
|
6
|
+
import { listTasks, loadProjects, locate, worktreeOf } from './project'
|
|
7
|
+
import { urlsOf } from './routes'
|
|
8
|
+
|
|
9
|
+
export interface Checkout {
|
|
10
|
+
project: string
|
|
11
|
+
task: string
|
|
12
|
+
dir: string
|
|
13
|
+
branch: string
|
|
14
|
+
url: string
|
|
15
|
+
running: boolean
|
|
16
|
+
/** Changed files over the root and its repos. */
|
|
17
|
+
dirty: number
|
|
18
|
+
/** Commits a worktree holds on no branch, which `wt rm --force` would lose; 0 for main, which wt never removes. */
|
|
19
|
+
unbranched: number
|
|
20
|
+
/** The terminal session name of the checkout: its folder's name for main, `<repo>--<task>` for a worktree, as Herdr spaces are named. */
|
|
21
|
+
session: string
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// A session name holds no "." or ":" (nor a slash or a blank), which a terminal's address reads as separators.
|
|
25
|
+
const UNSAFE_IN_SESSION = /[.:\s/]/g
|
|
26
|
+
const sessionOf = (name: string) => name.replace(UNSAFE_IN_SESSION, '-')
|
|
27
|
+
|
|
28
|
+
interface ListOptions extends GlobalOptions {
|
|
29
|
+
all?: boolean
|
|
30
|
+
json?: boolean
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// The current project, null outside one, and what to list: it alone, or every project when asked to or, for a person, when outside one; JSON outside one lists nothing, the worktrees mod hiding there anyway.
|
|
34
|
+
async function projectsToList(options: ListOptions): Promise<{ here: Project | null, projects: Project[] }> {
|
|
35
|
+
let here: Project | null = null
|
|
36
|
+
|
|
37
|
+
try {
|
|
38
|
+
here = (await locate(process.cwd(), options.project)).project
|
|
39
|
+
}
|
|
40
|
+
catch {}
|
|
41
|
+
|
|
42
|
+
const everywhere = options.all === true || (!here && !options.json)
|
|
43
|
+
|
|
44
|
+
return { here, projects: everywhere ? await loadProjects() : [here].filter(project => project !== null) }
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** How many files `git status --porcelain` outputs list, over every repo. */
|
|
48
|
+
export function changedFiles(outputs: string[]): number {
|
|
49
|
+
return outputs.flatMap(out => out.split('\n')).filter(line => line.trim() !== '').length
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// Without optional locks, so a commit running in the checkout meanwhile never meets an index.lock this status took
|
|
53
|
+
async function dirtyCount(dir: string, repos: string[]): Promise<number> {
|
|
54
|
+
const statuses = await Promise.all(['.', ...repos].map(async repo => git(join(dir, repo), '--no-optional-locks', 'status', '--porcelain')))
|
|
55
|
+
|
|
56
|
+
return changedFiles(statuses.filter(status => status.ok).map(status => status.out))
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async function checkoutsOf(project: Project, running: Set<string>): Promise<Checkout[]> {
|
|
60
|
+
const branchDir = project.repos[0] ?? '.'
|
|
61
|
+
const mainHost = project.routes.find(route => !route.host.startsWith('*.'))?.host
|
|
62
|
+
const main = { id: basename(project.root), task: 'main', dir: project.root, url: mainHost !== undefined ? `https://${mainHost}` : '' }
|
|
63
|
+
const worktrees = listTasks(project).map((task) => {
|
|
64
|
+
const worktree = worktreeOf(project, task)
|
|
65
|
+
|
|
66
|
+
return { id: worktree.id, task, dir: worktree.dir, url: urlsOf(worktree)[0] ?? '' }
|
|
67
|
+
})
|
|
68
|
+
|
|
69
|
+
return Promise.all([main, ...worktrees].map(async ({ id, task, dir, url }) => ({
|
|
70
|
+
project: project.name,
|
|
71
|
+
task,
|
|
72
|
+
dir,
|
|
73
|
+
branch: await currentBranch(join(dir, branchDir)),
|
|
74
|
+
url,
|
|
75
|
+
running: running.has(id),
|
|
76
|
+
dirty: await dirtyCount(dir, project.repos),
|
|
77
|
+
unbranched: task === 'main' ? 0 : await unreachableCount(dir, project.repos),
|
|
78
|
+
session: sessionOf(task === 'main' ? basename(dir) : id),
|
|
79
|
+
})))
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// One row per checkout, `*` marking a stack that is up; as JSON, `{ project, checkouts }`, project being the one the directory is in, null outside every one.
|
|
83
|
+
export async function listWorktrees(options: ListOptions): Promise<void> {
|
|
84
|
+
const [running, { here, projects }] = await Promise.all([runningProjects(), projectsToList(options)])
|
|
85
|
+
const checkouts = (await Promise.all(projects.map(async project => checkoutsOf(project, running)))).flat()
|
|
86
|
+
|
|
87
|
+
if (options.json) {
|
|
88
|
+
console.log(JSON.stringify({ project: here?.name ?? null, checkouts }))
|
|
89
|
+
|
|
90
|
+
return
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const rows = checkouts.map(checkout => [checkout.running ? '*' : ' ', checkout.project, checkout.task, checkout.branch, checkout.url, [checkout.dirty ? `${checkout.dirty} changed` : '', checkout.unbranched ? `${checkout.unbranched} on no branch` : ''].filter(Boolean).join(', ')])
|
|
94
|
+
const widths = rows[0]?.map((_, column) => Math.max(...rows.map(row => row[column]!.length))) ?? []
|
|
95
|
+
|
|
96
|
+
for (const row of rows)
|
|
97
|
+
console.log(row.map((cell, column) => cell.padEnd(widths[column]!)).join(' ').trimEnd())
|
|
98
|
+
}
|
package/src/port.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// The dev server port of a worktree, hashed from its name; kept as zshrc's wt computed it, since a worktree's env files already hold the port (cli-stack's `stringToPort` now hashes differently).
|
|
2
|
+
export function stringToPort(s: string, min = 1024, max = 65535): number {
|
|
3
|
+
let hash = 2166136261
|
|
4
|
+
|
|
5
|
+
for (let i = 0; i < s.length; i++) {
|
|
6
|
+
hash ^= s.charCodeAt(i)
|
|
7
|
+
hash = (hash * 16777619) >>> 0
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
return min + (hash % (max - min + 1))
|
|
11
|
+
}
|
package/src/project.ts
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
import type { Resolved } from './config'
|
|
2
|
+
import { existsSync, readdirSync, realpathSync } from 'node:fs'
|
|
3
|
+
import { basename, dirname, join } from 'node:path'
|
|
4
|
+
import { expandHome, fillTemplate, wtConfig } from './config'
|
|
5
|
+
import { KnownError } from './errors'
|
|
6
|
+
import { stringToPort } from './port'
|
|
7
|
+
|
|
8
|
+
export interface Route {
|
|
9
|
+
// The host the main stack answers on: a worktree answers on <task>.<host>, and *.<rest> becomes *.<task>.<rest>.
|
|
10
|
+
host: string
|
|
11
|
+
// 'client' for the dev server on the host, '<service>:<port>' for a container of the stack.
|
|
12
|
+
to: 'client' | `${string}:${number}`
|
|
13
|
+
// TLS stays with the stack's own nginx, which finds its certificate in `certs` under the host name.
|
|
14
|
+
passthrough?: boolean
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface ProjectConfig {
|
|
18
|
+
// Checkout the worktrees are made from.
|
|
19
|
+
root: string
|
|
20
|
+
// Nested repos checked out on the task branch, the root then a detached worktree; with none, the root itself is on the branch.
|
|
21
|
+
repos: string[]
|
|
22
|
+
// Gitignored files and dirs copied from main. Hosts in the `.env*` files among them are rewritten.
|
|
23
|
+
copy?: string[]
|
|
24
|
+
// Data each worktree gets its own copy of: a path under root, or the key of a named volume.
|
|
25
|
+
clone?: string[]
|
|
26
|
+
// Paths shared with main through a symlink.
|
|
27
|
+
link?: string[]
|
|
28
|
+
// Services left out of a worktree stack, typically one on the host network.
|
|
29
|
+
skip?: string[]
|
|
30
|
+
// Services dialling the stack's own hosts from inside a container. Only the shared proxy answers for
|
|
31
|
+
// those, and a project's own override only names main's, so the worktree's go into their /etc/hosts.
|
|
32
|
+
routeHosts?: string[]
|
|
33
|
+
// Values forced into copied env files, `{task}` standing for the task name and `{port}` for its dev server port.
|
|
34
|
+
env?: Record<string, Record<string, string>>
|
|
35
|
+
// Where the stack's own nginx reads certificates from, relative to root. Required by passthrough routes.
|
|
36
|
+
certs?: string
|
|
37
|
+
// Commands run once with sh, in the worktree, the first time its stack comes up.
|
|
38
|
+
setup?: string[]
|
|
39
|
+
// What `wt run` needs to run a command of the worktree in a throwaway container, beside its own test database.
|
|
40
|
+
run?: RunConfig
|
|
41
|
+
routes: Route[]
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface RunConfig {
|
|
45
|
+
// The compose service whose image runs the command, the worktree's `dir` mounted where main's is.
|
|
46
|
+
service: string
|
|
47
|
+
// Directory of the checkout the service bind-mounts, whose test env files name the database.
|
|
48
|
+
dir: string
|
|
49
|
+
// Shell commands run in that container, test env, the first time a worktree meets a fresh database: schema and fixtures, never a dump of dev data.
|
|
50
|
+
provision: string[]
|
|
51
|
+
// Resolver for the container, "127.0.0.1" when the tests look up outside hosts and Docker's forward to the host resolver takes seconds to fail each one.
|
|
52
|
+
dns?: string
|
|
53
|
+
// Variables the command runs with besides HOME and TEST_TOKEN, such as `APP_ENV: 'test'`.
|
|
54
|
+
env?: Record<string, string>
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface Project extends ProjectConfig {
|
|
58
|
+
name: string
|
|
59
|
+
// The wt config the manifest was loaded under, so every path below follows it.
|
|
60
|
+
settings: Resolved
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export interface Worktree {
|
|
64
|
+
project: Project
|
|
65
|
+
task: string
|
|
66
|
+
dir: string
|
|
67
|
+
// Compose project name, also the prefix of every name wt creates for this worktree.
|
|
68
|
+
id: string
|
|
69
|
+
clientPort: number
|
|
70
|
+
files: ReturnType<typeof worktreeFiles>
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export class WtError extends KnownError {}
|
|
74
|
+
|
|
75
|
+
// A DNS label, as the task prefixes every host of the worktree.
|
|
76
|
+
const TASK_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/
|
|
77
|
+
|
|
78
|
+
const ROUTE_TARGET = /^client$|^[\w.-]+:\d+$/
|
|
79
|
+
|
|
80
|
+
// Every file wt generates for a worktree outside of it, so `wt rm` has one list to delete.
|
|
81
|
+
export function worktreeFiles(settings: Resolved, id: string) {
|
|
82
|
+
return {
|
|
83
|
+
override: join(settings.overrides, `${id}.override.yml`),
|
|
84
|
+
setupMarker: join(settings.state, `${id}.setup`),
|
|
85
|
+
// The volumes a clone started filling and has not finished, one per line, so the next sync empties and fills them again.
|
|
86
|
+
clonesPending: join(settings.state, `${id}.clones-pending`),
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export function worktreeHost(host: string, task: string): string {
|
|
91
|
+
return host.startsWith('*.') ? `*.${task}.${host.slice(2)}` : `${task}.${host}`
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// Caught when the manifest loads, not halfway through a `wt add` that has already cloned data.
|
|
95
|
+
function assertValid(project: Project): void {
|
|
96
|
+
for (const route of project.routes) {
|
|
97
|
+
if (!ROUTE_TARGET.test(route.to))
|
|
98
|
+
throw new WtError(`${project.name}: route ${route.host} goes to "${route.to}", expected "client" or "<service>:<port>"`)
|
|
99
|
+
|
|
100
|
+
if (route.passthrough && project.certs === undefined)
|
|
101
|
+
throw new WtError(`${project.name}: passthrough route ${route.host} needs \`certs\``)
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export async function loadProjects(): Promise<Project[]> {
|
|
106
|
+
const settings = await wtConfig()
|
|
107
|
+
const files = existsSync(settings.manifests) ? readdirSync(settings.manifests).filter(file => file.endsWith('.ts')).sort() : []
|
|
108
|
+
|
|
109
|
+
return Promise.all(files.map(async (file) => {
|
|
110
|
+
const { default: config } = await import(join(settings.manifests, file)) as { default: ProjectConfig }
|
|
111
|
+
const project = { ...config, root: expandHome(config.root), name: basename(file, '.ts'), settings }
|
|
112
|
+
|
|
113
|
+
assertValid(project)
|
|
114
|
+
|
|
115
|
+
return project
|
|
116
|
+
}))
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export async function findProject(name: string): Promise<Project> {
|
|
120
|
+
const project = (await loadProjects()).find(p => p.name === name)
|
|
121
|
+
|
|
122
|
+
if (!project)
|
|
123
|
+
throw new WtError(`no project named ${name} in ${(await wtConfig()).manifests}`)
|
|
124
|
+
|
|
125
|
+
return project
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export const tasksDir = (project: Project) => fillTemplate([project.settings.worktrees], { root: dirname(project.root), repo: basename(project.root) })[0]!
|
|
129
|
+
|
|
130
|
+
export function worktreeOf(project: Project, task: string): Worktree {
|
|
131
|
+
if (task === 'main' || !TASK_PATTERN.test(task))
|
|
132
|
+
throw new WtError(`invalid task name "${task}": lowercase letters, digits and inner dashes, at most 63, and not "main"`)
|
|
133
|
+
|
|
134
|
+
const mainHosts = new Set(project.routes.map(route => route.host))
|
|
135
|
+
const taken = project.routes.find(route => mainHosts.has(worktreeHost(route.host, task)))
|
|
136
|
+
|
|
137
|
+
if (taken)
|
|
138
|
+
throw new WtError(`invalid task name "${task}": the worktree's ${worktreeHost(taken.host, task)} would be one of main's hosts`)
|
|
139
|
+
|
|
140
|
+
const id = `${basename(project.root)}--${task}`
|
|
141
|
+
|
|
142
|
+
return {
|
|
143
|
+
project,
|
|
144
|
+
task,
|
|
145
|
+
dir: join(tasksDir(project), task),
|
|
146
|
+
id,
|
|
147
|
+
clientPort: stringToPort(`${project.name}--${task}`),
|
|
148
|
+
files: worktreeFiles(project.settings, id),
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export function assertWorktreeExists(worktree: Worktree): void {
|
|
153
|
+
if (!existsSync(worktree.dir))
|
|
154
|
+
throw new WtError(`no worktree ${worktree.task}, create it with \`wt add ${worktree.task}\``)
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export function listTasks(project: Project): string[] {
|
|
158
|
+
const dir = tasksDir(project)
|
|
159
|
+
|
|
160
|
+
return existsSync(dir) ? readdirSync(dir).filter(task => TASK_PATTERN.test(task)).sort() : []
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// The project and task the working directory sits in, `main` when it is the project's own checkout.
|
|
164
|
+
export async function locate(cwd: string, projectName?: string): Promise<{ project: Project, task: string }> {
|
|
165
|
+
const here = realpathSync(cwd)
|
|
166
|
+
const projects = projectName !== undefined ? [await findProject(projectName)] : await loadProjects()
|
|
167
|
+
|
|
168
|
+
for (const project of projects) {
|
|
169
|
+
const dir = tasksDir(project)
|
|
170
|
+
|
|
171
|
+
if (here.startsWith(`${dir}/`)) {
|
|
172
|
+
const rest = here.slice(dir.length + 1)
|
|
173
|
+
const slash = rest.indexOf('/')
|
|
174
|
+
|
|
175
|
+
return { project, task: slash === -1 ? rest : rest.slice(0, slash) }
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
if (here === project.root || here.startsWith(`${project.root}/`))
|
|
179
|
+
return { project, task: 'main' }
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
if (projects.length === 1)
|
|
183
|
+
return { project: projects[0]!, task: 'main' }
|
|
184
|
+
|
|
185
|
+
throw new WtError('not inside a known project or worktree (cd into one, or pass --project)')
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export async function locateWorktree(cwd: string, task: string | undefined, projectName?: string): Promise<Worktree> {
|
|
189
|
+
const here = await locate(cwd, projectName)
|
|
190
|
+
const name = task ?? here.task
|
|
191
|
+
|
|
192
|
+
if (name === 'main')
|
|
193
|
+
throw new WtError('this is the main checkout, name a task')
|
|
194
|
+
|
|
195
|
+
return worktreeOf(here.project, name)
|
|
196
|
+
}
|
package/src/proxy.ts
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/** The shared proxy is devproxy (@kaynooo/devproxy): the one on PATH, else the copy installed with wt. */
|
|
2
|
+
|
|
3
|
+
import { dirname, join } from 'node:path'
|
|
4
|
+
import { $ } from 'bun'
|
|
5
|
+
import { WtError } from './project'
|
|
6
|
+
|
|
7
|
+
export interface ProxyHost {
|
|
8
|
+
host: string
|
|
9
|
+
// null for a route of the config, else the group holding it: docker-<project> for the labels of a running stack.
|
|
10
|
+
group: string | null
|
|
11
|
+
to: string
|
|
12
|
+
passthrough: boolean
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// PATH first, so a test sandbox's fake answers instead of the real one.
|
|
16
|
+
function devproxyArgv(): string[] {
|
|
17
|
+
const onPath = Bun.which('devproxy')
|
|
18
|
+
|
|
19
|
+
if (onPath !== null)
|
|
20
|
+
return [onPath]
|
|
21
|
+
|
|
22
|
+
try {
|
|
23
|
+
return [process.execPath, join(dirname(Bun.resolveSync('@kaynooo/devproxy', import.meta.dir)), '..', 'dist', 'cli.js')]
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return []
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Whether devproxy is installed and has a config to serve, so wt routes through it. */
|
|
31
|
+
export async function hasDevproxy(): Promise<boolean> {
|
|
32
|
+
const argv = devproxyArgv()
|
|
33
|
+
|
|
34
|
+
return argv.length > 0 && (await $`${argv} hosts --json`.quiet().nothrow()).exitCode === 0
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Every host the proxy serves; empty without devproxy or its config. */
|
|
38
|
+
export async function proxyHostList(): Promise<ProxyHost[]> {
|
|
39
|
+
const argv = devproxyArgv()
|
|
40
|
+
const result = argv.length ? await $`${argv} hosts --json`.quiet().nothrow() : undefined
|
|
41
|
+
|
|
42
|
+
return result?.exitCode === 0 ? JSON.parse(result.stdout.toString()) as ProxyHost[] : []
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Generates the proxy's files and starts it, network included; output goes to the terminal. */
|
|
46
|
+
export async function devproxyUp(): Promise<void> {
|
|
47
|
+
const argv = devproxyArgv()
|
|
48
|
+
|
|
49
|
+
if (!argv.length || (await $`${argv} up`.nothrow()).exitCode !== 0)
|
|
50
|
+
throw new WtError('the shared proxy did not come up: `devproxy status` says why')
|
|
51
|
+
}
|
package/src/queue.ts
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import type { Resolved } from './config'
|
|
2
|
+
import { mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
|
3
|
+
import { join } from 'node:path'
|
|
4
|
+
import { alive, bootTime } from './errors'
|
|
5
|
+
|
|
6
|
+
/** The folder of a queue's tickets, under the config's state folder. */
|
|
7
|
+
export const queueDir = (settings: Resolved, name: string) => join(settings.state, 'queues', name)
|
|
8
|
+
const POLL_MS = 1000
|
|
9
|
+
|
|
10
|
+
// The tickets still held, oldest first; one whose process is gone (killed while waiting), or taken before the machine booted, is swept on the way.
|
|
11
|
+
export function liveTickets(dir: string): string[] {
|
|
12
|
+
const names = readdirSync(dir).sort()
|
|
13
|
+
|
|
14
|
+
return names.filter((name) => {
|
|
15
|
+
const dash = name.indexOf('-')
|
|
16
|
+
|
|
17
|
+
if (Number(name.slice(0, dash)) >= bootTime() && alive(Number(name.slice(dash + 1))))
|
|
18
|
+
return true
|
|
19
|
+
|
|
20
|
+
rmSync(join(dir, name), { force: true })
|
|
21
|
+
|
|
22
|
+
return false
|
|
23
|
+
})
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// Empty for a ticket released since it was listed.
|
|
27
|
+
function labelOf(ticket: string): string {
|
|
28
|
+
try {
|
|
29
|
+
return readFileSync(ticket, 'utf8')
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
return ''
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// Runs `work` once every ticket taken before this one in `dir`, by any process on the machine, is released; `waiting` hears how many are ahead each time that changes, and what the first of them runs.
|
|
37
|
+
export async function inLine<T>(dir: string, label: string, waiting: (ahead: number, running: string) => void, work: () => Promise<T>): Promise<T> {
|
|
38
|
+
mkdirSync(dir, { recursive: true })
|
|
39
|
+
|
|
40
|
+
const name = `${String(Date.now()).padStart(15, '0')}-${process.pid}`
|
|
41
|
+
const ticket = join(dir, name)
|
|
42
|
+
const release = () => rmSync(ticket, { force: true })
|
|
43
|
+
|
|
44
|
+
writeFileSync(ticket, label)
|
|
45
|
+
process.once('exit', release)
|
|
46
|
+
|
|
47
|
+
try {
|
|
48
|
+
let shown = -1
|
|
49
|
+
|
|
50
|
+
for (;;) {
|
|
51
|
+
const ahead = liveTickets(dir).filter(other => other < name)
|
|
52
|
+
|
|
53
|
+
if (ahead.length === 0)
|
|
54
|
+
break
|
|
55
|
+
|
|
56
|
+
if (ahead.length !== shown) {
|
|
57
|
+
shown = ahead.length
|
|
58
|
+
waiting(ahead.length, labelOf(join(dir, ahead[0]!)))
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
await Bun.sleep(POLL_MS)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
return await work()
|
|
65
|
+
}
|
|
66
|
+
finally {
|
|
67
|
+
release()
|
|
68
|
+
}
|
|
69
|
+
}
|
package/src/routes.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { Worktree } from './project'
|
|
2
|
+
import { existsSync, mkdirSync } from 'node:fs'
|
|
3
|
+
import { join } from 'node:path'
|
|
4
|
+
import { $ } from 'bun'
|
|
5
|
+
import { worktreeHost, WtError } from './project'
|
|
6
|
+
|
|
7
|
+
const LEADING_STAR = /^\*/
|
|
8
|
+
|
|
9
|
+
async function mkcert(certFile: string, keyFile: string, hosts: string[]): Promise<void> {
|
|
10
|
+
const result = await $`mkcert -cert-file ${certFile} -key-file ${keyFile} ${hosts}`.quiet().nothrow()
|
|
11
|
+
|
|
12
|
+
if (result.exitCode !== 0)
|
|
13
|
+
throw new WtError(`mkcert failed for ${hosts.join(' ')}:\n${result.stderr.toString()}`)
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* devproxy serves the worktree's hosts from the labels of its override and makes their certificates; a project with `certs` terminates its passthrough hosts in its own nginx, which picks one certificate per host by name, named the way mkcert names them.
|
|
18
|
+
* A certificate without its key, or the other way round, is issued again.
|
|
19
|
+
*/
|
|
20
|
+
export async function writeStackCerts(worktree: Worktree): Promise<void> {
|
|
21
|
+
const { project } = worktree
|
|
22
|
+
|
|
23
|
+
if (project.certs === undefined)
|
|
24
|
+
return
|
|
25
|
+
|
|
26
|
+
const dir = join(worktree.dir, project.certs)
|
|
27
|
+
|
|
28
|
+
mkdirSync(dir, { recursive: true })
|
|
29
|
+
|
|
30
|
+
await Promise.all(project.routes.map(async (route) => {
|
|
31
|
+
const served = worktreeHost(route.host, worktree.task)
|
|
32
|
+
const name = served.replace(LEADING_STAR, '_wildcard')
|
|
33
|
+
const cert = join(dir, `${name}.pem`)
|
|
34
|
+
const key = join(dir, `${name}-key.pem`)
|
|
35
|
+
|
|
36
|
+
return existsSync(cert) && existsSync(key) ? undefined : mkcert(cert, key, [served])
|
|
37
|
+
}))
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function urlsOf(worktree: Worktree): string[] {
|
|
41
|
+
return worktree.project.routes.filter(route => !route.host.startsWith('*.')).map(route => `https://${worktreeHost(route.host, worktree.task)}`)
|
|
42
|
+
}
|