Parse environment variables from command string. Extracts VAR=value pairs from the beginning of the command. Handles quoted values and stops at the first non-env-var token. Examples: "FOO=bar command" -> {"FOO": "bar"} "FOO=bar BAZ=qux command" -> {"FOO": "bar", "B
(command: str)
| 158 | |
| 159 | |
| 160 | def parse_env_vars_from_command(command: str) -> dict[str, str]: |
| 161 | """ |
| 162 | Parse environment variables from command string. |
| 163 | |
| 164 | Extracts VAR=value pairs from the beginning of the command. |
| 165 | Handles quoted values and stops at the first non-env-var token. |
| 166 | |
| 167 | Examples: |
| 168 | "FOO=bar command" -> {"FOO": "bar"} |
| 169 | "FOO=bar BAZ=qux command" -> {"FOO": "bar", "BAZ": "qux"} |
| 170 | "FOO='bar baz' command" -> {"FOO": "bar baz"} |
| 171 | 'FOO="bar baz" command' -> {"FOO": "bar baz"} |
| 172 | |
| 173 | Returns: dict of env var names to values |
| 174 | """ |
| 175 | env_vars: dict[str, str] = {} |
| 176 | command = command.strip() |
| 177 | |
| 178 | # Pattern to match: VAR=value (with optional quotes) |
| 179 | # Matches at word boundaries to avoid partial matches |
| 180 | env_pattern = r'^([A-Z_][A-Z0-9_]*)=((?:[^\s"\']|"[^"]*"|\'[^\']*\')+)' |
| 181 | |
| 182 | while True: |
| 183 | match = re.match(env_pattern, command) |
| 184 | if not match: |
| 185 | break |
| 186 | |
| 187 | var_name = match.group(1) |
| 188 | var_value = match.group(2) |
| 189 | |
| 190 | # Remove quotes if present |
| 191 | if var_value.startswith('"') and var_value.endswith('"'): |
| 192 | var_value = var_value[1:-1] |
| 193 | elif var_value.startswith("'") and var_value.endswith("'"): |
| 194 | var_value = var_value[1:-1] |
| 195 | |
| 196 | env_vars[var_name] = var_value |
| 197 | |
| 198 | # Remove the matched part and continue |
| 199 | command = command[match.end() :].lstrip() |
| 200 | |
| 201 | return env_vars |
| 202 | |
| 203 | |
| 204 | def main(): |