igniscope 0.1.0

Deterministic CLI analyzer for Ignition project exports and gateway backups.
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
use std::fmt::Write as _;
use std::fs;
use std::path::{Path, PathBuf};

use crate::archive::{
    AnalyticsBundle, build_analytics_bundle, discover_resources_for_roots, inspect_archive,
    parse_project_metadata,
};
use crate::error::AppError;

const GENERATED_AT_PLACEHOLDER: &str = "1970-01-01T00:00:00Z";
const ANALYTICS_FILE_NAME: &str = "analytics.json";
const REPORT_FILE_NAME: &str = "report.md";

/// Handles the `summarize` command for archive inspection and project parsing.
pub fn run_summarize(archive_path: &Path, verbose: u8) -> Result<(), AppError> {
    let analytics = run_pipeline(archive_path)?;
    let output = render_summary_text(archive_path, &analytics, verbose);
    print!("{output}");
    Ok(())
}

/// Handles the `analyze` command for archive inspection and project parsing.
pub fn run_analyze(archive_path: &Path, out_dir: &Path, verbose: u8) -> Result<(), AppError> {
    let analytics = run_pipeline(archive_path)?;
    let output_paths = write_outputs(out_dir, &analytics)?;
    let summary_output = render_summary_text(archive_path, &analytics, verbose);
    print!("{summary_output}");
    println!("analytics_json: {}", output_paths.analytics_json.display());
    println!("report_md: {}", output_paths.report_md.display());
    Ok(())
}

/// Runs the full inspection and analytics pipeline for one archive.
fn run_pipeline(archive_path: &Path) -> Result<AnalyticsBundle, AppError> {
    let inspection = inspect_archive(archive_path)?;
    let project_metadata =
        parse_project_metadata(archive_path, &inspection.selected_project_roots)?;
    let resource_inventories =
        discover_resources_for_roots(archive_path, &inspection.selected_project_roots)?;
    build_analytics_bundle(
        archive_path,
        GENERATED_AT_PLACEHOLDER,
        &inspection,
        &project_metadata,
        &resource_inventories,
    )
}

/// Writes deterministic output artifacts to the requested directory.
fn write_outputs(out_dir: &Path, analytics: &AnalyticsBundle) -> Result<OutputPaths, AppError> {
    fs::create_dir_all(out_dir).map_err(|err| {
        AppError::internal(format!(
            "could not create output directory `{}`: {err}",
            out_dir.display()
        ))
    })?;

    let analytics_json_path = out_dir.join(ANALYTICS_FILE_NAME);
    let report_path = out_dir.join(REPORT_FILE_NAME);

    let analytics_json = serde_json::to_string_pretty(analytics).map_err(|err| {
        AppError::internal(format!(
            "could not serialize analytics output to JSON: {err}"
        ))
    })?;
    fs::write(&analytics_json_path, format!("{analytics_json}\n")).map_err(|err| {
        AppError::internal(format!(
            "could not write `{}`: {err}",
            analytics_json_path.display()
        ))
    })?;

    let report = render_report_markdown(analytics);
    fs::write(&report_path, report).map_err(|err| {
        AppError::internal(format!(
            "could not write `{}`: {err}",
            report_path.display()
        ))
    })?;

    Ok(OutputPaths {
        analytics_json: analytics_json_path,
        report_md: report_path,
    })
}

/// Renders deterministic `summarize` stdout text from analytics output.
fn render_summary_text(archive_path: &Path, analytics: &AnalyticsBundle, verbose: u8) -> String {
    let mut output = String::new();
    let _ = writeln!(&mut output, "archive_path: {}", archive_path.display());
    let _ = writeln!(
        &mut output,
        "archive_kind: {}",
        analytics.input.archive_kind
    );
    let _ = writeln!(
        &mut output,
        "projects_total: {}",
        analytics.summary.projects_total
    );
    let _ = writeln!(
        &mut output,
        "selected_project_roots: {:?}",
        analytics.input.selected_project_roots
    );
    let _ = writeln!(
        &mut output,
        "resources_total: {}",
        analytics.summary.resources_total
    );
    let _ = writeln!(
        &mut output,
        "files_total: {}",
        analytics.summary.files_total
    );
    let _ = writeln!(
        &mut output,
        "unknown_ratio: {:.6}",
        analytics.summary.unknown_ratio
    );

    if verbose > 0 {
        for project in &analytics.projects {
            let _ = writeln!(
                &mut output,
                "project: root={} title={} resources={} unknown_ratio={:.6}",
                display_project_root(&project.project_root),
                project.project.title,
                project.counts.resources_total,
                project.coverage.unknown_ratio
            );
        }
    }

    output
}

/// Renders deterministic markdown report output for `analyze`.
fn render_report_markdown(analytics: &AnalyticsBundle) -> String {
    let mut report = String::new();

    let _ = writeln!(&mut report, "# igniscope report");
    let _ = writeln!(&mut report);

    let _ = writeln!(&mut report, "## Input Summary");
    let _ = writeln!(&mut report);
    let _ = writeln!(
        &mut report,
        "- archive_kind: `{}`",
        analytics.input.archive_kind
    );
    let _ = writeln!(
        &mut report,
        "- projects_total: {}",
        analytics.summary.projects_total
    );
    let _ = writeln!(&mut report, "- selected_project_roots:");
    for project_root in &analytics.input.selected_project_roots {
        let _ = writeln!(&mut report, "  - `{}`", display_project_root(project_root));
    }
    let _ = writeln!(&mut report);

    let _ = writeln!(&mut report, "## Overall Aggregate Summary");
    let _ = writeln!(&mut report);
    let _ = writeln!(
        &mut report,
        "- resources_total: {}",
        analytics.summary.resources_total
    );
    let _ = writeln!(
        &mut report,
        "- files_total: {}",
        analytics.summary.files_total
    );
    let _ = writeln!(
        &mut report,
        "- binary_only_resources: {}",
        analytics.summary.binary_only_resources
    );
    let _ = writeln!(&mut report);

    write_count_map_section(
        &mut report,
        "## Counts By Section",
        &analytics.summary.resources_by_section,
    );
    write_count_map_section(
        &mut report,
        "## Counts By Type Key",
        &analytics.summary.resources_by_type,
    );
    write_count_map_section(
        &mut report,
        "## File Kind Breakdown",
        &analytics.summary.files_by_kind,
    );

    let _ = writeln!(&mut report, "## Coverage Summary");
    let _ = writeln!(&mut report);
    let _ = writeln!(
        &mut report,
        "- unknown_resources: {}",
        analytics.summary.unknown_resources
    );
    let _ = writeln!(
        &mut report,
        "- unknown_ratio: {:.6}",
        analytics.summary.unknown_ratio
    );
    let _ = writeln!(&mut report);

    let _ = writeln!(&mut report, "## Per-Project Details");
    let _ = writeln!(&mut report);
    for project in &analytics.projects {
        let _ = writeln!(
            &mut report,
            "### Project `{}`",
            display_project_root(&project.project_root)
        );
        let _ = writeln!(&mut report);
        let _ = writeln!(&mut report, "- title: {}", project.project.title);
        let _ = writeln!(
            &mut report,
            "- description: {:?}",
            project.project.description
        );
        let _ = writeln!(&mut report, "- parent: {:?}", project.project.parent);
        let _ = writeln!(&mut report, "- enabled: {}", project.project.enabled);
        let _ = writeln!(
            &mut report,
            "- inheritable: {}",
            project.project.inheritable
        );
        let _ = writeln!(
            &mut report,
            "- resources_total: {}",
            project.counts.resources_total
        );
        let _ = writeln!(&mut report, "- files_total: {}", project.counts.files_total);
        let _ = writeln!(
            &mut report,
            "- binary_only_resources: {}",
            project.counts.binary_only_resources
        );
        let _ = writeln!(
            &mut report,
            "- unknown_resources: {}",
            project.coverage.unknown_resources
        );
        let _ = writeln!(
            &mut report,
            "- unknown_ratio: {:.6}",
            project.coverage.unknown_ratio
        );
        let _ = writeln!(&mut report);

        write_project_count_subsection(
            &mut report,
            "#### Counts By Section",
            &project.counts.resources_by_section,
        );
        write_project_count_subsection(
            &mut report,
            "#### Counts By Type Key",
            &project.counts.resources_by_type,
        );
        write_project_count_subsection(
            &mut report,
            "#### File Kind Breakdown",
            &project.counts.files_by_kind,
        );

        if project.issues.is_empty() {
            let _ = writeln!(&mut report, "- issues: no issues");
        } else {
            let _ = writeln!(&mut report, "- issues:");
            for issue in &project.issues {
                let _ = writeln!(&mut report, "  - {issue}");
            }
        }
        let _ = writeln!(&mut report);
    }

    let _ = writeln!(&mut report, "## Issues");
    let _ = writeln!(&mut report);
    if analytics.issues.is_empty() {
        let _ = writeln!(&mut report, "No issues.");
    } else {
        for issue in &analytics.issues {
            let _ = writeln!(&mut report, "- {issue}");
        }
    }
    report
}

/// Writes a top-level summary count section as deterministic markdown bullets.
fn write_count_map_section(
    report: &mut String,
    heading: &str,
    counts: &std::collections::BTreeMap<String, usize>,
) {
    let _ = writeln!(report, "{heading}");
    let _ = writeln!(report);
    if counts.is_empty() {
        let _ = writeln!(report, "- none");
    } else {
        for (key, value) in counts {
            let _ = writeln!(report, "- `{key}`: {value}");
        }
    }
    let _ = writeln!(report);
}

/// Writes a per-project count subsection as deterministic markdown bullets.
fn write_project_count_subsection(
    report: &mut String,
    heading: &str,
    counts: &std::collections::BTreeMap<String, usize>,
) {
    let _ = writeln!(report, "{heading}");
    let _ = writeln!(report);
    if counts.is_empty() {
        let _ = writeln!(report, "- none");
    } else {
        for (key, value) in counts {
            let _ = writeln!(report, "- `{key}`: {value}");
        }
    }
    let _ = writeln!(report);
}

/// Normalizes project-root display to avoid empty-string output in reports.
fn display_project_root(project_root: &str) -> &str {
    if project_root.is_empty() {
        "(root)"
    } else {
        project_root
    }
}

#[derive(Debug)]
struct OutputPaths {
    analytics_json: PathBuf,
    report_md: PathBuf,
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;
    use std::path::Path;

    use crate::archive::{
        AnalyticsInput, AnalyticsSummary, CoverageMetrics, ProjectAnalytics, ProjectCounts,
        ProjectMetadata,
    };

    use super::{display_project_root, render_report_markdown, render_summary_text};

    fn synthetic_analytics() -> crate::archive::AnalyticsBundle {
        crate::archive::AnalyticsBundle {
            schema_version: "0.1.0".to_string(),
            generated_at: "1970-01-01T00:00:00Z".to_string(),
            input: AnalyticsInput {
                archive_path: "/tmp/synthetic.zip".to_string(),
                archive_kind: "project_export".to_string(),
                detected_project_roots: vec!["".to_string()],
                selected_project_roots: vec!["".to_string()],
            },
            summary: AnalyticsSummary {
                projects_total: 1,
                resources_total: 3,
                files_total: 5,
                binary_only_resources: 1,
                resources_by_section: BTreeMap::from([("Perspective".to_string(), 3usize)]),
                resources_by_type: BTreeMap::from([("perspective.view".to_string(), 3usize)]),
                files_by_kind: BTreeMap::from([
                    ("resource.json".to_string(), 3usize),
                    ("view.json".to_string(), 2usize),
                ]),
                unknown_resources: 0,
                unknown_ratio: 0.0,
            },
            projects: vec![ProjectAnalytics {
                project_root: "".to_string(),
                project: ProjectMetadata {
                    project_root: "".to_string(),
                    title: "Synthetic".to_string(),
                    description: None,
                    parent: None,
                    enabled: true,
                    inheritable: false,
                },
                counts: ProjectCounts {
                    resources_total: 3,
                    files_total: 5,
                    binary_only_resources: 1,
                    resources_by_section: BTreeMap::from([("Perspective".to_string(), 3usize)]),
                    resources_by_type: BTreeMap::from([("perspective.view".to_string(), 3usize)]),
                    files_by_kind: BTreeMap::from([
                        ("resource.json".to_string(), 3usize),
                        ("view.json".to_string(), 2usize),
                    ]),
                },
                coverage: CoverageMetrics {
                    unknown_resources: 0,
                    unknown_ratio: 0.0,
                },
                issues: vec![],
            }],
            issues: vec![],
            gateway_meta: None,
        }
    }

    #[test]
    fn summarize_output_includes_core_fields() {
        let analytics = synthetic_analytics();
        let output = render_summary_text(Path::new("/tmp/synthetic.zip"), &analytics, 0);
        assert!(output.contains("archive_kind: project_export"));
        assert!(output.contains("projects_total: 1"));
        assert!(output.contains("selected_project_roots: [\"\"]"));
    }

    #[test]
    fn summarize_output_includes_project_lines_in_verbose_mode() {
        let analytics = synthetic_analytics();
        let output = render_summary_text(Path::new("/tmp/synthetic.zip"), &analytics, 1);
        assert!(output.contains("project: root=(root) title=Synthetic resources=3"));
    }

    #[test]
    fn report_markdown_contains_required_sections() {
        let analytics = synthetic_analytics();
        let report = render_report_markdown(&analytics);
        assert!(report.contains("# igniscope report"));
        assert!(report.contains("## Input Summary"));
        assert!(report.contains("## Overall Aggregate Summary"));
        assert!(report.contains("## Counts By Section"));
        assert!(report.contains("## Counts By Type Key"));
        assert!(report.contains("## File Kind Breakdown"));
        assert!(report.contains("## Coverage Summary"));
        assert!(report.contains("## Per-Project Details"));
        assert!(report.contains("## Issues"));
    }

    #[test]
    fn root_display_is_human_readable() {
        assert_eq!(display_project_root(""), "(root)");
        assert_eq!(display_project_root("projects/alpha/"), "projects/alpha/");
    }
}