alia
Version:
Alias To Go
101 lines (100 loc) • 2.93 kB
JavaScript
import * as path from 'node:path';
import { homedir } from 'node:os';
import * as readline from 'node:readline/promises';
import { stdin as input, stdout as output } from 'process';
import logger from '../utils/logger.js';
import { file } from '../utils/file.js';
import { read } from '../utils/read.js';
export class ConfigService {
fileName = '.alia.json';
filePath = path.join(homedir(), this.fileName);
get defaultConfig() {
const cfgPath = path.resolve(import.meta.dirname, '..', '..', 'data', 'config.default.json');
const cfgFile = file.read(cfgPath);
const cfg = JSON.parse(cfgFile);
return cfg;
}
#config;
get config() {
if (this.#config) {
return this.#config;
}
try {
const config = file.read(this.filePath);
this.#config = JSON.parse(config);
return this.#config;
}
catch (_) {
return this.defaultConfig;
}
}
get isReady() {
return file.exists(this.filePath);
}
get alias() {
return this.config.alias;
}
get keys() {
return Object.keys(this.config.alias);
}
get options() {
return this.config.options;
}
getAlias(key) {
return this.config.alias[key];
}
setAlias(key, command) {
this.config.alias[key] = command;
this.save(this.config);
}
removeAlias(key) {
const { [key]: _, ...rest } = this.config.alias;
this.config.alias = rest;
this.save(this.config);
}
get shell() {
return this.config.options.shell ?? process.platform === 'win32';
}
set shell(value) {
this.config.options.shell = value;
this.save(this.config);
}
get token() {
return this.meta.gist.token;
}
set token(token) {
this.meta.gist.token = token;
this.save(this.config);
}
get gistId() {
return this.meta.gist.id;
}
set gistId(id) {
this.meta.gist.id = id;
this.save(this.config);
}
get meta() {
return this.config.meta;
}
async init() {
if (file.exists(this.filePath)) {
const rli = readline.createInterface({ input, output });
const answer = await read.question(rli, `config already exists at: ${this.filePath}\nwould you like to overwrite (y/n): `);
rli.close();
if (!/y(es)?/i.test(answer)) {
return;
}
this.backup(this.config);
}
this.save(this.defaultConfig);
logger.info('created config:', this.filePath);
}
save(config) {
file.write(this.filePath, config);
}
backup(config) {
const backupPath = `${this.filePath}.backup-${Date.now().toString()}`;
file.write(backupPath, config);
logger.info('backup created:', backupPath);
}
}