Skip to content

Commit 1a53f78

Browse files
authored
feat: cache the dprint context (#14)
1 parent bdc1a71 commit 1a53f78

File tree

3 files changed

+17
-5
lines changed

3 files changed

+17
-5
lines changed

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@
7070
"@dprint/toml": "^0.7.0",
7171
"eslint-formatting-reporter": "^0.0.0",
7272
"eslint-parser-plain": "^0.1.1",
73+
"ohash": "^2.0.11",
7374
"prettier": "^3.7.4",
7475
"synckit": "^0.11.11"
7576
},

pnpm-lock.yaml

Lines changed: 3 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

workers/dprint.cjs

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
const { Buffer } = require('node:buffer')
22
const fs = require('node:fs/promises')
3+
const { hash } = require('ohash')
34
// @ts-check
45
const { runAsWorker } = require('synckit')
56

67
let dprint
78
const cache = new Map()
9+
const context_cache = new Map()
810

911
async function loadBuffer(data) {
1012
if (typeof data === 'string' && data.startsWith('@dprint/'))
@@ -53,13 +55,19 @@ runAsWorker(async (code, filename, options) => {
5355
})
5456
}
5557
else {
56-
// TODO: context caching??
5758
const { plugins, ...rest } = options
58-
const context = dprint.createContext(rest)
59+
const options_hash = hash(options)
60+
const context = context_cache.has(options_hash)
61+
? context_cache.get(options_hash)
62+
: context_cache.set(options_hash, await (async () => {
63+
const context = dprint.createContext(rest)
5964

60-
for (const plugin of plugins) {
61-
context.addPlugin(await loadBuffer(plugin.plugin), plugin.options || {})
62-
}
65+
for (const plugin of plugins) {
66+
context.addPlugin(await loadBuffer(plugin.plugin), plugin.options || {})
67+
}
68+
69+
return context
70+
})()).get(options_hash)
6371

6472
return context.formatText({
6573
filePath: filename,

0 commit comments

Comments
 (0)