Skip to content

Commit

Permalink
Add option to force require() for config files handling (#43)
Browse files Browse the repository at this point in the history
* a63d067 - feat(config): add option to force require config files
* e6a5638 - test(config): fix temporary path resolution

Signed-off-by: Ryuu Mitsuki <[email protected]>
  • Loading branch information
mitsuki31 committed Aug 27, 2024
2 parents 8b08c73 + e6a5638 commit b91485e
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 7 deletions.
14 changes: 8 additions & 6 deletions lib/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ function configChecker({ config, file }) {
* @see {@link module:config~importConfig importConfig}
* (alias for <code>parseConfig(config, true)</code>)
*/
function parseConfig(configFile, resolve=true) {
function parseConfig(configFile, resolve=true, forceRequire=false) {
function resolveOrCheckOnly(config) {
// Attempt to extract the default export (only on ES module) if the configuration
// object only contains that 'default' property, for clarity:
Expand Down Expand Up @@ -294,15 +294,17 @@ function parseConfig(configFile, resolve=true) {
}`);
}

// Resolve the configuration file path
configFile = path.resolve(configFile);

// Import the configuration file
let config = null;
// Only include '.cjs' and '.json' to use require()
if (KNOWN_CONFIG_EXTS.slice(2).includes(path.extname(configFile))) {
if (KNOWN_CONFIG_EXTS.slice(2).includes(path.extname(configFile))
|| forceRequire) {
config = require(configFile);
} else {
// On Windows, replace all '\' with '/' to use import()
if (process.platform === 'win32') {
configFile = 'file:///' + configFile.replace(/\\/g, '/');
}
config = import(configFile);
}

Expand All @@ -328,7 +330,7 @@ function parseConfig(configFile, resolve=true) {
* @since 1.0.0
* @see {@link module:config~parseConfig parseConfig}
*/
const importConfig = (file) => parseConfig(file, true);
const importConfig = (file, forceRequire=false) => parseConfig(file, true, forceRequire);


module.exports = Object.freeze({
Expand Down
3 changes: 2 additions & 1 deletion test/unittest/config.spec.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,15 @@ import fs from 'node:fs';
import path from 'node:path';

import config from '../../lib/config.js';
import utils from '../../lib/utils.js';

describe('module:config', function () {
const testMessages = {
importConfig: [
'should parse and resolve the given configuration file'
]
};
const tempFile = path.join('tmp', 'tempTestConfig.json');
const tempFile = path.join(utils.ROOTDIR, 'tmp', 'tempTestConfig.json');
const configObj = {
downloadOptions: {
cwd: null,
Expand Down

0 comments on commit b91485e

Please sign in to comment.