-
Notifications
You must be signed in to change notification settings - Fork 12k
/
Copy pathnormalize-file-replacements.ts
70 lines (60 loc) · 1.91 KB
/
normalize-file-replacements.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
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { BaseException } from '@angular-devkit/core';
import { existsSync } from 'fs';
import * as path from 'path';
import { FileReplacement } from '../builders/browser/schema';
export class MissingFileReplacementException extends BaseException {
constructor(path: String) {
super(`The ${path} path in file replacements does not exist.`);
}
}
export interface NormalizedFileReplacement {
replace: string;
with: string;
}
export function normalizeFileReplacements(
fileReplacements: FileReplacement[],
workspaceRoot: string,
): NormalizedFileReplacement[] {
if (fileReplacements.length === 0) {
return [];
}
const normalizedReplacement = fileReplacements.map((replacement) =>
normalizeFileReplacement(replacement, workspaceRoot),
);
for (const { replace, with: replacementWith } of normalizedReplacement) {
if (!existsSync(replacementWith)) {
throw new MissingFileReplacementException(replacementWith);
}
if (!existsSync(replace)) {
throw new MissingFileReplacementException(replace);
}
}
return normalizedReplacement;
}
function normalizeFileReplacement(
fileReplacement: FileReplacement,
root: string,
): NormalizedFileReplacement {
let replacePath: string;
let withPath: string;
if (fileReplacement.src && fileReplacement.replaceWith) {
replacePath = fileReplacement.src;
withPath = fileReplacement.replaceWith;
} else if (fileReplacement.replace && fileReplacement.with) {
replacePath = fileReplacement.replace;
withPath = fileReplacement.with;
} else {
throw new Error(`Invalid file replacement: ${JSON.stringify(fileReplacement)}`);
}
return {
replace: path.join(root, replacePath),
with: path.join(root, withPath),
};
}