forked from angular/angular-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnormalize-file-replacements.ts
74 lines (63 loc) · 2.12 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
71
72
73
74
/**
* @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, Path, getSystemPath, join, normalize } from '@angular-devkit/core';
import { existsSync } from 'fs';
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: Path;
with: Path;
}
export function normalizeFileReplacements(
fileReplacements: FileReplacement[],
root: Path,
): NormalizedFileReplacement[] {
if (fileReplacements.length === 0) {
return [];
}
const normalizedReplacement = fileReplacements.map((replacement) =>
normalizeFileReplacement(replacement, root),
);
for (const { replace, with: replacementWith } of normalizedReplacement) {
if (!existsSync(getSystemPath(replacementWith))) {
throw new MissingFileReplacementException(getSystemPath(replacementWith));
}
if (!existsSync(getSystemPath(replace))) {
throw new MissingFileReplacementException(getSystemPath(replace));
}
}
return normalizedReplacement;
}
function normalizeFileReplacement(
fileReplacement: FileReplacement,
root?: Path,
): NormalizedFileReplacement {
let replacePath: Path;
let withPath: Path;
if (fileReplacement.src && fileReplacement.replaceWith) {
replacePath = normalize(fileReplacement.src);
withPath = normalize(fileReplacement.replaceWith);
} else if (fileReplacement.replace && fileReplacement.with) {
replacePath = normalize(fileReplacement.replace);
withPath = normalize(fileReplacement.with);
} else {
throw new Error(`Invalid file replacement: ${JSON.stringify(fileReplacement)}`);
}
// TODO: For 7.x should this only happen if not absolute?
if (root) {
replacePath = join(root, replacePath);
}
if (root) {
withPath = join(root, withPath);
}
return { replace: replacePath, with: withPath };
}