-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathindex.rs
More file actions
1702 lines (1458 loc) · 61.7 KB
/
index.rs
File metadata and controls
1702 lines (1458 loc) · 61.7 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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: MIT OR Apache-2.0
use anyhow::Result;
use clap::Parser;
use colored::Colorize;
use semcode::indexer::{
list_shas_in_range, process_commits_pipeline, process_lore_commits_pipeline,
};
use semcode::{measure, process_database_path, CodeVectorizer, DatabaseManager};
// Temporary call relationships are now embedded in function JSON columns
use semcode::perf_monitor::PERF_STATS;
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tracing::{error, info, warn};
#[derive(Parser, Debug)]
#[command(name = "semcode-index")]
#[command(about = "Index a codebase for semantic analysis", long_about = None)]
struct Args {
/// Path to the codebase directory (defaults to current directory)
#[arg(short, long, default_value = ".")]
source: PathBuf,
/// Path to database directory or parent directory containing .semcode.db (default: search source dir, then current dir)
#[arg(short, long)]
database: Option<String>,
/// File extensions to process (comma-separated)
#[arg(short, long, default_value_t = semcode::file_extensions::default_extensions_string())]
extensions: String,
/// Include directories (can be specified multiple times)
#[arg(short, long)]
include: Vec<PathBuf>,
/// Maximum depth for directory traversal
#[arg(long, default_value = "10")]
max_depth: usize,
/// Skip source indexing and only generate vectors for existing database content (requires model files)
#[arg(long)]
vectors: bool,
/// Use GPU for vectorization (if available)
#[arg(long)]
gpu: bool,
/// Path to local model directory (for vector generation)
#[arg(long, value_name = "PATH")]
model_path: Option<String>,
/// Number of files to process in a batch
#[arg(short, long, default_value = "200")]
batch_size: usize,
/// Parallelism configuration (analysis_threads[:batch_size])
/// Example: -j 16:512 means 16 analysis threads, batch size 512 for vectorization
#[arg(short = 'j', long = "jobs", value_name = "THREADS[:BATCH]")]
jobs: Option<String>,
/// Clear existing data before indexing
#[arg(long)]
clear: bool,
/// Skip typedef declarations (enabled by default)
#[arg(long)]
no_typedefs: bool,
/// Skip function-like macros (enabled by default)
#[arg(long)]
no_macros: bool,
/// Skip extracting comments before definitions (enabled by default)
#[arg(long)]
no_extra_comments: bool,
/// Drop and recreate tables after indexing for maximum space savings
#[arg(long)]
drop_recreate: bool,
/// Enable performance monitoring and display timing statistics
#[arg(long)]
perf: bool,
/// Index files modified in git commit range without checking them out.
/// Accepts range format only (SHA1..SHA2). Reads files directly from git blobs.
/// Uses incremental processing and deduplication with parallel streaming pipeline.
#[arg(long, value_name = "GIT_RANGE")]
git: Option<String>,
/// Index only git commit metadata for the specified revision range.
/// Accepts range format only (SHA1..SHA2), parsed the same way as --git.
/// Populates only the commits table without indexing any source files.
#[arg(long, value_name = "COMMIT_RANGE")]
commits: Option<String>,
/// Number of parallel database inserter threads for git range and commit indexing modes
#[arg(long, default_value = "2")]
db_threads: usize,
/// Clone and index lore.kernel.org archives into <db_dir>/lore/<repo>
/// Accepts comma-separated list of archives (e.g., --lore bpf,netdev,lkml/0)
/// Without arguments, refreshes all previously indexed archives
#[arg(long, value_name = "LIST", value_delimiter = ',', num_args = 0..)]
lore: Option<Vec<String>>,
// ==================== Multi-Branch Indexing ====================
/// Index a specific branch (can be specified multiple times)
/// Example: --branch main --branch develop
#[arg(long, value_name = "BRANCH")]
branch: Vec<String>,
/// Comma-separated list of branches to index
/// Example: --branches main,develop,feature-x
#[arg(long, value_name = "LIST", value_delimiter = ',')]
branches: Vec<String>,
/// Index all local branches
#[arg(long)]
all_branches: bool,
/// Include remote-tracking branches when using --all-branches
#[arg(long)]
remote_branches: bool,
/// Only index branches that have new commits since last indexed
/// (skip branches already indexed at current tip)
#[arg(long)]
update_branches: bool,
}
/// Fetch and parse the lore.kernel.org manifest
fn fetch_lore_manifest() -> Result<serde_json::Value> {
use flate2::read::GzDecoder;
use std::io::Read;
info!("Fetching lore.kernel.org manifest...");
let response = reqwest::blocking::get("https://lore.kernel.org/manifest.js.gz")?;
if !response.status().is_success() {
return Err(anyhow::anyhow!(
"Failed to fetch manifest: HTTP {}",
response.status()
));
}
let bytes = response.bytes()?;
let mut decoder = GzDecoder::new(&bytes[..]);
let mut json_str = String::new();
decoder.read_to_string(&mut json_str)?;
let manifest: serde_json::Value = serde_json::from_str(&json_str)?;
info!("Successfully fetched and parsed manifest");
// Print manifest in debug mode
if std::env::var("SEMCODE_DEBUG").as_deref() == Ok("debug") {
eprintln!("\n=== Lore Manifest ===");
eprintln!("{}", serde_json::to_string_pretty(&manifest)?);
eprintln!("===================\n");
}
Ok(manifest)
}
/// Resolve a lore list name to a full git URL
fn resolve_lore_url(lore_arg: &str, manifest: &serde_json::Value) -> Result<String> {
// Parse the list name and optional archive number
let (list_name, archive_num) = if let Some(slash_pos) = lore_arg.find('/') {
let (name, num) = lore_arg.split_at(slash_pos);
let num = num.trim_start_matches('/');
(name, Some(num))
} else {
(lore_arg, None)
};
// The manifest structure has keys like "/lkml/git/0.git", "/lkml/git/1.git", etc.
let lists = manifest
.as_object()
.ok_or_else(|| anyhow::anyhow!("Manifest is not a JSON object"))?;
// Find all entries matching the list name pattern
let pattern = format!("/{}/git/", list_name);
let mut matching_archives: Vec<(u32, String)> = Vec::new();
for (key, _value) in lists.iter() {
if key.starts_with(&pattern) && key.ends_with(".git") {
// Extract the archive number from the path
// Example: "/lkml/git/17.git" -> extract "17"
if let Some(num_str) = key
.strip_prefix(&pattern)
.and_then(|s| s.strip_suffix(".git"))
{
if let Ok(num) = num_str.parse::<u32>() {
let url = format!("https://lore.kernel.org{}", key);
matching_archives.push((num, url));
}
}
}
}
if matching_archives.is_empty() {
return Err(anyhow::anyhow!(
"List '{}' not found in manifest. Check available lists with SEMCODE_DEBUG=debug",
list_name
));
}
// Sort by archive number
matching_archives.sort_by_key(|(num, _)| *num);
if let Some(num) = archive_num {
// Specific archive requested
let requested_num = num
.parse::<u32>()
.map_err(|_| anyhow::anyhow!("Invalid archive number '{}'. Must be a number.", num))?;
matching_archives
.into_iter()
.find(|(n, _)| *n == requested_num)
.map(|(_, url)| url)
.ok_or_else(|| {
anyhow::anyhow!(
"Archive {}/{} not found in manifest",
list_name,
requested_num
)
})
} else {
// Find the latest archive (highest number)
let (max_num, url) = matching_archives
.last()
.ok_or_else(|| anyhow::anyhow!("No archives found for list '{}'", list_name))?;
info!(
"Resolved '{}' to latest archive: {}/{} (found {} total archives)",
list_name,
list_name,
max_num,
matching_archives.len()
);
Ok(url.clone())
}
}
/// Clone a lore.kernel.org archive into <db_dir>/lore/<repo>
async fn clone_lore_repository(lore_url: &str, db_path: &str) -> Result<PathBuf> {
use std::fs;
// Determine if lore_url is a direct URL or a list name
let final_url = if lore_url.starts_with("http://") || lore_url.starts_with("https://") {
// Direct URL provided - try to use it as-is
info!("Using provided URL: {}", lore_url);
// Check if it's a git repository by trying to clone
// We'll validate this later in the actual clone attempt
lore_url.to_string()
} else {
// Not a URL - treat as a list name and fetch manifest
info!(
"Resolving list name '{}' from lore.kernel.org manifest",
lore_url
);
println!("Fetching manifest from lore.kernel.org...");
let manifest = fetch_lore_manifest()?;
let resolved_url = resolve_lore_url(lore_url, &manifest)?;
println!("Resolved '{}' to: {}", lore_url, resolved_url);
info!("Resolved to URL: {}", resolved_url);
resolved_url
};
// Extract list path from URL
// Example: "https://lore.kernel.org/bpf/git/0.git" -> "bpf/0"
// We want to remove the "/git/" component that appears in the manifest URLs
// and strip the .git suffix from the final component
let url_parts: Vec<&str> = final_url.trim_end_matches('/').split('/').collect();
// Find where "lore.kernel.org" ends and extract everything after it
let lore_index = url_parts
.iter()
.position(|&part| part.contains("lore.kernel.org"));
let repo_name = if let Some(idx) = lore_index {
// Get all parts after lore.kernel.org
let parts_after = &url_parts[(idx + 1)..];
// Filter out "git" component if present
// Example: ["bpf", "git", "0.git"] -> ["bpf", "0.git"]
let filtered_parts: Vec<&str> = parts_after
.iter()
.filter(|&&part| part != "git")
.copied()
.collect();
// Strip .git suffix from the last component
// Example: "bpf/0.git" -> "bpf/0"
if filtered_parts.is_empty() {
return Err(anyhow::anyhow!("Invalid lore URL: {}", final_url));
}
let path_parts = filtered_parts;
let last_idx = path_parts.len() - 1;
let last_part = path_parts[last_idx]
.strip_suffix(".git")
.unwrap_or(path_parts[last_idx]);
if last_idx == 0 {
last_part.to_string()
} else {
format!("{}/{}", path_parts[..last_idx].join("/"), last_part)
}
} else {
// Fallback: just use the last two parts, filtering out "git"
let filtered_parts: Vec<&str> = url_parts
.iter()
.rev()
.take(3) // Take last 3 parts in case "git" is in there
.filter(|&&part| part != "git")
.take(2) // Only keep 2 parts
.copied()
.collect::<Vec<_>>()
.into_iter()
.rev()
.collect();
if filtered_parts.is_empty() {
return Err(anyhow::anyhow!("Invalid lore URL: {}", final_url));
}
// Strip .git suffix from the last component
let last_idx = filtered_parts.len() - 1;
let last_part = filtered_parts[last_idx]
.strip_suffix(".git")
.unwrap_or(filtered_parts[last_idx]);
if last_idx == 0 {
last_part.to_string()
} else {
format!("{}/{}", filtered_parts[..last_idx].join("/"), last_part)
}
};
// Create lore directory structure
let lore_base_dir = PathBuf::from(db_path).join("lore");
let clone_path = lore_base_dir.join(repo_name);
// Create the full directory tree including any subdirectories (e.g., lore/lkml/17)
// The parent() gives us everything except the final component, which will be created by git clone
if let Some(parent) = clone_path.parent() {
fs::create_dir_all(parent)?;
}
// Check if already cloned
if clone_path.exists() {
info!("Lore archive already exists at: {}", clone_path.display());
// Fetch new commits from remote
info!("Fetching new commits from remote...");
let repo = gix::discover(&clone_path)?;
// Find the remote named "origin"
let remote = repo.find_remote("origin")?;
// Connect and fetch - the receive() call automatically updates references
let connection = remote
.connect(gix::remote::Direction::Fetch)?
.prepare_fetch(gix::progress::Discard, Default::default())?;
let fetch_outcome =
connection.receive(gix::progress::Discard, &gix::interrupt::IS_INTERRUPTED)?;
// The receive() method in gix automatically calls refs::update() internally,
// so references should already be updated. Let's report what happened.
match &fetch_outcome.status {
gix::remote::fetch::Status::NoPackReceived { update_refs, .. } => {
info!(
"No new pack received. {} references checked, {} updated",
update_refs.updates.len(),
update_refs.edits.len()
);
}
gix::remote::fetch::Status::Change { update_refs, .. } => {
info!(
"Fetch complete: {} references checked, {} updated",
update_refs.updates.len(),
update_refs.edits.len()
);
}
}
// Note: We don't need to update the working tree.
// The lore indexer reads emails directly from git objects using gix,
// accessing the 'm' files from the object database, not the working directory.
// This is more efficient and doesn't require checking out files.
return Ok(clone_path);
}
println!(
"Cloning lore archive from {} to {}",
final_url,
clone_path.display()
);
info!(
"Cloning lore archive from {} to {}",
final_url,
clone_path.display()
);
// Use gix to clone the repository
// prepare_clone returns a PrepareFetch which can be configured and then executed
let mut prepare_clone = gix::prepare_clone(final_url.as_str(), &clone_path)?;
// Fetch and prepare for checkout
let (mut prepare_checkout, _fetch_outcome) = prepare_clone
.fetch_then_checkout(gix::progress::Discard, &gix::interrupt::IS_INTERRUPTED)?;
// Checkout the working tree
let (_repo, _checkout_outcome) =
prepare_checkout.main_worktree(gix::progress::Discard, &gix::interrupt::IS_INTERRUPTED)?;
info!(
"Successfully cloned lore archive to: {}",
clone_path.display()
);
Ok(clone_path)
}
/// Discover all existing lore archive repositories in <db_dir>/lore/
fn discover_lore_archives(db_path: &str) -> Result<Vec<PathBuf>> {
use std::fs;
let lore_base_dir = PathBuf::from(db_path).join("lore");
if !lore_base_dir.exists() {
return Ok(Vec::new());
}
let mut archives = Vec::new();
// Recursively find directories that are git repositories
fn find_git_repos(dir: &Path, repos: &mut Vec<PathBuf>) -> Result<()> {
if !dir.is_dir() {
return Ok(());
}
// Check if this directory is a git repo (has .git or is a bare repo with objects/)
let git_dir = dir.join(".git");
let objects_dir = dir.join("objects");
if git_dir.exists() || objects_dir.exists() {
repos.push(dir.to_path_buf());
return Ok(());
}
// Otherwise recurse into subdirectories
for entry in fs::read_dir(dir)? {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
find_git_repos(&path, repos)?;
}
}
Ok(())
}
find_git_repos(&lore_base_dir, &mut archives)?;
// Sort for consistent ordering
archives.sort();
Ok(archives)
}
/// Extract list name and archive number from a local lore archive path.
/// Returns (list_name, archive_number) if the path follows the expected structure.
///
/// Expected path structure: `<db_path>/lore/<list_name>/<archive_number>`
/// Example: `.semcode.db/lore/lkml/17` -> ("lkml", 17)
fn parse_lore_archive_path(archive_path: &Path, lore_base: &Path) -> Option<(String, u32)> {
// Get the path relative to lore base
let relative = archive_path.strip_prefix(lore_base).ok()?;
let components: Vec<_> = relative.components().collect();
if components.len() != 2 {
return None;
}
let list_name = components[0].as_os_str().to_str()?;
let archive_num_str = components[1].as_os_str().to_str()?;
let archive_num = archive_num_str.parse::<u32>().ok()?;
Some((list_name.to_string(), archive_num))
}
/// Check for new lore archives available on lore.kernel.org that are not locally cached.
/// Returns a list of (list_name, new_archive_numbers) for lists with newer archives.
fn find_new_lore_archives(
local_archives: &[PathBuf],
lore_base: &Path,
manifest: &serde_json::Value,
) -> Vec<(String, Vec<u32>)> {
use std::collections::HashMap;
// Build a map of list_name -> max local archive number
let mut local_max: HashMap<String, u32> = HashMap::new();
for archive_path in local_archives {
if let Some((list_name, archive_num)) = parse_lore_archive_path(archive_path, lore_base) {
local_max
.entry(list_name)
.and_modify(|max| {
if archive_num > *max {
*max = archive_num;
}
})
.or_insert(archive_num);
}
}
if local_max.is_empty() {
return Vec::new();
}
let lists = match manifest.as_object() {
Some(obj) => obj,
None => return Vec::new(),
};
let mut new_archives: Vec<(String, Vec<u32>)> = Vec::new();
for (list_name, max_local) in &local_max {
// Find all archives for this list in the manifest
let pattern = format!("/{}/git/", list_name);
let mut remote_archives: Vec<u32> = Vec::new();
for key in lists.keys() {
if key.starts_with(&pattern) && key.ends_with(".git") {
if let Some(num_str) = key
.strip_prefix(&pattern)
.and_then(|s| s.strip_suffix(".git"))
{
if let Ok(num) = num_str.parse::<u32>() {
if num > *max_local {
remote_archives.push(num);
}
}
}
}
}
if !remote_archives.is_empty() {
remote_archives.sort();
new_archives.push((list_name.clone(), remote_archives));
}
}
// Sort by list name for consistent output
new_archives.sort_by(|a, b| a.0.cmp(&b.0));
new_archives
}
/// Fetch new commits from remote for an existing lore archive.
/// Returns the opened repository on success so callers don't need to re-discover it.
///
/// This function wraps blocking git I/O in spawn_blocking to avoid blocking the
/// async executor thread during network operations.
async fn fetch_lore_archive(repo_path: PathBuf) -> Result<gix::Repository> {
info!(
"Fetching new commits from remote for {}...",
repo_path.display()
);
// Run blocking git operations on the blocking thread pool
let repo = tokio::task::spawn_blocking(move || -> Result<gix::Repository> {
let repo = gix::discover(&repo_path)?;
// Find the remote named "origin"
let remote = repo.find_remote("origin")?;
// Connect and fetch
let connection = remote
.connect(gix::remote::Direction::Fetch)?
.prepare_fetch(gix::progress::Discard, Default::default())?;
let fetch_outcome =
connection.receive(gix::progress::Discard, &gix::interrupt::IS_INTERRUPTED)?;
match &fetch_outcome.status {
gix::remote::fetch::Status::NoPackReceived { update_refs, .. } => {
info!(
"No new pack received. {} references checked, {} updated",
update_refs.updates.len(),
update_refs.edits.len()
);
}
gix::remote::fetch::Status::Change { update_refs, .. } => {
info!(
"Fetch complete: {} references checked, {} updated",
update_refs.updates.len(),
update_refs.edits.len()
);
}
}
Ok(repo)
})
.await??;
Ok(repo)
}
/// Result of indexing a single lore archive
struct LoreIndexResult {
new_emails: usize,
total_emails: usize,
}
/// Index a lore archive repository, filtering out already-indexed commits.
/// This is the common logic shared by both --lore and --refresh-lore handlers.
async fn index_lore_archive(
lore_repo: gix::Repository,
archive_path: &Path,
display_name: &str,
db_manager: &Arc<DatabaseManager>,
batch_size: usize,
num_workers: usize,
db_threads: usize,
) -> Result<LoreIndexResult> {
// Get the remote tracking branch to include all fetched commits
// Try refs/remotes/origin/master first, then refs/remotes/origin/main as fallback
let mut start_ref = lore_repo
.find_reference("refs/remotes/origin/master")
.or_else(|_| lore_repo.find_reference("refs/remotes/origin/main"))
.or_else(|_| {
info!("Remote tracking branch not found, using HEAD");
lore_repo
.head()?
.try_into_referent()
.ok_or_else(|| anyhow::anyhow!("HEAD is not a symbolic reference"))
})?;
let start_commit = start_ref.peel_to_commit()?;
// Use rev_walk to get all commits reachable from the remote tracking branch
let walk = lore_repo
.rev_walk([start_commit.id()])
.sorting(gix::revision::walk::Sorting::ByCommitTime(
Default::default(),
))
.all()?;
let mut all_commit_shas = Vec::new();
for info in walk {
all_commit_shas.push(info?.id().to_string());
}
// Reverse to get chronological order (oldest first)
all_commit_shas.reverse();
let total_commits = all_commit_shas.len();
info!("Found {} total commits in lore archive", total_commits);
// Get already indexed commits from database
println!("Checking for already-indexed commits...");
let existing_commits = db_manager.get_indexed_lore_commits().await?;
// Filter out already indexed commits
let new_commits: Vec<String> = all_commit_shas
.into_iter()
.filter(|sha| !existing_commits.contains(sha))
.collect();
let already_indexed = total_commits - new_commits.len();
if already_indexed > 0 {
println!(
"{} commits already indexed, processing {} new commits",
already_indexed,
new_commits.len()
);
} else {
println!("Processing all {} commits", new_commits.len());
}
if new_commits.is_empty() {
println!("All commits in {} are already indexed!", display_name);
return Ok(LoreIndexResult {
new_emails: 0,
total_emails: total_commits,
});
}
let new_count = new_commits.len();
// Process new commits
process_lore_commits_pipeline(
archive_path,
new_commits,
db_manager.clone(),
batch_size,
num_workers,
db_threads,
)
.await?;
println!(
"Indexed {} new emails from {} (total in archive: {})",
new_count, display_name, total_commits
);
Ok(LoreIndexResult {
new_emails: new_count,
total_emails: total_commits,
})
}
// ==================== Branch Indexing Support ====================
/// Collect branches to index from the various branch-related CLI flags
/// Returns BranchRef structs with proper is_remote/remote metadata
fn collect_branches_to_index(args: &Args) -> Result<Vec<semcode::git::BranchRef>> {
use semcode::git::{get_branch_info, list_branches, BranchRef};
let mut branch_names = Vec::new();
// Collect branch names from --branch flags (can be repeated)
branch_names.extend(args.branch.iter().cloned());
// Collect from --branches (comma-separated)
branch_names.extend(args.branches.iter().cloned());
// Remove duplicates while preserving order
let mut seen = HashSet::new();
branch_names.retain(|b| seen.insert(b.clone()));
// Convert manually-specified branch names to BranchRef with proper metadata
let mut branches: Vec<BranchRef> = Vec::new();
for name in &branch_names {
match get_branch_info(&args.source, name) {
Ok(branch_ref) => branches.push(branch_ref),
Err(e) => return Err(anyhow::anyhow!("Branch '{}' does not exist: {}", name, e)),
}
}
// If --all-branches is set, get all branches from git
if args.all_branches {
let git_branches = list_branches(&args.source, args.remote_branches)?;
for branch in git_branches {
// Skip if already added from --branch/--branches
if !branches.iter().any(|b| b.name == branch.name) {
branches.push(branch);
}
}
}
Ok(branches)
}
/// Run branch indexing mode - index multiple branches
async fn run_branch_indexing(args: Args, branches: Vec<semcode::git::BranchRef>) -> Result<()> {
info!("Starting multi-branch indexing mode");
info!(
"Branches to index: {:?}",
branches.iter().map(|b| &b.name).collect::<Vec<_>>()
);
// Process database path
let database_path = process_database_path(args.database.as_deref(), Some(&args.source));
// Create database manager wrapped in Arc for efficient sharing with process_git_range
// (Arc::clone is cheap - just increments ref count, reuses same LanceDB connection)
let db_manager = Arc::new(
DatabaseManager::new(&database_path, args.source.to_string_lossy().to_string()).await?,
);
db_manager.create_tables().await?;
if args.clear {
println!("Clearing existing data...");
db_manager.clear_all_data().await?;
println!("Existing data cleared.");
}
let start_time = std::time::Instant::now();
let mut branches_indexed = 0;
let mut branches_skipped = 0;
for branch in &branches {
let branch_name = &branch.name;
let tip_commit = &branch.tip_commit;
println!(
"\n{}",
format!("=== Processing branch: {} ===", branch_name).cyan()
);
info!("Branch {} at commit {}", branch_name, &tip_commit[..8]);
// Check if branch is already indexed at current tip (if --update-branches)
if args.update_branches
&& db_manager
.is_branch_current(branch_name, tip_commit)
.await?
{
println!(
" {} Branch already indexed at current tip, skipping",
"→".yellow()
);
branches_skipped += 1;
continue;
}
// Get extensions for this indexing operation
let extensions: Vec<String> = args
.extensions
.split(',')
.map(|s| s.trim().to_string())
.collect();
// Check if this is initial or incremental indexing
if let Some(indexed_tip) = db_manager.get_branch_tip(branch_name).await? {
// Incremental indexing: commits from last indexed tip to current tip
let range = format!("{}..{}", indexed_tip, tip_commit);
info!("Incremental indexing: {} for branch {}", range, branch_name);
println!(" {} Processing range: {}", "→".blue(), range);
// Get commit count for this range
let repo = gix::discover(&args.source)
.map_err(|e| anyhow::anyhow!("Not in a git repository: {}", e))?;
let commit_shas = match list_shas_in_range(&repo, &range) {
Ok(shas) => shas,
Err(e) => {
warn!("Failed to get commits for {}: {}", range, e);
vec![]
}
};
if commit_shas.is_empty() {
println!(" {} No new commits to index", "✓".green());
} else {
println!(
" {} Found {} commits to process",
"→".blue(),
commit_shas.len()
);
semcode::git_range::process_git_range(
&args.source,
&range,
&extensions,
db_manager.clone(),
args.no_macros,
args.db_threads,
)
.await?;
}
} else {
// Initial indexing: index the tree snapshot at the tip commit
// This is MUCH faster than walking all commits (e.g., 80k files vs 1.4M commits for Linux)
info!(
"Initial indexing for branch {} (tree at {})",
branch_name,
&tip_commit[..8]
);
println!(" {} Processing tree at {}", "→".blue(), &tip_commit[..8]);
semcode::git_range::process_git_tree(
&args.source,
tip_commit,
&extensions,
db_manager.clone(),
args.no_macros,
args.db_threads,
)
.await?;
}
// Record that this branch has been indexed at the current tip
// Use the proper remote info from BranchRef (not a naive string split)
db_manager
.record_branch_indexed(branch_name, tip_commit, branch.remote.as_deref())
.await?;
println!(" {} Branch indexed successfully", "✓".green());
branches_indexed += 1;
}
let total_time = start_time.elapsed();
println!(
"\n{}",
"=== Multi-Branch Indexing Complete ===".green().bold()
);
println!("Total time: {:.1}s", total_time.as_secs_f64());
println!("Branches indexed: {}", branches_indexed);
if branches_skipped > 0 {
println!("Branches skipped (already current): {}", branches_skipped);
}
// List all indexed branches
let indexed = db_manager.list_indexed_branches().await?;
if !indexed.is_empty() {
println!("\nIndexed branches:");
for branch in indexed {
println!(
" {} → {} (indexed {})",
branch.branch_name.cyan(),
&branch.tip_commit[..8],
chrono::DateTime::from_timestamp(branch.indexed_at, 0)
.map(|dt| dt.format("%Y-%m-%d %H:%M").to_string())
.unwrap_or_else(|| "unknown".to_string())
);
}
}
println!("\nTo query this database, run:");
println!(" semcode --database {}", database_path);
Ok(())
}
// ==================== End Branch Indexing Support ====================
#[tokio::main]
async fn main() -> Result<()> {
// Suppress ORT verbose logging
std::env::set_var("ORT_LOG_LEVEL", "ERROR");
let args = Args::parse();
// Enable performance monitoring if --perf flag is set
if args.perf {
semcode::perf_monitor::enable_performance_monitoring();
}
// Set up parallelism
let num_analysis_threads = if let Some(jobs_config) = &args.jobs {
let parts: Vec<&str> = jobs_config.split(':').collect();
let analysis_threads = if !parts.is_empty() && !parts[0].is_empty() {
parts[0].parse::<usize>().unwrap_or(0)
} else {
0
};
// Set vectorization batch size if provided (second parameter now controls batch size)
match parts.as_slice() {
[_] => {
// Just analysis threads specified
}
[_, batch] => {
std::env::set_var("SEMCODE_BATCH_SIZE", batch);
info!("Set vectorization batch size to {}", batch);
}
_ => {
warn!(
"Invalid jobs format '{}'. Expected: threads[:batch_size]",
jobs_config
);
}
}
analysis_threads
} else if let Ok(env_jobs) = std::env::var("SEMCODE_JOBS") {
env_jobs.parse::<usize>().unwrap_or(0)
} else {
0
};
// Use all CPU cores if 0 or not specified, but leave one for system/IO
let num_threads = if num_analysis_threads == 0 {
// Leave at least one core for system/IO operations for better overall performance
num_cpus::get().saturating_sub(1).max(1)
} else {
num_analysis_threads
};
// Configure optimized rayon thread pool
rayon::ThreadPoolBuilder::new()
.num_threads(num_threads)
.thread_name(|idx| format!("semcode-worker-{idx}"))
// Configure larger stack for complex AST parsing (8MB instead of default 2MB)
.stack_size(8 * 1024 * 1024)
.build_global()
.unwrap_or_else(|e| {
warn!("Failed to set rayon thread pool size: {}", e);
});
// Set environment variable to tune the stealing algorithm
std::env::set_var("RAYON_NUM_STEALS", "4");
info!("Using {} parallel threads for analysis", num_threads);
info!("Each thread will load its own Tree-sitter parser instance for true parallelism");
// Initialize tracing with SEMCODE_DEBUG environment variable support
semcode::logging::init_tracing();
// Process database path first (needed for lore cloning)
let database_path = process_database_path(args.database.as_deref(), Some(&args.source));