-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinitial-commit.mjs
More file actions
274 lines (236 loc) · 7.86 KB
/
initial-commit.mjs
File metadata and controls
274 lines (236 loc) · 7.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
#!/usr/bin/env node
/**
* Create a reproducible empty initial commit (160e2bf) for multi-origin template workflows.
*/
import { spawnSync } from 'node:child_process'
import fs from 'node:fs'
import path from 'node:path'
import { parseArgs } from 'node:util'
const EMPTY_TREE = '4b825dc642cb6eb9a060e54bf8d69288fbee4904'
const EXPECTED_SHA = '160e2bf1a43661662f877ad859f0aaacd839d7d2'
const COMMIT_MESSAGE = 'Initial empty commit'
const REDO_BRANCH = 'redo-initial-commit'
const COMMIT_ENV = {
GIT_AUTHOR_NAME: 'Initial empty commit',
GIT_AUTHOR_EMAIL: 'initial@example.com',
GIT_COMMITTER_NAME: 'Initial empty commit',
GIT_COMMITTER_EMAIL: 'initial@example.com',
GIT_AUTHOR_DATE: '2000-01-01T12:00:00+0000',
GIT_COMMITTER_DATE: '2000-01-01T12:00:00+0000',
}
main()
function usage() {
return `initial-commit — reproducible empty initial commit (160e2bf)
Usage:
npx initial-commit@latest [--rebase-everything] [<repo-dir>]
Options:
--rebase-everything When history already exists, create branch "${REDO_BRANCH}"
with the consistent initial commit and cherry-pick all commits
from the branch that was checked out. Prints instructions to
replace your local default branch, force-push with upstream
tracking, and fetch if you pushed without -u.
-h, --help Show this help.
Arguments:
<repo-dir> Target repository directory (default: current directory).
The initial commit is always ${EXPECTED_SHA} when author, committer, date, message,
and tree match the fixed recipe. Re-run fails if HEAD already exists unless
--rebase-everything is used.
`
}
function die(msg, code = 1) {
console.error(msg)
process.exit(code)
}
function git(cwd, args, input) {
const opts = {
cwd,
encoding: 'utf8',
stdio: input ? ['pipe', 'pipe', 'pipe'] : ['ignore', 'pipe', 'pipe'],
input: input ?? undefined,
}
const r = spawnSync('git', args, opts)
if (r.error) {
throw r.error
}
if (r.status !== 0) {
const err = (r.stderr || '').trim() || `git ${args.join(' ')} failed`
const e = new Error(err)
e.status = r.status
e.stderr = r.stderr
throw e
}
return (r.stdout || '').replace(/\r\n/g, '\n').trim()
}
function gitAllowFail(cwd, args) {
const r = spawnSync('git', args, {
cwd,
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'pipe'],
})
return {
status: r.status ?? 1,
stdout: (r.stdout || '').replace(/\r\n/g, '\n').trim(),
stderr: r.stderr || '',
}
}
function hasCommits(repo) {
const r = gitAllowFail(repo, ['rev-parse', '--verify', 'HEAD'])
return r.status === 0
}
function detectBranch(repo) {
const cur = gitAllowFail(repo, ['branch', '--show-current'])
if (cur.status === 0 && cur.stdout) {
return cur.stdout
}
const sym = gitAllowFail(repo, ['symbolic-ref', '--short', 'HEAD'])
if (sym.status === 0 && sym.stdout) {
return sym.stdout
}
return 'main'
}
function ensureGitRepo(repoDir) {
const abs = path.resolve(repoDir)
const st = fs.statSync(abs, { throwIfNoEntry: false })
if (!st?.isDirectory()) {
die(`Not a directory: ${repoDir}`)
}
const gitDir = path.join(abs, '.git')
if (!fs.existsSync(gitDir)) {
git(abs, ['init', '-b', 'main'])
}
return abs
}
function commitEnv() {
return { ...process.env, ...COMMIT_ENV }
}
function createInitialCommitSha(repo) {
const r = spawnSync('git', ['commit-tree', '-m', COMMIT_MESSAGE, EMPTY_TREE], {
cwd: repo,
encoding: 'utf8',
env: commitEnv(),
stdio: ['ignore', 'pipe', 'pipe'],
})
if (r.status !== 0) {
die(`git commit-tree failed: ${(r.stderr || '').trim() || r.stdout}`)
}
return (r.stdout || '').replace(/\r\n/g, '\n').trim()
}
function updateBranchRef(repo, branch, sha) {
git(repo, ['update-ref', '-m', COMMIT_MESSAGE, `refs/heads/${branch}`, sha])
}
function ensureHeadOnBranch(repo, branch) {
const headSym = gitAllowFail(repo, ['symbolic-ref', 'HEAD'])
const want = `refs/heads/${branch}`
if (headSym.status !== 0 || headSym.stdout !== want) {
git(repo, ['symbolic-ref', 'HEAD', want])
}
}
function verifyExpectedSha(repo) {
const actual = git(repo, ['rev-parse', 'HEAD'])
if (actual !== EXPECTED_SHA) {
die(`Initial commit hash mismatch.\n expected: ${EXPECTED_SHA}\n actual: ${actual}`)
}
return actual
}
function createInitialCommit(repo, branch) {
const sha = createInitialCommitSha(repo)
updateBranchRef(repo, branch, sha)
ensureHeadOnBranch(repo, branch)
return verifyExpectedSha(repo)
}
function cherryPickCommit(repo, sha) {
let r = spawnSync('git', ['cherry-pick', sha], {
cwd: repo,
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'pipe'],
})
if (r.status === 0) {
return
}
const err = (r.stderr || '').trim()
if (/previous cherry-pick is now empty|could be empty/i.test(err)) {
r = spawnSync('git', ['cherry-pick', '--allow-empty', sha], {
cwd: repo,
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'pipe'],
})
if (r.status === 0) {
return
}
}
die(`git cherry-pick ${sha.slice(0, 7)} failed:\n${(r.stderr || '').trim() || r.stdout}`)
}
function redoInitialCommit(repo, origBranch) {
const commits = git(repo, ['rev-list', '--reverse', origBranch]).split('\n').filter(Boolean)
if (commits.length === 0) {
die(`No commits on branch ${origBranch}.`)
}
const initialSha = createInitialCommitSha(repo)
if (initialSha !== EXPECTED_SHA) {
die(`Initial commit hash mismatch.\n expected: ${EXPECTED_SHA}\n actual: ${initialSha}`)
}
git(repo, ['branch', '-f', REDO_BRANCH, initialSha])
git(repo, ['checkout', REDO_BRANCH])
let replayed = 0
for (const sha of commits) {
cherryPickCommit(repo, sha)
replayed += 1
}
const tip = git(repo, ['rev-parse', 'HEAD'])
const root = git(repo, ['rev-list', '--max-parents=0', 'HEAD'])
if (root !== EXPECTED_SHA) {
die(`Root commit hash mismatch after replay.\n expected: ${EXPECTED_SHA}\n actual: ${root}`)
}
console.error(`Created branch '${REDO_BRANCH}' with initial commit 160e2bf and replayed ${replayed} commit(s).`)
console.error('')
console.error('Replace your local default branch:')
console.error(` git branch -D ${origBranch}`)
console.error(` git branch -m ${REDO_BRANCH} ${origBranch}`)
console.error('')
console.error('Update GitHub (rewrites remote history; coordinate with collaborators):')
console.error(` git push --force-with-lease -u origin ${origBranch}`)
console.error('')
console.log(`${repo} branch=${REDO_BRANCH} initial=160e2bf tip=${tip.slice(0, 7)}`)
}
function main() {
const argv = process.argv.slice(2)
if (argv.includes('--help') || argv.includes('-h')) {
console.log(usage())
process.exit(0)
}
let values
let positionals
try {
;({ values, positionals } = parseArgs({
args: argv,
options: {
'rebase-everything': { type: 'boolean', default: false },
},
allowPositionals: true,
}))
} catch (e) {
die(`${e instanceof Error ? e.message : String(e)}\n\n${usage()}`, 1)
}
if (positionals.length > 1) {
die(`Too many arguments: ${positionals.join(' ')}\n\n${usage()}`)
}
const repoDir = positionals[0] ?? process.cwd()
const rebaseEverything = values['rebase-everything'] === true
const repo = ensureGitRepo(repoDir)
const branch = detectBranch(repo)
if (hasCommits(repo)) {
if (!rebaseEverything) {
die(
`Repository already has commits (${repo}).\nUse --rebase-everything to rewrite history onto ${EXPECTED_SHA.slice(0, 7)}.`,
)
}
const origBranch = gitAllowFail(repo, ['branch', '--show-current']).stdout
if (!origBranch) {
die('Detached HEAD; checkout a branch before using --rebase-everything.')
}
redoInitialCommit(repo, origBranch)
return
}
const sha = createInitialCommit(repo, branch)
console.log(`${repo} branch=${branch} initial=${sha.slice(0, 7)} ${sha}`)
}