-
-
Notifications
You must be signed in to change notification settings - Fork 934
/
index.ts
246 lines (235 loc) · 8.31 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
238
239
240
241
242
243
244
245
246
import path from 'path'
import { calcDepState, DepsStateCache } from '@pnpm/calc-dep-state'
import { skippedOptionalDependencyLogger } from '@pnpm/core-loggers'
import { PnpmError } from '@pnpm/error'
import { runPostinstallHooks } from '@pnpm/lifecycle'
import { linkBins, linkBinsOfPackages } from '@pnpm/link-bins'
import { logger } from '@pnpm/logger'
import { hardLinkDir } from '@pnpm/fs.hard-link-dir'
import { readPackageJsonFromDir, safeReadPackageJsonFromDir } from '@pnpm/read-package-json'
import { StoreController } from '@pnpm/store-controller-types'
import { DependencyManifest } from '@pnpm/types'
import pDefer, { DeferredPromise } from 'p-defer'
import { applyPatch } from 'patch-package/dist/applyPatches'
import pickBy from 'ramda/src/pickBy'
import runGroups from 'run-groups'
import { buildSequence, DependenciesGraph, DependenciesGraphNode } from './buildSequence'
export { DepsStateCache }
export async function buildModules (
depGraph: DependenciesGraph,
rootDepPaths: string[],
opts: {
childConcurrency?: number
depsToBuild?: Set<string>
depsStateCache: DepsStateCache
extraBinPaths?: string[]
extraNodePaths?: string[]
extraEnv?: Record<string, string>
ignoreScripts?: boolean
lockfileDir: string
optional: boolean
preferSymlinkedExecutables?: boolean
rawConfig: object
unsafePerm: boolean
userAgent: string
scriptsPrependNodePath?: boolean | 'warn-only'
scriptShell?: string
shellEmulator?: boolean
sideEffectsCacheWrite: boolean
storeController: StoreController
rootModulesDir: string
hoistedLocations?: Record<string, string[]>
}
) {
const warn = (message: string) => logger.warn({ message, prefix: opts.lockfileDir })
// postinstall hooks
const buildDepOpts = { ...opts, warn }
if (opts.hoistedLocations) {
buildDepOpts['builtHoistedDeps'] = {}
}
const chunks = buildSequence(depGraph, rootDepPaths)
const groups = chunks.map((chunk) => {
chunk = chunk.filter((depPath) => {
const node = depGraph[depPath]
return (node.requiresBuild || node.patchFile != null) && !node.isBuilt
})
if (opts.depsToBuild != null) {
chunk = chunk.filter((depPath) => opts.depsToBuild!.has(depPath))
}
return chunk.map((depPath: string) =>
async () => buildDependency(depPath, depGraph, buildDepOpts)
)
})
await runGroups(opts.childConcurrency ?? 4, groups)
}
async function buildDependency (
depPath: string,
depGraph: DependenciesGraph,
opts: {
extraBinPaths?: string[]
extraNodePaths?: string[]
extraEnv?: Record<string, string>
depsStateCache: DepsStateCache
ignoreScripts?: boolean
lockfileDir: string
optional: boolean
preferSymlinkedExecutables?: boolean
rawConfig: object
rootModulesDir: string
scriptsPrependNodePath?: boolean | 'warn-only'
scriptShell?: string
shellEmulator?: boolean
sideEffectsCacheWrite: boolean
storeController: StoreController
unsafePerm: boolean
hoistedLocations?: Record<string, string[]>
builtHoistedDeps?: Record<string, DeferredPromise<void>>
warn: (message: string) => void
}
) {
const depNode = depGraph[depPath]
if (opts.builtHoistedDeps) {
if (opts.builtHoistedDeps[depNode.depPath]) {
await opts.builtHoistedDeps[depNode.depPath].promise
return
}
opts.builtHoistedDeps[depNode.depPath] = pDefer()
}
try {
await linkBinsOfDependencies(depNode, depGraph, opts)
const isPatched = depNode.patchFile?.path != null
if (isPatched) {
applyPatchToDep(depNode.dir, depNode.patchFile!.path)
}
const hasSideEffects = !opts.ignoreScripts && await runPostinstallHooks({
depPath,
extraBinPaths: opts.extraBinPaths,
extraEnv: opts.extraEnv,
initCwd: opts.lockfileDir,
optional: depNode.optional,
pkgRoot: depNode.dir,
rawConfig: opts.rawConfig,
rootModulesDir: opts.rootModulesDir,
scriptsPrependNodePath: opts.scriptsPrependNodePath,
scriptShell: opts.scriptShell,
shellEmulator: opts.shellEmulator,
unsafePerm: opts.unsafePerm || false,
})
if ((isPatched || hasSideEffects) && opts.sideEffectsCacheWrite) {
try {
const sideEffectsCacheKey = calcDepState(depGraph, opts.depsStateCache, depPath, {
patchFileHash: depNode.patchFile?.hash,
isBuilt: hasSideEffects,
})
await opts.storeController.upload(depNode.dir, {
sideEffectsCacheKey,
filesIndexFile: depNode.filesIndexFile,
})
} catch (err: any) { // eslint-disable-line
if (err.statusCode === 403) {
logger.warn({
message: `The store server disabled upload requests, could not upload ${depNode.dir}`,
prefix: opts.lockfileDir,
})
} else {
logger.warn({
error: err,
message: `An error occurred while uploading ${depNode.dir}`,
prefix: opts.lockfileDir,
})
}
}
}
} catch (err: any) { // eslint-disable-line
if (depNode.optional) {
// TODO: add parents field to the log
const pkg = await readPackageJsonFromDir(path.join(depNode.dir)) as DependencyManifest
skippedOptionalDependencyLogger.debug({
details: err.toString(),
package: {
id: depNode.dir,
name: pkg.name,
version: pkg.version,
},
prefix: opts.lockfileDir,
reason: 'build_failure',
})
return
}
throw err
} finally {
const hoistedLocationsOfDep = opts.hoistedLocations?.[depNode.depPath]
if (hoistedLocationsOfDep) {
// There is no need to build the same package in every location.
// We just copy the built package to every location where it is present.
const currentHoistedLocation = path.relative(opts.lockfileDir, depNode.dir)
const nonBuiltHoistedDeps = hoistedLocationsOfDep?.filter((hoistedLocation) => hoistedLocation !== currentHoistedLocation)
await hardLinkDir(depNode.dir, nonBuiltHoistedDeps)
}
if (opts.builtHoistedDeps) {
opts.builtHoistedDeps[depNode.depPath].resolve()
}
}
}
function applyPatchToDep (patchDir: string, patchFilePath: string) {
// Ideally, we would just run "patch" or "git apply".
// However, "patch" is not available on Windows and "git apply" is hard to execute on a subdirectory of an existing repository
const cwd = process.cwd()
process.chdir(patchDir)
const success = applyPatch({
patchFilePath,
patchDir,
})
process.chdir(cwd)
if (!success) {
throw new PnpmError('PATCH_FAILED', `Could not apply patch ${patchFilePath} to ${patchDir}`)
}
}
export async function linkBinsOfDependencies (
depNode: DependenciesGraphNode,
depGraph: DependenciesGraph,
opts: {
extraNodePaths?: string[]
optional: boolean
preferSymlinkedExecutables?: boolean
warn: (message: string) => void
}
) {
const childrenToLink: Record<string, string> = opts.optional
? depNode.children
: pickBy((child, childAlias) => !depNode.optionalDependencies.has(childAlias), depNode.children)
const binPath = path.join(depNode.dir, 'node_modules/.bin')
const pkgNodes = [
...Object.entries(childrenToLink)
.map(([alias, childDepPath]) => ({ alias, dep: depGraph[childDepPath] }))
.filter(({ alias, dep }) => {
if (!dep) {
// TODO: Try to reproduce this issue with a test in @pnpm/core
logger.debug({ message: `Failed to link bins of "${alias}" to "${binPath}". This is probably not an issue.` })
return false
}
return dep.hasBin && dep.installable !== false
})
.map(({ dep }) => dep),
depNode,
]
const pkgs = await Promise.all(pkgNodes
.map(async (dep) => ({
location: dep.dir,
manifest: await dep.fetchingBundledManifest?.() ?? (await safeReadPackageJsonFromDir(dep.dir) as DependencyManifest) ?? {},
}))
)
await linkBinsOfPackages(pkgs, binPath, {
extraNodePaths: opts.extraNodePaths,
preferSymlinkedExecutables: opts.preferSymlinkedExecutables,
})
// link also the bundled dependencies` bins
if (depNode.hasBundledDependencies) {
const bundledModules = path.join(depNode.dir, 'node_modules')
await linkBins(bundledModules, binPath, {
extraNodePaths: opts.extraNodePaths,
preferSymlinkedExecutables: opts.preferSymlinkedExecutables,
warn: opts.warn,
})
}
}