-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdeploy-zmk.js
490 lines (426 loc) · 14.4 KB
/
deploy-zmk.js
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
const fs = require('node:fs');
const path = require('node:path');
const https = require('node:https');
const readline = require('node:readline');
const os = require('node:os');
const { execFile } = require('node:child_process');
const { promisify } = require('node:util');
require('dotenv').config();
let ora;
(async () => {
ora = (await import('ora')).default;
})();
const GITHUB_ACTIONS_POLLING_INTERVAL = 10000; // ms
const FW_VOLUME_NAME = 'nicenano';
const args = process.argv.slice(2);
const WATCH_MODE = args.includes('--watch');
const sayIndex = args.findIndex(arg => arg.startsWith('--say'));
const SAY_MODE = sayIndex !== -1;
const SAY_VOICE = SAY_MODE && args[sayIndex].includes('=') ? args[sayIndex].split('=')[1] : null;
const TMP_DIR = path.join(__dirname, 'tmp');
// Ensure tmp directory exists
if (!fs.existsSync(TMP_DIR)) {
fs.mkdirSync(TMP_DIR);
}
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
// Platform-specific drive paths
const DRIVE_PATHS = {
linux: () => `/media/${process.env.USER}`,
darwin: () => '/Volumes'
};
const execFilePromise = promisify(execFile);
// Add constants for ANSI formatting
const ANSI = {
BOLD: '\x1b[1m',
DIM: '\x1b[2m',
GREEN: '\x1b[32m',
BLUE: '\x1b[94m', // Light blue
MAGENTA: '\x1b[95m', // Light magenta
RESET: '\x1b[0m'
};
function capitalizeFirstLetter(val) {
return String(val).charAt(0).toUpperCase() + String(val).slice(1);
}
function parseGitHubUrl(url) {
try {
const match = url.match(/github\.com\/([^\/]+)\/([^\/]+)/);
if (!match) {
throw new Error('Invalid GitHub URL format');
}
return {
owner: match[1],
repo: match[2].replace('.git', '')
};
} catch (error) {
throw new Error('Could not parse GitHub URL');
}
}
function getGitHubCredentials() {
const { GITHUB_REPO_URL, GITHUB_TOKEN } = process.env;
if (!GITHUB_REPO_URL) {
throw new Error('GITHUB_REPO_URL is not set in .env file');
}
if (!GITHUB_TOKEN) {
throw new Error('GITHUB_TOKEN is not set in .env file');
}
const { owner, repo } = parseGitHubUrl(GITHUB_REPO_URL);
return { owner, repo, token: GITHUB_TOKEN };
}
async function getWorkflowRun(runId, owner, repo, token) {
const options = {
hostname: 'api.github.com',
path: `/repos/${owner}/${repo}/actions/runs/${runId}`,
headers: {
'User-Agent': 'Node.js',
'Authorization': `Bearer ${token}`,
'Accept': 'application/vnd.github.v3+json'
}
};
return new Promise((resolve, reject) => {
https.get(options, (res) => {
let data = '';
res.on('data', (chunk) => data += chunk);
res.on('end', () => {
const run = JSON.parse(data);
resolve(run);
});
}).on('error', reject);
});
}
function formatCommitInfo(sha, branch, message) {
return `${ANSI.BOLD}${sha}${ANSI.RESET} (${ANSI.GREEN}${branch}${ANSI.RESET}) "${ANSI.DIM}${message}${ANSI.RESET}"`;
}
async function getLatestArtifact(owner, repo, token) {
const options = {
hostname: 'api.github.com',
path: `/repos/${owner}/${repo}/actions/artifacts`,
headers: {
'User-Agent': 'Node.js',
'Authorization': `Bearer ${token}`,
'Accept': 'application/vnd.github.v3+json'
}
};
return new Promise((resolve, reject) => {
https.get(options, (res) => {
let data = '';
res.on('data', (chunk) => data += chunk);
res.on('end', async () => {
const artifacts = JSON.parse(data);
if (artifacts.artifacts && artifacts.artifacts.length > 0) {
const artifact = artifacts.artifacts[0];
const run = await getWorkflowRun(artifact.workflow_run.id, owner, repo, token);
// Instead of rejecting, return null if workflow isn't complete
if (run.status !== 'completed' || run.conclusion !== 'success') {
resolve(null);
return;
}
resolve({
...artifact,
commit: {
sha: run.head_sha.slice(0, 7),
branch: run.head_branch,
message: run.head_commit.message
}
});
} else {
reject(new Error('No artifacts found'));
}
});
}).on('error', reject);
});
}
async function downloadArtifact(artifact, owner, repo, token) {
// First request to get the redirect URL
const options = {
hostname: 'api.github.com',
path: `/repos/${owner}/${repo}/actions/artifacts/${artifact.id}/zip`,
headers: {
'User-Agent': 'Node.js',
'Authorization': `Bearer ${token}`,
'Accept': 'application/vnd.github.v3+json'
}
};
return new Promise((resolve, reject) => {
https.get(options, (res) => {
if (res.statusCode === 302) {
// Follow the redirect
https.get(res.headers.location, (downloadRes) => {
const zipPath = path.join(TMP_DIR, 'firmware.zip');
const fileStream = fs.createWriteStream(zipPath);
downloadRes.pipe(fileStream);
fileStream.on('finish', () => resolve(zipPath));
fileStream.on('error', reject);
}).on('error', reject);
} else {
reject(new Error(`Failed to get download URL: ${res.statusCode}`));
}
}).on('error', reject);
});
}
function formatSide(side) {
return `${ANSI.BOLD}${side.toLowerCase() === 'left' ? ANSI.BLUE : ANSI.MAGENTA}${side}${ANSI.RESET}`;
}
async function waitForDrive(side, requireFresh = false) {
console.log('');
if (!ora) {
throw new Error('ora not initialized');
}
const spinner = ora({
text: `Waiting for bootloader volume, ${ANSI.BOLD}double-click the reset button on the ${formatSide(side)}${ANSI.BOLD} part of your keyboard...${ANSI.RESET}`,
spinner: 'dots'
});
try {
// If we're on macOS and say mode is enabled, use voice prompt
if (os.platform() === 'darwin' && SAY_MODE) {
const sayArgs = [`Uh-oh! Double-click the ${side} reset button`];
if (SAY_VOICE) {
sayArgs.unshift('-v', SAY_VOICE);
}
execFile('say', sayArgs);
}
// If we require a fresh mount, wait for drive to be absent first
if (requireFresh) {
while (true) {
const drive = await findMountedDrive();
if (!drive) {
break;
}
await new Promise(resolve => setTimeout(resolve, 1000));
}
}
spinner.start();
while (true) {
const drive = await findMountedDrive();
if (drive) {
spinner.stop();
console.log(`Found ${formatSide(side)} side keyboard at ${drive}`);
return drive;
}
// Wait 1 second before checking again
await new Promise(resolve => setTimeout(resolve, 1000));
}
} catch (error) {
spinner.stop();
throw error;
}
}
async function findMountedDrive() {
const platform = os.platform();
const drivePath = DRIVE_PATHS[platform];
if (!drivePath) {
throw new Error(`Unsupported platform: ${platform}`);
}
try {
const drives = fs.readdirSync(drivePath());
const niceBoot = drives.find(drive => drive.toLowerCase().includes(FW_VOLUME_NAME));
if (niceBoot) {
return path.join(drivePath(), niceBoot);
}
return null;
} catch (error) {
console.error(`Error accessing drives: ${error.message}`);
return null;
}
}
async function findFirmwareFile(side, directory) {
try {
const files = fs.readdirSync(directory);
const firmwareFile = files.find(file =>
file.toLowerCase().includes(side) && file.endsWith('.uf2')
);
if (!firmwareFile) {
throw new Error(`Could not find ${side} firmware file`);
}
return firmwareFile;
} catch (error) {
throw new Error(`Error finding ${side} firmware: ${error.message}`);
}
}
async function copyFirmware(side, drivePath) {
const firmwareFile = await findFirmwareFile(side, TMP_DIR);
const firmwarePath = path.join(TMP_DIR, firmwareFile);
const targetPath = path.join(drivePath, firmwareFile);
const attemptCopy = () => {
try {
fs.copyFileSync(firmwarePath, targetPath);
console.log(`${formatSide(capitalizeFirstLetter(side))} side firmware deployed!`);
return firmwareFile;
} catch (error) {
if (error.code === 'EIO') {
console.log(`${formatSide(capitalizeFirstLetter(side))} side firmware likely deployed successfully (drive disconnected during copy)`);
return firmwareFile;
}
throw error;
}
};
try {
return attemptCopy();
} catch (error) {
if (error.code === 'EACCES') {
console.log(`Permission denied, retrying ${formatSide(side)} side deployment...`);
// Small delay before retry
await new Promise(resolve => setTimeout(resolve, 1000));
return attemptCopy();
}
throw new Error(`Failed to copy firmware to ${formatSide(side)} side: ${error.message}`);
}
}
async function extractZip(zipPath, targetDir) {
try {
await execFilePromise('unzip', ['-o', zipPath, '-d', targetDir]);
} catch (error) {
throw new Error(`Failed to extract firmware: ${error.message}`);
}
}
async function deployFirmware(existingArtifact = null) {
try {
const { owner, repo, token } = getGitHubCredentials();
let artifact = existingArtifact;
if (!artifact) {
console.log('Fetching latest firmware artifact...');
artifact = await getLatestArtifact(owner, repo, token);
}
console.log(`Found firmware artifact from commit ${formatCommitInfo(artifact.commit.sha, artifact.commit.branch, artifact.commit.message)}`);
console.log('Downloading firmware...');
const zipPath = await downloadArtifact(artifact, owner, repo, token);
console.log('Extracting firmware...');
await extractZip(zipPath, TMP_DIR);
let leftFirmware, rightFirmware;
if (await findMountedDrive()) {
console.warn(`Found an already mounted drive - assuming this is the ${formatSide('left')} side`);
}
// Deploy left side (can be already mounted)
const leftDrive = await waitForDrive('left');
leftFirmware = await copyFirmware('left', leftDrive);
// Deploy right side (must be freshly mounted)
const rightDrive = await waitForDrive('right', true);
rightFirmware = await copyFirmware('right', rightDrive);
// Cleanup
fs.unlinkSync(zipPath);
fs.unlinkSync(path.join(TMP_DIR, leftFirmware));
fs.unlinkSync(path.join(TMP_DIR, rightFirmware));
console.log(`\n${ANSI.BOLD}${ANSI.GREEN}Deployment complete!${ANSI.RESET}`);
} catch (error) {
console.error('Error:', error.message);
} finally {
rl.close();
}
}
async function getLatestWorkflowRun(owner, repo, token) {
const options = {
hostname: 'api.github.com',
path: `/repos/${owner}/${repo}/actions/runs?status=in_progress`,
headers: {
'User-Agent': 'Node.js',
'Authorization': `Bearer ${token}`,
'Accept': 'application/vnd.github.v3+json'
}
};
return new Promise((resolve, reject) => {
https.get(options, (res) => {
let data = '';
res.on('data', (chunk) => data += chunk);
res.on('end', () => {
const response = JSON.parse(data);
if (response.workflow_runs && response.workflow_runs.length > 0) {
resolve(response.workflow_runs[0]);
} else {
resolve(null);
}
});
}).on('error', reject);
});
}
async function checkForNewFirmware(owner, repo, token, startTime, lastReportedWorkflowId) {
// First check if there's a build in progress
const runningWorkflow = await getLatestWorkflowRun(owner, repo, token);
if (runningWorkflow) {
const workflowStarted = new Date(runningWorkflow.created_at);
if (workflowStarted > startTime && runningWorkflow.id !== lastReportedWorkflowId) {
console.log(`Build in progress for commit ${formatCommitInfo(
runningWorkflow.head_sha.slice(0, 7),
runningWorkflow.head_branch,
runningWorkflow.head_commit.message
)}`);
return { type: 'in_progress', workflow: runningWorkflow };
}
}
try {
// Then check for completed artifacts
const artifact = await getLatestArtifact(owner, repo, token);
if (artifact) {
const artifactCreated = new Date(artifact.created_at);
if (artifactCreated > startTime) {
return { type: 'completed', artifact };
}
}
} catch (error) {
// Don't throw for incomplete builds, just return in_progress state
if (runningWorkflow) {
return { type: 'in_progress', workflow: runningWorkflow };
}
throw error; // Throw other errors
}
return null;
}
function formatGitHubUrl(owner, repo) {
return `${ANSI.DIM}https://github.com/${owner}/${repo}${ANSI.RESET}`;
}
async function watchAndDeploy() {
try {
const { owner, repo, token } = getGitHubCredentials();
let lastArtifactId = null;
let lastReportedWorkflowId = null;
let lastReportedIncomplete = false;
let isBusy = false;
const startTime = new Date();
console.log(`Watching for new firmware builds from ${formatGitHubUrl(owner, repo)}...`);
const checkForUpdates = async () => {
if (isBusy) return;
try {
const result = await checkForNewFirmware(owner, repo, token, startTime, lastReportedWorkflowId);
if (result) {
if (result.type === 'in_progress') {
if (!lastReportedIncomplete) {
console.log('Not all artifacts are ready yet, waiting...');
lastReportedIncomplete = true;
}
lastReportedWorkflowId = result.workflow.id;
} else if (result.type === 'completed' && lastArtifactId !== result.artifact.id) {
lastReportedIncomplete = false;
lastArtifactId = result.artifact.id;
isBusy = true;
await deployFirmware(result.artifact);
isBusy = false;
console.log(`\nWatching for new firmware builds from ${formatGitHubUrl(owner, repo)}...`);
}
}
} catch (error) {
console.error('Error checking for updates:', error.message);
}
};
// Run check immediately
await checkForUpdates();
// Then run on timer
const interval = setInterval(checkForUpdates, GITHUB_ACTIONS_POLLING_INTERVAL);
// Handle graceful shutdown
process.on('SIGINT', () => {
clearInterval(interval);
rl.close();
console.log('\nStopped watching for firmware builds');
process.exit(0);
});
} catch (error) {
console.error('Error:', error.message);
rl.close();
}
}
// Choose mode based on flag
if (WATCH_MODE) {
watchAndDeploy();
} else {
deployFirmware();
}