hellpipe/hellpipe/main.py

59 lines
1.2 KiB
Python

import shlex
from textwrap import indent
import sys
from . import convert
FILE_START = """\
# generated with hellpipe
def main():
"""
FILE_END = """
if __name__ == "__main__":
main()"""
INPUTCMD = """curl "https://httpbin.org/get?test=123" | jq ".headers|keys[]" -r | xargs -L 1 echo"""
def split_commands(tokens):
cur_command = []
for tok in tokens:
if tok == "|":
yield cur_command
cur_command = []
continue
cur_command.append(tok)
yield cur_command
def main():
command = sys.argv[1] if len(sys.argv) > 1 else INPUTCMD
oneliner = shlex.shlex(INPUTCMD, posix=True, punctuation_chars=True)
stages = []
last_stage = None
for com in split_commands(oneliner):
if not last_stage:
input_name = None
else:
input_name = last_stage.output_name
stage = convert.convert_command(com, input_name)
stages.append(stage)
last_stage = stage
for stage in stages:
print("\n".join(stage.imports))
print(FILE_START)
for stage in stages:
print(indent(stage.code, " "))
print(FILE_END)
if __name__ == "__main__":
main()