bash.py 1.7 KB

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