Skip to content
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
215 changes: 215 additions & 0 deletions docs/assets/reviews/style-baseline.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
6 changes: 4 additions & 2 deletions pythonlings/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@

from textual.app import App

from pythonlings.core.manifest import Manifest, load as load_manifest
from pythonlings.core.state import State, load as load_state, next_pending
from pythonlings.core.manifest import Manifest
from pythonlings.core.manifest import load as load_manifest
from pythonlings.core.state import State, next_pending
from pythonlings.core.state import load as load_state
from pythonlings.screens.topic_picker import TopicPickerScreen
from pythonlings.screens.track import TrackScreen

Expand Down
82 changes: 61 additions & 21 deletions pythonlings/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,29 @@

import argparse
import sys
from importlib.metadata import PackageNotFoundError, version as _package_version
from importlib.metadata import PackageNotFoundError
from importlib.metadata import version as _package_version
from pathlib import Path

from pythonlings.core.workspace import default_workspace_root

try:
__version__ = _package_version("pythonlings")
except PackageNotFoundError: # running from a source checkout without an install
except (
PackageNotFoundError
): # running from a source checkout without an install
__version__ = "0.0.0+unknown"


# Status glyphs, with ASCII stand-ins for consoles whose encoding cannot
# represent them (a Windows code page, or LC_ALL=C). The fallbacks stay one
# column wide so aligned output keeps its shape.
_ASCII_FALLBACK = {"\u2713": "+", "\u2717": "x", "\u25cf": ">", "\U0001f512": "-"}
_ASCII_FALLBACK = {
"\u2713": "+",
"\u2717": "x",
"\u25cf": ">",
"\U0001f512": "-",
}


def _encodable(stream: object, text: str) -> bool:
Expand All @@ -39,7 +47,7 @@ def _symbol(stream: object, glyph: str) -> str:


def _write(stream, text: str) -> None:
"""Write captured output, degrading characters the encoding cannot represent.
"""Write output, replacing characters the encoding cannot represent.

Check files print their own status line (`print("variables1 \u2713")`), so
curriculum output reaches us containing glyphs a strict-ASCII console
Expand All @@ -49,14 +57,20 @@ def _write(stream, text: str) -> None:
stream.write(text)
except UnicodeEncodeError:
encoding = getattr(stream, "encoding", None) or "ascii"
stream.write(text.encode(encoding, "replace").decode(encoding, "replace"))
stream.write(
text.encode(encoding, "replace").decode(encoding, "replace")
)


def _build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(prog="pythonlings")
parser.add_argument("--version", action="version", version=f"pythonlings {__version__}")
parser.add_argument(
"--debug", action="store_true", help="Write debug output to .pythonlings_debug.log."
"--version", action="version", version=f"pythonlings {__version__}"
)
parser.add_argument(
"--debug",
action="store_true",
help="Write debug output to .pythonlings_debug.log.",
)
parser.add_argument(
"--root",
Expand All @@ -69,10 +83,14 @@ def _build_parser() -> argparse.ArgumentParser:
p_init = sub.add_parser("init", help="Create a pythonlings workspace.")
p_init.add_argument("--path", type=Path, default=default_workspace_root())
p_init.add_argument(
"--force", action="store_true", help="Overwrite managed workspace files."
"--force",
action="store_true",
help="Overwrite managed workspace files.",
)

p_update = sub.add_parser("update", help="Update an existing pythonlings workspace.")
p_update = sub.add_parser(
"update", help="Update an existing pythonlings workspace."
)
p_update.add_argument("--path", type=Path, default=None)

sub.add_parser("watch", help="Launch the TUI in watch mode (default).")
Expand All @@ -81,7 +99,9 @@ def _build_parser() -> argparse.ArgumentParser:
p_run = sub.add_parser("run", help="Run a single exercise.")
p_run.add_argument("name")

p_dry_run = sub.add_parser("dry-run", help="Run one exercise non-interactively.")
p_dry_run = sub.add_parser(
"dry-run", help="Run one exercise non-interactively."
)
p_dry_run.add_argument("name")

p_solution = sub.add_parser(
Expand All @@ -92,15 +112,23 @@ def _build_parser() -> argparse.ArgumentParser:
p_hint = sub.add_parser("hint", help="Print the hint for an exercise.")
p_hint.add_argument("name")

p_list = sub.add_parser("list", help="List topics, or one topic's exercises.")
p_list.add_argument("topic", nargs="?", help="Show exercises of this topic.")
p_list = sub.add_parser(
"list", help="List topics, or one topic's exercises."
)
p_list.add_argument(
"topic", nargs="?", help="Show exercises of this topic."
)

p_start = sub.add_parser("start", help="Launch the TUI on a topic's track.")
p_start.add_argument("topic")

p_reset = sub.add_parser("reset", help="Restore an exercise from its snapshot.")
p_reset = sub.add_parser(
"reset", help="Restore an exercise from its snapshot."
)
p_reset.add_argument("name")
p_reset.add_argument("--yes", action="store_true", help="Skip the confirmation prompt.")
p_reset.add_argument(
"--yes", action="store_true", help="Skip the confirmation prompt."
)

p_verify = sub.add_parser(
"verify", help="Run every exercise, or just one topic's."
Expand Down Expand Up @@ -190,7 +218,8 @@ def _cmd_verify(root: Path, topic: str | None) -> int:

def _cmd_list(root: Path, topic: str | None) -> int:
from pythonlings.core.manifest import load as load_manifest
from pythonlings.core.state import load as load_state, next_pending
from pythonlings.core.state import load as load_state
from pythonlings.core.state import next_pending

manifest = load_manifest(root)
state = load_state(root)
Expand All @@ -199,8 +228,10 @@ def _cmd_list(root: Path, topic: str | None) -> int:
for name in manifest.topics():
exs = manifest.exercises_in(name)
done = sum(1 for ex in exs if ex.name in state.completed)
mark = _symbol(sys.stdout, "✓") if done == len(exs) else (
_symbol(sys.stdout, "●") if done else " "
mark = (
_symbol(sys.stdout, "✓")
if done == len(exs)
else (_symbol(sys.stdout, "●") if done else " ")
)
print(f" {mark} {name} {done}/{len(exs)}")
return 0
Expand Down Expand Up @@ -252,13 +283,16 @@ def _cmd_run(root: Path, name: str) -> int:
if result.stderr:
_write(sys.stderr, result.stderr)
if result.timed_out:
sys.stderr.write(f"pythonlings: {name} timed out after {result.duration_s:.1f}s\n")
sys.stderr.write(
f"pythonlings: {name} timed out after {result.duration_s:.1f}s\n"
)
return 1
if result.exit_code != 0:
return 1
if ex.is_pending():
sys.stderr.write(
f"pythonlings: tests pass but the '# I AM NOT DONE' marker is still in {name}.\n"
"pythonlings: tests pass but the '# I AM NOT DONE' marker "
f"is still in {name}.\n"
)
return 1
return 0
Expand Down Expand Up @@ -290,7 +324,8 @@ def _cmd_solution(root: Path, name: str) -> int:
def _cmd_reset(root: Path, name: str, yes: bool) -> int:
from pythonlings.core.manifest import load as load_manifest
from pythonlings.core.reset import ResetError, restore
from pythonlings.core.state import load as load_state, save as save_state
from pythonlings.core.state import load as load_state
from pythonlings.core.state import save as save_state

manifest = load_manifest(root)
try:
Expand Down Expand Up @@ -369,7 +404,9 @@ def main(argv: list[str] | None = None) -> int:
)
except (OSError, RuntimeError) as exc:
if args.command == "doctor":
unresolved = args.root if args.root is not None else Path(".")
unresolved = (
args.root if args.root is not None else Path(".")
)
return _cmd_doctor(unresolved, resolution_error=exc)
raise
root = resolved.root
Expand Down Expand Up @@ -422,9 +459,11 @@ def main(argv: list[str] | None = None) -> int:
start_topic = getattr(args, "topic", None)
if start_topic is not None:
from pythonlings.core.manifest import load as load_manifest

if _resolve_topic(load_manifest(root), start_topic) is None:
return 2
from pythonlings.app import run_tui # lazy: Textual is heavy

return run_tui(
root,
start_topic,
Expand All @@ -437,6 +476,7 @@ def main(argv: list[str] | None = None) -> int:
except Exception as e:
# Manifest errors and other startup failures use exit code 2.
from pythonlings.core.manifest import ManifestError

if isinstance(e, ManifestError):
sys.stderr.write(f"pythonlings: {e}\n")
return 2
Expand Down
7 changes: 5 additions & 2 deletions pythonlings/core/curriculum.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,9 @@ def _write_workspace_gitignore(root: Path) -> None:
existing = ""

existing_lines = set(existing.splitlines())
missing_lines = [line for line in GITIGNORE_LINES if line not in existing_lines]
missing_lines = [
line for line in GITIGNORE_LINES if line not in existing_lines
]
if not missing_lines:
return

Expand All @@ -95,7 +97,8 @@ def init_workspace(path: Path, *, force: bool = False) -> Path:
if path.exists() and any(path.iterdir()) and not force:
raise WorkspaceError(
f"{path} isn't empty and isn't a pythonlings workspace. "
"Pick another location with --path <dir>, or --force to set up here anyway."
"Pick another location with --path <dir>, "
"or --force to set up here anyway."
)
src_root = source_root().resolve()
if path == src_root:
Expand Down
4 changes: 3 additions & 1 deletion pythonlings/core/docs.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,9 @@ def load_snippet(topic: str, source_url: str = "") -> DocSnippet | None:
def _load_index() -> dict[str, Any] | None:
try:
docs_root = resources.files("pythonlings.docs")
return json.loads((docs_root / "index.json").read_text(encoding="utf-8"))
return json.loads(
(docs_root / "index.json").read_text(encoding="utf-8")
)
except (FileNotFoundError, json.JSONDecodeError, ModuleNotFoundError):
return None

Expand Down
37 changes: 27 additions & 10 deletions pythonlings/core/doctor.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# pythonlings/core/doctor.py
from __future__ import annotations

import errno
Expand Down Expand Up @@ -67,7 +68,8 @@ def run_diagnostics(
CheckResult(
"Workspace",
CheckStatus.FAILURE,
f"could not resolve {display_root}: {exc}; check the path and symlinks",
f"could not resolve {display_root}: {exc}; "
"check the path and symlinks",
)
)
return DoctorReport(root=display_root, checks=tuple(checks))
Expand Down Expand Up @@ -152,7 +154,8 @@ def _check_workspace(root: Path) -> CheckResult:
"Workspace",
CheckStatus.FAILURE,
f"missing or invalid required paths: {', '.join(invalid)}; "
"run `pythonlings update --path <workspace>` or initialize a new workspace",
"run `pythonlings update --path <workspace>` "
"or initialize a new workspace",
)
return CheckResult("Workspace", CheckStatus.OK, str(root))

Expand Down Expand Up @@ -238,10 +241,13 @@ def _check_state(root: Path) -> CheckResult:
return CheckResult(
"Progress state",
CheckStatus.WARNING,
f"state.json is a broken symlink: {exc}; replace or remove the link",
f"state.json is a broken symlink: {exc}; "
"replace or remove the link",
)
if not path.exists():
return CheckResult("Progress state", CheckStatus.OK, "no progress file yet")
return CheckResult(
"Progress state", CheckStatus.OK, "no progress file yet"
)
if not path.is_file():
return CheckResult(
"Progress state",
Expand All @@ -255,14 +261,16 @@ def _check_state(root: Path) -> CheckResult:
return CheckResult(
"Progress state",
CheckStatus.WARNING,
f"state.json is unreadable: {exc}; back it up before starting Pythonlings",
f"state.json is unreadable: {exc}; "
"back it up before starting Pythonlings",
)

if not isinstance(data, dict):
return CheckResult(
"Progress state",
CheckStatus.WARNING,
"state.json must contain an object; back it up before starting Pythonlings",
"state.json must contain an object; "
"back it up before starting Pythonlings",
)
if data.get("format_version") != FORMAT_VERSION:
return CheckResult(
Expand All @@ -283,7 +291,9 @@ def _check_state(root: Path) -> CheckResult:
"back up state.json before starting Pythonlings",
)
return CheckResult(
"Progress state", CheckStatus.OK, f"readable ({len(completed)} completed)"
"Progress state",
CheckStatus.OK,
f"readable ({len(completed)} completed)",
)


Expand Down Expand Up @@ -333,7 +343,8 @@ def _check_docs(manifest: Manifest | None) -> CheckResult:
return CheckResult(
"Bundled docs",
CheckStatus.OK,
"documentation index is readable; topic coverage was not checked",
"documentation index is readable; "
"topic coverage was not checked",
)

missing: list[str] = []
Expand Down Expand Up @@ -383,13 +394,19 @@ def _manifest_validation_error(manifest: Manifest) -> str | None:

for exercise in manifest.exercises:
if not isinstance(exercise.name, str) or not exercise.name:
return f"exercise name must be a non-empty string, got {exercise.name!r}"
return (
"exercise name must be a non-empty string, "
f"got {exercise.name!r}"
)
if not isinstance(exercise.hint, str):
return f"hint for {exercise.name!r} must be a string"
if not isinstance(exercise.docs, str):
return f"docs for {exercise.name!r} must be a string"
if not exercise.path.is_file():
return f"exercise path is not a file: {exercise.rel_path or exercise.path}"
return (
"exercise path is not a file: "
f"{exercise.rel_path or exercise.path}"
)
if not exercise.check_path.is_file():
return (
"check path is not a file: "
Expand Down
Loading
Loading