Skip to content
Open
Show file tree
Hide file tree
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
14 changes: 13 additions & 1 deletion src/config/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,19 @@ export function getHistoryPath(): string {
export async function loadConfig(): Promise<Config> {
const configPath = getConfigPath();
const raw = await readFile(configPath, 'utf-8');
const parsed = JSON.parse(raw) as Partial<Config>;
let parsed: Partial<Config>;

try {
parsed = JSON.parse(raw) as Partial<Config>;
} catch (error) {
if (error instanceof SyntaxError) {
throw new Error(
`Invalid JSON in config file: ${configPath}. Fix the JSON syntax or run \`commit-echo init\` to recreate it.`,
{ cause: error },
);
}
throw error;
}

return {
provider: parsed.provider ?? '',
Expand Down
46 changes: 46 additions & 0 deletions tests/config-store.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import assert from "node:assert/strict";
import { mkdir, mkdtemp, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname } from "node:path";
import test from "node:test";

import { getConfigPath, loadConfig } from "../dist/config/store.js";

function escapeRegExp(value) {
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}

test("loadConfig reports invalid JSON with the config path and fix hint", async () => {
const originalHome = process.env.HOME;
const originalXdgConfigHome = process.env.XDG_CONFIG_HOME;
const home = await mkdtemp(`${tmpdir()}/commit-echo-config-`);

process.env.HOME = home;
delete process.env.XDG_CONFIG_HOME;

try {
const configPath = getConfigPath();
await mkdir(dirname(configPath), { recursive: true });
await writeFile(configPath, "{ invalid json", "utf-8");

await assert.rejects(loadConfig(), (error) => {
assert.equal(error instanceof Error, true);
assert.match(error.message, /Invalid JSON in config file:/);
assert.match(error.message, new RegExp(escapeRegExp(configPath)));
assert.match(error.message, /Fix the JSON syntax or run `commit-echo init` to recreate it\./);
return true;
});
} finally {
if (originalHome === undefined) {
delete process.env.HOME;
} else {
process.env.HOME = originalHome;
}

if (originalXdgConfigHome === undefined) {
delete process.env.XDG_CONFIG_HOME;
} else {
process.env.XDG_CONFIG_HOME = originalXdgConfigHome;
}
}
});