Skip to content

Commit

Permalink
breaking: upgrade chokidar v4 (#237)
Browse files Browse the repository at this point in the history
  • Loading branch information
zce authored Oct 11, 2024
1 parent 02c4e2a commit d25ecd9
Show file tree
Hide file tree
Showing 9 changed files with 102 additions and 44 deletions.
2 changes: 1 addition & 1 deletion docs/guide/last-modified.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ const timestamp = defineSchema(() =>
addIssue({ fatal: false, code: 'custom', message: '`s.timestamp()` schema will resolve the value from `git log -1 --format=%cd`' })
}
const { stdout } = await execAsync(`git log -1 --format=%cd ${meta.path}`)
return new Date(stdout).toISOString()
return new Date(stdout || Date.now()).toISOString()
})
)
```
Expand Down
2 changes: 1 addition & 1 deletion docs/other/snippets.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ const timestamp = defineSchema(() =>
addIssue({ fatal: false, code: 'custom', message: '`s.timestamp()` schema will resolve the value from `git log -1 --format=%cd`' })
}
const { stdout } = await execAsync(`git log -1 --format=%cd ${meta.path}`)
return new Date(stdout).toISOString()
return new Date(stdout || Date.now()).toISOString()
})
)

Expand Down
2 changes: 1 addition & 1 deletion examples/basic/velite.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ const timestamp = () =>
addIssue({ fatal: false, code: 'custom', message: '`s.timestamp()` schema will resolve the value from `git log -1 --format=%cd`' })
}
const { stdout } = await execAsync(`git log -1 --format=%cd ${meta.path}`)
return new Date(stdout).toISOString()
return new Date(stdout || Date.now()).toISOString()
})

export default defineConfig({
Expand Down
2 changes: 1 addition & 1 deletion examples/nextjs/velite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ const timestamp = () =>
addIssue({ fatal: false, code: 'custom', message: '`s.timestamp()` schema will resolve the value from `git log -1 --format=%cd`' })
}
const { stdout } = await execAsync(`git log -1 --format=%cd ${meta.path}`)
return new Date(stdout).toISOString()
return new Date(stdout || Date.now()).toISOString()
})

const options = defineCollection({
Expand Down
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,18 +48,18 @@
"@rollup/plugin-node-resolve": "^15.3.0",
"@types/hast": "^3.0.4",
"@types/mdast": "^4.0.4",
"@types/micromatch": "^4.0.9",
"@types/node": "^20.16.11",
"@types/picomatch": "^3.0.1",
"@zce/prettier-config": "^0.4.0",
"chokidar": "^3.6.0",
"chokidar": "^4.0.1",
"fast-glob": "^3.3.2",
"hast-util-raw": "^9.0.4",
"hast-util-to-string": "^3.0.1",
"lint-staged": "^15.2.10",
"mdast-util-from-markdown": "^2.0.1",
"mdast-util-to-hast": "^13.2.0",
"mdast-util-toc": "^7.1.0",
"micromatch": "^4.0.8",
"picomatch": "^4.0.2",
"prettier": "^3.3.3",
"rehype-raw": "^7.0.0",
"rehype-stringify": "^10.0.1",
Expand Down
53 changes: 33 additions & 20 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

35 changes: 18 additions & 17 deletions src/build.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { mkdir, rm } from 'node:fs/promises'
import { join, normalize } from 'node:path'
import glob from 'fast-glob'
import micromatch from 'micromatch'
import { reporter } from 'vfile-reporter'

import { assets } from './assets'
Expand All @@ -10,6 +9,7 @@ import { VeliteFile } from './file'
import { logger } from './logger'
import { outputAssets, outputData, outputEntry } from './output'
import { getParsedType, ParseContext } from './schemas/zod'
import { matchPatterns } from './utils'

import type { LogLevel } from './logger'
import type { Schema, ZodMeta } from './schemas'
Expand Down Expand Up @@ -98,7 +98,7 @@ const resolve = async (config: Config, changed?: string): Promise<Record<string,

const entries = await Promise.all(
Object.entries(collections).map(async ([name, { pattern, schema }]): Promise<[string, VeliteFile[]]> => {
if (changed != null && !micromatch.contains(changed, pattern) && resolved.has(name)) {
if (changed != null && !matchPatterns(changed, pattern, root) && resolved.has(name)) {
// skip collection if changed file not match
logger.log(`skipped resolve '${name}', using previous resolved`)
return [name, resolved.get(name)!]
Expand Down Expand Up @@ -176,35 +176,36 @@ const watch = async (config: Config) => {

logger.info(`watching for changes in '${root}'`)

const files = Object.values(collections).flatMap(({ pattern }) => pattern)
files.push(...configImports) // watch config file and its dependencies
const patterns = Object.values(collections).flatMap(({ pattern }) => pattern)

const watcher = watch(files, {
const watcher = watch(['.', ...configImports], {
cwd: root,
ignored: /(^|[\/\\])[\._]./, // ignore dot & underscore files
ignoreInitial: true, // ignore initial scan
ignoreInitial: true,
awaitWriteFinish: { stabilityThreshold: 50, pollInterval: 10 }
}).on('all', async (event, filename) => {
if (event === 'addDir' || event === 'unlinkDir') return // ignore dir changes
if (event === 'addDir' || event === 'unlinkDir') return
if (filename == null) return

filename = join(root, filename)

try {
// remove changed file cache
for (const [key, value] of config.cache.entries()) {
if (value === filename) config.cache.delete(key)
}
const fullpath = join(root, filename)

if (configImports.includes(filename)) {
if (configImports.includes(fullpath)) {
logger.info('velite config changed, restarting...')
watcher.close()
return build({ config: config.configPath, clean: false, watch: true })
}

// skip if filename not match any collection pattern
if (!matchPatterns(filename, patterns)) return

// remove changed file cache
for (const [key, value] of config.cache.entries()) {
if (value === fullpath) config.cache.delete(key)
}

const begin = performance.now()
logger.info(`changed: '${filename}', rebuilding...`)
await resolve(config, filename)
logger.info(`changed: '${fullpath}', rebuilding...`)
await resolve(config, fullpath)
logger.info(`rebuild finished`, begin)
} catch (err) {
logger.warn(err)
Expand Down
23 changes: 23 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { relative } from 'node:path'
import pm from 'picomatch'

export const matchPatterns = (input: string, patterns: string | string[], base?: string) => {
const list = Array.isArray(patterns) ? patterns : [patterns]

// TODO: groupBy in feature
const { normal, negated } = list.reduce(
(acc, p) => {
acc[p.startsWith('!') ? 'negated' : 'normal'].push(p)
return acc
},
{ normal: [] as string[], negated: [] as string[] }
)

if (base != null) {
input = relative(base, input).replace(/^\.[\\/]/, '')
}

input = input.replaceAll('\\', '/')

return normal.some(i => pm(i)(input)) && negated.every(i => pm(i)(input))
}
21 changes: 21 additions & 0 deletions test/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { strictEqual } from 'node:assert'
import { describe, it } from 'node:test'

import { matchPatterns } from '../src/utils'

describe('matchPatterns function', async t => {
it('matches single pattern', () => {
strictEqual(matchPatterns('foo/bar.js', '**/*.js'), true)
strictEqual(matchPatterns('foo/bar.ts', '**/*.js'), false)
})

it('matches multiple patterns', () => {
strictEqual(matchPatterns('foo/bar.js', ['**/*.js', '**/*.ts']), true)
strictEqual(matchPatterns('foo/bar.css', ['**/*.js', '**/*.ts']), false)
})

it('handles negated patterns', () => {
strictEqual(matchPatterns('foo/bar.js', ['**/*.js', '!**/node_modules/**']), true)
strictEqual(matchPatterns('node_modules/foo/bar.js', ['**/*.js', '!**/node_modules/**']), false)
})
})

0 comments on commit d25ecd9

Please sign in to comment.