UNPKG

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