Beispiel #1
0
NYC.prototype.createTempDirectory = function () {
  mkdirp.sync(this.tempDirectory())
  if (this.cache) mkdirp.sync(this.cacheDirectory)

  if (this._showProcessTree) {
    mkdirp.sync(this.processInfoDirectory())
  }
}
Beispiel #2
0
module.exports = (options = {}) => {
	const {name} = options;
	let dir = options.cwd;

	if (options.files) {
		dir = commonDir(dir, options.files);
	} else {
		dir = dir || process.cwd();
	}

	dir = pkgDir.sync(dir);

	if (dir) {
		dir = path.join(dir, 'node_modules', '.cache', name);

		if (dir && options.create) {
			makeDir.sync(dir);
		}

		if (options.thunk) {
			return (...args) => path.join(dir, ...args);
		}
	}

	return dir;
};
Beispiel #3
0
      it('copies all files from <input> to <output> as well as those that have been instrumented', function (done) {
        const args = [bin, 'instrument', '--complete-copy', './nyc-config-js', './output']

        // force node_modules to exist so we can verify that it is copied.
        const nmDir = path.resolve(fixturesCLI, 'nyc-config-js', 'node_modules')
        makeDir.sync(nmDir)
        fs.writeFileSync(path.join(nmDir, 'test-file'), '')
        const proc = spawn(process.execPath, args, {
          cwd: fixturesCLI,
          env: env
        })

        proc.on('close', function (code) {
          code.should.equal(0)
          const files = fs.readdirSync(path.resolve(fixturesCLI, './output'))
          files.should.include('index.js')
          files.should.include('ignore.js')
          files.should.include('package.json')
          files.should.include('node_modules')
          const includeTarget = path.resolve(fixturesCLI, 'output', 'ignore.js')
          fs.readFileSync(includeTarget, 'utf8')
            .should.match(/var cov_/)
          done()
        })
      })
Beispiel #4
0
test.beforeEach(t => {
	t.context.tmp = tempy.directory();

	for (const fixture of fixtures) {
		makeDir.sync(path.join(t.context.tmp, fixture));
	}
});
Beispiel #5
0
  var visitor = function (filename) {
    var ext
    var transform
    var inFile = path.resolve(inputDir, filename)
    var code = fs.readFileSync(inFile, 'utf-8')

    for (ext in _this.transforms) {
      if (filename.toLowerCase().substr(-ext.length) === ext) {
        transform = _this.transforms[ext]
        break
      }
    }

    if (transform) {
      code = transform(code, {filename: filename, relFile: inFile})
    }

    if (!output) {
      console.log(code)
    } else {
      var outFile = path.resolve(output, filename)
      mkdirp.sync(path.dirname(outFile))
      fs.writeFileSync(outFile, code, 'utf-8')
    }
  }
Beispiel #6
0
	get store() {
		try {
			let data = fs.readFileSync(this.path, this.encryptionKey ? null : 'utf8');

			if (this.encryptionKey) {
				try {
					const decipher = crypto.createDecipher(encryptionAlgorithm, this.encryptionKey);
					data = Buffer.concat([decipher.update(data), decipher.final()]);
				} catch (_) {}
			}

			data = this.deserialize(data);
			this._validate(data);
			return Object.assign(plainObject(), data);
		} catch (error) {
			if (error.code === 'ENOENT') {
				// TODO: Use `fs.mkdirSync` `recursive` option when targeting Node.js 12
				makeDir.sync(path.dirname(this.path));
				return plainObject();
			}

			if (this._options.clearInvalidConfig && error.name === 'SyntaxError') {
				return plainObject();
			}

			throw error;
		}
	}
Beispiel #7
0
function setupCrypto (crypto) {
  logger.info(`Installing ${crypto.display}...`)
  const cryptoDir = coinUtils.cryptoDir(crypto)
  makeDir.sync(cryptoDir)
  const cryptoPlugin = plugin(crypto)
  const oldDir = process.cwd()
  const tmpDir = '/tmp/blockchain-install'

  makeDir.sync(tmpDir)
  process.chdir(tmpDir)
  common.es('rm -rf *')
  common.fetchAndInstall(crypto)

  cryptoPlugin.setup(cryptoDir)

  common.writeFile(installedVolumeFilePath(crypto), '')
  process.chdir(oldDir)
}
Beispiel #8
0
	set store(value) {
		// Ensure the directory exists as it could have been deleted in the meantime
		makeDir.sync(path.dirname(this.path));

		this._validate(value);
		let data = this.serialize(value);

		if (this.encryptionKey) {
			const cipher = crypto.createCipher(encryptionAlgorithm, this.encryptionKey);
			data = Buffer.concat([cipher.update(Buffer.from(data)), cipher.final()]);
		}

		writeFileAtomic.sync(this.path, data);
		this.events.emit('change');
	}
Beispiel #9
0
test('workers ensure test files load the same version of ava', t => {
	const target = path.join(__dirname, 'fixture', 'ava-paths', 'target');

	// Copy the index.js so the testFile imports it. It should then load the correct AVA install.
	const targetInstall = path.join(target, 'node_modules/ava');
	makeDir.sync(targetInstall);
	fs.writeFileSync(
		path.join(targetInstall, 'index.js'),
		fs.readFileSync(path.join(__dirname, '../index.js'))
	);

	const testFile = path.join(target, 'test.js');
	execCli([testFile], {dirname: path.join('fixture', 'ava-paths', 'cwd')}, err => {
		t.ifError(err);
		t.end();
	});
});
  /**
   * Change the generator destination root directory.
   * This path is used to find storage, when using a file system helper method (like
   * `this.write` and `this.copy`)
   * @param  {String} rootPath new destination root path
   * @return {String}          destination root path
   */
  destinationRoot(rootPath) {
    if (typeof rootPath === 'string') {
      this._destinationRoot = path.resolve(rootPath);

      if (!fs.existsSync(rootPath)) {
        makeDir.sync(rootPath);
      }

      process.chdir(rootPath);
      this.env.cwd = rootPath;

      // Reset the storage
      this.config = this._getStorage();
    }

    return this._destinationRoot || this.env.cwd;
  }
Beispiel #11
0
exports.handler = function (argv) {
  process.env.NYC_CWD = process.cwd()
  const nyc = new NYC(argv)
  let inputStat
  try {
    inputStat = fs.statSync(argv.inputDirectory)
    if (!inputStat.isDirectory()) {
      console.error(`${argv.inputDirectory} was not a directory`)
      process.exit(1)
    }
  } catch (err) {
    console.error(`failed access input directory ${argv.inputDirectory} with error:\n\n${err.message}`)
    process.exit(1)
  }
  makeDir.sync(path.dirname(argv.outputFile))
  const map = nyc.getCoverageMapFromAllCoverageFiles(argv.inputDirectory)
  fs.writeFileSync(argv.outputFile, JSON.stringify(map, null, 2), 'utf8')
  console.info(`coverage files in ${argv.inputDirectory} merged into ${argv.outputFile}`)
}
Beispiel #12
0
	save() {
		if (!this.hasChanges) {
			return null;
		}

		const {snapPath} = this;
		const buffer = encodeSnapshots(this.snapshotsByHash);

		const reportPath = path.join(this.dir, this.reportFile);
		const existingReport = this.appendOnly ? tryRead(reportPath) : null;
		const reportBuffer = existingReport ?
			appendReportEntries(existingReport, this.reportEntries) :
			generateReport(this.relFile, this.snapFile, this.reportEntries);

		makeDir.sync(this.dir);
		const tmpSnapPath = writeFileAtomic.sync(snapPath, buffer);
		const tmpReportPath = writeFileAtomic.sync(reportPath, reportBuffer);

		return [tmpSnapPath, tmpReportPath, snapPath, reportPath];
	}
    var processor = function (name, callback) {
            var inputFile = path.resolve(inputDir, name),
                outputFile = path.resolve(outputDir, name),
                inputFileExtension = path.extname(inputFile),
                isJavaScriptFile = extensions.indexOf(inputFileExtension) > -1,
                oDir = path.dirname(outputFile),
                readStream, writeStream;

            callback = once(callback);
            mkdirp.sync(oDir);

            /* istanbul ignore if */
            if (fs.statSync(inputFile).isDirectory()) {
                return callback(null, name);
            }

            if (isJavaScriptFile) {
                fs.readFile(inputFile, 'utf8', function (err, data) {
                    /* istanbul ignore if */ if (err) { return callback(err, name); }
                    instrumenter.instrument(data, inputFile, function (iErr, instrumented) {
                        if (iErr) { return callback(iErr, name); }
                        fs.writeFile(outputFile, instrumented, 'utf8', function (err) {
                            return callback(err, name);
                        });
                    });
                });
            }
            else {
                // non JavaScript file, copy it as is
                readStream = fs.createReadStream(inputFile, {'bufferSize': READ_FILE_CHUNK_SIZE});
                writeStream = fs.createWriteStream(outputFile);

                readStream.on('error', callback);
                writeStream.on('error', callback);

                readStream.pipe(writeStream);
                readStream.on('end', function() {
                    callback(null, name);
                });
            }
        },
Beispiel #14
0
 beforeEach(function () {
   makeDir.sync(path.resolve(fixturesCLI, 'output', 'removed-by-clean'))
 })
Beispiel #15
0
function build(projectDir, cacheDir, userOptions, powerAssert) {
	// Compute a seed based on the Node.js version and the project directory.
	// Dependency hashes may vary based on the Node.js version, e.g. with the
	// @ava/stage-4 Babel preset. Sources and dependencies paths are absolute in
	// the generated module and verifier state. Those paths wouldn't necessarily
	// be valid if the project directory changes.
	const seed = md5Hex([process.versions.node, projectDir]);

	// Ensure cacheDir exists
	makeDir.sync(cacheDir);

	// The file names predict where valid options may be cached, and thus should
	// include the seed.
	const optionsFile = path.join(cacheDir, `${seed}.babel-options.js`);
	const verifierFile = path.join(cacheDir, `${seed}.verifier.bin`);

	const baseOptions = {
		babelrc: false,
		plugins: [],
		presets: [
			['@ava/transform-test-files', {powerAssert}]
		]
	};
	if (userOptions === 'default') {
		baseOptions.presets.unshift('@ava/stage-4');
	}

	// Include object rest spread support for node versions that support it
	// natively.
	if (userOptions === 'default' && semver.satisfies(process.versions.node, '>= 8.3.0')) {
		baseOptions.plugins.push('babel-plugin-syntax-object-rest-spread');
	}

	const baseConfig = configManager.createConfig({
		dir: AVA_DIR, // Presets are resolved relative to this directory
		hash: md5Hex(JSON.stringify(baseOptions)),
		json5: false,
		options: baseOptions,
		source: SOURCE
	});

	if (userOptions !== 'default') {
		baseConfig.extend(configManager.createConfig({
			dir: projectDir,
			options: userOptions === 'inherit' ?
				{babelrc: true} :
				userOptions,
			source: path.join(projectDir, 'package.json') + '#ava.babel',
			hash: md5Hex(JSON.stringify(userOptions))
		}));
	}

	const cache = configManager.prepareCache();
	return verifyExistingOptions(verifierFile, baseConfig, cache)
		.then(cacheKeys => {
			if (cacheKeys) {
				return cacheKeys;
			}

			return resolveOptions(baseConfig, cache, optionsFile, verifierFile);
		})
		.then(cacheKeys => ({
			getOptions: require(optionsFile).getOptions,
			// Include the seed in the cache keys used to store compilation results.
			cacheKeys: Object.assign({seed}, cacheKeys)
		}));
}
function run(config, opts, callback) {
    opts = opts || {};
    var iOpts = config.instrumentation,
        input = opts.input,
        output = opts.output,
        excludes = opts.excludes,
        file,
        stats,
        stream,
        includes,
        instrumenter,
        origCallback = callback,
        needBaseline = iOpts.saveBaseline(),
        baselineFile = path.resolve(iOpts.baselineFile());

    if (iOpts.completeCopy()) {
        includes = ['**/*'];
    }
    else {
        includes = iOpts.extensions().map(function(ext) {
            return '**/*' + ext;
        });
    }

    if (!input) {
        return callback(new Error('No input specified'));
    }

    instrumenter = libInstrument.createInstrumenter(iOpts.getInstrumenterOpts());

    if (needBaseline) {
        mkdirp.sync(path.dirname(baselineFile));
        instrumenter = new BaselineCollector(instrumenter);
        callback = function (err) {
            /* istanbul ignore else */
            if (!err) {
                console.error('Saving baseline coverage at ' + baselineFile);
                fs.writeFileSync(baselineFile, JSON.stringify(instrumenter.getCoverage()), 'utf8');
            }
            return origCallback(err);
        };
    }

    file = path.resolve(input);
    stats = fs.statSync(file);
    if (stats.isDirectory()) {
        if (!output) { return callback(inputError.create('Need an output directory when input is a directory!')); }
        if (output === file) { return callback(inputError.create('Cannot instrument into the same directory/ file as input!')); }
        mkdirp.sync(output);
        filesFor({
            root: file,
            includes: includes,
            excludes: excludes || iOpts.excludes(false),
            relative: true
        }, function (err, files) {
            /* istanbul ignore if */
            if (err) { return callback(err); }
            processFiles(instrumenter, {
                inputDir: file,
                outputDir: output,
                names: files,
                extensions: iOpts.extensions(),
                verbose: config.verbose
            }, callback);
        });
    } else {
        if (output) {
            stream = fs.createWriteStream(output);
        } else {
            stream = process.stdout;
        }
        stream.write(instrumenter.instrumentSync(fs.readFileSync(file, 'utf8'), file));
        if (stream !== process.stdout) {
            stream.end();
        }
        return callback();
    }
}
 const path = _.attempt(() => makeDir.sync(v))