-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
executable file
·285 lines (243 loc) · 6.89 KB
/
Copy pathindex.js
File metadata and controls
executable file
·285 lines (243 loc) · 6.89 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
#!/usr/bin/env node
const fs = require("fs");
const path = require("path");
const minimist = require("minimist");
const ignore = require("ignore");
const { globSync } = require("glob");
const minimatch = require("minimatch");
const BINARY_EXTENSIONS = new Set([
".jpg",
".jpeg",
".png",
".gif",
".bmp",
".tiff",
".ico",
".svg",
".pdf",
".doc",
".docx",
".ppt",
".pptx",
".xls",
".xlsx",
".zip",
".tar",
".gz",
".7z",
".rar",
".mp3",
".mp4",
".avi",
".mov",
".wmv",
".ttf",
".woff",
".woff2",
".eot",
".exe",
".dll",
".so",
".dylib",
".pyc",
".class",
".o",
".obj",
".db",
".sqlite",
".mdb",
]);
const IGNORE_EXTENSIONS = new Set(['.md'])
const argv = minimist(process.argv.slice(2), {
boolean: ["help", "no-gitignore"],
string: ["include", "exclude", "output", "max-size"],
alias: {
h: "help",
i: "include",
e: "exclude",
o: "output",
n: "no-gitignore",
m: "max-size",
},
default: {
"no-gitignore": false,
"max-size": "1mb",
},
});
// Display help if requested
if (argv.help) {
console.log(`
llm-project-prompt - Generate an LLM prompt for your project's code
Usage:
llm-project-prompt [options]
Options:
-h, --help Show this help message
-i, --include Files or directories to include (glob pattern, can be used multiple times)
-e, --exclude Files or directories to exclude (glob pattern, can be used multiple times)
-o, --output Output file (defaults to stdout)
-n, --no-gitignore Ignore the .gitignore file
-m, --max-size Maximum size of the output (e.g., "1mb", "500kb", defaults to "1mb")
Examples:
llm-project-prompt
llm-project-prompt --include "src/**/*.js" --exclude "**/*.test.js"
llm-project-prompt --output prompt.txt
llm-project-prompt --max-size "2mb"
`);
process.exit(0);
}
function parseSize(sizeStr) {
const units = {
b: 1,
kb: 1024,
mb: 1024 * 1024,
gb: 1024 * 1024 * 1024,
};
const match = sizeStr.toLowerCase().match(/^(\d+(?:\.\d+)?)\s*([kmg]?b)$/);
if (!match) {
throw new Error(
`Invalid size format: ${sizeStr}. Use format like "1mb" or "500kb".`
);
}
const [, size, unit] = match;
return parseFloat(size) * (units[unit] || 1);
}
function estimateTokens(text) {
return Math.ceil(text.length / 4);
}
async function main() {
try {
const rootDir = process.cwd();
const maxSizeBytes = parseSize(argv["max-size"]);
let ignoreRules = ignore();
if (!argv["no-gitignore"]) {
const gitignorePath = path.join(rootDir, ".gitignore");
if (fs.existsSync(gitignorePath)) {
const gitignoreContent = fs.readFileSync(gitignorePath, "utf8");
ignoreRules = ignore().add(gitignoreContent);
}
}
const includePatterns = argv.include
? Array.isArray(argv.include)
? argv.include
: [argv.include]
: ["**/*"];
const excludePatterns = argv.exclude
? Array.isArray(argv.exclude)
? argv.exclude
: [argv.exclude]
: [];
let allFiles = [];
for (const pattern of includePatterns) {
const files = globSync(pattern, { cwd: rootDir, nodir: true });
allFiles = [...allFiles, ...files];
}
allFiles = [...new Set(allFiles)];
let filteredFiles = allFiles.filter((file) => {
const ext = path.extname(file).toLowerCase();
if (BINARY_EXTENSIONS.has(ext)) {
return false;
}
if (IGNORE_EXTENSIONS.has(ext)) {
return false;
}
for (const pattern of excludePatterns) {
if (minimatch(file, pattern)) {
return false;
}
}
if (!argv["no-gitignore"] && ignoreRules.ignores(file)) {
return false;
}
return true;
});
// Collect file info including size
const fileInfos = filteredFiles.map((file) => {
const filePath = path.join(rootDir, file);
const stats = fs.statSync(filePath);
return {
path: file,
size: stats.size,
};
});
let prompt = `# My Project code\n\n`;
prompt += `This prompt contains code files from the project.\n\n`;
let currentSize = prompt.length;
const skippedFiles = [];
const includedFiles = [];
prompt += `## File Contents\n\n`;
currentSize += 19; // Size of the header
for (const fileInfo of fileInfos) {
const filePath = path.join(rootDir, fileInfo.path);
try {
const content = fs.readFileSync(filePath, "utf8");
const extension = path.extname(fileInfo.path).substring(1); // Remove the dot
const fileHeader = `### File: ${fileInfo.path}\n\`\`\`${extension}\n`;
const fileFooter = `\n\`\`\`\n\n`;
const fileEntrySize =
fileHeader.length + content.length + fileFooter.length;
if (currentSize + fileEntrySize > maxSizeBytes) {
skippedFiles.push(fileInfo.path);
continue;
}
prompt += fileHeader + content + fileFooter;
currentSize += fileEntrySize;
includedFiles.push(fileInfo.path);
} catch (err) {
console.error(`Error reading file ${fileInfo.path}: ${err.message}`);
skippedFiles.push(fileInfo.path);
}
}
const promptLines = prompt.split("\n");
promptLines[2] = `This prompt contains ${includedFiles.length} files from the project.`;
if (skippedFiles.length > 0) {
promptLines.splice(
3,
0,
`Note: ${skippedFiles.length} files were skipped due to size constraints.`
);
}
const structureHeader = `## Project Structure\n\n`;
let structureContent = "";
const dirs = new Set();
for (const file of includedFiles) {
const dir = path.dirname(file);
if (dir !== ".") {
const parts = dir.split("/");
let currentPath = "";
for (const part of parts) {
currentPath = currentPath ? `${currentPath}/${part}` : part;
dirs.add(currentPath);
}
}
}
for (const dir of dirs) {
const depth = dir.split("/").length - 1;
const indent = " ".repeat(depth);
structureContent += `${indent}📁 ${dir}\n`;
}
for (const file of includedFiles) {
const dir = path.dirname(file);
const depth = dir === "." ? 0 : dir.split("/").length;
const indent = " ".repeat(depth);
structureContent += `${indent}📄 ${file}\n`;
}
promptLines.splice(4, 0, structureHeader + structureContent);
prompt = promptLines.join("\n");
const estimatedTokens = estimateTokens(prompt);
console.error(
`Prompt size: ${(prompt.length / 1024).toFixed(
2
)} KB, Est. tokens: ${estimatedTokens}`
);
if (argv.output) {
fs.writeFileSync(argv.output, prompt);
console.error(`Prompt written to ${argv.output}`);
} else {
console.log(prompt);
}
} catch (err) {
console.error(`Error: ${err.message}`);
process.exit(1);
}
}
main();