Skip to content

Commit 6ffc63c

Browse files
committed
refactor(@angular/build): simplify watch-mode asset precedence and ignore normalization
Simplify incremental asset precedence checks in `collectAssetsToEmit` by relying on in-memory `emittedAssets` state rather than redundant filesystem `statSync` calls, and index emitted asset sources by output path in `BuilderState` for O(1) eviction. Also expand wildcard-suffixed ignore patterns so both direct files and nested directory contents are ignored in watch mode.
1 parent 193abc0 commit 6ffc63c

3 files changed

Lines changed: 63 additions & 89 deletions

File tree

‎packages/angular/build/src/builders/library/builder-state.ts‎

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ export class BuilderState {
3737
#emittedBundleFiles = new Set<string>();
3838
#emittedManifestFiles = new Set<string>();
3939
readonly #emittedAssets = new Map<string, Set<string>>();
40+
readonly #emittedAssetSources = new Map<string, string>();
4041
#hasEmittedAssets = false;
4142

4243
#executionResult = new ExecutionResult();
@@ -421,13 +422,13 @@ export class BuilderState {
421422
continue;
422423
}
423424

424-
if (this.#hasEmittedAssets) {
425-
for (const [source, prevOutputs] of this.#emittedAssets) {
426-
if (prevOutputs.delete(emittedAsset.path)) {
427-
if (prevOutputs.size === 0) {
428-
this.#emittedAssets.delete(source);
429-
}
430-
break;
425+
const prevSource = this.#emittedAssetSources.get(emittedAsset.path);
426+
if (prevSource !== undefined) {
427+
const prevOutputs = this.#emittedAssets.get(prevSource);
428+
if (prevOutputs) {
429+
prevOutputs.delete(emittedAsset.path);
430+
if (prevOutputs.size === 0) {
431+
this.#emittedAssets.delete(prevSource);
431432
}
432433
}
433434
}
@@ -437,12 +438,14 @@ export class BuilderState {
437438
this.#emittedAssets.set(emittedAsset.source, outputs);
438439
}
439440
outputs.add(emittedAsset.path);
441+
this.#emittedAssetSources.set(emittedAsset.path, emittedAsset.source);
440442
}
441443

442444
for (const source of toDelete) {
443445
const outputs = this.#emittedAssets.get(source);
444446
if (outputs) {
445447
for (const output of outputs) {
448+
this.#emittedAssetSources.delete(output);
446449
filesToDelete.add(output);
447450
}
448451
this.#emittedAssets.delete(source);
@@ -481,6 +484,7 @@ export class BuilderState {
481484
this.#emittedBundleFiles.clear();
482485
this.#emittedManifestFiles.clear();
483486
this.#emittedAssets.clear();
487+
this.#emittedAssetSources.clear();
484488
this.#hasUpdatedBundles = false;
485489
}
486490
}

‎packages/angular/build/src/builders/library/pipeline/assets.ts‎

Lines changed: 36 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -43,15 +43,20 @@ export interface AssetMatcher {
4343
* expanding directory patterns with `/**`, and normalizing POSIX segments.
4444
*
4545
* @param pattern The raw glob pattern string.
46-
* @returns The normalized POSIX glob pattern.
46+
* @returns The normalized POSIX glob pattern(s).
4747
*/
48-
function normalizeGlobPattern(pattern: string): string {
49-
let result = pattern.endsWith('/') ? pattern.slice(0, -1) : pattern;
50-
if (pattern.endsWith('/') || !result.endsWith('*')) {
51-
result += '/**';
48+
function normalizeGlobPattern(pattern: string): string | string[] {
49+
const trimmed = pattern.endsWith('/') ? pattern.slice(0, -1) : pattern;
50+
if (!trimmed.endsWith('*')) {
51+
return path.posix.normalize(`${trimmed}/**`);
5252
}
5353

54-
return path.posix.normalize(result);
54+
const normalized = path.posix.normalize(trimmed);
55+
if (normalized === '**' || normalized.endsWith('/**')) {
56+
return normalized;
57+
}
58+
59+
return [normalized, `${normalized}/**`];
5560
}
5661

5762
/**
@@ -90,7 +95,7 @@ export function createAssetMatchers(assets: NormalizedAssetsPattern[]): readonly
9095
const { glob: rawGlob, ignore: rawIgnore, input } = asset;
9196
const ignore = [...DEFAULT_ASSET_IGNORE, ...(rawIgnore ?? [])]
9297
.filter((pattern) => pattern.length > 0)
93-
.map(normalizeGlobPattern);
98+
.flatMap(normalizeGlobPattern);
9499
const isMatch = picomatch(rawGlob ? path.posix.normalize(rawGlob) : [], {
95100
dot: true,
96101
windows: false,
@@ -186,77 +191,48 @@ export async function collectAssetsToEmit(
186191
}
187192

188193
if (matchers.length > 1) {
189-
// Ensure lower-priority modified assets do not overwrite existing higher-priority assets on disk.
194+
// Ensure lower-priority modified assets do not overwrite existing higher-priority assets.
190195
for (const [outputPath, { file, matcherIndex }] of filesToEmit) {
191196
for (let laterIndex = matchers.length - 1; laterIndex > matcherIndex; laterIndex--) {
192-
const laterMatcher = matchers[laterIndex];
193-
const candidateFile = getCandidateSourceForOutput(laterMatcher, outputPath);
194-
if (!candidateFile || candidateFile === file.source) {
195-
continue;
196-
}
197-
198-
if (isMatchingAssetFile(candidateFile, laterMatcher.asset.followSymlinks)) {
199-
if (emittedAssets.get(candidateFile)?.has(outputPath)) {
200-
filesToEmit.delete(outputPath);
201-
} else {
202-
filesToEmit.set(outputPath, {
203-
file: createDiskOutputFile(candidateFile, outputPath),
204-
matcherIndex: laterIndex,
205-
});
206-
}
197+
const candidateFile = getCandidateSourceForOutput(matchers[laterIndex], outputPath);
198+
if (
199+
candidateFile &&
200+
candidateFile !== file.source &&
201+
!filesToDelete.has(candidateFile) &&
202+
emittedAssets.get(candidateFile)?.has(outputPath)
203+
) {
204+
filesToEmit.delete(outputPath);
207205
break;
208-
} else if (emittedAssets.get(candidateFile)?.has(outputPath)) {
209-
filesToDelete.add(candidateFile);
210206
}
211207
}
212208
}
213209

214210
// Restore lower-priority fallback assets when a higher-priority overriding asset is deleted.
215211
for (const deletedFile of filesToDelete) {
216-
for (
217-
let deletedMatcherIndex = 0;
218-
deletedMatcherIndex < matchers.length;
219-
deletedMatcherIndex++
220-
) {
221-
const { asset, prefix, isMatch } = matchers[deletedMatcherIndex];
222-
if (!deletedFile.startsWith(prefix)) {
223-
continue;
224-
}
225-
226-
const relative = deletedFile.slice(prefix.length);
227-
if (!isMatch(relative)) {
228-
continue;
229-
}
230-
231-
const outputPath = path.posix.join(asset.output, relative);
232-
if (filesToEmit.has(outputPath)) {
233-
continue;
234-
}
235-
236-
for (let candidateIndex = matchers.length - 1; candidateIndex >= 0; candidateIndex--) {
237-
if (candidateIndex === deletedMatcherIndex) {
238-
continue;
239-
}
212+
const deletedOutputs = emittedAssets.get(deletedFile);
213+
if (!deletedOutputs) {
214+
continue;
215+
}
240216

217+
for (const outputPath of deletedOutputs) {
218+
const minCandidateIndex = (filesToEmit.get(outputPath)?.matcherIndex ?? -1) + 1;
219+
for (
220+
let candidateIndex = matchers.length - 1;
221+
candidateIndex >= minCandidateIndex;
222+
candidateIndex--
223+
) {
241224
const candidateMatcher = matchers[candidateIndex];
242225
const candidateFile = getCandidateSourceForOutput(candidateMatcher, outputPath);
243226
if (!candidateFile || filesToDelete.has(candidateFile)) {
244227
continue;
245228
}
246229

247230
if (isMatchingAssetFile(candidateFile, candidateMatcher.asset.followSymlinks)) {
248-
if (
249-
candidateIndex < deletedMatcherIndex ||
250-
!emittedAssets.get(candidateFile)?.has(outputPath)
251-
) {
252-
filesToEmit.set(outputPath, {
253-
file: createDiskOutputFile(candidateFile, outputPath),
254-
matcherIndex: candidateIndex,
255-
});
256-
}
231+
filesToEmit.set(outputPath, {
232+
file: createDiskOutputFile(candidateFile, outputPath),
233+
matcherIndex: candidateIndex,
234+
});
257235
break;
258-
} else if (emittedAssets.get(candidateFile)?.has(outputPath)) {
259-
filesToDelete.add(candidateFile);
260236
}
261237
}
262238
}

‎packages/angular/build/src/builders/library/pipeline/assets_spec.ts‎

Lines changed: 16 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ describe('library pipeline assets', () => {
3838
'./ignored-dir-2/',
3939
'**/ignored-subdir',
4040
'{brace-dir-a,brace-dir-b}',
41+
'wildcard-parent/*/',
4142
'specific.txt',
4243
],
4344
},
@@ -58,6 +59,9 @@ describe('library pipeline assets', () => {
5859
expect(matcher.isMatch('nested/ignored-subdir/deep/file.txt')).toBeFalse();
5960
expect(matcher.isMatch('brace-dir-a/file.txt')).toBeFalse();
6061
expect(matcher.isMatch('brace-dir-b/sub/file.txt')).toBeFalse();
62+
expect(matcher.isMatch('wildcard-parent/file.txt')).toBeFalse();
63+
expect(matcher.isMatch('wildcard-parent/sub/file.txt')).toBeFalse();
64+
expect(matcher.isMatch('wildcard-parent/sub/deep/file.txt')).toBeFalse();
6165
expect(matcher.isMatch('.gitkeep')).toBeFalse();
6266
expect(matcher.isMatch('nested/.DS_Store')).toBeFalse();
6367
});
@@ -121,17 +125,22 @@ describe('library pipeline assets', () => {
121125

122126
it('should not overwrite a higher-priority emitted asset when only a lower-priority asset is modified in watch mode', async () => {
123127
const defaultDir = `${tempRoot}/lib`;
128+
const fallbackDir = `${tempRoot}/fallback`;
124129
const customDir = `${tempRoot}/docs`;
125130
await mkdir(defaultDir, { recursive: true });
131+
await mkdir(fallbackDir, { recursive: true });
126132
await mkdir(customDir, { recursive: true });
127133

128134
const defaultReadme = `${defaultDir}/README.md`;
135+
const fallbackReadme = `${fallbackDir}/README.md`;
129136
const customReadme = `${customDir}/README.md`;
130137
await writeFile(defaultReadme, '# Default updated');
138+
await writeFile(fallbackReadme, '# Fallback');
131139
await writeFile(customReadme, '# Custom');
132140

133141
const assets = [
134142
{ glob: 'README.md', input: defaultDir, output: '.' },
143+
{ glob: 'README.md', input: fallbackDir, output: '.' },
135144
{ glob: 'README.md', input: customDir, output: '.' },
136145
];
137146

@@ -146,35 +155,20 @@ describe('library pipeline assets', () => {
146155
expect(resultWithEmitted.filesToEmit).toEqual([]);
147156
expect(resultWithEmitted.filesToDelete).toEqual([]);
148157

149-
// When customReadme was not yet recorded in emittedAssets, modifying defaultReadme should emit customReadme.
150-
const resultWithoutEmitted = await collectAssetsToEmit(
151-
assets,
152-
tempRoot,
153-
new Map(),
154-
new Set([defaultReadme]),
155-
);
156-
expect(resultWithoutEmitted.filesToEmit).toEqual([
157-
{
158-
origin: 'disk',
159-
source: customReadme,
160-
path: 'README.md',
161-
},
162-
]);
163-
164-
// When customReadme was recorded in emittedAssets but no longer exists on disk,
165-
// modifying defaultReadme should queue customReadme for deletion and emit defaultReadme.
158+
// When customReadme is deleted in the same watch iteration while defaultReadme is modified,
159+
// customReadme should be queued for deletion and higher-priority fallbackReadme should be emitted.
166160
await rm(customReadme);
167-
const resultWithMissingHigherPriority = await collectAssetsToEmit(
161+
const resultWithDeletedHigherPriority = await collectAssetsToEmit(
168162
assets,
169163
tempRoot,
170164
emittedAssets,
171-
new Set([defaultReadme]),
165+
new Set([defaultReadme, customReadme]),
172166
);
173-
expect(resultWithMissingHigherPriority.filesToDelete).toEqual([customReadme]);
174-
expect(resultWithMissingHigherPriority.filesToEmit).toEqual([
167+
expect(resultWithDeletedHigherPriority.filesToDelete).toEqual([customReadme]);
168+
expect(resultWithDeletedHigherPriority.filesToEmit).toEqual([
175169
{
176170
origin: 'disk',
177-
source: defaultReadme,
171+
source: fallbackReadme,
178172
path: 'README.md',
179173
},
180174
]);

0 commit comments

Comments
 (0)