2022-05-18 18:30:46 +03:00
|
|
|
from enum import Enum
|
2022-05-20 10:42:38 +03:00
|
|
|
from functools import singledispatch
|
|
|
|
|
2022-05-18 18:30:46 +03:00
|
|
|
from completion_flow import (
|
2022-05-20 10:42:38 +03:00
|
|
|
And,
|
2022-05-18 18:30:46 +03:00
|
|
|
Check,
|
|
|
|
Condition,
|
|
|
|
If,
|
2022-05-20 10:42:38 +03:00
|
|
|
Node,
|
2022-05-18 18:30:46 +03:00
|
|
|
Not,
|
2022-05-20 10:42:38 +03:00
|
|
|
Suggest,
|
|
|
|
Suggestion,
|
|
|
|
Variable,
|
2022-05-18 18:30:46 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
class ZSHVariable(str, Enum):
|
|
|
|
CURRENT = 'CURRENT'
|
|
|
|
NORMARG = 'NORMARG'
|
|
|
|
PREDECESSOR = 'predecessor'
|
|
|
|
METHODS = 'METHODS'
|
|
|
|
|
|
|
|
|
|
|
|
SUGGESTION_TO_FUNCTION = {
|
|
|
|
Suggestion.METHOD: '_httpie_method',
|
|
|
|
Suggestion.URL: '_httpie_url',
|
|
|
|
Suggestion.REQUEST_ITEM: '_httpie_request_item',
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
@singledispatch
|
|
|
|
def compile_zsh(node: Node) -> ...:
|
|
|
|
raise NotImplementedError(f'{type(node)} is not supported')
|
|
|
|
|
|
|
|
|
|
|
|
@compile_zsh.register(If)
|
|
|
|
def compile_if(node: If) -> str:
|
2022-05-19 14:56:25 +03:00
|
|
|
check = compile_zsh(node.check)
|
|
|
|
action = compile_zsh(node.action)
|
|
|
|
return f'if {check}; then\n {action} && ret=0\nfi'
|
2022-05-18 18:30:46 +03:00
|
|
|
|
|
|
|
|
|
|
|
@compile_zsh.register(Check)
|
|
|
|
def compile_check(node: Check) -> str:
|
|
|
|
args = [
|
|
|
|
ZSHVariable(arg.name) if isinstance(arg, Variable) else arg
|
|
|
|
for arg in node.args
|
|
|
|
]
|
|
|
|
|
|
|
|
if node.condition is Condition.POSITION_EQ:
|
|
|
|
return (
|
|
|
|
f'(( {ZSHVariable.CURRENT} == {ZSHVariable.NORMARG} + {args[0]} ))'
|
|
|
|
)
|
|
|
|
elif node.condition is Condition.POSITION_GE:
|
|
|
|
return (
|
|
|
|
f'(( {ZSHVariable.CURRENT} >= {ZSHVariable.NORMARG} + {args[0]} ))'
|
|
|
|
)
|
|
|
|
elif node.condition is Condition.CONTAINS_PREDECESSOR:
|
|
|
|
parts = [
|
|
|
|
'[[ ${',
|
|
|
|
args[0],
|
2022-05-19 16:06:37 +03:00
|
|
|
'[(ie)$',
|
2022-05-18 18:30:46 +03:00
|
|
|
ZSHVariable.PREDECESSOR,
|
|
|
|
']}',
|
|
|
|
' -le ${#',
|
|
|
|
args[0],
|
|
|
|
'} ]]',
|
|
|
|
]
|
|
|
|
return ''.join(parts)
|
|
|
|
|
|
|
|
|
|
|
|
@compile_zsh.register(And)
|
|
|
|
def compile_and(node: And) -> str:
|
2022-05-19 14:56:25 +03:00
|
|
|
return ' && '.join(compile_zsh(check) for check in node.checks)
|
2022-05-18 18:30:46 +03:00
|
|
|
|
|
|
|
|
|
|
|
@compile_zsh.register(Not)
|
|
|
|
def compile_not(node: Not) -> str:
|
2022-05-19 14:56:25 +03:00
|
|
|
return f'! {compile_zsh(node.check)}'
|
2022-05-18 18:30:46 +03:00
|
|
|
|
|
|
|
|
|
|
|
@compile_zsh.register(Suggest)
|
|
|
|
def compile_suggest(node: Suggest) -> str:
|
|
|
|
return SUGGESTION_TO_FUNCTION[node.suggestion]
|