Repository navigation
Expand file tree
/
Copy pathcommand.rs
More file actions
210 lines (175 loc) · 6.35 KB
/
Copy pathcommand.rs
File metadata and controls
210 lines (175 loc) · 6.35 KB
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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
//! Command parsing for the policy engine.
use crate::error::PolicyError;
/// A properly parsed command with separated program and arguments.
#[derive(Debug, Clone)]
pub struct ParsedCommand {
/// The program/executable name.
pub program: String,
/// The base name of the program (without path).
pub program_basename: String,
/// All arguments (properly parsed from shell).
pub args: Vec<String>,
/// Raw command string (for pattern matching fallback).
pub raw: String,
/// Whether the command involves piping.
pub has_pipe: bool,
/// Whether the command has shell operators.
pub has_shell_operators: bool,
/// Detected subcommands (for multi-command strings).
pub subcommands: Vec<ParsedCommand>,
}
impl ParsedCommand {
/// Parse a command from string slice arguments.
pub fn from_args(args: &[String]) -> Result<Self, PolicyError> {
if args.is_empty() {
return Err(PolicyError::InvalidCommand("empty command".to_string()));
}
let raw = args.join(" ");
let program = args[0].clone();
let program_basename = std::path::Path::new(&program)
.file_name()
.and_then(|s| s.to_str())
.unwrap_or(&program)
.to_string();
let has_pipe = raw.contains('|');
let has_shell_operators = raw.contains('|')
|| raw.contains(';')
|| raw.contains("&&")
|| raw.contains("||")
|| raw.contains('`')
|| raw.contains("$(");
let mut subcommands = Vec::new();
// Parse subcommands if shell operators detected
if has_shell_operators {
subcommands = Self::parse_subcommands(&raw)?;
}
Ok(Self {
program,
program_basename,
args: args[1..].to_vec(),
raw,
has_pipe,
has_shell_operators,
subcommands,
})
}
/// Parse a command from a raw shell string.
pub fn from_shell_string(cmd: &str) -> Result<Self, PolicyError> {
let trimmed = cmd.trim();
if trimmed.is_empty() {
return Err(PolicyError::InvalidCommand("empty command".to_string()));
}
// Use shlex for proper shell parsing
let parts = match shlex::split(trimmed) {
Some(parts) if !parts.is_empty() => parts,
_ => {
// Fallback to whitespace splitting if shlex fails
trimmed.split_whitespace().map(String::from).collect()
}
};
if parts.is_empty() {
return Err(PolicyError::InvalidCommand(
"no executable in command".to_string(),
));
}
Self::from_args(&parts)
}
/// Parse subcommands from a string with shell operators.
fn parse_subcommands(raw: &str) -> Result<Vec<ParsedCommand>, PolicyError> {
let mut commands = Vec::new();
// Split by common shell operators
let separators = [";", "&&", "||", "|"];
for sep in separators {
let parts: Vec<&str> = raw.split(sep).collect();
if parts.len() > 1 {
for part in parts {
let trimmed = part.trim();
if !trimmed.is_empty() {
// Try to parse each subcommand
if let Ok(parsed) = Self::from_shell_string(trimmed) {
commands.push(parsed);
}
}
}
break;
}
}
Ok(commands)
}
/// Check if an argument is present (exact match).
pub fn has_arg(&self, arg: &str) -> bool {
self.args.iter().any(|a| a == arg)
}
/// Check if any argument starts with a prefix.
pub fn has_arg_starting_with(&self, prefix: &str) -> bool {
self.args.iter().any(|a| a.starts_with(prefix))
}
/// Check if any argument contains a substring.
pub fn has_arg_containing(&self, substr: &str) -> bool {
self.args.iter().any(|a| a.contains(substr))
}
/// Check if a flag is present (handles -x, --xxx, -xyz formats).
pub fn has_flag(&self, short: Option<char>, long: Option<&str>) -> bool {
for arg in &self.args {
// Check long flag
if let Some(l) = long
&& (arg == &format!("--{l}") || arg.starts_with(&format!("--{l}=")))
{
return true;
}
// Check short flag
if let Some(s) = short {
// Exact short flag: -x
if arg == &format!("-{s}") {
return true;
}
// Combined short flags: -xyz (contains -x)
if arg.starts_with('-')
&& !arg.starts_with("--")
&& arg.len() > 1
&& arg[1..].contains(s)
{
return true;
}
}
}
false
}
/// Get the value for a flag (handles --flag=value and --flag value).
pub fn get_flag_value(&self, short: Option<char>, long: Option<&str>) -> Option<String> {
let args = &self.args;
for (i, arg) in args.iter().enumerate() {
// Check long flag with =
if let Some(l) = long {
if let Some(value) = arg.strip_prefix(&format!("--{l}=")) {
return Some(value.to_string());
}
// Check long flag followed by value
if arg == &format!("--{l}") && i + 1 < args.len() {
return Some(args[i + 1].clone());
}
}
// Check short flag
if let Some(s) = short
&& arg == &format!("-{s}")
&& i + 1 < args.len()
{
return Some(args[i + 1].clone());
}
}
None
}
/// Get all positional arguments (non-flag arguments).
/// Note: This is a heuristic and may not be 100% accurate for all commands.
pub fn positional_args(&self) -> Vec<&str> {
let mut positional = Vec::new();
for arg in &self.args {
// Skip any argument that looks like a flag
if arg.starts_with('-') {
continue;
}
positional.push(arg.as_str());
}
positional
}
}