summaryrefslogtreecommitdiff
path: root/poezio/decorators.py
blob: 4b5d032070339c573d2e27247b39e6567601dd5a (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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
"""
Module containing various decorators
"""
from typing import Any, Callable, List, Optional

from poezio import common


class RefreshWrapper:
    def __init__(self):
        self.core = None

    def conditional(self, func: Callable) -> Callable:
        """
        Decorator to refresh the UI if the wrapped function
        returns True
        """

        def wrap(*args, **kwargs):
            ret = func(*args, **kwargs)
            if self.core and ret:
                self.core.refresh_window()
            return ret

        return wrap

    def always(self, func: Callable) -> Callable:
        """
        Decorator that refreshs the UI no matter what after the function
        """

        def wrap(*args, **kwargs):
            ret = func(*args, **kwargs)
            if self.core:
                self.core.refresh_window()
            return ret

        return wrap

    def update(self, func: Callable) -> Callable:
        """
        Decorator that only updates the screen
        """

        def wrap(*args, **kwargs):
            ret = func(*args, **kwargs)
            if self.core:
                self.core.doupdate()
            return ret

        return wrap


refresh_wrapper = RefreshWrapper()


class CommandArgParser:
    """Modify the string argument of the function into a list of strings
    containing the right number of extracted arguments, or None if we don’t
    have enough.
    """

    @staticmethod
    def raw(func: Callable) -> Callable:
        """Just call the function with a single string, which is the original string
        untouched
        """

        def wrap(self, args, *a, **kw):
            return func(self, args, *a, **kw)

        return wrap

    @staticmethod
    def ignored(func: Callable) -> Callable:
        """
        Call the function without any argument
        """

        def wrap(self, args=None, *a, **kw):
            return func(self, *a, **kw)

        return wrap

    @staticmethod
    def quoted(mandatory: int,
               optional=0,
               defaults: Optional[List[Any]] = None,
               ignore_trailing_arguments=False):
        """The function receives a list with a number of arguments that is between
        the numbers `mandatory` and `optional`.

        If the string doesn’t contain at least `mandatory` arguments, we return
        None because the given arguments are invalid.

        If there are any remaining arguments after `mandatory` and `optional`
        arguments have been found (and “ignore_trailing_arguments" is not True),
        we append them to the last argument of the list.

        An argument is a string (with or without whitespaces) between two quotes
        ("), or a whitespace separated word (if not inside quotes).

        The argument `defaults` is a list of strings that are used when an
        optional argument is missing.  For example if we accept one optional
        argument and none is provided, but we have one value in the `defaults`
        list, we use that string inplace. The `defaults` list can only
        replace missing optional arguments, not mandatory ones. And it
        should not contain more than `mandatory` values. Also you cannot

        Example:
        This method needs at least one argument, and accepts up to 3
        arguments

        >> @command_args_parser.quoted(1, 2, ['default for first arg'], False)
        >> def f(args):
        >>     print(args)

        >> f('coucou les amis') # We have one mandatory and two optional
        ['coucou', 'les', 'amis']
        >> f('"coucou les amis" "PROUT PROUT"') # One mandator and only one optional,
                                                # no default for the second
        ['coucou les amis', 'PROUT PROUT']
        >> f('')                # Not enough args for mandatory number
        None
        >> f('"coucou les potes"') # One mandatory, and use the default value
                                   # for the first optional
        ['coucou les potes, 'default for first arg']
        >> f('"un et demi" deux trois quatre cinq six') # We have three trailing arguments
        ['un et demi', 'deux', 'trois quatre cinq six']

        """
        default_args_outer = defaults or []

        def first(func: Callable):
            def second(self, args: str, *a, **kw):
                default_args = default_args_outer
                if args and args.strip():
                    split_args = common.shell_split(args)
                else:
                    split_args = []
                if len(split_args) < mandatory:
                    return func(self, None, *a, **kw)
                res, split_args = split_args[:mandatory], split_args[
                    mandatory:]
                if optional == -1:
                    opt_args = split_args[:]
                else:
                    opt_args = split_args[:optional]

                if opt_args:
                    res += opt_args
                    split_args = split_args[len(opt_args):]
                    default_args = default_args[len(opt_args):]
                res += default_args
                if split_args and res and not ignore_trailing_arguments:
                    res[-1] += " " + " ".join(split_args)
                return func(self, res, *a, **kw)

            return second

        return first


command_args_parser = CommandArgParser()