forked from alexlafroscia/yaml-merge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
44 lines (36 loc) · 1.29 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
'use strict';
const readFileSync = require('fs').readFileSync;
const jsYaml = require('js-yaml');
const glob = require('glob');
const _ = require('lodash');
function readAsJSON(fileName) {
const fileBuffer = readFileSync(fileName);
const fileString = fileBuffer.toString();
return jsYaml.load(fileString);
}
/**
* Merges the given YAML file names into a single YAML document.
*
* @param {...string|object} from - The file paths to read from, followed optionally by an options object.
* @param {object} [options] - Options for merging behavior.
* @param {boolean} [options.overwriteArr=false] - Whether to overwrite arrays instead of concatenating them.
* @returns {string} The output YAML string.
*/
function yamlMerge(...from) {
const options = typeof from[from.length - 1] === 'object' ? from.pop() : {};
const files = from
.reduce((arr, el) => arr.concat(glob.sync(el)), [])
.map((path) => readAsJSON(path));
const outputJSON = _.mergeWith({}, ...files, (objValue, srcValue) => {
if (Array.isArray(objValue) && Array.isArray(srcValue)) {
if (options.overwriteArr) {
return srcValue;
}
return [...objValue, ...srcValue];
}
// handle it just like with _.merge
return undefined;
});
return jsYaml.dump(outputJSON);
}
module.exports = yamlMerge;