File size: 10,220 Bytes
9332ccf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import { vi, describe, it, expect, beforeEach } from 'vitest';
import { expandHomeDir, getDirectorySuggestions } from './directoryUtils.js';
import type * as osActual from 'node:os';
import * as path from 'node:path';
import * as fs from 'node:fs';
import * as fsPromises from 'node:fs/promises';

vi.mock('@google/gemini-cli-core', async (importOriginal) => {
  const original =
    await importOriginal<typeof import('@google/gemini-cli-core')>();
  return {
    ...original,
    homedir: () => mockHomeDir,
  };
});

const mockHomeDir =
  process.platform === 'win32' ? 'C:\\Users\\testuser' : '/home/testuser';

vi.mock('node:os', async (importOriginal) => {
  const original = await importOriginal<typeof osActual>();
  return {
    ...original,
    homedir: vi.fn(() => mockHomeDir),
  };
});

vi.mock('node:fs', async (importOriginal) => {
  const actual = await importOriginal<typeof import('node:fs')>();
  return {
    ...actual,
    existsSync: vi.fn(),
    statSync: vi.fn(),
  };
});

vi.mock('node:fs/promises', () => ({
  opendir: vi.fn(),
}));

interface MockDirent {
  name: string;
  isDirectory: () => boolean;
}

function createMockDir(entries: MockDirent[]) {
  let index = 0;
  const iterator = {
    async next() {
      if (index < entries.length) {
        return { value: entries[index++], done: false };
      }
      return { value: undefined, done: true };
    },
    [Symbol.asyncIterator]() {
      return this;
    },
  };

  return {
    [Symbol.asyncIterator]() {
      return iterator;
    },
    close: vi.fn().mockResolvedValue(undefined),
  };
}

describe('directoryUtils', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  describe('expandHomeDir', () => {
    it('should expand ~ to the home directory', () => {
      expect(expandHomeDir('~')).toBe(mockHomeDir);
    });

    it('should expand ~/path to the home directory path', () => {
      const expected = path.join(mockHomeDir, 'Documents');
      expect(expandHomeDir('~/Documents')).toBe(expected);
    });

    it('should expand %userprofile% on Windows', () => {
      if (process.platform === 'win32') {
        const expected = path.join(mockHomeDir, 'Desktop');
        expect(expandHomeDir('%userprofile%\\Desktop')).toBe(expected);
      }
    });

    it('should not change a path that does not need expansion', () => {
      const regularPath = path.join('usr', 'local', 'bin');
      expect(expandHomeDir(regularPath)).toBe(regularPath);
    });

    it('should return an empty string if input is empty', () => {
      expect(expandHomeDir('')).toBe('');
    });
  });

  describe('getDirectorySuggestions', () => {
    it('should return suggestions for an empty path', async () => {
      vi.mocked(fs.existsSync).mockReturnValue(true);
      vi.mocked(fs.statSync).mockReturnValue({
        isDirectory: () => true,
      } as fs.Stats);
      vi.mocked(fsPromises.opendir).mockResolvedValue(
        createMockDir([
          { name: 'docs', isDirectory: () => true },
          { name: 'src', isDirectory: () => true },
          { name: 'file.txt', isDirectory: () => false },
        ]) as unknown as fs.Dir,
      );

      const suggestions = await getDirectorySuggestions('');
      expect(suggestions).toEqual([`docs${path.sep}`, `src${path.sep}`]);
    });

    it('should return suggestions for a partial path', async () => {
      vi.mocked(fs.existsSync).mockReturnValue(true);
      vi.mocked(fs.statSync).mockReturnValue({
        isDirectory: () => true,
      } as fs.Stats);
      vi.mocked(fsPromises.opendir).mockResolvedValue(
        createMockDir([
          { name: 'docs', isDirectory: () => true },
          { name: 'src', isDirectory: () => true },
        ]) as unknown as fs.Dir,
      );

      const suggestions = await getDirectorySuggestions('d');
      expect(suggestions).toEqual([`docs${path.sep}`]);
    });

    it('should return suggestions for a path with trailing slash', async () => {
      vi.mocked(fs.existsSync).mockReturnValue(true);
      vi.mocked(fs.statSync).mockReturnValue({
        isDirectory: () => true,
      } as fs.Stats);
      vi.mocked(fsPromises.opendir).mockResolvedValue(
        createMockDir([
          { name: 'sub', isDirectory: () => true },
        ]) as unknown as fs.Dir,
      );

      const suggestions = await getDirectorySuggestions('docs/');
      expect(suggestions).toEqual(['docs/sub/']);
    });

    it('should return suggestions for a path with ~', async () => {
      vi.mocked(fs.existsSync).mockReturnValue(true);
      vi.mocked(fs.statSync).mockReturnValue({
        isDirectory: () => true,
      } as fs.Stats);
      vi.mocked(fsPromises.opendir).mockResolvedValue(
        createMockDir([
          { name: 'Downloads', isDirectory: () => true },
        ]) as unknown as fs.Dir,
      );

      const suggestions = await getDirectorySuggestions('~/');
      expect(suggestions).toEqual(['~/Downloads/']);
    });

    it('should return suggestions for a partial path with ~', async () => {
      vi.mocked(fs.existsSync).mockReturnValue(true);
      vi.mocked(fs.statSync).mockReturnValue({
        isDirectory: () => true,
      } as fs.Stats);
      vi.mocked(fsPromises.opendir).mockResolvedValue(
        createMockDir([
          { name: 'Downloads', isDirectory: () => true },
        ]) as unknown as fs.Dir,
      );

      const suggestions = await getDirectorySuggestions('~/Down');
      expect(suggestions).toEqual(['~/Downloads/']);
    });

    it('should return suggestions for ../', async () => {
      vi.mocked(fs.existsSync).mockReturnValue(true);
      vi.mocked(fs.statSync).mockReturnValue({
        isDirectory: () => true,
      } as fs.Stats);
      vi.mocked(fsPromises.opendir).mockResolvedValue(
        createMockDir([
          { name: 'other-project', isDirectory: () => true },
        ]) as unknown as fs.Dir,
      );

      const suggestions = await getDirectorySuggestions('../');
      expect(suggestions).toEqual(['../other-project/']);
    });

    it('should ignore hidden directories', async () => {
      vi.mocked(fs.existsSync).mockReturnValue(true);
      vi.mocked(fs.statSync).mockReturnValue({
        isDirectory: () => true,
      } as fs.Stats);
      vi.mocked(fsPromises.opendir).mockResolvedValue(
        createMockDir([
          { name: '.git', isDirectory: () => true },
          { name: 'src', isDirectory: () => true },
        ]) as unknown as fs.Dir,
      );

      const suggestions = await getDirectorySuggestions('');
      expect(suggestions).toEqual([`src${path.sep}`]);
    });

    it('should show hidden directories when filter starts with .', async () => {
      vi.mocked(fs.existsSync).mockReturnValue(true);
      vi.mocked(fs.statSync).mockReturnValue({
        isDirectory: () => true,
      } as fs.Stats);
      vi.mocked(fsPromises.opendir).mockResolvedValue(
        createMockDir([
          { name: '.git', isDirectory: () => true },
          { name: '.github', isDirectory: () => true },
          { name: '.vscode', isDirectory: () => true },
          { name: 'src', isDirectory: () => true },
        ]) as unknown as fs.Dir,
      );

      const suggestions = await getDirectorySuggestions('.g');
      expect(suggestions).toEqual([`.git${path.sep}`, `.github${path.sep}`]);
    });

    it('should return empty array if directory does not exist', async () => {
      vi.mocked(fs.existsSync).mockReturnValue(false);
      const suggestions = await getDirectorySuggestions('nonexistent/');
      expect(suggestions).toEqual([]);
    });

    it('should limit results to 50 suggestions', async () => {
      vi.mocked(fs.existsSync).mockReturnValue(true);
      vi.mocked(fs.statSync).mockReturnValue({
        isDirectory: () => true,
      } as fs.Stats);

      // Create 200 directories
      const manyDirs = Array.from({ length: 200 }, (_, i) => ({
        name: `dir${String(i).padStart(3, '0')}`,
        isDirectory: () => true,
      }));

      vi.mocked(fsPromises.opendir).mockResolvedValue(
        createMockDir(manyDirs) as unknown as fs.Dir,
      );

      const suggestions = await getDirectorySuggestions('');
      expect(suggestions).toHaveLength(50);
    });

    it('should terminate early after 150 matches for performance', async () => {
      vi.mocked(fs.existsSync).mockReturnValue(true);
      vi.mocked(fs.statSync).mockReturnValue({
        isDirectory: () => true,
      } as fs.Stats);

      // Create 200 directories
      const manyDirs = Array.from({ length: 200 }, (_, i) => ({
        name: `dir${String(i).padStart(3, '0')}`,
        isDirectory: () => true,
      }));

      const mockDir = createMockDir(manyDirs);
      vi.mocked(fsPromises.opendir).mockResolvedValue(
        mockDir as unknown as fs.Dir,
      );

      await getDirectorySuggestions('');

      // The close method should be called, indicating early termination
      expect(mockDir.close).toHaveBeenCalled();
    });
  });

  describe.skipIf(process.platform !== 'win32')(
    'getDirectorySuggestions (Windows)',
    () => {
      it('should handle %userprofile% expansion', async () => {
        vi.mocked(fs.existsSync).mockReturnValue(true);
        vi.mocked(fs.statSync).mockReturnValue({
          isDirectory: () => true,
        } as fs.Stats);
        vi.mocked(fsPromises.opendir).mockResolvedValue(
          createMockDir([
            { name: 'Documents', isDirectory: () => true },
            { name: 'Downloads', isDirectory: () => true },
          ]) as unknown as fs.Dir,
        );

        expect(await getDirectorySuggestions('%userprofile%\\')).toEqual([
          `%userprofile%\\Documents${path.sep}`,
          `%userprofile%\\Downloads${path.sep}`,
        ]);

        vi.mocked(fsPromises.opendir).mockResolvedValue(
          createMockDir([
            { name: 'Documents', isDirectory: () => true },
            { name: 'Downloads', isDirectory: () => true },
          ]) as unknown as fs.Dir,
        );

        expect(await getDirectorySuggestions('%userprofile%\\Doc')).toEqual([
          `%userprofile%\\Documents${path.sep}`,
        ]);
      });
    },
  );
});