-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcmd-index.ts
More file actions
216 lines (199 loc) · 7.45 KB
/
cmd-index.ts
File metadata and controls
216 lines (199 loc) · 7.45 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
/**
* Index command - Index a data source
*/
import { Command } from "commander";
import { Indexer } from "../core/indexer.js";
import { Source } from "../sources/types.js";
import { FilesystemStore } from "../stores/filesystem.js";
import { getS3Config } from "../stores/s3-config.js";
import { buildClientUserAgent } from "../core/utils.js";
// Shared store options
interface StoreOptions {
index?: string;
store: string;
storePath?: string;
}
function addStoreOptions(cmd: Command): Command {
return cmd
.option("-i, --index <name>", "Index name (creates named index in indexes/ subdirectory)")
.option("--store <type>", "Store type: filesystem, s3 (S3 requires CC_S3_* env vars)", "filesystem")
.option("--store-path <path>", "Store base path (files stored directly here if no --index)");
}
/**
* Create a store based on options.
*/
async function createStore(options: StoreOptions) {
if (options.store === "filesystem") {
return new FilesystemStore({ basePath: options.storePath });
} else if (options.store === "s3") {
const s3Config = getS3Config();
if (!s3Config.bucket) {
console.error("S3 store requires CC_S3_BUCKET environment variable");
process.exit(1);
}
const { S3Store } = await import("../stores/s3.js");
return new S3Store(s3Config);
} else {
console.error(`Unknown store type: ${options.store}`);
process.exit(1);
}
}
async function runIndex(
source: Source,
store: Awaited<ReturnType<typeof createStore>>,
indexKey: string,
sourceType: string
) {
console.log(`Indexing ${sourceType} source...`);
const indexer = new Indexer({
clientUserAgent: buildClientUserAgent("cli"),
});
const result = await indexer.index(source, store, indexKey);
console.log(`\nIndexing complete!`);
console.log(` Type: ${result.type}`);
console.log(` Duration: ${result.duration}ms`);
console.log();
console.log(`Summary:`);
console.log(` Total files: ${result.filesIndexed}`);
if (result.filesNewOrModified > 0) {
console.log(` - New/modified: ${result.filesNewOrModified} (uploaded and indexed)`);
}
if (result.filesUnchanged > 0) {
console.log(` - Unchanged: ${result.filesUnchanged} (skipped)`);
}
if (result.filesRemoved > 0) {
console.log(` Files removed: ${result.filesRemoved}`);
}
}
// GitHub subcommand
const githubCommand = new Command("github")
.description("Index a GitHub repository")
.requiredOption("--owner <owner>", "Repository owner")
.requiredOption("--repo <repo>", "Repository name")
.option("--ref <ref>", "Branch, tag, or commit", "HEAD");
addStoreOptions(githubCommand);
githubCommand.action(async (options) => {
try {
const { GitHubSource } = await import("../sources/github.js");
const source = new GitHubSource({
owner: options.owner,
repo: options.repo,
ref: options.ref,
});
const store = await createStore(options);
const indexKey = options.index || ".";
await runIndex(source, store, indexKey, "github");
} catch (error) {
console.error("Indexing failed:", error);
process.exit(1);
}
});
// GitLab subcommand
const gitlabCommand = new Command("gitlab")
.description("Index a GitLab project")
.requiredOption("--project <id>", "Project ID or path (e.g., group/project)")
.option("--ref <ref>", "Branch, tag, or commit", "HEAD")
.option("--gitlab-url <url>", "GitLab base URL (for self-hosted)", "https://gitlab.com");
addStoreOptions(gitlabCommand);
gitlabCommand.action(async (options) => {
try {
const { GitLabSource } = await import("../sources/gitlab.js");
const source = new GitLabSource({
baseUrl: options.gitlabUrl,
projectId: options.project,
ref: options.ref,
});
const store = await createStore(options);
const indexKey = options.index || ".";
await runIndex(source, store, indexKey, "gitlab");
} catch (error) {
console.error("Indexing failed:", error);
process.exit(1);
}
});
// BitBucket subcommand
const bitbucketCommand = new Command("bitbucket")
.description("Index a Bitbucket repository")
.requiredOption("--workspace <slug>", "Workspace slug")
.requiredOption("--repo <repo>", "Repository name")
.option("--ref <ref>", "Branch, tag, or commit", "HEAD")
.option("--bitbucket-url <url>", "Bitbucket base URL (for Server/Data Center)", "https://api.bitbucket.org/2.0");
addStoreOptions(bitbucketCommand);
bitbucketCommand.action(async (options) => {
try {
const { BitBucketSource } = await import("../sources/bitbucket.js");
const source = new BitBucketSource({
baseUrl: options.bitbucketUrl,
workspace: options.workspace,
repo: options.repo,
ref: options.ref,
});
const store = await createStore(options);
const indexKey = options.index || ".";
await runIndex(source, store, indexKey, "bitbucket");
} catch (error) {
console.error("Indexing failed:", error);
process.exit(1);
}
});
// Website subcommand
const websiteCommand = new Command("website")
.description("Crawl and index a website")
.requiredOption("--url <url>", "Website URL to crawl")
.option("--max-depth <n>", "Maximum crawl depth", (v) => parseInt(v, 10), 3)
.option("--max-pages <n>", "Maximum pages to crawl", (v) => parseInt(v, 10), 100)
.option("--include <patterns...>", "URL patterns to include (glob)")
.option("--exclude <patterns...>", "URL patterns to exclude (glob)")
.option("--save-content <dir>", "[Debug] Save crawled content to directory for inspection");
addStoreOptions(websiteCommand);
websiteCommand.action(async (options) => {
try {
const { WebsiteSource } = await import("../sources/website.js");
const source = new WebsiteSource({
url: options.url,
maxDepth: options.maxDepth,
maxPages: options.maxPages,
includePaths: options.include,
excludePaths: options.exclude,
});
// Save content locally if requested (this also triggers the crawl)
if (options.saveContent) {
const fs = await import("fs/promises");
const path = await import("path");
const files = await source.fetchAll();
const dir = path.resolve(options.saveContent);
await fs.mkdir(dir, { recursive: true });
let savedCount = 0;
for (const file of files) {
// Sanitize file.path to prevent path traversal attacks:
// 1. Normalize to resolve any .. segments
// 2. Ensure the result stays within the target directory
const safePath = path.normalize(file.path).replace(/^(\.\.[/\\])+/, "");
const filePath = path.resolve(dir, safePath);
if (!filePath.startsWith(dir + path.sep) && filePath !== dir) {
console.warn(`Skipping file with unsafe path: ${file.path}`);
continue;
}
await fs.mkdir(path.dirname(filePath), { recursive: true });
await fs.writeFile(filePath, file.contents, "utf-8");
savedCount++;
}
console.log(`Saved ${savedCount} files to ${dir}`);
// Note: source.fetchAll() caches results internally, so subsequent calls
// in runIndex will reuse the crawled data
}
const store = await createStore(options);
const indexKey = options.index || ".";
await runIndex(source, store, indexKey, "website");
} catch (error) {
console.error("Indexing failed:", error);
process.exit(1);
}
});
// Main index command
export const indexCommand = new Command("index")
.description("Index a data source")
.addCommand(githubCommand)
.addCommand(gitlabCommand)
.addCommand(bitbucketCommand)
.addCommand(websiteCommand);