Skip to main content

astrs_cli/command/
migrate.rs

1//! `astrs migrate from-dora` / `from-ros2` (blueprint §8.6, §17):
2//! delegates the actual mapping to `astrs-migrate`; this module is just
3//! the CLI-facing wiring (argument handling, output routing, human/JSON
4//! rendering).
5
6use std::io::Write;
7use std::path::PathBuf;
8
9use serde::Serialize;
10
11use crate::error::CliError;
12
13/// Arguments for `astrs migrate from-dora`.
14#[derive(Debug, Clone)]
15pub struct FromDoraArgs {
16    /// The dora dataflow descriptor to migrate.
17    pub input: PathBuf,
18    /// Write the migrated manifest here instead of the output sink.
19    pub output: Option<PathBuf>,
20    /// Emit a structured JSON report (migrated YAML plus every
21    /// [`astrs_migrate::MigrationNote`]) instead of plain YAML/a summary
22    /// line.
23    pub json: bool,
24}
25
26/// Arguments for `astrs migrate from-ros2`.
27#[derive(Debug, Clone)]
28pub struct FromRos2Args {
29    /// The ROS 2 launch file to skim (XML or Python -- dispatched by
30    /// extension, see [`astrs_migrate::migrate_ros2_launch_file`]).
31    pub input: PathBuf,
32    /// Write the migrated manifest here instead of the output sink.
33    pub output: Option<PathBuf>,
34    /// Emit a structured JSON report (migrated YAML plus every
35    /// [`astrs_migrate::Ros2MigrationNote`]) instead of plain YAML/a
36    /// summary line.
37    pub json: bool,
38}
39
40/// The result of `astrs migrate from-dora`.
41#[derive(Debug, Clone, Serialize)]
42pub struct FromDoraReport {
43    /// The migrated manifest, rendered as YAML with `TODO(astrs migrate)`
44    /// comments (see [`astrs_migrate::MigrationResult::yaml`]).
45    pub yaml: String,
46    /// Every observation made during the mapping.
47    pub notes: Vec<astrs_migrate::MigrationNote>,
48    /// The file it was written to, if [`FromDoraArgs::output`] was set.
49    pub written_to: Option<PathBuf>,
50}
51
52impl FromDoraReport {
53    /// `2` if any note is [`astrs_migrate::NoteSeverity::NeedsAttention`]
54    /// (the migrated manifest almost certainly needs a human before it
55    /// runs), `0` otherwise — mirroring `validate`'s "clean vs. needs a
56    /// look" convention, without reusing its exact 0/1/2 scale (a
57    /// migration note is never merely a warning: every
58    /// `NeedsAttention` note names something this importer could not
59    /// automatically translate at all).
60    #[must_use]
61    pub fn exit_code(&self) -> i32 {
62        if self
63            .notes
64            .iter()
65            .any(|n| n.severity == astrs_migrate::NoteSeverity::NeedsAttention)
66        {
67            2
68        } else {
69            0
70        }
71    }
72}
73
74/// The result of `astrs migrate from-ros2`.
75#[derive(Debug, Clone, Serialize)]
76pub struct FromRos2Report {
77    /// The migrated manifest, rendered as YAML with `TODO(astrs migrate)`
78    /// comments (see [`astrs_migrate::Ros2MigrationResult::yaml`]).
79    pub yaml: String,
80    /// Every observation made during the mapping.
81    pub notes: Vec<astrs_migrate::Ros2MigrationNote>,
82    /// The file it was written to, if [`FromRos2Args::output`] was set.
83    pub written_to: Option<PathBuf>,
84}
85
86impl FromRos2Report {
87    /// `2` if any note is [`astrs_migrate::Ros2NoteSeverity::NeedsAttention`],
88    /// `0` otherwise -- see [`FromDoraReport::exit_code`] for the
89    /// underlying convention this mirrors.
90    ///
91    /// For the XML launch-file path this is effectively **always `2`**
92    /// once at least one `<node>` was discovered: a bridge's
93    /// `message_type`/`direction` can never be inferred from a launch
94    /// file alone (`astrs_migrate::ros2::convert`'s own docs), so every
95    /// discovered node contributes at least one `NeedsAttention` note.
96    /// That is expected and honest, not a bug -- a `from-ros2` run that
97    /// reports `0` either found no nodes at all, or migrated a Python
98    /// launch file whose skim found no candidates either (its general
99    /// "Python is not parsed" note is root-level but still
100    /// `NeedsAttention`, so even that path is realistically never `0`
101    /// with real content).
102    #[must_use]
103    pub fn exit_code(&self) -> i32 {
104        if self
105            .notes
106            .iter()
107            .any(|n| n.severity == astrs_migrate::Ros2NoteSeverity::NeedsAttention)
108        {
109            2
110        } else {
111            0
112        }
113    }
114}
115
116/// Run `astrs migrate from-dora`.
117///
118/// With neither `--output` nor `--json`, the migrated YAML (comments and
119/// all) is written to `out` directly — `astrs migrate from-dora
120/// dataflow.yml > astrs-dataflow.yml` works exactly like every other
121/// Unix text-generating tool. `--json` always prints the full structured
122/// report instead (even alongside `--output`, so a script gets a
123/// programmatic summary of what needs attention without re-parsing YAML
124/// comments) regardless of whether `--output` was also given.
125///
126/// # Errors
127///
128/// Returns [`CliError::DoraMigrate`] if the input cannot be read or
129/// parsed, or [`CliError::Io`] if `--output` cannot be written.
130pub fn run_from_dora(out: &mut dyn Write, args: &FromDoraArgs) -> Result<FromDoraReport, CliError> {
131    let result = astrs_migrate::migrate_file(&args.input)?;
132
133    if let Some(path) = &args.output {
134        std::fs::write(path, &result.yaml).map_err(|err| CliError::io(path, err))?;
135    }
136
137    let report = FromDoraReport {
138        yaml: result.yaml,
139        notes: result.notes,
140        written_to: args.output.clone(),
141    };
142
143    match (&args.output, args.json) {
144        (_, true) => {
145            let json = serde_json::to_string_pretty(&report).unwrap_or_else(|err| {
146                format!("{{\"error\": \"failed to serialize migrate report: {err}\"}}")
147            });
148            writeln!(out, "{json}").map_err(|e| CliError::io("<output>", e))?;
149        }
150        (None, false) => {
151            writeln!(out, "{}", report.yaml).map_err(|e| CliError::io("<output>", e))?;
152        }
153        (Some(path), false) => {
154            let needs_attention = report
155                .notes
156                .iter()
157                .filter(|n| n.severity == astrs_migrate::NoteSeverity::NeedsAttention)
158                .count();
159            let dropped = report.notes.len() - needs_attention;
160            writeln!(
161                out,
162                "migrated `{}` -> `{}` ({needs_attention} note(s) need attention, {dropped} dropped)",
163                args.input.display(),
164                path.display(),
165            )
166            .map_err(|e| CliError::io("<output>", e))?;
167        }
168    }
169
170    Ok(report)
171}
172
173/// Run `astrs migrate from-ros2`.
174///
175/// Mirrors [`run_from_dora`] exactly -- same `--output`/`--json`
176/// precedence, same plain-text summary shape -- see that function's docs
177/// for the full behavior; the only difference is the underlying importer
178/// ([`astrs_migrate::migrate_ros2_launch_file`], which also dispatches
179/// XML vs. Python launch files by extension).
180///
181/// # Errors
182///
183/// Returns [`CliError::Ros2Migrate`] if the input cannot be read or
184/// parsed (or, for XML input, if its `<include>` graph is a cycle or
185/// nests past the depth limit), or [`CliError::Io`] if `--output` cannot
186/// be written.
187pub fn run_from_ros2(out: &mut dyn Write, args: &FromRos2Args) -> Result<FromRos2Report, CliError> {
188    let result = astrs_migrate::migrate_ros2_launch_file(&args.input)?;
189
190    if let Some(path) = &args.output {
191        std::fs::write(path, &result.yaml).map_err(|err| CliError::io(path, err))?;
192    }
193
194    let report = FromRos2Report {
195        yaml: result.yaml,
196        notes: result.notes,
197        written_to: args.output.clone(),
198    };
199
200    match (&args.output, args.json) {
201        (_, true) => {
202            let json = serde_json::to_string_pretty(&report).unwrap_or_else(|err| {
203                format!("{{\"error\": \"failed to serialize migrate report: {err}\"}}")
204            });
205            writeln!(out, "{json}").map_err(|e| CliError::io("<output>", e))?;
206        }
207        (None, false) => {
208            writeln!(out, "{}", report.yaml).map_err(|e| CliError::io("<output>", e))?;
209        }
210        (Some(path), false) => {
211            let needs_attention = report
212                .notes
213                .iter()
214                .filter(|n| n.severity == astrs_migrate::Ros2NoteSeverity::NeedsAttention)
215                .count();
216            let dropped = report.notes.len() - needs_attention;
217            writeln!(
218                out,
219                "migrated `{}` -> `{}` ({needs_attention} note(s) need attention, {dropped} dropped)",
220                args.input.display(),
221                path.display(),
222            )
223            .map_err(|e| CliError::io("<output>", e))?;
224        }
225    }
226
227    Ok(report)
228}
229
230#[cfg(test)]
231mod tests {
232    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
233    use super::*;
234
235    fn write_temp(name: &str, content: &str) -> PathBuf {
236        // A monotonic counter, not just `(pid, name)`, disambiguates the
237        // directory -- see `command::graph`'s own test helper for the
238        // observed race this guards against if a future test ever reuses
239        // an existing `name` under cargo's multi-threaded test runner.
240        static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
241        let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
242        let dir = std::env::temp_dir().join(format!(
243            "astrs-cli-migrate-test-{}-{name}-{n}",
244            std::process::id()
245        ));
246        std::fs::create_dir_all(&dir).unwrap();
247        let path = dir.join("dataflow.yml");
248        std::fs::write(&path, content).unwrap();
249        path
250    }
251
252    #[test]
253    fn plain_run_prints_yaml_directly_to_the_sink() {
254        let path = write_temp("plain", "nodes:\n  - id: solo\n    path: ./solo\n");
255        let mut out = Vec::new();
256        let report = run_from_dora(
257            &mut out,
258            &FromDoraArgs {
259                input: path,
260                output: None,
261                json: false,
262            },
263        )
264        .unwrap();
265        let printed = String::from_utf8(out).unwrap();
266        assert_eq!(printed.trim_end(), report.yaml.trim_end());
267        assert_eq!(report.exit_code(), 0);
268    }
269
270    #[test]
271    fn needs_attention_notes_produce_exit_code_two() {
272        let path = write_temp("hub", "nodes:\n  - id: x\n    hub: dora-yolo@^0.5\n");
273        let mut out = Vec::new();
274        let report = run_from_dora(
275            &mut out,
276            &FromDoraArgs {
277                input: path,
278                output: None,
279                json: false,
280            },
281        )
282        .unwrap();
283        assert_eq!(report.exit_code(), 2);
284    }
285
286    #[test]
287    fn output_flag_writes_the_file_and_prints_a_summary() {
288        let dir = std::env::temp_dir().join(format!(
289            "astrs-cli-migrate-test-{}-output",
290            std::process::id()
291        ));
292        std::fs::create_dir_all(&dir).unwrap();
293        let input = dir.join("dataflow.yml");
294        std::fs::write(&input, "nodes:\n  - id: solo\n    path: ./solo\n").unwrap();
295        let output = dir.join("migrated.yaml");
296
297        let mut out = Vec::new();
298        let report = run_from_dora(
299            &mut out,
300            &FromDoraArgs {
301                input,
302                output: Some(output.clone()),
303                json: false,
304            },
305        )
306        .unwrap();
307        let on_disk = std::fs::read_to_string(&output).unwrap();
308        assert_eq!(on_disk, report.yaml);
309        let printed = String::from_utf8(out).unwrap();
310        assert!(printed.contains("migrated"));
311        assert!(
312            !printed.contains("nodes:"),
313            "the sink should get a summary, not the YAML: {printed}"
314        );
315
316        let _ = std::fs::remove_dir_all(&dir);
317    }
318
319    #[test]
320    fn json_flag_emits_a_structured_report_with_notes() {
321        let path = write_temp(
322            "json",
323            "nodes:\n  - id: x\n    path: ./x\n    path_sha256: deadbeef\n",
324        );
325        let mut out = Vec::new();
326        let report = run_from_dora(
327            &mut out,
328            &FromDoraArgs {
329                input: path,
330                output: None,
331                json: true,
332            },
333        )
334        .unwrap();
335        let printed = String::from_utf8(out).unwrap();
336        let value: serde_json::Value = serde_json::from_str(&printed).unwrap();
337        assert_eq!(value["notes"].as_array().map(Vec::len), Some(1));
338        assert_eq!(report.notes.len(), 1);
339    }
340
341    #[test]
342    fn missing_input_is_a_dora_migrate_error() {
343        let mut out = Vec::new();
344        let err = run_from_dora(
345            &mut out,
346            &FromDoraArgs {
347                input: std::env::temp_dir().join("astrs-cli-migrate-does-not-exist.yml"),
348                output: None,
349                json: false,
350            },
351        )
352        .unwrap_err();
353        assert!(matches!(err, CliError::DoraMigrate(_)));
354    }
355
356    fn write_temp_ros2(name: &str, content: &str) -> PathBuf {
357        static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
358        let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
359        let dir = std::env::temp_dir().join(format!(
360            "astrs-cli-migrate-ros2-test-{}-{name}-{n}",
361            std::process::id()
362        ));
363        std::fs::create_dir_all(&dir).unwrap();
364        let path = dir.join("robot.launch.xml");
365        std::fs::write(&path, content).unwrap();
366        path
367    }
368
369    #[test]
370    fn ros2_plain_run_prints_yaml_directly_to_the_sink() {
371        let path = write_temp_ros2("plain", "<launch/>");
372        let mut out = Vec::new();
373        let report = run_from_ros2(
374            &mut out,
375            &FromRos2Args {
376                input: path,
377                output: None,
378                json: false,
379            },
380        )
381        .unwrap();
382        let printed = String::from_utf8(out).unwrap();
383        assert_eq!(printed.trim_end(), report.yaml.trim_end());
384        assert_eq!(
385            report.exit_code(),
386            0,
387            "a nodeless launch file has no notes at all"
388        );
389    }
390
391    #[test]
392    fn ros2_a_discovered_node_always_needs_attention() {
393        let path = write_temp_ros2(
394            "node",
395            r#"<launch><node pkg="p" exec="e" name="n"/></launch>"#,
396        );
397        let mut out = Vec::new();
398        let report = run_from_ros2(
399            &mut out,
400            &FromRos2Args {
401                input: path,
402                output: None,
403                json: false,
404            },
405        )
406        .unwrap();
407        assert_eq!(report.exit_code(), 2, "message_type is never inferable");
408    }
409
410    #[test]
411    fn ros2_output_flag_writes_the_file_and_prints_a_summary() {
412        let dir = std::env::temp_dir().join(format!(
413            "astrs-cli-migrate-ros2-test-{}-output",
414            std::process::id()
415        ));
416        std::fs::create_dir_all(&dir).unwrap();
417        let input = dir.join("robot.launch.xml");
418        std::fs::write(&input, "<launch/>").unwrap();
419        let output = dir.join("migrated.yaml");
420
421        let mut out = Vec::new();
422        let report = run_from_ros2(
423            &mut out,
424            &FromRos2Args {
425                input,
426                output: Some(output.clone()),
427                json: false,
428            },
429        )
430        .unwrap();
431        let on_disk = std::fs::read_to_string(&output).unwrap();
432        assert_eq!(on_disk, report.yaml);
433        let printed = String::from_utf8(out).unwrap();
434        assert!(printed.contains("migrated"));
435        assert!(
436            !printed.contains("nodes:"),
437            "the sink should get a summary, not the YAML: {printed}"
438        );
439
440        let _ = std::fs::remove_dir_all(&dir);
441    }
442
443    #[test]
444    fn ros2_json_flag_emits_a_structured_report_with_notes() {
445        let path = write_temp_ros2(
446            "json",
447            r#"<launch><node pkg="p" exec="e" name="n"/></launch>"#,
448        );
449        let mut out = Vec::new();
450        let report = run_from_ros2(
451            &mut out,
452            &FromRos2Args {
453                input: path,
454                output: None,
455                json: true,
456            },
457        )
458        .unwrap();
459        let printed = String::from_utf8(out).unwrap();
460        let value: serde_json::Value = serde_json::from_str(&printed).unwrap();
461        assert_eq!(value["notes"].as_array().map(Vec::len), Some(1));
462        assert_eq!(report.notes.len(), 1);
463    }
464
465    #[test]
466    fn ros2_missing_input_is_a_ros2_migrate_error() {
467        let mut out = Vec::new();
468        let err = run_from_ros2(
469            &mut out,
470            &FromRos2Args {
471                input: std::env::temp_dir().join("astrs-cli-migrate-ros2-does-not-exist.xml"),
472                output: None,
473                json: false,
474            },
475        )
476        .unwrap_err();
477        assert!(matches!(err, CliError::Ros2Migrate(_)));
478        assert_eq!(
479            err.exit_code(),
480            1,
481            "a missing file is an ordinary failure, not `this feature is unavailable`"
482        );
483    }
484
485    #[test]
486    fn ros2_malformed_xml_is_a_ros2_migrate_error() {
487        let path = write_temp_ros2("malformed", "<launch><node>");
488        let mut out = Vec::new();
489        let err = run_from_ros2(
490            &mut out,
491            &FromRos2Args {
492                input: path,
493                output: None,
494                json: false,
495            },
496        )
497        .unwrap_err();
498        assert!(matches!(err, CliError::Ros2Migrate(_)));
499    }
500
501    #[test]
502    fn ros2_dispatches_python_launch_files_by_extension() {
503        let dir = std::env::temp_dir().join(format!(
504            "astrs-cli-migrate-ros2-test-{}-python",
505            std::process::id()
506        ));
507        std::fs::create_dir_all(&dir).unwrap();
508        let path = dir.join("robot.launch.py");
509        std::fs::write(&path, "Node(name='n')").unwrap();
510
511        let mut out = Vec::new();
512        let report = run_from_ros2(
513            &mut out,
514            &FromRos2Args {
515                input: path,
516                output: None,
517                json: false,
518            },
519        )
520        .unwrap();
521        assert!(report.yaml.starts_with("# Skeleton scaffold"));
522
523        let _ = std::fs::remove_dir_all(&dir);
524    }
525}