Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: watch dynamic imports #397

Merged
merged 24 commits into from
Jun 15, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 33 additions & 8 deletions src/bin/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { platformIsValid } from '../helpers/get-runtime.js';
import { format } from '../helpers/format.js';
import { write } from '../helpers/logs.js';
import { hr } from '../helpers/hr.js';
import { mapTests } from '../services/map-tests.js';
import { watch } from '../services/watch.js';
import { poku } from '../modules/poku.js';
import { kill } from '../modules/processes.js';
Expand Down Expand Up @@ -111,21 +112,42 @@ import type { Configs } from '../@types/poku.js';
if (watchMode) {
const executing = new Set<string>();
const interval = Number(getArg('watch-interval')) || 1500;

fileResults.success.clear();
fileResults.fail.clear();

hr();
write(`Watching: ${dirs.join(', ')}`);
const resultsClear = () => {
fileResults.success.clear();
fileResults.fail.clear();
};

resultsClear();

mapTests('.', dirs).then((mappedTests) => [
Array.from(mappedTests.keys()).forEach((mappedTest) => {
watch(mappedTest, (file, event) => {
if (event === 'change') {
if (executing.has(file)) return;

executing.add(file);
resultsClear();

const tests = mappedTests.get(file);
if (!tests) return;

poku(tests, options).then(() => {
setTimeout(() => {
executing.delete(file);
}, interval);
});
}
});
}),
]);

dirs.forEach((dir) => {
watch(dir, (file, event) => {
if (event === 'change') {
if (executing.has(file)) return;

executing.add(file);
fileResults.success.clear();
fileResults.fail.clear();
resultsClear();

poku(file, options).then(() => {
setTimeout(() => {
Expand All @@ -135,6 +157,9 @@ import type { Configs } from '../@types/poku.js';
}
});
});

hr();
write(`Watching: ${dirs.join(', ')}`);
}
})();

Expand Down
12 changes: 12 additions & 0 deletions src/polyfills/fs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import {
stat as nodeStat,
readdir as nodeReaddir,
readFile as nodeReadFile,
type Dirent,
type Stats,
} from 'node:fs';
Expand All @@ -27,4 +28,15 @@ export const stat = (path: string): Promise<Stats> => {
});
};

export const readFile = (
path: string,
encoding: BufferEncoding = 'utf-8'
): Promise<string> =>
new Promise((resolve, reject) => {
nodeReadFile(path, encoding, (err, data) => {
if (err) reject(err);
else resolve(data);
});
});

/* c8 ignore stop */
53 changes: 53 additions & 0 deletions src/services/map-tests.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/* c8 ignore next */
import { relative, dirname } from 'node:path';
import { stat, readFile } from '../polyfills/fs.js';
import { listFiles } from '../modules/list-files.js';

const filter = /\.(js|cjs|mjs|ts|cts|mts)$/;

const normalizePath = (filePath: string) =>
filePath.replace(/(\.\.\/|\.\/)/g, '');
Fixed Show fixed Hide fixed

/* c8 ignore next */
export const mapTests = async (srcDir: string, testPaths: string[]) => {
const allTestFiles: string[] = [];
const allSrcFiles = await listFiles(srcDir, { filter });
const importMap = new Map<string, string[]>();

for (const testPath of testPaths) {
const stats = await stat(testPath);

if (stats.isDirectory()) {
const testFiles = await listFiles(testPath, { filter });

allTestFiles.push(...testFiles);
} else if (stats.isFile() && filter.test(testPath))
allTestFiles.push(testPath);
}

for (const testFile of allTestFiles) {
const content = await readFile(testFile, 'utf-8');

for (const srcFile of allSrcFiles) {
const relativePath = normalizePath(
relative(dirname(testFile), srcFile).replace(/\\/g, '/')
);

const normalizedSrcFile = normalizePath(srcFile.replace(/\\/g, '/'));

/* c8 ignore start */
if (
content.includes(relativePath.replace(filter, '')) ||
content.includes(normalizedSrcFile)
) {
if (!importMap.has(normalizedSrcFile))
importMap.set(normalizedSrcFile, []);

importMap.get(normalizedSrcFile)!.push(testFile);
}
/* c8 ignore stop */
}
}

return importMap;
};
63 changes: 63 additions & 0 deletions test/unit/map-tests.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import process from 'node:process';
import { nodeVersion } from '../../src/helpers/get-runtime.js';

if (nodeVersion && nodeVersion < 14) process.exit(0);

import { join } from 'node:path';
import { writeFileSync, mkdirSync, rmSync } from 'node:fs';
import { it } from '../../src/modules/it.js';
import { describe } from '../../src/modules/describe.js';
import { beforeEach, afterEach } from '../../src/modules/each.js';
import { assert } from '../../src/modules/assert.js';
import { mapTests } from '../../src/services/map-tests.js';

const createFileSync = (filePath: string, content: string) => {
writeFileSync(filePath, content);
};

const createDirSync = (dirPath: string) => {
mkdirSync(dirPath, { recursive: true });
};

const removeDirSync = (dirPath: string) => {
rmSync(dirPath, { recursive: true, force: true });
};

const testSrcDir = 'test-src';
const testTestDir = 'test-tests';

describe('mapTests', async () => {
beforeEach(() => {
createDirSync(testSrcDir);
createDirSync(testTestDir);
createFileSync(join(testSrcDir, 'example.js'), 'export const foo = 42;');
createFileSync(
join(testTestDir, 'example.test.js'),
'import { foo } from "../test-src/example.js";'
);
});

afterEach(() => {
removeDirSync(testSrcDir);
removeDirSync(testTestDir);
});

await it('should map test files to their corresponding source files', async () => {
const importMap = await mapTests(testSrcDir, [testTestDir]);
const expected = new Map([
['test-src/example.js', ['test-tests/example.test.js']],
]);

assert.deepStrictEqual(importMap, expected);
});

await it('should map single test file correctly', async () => {
const singleTestFile = join(testTestDir, 'example.test.js');
const importMap = await mapTests(testSrcDir, [singleTestFile]);
const expected = new Map([
['test-src/example.js', ['test-tests/example.test.js']],
]);

assert.deepStrictEqual(importMap, expected);
});
});
Loading