Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions cli/__version__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import os
import re
from importlib.metadata import PackageNotFoundError, version as pkg_version


APP_NAME = "101-linux"
PACKAGE_NAME = "linux-commands-cli"


def _discover_package_version() -> str:
"""Discover version from installed package or local setup.py when running from source.

- Prefer the installed distribution version (if available)
- Fallback to parsing version from cli/setup.py (source checkout)
- Lastly, fallback to "0.0.0" if nothing else is found
"""
try:
return pkg_version(PACKAGE_NAME)
except PackageNotFoundError:
pass

setup_path = os.path.join(os.path.dirname(__file__), "..", "setup.py")
if os.path.exists(setup_path):
try:
with open(setup_path, "r", encoding="utf-8") as f:
content = f.read()
match = re.search(r"version\s*=\s*[\"'](.*?)[\"']", content)
if match:
return match.group(1)
except (OSError, IOError, UnicodeDecodeError):
pass

return "0.0.0"


__version__ = _discover_package_version()


def get_version_string() -> str:
return f"{APP_NAME} v{__version__}"


23 changes: 23 additions & 0 deletions cli/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,31 @@
import typer

from commands import hello
from __version__ import get_version_string

app = typer.Typer(help="101 Linux Commands CLI 🚀")


def _version_callback(value: bool):
if value:
typer.echo(get_version_string())
raise typer.Exit()


@app.callback()
def main(
version: bool = typer.Option(
False,
"--version",
help="Show the application version and exit.",
is_eager=True,
callback=_version_callback,
)
):
"""Main entrypoint for global options."""
return

# Register subcommands
app.add_typer(hello.app, name="hello")


Expand Down
16 changes: 16 additions & 0 deletions cli/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
import subprocess
import sys

sys.path.insert(0, os.path.dirname(__file__))
from __version__ import get_version_string


def test_cli_help():
"""Test that the CLI shows help."""
Expand Down Expand Up @@ -58,6 +61,19 @@ def test_hello_help():
assert "Hello command group" in result.stdout


def test_global_version_flag():
"""Test the global --version flag prints version and exits."""
result = subprocess.run(
[sys.executable, "cli.py", "--version"],
capture_output=True,
text=True,
cwd=os.path.dirname(__file__),
)
assert result.returncode == 0
expected = get_version_string()
assert result.stdout.strip() == expected


if __name__ == "__main__":
test_cli_help()
test_hello_command()
Expand Down
Loading