Skip to content

Commit

Permalink
Validate JSON
Browse files Browse the repository at this point in the history
  • Loading branch information
sosukesuzuki committed Jul 16, 2022
1 parent 2e228d9 commit afcbd3c
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 4 deletions.
17 changes: 14 additions & 3 deletions src/cli/find-cache-file.js
@@ -1,9 +1,10 @@
"use strict";

const fs = require("fs").promises;
const os = require("os");
const path = require("path");
const findCacheDir = require("find-cache-dir");
const { statSafe } = require("./utils.js");
const { statSafe, isJson } = require("./utils.js");

/**
* Find default cache file (`./node_modules/.cache/prettier/.prettier-cache`) using https://github.com/avajs/find-cache-dir
Expand All @@ -21,9 +22,19 @@ async function findCacheFileFromOption(cacheLocation) {
const cacheFile = path.join(cwd, normalized);

const stat = await statSafe(cacheFile);
if (stat && stat.isDirectory()) {
throw new Error(`Resolved --cache-location '${cacheFile}' is a directory`);
if (stat) {
if (stat.isDirectory()) {
throw new Error(
`Resolved --cache-location '${cacheFile}' is a directory`
);
}

const data = await fs.readFile(cacheFile, "utf8");
if (!isJson(data)) {
throw new Error(`'${cacheFile}' isn't a valid JSON file`);
}
}

return cacheFile;
}

Expand Down
15 changes: 14 additions & 1 deletion src/cli/utils.js
Expand Up @@ -67,4 +67,17 @@ async function statSafe(filePath) {
}
}

module.exports = { printToScreen, groupBy, pick, createHash, statSafe };
/**
* @param {string} value
* @returns {boolean}
*/
function isJson(value) {
try {
JSON.parse(value);
return true;
} catch {
return false;
}
}

module.exports = { printToScreen, groupBy, pick, createHash, statSafe, isJson };
12 changes: 12 additions & 0 deletions tests/integration/__tests__/cache.js
Expand Up @@ -407,6 +407,18 @@ describe("--cache option", () => {
);
});

it("throws error for invalid JSON file", async () => {
const { stderr } = await runPrettier(dir, [
"--cache",
"--cache-location",
"a.js",
".",
]);
expect(stripAnsi(stderr).trim()).toEqual(
expect.stringMatching(/\[error] '.+' isn't a valid JSON file/)
);
});

describe("file", () => {
it("creates the cache file at location specified by `--cache-location`", async () => {
await expect(fs.stat(nonDefaultCacheFilePath)).rejects.toHaveProperty(
Expand Down

0 comments on commit afcbd3c

Please sign in to comment.