UNPKG

@cto.ai/ops

Version:

💻 CTO.ai Ops - The CLI built for Teams 🚀

94 lines (93 loc) 3.44 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const tslib_1 = require("tslib"); const sdk_1 = require("@cto.ai/sdk"); const debug_1 = tslib_1.__importDefault(require("debug")); const get_docker_1 = tslib_1.__importDefault(require("../utils/get-docker")); const debug = debug_1.default('ops:ContainerService'); class ContainerService { constructor() { this.log = console.log; this.create = async (op, options) => { const docker = await get_docker_1.default(console, 'ContainerService'); this.log(`⚙️ Running ${sdk_1.ux.colors.dim(op.name)}...`); try { this.container = await docker.createContainer(options); return this.container; } catch (err) { debug('%O', err); throw new Error('Error creating Docker container'); } }; this.start = async (stream) => { if (!this.container) throw new Error('No docker container to start up'); try { await this.container.start(); this.resize(); process.stdout.on('resize', this.resize); await this.container.wait(); this.handleExit(stream, false); } catch (err) { debug('%O', err); throw new Error(err); } }; this.handleStream = (stream) => { const CTRL_P = '\u0010'; const CTRL_Q = '\u0011'; let previousKey = ''; stream.pipe(process.stdout); const stdin = process.stdin; stdin.resume(); stdin.setEncoding('utf8'); stdin.setRawMode && stdin.setRawMode(true); stdin.pipe(stream); stdin.on('data', (key) => { // Detects it is detaching a running container if (previousKey === CTRL_P && key === CTRL_Q) { this.handleExit(stream, false); } previousKey = key; }); }; this.handleExit = (stream, isRaw) => { if (!this.container) throw new Error('No docker container for removal'); const stdout = process.stdout; const stdin = process.stdin; try { stdout.removeListener('resize', this.resize); stdin.removeAllListeners(); stdin.setRawMode && stdin.setRawMode(isRaw); stdin.resume(); stream.end(); this.container.remove(() => process.exit()); } catch (err) { debug('%O', err); throw new Error(err); } }; this.resize = () => { if (!this.container) throw new Error('No docker container for resize'); try { const dimensions = { h: process.stdout.rows, w: process.stderr.columns, }; if (dimensions.h !== 0 && dimensions.w !== 0) { this.container.resize(dimensions, () => { }); } } catch (err) { debug('%O', err); throw new Error(err); } }; } } exports.ContainerService = ContainerService;