|
| 1 | +/** |
| 2 | + * @license |
| 3 | + * Copyright Google LLC All Rights Reserved. |
| 4 | + * |
| 5 | + * Use of this source code is governed by an MIT-style license that can be |
| 6 | + * found in the LICENSE file at https://angular.io/license |
| 7 | + */ |
| 8 | + |
| 9 | +import { BuilderContext } from '@angular-devkit/architect'; |
| 10 | +import { PathLike, existsSync, promises as fsPromises } from 'fs'; |
| 11 | +import { join } from 'path'; |
| 12 | +import { normalizeCacheOptions } from './normalize-cache'; |
| 13 | + |
| 14 | +/** Delete stale cache directories used by previous versions of build-angular. */ |
| 15 | +export async function purgeStaleBuildCache(context: BuilderContext): Promise<void> { |
| 16 | + const projectName = context.target?.project; |
| 17 | + if (!projectName) { |
| 18 | + return; |
| 19 | + } |
| 20 | + |
| 21 | + const metadata = await context.getProjectMetadata(projectName); |
| 22 | + const { basePath, path, enabled } = normalizeCacheOptions(metadata, context.workspaceRoot); |
| 23 | + |
| 24 | + if (!enabled || !existsSync(basePath)) { |
| 25 | + return; |
| 26 | + } |
| 27 | + |
| 28 | + // The below should be removed and replaced with just `rm` when support for Node.Js 12 is removed. |
| 29 | + const { rm, rmdir } = fsPromises as typeof fsPromises & { |
| 30 | + rm?: ( |
| 31 | + path: PathLike, |
| 32 | + options?: { |
| 33 | + force?: boolean; |
| 34 | + maxRetries?: number; |
| 35 | + recursive?: boolean; |
| 36 | + retryDelay?: number; |
| 37 | + }, |
| 38 | + ) => Promise<void>; |
| 39 | + }; |
| 40 | + |
| 41 | + const entriesToDelete = (await fsPromises.readdir(basePath, { withFileTypes: true })) |
| 42 | + .filter((d) => join(basePath, d.name) !== path && d.isDirectory()) |
| 43 | + .map((d) => { |
| 44 | + const subPath = join(basePath, d.name); |
| 45 | + try { |
| 46 | + return rm |
| 47 | + ? rm(subPath, { force: true, recursive: true, maxRetries: 3 }) |
| 48 | + : rmdir(subPath, { recursive: true, maxRetries: 3 }); |
| 49 | + } catch {} |
| 50 | + }); |
| 51 | + |
| 52 | + await Promise.all(entriesToDelete); |
| 53 | +} |
0 commit comments