2 let mocklib = global.mocklib;
4 let byte = (str, off) => {
6 return length(v) ? v[0] : v;
12 for (let i = 0; i < length(s); i++)
13 h = h * 31 + byte(s, i);
18 let id = (config, t, n) => {
20 let id = sprintf('cfg%08x', hash(t + n));
22 if (!exists(config, id))
29 let fixup_config = (config) => {
33 for (let stype in config) {
34 switch (type(config[stype])) {
36 config[stype] = [ config[stype] ];
40 for (let idx, sobj in config[stype]) {
43 if (exists(sobj, '.name') && !exists(rv, sobj['.name'])) {
48 sid = id(rv, stype, idx);
53 '.index': n_section++,
65 for (let n, sid in sort(keys(rv), (a, b) => rv[a]['.index'] - rv[b]['.index']))
66 rv[sid]['.index'] = n;
75 load: function(file) {
76 let basename = replace(file, /^.+\//, ''),
77 path = sprintf("uci/%s.json", basename),
78 mock = mocklib.read_json_file(path);
80 if (!mock || mock != mock) {
81 mocklib.I("No configuration fixture defined for uci package %s.", file);
82 mocklib.I("Provide a mock configuration through the following JSON file:\n%s\n", path);
87 this._configs[basename] = fixup_config(mock);
90 _get_section: function(config, section) {
91 if (!exists(this._configs, config)) {
94 if (!exists(this._configs, config))
98 let cfg = this._configs[config],
99 extended = match(section, "^@([A-Za-z0-9_-]+)\[(-?[0-9]+)\]$");
102 let stype = extended[1],
103 sindex = +extended[2];
106 filter(keys(cfg), sid => cfg[sid]['.type'] == stype),
107 (a, b) => cfg[a]['.index'] - cfg[b]['.index']
111 sindex = sids.length + sindex;
113 return cfg[sids[sindex]];
119 get: function(config, section, option) {
120 let sobj = this._get_section(config, section);
122 if (option && index(option, ".") == 0)
124 else if (sobj && option)
127 return sobj[".type"];
130 get_all: function(config, section) {
131 return section ? this._get_section(config, section) : this._configs[config];
134 foreach: function(config, stype, cb) {
137 if (exists(this._configs, config)) {
138 let cfg = this._configs[config],
139 sids = sort(keys(cfg), (a, b) => cfg[a]['.index'] - cfg[b]['.index']);
141 for (let i, sid in sids) {
142 if (stype == null || cfg[sid]['.type'] == stype) {
143 if (cb({ ...(cfg[sid]) }) === false)