ros_remove 0.1.5

The Purpose of ros_remove is to provide the `cargo ros_remove` command to remove dependencies from `Cargo.toml` and the `package.xml`
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
//! A cargo subcommand for removing dependencies from both `Cargo.toml` and ROS `package.xml` files.
//!
//! This tool helps manage dependencies for ROS 2 packages written in Rust by
//! synchronizing dependencies between `Cargo.toml` and `package.xml` manifest files.
//! It removes specified dependencies from the appropriate sections in both files.
use case_clause::case;
use clap::{Arg, ArgAction, ArgGroup, ArgMatches, Command as ClapCommand};
use quick_xml::{de::from_str, se::Serializer};
use serde::{Deserialize, Serialize};
use std::{
    env,
    fmt::{self, Display},
    fs,
    io::ErrorKind,
    path::{Path, PathBuf},
    rc::Rc,
};
use toml_edit::{DocumentMut, Item};

struct InputString(Rc<str>);
struct PrefixString(Rc<str>);
struct SuffixString(Rc<str>);

/// Helper Struct to determine, in which kind of Package Group the Package has to be deleted
pub struct StringHelper(PrefixString, InputString, SuffixString);
impl StringHelper {
    /// main constructor for the `StringHelper`
    /// # example
    /// ```rust
    /// use ros_remove::StringHelper;
    /// assert_eq!(
    ///     StringHelper::new("prefix ","input ","suffix").to_string(),
    ///     "prefix input suffix"
    ///     );
    /// ```
    #[must_use]
    pub fn new(prefix: &str, input: &str, suffix: &str) -> Self {
        Self(
            PrefixString(prefix.into()),
            InputString(input.into()),
            SuffixString(suffix.into()),
        )
    }

    ///wrapper function for `StringHelper` for dependency options
    /// # example:
    /// ```rust
    /// use ros_remove::StringHelper;
    /// assert_eq!(
    ///     StringHelper::dependency("Cargo.toml"),
    ///     "Dependency will only be removed from Cargo.toml file."
    ///     );
    /// ```
    #[must_use]
    pub fn dependency(input: &str) -> String {
        Self::new("Dependency will only be removed from ", input, " file.").to_string()
    }

    ///wrapper function for `StringHelper` for section parts
    /// # example:
    /// ```rust
    /// use ros_remove::StringHelper;
    /// assert_eq!(
    ///     StringHelper::section("build"),"Remove from build-dependencies"
    ///     );
    /// ```
    #[must_use]
    pub fn section(input: &str) -> String {
        Self::new("Remove from ", input, "-dependencies").to_string()
    }
}

impl Display for StringHelper {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}{}{}", self.0.0, self.1.0, self.2.0)
    }
}

/// Converts command-line arguments into `clap::ArgMatches`.
///
/// This function defines the command-line interface for the `ros_remove` tool,
/// including arguments for specifying dependencies and various dependency types.
#[must_use]
pub fn env_to_matches(env_args: Vec<String>) -> ArgMatches {
    ClapCommand::new("ros_remove")
        .about("removes dependencies from a Cargo.toml and package.xml manifest file")
        .arg(
            Arg::new("dependency")
                .value_name("DEP_ID")
                .help(
                    [
                        "Reference to a package that should be removed as a dependency.",
                        "You can reference a package by:",
                        "- `<name>`, like `cargo ros-remove serde` (latest version will be used)",
                    ]
                    .join("\n"),
                )
                .required(true),
        )
        .arg(
            Arg::new("color")
                .help("Coloring\n \n")
                .long("color")
                .value_name("WHEN")
                .value_parser(["auto", "always", "never"]),
        )
        .arg(
            Arg::new("no_cargo_toml")
                .action(ArgAction::SetTrue)
                .help(StringHelper::dependency("package.xml"))
                .long("no-cargo-toml")
                .required(false),
        )
        .arg(
            Arg::new("no_package_xml")
                .action(ArgAction::SetTrue)
                .help(StringHelper::dependency("Cargo.toml"))
                .long("no-package-xml")
                .required(false),
        )
        .group(ArgGroup::new("section").multiple(true))
        .next_help_heading("Section")
        .args([
            Arg::new("build")
                .action(ArgAction::SetTrue)
                .help(StringHelper::section("build"))
                .long("build"),
            Arg::new("dev")
                .action(ArgAction::SetTrue)
                .help(StringHelper::section("dev"))
                .long("dev"),
        ])
        .get_matches_from(case!(
            env_args.iter().any(|arg| arg == "ros-remove") => env_args.iter().take(1).chain(env_args.iter().skip(2)).cloned().collect::<Vec<String>>(),
            true => env_args
        ))
}

fn remove_from_cargo_toml_helper(
    mut doc: DocumentMut,
    cargo_toml_path: &Path,
    dependency: &str,
    sections: Vec<&str>,
) -> Result<(), ErrorKind> {
    let mut removed = false;
    for section in sections {
        if let Some(item) = doc
            .get_mut(section)
            .and_then(Item::as_table_mut)
            .and_then(|deps| deps.remove(dependency))
        {
            println!("Removed `{dependency}` {item} from `{section}` in `Cargo.toml`");
            removed = true;
        }
    }
    if removed {
        fs::write(cargo_toml_path, doc.to_string()).map_err(|err| err.kind())?;
    }
    Ok(())
}

/// Removes a dependency from the `Cargo.toml` file.
///
/// # Arguments
/// * `cargo_toml_path` - Path to the `Cargo.toml` file.
/// * `dependency` - Name of the dependency to remove.
/// * `sections` - Sections to remove the dependency from (`dependencies`, `build-dependencies`, `dev-dependencies`).
///
/// # Returns
/// `Ok(())` if the dependency was removed successfully, or an error if the operation failed.
/// # Errors
/// Returns `std::io::ErrorKind` if something failes
pub fn remove_from_cargo_toml(
    cargo_toml_path: &Path,
    dependency: &str,
    sections: Vec<&str>,
) -> Result<(), ErrorKind> {
    remove_from_cargo_toml_helper(
        fs::read_to_string(cargo_toml_path)
            .map_err(|err| err.kind())?
            .parse::<DocumentMut>()
            .map_err(|_| ErrorKind::InvalidData)?,
        cargo_toml_path,
        dependency,
        sections,
    )
}

/// Represents the structure of a ROS `package.xml` file.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename = "package")]
pub struct PackageXml {
    ///format
    #[serde(rename = "@format")]
    pub format: String,

    ///name
    pub name: String,

    ///version
    pub version: String,

    ///description
    pub description: String,

    /// Using Vec for maintainers and licenses is standard for ROS packages
    pub maintainer: Vec<Maintainer>,

    ///license
    pub license: Vec<String>,

    ///dependencies
    #[serde(rename = "depend", default, skip_serializing_if = "Option::is_none")]
    pub depends: Option<Vec<String>>,
    #[serde(
        rename = "build_depend",
        default,
        skip_serializing_if = "Option::is_none"
    )]

    ///build dependencies
    pub build_depends: Option<Vec<String>>,
    #[serde(
        rename = "exec_depend",
        default,
        skip_serializing_if = "Option::is_none"
    )]

    ///runtime dependencies
    pub exec_depends: Option<Vec<String>>,

    ///text dependencies
    #[serde(
        rename = "test_depend",
        default,
        skip_serializing_if = "Option::is_none"
    )]
    pub test_depends: Option<Vec<String>>,

    /// documentation dependencies
    #[serde(
        rename = "doc_depend",
        default,
        skip_serializing_if = "Option::is_none"
    )]
    pub doc_depends: Option<Vec<String>>,

    ///```xml
    ///<export>value</export>
    ///```
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub export: Option<Export>,
}
impl PackageXml {
    /// creates a new Instance of `PackageXml` based on a given Path
    /// # Arguments
    /// * `path` - Path to the `package.xml` file.
    /// # Returns
    /// `Ok(())` if the path exists and can be converted to a deserialized rust struct
    /// # Errors
    /// `std::io::ErrorKind` if something failes
    fn new(path: &Path) -> Result<Self, ErrorKind> {
        fs::read_to_string(path)
            .map_err(|err| err.kind())
            .map(|string| from_str(&string).map_err(|_| ErrorKind::InvalidData))?
    }
}

///Represents the Package.xml maintainer type
#[derive(Debug, Serialize, Deserialize)]
pub struct Maintainer {
    ///email
    #[serde(rename = "@email")]
    pub email: String,
    ///name
    #[serde(rename = "$value")] // Captures the name between the tags
    pub name: String,
}

///Struct for Package.xml export type
#[derive(Debug, Serialize, Deserialize)]
pub struct Export {
    /// This allows for other export tags if they exist
    pub build_type: String,
}

fn process_list(list: &mut Option<Vec<String>>, dependency: &str) -> bool {
    if let Some(deps) = list {
        let initial_count = deps.len();
        deps.retain(|dep| dep != dependency);
        deps.len() != initial_count
    } else {
        false
    }
}

/// Removes a dependency from the `package.xml` file.
///
/// # Arguments
/// * `package_xml_path` - Path to the `package.xml` file.
/// * `dependency` - Name of the dependency to remove.
///
/// # Returns
/// `Ok(())` if the dependency was removed successfully, or an error if the operation failed.
/// # Errors
/// returns `std::io::ErrorKind` Errors
pub fn remove_from_package_xml(package_xml_path: &Path, dependency: &str) -> Result<(), ErrorKind> {
    let mut package: PackageXml = PackageXml::new(package_xml_path)?;

    if [
        &mut package.depends,
        &mut package.build_depends,
        &mut package.exec_depends,
        &mut package.doc_depends,
        &mut package.test_depends,
    ]
    .iter_mut()
    .any(|field| process_list(field, dependency))
    {
        let mut buffer = String::new();
        let mut ser = Serializer::new(&mut buffer);
        ser.indent(' ', 2);
        package
            .serialize(ser)
            .map_err(|_| ErrorKind::InvalidInput)?;
        fs::write(package_xml_path, buffer).map_err(|err| err.kind())?;
        println!("Removed `{dependency}` from `package.xml` (formatting preserved)");
    }

    Ok(())
}

fn remove_dependency_from_file(
    file_name: &str,
    dependency: &str,
    sections: Vec<&str>,
) -> Result<(), ErrorKind> {
    // Get the current directory to construct absolute path

    let file_path: PathBuf = env::current_dir()
        .map_err(|err| err.kind())?
        .join(file_name);

    if file_path.exists() || file_path.is_file() {
        match file_name {
            "Cargo.toml" => {
                remove_from_cargo_toml(&file_path, dependency, sections)?;
            }
            "package.xml" => {
                remove_from_package_xml(&file_path, dependency)?;
            }
            _ => {
                eprintln!("Warning: Unsupported file type: {file_name}");
                return Err(ErrorKind::InvalidFilename);
            }
        }
        Ok(())
    } else {
        eprintln!("Warning: `{file_name}` not found in the current directory");
        Err(ErrorKind::NotFound)
    }
}

/// Removes a dependency from both `Cargo.toml` and `package.xml` based on the provided arguments.
///
/// # Arguments
/// * `matches` - Command-line arguments parsed by `clap`.
///
/// # Returns
/// `Ok(())` if the operation succeeded, or an error if it failed.
/// # Errors
/// `ErrorKind` if the operation failed.
pub fn remove_dependency(matches: &ArgMatches) -> Result<(), ErrorKind> {
    let dependency: &String = matches.get_one::<String>("dependency").ok_or_else(|| {
        eprintln!("Dependency name is required");
        ErrorKind::InvalidInput
    })?;

    let mut sections: Vec<&str> = Vec::new();
    if !matches.get_flag("build") && !matches.get_flag("dev") {
        sections.push("dependencies");
    } else {
        for (key, val) in [("build", "build-dependencies"), ("dev", "dev-dependencies")] {
            if matches.get_flag(key) {
                sections.push(val);
            }
        }
    }

    // Process Cargo.toml unless --no-cargo-toml is set
    for val in [
        ("no_cargo_toml", "Cargo.toml"),
        ("no_package_xml", "package.xml"),
    ]
    .iter()
    .filter(|key| !matches.get_flag(key.0))
    .map(|key| key.1)
    {
        remove_dependency_from_file(val, dependency, sections.clone())?;
    }

    Ok(())
}