tiangolo / typer

Typer, build great CLIs. Easy to code. Based on Python type hints.

Home Page:https://typer.tiangolo.com/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Feature: Get the program version from toml file

qequ opened this issue · comments

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn't find it.
  • I searched the Typer documentation, with the integrated search.
  • I already searched in Google "How to X in Typer" and didn't find any information.
  • I already read and followed all the tutorial in the docs and didn't find an answer.
  • I already checked if it is not related to Typer but to Click.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

from typing import Optional

import typer

__version__ = "0.1.0"


def version_callback(value: bool):
    if value:
        print(f"Version: {__version__}")
        raise typer.Exit()


def name_callback(name: str):
    if name != "Camila":
        raise typer.BadParameter("Only Camila is allowed")


def main(
    name: str = typer.Option(..., callback=name_callback),
    version: Optional[bool] = typer.Option(
        None, "--version", callback=version_callback
    ),
):
    print(f"Hello {name}")


if __name__ == "__main__":
    typer.run(main)

Description

Being able to get the version of the program directly from the toml file instead of having a __version__ variable

Wanted Solution

a builtin function that parses the toml file looking for the version variable

Wanted Code

import typer

def version_callback(value: bool):
    if value:
        print(f"Version: {typer.get_toml_version()}")
        raise typer.Exit()


def name_callback(name: str):
    if name != "Camila":
        raise typer.BadParameter("Only Camila is allowed")


def main(
    name: str = typer.Option(..., callback=name_callback),
    version: Optional[bool] = typer.Option(
        None, "--version", callback=version_callback
    ),
):
    print(f"Hello {name}")


if __name__ == "__main__":
    typer.run(main)

Alternatives

No response

Operating System

Linux

Operating System Details

No response

Typer Version

0.6.1

Python Version

Python 3.8.10

Additional Context

No response

from importlib.metadata import version
print(version('<distribution-name>'))

I just found out that click offers version_option annotation, that behind the scenes uses a callback.
When I add it to my main click group, it works as expected: if --version is passed, it prints the version and exits, otherwise the program expects a subcommand and prints help if it's missing.

With typer, I can add a callback, but it complains about missing command. If I add invoke_without_command then it doesn't expect a subcommand

Is there a way to replicate click's version_option with typer?

Thanks for the help here @rafalkrupinski ! 👏 🙇

Thanks for reporting back and closing the issue @qequ 👍