@sixb/cli 0.1.14 → 0.1.16

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.
@@ -0,0 +1,246 @@
1
+ import { dirname, join, posix, relative } from "node:path"
2
+ import { SixbCliError } from "./errors"
3
+
4
+ /** The GitHub environment that holds the deploy secrets and gates the deploy job. */
5
+ export const CI_ENVIRONMENT = "production"
6
+
7
+ /** The secret a private submodule's checkout reads. */
8
+ export const SUBMODULE_TOKEN_SECRET = "SIXB_GITHUB_TOKEN"
9
+
10
+ /** Actions pinned by commit, so a moved tag cannot change what runs with the deploy key. */
11
+ const CHECKOUT = "actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1"
12
+ const SETUP_BUN = "oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0"
13
+
14
+ export interface GitHubRepo {
15
+ /** `owner/name`. */
16
+ readonly name: string
17
+ readonly defaultBranch: string
18
+ }
19
+
20
+ export interface Submodule {
21
+ readonly path: string
22
+ readonly url: string
23
+ /** `owner/name` when the submodule lives on GitHub. */
24
+ readonly repo: string | null
25
+ }
26
+
27
+ export interface WorkflowInput {
28
+ /** The deployment's name. */
29
+ readonly name: string
30
+ readonly branch: string
31
+ /** The project's directory relative to the repository root, `"."` at the root. */
32
+ readonly projectPath: string
33
+ /** The `package.json` that pins Bun, relative to the repository root. */
34
+ readonly bunVersionFile: string | null
35
+ /** GitHub secret names, by the environment variable the install lines read. */
36
+ readonly secrets: Readonly<Record<string, string>>
37
+ readonly install: readonly string[]
38
+ readonly submodules: "none" | "public" | "private"
39
+ }
40
+
41
+ /** A GitHub Actions workflow that deploys on every push to `branch`. */
42
+ export function renderWorkflow(input: WorkflowInput): string {
43
+ const workingDirectory =
44
+ input.projectPath === "." ? [] : [` working-directory: ${input.projectPath}`]
45
+ const checkoutWith = [
46
+ " persist-credentials: false",
47
+ ...(input.submodules === "none" ? [] : [" submodules: recursive"]),
48
+ ...(input.submodules === "private"
49
+ ? [` token: \${{ secrets.${SUBMODULE_TOKEN_SECRET} }}`]
50
+ : []),
51
+ ]
52
+ const tokenCheck =
53
+ input.submodules === "private"
54
+ ? [
55
+ " - name: Check the token for private submodules",
56
+ " env:",
57
+ ` HAS_TOKEN: \${{ secrets.${SUBMODULE_TOKEN_SECRET} != '' }}`,
58
+ " run: |",
59
+ ' if [ "$HAS_TOKEN" != true ]; then',
60
+ ` echo "::error::Set the ${SUBMODULE_TOKEN_SECRET} secret in the ${CI_ENVIRONMENT} environment to a token that can read this repository's private submodules."`,
61
+ " exit 1",
62
+ " fi",
63
+ ]
64
+ : []
65
+
66
+ return [
67
+ `# Written by \`sixb deploy ci\`. Run it again to rotate the deploy key.`,
68
+ `name: Deploy ${input.name}`,
69
+ "",
70
+ "on:",
71
+ " push:",
72
+ ` branches: [${JSON.stringify(input.branch)}]`,
73
+ " workflow_dispatch:",
74
+ "",
75
+ "permissions:",
76
+ " contents: read",
77
+ "",
78
+ "# One deploy at a time; a push during a deploy waits for it instead of cancelling it.",
79
+ "concurrency:",
80
+ ` group: sixb-deploy-${input.name}`,
81
+ " cancel-in-progress: false",
82
+ "",
83
+ "jobs:",
84
+ " deploy:",
85
+ " runs-on: ubuntu-latest",
86
+ ` environment: ${CI_ENVIRONMENT}`,
87
+ " timeout-minutes: 30",
88
+ " steps:",
89
+ ...tokenCheck,
90
+ ` - uses: ${CHECKOUT}`,
91
+ " with:",
92
+ ...checkoutWith,
93
+ ` - uses: ${SETUP_BUN}`,
94
+ ...(input.bunVersionFile
95
+ ? [" with:", ` bun-version-file: ${input.bunVersionFile}`]
96
+ : []),
97
+ " - name: Install dependencies",
98
+ " run: bun install --frozen-lockfile",
99
+ ...workingDirectory,
100
+ " - name: Install the deploy key",
101
+ " env:",
102
+ ...Object.entries(input.secrets).map(
103
+ ([variable, secret]) => ` ${variable}: \${{ secrets.${secret} }}`
104
+ ),
105
+ " run: |",
106
+ ...input.install.map((line) => ` ${line}`),
107
+ " - name: Deploy",
108
+ " run: bunx sixb deploy",
109
+ ...workingDirectory,
110
+ "",
111
+ ].join("\n")
112
+ }
113
+
114
+ /** Where the workflow for a deployment lives, relative to the repository root. */
115
+ export function workflowPath(name: string): string {
116
+ return `.github/workflows/deploy-${name}.yml`
117
+ }
118
+
119
+ /** The GitHub secret for one of a deployment's variables; a repository may deploy several. */
120
+ export function secretName(deployment: string, variable: string): string {
121
+ return `${variable}_${deployment.toUpperCase().replaceAll("-", "_")}`
122
+ }
123
+
124
+ /** The `package.json` that pins Bun for the project, relative to the repository root. */
125
+ export async function bunVersionFile(projectDir: string, repoRoot: string): Promise<string | null> {
126
+ for (let dir = projectDir; ; dir = dirname(dir)) {
127
+ const manifest = await Bun.file(join(dir, "package.json"))
128
+ .json()
129
+ .catch(() => null)
130
+ if (
131
+ typeof manifest?.packageManager === "string" &&
132
+ manifest.packageManager.startsWith("bun@")
133
+ ) {
134
+ return relative(repoRoot, join(dir, "package.json")).split("\\").join("/")
135
+ }
136
+ if (dir === repoRoot || dirname(dir) === dir) return null
137
+ }
138
+ }
139
+
140
+ /** The submodules `.gitmodules` lists, with the GitHub repository behind each. */
141
+ export async function readSubmodules(repoRoot: string, repo: GitHubRepo): Promise<Submodule[]> {
142
+ const output = await run(
143
+ ["git", "config", "--file", ".gitmodules", "--get-regexp", "^submodule\\..*\\.(path|url)$"],
144
+ { cwd: repoRoot }
145
+ ).catch(() => "")
146
+ const byName = new Map<string, { path?: string; url?: string }>()
147
+ for (const line of output.split("\n")) {
148
+ const match = line.match(/^submodule\.(.+)\.(path|url) (.+)$/)
149
+ if (!match?.[1] || !match[2] || !match[3]) continue
150
+ const entry = byName.get(match[1]) ?? {}
151
+ entry[match[2] as "path" | "url"] = match[3]
152
+ byName.set(match[1], entry)
153
+ }
154
+ return [...byName.values()].flatMap(({ path, url }) =>
155
+ path && url ? [{ path, url, repo: githubRepoOf(url, repo.name) }] : []
156
+ )
157
+ }
158
+
159
+ /** `owner/name` for a GitHub remote URL, resolving a relative one against `parent`. */
160
+ export function githubRepoOf(url: string, parent: string): string | null {
161
+ if (url.startsWith("./") || url.startsWith("../")) {
162
+ const resolved = posix.normalize(posix.join(parent, url))
163
+ return resolved.replace(/\.git$/, "").split("/").length === 2
164
+ ? resolved.replace(/\.git$/, "")
165
+ : null
166
+ }
167
+ const match = url.match(
168
+ /^(?:https:\/\/github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([^/]+\/[^/]+?)(?:\.git)?\/?$/
169
+ )
170
+ return match?.[1] ?? null
171
+ }
172
+
173
+ export async function currentRepo(cwd: string): Promise<GitHubRepo> {
174
+ const output = await gh(["repo", "view", "--json", "nameWithOwner,defaultBranchRef"], { cwd })
175
+ const parsed = JSON.parse(output) as {
176
+ nameWithOwner: string
177
+ defaultBranchRef: { name: string } | null
178
+ }
179
+ return { name: parsed.nameWithOwner, defaultBranch: parsed.defaultBranchRef?.name ?? "main" }
180
+ }
181
+
182
+ /** Whether CI's own token cannot read `repo`. A repository this login cannot see counts. */
183
+ export async function isPrivate(repo: string): Promise<boolean> {
184
+ const output = await gh(["api", `repos/${repo}`, "--jq", ".private"]).catch(() => "true")
185
+ return output.trim() !== "false"
186
+ }
187
+
188
+ /** Creates the environment when it is missing. An existing one keeps its protection rules. */
189
+ export async function ensureEnvironment(repo: GitHubRepo): Promise<void> {
190
+ const path = `repos/${repo.name}/environments/${CI_ENVIRONMENT}`
191
+ const exists = await gh(["api", path, "--silent"]).then(
192
+ () => true,
193
+ () => false
194
+ )
195
+ if (!exists) await gh(["api", "--method", "PUT", path, "--silent"])
196
+ }
197
+
198
+ export async function setSecret(repo: GitHubRepo, name: string, value: string): Promise<void> {
199
+ await gh(["secret", "set", name, "--env", CI_ENVIRONMENT, "--repo", repo.name], {
200
+ input: value,
201
+ })
202
+ }
203
+
204
+ /** Whether the environment or the repository has the secret. */
205
+ export async function hasSecret(repo: GitHubRepo, name: string): Promise<boolean> {
206
+ for (const scope of [["--env", CI_ENVIRONMENT], []]) {
207
+ const list = await gh(["secret", "list", ...scope, "--repo", repo.name, "--json", "name"])
208
+ if ((JSON.parse(list) as { name: string }[]).some((secret) => secret.name === name)) return true
209
+ }
210
+ return false
211
+ }
212
+
213
+ async function gh(
214
+ args: readonly string[],
215
+ options: { readonly cwd?: string; readonly input?: string } = {}
216
+ ): Promise<string> {
217
+ try {
218
+ return await run(["gh", ...args], options)
219
+ } catch (error) {
220
+ const reason = error instanceof Error ? error.message : String(error)
221
+ throw new SixbCliError(`[SixbDeploy] gh ${args.slice(0, 2).join(" ")} failed: ${reason}`, {
222
+ remediation:
223
+ "`sixb deploy ci` uses the GitHub CLI. Install it, run `gh auth login`, and make sure " +
224
+ "you can change this repository's settings.",
225
+ })
226
+ }
227
+ }
228
+
229
+ async function run(
230
+ command: readonly string[],
231
+ options: { readonly cwd?: string; readonly input?: string }
232
+ ): Promise<string> {
233
+ const child = Bun.spawn([...command], {
234
+ cwd: options.cwd,
235
+ stdin: options.input === undefined ? "ignore" : new Blob([options.input]),
236
+ stdout: "pipe",
237
+ stderr: "pipe",
238
+ })
239
+ const [exitCode, stdout, stderr] = await Promise.all([
240
+ child.exited,
241
+ new Response(child.stdout).text(),
242
+ new Response(child.stderr).text(),
243
+ ])
244
+ if (exitCode !== 0) throw new Error(stderr.trim() || `exited with code ${exitCode}`)
245
+ return stdout.trim()
246
+ }