Пример #1
0
class TableChoice(CompleteChoice):
    completion_items: list[CompletionItem] = [
        CompletionItem(submissions_table),
        CompletionItem(journals_table),
        CompletionItem(users_table),
        CompletionItem(comments_table),
    ]
Пример #2
0
class ShellChoice(CompleteChoice):
    completion_items: list[CompletionItem] = [
        CompletionItem(BashComplete.name, help="The Bourne Again SHell"),
        CompletionItem(FishComplete.name,
                       help="The friendly interactive shell"),
        CompletionItem(ZshComplete.name, help="The Z shell")
    ]
Пример #3
0
class SearchOutputChoice(CompleteChoice):
    completion_items: list[CompletionItem] = [
        CompletionItem(Output.table.value, help="Table format"),
        CompletionItem(Output.csv.value, help="CSV format (comma separated)"),
        CompletionItem(Output.tsv.value, help="TSV format (tab separated)"),
        CompletionItem(Output.json.value, help="JSON format"),
        CompletionItem(Output.none.value, help="Do not print results to screen"),
    ]
Пример #4
0
class SearchColumnsChoice(ColumnsChoice):
    completion_items: list[tuple[str, CompletionItem]] = [
        *SortColumnsChoice.completion_items,
        (submissions_table, CompletionItem("@", help=f"{submissions_table}:ALL")),
        (journals_table, CompletionItem("@", help=f"{journals_table}:ALL")),
        (users_table, CompletionItem("@", help=f"{users_table}:ALL")),
        (comments_table, CompletionItem("@", help=f"{comments_table}:ALL")),
    ]
Пример #5
0
 def shell_complete(
         self, ctx: click.Context, param: click.Parameter,
         incomplete: str) -> List[CompletionItem]:  # pragma: no cover
     items = [
         CompletionItem(t.name, help=t.description)
         for t in resources.targets.values()
     ]
     items.extend(
         CompletionItem(group) for group in ("micro", "normal", "all"))
     return items
Пример #6
0
class SortColumnsChoice(ColumnsChoice):
    completion_items: list[tuple[str, CompletionItem]] = [
        *[(submissions_table, CompletionItem(c.name, help=f"{submissions_table}:{c.name}"))
          for c in SubmissionsColumns.as_list()],
        *[(journals_table, CompletionItem(c.name, help=f"{journals_table}:{c.name}"))
          for c in JournalsColumns.as_list()],
        *[(users_table, CompletionItem(c.name, help=f"{users_table}:{c.name}"))
          for c in UsersColumns.as_list()],
        *[(comments_table, CompletionItem(c.name, help=f"{comments_table}:{c.name}"))
          for c in CommentsColumns.as_list()],
    ]
Пример #7
0
 def shell_complete(
         self, ctx: click.Context, param: click.Parameter,
         incomplete: str) -> List[CompletionItem]:  # pragma: no cover
     return [
         CompletionItem(t.name, help=t.description)
         for t in resources.tasks.values()
     ]
Пример #8
0
 async def async_shell_complete(self, root: Root, ctx: click.Context,
                                param: click.Parameter,
                                incomplete: str) -> List[CompletionItem]:
     variants: List[str] = []
     bake_id = ctx.params[self._bake_id_param_name]
     attempt_no = ctx.params[self._attempt_no_param_name]
     async with AsyncExitStack() as stack:
         client = await stack.enter_async_context(neuro_sdk.get())
         storage: Storage = await stack.enter_async_context(
             ApiStorage(client))
         runner: BatchRunner = await stack.enter_async_context(
             BatchRunner(root.config_dir, root.console, client, storage,
                         root))
         try:
             bake_id = await resolve_bake(bake_id,
                                          project=runner.project_id,
                                          storage=storage)
             attempt = await runner.get_bake_attempt(bake_id,
                                                     attempt_no=attempt_no)
         except ResourceNotFound:
             return []
         tasks = [
             task async for task in storage.bake(id=bake_id).attempt(
                 id=attempt.id).list_tasks()
         ]
         if self._include_finished:
             variants.extend(".".join(task.yaml_id) for task in tasks
                             if task.status.is_finished)
         if self._include_started:
             variants.extend(".".join(task.yaml_id) for task in tasks
                             if task.status.is_finished)
     return [
         CompletionItem(task) for task in variants
         if task.startswith(incomplete)
     ]
Пример #9
0
        def compat_autocompletion(
                ctx: click.Context, param: click.core.Parameter,
                incomplete: str
        ) -> List["click.shell_completion.CompletionItem"]:
            from click.shell_completion import CompletionItem

            out = []

            for c in autocompletion(ctx, [], incomplete):  # type: ignore
                if isinstance(c, tuple):
                    c = CompletionItem(c[0], help=c[1])
                elif isinstance(c, str):
                    c = CompletionItem(c)

                if c.value.startswith(incomplete):
                    out.append(c)

            return out
Пример #10
0
def list_users(ctx, param, incomplete):
    # You can generate completions with help strings by returning a list
    # of CompletionItem. You can match on whatever you want, including
    # the help.
    items = [("bob", "butcher"), ("alice", "baker"),
             ("jerry", "candlestick maker")]

    for value, help in items:
        if incomplete in value or incomplete in help:
            yield CompletionItem(value, help=help)
Пример #11
0
    def shell_complete(
        self,
        ctx: click.Context | None,
        param: click.Parameter | None,
        incomplete: str,
    ) -> list[CompletionItem]:

        from click.shell_completion import CompletionItem
        from ..utils import removeprefix
        from ..config import MaestralConfig

        matches: list[str] = []
        completions: list[CompletionItem] = []

        # check if we have been given an absolute path
        absolute = incomplete.startswith("/")
        incomplete = incomplete.lstrip("/")

        # get the Maestral config for which to complete paths
        config_name = ctx.params.get("config_name",
                                     "maestral") if ctx else "maestral"

        # get all matching paths in our local Dropbox folder
        # TODO: query from server if not too slow

        config = MaestralConfig(config_name)
        dropbox_dir = config.get("sync", "path")
        local_incomplete = osp.join(dropbox_dir, incomplete)
        local_dirname = osp.dirname(local_incomplete)

        try:
            with os.scandir(local_dirname) as it:
                for entry in it:
                    if entry.path.startswith(local_incomplete):
                        if self.file_okay and entry.is_file():
                            dbx_path = removeprefix(entry.path, dropbox_dir)
                            matches.append(dbx_path)
                        if self.dir_okay and entry.is_dir():
                            dbx_path = removeprefix(entry.path, dropbox_dir)
                            matches.append(dbx_path)
        except OSError:
            pass

        # get all matching excluded items

        for dbx_path in config.get("sync", "excluded_items"):
            if dbx_path.startswith("/" + incomplete):
                matches.append(dbx_path)

        for match in matches:
            if not absolute:
                match = match.lstrip("/")
            completions.append(CompletionItem(match))

        return completions
Пример #12
0
def commands_completion(ctx: Context, param: Option,
                        incomplete: str) -> list[CompletionItem]:
    try:
        return [
            CompletionItem(n, help=c.short_help) for n, c in reduce(
                lambda a, c: a.commands[c], ctx.params.get(
                    param.name, ctx.args), app).commands.items()
            if n.lower().startswith(incomplete.lower())
        ]
    except (KeyError, AttributeError):
        return []
Пример #13
0
    def shell_complete(self, ctx, param, incomplete):
        """Return a special completion marker that tells the completion
        system to use the shell to provide file path completions.

        :param ctx: Invocation context for this command.
        :param param: The parameter that is requesting completion.
        :param incomplete: Value being completed. May be empty.

        .. versionadded:: 8.0
        """
        from click.shell_completion import CompletionItem

        return [CompletionItem(incomplete, type="file")]
Пример #14
0
    def shell_complete(
        self,
        ctx: click.Context | None,
        param: click.Parameter | None,
        incomplete: str,
    ) -> list[CompletionItem]:

        from click.shell_completion import CompletionItem
        from ..config.main import KEY_SECTION_MAP as KEYS

        return [
            CompletionItem(key) for key in KEYS if key.startswith(incomplete)
        ]
Пример #15
0
    def shell_complete(self, ctx, param, incomplete):
        """Complete choices that start with the incomplete value.

        :param ctx: Invocation context for this command.
        :param param: The parameter that is requesting completion.
        :param incomplete: Value being completed. May be empty.

        .. versionadded:: 8.0
        """
        from click.shell_completion import CompletionItem

        str_choices = map(str, self.choices)
        return [CompletionItem(c) for c in str_choices if c.startswith(incomplete)]
Пример #16
0
    def shell_complete(
        self,
        ctx: click.Context | None,
        param: click.Parameter | None,
        incomplete: str,
    ) -> list[CompletionItem]:

        from click.shell_completion import CompletionItem
        from ..config import list_configs

        matches = [
            conf for conf in list_configs() if conf.startswith(incomplete)
        ]
        return [CompletionItem(m) for m in matches]
Пример #17
0
def _typer_param_shell_complete(
        self: click.core.Parameter, ctx: click.Context,
        incomplete: str) -> List["click.shell_completion.CompletionItem"]:
    if self._custom_shell_complete is not None:
        results = self._custom_shell_complete(ctx, self, incomplete)

        if results and isinstance(results[0], str):
            from click.shell_completion import CompletionItem

            results = [CompletionItem(c) for c in results]

        return cast(List["click.shell_completion.CompletionItem"], results)

    return self.type.shell_complete(ctx, self, incomplete)
Пример #18
0
 async def async_shell_complete(self, root: Root, ctx: click.Context,
                                param: click.Parameter,
                                incomplete: str) -> List[CompletionItem]:
     variants = []
     for file in root.config_dir.config_dir.rglob("*.yml"):
         # We are not trying to parse properly to allow autocompletion of
         # broken yaml files
         if "batch" in file.read_text():
             variants.append(file.stem)
     if self._allow_all:
         variants += ["ALL"]
     return [
         CompletionItem(batch) for batch in variants
         if batch.startswith(incomplete)
     ]
Пример #19
0
    def shell_complete(self, ctx, param, incomplete):
        """Return a special completion marker that tells the completion
        system to use the shell to provide path completions for only
        directories or any paths.

        :param ctx: Invocation context for this command.
        :param param: The parameter that is requesting completion.
        :param incomplete: Value being completed. May be empty.

        .. versionadded:: 8.0
        """
        from click.shell_completion import CompletionItem

        type = "dir" if self.dir_okay and not self.file_okay else "file"
        return [CompletionItem(incomplete, type=type)]
Пример #20
0
 async def async_shell_complete(self, root: Root, ctx: click.Context,
                                param: click.Parameter,
                                incomplete: str) -> List[CompletionItem]:
     job_id = ctx.params[self._job_id_param_name]
     async with AsyncExitStack() as stack:
         client = await stack.enter_async_context(neuro_sdk.get())
         storage: Storage = await stack.enter_async_context(
             ApiStorage(client))
         runner = await stack.enter_async_context(
             LiveRunner(root.config_dir, root.console, client, storage,
                        root))
         variants = await runner.list_suffixes(job_id)
     return [
         CompletionItem(suffix) for suffix in variants
         if suffix.startswith(incomplete)
     ]
Пример #21
0
 async def async_shell_complete(self, root: Root, ctx: click.Context,
                                param: click.Parameter,
                                incomplete: str) -> List[CompletionItem]:
     async with AsyncExitStack() as stack:
         client = await stack.enter_async_context(neuro_sdk.get())
         storage: Storage = await stack.enter_async_context(
             ApiStorage(client))
         runner = await stack.enter_async_context(
             LiveRunner(root.config_dir, root.console, client, storage,
                        root))
         variants = list(runner.flow.job_ids)
         if self._allow_all:
             variants += ["ALL"]
     return [
         CompletionItem(job_id) for job_id in variants
         if job_id.startswith(incomplete)
     ]
Пример #22
0
 async def async_shell_complete(self, root: Root, ctx: click.Context,
                                param: click.Parameter,
                                incomplete: str) -> List[CompletionItem]:
     variants = []
     async with AsyncExitStack() as stack:
         client = await stack.enter_async_context(neuro_sdk.get())
         storage: Storage = await stack.enter_async_context(
             ApiStorage(client))
         try:
             async for project in storage.list_projects():
                 variants.append(project.yaml_id)
         except ValueError:
             pass
     return [
         CompletionItem(yaml_id) for yaml_id in variants
         if yaml_id.startswith(incomplete)
     ]
Пример #23
0
Файл: jp.py Проект: ivirshup/jp
def running_arg_complete(ctx, args, incomplete):
    """Argument completion for `jp join`"""
    from click.shell_completion import CompletionItem

    # TODO: There must be a better way to get default values
    port = ctx.params["port"] if ctx.params.get("port", None) is not None else "8888"
    kernels = running_server(port).running_kernels()
    matching_kernels = []
    for kernel in kernels:
        name = Path(kernel["path"]).stem
        if incomplete in name:
            path = kernel["path"]
            kernel_type = kernel["kernel"]["name"]
            matching_kernels.append(
                CompletionItem(name, help=f"{kernel_type} at '{path}'")
            )

    return matching_kernels
Пример #24
0
 async def async_shell_complete(self, root: Root, ctx: click.Context,
                                param: click.Parameter,
                                incomplete: str) -> List[CompletionItem]:
     async with AsyncExitStack() as stack:
         client = await stack.enter_async_context(neuro_sdk.get())
         storage: Storage = await stack.enter_async_context(
             ApiStorage(client))
         runner = await stack.enter_async_context(
             LiveRunner(root.config_dir, root.console, client, storage,
                        root))
         variants = [
             volume.id for volume in runner.flow.volumes.values()
             if volume.local is not None
         ]
         if self._allow_all:
             variants += ["ALL"]
     return [
         CompletionItem(image) for image in variants
         if image.startswith(incomplete)
     ]
Пример #25
0
    def shell_complete(
        self, ctx: "Context", param: "Parameter", incomplete: str
    ) -> t.List["CompletionItem"]:
        """Complete choices that start with the incomplete value.

        :param ctx: Invocation context for this command.
        :param param: The parameter that is requesting completion.
        :param incomplete: Value being completed. May be empty.

        .. versionadded:: 8.0
        """
        from click.shell_completion import CompletionItem

        str_choices = map(str, self.choices)

        if self.case_sensitive:
            matched = (c for c in str_choices if c.startswith(incomplete))
        else:
            incomplete = incomplete.lower()
            matched = (c for c in str_choices if c.lower().startswith(incomplete))

        return [CompletionItem(c) for c in matched]
Пример #26
0
 async def async_shell_complete(self, root: Root, ctx: click.Context,
                                param: click.Parameter,
                                incomplete: str) -> List[CompletionItem]:
     variants = []
     async with AsyncExitStack() as stack:
         client = await stack.enter_async_context(neuro_sdk.get())
         storage: Storage = await stack.enter_async_context(
             ApiStorage(client))
         runner: BatchRunner = await stack.enter_async_context(
             BatchRunner(root.config_dir, root.console, client, storage,
                         root))
         try:
             async for bake in runner.get_bakes():
                 variants.append(bake.id)
                 if bake.name is not None:
                     variants.append(bake.name)
         except ValueError:
             pass
     return [
         CompletionItem(bake) for bake in variants
         if bake.startswith(incomplete)
     ]
Пример #27
0
class ClearChoice(CompleteChoice):
    completion_items: list[CompletionItem] = [
        CompletionItem("clear", "Clear history")
    ]
Пример #28
0
def test_completion_item_data():
    c = CompletionItem("test", a=1)
    assert c.a == 1
    assert c.b is None
Пример #29
0
class SearchOrderChoice(CompleteChoice):
    completion_items: list[CompletionItem] = [
        CompletionItem("asc", help="Ascending order"),
        CompletionItem("desc", help="Descending order"),
    ]
Пример #30
0
    def shell_complete(self, _ctx, _param, incomplete):
        from click.shell_completion import CompletionItem

        return [CompletionItem(c) for c in self.get_completions(incomplete)]