use std::io::Write;
use std::path::PathBuf;
use serde::Serialize;
use crate::error::CliError;
#[derive(Debug, Clone)]
pub struct FromDoraArgs {
pub input: PathBuf,
pub output: Option<PathBuf>,
pub json: bool,
}
#[derive(Debug, Clone)]
pub struct FromRos2Args {
pub input: PathBuf,
pub output: Option<PathBuf>,
pub json: bool,
}
#[derive(Debug, Clone, Serialize)]
pub struct FromDoraReport {
pub yaml: String,
pub notes: Vec<astrs_migrate::MigrationNote>,
pub written_to: Option<PathBuf>,
}
impl FromDoraReport {
#[must_use]
pub fn exit_code(&self) -> i32 {
if self
.notes
.iter()
.any(|n| n.severity == astrs_migrate::NoteSeverity::NeedsAttention)
{
2
} else {
0
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct FromRos2Report {
pub yaml: String,
pub notes: Vec<astrs_migrate::Ros2MigrationNote>,
pub written_to: Option<PathBuf>,
}
impl FromRos2Report {
#[must_use]
pub fn exit_code(&self) -> i32 {
if self
.notes
.iter()
.any(|n| n.severity == astrs_migrate::Ros2NoteSeverity::NeedsAttention)
{
2
} else {
0
}
}
}
pub fn run_from_dora(out: &mut dyn Write, args: &FromDoraArgs) -> Result<FromDoraReport, CliError> {
let result = astrs_migrate::migrate_file(&args.input)?;
if let Some(path) = &args.output {
std::fs::write(path, &result.yaml).map_err(|err| CliError::io(path, err))?;
}
let report = FromDoraReport {
yaml: result.yaml,
notes: result.notes,
written_to: args.output.clone(),
};
match (&args.output, args.json) {
(_, true) => {
let json = serde_json::to_string_pretty(&report).unwrap_or_else(|err| {
format!("{{\"error\": \"failed to serialize migrate report: {err}\"}}")
});
writeln!(out, "{json}").map_err(|e| CliError::io("<output>", e))?;
}
(None, false) => {
writeln!(out, "{}", report.yaml).map_err(|e| CliError::io("<output>", e))?;
}
(Some(path), false) => {
let needs_attention = report
.notes
.iter()
.filter(|n| n.severity == astrs_migrate::NoteSeverity::NeedsAttention)
.count();
let dropped = report.notes.len() - needs_attention;
writeln!(
out,
"migrated `{}` -> `{}` ({needs_attention} note(s) need attention, {dropped} dropped)",
args.input.display(),
path.display(),
)
.map_err(|e| CliError::io("<output>", e))?;
}
}
Ok(report)
}
pub fn run_from_ros2(out: &mut dyn Write, args: &FromRos2Args) -> Result<FromRos2Report, CliError> {
let result = astrs_migrate::migrate_ros2_launch_file(&args.input)?;
if let Some(path) = &args.output {
std::fs::write(path, &result.yaml).map_err(|err| CliError::io(path, err))?;
}
let report = FromRos2Report {
yaml: result.yaml,
notes: result.notes,
written_to: args.output.clone(),
};
match (&args.output, args.json) {
(_, true) => {
let json = serde_json::to_string_pretty(&report).unwrap_or_else(|err| {
format!("{{\"error\": \"failed to serialize migrate report: {err}\"}}")
});
writeln!(out, "{json}").map_err(|e| CliError::io("<output>", e))?;
}
(None, false) => {
writeln!(out, "{}", report.yaml).map_err(|e| CliError::io("<output>", e))?;
}
(Some(path), false) => {
let needs_attention = report
.notes
.iter()
.filter(|n| n.severity == astrs_migrate::Ros2NoteSeverity::NeedsAttention)
.count();
let dropped = report.notes.len() - needs_attention;
writeln!(
out,
"migrated `{}` -> `{}` ({needs_attention} note(s) need attention, {dropped} dropped)",
args.input.display(),
path.display(),
)
.map_err(|e| CliError::io("<output>", e))?;
}
}
Ok(report)
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
fn write_temp(name: &str, content: &str) -> PathBuf {
static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let dir = std::env::temp_dir().join(format!(
"astrs-cli-migrate-test-{}-{name}-{n}",
std::process::id()
));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("dataflow.yml");
std::fs::write(&path, content).unwrap();
path
}
#[test]
fn plain_run_prints_yaml_directly_to_the_sink() {
let path = write_temp("plain", "nodes:\n - id: solo\n path: ./solo\n");
let mut out = Vec::new();
let report = run_from_dora(
&mut out,
&FromDoraArgs {
input: path,
output: None,
json: false,
},
)
.unwrap();
let printed = String::from_utf8(out).unwrap();
assert_eq!(printed.trim_end(), report.yaml.trim_end());
assert_eq!(report.exit_code(), 0);
}
#[test]
fn needs_attention_notes_produce_exit_code_two() {
let path = write_temp("hub", "nodes:\n - id: x\n hub: dora-yolo@^0.5\n");
let mut out = Vec::new();
let report = run_from_dora(
&mut out,
&FromDoraArgs {
input: path,
output: None,
json: false,
},
)
.unwrap();
assert_eq!(report.exit_code(), 2);
}
#[test]
fn output_flag_writes_the_file_and_prints_a_summary() {
let dir = std::env::temp_dir().join(format!(
"astrs-cli-migrate-test-{}-output",
std::process::id()
));
std::fs::create_dir_all(&dir).unwrap();
let input = dir.join("dataflow.yml");
std::fs::write(&input, "nodes:\n - id: solo\n path: ./solo\n").unwrap();
let output = dir.join("migrated.yaml");
let mut out = Vec::new();
let report = run_from_dora(
&mut out,
&FromDoraArgs {
input,
output: Some(output.clone()),
json: false,
},
)
.unwrap();
let on_disk = std::fs::read_to_string(&output).unwrap();
assert_eq!(on_disk, report.yaml);
let printed = String::from_utf8(out).unwrap();
assert!(printed.contains("migrated"));
assert!(
!printed.contains("nodes:"),
"the sink should get a summary, not the YAML: {printed}"
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn json_flag_emits_a_structured_report_with_notes() {
let path = write_temp(
"json",
"nodes:\n - id: x\n path: ./x\n path_sha256: deadbeef\n",
);
let mut out = Vec::new();
let report = run_from_dora(
&mut out,
&FromDoraArgs {
input: path,
output: None,
json: true,
},
)
.unwrap();
let printed = String::from_utf8(out).unwrap();
let value: serde_json::Value = serde_json::from_str(&printed).unwrap();
assert_eq!(value["notes"].as_array().map(Vec::len), Some(1));
assert_eq!(report.notes.len(), 1);
}
#[test]
fn missing_input_is_a_dora_migrate_error() {
let mut out = Vec::new();
let err = run_from_dora(
&mut out,
&FromDoraArgs {
input: std::env::temp_dir().join("astrs-cli-migrate-does-not-exist.yml"),
output: None,
json: false,
},
)
.unwrap_err();
assert!(matches!(err, CliError::DoraMigrate(_)));
}
fn write_temp_ros2(name: &str, content: &str) -> PathBuf {
static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let dir = std::env::temp_dir().join(format!(
"astrs-cli-migrate-ros2-test-{}-{name}-{n}",
std::process::id()
));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("robot.launch.xml");
std::fs::write(&path, content).unwrap();
path
}
#[test]
fn ros2_plain_run_prints_yaml_directly_to_the_sink() {
let path = write_temp_ros2("plain", "<launch/>");
let mut out = Vec::new();
let report = run_from_ros2(
&mut out,
&FromRos2Args {
input: path,
output: None,
json: false,
},
)
.unwrap();
let printed = String::from_utf8(out).unwrap();
assert_eq!(printed.trim_end(), report.yaml.trim_end());
assert_eq!(
report.exit_code(),
0,
"a nodeless launch file has no notes at all"
);
}
#[test]
fn ros2_a_discovered_node_always_needs_attention() {
let path = write_temp_ros2(
"node",
r#"<launch><node pkg="p" exec="e" name="n"/></launch>"#,
);
let mut out = Vec::new();
let report = run_from_ros2(
&mut out,
&FromRos2Args {
input: path,
output: None,
json: false,
},
)
.unwrap();
assert_eq!(report.exit_code(), 2, "message_type is never inferable");
}
#[test]
fn ros2_output_flag_writes_the_file_and_prints_a_summary() {
let dir = std::env::temp_dir().join(format!(
"astrs-cli-migrate-ros2-test-{}-output",
std::process::id()
));
std::fs::create_dir_all(&dir).unwrap();
let input = dir.join("robot.launch.xml");
std::fs::write(&input, "<launch/>").unwrap();
let output = dir.join("migrated.yaml");
let mut out = Vec::new();
let report = run_from_ros2(
&mut out,
&FromRos2Args {
input,
output: Some(output.clone()),
json: false,
},
)
.unwrap();
let on_disk = std::fs::read_to_string(&output).unwrap();
assert_eq!(on_disk, report.yaml);
let printed = String::from_utf8(out).unwrap();
assert!(printed.contains("migrated"));
assert!(
!printed.contains("nodes:"),
"the sink should get a summary, not the YAML: {printed}"
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn ros2_json_flag_emits_a_structured_report_with_notes() {
let path = write_temp_ros2(
"json",
r#"<launch><node pkg="p" exec="e" name="n"/></launch>"#,
);
let mut out = Vec::new();
let report = run_from_ros2(
&mut out,
&FromRos2Args {
input: path,
output: None,
json: true,
},
)
.unwrap();
let printed = String::from_utf8(out).unwrap();
let value: serde_json::Value = serde_json::from_str(&printed).unwrap();
assert_eq!(value["notes"].as_array().map(Vec::len), Some(1));
assert_eq!(report.notes.len(), 1);
}
#[test]
fn ros2_missing_input_is_a_ros2_migrate_error() {
let mut out = Vec::new();
let err = run_from_ros2(
&mut out,
&FromRos2Args {
input: std::env::temp_dir().join("astrs-cli-migrate-ros2-does-not-exist.xml"),
output: None,
json: false,
},
)
.unwrap_err();
assert!(matches!(err, CliError::Ros2Migrate(_)));
assert_eq!(
err.exit_code(),
1,
"a missing file is an ordinary failure, not `this feature is unavailable`"
);
}
#[test]
fn ros2_malformed_xml_is_a_ros2_migrate_error() {
let path = write_temp_ros2("malformed", "<launch><node>");
let mut out = Vec::new();
let err = run_from_ros2(
&mut out,
&FromRos2Args {
input: path,
output: None,
json: false,
},
)
.unwrap_err();
assert!(matches!(err, CliError::Ros2Migrate(_)));
}
#[test]
fn ros2_dispatches_python_launch_files_by_extension() {
let dir = std::env::temp_dir().join(format!(
"astrs-cli-migrate-ros2-test-{}-python",
std::process::id()
));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("robot.launch.py");
std::fs::write(&path, "Node(name='n')").unwrap();
let mut out = Vec::new();
let report = run_from_ros2(
&mut out,
&FromRos2Args {
input: path,
output: None,
json: false,
},
)
.unwrap();
assert!(report.yaml.starts_with("# Skeleton scaffold"));
let _ = std::fs::remove_dir_all(&dir);
}
}