From 984fe48f63a844ec10c92f313b669ab920c51438 Mon Sep 17 00:00:00 2001 From: Philippe Martin Date: Tue, 23 Jan 2024 12:19:29 +0100 Subject: [PATCH] fix: getLocalModels returns an empty array if the models folder does not exist (#117) * fix: getLocalModels returns an empty array if the models folder does not exist * remove duplicate code * fix windows path --- .../src/managers/modelsManager.spec.ts | 23 +++++++++++++++++++ .../backend/src/managers/modelsManager.ts | 3 +++ 2 files changed, 26 insertions(+) diff --git a/packages/backend/src/managers/modelsManager.spec.ts b/packages/backend/src/managers/modelsManager.spec.ts index 7b5778ddc..fbf0ea0a6 100644 --- a/packages/backend/src/managers/modelsManager.spec.ts +++ b/packages/backend/src/managers/modelsManager.spec.ts @@ -10,6 +10,15 @@ beforeEach(() => { test('getLocalModels should return models in local directory', () => { vi.spyOn(os, 'homedir').mockReturnValue('/home/user'); + const existsSyncSpy = vi.spyOn(fs, 'existsSync'); + existsSyncSpy.mockImplementation((path: string) => { + if (process.platform === 'win32') { + expect(path).toBe('\\home\\user\\aistudio\\models'); + } else { + expect(path).toBe('/home/user/aistudio/models'); + } + return true; + }); const readdirSyncMock = vi.spyOn(fs, 'readdirSync') as unknown as MockInstance< [path: string], string[] | fs.Dirent[] @@ -51,3 +60,17 @@ test('getLocalModels should return models in local directory', () => { }, ]); }); + +test('getLocalModels should return an empty array if the models folder does not exist', () => { + vi.spyOn(os, 'homedir').mockReturnValue('/home/user'); + const existsSyncSpy = vi.spyOn(fs, 'existsSync'); + existsSyncSpy.mockReturnValue(false); + const manager = new ModelsManager('/home/user/aistudio'); + const models = manager.getLocalModels(); + expect(models).toEqual([]); + if (process.platform === 'win32') { + expect(existsSyncSpy).toHaveBeenCalledWith('\\home\\user\\aistudio\\models'); + } else { + expect(existsSyncSpy).toHaveBeenCalledWith('/home/user/aistudio/models'); + } +}); diff --git a/packages/backend/src/managers/modelsManager.ts b/packages/backend/src/managers/modelsManager.ts index c69e3d97e..32ac7d3bf 100644 --- a/packages/backend/src/managers/modelsManager.ts +++ b/packages/backend/src/managers/modelsManager.ts @@ -8,6 +8,9 @@ export class ModelsManager { getLocalModels(): LocalModelInfo[] { const result: LocalModelInfo[] = []; const modelsDir = path.join(this.appUserDirectory, 'models'); + if (!fs.existsSync(modelsDir)) { + return []; + } const entries = fs.readdirSync(modelsDir, { withFileTypes: true }); const dirs = entries.filter(dir => dir.isDirectory()); for (const d of dirs) {