forked from colt-1/toml-editor
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
91 lines (75 loc) · 2.12 KB
/
index.js
File metadata and controls
91 lines (75 loc) · 2.12 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
const core = require("@actions/core");
const path = require("node:path");
const fs = require("node:fs");
const toml = require("@iarna/toml");
function run() {
try {
const fileName = core.getInput("file", { required: true });
const key = core.getInput("key", { required: true });
const value = core.getInput("value", { required: true });
const filePath = path.join(process.env.GITHUB_WORKSPACE, fileName);
let tomlContent = getTomlContent(filePath);
let tomlObj = parseTomlContent(tomlContent);
updateToml(tomlObj, key, value);
const parsed = toml.stringify(tomlObj);
writeTomlObj(tomlObj, filePath);
} catch (error) {
core.setFailed(error.message);
}
}
function updateToml(tomlObj, key, value) {
let keys = key.split(".");
if (keys.length == 1) {
tomlObj[keys[0]] = value;
return;
}
let targetTable = null;
for (let index = 0; index < keys.length - 1; index++) {
if (targetTable === null) {
targetTable = tomlObj[keys[index]];
} else if (targetTable[keys[index]] === undefined) {
let newTable = {};
targetTable[keys[index]] = newTable;
targetTable = newTable;
} else {
targetTable = targetTable[keys[index]];
}
}
targetTable[keys[keys.length - 1]] = value;
}
function getTomlValue(tomlObj, key) {
let keys = key.split(".");
let targetTable = null;
for (let index = 0; index < keys.length; index++) {
if (targetTable === null) {
targetTable = tomlObj[keys[index]];
} else {
targetTable = targetTable[keys[index]];
}
}
return targetTable;
}
function getTomlContent(filePath) {
if (!fs.existsSync(filePath)) {
throw new Error(`The toml file does not exist: ${filePath}`);
}
return fs.readFileSync(filePath, "utf8");
}
function parseTomlContent(tomlContent) {
return toml.parse(tomlContent);
}
function stringifyToml(tomlObj) {
return toml.stringify(tomlObj);
}
function writeTomlObj(tomlObj, filePath) {
fs.writeFileSync(filePath, stringifyToml(tomlObj));
}
module.exports = {
updateToml,
getTomlValue,
getTomlContent,
parseTomlContent,
stringifyToml,
writeTomlObj,
};
run();