From 61c0129ce5742753fa2bb3ae78eaeacea982372e Mon Sep 17 00:00:00 2001 From: SUZUKI Sosuke Date: Wed, 12 Feb 2025 16:32:51 +0900 Subject: [PATCH] Invalidate outdated cache file (#17100) --- changelog_unreleased/cli/17100.md | 3 +++ src/cli/format-results-cache.js | 23 +++++++++++++++++++---- 2 files changed, 22 insertions(+), 4 deletions(-) create mode 100644 changelog_unreleased/cli/17100.md diff --git a/changelog_unreleased/cli/17100.md b/changelog_unreleased/cli/17100.md new file mode 100644 index 000000000..3c720fc8c --- /dev/null +++ b/changelog_unreleased/cli/17100.md @@ -0,0 +1,3 @@ +#### Fix CLI crash when cache for old version exists (#17100 by @sosukesuzuki) + +Prettier 3.5 uses a different cache format than previous versions, Prettier stable crashes when reading existing cache file, Prettier main fixed the problem. diff --git a/src/cli/format-results-cache.js b/src/cli/format-results-cache.js index 58c4f428d..c1dd652a1 100644 --- a/src/cli/format-results-cache.js +++ b/src/cli/format-results-cache.js @@ -1,6 +1,7 @@ // Inspired by LintResultsCache from ESLint // https://github.com/eslint/eslint/blob/c2d0a830754b6099a3325e6d3348c3ba983a677a/lib/cli-engine/lint-result-cache.js +import fs from "node:fs"; import stringify from "fast-json-stable-stringify"; import fileEntryCache from "file-entry-cache"; import { version as prettierVersion } from "../index.js"; @@ -44,10 +45,24 @@ class FormatResultsCache { constructor(cacheFileLocation, cacheStrategy) { const useChecksum = cacheStrategy === "content"; - this.#fileEntryCache = fileEntryCache.createFromFile( - /* filePath */ cacheFileLocation, - useChecksum, - ); + try { + this.#fileEntryCache = fileEntryCache.createFromFile( + /* filePath */ cacheFileLocation, + useChecksum, + ); + } catch { + // https://github.com/prettier/prettier/issues/17092 + // If `createFromFile()` fails, it's probably because the format + // of cache file changed,it happened when we release v3.5.0 + if (fs.existsSync(cacheFileLocation)) { + fs.unlinkSync(cacheFileLocation); + // retry + this.#fileEntryCache = fileEntryCache.createFromFile( + /* filePath */ cacheFileLocation, + useChecksum, + ); + } + } } /**