MCPcopy Create free account
hub / github.com/AutoForgeAI/autoforge / extract_commands

Function extract_commands

security.py:211–304  ·  view source on GitHub ↗

Extract command names from a shell command string. Handles pipes, command chaining (&&, ||, ;), and subshells. Returns the base command names (without paths). Args: command_string: The full shell command Returns: List of command names found in the string

(command_string: str)

Source from the content-addressed store, hash-verified

209
210
211def extract_commands(command_string: str) -> list[str]:
212 """
213 Extract command names from a shell command string.
214
215 Handles pipes, command chaining (&&, ||, ;), and subshells.
216 Returns the base command names (without paths).
217
218 Args:
219 command_string: The full shell command
220
221 Returns:
222 List of command names found in the string
223 """
224 commands = []
225
226 # shlex doesn't treat ; as a separator, so we need to pre-process
227
228 # Split on semicolons that aren't inside quotes (simple heuristic)
229 # This handles common cases like "echo hello; ls"
230 segments = re.split(r'(?<!["\'])\s*;\s*(?!["\'])', command_string)
231
232 for segment in segments:
233 segment = segment.strip()
234 if not segment:
235 continue
236
237 try:
238 tokens = shlex.split(segment)
239 except ValueError:
240 # Malformed command (unclosed quotes, etc.)
241 # Try fallback extraction instead of blocking entirely
242 fallback_cmd = _extract_primary_command(segment)
243 if fallback_cmd:
244 logger.debug(
245 "shlex fallback used: segment=%r -> command=%r",
246 segment,
247 fallback_cmd,
248 )
249 commands.append(fallback_cmd)
250 else:
251 logger.debug(
252 "shlex fallback failed: segment=%r (no command extracted)",
253 segment,
254 )
255 continue
256
257 if not tokens:
258 continue
259
260 # Track when we expect a command vs arguments
261 expect_command = True
262
263 for token in tokens:
264 # Shell operators indicate a new command follows
265 if token in ("|", "||", "&&", "&"):
266 expect_command = True
267 continue
268

Callers 3

test_extract_commandsFunction · 0.90
validate_dev_commandFunction · 0.90
bash_security_hookFunction · 0.85

Calls 1

_extract_primary_commandFunction · 0.85

Tested by 1

test_extract_commandsFunction · 0.72