forked from pnpm/pnpm
/
index.ts
237 lines (223 loc) · 7.02 KB
/
index.ts
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
import { promises as fs, type Stats } from 'fs'
import path from 'path'
import { PnpmError } from '@pnpm/error'
import { type ProjectManifest } from '@pnpm/types'
import { extractComments, type CommentSpecifier } from '@pnpm/text.comments-parser'
import { writeProjectManifest } from '@pnpm/write-project-manifest'
import detectIndent from '@gwhitney/detect-indent'
import equal from 'fast-deep-equal'
import isWindows from 'is-windows'
import sortKeys from 'sort-keys'
import {
readYamlFile,
readJson5File,
readJsonFile,
} from './readFile'
type WriteProjectManifest = (manifest: ProjectManifest, force?: boolean) => Promise<void>
export async function safeReadProjectManifestOnly (projectDir: string) {
try {
return await readProjectManifestOnly(projectDir)
} catch (err: any) { // eslint-disable-line
if ((err as NodeJS.ErrnoException).code === 'ERR_PNPM_NO_IMPORTER_MANIFEST_FOUND') {
return null
}
throw err
}
}
export async function readProjectManifest (projectDir: string): Promise<{
fileName: string
manifest: ProjectManifest
writeProjectManifest: WriteProjectManifest
}> {
const result = await tryReadProjectManifest(projectDir)
if (result.manifest !== null) {
return result as {
fileName: string
manifest: ProjectManifest
writeProjectManifest: WriteProjectManifest
}
}
throw new PnpmError('NO_IMPORTER_MANIFEST_FOUND',
`No package.json (or package.yaml, or package.json5) was found in "${projectDir}".`)
}
export async function readProjectManifestOnly (projectDir: string): Promise<ProjectManifest> {
const { manifest } = await readProjectManifest(projectDir)
return manifest
}
export async function tryReadProjectManifest (projectDir: string): Promise<{
fileName: string
manifest: ProjectManifest | null
writeProjectManifest: WriteProjectManifest
}> {
try {
const manifestPath = path.join(projectDir, 'package.json')
const { data, text } = await readJsonFile(manifestPath)
return {
fileName: 'package.json',
manifest: data,
writeProjectManifest: createManifestWriter({
...detectFileFormatting(text),
initialManifest: data,
manifestPath,
}),
}
} catch (err: any) { // eslint-disable-line
if (err.code !== 'ENOENT') throw err
}
try {
const manifestPath = path.join(projectDir, 'package.json5')
const { data, text } = await readJson5File(manifestPath)
return {
fileName: 'package.json5',
manifest: data,
writeProjectManifest: createManifestWriter({
...detectFileFormattingAndComments(text),
initialManifest: data,
manifestPath,
}),
}
} catch (err: any) { // eslint-disable-line
if (err.code !== 'ENOENT') throw err
}
try {
const manifestPath = path.join(projectDir, 'package.yaml')
const { data, text } = await readPackageYaml(manifestPath)
return {
fileName: 'package.yaml',
manifest: data,
writeProjectManifest: createManifestWriter({ //initialManifest: data, manifestPath }),
...detectFileFormatting(text), //AndComments(text),
initialManifest: data,
manifestPath,
})
}
} catch (err: any) { // eslint-disable-line
if (err.code !== 'ENOENT') throw err
}
if (isWindows()) {
// ENOTDIR isn't used on Windows, but pnpm expects it.
let s: Stats | undefined
try {
s = await fs.stat(projectDir)
} catch (err: any) { // eslint-disable-line
// Ignore
}
if ((s != null) && !s.isDirectory()) {
const err = new Error(`"${projectDir}" is not a directory`)
// @ts-expect-error
err['code'] = 'ENOTDIR'
throw err
}
}
const filePath = path.join(projectDir, 'package.json')
return {
fileName: 'package.json',
manifest: null,
writeProjectManifest: async (manifest: ProjectManifest) => writeProjectManifest(filePath, manifest),
}
}
function detectFileFormattingAndComments (text: string) {
const { comments, text: newText, hasFinalNewline } = extractComments(text)
return {
comments,
indent: detectIndent(newText).indent,
insertFinalNewline: hasFinalNewline,
}
}
function detectFileFormatting (text: string) {
return {
indent: detectIndent(text).indent,
insertFinalNewline: text.endsWith('\n'),
}
}
export async function readExactProjectManifest (manifestPath: string) {
const base = path.basename(manifestPath).toLowerCase()
switch (base) {
case 'package.json': {
const { data, text } = await readJsonFile(manifestPath)
return {
manifest: data,
writeProjectManifest: createManifestWriter({
...detectFileFormatting(text),
initialManifest: data,
manifestPath,
}),
}
}
case 'package.json5': {
const { data, text } = await readJson5File(manifestPath)
return {
manifest: data,
writeProjectManifest: createManifestWriter({
...detectFileFormattingAndComments(text),
initialManifest: data,
manifestPath,
}),
}
}
case 'package.yaml': {
const { data, text } = await readPackageYaml(manifestPath)
return {
manifest: data,
writeProjectManifest: createManifestWriter({ //initialManifest: manifest, manifestPath }),
...detectFileFormatting(text), //AndComments(text),
initialManifest: data,
manifestPath,
}),
}
}
}
throw new Error(`Not supported manifest name "${base}"`)
}
async function readPackageYaml (filePath: string) {
try {
return await readYamlFile<ProjectManifest>(filePath)
} catch (err: any) { // eslint-disable-line
if (err.name !== 'YAMLException') throw err
err.message = `${err.message as string}\nin ${filePath}`
err.code = 'ERR_PNPM_YAML_PARSE'
throw err
}
}
function createManifestWriter (
opts: {
initialManifest: ProjectManifest
comments?: CommentSpecifier[]
indent?: string | number | undefined
insertFinalNewline?: boolean
manifestPath: string
}
): (WriteProjectManifest) {
let initialManifest = normalize(opts.initialManifest)
return async (updatedManifest: ProjectManifest, force?: boolean) => {
updatedManifest = normalize(updatedManifest)
if (force === true || !equal(initialManifest, updatedManifest)) {
await writeProjectManifest(opts.manifestPath, updatedManifest, {
comments: opts.comments,
indent: opts.indent,
insertFinalNewline: opts.insertFinalNewline,
})
initialManifest = normalize(updatedManifest)
return Promise.resolve(undefined)
}
return Promise.resolve(undefined)
}
}
const dependencyKeys = new Set([
'dependencies',
'devDependencies',
'optionalDependencies',
'peerDependencies',
])
function normalize (manifest: ProjectManifest) {
manifest = JSON.parse(JSON.stringify(manifest))
const result: Record<string, any> = {} // eslint-disable-line @typescript-eslint/no-explicit-any
for (const [key, value] of Object.entries(manifest)) {
if (!dependencyKeys.has(key)) {
result[key] = value
} else if (Object.keys(value).length !== 0) {
result[key] = sortKeys(value)
}
}
return result
}