1 | import * as fs from 'fs-extra'
|
2 | import * as path from 'path'
|
3 |
|
4 | export function getRootPath (): string {
|
5 | return path.resolve(__dirname, '../../')
|
6 | }
|
7 |
|
8 | export function getPkgVersion (): string {
|
9 | return require(path.join(getRootPath(), 'package.json')).version
|
10 | }
|
11 |
|
12 | export function getPkgItemByKey (key: string) {
|
13 | const packageMap = require(path.join(getRootPath(), 'package.json'))
|
14 | if (Object.keys(packageMap).indexOf(key) === -1) {
|
15 | return {}
|
16 | } else {
|
17 | return packageMap[key]
|
18 | }
|
19 | }
|
20 |
|
21 | export function printPkgVersion () {
|
22 | const taroVersion = getPkgVersion()
|
23 | console.log(`👽 Taro v${taroVersion}`)
|
24 | console.log()
|
25 | }
|
26 |
|
27 | export const getAllFilesInFloder = async (
|
28 | floder: string,
|
29 | filter: string[] = []
|
30 | ): Promise<string[]> => {
|
31 | let files: string[] = []
|
32 | const list = readDirWithFileTypes(floder)
|
33 |
|
34 | await Promise.all(
|
35 | list.map(async item => {
|
36 | const itemPath = path.join(floder, item.name)
|
37 | if (item.isDirectory) {
|
38 | const _files = await getAllFilesInFloder(itemPath, filter)
|
39 | files = [...files, ..._files]
|
40 | } else if (item.isFile) {
|
41 | if (!filter.find(rule => rule === item.name)) files.push(itemPath)
|
42 | }
|
43 | })
|
44 | )
|
45 |
|
46 | return files
|
47 | }
|
48 |
|
49 | export type TemplateSourceType = 'git' | 'url'
|
50 |
|
51 | export function getTemplateSourceType (url: string): TemplateSourceType {
|
52 | if (/^github:/.test(url) || /^gitlab:/.test(url) || /^direct:/.test(url)) {
|
53 | return 'git'
|
54 | } else {
|
55 | return 'url'
|
56 | }
|
57 | }
|
58 |
|
59 | interface FileStat {
|
60 | name: string
|
61 | isDirectory: boolean
|
62 | isFile: boolean
|
63 | }
|
64 |
|
65 | export function readDirWithFileTypes (floder: string): FileStat[] {
|
66 | const list = fs.readdirSync(floder)
|
67 | const res = list.map(name => {
|
68 | const stat = fs.statSync(path.join(floder, name))
|
69 | return {
|
70 | name,
|
71 | isDirectory: stat.isDirectory(),
|
72 | isFile: stat.isFile()
|
73 | }
|
74 | })
|
75 | return res
|
76 | }
|
77 |
|
78 | export function recursiveReplaceObjectKeys (obj, keyMap) {
|
79 | Object.keys(obj).forEach(key => {
|
80 | if (keyMap[key]) {
|
81 | obj[keyMap[key]] = obj[key]
|
82 | if (typeof obj[key] === 'object') {
|
83 | recursiveReplaceObjectKeys(obj[keyMap[key]], keyMap)
|
84 | }
|
85 | delete obj[key]
|
86 | } else if (keyMap[key] === false) {
|
87 | delete obj[key]
|
88 | } else if (typeof obj[key] === 'object') {
|
89 | recursiveReplaceObjectKeys(obj[key], keyMap)
|
90 | }
|
91 | })
|
92 | }
|