forked from rvolo/xml-replace-action
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
44 lines (39 loc) · 1.4 KB
/
index.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
import { getInput, setFailed } from '@actions/core';
import { select } from 'xpath';
import { DOMParser, XMLSerializer } from '@xmldom/xmldom';
import { readFileSync, writeFileSync } from 'fs';
try {
const filePath = getInput('filepath', {required: true});
const xpathString = getInput('xpath', {required: true});
const replaceString = getInput('replace');
const oldContent = readFileSync(filePath, 'utf8');
const newContent = replace(oldContent, xpathString, replaceString);
writeFileSync(filePath, newContent);
} catch (error) {
console.log(error)
setFailed(error.message);
}
function replace(content, xpathString, replaceString) {
const document = new DOMParser().parseFromString(content);
const nodes = select(xpathString, document);
if (nodes.length === 0) {
setFailed("No matching xml nodes found");
} else {
for (const node of nodes) {
console.log("Setting xml value at " + getNodePath(node));
if (replaceString === null) {
node.parentNode.removeChild(node);
} else {
node.textContent = replaceString;
}
}
return new XMLSerializer().serializeToString(document)
}
}
function getNodePath(node) {
let parentNode = node.parentNode;
if (parentNode == null) {
return node.nodeName;
}
return (getNodePath(parentNode)) + "/" + node.nodeName;
}