From f2fb5a9312b271f0e973e71359de976e7cba1853 Mon Sep 17 00:00:00 2001 From: Daniel Izdebski Date: Mon, 22 Jan 2024 16:52:10 +0100 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(core):=20Add=20`isDirEmpty`=20?= =?UTF-8?q?util?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/core/src/utils/isDirEmpty.ts | 7 ++++ packages/core/test/utils/isDirEmpty.test.ts | 39 +++++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 packages/core/src/utils/isDirEmpty.ts create mode 100644 packages/core/test/utils/isDirEmpty.test.ts diff --git a/packages/core/src/utils/isDirEmpty.ts b/packages/core/src/utils/isDirEmpty.ts new file mode 100644 index 000000000..e3fb88f2b --- /dev/null +++ b/packages/core/src/utils/isDirEmpty.ts @@ -0,0 +1,7 @@ +import fs from 'fs-extra' + +export async function isDirEmpty(dirPath: string) { + const files = await fs.readdir(dirPath) + + return files.length === 0 +} diff --git a/packages/core/test/utils/isDirEmpty.test.ts b/packages/core/test/utils/isDirEmpty.test.ts new file mode 100644 index 000000000..d28d15518 --- /dev/null +++ b/packages/core/test/utils/isDirEmpty.test.ts @@ -0,0 +1,39 @@ +import path from 'node:path' +import { fs, vol } from 'memfs' +import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { isDirEmpty } from '../../src/utils/isDirEmpty' + +const ROOT_DIR = '/tmp' +const FILE_PATH = path.join(ROOT_DIR, 'file.txt') + +vi.mock('fs-extra', async () => { + return { + default: fs.promises + } +}) + +describe('isDirEmpty', () => { + afterAll(() => { + vi.resetAllMocks() + }) + + beforeEach(() => { + vol.mkdirSync(ROOT_DIR) + }) + + afterEach(() => { + vol.reset() // Clear the in-memory file system after each test + }) + + it('returns `true` if the directory is empty', async () => { + const isEmpty = await isDirEmpty(ROOT_DIR) + expect(isEmpty).toEqual(true) + }) + + it('returns `false` if the directory contains files', async () => { + fs.writeFileSync(FILE_PATH, 'Hello there! 👋') + + const isEmpty = await isDirEmpty(ROOT_DIR) + expect(isEmpty).toEqual(false) + }) +})