-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathfs.ts
More file actions
279 lines (248 loc) · 6.91 KB
/
Copy pathfs.ts
File metadata and controls
279 lines (248 loc) · 6.91 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
import * as fs from "fs/promises";
import * as path from "path";
import * as crypto from "crypto";
import { glob } from "glob";
import * as mimeTypes from "mime-types";
import * as ignore from "ignore";
import { FileSystemEntry, FileType } from "../types";
import { isEnhancedTextFile } from "./mime-types";
/**
* Check if a path exists
*/
export async function pathExists(filePath: string): Promise<boolean> {
try {
await fs.access(filePath);
return true;
} catch {
return false;
}
}
/**
* Get file system entry metadata
*/
export async function getFileSystemEntry(
filePath: string
): Promise<FileSystemEntry | null> {
try {
const stats = await fs.stat(filePath);
const type = stats.isDirectory()
? FileType.DIRECTORY
: (await isEnhancedTextFile(filePath))
? FileType.TEXT
: FileType.BINARY;
return {
path: filePath,
type,
size: stats.size,
mtime: stats.mtime,
permissions: stats.mode & parseInt("777", 8),
};
} catch {
return null;
}
}
/**
* Determine if a file is text or binary
*/
export async function isTextFile(filePath: string): Promise<boolean> {
try {
const mimeType = mimeTypes.lookup(filePath);
if (mimeType) {
return (
mimeType.startsWith("text/") ||
mimeType === "application/json" ||
mimeType === "application/xml" ||
mimeType.includes("javascript") ||
mimeType.includes("typescript")
);
}
// Sample first 8KB to detect binary content
const handle = await fs.open(filePath, "r");
const buffer = Buffer.alloc(Math.min(8192, (await handle.stat()).size));
await handle.read(buffer, 0, buffer.length, 0);
await handle.close();
// Check for null bytes which indicate binary content
return !buffer.includes(0);
} catch {
return false;
}
}
/**
* Read file content as string or buffer
*/
export async function readFileContent(
filePath: string
): Promise<string | Uint8Array> {
const isText = await isEnhancedTextFile(filePath);
if (isText) {
return await fs.readFile(filePath, "utf8");
} else {
const buffer = await fs.readFile(filePath);
return new Uint8Array(buffer);
}
}
/**
* Write file content from string or buffer
*/
export async function writeFileContent(
filePath: string,
content: string | Uint8Array
): Promise<void> {
await ensureDirectoryExists(path.dirname(filePath));
if (typeof content === "string") {
await fs.writeFile(filePath, content, "utf8");
} else {
await fs.writeFile(filePath, content);
}
}
/**
* Ensure directory exists, creating it if necessary
*/
export async function ensureDirectoryExists(dirPath: string): Promise<void> {
try {
await fs.mkdir(dirPath, { recursive: true });
} catch (error: any) {
if (error.code !== "EEXIST") {
throw error;
}
}
}
/**
* Remove file or directory
*/
export async function removePath(filePath: string): Promise<void> {
try {
const stats = await fs.stat(filePath);
if (stats.isDirectory()) {
await fs.rm(filePath, { recursive: true });
} else {
await fs.unlink(filePath);
}
} catch (error: any) {
if (error.code !== "ENOENT") {
throw error;
}
}
}
/**
* Check if a path matches any of the exclude patterns using the ignore library
* Supports proper gitignore-style patterns (e.g., "node_modules", "*.tmp", ".git")
*/
function isExcluded(
filePath: string,
basePath: string,
excludePatterns: string[]
): boolean {
if (excludePatterns.length === 0) return false;
const relativePath = path.relative(basePath, filePath);
// Use the ignore library which implements proper .gitignore semantics
// This is the same library used by ESLint and other major tools
const ig = ignore.default().add(excludePatterns);
return ig.ignores(relativePath);
}
/**
* List directory contents with metadata
*/
export async function listDirectory(
dirPath: string,
recursive = false,
excludePatterns: string[] = []
): Promise<FileSystemEntry[]> {
const entries: FileSystemEntry[] = [];
try {
const pattern = recursive
? path.join(dirPath, "**/*")
: path.join(dirPath, "*");
// Use glob to get all paths (with dot files)
// Note: We don't use glob's ignore option because it doesn't support gitignore semantics
const paths = await glob(pattern, {
dot: true,
});
// Parallelize all stat calls for better performance
const allEntries = await Promise.all(
paths.map(async (filePath) => {
// Filter using proper gitignore semantics from the ignore library
if (isExcluded(filePath, dirPath, excludePatterns)) {
return null;
}
return await getFileSystemEntry(filePath);
})
);
// Filter out null entries (excluded files or files that couldn't be read)
entries.push(...allEntries.filter((e): e is FileSystemEntry => e !== null));
} catch {
// Return empty array if directory doesn't exist or can't be read
}
return entries;
}
/**
* Copy file with metadata preservation
*/
export async function copyFile(
sourcePath: string,
destPath: string
): Promise<void> {
await ensureDirectoryExists(path.dirname(destPath));
await fs.copyFile(sourcePath, destPath);
// Preserve file permissions
const stats = await fs.stat(sourcePath);
await fs.chmod(destPath, stats.mode);
}
/**
* Move/rename file or directory
*/
export async function movePath(
sourcePath: string,
destPath: string
): Promise<void> {
await ensureDirectoryExists(path.dirname(destPath));
await fs.rename(sourcePath, destPath);
}
/**
* Calculate content hash for change detection
*/
export async function calculateContentHash(
content: string | Uint8Array
): Promise<string> {
const hash = crypto.createHash("sha256");
hash.update(content);
return hash.digest("hex");
}
/**
* Get MIME type for file
*/
export function getMimeType(filePath: string): string {
return mimeTypes.lookup(filePath) || "application/octet-stream";
}
/**
* Get file extension
*/
export function getFileExtension(filePath: string): string {
const ext = path.extname(filePath);
return ext.startsWith(".") ? ext.slice(1) : ext;
}
/**
* Normalize path separators for cross-platform compatibility
*/
export function normalizePath(filePath: string): string {
return path.posix.normalize(filePath.replace(/\\/g, "/"));
}
/**
* Get relative path from base directory
*/
export function getRelativePath(basePath: string, filePath: string): string {
return normalizePath(path.relative(basePath, filePath));
}
/**
* Format a path as a relative path with proper prefix
* Ensures paths like "src" become "./src" for clarity
* Leaves absolute paths and paths already starting with . or .. unchanged
*/
export function formatRelativePath(filePath: string): string {
// Already starts with . or / - leave as-is
if (filePath.startsWith(".") || filePath.startsWith("/")) {
return filePath;
}
// Add ./ prefix for clarity
return `./${filePath}`;
}