-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathupdate.js
More file actions
216 lines (182 loc) · 6.97 KB
/
Copy pathupdate.js
File metadata and controls
216 lines (182 loc) · 6.97 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
#!/usr/bin/env node
/**
* @file update.js
*
* Updates Blog-Doc to the latest version by pulling the newest code
* from the repository and refreshing dependencies (only if they changed).
*
* Run this from your project root whenever a new version is released:
*
* node update.js
* — or —
* npm run update
*
* Your content and data are never touched by this script.
* The following are gitignored and therefore completely safe:
*
* app/content/ ← your pages, posts and images
* app/data/ ← your settings, menus and active theme
* app/themes/ ← your installed themes (except the bundled default)
*/
import { spawnSync } from "child_process"
import { readFileSync, existsSync } from "fs"
import readline from "node:readline/promises"
const IS_WINDOWS = process.platform === "win32"
const RELEASES_URL = "https://github.com/LebCit/blog-doc/releases"
/**
* Runs a git command and returns its trimmed stdout.
* Throws with the command's stderr on failure.
*
* @param {string[]} args - Arguments passed to git.
* @param {object} [options] - Extra spawnSync options.
* @returns {string} Trimmed stdout.
*/
function git(args, options = {}) {
const result = spawnSync("git", args, { encoding: "utf-8", ...options })
if (result.error) {
throw new Error(result.error.message)
}
if (result.status !== 0) {
throw new Error(result.stderr?.trim() || `git ${args.join(" ")} failed`)
}
return (result.stdout || "").trim()
}
/**
* Checks the Node.js version and exits if the version is less than 18.
*/
function checkNodeVersion() {
const currentVersion = process.versions.node
const majorVersion = parseInt(currentVersion.split(".")[0], 10)
if (majorVersion < 18) {
console.error(`Node.js v${currentVersion} is not supported. Please upgrade to Node.js v18 or higher.`)
process.exit(1)
}
}
/**
* Verifies the current directory is a Blog-Doc project root, to avoid
* running git operations in the wrong place.
*
* @returns {{ name: string, version: string }} The parsed package.json.
*/
function checkInsideProject() {
if (!existsSync("package.json") || !existsSync(".git")) {
console.error("\n This doesn't look like a Blog-Doc project root.")
console.error(" Run this command from the folder created by create-blog-doc.\n")
process.exit(1)
}
const pkg = JSON.parse(readFileSync("package.json", "utf-8"))
if (pkg.name !== "blog-doc") {
console.error("\n This doesn't look like a Blog-Doc project root.")
console.error(` Expected package.json name "blog-doc", found "${pkg.name}".\n`)
process.exit(1)
}
return pkg
}
/**
* Resolves the configured upstream branch (e.g. "origin/main") for HEAD.
* Does not guess a branch name if none is configured.
*
* @returns {string} The upstream ref.
*/
function getUpstream() {
try {
return git(["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"])
} catch {
console.error("\n No upstream branch is configured for this repository.")
console.error(" Run: git branch --set-upstream-to=origin/<branch-name>\n")
process.exit(1)
}
}
/**
* Warns about uncommitted changes to tracked files and asks for confirmation
* before continuing. Aborts automatically in non-interactive environments,
* since silently pulling over local changes is not a safe default.
*/
async function guardUncommittedChanges() {
const status = git(["status", "--porcelain"])
if (!status) {
return
}
const changedCount = status.split("\n").filter(Boolean).length
console.warn(
`\n You have ${changedCount} uncommitted change(s) to tracked file(s). Updating may cause conflicts.\n`,
)
if (!process.stdin.isTTY) {
console.error(" Aborting: run this interactively, or commit/stash your changes first.\n")
process.exit(1)
}
const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
let answer
try {
answer = await rl.question(" Continue anyway? (y/N) ")
} finally {
rl.close()
}
if (answer.trim().toLowerCase() !== "y") {
console.log("\n Update cancelled.\n")
process.exit(0)
}
}
async function main() {
checkNodeVersion()
const pkg = checkInsideProject()
const upstream = getUpstream()
await guardUncommittedChanges()
console.log("\n Updating Blog-Doc...\n")
console.log(" › Fetching latest changes...")
try {
git(["fetch"], { stdio: "inherit" })
} catch (error) {
console.error("\n Could not fetch from the remote repository.")
console.error(" Possible causes: no internet connection, or the remote is unreachable.")
console.error(` ${error.message}\n`)
process.exit(1)
}
const behindCount = parseInt(git(["rev-list", "HEAD..." + upstream, "--count"]), 10)
if (behindCount === 0) {
console.log(`\n Already up to date (v${pkg.version}).\n`)
return
}
let latestVersion = "unknown"
try {
const remotePkgRaw = git(["show", `${upstream}:package.json`])
latestVersion = JSON.parse(remotePkgRaw).version
} catch {
// Non-fatal — version display is a nicety, not a requirement.
}
console.log(`\n Current version: v${pkg.version}`)
console.log(` Latest version: v${latestVersion}\n`)
const oldHead = git(["rev-parse", "HEAD"])
console.log(" › Applying update...")
try {
git(["merge", "--ff-only", upstream], { stdio: "inherit" })
} catch (error) {
console.error("\n Could not apply the update (fast-forward failed).")
console.error(" This usually means a tracked file was modified locally outside of git.")
console.error(" Run 'git status' to inspect the conflict, or 'git log' to compare history.")
console.error(` ${error.message}\n`)
process.exit(1)
}
const newHead = git(["rev-parse", "HEAD"])
const changedFiles = git(["diff", "--name-only", oldHead, newHead]).split("\n").filter(Boolean)
const depsChanged = changedFiles.includes("package.json") || changedFiles.includes("package-lock.json")
if (depsChanged) {
console.log("\n › Installing dependencies...\n")
const installResult = spawnSync("npm", ["install"], { stdio: "inherit", shell: IS_WINDOWS })
if (installResult.status !== 0) {
console.error("\n Update applied, but dependency installation failed.")
console.error(" Run 'npm install' manually to finish.\n")
process.exit(1)
}
} else {
console.log("\n › Dependencies unchanged, skipping install.")
}
console.log(`\n Blog-Doc updated to v${latestVersion}.`)
console.log(" Your content and data are untouched.")
console.log(`\n See what's new: ${RELEASES_URL}`)
console.log(" Start the app: npm start\n")
}
main().catch((error) => {
console.error("\n Update failed:", error.message, "\n")
process.exit(1)
})