summaryrefslogtreecommitdiffstats
path: root/extras/scripts/completion/zsh.py
blob: 1a952e4f467f2371bd1b5a2f553b369ab778b984 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
from functools import singledispatch
from enum import Enum
from lib2to3.pgen2.pgen import generate_grammar
from completion_flow import (
    Node,
    Check,
    Suggest,
    Variable,
    Condition,
    Suggestion,
    If,
    And,
    Not,
    generate_flow,
)


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:
    check = compile_zsh(node.check)
    action = compile_zsh(node.action)
    return f'if {check}; then\n    {action} && ret=0\nfi'


@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)$',
            ZSHVariable.PREDECESSOR,
            ']}',
            ' -le ${#',
            args[0],
            '} ]]',
        ]
        return ''.join(parts)


@compile_zsh.register(And)
def compile_and(node: And) -> str:
    return ' && '.join(compile_zsh(check) for check in node.checks)


@compile_zsh.register(Not)
def compile_not(node: Not) -> str:
    return f'! {compile_zsh(node.check)}'


@compile_zsh.register(Suggest)
def compile_suggest(node: Suggest) -> str:
    return SUGGESTION_TO_FUNCTION[node.suggestion]