-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfigUtils.js
More file actions
54 lines (47 loc) · 1.87 KB
/
configUtils.js
File metadata and controls
54 lines (47 loc) · 1.87 KB
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
45
46
47
48
49
50
51
52
53
54
const fs = require("fs");
const path = require("path");
const os = require("os");
const { validateConfigSchema } = require("../utils/validateConfigSchema");
/**
* Loads and parses a configuration file from a specified path or default locations.
*
* If a `configPath` is provided, it attempts to load the configuration from that path.
* If not, it checks for a project-specific configuration file in the current working directory,
* and if not found, it checks for a global configuration file in the user's home directory.
*
* @param {string} [configPath] - Optional path to a specific configuration file.
* @returns {Object} The parsed configuration object, or an empty object if no valid configuration file is found.
*/
const loadConfig = (configPath) => {
const CONFIG_FILES = {
PROJECT: "contract-shield.config.json",
GLOBAL: "contract-shield.json",
};
const defaultProjectConfig = path.resolve(process.cwd(), CONFIG_FILES.PROJECT);
// const defaultGlobalConfig = path.resolve(os.homedir(), CONFIG_FILES.GLOBAL);
const defaultGlobalConfig = path.resolve(__dirname__, CONFIG_FILES.GLOBAL);
const finalConfigPath = configPath ||
[defaultProjectConfig, defaultGlobalConfig].find(fs.existsSync) || null;
if (finalConfigPath) {
try {
const fileContent = fs.readFileSync(finalConfigPath, "utf-8");
try {
const config = JSON.parse(fileContent);
const isValidConfig = validateConfigSchema(config);
if (!isValidConfig) {
console.error("Invalid configuration structure.");
return {};
}
return config;
} catch (parseError) {
console.error("Error parsing JSON:", parseError);
return {};
}
} catch (error) {
console.error(`Error loading configuration from ${finalConfigPath}:`, error);
return {};
}
}
return {};
};
module.exports = { loadConfig };