bash.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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.debug(
  8. f'Failed to parse bash commands\n'
  9. f'[input]: {commands}\n'
  10. f'[warning]: {e}\n'
  11. f'The original command will be returned as is.'
  12. )
  13. # If parsing fails, return the original commands
  14. return [commands]
  15. result: list[str] = []
  16. last_end = 0
  17. for node in parsed:
  18. start, end = node.pos
  19. # Include any text between the last command and this one
  20. if start > last_end:
  21. between = commands[last_end:start]
  22. logger.debug(f'BASH PARSING between: {between}')
  23. if result:
  24. result[-1] += between.rstrip()
  25. elif between.strip():
  26. # THIS SHOULD NOT HAPPEN
  27. result.append(between.rstrip())
  28. # Extract the command, preserving original formatting
  29. command = commands[start:end].rstrip()
  30. logger.debug(f'BASH PARSING command: {command}')
  31. result.append(command)
  32. last_end = end
  33. # Add any remaining text after the last command to the last command
  34. remaining = commands[last_end:].rstrip()
  35. logger.debug(f'BASH PARSING remaining: {remaining}')
  36. if last_end < len(commands) and result:
  37. result[-1] += remaining
  38. logger.debug(f'BASH PARSING result[-1] += remaining: {result[-1]}')
  39. elif last_end < len(commands):
  40. if remaining:
  41. result.append(remaining)
  42. logger.debug(f'BASH PARSING result.append(remaining): {result[-1]}')
  43. return result