Skip to content
Open
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
4 changes: 2 additions & 2 deletions Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -147,12 +147,12 @@ path.
| Key | Action |
|---|---|
| `F1` | Toggle hint |
| `F2` | Reset the current exercise |
| `F2` | Ask to reset the current exercise (`Y` resets, `N` or `Esc` cancels) |
| `F3` | Toggle the exercise list |
| `F4` | Return to the topic picker |
| `F5` | Show the local Python reference |
| `O` | Open official docs from the reference window |
| `Esc` | Close docs, or quit from main screens |
| `Esc` | Close docs, cancel reset, or quit from main screens |
| `Ctrl+Q` | Quit |

![Local docs reference](https://raw.githubusercontent.com/abhiksark/pythonlings/v0.4.4/docs/assets/screenshots/docs-reference.png)
Expand Down
4 changes: 2 additions & 2 deletions docs-site/interface.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,10 @@ exercise. Press `O` from that window to open the official Python docs page.
| Key | Action |
|---|---|
| `F1` | Toggle hint |
| `F2` | Reset the current exercise |
| `F2` | Ask to reset the current exercise (`Y` resets, `N` or `Esc` cancels) |
| `F3` | Toggle the exercise list |
| `F4` | Return to the topic picker |
| `F5` | Show the local Python reference |
| `O` | Open official docs from the reference window |
| `Esc` | Close docs, or quit from main screens |
| `Esc` | Close docs, cancel reset, or quit from main screens |
| `Ctrl+Q` | Quit |
35 changes: 32 additions & 3 deletions pythonlings/core/reset.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from __future__ import annotations

import shutil
import tempfile
from pathlib import Path

from pythonlings.core.exercise import Exercise
Expand Down Expand Up @@ -41,9 +42,37 @@ def snapshot(root: Path, exercise: Exercise) -> None:
def restore(root: Path, exercise: Exercise) -> None:
"""Overwrite the exercise file with its pristine original."""
snap = _original_path(root, exercise)
if not snap.exists():
try:
contents = snap.read_bytes()
except FileNotFoundError as exc:
raise ResetError(
f"no snapshot for {exercise.name!r}. "
"Run 'pythonlings update' first."
)
shutil.copy2(snap, exercise.path)
) from exc
except OSError as exc:
raise ResetError(
f"could not read the snapshot for {exercise.name!r}: {exc}"
) from exc
try:
contents.decode("utf-8")
except UnicodeDecodeError as exc:
raise ResetError(
f"snapshot for {exercise.name!r} is not valid UTF-8. "
"Check .pythonlings/originals before retrying."
) from exc

try:
# Stage the replacement next to the exercise so a failed copy leaves
# the learner's file intact. Follow an in-workspace exercise symlink
# as the previous copy did.
destination = exercise.path.resolve()
with tempfile.TemporaryDirectory(dir=destination.parent) as staging:
replacement = Path(staging) / destination.name
replacement.write_bytes(contents)
shutil.copystat(snap, replacement)
replacement.replace(destination)
except (OSError, RuntimeError) as exc:
raise ResetError(
f"could not restore {exercise.name!r}. "
f"Check that its file is writable: {exc}"
) from exc
22 changes: 22 additions & 0 deletions pythonlings/pythonlings.tcss
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,28 @@ DocsScreen {
color: $text;
}

ResetConfirmScreen {
align: center middle;
}

#reset-window {
width: 90%;
max-width: 60;
height: auto;
padding: 1 2;
border: heavy $primary;
background: $surface;
color: $text;
}

#reset-message {
margin: 1 0;
}

#reset-keys {
color: $text-muted;
}

WelcomeScreen {
align: center middle;
}
Expand Down
39 changes: 39 additions & 0 deletions pythonlings/screens/reset.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# pythonlings/screens/reset.py
from __future__ import annotations

from textual.app import ComposeResult
from textual.binding import Binding
from textual.containers import Vertical
from textual.screen import ModalScreen
from textual.widgets import Static


class ResetConfirmScreen(ModalScreen[bool]):
"""Ask before overwriting the current exercise with its snapshot."""

BINDINGS = [
Binding("y", "confirm", "Reset"),
Binding("n,escape", "cancel", "Cancel", priority=True),
]

def __init__(self, exercise_name: str) -> None:
super().__init__()
self.exercise_name = exercise_name

def compose(self) -> ComposeResult:
yield Vertical(
Static("[bold]Reset exercise?[/bold]"),
Static(
f"Replace edits to {self.exercise_name} with the original?",
markup=False,
id="reset-message",
),
Static("Y Reset N / Esc Cancel", id="reset-keys"),
id="reset-window",
)

def action_confirm(self) -> None:
self.dismiss(True)

def action_cancel(self) -> None:
self.dismiss(False)
51 changes: 43 additions & 8 deletions pythonlings/screens/track.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# pythonlings/screens/track.py
from __future__ import annotations

from rich.markup import escape
from textual import events
from textual.app import ComposeResult
from textual.binding import Binding
Expand All @@ -10,9 +11,11 @@
from textual.widgets import Footer, Header, TextArea

from pythonlings.core.exercise import Exercise, RunResult
from pythonlings.core.reset import ResetError, restore
from pythonlings.core.runner import run as run_exercise
from pythonlings.core.state import completed_count, next_pending
from pythonlings.core.state import save as save_state
from pythonlings.screens.reset import ResetConfirmScreen
from pythonlings.widgets.editor_pane import EditorPane
from pythonlings.widgets.exercise_tree import ExerciseTree
from pythonlings.widgets.output_panel import OutputPanel
Expand Down Expand Up @@ -87,6 +90,10 @@ def __init__(self, topic: str, start_exercise: str | None = None) -> None:
self._persisted_text = ""
self._run_id = 0
self._failure_counts: dict[str, int] = {}
self._confirming_reset = False
self._deferred_result: tuple[Exercise, RunResult, str, int] | None = (
None
)
self.current: str | None = None

def compose(self) -> ComposeResult:
Expand Down Expand Up @@ -183,7 +190,9 @@ def on_text_area_changed(self, event: TextArea.Changed) -> None:
if self._save_timer is not None:
self._save_timer.stop()
self._save_timer = self.set_timer(
_DEBOUNCE_SECONDS, self._flush_and_run
_DEBOUNCE_SECONDS,
self._flush_and_run,
pause=self._confirming_reset,
)

def _flush_and_run(self) -> None:
Expand Down Expand Up @@ -235,6 +244,9 @@ def _apply_result(
or self.query_one(EditorPane).text != checked_text
):
return
if self._confirming_reset:
self._deferred_result = (exercise, result, checked_text, run_id)
return
if result.exit_code != 0 or result.timed_out:
self._failure_counts[exercise.name] = (
self._failure_counts.get(exercise.name, 0) + 1
Expand Down Expand Up @@ -300,6 +312,8 @@ def _stop_advance_timer(self) -> None:

def _tick_advance(self) -> None:
"""Decrement the countdown each second, firing the advance at zero."""
if self._confirming_reset:
return
self._advance_remaining -= 1
exercise, checked_text = self._advance_exercise, self._advance_text
if self._advance_remaining <= 0:
Expand Down Expand Up @@ -337,16 +351,37 @@ def action_toggle_hint(self) -> None:
)

def action_reset(self) -> None:
from pythonlings.core.reset import restore

if self.current is None:
return
# Keep queued edits and checks from changing the exercise mid-prompt.
self._confirming_reset = True
if self._save_timer is not None:
self._save_timer.stop()
self._save_timer = None
restore(self.app.root, self._exercise(self.current))
self._load_current()
self._run_current()
self._save_timer.pause()
self.app.push_screen(
ResetConfirmScreen(self.current), self._finish_reset
)

def _finish_reset(self, confirmed: bool | None) -> None:
self._confirming_reset = False
deferred, self._deferred_result = self._deferred_result, None
if confirmed and self.current is not None:
try:
restore(self.app.root, self._exercise(self.current))
except ResetError as exc:
self.notify(
escape(str(exc)),
title="Reset failed",
severity="error",
timeout=8,
)
else:
self._load_current()
self._run_current()
return
if self._save_timer is not None:
self._save_timer.resume()
if deferred is not None:
self._apply_result(*deferred)

def action_toggle_list(self) -> None:
tree = self.query_one(ExerciseTree)
Expand Down
Loading