chore(utils): extend fs utils with createCacheReadStream and statCach… (#30600)

This commit is contained in:
oxdev03 2024-08-05 18:57:21 +02:00 committed by GitHub
parent 1141b9d378
commit 5bdb8210ef
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 52 additions and 0 deletions

View file

@ -8,6 +8,7 @@ import {
cachePathExists,
cachePathIsFile,
chmodLocalFile,
createCacheReadStream,
createCacheWriteStream,
deleteLocalFile,
ensureCacheDir,
@ -32,6 +33,7 @@ import {
readSystemFile,
renameLocalFile,
rmCache,
statCacheFile,
statLocalFile,
writeLocalFile,
writeSystemFile,
@ -332,6 +334,29 @@ describe('util/fs/index', () => {
});
});
describe('createCacheReadStream', () => {
it('creates read stream', async () => {
const path = `${cacheDir}/file.txt`;
const fileContent = 'foo';
await fs.outputFile(path, fileContent);
const stream = createCacheReadStream('file.txt');
expect(stream).toBeInstanceOf(fs.ReadStream);
let data = '';
stream.on('data', (chunk) => {
data += chunk.toString();
});
await new Promise((resolve, reject) => {
stream.on('end', resolve);
stream.on('error', reject);
});
expect(data).toBe(fileContent);
});
});
describe('localPathIsFile', () => {
it('returns true for file', async () => {
const path = `${localDir}/file.txt`;
@ -431,6 +456,17 @@ describe('util/fs/index', () => {
});
});
describe('statCacheFile', () => {
it('returns stat object', async () => {
expect(await statCacheFile('foo')).toBeNull();
await fs.outputFile(`${cacheDir}/foo`, 'foobar');
const stat = await statCacheFile('foo');
expect(stat).toBeTruthy();
expect(stat!.isFile()).toBeTrue();
});
});
describe('listCacheDir', () => {
it('lists directory', async () => {
await fs.outputFile(`${cacheDir}/foo/bar.txt`, 'foobar');

View file

@ -176,6 +176,11 @@ export function createCacheWriteStream(path: string): fs.WriteStream {
return fs.createWriteStream(fullPath);
}
export function createCacheReadStream(path: string): fs.ReadStream {
const fullPath = ensureCachePath(path);
return fs.createReadStream(fullPath);
}
export async function localPathIsFile(pathName: string): Promise<boolean> {
const path = ensureLocalPath(pathName);
try {
@ -249,6 +254,17 @@ export async function statLocalFile(
}
}
export async function statCacheFile(
pathName: string,
): Promise<fs.Stats | null> {
const path = ensureCachePath(pathName);
try {
return await fs.stat(path);
} catch (_) {
return null;
}
}
export function listCacheDir(
path: string,
options: { recursive: boolean } = { recursive: false },