bruno/packages/bruno-lang/v2/src/envToJson.js

117 lines
2.3 KiB
JavaScript
Raw Normal View History

const ohm = require('ohm-js');
2023-02-05 14:36:48 +01:00
const _ = require('lodash');
const grammar = ohm.grammar(`Bru {
BruEnvFile = (vars)*
nl = "\\r"? "\\n"
st = " " | "\\t"
stnl = st | nl
2023-02-05 14:36:48 +01:00
tagend = nl "}"
optionalnl = ~tagend nl
keychar = ~(tagend | st | nl | ":") any
valuechar = ~(nl | tagend) any
2023-02-05 14:36:48 +01:00
// Dictionary Blocks
dictionary = st* "{" pairlist? tagend
pairlist = optionalnl* pair (~tagend stnl* pair)* (~tagend space)*
pair = st* key st* ":" st* value st*
key = keychar*
value = valuechar*
2023-02-05 14:36:48 +01:00
vars = "vars" dictionary
}`);
const mapPairListToKeyValPairs = (pairList = []) => {
if (!pairList.length) {
2023-02-05 14:36:48 +01:00
return [];
}
return _.map(pairList[0], (pair) => {
2023-02-05 14:36:48 +01:00
let name = _.keys(pair)[0];
let value = pair[name];
let enabled = true;
if (name && name.length && name.charAt(0) === '~') {
2023-02-05 14:36:48 +01:00
name = name.slice(1);
enabled = false;
}
return {
name,
value,
enabled
};
});
};
const concatArrays = (objValue, srcValue) => {
if (_.isArray(objValue) && _.isArray(srcValue)) {
return objValue.concat(srcValue);
}
};
const sem = grammar.createSemantics().addAttribute('ast', {
BruEnvFile(tags) {
if (!tags || !tags.ast || !tags.ast.length) {
return {
variables: []
};
2023-02-05 14:36:48 +01:00
}
return _.reduce(
tags.ast,
(result, item) => {
return _.mergeWith(result, item, concatArrays);
},
{}
);
2023-02-05 14:36:48 +01:00
},
dictionary(_1, _2, pairlist, _3) {
return pairlist.ast;
},
pairlist(_1, pair, _2, rest, _3) {
return [pair.ast, ...rest.ast];
},
pair(_1, key, _2, _3, _4, value, _5) {
let res = {};
res[key.ast] = value.ast ? value.ast.trim() : '';
2023-02-05 14:36:48 +01:00
return res;
},
key(chars) {
return chars.sourceString ? chars.sourceString.trim() : '';
},
value(chars) {
return chars.sourceString ? chars.sourceString.trim() : '';
},
nl(_1, _2) {
return '';
},
st(_) {
return '';
},
tagend(_1, _2) {
2023-02-05 14:36:48 +01:00
return '';
},
_iter(...elements) {
return elements.map((e) => e.ast);
2023-02-05 14:36:48 +01:00
},
vars(_1, dictionary) {
const vars = mapPairListToKeyValPairs(dictionary.ast);
return {
variables: vars
};
}
});
const parser = (input) => {
const match = grammar.match(input);
if (match.succeeded()) {
2023-02-05 14:36:48 +01:00
return sem(match).ast;
} else {
throw new Error(match.message);
}
};
2023-02-05 14:36:48 +01:00
module.exports = parser;