-
Notifications
You must be signed in to change notification settings - Fork 682
Expand file tree
/
Copy pathDeleteFilesPlugin.ts
More file actions
174 lines (155 loc) · 5.92 KB
/
DeleteFilesPlugin.ts
File metadata and controls
174 lines (155 loc) · 5.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
import type * as fs from 'node:fs';
import { FileSystem, Async } from '@rushstack/node-core-library';
import type { ITerminal } from '@rushstack/terminal';
import { Constants } from '../utilities/Constants';
import {
getFileSelectionSpecifierPathsAsync,
asAbsoluteFileSelectionSpecifier,
type IFileSelectionSpecifier
} from './FileGlobSpecifier';
import type { HeftConfiguration } from '../configuration/HeftConfiguration';
import type { IHeftTaskPlugin } from '../pluginFramework/IHeftPlugin';
import type { IHeftTaskSession, IHeftTaskFileOperations } from '../pluginFramework/HeftTaskSession';
import type {
DeleteFilesHeftTaskEventOptions as IDeleteFilesPluginOptions,
DeleteOperationBase as IDeleteOperationBase
} from '../schemas/delete-files-options.schema.json.d.ts';
/**
* @internal
*/
export type { IDeleteOperationBase };
/**
* Used to specify a selection of source files to delete from the specified source folder.
*
* @public
*/
export interface IDeleteOperation extends IFileSelectionSpecifier, IDeleteOperationBase {}
interface IGetPathsToDeleteResult {
filesToDelete: Set<string>;
foldersToDelete: Set<string>;
}
async function _getPathsToDeleteAsync(
rootFolderPath: string,
deleteOperations: Iterable<IDeleteOperation>
): Promise<IGetPathsToDeleteResult> {
const result: IGetPathsToDeleteResult = {
filesToDelete: new Set<string>(),
foldersToDelete: new Set<string>()
};
await Async.forEachAsync(
deleteOperations,
async (deleteOperation: IDeleteOperation) => {
const absoluteSpecifier: IDeleteOperation = asAbsoluteFileSelectionSpecifier(
rootFolderPath,
deleteOperation
);
// Glob the files under the source path and add them to the set of files to delete
const sourcePaths: Map<string, fs.Dirent> = await getFileSelectionSpecifierPathsAsync({
fileGlobSpecifier: absoluteSpecifier,
includeFolders: true
});
for (const [sourcePath, dirent] of sourcePaths) {
// If the sourcePath is a folder, add it to the foldersToDelete set. Otherwise, add it to
// the filesToDelete set. Symlinks and junctions are treated as files, and thus will fall
// into the filesToDelete set.
if (dirent.isDirectory()) {
result.foldersToDelete.add(sourcePath);
} else {
result.filesToDelete.add(sourcePath);
}
}
},
{ concurrency: Constants.maxParallelism }
);
return result;
}
export async function deleteFilesAsync(
rootFolderPath: string,
deleteOperations: Iterable<IDeleteOperation>,
terminal: ITerminal
): Promise<void> {
const pathsToDelete: IGetPathsToDeleteResult = await _getPathsToDeleteAsync(
rootFolderPath,
deleteOperations
);
await _deleteFilesInnerAsync(pathsToDelete, terminal);
}
async function _deleteFilesInnerAsync(
pathsToDelete: IGetPathsToDeleteResult,
terminal: ITerminal
): Promise<void> {
let deletedFiles: number = 0;
let deletedFolders: number = 0;
const { filesToDelete, foldersToDelete } = pathsToDelete;
await Async.forEachAsync(
filesToDelete,
async (pathToDelete: string) => {
try {
await FileSystem.deleteFileAsync(pathToDelete, { throwIfNotExists: true });
terminal.writeVerboseLine(`Deleted "${pathToDelete}".`);
deletedFiles++;
} catch (error) {
// If it doesn't exist, we can ignore the error.
if (!FileSystem.isNotExistError(error)) {
throw error;
}
}
},
{ concurrency: Constants.maxParallelism }
);
// Reverse the list of matching folders. Assuming that the list of folders came from
// the globber, the folders will be specified in tree-walk order, so by reversing the
// list we delete the deepest folders first and avoid not-exist errors for subfolders
// of an already-deleted parent folder.
const reversedFoldersToDelete: string[] = Array.from(foldersToDelete).reverse();
// Clear out any folders that were encountered during the file deletion process. This
// will recursively delete the folder and it's contents. There are two scenarios that
// this handles:
// - Deletions of empty folder structures (ex. when the delete glob is '**/*')
// - Deletions of folders that still contain files (ex. when the delete glob is 'lib')
// In the latter scenario, the count of deleted files will not be tracked. However,
// this is a fair trade-off for the performance benefit of not having to glob the
// folder structure again.
await Async.forEachAsync(
reversedFoldersToDelete,
async (folderToDelete: string) => {
try {
await FileSystem.deleteFolderAsync(folderToDelete);
terminal.writeVerboseLine(`Deleted folder "${folderToDelete}".`);
deletedFolders++;
} catch (error) {
// If it doesn't exist, we can ignore the error.
if (!FileSystem.isNotExistError(error)) {
throw error;
}
}
},
{ concurrency: Constants.maxParallelism }
);
if (deletedFiles > 0 || deletedFolders > 0) {
terminal.writeLine(
`Deleted ${deletedFiles} file${deletedFiles !== 1 ? 's' : ''} ` +
`and ${deletedFolders} folder${deletedFolders !== 1 ? 's' : ''}`
);
}
}
const PLUGIN_NAME: 'delete-files-plugin' = 'delete-files-plugin';
export default class DeleteFilesPlugin implements IHeftTaskPlugin<IDeleteFilesPluginOptions> {
public apply(
taskSession: IHeftTaskSession,
heftConfiguration: HeftConfiguration,
pluginOptions: IDeleteFilesPluginOptions
): void {
taskSession.hooks.registerFileOperations.tap(
PLUGIN_NAME,
(fileOperations: IHeftTaskFileOperations): IHeftTaskFileOperations => {
for (const deleteOperation of pluginOptions.deleteOperations) {
fileOperations.deleteOperations.add(deleteOperation);
}
return fileOperations;
}
);
}
}