forked from PRX/prx-podagent
-
Notifications
You must be signed in to change notification settings - Fork 1
/
lock.js
64 lines (57 loc) · 1.72 KB
/
lock.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
const fs = require('fs');
const yaml = require('js-yaml');
/**
* Normalize and lock agents database
*/
let agentsText = fs.readFileSync(`${__dirname}/db/agents.yml`, 'utf8');
let lockText = fs.readFileSync(`${__dirname}/db/agents.lock.yml`, 'utf8');
let agentsData = yaml.safeLoad(agentsText) || {};
let lockData = yaml.safeLoad(lockText) || {};
const TAG_NAMES = ['name', 'type', 'os'];
function invert(obj) {
let ret = {};
Object.keys(obj).forEach(k => ret[obj[k]] = k);
return ret;
}
console.log('reading existing lockfile...');
let tags = invert(lockData.tags || {}), nextId = 1;
Object.values(tags).forEach(id => {
if (+id >= nextId) {
nextId = +id + 1;
}
});
console.log(` got ${Object.keys(tags).length} tags`);
console.log(` next id: ${nextId}`);
console.log('reading current db...');
let changes = false;
TAG_NAMES.forEach(tag => {
(agentsData.agents || []).map(a => a[tag]).filter(v => v).forEach(val => {
if (!tags[val]) {
changes = true;
tags[val] = `${nextId++}`;
console.log(` +${tag}[${val}] -> ${tags[val]}`);
}
});
});
if (!changes) {
console.log(' no changes.');
}
console.log('writing new lockfile...');
let newLock = {};
newLock.agents = (agentsData.agents || []).map(agent => {
let data = {};
Object.keys(agent).forEach(key => {
if (TAG_NAMES.indexOf(key) === -1) {
data[key] = agent[key];
} else if (agent[key]) {
data[key] = tags[agent[key]];
}
});
return data;
});
newLock.tags = invert(tags);
console.log(` ${newLock.agents.length} agents`);
console.log(` ${Object.keys(newLock.tags).length} tags`);
let newText = yaml.safeDump(newLock, {lineWidth: 200});
fs.writeFileSync(`${__dirname}/db/agents.lock.yml`, newText);
console.log('done!');