Skip to content

Commit

Permalink
feat(#90): improve conf retrieval
Browse files Browse the repository at this point in the history
  • Loading branch information
jannis-baum committed Jul 15, 2024
1 parent 26421fa commit 07296ea
Showing 1 changed file with 38 additions and 16 deletions.
54 changes: 38 additions & 16 deletions src/parser/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,30 +4,52 @@ import path from 'path';

type Config = {
styles?: string;
port: number;
/* eslint-disable-next-line @typescript-eslint/no-explicit-any */
katexOptions?: any;
pageTitle?: string;
mdExtensions?: string[];
};
let config: Config = {};

const defaultConfig: Config = {
port: 31622,
};

const configPaths = [
path.join(homedir(), '.vivify', 'config.json'),
path.join(homedir(), '.vivify.json'),
];

for (const cp of configPaths) {
if (!fs.existsSync(cp)) continue;
try {
config = JSON.parse(fs.readFileSync(cp, 'utf8'));
break;
} catch {}
}

if (config.styles && config.styles.length > 0) {
const stylePath =
config.styles[0] === '~' ? path.join(homedir(), config.styles.slice(1)) : config.styles;
config.styles = fs.existsSync(stylePath) ? fs.readFileSync(stylePath, 'utf8') : '';
}

export default config;
const envConfigs: [[string, keyof Config]] = [['VIV_PORT', 'port']];

const getConfig = (): Config => {
let config = undefined;
// greedily get config
for (const cp of configPaths) {
if (!fs.existsSync(cp)) continue;
try {
config = JSON.parse(fs.readFileSync(cp, 'utf8'));
break;
} catch {}
}

if (config === undefined) return defaultConfig;

// get styles
if (config.styles && config.styles.length > 0) {
const stylePath =
config.styles[0] === '~' ? path.join(homedir(), config.styles.slice(1)) : config.styles;
config.styles = fs.existsSync(stylePath) ? fs.readFileSync(stylePath, 'utf8') : '';
}
// fill missing values from default config
for (const [key, value] of Object.entries(defaultConfig)) {
if (config[key] === undefined) config[key] = value;
}
// environment overrides
for (const [env, key] of envConfigs) {
if (process.env[env]) config[key] = process.env[env];
}
return config;
};

export default getConfig();

0 comments on commit 07296ea

Please sign in to comment.