Skip to content

✨ feat(config.ts): add caching mechanism to reduce file I/O operations #166

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion src/commands/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { getI18nLocal } from '../i18n';
import * as dotenv from 'dotenv';

dotenv.config();
let configCache:ConfigType | null = null;

export enum CONFIG_KEYS {
OCO_OPENAI_API_KEY = 'OCO_OPENAI_API_KEY',
Expand Down Expand Up @@ -134,6 +135,9 @@ export type ConfigType = {
const configPath = pathJoin(homedir(), '.opencommit');

export const getConfig = (): ConfigType | null => {
// If it is enable, use configCache
if (configCache) return configCache;

const configFromEnv = {
OCO_OPENAI_API_KEY: process.env.OCO_OPENAI_API_KEY,
OCO_OPENAI_MAX_TOKENS: process.env.OCO_OPENAI_MAX_TOKENS ? Number(process.env.OCO_OPENAI_MAX_TOKENS) : undefined,
Expand All @@ -145,7 +149,10 @@ export const getConfig = (): ConfigType | null => {
};

const configExists = existsSync(configPath);
if (!configExists) return configFromEnv;
if (!configExists) {
configCache = configFromEnv;
return configFromEnv;
}

const configFile = readFileSync(configPath, 'utf8');
const config = iniParse(configFile);
Expand Down Expand Up @@ -173,6 +180,8 @@ export const getConfig = (): ConfigType | null => {
}
}

// Store configCache
configCache = config
return config;
};

Expand Down