-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.mjs
More file actions
319 lines (278 loc) · 10.4 KB
/
index.mjs
File metadata and controls
319 lines (278 loc) · 10.4 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
#!/usr/bin/env node
import fs from 'fs';
import path from 'path';
import { glob } from 'glob';
import inquirer from 'inquirer';
import inquirerAutocompletePrompt from 'inquirer-autocomplete-prompt';
import { execSync } from 'child_process';
import ora from 'ora';
import { expandHomeDir, isGitRepo, validateMaxDepth, getExecuteCommand, validateConfig, getReadmePreview, detectLanguages } from './src/utils.mjs';
import { RepoCache } from './src/cache.mjs';
import { createInteractiveConfig } from './src/config.mjs';
// Register the autocomplete prompt
inquirer.registerPrompt('autocomplete', inquirerAutocompletePrompt);
// Get the directory from the first argument or default to the current directory
// Path to the configuration file
const configPath = path.resolve(process.env.HOME, '.lcodeconfig');
const cache = new RepoCache();
// Show help
if (process.argv.includes('--help') || process.argv.includes('-h')) {
console.log(`
lcode - A CLI tool to search your git repos and open them
Usage: lcode [path] [maxDepth] [command]
Arguments:
path Starting directory to search (default: current directory)
maxDepth Maximum search depth 1-10 (default: 5)
command Command to execute in selected repo (default: "code .")
Options:
--init Create configuration file (interactive)
--cleanup Remove configuration file
--list List all repositories (non-interactive)
--select N Select repository by index (0-based)
--lang L Filter by language (js, ts, python, java, kotlin, go, rust, ruby, php, nx, other)
Can specify multiple: --lang ts,js or --lang java,kotlin
--help Show this help
Examples:
lcode # Interactive mode
lcode --list # List all repos
lcode --list --lang ts # List only TypeScript repos
lcode --list --lang ts,js # List TypeScript or JavaScript repos
lcode --list --lang java,kotlin # List Java or Kotlin repos
lcode --select 0 # Select first repo
lcode ~ 5 --list # List repos from ~ with depth 5
lcode ~ 5 --select 2 "code ." # Select 3rd repo and open in VS Code
`);
process.exit(0);
}
// Main async function to handle top-level await
(async () => {
// Check if the program is called with --init
if (process.argv.includes('--init')) {
const success = await createInteractiveConfig();
process.exit(success ? 0 : 1);
}
// Check if the program is called with --cleanup
if (process.argv.includes('--cleanup')) {
try {
if (fs.existsSync(configPath)) {
fs.unlinkSync(configPath);
cache.clear();
console.log(`✓ Configuration file and cache removed`);
} else {
console.log(`No configuration file found at ${configPath}`);
}
} catch (error) {
console.error(`✗ Failed to cleanup: ${error.message}`);
process.exit(1);
}
process.exit(0);
}
// Load configuration
let config = {};
if (fs.existsSync(configPath)) {
try {
config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
// Validate config structure
const errors = validateConfig(config);
if (errors.length > 0) {
console.error(`✗ Invalid configuration: ${errors.join(', ')}`);
process.exit(1);
}
} catch (error) {
console.error(`✗ Invalid configuration file: ${error.message}`);
process.exit(1);
}
} else {
// No config exists - prompt user to create one (only in interactive mode)
const isNonInteractive = process.argv.includes('--list') ||
process.argv.includes('--select') ||
!process.stdin.isTTY;
if (!isNonInteractive) {
console.log('🔧 No configuration found. Let\'s set one up!');
const shouldCreate = await inquirer.prompt([
{
type: 'confirm',
name: 'create',
message: 'Would you like to create a configuration file?',
default: true
}
]);
if (shouldCreate.create) {
const success = await createInteractiveConfig();
if (success) {
// Reload the config
config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
}
} else {
console.log('Continuing with default settings...');
}
}
}
// Parse arguments properly
const selectIndex = process.argv.findIndex(arg => arg === '--select');
const selectValue = selectIndex !== -1 ? process.argv[selectIndex + 1] : null;
const langIndex = process.argv.findIndex(arg => arg === '--lang');
const langFilterRaw = langIndex !== -1 ? process.argv[langIndex + 1] : null;
const langFilters = langFilterRaw ? langFilterRaw.split(',').map(l => l.trim()) : null;
// Filter out --select, --lang and their values for normal arg parsing
const filteredArgs = process.argv.slice(2).filter((arg, index, arr) => {
if (arg === '--select') return false;
if (index > 0 && arr[index - 1] === '--select') return false;
if (arg === '--lang') return false;
if (index > 0 && arr[index - 1] === '--lang') return false;
if (arg === '--list') return false;
return true;
});
const BASE_DIR = path.resolve(filteredArgs[0] || expandHomeDir(config.path) || '.');
const MAX_DEPTH = validateMaxDepth(filteredArgs[1], config.maxDepth);
const EXECUTE = filteredArgs[2] || getExecuteCommand(process.argv, config);
// Recursively scan for directories containing a .git folder
const getGitRepos = (baseDir, maxDepth) => {
const spinner = ora('Scanning for git repositories...').start();
try {
const allDirs = glob.sync('**/*/', {
cwd: baseDir,
ignore: [
'**/node_modules/**',
'**/Applications/**',
'**/Desktop/**',
'**/Downloads/**',
'**/Library/**',
'**/Movies/**',
'**/Music/**',
'**/Pictures/**',
'**/Public/**',
'**/.git/**',
'**/build/**',
'**/dist/**',
'**/.next/**',
],
maxDepth: maxDepth,
});
const gitRepos = allDirs
.map((dir) => path.join(baseDir, dir))
.filter(isGitRepo);
spinner.succeed(`Found ${gitRepos.length} git repositories`);
return gitRepos;
} catch (error) {
spinner.fail(`Error scanning directories: ${error.message}`);
throw error;
}
};
// Get repos with caching
const getCachedRepos = (baseDir, maxDepth) => {
const cached = cache.get(baseDir, maxDepth);
if (cached) {
console.log(`Using cached results (${cached.length} repositories)`);
return cached;
}
const repos = getGitRepos(baseDir, maxDepth);
cache.set(baseDir, maxDepth, repos);
return repos;
};
// Main function to list repos and allow selection
const main = async () => {
try {
// Check if the base directory exists and is accessible
if (!fs.existsSync(BASE_DIR)) {
console.error(`✗ Directory "${BASE_DIR}" does not exist.`);
process.exit(1);
}
try {
fs.accessSync(BASE_DIR, fs.constants.R_OK);
} catch {
console.error(`✗ Directory "${BASE_DIR}" is not accessible.`);
process.exit(1);
}
const gitRepos = getCachedRepos(BASE_DIR, MAX_DEPTH);
if (gitRepos.length === 0) {
console.log('No git repositories found.');
return;
}
// Filter by language if specified
let filteredRepos = gitRepos;
if (langFilters) {
filteredRepos = gitRepos.filter(repo => {
const repoLangs = detectLanguages(repo);
return langFilters.some(filter => repoLangs.includes(filter));
});
if (filteredRepos.length === 0) {
console.log(`No repositories found with language(s): ${langFilters.join(', ')}`);
return;
}
console.log(`Filtered to ${filteredRepos.length} repositories with language(s): ${langFilters.join(', ')}`);
}
// Non-interactive modes
if (process.argv.includes('--list')) {
filteredRepos.forEach((repo, index) => {
const relativePath = path.relative(BASE_DIR, repo) || path.basename(repo);
const langs = detectLanguages(repo);
const langDisplay = langs.join(',');
const preview = getReadmePreview(repo, config.previewLength || 80);
const display = preview ? `${relativePath} [${langDisplay}] - ${preview}` : `${relativePath} [${langDisplay}]`;
console.log(`${index}: ${display}`);
});
return;
}
if (selectValue) {
const index = parseInt(selectValue, 10);
if (isNaN(index) || index < 0 || index >= filteredRepos.length) {
console.error(`✗ Invalid index ${index}. Available: 0-${filteredRepos.length - 1}`);
process.exit(1);
}
const selectedRepo = filteredRepos[index];
const relativePath = path.relative(BASE_DIR, selectedRepo) || path.basename(selectedRepo);
console.log(`→ Selected: ${relativePath}`);
console.log(`→ Command: ${EXECUTE}\n`);
execSync(`cd "${selectedRepo}" && ${EXECUTE}`, {
stdio: 'inherit',
shell: '/bin/bash'
});
return;
}
// Interactive mode
const choices = filteredRepos.map((repo) => {
const name = path.relative(BASE_DIR, repo) || path.basename(repo);
const langs = detectLanguages(repo);
const langDisplay = langs.join(',');
const preview = getReadmePreview(repo, config.previewLength || 80);
return {
name: preview ? `${name} [${langDisplay}] - ${preview}` : `${name} [${langDisplay}]`,
value: repo,
};
});
const answer = await inquirer.prompt([
{
type: 'autocomplete',
name: 'repo',
message: 'Select a git repository:',
source: (answersSoFar, input) => {
input = input || '';
return new Promise((resolve) => {
const filtered = choices.filter((choice) =>
choice.name.toLowerCase().includes(input.toLowerCase())
);
resolve(filtered);
});
},
},
]);
console.log(`\n→ Opening: ${path.relative(BASE_DIR, answer.repo) || path.basename(answer.repo)}`);
console.log(`→ Command: ${EXECUTE}\n`);
execSync(`cd "${answer.repo}" && ${EXECUTE}`, {
stdio: 'inherit',
shell: '/bin/bash'
});
} catch (error) {
if (error.isTtyError) {
console.error('✗ Prompt couldn\'t be rendered in the current environment');
} else if (error.message.includes('User force closed the prompt')) {
console.log('\nOperation cancelled.');
} else {
console.error('✗ An error occurred:', error.message);
}
process.exit(1);
}
};
await main();
})();