Skip to content

Commit

Permalink
feat(promisified fs): use node 10 promisified functions (#2028)
Browse files Browse the repository at this point in the history
BREAKING CHANGE: removed fsAsPromised from @stryker-mutator/util

Fixes #2028
  • Loading branch information
simondel authored Feb 12, 2020
1 parent 9eff1c7 commit 1c57d8f
Show file tree
Hide file tree
Showing 24 changed files with 88 additions and 139 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ jobs:
strategy:
fail-fast: false
matrix:
node-version: [8.x, 12.x]
node-version: [10.x, 12.x]

steps:
- uses: actions/checkout@v1
Expand Down
2 changes: 1 addition & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ language: node_js
install: npm install
node_js:
- 'node'
- '8'
- '10'
before_script:
- npm prune
- npm ls
Expand Down
7 changes: 4 additions & 3 deletions e2e/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import { promises as fs } from 'fs';

import { mutationTestReportSchema } from '@stryker-mutator/api/report';
import { fsAsPromised } from '@stryker-mutator/util';
import { expect } from 'chai';
import * as path from 'path';
import { calculateMetrics, MetricsResult, Metrics } from 'mutation-testing-metrics';

export async function readMutationTestResult(eventResultDirectory = path.resolve('reports', 'mutation', 'events')) {
const allReportFiles = await fsAsPromised.readdir(eventResultDirectory);
const allReportFiles = await fs.readdir(eventResultDirectory);
const mutationTestReportFile = allReportFiles.find(file => !!file.match(/.*onMutationTestReportReady.*/));
expect(mutationTestReportFile).ok;
const mutationTestReportContent = await fsAsPromised.readFile(path.resolve(eventResultDirectory, mutationTestReportFile || ''), 'utf8');
const mutationTestReportContent = await fs.readFile(path.resolve(eventResultDirectory, mutationTestReportFile || ''), 'utf8');
const report = JSON.parse(mutationTestReportContent) as mutationTestReportSchema.MutationTestResult;
const metricsResult = calculateMetrics(report.files);
return metricsResult;
Expand Down
5 changes: 3 additions & 2 deletions e2e/test/command/verify/verify.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { fsAsPromised } from '@stryker-mutator/util';
import { promises as fs } from 'fs';

import { expect } from 'chai';
import { expectMetricsResult, produceMetrics } from '../../../helpers';

Expand All @@ -20,7 +21,7 @@ describe('After running stryker with the command test runner', () => {
});

it('should write to a log file', async () => {
const strykerLog = await fsAsPromised.readFile('./stryker.log', 'utf8');
const strykerLog = await fs.readFile('./stryker.log', 'utf8');
expect(strykerLog).contains('INFO InitialTestExecutor Initial test run succeeded. Ran 1 test');
expect(strykerLog).matches(/Stryker Done in \d+/);
expect(strykerLog).not.contains('ERROR');
Expand Down
5 changes: 3 additions & 2 deletions e2e/test/jasmine-jasmine/verify/verify.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { fsAsPromised } from '@stryker-mutator/util';
import { promises as fs } from 'fs';

import { expect } from 'chai';
import { expectMetricsResult, produceMetrics } from '../../../helpers';

Expand All @@ -21,7 +22,7 @@ describe('After running stryker with test runner jasmine, test framework jasmine
});

it('should write to a log file', async () => {
const strykerLog = await fsAsPromised.readFile('./stryker.log', 'utf8');
const strykerLog = await fs.readFile('./stryker.log', 'utf8');
expect(strykerLog).matches(/INFO InputFileResolver Found 2 of 1\d file\(s\) to be mutated/);
expect(strykerLog).matches(/Stryker Done in \d+/);
// TODO, we now have an error because of a memory leak: https://github.com/jasmine/jasmine-npm/issues/134
Expand Down
5 changes: 2 additions & 3 deletions packages/core/src/di/PluginLoader.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import * as path from 'path';
import { readdirSync } from 'fs';

import { Logger } from '@stryker-mutator/api/logging';
import { commonTokens, Plugin, PluginKind, PluginResolver, Plugins } from '@stryker-mutator/api/plugin';
import { fsAsPromised } from '@stryker-mutator/util';
import { tokens } from 'typed-inject';

import { importModule } from '../utils/fileUtils';
Expand Down Expand Up @@ -59,8 +59,7 @@ export class PluginLoader implements PluginResolver {
const regexp = new RegExp('^' + path.basename(pluginExpression).replace('*', '.*'));

this.log.debug('Loading %s from %s', pluginExpression, pluginDirectory);
const plugins = fsAsPromised
.readdirSync(pluginDirectory)
const plugins = readdirSync(pluginDirectory)
.filter(pluginName => !IGNORED_PACKAGES.includes(pluginName) && regexp.test(pluginName))
.map(pluginName => path.resolve(pluginDirectory, pluginName));
if (plugins.length === 0) {
Expand Down
8 changes: 4 additions & 4 deletions packages/core/src/initializer/GitignoreWriter.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as os from 'os';
import { existsSync, promises as fs } from 'fs';

import { tokens } from '@stryker-mutator/api/plugin';
import { fsAsPromised } from '@stryker-mutator/util';
import { defaultTempDirName } from '@stryker-mutator/api/config';

import { initializerTokens } from '.';
Expand All @@ -13,11 +13,11 @@ export default class GitignoreWriter {
constructor(private readonly out: typeof console.log) {}

public async addStrykerTempFolder() {
if (fsAsPromised.existsSync(GITIGNORE_FILE)) {
const gitignoreContent = await fsAsPromised.readFile(GITIGNORE_FILE);
if (existsSync(GITIGNORE_FILE)) {
const gitignoreContent = await fs.readFile(GITIGNORE_FILE);
if (!gitignoreContent.toString().includes(defaultTempDirName)) {
const strykerTempFolderSpecification = `${os.EOL}# stryker temp files${os.EOL}${defaultTempDirName}${os.EOL}`;
await fsAsPromised.appendFile(GITIGNORE_FILE, strykerTempFolderSpecification);
await fs.appendFile(GITIGNORE_FILE, strykerTempFolderSpecification);
this.out('Note: Your .gitignore file has been updated to include recommended git ignore patterns for Stryker');
}
} else {
Expand Down
8 changes: 5 additions & 3 deletions packages/core/src/initializer/StrykerConfigWriter.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { existsSync, promises as fs } from 'fs';

import { StrykerOptions } from '@stryker-mutator/api/core';
import { Logger } from '@stryker-mutator/api/logging';
import { commonTokens, tokens } from '@stryker-mutator/api/plugin';
import { childProcessAsPromised, fsAsPromised } from '@stryker-mutator/util';
import { childProcessAsPromised } from '@stryker-mutator/util';

import PresetConfiguration from './presets/PresetConfiguration';
import PromptOption from './PromptOption';
Expand All @@ -15,7 +17,7 @@ export default class StrykerConfigWriter {
constructor(private readonly log: Logger, private readonly out: typeof console.log) {}

public guardForExistingConfig() {
if (fsAsPromised.existsSync(STRYKER_CONFIG_FILE)) {
if (existsSync(STRYKER_CONFIG_FILE)) {
const msg = 'Stryker config file "stryker.conf.js" already exists in the current directory. Please remove it and try again.';
this.log.error(msg);
throw new Error(msg);
Expand Down Expand Up @@ -77,7 +79,7 @@ export default class StrykerConfigWriter {
${rawConfig}
);
}`;
await fsAsPromised.writeFile(STRYKER_CONFIG_FILE, formattedConf);
await fs.writeFile(STRYKER_CONFIG_FILE, formattedConf);
try {
await childProcessAsPromised.exec(`npx prettier --write ${STRYKER_CONFIG_FILE}`);
} catch (error) {
Expand Down
5 changes: 3 additions & 2 deletions packages/core/src/input/InputFileResolver.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import * as path from 'path';
import { promises as fs } from 'fs';

import { Config } from '@stryker-mutator/api/config';
import { File, StrykerOptions } from '@stryker-mutator/api/core';
import { Logger } from '@stryker-mutator/api/logging';
import { commonTokens, tokens } from '@stryker-mutator/api/plugin';
import { SourceFile } from '@stryker-mutator/api/report';
import { childProcessAsPromised, fsAsPromised, isErrnoException, normalizeWhitespaces, StrykerError } from '@stryker-mutator/util';
import { childProcessAsPromised, isErrnoException, normalizeWhitespaces, StrykerError } from '@stryker-mutator/util';

import { coreTokens } from '../di';
import StrictReporter from '../reporters/StrictReporter';
Expand Down Expand Up @@ -135,7 +136,7 @@ export default class InputFileResolver {
}

private readFile(fileName: string): Promise<File | null> {
return fsAsPromised
return fs
.readFile(fileName)
.then((content: Buffer) => new File(fileName, content))
.then((file: File) => {
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/reporters/EventRecorderReporter.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import * as path from 'path';
import { promises as fs } from 'fs';

import { StrykerOptions } from '@stryker-mutator/api/core';
import { Logger } from '@stryker-mutator/api/logging';
import { commonTokens, tokens } from '@stryker-mutator/api/plugin';
import { MatchedMutant, MutantResult, mutationTestReportSchema, Reporter, ScoreResult, SourceFile } from '@stryker-mutator/api/report';
import { fsAsPromised } from '@stryker-mutator/util';

import { cleanFolder } from '../utils/fileUtils';

Expand Down Expand Up @@ -42,7 +42,7 @@ export default class EventRecorderReporter implements StrictReporter {
private writeToFile(methodName: keyof Reporter, data: any) {
const filename = path.join(this.baseFolder, `${this.format(this.index++)}-${methodName}.json`);
this.log.debug(`Writing event ${methodName} to file ${filename}`);
return fsAsPromised.writeFile(filename, JSON.stringify(data), { encoding: 'utf8' });
return fs.writeFile(filename, JSON.stringify(data), { encoding: 'utf8' });
}

private format(input: number) {
Expand Down
6 changes: 3 additions & 3 deletions packages/core/src/utils/TemporaryDirectory.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import * as path from 'path';
import { createReadStream, createWriteStream } from 'fs';

import { StrykerOptions } from '@stryker-mutator/api/core';
import { Logger } from '@stryker-mutator/api/logging';
import { commonTokens, tokens } from '@stryker-mutator/api/plugin';
import { fsAsPromised } from '@stryker-mutator/util';
import * as mkdirp from 'mkdirp';
import { Disposable } from 'typed-inject';

Expand Down Expand Up @@ -47,8 +47,8 @@ export class TemporaryDirectory implements Disposable {
*/
public copyFile(fromFilename: string, toFilename: string, instrumenter: NodeJS.ReadWriteStream | null): Promise<void> {
return new Promise<void>((resolve, reject) => {
let readStream: NodeJS.ReadableStream = fsAsPromised.createReadStream(fromFilename, { encoding: 'utf8' });
const writeStream = fsAsPromised.createWriteStream(toFilename);
let readStream: NodeJS.ReadableStream = createReadStream(fromFilename, { encoding: 'utf8' });
const writeStream = createWriteStream(toFilename);
readStream.on('error', reject);
writeStream.on('error', reject);
if (instrumenter) {
Expand Down
15 changes: 8 additions & 7 deletions packages/core/src/utils/fileUtils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as path from 'path';
import { promises as fs } from 'fs';

import { fsAsPromised } from '@stryker-mutator/util';
import * as nodeGlob from 'glob';
import * as mkdirp from 'mkdirp';
import * as rimraf from 'rimraf';
Expand All @@ -23,7 +23,7 @@ export function deleteDir(dirToDelete: string): Promise<void> {

export async function cleanFolder(folderName: string) {
try {
await fsAsPromised.lstat(folderName);
await fs.lstat(folderName);
await deleteDir(folderName);
return mkdirp.sync(folderName);
} catch (e) {
Expand All @@ -46,9 +46,9 @@ export function importModule(moduleName: string): unknown {
*/
export function writeFile(fileName: string, data: string | Buffer): Promise<void> {
if (Buffer.isBuffer(data)) {
return fsAsPromised.writeFile(fileName, data);
return fs.writeFile(fileName, data);
} else {
return fsAsPromised.writeFile(fileName, data, 'utf8');
return fs.writeFile(fileName, data, 'utf8');
}
}

Expand All @@ -58,7 +58,7 @@ export function writeFile(fileName: string, data: string | Buffer): Promise<void
* @param from The thing you want to point from
*/
export function symlinkJunction(to: string, from: string) {
return fsAsPromised.symlink(to, from, 'junction');
return fs.symlink(to, from, 'junction');
}

/**
Expand All @@ -69,9 +69,10 @@ export function symlinkJunction(to: string, from: string) {
export async function findNodeModules(basePath: string): Promise<string | null> {
basePath = path.resolve(basePath);
const nodeModules = path.resolve(basePath, 'node_modules');
if (await fsAsPromised.exists(nodeModules)) {
try {
await fs.stat(nodeModules);
return nodeModules;
} else {
} catch (e) {
const parent = path.dirname(basePath);
if (parent === basePath) {
return null;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as path from 'path';
import { promises as fs } from 'fs';

import { File } from '@stryker-mutator/api/core';
import { fsAsPromised } from '@stryker-mutator/util';
import { expect } from 'chai';

import { TranspiledSourceMapper } from '../../../src/transpiler/SourceMapper';
Expand All @@ -11,9 +11,7 @@ function resolve(...filePart: string[]) {
}

function readFiles(...files: string[]): Promise<File[]> {
return Promise.all(
files.map(relative => resolve(relative)).map(fileName => fsAsPromised.readFile(fileName).then(content => new File(fileName, content)))
);
return Promise.all(files.map(relative => resolve(relative)).map(fileName => fs.readFile(fileName).then(content => new File(fileName, content))));
}

describe('Source mapper integration', () => {
Expand Down
4 changes: 2 additions & 2 deletions packages/core/test/unit/di/PluginLoaderSpec.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as path from 'path';
import * as fs from 'fs';

import { testInjector } from '@stryker-mutator/test-helpers';
import { fsAsPromised } from '@stryker-mutator/util';
import { expect } from 'chai';
import * as sinon from 'sinon';

Expand All @@ -18,7 +18,7 @@ describe('PluginLoader', () => {
beforeEach(() => {
sandbox = sinon.createSandbox();
importModuleStub = sinon.stub(fileUtils, 'importModule');
pluginDirectoryReadMock = sinon.stub(fsAsPromised, 'readdirSync');
pluginDirectoryReadMock = sinon.stub(fs, 'readdirSync');
});

function createSut(pluginDescriptors: string[]) {
Expand Down
8 changes: 4 additions & 4 deletions packages/core/test/unit/initializer/GitignoreWriter.spec.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as os from 'os';
import * as fs from 'fs';

import * as sinon from 'sinon';
import { fsAsPromised } from '@stryker-mutator/util';
import { testInjector } from '@stryker-mutator/test-helpers';
import { expect } from 'chai';
import { defaultTempDirName } from '@stryker-mutator/api/config';
Expand All @@ -20,9 +20,9 @@ describe(GitignoreWriter.name, () => {

beforeEach(() => {
out = sinon.stub();
fsAppendFile = sinon.stub(fsAsPromised, 'appendFile');
fsExistsSync = sinon.stub(fsAsPromised, 'existsSync');
fsReadFile = sinon.stub(fsAsPromised, 'readFile');
fsAppendFile = sinon.stub(fs.promises, 'appendFile');
fsExistsSync = sinon.stub(fs, 'existsSync');
fsReadFile = sinon.stub(fs.promises, 'readFile');
sut = testInjector.injector.provideValue(initializerTokens.out, (out as unknown) as typeof console.log).injectClass(GitignoreWriter);
});

Expand Down
Loading

0 comments on commit 1c57d8f

Please sign in to comment.