-
-
Notifications
You must be signed in to change notification settings - Fork 121
/
Copy pathretrieve-win-deps.js
220 lines (184 loc) · 6.27 KB
/
retrieve-win-deps.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
/**
* Copyright (c) Jonathan Cardoso Machado. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// https://github.com/nodejs/node-gyp/blob/64bb407c14149c216885a48e78df178cedaec8fd/bin/node-gyp.js#L25
if (process.platform !== 'win32') {
process.exit(0)
}
const { exec } = require('child_process')
const fs = require('fs')
const path = require('path')
const os = require('os')
const util = require('util')
const envPaths = require('env-paths')
// we cannot use fs.promises because it was added on Node.js 10
// but we need to support Node.js >= 8
const fsOpenAsync = util.promisify(fs.open)
const fsCloseAsync = util.promisify(fs.close)
const fsReadAsync = util.promisify(fs.read)
const fsWriteAsync = util.promisify(fs.write)
const fsStatAsync = util.promisify(fs.stat)
const execAsync = util.promisify(exec)
const homeDir = os.homedir()
let { version } = process
let gypFolder = envPaths('node-gyp', { suffix: '' }).cache
if (process.env.npm_config_runtime === 'node-webkit') {
version = process.env.npm_config_target
gypFolder = path.resolve(homeDir, '.nw-gyp')
}
// node-gyp path from here: https://github.com/nodejs/node-gyp/blob/v5.0.3/bin/node-gyp.js#L31
const gypDir = path.resolve(gypFolder, version.replace('v', ''))
// we are renaming the openssl directory so it does not get used when compilling.
// node-gyp default addon.gyp file adds the above folder as include, which would make
// the c++ includes for openssl/* point to that folder, instead of using the one from the openssl
// we are building. This only happens for node >= 10, probably because only with this version
// openssl started to be have their symbols exported on Windows, or for another obscure reason.
const opensslFolder = path.resolve(gypDir, 'include', 'node', 'openssl')
const opensslFolderDisabled = `${opensslFolder}.disabled`
if (fs.existsSync(opensslFolder)) {
fs.renameSync(opensslFolder, opensslFolderDisabled)
}
const execConfig = {
cwd: path.resolve(__dirname + '/..'),
}
const depsGypTarget = 'curl-for-windows/curl.gyp:libcurl'
const fileWithDepsTag = 'LIBCURL_VERSION_WIN_DEPS'
const depsRepo = 'https://github.com/JCMais/curl-for-windows.git'
const envCurlForWindowsDepsVersionTag = process.env.NODE_LIBCURL_WINDEPS_TAG
const cleanupAndExit = (code = 0) => {
// we are not reverting the openssl change we did above in here because
// this is being done inside scripts/postinstall.js
process.exit(code)
}
// let the magic begins
const run = async () => {
try {
const { stdout } = await execAsync(
'git rev-parse --show-toplevel',
execConfig,
)
// Check if we are in the root git dir.
// That is, someone is running this directly from the node-libcurl repo.
// if we are, just replace the tokens.
if (path.relative(execConfig.cwd, stdout.trim()) === '') {
return replaceTokensOnFiles(
path.resolve(__dirname, '..', 'deps', 'curl-for-windows'),
).then(() => {
process.stdout.write(`deps/${depsGypTarget}`)
})
}
} catch (_) {
// ignore errors
}
// otherwise retrieve the deps
return retrieveWinDeps()
}
const retrieveWinDeps = async () => {
const fileExists = fs.existsSync(fileWithDepsTag)
if (!fileExists && !envCurlForWindowsDepsVersionTag) {
console.error(
`File: ${fileWithDepsTag} not found, and no NODE_LIBCURL_WINDEPS_TAG environment variable found.`,
)
cleanupAndExit(1)
}
const depsTag = envCurlForWindowsDepsVersionTag
? envCurlForWindowsDepsVersionTag.trim()
: fs.readFileSync(fileWithDepsTag).toString().replace(/\n|\s/g, '')
try {
await execAsync(`git clone --branch ${depsTag} ${depsRepo}`, execConfig)
} catch (error) {
if (
error
.toString()
.indexOf('already exists and is not an empty directory') !== -1
) {
await execAsync('rmdir curl-for-windows /S /Q', execConfig)
return retrieveWinDeps()
} else {
throw error
}
}
await execAsync(
'cd curl-for-windows && git submodule update --init && python configure.py',
execConfig,
)
// Grab gyp config files and replace <(library) with static_library
await replaceTokensOnFiles(path.resolve(__dirname, '..', 'curl-for-windows'))
// remove git folder
await execAsync('rmdir curl-for-windows\\.git /S /Q', execConfig)
process.stdout.write(depsGypTarget)
}
async function replaceTokensOnFiles(dir) {
const filesToCheck = [
'libssh2.gyp',
'openssl/openssl.gyp',
'cares/cares.gyp',
'nghttp2/nghttp2.gyp',
'zlib.gyp',
'curl.gyp',
]
const replacements = [
{
pattern: /<\(library\)/g,
replacement: 'static_library',
},
// {
// pattern: /curl_for_windows_build_openssl%': 'true'/g,
// replacement: 'curl_for_windows_build_openssl\': \'false\'',
// },
]
await Promise.all(
filesToCheck.map(async (file) => {
const filePath = path.resolve(dir, file)
for (const patternReplacementPair of replacements) {
await replaceOnFile(
filePath,
patternReplacementPair.pattern,
patternReplacementPair.replacement,
)
}
}),
)
}
const REPLACE_ON_FILE_INITIAL_CHUNK_SIZE = 2048
async function replaceOnFile(file, search, replacement) {
const fd = await fsOpenAsync(file, 'r+')
try {
const stat = await fsStatAsync(file)
const totalSize = stat.size
const buffer = Buffer.alloc(totalSize)
let chunkSize = REPLACE_ON_FILE_INITIAL_CHUNK_SIZE
let totalRead = 0
// this while is not the best way to do this
// but hey, it works, and we are processing just 5 files :D
// The best way here probably would be to use a readable stream
while (totalRead < totalSize) {
if (totalRead + chunkSize > totalSize) {
chunkSize = totalSize - totalRead
}
const { bytesRead } = await fsReadAsync(
fd,
buffer,
totalRead,
chunkSize,
totalRead,
)
totalRead += bytesRead
}
const fileNewContent = buffer.toString('utf8').replace(search, replacement)
await fsWriteAsync(fd, fileNewContent, 0, 'utf8')
} finally {
await fsCloseAsync(fd)
}
}
run()
.then(() => {
cleanupAndExit()
})
.catch((error) => {
console.error(error.toString())
cleanupAndExit(1)
})