Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/python-wasm
Path: blob/main/python/pylang/tools/ini.js
1396 views
1
/* vim:fileencoding=utf-8
2
*
3
* Copyright (C) 2015 Kovid Goyal <kovid at kovidgoyal.net>
4
*
5
* Distributed under terms of the BSD license
6
*/
7
"use strict"; /*jshint node:true */
8
9
var fs = require("fs");
10
var path = require("path");
11
12
function parse_ini_data(data) {
13
// Based on MIT licensed code from:
14
// https://github.com/shockie/node-iniparser/blob/master/lib/node-iniparser.js
15
var ans = {},
16
match;
17
var lines = data.split(/\r\n|\r|\n/);
18
var section = null;
19
var section_pat = /^\s*\[\s*([^\]]*)\s*\]\s*$/;
20
var param_pat = /^\s*([\w\.\-\_]+)\s*=\s*(.*?)\s*$/;
21
var comment_pat = /^\s*;.*$/;
22
23
lines.forEach(function (line) {
24
if (comment_pat.test(line)) {
25
return;
26
} else if (param_pat.test(line)) {
27
match = line.match(param_pat);
28
if (section) {
29
ans[section][match[1]] = match[2];
30
} else {
31
ans[match[1]] = match[2];
32
}
33
} else if (section_pat.test(line)) {
34
match = line.match(section_pat);
35
ans[match[1]] = {};
36
section = match[1];
37
} else if (line.length === 0 && section) {
38
section = null;
39
}
40
});
41
return ans;
42
}
43
44
function find_cfg_file(toplevel_dir) {
45
var current_dir = toplevel_dir,
46
previous_dir = toplevel_dir;
47
do {
48
try {
49
return fs.readFileSync(path.join(current_dir, "setup.cfg"), "utf-8");
50
} catch (e) {
51
if (e.code !== "ENOENT") throw e;
52
}
53
previous_dir = current_dir;
54
current_dir = path.dirname(current_dir);
55
} while (current_dir != previous_dir && current_dir);
56
57
return null;
58
}
59
60
function read_config(toplevel_dir) {
61
var data = find_cfg_file(toplevel_dir);
62
if (!data) return {};
63
return parse_ini_data(data);
64
}
65
66
exports.read_config = read_config;
67
68