-
Notifications
You must be signed in to change notification settings - Fork 13.3k
Expand file tree
/
Copy pathpaths.ts
More file actions
415 lines (363 loc) · 11.7 KB
/
paths.ts
File metadata and controls
415 lines (363 loc) · 11.7 KB
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import path from 'node:path';
import os from 'node:os';
import * as crypto from 'node:crypto';
import * as fs from 'node:fs';
import { fileURLToPath } from 'node:url';
export const GEMINI_DIR = '.gemini';
export const GOOGLE_ACCOUNTS_FILENAME = 'google_accounts.json';
/**
* Returns the home directory.
* If GEMINI_CLI_HOME environment variable is set, it returns its value.
* Otherwise, it returns the user's home directory.
*/
export function homedir(): string {
const envHome = process.env['GEMINI_CLI_HOME'];
if (envHome) {
return envHome;
}
return os.homedir();
}
/**
* Returns the operating system's default directory for temporary files.
*/
export function tmpdir(): string {
return os.tmpdir();
}
/**
* Replaces the home directory with a tilde.
* @param path - The path to tildeify.
* @returns The tildeified path.
*/
export function tildeifyPath(path: string): string {
const homeDir = homedir();
if (path.startsWith(homeDir)) {
return path.replace(homeDir, '~');
}
return path;
}
/**
* Shortens a path string if it exceeds maxLen, prioritizing the start and end segments.
* Example: /path/to/a/very/long/file.txt -> /path/.../long/file.txt
*/
export function shortenPath(filePath: string, maxLen: number = 35): string {
if (filePath.length <= maxLen) {
return filePath;
}
const simpleTruncate = () => {
const keepLen = Math.floor((maxLen - 3) / 2);
if (keepLen <= 0) {
return filePath.substring(0, maxLen - 3) + '...';
}
const start = filePath.substring(0, keepLen);
const end = filePath.substring(filePath.length - keepLen);
return `${start}...${end}`;
};
type TruncateMode = 'start' | 'end' | 'center';
const truncateComponent = (
component: string,
targetLength: number,
mode: TruncateMode,
): string => {
if (component.length <= targetLength) {
return component;
}
if (targetLength <= 0) {
return '';
}
if (targetLength <= 3) {
if (mode === 'end') {
return component.slice(-targetLength);
}
return component.slice(0, targetLength);
}
if (mode === 'start') {
return `${component.slice(0, targetLength - 3)}...`;
}
if (mode === 'end') {
return `...${component.slice(component.length - (targetLength - 3))}`;
}
const front = Math.ceil((targetLength - 3) / 2);
const back = targetLength - 3 - front;
return `${component.slice(0, front)}...${component.slice(
component.length - back,
)}`;
};
const parsedPath = path.parse(filePath);
const root = parsedPath.root;
const separator = path.sep;
// Get segments of the path *after* the root
const relativePath = filePath.substring(root.length);
const segments = relativePath.split(separator).filter((s) => s !== ''); // Filter out empty segments
// Handle cases with no segments after root (e.g., "/", "C:\") or only one segment
if (segments.length <= 1) {
// Fall back to simple start/end truncation for very short paths or single segments
return simpleTruncate();
}
const firstDir = segments[0];
const lastSegment = segments[segments.length - 1];
const startComponent = root + firstDir;
const endPartSegments = [lastSegment];
let endPartLength = lastSegment.length;
// Iterate backwards through the middle segments
for (let i = segments.length - 2; i > 0; i--) {
const segment = segments[i];
const newLength =
startComponent.length +
separator.length +
3 + // for "..."
separator.length +
endPartLength +
separator.length +
segment.length;
if (newLength <= maxLen) {
endPartSegments.unshift(segment);
endPartLength += separator.length + segment.length;
} else {
break;
}
}
const components = [firstDir, ...endPartSegments];
const componentModes: TruncateMode[] = components.map((_, index) => {
if (index === 0) {
return 'start';
}
if (index === components.length - 1) {
return 'end';
}
return 'center';
});
const separatorsCount = endPartSegments.length + 1;
const fixedLen = root.length + separatorsCount * separator.length + 3; // ellipsis length
const availableForComponents = maxLen - fixedLen;
const trailingFallback = () => {
const ellipsisTail = `...${separator}${lastSegment}`;
if (ellipsisTail.length <= maxLen) {
return ellipsisTail;
}
if (root) {
const rootEllipsisTail = `${root}...${separator}${lastSegment}`;
if (rootEllipsisTail.length <= maxLen) {
return rootEllipsisTail;
}
}
if (root && `${root}${lastSegment}`.length <= maxLen) {
return `${root}${lastSegment}`;
}
if (lastSegment.length <= maxLen) {
return lastSegment;
}
// As a final resort (e.g., last segment itself exceeds maxLen), fall back to simple truncation.
return simpleTruncate();
};
if (availableForComponents <= 0) {
return trailingFallback();
}
const minLengths = components.map((component, index) => {
if (index === 0) {
return Math.min(component.length, 1);
}
if (index === components.length - 1) {
return component.length; // Never truncate the last segment when possible.
}
return Math.min(component.length, 1);
});
const minTotal = minLengths.reduce((sum, len) => sum + len, 0);
if (availableForComponents < minTotal) {
return trailingFallback();
}
const budgets = components.map((component) => component.length);
let currentTotal = budgets.reduce((sum, len) => sum + len, 0);
const pickIndexToReduce = () => {
let bestIndex = -1;
let bestScore = -Infinity;
for (let i = 0; i < budgets.length; i++) {
if (budgets[i] <= minLengths[i]) {
continue;
}
const isLast = i === budgets.length - 1;
const score = (isLast ? 0 : 1_000_000) + budgets[i];
if (score > bestScore) {
bestScore = score;
bestIndex = i;
}
}
return bestIndex;
};
while (currentTotal > availableForComponents) {
const index = pickIndexToReduce();
if (index === -1) {
return trailingFallback();
}
budgets[index]--;
currentTotal--;
}
const truncatedComponents = components.map((component, index) =>
truncateComponent(component, budgets[index], componentModes[index]),
);
const truncatedFirst = truncatedComponents[0];
const truncatedEnd = truncatedComponents.slice(1).join(separator);
const result = `${root}${truncatedFirst}${separator}...${separator}${truncatedEnd}`;
if (result.length > maxLen) {
return trailingFallback();
}
return result;
}
/**
* Calculates the relative path from a root directory to a target path.
* If targetPath is relative, it is returned as-is.
* Returns '.' if the target path is the same as the root directory.
*
* @param targetPath The absolute or relative path to make relative.
* @param rootDirectory The absolute path of the directory to make the target path relative to.
* @returns The relative path from rootDirectory to targetPath.
*/
export function makeRelative(
targetPath: string,
rootDirectory: string,
): string {
if (!path.isAbsolute(targetPath)) {
return targetPath;
}
const resolvedRootDirectory = path.resolve(rootDirectory);
const relativePath = path.relative(resolvedRootDirectory, targetPath);
// If the paths are the same, path.relative returns '', return '.' instead
return relativePath || '.';
}
/**
* Escape paths for at-commands.
*
* - Windows: double quoted if they contain special chars, otherwise bare
* - POSIX: backslash-escaped
*/
export function escapePath(filePath: string): string {
if (process.platform === 'win32') {
// Windows: Double quote if it contains special chars
if (/[\s&()[\]{}^=;!'+,`~%$@#]/.test(filePath)) {
return `"${filePath}"`;
}
return filePath;
} else {
// POSIX: Backslash escape
return filePath.replace(/([ \t()[\]{};|*?$`'"#&<>!~\\])/g, '\\$1');
}
}
/**
* Unescapes paths for at-commands.
*
* - Windows: double quoted if they contain special chars, otherwise bare
* - POSIX: backslash-escaped
*/
export function unescapePath(filePath: string): string {
if (process.platform === 'win32') {
if (
filePath.length >= 2 &&
filePath.startsWith('"') &&
filePath.endsWith('"')
) {
return filePath.slice(1, -1);
}
return filePath;
} else {
return filePath.replace(/\\(.)/g, '$1');
}
}
/**
* Generates a unique hash for a project based on its root path.
* @param projectRoot The absolute path to the project's root directory.
* @returns A SHA256 hash of the project root path.
*/
export function getProjectHash(projectRoot: string): string {
return crypto.createHash('sha256').update(projectRoot).digest('hex');
}
/**
* Normalizes a path for reliable comparison across platforms.
* - Resolves to an absolute path.
* - Converts all path separators to forward slashes.
* - On Windows, converts to lowercase for case-insensitivity.
*/
export function normalizePath(p: string): string {
const resolved = path.resolve(p);
const normalized = resolved.replace(/\\/g, '/');
return process.platform === 'win32' ? normalized.toLowerCase() : normalized;
}
/**
* Checks if a path is a subpath of another path.
* @param parentPath The parent path.
* @param childPath The child path.
* @returns True if childPath is a subpath of parentPath, false otherwise.
*/
export function isSubpath(parentPath: string, childPath: string): boolean {
const isWindows = process.platform === 'win32';
const pathModule = isWindows ? path.win32 : path;
// On Windows, path.relative is case-insensitive. On POSIX, it's case-sensitive.
const relative = pathModule.relative(parentPath, childPath);
return (
!relative.startsWith(`..${pathModule.sep}`) &&
relative !== '..' &&
!pathModule.isAbsolute(relative)
);
}
/**
* Resolves a path to its real path, sanitizing it first.
* - Removes 'file://' protocol if present.
* - Decodes URI components (e.g. %20 -> space).
* - Resolves symbolic links using fs.realpathSync.
*
* @param pathStr The path string to resolve.
* @returns The resolved real path.
*/
export function resolveToRealPath(pathStr: string): string {
let resolvedPath = pathStr;
try {
if (resolvedPath.startsWith('file://')) {
resolvedPath = fileURLToPath(resolvedPath);
}
resolvedPath = decodeURIComponent(resolvedPath);
} catch (_e) {
// Ignore error (e.g. malformed URI), keep path from previous step
}
return robustRealpath(path.resolve(resolvedPath));
}
function robustRealpath(p: string, visited = new Set<string>()): string {
const key = process.platform === 'win32' ? p.toLowerCase() : p;
if (visited.has(key)) {
throw new Error(`Infinite recursion detected in robustRealpath: ${p}`);
}
visited.add(key);
try {
return fs.realpathSync(p);
} catch (e: unknown) {
if (e && typeof e === 'object' && 'code' in e && e.code === 'ENOENT') {
try {
const stat = fs.lstatSync(p);
if (stat.isSymbolicLink()) {
const target = fs.readlinkSync(p);
const resolvedTarget = path.resolve(path.dirname(p), target);
return robustRealpath(resolvedTarget, visited);
}
} catch (lstatError: unknown) {
// Not a symlink, or lstat failed. Re-throw if it's not an expected
// ENOENT (e.g., a permissions error), otherwise resolve parent.
if (
!(
lstatError &&
typeof lstatError === 'object' &&
'code' in lstatError &&
lstatError.code === 'ENOENT'
)
) {
throw lstatError;
}
}
const parent = path.dirname(p);
if (parent === p) return p;
return path.join(robustRealpath(parent, visited), path.basename(p));
}
throw e;
}
}