myshell-py 0.2.0__py3-none-any.whl
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/__init__.py +1 -0
- myshell/__main__.py +5 -0
- myshell/aliases.py +22 -0
- myshell/arith.py +273 -0
- myshell/builtins.py +490 -0
- myshell/cli.py +155 -0
- myshell/compat.py +14 -0
- myshell/completion.py +137 -0
- myshell/coreutils.py +837 -0
- myshell/editor.py +218 -0
- myshell/errors.py +41 -0
- myshell/executor.py +752 -0
- myshell/expand.py +704 -0
- myshell/guide.py +609 -0
- myshell/heredoc.py +26 -0
- myshell/highlight.py +227 -0
- myshell/history.py +123 -0
- myshell/jobs.py +254 -0
- myshell/lexer.py +246 -0
- myshell/more_builtins.py +544 -0
- myshell/parser.py +437 -0
- myshell/paths.py +18 -0
- myshell/progress.py +98 -0
- myshell/prompt.py +197 -0
- myshell/quiz.py +148 -0
- myshell/state.py +107 -0
- myshell_py-0.2.0.dist-info/METADATA +195 -0
- myshell_py-0.2.0.dist-info/RECORD +30 -0
- myshell_py-0.2.0.dist-info/WHEEL +4 -0
- myshell_py-0.2.0.dist-info/entry_points.txt +2 -0
myshell/guide.py
ADDED
|
@@ -0,0 +1,609 @@
|
|
|
1
|
+
"""Pip, the shell guide: a small character that greets you, teaches by example,
|
|
2
|
+
and explains mistakes. Pip is an original character made for this shell.
|
|
3
|
+
|
|
4
|
+
guide open the topic menu
|
|
5
|
+
guide TOPIC run one lesson (a name or a number)
|
|
6
|
+
guide list list the topics
|
|
7
|
+
guide cheat print a cheat sheet
|
|
8
|
+
guide quiz [TOPIC] [N] test yourself with N questions (default 5)
|
|
9
|
+
guide progress show finished lessons and quiz scores (reset clears them)
|
|
10
|
+
guide tip print a random tip
|
|
11
|
+
guide off | on hide or show Pip's greeting and hints
|
|
12
|
+
|
|
13
|
+
Set GUIDE=off in ~/.myshellrc to start without Pip."""
|
|
14
|
+
import difflib
|
|
15
|
+
import os
|
|
16
|
+
import random
|
|
17
|
+
import shutil
|
|
18
|
+
import sys
|
|
19
|
+
import tempfile
|
|
20
|
+
import textwrap
|
|
21
|
+
from dataclasses import dataclass, field
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
from typing import Callable, List, Optional, TextIO
|
|
24
|
+
|
|
25
|
+
from . import compat, history, progress, quiz
|
|
26
|
+
from .state import ShellState
|
|
27
|
+
|
|
28
|
+
# --- the character ---------------------------------------------------------
|
|
29
|
+
|
|
30
|
+
ART = [
|
|
31
|
+
r" ,---. ",
|
|
32
|
+
r"( {e} )",
|
|
33
|
+
r" \ {m} / ",
|
|
34
|
+
r" (_@_)>",
|
|
35
|
+
]
|
|
36
|
+
MOODS = { # mood: (eyes, mouth)
|
|
37
|
+
"happy": ("^ ^", "v"),
|
|
38
|
+
"think": ("o o", "-"),
|
|
39
|
+
"worried": ("' '", "~"),
|
|
40
|
+
"wow": ("* *", "O"),
|
|
41
|
+
}
|
|
42
|
+
ART_WIDTH = 7
|
|
43
|
+
YELLOW, RESET = "\x1b[33m", "\x1b[0m"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def pip_lines(mood: str = "happy") -> List[str]:
|
|
47
|
+
eyes, mouth = MOODS.get(mood, MOODS["happy"])
|
|
48
|
+
return [line.format(e=eyes, m=mouth).ljust(ART_WIDTH)[:ART_WIDTH] for line in ART]
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def bubble(text: str, width: int) -> List[str]:
|
|
52
|
+
"""Wrap text and draw a box around it."""
|
|
53
|
+
wrapped: List[str] = []
|
|
54
|
+
for paragraph in text.split("\n"):
|
|
55
|
+
wrapped.extend(textwrap.wrap(paragraph, width) or [""])
|
|
56
|
+
inner = max(len(line) for line in wrapped)
|
|
57
|
+
lines = ["." + "-" * (inner + 2) + "."]
|
|
58
|
+
lines += ["| " + line.ljust(inner) + " |" for line in wrapped]
|
|
59
|
+
lines.append("'" + "-" * (inner + 2) + "'")
|
|
60
|
+
return lines
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def use_color(out: TextIO) -> bool:
|
|
64
|
+
return (hasattr(out, "isatty") and out.isatty() and "NO_COLOR" not in os.environ
|
|
65
|
+
and os.environ.get("TERM", "") not in ("", "dumb"))
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def render(text: str, mood: str = "happy", color: bool = False, columns: int = 80) -> str:
|
|
69
|
+
"""Pip on the left and a speech bubble on the right."""
|
|
70
|
+
width = max(20, min(columns - ART_WIDTH - 8, 60))
|
|
71
|
+
art = pip_lines(mood)
|
|
72
|
+
box = bubble(text, width)
|
|
73
|
+
rows = max(len(art), len(box))
|
|
74
|
+
out = []
|
|
75
|
+
for i in range(rows):
|
|
76
|
+
face = art[i] if i < len(art) else " " * ART_WIDTH
|
|
77
|
+
if color and i < len(art):
|
|
78
|
+
face = YELLOW + face + RESET
|
|
79
|
+
out.append(f"{face} {box[i] if i < len(box) else ''}".rstrip())
|
|
80
|
+
return "\n".join(out)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def say(text: str, mood: str = "happy", out: Optional[TextIO] = None) -> None:
|
|
84
|
+
out = out or sys.stdout
|
|
85
|
+
columns = shutil.get_terminal_size((80, 24)).columns
|
|
86
|
+
print(render(text, mood, use_color(out), columns), file=out)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
# --- lessons ---------------------------------------------------------------
|
|
90
|
+
|
|
91
|
+
@dataclass
|
|
92
|
+
class Step:
|
|
93
|
+
text: str
|
|
94
|
+
command: str = ""
|
|
95
|
+
run: bool = True # False shows the command without running it
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
@dataclass
|
|
99
|
+
class Lesson:
|
|
100
|
+
key: str
|
|
101
|
+
title: str
|
|
102
|
+
summary: str
|
|
103
|
+
steps: List[Step] = field(default_factory=list)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def build_lessons() -> List[Lesson]:
|
|
107
|
+
tmp = Path(tempfile.gettempdir()).as_posix() # forward slashes, so Windows paths work too
|
|
108
|
+
demo = f"{tmp}/pip_demo.txt"
|
|
109
|
+
wild = f"{tmp}/pip_wild"
|
|
110
|
+
background = ([Step("Add & to run a command in the background. jobs lists them. wait waits.",
|
|
111
|
+
"sleep 1 & jobs; wait")] if compat.HAS_FORK else
|
|
112
|
+
[Step("On this system commands do not run in the background. On Linux and macOS, "
|
|
113
|
+
"a trailing & starts one, jobs lists them and wait waits.")])
|
|
114
|
+
return [
|
|
115
|
+
Lesson("basics", "First steps", "run commands and move around", [
|
|
116
|
+
Step("A shell runs commands. echo prints text.", "echo hello from myshell"),
|
|
117
|
+
Step("pwd shows the folder you are in.", "pwd"),
|
|
118
|
+
Step("cd moves you to another folder. cd - jumps back.", "cd / && pwd && cd -"),
|
|
119
|
+
Step("Tab completes commands and file names. Press it twice to see choices. "
|
|
120
|
+
"Press the up arrow to bring back an earlier command."),
|
|
121
|
+
]),
|
|
122
|
+
Lesson("pipes", "Pipes and files", "connect commands and save output", [
|
|
123
|
+
Step("A pipe sends the output of one command into the next.",
|
|
124
|
+
"echo hello | tr a-z A-Z"),
|
|
125
|
+
Step("> writes output to a file. >> adds to the end of a file.",
|
|
126
|
+
f"echo first > {demo}; echo second >> {demo}; cat {demo}; rm {demo}"),
|
|
127
|
+
Step("2>&1 sends error messages down the same path as normal output.",
|
|
128
|
+
"ls /no/such/folder 2>&1 | head -1"),
|
|
129
|
+
Step("A here-string feeds a line of text to a command as input.",
|
|
130
|
+
"cat <<< 'from a here-string'"),
|
|
131
|
+
Step("A here-document feeds several lines. It ends at the marker word.",
|
|
132
|
+
"cat <<EOF\nline one\nline two\nEOF", run=False),
|
|
133
|
+
]),
|
|
134
|
+
Lesson("variables", "Variables and math", "store values and calculate", [
|
|
135
|
+
Step("Set a variable with NAME=value. Read it with $NAME.",
|
|
136
|
+
"demo=world; echo hello $demo; unset demo"),
|
|
137
|
+
Step("Put math inside $(( )). It handles + - * / % and more.",
|
|
138
|
+
"echo $((6 * 7))"),
|
|
139
|
+
Step("Variables work inside math too, with += and similar.",
|
|
140
|
+
"n=5; n=$((n + 1)); echo n is $n; unset n"),
|
|
141
|
+
Step("$( ) captures the output of a command. Backticks do the same.",
|
|
142
|
+
"echo I am in $(pwd)"),
|
|
143
|
+
Step("$? holds the exit status of the last command. 0 means success.",
|
|
144
|
+
"true; echo $?; false; echo $?"),
|
|
145
|
+
]),
|
|
146
|
+
Lesson("quotes", "Quotes and wildcards", "control what the shell changes", [
|
|
147
|
+
Step("Single quotes keep text exactly as typed.",
|
|
148
|
+
"echo '$HOME stays as typed'"),
|
|
149
|
+
Step("Double quotes allow variables and keep spaces together.",
|
|
150
|
+
'echo "your home is $HOME"'),
|
|
151
|
+
Step("A star matches any run of characters in file names. This makes two demo files "
|
|
152
|
+
"and matches them.",
|
|
153
|
+
f"touch {wild}_a.demo {wild}_b.demo; echo {wild}_*.demo; rm {wild}_*.demo"),
|
|
154
|
+
Step("A backslash turns off the next character's special meaning.",
|
|
155
|
+
r"echo \$HOME costs \* nothing"),
|
|
156
|
+
]),
|
|
157
|
+
Lesson("logic", "Choices and loops", "decide and repeat", [
|
|
158
|
+
Step("&& runs the next command only after success. || runs it after failure.",
|
|
159
|
+
"true && echo yes; false || echo fallback"),
|
|
160
|
+
Step("if tests a condition. [ ] compares numbers, text and files.",
|
|
161
|
+
"if [ 3 -gt 2 ]; then echo bigger; else echo smaller; fi"),
|
|
162
|
+
Step("for repeats a command for each item in a list.",
|
|
163
|
+
"for n in 1 2 3; do echo number $n; done"),
|
|
164
|
+
Step("while repeats as long as a test passes. break leaves a loop early.",
|
|
165
|
+
"i=0; while [ $i -lt 5 ]; do i=$((i+1)); [ $i = 3 ] && break; echo i is $i; done; unset i"),
|
|
166
|
+
Step("File tests: -f is a file, -d is a folder, -e exists.",
|
|
167
|
+
"[ -d . ] && echo . is a folder"),
|
|
168
|
+
]),
|
|
169
|
+
Lesson("jobs", "Background jobs", "run several things at once", [
|
|
170
|
+
*background,
|
|
171
|
+
Step("Press Ctrl+C to stop a running command. Press Ctrl+Z to pause it. "
|
|
172
|
+
"Then bg runs it in the background, and fg brings it back."),
|
|
173
|
+
]),
|
|
174
|
+
Lesson("functions", "Functions and arguments", "name a few commands and reuse them", [
|
|
175
|
+
Step("A function groups commands under a name. Call it like any command.",
|
|
176
|
+
"pip_hi() { echo hello $1; }; pip_hi Pip"),
|
|
177
|
+
Step("$1, $2 ... are the arguments. $# counts them. $@ lists them all.",
|
|
178
|
+
'pip_args() { echo "$# arguments: $@"; }; pip_args one "two words" three'),
|
|
179
|
+
Step('Use "$@" in quotes to pass every argument on, with spaces kept.',
|
|
180
|
+
'pip_each() { for item in "$@"; do echo "[$item]"; done; }; pip_each "a b" c'),
|
|
181
|
+
Step("return ends the function with a status. $? shows it.",
|
|
182
|
+
"pip_check() { [ $1 -gt 5 ] && return 0; return 1; }; pip_check 9; echo $?"),
|
|
183
|
+
Step("local keeps a variable inside the function.",
|
|
184
|
+
"x=outside; pip_local() { local x=inside; echo $x; }; pip_local; echo $x; unset x"),
|
|
185
|
+
Step("A for loop with no list walks over the arguments. Scripts get arguments too: "
|
|
186
|
+
"myshell script.sh a b makes $1 equal to a.",
|
|
187
|
+
"pip_walk() { for a; do echo item $a; done; }; pip_walk x y; "
|
|
188
|
+
"unset -f pip_hi pip_args pip_each pip_check pip_local pip_walk"),
|
|
189
|
+
]),
|
|
190
|
+
Lesson("expansion", "Expansions", "defaults, trimming, replacing and braces", [
|
|
191
|
+
Step("${NAME:-default} uses a default when NAME is empty or unset.",
|
|
192
|
+
"echo ${pip_none:-fallback}"),
|
|
193
|
+
Step("${#NAME} is the length of the value.",
|
|
194
|
+
"pip_w=shell; echo ${#pip_w}"),
|
|
195
|
+
Step("${NAME%pattern} cuts a matching ending. ${NAME#pattern} cuts a matching start. "
|
|
196
|
+
"Doubling the symbol cuts the longest match.",
|
|
197
|
+
"pip_f=report.final.txt; echo ${pip_f%.txt} ${pip_f%%.*} ${pip_f#*.} ${pip_f##*.}"),
|
|
198
|
+
Step("${NAME/old/new} replaces the first match. Two slashes replace all.",
|
|
199
|
+
"echo ${pip_f/./_} ${pip_f//./_}"),
|
|
200
|
+
Step("${NAME:start:length} cuts a slice. ${NAME^^} makes capitals.",
|
|
201
|
+
"echo ${pip_f:0:6} ${pip_f^^}; unset pip_f pip_w"),
|
|
202
|
+
Step("{a,b} builds several words. {1..5} counts.",
|
|
203
|
+
"echo file.{txt,md}; echo {1..5}; echo {a..e}; echo {01..03}"),
|
|
204
|
+
Step("Braces save typing when you make files or folders.",
|
|
205
|
+
f"mkdir -p {tmp}/pip_b/{{one,two}}; ls {tmp}/pip_b; rm -r {tmp}/pip_b"),
|
|
206
|
+
]),
|
|
207
|
+
Lesson("case", "Case statements", "match one value against patterns", [
|
|
208
|
+
Step("case compares a word with patterns. Each arm ends with ;;.",
|
|
209
|
+
"case apple in apple) echo fruit;; carrot) echo vegetable;; esac"),
|
|
210
|
+
Step("Use | for several patterns and * as the catch-all.",
|
|
211
|
+
"case notes.md in *.txt|*.md) echo text;; *.png) echo image;; *) echo other;; esac"),
|
|
212
|
+
Step("Patterns can use ? and [ ] too.",
|
|
213
|
+
"case 7 in [0-9]) echo one digit;; *) echo longer;; esac"),
|
|
214
|
+
Step("Inside a function, case makes a tidy menu.",
|
|
215
|
+
"pip_do() { case $1 in start) echo starting;; stop) echo stopping;; "
|
|
216
|
+
"*) echo unknown $1;; esac; }; pip_do start; pip_do jump; unset -f pip_do"),
|
|
217
|
+
]),
|
|
218
|
+
Lesson("tools", "More builtins", "read, printf, set, env, which, trap and friends", [
|
|
219
|
+
Step("read puts a line of input into variables. Here it reads a here-string.",
|
|
220
|
+
'read pip_a pip_b <<< "first second third"; echo $pip_a / $pip_b; unset pip_a pip_b'),
|
|
221
|
+
Step("printf formats text. %s is text, %d is a whole number, %5.2f is a decimal.",
|
|
222
|
+
"printf '%s has %d items costing %5.2f\\n' cart 3 9.5"),
|
|
223
|
+
Step("printf repeats its format for extra arguments.",
|
|
224
|
+
"printf '%s\\n' one two three"),
|
|
225
|
+
Step("env lists the environment. env NAME=value command runs a command with that value.",
|
|
226
|
+
"env PIP_COLOR=blue echo run with a temporary value"),
|
|
227
|
+
Step("which tells how a name runs: builtin, alias, function or program path.",
|
|
228
|
+
"alias pip_a='echo hi'; which echo pip_a; unalias pip_a"),
|
|
229
|
+
Step("trap runs a command when a signal or the shell exit arrives.",
|
|
230
|
+
"trap 'echo goodbye from trap' EXIT; trap; trap - EXIT"),
|
|
231
|
+
Step("set -e stops a script at the first failure. set -u stops at an unset variable. "
|
|
232
|
+
"set -x prints each command. Turn one off with +e, +u or +x. "
|
|
233
|
+
"set -- a b c sets $1 $2 $3."),
|
|
234
|
+
Step("exec replaces the shell with a command. true, false and : do nothing "
|
|
235
|
+
"and give status 0 or 1."),
|
|
236
|
+
]),
|
|
237
|
+
Lesson("prompt", "Prompt extras", "git branch, the time and slow commands", [
|
|
238
|
+
Step("Inside a git repository the default prompt shows the branch in brackets. "
|
|
239
|
+
"Use \\g in your own PS1 to place it."),
|
|
240
|
+
Step("\\t is the time as 24-hour HH:MM:SS. \\A is HH:MM. \\d is the date.",
|
|
241
|
+
"PS1='\\t \\w \\$ '", run=False),
|
|
242
|
+
Step("The shell prints how long a command took when it ran longer than 2 seconds. "
|
|
243
|
+
"Change the limit with SLOW_COMMAND_SECS, or set it to off.",
|
|
244
|
+
"SLOW_COMMAND_SECS=5", run=False),
|
|
245
|
+
]),
|
|
246
|
+
Lesson("typing", "Typing faster", "history search, suggestions and colors", [
|
|
247
|
+
Step("Press Ctrl+R and type part of an old command. Press Ctrl+R again for the "
|
|
248
|
+
"next match. Enter runs it. Esc lets you edit it first."),
|
|
249
|
+
Step("As you type, a grey suggestion from your history appears. "
|
|
250
|
+
"Press the Right arrow or End to accept it."),
|
|
251
|
+
Step("Colors show what you typed. A known command is green, an unknown one is red, "
|
|
252
|
+
"strings are yellow and variables are cyan. A red command is a typo."),
|
|
253
|
+
Step("If your terminal does not support this, the shell falls back to a plain prompt. "
|
|
254
|
+
"Set MYSHELL_EDITOR=basic to choose that yourself."),
|
|
255
|
+
]),
|
|
256
|
+
Lesson("customize", "Make it yours", "aliases, prompt and history", [
|
|
257
|
+
Step("An alias is a short name for a longer command.",
|
|
258
|
+
"alias ll='ls -l'", run=False),
|
|
259
|
+
Step("PS1 sets your prompt. \\w is the folder, \\u is your name, \\? is the last status. "
|
|
260
|
+
"More in the prompt lesson.",
|
|
261
|
+
"PS1='\\u \\w \\$ '", run=False),
|
|
262
|
+
Step("Put aliases and settings in ~/.myshellrc and they load at every start. "
|
|
263
|
+
"Add GUIDE=off there if you do not want me."),
|
|
264
|
+
Step("history lists earlier commands. history 5 shows the last five.",
|
|
265
|
+
"history 5"),
|
|
266
|
+
]),
|
|
267
|
+
]
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
CHEAT = """\
|
|
271
|
+
Run and combine a | b a && b a || b a; b a &
|
|
272
|
+
Redirect > file >> file < file 2> file 2>&1
|
|
273
|
+
Text input <<< 'text' <<EOF ... EOF
|
|
274
|
+
Variables X=1 $X ${X} $? $$
|
|
275
|
+
Capture and math $(cmd) `cmd` $((1 + 2))
|
|
276
|
+
Quotes 'literal' "with $X" \\x
|
|
277
|
+
Wildcards * ? [ab] ~
|
|
278
|
+
Tests [ -f file ] [ -d dir ] [ -z str ] [ 1 -lt 2 ] [ a = b ]
|
|
279
|
+
Functions name() { cmds; } $1 $2 $# $@ "$@" return N local X
|
|
280
|
+
Expansions ${X:-dflt} ${#X} ${X%.txt} ${X#pre} ${X/old/new} ${X:1:3} {a,b} {1..5}
|
|
281
|
+
Choices if C; then A; elif D; then B; else E; fi
|
|
282
|
+
Case case $X in a|b) cmds;; *.txt) cmds;; *) cmds;; esac
|
|
283
|
+
Loops for X in a b; do ..; done while C; do ..; done until C; do ..; done
|
|
284
|
+
Loop control break continue break 2
|
|
285
|
+
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
|
|
287
|
+
source exec trap shift local history true false : exit
|
|
288
|
+
Files and text ls cat head tr wc grep touch mkdir rm cp mv sleep
|
|
289
|
+
Set options set -e (stop on error) set -u (unset is error) set -x (trace)
|
|
290
|
+
Typing Ctrl+R search history Right arrow takes the suggestion
|
|
291
|
+
Guide guide guide TOPIC guide cheat guide tip guide quiz guide progress"""
|
|
292
|
+
|
|
293
|
+
TIPS = [
|
|
294
|
+
"Press Tab to complete a command or a file name.",
|
|
295
|
+
"Press the up arrow to bring back your last command.",
|
|
296
|
+
"cd - takes you back to the folder you were in before.",
|
|
297
|
+
"Use && to run a second command only when the first one works.",
|
|
298
|
+
"echo $? shows whether your last command worked. 0 means yes.",
|
|
299
|
+
"Wrap a variable in double quotes when it may hold spaces.",
|
|
300
|
+
"history 10 shows your last ten commands.",
|
|
301
|
+
"Put aliases in ~/.myshellrc and they load every time you start.",
|
|
302
|
+
"Use type NAME to see whether a name is a builtin, an alias or a program.",
|
|
303
|
+
"Press Ctrl+Z to pause a program. Then bg or fg decides what happens next.",
|
|
304
|
+
"Use $((a + b)) for quick math right in the prompt.",
|
|
305
|
+
"A trailing & runs a command in the background.",
|
|
306
|
+
"Press Ctrl+R and type a few letters to search your history.",
|
|
307
|
+
"Use ${NAME:-default} to fall back to a default value.",
|
|
308
|
+
"Use {1..5} or file.{txt,md} to save typing.",
|
|
309
|
+
"Try guide quiz to test what you know.",
|
|
310
|
+
"Wrap repeated commands in a function: name() { echo hi; }.",
|
|
311
|
+
"Type guide progress to see which lessons you finished.",
|
|
312
|
+
]
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def tip() -> str:
|
|
316
|
+
return random.choice(TIPS)
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
# --- hints -----------------------------------------------------------------
|
|
320
|
+
|
|
321
|
+
_path_cache: dict = {}
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def known_commands() -> List[str]:
|
|
325
|
+
"""Builtins, aliases are added by the caller, and every program on PATH."""
|
|
326
|
+
from .builtins import builtin_names
|
|
327
|
+
path = os.environ.get("PATH", "")
|
|
328
|
+
if path not in _path_cache:
|
|
329
|
+
names = set()
|
|
330
|
+
for folder in path.split(os.pathsep):
|
|
331
|
+
try:
|
|
332
|
+
for entry in os.listdir(folder or "."):
|
|
333
|
+
full = os.path.join(folder, entry)
|
|
334
|
+
if os.path.isfile(full) and os.access(full, os.X_OK):
|
|
335
|
+
names.add(entry)
|
|
336
|
+
except OSError:
|
|
337
|
+
pass
|
|
338
|
+
_path_cache.clear()
|
|
339
|
+
_path_cache[path] = sorted(names)
|
|
340
|
+
return sorted(set(builtin_names()) | set(_path_cache[path]))
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def missing_hint(name: str, state: ShellState) -> Optional[str]:
|
|
344
|
+
"""What Pip says after `name: command not found`. None when the program exists."""
|
|
345
|
+
if "/" in name or shutil.which(name):
|
|
346
|
+
return None
|
|
347
|
+
candidates = known_commands() + list(state.aliases)
|
|
348
|
+
close = difflib.get_close_matches(name, candidates, n=3, cutoff=0.7)
|
|
349
|
+
if close:
|
|
350
|
+
return (f"I do not know '{name}'. Did you mean '{close[0]}'?"
|
|
351
|
+
if len(close) == 1 else
|
|
352
|
+
f"I do not know '{name}'. Did you mean " +
|
|
353
|
+
", ".join(f"'{c}'" for c in close) + "?")
|
|
354
|
+
return f"I could not find '{name}'. Check the spelling, or install the program."
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
SYNTAX_HINTS = [
|
|
358
|
+
("unterminated quote", "A quote was opened and never closed. Add the matching quote."),
|
|
359
|
+
("unterminated command substitution",
|
|
360
|
+
"A $( or a backtick was opened and never closed. Add the closing ) or backtick."),
|
|
361
|
+
("unexpected end of file", "A block is still open. End it with fi or done."),
|
|
362
|
+
("unexpected end of line",
|
|
363
|
+
"The line ended too early. Something must follow the last operator."),
|
|
364
|
+
("unexpected token",
|
|
365
|
+
"The shell hit a symbol it did not expect. Operators such as | and && need a command "
|
|
366
|
+
"on both sides, and if needs then and fi."),
|
|
367
|
+
]
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def syntax_hint(message: str) -> Optional[str]:
|
|
371
|
+
for fragment, hint in SYNTAX_HINTS:
|
|
372
|
+
if fragment in message:
|
|
373
|
+
return hint
|
|
374
|
+
return None
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
# --- the builtin and the interactive menu ---------------------------------
|
|
378
|
+
|
|
379
|
+
Ask = Callable[[str], Optional[str]]
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def make_ask() -> Ask:
|
|
383
|
+
"""Read one line. Returns None at end of input. Answers stay out of the history."""
|
|
384
|
+
def ask(prompt: str) -> Optional[str]:
|
|
385
|
+
try:
|
|
386
|
+
before = history.length()
|
|
387
|
+
text = input(prompt)
|
|
388
|
+
if history.records_input() and history.length() > before:
|
|
389
|
+
history.forget_last()
|
|
390
|
+
return text.strip()
|
|
391
|
+
except EOFError:
|
|
392
|
+
return None
|
|
393
|
+
return ask
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def run_lesson(state: ShellState, lesson: Lesson, out: TextIO, ask: Ask) -> bool:
|
|
397
|
+
"""Teach one lesson. Returns False when the person stops or input ends."""
|
|
398
|
+
say(f"{lesson.title}: {lesson.summary}.", "happy", out)
|
|
399
|
+
for step in lesson.steps:
|
|
400
|
+
say(step.text, "think", out)
|
|
401
|
+
if not step.command:
|
|
402
|
+
continue
|
|
403
|
+
for line in step.command.split("\n"):
|
|
404
|
+
print(f" $ {line}", file=out)
|
|
405
|
+
if not step.run:
|
|
406
|
+
print(" (shown only. Type it yourself when you want it.)", file=out)
|
|
407
|
+
continue
|
|
408
|
+
answer = ask(" Enter runs it. s skips. q stops > ")
|
|
409
|
+
if answer is None or answer.lower() in ("q", "quit"):
|
|
410
|
+
say("Okay. Type guide when you want to continue.", "happy", out)
|
|
411
|
+
return False
|
|
412
|
+
if answer.lower() == "s":
|
|
413
|
+
continue
|
|
414
|
+
saved = state.last_status
|
|
415
|
+
try:
|
|
416
|
+
state.execute(step.command)
|
|
417
|
+
except Exception as e: # a lesson must never close the shell
|
|
418
|
+
print(e, file=out)
|
|
419
|
+
state.last_status = saved
|
|
420
|
+
print(file=out)
|
|
421
|
+
progress.mark_lesson(state.progress_file, lesson.key)
|
|
422
|
+
say("That is the topic. Pick another one, or press q. Try guide quiz to test yourself.",
|
|
423
|
+
"wow", out)
|
|
424
|
+
return True
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def find_lesson(lessons: List[Lesson], choice: str) -> Optional[Lesson]:
|
|
428
|
+
choice = choice.strip().lower()
|
|
429
|
+
if choice.isdigit() and 1 <= int(choice) <= len(lessons):
|
|
430
|
+
return lessons[int(choice) - 1]
|
|
431
|
+
for lesson in lessons:
|
|
432
|
+
if choice == lesson.key or (len(choice) >= 3 and lesson.key.startswith(choice)):
|
|
433
|
+
return lesson
|
|
434
|
+
return None
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
def print_topics(lessons: List[Lesson], out: TextIO, state: Optional[ShellState] = None) -> None:
|
|
438
|
+
done = set(progress.done_lessons(state.progress_file)) if state else set()
|
|
439
|
+
for i, lesson in enumerate(lessons, 1):
|
|
440
|
+
mark = "[x]" if lesson.key in done else "[ ]"
|
|
441
|
+
print(f" {i:>2}) {lesson.title:<24} {mark} {lesson.summary}", file=out)
|
|
442
|
+
print(" c) Cheat sheet", file=out)
|
|
443
|
+
print(" z) Quiz", file=out)
|
|
444
|
+
print(" p) Progress", file=out)
|
|
445
|
+
print(" q) Quit", file=out)
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
# --- quiz and progress -----------------------------------------------------
|
|
449
|
+
|
|
450
|
+
LETTERS = "abcd"
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def run_quiz(state: ShellState, out: TextIO, ask: Ask, topic: Optional[str] = None,
|
|
454
|
+
count: int = 5, rng: Optional[random.Random] = None) -> int:
|
|
455
|
+
"""Ask count multiple-choice questions. Answer with a letter or a number. q stops."""
|
|
456
|
+
questions = quiz.pick(count, topic, rng)
|
|
457
|
+
if not questions:
|
|
458
|
+
say("I have no questions for that topic.", "worried", out)
|
|
459
|
+
return 1
|
|
460
|
+
say(f"Quiz time: {len(questions)} question{'s' if len(questions) != 1 else ''}"
|
|
461
|
+
+ (f" about {topic}" if topic else "") + ". Answer with a letter. q stops.", "think", out)
|
|
462
|
+
score = 0
|
|
463
|
+
for number, item in enumerate(questions, 1):
|
|
464
|
+
print(f"\n{number}. {item.text}", file=out)
|
|
465
|
+
for letter, choice in zip(LETTERS, item.choices):
|
|
466
|
+
print(f" {letter}) {choice}", file=out)
|
|
467
|
+
while True:
|
|
468
|
+
answer = ask(" Your answer > ")
|
|
469
|
+
if answer is None or answer.lower() in ("q", "quit"):
|
|
470
|
+
say("Okay. No score saved for a quiz you stop.", "happy", out)
|
|
471
|
+
return 0
|
|
472
|
+
key = answer.lower()[:1]
|
|
473
|
+
if key in LETTERS[:len(item.choices)]:
|
|
474
|
+
picked = LETTERS.index(key)
|
|
475
|
+
elif key.isdigit() and 1 <= int(key) <= len(item.choices):
|
|
476
|
+
picked = int(key) - 1
|
|
477
|
+
else:
|
|
478
|
+
print(" Type a, b, c or d.", file=out)
|
|
479
|
+
continue
|
|
480
|
+
break
|
|
481
|
+
if picked == item.answer:
|
|
482
|
+
score += 1
|
|
483
|
+
say(f"Right. {item.why}", "wow", out)
|
|
484
|
+
else:
|
|
485
|
+
say(f"Not quite. The answer is {LETTERS[item.answer]}) {item.choices[item.answer]}. "
|
|
486
|
+
f"{item.why}", "worried", out)
|
|
487
|
+
best = progress.record_quiz(state.progress_file, topic or "all", score, len(questions))
|
|
488
|
+
ending = " That is your best score yet." if best and score else ""
|
|
489
|
+
say(f"You got {score} of {len(questions)}.{ending}",
|
|
490
|
+
"wow" if score == len(questions) else "happy", out)
|
|
491
|
+
return 0
|
|
492
|
+
|
|
493
|
+
|
|
494
|
+
def show_progress(state: ShellState, out: TextIO) -> None:
|
|
495
|
+
lessons = build_lessons()
|
|
496
|
+
done = set(progress.done_lessons(state.progress_file))
|
|
497
|
+
finished = [x for x in lessons if x.key in done]
|
|
498
|
+
print(f"Lessons finished: {len(finished)} of {len(lessons)}", file=out)
|
|
499
|
+
for lesson in lessons:
|
|
500
|
+
print(f" {'[x]' if lesson.key in done else '[ ]'} {lesson.title}", file=out)
|
|
501
|
+
scores = progress.best_scores(state.progress_file)
|
|
502
|
+
if scores:
|
|
503
|
+
print("Best quiz scores:", file=out)
|
|
504
|
+
for topic in sorted(scores):
|
|
505
|
+
got, total = scores[topic]
|
|
506
|
+
print(f" {topic:<12} {got} of {total}", file=out)
|
|
507
|
+
else:
|
|
508
|
+
print("No quiz taken yet. Try guide quiz.", file=out)
|
|
509
|
+
left = [x.key for x in lessons if x.key not in done]
|
|
510
|
+
if left:
|
|
511
|
+
say(f"Next up: {left[0]}. Type guide {left[0]}.", "happy", out)
|
|
512
|
+
else:
|
|
513
|
+
say("You finished every lesson. Keep going with guide quiz.", "wow", out)
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
def parse_quiz_args(args: List[str]):
|
|
517
|
+
"""guide quiz [TOPIC] [COUNT]. Returns (topic, count) or an error text."""
|
|
518
|
+
topic, count = None, 5
|
|
519
|
+
for a in args:
|
|
520
|
+
if a.isdigit():
|
|
521
|
+
count = max(1, min(int(a), 20))
|
|
522
|
+
elif a in quiz.topics():
|
|
523
|
+
topic = a
|
|
524
|
+
else:
|
|
525
|
+
matches = [t for t in quiz.topics() if len(a) >= 3 and t.startswith(a.lower())]
|
|
526
|
+
if len(matches) != 1:
|
|
527
|
+
return f"unknown quiz topic '{a}'. Topics: " + ", ".join(quiz.topics())
|
|
528
|
+
topic = matches[0]
|
|
529
|
+
return topic, count
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
def run_menu(state: ShellState, out: TextIO, ask: Ask) -> int:
|
|
533
|
+
lessons = build_lessons()
|
|
534
|
+
say("Hi, I am Pip. I show what this shell does with examples you can run. "
|
|
535
|
+
"Pick a topic.", "happy", out)
|
|
536
|
+
while True:
|
|
537
|
+
print_topics(lessons, out, state)
|
|
538
|
+
choice = ask("Pick one > ")
|
|
539
|
+
if choice is None or choice.lower() in ("q", "quit", "exit"):
|
|
540
|
+
say("See you soon. Type guide any time.", "happy", out)
|
|
541
|
+
return 0
|
|
542
|
+
if choice.lower() in ("c", "cheat"):
|
|
543
|
+
print(CHEAT, file=out)
|
|
544
|
+
continue
|
|
545
|
+
if choice.lower() in ("z", "quiz"):
|
|
546
|
+
run_quiz(state, out, ask)
|
|
547
|
+
continue
|
|
548
|
+
if choice.lower() in ("p", "progress"):
|
|
549
|
+
show_progress(state, out)
|
|
550
|
+
continue
|
|
551
|
+
lesson = find_lesson(lessons, choice)
|
|
552
|
+
if lesson is None:
|
|
553
|
+
say("I do not know that one. Type a number from the list.", "worried", out)
|
|
554
|
+
continue
|
|
555
|
+
if not run_lesson(state, lesson, out, ask):
|
|
556
|
+
return 0
|
|
557
|
+
|
|
558
|
+
|
|
559
|
+
def guide_enabled(state: ShellState) -> bool:
|
|
560
|
+
return (state.get_variable("GUIDE") or "").lower() != "off"
|
|
561
|
+
|
|
562
|
+
|
|
563
|
+
def greeting(state: ShellState, out: TextIO) -> None:
|
|
564
|
+
say("Hi, I am Pip, your shell guide. Type guide for a tour, or start typing. "
|
|
565
|
+
f"Tip: {tip()}", "happy", out)
|
|
566
|
+
|
|
567
|
+
|
|
568
|
+
def guide_main(state: ShellState, args: List[str], stdout: TextIO, stderr: TextIO) -> int:
|
|
569
|
+
if not args:
|
|
570
|
+
return run_menu(state, stdout, make_ask())
|
|
571
|
+
word = args[0].lower()
|
|
572
|
+
if word == "quiz":
|
|
573
|
+
parsed = parse_quiz_args(args[1:])
|
|
574
|
+
if isinstance(parsed, str):
|
|
575
|
+
print(f"guide: {parsed}", file=stderr)
|
|
576
|
+
return 1
|
|
577
|
+
return run_quiz(state, stdout, make_ask(), parsed[0], parsed[1])
|
|
578
|
+
if word == "progress" and args[1:] == ["reset"]:
|
|
579
|
+
progress.reset(state.progress_file)
|
|
580
|
+
say("Progress cleared.", "happy", stdout)
|
|
581
|
+
return 0
|
|
582
|
+
if len(args) > 1:
|
|
583
|
+
print("guide: too many arguments", file=stderr)
|
|
584
|
+
return 1
|
|
585
|
+
lessons = build_lessons()
|
|
586
|
+
if word == "progress":
|
|
587
|
+
show_progress(state, stdout)
|
|
588
|
+
return 0
|
|
589
|
+
if word == "list":
|
|
590
|
+
print_topics(lessons, stdout, state)
|
|
591
|
+
return 0
|
|
592
|
+
if word == "cheat":
|
|
593
|
+
print(CHEAT, file=stdout)
|
|
594
|
+
return 0
|
|
595
|
+
if word == "tip":
|
|
596
|
+
say(tip(), "happy", stdout)
|
|
597
|
+
return 0
|
|
598
|
+
if word in ("on", "off"):
|
|
599
|
+
state.set_variable("GUIDE", word)
|
|
600
|
+
say("Hints are on. I will greet you and explain mistakes." if word == "on"
|
|
601
|
+
else "Hints are off. Type guide on to bring me back.", "happy", stdout)
|
|
602
|
+
return 0
|
|
603
|
+
lesson = find_lesson(lessons, word)
|
|
604
|
+
if lesson is None:
|
|
605
|
+
print(f"guide: unknown topic '{args[0]}'. Type guide list to see the topics.",
|
|
606
|
+
file=stderr)
|
|
607
|
+
return 1
|
|
608
|
+
run_lesson(state, lesson, stdout, make_ask())
|
|
609
|
+
return 0
|
myshell/heredoc.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""Here-documents: reading the body that follows a line with << or <<-."""
|
|
2
|
+
import sys
|
|
3
|
+
from typing import Callable, List, Optional
|
|
4
|
+
|
|
5
|
+
ReadLine = Callable[[], Optional[str]]
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def read_heredoc_body(delimiter: str, strip_tabs: bool,
|
|
9
|
+
read_line: Optional[ReadLine]) -> str:
|
|
10
|
+
"""Read lines until one equals the delimiter. Returns the body with a newline
|
|
11
|
+
after each line. With strip_tabs (<<-), leading tabs are removed from every line,
|
|
12
|
+
including the delimiter line. If input ends first, the body so far is used and a
|
|
13
|
+
warning goes to stderr."""
|
|
14
|
+
lines: List[str] = []
|
|
15
|
+
while True:
|
|
16
|
+
line = read_line() if read_line is not None else None
|
|
17
|
+
if line is None:
|
|
18
|
+
print(f"myshell: warning: here-document delimited by end-of-file "
|
|
19
|
+
f"(wanted `{delimiter}')", file=sys.stderr)
|
|
20
|
+
break
|
|
21
|
+
if strip_tabs:
|
|
22
|
+
line = line.lstrip("\t")
|
|
23
|
+
if line == delimiter:
|
|
24
|
+
break
|
|
25
|
+
lines.append(line)
|
|
26
|
+
return "".join(line + "\n" for line in lines)
|