alacritty-theme-switch
Version:
CLI utility for switching Alacritty color themes
75 lines (74 loc) • 2.9 kB
JavaScript
import { copy } from "../../deps/jsr.io/@std/fs/1.0.21/copy.js";
import { dirname } from "../../deps/jsr.io/@std/path/1.1.4/dirname.js";
import { errAsync, fromPromise, okAsync } from "neverthrow";
import { FileIsDirectoryError, FileNotTOMLError } from "../utils/fs-errors.js";
import { safeEnsureDir, safeStat, safeWriteFile } from "../utils/fs-utils.js";
import { isToml, safeParseToml, safeStringifyToml, } from "../utils/toml-utils.js";
import { BackupError } from "./errors.js";
/**
* Creates a backup copy of the configuration file.
*
* @param configPath - Path to the configuration file
* @param backupPath - Path to the backup file
* @returns A ResultAsync containing void or an error
*/
export function createBackup(configPath, backupPath) {
return fromPromise(copy(configPath, backupPath, { overwrite: true }), (error) => new BackupError(configPath, { cause: error }));
}
/**
* Writes the configuration to the specified file in a safe manner.
*
* @param path - Path to the configuration file
* @param config - Configuration to write
* @returns A ResultAsync containing void or an error
*/
export function writeConfigToFile(path, config) {
return safeStringifyToml(config)
.asyncAndThen((content) => safeWriteFile(path, content));
}
/**
* Ensures the configuration file exists, creating it with minimal config if needed.
*
* @param configPath - Path to the configuration file
* @returns A ResultAsync containing void or an error
*/
function ensureConfigFile(configPath) {
return safeStat(configPath)
.orElse((error) => {
if (error._tag === "FileNotFoundError") {
const parentDir = dirname(configPath);
const ensureDirResult = safeEnsureDir(parentDir);
return ensureDirResult.andThen(() => {
const minimalConfig = {
general: {
import: [],
},
};
return safeStringifyToml(minimalConfig)
.asyncAndThen((content) => safeWriteFile(configPath, content));
});
}
return errAsync(error);
});
}
/**
* Parses an Alacritty configuration file from TOML format.
* Creates the file with minimal configuration if it doesn't exist.
*
* @param configPath - Path to the configuration file
* @returns A ResultAsync containing the parsed configuration or an error
*/
export function parseConfig(configPath) {
//TODO: Should validate and return a Config type
if (!isToml(configPath)) {
return errAsync(new FileNotTOMLError(configPath));
}
return ensureConfigFile(configPath)
.andThen(() => safeStat(configPath))
.andThen((stat) => {
return stat.isFile
? okAsync(stat)
: errAsync(new FileIsDirectoryError(configPath));
})
.andThen(() => safeParseToml(configPath));
}