From fe040aeef90c7fc3db4514b92275e61cc5dd3b99 Mon Sep 17 00:00:00 2001 From: Konv Suu Date: Sat, 27 Jun 2026 17:45:39 +0800 Subject: [PATCH] Fix cache not invalidated when files are ignored or restored (#18029) --- src/cli/format.js | 4 +++ tests/integration/__tests__/cache.js | 51 +++++++++++++++++++++++++++- 2 files changed, 54 insertions(+), 1 deletion(-) diff --git a/src/cli/format.js b/src/cli/format.js index c2434b803..84de34946 100644 --- a/src/cli/format.js +++ b/src/cli/format.js @@ -321,6 +321,10 @@ async function formatFiles(context) { context.argv.check || context.argv.listDifferent) ) { + // If the file is ignored remove it from the cache + // - it won't be formatted anymore + // - if it has been restored, we shouldn't keep the old cache entry + formatResultsCache?.removeFormatResultsCache(filename); continue; } diff --git a/tests/integration/__tests__/cache.js b/tests/integration/__tests__/cache.js index 538a9c02e..5ddc23d80 100644 --- a/tests/integration/__tests__/cache.js +++ b/tests/integration/__tests__/cache.js @@ -19,6 +19,7 @@ describe("--cache option", () => { const nonDefaultCacheFileName = ".non-default-cache-file"; const directoryNameAsCacheFile = "directory-as-cache-file"; const nonDefaultCacheFilePath = path.join(dir, nonDefaultCacheFileName); + const prettierIgnorePath = path.join(dir, ".prettierignore"); const contentA = `function a() { console.log("this is a.js") @@ -374,6 +375,54 @@ describe("--cache option", () => { await runCliWithoutGitignore(dir, ["--write", "*.js"]); await expect(fs.stat(defaultCacheFile)).rejects.toThrow(); }); + + it("invalidates cache when previously ignored files are restored", async () => { + await runCliWithoutGitignore(dir, [ + "--write", + "--cache", + "--cache-strategy", + "metadata", + "*.js", + ]); + + await fs.writeFile(prettierIgnorePath, ["b.js"].join("\n")); + + await fs.writeFile( + path.join(dir, "b.js"), + "const b = 'this is new content';", + ); + + const { stdout: secondStdout } = await runCliWithoutGitignore(dir, [ + "--write", + "--cache", + "--cache-strategy", + "metadata", + "*.js", + ]); + + expect(secondStdout.split("\n")).toEqual( + expect.arrayContaining([ + expect.stringMatching(/^a\.js .+ms \(unchanged\) \(cached\)$/u), + ]), + ); + + await fs.rm(prettierIgnorePath, { force: true }); + + const { stdout: thirdStdout } = await runCliWithoutGitignore(dir, [ + "--write", + "--cache", + "--cache-strategy", + "metadata", + "*.js", + ]); + + expect(thirdStdout.split("\n")).toEqual( + expect.arrayContaining([ + expect.stringMatching(/^a\.js .+ms \(unchanged\) \(cached\)$/u), + expect.stringMatching(/^b\.js .+ms$/u), + ]), + ); + }); }); describe("--cache-strategy content", () => { @@ -701,7 +750,7 @@ describe("--cache option", () => { await expect(fs.stat(nonDefaultCacheFilePath)).resolves.not.toThrow(); }); - it("does'nt format when cache is available", async () => { + it("doesn't format when cache is available", async () => { const cliArguments = [ "--cache", "--write",