UNPKG

3.03 kBJavaScriptView Raw
1const path = require('path')
2const sum = require('hash-sum')
3const paths = require('./paths')
4const store = require('./store')
5const SherryError = require('./SherryError')
6const isLocalPath = require('./utils/isLocalPath')
7const { escapeDots } = require('./utils/common')
8const { SHERRY_MODULE_PREFIX } = require('./env')
9
10/**
11 *
12 * @param {string} generator
13 * @return {Object}
14 */
15module.exports = generator => {
16 if (isLocalPath(generator)) {
17 let subGenerator
18 if (isLocalPath.removePrefix(generator).includes(':')) {
19 subGenerator = generator.slice(generator.lastIndexOf(':') + 1)
20 generator = generator.slice(0, generator.lastIndexOf(':'))
21 }
22 const absolutePath = path.resolve(generator)
23 return {
24 type: 'local',
25 path: absolutePath,
26 hash: sum(absolutePath),
27 subGenerator
28 }
29 }
30
31 const SPECIAL_PREFIX_RE = /^(npm|github|bitbucket|gitlab|alias):/
32
33 if (!SPECIAL_PREFIX_RE.test(generator) && !generator.includes('/')) {
34 generator = `npm:${SHERRY_MODULE_PREFIX}-${generator}`
35 }
36
37 /** @type {string|null} */
38 let type = null
39 if (SPECIAL_PREFIX_RE.test(generator)) {
40 type = SPECIAL_PREFIX_RE.exec(generator)[1]
41 generator = generator.replace(SPECIAL_PREFIX_RE, '')
42 }
43
44 if (type === 'npm') {
45 const hasSubGenerator = generator.indexOf(':') !== -1
46 const slug = generator.slice(
47 0,
48 hasSubGenerator ? generator.indexOf(':') : generator.length
49 )
50 const parsed = require('parse-package-name')(slug)
51 const hash = sum(`npm:${slug}`)
52 return {
53 type: 'npm',
54 name: parsed.name,
55 version: parsed.version,
56 slug,
57 subGenerator:
58 hasSubGenerator && generator.slice(generator.indexOf(':') + 1),
59 hash,
60 path: path.join(paths.packagePath, hash, 'node_modules', parsed.name)
61 }
62 }
63
64 if (type === 'alias') {
65 const hasSubGenerator = generator.indexOf(':') !== -1
66 const alias = generator.slice(
67 0,
68 hasSubGenerator ? generator.indexOf(':') : generator.length
69 )
70 const url = store.get(`alias.${escapeDots(alias)}`)
71 if (!url) {
72 throw new SherryError(`Cannot find alias '${alias}'`)
73 }
74 if (isLocalPath(url)) {
75 return {
76 type: 'local',
77 path: url,
78 subGenerator:
79 hasSubGenerator && generator.slice(generator.indexOf(':') + 1),
80 hash: sum(url)
81 }
82 }
83 const slug = `direct:${url}`
84 const hash = sum(`repo:${slug}`)
85 return {
86 type: 'repo',
87 slug,
88 subGenerator:
89 hasSubGenerator && generator.slice(generator.indexOf(':') + 1),
90 hash,
91 path: path.join(paths.repoPath, hash)
92 }
93 }
94
95 const [
96 ,
97 user,
98 repo,
99 version,
100 subGenerator
101 ] = /([^/]+)\/([^#:]+)(?:#(.+))?(?::(.+))?$/.exec(generator)
102 const slug = `${type ? `${type}:` : ''}${user}/${repo}${
103 version ? `#${version}` : ''
104 }`
105 const hash = sum(`repo:${slug}`)
106 return {
107 type: 'repo',
108 slug,
109 subGenerator,
110 hash,
111 path: path.join(paths.repoPath, hash)
112 }
113}