ros_add 0.1.8

The Purpose of the Package is to provide the `cargo ros_add` command to add dependencies to `Cargo.toml` and the `package.xml`
Documentation
//! Main entry point for the `cargo ros-add` subcommand.
//!
//! This binary handles adding dependencies to both Cargo.toml and package.xml files
//! for ROS 2 packages written in Rust.
//!
use clap::ArgMatches;
use ros_add::{DependencyType, PackageName, PathDoc, XMLHelper, env_to_matches};
use std::{env, io::ErrorKind, path::Path, process::Command};

fn main() -> Result<(), ErrorKind> {
    let matches: ArgMatches = env_to_matches(env::args().collect::<Vec<_>>());

    let dependency: &str = matches.get_one::<String>("dependency").ok_or_else(|| {
        eprintln!(
            "Argument 'dependency' is required but missing. Check `env_to_matches` implementation."
        );
        ErrorKind::InvalidInput
    })?;

    let processed_dependency: PackageName = dependency.into();
    let dependency_type: DependencyType = matches.clone().into();

    // First try with cargo add
    if !(matches.get_flag("no_cargo_toml") || matches.get_flag("buildtool"))
        && Path::new("Cargo.toml").exists()
    {
        println!("Attempting to add '{dependency}' to Cargo.toml...");

        let mut cargo_add = Command::new("cargo");
        cargo_add.arg("add").arg(dependency);

        // Add --color if specified
        if let Some(color) = matches.get_one::<String>("color") {
            cargo_add.args(["--color", color]);
        }

        // Only add --build if the flag was explicitly given
        if matches.get_flag("build") || matches.get_flag("build-export") {
            cargo_add.arg("--build");
        }

        PathDoc::new("Cargo.toml", dependency_type)
            .map_or_else(
                |dings| {
                    eprintln!("{dings}");
                    Err(dings)
                },
                |ok| ok.add_dependency_to_cargo_toml(&processed_dependency.clone()),
            )
            .unwrap_or_else(|dings| println!("{dings}"));
    }
    if !matches.get_flag("no_package_xml") {
        println!(
            "Attempting to add '{}' to package.xml...",
            processed_dependency.name.clone()
        );
        // First add to package.xml
        XMLHelper::new("package.xml", dependency_type)
            .map(|ok| ok.add_dependency_to_package_xml(&processed_dependency))??;
    }

    Ok(())
}