-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeploy.ts
More file actions
240 lines (205 loc) · 6.81 KB
/
Copy pathdeploy.ts
File metadata and controls
240 lines (205 loc) · 6.81 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
import { spawnSync } from "node:child_process";
import { existsSync } from "node:fs";
import path from "node:path";
import { config as loadEnv } from "dotenv";
const rootDir = process.cwd();
const envFiles = [".env", ".env.local", ".env.deploy", ".env.deploy.local"];
for (const file of envFiles) {
const envPath = path.resolve(rootDir, file);
if (existsSync(envPath)) {
loadEnv({ path: envPath, override: true });
}
}
const helpText = `
Usage:
pnpm deploy:hostinger
pnpm deploy:hostinger -- --skip-build
pnpm deploy:hostinger -- --dry-run
Required env vars (.env.deploy or .env.deploy.local):
DEPLOY_SSH_HOST
DEPLOY_SSH_PORT
DEPLOY_SSH_USER
DEPLOY_SSH_KEY_PATH
DEPLOY_REMOTE_DIR
Optional:
DEPLOY_SITE_URL
DEPLOY_KEEP_BACKUPS (default: 5)
`.trim();
const args = new Set(process.argv.slice(2));
if (args.has("--help")) {
console.log(helpText);
process.exit(0);
}
const skipBuild = args.has("--skip-build");
const dryRun = args.has("--dry-run");
const requiredKeys = [
"DEPLOY_SSH_HOST",
"DEPLOY_SSH_PORT",
"DEPLOY_SSH_USER",
"DEPLOY_SSH_KEY_PATH",
"DEPLOY_REMOTE_DIR",
] as const;
const missingKeys = requiredKeys.filter((key) => !process.env[key]);
if (missingKeys.length > 0) {
console.error(
`Missing deploy env vars: ${missingKeys.join(", ")}\n\n${helpText}`
);
process.exit(1);
}
const deployConfig = {
host: process.env.DEPLOY_SSH_HOST!,
port: process.env.DEPLOY_SSH_PORT!,
user: process.env.DEPLOY_SSH_USER!,
keyPath: process.env.DEPLOY_SSH_KEY_PATH!,
remoteDir: process.env.DEPLOY_REMOTE_DIR!,
siteUrl:
process.env.DEPLOY_SITE_URL ||
process.env.VITE_SITE_URL ||
"https://bebitterbebetter.com.br",
keepBackups: parsePositiveInt(process.env.DEPLOY_KEEP_BACKUPS, 5),
};
if (!existsSync(deployConfig.keyPath)) {
console.error(`SSH key not found: ${deployConfig.keyPath}`);
process.exit(1);
}
const remoteTarget = `${deployConfig.user}@${deployConfig.host}`;
const sshArgs = [
"-i",
deployConfig.keyPath,
"-p",
deployConfig.port,
"-o",
"StrictHostKeyChecking=accept-new",
];
const sshTransport = `ssh -i ${quoteForShell(deployConfig.keyPath)} -p ${quoteForShell(deployConfig.port)} -o StrictHostKeyChecking=accept-new`;
const backupSuffix = formatTimestamp(new Date());
const backupDir = `${deployConfig.remoteDir}.backup-${backupSuffix}`;
if (!skipBuild) {
run("pnpm", ["build"]);
}
if (!dryRun) {
run("ssh", [
...sshArgs,
remoteTarget,
[
"set -eu",
`test -d ${quoteForShell(deployConfig.remoteDir)}`,
`test ! -e ${quoteForShell(backupDir)}`,
`cp -a ${quoteForShell(deployConfig.remoteDir)} ${quoteForShell(backupDir)}`,
`printf 'Remote backup created: %s\\n' ${quoteForShell(backupDir)}`,
].join("; "),
]);
}
const rsyncArgs = [
"-az",
"--delete",
"--checksum",
"--human-readable",
"--itemize-changes",
...(dryRun ? ["--dry-run"] : []),
"-e",
sshTransport,
"dist/",
`${remoteTarget}:${deployConfig.remoteDir}/`,
];
run("rsync", rsyncArgs);
if (!dryRun) {
run("ssh", [
...sshArgs,
remoteTarget,
[
"set -eu",
`chmod -R u=rwX,go=rX ${quoteForShell(deployConfig.remoteDir)}`,
`test -f ${quoteForShell(path.posix.join(deployConfig.remoteDir, "index.html"))}`,
`test -f ${quoteForShell(path.posix.join(deployConfig.remoteDir, ".htaccess"))}`,
`test -f ${quoteForShell(path.posix.join(deployConfig.remoteDir, "robots.txt"))}`,
`test -f ${quoteForShell(path.posix.join(deployConfig.remoteDir, "sitemap.xml"))}`,
"printf 'Remote verification passed.\\n'",
].join("; "),
]);
verifyHttp(deployConfig.siteUrl);
pruneRemoteBackups();
}
/**
* Backups are siblings named `<remoteDir>.backup-YYYYMMDD-HHMMSS`. Since the
* suffix is zero-padded, sorting by name descending gives newest first — mtime
* is useless here because `cp -a` copies the source timestamps. Keeps the
* newest `keepBackups` and drops the rest; never fails the deploy, which has
* already succeeded by this point.
*/
function pruneRemoteBackups() {
if (deployConfig.keepBackups < 1) {
console.log("\nBackup pruning disabled (DEPLOY_KEEP_BACKUPS < 1).");
return;
}
const backupGlob = `${quoteForShell(deployConfig.remoteDir)}.backup-*`;
const stale = `ls -1d ${backupGlob} 2>/dev/null | sort -r | tail -n +${deployConfig.keepBackups + 1}`;
run("ssh", [
...sshArgs,
remoteTarget,
[
"set -u",
`stale=$(${stale})`,
// Scoped strictly to the .backup-* glob above; an empty list is a no-op.
`if [ -n "$stale" ]; then printf '%s\\n' "$stale" | while IFS= read -r dir; do rm -rf -- "$dir" && printf 'Pruned backup: %s\\n' "$dir"; done; fi`,
`printf 'Backups kept: %s\\n' "$(ls -1d ${backupGlob} 2>/dev/null | wc -l)"`,
].join("; "),
]);
}
function parsePositiveInt(value: string | undefined, fallback: number) {
if (!value) return fallback;
const parsed = Number.parseInt(value, 10);
return Number.isNaN(parsed) ? fallback : parsed;
}
function run(command: string, commandArgs: string[], captureOutput = false) {
const printableArgs = commandArgs.map((arg) =>
/\s/.test(arg) ? quoteForShell(arg) : arg
);
console.log(`\n$ ${command} ${printableArgs.join(" ")}`);
const result = spawnSync(command, commandArgs, {
cwd: rootDir,
encoding: "utf8",
stdio: captureOutput ? ["inherit", "pipe", "pipe"] : "inherit",
});
if (result.status !== 0) {
if (captureOutput) {
if (result.stdout) process.stdout.write(result.stdout);
if (result.stderr) process.stderr.write(result.stderr);
}
process.exit(result.status ?? 1);
}
return captureOutput ? result.stdout : "";
}
function verifyHttp(siteUrl: string) {
const indexHtml = run(
"curl",
["-fsSL", "-H", "Cache-Control: no-cache", siteUrl],
true
);
const robotsTxt = run("curl", ["-fsSL", `${siteUrl}/robots.txt`], true);
const sitemapXml = run("curl", ["-fsSL", `${siteUrl}/sitemap.xml`], true);
assertIncludes(indexHtml, "<div id=\"root\"></div>", "homepage root");
assertIncludes(robotsTxt, "Sitemap:", "robots sitemap declaration");
assertIncludes(sitemapXml, "<urlset", "sitemap urlset");
console.log("\nHTTP verification passed.");
}
function assertIncludes(contents: string, expected: string, label: string) {
if (!contents.includes(expected)) {
console.error(`Expected ${label} to include: ${expected}`);
process.exit(1);
}
}
function quoteForShell(value: string) {
return `'${value.replace(/'/g, `'\\''`)}'`;
}
function formatTimestamp(date: Date) {
const parts = [
date.getFullYear().toString(),
String(date.getMonth() + 1).padStart(2, "0"),
String(date.getDate()).padStart(2, "0"),
String(date.getHours()).padStart(2, "0"),
String(date.getMinutes()).padStart(2, "0"),
String(date.getSeconds()).padStart(2, "0"),
];
return `${parts[0]}${parts[1]}${parts[2]}-${parts[3]}${parts[4]}${parts[5]}`;
}