1
0
mirror of https://github.com/httpie/cli.git synced 2025-06-27 00:51:16 +02:00
Files
httpie-cli/extras/scripts/completion/zsh.py

85 lines
1.9 KiB
Python
Raw Permalink Normal View History

2022-05-18 18:30:46 +03:00
from enum import Enum
from functools import singledispatch
2022-05-18 18:30:46 +03:00
from completion_flow import (
And,
2022-05-18 18:30:46 +03:00
Check,
Condition,
If,
Node,
2022-05-18 18:30:46 +03:00
Not,
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],
'[(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]