@oakgreencc/graft 0.2.0 → 0.2.2
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/docs/github-setup.md +21 -7
- package/package.json +7 -7
- package/src/setup/optional.mjs +172 -0
- package/src/setup/project.mjs +131 -59
- package/src/setup/prompt.mjs +10 -7
- package/src/setup/rulesets.mjs +10 -7
- package/src/setup/style.mjs +55 -0
package/docs/github-setup.md
CHANGED
|
@@ -86,16 +86,30 @@ Don't add the App to the bypass list.
|
|
|
86
86
|
|
|
87
87
|
## 3. Optional: a branch-name ruleset for the App
|
|
88
88
|
|
|
89
|
-
|
|
90
|
-
branches
|
|
91
|
-
|
|
92
|
-
|
|
89
|
+
`graft setup project` asks whether to confine the App to its own namespace
|
|
90
|
+
(`--app-branches <prefix | none>` answers without asking). Yes creates a second
|
|
91
|
+
ruleset, `graft: app branches`, through `gh`, as you: it targets every branch
|
|
92
|
+
except `agent/**` and restricts creations. Repository admins, maintainers and
|
|
93
|
+
writers bypass it, so people can still create any branch; the App never can.
|
|
94
|
+
With it in place, a mangled command can't create a branch named `--api`.
|
|
95
|
+
|
|
96
|
+
It restricts creations only. Writing to the base directly is already blocked
|
|
97
|
+
by the base ruleset's pull-request rule, and restricting updates outside
|
|
98
|
+
`agent/**` would also block the App's own `graft pr merge`.
|
|
99
|
+
|
|
100
|
+
Other bots that create branches — Dependabot, Renovate — are held to it too.
|
|
101
|
+
When setup finds their config it says so and defaults to no; to have both, add
|
|
102
|
+
them to the ruleset's bypass list.
|
|
93
103
|
|
|
94
104
|
## 4. Optional: auto-merge
|
|
95
105
|
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
106
|
+
`graft setup project` asks whether to turn on **Allow auto-merge**, which
|
|
107
|
+
`graft pr merge --auto` needs (`--auto-merge` / `--no-auto-merge` answer
|
|
108
|
+
without asking). It defaults to yes when agents may merge into some base. The
|
|
109
|
+
merge still waits for the ruleset's required checks and reviews.
|
|
110
|
+
|
|
111
|
+
Without `gh` logged in as a repository admin, both steps print where to do them
|
|
112
|
+
by hand instead.
|
|
99
113
|
|
|
100
114
|
## 5. Check
|
|
101
115
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@oakgreencc/graft",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.2",
|
|
4
4
|
"description": "Let an agent work a GitHub project without the local git CLI's write path: Verified commits created by a GitHub App, the repo's git hooks run at the right moments, CODEOWNERS as the manifest of what needs a human, and a scoped maintainer mode for when one says yes.",
|
|
5
5
|
"license": "AGPL-3.0-only",
|
|
6
6
|
"type": "module",
|
|
@@ -33,11 +33,6 @@
|
|
|
33
33
|
".claude-plugin/",
|
|
34
34
|
"docs/"
|
|
35
35
|
],
|
|
36
|
-
"scripts": {
|
|
37
|
-
"lint": "biome check .",
|
|
38
|
-
"test": "node --test 'test/*.test.mjs'",
|
|
39
|
-
"conformance": "GRAFT_CONFORMANCE=1 node --test test/permissions.test.mjs"
|
|
40
|
-
},
|
|
41
36
|
"engines": {
|
|
42
37
|
"node": ">=22"
|
|
43
38
|
},
|
|
@@ -61,5 +56,10 @@
|
|
|
61
56
|
"cache": false
|
|
62
57
|
}
|
|
63
58
|
}
|
|
59
|
+
},
|
|
60
|
+
"scripts": {
|
|
61
|
+
"lint": "biome check .",
|
|
62
|
+
"test": "node --test 'test/*.test.mjs'",
|
|
63
|
+
"conformance": "GRAFT_CONFORMANCE=1 node --test test/permissions.test.mjs"
|
|
64
64
|
}
|
|
65
|
-
}
|
|
65
|
+
}
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
/**
|
|
3
|
+
* The optional half of `graft setup project`: asked, then done — never a
|
|
4
|
+
* checklist left for the reader.
|
|
5
|
+
*
|
|
6
|
+
* App branches a second ruleset: the App may create branches under one
|
|
7
|
+
* prefix only (agent/** by default). Repository admins,
|
|
8
|
+
* maintainers and writers bypass it, so people are not held
|
|
9
|
+
* to it; the App is never a bypass actor.
|
|
10
|
+
* auto-merge the repository setting `graft pr merge --auto` needs.
|
|
11
|
+
*
|
|
12
|
+
* Both are written as the human through `gh` (rulesets.mjs `ghAdmin`), for
|
|
13
|
+
* the same reason as the base ruleset: the App holds no Administration
|
|
14
|
+
* permission. When `gh` cannot do it, the step says where to do it by hand.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
/** The ruleset graft owns for the App's branches. */
|
|
18
|
+
export const APP_BRANCHES_RULESET = 'graft: app branches'
|
|
19
|
+
|
|
20
|
+
/** People bypass the creation rule; the App is never listed. 5 admin, 2 maintain, 4 write. */
|
|
21
|
+
export const PEOPLE_BYPASS = Object.freeze(
|
|
22
|
+
[5, 2, 4].map((actor_id) => ({ actor_id, actor_type: 'RepositoryRole', bypass_mode: 'always' })),
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
/** Files that mean a bot creates branches here, and would be blocked too. */
|
|
26
|
+
export const BRANCH_BOT_FILES = [
|
|
27
|
+
'.github/dependabot.yml',
|
|
28
|
+
'.github/dependabot.yaml',
|
|
29
|
+
'renovate.json',
|
|
30
|
+
'renovate.json5',
|
|
31
|
+
'.github/renovate.json',
|
|
32
|
+
'.github/renovate.json5',
|
|
33
|
+
'.renovaterc',
|
|
34
|
+
'.renovaterc.json',
|
|
35
|
+
]
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* `agent/**`, `agent/`, `agent` → `agent/**`; empty or `none` → null.
|
|
39
|
+
*
|
|
40
|
+
* @param {string | null | undefined} answer
|
|
41
|
+
*/
|
|
42
|
+
export function branchPattern(answer) {
|
|
43
|
+
const a = String(answer ?? '').trim()
|
|
44
|
+
if (!a || a === 'none') return null
|
|
45
|
+
if (/[\s~^:?[\\]/.test(a) || a.startsWith('/') || a.startsWith('refs/'))
|
|
46
|
+
throw new Error(`--app-branches takes a branch prefix like agent/**, not "${a}"`)
|
|
47
|
+
return a.endsWith('/**') ? a : `${a.replace(/\/+$/, '')}/**`
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* The ruleset that lets the App create only `pattern` branches.
|
|
52
|
+
*
|
|
53
|
+
* @param {string} pattern e.g. agent/**
|
|
54
|
+
*/
|
|
55
|
+
export function appBranchesBody(pattern) {
|
|
56
|
+
return {
|
|
57
|
+
name: APP_BRANCHES_RULESET,
|
|
58
|
+
target: 'branch',
|
|
59
|
+
enforcement: 'active',
|
|
60
|
+
conditions: { ref_name: { include: ['~ALL'], exclude: [`refs/heads/${pattern}`] } },
|
|
61
|
+
bypass_actors: PEOPLE_BYPASS.map((a) => ({ ...a })),
|
|
62
|
+
rules: [{ type: 'creation' }],
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* @typedef {{
|
|
68
|
+
* owner: string, repo: string,
|
|
69
|
+
* admin: { who: string, api: (method: string, path: string, body?: any) => Promise<any> },
|
|
70
|
+
* prompt: import('./prompt.mjs').Prompter,
|
|
71
|
+
* say: (line?: string) => void,
|
|
72
|
+
* c: import('./style.mjs').Palette,
|
|
73
|
+
* }} Step
|
|
74
|
+
*/
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Ask whether to limit the App's branches, and create the ruleset if so.
|
|
78
|
+
*
|
|
79
|
+
* @param {Step & { answer?: string | null, bots?: string[] }} input
|
|
80
|
+
* `answer`: --app-branches, if given. `bots`: BRANCH_BOT_FILES present here.
|
|
81
|
+
* @returns {Promise<'ok' | 'created' | 'skipped' | 'manual'>}
|
|
82
|
+
*/
|
|
83
|
+
export async function ensureAppBranches({ owner, repo, admin, prompt, say, c, answer = null, bots = [] }) {
|
|
84
|
+
const rulesets = `/repos/${owner}/${repo}/rulesets`
|
|
85
|
+
const manual = `https://github.com/${owner}/${repo}/settings/rules`
|
|
86
|
+
let existing = null
|
|
87
|
+
try {
|
|
88
|
+
existing = ((await admin.api('GET', rulesets)) ?? []).find((r) => r.name === APP_BRANCHES_RULESET)
|
|
89
|
+
} catch (err) {
|
|
90
|
+
say(c.warn(`could not read the rulesets as ${admin.who}: ${/** @type {Error} */ (err).message}`))
|
|
91
|
+
say(c.skip(`limit the App's branches by hand, if you want to: ${manual}`))
|
|
92
|
+
return 'manual'
|
|
93
|
+
}
|
|
94
|
+
if (existing) {
|
|
95
|
+
say(c.ok(`the App may only create the branches "${APP_BRANCHES_RULESET}" allows`))
|
|
96
|
+
return 'ok'
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
if (answer === null) {
|
|
100
|
+
say(`The App can create any branch. A ruleset can hold it to one prefix; people are not held to it.`)
|
|
101
|
+
if (bots.length)
|
|
102
|
+
say(
|
|
103
|
+
c.warn(
|
|
104
|
+
`${bots.join(', ')} ${bots.length > 1 ? 'mean bots create' : 'means a bot creates'} branches here; ` +
|
|
105
|
+
'the ruleset would block them too until you add them to its bypass list.',
|
|
106
|
+
),
|
|
107
|
+
)
|
|
108
|
+
}
|
|
109
|
+
let pattern
|
|
110
|
+
try {
|
|
111
|
+
pattern =
|
|
112
|
+
answer !== null
|
|
113
|
+
? branchPattern(answer)
|
|
114
|
+
: (await prompt.confirm('Limit the App to creating agent/** branches?', {
|
|
115
|
+
default: bots.length === 0,
|
|
116
|
+
flag: '--app-branches',
|
|
117
|
+
}))
|
|
118
|
+
? 'agent/**'
|
|
119
|
+
: null
|
|
120
|
+
} catch (err) {
|
|
121
|
+
say(c.warn(/** @type {Error} */ (err).message))
|
|
122
|
+
return 'skipped'
|
|
123
|
+
}
|
|
124
|
+
if (!pattern) {
|
|
125
|
+
say(c.skip('the App may create any branch'))
|
|
126
|
+
return 'skipped'
|
|
127
|
+
}
|
|
128
|
+
try {
|
|
129
|
+
await admin.api('POST', rulesets, appBranchesBody(pattern))
|
|
130
|
+
} catch (err) {
|
|
131
|
+
say(c.warn(`could not create the ruleset as ${admin.who}: ${/** @type {Error} */ (err).message}`))
|
|
132
|
+
say(c.skip(`create it by hand: ${manual}`))
|
|
133
|
+
return 'manual'
|
|
134
|
+
}
|
|
135
|
+
say(c.done(`created ruleset "${APP_BRANCHES_RULESET}": the App may only create ${c.code(pattern)} branches`))
|
|
136
|
+
return 'created'
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Ask whether to allow auto-merge, and turn it on if so.
|
|
141
|
+
*
|
|
142
|
+
* @param {Step & { enabled: boolean | undefined, agentsMerge: boolean, answer?: boolean | null }} input
|
|
143
|
+
* `enabled`: the repository's allow_auto_merge, as the App sees it.
|
|
144
|
+
* `agentsMerge`: some base is mergeable by agents — the reason to want it.
|
|
145
|
+
* `answer`: --auto-merge / --no-auto-merge, if given.
|
|
146
|
+
* @returns {Promise<'ok' | 'enabled' | 'skipped' | 'manual'>}
|
|
147
|
+
*/
|
|
148
|
+
export async function ensureAutoMerge({ owner, repo, admin, prompt, say, c, enabled, agentsMerge, answer = null }) {
|
|
149
|
+
if (enabled) {
|
|
150
|
+
say(c.ok('auto-merge is allowed (graft pr merge --auto)'))
|
|
151
|
+
return 'ok'
|
|
152
|
+
}
|
|
153
|
+
const want =
|
|
154
|
+
answer ??
|
|
155
|
+
(await prompt.confirm('Allow auto-merge, so agents can use `graft pr merge --auto`?', {
|
|
156
|
+
default: agentsMerge,
|
|
157
|
+
flag: '--auto-merge',
|
|
158
|
+
}))
|
|
159
|
+
if (!want) {
|
|
160
|
+
say(c.skip('auto-merge stays off'))
|
|
161
|
+
return 'skipped'
|
|
162
|
+
}
|
|
163
|
+
try {
|
|
164
|
+
await admin.api('PATCH', `/repos/${owner}/${repo}`, { allow_auto_merge: true })
|
|
165
|
+
} catch (err) {
|
|
166
|
+
say(c.warn(`could not allow auto-merge as ${admin.who}: ${/** @type {Error} */ (err).message}`))
|
|
167
|
+
say(c.skip(`turn it on by hand: https://github.com/${owner}/${repo}/settings → General → Allow auto-merge`))
|
|
168
|
+
return 'manual'
|
|
169
|
+
}
|
|
170
|
+
say(c.done('allowed auto-merge'))
|
|
171
|
+
return 'enabled'
|
|
172
|
+
}
|
package/src/setup/project.mjs
CHANGED
|
@@ -20,7 +20,8 @@
|
|
|
20
20
|
* And the base branch's ruleset on GitHub (rulesets.mjs) — what turns
|
|
21
21
|
* CODEOWNERS from documentation into a boundary. The App detects it; the
|
|
22
22
|
* human's `gh` writes it, because the App holds no Administration permission,
|
|
23
|
-
* on purpose.
|
|
23
|
+
* on purpose. Then the optional steps (optional.mjs) — each a question, then
|
|
24
|
+
* done — and an offer to run `graft doctor`.
|
|
24
25
|
*/
|
|
25
26
|
|
|
26
27
|
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
|
@@ -30,10 +31,13 @@ import { PACKAGE_FILE, PACKAGE_KEY, PROJECT_FILE, locateProjectConfig } from '..
|
|
|
30
31
|
import { contextOptions } from '../cli/common.mjs'
|
|
31
32
|
import { flag, has, resolveContext } from '../context.mjs'
|
|
32
33
|
import { NoAppError, isNotFound, readAppCredentials } from '../github/app.mjs'
|
|
34
|
+
import { run as doctor } from './doctor.mjs'
|
|
33
35
|
import { installUrl } from './manifest.mjs'
|
|
36
|
+
import { BRANCH_BOT_FILES, ensureAppBranches, ensureAutoMerge } from './optional.mjs'
|
|
34
37
|
import { createPrompter } from './prompt.mjs'
|
|
35
38
|
import { ensureBaseRuleset, ghAdmin } from './rulesets.mjs'
|
|
36
39
|
import { claudeHooks, envToPairs, gitConfigEnv, mergeSettings } from './settings.mjs'
|
|
40
|
+
import { colorOn, palette } from './style.mjs'
|
|
37
41
|
|
|
38
42
|
const say = (line = '') => console.log(line)
|
|
39
43
|
|
|
@@ -113,20 +117,21 @@ export function lineDiff(before, after) {
|
|
|
113
117
|
]
|
|
114
118
|
}
|
|
115
119
|
|
|
116
|
-
/**
|
|
117
|
-
|
|
118
|
-
|
|
120
|
+
/**
|
|
121
|
+
* What setup cannot do for you, said last: only what applies.
|
|
122
|
+
*
|
|
123
|
+
* @param {{ requiredCheck: string | null, slug: string | null, c?: import('./style.mjs').Palette }} input
|
|
124
|
+
* @returns {string[]}
|
|
125
|
+
*/
|
|
126
|
+
export function closingNotes({ requiredCheck, slug, c = palette(false) }) {
|
|
119
127
|
return [
|
|
120
|
-
'Optional, on GitHub:',
|
|
121
128
|
...(requiredCheck
|
|
122
129
|
? []
|
|
123
|
-
: [
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
...(slug ? [
|
|
127
|
-
|
|
128
|
-
'Then check everything with: graft doctor',
|
|
129
|
-
].join('\n')
|
|
130
|
+
: [
|
|
131
|
+
`Once CI exists, ${c.code('graft setup project --required-check <job>')} adds its check to the base ruleset.`,
|
|
132
|
+
]),
|
|
133
|
+
...(slug ? [`Which repositories the App may touch: ${c.code(installUrl(slug))}`] : []),
|
|
134
|
+
]
|
|
130
135
|
}
|
|
131
136
|
|
|
132
137
|
/**
|
|
@@ -135,14 +140,15 @@ export function githubChecklist({ owner, repo, requiredCheck, slug }) {
|
|
|
135
140
|
* what was just written — its raw git still authenticates as the human.
|
|
136
141
|
*/
|
|
137
142
|
export const RESTART_NOTICE = [
|
|
138
|
-
'
|
|
143
|
+
'Claude Code sessions already open in this repository are NOT protected by what was just written:',
|
|
139
144
|
' they loaded .claude/settings.json (the git env and the hooks) when they started. Restart them.',
|
|
140
145
|
].join('\n')
|
|
141
146
|
|
|
142
147
|
const USAGE = `usage: graft setup project [--config-in <.graft.json | package.json>] [--base <branch>]
|
|
143
148
|
[--validate "<command>"] [--required-check <name>]
|
|
144
149
|
[--mergeable <a,b | none>] [--codeowner <@handle>] [--hooks-path <dir>]
|
|
145
|
-
[--
|
|
150
|
+
[--app-branches <prefix | none>] [--auto-merge | --no-auto-merge]
|
|
151
|
+
[--no-claude] [--no-doctor] [--yes]`
|
|
146
152
|
|
|
147
153
|
/** An answer to "where does the policy live", or `null` when it names neither place. */
|
|
148
154
|
export function configLocation(answer) {
|
|
@@ -189,18 +195,26 @@ export function placePolicy({ target, policy, graftText, pkgText }) {
|
|
|
189
195
|
return out
|
|
190
196
|
}
|
|
191
197
|
|
|
198
|
+
/** Where the policy is, in words: `.graft.json` or `package.json's "graft" key`. */
|
|
199
|
+
const placeName = (p) => (p === PACKAGE_FILE ? `${PACKAGE_FILE}'s "${PACKAGE_KEY}" key` : p)
|
|
200
|
+
|
|
192
201
|
/**
|
|
193
202
|
* @param {string[]} argv
|
|
194
|
-
* @param {{
|
|
203
|
+
* @param {{
|
|
204
|
+
* prompt?: import('./prompt.mjs').Prompter, cwd?: string, env?: NodeJS.ProcessEnv,
|
|
205
|
+
* admin?: ReturnType<typeof ghAdmin>, color?: boolean,
|
|
206
|
+
* doctor?: (argv: string[], deps: { cwd?: string, env?: NodeJS.ProcessEnv }) => Promise<unknown>,
|
|
207
|
+
* }} [deps]
|
|
195
208
|
*/
|
|
196
209
|
export async function setupProject(argv, deps = {}) {
|
|
197
210
|
if (has(argv, '--help')) return say(USAGE)
|
|
211
|
+
const c = palette(deps.color ?? colorOn(process.stdout, deps.env ?? process.env))
|
|
198
212
|
const prompt = deps.prompt ?? createPrompter({ yes: has(argv, '--yes') })
|
|
199
213
|
try {
|
|
200
214
|
const ctx = resolveContext(contextOptions(argv, deps))
|
|
201
215
|
const root = ctx.requireRoot()
|
|
202
216
|
const { owner, repo, full } = ctx.repo()
|
|
203
|
-
say(
|
|
217
|
+
say(`${c.bold('graft setup project')} ${c.dim('·')} ${c.code(full)} ${c.dim(`in ${root}`)}`)
|
|
204
218
|
|
|
205
219
|
// --- the App must reach this repo -----------------------------------
|
|
206
220
|
let meta
|
|
@@ -224,9 +238,10 @@ export async function setupProject(argv, deps = {}) {
|
|
|
224
238
|
}
|
|
225
239
|
throw err
|
|
226
240
|
}
|
|
227
|
-
say(
|
|
241
|
+
say(c.ok(`the App can reach ${full} (default branch: ${meta.default_branch})`))
|
|
228
242
|
|
|
229
243
|
// --- the policy: .graft.json, or package.json's "graft" key ------------
|
|
244
|
+
say(c.section('Policy'))
|
|
230
245
|
const readRoot = (/** @type {string} */ p) =>
|
|
231
246
|
existsSync(join(root, p)) ? readFileSync(join(root, p), 'utf8') : null
|
|
232
247
|
let located
|
|
@@ -243,7 +258,8 @@ export async function setupProject(argv, deps = {}) {
|
|
|
243
258
|
(pkgText === null
|
|
244
259
|
? PROJECT_FILE
|
|
245
260
|
: await prompt.ask(
|
|
246
|
-
`Where should graft keep this repo's policy: ${PROJECT_FILE}, or the "${PACKAGE_KEY}" key in ${PACKAGE_FILE}
|
|
261
|
+
`Where should graft keep this repo's policy: ${PROJECT_FILE}, or the "${PACKAGE_KEY}" key in ${PACKAGE_FILE}?` +
|
|
262
|
+
(located.source ? ` (now: ${located.source})` : ''),
|
|
247
263
|
{ default: located.source ?? PROJECT_FILE, flag: '--config-in' },
|
|
248
264
|
))
|
|
249
265
|
const target = configLocation(configAnswer)
|
|
@@ -289,16 +305,23 @@ export async function setupProject(argv, deps = {}) {
|
|
|
289
305
|
else delete project.requiredCheck
|
|
290
306
|
if (validate) project.validate = { ...(current.validate ?? {}), command: validate }
|
|
291
307
|
if (hooksDir) project.hooks = { ...(current.hooks ?? {}), path: hooksDir }
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
308
|
+
const writes = placePolicy({ target, policy: project, graftText: readRoot(PROJECT_FILE), pkgText })
|
|
309
|
+
const from = located.source && located.source !== target ? located.source : null
|
|
310
|
+
await applyWrites(prompt, writes, root, c, {
|
|
311
|
+
// A move is one change: both halves, or neither — never the policy in two places.
|
|
312
|
+
title: from ? `move the policy from ${placeName(from)} to ${placeName(target)}` : null,
|
|
313
|
+
declined: from ? `kept the policy in ${placeName(from)}; nothing was written` : null,
|
|
314
|
+
})
|
|
295
315
|
if (target === PACKAGE_FILE)
|
|
296
316
|
say(
|
|
297
|
-
|
|
298
|
-
`
|
|
317
|
+
c.dim(
|
|
318
|
+
` note: graft protects the "${PACKAGE_KEY}" key, not the whole ${PACKAGE_FILE}. GitHub cannot enforce a key;\n` +
|
|
319
|
+
` own /${PACKAGE_FILE} in CODEOWNERS too if every change to it should need review.`,
|
|
320
|
+
),
|
|
299
321
|
)
|
|
300
322
|
|
|
301
323
|
// --- CODEOWNERS ------------------------------------------------------
|
|
324
|
+
say(c.section('Code owners'))
|
|
302
325
|
const found = findCodeowners((p) => (existsSync(join(root, p)) ? readFileSync(join(root, p), 'utf8') : null))
|
|
303
326
|
const isOrg = meta.owner?.type === 'Organization'
|
|
304
327
|
const coPath = found.path ?? CODEOWNERS_LOCATIONS[0]
|
|
@@ -319,12 +342,13 @@ export async function setupProject(argv, deps = {}) {
|
|
|
319
342
|
const next = found.path
|
|
320
343
|
? `${found.text.replace(/\n*$/, '\n')}\n# The protection itself (added by graft setup).\n${missing.join('\n')}\n`
|
|
321
344
|
: newCodeowners(missing)
|
|
322
|
-
await
|
|
323
|
-
} else say(
|
|
345
|
+
await applyWrites(prompt, [{ path: coPath, content: next }], root, c)
|
|
346
|
+
} else say(c.ok(`${coPath} already owns the protection itself`))
|
|
324
347
|
|
|
325
348
|
// --- .claude/settings.json ------------------------------------------
|
|
326
349
|
let settingsWritten = false
|
|
327
350
|
if (!has(argv, '--no-claude')) {
|
|
351
|
+
say(c.section('Claude Code'))
|
|
328
352
|
const settingsPath = join(root, '.claude', 'settings.json')
|
|
329
353
|
const existing = existsSync(settingsPath) ? JSON.parse(readFileSync(settingsPath, 'utf8')) : {}
|
|
330
354
|
// Keep rewrites for other owners the file already names.
|
|
@@ -334,15 +358,26 @@ export async function setupProject(argv, deps = {}) {
|
|
|
334
358
|
if (/^url\..*\.insteadOf$/.test(k) && m) owners.add(m[1])
|
|
335
359
|
}
|
|
336
360
|
const next = mergeSettings(existing, { env: gitConfigEnv({ owners: [...owners] }), hooks: claudeHooks() })
|
|
337
|
-
settingsWritten = await
|
|
361
|
+
settingsWritten = await applyWrites(
|
|
362
|
+
prompt,
|
|
363
|
+
[{ path: join('.claude', 'settings.json'), content: `${JSON.stringify(next, null, 2)}\n` }],
|
|
364
|
+
root,
|
|
365
|
+
c,
|
|
366
|
+
)
|
|
338
367
|
}
|
|
339
368
|
|
|
340
|
-
// --- the base branch's ruleset,
|
|
369
|
+
// --- on GitHub: the base branch's ruleset, then the optional steps ---
|
|
370
|
+
say(c.section('GitHub'))
|
|
371
|
+
const admin = deps.admin ?? ghAdmin()
|
|
341
372
|
let effective = null
|
|
342
373
|
try {
|
|
343
374
|
effective = await client.api(`/repos/${owner}/${repo}/rules/branches/${encodeURIComponent(baseBranch)}`)
|
|
344
375
|
} catch (err) {
|
|
345
|
-
say(
|
|
376
|
+
say(
|
|
377
|
+
c.warn(
|
|
378
|
+
`could not read the rules on ${baseBranch}: ${String(/** @type {Error} */ (err).message).slice(0, 200)}`,
|
|
379
|
+
),
|
|
380
|
+
)
|
|
346
381
|
}
|
|
347
382
|
if (effective)
|
|
348
383
|
await ensureBaseRuleset({
|
|
@@ -351,50 +386,87 @@ export async function setupProject(argv, deps = {}) {
|
|
|
351
386
|
base: baseBranch,
|
|
352
387
|
requiredCheck: requiredCheck || null,
|
|
353
388
|
effective,
|
|
354
|
-
admin
|
|
389
|
+
admin,
|
|
355
390
|
prompt,
|
|
356
391
|
say,
|
|
357
392
|
env: ctx.env,
|
|
393
|
+
c,
|
|
358
394
|
})
|
|
395
|
+
const step = { owner, repo, admin, prompt, say, c }
|
|
396
|
+
await ensureAppBranches({
|
|
397
|
+
...step,
|
|
398
|
+
answer: flag(argv, '--app-branches') ?? null,
|
|
399
|
+
bots: BRANCH_BOT_FILES.filter((f) => existsSync(join(root, f))),
|
|
400
|
+
})
|
|
401
|
+
await ensureAutoMerge({
|
|
402
|
+
...step,
|
|
403
|
+
enabled: meta.allow_auto_merge,
|
|
404
|
+
agentsMerge: mergeable.length > 0,
|
|
405
|
+
answer: has(argv, '--auto-merge') ? true : has(argv, '--no-auto-merge') ? false : null,
|
|
406
|
+
})
|
|
359
407
|
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
408
|
+
const notes = closingNotes({ requiredCheck: requiredCheck || null, slug, c })
|
|
409
|
+
if (notes.length) {
|
|
410
|
+
say(c.section('Left to you'))
|
|
411
|
+
for (const n of notes) say(` ${n}`)
|
|
412
|
+
}
|
|
413
|
+
if (settingsWritten) say(`\n${c.warn(c.yellow(RESTART_NOTICE))}`)
|
|
414
|
+
|
|
415
|
+
if (has(argv, '--no-doctor')) say(`\n${c.dim('Check everything with:')} ${c.code('graft doctor')}`)
|
|
416
|
+
else if (await prompt.confirm('Run graft doctor now?', { default: true })) {
|
|
417
|
+
say(c.section('graft doctor'))
|
|
418
|
+
await (deps.doctor ?? doctor)(argv, { cwd: deps.cwd, env: deps.env })
|
|
419
|
+
} else say(c.skip(`check everything later with ${c.code('graft doctor')}`))
|
|
363
420
|
} finally {
|
|
364
421
|
prompt.close()
|
|
365
422
|
}
|
|
366
423
|
}
|
|
367
424
|
|
|
368
|
-
/**
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
}
|
|
425
|
+
/**
|
|
426
|
+
* Show what would change, confirm once, apply. Unchanged files are left alone.
|
|
427
|
+
* Several writes with a `title` are one change: confirmed together, applied
|
|
428
|
+
* together, or not at all.
|
|
429
|
+
*
|
|
430
|
+
* @param {import('./prompt.mjs').Prompter} prompt
|
|
431
|
+
* @param {{ path: string, content: string | null }[]} writes `content: null` deletes
|
|
432
|
+
* @param {string} root
|
|
433
|
+
* @param {import('./style.mjs').Palette} c
|
|
434
|
+
* @param {{ title?: string | null, declined?: string | null }} [opts]
|
|
435
|
+
* @returns {Promise<boolean>} whether anything was written
|
|
436
|
+
*/
|
|
437
|
+
export async function applyWrites(prompt, writes, root, c, { title = null, declined = null } = {}) {
|
|
438
|
+
const changes = writes
|
|
439
|
+
.map((w) => {
|
|
440
|
+
const abs = join(root, w.path)
|
|
441
|
+
const before = existsSync(abs) ? readFileSync(abs, 'utf8') : null
|
|
442
|
+
return { ...w, abs, before }
|
|
443
|
+
})
|
|
444
|
+
.filter((w) => (w.content === null ? w.before !== null : w.before !== w.content))
|
|
445
|
+
for (const w of writes)
|
|
446
|
+
if (!changes.some((x) => x.path === w.path) && w.content !== null) say(c.ok(`${w.path} is up to date`))
|
|
447
|
+
if (!changes.length) return false
|
|
381
448
|
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
return false
|
|
449
|
+
if (title) say(c.bold(title))
|
|
450
|
+
for (const w of changes) {
|
|
451
|
+
const verb = w.content === null ? 'remove' : w.before === null ? 'create' : 'update'
|
|
452
|
+
say(`${title ? ' ' : ''}${verb} ${c.code(w.path)}${w.content === null ? '' : ':'}`)
|
|
453
|
+
if (w.content !== null)
|
|
454
|
+
for (const l of lineDiff(w.before, w.content).slice(0, 40)) say(`${title ? ' ' : ' '}${c.diff(l)}`)
|
|
389
455
|
}
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
456
|
+
const question = title
|
|
457
|
+
? `${title.charAt(0).toUpperCase()}${title.slice(1)}?`
|
|
458
|
+
: `${changes[0].before === null ? 'Create' : 'Update'} ${changes[0].path}?`
|
|
459
|
+
if (!(await prompt.confirm(question, { default: true, flag: '--yes' }))) {
|
|
460
|
+
say(c.skip(declined ?? `skipped ${changes.map((w) => w.path).join(', ')}`))
|
|
394
461
|
return false
|
|
395
462
|
}
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
463
|
+
for (const w of changes) {
|
|
464
|
+
if (w.content === null) rmSync(w.abs)
|
|
465
|
+
else {
|
|
466
|
+
mkdirSync(dirname(w.abs), { recursive: true })
|
|
467
|
+
writeFileSync(w.abs, w.content)
|
|
468
|
+
}
|
|
469
|
+
say(c.done(`${w.content === null ? 'removed' : 'wrote'} ${w.path}`))
|
|
470
|
+
}
|
|
399
471
|
return true
|
|
400
472
|
}
|
package/src/setup/prompt.mjs
CHANGED
|
@@ -5,12 +5,13 @@
|
|
|
5
5
|
*
|
|
6
6
|
* Every question has a flag. Without a TTY (an agent's Bash call, a `!`
|
|
7
7
|
* command, CI) there is nobody to ask, so it runs as if `--yes` were given: a
|
|
8
|
-
* question
|
|
9
|
-
*
|
|
10
|
-
*
|
|
8
|
+
* question or a confirmation takes its default, and a question without a
|
|
9
|
+
* default fails naming the flag that answers it — an unattended run never
|
|
10
|
+
* blocks on stdin that will never come.
|
|
11
11
|
*/
|
|
12
12
|
|
|
13
13
|
import { createInterface } from 'node:readline/promises'
|
|
14
|
+
import { colorOn, palette } from './style.mjs'
|
|
14
15
|
|
|
15
16
|
/**
|
|
16
17
|
* @typedef {{
|
|
@@ -21,7 +22,7 @@ import { createInterface } from 'node:readline/promises'
|
|
|
21
22
|
*/
|
|
22
23
|
|
|
23
24
|
/**
|
|
24
|
-
* @param {{ yes?: boolean, interactive?: boolean, input?: NodeJS.ReadableStream, output?: NodeJS.WritableStream }} [opts]
|
|
25
|
+
* @param {{ yes?: boolean, interactive?: boolean, input?: NodeJS.ReadableStream, output?: NodeJS.WritableStream, env?: NodeJS.ProcessEnv }} [opts]
|
|
25
26
|
* @returns {Prompter}
|
|
26
27
|
*/
|
|
27
28
|
export function createPrompter({
|
|
@@ -29,7 +30,9 @@ export function createPrompter({
|
|
|
29
30
|
interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY),
|
|
30
31
|
input = process.stdin,
|
|
31
32
|
output = process.stdout,
|
|
33
|
+
env = process.env,
|
|
32
34
|
} = {}) {
|
|
35
|
+
const c = palette(colorOn(/** @type {any} */ (output), env))
|
|
33
36
|
/** @type {import('node:readline/promises').Interface | null} */
|
|
34
37
|
let rl = null
|
|
35
38
|
const line = async (q) => {
|
|
@@ -47,14 +50,14 @@ export function createPrompter({
|
|
|
47
50
|
if (unattended && def !== null) return def
|
|
48
51
|
if (!interactive) throw unanswerable(question, flag)
|
|
49
52
|
for (;;) {
|
|
50
|
-
const got = await line(`${question}${def ? ` [${def}]` : ''}: `)
|
|
53
|
+
const got = await line(`${c.code('?')} ${c.bold(question)}${def ? c.dim(` [${def}]`) : ''}: `)
|
|
51
54
|
if (got) return got
|
|
52
55
|
if (def !== null) return def
|
|
53
56
|
}
|
|
54
57
|
},
|
|
55
58
|
async confirm(question, { default: def = true } = {}) {
|
|
56
|
-
if (unattended) return
|
|
57
|
-
const got = (await line(`${question} ${def ? '[Y/n]' : '[y/N]'} `)).toLowerCase()
|
|
59
|
+
if (unattended) return def
|
|
60
|
+
const got = (await line(`${c.code('?')} ${c.bold(question)} ${c.dim(def ? '[Y/n]' : '[y/N]')} `)).toLowerCase()
|
|
58
61
|
if (!got) return def
|
|
59
62
|
return got.startsWith('y')
|
|
60
63
|
},
|
package/src/setup/rulesets.mjs
CHANGED
|
@@ -24,6 +24,7 @@ import { spawnSync } from 'node:child_process'
|
|
|
24
24
|
import { mkdirSync, writeFileSync } from 'node:fs'
|
|
25
25
|
import { join } from 'node:path'
|
|
26
26
|
import { graftHome } from '../config.mjs'
|
|
27
|
+
import { palette } from './style.mjs'
|
|
27
28
|
|
|
28
29
|
/** The ruleset graft owns on a base branch. Other rulesets are never touched. */
|
|
29
30
|
export const rulesetName = (base) => `graft: ${base}`
|
|
@@ -201,6 +202,7 @@ export function ghAdmin({ run = spawnSync } = {}) {
|
|
|
201
202
|
* prompt: import('./prompt.mjs').Prompter,
|
|
202
203
|
* say?: (line?: string) => void,
|
|
203
204
|
* env?: NodeJS.ProcessEnv,
|
|
205
|
+
* c?: import('./style.mjs').Palette,
|
|
204
206
|
* }} input
|
|
205
207
|
* @returns {Promise<{ state: 'ok' | 'created' | 'updated' | 'skipped' | 'file', file?: string }>}
|
|
206
208
|
*/
|
|
@@ -214,23 +216,24 @@ export async function ensureBaseRuleset({
|
|
|
214
216
|
prompt,
|
|
215
217
|
say = console.log,
|
|
216
218
|
env = process.env,
|
|
219
|
+
c = palette(false),
|
|
217
220
|
}) {
|
|
218
221
|
const wanted = wantedRules({ requiredCheck })
|
|
219
222
|
const missing = missingRules(effective, wanted)
|
|
220
223
|
if (!missing.length) {
|
|
221
|
-
say(
|
|
224
|
+
say(c.ok(`${base} on GitHub: ${wanted.map(describeRule).join('; ')}`))
|
|
222
225
|
return { state: 'ok' }
|
|
223
226
|
}
|
|
224
227
|
const name = rulesetName(base)
|
|
225
228
|
const rulesets = `/repos/${owner}/${repo}/rulesets`
|
|
226
|
-
say(
|
|
227
|
-
for (const m of missing) say(` + ${describeRule(m)}`)
|
|
229
|
+
say(`${base} on GitHub lacks:`)
|
|
230
|
+
for (const m of missing) say(c.green(` + ${describeRule(m)}`))
|
|
228
231
|
|
|
229
232
|
const toFile = (why) => {
|
|
230
233
|
const file = join(graftHome(env), 'rulesets', `${owner}-${repo}-${base.replace(/[^\w.-]/g, '_')}.json`)
|
|
231
234
|
mkdirSync(join(graftHome(env), 'rulesets'), { recursive: true })
|
|
232
235
|
writeFileSync(file, `${JSON.stringify(rulesetBody({ base, wanted, missing }), null, 2)}\n`)
|
|
233
|
-
say(
|
|
236
|
+
say(c.warn(`could not apply it as you (${why}).`))
|
|
234
237
|
say(` A repository admin can import ${file}`)
|
|
235
238
|
say(` at https://github.com/${owner}/${repo}/settings/rules → New ruleset → Import a ruleset,`)
|
|
236
239
|
say(` or log in with \`gh auth login\` and run graft setup project again.`)
|
|
@@ -249,9 +252,9 @@ export async function ensureBaseRuleset({
|
|
|
249
252
|
}
|
|
250
253
|
const body = rulesetBody({ base, wanted, missing, existing })
|
|
251
254
|
const verb = existing ? 'update' : 'create'
|
|
252
|
-
if (!existing) say(` bypass: repository admins, through pull requests only (the App never)`)
|
|
255
|
+
if (!existing) say(c.dim(` bypass: repository admins, through pull requests only (the App never)`))
|
|
253
256
|
if (!(await prompt.confirm(`${verb} ruleset "${name}" on ${owner}/${repo}, as ${admin.who}?`, { default: true }))) {
|
|
254
|
-
say(
|
|
257
|
+
say(c.skip('skipped the ruleset'))
|
|
255
258
|
return { state: 'skipped' }
|
|
256
259
|
}
|
|
257
260
|
try {
|
|
@@ -259,6 +262,6 @@ export async function ensureBaseRuleset({
|
|
|
259
262
|
} catch (err) {
|
|
260
263
|
return toFile(/** @type {Error} */ (err).message)
|
|
261
264
|
}
|
|
262
|
-
say(
|
|
265
|
+
say(c.done(`${verb}d ruleset "${name}"`))
|
|
263
266
|
return { state: existing ? 'updated' : 'created' }
|
|
264
267
|
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
/**
|
|
3
|
+
* Color for the setup commands' output — off unless a person is reading it.
|
|
4
|
+
*
|
|
5
|
+
* On when the stream is a terminal, or FORCE_COLOR asks for it; off for
|
|
6
|
+
* NO_COLOR, TERM=dumb, pipes, agents' shells and tests. Decided here, not by
|
|
7
|
+
* `styleText`'s own check, because that check only exists from Node 22.13 and
|
|
8
|
+
* graft runs on any 22.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { styleText } from 'node:util'
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* @param {{ isTTY?: boolean }} [stream]
|
|
15
|
+
* @param {NodeJS.ProcessEnv} [env]
|
|
16
|
+
*/
|
|
17
|
+
export function colorOn(stream = process.stdout, env = process.env) {
|
|
18
|
+
if (env.NO_COLOR) return false
|
|
19
|
+
if (env.FORCE_COLOR !== undefined) return env.FORCE_COLOR !== '0' && env.FORCE_COLOR !== 'false'
|
|
20
|
+
return Boolean(stream?.isTTY) && env.TERM !== 'dumb'
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** @typedef {ReturnType<typeof palette>} Palette */
|
|
24
|
+
|
|
25
|
+
/** Styling functions; each is the identity when color is off. */
|
|
26
|
+
export function palette(on = colorOn()) {
|
|
27
|
+
/** @param {Parameters<typeof styleText>[0]} fmt */
|
|
28
|
+
const s = (fmt) => (/** @type {unknown} */ t) =>
|
|
29
|
+
on ? styleText(fmt, String(t), { validateStream: false }) : String(t)
|
|
30
|
+
const p = {
|
|
31
|
+
on,
|
|
32
|
+
bold: s('bold'),
|
|
33
|
+
dim: s('dim'),
|
|
34
|
+
code: s('cyan'),
|
|
35
|
+
green: s('green'),
|
|
36
|
+
yellow: s('yellow'),
|
|
37
|
+
red: s('red'),
|
|
38
|
+
heading: s(['bold', 'cyan']),
|
|
39
|
+
}
|
|
40
|
+
return {
|
|
41
|
+
...p,
|
|
42
|
+
/** `✓ text` — already right, nothing to do. */
|
|
43
|
+
ok: (/** @type {string} */ t) => `${p.green('✓')} ${t}`,
|
|
44
|
+
/** `! text` — needs the reader's attention. */
|
|
45
|
+
warn: (/** @type {string} */ t) => `${p.yellow('!')} ${t}`,
|
|
46
|
+
/** `→ text` — something setup just changed. */
|
|
47
|
+
done: (/** @type {string} */ t) => ` ${p.green('→')} ${t}`,
|
|
48
|
+
/** `· text` — something setup left as it was. */
|
|
49
|
+
skip: (/** @type {string} */ t) => ` ${p.dim(`· ${t}`)}`,
|
|
50
|
+
/** A section title, with a blank line before it. */
|
|
51
|
+
section: (/** @type {string} */ t) => `\n${p.heading(t)}`,
|
|
52
|
+
/** One `lineDiff` line: `+` green, `-` red. */
|
|
53
|
+
diff: (/** @type {string} */ l) => (l.startsWith('+') ? p.green(l) : l.startsWith('-') ? p.red(l) : l),
|
|
54
|
+
}
|
|
55
|
+
}
|