|
| 1 | +import { spawn } from '@homebridge/node-pty-prebuilt-multiarch'; |
| 2 | +import { diffChars } from 'diff'; |
| 3 | +import fs from 'node:fs/promises'; |
| 4 | +import os from 'node:os'; |
| 5 | +import path from 'node:path'; |
| 6 | +import { WebSocket } from 'ws'; |
| 7 | + |
| 8 | +import { ConnectOrchestrator } from '../../../orchestrators/connect.js'; |
| 9 | +import { Session, SocketServer } from '../../socket-server.js'; |
| 10 | +import { ConnectCommand, createCommandHandler } from '../create-command.js'; |
| 11 | + |
| 12 | +export function initHandler() { |
| 13 | + const spawnCommand = async (body: Record<string, unknown>, ws: WebSocket, session: Session) => { |
| 14 | + const tmpDir = await fs.mkdtemp(os.tmpdir()); |
| 15 | + const filePath = path.join(tmpDir, 'codify.jsonc'); |
| 16 | + await fs.writeFile(filePath, '[]'); |
| 17 | + session.additionalData.filePath = filePath; |
| 18 | + session.additionalData.existingFile = '[]'; |
| 19 | + |
| 20 | + return spawn('zsh', ['-c', `${ConnectOrchestrator.nodeBinary} ${ConnectOrchestrator.rootCommand} init -p ${filePath}`], { |
| 21 | + name: 'xterm-color', |
| 22 | + cols: 80, |
| 23 | + rows: 30, |
| 24 | + cwd: process.env.HOME, |
| 25 | + env: process.env |
| 26 | + }); |
| 27 | + } |
| 28 | + |
| 29 | + const onExit = async (exitCode: number, ws: WebSocket, session: Session) => { |
| 30 | + if (session.additionalData.filePath) { |
| 31 | + const updatedFile = await fs.readFile(session.additionalData.filePath as string, 'utf8') |
| 32 | + |
| 33 | + // Changes were found |
| 34 | + if (diffChars(updatedFile, session.additionalData.existingFile as string).length > 0) { |
| 35 | + console.log('Writing imported changes to Codify dashboard'); |
| 36 | + |
| 37 | + const ws = SocketServer.get().getMainConnection(session.clientId); |
| 38 | + if (!ws) { |
| 39 | + throw new Error(`Unable to find client for clientId ${session.clientId}`); |
| 40 | + } |
| 41 | + |
| 42 | + ws.send(JSON.stringify({ key: 'new_init', data: { |
| 43 | + updated: updatedFile, |
| 44 | + } })) |
| 45 | + } |
| 46 | + |
| 47 | + |
| 48 | + await fs.rm(session.additionalData.filePath as string, { recursive: true, force: true }); |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + return createCommandHandler({ |
| 53 | + name: ConnectCommand.IMPORT, |
| 54 | + spawnCommand, |
| 55 | + onExit |
| 56 | + }); |
| 57 | +} |
0 commit comments