provenant-cli 0.1.3

Independent Rust scanner for ScanCode-compatible workflows, licenses, package metadata, SBOMs, and provenance data.
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
// SPDX-FileCopyrightText: Provenant contributors
// SPDX-License-Identifier: Apache-2.0

//! Parser for Conan C/C++ package manager manifests.
//!
//! Extracts package metadata and dependencies from Conan manifest files.
//!
//! # Supported Formats
//! - conanfile.py (Recipe files with Python AST parsing)
//! - conanfile.txt (Simple dependency specification format)
//! - conan.lock (Lockfile with resolved dependency graph)
//!
//! # Key Features
//! - AST-based conanfile.py parsing (NO code execution)
//! - Dependency extraction from [requires] and [build_requires] sections
//! - Version constraint parsing for Conan reference format (name/version@user/channel)
//! - Package URL (purl) generation for resolved dependencies
//! - Lockfile dependency graph parsing
//!
//! # Implementation Notes
//! - conanfile.py: AST extracts class attributes and self.requires() calls
//! - conanfile.txt sections: [requires] = runtime, [build_requires] = build-time
//! - conan.lock uses JSON format with graph_lock.nodes structure
//! - Version constraints use Conan-specific operators: [>, <, ranges]
//! - Only exact versions (without operators) are extracted as pinned versions

use std::path::Path;

use crate::parser_warn as warn;
use packageurl::PackageUrl;
use ruff_python_ast as ast;
use ruff_python_parser::parse_module;
use serde_json::Value;

use crate::models::{DatasourceId, Dependency, PackageData, PackageType};

use super::PackageParser;
use super::license_normalization::{
    DeclaredLicenseMatchMetadata, build_declared_license_data, normalize_declared_license_key,
};
use super::utils::{MAX_ITERATION_COUNT, read_file_to_string, truncate_field};

const MAX_AST_DEPTH: usize = 50;
const MAX_AST_NODES: usize = 10_000;

/// Conan conanfile.py recipe parser.
///
/// Parses Python-based Conan recipe files using AST analysis (no code execution).
/// Extracts package metadata and dependencies from ConanFile class attributes.
pub struct ConanFilePyParser;

impl PackageParser for ConanFilePyParser {
    const PACKAGE_TYPE: PackageType = PackageType::Conan;

    fn is_match(path: &Path) -> bool {
        path.file_name().is_some_and(|name| name == "conanfile.py")
    }

    fn extract_packages(path: &Path) -> Vec<PackageData> {
        let contents = match read_file_to_string(path, None) {
            Ok(c) => c,
            Err(e) => {
                warn!("Failed to read {}: {}", path.display(), e);
                return vec![default_package_data(DatasourceId::ConanConanFilePy)];
            }
        };

        vec![match parse_module(&contents) {
            Ok(parsed) => parse_conanfile_py(parsed.suite()),
            Err(e) => {
                warn!("Failed to parse Python AST in {}: {}", path.display(), e);
                default_package_data(DatasourceId::ConanConanFilePy)
            }
        }]
    }

    fn metadata() -> Vec<super::metadata::ParserMetadata> {
        vec![super::metadata::ParserMetadata {
            description: "Conan C/C++ package manifest",
            file_patterns: &["**/conanfile.py", "**/conanfile.txt", "**/conan.lock"],
            package_type: "conan",
            primary_language: "C++",
            documentation_url: Some("https://docs.conan.io/"),
        }]
    }
}

/// Parse conanfile.py AST to extract ConanFile class attributes
fn parse_conanfile_py(statements: &[ast::Stmt]) -> PackageData {
    for stmt in statements {
        if let ast::Stmt::ClassDef(class_def) = stmt
            && has_conanfile_base(class_def)
        {
            return extract_conanfile_data(class_def);
        }
    }

    default_package_data(DatasourceId::ConanConanFilePy)
}

/// Check if class inherits from ConanFile
fn has_conanfile_base(class_def: &ast::StmtClassDef) -> bool {
    class_def.bases().iter().any(|base| {
        if let ast::Expr::Name(ast::ExprName { id, .. }) = base {
            id.as_str() == "ConanFile"
        } else {
            false
        }
    })
}

/// Extract package data from ConanFile class definition
fn extract_conanfile_data(class_def: &ast::StmtClassDef) -> PackageData {
    let mut name = None;
    let mut version = None;
    let mut description = None;
    let mut _author = None;
    let mut homepage_url = None;
    let mut vcs_url = None;
    let mut license_list = Vec::new();
    let mut keywords = Vec::new();
    let mut requires_list = Vec::new();
    let mut tool_requires_list = Vec::new();

    for stmt in class_def.body.iter().take(MAX_ITERATION_COUNT) {
        match stmt {
            ast::Stmt::Assign(ast::StmtAssign { targets, value, .. }) => {
                if let Some(target_name) = get_assignment_target(targets) {
                    match target_name.as_str() {
                        "name" => name = get_string_value(value).map(truncate_field),
                        "version" => version = get_string_value(value).map(truncate_field),
                        "description" => description = get_string_value(value).map(truncate_field),
                        "author" => _author = get_string_value(value).map(truncate_field),
                        "homepage" => homepage_url = get_string_value(value).map(truncate_field),
                        "url" => vcs_url = get_string_value(value).map(truncate_field),
                        "license" => {
                            license_list = get_list_values(value)
                                .into_iter()
                                .map(truncate_field)
                                .collect()
                        }
                        "topics" => {
                            keywords = get_list_values(value)
                                .into_iter()
                                .map(truncate_field)
                                .collect()
                        }
                        "requires" => {
                            requires_list = get_list_values(value)
                                .into_iter()
                                .map(truncate_field)
                                .collect()
                        }
                        _ => {}
                    }
                }
            }
            ast::Stmt::FunctionDef(ast::StmtFunctionDef { body, .. }) => {
                if let Some(requires) = extract_self_requires_calls(body, "requires") {
                    requires_list.extend(requires);
                }
                if let Some(tool_requires) = extract_self_requires_calls(body, "tool_requires") {
                    tool_requires_list.extend(tool_requires);
                }
            }
            _ => {}
        }
    }

    let mut dependencies = requires_list
        .into_iter()
        .filter_map(|req| parse_conan_reference(&req))
        .collect::<Vec<_>>();
    dependencies.extend(
        tool_requires_list
            .into_iter()
            .filter_map(|req| parse_conan_reference(&req))
            .map(|dep| Dependency {
                scope: Some("build".to_string()),
                is_runtime: Some(false),
                ..dep
            }),
    );

    let extracted_license = if !license_list.is_empty() {
        Some(truncate_field(license_list.join(", ")))
    } else {
        None
    };
    let (declared_license_expression, declared_license_expression_spdx, license_detections) =
        if license_list.len() == 1 {
            if let Some(normalized) = normalize_declared_license_key(&license_list[0]) {
                let (expr, spdx, detections) = build_declared_license_data(
                    normalized,
                    DeclaredLicenseMatchMetadata::single_line(&license_list[0]),
                );
                (
                    expr.map(truncate_field),
                    spdx.map(truncate_field),
                    detections,
                )
            } else {
                (None, None, Vec::new())
            }
        } else {
            (None, None, Vec::new())
        };

    PackageData {
        name,
        version,
        description,
        homepage_url,
        vcs_url,
        keywords,
        dependencies,
        declared_license_expression,
        declared_license_expression_spdx,
        license_detections,
        extracted_license_statement: extracted_license,
        datasource_id: Some(DatasourceId::ConanConanFilePy),
        ..default_package_data(DatasourceId::ConanConanFilePy)
    }
}

/// Get assignment target name (e.g., "name" from "name = 'foo'")
fn get_assignment_target(targets: &[ast::Expr]) -> Option<String> {
    targets.first().and_then(|target| {
        if let ast::Expr::Name(ast::ExprName { id, .. }) = target {
            Some(id.to_string())
        } else {
            None
        }
    })
}

/// Extract string value from AST expression
fn get_string_value(expr: &ast::Expr) -> Option<String> {
    match expr {
        ast::Expr::StringLiteral(ast::ExprStringLiteral { value, .. }) => {
            Some(value.to_str().to_string())
        }
        _ => None,
    }
}

/// Extract list of strings from tuple or list expression
fn get_list_values(expr: &ast::Expr) -> Vec<String> {
    match expr {
        ast::Expr::Tuple(ast::ExprTuple { elts, .. }) => {
            elts.iter().filter_map(get_string_value).collect()
        }
        ast::Expr::List(ast::ExprList { elts, .. }) => {
            elts.iter().filter_map(get_string_value).collect()
        }
        _ => {
            if let Some(s) = get_string_value(expr) {
                vec![s]
            } else {
                Vec::new()
            }
        }
    }
}

/// Extract self.requires() method calls from function body
fn extract_self_requires_calls(body: &[ast::Stmt], method_name: &str) -> Option<Vec<String>> {
    let mut requires = Vec::new();
    let mut node_count = 0usize;

    for stmt in body {
        collect_self_method_calls(stmt, method_name, &mut requires, 0, &mut node_count);
        if node_count >= MAX_AST_NODES {
            warn!(
                "Exceeded MAX_AST_NODES ({}) in extract_self_requires_calls",
                MAX_AST_NODES
            );
            break;
        }
    }

    if requires.is_empty() {
        None
    } else {
        Some(requires)
    }
}

fn collect_self_method_calls(
    stmt: &ast::Stmt,
    method_name: &str,
    out: &mut Vec<String>,
    depth: usize,
    node_count: &mut usize,
) {
    if depth > MAX_AST_DEPTH {
        warn!(
            "Exceeded MAX_AST_DEPTH ({}) in collect_self_method_calls",
            MAX_AST_DEPTH
        );
        return;
    }
    *node_count += 1;
    if *node_count > MAX_AST_NODES {
        return;
    }

    match stmt {
        ast::Stmt::Expr(ast::StmtExpr { value, .. }) => {
            if let ast::Expr::Call(call) = value.as_ref()
                && is_self_method_call(call, method_name)
                && let Some(arg) = call.arguments.args.first()
                && let Some(req) = get_string_value(arg)
            {
                out.push(truncate_field(req));
            }
        }
        ast::Stmt::If(ast::StmtIf {
            body,
            elif_else_clauses,
            ..
        }) => {
            for nested in body {
                collect_self_method_calls(nested, method_name, out, depth + 1, node_count);
            }
            for clause in elif_else_clauses {
                for nested in &clause.body {
                    collect_self_method_calls(nested, method_name, out, depth + 1, node_count);
                }
            }
        }
        ast::Stmt::With(ast::StmtWith { body, .. })
        | ast::Stmt::While(ast::StmtWhile { body, .. })
        | ast::Stmt::For(ast::StmtFor { body, .. }) => {
            for nested in body {
                collect_self_method_calls(nested, method_name, out, depth + 1, node_count);
            }
        }
        ast::Stmt::Try(ast::StmtTry {
            body,
            handlers,
            orelse,
            finalbody,
            ..
        }) => {
            for nested in body.iter().chain(orelse.iter()).chain(finalbody.iter()) {
                collect_self_method_calls(nested, method_name, out, depth + 1, node_count);
            }
            for handler in handlers {
                let ast::ExceptHandler::ExceptHandler(handler) = handler;
                for nested in &handler.body {
                    collect_self_method_calls(nested, method_name, out, depth + 1, node_count);
                }
            }
        }
        ast::Stmt::Match(ast::StmtMatch { cases, .. }) => {
            for case in cases {
                for nested in &case.body {
                    collect_self_method_calls(nested, method_name, out, depth + 1, node_count);
                }
            }
        }
        _ => {}
    }
}

fn is_self_method_call(call: &ast::ExprCall, method_name: &str) -> bool {
    if let ast::Expr::Attribute(ast::ExprAttribute { value, attr, .. }) = call.func.as_ref()
        && let ast::Expr::Name(ast::ExprName { id, .. }) = value.as_ref()
    {
        return id.as_str() == "self" && attr.as_str() == method_name;
    }
    false
}

/// Conan conanfile.txt manifest parser.
///
/// Extracts dependencies from the simple conanfile.txt format, which uses
/// INI-style sections to specify runtime and build-time dependencies.
pub struct ConanfileTxtParser;

impl PackageParser for ConanfileTxtParser {
    const PACKAGE_TYPE: PackageType = PackageType::Conan;

    fn is_match(path: &Path) -> bool {
        path.file_name().is_some_and(|name| name == "conanfile.txt")
    }

    fn extract_packages(path: &Path) -> Vec<PackageData> {
        let contents = match read_file_to_string(path, None) {
            Ok(c) => c,
            Err(e) => {
                warn!("Failed to read {}: {}", path.display(), e);
                return vec![default_package_data(DatasourceId::ConanConanFileTxt)];
            }
        };

        let dependencies = parse_conanfile_txt(&contents);

        vec![PackageData {
            package_type: Some(Self::PACKAGE_TYPE),
            dependencies,
            primary_language: Some("C++".to_string()),
            datasource_id: Some(DatasourceId::ConanConanFileTxt),
            ..default_package_data(DatasourceId::ConanConanFileTxt)
        }]
    }
}

/// Conan lockfile (conan.lock) parser.
///
/// Extracts resolved dependencies from Conan lockfiles, which capture the
/// complete dependency graph with exact versions and revisions.
pub struct ConanLockParser;

impl PackageParser for ConanLockParser {
    const PACKAGE_TYPE: PackageType = PackageType::Conan;

    fn is_match(path: &Path) -> bool {
        path.file_name().is_some_and(|name| name == "conan.lock")
    }

    fn extract_packages(path: &Path) -> Vec<PackageData> {
        let contents = match read_file_to_string(path, None) {
            Ok(c) => c,
            Err(e) => {
                warn!("Failed to read {}: {}", path.display(), e);
                return vec![default_package_data(DatasourceId::ConanLock)];
            }
        };

        let json: Value = match serde_json::from_str(&contents) {
            Ok(j) => j,
            Err(e) => {
                warn!("Failed to parse JSON in {}: {}", path.display(), e);
                return vec![default_package_data(DatasourceId::ConanLock)];
            }
        };

        let dependencies = parse_conan_lock(&json);

        vec![PackageData {
            package_type: Some(Self::PACKAGE_TYPE),
            dependencies,
            primary_language: Some("C++".to_string()),
            datasource_id: Some(DatasourceId::ConanLock),
            ..default_package_data(DatasourceId::ConanLock)
        }]
    }
}

fn parse_conan_reference(ref_str: &str) -> Option<Dependency> {
    let (name, version_spec) = if let Some((n, v)) = ref_str.split_once('/') {
        (n.trim(), Some(truncate_field(v.trim().to_string())))
    } else {
        (ref_str.trim(), None)
    };

    let version = version_spec.as_ref().and_then(|v| {
        if !v.contains('[') && !v.contains('>') && !v.contains('<') {
            Some(v.clone())
        } else {
            None
        }
    });

    let purl = if let Some(v) = version.as_deref() {
        PackageUrl::new("conan", name)
            .map(|mut p| {
                let _ = p.with_version(v);
                p.to_string()
            })
            .unwrap_or_else(|_| format!("pkg:conan/{}", name))
    } else {
        format!("pkg:conan/{}", name)
    };

    let is_pinned = version_spec
        .as_ref()
        .map(|v| !v.contains('[') && !v.contains('>') && !v.contains('<'))
        .unwrap_or(false);

    Some(Dependency {
        purl: Some(truncate_field(purl)),
        extracted_requirement: version_spec,
        scope: Some("install".to_string()),
        is_runtime: Some(true),
        is_optional: Some(false),
        is_pinned: Some(is_pinned),
        is_direct: Some(true),
        resolved_package: None,
        extra_data: None,
    })
}

fn parse_conanfile_txt(contents: &str) -> Vec<Dependency> {
    let mut dependencies = Vec::new();
    let mut current_section = None;

    for line in contents.lines().take(MAX_ITERATION_COUNT) {
        let trimmed = line.trim();

        if trimmed.is_empty() || trimmed.starts_with('#') {
            continue;
        }

        if trimmed.starts_with('[') && trimmed.ends_with(']') {
            current_section = Some(trimmed.trim_matches(|c| c == '[' || c == ']').to_string());
            continue;
        }

        if let Some(ref section) = current_section {
            let (scope, is_runtime) = match section.as_str() {
                "requires" => ("install", true),
                "build_requires" => ("build", false),
                _ => continue,
            };

            if let Some(dep) = parse_conan_reference(trimmed) {
                dependencies.push(Dependency {
                    scope: Some(scope.to_string()),
                    is_runtime: Some(is_runtime),
                    ..dep
                });
            }
        }
    }

    dependencies
}

fn parse_conan_lock(json: &Value) -> Vec<Dependency> {
    let mut dependencies = Vec::new();

    if let Some(graph_lock) = json.get("graph_lock")
        && let Some(nodes) = graph_lock.get("nodes").and_then(|n| n.as_object())
    {
        for (_node_id, node_data) in nodes.iter().take(MAX_ITERATION_COUNT) {
            if let Some(ref_str) = node_data.get("ref").and_then(|r| r.as_str())
                && !ref_str.is_empty()
                && ref_str != "conanfile"
                && let Some(dep) = parse_conan_reference(ref_str)
            {
                dependencies.push(dep);
            }
        }
    }

    dependencies
}

fn default_package_data(datasource_id: DatasourceId) -> PackageData {
    PackageData {
        package_type: Some(ConanFilePyParser::PACKAGE_TYPE),
        primary_language: Some("C++".to_string()),
        datasource_id: Some(datasource_id),
        ..Default::default()
    }
}