poad 2.47.0 → 2.48.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/global/cli.js +2 -0
- package/global/create.js +4 -4
- package/global/init.js +2 -0
- package/global/ls.js +2 -0
- package/global/projects.js +122 -0
- package/global/start.js +2 -0
- package/package.json +1 -1
- package/project/upgrade.js +1 -0
- package/test/projects.test.js +167 -0
- package/utils/banner.js +1 -0
- package/utils/engine.js +1 -0
- package/utils/help-details.js +14 -0
- package/utils/projects.js +332 -0
package/global/cli.js
CHANGED
|
@@ -22,4 +22,6 @@ module.exports = {
|
|
|
22
22
|
models: 'Model catalog (poadio/permalink, cached): default model, prices and status per provider: ai models [provider] [--refresh]',
|
|
23
23
|
},
|
|
24
24
|
clean: 'Remove what stopped poad projects left on this machine: orphan services, networks, unused engine images',
|
|
25
|
+
projects: 'The poad projects of this machine (folder, state, engine, console URL), from ~/.poad/projects.json and Docker',
|
|
26
|
+
ls: 'Same as poad projects',
|
|
25
27
|
};
|
package/global/create.js
CHANGED
|
@@ -281,11 +281,11 @@ async function makeApp(appDir, tpl, { name, title, app, pm, workspace, exclude,
|
|
|
281
281
|
}
|
|
282
282
|
|
|
283
283
|
/** poad init dans dir (le dépôt git est fait plus tard, sans question sur les services) */
|
|
284
|
-
async function poadInit(dir) {
|
|
284
|
+
async function poadInit(dir, template) {
|
|
285
285
|
const cwd = process.cwd();
|
|
286
286
|
try {
|
|
287
287
|
process.chdir(dir);
|
|
288
|
-
return await require('./init')({}, [], { git: false, setup: false });
|
|
288
|
+
return await require('./init')({}, [], { git: false, setup: false, template });
|
|
289
289
|
} finally {
|
|
290
290
|
process.chdir(cwd);
|
|
291
291
|
}
|
|
@@ -422,7 +422,7 @@ async function create(opts, { intro } = {}) {
|
|
|
422
422
|
try {
|
|
423
423
|
if (mode === 'new') {
|
|
424
424
|
fs.mkdirSync(root, { recursive: true });
|
|
425
|
-
await poadInit(root);
|
|
425
|
+
await poadInit(root, template && template.value);
|
|
426
426
|
const tplPm = typeof tpl.pkg.packageManager === 'string' && tpl.pkg.packageManager.startsWith(`${pm}@`) ? tpl.pkg.packageManager : undefined;
|
|
427
427
|
ws.writeJson(path.join(root, 'package.json'), ws.rootPackageJson(starter.packageName(path.basename(root)), [app], tplPm));
|
|
428
428
|
ws.writeStartScript(root);
|
|
@@ -431,7 +431,7 @@ async function create(opts, { intro } = {}) {
|
|
|
431
431
|
dev = await makeApp(appDir, tpl, { name: app, title: path.basename(root), app, pm, workspace, exclude: ws.usedPorts(root) });
|
|
432
432
|
} else if (mode === 'flat') {
|
|
433
433
|
dev = await makeApp(appDir, tpl, { name: starter.packageName(path.basename(root)), title: path.basename(root), app, pm, workspace: false, exclude: new Set(), keepPoad: true });
|
|
434
|
-
await poadInit(root);
|
|
434
|
+
await poadInit(root, template && template.value);
|
|
435
435
|
} else {
|
|
436
436
|
const rootPkg = ws.readJson(path.join(root, 'package.json'));
|
|
437
437
|
workspace = Boolean(ws.workspacesOf(rootPkg)) && appDir !== root;
|
package/global/init.js
CHANGED
|
@@ -47,6 +47,8 @@ module.exports = async (args = {}, raw, options = {}) => {
|
|
|
47
47
|
};
|
|
48
48
|
fs.writeFileSync(root, json2toml(config));
|
|
49
49
|
writeSecrets(root, generateSecrets());
|
|
50
|
+
// Registre des projets de la machine (~/.poad/projects.json, sans secret)
|
|
51
|
+
require('../utils/projects').record(root, { template: options.template });
|
|
50
52
|
ensureGitignore(root);
|
|
51
53
|
fs.mkdirSync(migrations.dir(root), { recursive: true });
|
|
52
54
|
fs.writeFileSync(path.join(migrations.dir(root), '.gitkeep'), '');
|
package/global/ls.js
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
// poad projects (ou poad ls) les projets poad de cette machine, d'après le
|
|
2
|
+
// registre ~/.poad/projects.json (tenu par poad
|
|
3
|
+
// init, create, start, upgrade) et l'état Docker
|
|
4
|
+
// (un seul « docker ps -a »)
|
|
5
|
+
// --json sortie JSON (pour un script)
|
|
6
|
+
// --all avec les projets dont le dossier n'existe plus
|
|
7
|
+
// --prune retire du registre les projets dont le dossier n'existe plus
|
|
8
|
+
// (liste d'abord ; question, sauf --yes)
|
|
9
|
+
// --scan retrouve les projets d'après les conteneurs Docker (lecture
|
|
10
|
+
// seule) et le dossier courant ; fait d'office au premier appel
|
|
11
|
+
//
|
|
12
|
+
// Rien n'est démarré, arrêté ni supprimé : seul le registre change (--scan,
|
|
13
|
+
// --prune). Aucun secret n'est lu ni affiché.
|
|
14
|
+
module.exports = async (args = {}) => {
|
|
15
|
+
const chalk = require('chalk-v2');
|
|
16
|
+
const os = require('os');
|
|
17
|
+
const reg = require('../utils/projects');
|
|
18
|
+
const { findPoadDir } = require('../utils/findpoad');
|
|
19
|
+
const flag = (f) => Boolean(args[f] || args[`--${f}`]);
|
|
20
|
+
const json = flag('json');
|
|
21
|
+
const yes = flag('yes') || Boolean(args['-y']);
|
|
22
|
+
|
|
23
|
+
const cwdRoot = findPoadDir(process.cwd());
|
|
24
|
+
// Le projet du dossier courant est toujours inscrit
|
|
25
|
+
if (cwdRoot) reg.record(cwdRoot);
|
|
26
|
+
|
|
27
|
+
let scanned = null;
|
|
28
|
+
const { exists, corrupt } = reg.read();
|
|
29
|
+
if (flag('scan') || !exists || corrupt) {
|
|
30
|
+
try {
|
|
31
|
+
scanned = await reg.scan({ cwdRoot });
|
|
32
|
+
} catch (e) {
|
|
33
|
+
if (!json) console.log(chalk.yellowBright(` Scan failed: ${e.message}`));
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
if (corrupt && !json) console.log(chalk.yellowBright(` The registry could not be read: kept aside as ${corrupt}, rebuilt from Docker.`));
|
|
37
|
+
|
|
38
|
+
const ps = await reg.docker(['ps', '-a', '--format', '{{json .}}']);
|
|
39
|
+
const containers = ps === null ? null : reg.parsePs(ps);
|
|
40
|
+
const { data } = reg.read();
|
|
41
|
+
|
|
42
|
+
if (flag('prune')) {
|
|
43
|
+
const gone = reg.rows(data, containers, { all: true }).filter((r) => r.missing);
|
|
44
|
+
if (!gone.length) return json ? console.log(JSON.stringify({ removed: [] })) : console.log(chalk.grey('\n No project with a missing folder: nothing to prune.'));
|
|
45
|
+
if (!json) {
|
|
46
|
+
console.log(chalk.bold('\n Projects whose folder no longer exists'));
|
|
47
|
+
for (const r of gone) console.log(` ${chalk.white(r.name)} ${chalk.grey(r.id)} ${chalk.grey(tilde(r.path))}`);
|
|
48
|
+
console.log(chalk.grey(' Only their line in ~/.poad/projects.json is removed (containers and images: poad clean).'));
|
|
49
|
+
}
|
|
50
|
+
let go = yes;
|
|
51
|
+
if (!go && process.stdin.isTTY && process.stdout.isTTY && !json) {
|
|
52
|
+
const { confirm } = require('@inquirer/prompts');
|
|
53
|
+
go = await confirm({ message: `Remove ${gone.length} entr${gone.length > 1 ? 'ies' : 'y'} from the registry?`, default: true }).catch(() => false);
|
|
54
|
+
}
|
|
55
|
+
if (!go) {
|
|
56
|
+
if (!json) console.log(chalk.grey(' Nothing removed (add --yes outside a terminal).'));
|
|
57
|
+
else console.log(JSON.stringify({ removed: [], reason: 'confirmation required (--yes)' }));
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
const n = reg.remove(gone.map((r) => r.id));
|
|
61
|
+
return json ? console.log(JSON.stringify({ removed: gone.map((r) => r.id) })) : console.log(chalk.green(` ${n} entr${n > 1 ? 'ies' : 'y'} removed.`));
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const list = reg.rows(data, containers, { all: flag('all') });
|
|
65
|
+
const hidden = reg.rows(data, containers, { all: true }).length - list.length;
|
|
66
|
+
|
|
67
|
+
if (json) {
|
|
68
|
+
console.log(JSON.stringify(list.map(({ id, name, path, state, engine, port, template, created_at, last_used_at }) => ({ id, name, path, state, engine, api: port ? `http://localhost:${port}` : null, console: port ? `http://localhost:${port}/console` : null, template, created_at, last_used_at })), null, 2));
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
console.log(' ');
|
|
73
|
+
console.log(chalk.bold(` POAD projects on this machine`) + chalk.grey(` (${list.length}${hidden ? `, ${hidden} with a missing folder: --all` : ''})`));
|
|
74
|
+
if (scanned && scanned.added) console.log(chalk.grey(` ${scanned.added} found from Docker and added to the registry.`));
|
|
75
|
+
if (containers === null) console.log(chalk.yellowBright(' Docker is not reachable: state unknown.'));
|
|
76
|
+
console.log(' ');
|
|
77
|
+
if (!list.length) {
|
|
78
|
+
console.log(chalk.grey(' None yet. poad init or poad create records a project here; poad projects --scan looks for existing ones in Docker.'));
|
|
79
|
+
console.log(' ');
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const STATE = {
|
|
84
|
+
running: chalk.green('● running'),
|
|
85
|
+
stopped: chalk.grey('○ stopped'),
|
|
86
|
+
none: chalk.grey('○ not started'),
|
|
87
|
+
unknown: chalk.grey('? unknown'),
|
|
88
|
+
missing: chalk.red('✕ folder gone'),
|
|
89
|
+
};
|
|
90
|
+
const cols = [
|
|
91
|
+
{ h: 'NAME', v: (r) => r.name, s: chalk.bold.white },
|
|
92
|
+
{ h: 'STATE', v: (r) => STATE[r.state] || r.state },
|
|
93
|
+
{ h: 'ENGINE', v: (r) => r.engine || '–', s: chalk.white },
|
|
94
|
+
{ h: 'CONSOLE', v: (r) => (r.port ? `http://localhost:${r.port}/console` : '–'), s: (t) => (t === '–' ? chalk.grey(t) : chalk.cyanBright(t)) },
|
|
95
|
+
{ h: 'LAST USED', v: (r) => ago(r.last_used_at || r.created_at), s: chalk.grey },
|
|
96
|
+
{ h: 'PATH', v: (r) => tilde(r.path), s: chalk.grey },
|
|
97
|
+
];
|
|
98
|
+
const { visible } = require('../utils/layout');
|
|
99
|
+
const cells = list.map((r) => cols.map((c) => String(c.v(r))));
|
|
100
|
+
const width = cols.map((c, i) => Math.max(visible(c.h), ...cells.map((row) => visible(row[i]))));
|
|
101
|
+
const pad = (t, w) => t + ' '.repeat(Math.max(0, w - visible(t)));
|
|
102
|
+
console.log(' ' + cols.map((c, i) => chalk.grey(pad(c.h, width[i]))).join(' '));
|
|
103
|
+
cells.forEach((row) => console.log(' ' + row.map((t, i) => pad(cols[i].s ? cols[i].s(t) : t, width[i])).join(' ')));
|
|
104
|
+
console.log(' ');
|
|
105
|
+
console.log(chalk.grey(' cd <path> && poad start · poad projects --json · --scan to find older projects · --prune to forget deleted ones'));
|
|
106
|
+
console.log(' ');
|
|
107
|
+
|
|
108
|
+
function tilde(p) {
|
|
109
|
+
const home = os.homedir();
|
|
110
|
+
return p === home || p.startsWith(home + '/') ? '~' + p.slice(home.length) : p;
|
|
111
|
+
}
|
|
112
|
+
function ago(iso) {
|
|
113
|
+
const t = Date.parse(iso || '');
|
|
114
|
+
if (!t) return '–';
|
|
115
|
+
const s = Math.max(0, (Date.now() - t) / 1000);
|
|
116
|
+
if (s < 90) return 'just now';
|
|
117
|
+
if (s < 5400) return `${Math.round(s / 60)} min ago`;
|
|
118
|
+
if (s < 129600) return `${Math.round(s / 3600)} h ago`;
|
|
119
|
+
if (s < 60 * 86400) return `${Math.round(s / 86400)} d ago`;
|
|
120
|
+
return new Date(t).toISOString().slice(0, 10);
|
|
121
|
+
}
|
|
122
|
+
};
|
package/global/start.js
CHANGED
|
@@ -30,6 +30,8 @@ module.exports = async (args = {}) => {
|
|
|
30
30
|
if (!root) return console.log(chalk.redBright('You are not in a poad project directory.'));
|
|
31
31
|
const config = require('../utils/config').readConfig(root);
|
|
32
32
|
const containerName = config.project_uuid;
|
|
33
|
+
// Registre des projets de la machine : dernière utilisation (inscrit s'il n'y était pas)
|
|
34
|
+
require('../utils/projects').record(root, { used: true });
|
|
33
35
|
console.log(' ');
|
|
34
36
|
const { wantsAll, SERVICES, autostartServices } = require('../utils/services');
|
|
35
37
|
const all = wantsAll(args);
|
package/package.json
CHANGED
package/project/upgrade.js
CHANGED
|
@@ -91,6 +91,7 @@ module.exports = async (args = {}) => {
|
|
|
91
91
|
progress = ora('Restoring the backup').start();
|
|
92
92
|
await backup.restore(docker, root, image, chosen);
|
|
93
93
|
progress.succeed(chalk.bold(`Restored ${chosen.file} (engine ${chosen.engine}).`));
|
|
94
|
+
require('../utils/projects').record(root);
|
|
94
95
|
} catch (err) {
|
|
95
96
|
const msg = chalk.redBright(`Restore failed: ${err.message}. Nothing restarted.`);
|
|
96
97
|
if (progress) progress.fail(msg);
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
const test = require('node:test');
|
|
2
|
+
const assert = require('node:assert');
|
|
3
|
+
const fs = require('fs');
|
|
4
|
+
const os = require('os');
|
|
5
|
+
const path = require('path');
|
|
6
|
+
const reg = require('../utils/projects');
|
|
7
|
+
|
|
8
|
+
const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), 'poad-reg-'));
|
|
9
|
+
|
|
10
|
+
/** Un projet poad minimal : <dir>/poad/config.toml, sans secret */
|
|
11
|
+
function project(base, name, uuid, engine = '0.38.0', port = 57111) {
|
|
12
|
+
const dir = path.join(base, name);
|
|
13
|
+
fs.mkdirSync(path.join(dir, 'poad', 'data'), { recursive: true });
|
|
14
|
+
fs.writeFileSync(path.join(dir, 'poad', 'config.toml'), `project_id = "${name}"\nproject_uuid = "${uuid}"\nengine = "${engine}"\n[web]\nport = ${port}\n`);
|
|
15
|
+
return path.join(dir, 'poad', 'config.toml');
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
test('record writes a 0600 file in a 0700 folder, with no secret', () => {
|
|
19
|
+
const home = tmp();
|
|
20
|
+
const root = project(home, 'alpha', 'a1b2c3d4e5f6g7h8i9j0');
|
|
21
|
+
fs.writeFileSync(path.join(path.dirname(root), 'secrets.toml'), '[auth]\nsecret = "TOPSECRET"\n');
|
|
22
|
+
const e = reg.record(root, { home, template: 'next' });
|
|
23
|
+
assert.equal(e.id, 'a1b2c3d4e5f6g7h8i9j0');
|
|
24
|
+
assert.equal(e.name, 'alpha');
|
|
25
|
+
assert.equal(e.engine, '0.38.0');
|
|
26
|
+
assert.equal(e.template, 'next');
|
|
27
|
+
assert.equal(e.path, path.join(home, 'alpha'));
|
|
28
|
+
const f = reg.file(home);
|
|
29
|
+
assert.equal(fs.statSync(f).mode & 0o777, 0o600);
|
|
30
|
+
assert.equal(fs.statSync(reg.dir(home)).mode & 0o777, 0o700);
|
|
31
|
+
const text = fs.readFileSync(f, 'utf8');
|
|
32
|
+
assert.ok(!/TOPSECRET|secret|anon|service/i.test(text));
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
test('record keeps created_at and template, refreshes engine and last_used_at', async () => {
|
|
36
|
+
const home = tmp();
|
|
37
|
+
const root = project(home, 'beta', 'bbbbbbbbbbbbbbbbbbbb', '0.37.0');
|
|
38
|
+
const first = reg.record(root, { home, template: 'angular' });
|
|
39
|
+
await new Promise((r) => setTimeout(r, 5));
|
|
40
|
+
fs.writeFileSync(root, fs.readFileSync(root, 'utf8').replace('0.37.0', '0.39.0'));
|
|
41
|
+
const second = reg.record(root, { home, used: true });
|
|
42
|
+
assert.equal(second.created_at, first.created_at);
|
|
43
|
+
assert.equal(second.template, 'angular');
|
|
44
|
+
assert.equal(second.engine, '0.39.0');
|
|
45
|
+
assert.ok(second.last_used_at);
|
|
46
|
+
assert.equal(Object.keys(reg.read(home).data.projects).length, 1);
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
test('record never throws (no config, unreadable config)', () => {
|
|
50
|
+
const home = tmp();
|
|
51
|
+
assert.equal(reg.record(path.join(home, 'nope', 'poad', 'config.toml'), { home }), null);
|
|
52
|
+
const root = project(home, 'gamma', 'cccccccccccccccccccc');
|
|
53
|
+
fs.writeFileSync(root, 'not = [toml');
|
|
54
|
+
assert.equal(reg.record(root, { home }), null);
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
test('a corrupt registry is kept aside and rebuilt', () => {
|
|
58
|
+
const home = tmp();
|
|
59
|
+
fs.mkdirSync(reg.dir(home), { recursive: true });
|
|
60
|
+
fs.writeFileSync(reg.file(home), '{ broken');
|
|
61
|
+
const r = reg.read(home);
|
|
62
|
+
assert.ok(r.corrupt && fs.existsSync(r.corrupt));
|
|
63
|
+
assert.deepEqual(r.data.projects, {});
|
|
64
|
+
const root = project(home, 'delta', 'dddddddddddddddddddd');
|
|
65
|
+
assert.ok(reg.record(root, { home }));
|
|
66
|
+
assert.equal(Object.keys(reg.read(home).data.projects).length, 1);
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
test('unknown fields and invalid entries never enter the registry', () => {
|
|
70
|
+
const home = tmp();
|
|
71
|
+
fs.mkdirSync(reg.dir(home), { recursive: true });
|
|
72
|
+
fs.writeFileSync(
|
|
73
|
+
reg.file(home),
|
|
74
|
+
JSON.stringify({ version: 1, projects: { x: { id: 'okokokokokokokokokok', path: '/tmp/x', anon_key: 'eyJ', engine: 'latest; rm' }, y: { id: '../bad', path: '/tmp/y' }, z: { id: 'zzz', path: 'relative' } } }),
|
|
75
|
+
);
|
|
76
|
+
const { data } = reg.read(home);
|
|
77
|
+
assert.deepEqual(Object.keys(data.projects), ['okokokokokokokokokok']);
|
|
78
|
+
assert.equal(data.projects.okokokokokokokokokok.anon_key, undefined);
|
|
79
|
+
assert.equal(data.projects.okokokokokokokokokok.engine, null);
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
test('concurrent updates merge (lock): no entry lost', async () => {
|
|
83
|
+
const home = tmp();
|
|
84
|
+
const roots = Array.from({ length: 12 }, (_, i) => project(home, `p${i}`, `p${String(i).padStart(19, '0')}`));
|
|
85
|
+
// Processus séparés, lancés ensemble
|
|
86
|
+
const { spawn } = require('child_process');
|
|
87
|
+
const mod = require.resolve('../utils/projects');
|
|
88
|
+
await Promise.all(
|
|
89
|
+
roots.map(
|
|
90
|
+
(root) =>
|
|
91
|
+
new Promise((resolve, reject) => {
|
|
92
|
+
const p = spawn(process.execPath, ['-e', `require(${JSON.stringify(mod)}).record(${JSON.stringify(root)}, { home: ${JSON.stringify(home)} })`]);
|
|
93
|
+
p.on('exit', (c) => (c === 0 ? resolve() : reject(new Error('exit ' + c))));
|
|
94
|
+
}),
|
|
95
|
+
),
|
|
96
|
+
);
|
|
97
|
+
assert.equal(Object.keys(reg.read(home).data.projects).length, 12);
|
|
98
|
+
assert.ok(!fs.existsSync(reg.file(home) + '.lock'));
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
test('a stale lock is taken over', () => {
|
|
102
|
+
const home = tmp();
|
|
103
|
+
fs.mkdirSync(reg.file(home) + '.lock', { recursive: true });
|
|
104
|
+
const old = new Date(Date.now() - 60_000);
|
|
105
|
+
fs.utimesSync(reg.file(home) + '.lock', old, old);
|
|
106
|
+
assert.ok(reg.record(project(home, 'eps', 'eeeeeeeeeeeeeeeeeeee'), { home }));
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
test('remove (prune) drops only the given entries', () => {
|
|
110
|
+
const home = tmp();
|
|
111
|
+
reg.record(project(home, 'keep', 'kkkkkkkkkkkkkkkkkkkk'), { home });
|
|
112
|
+
reg.record(project(home, 'gone', 'gggggggggggggggggggg'), { home });
|
|
113
|
+
fs.rmSync(path.join(home, 'gone'), { recursive: true });
|
|
114
|
+
const { data } = reg.read(home);
|
|
115
|
+
const missing = reg.rows(data, [], { all: true }).filter((r) => r.missing);
|
|
116
|
+
assert.deepEqual(missing.map((r) => r.id), ['gggggggggggggggggggg']);
|
|
117
|
+
assert.equal(reg.rows(data, [], {}).length, 1);
|
|
118
|
+
assert.equal(reg.remove(missing.map((r) => r.id), home), 1);
|
|
119
|
+
assert.deepEqual(Object.keys(reg.read(home).data.projects), ['kkkkkkkkkkkkkkkkkkkk']);
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
test('docker ps parsing and project state', () => {
|
|
123
|
+
const ps = [
|
|
124
|
+
{ ID: '1', Names: 'aaaaaaaaaaaaaaaaaaaa', State: 'running', Image: 'poadio/engine:0.38.0', Ports: '127.0.0.1:57111->8000/tcp' },
|
|
125
|
+
{ ID: '2', Names: 'aaaaaaaaaaaaaaaaaaaa-mail', State: 'running', Image: 'axllent/mailpit', Ports: '' },
|
|
126
|
+
{ ID: '3', Names: 'bbbbbbbbbbbbbbbbbbbb', State: 'exited', Image: 'poadio/engine:0.37.0', Ports: '' },
|
|
127
|
+
{ ID: '4', Names: 'cccccccccccccccccccc-valkey', State: 'running', Image: 'valkey', Ports: '' },
|
|
128
|
+
]
|
|
129
|
+
.map((j) => JSON.stringify(j))
|
|
130
|
+
.join('\n');
|
|
131
|
+
const c = reg.parsePs(ps + '\nnot json\n');
|
|
132
|
+
assert.equal(c.length, 4);
|
|
133
|
+
assert.equal(reg.stateOf('aaaaaaaaaaaaaaaaaaaa', c), 'running');
|
|
134
|
+
assert.equal(reg.stateOf('bbbbbbbbbbbbbbbbbbbb', c), 'stopped');
|
|
135
|
+
assert.equal(reg.stateOf('cccccccccccccccccccc', c), 'stopped'); // annexe seule, engine absent
|
|
136
|
+
assert.equal(reg.stateOf('dddddddddddddddddddd', c), 'none');
|
|
137
|
+
assert.deepEqual(reg.hostPorts(c[0].ports), [57111]);
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
test('docker inspect parsing finds the project folder, engine wins over side services', () => {
|
|
141
|
+
const inspect = [
|
|
142
|
+
{ Name: '/qcz7dr23bzu1538sm8qb-valkey', Created: '2026-11-20T10:00:00Z', Config: { Image: 'valkey/valkey:8' }, Mounts: [{ Source: '/Users/me/prj/shop/poad/data/valkey', Destination: '/data' }] },
|
|
143
|
+
{ Name: '/qcz7dr23bzu1538sm8qb', Created: '2026-11-19T10:00:00Z', Config: { Image: 'poadio/engine:0.32.0' }, Mounts: [{ Source: '/Users/me/prj/shop/poad/data', Destination: '/data' }, { Source: '/Users/me/prj/shop/poad/functions', Destination: '/functions' }] },
|
|
144
|
+
{ Name: '/8usd0lgz1ziyoci9enbk-mail', Config: { Image: 'axllent/mailpit' }, Mounts: [{ Source: '/Users/me/prj/blog/poad/data/mail', Destination: '/data' }] },
|
|
145
|
+
{ Name: '/unrelated', Config: { Image: 'nginx' }, Mounts: [{ Source: '/srv/www', Destination: '/usr/share/nginx' }] },
|
|
146
|
+
];
|
|
147
|
+
const found = reg.parseInspect(inspect).sort((a, b) => a.path.localeCompare(b.path));
|
|
148
|
+
assert.deepEqual(found, [
|
|
149
|
+
{ id: '8usd0lgz1ziyoci9enbk', path: '/Users/me/prj/blog', engine: null, created_at: null },
|
|
150
|
+
{ id: 'qcz7dr23bzu1538sm8qb', path: '/Users/me/prj/shop', engine: '0.32.0', created_at: '2026-11-20T10:00:00Z' },
|
|
151
|
+
]);
|
|
152
|
+
assert.deepEqual(reg.parseInspect('garbage'), []);
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
test('rows: running first, console port from config, missing hidden unless all', () => {
|
|
156
|
+
const home = tmp();
|
|
157
|
+
reg.record(project(home, 'run', 'rrrrrrrrrrrrrrrrrrrr', '0.38.0', 57200), { home });
|
|
158
|
+
reg.record(project(home, 'idle', 'iiiiiiiiiiiiiiiiiiii'), { home });
|
|
159
|
+
const containers = reg.parsePs(JSON.stringify({ ID: '1', Names: 'rrrrrrrrrrrrrrrrrrrr', State: 'running', Image: 'poadio/engine:0.38.0', Ports: '127.0.0.1:57200->8000/tcp' }));
|
|
160
|
+
const r = reg.rows(reg.read(home).data, containers);
|
|
161
|
+
assert.equal(r[0].name, 'run');
|
|
162
|
+
assert.equal(r[0].state, 'running');
|
|
163
|
+
assert.equal(r[0].port, 57200);
|
|
164
|
+
assert.equal(r[1].state, 'none');
|
|
165
|
+
assert.equal(r[1].port, null);
|
|
166
|
+
assert.equal(reg.rows(reg.read(home).data, null)[1].state, 'unknown');
|
|
167
|
+
});
|
package/utils/banner.js
CHANGED
|
@@ -19,6 +19,7 @@ const SHORT = {
|
|
|
19
19
|
stop: 'Stop the project',
|
|
20
20
|
run: 'Run an optional service (kc, valkey, runner)',
|
|
21
21
|
ai: 'AI providers: keys of this machine, use in a project',
|
|
22
|
+
projects: 'The poad projects of this machine (also: poad ls)',
|
|
22
23
|
clean: 'Remove what stopped projects left on this machine',
|
|
23
24
|
},
|
|
24
25
|
project: {
|
package/utils/engine.js
CHANGED
|
@@ -97,6 +97,7 @@ const writeEngine = (root, version) => {
|
|
|
97
97
|
const updated = text.replace(/^(\s*engine\s*=\s*)["'][^"']*["']/m, `$1"${version}"`);
|
|
98
98
|
if (updated === text) return false;
|
|
99
99
|
fs.writeFileSync(root, updated);
|
|
100
|
+
require('./projects').record(root);
|
|
100
101
|
return true;
|
|
101
102
|
};
|
|
102
103
|
|
package/utils/help-details.js
CHANGED
|
@@ -8,6 +8,20 @@
|
|
|
8
8
|
// notes paragraphes après les options
|
|
9
9
|
|
|
10
10
|
const sheets = {
|
|
11
|
+
projects: {
|
|
12
|
+
usage: ['poad projects [--json | --all | --scan | --prune [--yes]]', 'poad ls'],
|
|
13
|
+
text: [
|
|
14
|
+
'The poad projects of this machine: name, state (running, stopped, not started, folder gone), engine version, console URL when running, last use and folder. The list comes from ~/.poad/projects.json, kept by poad init, create, start and upgrade; the state comes from one "docker ps -a". Nothing is started, stopped or deleted.',
|
|
15
|
+
],
|
|
16
|
+
options: [
|
|
17
|
+
['--json', 'the list as JSON, for a script'],
|
|
18
|
+
['--all', 'also the projects whose folder no longer exists'],
|
|
19
|
+
['--scan', 'look for existing projects in Docker (read only) and in this folder, and add them; done once on the first call'],
|
|
20
|
+
['--prune', 'forget the projects whose folder no longer exists (their line only; containers and images: poad clean); asks first, --yes outside a terminal'],
|
|
21
|
+
],
|
|
22
|
+
notes: ['~/.poad/projects.json holds no secret (no key, password or token), is readable by you only (0600), and is never read by the engine.'],
|
|
23
|
+
},
|
|
24
|
+
ls: { usage: ['poad ls [--json | --all | --scan | --prune [--yes]]'], text: ['Same as poad projects.'] },
|
|
11
25
|
start: {
|
|
12
26
|
usage: ['poad start [--all | --bare | --quiet]'],
|
|
13
27
|
text: [
|
|
@@ -0,0 +1,332 @@
|
|
|
1
|
+
// Registre des projets poad de cette machine : ~/.poad/projects.json.
|
|
2
|
+
//
|
|
3
|
+
// Écrit par le CLI seulement (poad init, create, start, upgrade), jamais lu par
|
|
4
|
+
// l'engine. Aucun secret : identifiant, nom, chemin, dates, version d'engine,
|
|
5
|
+
// modèle. Fichier 0600 dans un dossier 0700, écrit par fichier temporaire puis
|
|
6
|
+
// renommage, sous un verrou (dossier .lock) pour que deux poad lancés en même
|
|
7
|
+
// temps ne perdent pas d'entrée. Un fichier illisible est mis de côté
|
|
8
|
+
// (projects.json.corrupt-<date>) et le registre repart de zéro, puis se
|
|
9
|
+
// reconstruit au fil des commandes ou par poad projects --scan.
|
|
10
|
+
//
|
|
11
|
+
// Une écriture du registre n'arrête jamais une commande : record() avale ses
|
|
12
|
+
// erreurs (le registre est une commodité, pas une source de vérité).
|
|
13
|
+
//
|
|
14
|
+
// Format :
|
|
15
|
+
// { "version": 1, "projects": { "<project_uuid>": { id, name, path, created_at,
|
|
16
|
+
// last_used_at, engine, template } } }
|
|
17
|
+
|
|
18
|
+
const fs = require('fs');
|
|
19
|
+
const os = require('os');
|
|
20
|
+
const path = require('path');
|
|
21
|
+
|
|
22
|
+
const VERSION = 1;
|
|
23
|
+
const LOCK_STALE_MS = 10_000;
|
|
24
|
+
const LOCK_WAIT_MS = 2_000;
|
|
25
|
+
|
|
26
|
+
const dir = (home = os.homedir()) => path.join(home, '.poad');
|
|
27
|
+
const file = (home) => path.join(dir(home), 'projects.json');
|
|
28
|
+
|
|
29
|
+
const ID_RE = /^[A-Za-z0-9_.-]{1,80}$/;
|
|
30
|
+
const VERSION_RE = /^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$/;
|
|
31
|
+
|
|
32
|
+
const empty = () => ({ version: VERSION, projects: {} });
|
|
33
|
+
|
|
34
|
+
/** Entrée nettoyée : seulement les champs connus, de types attendus (rien d'autre n'entre) */
|
|
35
|
+
function clean(e) {
|
|
36
|
+
if (!e || typeof e !== 'object' || !ID_RE.test(String(e.id || ''))) return null;
|
|
37
|
+
if (typeof e.path !== 'string' || !path.isAbsolute(e.path)) return null;
|
|
38
|
+
const str = (v, max = 200) => (typeof v === 'string' && v.length <= max ? v : null);
|
|
39
|
+
return {
|
|
40
|
+
id: e.id,
|
|
41
|
+
name: str(e.name) || path.basename(e.path),
|
|
42
|
+
path: e.path,
|
|
43
|
+
created_at: str(e.created_at, 40),
|
|
44
|
+
last_used_at: str(e.last_used_at, 40),
|
|
45
|
+
engine: typeof e.engine === 'string' && VERSION_RE.test(e.engine) ? e.engine : null,
|
|
46
|
+
template: str(e.template, 40),
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Lecture : { data, corrupt } ; un fichier absent donne un registre vide */
|
|
51
|
+
function read(home) {
|
|
52
|
+
const f = file(home);
|
|
53
|
+
let text;
|
|
54
|
+
try {
|
|
55
|
+
text = fs.readFileSync(f, 'utf8');
|
|
56
|
+
} catch (e) {
|
|
57
|
+
if (e.code === 'ENOENT') return { data: empty(), exists: false, corrupt: false };
|
|
58
|
+
throw e;
|
|
59
|
+
}
|
|
60
|
+
try {
|
|
61
|
+
const raw = JSON.parse(text);
|
|
62
|
+
if (!raw || typeof raw !== 'object' || typeof raw.projects !== 'object' || Array.isArray(raw.projects)) throw new Error('bad shape');
|
|
63
|
+
const data = empty();
|
|
64
|
+
for (const v of Object.values(raw.projects)) {
|
|
65
|
+
const c = clean(v);
|
|
66
|
+
if (c) data.projects[c.id] = c;
|
|
67
|
+
}
|
|
68
|
+
return { data, exists: true, corrupt: false };
|
|
69
|
+
} catch {
|
|
70
|
+
// Mis de côté, jamais effacé : on repart d'un registre vide
|
|
71
|
+
const aside = `${f}.corrupt-${new Date().toISOString().replace(/[:.]/g, '-')}`;
|
|
72
|
+
try {
|
|
73
|
+
fs.renameSync(f, aside);
|
|
74
|
+
} catch {}
|
|
75
|
+
return { data: empty(), exists: false, corrupt: aside };
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function ensureDir(home) {
|
|
80
|
+
const d = dir(home);
|
|
81
|
+
fs.mkdirSync(d, { recursive: true, mode: 0o700 });
|
|
82
|
+
try {
|
|
83
|
+
fs.chmodSync(d, 0o700);
|
|
84
|
+
} catch {}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function write(home, data) {
|
|
88
|
+
ensureDir(home);
|
|
89
|
+
const f = file(home);
|
|
90
|
+
const tmp = `${f}.${process.pid}.${Date.now()}.tmp`;
|
|
91
|
+
const sorted = { version: VERSION, projects: {} };
|
|
92
|
+
for (const k of Object.keys(data.projects).sort()) sorted.projects[k] = data.projects[k];
|
|
93
|
+
fs.writeFileSync(tmp, JSON.stringify(sorted, null, 2) + '\n', { mode: 0o600 });
|
|
94
|
+
fs.renameSync(tmp, f);
|
|
95
|
+
try {
|
|
96
|
+
fs.chmodSync(f, 0o600);
|
|
97
|
+
} catch {}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const sleep = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
101
|
+
|
|
102
|
+
/** Verrou par dossier (mkdir est atomique) ; un verrou de plus de 10 s est repris */
|
|
103
|
+
function lock(home) {
|
|
104
|
+
ensureDir(home);
|
|
105
|
+
const l = `${file(home)}.lock`;
|
|
106
|
+
const until = Date.now() + LOCK_WAIT_MS;
|
|
107
|
+
for (;;) {
|
|
108
|
+
try {
|
|
109
|
+
fs.mkdirSync(l);
|
|
110
|
+
return () => {
|
|
111
|
+
try {
|
|
112
|
+
fs.rmdirSync(l);
|
|
113
|
+
} catch {}
|
|
114
|
+
};
|
|
115
|
+
} catch (e) {
|
|
116
|
+
if (e.code !== 'EEXIST') throw e;
|
|
117
|
+
try {
|
|
118
|
+
if (Date.now() - fs.statSync(l).mtimeMs > LOCK_STALE_MS) {
|
|
119
|
+
fs.rmdirSync(l);
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
122
|
+
} catch {
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
if (Date.now() > until) throw new Error('projects registry is locked');
|
|
126
|
+
sleep(25);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Relit, applique mutate(data) sous le verrou, réécrit ; renvoie la valeur de mutate */
|
|
132
|
+
function update(mutate, home) {
|
|
133
|
+
const release = lock(home);
|
|
134
|
+
try {
|
|
135
|
+
const { data } = read(home);
|
|
136
|
+
const out = mutate(data);
|
|
137
|
+
write(home, data);
|
|
138
|
+
return out;
|
|
139
|
+
} finally {
|
|
140
|
+
release();
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Champs non secrets de poad/config.toml : { id, name, engine } ou null */
|
|
145
|
+
function projectInfo(root) {
|
|
146
|
+
try {
|
|
147
|
+
const toml = require('toml');
|
|
148
|
+
const c = toml.parse(fs.readFileSync(root, 'utf8'));
|
|
149
|
+
if (!ID_RE.test(String(c.project_uuid || ''))) return null;
|
|
150
|
+
return {
|
|
151
|
+
id: String(c.project_uuid),
|
|
152
|
+
name: typeof c.project_id === 'string' ? c.project_id : null,
|
|
153
|
+
engine: typeof c.engine === 'string' ? c.engine : null,
|
|
154
|
+
port: c.web && Number.isInteger(c.web.port) ? c.web.port : null,
|
|
155
|
+
};
|
|
156
|
+
} catch {
|
|
157
|
+
return null;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Dossier du projet (celui qui contient poad/) depuis poad/config.toml */
|
|
162
|
+
const projectPath = (root) => path.dirname(path.dirname(path.resolve(root)));
|
|
163
|
+
|
|
164
|
+
/** Ajoute ou rafraîchit l'entrée du projet ; created_at et template sont gardés */
|
|
165
|
+
function upsert(data, entry, now = new Date().toISOString()) {
|
|
166
|
+
const prev = data.projects[entry.id];
|
|
167
|
+
const next = clean({
|
|
168
|
+
...prev,
|
|
169
|
+
...Object.fromEntries(Object.entries(entry).filter(([, v]) => v !== undefined && v !== null)),
|
|
170
|
+
created_at: (prev && prev.created_at) || entry.created_at || now,
|
|
171
|
+
});
|
|
172
|
+
if (!next) return null;
|
|
173
|
+
data.projects[next.id] = next;
|
|
174
|
+
return next;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* poad init / create / start / upgrade : le projet de root est inscrit (ou mis
|
|
179
|
+
* à jour). opts : { template, used (dernière utilisation : start), home }.
|
|
180
|
+
* Ne lève jamais : renvoie l'entrée, ou null.
|
|
181
|
+
*/
|
|
182
|
+
function record(root, opts = {}) {
|
|
183
|
+
try {
|
|
184
|
+
if (process.env.POAD_NO_REGISTRY === '1') return null;
|
|
185
|
+
const info = projectInfo(root);
|
|
186
|
+
if (!info) return null;
|
|
187
|
+
const now = new Date().toISOString();
|
|
188
|
+
return update(
|
|
189
|
+
(data) =>
|
|
190
|
+
upsert(
|
|
191
|
+
data,
|
|
192
|
+
{ id: info.id, name: info.name, path: projectPath(root), engine: info.engine, template: opts.template, last_used_at: opts.used ? now : undefined },
|
|
193
|
+
now,
|
|
194
|
+
),
|
|
195
|
+
opts.home,
|
|
196
|
+
);
|
|
197
|
+
} catch {
|
|
198
|
+
return null;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** Retire des entrées par identifiant ; renvoie le nombre retiré */
|
|
203
|
+
function remove(ids, home) {
|
|
204
|
+
return update((data) => {
|
|
205
|
+
let n = 0;
|
|
206
|
+
for (const id of ids) if (data.projects[id]) (delete data.projects[id], n++);
|
|
207
|
+
return n;
|
|
208
|
+
}, home);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// --- Docker (lecture seule) ------------------------------------------------
|
|
212
|
+
|
|
213
|
+
const { execFile } = require('child_process');
|
|
214
|
+
|
|
215
|
+
function docker(args, { timeout = 5000 } = {}) {
|
|
216
|
+
return new Promise((resolve) => {
|
|
217
|
+
execFile('docker', args, { timeout, maxBuffer: 32 * 1024 * 1024 }, (err, stdout) => resolve(err ? null : stdout));
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** Sortie de « docker ps -a --format {{json .}} » -> [{ name, state, image, ports }] */
|
|
222
|
+
function parsePs(text) {
|
|
223
|
+
const out = [];
|
|
224
|
+
for (const line of String(text || '').split('\n')) {
|
|
225
|
+
if (!line.trim()) continue;
|
|
226
|
+
try {
|
|
227
|
+
const j = JSON.parse(line);
|
|
228
|
+
out.push({ id: j.ID, name: String(j.Names || '').split(',')[0], state: String(j.State || '').toLowerCase(), image: j.Image || '', ports: j.Ports || '' });
|
|
229
|
+
} catch {}
|
|
230
|
+
}
|
|
231
|
+
return out;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** Un conteneur appartient au projet id : « id » ou « id-<service> » */
|
|
235
|
+
const belongsTo = (name, id) => name === id || name.startsWith(id + '-');
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* État d'un projet d'après les conteneurs : running (l'engine tourne),
|
|
239
|
+
* stopped (conteneurs présents, engine arrêté), none (aucun conteneur).
|
|
240
|
+
*/
|
|
241
|
+
function stateOf(id, containers) {
|
|
242
|
+
const mine = containers.filter((c) => belongsTo(c.name, id));
|
|
243
|
+
if (!mine.length) return 'none';
|
|
244
|
+
const engine = mine.find((c) => c.name === id);
|
|
245
|
+
return engine && engine.state === 'running' ? 'running' : 'stopped';
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* Projets trouvés dans la sortie de « docker inspect » (tableau JSON) : un
|
|
250
|
+
* montage dont la source contient /poad/data donne le dossier du projet.
|
|
251
|
+
* -> [{ id, path, engine, created_at }]
|
|
252
|
+
*/
|
|
253
|
+
function parseInspect(list) {
|
|
254
|
+
const found = new Map();
|
|
255
|
+
for (const c of Array.isArray(list) ? list : []) {
|
|
256
|
+
const name = String(c.Name || '').replace(/^\//, '');
|
|
257
|
+
if (!name) continue;
|
|
258
|
+
const mount = (c.Mounts || []).find((m) => typeof m.Source === 'string' && /\/poad\/data(\/|$)/.test(m.Source));
|
|
259
|
+
if (!mount) continue;
|
|
260
|
+
const p = mount.Source.slice(0, mount.Source.search(/\/poad\/data(\/|$)/));
|
|
261
|
+
if (!p || !path.isAbsolute(p)) continue;
|
|
262
|
+
const image = (c.Config && c.Config.Image) || c.Image || '';
|
|
263
|
+
const m = /^(?:docker\.io\/)?poadio\/engine:([0-9][^@\s]*)$/.exec(image);
|
|
264
|
+
const prev = found.get(p);
|
|
265
|
+
// L'engine (nom sans suffixe) l'emporte sur les services annexes (<id>-valkey…)
|
|
266
|
+
const side = name.includes('-');
|
|
267
|
+
const keepPrev = prev && (!prev.side || side);
|
|
268
|
+
found.set(p, {
|
|
269
|
+
id: keepPrev ? prev.id : side ? name.split('-')[0] : name,
|
|
270
|
+
side: keepPrev ? prev.side : side,
|
|
271
|
+
path: p,
|
|
272
|
+
engine: (m && m[1]) || (prev && prev.engine) || null,
|
|
273
|
+
created_at: (prev && prev.created_at) || (typeof c.Created === 'string' ? c.Created : null),
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
return [...found.values()].map(({ side, ...e }) => e);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/**
|
|
280
|
+
* Reconstitue le registre depuis Docker (lecture seule : ps et inspect, rien
|
|
281
|
+
* n'est démarré ni arrêté) et depuis le dossier courant. Le config.toml d'un
|
|
282
|
+
* dossier trouvé fait foi pour l'identifiant et le nom. Renvoie { added, seen }.
|
|
283
|
+
*/
|
|
284
|
+
async function scan({ home, cwdRoot } = {}) {
|
|
285
|
+
const ids = await docker(['ps', '-aq']);
|
|
286
|
+
let fromDocker = [];
|
|
287
|
+
if (ids && ids.trim()) {
|
|
288
|
+
const raw = await docker(['inspect', ...ids.trim().split(/\s+/)], { timeout: 15000 });
|
|
289
|
+
try {
|
|
290
|
+
fromDocker = parseInspect(JSON.parse(raw || '[]'));
|
|
291
|
+
} catch {}
|
|
292
|
+
}
|
|
293
|
+
const candidates = fromDocker.map((d) => ({ ...d, root: path.join(d.path, 'poad', 'config.toml') }));
|
|
294
|
+
if (cwdRoot) candidates.push({ root: cwdRoot, path: projectPath(cwdRoot) });
|
|
295
|
+
return update((data) => {
|
|
296
|
+
let added = 0;
|
|
297
|
+
for (const c of candidates) {
|
|
298
|
+
const info = fs.existsSync(c.root) ? projectInfo(c.root) : null;
|
|
299
|
+
const id = (info && info.id) || c.id;
|
|
300
|
+
if (!id || !ID_RE.test(id)) continue;
|
|
301
|
+
const isNew = !data.projects[id];
|
|
302
|
+
const e = upsert(data, { id, name: (info && info.name) || undefined, path: c.path, engine: (info && info.engine) || c.engine || undefined, created_at: c.created_at || undefined });
|
|
303
|
+
if (e && isNew) added++;
|
|
304
|
+
}
|
|
305
|
+
return { added, seen: candidates.length };
|
|
306
|
+
}, home);
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/** Ports publiés d'un conteneur (« 127.0.0.1:57111->8000/tcp ») : ports de la machine */
|
|
310
|
+
const hostPorts = (ports) => [...String(ports || '').matchAll(/:(\d+)->/g)].map((m) => Number(m[1]));
|
|
311
|
+
|
|
312
|
+
/** Lignes du tableau de poad projects : entrées du registre + état Docker */
|
|
313
|
+
function rows(data, containers, { all = false } = {}) {
|
|
314
|
+
const list = Object.values(data.projects).map((e) => {
|
|
315
|
+
const missing = !fs.existsSync(path.join(e.path, 'poad', 'config.toml'));
|
|
316
|
+
const state = containers === null ? 'unknown' : stateOf(e.id, containers);
|
|
317
|
+
const info = missing ? null : projectInfo(path.join(e.path, 'poad', 'config.toml'));
|
|
318
|
+
const engine = (info && info.engine) || e.engine;
|
|
319
|
+
let port = null;
|
|
320
|
+
if (state === 'running') {
|
|
321
|
+
const c = containers.find((x) => x.name === e.id);
|
|
322
|
+
port = (info && info.port && hostPorts(c && c.ports).includes(info.port) ? info.port : null) || (info && info.port) || null;
|
|
323
|
+
}
|
|
324
|
+
return { ...e, name: (info && info.name) || e.name, engine, missing, state: missing ? 'missing' : state, port };
|
|
325
|
+
});
|
|
326
|
+
const order = { running: 0, stopped: 1, none: 2, unknown: 2, missing: 3 };
|
|
327
|
+
return list
|
|
328
|
+
.filter((r) => all || !r.missing)
|
|
329
|
+
.sort((a, b) => order[a.state] - order[b.state] || String(b.last_used_at || b.created_at || '').localeCompare(String(a.last_used_at || a.created_at || '')) || a.name.localeCompare(b.name));
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
module.exports = { dir, file, read, write, update, record, remove, upsert, clean, projectInfo, projectPath, parsePs, parseInspect, stateOf, belongsTo, scan, rows, docker, hostPorts };
|