UNPKG

@taizo-pro/github-discussions-cli

Version:

A powerful command-line tool for interacting with GitHub Discussions without opening a browser

101 lines 3.58 kB
import { promises as fs } from 'fs'; import { join } from 'path'; import { homedir } from 'os'; import { ErrorType } from './types.js'; export class FileConfigManager { configDir; configFile; constructor() { this.configDir = join(homedir(), '.github-discussions'); this.configFile = join(this.configDir, 'config.json'); } async getDefaultRepo() { const config = await this.getConfig(); return config.defaultRepo || null; } async setDefaultRepo(repo) { await this.updateConfig({ defaultRepo: repo }); } async getConfig() { try { const configData = await fs.readFile(this.configFile, 'utf8'); const config = JSON.parse(configData); return this.validateConfig(config); } catch (error) { if (error.code === 'ENOENT') { return this.getDefaultConfig(); } if (error instanceof SyntaxError) { throw this.createError(ErrorType.CONFIGURATION_ERROR, 'Invalid JSON in config file', error); } throw this.createError(ErrorType.CONFIGURATION_ERROR, 'Failed to read config file', error); } } async updateConfig(partialConfig) { try { const currentConfig = await this.getConfig(); const newConfig = { ...currentConfig, ...partialConfig }; await this.ensureConfigDir(); await fs.writeFile(this.configFile, JSON.stringify(newConfig, null, 2), 'utf8'); } catch (error) { throw this.createError(ErrorType.CONFIGURATION_ERROR, 'Failed to update config file', error); } } validateConfig(config) { const validatedConfig = {}; if (config.defaultRepo && typeof config.defaultRepo === 'string') { if (this.isValidRepoFormat(config.defaultRepo)) { validatedConfig.defaultRepo = config.defaultRepo; } } if (config.token && typeof config.token === 'string') { validatedConfig.token = config.token; } if (config.outputFormat && typeof config.outputFormat === 'string') { if (['table', 'json', 'markdown'].includes(config.outputFormat)) { validatedConfig.outputFormat = config.outputFormat; } } return validatedConfig; } isValidRepoFormat(repo) { const repoPattern = /^[a-zA-Z0-9._-]+\/[a-zA-Z0-9._-]+$/; return repoPattern.test(repo); } getDefaultConfig() { return { outputFormat: 'table', }; } async ensureConfigDir() { try { await fs.mkdir(this.configDir, { recursive: true, mode: 0o700 }); } catch (error) { throw this.createError(ErrorType.CONFIGURATION_ERROR, 'Failed to create config directory', error); } } createError(type, message, originalError) { return { type, message, details: originalError, suggestions: this.getSuggestions(type), }; } getSuggestions(type) { switch (type) { case ErrorType.CONFIGURATION_ERROR: return [ 'Check the config file at ~/.github-discussions/config.json', 'Ensure the JSON format is valid', 'Delete the config file to reset to defaults', ]; default: return []; } } } //# sourceMappingURL=config-manager.js.map