This repository was archived by the owner on Dec 15, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathbase-cmd-abstract.ts
More file actions
365 lines (323 loc) · 8.76 KB
/
base-cmd-abstract.ts
File metadata and controls
365 lines (323 loc) · 8.76 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
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
import { Command, Config, ux } from '@oclif/core'
import {execSync, spawnSync} from 'node:child_process'
import fs from 'node:fs'
import fspath from "node:path";
import {AppSettings} from "../app-settings.js";
import CeDevControllerManager from '../controller-manager.js'
import CeDevConfig from '../interfaces/ce-dev-config-interface.js'
import ComposeConfig from '../interfaces/docker-compose-config-interface.js'
import UserConfig from '../interfaces/user-config-interface.js'
import YamlParser from '../yaml-parser.js'
export default abstract class BaseCmd extends Command {
/**
* @member
* Path to the active docker-compose.yml file.
*/
protected activeComposeFilePath = ''
/**
* @member
* Project info.
*/
protected activeProjectInfo: CeDevConfig = {
deploy: [],
project_name: 'ce-dev',
provision: [],
registry: 'codeenigma',
ssh_hosts: [],
unison: {},
urls: [],
version: AppSettings.ceDevVersion + '.x',
}
/**
* @member
* Path to the active ansible info file.
*/
protected activeProjectInfoFilePath = ''
/**
* @member
* Inner ce-dev dir.
*/
protected ceDevDir = ''
/**
* @member
* Docker executable path.
*/
protected dockerBin = 'docker'
/**
* @member
* Docker-compose executable path.
*/
protected dockerComposeBin = 'docker compose'
/**
* @member
* Docker repository to use.
*/
protected dockerRegistry = ''
/**
* @member
* MKCERT executable path.
*/
protected mkcertBin = 'mkcert'
/**
* @member
* Project root
*/
protected rootDir: string = process.cwd()
/**
* @member
* User preferences.
*/
protected UserConfig: UserConfig = {
docker_bin: this.config.platform === 'linux' ? 'sudo docker' : 'docker',
docker_compose_bin:
this.config.platform === 'linux' ?
'sudo docker compose' :
'docker compose',
mkcert_bin: 'mkcert',
ssh_key: (process.env.HOME as string) + '/.ssh/id_rsa',
ssh_user: process.env.USER as string,
}
/**
* @member
* Path to the user config file.
*/
protected userConfigFilePath = fspath.resolve(
this.config.configDir + '/preferences.yml',
)
/**
* @member
* Docker compose content.
*/
private readonly controllerManager: CeDevControllerManager
/**
* @member
* Development mode or not.
*/
protected developmentMode: boolean = false
/**
* @inheritdoc
*/
protected constructor(argv: string[], config: Config) {
super(argv, config)
const gitRoot = spawnSync('git', ['rev-parse', '--show-toplevel'])
.stdout.toString()
.trim()
if (fs.existsSync(gitRoot) && fs.lstatSync(gitRoot).isDirectory()) {
this.rootDir = gitRoot
}
const ceDevDir = this.rootDir + '/ce-dev'
if (fs.existsSync(ceDevDir) && fs.lstatSync(ceDevDir).isDirectory()) {
this.ceDevDir = ceDevDir
}
this.activeComposeFilePath = this.ceDevDir + '/docker-compose.yml'
// Create data dir if needed.
const config_path = fspath.resolve(this.config.dataDir + '/' + this.rootDir)
if (!fs.existsSync(config_path)) {
fs.mkdirSync(config_path, {recursive: true})
}
this.activeProjectInfoFilePath = fspath.resolve(
config_path + '/project.yml',
)
if (fs.existsSync(this.activeProjectInfoFilePath)) {
this.activeProjectInfo = this.parseYaml(this.activeProjectInfoFilePath) as CeDevConfig
}
if (fs.existsSync(this.userConfigFilePath)) {
this.UserConfig = this.parseYaml(this.userConfigFilePath) as UserConfig
}
if ((typeof process.env.NODE_ENV !== 'undefined') && (process.env.NODE_ENV === 'development')) {
this.developmentMode = true;
}
this.dockerBin = this.UserConfig.docker_bin
this.dockerComposeBin = this.UserConfig.docker_compose_bin
this.mkcertBin = this.UserConfig.mkcert_bin
this.dockerRegistry = this.activeProjectInfo.registry
this.controllerManager = new CeDevControllerManager(
this.config,
this.dockerBin,
this.dockerComposeBin,
this.mkcertBin,
)
this.ensureController()
}
/**
* Check that we have a generated compose file, or exit.
*
* @return void
*/
protected ensureActiveComposeFile(): void {
if (fs.existsSync(this.activeComposeFilePath) === false) {
this.error(
'No active docker-compose.yml file found. You must generate one first with `ce-dev init`.',
)
}
}
/**
* Create private network and starting controller container
*
* @return void
*/
protected ensureController(): void {
if (this.controllerManager.networkExists() === false) {
this.log('Creating private network...')
this.controllerManager.networkStart()
}
if (this.controllerManager.controllerExists() === false) {
this.log('Starting controller container...')
this.controllerManager.controllerStart()
}
}
/**
* Generate an SSL certificate.
*
* @param domain
* Domain/host name.
*
* @return void
*/
protected generateCertificate(domain: string): void {
this.controllerManager.generateCertificate(domain)
}
/**
* Try to "fix" relative paths based on git repo root.
*
* @param target
* Relative (or absolute) path to a file.
*
* @returns string
*/
protected getPathFromRelative(target: string): string {
const paths = [
target,
process.cwd() + '/' + target,
this.rootDir + '/' + target,
this.ceDevDir + '/' + target,
]
let exists = ''
for (const path of paths) {
const absolutePath = fspath.resolve(path.trim())
if (fs.existsSync(absolutePath)) {
exists = absolutePath
}
}
return exists
}
/**
* Gather project's containers that are actually running.
*
* @returns Array
*/
protected getProjectRunningContainers(): Array<string> {
const config: ComposeConfig = this.loadComposeConfig(
this.activeComposeFilePath,
)
const projectContainers: Array<string> = []
if (config.services) {
for (const service of Object.values(config.services)) {
projectContainers.push(service.container_name as string)
}
}
const running = execSync(this.dockerBin + ' ps --format={{.Names}}').toString()
const runningContainers = running.split('\n').filter(item => {
if (item.length === 0) {
return false
}
return projectContainers.includes(item)
})
return runningContainers
}
/**
* Gather project's containers that are build from ce-dev base image.
*
* @returns Array.
*/
protected getProjectRunningContainersCeDev(): Array<string> {
const running = this.getProjectRunningContainers();
const ceDev = [];
const regex = /ce-dev.*/;
for (const containerName of running) {
const image = execSync(this.dockerBin +
' inspect ' +
containerName +
' --format={{.Config.Image}}')
.toString()
.trim();
const labels = execSync(
this.dockerBin + ' inspect ' + image + ' --format={{.Config.Labels}}')
.toString()
.trim()
if (regex.test(labels)) {
ceDev.push(containerName);
}
}
return ceDev;
}
/**
* Get path relative to repo root.
* Note: no check of existence of passed path.
*
* @param target
* Absolute path to a file/dir.
*
* @returns string
*/
protected getRelativePath(target: string): string {
return fspath.relative(this.rootDir, target)
}
/**
* Installs CA for mkcerts on the host.
*
* @return void
*/
protected installCertificateAuth(): void {
this.controllerManager.installCertificateAuth()
}
/**
* Ensure compose config is valid.
*
* @param file
* Path to a file to parse.
*
* @return object
* Parsed docker compose declaration.
*/
protected loadComposeConfig(file: string): ComposeConfig {
// @todo Check config is valid.
const composeConfig = this.parseYaml(file) as ComposeConfig
return composeConfig
}
/**
* Parse a YAML file.
*
* @param file
* Path to a file to parse
*
* @returns Parsed YAML.
*/
protected parseYaml(file: string): unknown {
return YamlParser.parseYaml(file)
}
/**
* Pull controller latest|devel image.
*
* @return void
*/
protected pullControllerContainer(): void {
this.controllerManager.pullImage()
}
protected saveActiveProjectInfo(): void {
YamlParser.writeYaml(this.activeProjectInfoFilePath, this.activeProjectInfo)
}
protected saveUserConfig(): void {
YamlParser.writeYaml(this.userConfigFilePath, this.UserConfig, true)
}
/**
* Stop the global controller container.
*
* @return void
*/
protected stopControllerContainer(): void {
ux.action.start('Stopping controller container')
this.controllerManager.controllerStop()
ux.action.stop()
}
}