1 let mocklib = global.mocklib;
3 let byte = (str, off) => {
5 return length(v) ? v[0] : v;
11 for (let i = 0; i < length(s); i++)
12 h = h * 31 + byte(s, i);
17 let id = (config, t, n) => {
19 let id = sprintf('cfg%08x', hash(t + n));
21 if (!exists(config, id))
28 let fixup_config = (config) => {
32 for (let stype in config) {
33 switch (type(config[stype])) {
35 config[stype] = [ config[stype] ];
39 for (let idx, sobj in config[stype]) {
42 if (exists(sobj, '.name') && !exists(rv, sobj['.name'])) {
47 sid = id(rv, stype, idx);
52 '.index': n_section++,
64 for (let n, sid in sort(keys(rv), (a, b) => rv[a]['.index'] - rv[b]['.index']))
65 rv[sid]['.index'] = n;
74 load: function(file) {
75 let basename = replace(file, /^.+\//, ''),
76 path = sprintf("uci/%s.json", basename),
77 mock = mocklib.read_json_file(path);
79 if (!mock || mock != mock) {
80 mocklib.I("No configuration fixture defined for uci package %s.", file);
81 mocklib.I("Provide a mock configuration through the following JSON file:\n%s\n", path);
86 this._configs[basename] = fixup_config(mock);
89 _get_section: function(config, section) {
90 if (!exists(this._configs, config)) {
93 if (!exists(this._configs, config))
97 let cfg = this._configs[config],
98 extended = match(section, "^@([A-Za-z0-9_-]+)\[(-?[0-9]+)\]$");
101 let stype = extended[1],
102 sindex = +extended[2];
105 filter(keys(cfg), sid => cfg[sid]['.type'] == stype),
106 (a, b) => cfg[a]['.index'] - cfg[b]['.index']
110 sindex = sids.length + sindex;
112 return cfg[sids[sindex]];
118 get: function(config, section, option) {
119 let sobj = this._get_section(config, section);
121 if (option && index(option, ".") == 0)
123 else if (sobj && option)
126 return sobj[".type"];
129 get_all: function(config, section) {
130 return section ? this._get_section(config, section) : this._configs[config];
133 foreach: function(config, stype, cb) {
136 if (exists(this._configs, config)) {
137 let cfg = this._configs[config],
138 sids = sort(keys(cfg), (a, b) => cfg[a]['.index'] - cfg[b]['.index']);
140 for (let i, sid in sids) {
141 if (stype == null || cfg[sid]['.type'] == stype) {
142 if (cb({ ...(cfg[sid]) }) === false)