bash.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import bashlex
  2. from opendevin.core.logger import opendevin_logger as logger
  3. def split_bash_commands(commands):
  4. try:
  5. parsed = bashlex.parse(commands)
  6. except bashlex.errors.ParsingError as e:
  7. logger.error(
  8. f'Failed to parse bash commands\n[input]: {commands}\n[error]: {e}'
  9. )
  10. # If parsing fails, return the original commands
  11. return [commands]
  12. result: list[str] = []
  13. last_end = 0
  14. for node in parsed:
  15. start, end = node.pos
  16. # Include any text between the last command and this one
  17. if start > last_end:
  18. between = commands[last_end:start]
  19. logger.debug(f'BASH PARSING between: {between}')
  20. if result:
  21. result[-1] += between.rstrip()
  22. elif between.strip():
  23. # THIS SHOULD NOT HAPPEN
  24. result.append(between.rstrip())
  25. # Extract the command, preserving original formatting
  26. command = commands[start:end].rstrip()
  27. logger.debug(f'BASH PARSING command: {command}')
  28. result.append(command)
  29. last_end = end
  30. # Add any remaining text after the last command to the last command
  31. remaining = commands[last_end:].rstrip()
  32. logger.debug(f'BASH PARSING remaining: {remaining}')
  33. if last_end < len(commands) and result:
  34. result[-1] += remaining
  35. logger.debug(f'BASH PARSING result[-1] += remaining: {result[-1]}')
  36. elif last_end < len(commands):
  37. if remaining:
  38. result.append(remaining)
  39. logger.debug(f'BASH PARSING result.append(remaining): {result[-1]}')
  40. return result