tea_coding_tools/bash/
command.rs1use std::fs;
2use std::path::{Path, PathBuf};
3use std::time::Duration;
4
5use crate::{FileToolError, FileToolErrorCode};
6
7#[derive(Debug, Clone, PartialEq, Eq)]
9pub struct BashShell {
10 executable: PathBuf,
11 command_argument: String,
12}
13
14impl BashShell {
15 pub fn new(
21 executable: impl AsRef<Path>,
22 command_argument: impl Into<String>,
23 ) -> Result<Self, FileToolError> {
24 let executable = executable.as_ref();
25 let command_argument = command_argument.into();
26 if !executable.is_absolute()
27 || command_argument.is_empty()
28 || command_argument.len() > 32
29 || command_argument.chars().any(char::is_control)
30 {
31 return Err(FileToolError::new(FileToolErrorCode::InvalidArguments));
32 }
33 let executable = fs::canonicalize(executable)
34 .map_err(|_| FileToolError::new(FileToolErrorCode::NotFound))?;
35 if !executable.is_file() {
36 return Err(FileToolError::new(FileToolErrorCode::NotAFile));
37 }
38 Ok(Self {
39 executable,
40 command_argument,
41 })
42 }
43
44 pub(crate) fn executable(&self) -> &Path {
45 &self.executable
46 }
47
48 pub(crate) fn command_argument(&self) -> &str {
49 &self.command_argument
50 }
51}
52
53#[derive(Debug, Clone, PartialEq, Eq)]
55pub struct BashOutputDirectory {
56 path: PathBuf,
57}
58
59impl BashOutputDirectory {
60 pub fn new(path: impl AsRef<Path>) -> Result<Self, FileToolError> {
66 let path =
67 fs::canonicalize(path).map_err(|_| FileToolError::new(FileToolErrorCode::NotFound))?;
68 if !path.is_dir() {
69 return Err(FileToolError::new(FileToolErrorCode::NotAFile));
70 }
71 Ok(Self { path })
72 }
73
74 pub(crate) fn path(&self) -> &Path {
75 &self.path
76 }
77}
78
79#[derive(Debug, Clone)]
81pub struct BashConfig {
82 shell: BashShell,
83 output_directory: BashOutputDirectory,
84 timeout: Duration,
85}
86
87impl BashConfig {
88 pub fn new(
94 shell: BashShell,
95 output_directory: BashOutputDirectory,
96 timeout: Duration,
97 ) -> Result<Self, FileToolError> {
98 if timeout.is_zero() || timeout > Duration::from_mins(2) {
99 return Err(FileToolError::new(FileToolErrorCode::InvalidArguments));
100 }
101 Ok(Self {
102 shell,
103 output_directory,
104 timeout,
105 })
106 }
107
108 pub(crate) const fn shell(&self) -> &BashShell {
109 &self.shell
110 }
111
112 pub(crate) const fn output_directory(&self) -> &BashOutputDirectory {
113 &self.output_directory
114 }
115
116 pub(crate) const fn timeout(&self) -> Duration {
117 self.timeout
118 }
119}