|
| 1 | +use std::{ |
| 2 | + fmt::{Debug, Display}, |
| 3 | + process::{Command, ExitStatus}, |
| 4 | + str::FromStr, |
| 5 | +}; |
| 6 | + |
| 7 | +use log::{debug, error, trace, warn}; |
| 8 | +use serde::{Deserialize, Serialize, Serializer}; |
| 9 | +use serde_with::{serde_as, DisplayFromStr, PickFirst}; |
| 10 | + |
| 11 | +use crate::{ |
| 12 | + error::{RepositoryErrorKind, RusticErrorKind}, |
| 13 | + RusticError, RusticResult, |
| 14 | +}; |
| 15 | + |
| 16 | +/// A command to be called which can be given as CLI option as well as in config files |
| 17 | +/// `CommandInput` implements Serialize/Deserialize as well as FromStr. |
| 18 | +#[serde_as] |
| 19 | +#[derive(Debug, Default, Clone, PartialEq, Eq, Deserialize)] |
| 20 | +pub struct CommandInput( |
| 21 | + // Note: we use _CommandInput here which itself impls FromStr in order to use serde_as PickFirst for CommandInput. |
| 22 | + //#[serde( |
| 23 | + // serialize_with = "serialize_command", |
| 24 | + // deserialize_with = "deserialize_command" |
| 25 | + //)] |
| 26 | + #[serde_as(as = "PickFirst<(DisplayFromStr,_)>")] _CommandInput, |
| 27 | +); |
| 28 | + |
| 29 | +impl Serialize for CommandInput { |
| 30 | + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> |
| 31 | + where |
| 32 | + S: Serializer, |
| 33 | + { |
| 34 | + // if on_failure is default, we serialize to the short `Display` version, else we serialize the struct |
| 35 | + if self.0.on_failure == OnFailure::default() { |
| 36 | + serializer.serialize_str(&self.to_string()) |
| 37 | + } else { |
| 38 | + self.0.serialize(serializer) |
| 39 | + } |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +impl From<Vec<String>> for CommandInput { |
| 44 | + fn from(value: Vec<String>) -> Self { |
| 45 | + Self(value.into()) |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +impl From<CommandInput> for Vec<String> { |
| 50 | + fn from(value: CommandInput) -> Self { |
| 51 | + value.0.iter().cloned().collect() |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +impl CommandInput { |
| 56 | + /// Returns if a command is set |
| 57 | + #[must_use] |
| 58 | + pub fn is_set(&self) -> bool { |
| 59 | + !self.0.command.is_empty() |
| 60 | + } |
| 61 | + |
| 62 | + /// Returns the command |
| 63 | + #[must_use] |
| 64 | + pub fn command(&self) -> &str { |
| 65 | + &self.0.command |
| 66 | + } |
| 67 | + |
| 68 | + /// Returns the command args |
| 69 | + #[must_use] |
| 70 | + pub fn args(&self) -> &[String] { |
| 71 | + &self.0.args |
| 72 | + } |
| 73 | + |
| 74 | + /// Returns the error handling for the command |
| 75 | + #[must_use] |
| 76 | + pub fn on_failure(&self) -> OnFailure { |
| 77 | + self.0.on_failure |
| 78 | + } |
| 79 | + |
| 80 | + /// Runs the command if it is set |
| 81 | + /// |
| 82 | + /// # Errors |
| 83 | + /// |
| 84 | + /// `RusticError` if return status cannot be read |
| 85 | + pub fn run(&self, context: &str, what: &str) -> RusticResult<()> { |
| 86 | + if !self.is_set() { |
| 87 | + trace!("not calling command {context}:{what} - not set"); |
| 88 | + return Ok(()); |
| 89 | + } |
| 90 | + debug!("calling command {context}:{what}: {self:?}"); |
| 91 | + let status = Command::new(self.command()).args(self.args()).status(); |
| 92 | + self.on_failure().handle_status(status, context, what)?; |
| 93 | + Ok(()) |
| 94 | + } |
| 95 | +} |
| 96 | + |
| 97 | +impl FromStr for CommandInput { |
| 98 | + type Err = RusticError; |
| 99 | + fn from_str(s: &str) -> Result<Self, Self::Err> { |
| 100 | + Ok(Self(_CommandInput::from_str(s)?)) |
| 101 | + } |
| 102 | +} |
| 103 | + |
| 104 | +impl Display for CommandInput { |
| 105 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 106 | + Display::fmt(&self.0, f) |
| 107 | + } |
| 108 | +} |
| 109 | + |
| 110 | +#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 111 | +#[serde(default, rename_all = "kebab-case")] |
| 112 | +struct _CommandInput { |
| 113 | + command: String, |
| 114 | + args: Vec<String>, |
| 115 | + on_failure: OnFailure, |
| 116 | +} |
| 117 | + |
| 118 | +impl _CommandInput { |
| 119 | + fn iter(&self) -> impl Iterator<Item = &String> { |
| 120 | + std::iter::once(&self.command).chain(self.args.iter()) |
| 121 | + } |
| 122 | +} |
| 123 | + |
| 124 | +impl From<Vec<String>> for _CommandInput { |
| 125 | + fn from(mut value: Vec<String>) -> Self { |
| 126 | + if value.is_empty() { |
| 127 | + Self::default() |
| 128 | + } else { |
| 129 | + let command = value.remove(0); |
| 130 | + Self { |
| 131 | + command, |
| 132 | + args: value, |
| 133 | + ..Default::default() |
| 134 | + } |
| 135 | + } |
| 136 | + } |
| 137 | +} |
| 138 | + |
| 139 | +impl FromStr for _CommandInput { |
| 140 | + type Err = RusticError; |
| 141 | + fn from_str(s: &str) -> Result<Self, Self::Err> { |
| 142 | + Ok(split(s)?.into()) |
| 143 | + } |
| 144 | +} |
| 145 | + |
| 146 | +impl Display for _CommandInput { |
| 147 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 148 | + let s = shell_words::join(self.iter()); |
| 149 | + f.write_str(&s) |
| 150 | + } |
| 151 | +} |
| 152 | + |
| 153 | +/// Error handling for commands called as `CommandInput` |
| 154 | +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 155 | +#[serde(rename_all = "lowercase")] |
| 156 | +pub enum OnFailure { |
| 157 | + /// errors in command calling will result in rustic errors |
| 158 | + #[default] |
| 159 | + Error, |
| 160 | + /// errors in command calling will result in rustic warnings, but are otherwise ignored |
| 161 | + Warn, |
| 162 | + /// errors in command calling will be ignored |
| 163 | + Ignore, |
| 164 | +} |
| 165 | + |
| 166 | +impl OnFailure { |
| 167 | + fn eval<T>(self, res: RusticResult<T>) -> RusticResult<Option<T>> { |
| 168 | + match res { |
| 169 | + Err(err) => match self { |
| 170 | + Self::Error => { |
| 171 | + error!("{err}"); |
| 172 | + Err(err) |
| 173 | + } |
| 174 | + Self::Warn => { |
| 175 | + warn!("{err}"); |
| 176 | + Ok(None) |
| 177 | + } |
| 178 | + Self::Ignore => Ok(None), |
| 179 | + }, |
| 180 | + Ok(res) => Ok(Some(res)), |
| 181 | + } |
| 182 | + } |
| 183 | + |
| 184 | + /// Handle a status of a called command depending on the defined error handling |
| 185 | + pub fn handle_status( |
| 186 | + self, |
| 187 | + status: Result<ExitStatus, std::io::Error>, |
| 188 | + context: &str, |
| 189 | + what: &str, |
| 190 | + ) -> RusticResult<()> { |
| 191 | + let status = status.map_err(|err| { |
| 192 | + RepositoryErrorKind::CommandExecutionFailed(context.into(), what.into(), err).into() |
| 193 | + }); |
| 194 | + let Some(status) = self.eval(status)? else { |
| 195 | + return Ok(()); |
| 196 | + }; |
| 197 | + |
| 198 | + if !status.success() { |
| 199 | + let _: Option<()> = self.eval(Err(RepositoryErrorKind::CommandErrorStatus( |
| 200 | + context.into(), |
| 201 | + what.into(), |
| 202 | + status, |
| 203 | + ) |
| 204 | + .into()))?; |
| 205 | + } |
| 206 | + Ok(()) |
| 207 | + } |
| 208 | +} |
| 209 | + |
| 210 | +/// helper to split arguments |
| 211 | +// TODO: Maybe use special parser (winsplit?) for windows? |
| 212 | +fn split(s: &str) -> RusticResult<Vec<String>> { |
| 213 | + Ok(shell_words::split(s).map_err(|err| RusticErrorKind::Command(err.into()))?) |
| 214 | +} |
0 commit comments