forked from mingjun97/file-regex-replace
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
50 lines (46 loc) · 1.52 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
45
46
47
48
49
50
const core = require('@actions/core');
const fs = require('fs');
const path = require("path");
function walk_recursive(dir, exclude, callback) {
fs.readdir(dir, function(err, files) {
if (err) throw err;
files.forEach(function(file) {
var filepath = path.join(dir, file);
if (!exclude.test(filepath)) {
fs.stat(filepath, function(err,stats) {
if (stats.isDirectory()) {
walk_recursive(filepath, exclude, callback);
} else if (stats.isFile()) {
callback(filepath, stats);
}
});
}
});
});
}
try {
const regex = new RegExp(core.getInput('regex'), core.getInput('flags'));
const replacement = core.getInput('replacement');
const include = new RegExp(core.getInput('include'));
const exclude = new RegExp(core.getInput('exclude'));
const encoding = core.getInput('encoding');
const start_path = core.getInput('path');
walk_recursive(start_path, exclude, (file) => {
if (include.test(file)){
fs.readFile(file, encoding, function (err,data) {
if (err) {
return console.log(err);
}
var result = data.replace(regex, replacement);
if (data != result) {
console.log('Modifying ', file);
fs.writeFile(file, result, encoding, function (err) {
if (err) return core.setFailed(err);
});
}
});
}
})
} catch (error) {
core.setFailed(error.message);
}