use std::fmt;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Arg {
Text(String),
Glob(String),
MixedGlob {
text: String,
active_metacharacters: Vec<usize>,
},
}
impl Arg {
pub fn as_str(&self) -> &str {
match self {
Arg::Text(v) | Arg::Glob(v) => v,
Arg::MixedGlob { text, .. } => text,
}
}
pub fn into_text(self) -> String {
match self {
Arg::Text(v) | Arg::Glob(v) => v,
Arg::MixedGlob { text, .. } => text,
}
}
pub fn parse<T: std::str::FromStr>(&self) -> Result<T, T::Err> {
self.as_str().parse()
}
pub fn as_owned_text(&self) -> String {
self.as_str().to_string()
}
pub(crate) fn from_glob_parts(text: String, active_metacharacters: Vec<usize>) -> Self {
if !active_metacharacters.iter().any(|index| {
text.chars()
.nth(*index)
.is_some_and(|ch| matches!(ch, '*' | '?' | '[' | ']'))
}) {
return Self::Text(text);
}
let metacharacter_count = text
.chars()
.filter(|ch| matches!(ch, '*' | '?' | '[' | ']'))
.count();
if metacharacter_count == active_metacharacters.len() {
Self::Glob(text)
} else {
Self::MixedGlob {
text,
active_metacharacters,
}
}
}
pub(crate) fn active_metacharacters(&self) -> Vec<usize> {
match self {
Self::Text(_) => Vec::new(),
Self::Glob(text) => text
.chars()
.enumerate()
.filter_map(|(index, ch)| matches!(ch, '*' | '?' | '[' | ']').then_some(index))
.collect(),
Self::MixedGlob {
active_metacharacters,
..
} => active_metacharacters.clone(),
}
}
}
impl From<String> for Arg {
fn from(value: String) -> Self {
Self::Text(value)
}
}
impl From<&str> for Arg {
fn from(value: &str) -> Self {
Self::Text(value.to_string())
}
}
impl PartialEq<String> for Arg {
fn eq(&self, other: &String) -> bool {
self.as_str() == other
}
}
impl PartialEq<Arg> for String {
fn eq(&self, other: &Arg) -> bool {
self == other.as_str()
}
}
impl PartialEq<&str> for Arg {
fn eq(&self, other: &&str) -> bool {
self.as_str() == *other
}
}
impl fmt::Display for Arg {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Redirect {
pub source_fd: usize,
pub op: String,
pub target: Arg,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Command {
pub args: Vec<Arg>,
pub redirects: Vec<Redirect>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Pipeline {
pub commands: Vec<Command>,
pub negate: bool,
pub pipe_fail: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ScriptNode {
Pipeline(Pipeline),
Seq(Box<ScriptNode>, SeqOp, Box<ScriptNode>),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SeqOp {
Semicolon,
Ampersand,
Or,
And,
}
impl fmt::Display for SeqOp {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let repr = match self {
SeqOp::Semicolon => ";",
SeqOp::Ampersand => "&",
SeqOp::Or => "||",
SeqOp::And => "&&",
};
write!(f, "{repr}")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn redirect_repr() {
let r = Redirect {
source_fd: 1,
op: ">".into(),
target: "x".into(),
};
assert_eq!(r.source_fd, 1);
assert_eq!(r.target, "x");
}
}