Skip to content

Commit

Permalink
fix: Don't replace malformed appmap.yml
Browse files Browse the repository at this point in the history
- Use defaults only when there is no config file (ENOENT).
- Rethrow every other error thrown from readFileSync (ex: EACCESS).
- Rethrow YAML parsing error when appmap.yml is malformed, appending
  an informative message.
  • Loading branch information
zermelo-wisen authored and dividedmind committed Apr 3, 2024
1 parent b449c14 commit 48df24c
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
13 changes: 12 additions & 1 deletion src/__tests__/config.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { mkdirSync, writeFileSync } from "node:fs";
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { basename } from "node:path";
import { chdir, cwd } from "node:process";

Expand Down Expand Up @@ -101,6 +101,17 @@ describe(Config, () => {
});
});

it("if the appmap.yml is malformed throws with an informative message", () => {
const malformedAppMapFileContent = "{ appmap-dir: 'abc/xyz' ";
writeFileSync("appmap.yml", malformedAppMapFileContent);

expect(() => new Config()).toThrowError(
/You can remove the file to use the default configuration\.$/,
);

expect(readFileSync("appmap.yml").toString()).toEqual(malformedAppMapFileContent);
});

let dir: string;
beforeEach(() => {
chdir((dir = tmp.dirSync().name));
Expand Down
20 changes: 19 additions & 1 deletion src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import PackageMatcher, { Package, parsePackages } from "./PackageMatcher";
import locateFileUp from "./util/findFileUp";
import lazyOpt from "./util/lazyOpt";
import tryOr from "./util/tryOr";
import { isNativeError } from "node:util/types";

const responseBodyMaxLengthDefault = 10000;
const kResponseBodyMaxLengthEnvar = "APPMAP_RESPONSE_BODY_MAX_LENGTH";
Expand Down Expand Up @@ -98,7 +99,24 @@ interface ConfigFile {

function readConfigFile(path: string | undefined): ConfigFile | undefined {
if (!path) return;
const config = tryOr(() => YAML.parse(readFileSync(path, "utf8")) as unknown);

let fileContent: string;
try {
fileContent = readFileSync(path, "utf-8");
} catch (exn) {
if (exn && typeof exn == "object" && "code" in exn && exn.code == "ENOENT") return;
throw exn;
}

let config;
try {
config = YAML.parse(fileContent) as unknown;
} catch (exn) {
assert(isNativeError(exn));
throw new Error(
`Error parsing config file at ${path}: ${exn.message}\nYou can remove the file to use the default configuration.`,
);
}
if (!config) return;

const result: ConfigFile = {};
Expand Down

0 comments on commit 48df24c

Please sign in to comment.