示例#1
0
def eve_esi(
    ctx: typer.Context,
    version: str = typer.Option(
        "latest",
        "--version",
        help="Esi schema version to load from Eve Esi Jobs app data directory",
    ),
    schema_path: Optional[Path] = typer.Option(
        None, "--schema-path", "-s", help="Path to local schema file."
    ),
):
    """
    Welcome to Eve Esi Jobs. Get started by downloading a schema, or checkout the
    docs at: https://eve-esi-jobs.readthedocs.io/en/latest/
    """
    config = make_config_from_env()
    typer.echo(f"Logging at {config.log_path}")
    ctx.obj = {}
    start = perf_counter_ns()
    ctx.obj["start_time"] = start
    logger.info("loading schema")
    ctx.obj["config"] = config
    schema = None
    schema_source = ""
    if schema_path is not None:
        try:
            schema_text = schema_path.read_text()
            schema = json.loads(schema_text)
            typer.echo(f"Loaded schema from {schema_path}")
            schema_source = str(schema_path)
        except FileNotFoundError as ex:
            logger.exception("Error loading schema from file.")
            raise typer.BadParameter(
                f"Error loading schema from {schema_path}. "
                f"Error: {ex.__class__.__name__} msg: {ex}."
            )
    else:
        schema = load_schema(config.app_dir, version)
        schema_source = str(config.app_dir) + f"version: {version}"
        if schema is None:
            typer.echo("Schema not found in app data, attempting to download.")
            typer.echo("Consider using `eve-esi schema download` to save a local copy,")
            typer.echo("or provide a valid local path to the schema.")
            schema = download_json(config.schema_url)
            schema_source = config.schema_url
    try:
        operation_manifest = OperationManifest(schema)
    except Exception as ex:
        logger.exception(
            "Tried to make operation_manifest with invalid schema. version: %s, source: %s, error: %s, msg: %s",
            version,
            schema_source,
            ex.__class__.__name__,
            ex,
        )
        raise typer.BadParameter(
            "The provided schema was invalid. please try a different one."
        )
    ctx.obj["operation_manifest"] = operation_manifest
    typer.echo(f"Loaded ESI schema version {operation_manifest.version}.\n")
示例#2
0
文件: cli.py 项目: avaldebe/PyPMS
def callback(
    ctx: Context,
    model: Supported = Option(Supported.default,
                              "--sensor-model",
                              "-m",
                              help="sensor model"),
    port: str = Option("/dev/ttyUSB0",
                       "--serial-port",
                       "-s",
                       help="serial port"),
    seconds: int = Option(60,
                          "--interval",
                          "-i",
                          help="seconds to wait between updates"),
    samples: Optional[int] = Option(None,
                                    "--samples",
                                    "-n",
                                    help="stop after N samples"),
    debug: bool = Option(False, "--debug",
                         help="print DEBUG/logging messages"),
    version: Optional[bool] = Option(None,
                                     "--version",
                                     "-V",
                                     callback=version_callback),
):
    """Read serial sensor"""
    logger.setLevel("DEBUG" if debug else os.getenv("LEVEL", "WARNING"))
    ctx.obj = {"reader": SensorReader(model, port, seconds, samples)}
示例#3
0
def main_callback(
    ctx: typer.Context,
    light_id: int = typer.Option(
        0,
        "--light-id",
        "-l",
        show_default=True,
        help="Which light to operate on, see list output.",
    ),
    all_lights: bool = typer.Option(False,
                                    "--all",
                                    "-a",
                                    is_flag=True,
                                    help="Operate on all lights."),
    debug: bool = typer.Option(
        False,
        "--debug",
        "-D",
        is_flag=True,
        help="Enable logging",
    ),
):
    """Control USB attached LED lights like a Human™

    Make a USB attached LED light turn on, off and blink; all from the
    comfort of your very own command-line. If your platform supports
    HIDAPI (Linux, MacOS, Windows and probably others), then you can use
    busylight with supported lights!
    """

    ctx.obj = ALL_LIGHTS if all_lights else light_id

    if debug:
        logger.enable("busylight")
示例#4
0
def main(ctx: typer.Context, cfg_file: str = None):
    """Capture traces for side-channel analysis."""

    cfg_file = 'capture_aes.yaml' if cfg_file is None else cfg_file
    with open(cfg_file) as f:
        cfg = yaml.load(f, Loader=yaml.FullLoader)

    # Store config in the user data attribute (`obj`) of the context.
    ctx.obj = SimpleNamespace(cfg=cfg)
示例#5
0
def init(
    ctx: typer.Context,
    config_file: List[pathlib.Path] = typer.Option(
        None,
        exists=True,
        dir_okay=False,
        help="A file to read configuration values from. May be specified multiple times to combine configuration values from multiple files.",
    ),
    verbosity: Verbosity = typer.Option(
        Verbosity.info, case_sensitive=False, help="Set the verbosity of the logging."
    ),
) -> None:
    """
    Conventional - An extensible command-line tool for parsing and processing structured commits.
    """
    import asyncio
    import logging

    import confuse

    from .util.typer import ColorFormatter, TyperHandler

    handler = TyperHandler()
    handler.formatter = ColorFormatter()

    logger = logging.getLogger()
    logging.basicConfig(handlers=[handler], force=True)

    # Importing aiocache results in a warning being logged. Temporarily disable it
    # until it has been imported.
    logging.getLogger("aiocache").setLevel(logging.ERROR)
    import aiocache  # noqa: F401

    # Reset aiocache log level since aiocache has now been imported and unnecessary
    # warning has been avioded.
    logging.getLogger("aiocache").setLevel(logging.NOTSET)

    from .util.config import find_project_configuration_file

    logging.getLogger().setLevel(getattr(logging, verbosity))

    config = confuse.Configuration("Conventional", "conventional")

    project_config_file = asyncio.run(find_project_configuration_file())
    if project_config_file is not None:
        logger.debug(f"Loading configuration file, {project_config_file.as_posix()}")
        config.set_file(project_config_file)

    for filename in config_file:
        logger.debug(f"Loading configuration file, {filename.as_posix()}")
        config.set_file(filename)

    ctx.obj = config
def main(
    ctx: typer.Context,
    verbose: bool = typer.Option(
        False, help="Enable verbose logging to the terminal"),
    full: bool = typer.Option(False,
                              help="Print all fields from CRUD commands"),
    raw: bool = typer.Option(
        False, help="Print output from CRUD commands as raw json"),
    version: bool = typer.Option(
        False, help="Print the version of jobbergate-cli and exit"),
):
    """
    Welcome to the Jobbergate CLI!

    More information can be shown for each command listed below by running it with the --help option.
    """
    if version:
        typer.echo(importlib_metadata.version("jobbergate-cli"))
        raise typer.Exit()

    if ctx.invoked_subcommand is None:
        terminal_message(
            conjoin(
                "No command provided. Please check the [bold magenta]usage[/bold magenta] and add a command",
                "",
                f"[yellow]{ctx.get_help()}[/yellow]",
            ),
            subject="Need a jobbergate command",
        )
        raise typer.Exit()

    init_logs(verbose=verbose)
    init_sentry()
    persona = None

    client = httpx.Client(
        base_url=f"https://{settings.AUTH0_LOGIN_DOMAIN}",
        headers={"content-type": "application/x-www-form-urlencoded"},
    )
    context = JobbergateContext(persona=None, client=client)

    if ctx.invoked_subcommand not in ("login", "logout"):
        persona = init_persona(context)
        context.client = httpx.Client(
            base_url=settings.JOBBERGATE_API_ENDPOINT,
            headers=dict(
                Authorization=f"Bearer {persona.token_set.access_token}"),
        )
        context.persona = persona
        context.full_output = full
        context.raw_output = raw

    ctx.obj = context
示例#7
0
    def init(
        self,
        ctx: Context,
        version: Optional[bool] = Option(None,
                                         "--version",
                                         is_eager=True,
                                         help="Show version number and exit"),
    ):

        if ctx.resilient_parsing:  # pragma: no cover
            return

        if version:
            v = get_distribution("falca").version
            cprint(f":package: Falca v{v}")
            raise Exit

        ctx.obj = self.app
示例#8
0
def validate_parameters(ctx: typer.Context, value: List[str]) -> List[str]:

    file_path = Path(ctx.params["file_path"]).absolute()
    if not ctx.obj:
        parsed_src = SourceParser(
            str(SourceParser.get_project_path(file_path)), str(file_path)
        )
        parsed_src.set_entity(str(parsed_src.get_entities()[0].get_name()))
        ctx.obj = parsed_src
    else:
        parsed_src: SourceParser = ctx.obj
    parameter_name_list = [p.get_name() for p in parsed_src.get_parameters()]
    for chosen_parameter in value:
        if chosen_parameter not in parameter_name_list:
            raise typer.BadParameter(
                "Chosen parameter: "
                + chosen_parameter
                + " is not among available parameters "
                + str(parameter_name_list)
            )
    return value
示例#9
0
def main(
    ctx: typer.Context,
    version: Optional[bool] = typer.Option(
        None,
        "--version",
        help="Show version and exit.",
        callback=version_callback,
        is_eager=True,
    ),
    overlay_dir: Optional[Path] = typer.Option(
        ".", "--overlay-dir", help="Specify location for overlay."
    ),
    worker_count: int = typer.Option(
        8, min=1, help="Number of workers for creating package cache."
    ),
    quiet: Optional[bool] = typer.Option(
        False,
        "--quiet",
        help="Suppresses output. For commands checking versions exit code 100 means newer versions are available.",
    ),
):
    """Provides certain tools to be run on the overlay directory. See individual commands help for details."""
    state = State()
    ctx.obj = state
    if overlay_dir != ".":
        state.overlay_dir = Path(overlay_dir).absolute()

    state.quiet = quiet or (ctx.invoked_subcommand == "mkreadme")

    state.print_stdout("Starting overlay-maintain-tools CLI")

    state.print_stdout(f"Building package cache from {str(overlay_dir)}.")
    state.pkg_cache = sorted(
        build_pkgs_cache(overlay_dir=overlay_dir, worker_count=worker_count),
        key=lambda _: _.atomname,
    )
    state.print_stdout(f"Package cache built.")
    state.worker_count = worker_count
示例#10
0
def root(
        ctx: typer.Context,
        version: typing.Optional[bool] = typer.Option(
            False,
            "--version",
            callback=version_callback,
            is_eager=True,
        ),
        base_url: str = typer.
    Option(
        "http://localhost:8090",
        help=
        "Set the base-url of your instance. This flag will overwrite scheme, host, path and port, if those are set in"
        "this string.",
        callback=furl_callback,
    ),
        user: str = typer.Option(
            "admin",
            help="Set the username of the user you want to use",
        ),
        password: str = typer.Option(
            "admin",
            help="Set the password of the user you want to use",
        ),
        port: typing.Optional[int] = typer.Option(None),
        ask_for_password: typing.Optional[bool] = typer.Option(
            False, help="Asks user for password interactively"),
        logo: bool = typer.Option(True, help="Print lively apps logo"),
):
    """ A simple command line plugin uploader/installer/manager for atlassian product server
    instances (Confluence/Jira) written in python(3).
    """
    if logo:
        print(LOGO)
    if ask_for_password:
        password = typer.prompt("Password: "******"base_url": burl}
 def _main_callback(ctx: Context):
     ctx.obj = dummy_context
def main(context: typer.Context, verbose: bool = False):
    """Perform various development-oriented tasks for this plugin"""
    context.obj = {"verbose": verbose}
示例#13
0
def main(context: typer.Context, verbose: bool = False, qgis_profile: str = "default"):
    """Perform various development-oriented tasks for this plugin"""
    context.obj = {
        "verbose": verbose,
        "qgis_profile": qgis_profile,
    }
示例#14
0
def load_ctx(ctx: typer.Context):
    ctx.obj = {}
    ctx.obj["rules"] = RULES
示例#15
0
def main(
    ctx: typer.Context,
    language: Language = typer.Option(
        None,
        "--language",
        "-L",
        show_choices=True,
        show_default=True,
        help="Choose catalog language",
    ),
    topic: Topic = typer.Option(
        None,
        "--topic",
        "-T",
        show_default=True,
        show_choices=True,
        help="Choose a catalog topic.",
    ),
):
    """![Downloading](https://github.com/JnyJny/springer_downloader/raw/master/demo/animations/download-catalog.gif)
    __Springer Textbook Bulk Download Tool__
    
    ## NOTICE

    The author of this software is not affiliated with Springer and this
    tool is not authorized or supported by Springer. Thank you to
    Springer for making these high quality textbooks available at no
    cost.

    \b
    >"With the Coronavirus outbreak having an unprecedented impact on
    >education, Springer Nature is launching a global program to support
    >learning and teaching at higher education institutions
    >worldwide. Remote access to educational resources has become
    >essential. We want to support lecturers, teachers and students
    >during this challenging period and hope that this initiative will go
    >some way to help.
    >
    >Institutions will be able to access more than 500 key textbooks
    >across Springer Nature’s eBook subject collections for free. In
    >addition, we are making a number of German-language Springer medical
    >training books on emergency nursing freely accessible.  These books
    >will be available via SpringerLink until at least the end of July."

    [Source](https://www.springernature.com/gp/librarians/news-events/all-news-articles/industry-news-initiatives/free-access-to-textbooks-for-institutions-affected-by-coronaviru/17855960)

    ## Overview

    This tool automates the process of downloading the Springer-provided
    Excel catalogs, locating URLs and downloading the files in PDF or epub
    format.

    Catalogs are lists of books in a specific _language_, spanning a
    _topic_. Catalogs are further subdivided into _packages_ which are
    books grouped by sub-topics.
    
    Textbooks can be downloaded by; title, package name or the entire
    catalog. Title and package names can be incompletely specified and
    are case-insensitive. 

    The available languages are: English & German.

    The available topics are: _All Disciplines_ and _Emergency Nursing_.

    **Note: The _Emergency Nursing_ topic is not available in English.**

    ## Source and License

    Full source is available on
    [GitHub](https://github.com/JnyJny/springer_downloader) and it is
    licensed under the
    [Apache-2.0](https://www.apache.org/licenses/LICENSE-2.0)
    license.

    ## Installation

    This utility can be installed using `pip`:

    `$ python3 -m pip install springer`

    Or from the latest source on GitHub:

    `$ python3 -m pip install git+https://github.com/JnyJny/springer_downloader`
    """

    # EJO The callback function is called before any of the command functions
    #     are invoked. Since all the subcommands work with an instantiation of
    #     springer.catalog.Catalog, we create one in the callback and attach it
    #     to the typer.Context object using the attribute 'obj'. I don't
    #     particularly care for accessing the catalog as 'ctx.obj' in the
    #     subcommands, but I haven't found a better solution to this "problem"
    #     yet.

    try:
        ctx.obj = Catalog(language, topic)

    except KeyError as error:
        typer.secho(
            f"Failed to locate a catalog for: '{error.args[0].value!s}'",
            fg="red")
        raise typer.Exit(-1)
示例#16
0
def callback(
    ctx: typer.Context,
    select_addons_dirs: Optional[List[Path]] = typer.Option(
        None,
        "--select-addons-dir",
        "-d",
        exists=True,
        file_okay=False,
        dir_okay=True,
        help=(
            "Select all installable addons found in this directory. "
            "This option may be repeated. "
            "The directories selected with this options are "
            "automatically added to the addons search path."
        ),
        show_default=False,
    ),
    select_include: Optional[str] = typer.Option(
        None,
        "--select-include",
        "--select",
        metavar="addon1,addon2,...",
        help=(
            "Comma separated list of addons to select. "
            "These addons will be searched in the addons path."
        ),
    ),
    select_exclude: Optional[str] = typer.Option(
        None,
        metavar="addon1,addon2,...",
        help=(
            "Comma separated list of addons to exclude from selection. "
            "This option is useful in combination with `--select-addons-dir`."
        ),
    ),
    select_core_addons: bool = typer.Option(
        False,
        "--select-core-addons",
        help="Select the Odoo core addons (CE and EE) for the given series.",
        show_default=False,
    ),
    addons_path: Optional[str] = typer.Option(
        None,
        help="Expand addons path with this comma separated list of directories.",
    ),
    addons_path_from_import_odoo: bool = typer.Option(
        True,
        help=(
            "Expand addons path by trying to `import odoo` and "
            "looking at `odoo.addons.__path__`. This option is useful when "
            "addons have been installed with pip."
        ),
    ),
    addons_path_python: str = typer.Option(
        "python",
        "--addons-path-python",
        show_default=False,
        metavar="PYTHON",
        help=(
            "The python executable to use when importing `odoo.addons.__path__`. "
            "Defaults to the `python` executable found in PATH."
        ),
    ),
    addons_path_from_odoo_cfg: Optional[Path] = typer.Option(
        None,
        exists=True,
        file_okay=True,
        dir_okay=False,
        readable=True,
        envvar="ODOO_RC",
        help=(
            "Expand addons path by looking into the provided Odoo configuration file. "
        ),
    ),
    separator: str = typer.Option(
        default=None,
        hidden=True,  # deprecated
    ),
    odoo_series: Optional[OdooSeries] = typer.Option(
        None,
        envvar=["ODOO_VERSION", "ODOO_SERIES"],
        help="Odoo series to use, in case it is not autodetected from addons version.",
    ),
    verbose: int = typer.Option(
        0,
        "--verbose",
        "-v",
        count=True,
        show_default=False,
    ),
    quiet: int = typer.Option(
        0,
        "--quiet",
        "-q",
        count=True,
        show_default=False,
    ),
    version: Optional[bool] = typer.Option(
        None,
        "--version",
        callback=version_callback,
        is_eager=True,
    ),
) -> None:
    """Reason about Odoo addons manifests.

    The `--select-*` options of this command select addons on which the
    subcommands will act. The `--addons-path` options provide locations to
    search for addons.

    Run `manifestoo <subcommand> --help` for more options.
    """
    echo.verbosity += verbose
    echo.verbosity -= quiet
    main_options = MainOptions()
    if separator:
        echo.warning(
            "--separator is deprecated as a global option. "
            "Please use the same option of list, list-depends."
        )
        main_options.separator = separator
    # resolve addons_path
    if select_addons_dirs:
        main_options.addons_path.extend_from_addons_dirs(select_addons_dirs)
    if addons_path:
        main_options.addons_path.extend_from_addons_path(addons_path)
    if addons_path_from_import_odoo:
        main_options.addons_path.extend_from_import_odoo(addons_path_python)
    if addons_path_from_odoo_cfg:
        main_options.addons_path.extend_from_odoo_cfg(addons_path_from_odoo_cfg)
    echo.info(str(main_options.addons_path), bold_intro="Addons path: ")
    # populate addons_set
    main_options.addons_set.add_from_addons_dirs(main_options.addons_path)
    echo.info(str(main_options.addons_set), bold_intro="Addons set: ")
    # Odoo series
    if odoo_series:
        main_options.odoo_series = odoo_series
    else:
        detected_odoo_series = detect_from_addons_set(main_options.addons_set)
        if len(detected_odoo_series) == 0:
            echo.notice("No Odoo series detected in addons set")
            main_options.odoo_series = None
        elif len(detected_odoo_series) > 1:
            echo.notice(
                f"Different Odoo series detected in addons set: "
                f"{', '.join(detected_odoo_series)}"
            )
            main_options.odoo_series = None
        else:
            main_options.odoo_series = detected_odoo_series.pop()
    # addons selection
    if select_addons_dirs:
        main_options.addons_selection.add_addons_dirs(select_addons_dirs)
    if select_include:
        main_options.addons_selection.add_addon_names(select_include)
    if select_exclude:
        main_options.addons_selection.remove_addon_names(select_exclude)
    if select_core_addons:
        ensure_odoo_series(main_options.odoo_series)
        assert main_options.odoo_series
        main_options.addons_selection.update(get_core_addons(main_options.odoo_series))
    if main_options.addons_selection:
        echo.info(str(main_options.addons_selection), bold_intro="Addons selection: ")
    else:
        echo.notice("No addon selected, please use one of the --select options.")
    echo.info(f"{main_options.odoo_series}", bold_intro="Odoo series: ")
    # pass main options to commands
    ctx.obj = main_options
示例#17
0
def main(ctx: typer.Context):
    ctx.obj = {"storage": LocalStorage()}
示例#18
0
def blync_callback(
    ctx: typer.Context,
    light_id: int = typer.Option(
        0,
        "--light-id",
        "-l",
        show_default=True,
        help="Light identifier",
    ),
    red: int = typer.Option(
        0,
        "--red",
        "-r",
        is_flag=True,
        show_default=True,
        help="Red color value range: 0 - 255",
    ),
    blue: int = typer.Option(
        0,
        "--blue",
        "-b",
        is_flag=True,
        show_default=True,
        help="Blue color value range: 0 - 255",
    ),
    green: int = typer.Option(
        0,
        "--green",
        "-g",
        is_flag=True,
        help="Green color value range: 0 - 255",
        show_default=True,
    ),
    red_b: bool = typer.Option(False,
                               "--RED",
                               "-R",
                               is_flag=True,
                               help="Full value red [255]"),
    blue_b: bool = typer.Option(False,
                                "--BLUE",
                                "-B",
                                is_flag=True,
                                help="Full value blue [255]"),
    green_b: bool = typer.Option(False,
                                 "--GREEN",
                                 "-G",
                                 is_flag=True,
                                 help="Full value green [255]"),
    off: bool = typer.Option(False,
                             "--off/--on",
                             "-o/-n",
                             show_default=True,
                             help="Turn the light off/on."),
    dim: bool = typer.Option(
        False,
        "--dim",
        "-d",
        is_flag=True,
        help="Toggle bright/dim mode.",
        show_default=True,
    ),
    flash: int = typer.Option(
        0,
        "--flash",
        "-f",
        count=True,
        is_flag=True,
        help="Enable flash mode.",
    ),
    play: int = typer.Option(0, "--play", "-p", help="Select song: 1-15"),
    repeat: bool = typer.Option(
        False,
        "--repeat",
        is_flag=True,
        show_default=True,
        help="Repeat the selected song.",
    ),
    volume: int = typer.Option(5,
                               "--volume",
                               show_default=True,
                               help="Set the volume: 1-10"),
    available: bool = typer.Option(
        False,
        "--list-available",
        "-a",
        is_flag=True,
        is_eager=True,
        callback=list_lights,
    ),
    verbose: int = typer.Option(0,
                                "--verbose",
                                "-v",
                                count=True,
                                callback=verbosity),
    version: bool = typer.Option(False,
                                 "--version",
                                 "-V",
                                 is_flag=True,
                                 is_eager=True,
                                 callback=report_version),
):
    """Control your Embrava BlyncLight from the command-line!

    ## Usage

    Use the `blync` utility to directly control your Embrava BlyncLight:

    \b
    ```console
    $ blync -R        # turn the light on with red color and leave it on
    $ blync --off     # turn the light off
    $ blync -RG --dim # turn the light on with yellow color and dim
    $ blync -RBG      # turn the light on with white color
    ```

    Colors can be specified by values between 0 and 255 using the lower-case
    color options or using the upper-case full value options.

    \b
    ```console
    $ blync -r 127                # half intensity red
    $ blync -r 255                # full intensity red
    $ blync -R                    # also full intensity red
    $ blync -r 255 -b 255 -g 255  # full intensity white
    $ blync -RBG                  # full intensity white
    ```


    If that's not enough fun, there are three builtin color modes:
    `fli`, `throbber`, and `rainbow`. All modes continue until the
    user terminates with a Control-C or platform equivalent.

    \b
    ```console
    $ blync fli
    $ blync throbber
    $ blync rainbow
    ```

    ## Installation

    \b
    ```console
    $ python3 -m pip install blynclight
    $ python3 -m pip install git+https://github.com/JnyJny/blynclight.git # latest
    ```

    This module depends on
    [hidapi](https://github.com/trezor/cython-hidapi), which supports
    Windows, Linux, FreeBSD and MacOS via a Cython module.
    """

    if ctx.invoked_subcommand == "udev-rules":
        return

    try:
        light = BlyncLight.get_light(light_id, immediate=False)
    except BlyncLightNotFound as error:
        typer.secho(str(error), fg="red")
        raise typer.Exit(-1) from None

    assert not light.immediate

    light.red = red if not red_b else 255
    light.blue = blue if not blue_b else 255
    light.green = green if not green_b else 255
    light.off = 1 if off else 0
    light.dim = 1 if dim else 0
    light.flash = 1 if flash > 0 else 0
    light.speed = flash

    light.mute = 0 if play else 1
    light.music = play
    light.play = 1 if play else 0
    light.volume = volume
    light.repeat = 1 if repeat else 0

    if not ctx.invoked_subcommand:

        if light.on and light.color == (0, 0, 0):
            light.color = DEFAULT_COLOR
        try:
            light.immediate = True
            for line in str(light).splitlines():
                logger.info(line)
        except Exception as error:
            typer.secho(str(error), fg="red")
            raise typer.Exit(-1) from None
        raise typer.Exit()

    # Disable flashing for subcommands.
    light.flash = 0

    ctx.obj = light
示例#19
0
def dovado(
    ctx: typer.Context,
    # Arguments
    # file_path is used through the context in cli_utility during parameters validation
    # and is then passed through context
    # until it reaches this method where it is extracted and used as parsed_src
    file_path: Path = typer.Option(  # pylint: disable=unused-argument
        ...,
        exists=True,
        file_okay=True,
        readable=True,
        resolve_path=True,
        help=
        ("path of the rtl file containing the top level entity, please check the documentation"
         + " for the directory structure your RTL project should comply with"),
    ),
    # Required Cli options
    board: str = typer.Option(
        ...,
        callback=validate_board,
        help="Part name for synthesis/implementation, inserting the wrong one"
        +
        " will get an error message with all the parts available with your Vivado installation",
    ),
    parameters: List[str] = typer.Option(
        ...,
        callback=validate_parameters,
        help=
        "parameters to use for point/space exploration, only integer and integer subtypes are supported",
    ),
    clock_port: str = typer.Option(
        ...,
        callback=validate_clock_port,
        help="clock port name of the top module/entity",
    ),
    # Optional Cli options
    implementation: bool = typer.Option(
        False,
        help=
        "flag to set point/space exploration to stop at implementation instead of synthesis",
    ),
    incremental: bool = typer.Option(
        False,
        help=
        "flag to choose whether to choose incrementaly synthesis/implementation",
    ),
    directives: Tuple[str, str, str] = typer.Option(
        default=(
            "runtimeoptimized",
            "RuntimeOptimized",
            "RuntimeOptimized",
        ),  # capitalization is necessary to comply with vivado directives specification
        callback=validate_directives,
        help="directives to pass respectively to synthesis, place and route",
    ),
    target_clock: float = typer.Option(
        default=1000,
        callback=validate_target_clock,
        help="target clock (Mhz) on which the worst negative slack is computed,"
        +
        "make sure this is sufficiently large to never be reached by your design",
    ),
    metrics: Optional[List[int]] = typer.Option(
        None,
        callback=validate_int_metrics,
        help="list of integers representing selected metrics, " +
        "wait for first synthesis/implementation if you do not know the mapping",
    ),
):  # pylint: disable=too-many-arguments
    # pylint: disable=too-many-locals
    config = Configuration()
    Path(str(config.get_config("WORK_DIR"))).mkdir(parents=True, exist_ok=True)

    parsed_src = ctx.obj
    project_path = parsed_src.get_root_folder()

    if implementation:
        stop_step = StopStep.IMPLEMENTATION
    else:
        stop_step = StopStep.SYNTHESIS
    if incremental:
        incremental_mode = IsIncremental(True, True)
    else:
        incremental_mode = IsIncremental(False, False)

    XdcFrameHandler(
        str(config.get_config("PLACEHOLDER")),
        str(config.get_config("XDC_DIR")) +
        str(config.get_config("CONSTRAINT_FRAME")),
        1000 / target_clock,
        str(config.get_config("WORK_DIR")) +
        str(config.get_config("CONSTRAINT")),
    ).fill()

    tcl_handler = TclFrameHandler(
        config,
        parsed_src,
        str(project_path),
        board,
        directives[0],
        incremental_mode,
        stop_step,
        directives[1],
        directives[2],
    )
    tcl_handler.fill()

    box_handler = HdlBoxFrameHandler(
        str(config.get_config("PLACEHOLDER")),
        str(config.get_config("VHDL_DIR")) +
        str(config.get_config("VHDL_BOX_FRAME"))
        if parsed_src.get_hdl() is RTL.VHDL else
        str(config.get_config("VERILOG_DIR")) +
        str(config.get_config("VERILOG_BOX_FRAME")),
        parsed_src.get_selected_entity().get_name(),
        parsed_src.get_ports(),
        parsed_src.get_port(clock_port),
        str(config.get_config("WORK_DIR")) +
        str(config.get_config("VHDL_BOX")) if parsed_src.get_hdl() is RTL.VHDL
        else str(config.get_config("WORK_DIR")) +
        str(config.get_config("VERILOG_BOX")),
        parsed_src.get_hdl(),
        parsed_src.get_folder(),
    )

    point_evaluator = DesignPointEvaluator(
        config,
        parsed_src,
        box_handler,
        tcl_handler,
        target_clock,
        incremental_mode,
        stop_step,
        list(parameters),
        metrics,
    )
    ctx.obj = {
        "parameters": parameters,
        "point_evaluator": point_evaluator,
        "config": config,
    }