-
Notifications
You must be signed in to change notification settings - Fork 32
/
index.js
executable file
·305 lines (258 loc) · 9.53 KB
/
index.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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
const path = require("path")
const child_process = require("child_process")
const fs = require("fs")
const readPkgUp = require("read-pkg-up")
const rimraf = require("rimraf")
const globby = require("globby")
const checksum = require("checksum")
const merge = require("lodash/merge")
const debounce = require("lodash/debounce")
const { spawn } = require("yarn-or-npm")
const tar = require("tar")
async function installRelativeDeps() {
const projectPkgJson = readPkgUp.sync()
const relativeDependencies = projectPkgJson.package.relativeDependencies
if (!relativeDependencies) {
console.warn("[relative-deps][WARN] No 'relativeDependencies' specified in package.json")
process.exit(0)
}
const targetDir = path.dirname(projectPkgJson.path)
const depNames = Object.keys(relativeDependencies)
for (const name of depNames) {
const libDir = path.resolve(targetDir, relativeDependencies[name])
console.log(`[relative-deps] Checking '${name}' in '${libDir}'`)
const regularDep =
(projectPkgJson.package.dependencies && projectPkgJson.package.dependencies[name]) ||
(projectPkgJson.package.devDependencies && projectPkgJson.package.devDependencies[name])
if (!regularDep) {
console.warn(`[relative-deps][WARN] The relative dependency '${name}' should also be added as normal- or dev-dependency`)
}
// Check if target dir exists
if (!fs.existsSync(libDir)) {
// Nope, but is the dependency mentioned as normal dependency in the package.json? Use that one
if (regularDep) {
console.warn(`[relative-deps][WARN] Could not find target directory '${libDir}', using normally installed version ('${regularDep}') instead`)
return
} else {
console.error(
`[relative-deps][ERROR] Failed to resolve dependency ${name}: failed to find target directory '${libDir}', and the library is not present as normal depenency either`
)
process.exit(1)
}
}
const hashStore = {
hash: "",
file: ""
}
const hasChanges = await libraryHasChanged(name, libDir, targetDir, hashStore)
if (hasChanges) {
buildLibrary(name, libDir)
packAndInstallLibrary(name, libDir, targetDir)
fs.writeFileSync(hashStore.file, hashStore.hash)
console.log(`[relative-deps] Re-installing ${name}... DONE`)
}
}
}
async function watchRelativeDeps() {
const projectPkgJson = readPkgUp.sync()
const relativeDependencies = projectPkgJson.package.relativeDependencies
if (!relativeDependencies) {
console.warn("[relative-deps][WARN] No 'relativeDependencies' specified in package.json")
process.exit(0)
}
Object.values(relativeDependencies).forEach(path => {
fs.watch(path, { recursive: true }, debounce(installRelativeDeps, 500))
});
}
async function libraryHasChanged(name, libDir, targetDir, hashStore) {
const hashFile = path.join(targetDir, "node_modules", name, ".relative-deps-hash")
const referenceContents = fs.existsSync(hashFile) ? fs.readFileSync(hashFile, "utf8") : ""
// compute the hahses
const libFiles = await findFiles(libDir, targetDir)
const hashes = []
for (file of libFiles) hashes.push(await getFileHash(path.join(libDir, file)))
const contents = libFiles.map((file, index) => hashes[index] + " " + file).join("\n")
hashStore.file = hashFile
hashStore.hash = contents
if (contents === referenceContents) {
// computed hashes still the same?
console.log("[relative-deps] No changes")
return false
}
// Print which files did change
if (referenceContents) {
const contentsLines = contents.split("\n")
const refLines = referenceContents.split("\n")
for (let i = 0; i < contentsLines.length; i++)
if (contentsLines[i] !== refLines[i]) {
console.log("[relative-deps] Changed file: " + libFiles[i]) //, contentsLines[i], refLines[i])
break
}
}
return true
}
async function findFiles(libDir, targetDir) {
const ignore = ["**/*", "!node_modules", "!.git"]
// TODO: use resolved paths here
if (targetDir.indexOf(libDir) === 0) {
// The target dir is in the lib directory, make sure that path is excluded
ignore.push("!" + targetDir.substr(libDir.length + 1).split(path.sep)[0])
}
const files = await globby(ignore, {
gitignore: true,
cwd: libDir,
nodir: true
})
return files.sort()
}
function buildLibrary(name, dir) {
// Run install if never done before
if (!fs.existsSync(path.join(dir, "node_modules"))) {
console.log(`[relative-deps] Running 'install' in ${dir}`)
spawn.sync(["install"], { cwd: dir, stdio: [0, 1, 2] })
}
// Run build script if present
const libraryPkgJson = JSON.parse(fs.readFileSync(path.join(dir, "package.json"), "utf8"))
if (!libraryPkgJson.name === name) {
console.error(`[relative-deps][ERROR] Mismatch in package name: found '${libraryPkgJson.name}', expected '${name}'`)
process.exit(1)
}
if (libraryPkgJson.scripts && libraryPkgJson.scripts.build) {
console.log(`[relative-deps] Building ${name} in ${dir}`)
spawn.sync(["run", "build"], { cwd: dir, stdio: [0, 1, 2] })
}
}
function packAndInstallLibrary(name, dir, targetDir) {
const libDestDir = path.join(targetDir, "node_modules", name)
let fullPackageName
try {
console.log("[relative-deps] Copying to local node_modules")
spawn.sync(["pack"], { cwd: dir, stdio: [0, 1, 2] })
if (fs.existsSync(libDestDir)) {
// TODO: should we really remove it? Just overwritting could be fine
rimraf.sync(libDestDir)
}
fs.mkdirSync(libDestDir, { recursive: true })
const tmpName = name.replace(/[\s\/]/g, "-").replace(/@/g, "")
// npm replaces @... with at- where yarn just removes it, so we test for both files here
const regex = new RegExp(`^(at-)?${tmpName}(.*).tgz$`)
const packagedName = fs.readdirSync(dir).find(file => regex.test(file))
fullPackageName = path.join(dir, packagedName)
console.log(`[relative-deps] Extracting "${fullPackageName}" to ${libDestDir}`)
const [cwd, file] = [libDestDir, fullPackageName].map(absolutePath =>
path.relative(process.cwd(), absolutePath)
)
tar.extract({
cwd,
file,
gzip: true,
stripComponents: 1,
sync: true
})
} finally {
if (fullPackageName) {
fs.unlinkSync(fullPackageName)
}
}
}
async function getFileHash(file) {
return await new Promise((resolve, reject) => {
checksum.file(file, (error, hash) => {
if (error) reject(error)
else resolve(hash)
})
})
}
function addScriptToPackage(script) {
let pkg = getPackageJson()
if (!pkg.scripts) {
pkg.scripts = {}
}
const msg = `[relative-deps] Adding relative-deps to ${script} script in package.json`
if (!pkg.scripts[script]) {
console.log(msg)
pkg.scripts[script] = "relative-deps"
} else if (!pkg.scripts[script].includes("relative-deps")) {
console.log(msg)
pkg.scripts[script] = `${pkg.scripts[script]} && relative-deps`
}
setPackageData(pkg)
}
function installRelativeDepsPackage() {
let pkg = getPackageJson()
if (!(
(pkg.devDependencies && pkg.devDependencies["relative-deps"]) ||
(pkg.dependencies && pkg.dependencies["relative-deps"])
)) {
console.log('[relative-deps] Installing relative-deps package')
spawn.sync(["add", "-D", "relative-deps"])
}
}
function setupEmptyRelativeDeps() {
let pkg = getPackageJson()
if (!pkg.relativeDependencies) {
console.log(`[relative-deps] Setting up relativeDependencies section in package.json`)
pkg.relativeDependencies = {}
setPackageData(pkg)
}
}
function initRelativeDeps({ script }) {
installRelativeDepsPackage()
setupEmptyRelativeDeps()
addScriptToPackage(script)
}
async function addRelativeDeps({ paths, dev, script }) {
initRelativeDeps({ script })
if (!paths || paths.length === 0) {
console.log(`[relative-deps][WARN] no paths provided running ${script}`)
spawn.sync([script])
return
}
const libraries = paths.map(relPath => {
const libPackagePath = path.resolve(process.cwd(), relPath, "package.json")
if (!fs.existsSync(libPackagePath)) {
console.error(
`[relative-deps][ERROR] Failed to resolve dependency ${relPath}`
)
process.exit(1)
}
const libraryPackageJson = JSON.parse(fs.readFileSync(libPackagePath, "utf-8"))
return {
relPath,
name: libraryPackageJson.name,
version: libraryPackageJson.version
}
})
let pkg = getPackageJson()
const depsKey = dev ? "devDependencies" : "dependencies"
if (!pkg[depsKey]) pkg[depsKey] = {}
libraries.forEach(library => {
if (!pkg[depsKey][library.name]) {
try {
spawn.sync(["add", ...[dev ? ["-D"] : []], library.name], { stdio: "ignore" })
} catch (_e) {
console.log(`[relative-deps][WARN] Unable to fetch ${library.name} from registry. Installing as a relative dependency only.`)
}
}
})
if (!pkg.relativeDependencies) pkg.relativeDependencies = {}
libraries.forEach(dependency => {
pkg.relativeDependencies[dependency.name] = dependency.relPath
})
setPackageData(pkg)
await installRelativeDeps()
}
function setPackageData(pkgData) {
const source = getPackageJson()
fs.writeFileSync(
path.join(process.cwd(), "package.json"),
JSON.stringify(merge(source, pkgData), null, 2)
)
}
function getPackageJson() {
return JSON.parse(fs.readFileSync(path.join(process.cwd(), 'package.json'), "utf-8"))
}
module.exports.watchRelativeDeps = watchRelativeDeps
module.exports.installRelativeDeps = installRelativeDeps
module.exports.initRelativeDeps = initRelativeDeps
module.exports.addRelativeDeps = addRelativeDeps