meta-ast 0.5.0

Polyglot static-analysis engine: extract symbols and cross-language dependency graphs from 9 supported source languages, with optional MetaCall deployment manifest generation.
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
//! Per-language external dependency resolution.
//!
//! Classifies `ExternalNode` entries (created during graph builder import
//! resolution) into resolved dependencies with package name and version.
//! Lockfiles are preferred over manifests for exact pinning.
//! C/C++ relies on best-effort classification only.

use std::path::Path;

use crate::graph::node::{DependencySource, ExternalClassification, ExternalNode};
use crate::language::LangId;

/// A resolved dependency entry for the pod manifest.
#[derive(Debug, Clone, serde::Serialize)]
pub struct DependencyEntry {
    pub name: String,
    pub version: Option<String>,
    pub language: LangId,
    pub source: DependencySource,
}

/// Classify a single external dependency using language-specific strategies.
///
/// Dispatches by `external.language` via exhaustive match, following the
/// repo's enum-static-dispatch convention. Lockfiles are tried first;
/// if missing or unparseable, falls back to the manifest file. If that
/// also fails, returns `Unresolved` (never blocks).
pub fn classify_external(external: &ExternalNode, project_root: &Path) -> ExternalClassification {
    match external.language {
        LangId::Python => classify_python(external, project_root),
        LangId::JavaScript | LangId::TypeScript | LangId::Tsx => {
            classify_node_ecosystem(external, project_root)
        }
        LangId::Rust => classify_rust(external, project_root),
        LangId::Go => classify_go(external, project_root),
        LangId::Ruby => classify_ruby(external, project_root),
        LangId::C | LangId::Cpp => classify_c_cpp_best_effort(external, project_root),
    }
}

/// Resolve all external nodes in a graph and return per-pod dependency lists.
///
/// Walks Import edges from each pod's files to ExternalNode targets,
/// classifies each external, and groups results by pod ID.
pub fn resolve_dependencies(
    graph: &crate::graph::CodeGraph,
    partition: &crate::deploy::pod::PodPartition,
    project_root: &Path,
) -> std::collections::HashMap<usize, Vec<DependencyEntry>> {
    let mut deps: std::collections::HashMap<usize, Vec<DependencyEntry>> =
        std::collections::HashMap::new();

    // Build FileId -> pod_id lookup.
    let mut file_to_pod: std::collections::HashMap<crate::model::FileId, usize> =
        std::collections::HashMap::new();
    for pod in &partition.pods {
        for &fid in &pod.files {
            file_to_pod.insert(fid, pod.id);
        }
    }

    for edge_idx in graph.graph.edge_indices() {
        let weight = &graph.graph[edge_idx];
        if weight.kind != crate::graph::EdgeKind::Import {
            continue;
        }
        let Some((src, dst)) = graph.graph.edge_endpoints(edge_idx) else {
            continue;
        };

        // Source must be a file in a known pod.
        let src_fid = match &graph.graph[src] {
            crate::graph::NodeData::File(f) => f.id,
            crate::graph::NodeData::Symbol(s) => s.file_id,
            _ => continue,
        };
        let Some(&pod_id) = file_to_pod.get(&src_fid) else {
            continue;
        };

        // Target must be an ExternalNode.
        let ext = match &graph.graph[dst] {
            crate::graph::NodeData::External(e) => e,
            _ => continue,
        };

        let classification = classify_external(ext, project_root);
        let entry = match &classification {
            ExternalClassification::Classified {
                package_name,
                version,
                language,
                source,
            } => DependencyEntry {
                name: package_name.clone(),
                version: version.clone(),
                language: *language,
                source: *source,
            },
            ExternalClassification::Unresolved { .. } => continue,
        };

        let pod_deps = deps.entry(pod_id).or_default();
        if !pod_deps.iter().any(|d| d.name == entry.name) {
            pod_deps.push(entry);
        }
    }

    deps
}

// ── Per-language resolvers ─────────────────────────────────────────

fn classify_python(external: &ExternalNode, root: &Path) -> ExternalClassification {
    let lockfiles = [
        root.join("uv.lock"),
        root.join("poetry.lock"),
        root.join("Pipfile.lock"),
    ];
    for lf in &lockfiles {
        if lf.exists() {
            return ExternalClassification::Classified {
                package_name: external.raw_path.clone(),
                version: parse_version_from_lockfile(lf, &external.raw_path),
                language: LangId::Python,
                source: DependencySource::Lockfile,
            };
        }
    }

    let manifests = [root.join("pyproject.toml"), root.join("requirements.txt")];
    for mf in &manifests {
        if mf.exists() {
            return ExternalClassification::Classified {
                package_name: external.raw_path.clone(),
                version: None,
                language: LangId::Python,
                source: DependencySource::Manifest,
            };
        }
    }

    // Check immediate subdirectories (monorepo layout).
    if let Ok(entries) = std::fs::read_dir(root) {
        for entry in entries.flatten() {
            let subdir = entry.path();
            if !subdir.is_dir() {
                continue;
            }
            for mf in &manifests {
                let p = subdir.join(mf.file_name().unwrap_or_default());
                if p.exists() {
                    return ExternalClassification::Classified {
                        package_name: external.raw_path.clone(),
                        version: None,
                        language: LangId::Python,
                        source: DependencySource::Manifest,
                    };
                }
            }
        }
    }

    ExternalClassification::Unresolved {
        raw_path: external.raw_path.clone(),
        reason: "no Python lockfile or manifest found".into(),
    }
}

fn classify_node_ecosystem(external: &ExternalNode, root: &Path) -> ExternalClassification {
    // Check root-level lockfiles and manifests first.
    let lockfiles = [
        root.join("package-lock.json"),
        root.join("yarn.lock"),
        root.join("pnpm-lock.yaml"),
    ];
    for lf in &lockfiles {
        if lf.exists() {
            return ExternalClassification::Classified {
                package_name: external.raw_path.clone(),
                version: parse_version_from_lockfile(lf, &external.raw_path),
                language: external.language,
                source: DependencySource::Lockfile,
            };
        }
    }

    let mf = root.join("package.json");
    if mf.exists() {
        return ExternalClassification::Classified {
            package_name: external.raw_path.clone(),
            version: parse_version_from_package_json(&mf, &external.raw_path),
            language: external.language,
            source: DependencySource::Manifest,
        };
    }

    // Search immediate subdirectories for package.json (monorepo layout).
    if let Ok(entries) = std::fs::read_dir(root) {
        for entry in entries.flatten() {
            let subdir = entry.path();
            if !subdir.is_dir() {
                continue;
            }
            let lock_path = subdir.join("package-lock.json");
            if lock_path.exists() {
                return ExternalClassification::Classified {
                    package_name: external.raw_path.clone(),
                    version: parse_version_from_lockfile(&lock_path, &external.raw_path),
                    language: external.language,
                    source: DependencySource::Lockfile,
                };
            }
            let pkg_path = subdir.join("package.json");
            if pkg_path.exists() {
                return ExternalClassification::Classified {
                    package_name: external.raw_path.clone(),
                    version: parse_version_from_package_json(&pkg_path, &external.raw_path),
                    language: external.language,
                    source: DependencySource::Manifest,
                };
            }
        }
    }

    ExternalClassification::Unresolved {
        raw_path: external.raw_path.clone(),
        reason: "no Node.js lockfile or package.json found".into(),
    }
}

fn classify_rust(external: &ExternalNode, root: &Path) -> ExternalClassification {
    let lf = root.join("Cargo.lock");
    if lf.exists() {
        return ExternalClassification::Classified {
            package_name: external.raw_path.clone(),
            version: parse_version_from_cargo_lock(&lf, &external.raw_path),
            language: LangId::Rust,
            source: DependencySource::Lockfile,
        };
    }

    let mf = root.join("Cargo.toml");
    if mf.exists() {
        return ExternalClassification::Classified {
            package_name: external.raw_path.clone(),
            version: None,
            language: LangId::Rust,
            source: DependencySource::Manifest,
        };
    }

    ExternalClassification::Unresolved {
        raw_path: external.raw_path.clone(),
        reason: "no Cargo.lock or Cargo.toml found".into(),
    }
}

fn classify_go(external: &ExternalNode, root: &Path) -> ExternalClassification {
    let lf = root.join("go.sum");
    if lf.exists() {
        return ExternalClassification::Classified {
            package_name: external.raw_path.clone(),
            version: parse_version_from_go_sum(&lf, &external.raw_path),
            language: LangId::Go,
            source: DependencySource::Lockfile,
        };
    }

    let mf = root.join("go.mod");
    if mf.exists() {
        return ExternalClassification::Classified {
            package_name: external.raw_path.clone(),
            version: None,
            language: LangId::Go,
            source: DependencySource::Manifest,
        };
    }

    ExternalClassification::Unresolved {
        raw_path: external.raw_path.clone(),
        reason: "no go.sum or go.mod found".into(),
    }
}

fn classify_ruby(external: &ExternalNode, root: &Path) -> ExternalClassification {
    let lf = root.join("Gemfile.lock");
    if lf.exists() {
        return ExternalClassification::Classified {
            package_name: external.raw_path.clone(),
            version: parse_version_from_gemfile_lock(&lf, &external.raw_path),
            language: LangId::Ruby,
            source: DependencySource::Lockfile,
        };
    }

    let mf = root.join("Gemfile");
    if mf.exists() {
        return ExternalClassification::Classified {
            package_name: external.raw_path.clone(),
            version: None,
            language: LangId::Ruby,
            source: DependencySource::Manifest,
        };
    }

    ExternalClassification::Unresolved {
        raw_path: external.raw_path.clone(),
        reason: "no Gemfile.lock or Gemfile found".into(),
    }
}

fn classify_c_cpp_best_effort(external: &ExternalNode, root: &Path) -> ExternalClassification {
    // C/C++ has no universal convention. Try conanfile.txt, then vcpkg.json.
    // If neither exists, silently fall back to Unresolved.
    if root.join("conanfile.txt").exists() {
        return ExternalClassification::Classified {
            package_name: external.raw_path.clone(),
            version: None,
            language: external.language,
            source: DependencySource::Manifest,
        };
    }
    if root.join("vcpkg.json").exists() {
        return ExternalClassification::Classified {
            package_name: external.raw_path.clone(),
            version: None,
            language: external.language,
            source: DependencySource::Manifest,
        };
    }

    tracing::trace!(path = %external.raw_path, "C/C++ external dependency unresolved");
    ExternalClassification::Unresolved {
        raw_path: external.raw_path.clone(),
        reason: "no C/C++ manifest convention found (conanfile.txt, vcpkg.json)".into(),
    }
}

// ── Lockfile parsing helpers ───────────────────────────────────────

/// Best-effort version extraction from a lockfile by searching for the
/// package name followed by a version-like string. Returns None if the
/// package isn't found or the file can't be read.
fn parse_version_from_lockfile(path: &Path, package: &str) -> Option<String> {
    let content = std::fs::read_to_string(path).ok()?;
    // Search for the package name, then grab the next quoted/hyphenated
    // version-like token on the same or next line.
    for line in content.lines() {
        if line.contains(package) {
            // Look for a semver-like pattern on this line or the next few.
            for candidate in content.lines().skip_while(|l| !l.contains(package)).take(5) {
                if let Some(v) = extract_semver(candidate) {
                    return Some(v);
                }
            }
        }
    }
    None
}

fn parse_version_from_package_json(path: &Path, package: &str) -> Option<String> {
    let content = std::fs::read_to_string(path).ok()?;
    let json: serde_json::Value = serde_json::from_str(&content).ok()?;
    // Check dependencies/devDependencies for the package.
    for section in ["dependencies", "devDependencies", "peerDependencies"] {
        if let Some(version) = json.get(section).and_then(|d| d.get(package))
            && let Some(s) = version.as_str()
        {
            return Some(s.to_string());
        }
    }
    None
}

fn parse_version_from_cargo_lock(path: &Path, package: &str) -> Option<String> {
    let content = std::fs::read_to_string(path).ok()?;
    // Cargo.lock uses TOML; search for [[package]] sections with name = "..."
    let mut in_package_section = false;
    for line in content.lines() {
        if line.trim_start().starts_with("[[package]]") {
            in_package_section = false;
        }
        if let Some(rest) = line.strip_prefix("name = ") {
            let name = rest.trim().trim_matches('"');
            if name == package {
                in_package_section = true;
            }
        }
        if in_package_section && let Some(rest) = line.strip_prefix("version = ") {
            return Some(rest.trim().trim_matches('"').to_string());
        }
    }
    None
}

fn parse_version_from_go_sum(path: &Path, package: &str) -> Option<String> {
    let content = std::fs::read_to_string(path).ok()?;
    // go.sum format: <module> <version> <hash>
    // Take the first line matching the package.
    for line in content.lines() {
        if line.starts_with(package) {
            let parts: Vec<&str> = line.split_whitespace().collect();
            if parts.len() >= 2 {
                return Some(parts[1].to_string());
            }
        }
    }
    None
}

fn parse_version_from_gemfile_lock(path: &Path, name: &str) -> Option<String> {
    let content = std::fs::read_to_string(path).ok()?;
    // Gemfile.lock lists each gem as "  <name> (<version>)" under a specs
    // section. The name has no quotes; match the indented line exactly.
    for line in content.lines() {
        let line = line.trim_start();
        if let Some(rest) = line
            .strip_prefix(&format!("{name} ("))
            .and_then(|rest| rest.strip_suffix(')'))
        {
            return Some(rest.trim().to_string());
        }
    }
    None
}

/// Extract the first semver-like substring from a line.
fn extract_semver(line: &str) -> Option<String> {
    let mut chars = line.chars().peekable();
    let mut start = None;
    let mut i = 0usize;
    while let Some(&c) = chars.peek() {
        if c.is_ascii_digit() {
            // Potential start of a version.
            let mut version = String::new();
            let mut dot_count = 0;
            while let Some(&c) = chars.peek() {
                if c.is_ascii_digit() {
                    version.push(c);
                    chars.next();
                } else if c == '.' {
                    version.push(c);
                    dot_count += 1;
                    chars.next();
                } else {
                    break;
                }
            }
            if dot_count >= 2 && !version.is_empty() {
                return Some(version);
            }
            start = Some(i);
        } else {
            chars.next();
        }
        i += 1;
    }
    let _ = start;
    None
}

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

    fn external_node(raw_path: &str) -> ExternalNode {
        ExternalNode {
            raw_path: raw_path.to_string(),
            language: LangId::Ruby,
            classification: None,
        }
    }

    fn test_dir(name: &str) -> std::path::PathBuf {
        let dir = std::env::temp_dir().join(format!("meta_ast_ruby_dep_{name}"));
        if dir.exists() {
            let _ = std::fs::remove_dir_all(&dir);
        }
        std::fs::create_dir_all(&dir).unwrap();
        dir
    }

    #[test]
    fn parse_version_from_gemfile_lock_extracts_version() {
        let dir = test_dir("parse");
        let lf = dir.join("Gemfile.lock");
        std::fs::write(
            &lf,
            "GEM\n  remote: https://rubygems.org/\n  specs:\n    rails (7.0.8.4)\n      actioncable (= 7.0.8.4)\n",
        )
        .unwrap();

        assert_eq!(
            parse_version_from_gemfile_lock(&lf, "rails"),
            Some("7.0.8.4".to_string())
        );
        assert_eq!(parse_version_from_gemfile_lock(&lf, "missing"), None);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn classify_ruby_uses_gemfile_lock() {
        let dir = test_dir("classify_lock");
        std::fs::write(
            dir.join("Gemfile.lock"),
            "GEM\n  specs:\n    rails (7.0.8.4)\n",
        )
        .unwrap();

        let classification = classify_ruby(&external_node("rails"), &dir);
        match classification {
            ExternalClassification::Classified {
                package_name,
                version,
                language,
                source,
            } => {
                assert_eq!(package_name, "rails");
                assert_eq!(version.as_deref(), Some("7.0.8.4"));
                assert_eq!(language, LangId::Ruby);
                assert_eq!(source, DependencySource::Lockfile);
            }
            other => panic!("expected Classified, got {other:?}"),
        }
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn classify_ruby_unresolved_without_gemfile() {
        let missing = std::env::temp_dir().join("meta_ast_ruby_dep_missing_dir");
        let classification = classify_ruby(&external_node("rails"), &missing);
        match classification {
            ExternalClassification::Unresolved { raw_path, reason } => {
                assert_eq!(raw_path, "rails");
                assert_eq!(reason, "no Gemfile.lock or Gemfile found");
            }
            other => panic!("expected Unresolved, got {other:?}"),
        }
    }
}