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
use std::env;
use std::path::{Path, PathBuf};

pub struct Args {
    all: Vec<String>,
    target: Option<String>,
    manifest_path: Option<PathBuf>,
    verbosity: Option<Verbosity>,
}

#[derive(Debug, Eq, PartialEq)]
pub enum Verbosity {
    Quiet,
    Verbose,
}

impl Args {
    /// Create args explicitly, with other args passed unchanged to cargo invocation
    pub fn new<T, P, A, S>(
        target: Option<T>,
        manifest_path: Option<P>,
        verbosity: Option<Verbosity>,
        other_args: A,
    ) -> Result<Self, String>
    where
        T: Into<String> + Clone,
        P: AsRef<Path>,
        A: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        let other_args = other_args
            .into_iter()
            .map(|a| a.as_ref().to_string())
            .collect::<Vec<_>>();

        // check for duplicates of the explicit args
        let explicit_args = ["--target", "--manifest-path", "--verbose", "--quiet"];
        let duplicates = other_args
            .iter()
            .filter(|a| {
                explicit_args
                    .iter()
                    .any(|ea| a == ea || a.starts_with(&format!("{}=", ea)))
            })
            .collect::<Vec<_>>();
        if !duplicates.is_empty() {
            return Err(format!(
                "The following args should be passed explicitly: {:?}",
                duplicates
            ));
        }

        // add the explicit args to `all` which will be passed on to `cargo`
        let mut all = other_args;
        if let Some(target) = target.clone() {
            all.push(format!("--target={}", target.into()))
        }
        if let Some(ref manifest_path) = manifest_path {
            all.push(format!(
                "--manifest-path={}",
                manifest_path.as_ref().to_string_lossy()
            ))
        }
        if let Some(ref verbosity) = verbosity {
            match verbosity {
                Verbosity::Verbose => all.push("--verbose".into()),
                Verbosity::Quiet => all.push("--quiet".into()),
            }
        }

        Ok(Args {
            all,
            target: target.map(Into::into),
            manifest_path: manifest_path.map(|p| p.as_ref().into()),
            verbosity,
        })
    }

    /// Parse raw args from command line
    pub fn from_raw<A, S>(all: A) -> Result<Self, String>
    where
        A: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        let all = all
            .into_iter()
            .map(|a| a.as_ref().to_string())
            .collect::<Vec<_>>();

        let mut target: Option<String> = None;
        let mut manifest_path = None;
        let mut verbosity = None;
        {
            let mut args = all.iter();
            while let Some(arg) = args.next() {
                if arg == "--target" {
                    target = args.next().map(|s| s.to_owned());
                } else if arg.starts_with("--target=") {
                    target = arg.splitn(2, '=').nth(1).map(|s| s.to_owned());
                }
                if arg == "--manifest-path" {
                    manifest_path = args.next().map(|s| s.to_owned());
                } else if arg.starts_with("--manifest-path=") {
                    manifest_path = arg.splitn(2, '=').nth(1).map(|s| s.to_owned());
                }
                if arg == "--verbose" || arg == "-v" || arg == "-vv" {
                    if let Some(Verbosity::Quiet) = verbosity {
                        return Err("cannot set both --verbose and --quiet".into());
                    }
                    verbosity = Some(Verbosity::Verbose)
                }
                if arg == "--quiet" || arg == "-q" {
                    if let Some(Verbosity::Verbose) = verbosity {
                        return Err("cannot set both --verbose and --quiet".into());
                    }
                    verbosity = Some(Verbosity::Quiet)
                }
            }
        }

        Ok(Args {
            all,
            target: target.map(Into::into),
            manifest_path: manifest_path.map(Into::into),
            verbosity,
        })
    }

    pub fn all(&self) -> &[String] {
        &self.all
    }

    pub fn target(&self) -> Option<&str> {
        self.target.as_ref().map(|s| &**s)
    }

    pub fn manifest_path(&self) -> Option<&Path> {
        self.manifest_path.as_ref().map(|s| &**s)
    }

    pub fn quiet(&self) -> bool {
        self.verbosity == Some(Verbosity::Quiet)
    }

    pub fn verbose(&self) -> bool {
        self.verbosity == Some(Verbosity::Verbose)
    }
}

pub fn args(command_name: &str) -> Result<(Command, Args), String> {
    let mut args = env::args().skip(1);
    if args.next() != Some("x".to_string() + command_name) {
        Err(format!(
            "must be invoked as cargo subcommand: `cargo x{}`",
            command_name
        ))?;
    }
    let all = args.collect::<Vec<_>>();
    let command = match all.first().map(|s| s.as_str()) {
        Some("-h") | Some("--help") => Command::Help,
        Some("-v") | Some("--version") => Command::Version,
        _ => Command::Build,
    };

    let args = Args::from_raw(all)?;
    Ok((command, args))
}

#[derive(Clone, PartialEq)]
pub enum Command {
    Build,
    Help,
    Version,
}