codeix 0.5.0

Fast semantic code search for AI agents — find symbols, references, and callers across any codebase
Documentation
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
//! Package manifest parsing for project metadata extraction.
//!
//! Parses common package manifests (package.json, Cargo.toml, pyproject.toml, go.mod, pom.xml, *.gemspec)
//! and returns both fixed metadata (name, description) and list of manifest files found.

use std::fs;
use std::path::Path;

use serde::Serialize;

/// Fixed project metadata extracted from manifests.
#[derive(Debug, Clone, Serialize)]
pub struct ProjectMetadata {
    /// Human-readable project name (from first manifest found, or directory name)
    pub name: String,
    /// Project description (from first manifest with description)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// List of manifest files found (e.g., ["package.json", "Cargo.toml"])
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub manifest_files: Vec<String>,
}

/// Extract project metadata from all manifests found in the project root.
///
/// Checks for: package.json, Cargo.toml, pyproject.toml, go.mod, pom.xml, *.gemspec
/// Returns fixed metadata (name, description) plus list of manifest files found.
pub fn extract_metadata(project_root: &Path) -> ProjectMetadata {
    let mut manifest_files = Vec::new();
    let mut name: Option<String> = None;
    let mut description: Option<String> = None;

    // Try each manifest type
    if let Some((n, d)) = try_package_json(project_root) {
        if name.is_none() {
            name = Some(n);
        }
        if description.is_none() {
            description = d;
        }
        manifest_files.push("package.json".to_string());
    }

    if let Some((n, d)) = try_cargo_toml(project_root) {
        if name.is_none() {
            name = Some(n);
        }
        if description.is_none() {
            description = d;
        }
        manifest_files.push("Cargo.toml".to_string());
    }

    if let Some((n, d)) = try_pyproject_toml(project_root) {
        if name.is_none() {
            name = Some(n);
        }
        if description.is_none() {
            description = d;
        }
        manifest_files.push("pyproject.toml".to_string());
    }

    if let Some(n) = try_go_mod(project_root) {
        if name.is_none() {
            name = Some(n);
        }
        // go.mod has no description
        manifest_files.push("go.mod".to_string());
    }

    if let Some((n, d)) = try_pom_xml(project_root) {
        if name.is_none() {
            name = Some(n);
        }
        if description.is_none() {
            description = d;
        }
        manifest_files.push("pom.xml".to_string());
    }

    if let Some((gemspec_file, n, d)) = try_gemspec(project_root) {
        if name.is_none() {
            name = Some(n);
        }
        if description.is_none() {
            description = d;
        }
        manifest_files.push(gemspec_file);
    }

    // Fallback: directory name
    let name = name.unwrap_or_else(|| {
        project_root
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("unknown")
            .to_string()
    });

    ProjectMetadata {
        name,
        description,
        manifest_files,
    }
}

/// Parse package.json and return (name, description)
/// Handles both regular packages and monorepo roots (private: true without name).
fn try_package_json(root: &Path) -> Option<(String, Option<String>)> {
    let path = root.join("package.json");
    let content = fs::read_to_string(path).ok()?;
    let json: serde_json::Value = serde_json::from_str(&content).ok()?;

    // Try to get name from the package
    if let Some(name) = json.get("name").and_then(|n| n.as_str()) {
        let description = json
            .get("description")
            .and_then(|d| d.as_str())
            .map(String::from);
        return Some((name.to_string(), description));
    }

    // Handle monorepo roots (private: true without name) - use directory name
    if json.get("private") == Some(&serde_json::Value::Bool(true)) {
        let name = root
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("package")
            .to_string();
        let description = json
            .get("description")
            .and_then(|d| d.as_str())
            .map(String::from);
        return Some((name, description));
    }

    None
}

/// Parse Cargo.toml and return (name, description)
/// Handles both package manifests ([package]) and workspace manifests ([workspace]).
fn try_cargo_toml(root: &Path) -> Option<(String, Option<String>)> {
    let path = root.join("Cargo.toml");
    let content = fs::read_to_string(path).ok()?;
    let toml_value: toml::Value = toml::from_str(&content).ok()?;

    // Try [package] first (standard crate)
    if let Some(package) = toml_value.get("package")
        && let Some(name) = package.get("name").and_then(|n| n.as_str())
    {
        let description = package
            .get("description")
            .and_then(|d| d.as_str())
            .map(String::from);
        return Some((name.to_string(), description));
    }

    // Try [workspace] (workspace root) - use directory name, no description
    if toml_value.get("workspace").is_some() {
        let name = root
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("workspace")
            .to_string();
        return Some((name, None));
    }

    None
}

/// Parse pyproject.toml and return (name, description)
fn try_pyproject_toml(root: &Path) -> Option<(String, Option<String>)> {
    let path = root.join("pyproject.toml");
    let content = fs::read_to_string(path).ok()?;
    let toml_value: toml::Value = toml::from_str(&content).ok()?;

    // Try project.name (PEP 621)
    if let Some(project) = toml_value.get("project")
        && let Some(name) = project.get("name").and_then(|n| n.as_str())
    {
        let description = project
            .get("description")
            .and_then(|d| d.as_str())
            .map(String::from);
        return Some((name.to_string(), description));
    }

    // Try tool.poetry.name (Poetry)
    if let Some(tool) = toml_value.get("tool")
        && let Some(poetry) = tool.get("poetry")
        && let Some(name) = poetry.get("name").and_then(|n| n.as_str())
    {
        let description = poetry
            .get("description")
            .and_then(|d| d.as_str())
            .map(String::from);
        return Some((name.to_string(), description));
    }

    None
}

/// Parse go.mod and return the module name
/// go.mod has no description field
fn try_go_mod(root: &Path) -> Option<String> {
    let path = root.join("go.mod");
    let content = fs::read_to_string(path).ok()?;

    let mut module_path: Option<String> = None;

    for line in content.lines() {
        let line = line.trim();
        if line.starts_with("module ") {
            module_path = line.strip_prefix("module ").map(|s| s.trim().to_string());
            break;
        }
    }

    let module_path = module_path?;
    // Use last segment as name, filter out empty strings
    module_path
        .split('/')
        .next_back()
        .filter(|s| !s.is_empty())
        .map(|s| s.to_string())
}

/// Parse pom.xml (Maven) and return (name, description)
/// Uses simple regex-based extraction to avoid adding an XML dependency.
fn try_pom_xml(root: &Path) -> Option<(String, Option<String>)> {
    let path = root.join("pom.xml");
    let content = fs::read_to_string(path).ok()?;

    // Extract artifactId as name (prefer <name> if present at top level)
    // We look for top-level elements, not nested in <parent> or <dependency>
    let name = extract_xml_element(&content, "name")
        .or_else(|| extract_xml_element(&content, "artifactId"))?;

    let description = extract_xml_element(&content, "description");

    Some((name, description))
}

/// Simple XML element extraction (first occurrence, top-level only).
/// This is a basic implementation that works for common pom.xml structures.
fn extract_xml_element(content: &str, tag: &str) -> Option<String> {
    let open_tag = format!("<{}>", tag);
    let close_tag = format!("</{}>", tag);

    let start = content.find(&open_tag)? + open_tag.len();
    let end = content[start..].find(&close_tag)? + start;

    let value = content[start..end].trim();
    if value.is_empty() || value.starts_with('<') {
        // Empty or contains nested elements
        None
    } else {
        Some(value.to_string())
    }
}

/// Parse *.gemspec (Ruby gem) and return (filename, name, description)
/// Looks for .name and .summary/.description assignments.
fn try_gemspec(root: &Path) -> Option<(String, String, Option<String>)> {
    // Find *.gemspec file in the directory
    let gemspec_file = fs::read_dir(root)
        .ok()?
        .filter_map(|e| e.ok())
        .find(|e| e.path().extension().is_some_and(|ext| ext == "gemspec"))?;

    let filename = gemspec_file.file_name().to_string_lossy().to_string();
    let content = fs::read_to_string(gemspec_file.path()).ok()?;

    // Extract name: look for .name = "..." or .name = '...'
    let name = extract_ruby_string_assignment(&content, "name")?;

    // Extract description: prefer .summary, fall back to .description
    let description = extract_ruby_string_assignment(&content, "summary")
        .or_else(|| extract_ruby_string_assignment(&content, "description"));

    Some((filename, name, description))
}

/// Extract a Ruby string assignment like `s.name = "value"` or `spec.name = 'value'`
fn extract_ruby_string_assignment(content: &str, field: &str) -> Option<String> {
    // Pattern: <var>.field = "value" or <var>.field = 'value'
    let field_pattern = format!(".{}", field);

    for line in content.lines() {
        let line = line.trim();
        // Find .field in the line (e.g., "s.name" or "spec.name")
        if let Some(pos) = line.find(&field_pattern) {
            let rest = &line[pos + field_pattern.len()..];
            let rest = rest.trim();
            if let Some(rest) = rest.strip_prefix('=') {
                let rest = rest.trim();
                // Handle quoted strings
                if let Some(value) = extract_quoted_string(rest) {
                    return Some(value);
                }
            }
        }
    }
    None
}

/// Extract a quoted string (single or double quotes)
fn extract_quoted_string(s: &str) -> Option<String> {
    let s = s.trim();
    if let Some(rest) = s.strip_prefix('"') {
        let end = rest.find('"')?;
        Some(rest[..end].to_string())
    } else if let Some(rest) = s.strip_prefix('\'') {
        let end = rest.find('\'')?;
        Some(rest[..end].to_string())
    } else {
        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    #[test]
    fn test_package_json_parsing() {
        let tmp = TempDir::new().unwrap();
        fs::write(
            tmp.path().join("package.json"),
            r#"{"name": "my-app", "description": "A cool app", "version": "1.0.0"}"#,
        )
        .unwrap();

        let meta = extract_metadata(tmp.path());
        assert_eq!(meta.name, "my-app");
        assert_eq!(meta.description, Some("A cool app".into()));
        assert!(meta.manifest_files.contains(&"package.json".to_string()));
    }

    #[test]
    fn test_cargo_toml_parsing() {
        let tmp = TempDir::new().unwrap();
        fs::write(
            tmp.path().join("Cargo.toml"),
            r#"
[package]
name = "my-crate"
version = "0.1.0"
description = "A Rust library"
"#,
        )
        .unwrap();

        let meta = extract_metadata(tmp.path());
        assert_eq!(meta.name, "my-crate");
        assert_eq!(meta.description, Some("A Rust library".into()));
        assert!(meta.manifest_files.contains(&"Cargo.toml".to_string()));
    }

    #[test]
    fn test_pyproject_toml_pep621() {
        let tmp = TempDir::new().unwrap();
        fs::write(
            tmp.path().join("pyproject.toml"),
            r#"
[project]
name = "my-python-pkg"
description = "A Python package"
version = "1.0.0"
"#,
        )
        .unwrap();

        let meta = extract_metadata(tmp.path());
        assert_eq!(meta.name, "my-python-pkg");
        assert_eq!(meta.description, Some("A Python package".into()));
        assert!(meta.manifest_files.contains(&"pyproject.toml".to_string()));
    }

    #[test]
    fn test_pyproject_toml_poetry() {
        let tmp = TempDir::new().unwrap();
        fs::write(
            tmp.path().join("pyproject.toml"),
            r#"
[tool.poetry]
name = "poetry-pkg"
description = "A Poetry package"
version = "2.0.0"
"#,
        )
        .unwrap();

        let meta = extract_metadata(tmp.path());
        assert_eq!(meta.name, "poetry-pkg");
        assert_eq!(meta.description, Some("A Poetry package".into()));
    }

    #[test]
    fn test_go_mod_parsing() {
        let tmp = TempDir::new().unwrap();
        fs::write(
            tmp.path().join("go.mod"),
            "module github.com/user/myrepo\n\ngo 1.21\n",
        )
        .unwrap();

        let meta = extract_metadata(tmp.path());
        assert_eq!(meta.name, "myrepo");
        assert_eq!(meta.description, None); // go.mod has no description
        assert!(meta.manifest_files.contains(&"go.mod".to_string()));
    }

    #[test]
    fn test_fallback_to_directory_name() {
        let tmp = TempDir::new().unwrap();
        // No manifest files

        let meta = extract_metadata(tmp.path());
        // Name should be the temp directory name (starts with '.')
        assert!(!meta.name.is_empty());
        assert_eq!(meta.description, None);
        assert!(meta.manifest_files.is_empty());
    }

    #[test]
    fn test_multiple_manifests() {
        let tmp = TempDir::new().unwrap();
        fs::write(
            tmp.path().join("package.json"),
            r#"{"name": "npm-name", "description": "NPM desc"}"#,
        )
        .unwrap();
        fs::write(
            tmp.path().join("Cargo.toml"),
            r#"
[package]
name = "cargo-name"
description = "Cargo desc"
"#,
        )
        .unwrap();

        let meta = extract_metadata(tmp.path());
        // First found (npm) wins for name/description
        assert_eq!(meta.name, "npm-name");
        assert_eq!(meta.description, Some("NPM desc".into()));
        // But both manifest files are listed
        assert!(meta.manifest_files.contains(&"package.json".to_string()));
        assert!(meta.manifest_files.contains(&"Cargo.toml".to_string()));
    }

    #[test]
    fn test_first_description_wins() {
        let tmp = TempDir::new().unwrap();
        // package.json with name but no description
        fs::write(tmp.path().join("package.json"), r#"{"name": "npm-name"}"#).unwrap();
        // Cargo.toml with description
        fs::write(
            tmp.path().join("Cargo.toml"),
            r#"
[package]
name = "cargo-name"
description = "Cargo has the description"
"#,
        )
        .unwrap();

        let meta = extract_metadata(tmp.path());
        assert_eq!(meta.name, "npm-name"); // npm first
        assert_eq!(meta.description, Some("Cargo has the description".into())); // cargo provides description
    }

    #[test]
    fn test_pom_xml_parsing() {
        let tmp = TempDir::new().unwrap();
        fs::write(
            tmp.path().join("pom.xml"),
            r#"<?xml version="1.0" encoding="UTF-8"?>
<project>
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>my-java-app</artifactId>
    <version>1.0.0</version>
    <name>My Java Application</name>
    <description>A sample Java application</description>
</project>
"#,
        )
        .unwrap();

        let meta = extract_metadata(tmp.path());
        assert_eq!(meta.name, "My Java Application");
        assert_eq!(meta.description, Some("A sample Java application".into()));
        assert!(meta.manifest_files.contains(&"pom.xml".to_string()));
    }

    #[test]
    fn test_pom_xml_without_name() {
        let tmp = TempDir::new().unwrap();
        fs::write(
            tmp.path().join("pom.xml"),
            r#"<?xml version="1.0" encoding="UTF-8"?>
<project>
    <groupId>com.example</groupId>
    <artifactId>simple-app</artifactId>
    <version>1.0.0</version>
</project>
"#,
        )
        .unwrap();

        let meta = extract_metadata(tmp.path());
        // Falls back to artifactId when <name> is not present
        assert_eq!(meta.name, "simple-app");
        assert_eq!(meta.description, None);
        assert!(meta.manifest_files.contains(&"pom.xml".to_string()));
    }

    #[test]
    fn test_gemspec_parsing() {
        let tmp = TempDir::new().unwrap();
        fs::write(
            tmp.path().join("my_gem.gemspec"),
            r#"
Gem::Specification.new do |s|
  s.name        = "my_gem"
  s.version     = "1.0.0"
  s.summary     = "A sample Ruby gem"
  s.description = "A longer description of my gem"
  s.authors     = ["Test Author"]
end
"#,
        )
        .unwrap();

        let meta = extract_metadata(tmp.path());
        assert_eq!(meta.name, "my_gem");
        assert_eq!(meta.description, Some("A sample Ruby gem".into())); // uses summary
        assert!(meta.manifest_files.contains(&"my_gem.gemspec".to_string()));
    }

    #[test]
    fn test_gemspec_single_quotes() {
        let tmp = TempDir::new().unwrap();
        fs::write(
            tmp.path().join("another.gemspec"),
            r#"
Gem::Specification.new do |spec|
  spec.name    = 'another-gem'
  spec.version = '2.0.0'
  spec.summary = 'Single quoted summary'
end
"#,
        )
        .unwrap();

        let meta = extract_metadata(tmp.path());
        assert_eq!(meta.name, "another-gem");
        assert_eq!(meta.description, Some("Single quoted summary".into()));
        assert!(meta.manifest_files.contains(&"another.gemspec".to_string()));
    }

    #[test]
    fn test_cargo_workspace_toml() {
        let tmp = TempDir::new().unwrap();
        // Create a subdirectory with a specific name
        let workspace_dir = tmp.path().join("my-workspace");
        fs::create_dir(&workspace_dir).unwrap();
        fs::write(
            workspace_dir.join("Cargo.toml"),
            r#"
[workspace]
resolver = "2"
members = ["crate-a", "crate-b"]
"#,
        )
        .unwrap();

        let meta = extract_metadata(&workspace_dir);
        assert_eq!(meta.name, "my-workspace"); // Uses directory name
        assert_eq!(meta.description, None); // Workspaces don't have description
        assert!(meta.manifest_files.contains(&"Cargo.toml".to_string()));
    }

    #[test]
    fn test_package_json_monorepo() {
        let tmp = TempDir::new().unwrap();
        // Create a subdirectory with a specific name
        let monorepo_dir = tmp.path().join("my-monorepo");
        fs::create_dir(&monorepo_dir).unwrap();
        fs::write(
            monorepo_dir.join("package.json"),
            r#"{"private": true, "workspaces": ["packages/*"]}"#,
        )
        .unwrap();

        let meta = extract_metadata(&monorepo_dir);
        assert_eq!(meta.name, "my-monorepo"); // Uses directory name
        assert_eq!(meta.description, None);
        assert!(meta.manifest_files.contains(&"package.json".to_string()));
    }
}