/
index.ts
217 lines (203 loc) · 6.11 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
import { Stats } from 'fs'
import { promisify } from 'util'
import PnpmError from '@pnpm/error'
import { ProjectManifest } from '@pnpm/types'
import writeProjectManifest from '@pnpm/write-project-manifest'
import readYamlFile from 'read-yaml-file'
import {
readJson5File,
readJsonFile,
} from './readFile'
import fs = require('fs')
import detectIndent = require('detect-indent')
import equal = require('fast-deep-equal')
import isWindows = require('is-windows')
import path = require('path')
import sortKeys = require('sort-keys')
const stat = promisify(fs.stat)
type WriteProjectManifest = (manifest: ProjectManifest, force?: boolean) => Promise<void>
export async function safeReadProjectManifestOnly (projectDir: string) {
try {
return await readProjectManifestOnly(projectDir)
} catch (err) {
if ((err as NodeJS.ErrnoException).code === 'ERR_PNPM_NO_IMPORTER_MANIFEST_FOUND') {
return null
}
throw err
}
}
export default 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) {
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({
...detectFileFormatting(text),
initialManifest: data,
manifestPath,
}),
}
} catch (err) {
if (err.code !== 'ENOENT') throw err
}
try {
const manifestPath = path.join(projectDir, 'package.yaml')
const manifest = await readPackageYaml(manifestPath)
return {
fileName: 'package.yaml',
manifest,
writeProjectManifest: createManifestWriter({ initialManifest: manifest, manifestPath }),
}
} catch (err) {
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 stat(projectDir)
} catch (err) {
// Ignore
}
if (s && !s.isDirectory()) {
const err = new Error(`"${projectDir}" is not a directory`)
err['code'] = 'ENOTDIR' // eslint-disable-line
throw err
}
}
const filePath = path.join(projectDir, 'package.json')
return {
fileName: 'package.json',
manifest: null,
writeProjectManifest: (manifest: ProjectManifest) => writeProjectManifest(filePath, manifest),
}
}
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({
...detectFileFormatting(text),
initialManifest: data,
manifestPath,
}),
}
}
case 'package.yaml': {
const manifest = await readPackageYaml(manifestPath)
return {
manifest,
writeProjectManifest: createManifestWriter({ initialManifest: manifest, 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
indent?: string | number | undefined
insertFinalNewline?: boolean
manifestPath: string
}
): (WriteProjectManifest) {
const initialManifest = normalize(JSON.parse(JSON.stringify(opts.initialManifest)))
return (updatedManifest: ProjectManifest, force?: boolean) => {
updatedManifest = normalize(updatedManifest)
if (force === true || !equal(initialManifest, updatedManifest)) {
return writeProjectManifest(opts.manifestPath, updatedManifest, {
indent: opts.indent,
insertFinalNewline: opts.insertFinalNewline,
})
}
return Promise.resolve(undefined)
}
}
const dependencyKeys = new Set([
'dependencies',
'devDependencies',
'optionalDependencies',
'peerDependencies',
])
function normalize (manifest: ProjectManifest) {
const result = {}
for (const key of Object.keys(manifest)) {
if (!dependencyKeys.has(key)) {
result[key] = manifest[key]
} else if (Object.keys(manifest[key]).length !== 0) {
result[key] = sortKeys(manifest[key])
}
}
return result
}