Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Fixed

- Use the latest file contents when an atomic save lands during a CLI `--watch` rebuild ([#20636](https://github.com/tailwindlabs/tailwindcss/pull/20636))
- Ensure classes are extracted when a variant precedes an arbitrary variant containing a quoted attribute selector (e.g. `focus-visible:[&:not([aria-selected="true"])]:bg-red-500`) ([#20374](https://github.com/tailwindlabs/tailwindcss/pull/20374))
- Fix negation of `theme()` in arbitrary values (e.g. `-m-[theme(margin.1)]`) ([#19928](https://github.com/tailwindlabs/tailwindcss/pull/19928))

Expand Down
92 changes: 41 additions & 51 deletions src/cli/build/watching.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,15 +50,12 @@ export function createWatcher(args, { state, rebuild }) {
: false,
})

// A queue of rebuilds, file reads, etc… to run
let chain = Promise.resolve()

/**
* A list of files that have been changed since the last rebuild
* Latest pending change per file.
*
* @type {{file: string, content: () => Promise<string>, extension: string}[]}
* @type {Map<string, {file: string, content: () => Promise<string>, extension: string}>}
*/
let changedContent = []
let changedFiles = new Map()

/**
* A list of files for which a rebuild has already been queued.
Expand All @@ -68,31 +65,48 @@ export function createWatcher(args, { state, rebuild }) {
**/
let pendingRebuilds = new Set()

let _timer
let _reject
/** @type {ReturnType<typeof setTimeout> | null} */
let timer = null

/**
* Rebuilds the changed files and resolves when the rebuild is
* complete regardless of whether it was successful or not
*/
async function rebuildAndContinue() {
let changes = changedContent.splice(0)
let running = false

function arm() {
if (running) {
return
}

if (timer) {
clearTimeout(timer)
}

timer = setTimeout(run, 10)
}

async function run() {
timer = null

let changes = [...changedFiles.values()]
changedFiles.clear()

// There are no changes to rebuild so we can just do nothing
if (changes.length === 0) {
return Promise.resolve()
return
}

// Clear all pending rebuilds for the about-to-be-built files
changes.forEach((change) => pendingRebuilds.delete(change.file))

// Resolve the promise even when the rebuild fails
return rebuild(changes).then(
() => {},
(e) => {
console.error(e.toString())
}
)
running = true
try {
await rebuild(changes)
} catch (e) {
console.error(e.toString())
} finally {
running = false
}

if (changedFiles.size > 0) {
arm()
}
}

/**
Expand All @@ -115,33 +129,15 @@ export function createWatcher(args, { state, rebuild }) {
// It MUST happen synchronously before the rebuild is queued for this to be effective
pendingRebuilds.add(file)

changedContent.push({
changedFiles.set(file, {
file,
content: content ?? (() => fs.promises.readFile(file, 'utf8')),
extension: path.extname(file).slice(1),
Comment on lines +132 to 135

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Later events discard saved text

During a long rebuild, an atomic save can queue captured text, clear its pending flag, then emit change. This changedFiles.set() replaces the captured text with a deferred fs.promises.readFile call. If the user moves or deletes the file before the next rebuild, that read fails and parseChanges() rejects the entire batch, dropping updates from other files too. Previously, the pending flag blocked that replacement. Keep a safe snapshot when later events update the queued entry.

})

if (_timer) {
clearTimeout(_timer)
_reject()
}
arm()

// If a rebuild is already in progress we don't want to start another one until the 10ms timer has expired
chain = chain.then(
() =>
new Promise((resolve, reject) => {
_timer = setTimeout(resolve, 10)
_reject = reject
})
)

// Resolves once this file has been rebuilt (or the rebuild for this file has failed)
// This queues as many rebuilds as there are changed files
// But those rebuilds happen after some delay
// And will immediately resolve if there are no changes
chain = chain.then(rebuildAndContinue, rebuildAndContinue)

return chain
return Promise.resolve()
}

watcher.on('change', (file) => recordChangedFile(file))
Expand Down Expand Up @@ -184,23 +180,17 @@ export function createWatcher(args, { state, rebuild }) {
return
}

// We'll go ahead and add the file to the pending rebuilds list here
// It'll be removed when the rebuild starts unless the read fails
// which will be taken care of as well
pendingRebuilds.add(filePath)

async function enqueue() {
try {
// We need to read the file as early as possible outside of the chain
// because it may be gone by the time we get to it. doing the read
// immediately increases the chance that the file is still there
// The file may be gone by the time the rebuild runs.
let content = await readFileWithRetries(path.resolve(filePath))

if (content === undefined) {
return
}

// This will push the rebuild onto the chain
// We MUST skip the rebuild check here otherwise the rebuild will never happen on Linux
// This is because the order of events and timing is different on Linux
// @ts-ignore: TypeScript isn't picking up that content is a string here
Expand Down
145 changes: 145 additions & 0 deletions tests/watching.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
import fs from 'fs'
import os from 'os'
import path from 'path'
import { createWatcher } from '../src/cli/build/watching'

let tmp
let current
let releaseGate = () => {}

beforeEach(() => {
tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'tw-watch-'))
})

afterEach(async () => {
releaseGate()
releaseGate = () => {}
await current?.fswatcher.close()
current = undefined
fs.rmSync(tmp, { recursive: true, force: true })
})

function write(name, text) {
let file = path.join(tmp, name)
fs.writeFileSync(file, text)
return file
}

function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms))
}

async function waitFor(predicate) {
let started = Date.now()
while (!predicate()) {
if (Date.now() - started > 5000) {
throw new Error('timed out waiting for the watcher')
}
await delay(10)
}
}

function watch(rebuild) {
current = createWatcher(
{},
{
state: {
contentPatterns: {
all: [path.join(tmp, '**/*')],
dynamic: [path.join(tmp, '**/*')],
},
contextDependencies: new Set(),
configBag: { dependencies: new Set() },
},
rebuild,
}
)

return current
}

async function readChanges(changes) {
let read = []
for (let change of changes) {
read.push({
file: change.file,
extension: change.extension,
content: await change.content(),
})
}
return read
}

function holdFirstRebuild() {
let calls = []
let markStarted
let started = new Promise((resolve) => {
markStarted = resolve
})
let gate = new Promise((resolve) => {
releaseGate = resolve
})

watch(async (changes) => {
calls.push(await readChanges(changes))
if (calls.length === 1) {
markStarted()
await gate
}
})

return { calls, started }
}

test('repeated change events during a rebuild still coalesce into one follow-up read', async () => {
let { calls, started } = holdFirstRebuild()
let page = write('page.html', 'initial')
let view = write('view.html', 'initial')

current.fswatcher.emit('change', page)
await started

for (let i = 0; i < 20; i++) {
fs.writeFileSync(page, `page ${i}`)
fs.writeFileSync(view, `view ${i}`)
current.fswatcher.emit('change', page)
current.fswatcher.emit('change', view)
}
releaseGate()

await waitFor(() => calls.length >= 2)
await delay(80)

expect(calls).toHaveLength(2)
expect(calls[1]).toEqual([
{ file: path.resolve(page), extension: 'html', content: 'page 19' },
{ file: path.resolve(view), extension: 'html', content: 'view 19' },
])
})

test('rename events during a rebuild keep each file once, with its latest text', async () => {
let { calls, started } = holdFirstRebuild()
let page = write('page.html', 'seed')
let view = write('view.html', 'seed')

current.fswatcher.emit('change', page)
await started

for (let i = 0; i < 8; i++) {
fs.writeFileSync(page, `page ${i}`)
fs.writeFileSync(view, `view ${i}`)
current.fswatcher.emit('raw', 'rename', page, { watchedPath: page })
current.fswatcher.emit('raw', 'rename', view, { watchedPath: view })
await delay(30)
}
releaseGate()

await waitFor(() => calls.length >= 2)
await delay(80)

expect(calls).toHaveLength(2)
expect(calls[1]).toEqual([
{ file: path.resolve(page), extension: 'html', content: 'page 7' },
{ file: path.resolve(view), extension: 'html', content: 'view 7' },
])
})