myshell-py 0.2.0__tar.gz → 0.3.2__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {myshell_py-0.2.0 → myshell_py-0.3.2}/PKG-INFO +13 -2
- {myshell_py-0.2.0 → myshell_py-0.3.2}/README.md +12 -1
- {myshell_py-0.2.0 → myshell_py-0.3.2}/myshell/cli.py +8 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/myshell/completion.py +3 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/myshell/editor.py +7 -3
- {myshell_py-0.2.0 → myshell_py-0.3.2}/myshell/guide.py +36 -28
- {myshell_py-0.2.0 → myshell_py-0.3.2}/myshell/more_builtins.py +43 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/myshell/prompt.py +11 -6
- myshell_py-0.3.2/myshell/theme.py +203 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/pyproject.toml +2 -1
- myshell_py-0.3.2/requirements.txt +4 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/tests/conftest.py +10 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/tests/test_editor.py +1 -1
- {myshell_py-0.2.0 → myshell_py-0.3.2}/tests/test_guide.py +1 -1
- myshell_py-0.3.2/tests/test_theme.py +272 -0
- myshell_py-0.2.0/requirements.txt +0 -16
- {myshell_py-0.2.0 → myshell_py-0.3.2}/.gitignore +0 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/myshell/__init__.py +0 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/myshell/__main__.py +0 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/myshell/aliases.py +0 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/myshell/arith.py +0 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/myshell/builtins.py +0 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/myshell/compat.py +0 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/myshell/coreutils.py +0 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/myshell/errors.py +0 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/myshell/executor.py +0 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/myshell/expand.py +0 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/myshell/heredoc.py +0 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/myshell/highlight.py +0 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/myshell/history.py +0 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/myshell/jobs.py +0 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/myshell/lexer.py +0 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/myshell/parser.py +0 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/myshell/paths.py +0 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/myshell/progress.py +0 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/myshell/quiz.py +0 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/myshell/state.py +0 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/pytest.ini +0 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/shell.py +0 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/src/myshell/__init__.py +0 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/tests/test_aliases.py +0 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/tests/test_arith.py +0 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/tests/test_builtins.py +0 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/tests/test_cli.py +0 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/tests/test_completion.py +0 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/tests/test_coreutils.py +0 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/tests/test_expand.py +0 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/tests/test_expansion_e2e.py +0 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/tests/test_heredoc.py +0 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/tests/test_highlight.py +0 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/tests/test_history.py +0 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/tests/test_history_fallback.py +0 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/tests/test_if.py +0 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/tests/test_interactive.py +0 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/tests/test_jobs.py +0 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/tests/test_language.py +0 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/tests/test_lexer.py +0 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/tests/test_loops.py +0 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/tests/test_more_builtins.py +0 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/tests/test_parser.py +0 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/tests/test_pipelines.py +0 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/tests/test_prompt.py +0 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/tests/test_quiz_progress.py +0 -0
- {myshell_py-0.2.0 → myshell_py-0.3.2}/tests/test_redirects.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: myshell-py
|
|
3
|
-
Version: 0.2
|
|
3
|
+
Version: 0.3.2
|
|
4
4
|
Summary: A Unix-style shell written in Python, with a built-in guide.
|
|
5
5
|
License: MIT
|
|
6
6
|
Keywords: education,shell,terminal
|
|
@@ -20,7 +20,7 @@ A Unix-style shell written in Python. It runs on Linux and macOS with full job c
|
|
|
20
20
|
|
|
21
21
|
## Requirements
|
|
22
22
|
|
|
23
|
-
- Python 3.9 or newer. Tested on 3.9 and 3.13 on Linux, macOS and Windows
|
|
23
|
+
- Python 3.9 or newer. Tested on 3.9 and 3.13 on Linux, macOS and Windows.
|
|
24
24
|
- `prompt_toolkit` is optional. With it you get Ctrl+R history search, grey suggestions and syntax colors. Without it the shell uses plain `input()` and readline.
|
|
25
25
|
- pytest and pyflakes for development: `pip install -e ".[dev]"`
|
|
26
26
|
|
|
@@ -155,6 +155,16 @@ Pip is a small original character who lives in the shell.
|
|
|
155
155
|
|
|
156
156
|
The default prompt adds the branch in brackets inside a git repository.
|
|
157
157
|
|
|
158
|
+
### Themes
|
|
159
|
+
|
|
160
|
+
A theme sets the colors of the default prompt, the syntax colors in the editor and Pip. Every theme except `default` and `mono` also colors the text you type and the text commands print.
|
|
161
|
+
|
|
162
|
+
theme list the themes with a preview
|
|
163
|
+
theme ocean switch and remember (saved in ~/.myshell_theme)
|
|
164
|
+
theme reset back to the default
|
|
165
|
+
|
|
166
|
+
Themes: `default`, `ocean`, `forest`, `sunset`, `light` (for a white background) and `mono` (no colors). `MYSHELL_THEME=ocean` picks one at start and wins over the saved choice. A `PS1` you set yourself keeps its own colors, and `NO_COLOR` turns colors off.
|
|
167
|
+
|
|
158
168
|
Example `~/.myshellrc`:
|
|
159
169
|
|
|
160
170
|
PS1='\u@\h \W \$ '
|
|
@@ -180,6 +190,7 @@ Example `~/.myshellrc`:
|
|
|
180
190
|
| `progress.py` `quiz.py` | Pip's progress file and quiz questions |
|
|
181
191
|
| `completion.py` | tab completion |
|
|
182
192
|
| `prompt.py` | prompt escapes |
|
|
193
|
+
| `theme.py` | color themes |
|
|
183
194
|
| `guide.py` | Pip: lessons, hints, greeting |
|
|
184
195
|
| `state.py` | variables, aliases, history, status |
|
|
185
196
|
| `compat.py` | platform checks |
|
|
@@ -4,7 +4,7 @@ A Unix-style shell written in Python. It runs on Linux and macOS with full job c
|
|
|
4
4
|
|
|
5
5
|
## Requirements
|
|
6
6
|
|
|
7
|
-
- Python 3.9 or newer. Tested on 3.9 and 3.13 on Linux, macOS and Windows
|
|
7
|
+
- Python 3.9 or newer. Tested on 3.9 and 3.13 on Linux, macOS and Windows.
|
|
8
8
|
- `prompt_toolkit` is optional. With it you get Ctrl+R history search, grey suggestions and syntax colors. Without it the shell uses plain `input()` and readline.
|
|
9
9
|
- pytest and pyflakes for development: `pip install -e ".[dev]"`
|
|
10
10
|
|
|
@@ -139,6 +139,16 @@ Pip is a small original character who lives in the shell.
|
|
|
139
139
|
|
|
140
140
|
The default prompt adds the branch in brackets inside a git repository.
|
|
141
141
|
|
|
142
|
+
### Themes
|
|
143
|
+
|
|
144
|
+
A theme sets the colors of the default prompt, the syntax colors in the editor and Pip. Every theme except `default` and `mono` also colors the text you type and the text commands print.
|
|
145
|
+
|
|
146
|
+
theme list the themes with a preview
|
|
147
|
+
theme ocean switch and remember (saved in ~/.myshell_theme)
|
|
148
|
+
theme reset back to the default
|
|
149
|
+
|
|
150
|
+
Themes: `default`, `ocean`, `forest`, `sunset`, `light` (for a white background) and `mono` (no colors). `MYSHELL_THEME=ocean` picks one at start and wins over the saved choice. A `PS1` you set yourself keeps its own colors, and `NO_COLOR` turns colors off.
|
|
151
|
+
|
|
142
152
|
Example `~/.myshellrc`:
|
|
143
153
|
|
|
144
154
|
PS1='\u@\h \W \$ '
|
|
@@ -164,6 +174,7 @@ Example `~/.myshellrc`:
|
|
|
164
174
|
| `progress.py` `quiz.py` | Pip's progress file and quiz questions |
|
|
165
175
|
| `completion.py` | tab completion |
|
|
166
176
|
| `prompt.py` | prompt escapes |
|
|
177
|
+
| `theme.py` | color themes |
|
|
167
178
|
| `guide.py` | Pip: lessons, hints, greeting |
|
|
168
179
|
| `state.py` | variables, aliases, history, status |
|
|
169
180
|
| `compat.py` | platform checks |
|
|
@@ -16,6 +16,7 @@ from .errors import ShellError, ShellExit
|
|
|
16
16
|
from .executor import Executor
|
|
17
17
|
from .guide import greeting, guide_enabled, missing_hint, say, syntax_hint
|
|
18
18
|
from .editor import make_reader
|
|
19
|
+
from . import theme
|
|
19
20
|
from .prompt import build_continuation_prompt, build_prompt, slow_notice
|
|
20
21
|
from .state import ShellState
|
|
21
22
|
|
|
@@ -98,6 +99,10 @@ def run_interactive(state: ShellState) -> int:
|
|
|
98
99
|
except EOFError:
|
|
99
100
|
return None
|
|
100
101
|
state.missing_command = None
|
|
102
|
+
tint = theme.text_start() if interactive else ""
|
|
103
|
+
if tint:
|
|
104
|
+
sys.stdout.write(tint) # the theme's text color covers what the command prints
|
|
105
|
+
sys.stdout.flush()
|
|
101
106
|
started = time.monotonic()
|
|
102
107
|
try:
|
|
103
108
|
state.execute(line, read_more)
|
|
@@ -111,6 +116,9 @@ def run_interactive(state: ShellState) -> int:
|
|
|
111
116
|
except KeyboardInterrupt:
|
|
112
117
|
print()
|
|
113
118
|
state.last_duration = time.monotonic() - started
|
|
119
|
+
if tint:
|
|
120
|
+
sys.stdout.write("\x1b[0m")
|
|
121
|
+
sys.stdout.flush()
|
|
114
122
|
if interactive:
|
|
115
123
|
state.save_history() # saved after every line, so a killed shell loses nothing
|
|
116
124
|
if state.pending_traps:
|
|
@@ -44,6 +44,9 @@ class Completer:
|
|
|
44
44
|
if text.startswith("$"):
|
|
45
45
|
return self.variable_matches(text)
|
|
46
46
|
before = before.rstrip()
|
|
47
|
+
if before == "theme":
|
|
48
|
+
from . import theme
|
|
49
|
+
return sorted(n for n in theme.names() + ["reset"] if n.startswith(text))
|
|
47
50
|
at_command = (before == "" or (before.endswith(COMMAND_PREFIXES)
|
|
48
51
|
and not before.endswith(">")))
|
|
49
52
|
if at_command and "/" not in text and not text.startswith("~"):
|
|
@@ -9,7 +9,8 @@ from typing import Any, Callable, Dict, List, Optional, Tuple
|
|
|
9
9
|
|
|
10
10
|
from . import history
|
|
11
11
|
from .completion import complete_line
|
|
12
|
-
from .
|
|
12
|
+
from . import theme
|
|
13
|
+
from .highlight import tokenize_for_color
|
|
13
14
|
from .state import ShellState
|
|
14
15
|
|
|
15
16
|
SUGGESTION_STYLE = "fg:#888888"
|
|
@@ -70,7 +71,7 @@ def _build(state: ShellState, input: Any, output: Any) -> Any:
|
|
|
70
71
|
from prompt_toolkit.history import History
|
|
71
72
|
from prompt_toolkit.lexers import Lexer
|
|
72
73
|
from prompt_toolkit.shortcuts import CompleteStyle
|
|
73
|
-
from prompt_toolkit.styles import Style
|
|
74
|
+
from prompt_toolkit.styles import DynamicStyle, Style
|
|
74
75
|
|
|
75
76
|
class ShellHistory(History):
|
|
76
77
|
"""The shell's own history list, newest first. Lines are added by the shell."""
|
|
@@ -148,7 +149,10 @@ def _build(state: ShellState, input: Any, output: Any) -> Any:
|
|
|
148
149
|
|
|
149
150
|
bindings.add("right", filter=at_end_without_suggestion)(accept_now)
|
|
150
151
|
bindings.add("end", filter=at_end_without_suggestion)(accept_now)
|
|
151
|
-
|
|
152
|
+
def current_style() -> Any:
|
|
153
|
+
t = theme.active()
|
|
154
|
+
return Style.from_dict(dict(t.syntax, **{"auto-suggestion": t.suggestion or SUGGESTION_STYLE}))
|
|
155
|
+
style = DynamicStyle(current_style)
|
|
152
156
|
kwargs: Dict[str, Any] = {}
|
|
153
157
|
if input is not None:
|
|
154
158
|
kwargs["input"] = input
|
|
@@ -22,7 +22,7 @@ from dataclasses import dataclass, field
|
|
|
22
22
|
from pathlib import Path
|
|
23
23
|
from typing import Callable, List, Optional, TextIO
|
|
24
24
|
|
|
25
|
-
from . import compat, history, progress, quiz
|
|
25
|
+
from . import compat, history, progress, quiz, theme
|
|
26
26
|
from .state import ShellState
|
|
27
27
|
|
|
28
28
|
# --- the character ---------------------------------------------------------
|
|
@@ -40,7 +40,7 @@ MOODS = { # mood: (eyes, mouth)
|
|
|
40
40
|
"wow": ("* *", "O"),
|
|
41
41
|
}
|
|
42
42
|
ART_WIDTH = 7
|
|
43
|
-
|
|
43
|
+
RESET = "\x1b[0m"
|
|
44
44
|
|
|
45
45
|
|
|
46
46
|
def pip_lines(mood: str = "happy") -> List[str]:
|
|
@@ -61,8 +61,7 @@ def bubble(text: str, width: int) -> List[str]:
|
|
|
61
61
|
|
|
62
62
|
|
|
63
63
|
def use_color(out: TextIO) -> bool:
|
|
64
|
-
return
|
|
65
|
-
and os.environ.get("TERM", "") not in ("", "dumb"))
|
|
64
|
+
return hasattr(out, "isatty") and out.isatty() and theme.terminal_colors()
|
|
66
65
|
|
|
67
66
|
|
|
68
67
|
def render(text: str, mood: str = "happy", color: bool = False, columns: int = 80) -> str:
|
|
@@ -75,7 +74,9 @@ def render(text: str, mood: str = "happy", color: bool = False, columns: int = 8
|
|
|
75
74
|
for i in range(rows):
|
|
76
75
|
face = art[i] if i < len(art) else " " * ART_WIDTH
|
|
77
76
|
if color and i < len(art):
|
|
78
|
-
|
|
77
|
+
active = theme.active()
|
|
78
|
+
if active.colorful:
|
|
79
|
+
face = active.sgr(active.pip) + face + theme.text_reset()
|
|
79
80
|
out.append(f"{face} {box[i] if i < len(box) else ''}".rstrip())
|
|
80
81
|
return "\n".join(out)
|
|
81
82
|
|
|
@@ -113,7 +114,9 @@ def build_lessons() -> List[Lesson]:
|
|
|
113
114
|
"a trailing & starts one, jobs lists them and wait waits.")])
|
|
114
115
|
return [
|
|
115
116
|
Lesson("basics", "First steps", "run commands and move around", [
|
|
116
|
-
Step("A shell runs commands. echo prints text.
|
|
117
|
+
Step("A shell runs commands. echo prints text. Put the text in quotes. "
|
|
118
|
+
"The shell removes the quotes, so echo prints only the words.",
|
|
119
|
+
'echo "hello from myshell"'),
|
|
117
120
|
Step("pwd shows the folder you are in.", "pwd"),
|
|
118
121
|
Step("cd moves you to another folder. cd - jumps back.", "cd / && pwd && cd -"),
|
|
119
122
|
Step("Tab completes commands and file names. Press it twice to see choices. "
|
|
@@ -121,9 +124,9 @@ def build_lessons() -> List[Lesson]:
|
|
|
121
124
|
]),
|
|
122
125
|
Lesson("pipes", "Pipes and files", "connect commands and save output", [
|
|
123
126
|
Step("A pipe sends the output of one command into the next.",
|
|
124
|
-
|
|
127
|
+
'echo "hello" | tr a-z A-Z'),
|
|
125
128
|
Step("> writes output to a file. >> adds to the end of a file.",
|
|
126
|
-
f
|
|
129
|
+
f'echo "first" > {demo}; echo "second" >> {demo}; cat {demo}; rm {demo}'),
|
|
127
130
|
Step("2>&1 sends error messages down the same path as normal output.",
|
|
128
131
|
"ls /no/such/folder 2>&1 | head -1"),
|
|
129
132
|
Step("A here-string feeds a line of text to a command as input.",
|
|
@@ -133,17 +136,22 @@ def build_lessons() -> List[Lesson]:
|
|
|
133
136
|
]),
|
|
134
137
|
Lesson("variables", "Variables and math", "store values and calculate", [
|
|
135
138
|
Step("Set a variable with NAME=value. Read it with $NAME.",
|
|
136
|
-
|
|
139
|
+
'demo=world; echo "hello $demo"; unset demo'),
|
|
137
140
|
Step("Put math inside $(( )). It handles + - * / % and more.",
|
|
138
141
|
"echo $((6 * 7))"),
|
|
139
142
|
Step("Variables work inside math too, with += and similar.",
|
|
140
|
-
|
|
143
|
+
'n=5; n=$((n + 1)); echo "n is $n"; unset n'),
|
|
141
144
|
Step("$( ) captures the output of a command. Backticks do the same.",
|
|
142
|
-
|
|
145
|
+
'echo "I am in $(pwd)"'),
|
|
143
146
|
Step("$? holds the exit status of the last command. 0 means success.",
|
|
144
147
|
"true; echo $?; false; echo $?"),
|
|
145
148
|
]),
|
|
146
149
|
Lesson("quotes", "Quotes and wildcards", "control what the shell changes", [
|
|
150
|
+
Step("Quotes mark where text starts and ends. The shell removes them before the "
|
|
151
|
+
"command runs, so echo prints the words without the quote marks.",
|
|
152
|
+
'echo "hello"'),
|
|
153
|
+
Step("To print the quote marks, put them inside the other kind of quote.",
|
|
154
|
+
"""echo '"hello"'"""),
|
|
147
155
|
Step("Single quotes keep text exactly as typed.",
|
|
148
156
|
"echo '$HOME stays as typed'"),
|
|
149
157
|
Step("Double quotes allow variables and keep spaces together.",
|
|
@@ -156,15 +164,15 @@ def build_lessons() -> List[Lesson]:
|
|
|
156
164
|
]),
|
|
157
165
|
Lesson("logic", "Choices and loops", "decide and repeat", [
|
|
158
166
|
Step("&& runs the next command only after success. || runs it after failure.",
|
|
159
|
-
|
|
167
|
+
'true && echo "yes"; false || echo "fallback"'),
|
|
160
168
|
Step("if tests a condition. [ ] compares numbers, text and files.",
|
|
161
|
-
|
|
169
|
+
'if [ 3 -gt 2 ]; then echo "bigger"; else echo "smaller"; fi'),
|
|
162
170
|
Step("for repeats a command for each item in a list.",
|
|
163
|
-
|
|
171
|
+
'for n in 1 2 3; do echo "number $n"; done'),
|
|
164
172
|
Step("while repeats as long as a test passes. break leaves a loop early.",
|
|
165
|
-
|
|
173
|
+
'i=0; while [ $i -lt 5 ]; do i=$((i+1)); [ $i = 3 ] && break; echo "i is $i"; done; unset i'),
|
|
166
174
|
Step("File tests: -f is a file, -d is a folder, -e exists.",
|
|
167
|
-
|
|
175
|
+
'[ -d . ] && echo ". is a folder"'),
|
|
168
176
|
]),
|
|
169
177
|
Lesson("jobs", "Background jobs", "run several things at once", [
|
|
170
178
|
*background,
|
|
@@ -173,7 +181,7 @@ def build_lessons() -> List[Lesson]:
|
|
|
173
181
|
]),
|
|
174
182
|
Lesson("functions", "Functions and arguments", "name a few commands and reuse them", [
|
|
175
183
|
Step("A function groups commands under a name. Call it like any command.",
|
|
176
|
-
|
|
184
|
+
'pip_hi() { echo "hello $1"; }; pip_hi Pip'),
|
|
177
185
|
Step("$1, $2 ... are the arguments. $# counts them. $@ lists them all.",
|
|
178
186
|
'pip_args() { echo "$# arguments: $@"; }; pip_args one "two words" three'),
|
|
179
187
|
Step('Use "$@" in quotes to pass every argument on, with spaces kept.',
|
|
@@ -184,7 +192,7 @@ def build_lessons() -> List[Lesson]:
|
|
|
184
192
|
"x=outside; pip_local() { local x=inside; echo $x; }; pip_local; echo $x; unset x"),
|
|
185
193
|
Step("A for loop with no list walks over the arguments. Scripts get arguments too: "
|
|
186
194
|
"myshell script.sh a b makes $1 equal to a.",
|
|
187
|
-
|
|
195
|
+
'pip_walk() { for a; do echo "item $a"; done; }; pip_walk x y; '
|
|
188
196
|
"unset -f pip_hi pip_args pip_each pip_check pip_local pip_walk"),
|
|
189
197
|
]),
|
|
190
198
|
Lesson("expansion", "Expansions", "defaults, trimming, replacing and braces", [
|
|
@@ -206,14 +214,14 @@ def build_lessons() -> List[Lesson]:
|
|
|
206
214
|
]),
|
|
207
215
|
Lesson("case", "Case statements", "match one value against patterns", [
|
|
208
216
|
Step("case compares a word with patterns. Each arm ends with ;;.",
|
|
209
|
-
|
|
217
|
+
'case apple in apple) echo "fruit";; carrot) echo "vegetable";; esac'),
|
|
210
218
|
Step("Use | for several patterns and * as the catch-all.",
|
|
211
|
-
|
|
219
|
+
'case notes.md in *.txt|*.md) echo "text";; *.png) echo "image";; *) echo "other";; esac'),
|
|
212
220
|
Step("Patterns can use ? and [ ] too.",
|
|
213
|
-
|
|
221
|
+
'case 7 in [0-9]) echo "one digit";; *) echo "longer";; esac'),
|
|
214
222
|
Step("Inside a function, case makes a tidy menu.",
|
|
215
|
-
|
|
216
|
-
|
|
223
|
+
'pip_do() { case $1 in start) echo "starting";; stop) echo "stopping";; '
|
|
224
|
+
'*) echo "unknown $1";; esac; }; pip_do start; pip_do jump; unset -f pip_do'),
|
|
217
225
|
]),
|
|
218
226
|
Lesson("tools", "More builtins", "read, printf, set, env, which, trap and friends", [
|
|
219
227
|
Step("read puts a line of input into variables. Here it reads a here-string.",
|
|
@@ -223,11 +231,11 @@ def build_lessons() -> List[Lesson]:
|
|
|
223
231
|
Step("printf repeats its format for extra arguments.",
|
|
224
232
|
"printf '%s\\n' one two three"),
|
|
225
233
|
Step("env lists the environment. env NAME=value command runs a command with that value.",
|
|
226
|
-
|
|
234
|
+
'env PIP_COLOR=blue echo "run with a temporary value"'),
|
|
227
235
|
Step("which tells how a name runs: builtin, alias, function or program path.",
|
|
228
|
-
|
|
236
|
+
'alias pip_a="echo hi"; which echo pip_a; unalias pip_a'),
|
|
229
237
|
Step("trap runs a command when a signal or the shell exit arrives.",
|
|
230
|
-
|
|
238
|
+
'trap "echo goodbye from trap" EXIT; trap; trap - EXIT'),
|
|
231
239
|
Step("set -e stops a script at the first failure. set -u stops at an unset variable. "
|
|
232
240
|
"set -x prints each command. Turn one off with +e, +u or +x. "
|
|
233
241
|
"set -- a b c sets $1 $2 $3."),
|
|
@@ -283,7 +291,7 @@ Case case $X in a|b) cmds;; *.txt) cmds;; *) cmds;; esac
|
|
|
283
291
|
Loops for X in a b; do ..; done while C; do ..; done until C; do ..; done
|
|
284
292
|
Loop control break continue break 2
|
|
285
293
|
Jobs cmd & jobs fg bg wait Ctrl+C Ctrl+Z
|
|
286
|
-
Builtins cd pwd echo printf read alias unalias type which export unset set env
|
|
294
|
+
Builtins cd pwd echo printf read alias unalias type which export unset set env theme
|
|
287
295
|
source exec trap shift local history true false : exit
|
|
288
296
|
Files and text ls cat head tr wc grep touch mkdir rm cp mv sleep
|
|
289
297
|
Set options set -e (stop on error) set -u (unset is error) set -x (trace)
|
|
@@ -307,7 +315,7 @@ TIPS = [
|
|
|
307
315
|
"Use ${NAME:-default} to fall back to a default value.",
|
|
308
316
|
"Use {1..5} or file.{txt,md} to save typing.",
|
|
309
317
|
"Try guide quiz to test what you know.",
|
|
310
|
-
|
|
318
|
+
'Wrap repeated commands in a function: name() { echo "hi"; }.',
|
|
311
319
|
"Type guide progress to see which lessons you finished.",
|
|
312
320
|
]
|
|
313
321
|
|
|
@@ -6,6 +6,9 @@ import shutil
|
|
|
6
6
|
import signal
|
|
7
7
|
from typing import Callable, Dict, List, Optional, TextIO
|
|
8
8
|
|
|
9
|
+
import difflib
|
|
10
|
+
|
|
11
|
+
from . import theme
|
|
9
12
|
from .errors import ReturnFromFunction, ShellExit
|
|
10
13
|
from .state import ShellState
|
|
11
14
|
|
|
@@ -526,7 +529,47 @@ def builtin_trap(state: ShellState, args: List[str], stdout: TextIO, stderr: Tex
|
|
|
526
529
|
return status
|
|
527
530
|
|
|
528
531
|
|
|
532
|
+
def builtin_theme(state: ShellState, args: List[str], stdout: TextIO, stderr: TextIO) -> int:
|
|
533
|
+
"""theme: list the themes. theme NAME: switch and remember. theme reset: back to default."""
|
|
534
|
+
color = hasattr(stdout, "isatty") and stdout.isatty() and theme.terminal_colors()
|
|
535
|
+
if args and args[0] in ("-h", "--help"):
|
|
536
|
+
print("usage: theme [NAME | reset]\n theme list the themes\n"
|
|
537
|
+
" theme NAME use a theme and remember it\n theme reset go back to the default",
|
|
538
|
+
file=stdout)
|
|
539
|
+
return 0
|
|
540
|
+
if not args:
|
|
541
|
+
now = theme.active().name
|
|
542
|
+
for t in theme.THEMES.values():
|
|
543
|
+
mark = "*" if t.name == now else " "
|
|
544
|
+
print(f"{mark} {t.name:<8} {theme.sample(t, color)} {t.about}", file=stdout)
|
|
545
|
+
if hasattr(stdout, "isatty") and stdout.isatty():
|
|
546
|
+
why = theme.colors_off_reason()
|
|
547
|
+
if why:
|
|
548
|
+
print(f"Colors are off: {why}.", file=stdout)
|
|
549
|
+
if os.environ.get("MYSHELL_THEME"):
|
|
550
|
+
print(f"MYSHELL_THEME={os.environ['MYSHELL_THEME']} sets the theme at start.", file=stdout)
|
|
551
|
+
return 0
|
|
552
|
+
if len(args) > 1:
|
|
553
|
+
print("theme: too many arguments", file=stderr)
|
|
554
|
+
return 2
|
|
555
|
+
name = theme.DEFAULT if args[0] == "reset" else args[0].lower()
|
|
556
|
+
if name not in theme.THEMES:
|
|
557
|
+
close = difflib.get_close_matches(name, theme.names(), n=1)
|
|
558
|
+
hint = f" Did you mean '{close[0]}'?" if close else ""
|
|
559
|
+
print(f"theme: unknown theme '{args[0]}'.{hint} Run theme to see the list.", file=stderr)
|
|
560
|
+
return 1
|
|
561
|
+
chosen = theme.select(name)
|
|
562
|
+
if color:
|
|
563
|
+
stdout.write(theme.text_start()) # the message already shows the new text color
|
|
564
|
+
print(f"Theme: {name}", file=stdout)
|
|
565
|
+
why = theme.colors_off_reason(chosen) if name != "mono" else ""
|
|
566
|
+
if why and hasattr(stdout, "isatty") and stdout.isatty():
|
|
567
|
+
print(f"Colors are off: {why}.", file=stdout)
|
|
568
|
+
return 0
|
|
569
|
+
|
|
570
|
+
|
|
529
571
|
EXTRA_BUILTINS: Dict[str, Builtin] = {
|
|
572
|
+
"theme": builtin_theme,
|
|
530
573
|
"true": builtin_true,
|
|
531
574
|
"false": builtin_false,
|
|
532
575
|
":": builtin_true,
|
|
@@ -6,6 +6,7 @@ import sys
|
|
|
6
6
|
import time
|
|
7
7
|
from typing import List, Optional
|
|
8
8
|
|
|
9
|
+
from . import theme
|
|
9
10
|
from .state import ShellState
|
|
10
11
|
|
|
11
12
|
try:
|
|
@@ -13,7 +14,7 @@ try:
|
|
|
13
14
|
# The libedit on macOS prints the text between \x01 and \x02 out of order, so no markers there.
|
|
14
15
|
MARKERS = not (sys.platform == "darwin" and "libedit" in (_readline.__doc__ or ""))
|
|
15
16
|
except ImportError:
|
|
16
|
-
MARKERS =
|
|
17
|
+
MARKERS = False # without readline, input() would print the markers
|
|
17
18
|
|
|
18
19
|
|
|
19
20
|
# Prompt
|
|
@@ -184,14 +185,18 @@ def build_prompt(state: ShellState) -> str:
|
|
|
184
185
|
custom = state.get_variable("PS1")
|
|
185
186
|
if custom is not None:
|
|
186
187
|
return expand_prompt(custom, state)
|
|
187
|
-
|
|
188
|
-
|
|
188
|
+
th = theme.active()
|
|
189
|
+
color = th.colorful and theme.terminal_colors()
|
|
190
|
+
back = (r"\[\e[0m\]" + (r"\[\e[" + th.text + r"m\]" if th.text else "")) if color else ""
|
|
191
|
+
template = (r"\[\e[" + th.dir + r"m\]\w" + back + r" \$ ") if color else DEFAULT_PS1_PLAIN
|
|
192
|
+
tail = (r"\[\e[" + th.text + r"m\]") if color and th.text else ""
|
|
189
193
|
branch = git_branch()
|
|
190
194
|
if branch:
|
|
191
195
|
# The branch name goes in as plain text. A backslash in it must not act as an escape.
|
|
192
196
|
safe = branch.replace("\\", "\\\\")
|
|
193
|
-
shown = (r"\[\e[
|
|
197
|
+
shown = (r"\[\e[" + th.branch + r"m\](" + safe + ")" + back) if color else "(" + safe + ")"
|
|
194
198
|
template = template.replace(r" \$ ", " " + shown + r" \$ ")
|
|
195
199
|
if state.last_status != 0:
|
|
196
|
-
|
|
197
|
-
|
|
200
|
+
failed = (r"\[\e[" + th.fail + r"m\][\?]" + back + " ") if color else FAILED_PREFIX_PLAIN
|
|
201
|
+
template = failed + template
|
|
202
|
+
return expand_prompt(template + tail, state)
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
"""Color themes for the prompt, the syntax colors in the editor and Pip.
|
|
2
|
+
|
|
3
|
+
A theme is a few ANSI color codes. The active theme comes from MYSHELL_THEME, then from
|
|
4
|
+
~/.myshell_theme (written by the theme builtin), then it is "default". Nothing here imports
|
|
5
|
+
prompt_toolkit or the shell state."""
|
|
6
|
+
import os
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from typing import Dict, List, Optional
|
|
9
|
+
|
|
10
|
+
from .paths import home_file
|
|
11
|
+
|
|
12
|
+
RESET = "\x1b[0m"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True)
|
|
16
|
+
class Theme:
|
|
17
|
+
name: str
|
|
18
|
+
about: str
|
|
19
|
+
dir: str # SGR code for the folder in the prompt, such as "1;32"
|
|
20
|
+
fail: str # the [status] shown after a failed command
|
|
21
|
+
branch: str # the git branch
|
|
22
|
+
pip: str # Pip's face
|
|
23
|
+
syntax: Dict[str, str] = field(default_factory=dict) # prompt_toolkit styles by class name
|
|
24
|
+
suggestion: str = "fg:#888888"
|
|
25
|
+
colorful: bool = True # False means no color anywhere
|
|
26
|
+
text: str = "" # SGR code for ordinary text: what you type and what commands print. "" keeps the terminal's own
|
|
27
|
+
|
|
28
|
+
def sgr(self, code: str) -> str:
|
|
29
|
+
return f"\x1b[{code}m" if code else ""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _syntax(command, bad, keyword, string, variable, operator, comment):
|
|
33
|
+
return {"command": command, "badcommand": bad, "keyword": keyword, "string": string,
|
|
34
|
+
"variable": variable, "operator": operator, "comment": comment, "plain": ""}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
THEMES: Dict[str, Theme] = {t.name: t for t in [
|
|
38
|
+
Theme("default", "green folder, red failures", "1;32", "1;31", "35", "33",
|
|
39
|
+
_syntax("fg:ansigreen", "fg:ansired", "fg:ansiblue bold", "fg:ansiyellow",
|
|
40
|
+
"fg:ansicyan", "fg:ansimagenta", "fg:ansibrightblack")),
|
|
41
|
+
Theme("ocean", "blues and cyans", "1;36", "1;31", "34", "36",
|
|
42
|
+
_syntax("fg:ansicyan", "fg:ansired", "fg:ansiblue bold", "fg:ansibrightcyan",
|
|
43
|
+
"fg:ansibrightwhite", "fg:ansibrightmagenta", "fg:ansibrightblack"), "fg:#6b8ba4",
|
|
44
|
+
text="94"),
|
|
45
|
+
Theme("forest", "greens and earth tones", "1;33", "1;31", "36", "32",
|
|
46
|
+
_syntax("fg:ansibrightgreen", "fg:ansired", "fg:ansiyellow bold", "fg:ansibrightyellow",
|
|
47
|
+
"fg:ansicyan", "fg:ansibrightblack", "fg:ansibrightblack"), "fg:#7a8f6b",
|
|
48
|
+
text="32"),
|
|
49
|
+
Theme("sunset", "warm reds and yellows", "1;93", "1;31", "35", "31",
|
|
50
|
+
_syntax("fg:ansibrightyellow", "fg:ansired", "fg:ansibrightred bold", "fg:ansibrightmagenta",
|
|
51
|
+
"fg:ansimagenta", "fg:ansired", "fg:ansibrightblack"), "fg:#a08070",
|
|
52
|
+
text="33"),
|
|
53
|
+
Theme("light", "darker colors for a white background", "1;35", "1;31", "32", "34",
|
|
54
|
+
_syntax("fg:ansigreen", "fg:ansired", "fg:ansimagenta bold", "fg:ansired",
|
|
55
|
+
"fg:ansicyan", "fg:ansibrightblack", "fg:ansibrightblack"), "fg:#999999",
|
|
56
|
+
text="34"),
|
|
57
|
+
Theme("mono", "no colors", "", "", "", "", _syntax("", "", "bold", "", "", "", ""),
|
|
58
|
+
"fg:#888888", colorful=False),
|
|
59
|
+
]}
|
|
60
|
+
DEFAULT = "default"
|
|
61
|
+
|
|
62
|
+
_ANSI_NAMES = ["black", "red", "green", "yellow", "blue", "magenta", "cyan", "white"]
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _ansi_style(code: str) -> str:
|
|
66
|
+
"""prompt_toolkit style for a plain SGR color such as "32" or "94". "" when it is not one."""
|
|
67
|
+
if code.isdigit():
|
|
68
|
+
n = int(code)
|
|
69
|
+
if 30 <= n <= 37:
|
|
70
|
+
return "fg:ansi" + _ANSI_NAMES[n - 30]
|
|
71
|
+
if 90 <= n <= 97:
|
|
72
|
+
return "fg:ansibright" + _ANSI_NAMES[n - 90]
|
|
73
|
+
return ""
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
for _t in THEMES.values(): # typed words that are not a command or a string take the text color
|
|
77
|
+
if _t.text:
|
|
78
|
+
_t.syntax["plain"] = _ansi_style(_t.text)
|
|
79
|
+
_TEXT_STYLE = {"94": "fg:ansibrightblue", "32": "fg:ansigreen", "33": "fg:ansiyellow", "34": "fg:ansiblue"}
|
|
80
|
+
for _t in THEMES.values():
|
|
81
|
+
if _t.text:
|
|
82
|
+
_t.syntax["plain"] = _TEXT_STYLE[_t.text]
|
|
83
|
+
|
|
84
|
+
_active: Optional[Theme] = None
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def theme_file() -> str:
|
|
88
|
+
return home_file(".myshell_theme")
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def names() -> List[str]:
|
|
92
|
+
return list(THEMES)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _read_saved() -> Optional[str]:
|
|
96
|
+
try:
|
|
97
|
+
with open(theme_file(), encoding="utf-8") as f:
|
|
98
|
+
return f.read().strip()
|
|
99
|
+
except OSError:
|
|
100
|
+
return None
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def active() -> Theme:
|
|
104
|
+
"""The theme in use now. An unknown name falls back to the default."""
|
|
105
|
+
global _active
|
|
106
|
+
if _active is None:
|
|
107
|
+
name = os.environ.get("MYSHELL_THEME") or _read_saved() or DEFAULT
|
|
108
|
+
_active = THEMES.get(name, THEMES[DEFAULT])
|
|
109
|
+
return _active
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def select(name: str, save: bool = True) -> Theme:
|
|
113
|
+
"""Switch theme. Raises KeyError for an unknown name."""
|
|
114
|
+
global _active
|
|
115
|
+
chosen = THEMES[name]
|
|
116
|
+
_active = chosen
|
|
117
|
+
if save:
|
|
118
|
+
try:
|
|
119
|
+
if name == DEFAULT:
|
|
120
|
+
os.remove(theme_file())
|
|
121
|
+
else:
|
|
122
|
+
with open(theme_file(), "w", encoding="utf-8") as f:
|
|
123
|
+
f.write(name + "\n")
|
|
124
|
+
except OSError:
|
|
125
|
+
pass
|
|
126
|
+
return chosen
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def reset() -> None:
|
|
130
|
+
"""Forget the cached theme so the next call reads the environment again."""
|
|
131
|
+
global _active
|
|
132
|
+
_active = None
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def sample(t: Theme, color: bool) -> str:
|
|
136
|
+
"""A short preview: how the folder, branch and a failure look."""
|
|
137
|
+
parts = [("~/proj", t.dir), ("(main)", t.branch), ("[1]", t.fail), ("text", t.text)]
|
|
138
|
+
if not (color and t.colorful):
|
|
139
|
+
return " ".join(text for text, _ in parts)
|
|
140
|
+
back = text_start() # after each sample, the text goes back to the theme in use
|
|
141
|
+
return " ".join(f"{t.sgr(code)}{text}{RESET}{back}" for text, code in parts)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def text_start() -> str:
|
|
145
|
+
"""The escape code that starts the theme's text color, or an empty string."""
|
|
146
|
+
t = active()
|
|
147
|
+
return t.sgr(t.text) if t.text and t.colorful and terminal_colors() else ""
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def text_reset() -> str:
|
|
151
|
+
"""A reset code followed by the theme's text color, so text after it keeps the theme."""
|
|
152
|
+
return RESET + text_start()
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _is_windows() -> bool:
|
|
156
|
+
return os.name == "nt"
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
_vt_ok: Optional[bool] = None
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _enable_windows_vt() -> bool:
|
|
163
|
+
"""Turn on ANSI color codes in the Windows console. True when the console accepts them."""
|
|
164
|
+
global _vt_ok
|
|
165
|
+
if _vt_ok is None:
|
|
166
|
+
try:
|
|
167
|
+
import ctypes
|
|
168
|
+
kernel = ctypes.windll.kernel32 # type: ignore[attr-defined]
|
|
169
|
+
handle = kernel.GetStdHandle(-11)
|
|
170
|
+
mode = ctypes.c_uint32()
|
|
171
|
+
_vt_ok = bool(kernel.GetConsoleMode(handle, ctypes.byref(mode))) and bool(
|
|
172
|
+
kernel.SetConsoleMode(handle, mode.value | 0x0004))
|
|
173
|
+
except Exception:
|
|
174
|
+
_vt_ok = False
|
|
175
|
+
return _vt_ok
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def terminal_colors() -> bool:
|
|
179
|
+
"""Does the terminal show colors? NO_COLOR and TERM=dumb say no. Windows usually has no TERM
|
|
180
|
+
but the console shows colors, so there the console itself is asked."""
|
|
181
|
+
if "NO_COLOR" in os.environ:
|
|
182
|
+
return False
|
|
183
|
+
term = os.environ.get("TERM", "")
|
|
184
|
+
if term == "dumb":
|
|
185
|
+
return False
|
|
186
|
+
if term:
|
|
187
|
+
return True
|
|
188
|
+
return _is_windows() and _enable_windows_vt()
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def colors_off_reason(t: Optional[Theme] = None) -> str:
|
|
192
|
+
"""Why the prompt shows no colors, or an empty string when it does."""
|
|
193
|
+
t = t or active()
|
|
194
|
+
if not t.colorful:
|
|
195
|
+
return f"the {t.name} theme has no colors"
|
|
196
|
+
if "NO_COLOR" in os.environ:
|
|
197
|
+
return "NO_COLOR is set"
|
|
198
|
+
if not terminal_colors():
|
|
199
|
+
term = os.environ.get("TERM", "")
|
|
200
|
+
if _is_windows() and not term:
|
|
201
|
+
return "this Windows console does not accept color codes. Try Windows Terminal"
|
|
202
|
+
return "TERM is " + (f"'{term}'" if term else "not set") + ". Try: export TERM=xterm-256color"
|
|
203
|
+
return ""
|
|
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "myshell-py"
|
|
7
|
-
version = "0.2
|
|
7
|
+
version = "0.3.2"
|
|
8
8
|
description = "A Unix-style shell written in Python, with a built-in guide."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.9"
|
|
@@ -23,6 +23,7 @@ dev = ["pytest>=7.0", "pyflakes>=3.0"]
|
|
|
23
23
|
|
|
24
24
|
[project.scripts]
|
|
25
25
|
myshell = "myshell.cli:main"
|
|
26
|
+
myshell-py = "myshell.cli:main"
|
|
26
27
|
|
|
27
28
|
[tool.hatch.build.targets.wheel]
|
|
28
29
|
packages = ["myshell"]
|
|
@@ -167,3 +167,13 @@ def pty_shell(dirs):
|
|
|
167
167
|
yield start
|
|
168
168
|
for s in sessions:
|
|
169
169
|
s.close()
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
@pytest.fixture(autouse=True)
|
|
173
|
+
def _fresh_theme(monkeypatch):
|
|
174
|
+
"""Every test starts with the default theme, whatever an earlier test chose."""
|
|
175
|
+
from myshell import theme
|
|
176
|
+
monkeypatch.delenv("MYSHELL_THEME", raising=False)
|
|
177
|
+
theme.reset()
|
|
178
|
+
yield
|
|
179
|
+
theme.reset()
|
|
@@ -208,4 +208,4 @@ class TestKindOf:
|
|
|
208
208
|
tool.chmod(tool.stat().st_mode | stat.S_IXUSR)
|
|
209
209
|
assert kind_of("later") == "unknown" # cached for this PATH
|
|
210
210
|
monkeypatch.setenv("PATH", str(d) + os.pathsep + "/nonexistent")
|
|
211
|
-
assert kind_of("later") == "command"
|
|
211
|
+
assert kind_of("later") == "command"
|
|
@@ -41,7 +41,7 @@ class TestCharacter:
|
|
|
41
41
|
|
|
42
42
|
def test_render_adds_color_only_when_asked(self):
|
|
43
43
|
assert "\x1b[" not in guide.render("x", color=False)
|
|
44
|
-
assert
|
|
44
|
+
assert "\x1b[33m" in guide.render("x", color=True)
|
|
45
45
|
|
|
46
46
|
def test_narrow_terminal_still_renders(self):
|
|
47
47
|
assert "hi" in guide.render("hi", columns=10)
|
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
import os
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
|
|
5
|
+
from conftest import unix_only
|
|
6
|
+
from myshell import theme
|
|
7
|
+
from myshell.prompt import build_prompt
|
|
8
|
+
from myshell.more_builtins import builtin_theme
|
|
9
|
+
import io
|
|
10
|
+
|
|
11
|
+
CH = "#" if hasattr(os, "geteuid") and os.geteuid() == 0 else "$"
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@pytest.fixture
|
|
15
|
+
def home(dirs, state):
|
|
16
|
+
"""The temporary home folder. The state fixture points HOME at it."""
|
|
17
|
+
return dirs[0]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@pytest.fixture
|
|
21
|
+
def st(state):
|
|
22
|
+
return state
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def run(st, *args, tty=False):
|
|
26
|
+
out, err = io.StringIO(), io.StringIO()
|
|
27
|
+
if tty:
|
|
28
|
+
out.isatty = lambda: True
|
|
29
|
+
code = builtin_theme(st, list(args), out, err)
|
|
30
|
+
return code, out.getvalue(), err.getvalue()
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class TestThemes:
|
|
34
|
+
def test_every_theme_is_complete(self):
|
|
35
|
+
keys = {"command", "badcommand", "keyword", "string", "variable", "operator", "comment", "plain"}
|
|
36
|
+
for t in theme.THEMES.values():
|
|
37
|
+
assert set(t.syntax) == keys and t.about
|
|
38
|
+
if t.colorful:
|
|
39
|
+
assert t.dir and t.fail and t.branch and t.pip
|
|
40
|
+
|
|
41
|
+
def test_default_is_the_current_look(self):
|
|
42
|
+
t = theme.THEMES["default"]
|
|
43
|
+
assert (t.dir, t.fail, t.branch, t.pip) == ("1;32", "1;31", "35", "33")
|
|
44
|
+
|
|
45
|
+
def test_default_when_nothing_is_set(self, home):
|
|
46
|
+
assert theme.active().name == "default"
|
|
47
|
+
|
|
48
|
+
def test_environment_chooses_the_theme(self, home, monkeypatch):
|
|
49
|
+
monkeypatch.setenv("MYSHELL_THEME", "ocean")
|
|
50
|
+
theme.reset()
|
|
51
|
+
assert theme.active().name == "ocean"
|
|
52
|
+
|
|
53
|
+
def test_unknown_name_in_environment_falls_back(self, home, monkeypatch):
|
|
54
|
+
monkeypatch.setenv("MYSHELL_THEME", "nope")
|
|
55
|
+
theme.reset()
|
|
56
|
+
assert theme.active().name == "default"
|
|
57
|
+
|
|
58
|
+
def test_saved_theme_is_read_back(self, home):
|
|
59
|
+
theme.select("forest")
|
|
60
|
+
theme.reset()
|
|
61
|
+
assert theme.active().name == "forest"
|
|
62
|
+
assert (home / ".myshell_theme").read_text().strip() == "forest"
|
|
63
|
+
|
|
64
|
+
def test_environment_beats_the_saved_file(self, home, monkeypatch):
|
|
65
|
+
theme.select("forest")
|
|
66
|
+
monkeypatch.setenv("MYSHELL_THEME", "sunset")
|
|
67
|
+
theme.reset()
|
|
68
|
+
assert theme.active().name == "sunset"
|
|
69
|
+
|
|
70
|
+
def test_selecting_default_removes_the_file(self, home):
|
|
71
|
+
theme.select("ocean")
|
|
72
|
+
theme.select("default")
|
|
73
|
+
assert not (home / ".myshell_theme").exists()
|
|
74
|
+
|
|
75
|
+
def test_unknown_select_raises(self, home):
|
|
76
|
+
with pytest.raises(KeyError):
|
|
77
|
+
theme.select("nope")
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class TestPrompt:
|
|
81
|
+
def test_prompt_uses_the_theme_colors(self, home, st, monkeypatch):
|
|
82
|
+
monkeypatch.setenv("TERM", "xterm")
|
|
83
|
+
theme.select("ocean", save=False)
|
|
84
|
+
assert "\x1b[1;36m" in build_prompt(st) and "\x1b[1;32m" not in build_prompt(st)
|
|
85
|
+
|
|
86
|
+
def test_failure_color_follows_the_theme(self, home, st, monkeypatch):
|
|
87
|
+
monkeypatch.setenv("TERM", "xterm")
|
|
88
|
+
st.last_status = 3
|
|
89
|
+
assert "[3]" in build_prompt(st)
|
|
90
|
+
assert "\x1b[1;31m" in build_prompt(st)
|
|
91
|
+
|
|
92
|
+
def test_prompt_ends_with_the_text_color(self, home, st, monkeypatch):
|
|
93
|
+
monkeypatch.setenv("TERM", "xterm")
|
|
94
|
+
theme.select("ocean", save=False)
|
|
95
|
+
assert build_prompt(st).endswith("\x01\x1b[94m\x02") or build_prompt(st).endswith("\x1b[94m")
|
|
96
|
+
|
|
97
|
+
def test_default_leaves_the_text_color_alone(self, home, st, monkeypatch):
|
|
98
|
+
monkeypatch.setenv("TERM", "xterm")
|
|
99
|
+
assert build_prompt(st).endswith(f"{CH} ")
|
|
100
|
+
|
|
101
|
+
def test_mono_has_no_escape_codes(self, home, st, monkeypatch):
|
|
102
|
+
monkeypatch.setenv("TERM", "xterm")
|
|
103
|
+
theme.select("mono", save=False)
|
|
104
|
+
st.last_status = 1
|
|
105
|
+
assert "\x1b" not in build_prompt(st) and "\x01" not in build_prompt(st)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class TestBuiltin:
|
|
109
|
+
def test_lists_all_and_marks_the_current(self, home, st):
|
|
110
|
+
code, out, _ = run(st)
|
|
111
|
+
assert code == 0
|
|
112
|
+
for name in theme.names():
|
|
113
|
+
assert name in out
|
|
114
|
+
assert "* default" in out
|
|
115
|
+
|
|
116
|
+
def test_switch_saves(self, home, st):
|
|
117
|
+
code, out, _ = run(st, "ocean")
|
|
118
|
+
assert code == 0 and "ocean" in out
|
|
119
|
+
assert theme.active().name == "ocean"
|
|
120
|
+
assert (home / ".myshell_theme").read_text().strip() == "ocean"
|
|
121
|
+
assert "* ocean" in run(st)[1]
|
|
122
|
+
|
|
123
|
+
def test_name_is_not_case_sensitive(self, home, st):
|
|
124
|
+
assert run(st, "OCEAN")[0] == 0 and theme.active().name == "ocean"
|
|
125
|
+
|
|
126
|
+
def test_reset(self, home, st):
|
|
127
|
+
run(st, "forest")
|
|
128
|
+
assert run(st, "reset")[0] == 0
|
|
129
|
+
assert theme.active().name == "default" and not (home / ".myshell_theme").exists()
|
|
130
|
+
|
|
131
|
+
def test_unknown_name_suggests_a_close_one(self, home, st):
|
|
132
|
+
code, _, err = run(st, "ocea")
|
|
133
|
+
assert code == 1 and "unknown theme" in err and "'ocean'" in err
|
|
134
|
+
assert theme.active().name == "default"
|
|
135
|
+
|
|
136
|
+
def test_too_many_arguments(self, home, st):
|
|
137
|
+
assert run(st, "a", "b")[0] == 2
|
|
138
|
+
|
|
139
|
+
def test_help(self, home, st):
|
|
140
|
+
assert "usage: theme" in run(st, "--help")[1]
|
|
141
|
+
|
|
142
|
+
def test_colored_preview_only_on_a_terminal(self, home, st, monkeypatch):
|
|
143
|
+
monkeypatch.setenv("TERM", "xterm")
|
|
144
|
+
monkeypatch.delenv("NO_COLOR", raising=False)
|
|
145
|
+
assert "\x1b[" not in run(st)[1]
|
|
146
|
+
assert "\x1b[1;32m" in run(st, tty=True)[1]
|
|
147
|
+
monkeypatch.setenv("NO_COLOR", "1")
|
|
148
|
+
assert "\x1b[" not in run(st, tty=True)[1]
|
|
149
|
+
|
|
150
|
+
def test_runs_from_the_shell(self, sh):
|
|
151
|
+
r = sh("theme sunset\ntheme")
|
|
152
|
+
assert "* sunset" in r.out
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
class TestWhyNoColor:
|
|
156
|
+
def test_reasons(self, home, monkeypatch):
|
|
157
|
+
monkeypatch.setattr(theme, "_is_windows", lambda: False) # Windows words its message differently
|
|
158
|
+
monkeypatch.setenv("TERM", "xterm")
|
|
159
|
+
monkeypatch.delenv("NO_COLOR", raising=False)
|
|
160
|
+
assert theme.colors_off_reason() == ""
|
|
161
|
+
monkeypatch.setenv("NO_COLOR", "1")
|
|
162
|
+
assert "NO_COLOR" in theme.colors_off_reason()
|
|
163
|
+
monkeypatch.delenv("NO_COLOR")
|
|
164
|
+
monkeypatch.setenv("TERM", "dumb")
|
|
165
|
+
assert "TERM" in theme.colors_off_reason()
|
|
166
|
+
monkeypatch.delenv("TERM")
|
|
167
|
+
assert "not set" in theme.colors_off_reason()
|
|
168
|
+
theme.select("mono", save=False)
|
|
169
|
+
assert "mono" in theme.colors_off_reason()
|
|
170
|
+
|
|
171
|
+
def test_list_explains_on_a_terminal(self, home, st, monkeypatch):
|
|
172
|
+
monkeypatch.setenv("TERM", "dumb")
|
|
173
|
+
assert "Colors are off: TERM is 'dumb'" in run(st, tty=True)[1]
|
|
174
|
+
assert "Colors are off" not in run(st)[1] # not a terminal, no note
|
|
175
|
+
assert "Colors are off" in run(st, "ocean", tty=True)[1]
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
class TestTerminalColors:
|
|
179
|
+
def test_term_and_no_color(self, monkeypatch):
|
|
180
|
+
monkeypatch.delenv("NO_COLOR", raising=False)
|
|
181
|
+
monkeypatch.setenv("TERM", "xterm")
|
|
182
|
+
assert theme.terminal_colors()
|
|
183
|
+
monkeypatch.setenv("TERM", "dumb")
|
|
184
|
+
assert not theme.terminal_colors()
|
|
185
|
+
monkeypatch.setenv("TERM", "xterm")
|
|
186
|
+
monkeypatch.setenv("NO_COLOR", "1")
|
|
187
|
+
assert not theme.terminal_colors()
|
|
188
|
+
|
|
189
|
+
def test_no_term_means_no_color_on_unix(self, monkeypatch):
|
|
190
|
+
monkeypatch.delenv("NO_COLOR", raising=False)
|
|
191
|
+
monkeypatch.delenv("TERM", raising=False)
|
|
192
|
+
monkeypatch.setattr(theme, "_is_windows", lambda: False)
|
|
193
|
+
assert not theme.terminal_colors()
|
|
194
|
+
|
|
195
|
+
def test_windows_asks_the_console(self, monkeypatch):
|
|
196
|
+
monkeypatch.delenv("NO_COLOR", raising=False)
|
|
197
|
+
monkeypatch.delenv("TERM", raising=False)
|
|
198
|
+
monkeypatch.setattr(theme, "_is_windows", lambda: True)
|
|
199
|
+
monkeypatch.setattr(theme, "_enable_windows_vt", lambda: True)
|
|
200
|
+
assert theme.terminal_colors()
|
|
201
|
+
monkeypatch.setattr(theme, "_enable_windows_vt", lambda: False)
|
|
202
|
+
assert not theme.terminal_colors()
|
|
203
|
+
assert "Windows" in theme.colors_off_reason()
|
|
204
|
+
|
|
205
|
+
def test_windows_console_can_still_say_no_color(self, monkeypatch):
|
|
206
|
+
monkeypatch.setenv("NO_COLOR", "1")
|
|
207
|
+
monkeypatch.setattr(theme, "_is_windows", lambda: True)
|
|
208
|
+
monkeypatch.setattr(theme, "_enable_windows_vt", lambda: True)
|
|
209
|
+
assert not theme.terminal_colors()
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
class TestTextColor:
|
|
213
|
+
def test_every_colored_theme_but_default_tints_text(self):
|
|
214
|
+
for name, t in theme.THEMES.items():
|
|
215
|
+
assert bool(t.text) == (name not in ("default", "mono"))
|
|
216
|
+
if t.text:
|
|
217
|
+
assert t.syntax["plain"].startswith("fg:")
|
|
218
|
+
|
|
219
|
+
def test_text_start_follows_the_terminal(self, home, monkeypatch):
|
|
220
|
+
monkeypatch.setenv("TERM", "xterm")
|
|
221
|
+
monkeypatch.delenv("NO_COLOR", raising=False)
|
|
222
|
+
theme.select("forest", save=False)
|
|
223
|
+
assert theme.text_start() == "\x1b[32m"
|
|
224
|
+
monkeypatch.setenv("NO_COLOR", "1")
|
|
225
|
+
assert theme.text_start() == ""
|
|
226
|
+
monkeypatch.delenv("NO_COLOR")
|
|
227
|
+
theme.select("default", save=False)
|
|
228
|
+
assert theme.text_start() == ""
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
@unix_only
|
|
232
|
+
def test_command_output_is_tinted_in_a_real_terminal(pty_shell):
|
|
233
|
+
s = pty_shell({"TERM": "xterm", "MYSHELL_THEME": "forest", "MYSHELL_EDITOR": "basic"})
|
|
234
|
+
seen = s.expect(f"{CH} ")
|
|
235
|
+
assert "\x1b[32m" in seen.rsplit("\x1b[0m", 1)[-1] # the prompt switches to the theme's text color
|
|
236
|
+
s.send("echo hello\n")
|
|
237
|
+
s.expect("\x1b[32mhello") # the command's output starts in the theme's text color
|
|
238
|
+
rest = s.expect(f"{CH} ")
|
|
239
|
+
assert "\x1b[0m" in rest
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
class TestTextEverywhere:
|
|
243
|
+
def test_prompt_returns_to_the_text_color_after_each_colored_part(self, home, st, monkeypatch):
|
|
244
|
+
monkeypatch.setenv("TERM", "xterm")
|
|
245
|
+
monkeypatch.setattr("myshell.prompt.MARKERS", False)
|
|
246
|
+
theme.select("forest", save=False)
|
|
247
|
+
st.last_status = 2
|
|
248
|
+
p = build_prompt(st)
|
|
249
|
+
assert p.count("\x1b[0m\x1b[32m") >= 2 and p.endswith("\x1b[32m")
|
|
250
|
+
|
|
251
|
+
def test_pip_keeps_the_text_color_after_the_face(self, home, monkeypatch):
|
|
252
|
+
from myshell import guide
|
|
253
|
+
monkeypatch.setenv("TERM", "xterm")
|
|
254
|
+
theme.select("ocean", save=False)
|
|
255
|
+
first = guide.render("hello", color=True).splitlines()[0]
|
|
256
|
+
assert "\x1b[0m\x1b[94m" in first
|
|
257
|
+
|
|
258
|
+
def test_preview_keeps_the_text_color_after_each_sample(self, home, monkeypatch):
|
|
259
|
+
monkeypatch.setenv("TERM", "xterm")
|
|
260
|
+
theme.select("sunset", save=False)
|
|
261
|
+
shown = theme.sample(theme.THEMES["ocean"], True)
|
|
262
|
+
assert shown.count("\x1b[0m\x1b[33m") == 4
|
|
263
|
+
|
|
264
|
+
def test_switching_starts_the_new_text_color_first(self, home, st, monkeypatch):
|
|
265
|
+
monkeypatch.setenv("TERM", "xterm")
|
|
266
|
+
monkeypatch.delenv("NO_COLOR", raising=False)
|
|
267
|
+
out = run(st, "forest", tty=True)[1]
|
|
268
|
+
assert out.startswith("\x1b[32mTheme: forest")
|
|
269
|
+
|
|
270
|
+
def test_typed_words_use_the_text_color_in_the_editor(self):
|
|
271
|
+
assert theme.THEMES["forest"].syntax["plain"] == "fg:ansigreen"
|
|
272
|
+
assert theme.THEMES["ocean"].syntax["plain"] == "fg:ansibrightblue"
|
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
<<<<<<< HEAD
|
|
2
|
-
# No external dependencies yet
|
|
3
|
-
# Example for future:
|
|
4
|
-
# rich
|
|
5
|
-
# prompt_toolkit
|
|
6
|
-
# Cross-platform readline support
|
|
7
|
-
readline; sys_platform != "win32"
|
|
8
|
-
|
|
9
|
-
# Windows readline replacement
|
|
10
|
-
pyreadline3; sys_platform == "win32"
|
|
11
|
-
=======
|
|
12
|
-
# The shell itself needs only the Python standard library.
|
|
13
|
-
# These packages are for the tests and the lint check.
|
|
14
|
-
pytest>=7.0
|
|
15
|
-
pyflakes>=3.0
|
|
16
|
-
>>>>>>> 9bfa749 (new upgraded versions)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|