Skip to content

Add some CLI functionality #48

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Apr 8, 2025
Merged
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
6 changes: 6 additions & 0 deletions ChangeLog.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@

- Added a system command for reversing the current sort order.
([#46](https://github.com/davep/peplum/pull/46))
- Added `--theme` as a command line switch.
([#48](https://github.com/davep/peplum/pull/48))
- Added `--sort-by` as a command line switch.
([#48](https://github.com/davep/peplum/pull/48))
- Added support for taking a PEP number on the command line and jumping to
it on startup. ([#48](https://github.com/davep/peplum/pull/48))

## v0.4.2

Expand Down
2 changes: 1 addition & 1 deletion src/peplum/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""Peplum -- The PEP lookup manager for your terminal."""
"""The PEP lookup manager for your terminal."""

##############################################################################
# Python imports.
Expand Down
85 changes: 84 additions & 1 deletion src/peplum/__main__.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,97 @@
"""Main entry point for the application."""

##############################################################################
# Python imports.
from argparse import ArgumentParser, Namespace
from inspect import cleandoc
from typing import get_args as get_literal_values

##############################################################################
# Local imports.
from . import __doc__, __version__
from .app import Peplum
from .app.data import SortOrder


##############################################################################
def get_args() -> Namespace:
"""Get the command line arguments.

Returns:
The arguments.
"""

# Build the parser.
parser = ArgumentParser(
prog="peplum",
description=__doc__,
epilog=f"v{__version__}",
)

# Add --version
parser.add_argument(
"-v",
"--version",
help="Show version information",
action="version",
version=f"%(prog)s v{__version__}",
)

# Add --license
parser.add_argument(
"--license",
"--licence",
help="Show license information",
action="store_true",
)

# Add --sort
parser.add_argument(
"-s",
"--sort-by",
help="Set the sort order for the PEPs; prefix with '~' for reverse order",
choices=(
*get_literal_values(SortOrder),
*(f"~{order}" for order in get_literal_values(SortOrder)),
),
)

# Add --theme
parser.add_argument(
"-t",
"--theme",
help="Set the theme for the application (set to ? to list available themes)",
)

# The remainder is going to be the initial command.
parser.add_argument(
"pep",
help="A PEP to highlight",
nargs="?",
)

# Finally, parse the command line.
return parser.parse_args()


##############################################################################
def show_themes() -> None:
"""Show the available themes."""
for theme in sorted(Peplum(Namespace(theme=None)).available_themes):
if theme != "textual-ansi":
print(theme)


##############################################################################
def main() -> None:
"""Main entry point."""
Peplum().run()
args = get_args()
if args.license:
print(cleandoc(Peplum.HELP_LICENSE))
elif args.theme == "?":
show_themes()
else:
Peplum(args).run()


##############################################################################
Expand Down
2 changes: 2 additions & 0 deletions src/peplum/app/data/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
PEPCount,
PEPs,
PythonVersionCount,
SortOrder,
StatusCount,
TypeCount,
WithAuthor,
Expand Down Expand Up @@ -44,6 +45,7 @@
"PostHistory",
"PythonVersionCount",
"save_configuration",
"SortOrder",
"StatusCount",
"TypeCount",
"update_configuration",
Expand Down
26 changes: 20 additions & 6 deletions src/peplum/app/peplum.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
"""Provides the main application class."""

##############################################################################
# Python imports.
from argparse import Namespace

##############################################################################
# Textual imports.
from textual.app import InvalidThemeError
Expand Down Expand Up @@ -48,13 +52,19 @@ class Peplum(EnhancedApp[None]):

COMMANDS = set()

def __init__(self) -> None:
"""Initialise the application."""
def __init__(self, arguments: Namespace) -> None:
"""Initialise the application.

Args:
The command line arguments passed to the application.
"""
self._arguments = arguments
"""The command line arguments passed to the application."""
super().__init__()
configuration = load_configuration()
if configuration.theme is not None:
try:
self.theme = configuration.theme
self.theme = arguments.theme or configuration.theme
except InvalidThemeError:
pass

Expand All @@ -63,9 +73,13 @@ def watch_theme(self) -> None:
with update_configuration() as config:
config.theme = self.theme

def on_mount(self) -> None:
"""Display the main screen."""
self.push_screen(Main())
def get_default_screen(self) -> Main:
"""Get the default screen for the application.

Returns:
The main screen.
"""
return Main(self._arguments)


### peplum.py ends here
48 changes: 47 additions & 1 deletion src/peplum/app/screens/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

##############################################################################
# Python imports.
from argparse import Namespace
from dataclasses import dataclass
from json import dumps, loads
from webbrowser import open as visit_url
Expand Down Expand Up @@ -189,6 +190,18 @@ class Main(EnhancedScreen[None]):
notes: var[Notes] = var(Notes)
"""The user's notes about PEPs."""

def __init__(self, arguments: Namespace) -> None:
"""Initialise the main screen.

Args:
arguments: The arguments passed to the application on the command line.
"""
self._arguments = arguments
"""The arguments passed on the command line."""
super().__init__()
self._jump_to_on_load: str | None = self._arguments.pep
"""A PEP to jump to once the display is loaded."""

def compose(self) -> ComposeResult:
"""Compose the content of the main screen."""
yield Header()
Expand Down Expand Up @@ -243,9 +256,31 @@ async def download_pep_data(self) -> None:
self.notify("Fresh PEP data downloaded from the PEP API")
self.load_pep_data()

@staticmethod
def _extract_pep(pep: str) -> int | None:
"""Try and extract a PEP number from a string.

Args:
pep: A string that should contain a PEP number.

Returns:
A PEP number or [`None`][None] if one could not be found.

Notes:
The likes of `2342` and `PEP2342` are handled.
"""
try:
return int(pep.strip().upper().removeprefix("PEP"))
except ValueError:
return None

@on(Loaded)
def load_fresh_peps(self, message: Loaded) -> None:
"""React to a fresh set of PEPs being made available."""
"""React to a fresh set of PEPs being made available.

Args:
message: The message letting us know we have fresh PEPs.
"""
if len(message.peps.authors) == 0:
self.notify(
"You likely have a cached copy of the older version of the PEP data; a redownload is recommended.",
Expand All @@ -256,9 +291,20 @@ def load_fresh_peps(self, message: Loaded) -> None:
self.all_peps = message.peps.sorted_by(config.peps_sort_order).reversed(
config.peps_sort_reversed
)
if self._jump_to_on_load is not None:
if (pep := self._extract_pep(self._jump_to_on_load)) is not None:
self.post_message(GotoPEP(pep))
self._jump_to_on_load = None

def on_mount(self) -> None:
"""Configure the application once the DOM is mounted."""
# The caller has passed sorting preferences on the command line;
# let's get them into the configuration before anything else kicks
# off.
if self._arguments.sort_by is not None:
with update_configuration() as config:
config.peps_sort_reversed = self._arguments.sort_by[0] == "~"
config.peps_sort_order = self._arguments.sort_by.removeprefix("~")
self.set_class(load_configuration().details_visble, "details-visible")
# On startup, if we've got local PEP data...
if pep_data().exists():
Expand Down
Loading