Skip to content

Commit ca49e4c

Browse files
authored
feat: Add CommandInput (#252)
Add the new type CommandInput. This type supports serde and clap (using `FromStr`) and is supposed to be used where users need to specify commands which are to be executed. There are 3 ways to define commands (here TOML is used): - as one string: `command = "echo test"` - as command and args as string array: `command = {command = "echo", args = ["test1", "test2"] }` - additionally specify error treatment: `command = {command = "echo", args = ["test1", "test2"], on_failure = "ignore" }` In the first example the full command and the args are split using `shell_words` which requires special escaping or quoting when spaces are contained. In the other examples every string is taken literally as given (but TOML escapes may apply when parsing TOML). This PR only adds the new type, using it on existing commands will be a breaking change.
1 parent 8ef75e6 commit ca49e4c

File tree

6 files changed

+323
-4
lines changed

6 files changed

+323
-4
lines changed

crates/core/Cargo.toml

+3-2
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ edition = "2021"
3232
default = []
3333
cli = ["merge", "clap"]
3434
merge = ["dep:merge"]
35-
clap = ["dep:clap", "dep:shell-words"]
35+
clap = ["dep:clap"]
3636
webdav = ["dep:dav-server", "dep:futures"]
3737

3838
[package.metadata.docs.rs]
@@ -88,7 +88,6 @@ dirs = "5.0.1"
8888
# cli support
8989
clap = { version = "4.5.16", optional = true, features = ["derive", "env", "wrap_help"] }
9090
merge = { version = "0.1.0", optional = true }
91-
shell-words = { version = "1.1.0", optional = true }
9291

9392
# vfs support
9493
dav-server = { version = "0.7.0", default-features = false, optional = true }
@@ -107,6 +106,7 @@ gethostname = "0.5.0"
107106
humantime = "2.1.0"
108107
itertools = "0.13.0"
109108
quick_cache = "0.6.2"
109+
shell-words = "1.1.0"
110110
strum = { version = "0.26.3", features = ["derive"] }
111111
zstd = "0.13.2"
112112

@@ -140,6 +140,7 @@ rustup-toolchain = "0.1.7"
140140
simplelog = "0.12.2"
141141
tar = "0.4.41"
142142
tempfile = { workspace = true }
143+
toml = "0.8.19"
143144

144145
[lints]
145146
workspace = true

crates/core/src/error.rs

+7
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ use std::{
1111
num::{ParseIntError, TryFromIntError},
1212
ops::RangeInclusive,
1313
path::{PathBuf, StripPrefixError},
14+
process::ExitStatus,
1415
str::Utf8Error,
1516
};
1617

@@ -220,6 +221,8 @@ pub enum CommandErrorKind {
220221
NotAllowedWithAppendOnly(String),
221222
/// Specify one of the keep-* options for forget! Please use keep-none to keep no snapshot.
222223
NoKeepOption,
224+
/// {0:?}
225+
FromParseError(#[from] shell_words::ParseError),
223226
}
224227

225228
/// [`CryptoErrorKind`] describes the errors that can happen while dealing with Cryptographic functions
@@ -285,6 +288,10 @@ pub enum RepositoryErrorKind {
285288
PasswordCommandExecutionFailed,
286289
/// error reading password from command
287290
ReadingPasswordFromCommandFailed,
291+
/// running command {0}:{1} was not successful: {2}
292+
CommandExecutionFailed(String, String, std::io::Error),
293+
/// running command {0}:{1} returned status: {2}
294+
CommandErrorStatus(String, String, ExitStatus),
288295
/// error listing the repo config file
289296
ListingRepositoryConfigFileFailed,
290297
/// error listing the repo keys

crates/core/src/lib.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,7 @@ pub use crate::{
149149
PathList, SnapshotGroup, SnapshotGroupCriterion, SnapshotOptions, StringList,
150150
},
151151
repository::{
152-
FullIndex, IndexedFull, IndexedIds, IndexedStatus, IndexedTree, OpenStatus, Repository,
153-
RepositoryOptions,
152+
CommandInput, FullIndex, IndexedFull, IndexedIds, IndexedStatus, IndexedTree, OpenStatus,
153+
Repository, RepositoryOptions,
154154
},
155155
};

crates/core/src/repository.rs

+3
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
// Note: we need a fully qualified Vec here for clap, see https://github.com/clap-rs/clap/issues/4481
22
#![allow(unused_qualifications)]
33

4+
mod command_input;
45
mod warm_up;
56

7+
pub use command_input::CommandInput;
8+
69
use std::{
710
cmp::Ordering,
811
fs::File,
+214
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,214 @@
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+
}

crates/core/tests/command_input.rs

+94
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
use std::fs::File;
2+
3+
use anyhow::Result;
4+
use rustic_core::CommandInput;
5+
use serde::{Deserialize, Serialize};
6+
use tempfile::tempdir;
7+
8+
#[test]
9+
fn from_str() -> Result<()> {
10+
let cmd: CommandInput = "echo test".parse()?;
11+
assert_eq!(cmd.command(), "echo");
12+
assert_eq!(cmd.args(), ["test"]);
13+
14+
let cmd: CommandInput = r#"echo "test test" test"#.parse()?;
15+
assert_eq!(cmd.command(), "echo");
16+
assert_eq!(cmd.args(), ["test test", "test"]);
17+
Ok(())
18+
}
19+
20+
#[cfg(not(windows))]
21+
#[test]
22+
fn from_str_failed() {
23+
let failed_cmd: std::result::Result<CommandInput, _> = "echo \"test test".parse();
24+
assert!(failed_cmd.is_err());
25+
}
26+
27+
#[test]
28+
fn toml() -> Result<()> {
29+
#[derive(Deserialize, Serialize)]
30+
struct Test {
31+
command1: CommandInput,
32+
command2: CommandInput,
33+
command3: CommandInput,
34+
command4: CommandInput,
35+
}
36+
37+
let test = toml::from_str::<Test>(
38+
r#"
39+
command1 = "echo test"
40+
command2 = {command = "echo", args = ["test test"], on-failure = "error"}
41+
command3 = {command = "echo", args = ["test test", "test"]}
42+
command4 = {command = "echo", args = ["test test", "test"], on-failure = "warn"}
43+
"#,
44+
)?;
45+
46+
assert_eq!(test.command1.command(), "echo");
47+
assert_eq!(test.command1.args(), ["test"]);
48+
assert_eq!(test.command2.command(), "echo");
49+
assert_eq!(test.command2.args(), ["test test"]);
50+
assert_eq!(test.command3.command(), "echo");
51+
assert_eq!(test.command3.args(), ["test test", "test"]);
52+
53+
let test_ser = toml::to_string(&test)?;
54+
assert_eq!(
55+
test_ser,
56+
r#"command1 = "echo test"
57+
command2 = "echo 'test test'"
58+
command3 = "echo 'test test' test"
59+
60+
[command4]
61+
command = "echo"
62+
args = ["test test", "test"]
63+
on-failure = "warn"
64+
"#
65+
);
66+
Ok(())
67+
}
68+
69+
#[test]
70+
fn run_empty() -> Result<()> {
71+
// empty command
72+
let command: CommandInput = "".parse()?;
73+
dbg!(&command);
74+
assert!(!command.is_set());
75+
command.run("test", "empty")?;
76+
Ok(())
77+
}
78+
79+
#[cfg(not(windows))]
80+
#[test]
81+
fn run_deletey() -> Result<()> {
82+
// create a tmp file which will be removed by
83+
let dir = tempdir()?;
84+
let filename = dir.path().join("file");
85+
let _ = File::create(&filename)?;
86+
assert!(filename.exists());
87+
88+
let command: CommandInput = format!("rm {}", filename.to_str().unwrap()).parse()?;
89+
assert!(command.is_set());
90+
command.run("test", "test-call")?;
91+
assert!(!filename.exists());
92+
93+
Ok(())
94+
}

0 commit comments

Comments
 (0)