UNPKG

1.88 kBJavaScriptView Raw
1var path = require('path');
2var process = require('process');
3var fs = require('fs');
4
5module.exports = function dynamicPathParser(project, entityName) {
6 var projectRoot = project.root;
7 var sourceDir = project.ngConfig.apps[0].root;
8 var appRoot = path.join(sourceDir, 'app');
9 var cwd = process.env.PWD;
10
11 var rootPath = path.join(projectRoot, appRoot);
12
13 var outputPath = path.join(rootPath, entityName);
14
15 if (entityName.indexOf(path.sep) === 0) {
16 outputPath = path.join(rootPath, entityName.substr(1));
17 } else if (cwd.indexOf(rootPath) >= 0) {
18 outputPath = path.join(cwd, entityName);
19 }
20
21 if (!fs.existsSync(outputPath)) {
22 // Verify the path exists on disk.
23 var parsedOutputPath = path.parse(outputPath);
24 var parts = parsedOutputPath.dir.split(path.sep).slice(1);
25 var newPath = parts.reduce((tempPath, part) => {
26 // if (tempPath === '') {
27 // return part;
28 // }
29 var withoutPlus = path.join(tempPath, path.sep, part);
30 var withPlus = path.join(tempPath, path.sep, '+' + part);
31 if (fs.existsSync(withoutPlus)) {
32 return withoutPlus;
33 } else if (fs.existsSync(withPlus)) {
34 return withPlus;
35 }
36
37 throw `Invalid path: "${withoutPlus}"" is not a valid path.`
38 }, parsedOutputPath.root);
39 outputPath = path.join(newPath, parsedOutputPath.name);
40 }
41
42 if (outputPath.indexOf(rootPath) < 0) {
43 throw `Invalid path: "${entityName}" cannot be ` +
44 `above the "${appRoot}" directory`;
45 }
46
47 var adjustedPath = outputPath.replace(projectRoot, '');
48
49 var parsedPath = path.parse(adjustedPath);
50
51 if (parsedPath.dir.indexOf(path.sep) === 0) {
52 parsedPath.dir = parsedPath.dir.substr(1);
53 }
54
55 parsedPath.dir = parsedPath.dir === path.sep ? '' : parsedPath.dir;
56 parsedPath.appRoot = appRoot;
57 parsedPath.sourceDir = sourceDir;
58
59 return parsedPath;
60};