-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
453 lines (362 loc) · 9.7 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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
const fs = require('fs')
const path = require('path')
const { execSync, spawnSync } = require('child_process')
const { version } = require('./package.json')
const cloneOrPull = require('./git')
const pkgLocation = path.join(process.cwd(), '/package.json')
function getPackage (cmd) {
let pkg = null
try {
pkg = require(pkgLocation)
} catch (err) {
const ENOTFOUND = err.message.includes('Cannot find')
if (!ENOTFOUND) {
console.error(err.message)
process.exit(1)
}
if (!['h', 'help', 'init'].includes(cmd)) {
console.error('No package.json found. Try "build init"?')
process.exit(1)
}
let remote = ''
try {
const opts = { stdio: 'pipe', cwd: process.cwd() }
remote = execSync('git remote get-url origin', opts)
} catch (err) {
console.log(String(err.stderr))
process.exit(1)
}
pkg = {
name: '',
description: '',
repository: {
type: 'git',
url: remote.toString().trim()
},
dependencies: {},
license: 'MIT',
scripts: {
'test': [
'clang++ -std=c++2a -stdlib=libc++',
'test/index.cxx -o test/index && ./test/index'
],
'install': ''
},
flags: ['-std=c++2a', '-stdlib=libc++', '-O3'],
files: ['index.cxx']
}
}
return pkg
}
function writePackage (pkg) {
try {
fs.writeFileSync(pkgLocation, JSON.stringify(pkg, 2, 2))
} catch (err) {
console.error(`Unable to write to package.json (${err.message})`)
process.exit(1)
}
}
function help (argv, pkg) {
console.log(`
hyper-build v${version}
build [...args] build the project [with ...args]
build -h|help print this help screen
build -i|install [dep] recursively install dep(s)
build -u|upgrade [dep] recursively upgrade dep(s)
build add <remote> [hash] [-d] add git dep [at commit] [as dev]
build init initialze a new project
build find <lib> check if <lib> installed
build run <name> run a sepecific script
build test run the test script
`)
}
function add (argv, pkg) {
let isDevDep = argv.findIndex(s => s === '-d')
if (isDevDep > -1) {
argv.splice(isDevDep, 1)
}
const shorthandRE = /^[^/ ]+\/[^/ ]+$/
const hash = argv[1] || '*'
let remote = argv[0]
if (shorthandRE.test(remote)) {
remote = `git@github.com:${remote}`
}
if (isDevDep > -1) {
pkg.devDependencies = pkg.devDependencies || {}
pkg.devDependencies[remote] = hash
} else {
pkg.dependencies = pkg.dependencies || {}
pkg.dependencies[remote] = hash
}
writePackage(pkg)
}
function collect () {
let sources = []
let headers = []
let flags = []
//
// - visit each dep
// - join the path of the package and the sources field.
// - collect all the flags
// - if is a .hxx push to headers[]
// - otherwise push to sources[]
//
const walk = pwd => {
const files = fs.readdirSync(pwd)
for (const file of files) {
if (file[0] === '.') continue
let stat = null
const p = path.join(pwd, file)
try {
stat = fs.statSync(p)
} catch (err) {}
if (stat.isDirectory()) {
walk(p)
continue
}
if (file !== 'package.json') continue
const dpkg = require(p)
if (dpkg.flags) {
flags.push(...dpkg.flags)
}
if (!dpkg.files) {
console.error('Package has no files field!')
process.exit(1)
}
dpkg.files.forEach(file => {
const v = path.join(pwd, path.dirname(file))
if (path.extname(file).includes('.h')) {
headers.push(v)
} else if (path.extname(file).includes('.c')) {
sources.push(path.join(pwd, file))
}
})
}
}
walk(process.cwd())
//
// Headers are naturally deduped by their guards. But sources
// can become deuplicated when a dependency is installed by
// multiple packages. The rest of this code dedupes sources,
// headers and flags for each dependency.
//
const uniqueSources = {}
;[...new Set(sources)].forEach(source => {
const index = source.lastIndexOf('/deps')
if (index === -1) {
uniqueSources[Math.random()] = source
return
}
const path = source.slice(index)
uniqueSources[path] = source
})
return {
sources: Object.values(uniqueSources),
headers: [...new Set(headers)],
flags: [...new Set(flags)]
}
}
function build (argv, pkg) {
const { headers, sources } = collect()
const compiler = pkg.compiler || 'clang++'
const NL = ' \\\n'
const cmd = [
`${compiler} ${NL}`,
pkg.flags ? pkg.flags.join(NL) : '',
argv.join(NL),
sources.join(NL)
].join(' \\\n')
const env = {
CPLUS_INCLUDE_PATH: headers.join(path.delimiter)
}
return run(cmd, { env })
}
function test (script, argv) {
if (Array.isArray(script)) {
script = script.join(' ')
}
const { headers, sources, flags } = collect()
const NL = ' \\\n'
const extras = [
flags.join(' '),
sources.join(' ')
].join(' ')
script = script.replace('++', '++ ' + extras)
const cmd = [
script,
argv.join(NL)
].join(' \\\n')
const env = {
CPLUS_INCLUDE_PATH: headers.join(path.delimiter)
}
if (process.env.DEBUG) {
console.log(env)
}
return run(cmd, { env })
}
function run (script, opts = {}) {
if (process.env.DEBUG) {
console.log(script)
}
if (Array.isArray(script)) script = script.join(' ')
opts.stdio = 'pipe'
try {
const output = execSync(script, opts)
return {
status: 0,
output: output.toString().trim()
}
} catch (err) {
return {
status: err.status,
output: err.output
.filter(Boolean)
.map(buf => String(buf))
.join('\n')
.trim()
}
}
}
//
// may be called recursively, starting at cwd.
// clones all dependencies into their `deps` dir.
// runs their install scripts, depth first.
//
async function install (cwd, argv, pkg, upgrade) {
async function _install (prop, deps, cwd, argv, pkg, upgrade) {
for (let [remote, hash] of deps) {
if (hash === '*' || upgrade) {
//
// if the hash is '*', dont pass it,
// let git tell us what hash to use.
//
hash = undefined
}
const info = await cloneOrPull(cwd, remote, hash)
pkg[prop] = pkg[prop] || {}
pkg[prop][remote] = info.hash
//
// get the package.json for this dep
//
const dpkg = require(path.join(info.target, 'package.json'))
//
// recurse! (but only for "dependencies")
//
const dpkgDeps = Object.entries(dpkg.dependencies || {})
await _install('dependencies', dpkgDeps, info.target, argv, dpkg)
//
// If there are install script, run them (depth first).
//
if (!dpkg.scripts) continue
const opts = { cwd: info.target }
if (dpkg.scripts.install) {
console.log(`${dpkg.name} -> ${dpkg.scripts.install}`)
const r = run(dpkg.scripts.install, opts)
console.log(r.output)
}
}
}
let deps = Object.entries(pkg.dependencies || {})
let devDeps = Object.entries(pkg.devDependencies || {})
if (argv[0]) {
deps = deps.filter(dep => dep[0].includes(argv[0]))
}
const args = [cwd, argv, pkg, upgrade]
if (deps.length) await _install('dependencies', deps, ...args)
if (devDeps.length) await _install('devDependencies', devDeps, ...args)
writePackage(pkg)
}
function init (argv, pkg) {
try {
fs.statSync(pkgLocation)
} catch (err) {
writePackage(pkg)
}
const depsDir = path.join(process.cwd(), 'deps')
const testDir = path.join(process.cwd(), 'test')
const gitIgnore = path.join(process.cwd(), '.gitignore')
try {
fs.statSync(depsDir)
} catch (err) {
fs.mkdirSync(depsDir)
}
try {
fs.statSync(testDir)
} catch (err) {
fs.mkdirSync(testDir)
fs.writeFileSync(path.join(testDir, 'index.cxx'), '')
}
try {
fs.statSync(gitIgnore)
} catch (err) {
fs.writeFileSync(gitIgnore, '/deps\n/test/index')
}
}
function find (argv, pkg) {
const name = argv[0]
const compiler = pkg.compiler || 'clang++'
try {
execSync(`${compiler} -l${name}`, { stdio: 'pipe' })
} catch (err) {
const s = String(err.stderr || '')
if (s.includes(`cannot find -l${name}`)) {
process.exit(1)
}
}
process.exit(0)
}
async function main () {
const argv = process.argv.slice(2)
const cmd = argv.shift()
const pkg = getPackage(cmd)
switch (cmd) {
case 'add':
return add(argv, pkg)
case 'find':
return find(argv, pkg)
case '-h':
case 'help':
return help(argv, pkg)
case '-i':
case 'install':
return install(process.cwd(), argv, pkg)
case '-u':
case 'upgrade':
return install(process.cwd(), argv, pkg, true)
case 'init':
return init(argv, pkg)
case 'test': {
if (!pkg.scripts) {
console.log('Package has no .scripts[] property.')
process.exit(1)
}
if (pkg.scripts.pretest) {
const r = run(pkg.scripts.pretest, argv)
console.log(r.output)
}
const r = test(pkg.scripts.test, argv)
console.log(r.output)
if (pkg.scripts.posttest) {
const r = run(pkg.scripts.posttest, argv)
console.log(r.output)
}
break
}
case 'run': {
const name = argv.shift()
const script = pkg.scripts[name]
const r = run(script, {})
console.log(r.output)
break
}
default: {
const r = build([cmd, ...argv], pkg)
if (r === 0) {
console.log('OK build')
} else {
console.log(r.output)
}
}
}
}
main()