Exemplo n.º 1
0
def list_input(prompt: str, options: typing.List, default: typing.List = None, mappings: typing.List = None) -> typing.List[typing.Any]:
    def rtrn(values: typing.Union[int, typing.List[int]]):
        if not isinstance(values, list):
            values = [values]
        out = [n-1 for n in values]
        if mappings is not None:
            out = list(map(lambda n: mappings[n], out))
        return out

    if len(options) != len(mappings):
        raise ValueError("Length of options and mappings don't match")

    if default:
        prompt += f" [Default: {default}]"
    print(prompt)

    options.insert(0, "[none match]")
    for i, item in enumerate(options):
        print(f"{i}. {item}")

    while True:
        choice = input("> ")
        if choice == "":
            return default
        try:
            choices = []
            for i in choice.strip().split(' '):
                choice = int(i)
                if not (0 <= choice <= len(options)):
                    raise IndexError("Option out of index")
                if choice != 0:
                    choices.append(choice)
            return rtrn(choices)
        except (ValueError, IndexError):
            print("Could not process your input, please try again.")
Exemplo n.º 2
0
 def walk(element: typing.List, ancestors: typing.Tuple[BaseElement,
                                                        ...]):
     replacment_indices = []
     for i, e in enumerate(element):
         if isinstance(e, BaseElement):
             if select_func(e, ancestors):
                 replacment_indices.append(i)
             if isinstance(e, HTMLElement):
                 walk(list(e.attributes.values()),
                      ancestors=ancestors + (e, ))
             walk(e, ancestors=ancestors + (e, ))
     for i in replacment_indices:
         element.pop(i)
         if replacement is not None:
             element.insert(i, replacement)
         if not all:
             raise ReachFirstException()
Exemplo n.º 3
0
    def _kubectl_str(
        self,
        cmd: typing.List,
        namespace: typing.AnyStr = None,
        input: typing.IO = None,
    ) -> typing.AnyStr:

        cmd = list(cmd)
        cmd.insert(0, "kubectl")

        if namespace is not None and "-n" not in cmd:
            cmd.extend(["-n", namespace])

        proc = subprocess.run(cmd, input=input, capture_output=True)
        try:
            proc.check_returncode()
        except:
            print(proc.stderr.decode("utf8"))
            raise

        return proc.stdout
Exemplo n.º 4
0
    def _list_insert(self, list_: ty.List, path: Path, value: _AT):
        pos = int(path[0][1:])
        if len(path) == 1:
            try:
                list_[pos] = value
            except IndexError:
                list_.insert(pos, value)
        else:
            empty_value = []
            if isinstance(value, self.unconverted_types):
                empty_value = ""

            if path[1].startswith(self.ld):

                try:
                    list_ = list_[pos]
                except IndexError:
                    list_.insert(pos, empty_value)
                return self._list_insert(list_, path[1:], value)
            else:
                try:
                    dict_ = list_[pos]
                    if not isinstance(dict_, self.__class__):
                        dict_ = self.__class__(dict_=dict_)
                except IndexError:
                    list_.insert(pos, self.__class__(dict_={}))
                    dict_ = list_[pos]

                dict_[path[1:]] = value
                list_[pos] = dict_.as_dict()
        return list_
Exemplo n.º 5
0
def _process_add_job_args(jobcall: JobCall, args: typing.List,
                          kwargs: typing.Dict):
    if not isinstance(jobcall, JobCall):
        if isinstance(jobcall, typing.Callable):
            jobcall = JobCall(jobcall, [], {})
        else:
            raise ValueError(
                "1st argument must be a JobCall created by util.make_jobcall")

    if not 'id' in kwargs:
        raise ValueError("Must provide id for job")

    orig_job_id = kwargs["id"]

    if kwargs.get("prefix_job_id", True):
        kwargs["id"] = inspect.stack(
        )[2].frame.f_globals["__name__"] + ":" + orig_job_id

    if "prefix_job_id" in kwargs:
        del kwargs["prefix_job_id"]

    args.insert(0, _call_jobcall_with_global_bot)
    kwargs["kwargs"] = {}
    kwargs["args"] = [jobcall, orig_job_id]