-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
copy-assets-handler.ts
173 lines (158 loc) · 5.05 KB
/
copy-assets-handler.ts
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
import { logger } from '@nrwl/devkit';
import { AssetGlob } from '@nrwl/workspace/src/utilities/assets';
import type { Event } from '@parcel/watcher';
import * as fg from 'fast-glob';
import * as fse from 'fs-extra';
import { Ignore } from 'ignore';
import * as minimatch from 'minimatch';
import { createIgnore } from 'nx/src/utils/ignore';
import * as path from 'path';
export type FileEventType = 'create' | 'update' | 'delete';
export interface FileEvent {
type: FileEventType;
src: string;
dest: string;
}
interface CopyAssetHandlerOptions {
projectDir: string;
rootDir: string;
outputDir: string;
assets: (string | AssetGlob)[];
callback?: (events: FileEvent[]) => void;
}
interface AssetEntry {
isGlob: boolean;
pattern: string;
ignore: string[] | null;
input: string;
output: string;
}
export const defaultFileEventHandler = (events: FileEvent[]) => {
const dirs = new Set(events.map((event) => path.dirname(event.dest)));
dirs.forEach((d) => fse.ensureDirSync(d));
events.forEach((event) => {
if (event.type === 'create' || event.type === 'update') {
fse.copyFileSync(event.src, event.dest);
} else if (event.type === 'delete') {
fse.removeSync(event.dest);
} else {
logger.error(`Unknown file event: ${event.type}`);
}
});
};
export class CopyAssetsHandler {
private readonly projectDir: string;
private readonly rootDir: string;
private readonly outputDir: string;
private readonly assetGlobs: AssetEntry[];
private readonly ignore: Ignore;
private readonly callback: (events: FileEvent[]) => void;
constructor(opts: CopyAssetHandlerOptions) {
this.rootDir = opts.rootDir;
this.projectDir = opts.projectDir;
this.outputDir = opts.outputDir;
this.callback = opts.callback ?? defaultFileEventHandler;
this.ignore = createIgnore(opts.rootDir);
this.assetGlobs = opts.assets.map((f) => {
let isGlob = false;
let pattern: string;
// Input and output directories are normalized to be relative to root
let input: string;
let output: string;
let ignore: string[] | null = null;
if (typeof f === 'string') {
pattern = f;
input = path.relative(opts.rootDir, opts.projectDir);
output = path.relative(opts.rootDir, opts.outputDir);
} else {
isGlob = true;
pattern = path.join(f.input, f.glob);
input = f.input;
output = path.join(
path.relative(opts.rootDir, opts.outputDir),
f.output
);
if (f.ignore) ignore = f.ignore.map((ig) => path.join(f.input, ig));
}
return {
isGlob,
input,
pattern,
ignore,
output,
};
});
}
async processAllAssetsOnce(): Promise<void> {
await Promise.all(
this.assetGlobs.map(async (ag) => {
let pattern: string;
if (typeof ag === 'string') {
pattern = ag;
} else {
pattern = ag.pattern;
}
// fast-glob only supports Unix paths
const files = await fg(pattern.replace(/\\/g, '/'), {
cwd: this.rootDir,
dot: true, // enable hidden files
});
this.callback(
files.reduce((acc, src) => {
if (
!ag.ignore?.some((ig) => minimatch(src, ig)) &&
!this.ignore.ignores(src)
) {
const relPath = path.relative(ag.input, src);
const dest = relPath.startsWith('..') ? src : relPath;
acc.push({
type: 'create',
src: path.join(this.rootDir, src),
dest: path.join(this.rootDir, ag.output, dest),
});
}
return acc;
}, [])
);
})
);
}
async watchAndProcessOnAssetChange(): Promise<() => Promise<void>> {
const watcher = await import('@parcel/watcher');
const subscription = await watcher.subscribe(
this.rootDir,
(err, events) => {
if (err) {
logger.error(`Watch error: ${err?.message ?? 'Unknown'}`);
} else {
this.processEvents(events);
}
}
);
return () => subscription.unsubscribe();
}
private async processEvents(events: Event[]): Promise<void> {
const fileEvents: FileEvent[] = [];
for (const event of events) {
const pathFromRoot = path.relative(this.rootDir, event.path);
for (const ag of this.assetGlobs) {
if (
minimatch(pathFromRoot, ag.pattern) &&
!ag.ignore?.some((ig) => minimatch(pathFromRoot, ig)) &&
!this.ignore.ignores(pathFromRoot)
) {
const relPath = path.relative(ag.input, pathFromRoot);
const destPath = relPath.startsWith('..') ? pathFromRoot : relPath;
fileEvents.push({
type: event.type,
src: path.join(this.rootDir, pathFromRoot),
dest: path.join(this.rootDir, ag.output, destPath),
});
// Match first entry and skip the rest for this file.
break;
}
}
}
if (fileEvents.length > 0) this.callback(fileEvents);
}
}