1 | const { homedir } = require('os')
|
2 | const { resolve, join, sep } = require('path')
|
3 | const { cwd: getCwd } = require('process')
|
4 |
|
5 | const { getCacheDir } = require('./dir')
|
6 |
|
7 |
|
8 | const parsePath = async function(path, cacheDir) {
|
9 | const srcPath = getSrcPath(path)
|
10 | const cachePath = await getCachePath(srcPath, cacheDir)
|
11 | return { srcPath, cachePath }
|
12 | }
|
13 |
|
14 |
|
15 | const getSrcPath = function(path) {
|
16 | const cwd = getCwd()
|
17 | const srcPath = resolve(cwd, path)
|
18 | checkSrcPath(srcPath, cwd)
|
19 | return srcPath
|
20 | }
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 | const checkSrcPath = function(srcPath, cwd) {
|
31 | if (isParentPath(srcPath, cwd)) {
|
32 | throw new Error(`Cannot cache ${srcPath} because it is the current directory (${cwd}) or a parent directory`)
|
33 | }
|
34 | }
|
35 |
|
36 |
|
37 | const isParentPath = function(srcPath, cwd) {
|
38 | return `${cwd}${sep}`.startsWith(`${srcPath}${sep}`)
|
39 | }
|
40 |
|
41 | const getCachePath = async function(srcPath, cacheDir) {
|
42 | const cacheDirA = await getCacheDir(cacheDir)
|
43 | const { name, relPath } = findBase(srcPath)
|
44 | const cachePath = join(cacheDirA, name, relPath)
|
45 | return cachePath
|
46 | }
|
47 |
|
48 |
|
49 |
|
50 |
|
51 | const findBase = function(srcPath) {
|
52 | const srcPathA = normalizeWindows(srcPath)
|
53 | return BASES.map(({ name, base }) => parseBase(name, base, srcPathA)).find(Boolean)
|
54 | }
|
55 |
|
56 |
|
57 |
|
58 |
|
59 |
|
60 |
|
61 |
|
62 |
|
63 |
|
64 |
|
65 |
|
66 | const normalizeWindows = function(srcPath) {
|
67 | return srcPath.replace(WINDOWS_DRIVE_REGEX, '\\')
|
68 | }
|
69 |
|
70 | const WINDOWS_DRIVE_REGEX = /^[a-zA-Z]:\\/
|
71 |
|
72 |
|
73 | const parseBase = function(name, base, srcPath) {
|
74 | if (srcPath === base || !srcPath.startsWith(base)) {
|
75 | return
|
76 | }
|
77 |
|
78 | const relPath = srcPath.replace(base, '')
|
79 | return { name, relPath }
|
80 | }
|
81 |
|
82 | const BASES = [
|
83 | { name: 'cwd', base: getCwd() },
|
84 | { name: 'home', base: homedir() },
|
85 | { name: 'root', base: sep },
|
86 | ]
|
87 |
|
88 | module.exports = { parsePath, BASES }
|