Skip to content

Commit

Permalink
Use flag validation
Browse files Browse the repository at this point in the history
  • Loading branch information
sosukesuzuki committed May 30, 2022
1 parent cd464a9 commit 9499918
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 31 deletions.
12 changes: 11 additions & 1 deletion src/cli/constant.js
Expand Up @@ -77,10 +77,20 @@ const options = {
type: "boolean",
},
"cache-strategy": {
choices: [
{
description: "Use the file metadata such as timestamps as cache keys",
value: "metadata",
},
{
description: "Use the file content as cache keys",
value: "content",
},
],
default: "metadata",
describe:
"Strategy for the cache to use for detecting changed files. Can be either `metadata` or `content`. ",
type: "string",
type: "choice",
},
check: {
alias: "c",
Expand Down
20 changes: 0 additions & 20 deletions src/cli/format-results-cache.js
Expand Up @@ -38,32 +38,12 @@ function getMetadataFromFileDescriptor(fileDescriptor) {
return fileDescriptor.meta;
}

const cacheStrategies = ["metadata", "content"];
const cacheStrategiesSet = new Set(cacheStrategies);

/**
* @typedef {"metadata" | "content"} CacheStrategy
*
* @param {string} value
* @returns {value is CacheStrategy}
*/
function isValidCacheStrategy(value) {
return cacheStrategiesSet.has(value);
}

class FormatResultsCache {
/**
* @param {string} cacheFileLocation The path of cache file location. (default: `node_modules/.cache/prettier/prettier-cache`)
* @param {string} cacheStrategy
*/
constructor(cacheFileLocation, cacheStrategy) {
if (!isValidCacheStrategy(cacheStrategy)) {
const errorMessage = `Cache strategy must be one of: ${cacheStrategies
.map((strategy) => `"${strategy}"`)
.join(", ")}`;
throw new Error(errorMessage);
}

const useChecksum = cacheStrategy === "content";

this.cacheFileLocation = cacheFileLocation;
Expand Down
13 changes: 4 additions & 9 deletions src/cli/format.js
Expand Up @@ -301,15 +301,10 @@ async function formatFiles(context) {
let formatResultsCache;
const cacheFilePath = findCacheFile();
if (context.argv.cache) {
try {
formatResultsCache = new FormatResultsCache(
cacheFilePath,
context.argv.cacheStrategy
);
} catch (error) {
context.logger.error(error.message);
process.exit(2);
}
formatResultsCache = new FormatResultsCache(
cacheFilePath,
context.argv.cacheStrategy
);
} else {
const stat = await statSafe(cacheFilePath);
if (stat) {
Expand Down
2 changes: 1 addition & 1 deletion tests/integration/__tests__/cache.js
Expand Up @@ -40,7 +40,7 @@ describe("--cache option", () => {
".",
]);
expect(stripAnsi(stderr.trim())).toBe(
'[error] Cache strategy must be one of: "metadata", "content"'
'[error] Invalid --cache-strategy value. Expected "content" or "metadata", but received "invalid".'
);
});

Expand Down

0 comments on commit 9499918

Please sign in to comment.