Debian Codegraph @

nyc/lib/commands/instrument.js

raw ◀ ▶
1 Debian patch touch this file
1 'use strict'
2
3 const NYC = require('../../index.js')
4 const path = require('path')
5 const { promisify } = require('util')
6 const resolveFrom = require('resolve-from')
•7 const { rimraf } = require('rimraf')
8 const { cliWrapper, setupOptions } = require('./helpers.js')
9
10 exports.command = 'instrument <input> [output]'
11
12 exports.describe = 'instruments a file or a directory tree and writes the instrumented code to the desired output location'
13
14 exports.builder = function (yargs) {
15 yargs
16 .demandCommand(0, 0)
17 .example('$0 instrument ./lib ./output', 'instrument all .js files in ./lib with coverage and output in ./output')
18
19 setupOptions(yargs, 'instrument')
20 }
21
22 exports.handler = cliWrapper(async argv => {
23 if (argv.output && !argv.inPlace && (path.resolve(argv.cwd, argv.input) === path.resolve(argv.cwd, argv.output))) {
24 throw new Error('cannot instrument files in place, <input> must differ from <output>. Set \'--in-place\' to force')
25 }
26
27 if (path.relative(argv.cwd, path.resolve(argv.cwd, argv.input)).startsWith('..')) {
28 throw new Error('cannot instrument files outside project root directory')
29 }
30
31 if (argv.delete && argv.inPlace) {
32 throw new Error('cannot use \'--delete\' when instrumenting files in place')
33 }
34
35 if (argv.delete && argv.output && argv.output.length !== 0) {
36 const relPath = path.relative(process.cwd(), path.resolve(argv.output))
37 if (relPath !== '' && !relPath.startsWith('..')) {
38 await rimraf(argv.output)
39 } else {
40 throw new Error(`attempt to delete '${process.cwd()}' or containing directory.`)
41 }
42 }
43
44 // If instrument is set to false enable a noop instrumenter.
45 argv.instrumenter = (argv.instrument)
46 ? './lib/instrumenters/istanbul'
47 : './lib/instrumenters/noop'
48
49 if (argv.inPlace) {
50 argv.output = argv.input
51 argv.completeCopy = false
52 }
53
54 const nyc = new NYC(argv)
55 if (!argv.useSpawnWrap) {
56 nyc.require.forEach(requireModule => {
57 const mod = resolveFrom.silent(nyc.cwd, requireModule) || requireModule
58 require(mod)
59 })
60 }
61
62 await nyc.instrumentAllFiles(argv.input, argv.output)
63 })