-
Notifications
You must be signed in to change notification settings - Fork 18
/
core.js
248 lines (213 loc) · 5.94 KB
/
core.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
import spawn from 'cross-spawn'
import glob from 'fast-glob'
import micromatch from 'micromatch'
import { promises as fs } from 'node:fs'
import { basename, join } from 'node:path'
import IGNORE_FIELDS from './exception/ignore-fields.js'
import IGNORE_FILES from './exception/ignore-files.js'
import NPM_SCRIPTS from './exception/npm-scripts.js'
import {
copy,
filterObjectByKey,
isObject,
readJSON,
remove,
writeJSON
} from './utils.js'
// https://pnpm.io/package_json#publishconfig
const PUBLISH_CONFIG_FIELDS = [
'bin',
'main',
'exports',
'types',
'typings',
'module',
'browser',
'esnext',
'es2015',
'unpkg',
'umd:main',
'typesVersions',
'cpu',
'os'
]
export function readPackageJSON() {
return readJSON('package.json')
}
export function writePackageJSON(directoryName, packageJSON) {
return writeJSON(join(directoryName, 'package.json'), packageJSON)
}
function applyPublishConfig(packageJson) {
if (!packageJson.publishConfig) {
return packageJson
}
const publishConfig = {
...packageJson.publishConfig
}
PUBLISH_CONFIG_FIELDS.forEach(field => {
if (publishConfig[field]) {
packageJson[field] = publishConfig[field]
delete publishConfig[field]
}
})
if (!Object.keys(publishConfig).length) {
// delete property by destructuring
// eslint-disable-next-line no-unused-vars
const { publishConfig: _, ...pkg } = packageJson
return pkg
}
return {
...packageJson,
publishConfig
}
}
export function clearPackageJSON(packageJson, inputIgnoreFields) {
const ignoreFields = inputIgnoreFields
? IGNORE_FIELDS.concat(inputIgnoreFields)
: IGNORE_FIELDS
const cleanPackageJSON = filterObjectByKey(
applyPublishConfig(packageJson),
key => !ignoreFields.includes(key) && key !== 'scripts'
)
if (packageJson.scripts && !ignoreFields.includes('scripts')) {
cleanPackageJSON.scripts = filterObjectByKey(packageJson.scripts, script =>
NPM_SCRIPTS.includes(script)
)
if (
cleanPackageJSON.scripts.publish &&
/^clean-publish( |$)/.test(cleanPackageJSON.scripts.publish)
) {
// "custom" publish script is actually calling clean-publish
delete cleanPackageJSON.scripts.publish
}
}
for (const i in cleanPackageJSON) {
if (
isObject(cleanPackageJSON[i]) &&
Object.keys(cleanPackageJSON[i]).length === 0
) {
delete cleanPackageJSON[i]
}
}
return cleanPackageJSON
}
export function createIgnoreMatcher(ignorePattern) {
if (ignorePattern instanceof RegExp) {
return filename => !ignorePattern.test(filename)
}
if (glob.isDynamicPattern(ignorePattern)) {
const isMatch = micromatch.matcher(ignorePattern)
return (_filename, path) => !isMatch(path)
}
return filename => filename !== ignorePattern
}
export function createFilesFilter(ignoreFiles) {
const ignorePatterns = ignoreFiles
? IGNORE_FILES.concat(ignoreFiles).filter(Boolean)
: IGNORE_FILES
const filter = ignorePatterns.reduce((next, ignorePattern) => {
const ignoreMatcher = createIgnoreMatcher(ignorePattern)
if (!next) {
return ignoreMatcher
}
return (filename, path) =>
ignoreMatcher(filename, path) && next(filename, path)
}, null)
return path => {
const filename = basename(path)
return filter(filename, path)
}
}
export async function copyFiles(tempDir, filter) {
const rootFiles = await fs.readdir('./')
return Promise.all(
rootFiles.map(async file => {
if (file !== tempDir) {
await copy(file, join(tempDir, file), { filter })
}
})
)
}
export function publish(
cwd,
{ access, dryRun, packageManager, packageManagerOptions = [], tag }
) {
return new Promise((resolve, reject) => {
const args = ['publish', ...packageManagerOptions]
if (access) args.push('--access', access)
if (tag) args.push('--tag', tag)
if (dryRun) args.push('--dry-run')
spawn(packageManager, args, {
cwd,
stdio: 'inherit'
})
.on('close', (code, signal) => {
resolve({
code,
signal
})
})
.on('error', reject)
})
}
export async function createTempDirectory(name) {
if (name) {
try {
await fs.mkdir(name)
} catch (err) {
if (err.code === 'EEXIST') {
throw new Error(`Temporary directory "${name}" already exists.`)
}
}
return name
}
return await fs.mkdtemp('tmp')
}
export function removeTempDirectory(directoryName) {
return remove(directoryName)
}
export function runScript(script, ...args) {
return new Promise((resolve, reject) => {
spawn(script, args, { stdio: 'inherit' })
.on('close', code => {
resolve(code === 0)
})
.on('error', reject)
})
}
export function getReadmeUrlFromRepository(repository) {
const repoUrl = typeof repository === 'object' ? repository.url : repository
if (repoUrl) {
const name = repoUrl.match(/[^/:]+\/[^/:]+$/)?.[0]?.replace(/\.git$/, '')
return `https://github.com/${name}#readme`
}
return null
}
export async function cleanDocs(drectoryName, repository, homepage) {
const readmePath = join(drectoryName, 'README.md')
const readme = await fs.readFile(readmePath)
const readmeUrl = getReadmeUrlFromRepository(repository)
if (homepage || readmeUrl) {
const cleaned =
readme.toString().split(/\n##\s*\w/m)[0] +
'\n## Docs\n' +
`Read full docs **[here](${homepage || readmeUrl})**.\n`
await fs.writeFile(readmePath, cleaned)
}
}
export async function cleanComments(drectoryName) {
const files = await glob(['**/*.js'], { cwd: drectoryName })
await Promise.all(
files.map(async i => {
const file = join(drectoryName, i)
const content = await fs.readFile(file)
const cleaned = content
.toString()
.replace(/\s*\/\/.*\n/gm, '\n')
.replace(/\s*\/\*[^/]+\*\/\n?/gm, '\n')
.replace(/\n+/gm, '\n')
.replace(/^\n+/gm, '')
await fs.writeFile(file, cleaned)
})
)
}