Elffuss BraidHub

kikocis/continue public

0a1f7aa3091d · 14.1 KiBRawPermalink
1import * as fs from "fs";
2import * as os from "os";
3import * as path from "path";
4import * as URI from "uri-js";
5import * as YAML from "yaml";
6
7import { ConfigYaml, DevEventName } from "@continuedev/config-yaml";
8import * as JSONC from "comment-json";
9import dotenv from "dotenv";
10
11import { IdeType, SerializedContinueConfig } from "../";
12import { defaultConfig, defaultConfigJetBrains } from "../config/default";
13import Types from "../config/types";
14
15dotenv.config();
16
17const CONTINUE_GLOBAL_DIR = (() => {
18 const configPath = process.env.CONTINUE_GLOBAL_DIR;
19 if (configPath) {
20 // Convert relative path to absolute paths based on current working directory
21 return path.isAbsolute(configPath)
22 ? configPath
23 : path.resolve(process.cwd(), configPath);
24 }
25 return path.join(os.homedir(), ".continue");
26})();
27
28// export const DEFAULT_CONFIG_TS_CONTENTS = `import { Config } from "./types"\n\nexport function modifyConfig(config: Config): Config {
29// return config;
30// }`;
31
32export const DEFAULT_CONFIG_TS_CONTENTS = `export function modifyConfig(config: Config): Config {
33 return config;
34}`;
35
36export function getChromiumPath(): string {
37 return path.join(getContinueUtilsPath(), ".chromium-browser-snapshots");
38}
39
40export function getContinueUtilsPath(): string {
41 const utilsPath = path.join(getContinueGlobalPath(), ".utils");
42 if (!fs.existsSync(utilsPath)) {
43 fs.mkdirSync(utilsPath);
44 }
45 return utilsPath;
46}
47
48export function getGlobalContinueIgnorePath(): string {
49 const continueIgnorePath = path.join(
50 getContinueGlobalPath(),
51 ".continueignore",
52 );
53 if (!fs.existsSync(continueIgnorePath)) {
54 fs.writeFileSync(continueIgnorePath, "");
55 }
56 return continueIgnorePath;
57}
58
59export function getContinueGlobalPath(): string {
60 // This is ~/.continue on mac/linux
61 const continuePath = CONTINUE_GLOBAL_DIR;
62 if (!fs.existsSync(continuePath)) {
63 fs.mkdirSync(continuePath);
64 }
65 return continuePath;
66}
67
68export function getSessionsFolderPath(): string {
69 const sessionsPath = path.join(getContinueGlobalPath(), "sessions");
70 if (!fs.existsSync(sessionsPath)) {
71 fs.mkdirSync(sessionsPath);
72 }
73 return sessionsPath;
74}
75
76export function getIndexFolderPath(): string {
77 const indexPath = path.join(getContinueGlobalPath(), "index");
78 if (!fs.existsSync(indexPath)) {
79 fs.mkdirSync(indexPath);
80 }
81 return indexPath;
82}
83
84export function getGlobalContextFilePath(): string {
85 return path.join(getIndexFolderPath(), "globalContext.json");
86}
87
88export function getSharedConfigFilePath(): string {
89 return path.join(getContinueGlobalPath(), "sharedConfig.json");
90}
91
92export function getSessionFilePath(sessionId: string): string {
93 return path.join(getSessionsFolderPath(), `${sessionId}.json`);
94}
95
96export function getSessionsListPath(): string {
97 const filepath = path.join(getSessionsFolderPath(), "sessions.json");
98 if (!fs.existsSync(filepath)) {
99 fs.writeFileSync(filepath, JSON.stringify([]));
100 }
101 return filepath;
102}
103
104export function getConfigJsonPath(): string {
105 const p = path.join(getContinueGlobalPath(), "config.json");
106 return p;
107}
108
109export function getConfigYamlPath(ideType?: IdeType): string {
110 const p = path.join(getContinueGlobalPath(), "config.yaml");
111 if (!fs.existsSync(p) && !fs.existsSync(getConfigJsonPath())) {
112 if (ideType === "jetbrains") {
113 fs.writeFileSync(p, YAML.stringify(defaultConfigJetBrains));
114 } else {
115 fs.writeFileSync(p, YAML.stringify(defaultConfig));
116 }
117 }
118 return p;
119}
120
121export function getPrimaryConfigFilePath(): string {
122 const configYamlPath = getConfigYamlPath();
123 if (fs.existsSync(configYamlPath)) {
124 return configYamlPath;
125 }
126 return getConfigJsonPath();
127}
128
129export function getConfigTsPath(): string {
130 const p = path.join(getContinueGlobalPath(), "config.ts");
131 if (!fs.existsSync(p)) {
132 fs.writeFileSync(p, DEFAULT_CONFIG_TS_CONTENTS);
133 }
134
135 const typesPath = path.join(getContinueGlobalPath(), "types");
136 if (!fs.existsSync(typesPath)) {
137 fs.mkdirSync(typesPath);
138 }
139 const corePath = path.join(typesPath, "core");
140 if (!fs.existsSync(corePath)) {
141 fs.mkdirSync(corePath);
142 }
143 const packageJsonPath = path.join(getContinueGlobalPath(), "package.json");
144 if (!fs.existsSync(packageJsonPath)) {
145 fs.writeFileSync(
146 packageJsonPath,
147 JSON.stringify({
148 name: "continue-config",
149 version: "1.0.0",
150 description: "My Continue Configuration",
151 main: "config.js",
152 }),
153 );
154 }
155
156 fs.writeFileSync(path.join(corePath, "index.d.ts"), Types);
157 return p;
158}
159
160export function getConfigJsPath(): string {
161 // Do not create automatically
162 return path.join(getContinueGlobalPath(), "out", "config.js");
163}
164
165export function getTsConfigPath(): string {
166 const tsConfigPath = path.join(getContinueGlobalPath(), "tsconfig.json");
167 if (!fs.existsSync(tsConfigPath)) {
168 fs.writeFileSync(
169 tsConfigPath,
170 JSON.stringify(
171 {
172 compilerOptions: {
173 target: "ESNext",
174 useDefineForClassFields: true,
175 lib: ["DOM", "DOM.Iterable", "ESNext"],
176 allowJs: true,
177 skipLibCheck: true,
178 esModuleInterop: false,
179 allowSyntheticDefaultImports: true,
180 strict: true,
181 forceConsistentCasingInFileNames: true,
182 module: "System",
183 moduleResolution: "Node",
184 noEmit: false,
185 noEmitOnError: false,
186 outFile: "./out/config.js",
187 typeRoots: ["./node_modules/@types", "./types"],
188 },
189 include: ["./config.ts"],
190 },
191 null,
192 2,
193 ),
194 );
195 }
196 return tsConfigPath;
197}
198
199export function getContinueRcPath(): string {
200 // Disable indexing of the config folder to prevent infinite loops
201 const continuercPath = path.join(getContinueGlobalPath(), ".continuerc.json");
202 if (!fs.existsSync(continuercPath)) {
203 fs.writeFileSync(
204 continuercPath,
205 JSON.stringify(
206 {
207 disableIndexing: true,
208 },
209 null,
210 2,
211 ),
212 );
213 }
214 return continuercPath;
215}
216
217function getDevDataPath(): string {
218 const sPath = path.join(getContinueGlobalPath(), "dev_data");
219 if (!fs.existsSync(sPath)) {
220 fs.mkdirSync(sPath);
221 }
222 return sPath;
223}
224
225export function getDevDataSqlitePath(): string {
226 return path.join(getDevDataPath(), "devdata.sqlite");
227}
228
229export function getDevDataFilePath(
230 eventName: DevEventName,
231 schema: string,
232): string {
233 const versionPath = path.join(getDevDataPath(), schema);
234 if (!fs.existsSync(versionPath)) {
235 fs.mkdirSync(versionPath);
236 }
237 return path.join(versionPath, `${String(eventName)}.jsonl`);
238}
239
240function editConfigJson(
241 callback: (config: SerializedContinueConfig) => SerializedContinueConfig,
242): void {
243 const config = fs.readFileSync(getConfigJsonPath(), "utf8");
244 let configJson = JSONC.parse(config);
245 // Check if it's an object
246 if (typeof configJson === "object" && configJson !== null) {
247 configJson = callback(configJson as any) as any;
248 fs.writeFileSync(getConfigJsonPath(), JSONC.stringify(configJson, null, 2));
249 } else {
250 console.warn("config.json is not a valid object");
251 }
252}
253
254function editConfigYaml(callback: (config: ConfigYaml) => ConfigYaml): void {
255 const config = fs.readFileSync(getConfigYamlPath(), "utf8");
256 let configYaml = YAML.parse(config);
257 // Check if it's an object
258 if (typeof configYaml === "object" && configYaml !== null) {
259 configYaml = callback(configYaml as any) as any;
260 fs.writeFileSync(getConfigYamlPath(), YAML.stringify(configYaml));
261 } else {
262 console.warn("config.yaml is not a valid object");
263 }
264}
265
266export function editConfigFile(
267 configJsonCallback: (
268 config: SerializedContinueConfig,
269 ) => SerializedContinueConfig,
270 configYamlCallback: (config: ConfigYaml) => ConfigYaml,
271): void {
272 if (fs.existsSync(getConfigYamlPath())) {
273 editConfigYaml(configYamlCallback);
274 } else if (fs.existsSync(getConfigJsonPath())) {
275 editConfigJson(configJsonCallback);
276 }
277}
278
279function getMigrationsFolderPath(): string {
280 const migrationsPath = path.join(getContinueGlobalPath(), ".migrations");
281 if (!fs.existsSync(migrationsPath)) {
282 fs.mkdirSync(migrationsPath);
283 }
284 return migrationsPath;
285}
286
287export async function migrate(
288 id: string,
289 callback: () => void | Promise<void>,
290 onAlreadyComplete?: () => void,
291) {
292 if (process.env.NODE_ENV === "test") {
293 return await Promise.resolve(callback());
294 }
295
296 const migrationsPath = getMigrationsFolderPath();
297 const migrationPath = path.join(migrationsPath, id);
298
299 if (!fs.existsSync(migrationPath)) {
300 try {
301 console.log(`Running migration: ${id}`);
302
303 fs.writeFileSync(migrationPath, "");
304 await Promise.resolve(callback());
305 } catch (e) {
306 console.warn(`Migration ${id} failed`, e);
307 }
308 } else if (onAlreadyComplete) {
309 onAlreadyComplete();
310 }
311}
312
313export function getIndexSqlitePath(): string {
314 return path.join(getIndexFolderPath(), "index.sqlite");
315}
316
317export function getLanceDbPath(): string {
318 return path.join(getIndexFolderPath(), "lancedb");
319}
320
321export function getTabAutocompleteCacheSqlitePath(): string {
322 return path.join(getIndexFolderPath(), "autocompleteCache.sqlite");
323}
324
325export function getDocsSqlitePath(): string {
326 return path.join(getIndexFolderPath(), "docs.sqlite");
327}
328
329export function getRemoteConfigsFolderPath(): string {
330 const dir = path.join(getContinueGlobalPath(), ".configs");
331 if (!fs.existsSync(dir)) {
332 fs.mkdirSync(dir);
333 }
334 return dir;
335}
336
337export function getPathToRemoteConfig(remoteConfigServerUrl: string): string {
338 let url: URL | undefined = undefined;
339 try {
340 url =
341 typeof remoteConfigServerUrl !== "string" || remoteConfigServerUrl === ""
342 ? undefined
343 : new URL(remoteConfigServerUrl);
344 } catch (e) {}
345 const dir = path.join(getRemoteConfigsFolderPath(), url?.hostname ?? "None");
346 if (!fs.existsSync(dir)) {
347 fs.mkdirSync(dir);
348 }
349 return dir;
350}
351
352export function getConfigJsonPathForRemote(
353 remoteConfigServerUrl: string,
354): string {
355 return path.join(getPathToRemoteConfig(remoteConfigServerUrl), "config.json");
356}
357
358export function getConfigJsPathForRemote(
359 remoteConfigServerUrl: string,
360): string {
361 return path.join(getPathToRemoteConfig(remoteConfigServerUrl), "config.js");
362}
363
364export function getContinueDotEnv(): { [key: string]: string } {
365 const filepath = path.join(getContinueGlobalPath(), ".env");
366 if (fs.existsSync(filepath)) {
367 return dotenv.parse(fs.readFileSync(filepath));
368 }
369 return {};
370}
371
372export function getLogsDirPath(): string {
373 const logsPath = path.join(getContinueGlobalPath(), "logs");
374 if (!fs.existsSync(logsPath)) {
375 fs.mkdirSync(logsPath);
376 }
377 return logsPath;
378}
379
380export function getCoreLogsPath(): string {
381 return path.join(getLogsDirPath(), "core.log");
382}
383
384export function getPromptLogsPath(): string {
385 return path.join(getLogsDirPath(), "prompt.log");
386}
387
388export function getGlobalFolderWithName(name: string): string {
389 return path.join(getContinueGlobalPath(), name);
390}
391
392export function getGlobalPromptsPath(): string {
393 return getGlobalFolderWithName("prompts");
394}
395
396export function readAllGlobalPromptFiles(
397 folderPath: string = getGlobalPromptsPath(),
398): { path: string; content: string }[] {
399 if (!fs.existsSync(folderPath)) {
400 return [];
401 }
402 const files = fs.readdirSync(folderPath);
403 const promptFiles: { path: string; content: string }[] = [];
404 files.forEach((file) => {
405 const filepath = path.join(folderPath, file);
406 const stats = fs.statSync(filepath);
407
408 if (stats.isDirectory()) {
409 const nestedPromptFiles = readAllGlobalPromptFiles(filepath);
410 promptFiles.push(...nestedPromptFiles);
411 } else if (file.endsWith(".prompt")) {
412 const content = fs.readFileSync(filepath, "utf8");
413 promptFiles.push({ path: filepath, content });
414 }
415 });
416
417 return promptFiles;
418}
419
420export function getRepoMapFilePath(): string {
421 return path.join(getContinueUtilsPath(), "repo_map.txt");
422}
423
424export function getEsbuildBinaryPath(): string {
425 return path.join(getContinueUtilsPath(), "esbuild");
426}
427
428export function migrateV1DevDataFiles() {
429 const devDataPath = getDevDataPath();
430 function moveToV1FolderIfExists(
431 oldFileName: string,
432 newFileName: DevEventName,
433 ) {
434 const oldFilePath = path.join(devDataPath, `${oldFileName}.jsonl`);
435 if (fs.existsSync(oldFilePath)) {
436 const newFilePath = getDevDataFilePath(newFileName, "0.1.0");
437 if (!fs.existsSync(newFilePath)) {
438 fs.copyFileSync(oldFilePath, newFilePath);
439 fs.unlinkSync(oldFilePath);
440 }
441 }
442 }
443 moveToV1FolderIfExists("tokens_generated", "tokensGenerated");
444 moveToV1FolderIfExists("chat", "chatFeedback");
445 moveToV1FolderIfExists("quickEdit", "quickEdit");
446 moveToV1FolderIfExists("autocomplete", "autocomplete");
447}
448
449export function getLocalEnvironmentDotFilePath(): string {
450 return path.join(getContinueGlobalPath(), ".local");
451}
452
453export function getStagingEnvironmentDotFilePath(): string {
454 return path.join(getContinueGlobalPath(), ".staging");
455}
456
457export function getDiffsDirectoryPath(): string {
458 const diffsPath = path.join(getContinueGlobalPath(), ".diffs"); // .replace(/^C:/, "c:"); ??
459 if (!fs.existsSync(diffsPath)) {
460 fs.mkdirSync(diffsPath, {
461 recursive: true,
462 });
463 }
464 return diffsPath;
465}
466
467export const isFileWithinFolder = (
468 fileUri: string,
469 folderPath: string,
470): boolean => {
471 try {
472 if (!fileUri || !folderPath) {
473 return false;
474 }
475
476 const fileUriParsed = URI.parse(fileUri);
477 const fileScheme = fileUriParsed.scheme || "file";
478 let filePath = fileUriParsed.path || "";
479 filePath = decodeURIComponent(filePath);
480
481 let folderWithScheme = folderPath;
482 if (!folderPath.includes("://")) {
483 folderWithScheme = `${fileScheme}://${folderPath.startsWith("/") ? "" : "/"}${folderPath}`;
484 }
485 const folderUriParsed = URI.parse(folderWithScheme);
486
487 let folderPathClean = folderUriParsed.path || "";
488 folderPathClean = decodeURIComponent(folderPathClean);
489
490 filePath = filePath.replace(/\/$/, "");
491 folderPathClean = folderPathClean.replace(/\/$/, "");
492
493 return (
494 filePath === folderPathClean || filePath.startsWith(`${folderPathClean}/`)
495 );
496 } catch (error) {
497 console.error("Error in isFileWithinFolder:", error);
498 return false;
499 }
500};