1use std::io::Write;
7use std::path::PathBuf;
8
9use serde::Serialize;
10
11use crate::error::CliError;
12
13#[derive(Debug, Clone)]
15pub struct FromDoraArgs {
16 pub input: PathBuf,
18 pub output: Option<PathBuf>,
20 pub json: bool,
24}
25
26#[derive(Debug, Clone)]
28pub struct FromRos2Args {
29 pub input: PathBuf,
32 pub output: Option<PathBuf>,
34 pub json: bool,
38}
39
40#[derive(Debug, Clone, Serialize)]
42pub struct FromDoraReport {
43 pub yaml: String,
46 pub notes: Vec<astrs_migrate::MigrationNote>,
48 pub written_to: Option<PathBuf>,
50}
51
52impl FromDoraReport {
53 #[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#[derive(Debug, Clone, Serialize)]
76pub struct FromRos2Report {
77 pub yaml: String,
80 pub notes: Vec<astrs_migrate::Ros2MigrationNote>,
82 pub written_to: Option<PathBuf>,
84}
85
86impl FromRos2Report {
87 #[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
116pub 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
173pub 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 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}