Skip to content
This repository has been archived by the owner on Mar 19, 2024. It is now read-only.

Commit

Permalink
refactor: faster file watcher
Browse files Browse the repository at this point in the history
  • Loading branch information
hanspagel committed Feb 9, 2024
1 parent 3a232ac commit a9dee2d
Show file tree
Hide file tree
Showing 4 changed files with 161 additions and 16 deletions.
1 change: 1 addition & 0 deletions packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
],
"dependencies": {
"@hono/node-server": "^1.7.0",
"@parcel/watcher": "^2.4.0",
"@scalar/api-reference": "^1.15.1",
"@seriousme/openapi-schema-validator": "^2.1.6",
"commander": "^12.0.0",
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/petstore.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
"/pet": {
"put": {
"tags": ["pet"],
"summary": "Update an existing pet",
"summary": "Hello iuapsd",
"description": "Update an existing pet by Id",
"operationId": "updatePet",
"requestBody": {
Expand Down
21 changes: 14 additions & 7 deletions packages/cli/src/utils/watchFile.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,31 @@
import watcher from '@parcel/watcher'
import fs from 'node:fs'
import path from 'node:path'

/**
* Watch a file for changes and call a callback when it does.
* Watch a foobar for changes and call a callback when it does.
*/
export async function watchFile(
file: string,
callback: () => void,
options?: { immediate?: boolean },
) {
console.log(`[INFO] Watch ${file}`)
const absoluteFilePath = path.join(process.cwd(), file)

// Check if file exists
if (!fs.existsSync(file)) {
throw new Error(`File ${file} does not exist`)
if (!fs.existsSync(absoluteFilePath)) {
throw new Error(`File ${absoluteFilePath} does not exist`)
}

// Watch the file for changes
fs.watchFile(file, async () => {
// Call the callback
callback()
console.log(`[INFO] Watch ${file}`)

// Start the watcher
await watcher.subscribe(process.cwd(), (err, events) => {
// Match the file path
if (events.some((event) => event.path === absoluteFilePath)) {
callback()
}
})

// Call the callback immediately
Expand Down
153 changes: 145 additions & 8 deletions pnpm-lock.yaml

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

0 comments on commit a9dee2d

Please sign in to comment.