dulab 1.0.1__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.
- dulab/__init__.py +67 -0
- dulab/__main__.py +3 -0
- dulab/cli.py +454 -0
- dulab/commands.py +270 -0
- dulab/ds_programs.py +1489 -0
- dulab/os_programs.py +845 -0
- dulab/terminal.py +181 -0
- dulab-1.0.1.dist-info/METADATA +148 -0
- dulab-1.0.1.dist-info/RECORD +13 -0
- dulab-1.0.1.dist-info/WHEEL +5 -0
- dulab-1.0.1.dist-info/entry_points.txt +2 -0
- dulab-1.0.1.dist-info/licenses/LICENSE +21 -0
- dulab-1.0.1.dist-info/top_level.txt +1 -0
dulab/__init__.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""dulab - Operating Systems and Data Structures lab practicals in C++.
|
|
2
|
+
|
|
3
|
+
Run ``dulab`` (or ``python -m dulab``) for the menu.
|
|
4
|
+
|
|
5
|
+
From Python:
|
|
6
|
+
|
|
7
|
+
>>> import dulab
|
|
8
|
+
>>> print(dulab.get_code("os8")) # FCFS scheduling program
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from .commands import PARTS, QUESTION_PARTS
|
|
12
|
+
from .ds_programs import DS_PROGRAMS
|
|
13
|
+
from .os_programs import OS_PROGRAMS
|
|
14
|
+
|
|
15
|
+
__version__ = "1.0.1"
|
|
16
|
+
__all__ = ["SUBJECTS", "get", "get_code", "__version__"]
|
|
17
|
+
|
|
18
|
+
OS_COMMANDS = [
|
|
19
|
+
{
|
|
20
|
+
"id": "os2",
|
|
21
|
+
"subject": "os",
|
|
22
|
+
"number": 2,
|
|
23
|
+
"kind": "commands",
|
|
24
|
+
"title": "Linux commands: information, file and directory management",
|
|
25
|
+
"aim": "Execute various LINUX commands for: (i) Information Maintenance: wc, clear, cal, who, "
|
|
26
|
+
"date, pwd; (ii) File Management: cat, cp, rm, mv, cmp, comm, diff, find, grep, awk; "
|
|
27
|
+
"(iii) Directory Management: cd, mkdir, rmdir, ls.",
|
|
28
|
+
"parts": QUESTION_PARTS["2"],
|
|
29
|
+
},
|
|
30
|
+
{
|
|
31
|
+
"id": "os3",
|
|
32
|
+
"subject": "os",
|
|
33
|
+
"number": 3,
|
|
34
|
+
"kind": "commands",
|
|
35
|
+
"title": "Linux commands: process control, communication, protection",
|
|
36
|
+
"aim": "Execute various LINUX commands for: (i) Process Control: fork, getpid, ps, kill, sleep; "
|
|
37
|
+
"(ii) Communication: input-output redirection, pipe; "
|
|
38
|
+
"(iii) Protection Management: chmod, chown, chgrp.",
|
|
39
|
+
"parts": QUESTION_PARTS["3"],
|
|
40
|
+
},
|
|
41
|
+
]
|
|
42
|
+
|
|
43
|
+
OS_ITEMS = sorted(OS_COMMANDS + OS_PROGRAMS, key=lambda item: item["number"])
|
|
44
|
+
DS_ITEMS = list(DS_PROGRAMS)
|
|
45
|
+
|
|
46
|
+
SUBJECTS = {
|
|
47
|
+
"os": {"name": "Operating Systems (DSC08)", "language": "C++", "items": OS_ITEMS},
|
|
48
|
+
"ds": {"name": "Data Structures", "language": "C++", "items": DS_ITEMS},
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def get(item_id):
|
|
53
|
+
"""Return the practical with id like 'os8' or 'ds3'."""
|
|
54
|
+
key = str(item_id).strip().lower()
|
|
55
|
+
for subject in SUBJECTS.values():
|
|
56
|
+
for item in subject["items"]:
|
|
57
|
+
if item["id"] == key:
|
|
58
|
+
return item
|
|
59
|
+
raise ValueError("No practical called %r. Try os2-os12 or ds1-ds7." % item_id)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def get_code(item_id):
|
|
63
|
+
"""Return the source code of a program practical as one string."""
|
|
64
|
+
item = get(item_id)
|
|
65
|
+
if item["kind"] != "code":
|
|
66
|
+
raise ValueError("%s is a Linux commands practical, not a program." % item["id"])
|
|
67
|
+
return "\n".join(f["code"] for f in item["files"])
|
dulab/__main__.py
ADDED
dulab/cli.py
ADDED
|
@@ -0,0 +1,454 @@
|
|
|
1
|
+
"""dulab command-line menu.
|
|
2
|
+
|
|
3
|
+
Programs are saved to Desktop/<roll number>/<file>.
|
|
4
|
+
Linux-command practicals open a new terminal window and run the commands.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import argparse
|
|
8
|
+
import os
|
|
9
|
+
import re
|
|
10
|
+
import sys
|
|
11
|
+
import textwrap
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from . import SUBJECTS, __version__, get
|
|
15
|
+
from .commands import PARTS, build_script
|
|
16
|
+
from .terminal import TerminalError, open_in_new_terminal, run_here, write_script
|
|
17
|
+
|
|
18
|
+
# ------------------------------------------------------------------ colours
|
|
19
|
+
|
|
20
|
+
_COLOR = False
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _init_color():
|
|
24
|
+
global _COLOR
|
|
25
|
+
if os.environ.get("NO_COLOR") or not sys.stdout.isatty():
|
|
26
|
+
_COLOR = False
|
|
27
|
+
return
|
|
28
|
+
if sys.platform == "win32":
|
|
29
|
+
os.system("")
|
|
30
|
+
_COLOR = True
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _c(text, code):
|
|
34
|
+
return "\033[%sm%s\033[0m" % (code, text) if _COLOR else text
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def bold(t):
|
|
38
|
+
return _c(t, "1")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def cyan(t):
|
|
42
|
+
return _c(t, "1;36")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def green(t):
|
|
46
|
+
return _c(t, "1;32")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def yellow(t):
|
|
50
|
+
return _c(t, "33")
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def red(t):
|
|
54
|
+
return _c(t, "1;31")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def dim(t):
|
|
58
|
+
return _c(t, "2")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
# ------------------------------------------------------------------ Desktop
|
|
62
|
+
|
|
63
|
+
def _windows_desktop():
|
|
64
|
+
try:
|
|
65
|
+
import ctypes
|
|
66
|
+
import uuid
|
|
67
|
+
from ctypes import wintypes
|
|
68
|
+
|
|
69
|
+
class GUID(ctypes.Structure):
|
|
70
|
+
_fields_ = [("Data1", ctypes.c_uint32), ("Data2", ctypes.c_uint16),
|
|
71
|
+
("Data3", ctypes.c_uint16), ("Data4", ctypes.c_ubyte * 8)]
|
|
72
|
+
|
|
73
|
+
folder_id = GUID.from_buffer_copy(uuid.UUID("{B4BFCC3A-DB2C-424C-B029-7FE99A87C641}").bytes_le)
|
|
74
|
+
fn = ctypes.windll.shell32.SHGetKnownFolderPath
|
|
75
|
+
fn.argtypes = [ctypes.POINTER(GUID), wintypes.DWORD, wintypes.HANDLE,
|
|
76
|
+
ctypes.POINTER(ctypes.c_wchar_p)]
|
|
77
|
+
fn.restype = ctypes.c_long
|
|
78
|
+
out = ctypes.c_wchar_p()
|
|
79
|
+
if fn(ctypes.byref(folder_id), 0, None, ctypes.byref(out)) == 0 and out.value:
|
|
80
|
+
path = Path(out.value)
|
|
81
|
+
ctypes.windll.ole32.CoTaskMemFree(out)
|
|
82
|
+
return path
|
|
83
|
+
except Exception:
|
|
84
|
+
pass
|
|
85
|
+
try:
|
|
86
|
+
import winreg
|
|
87
|
+
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
|
|
88
|
+
r"Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders")
|
|
89
|
+
value, _ = winreg.QueryValueEx(key, "Desktop")
|
|
90
|
+
return Path(os.path.expandvars(value))
|
|
91
|
+
except Exception:
|
|
92
|
+
return None
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _xdg_desktop():
|
|
96
|
+
home = Path.home()
|
|
97
|
+
cfg = Path(os.environ.get("XDG_CONFIG_HOME") or home / ".config") / "user-dirs.dirs"
|
|
98
|
+
try:
|
|
99
|
+
for line in cfg.read_text(errors="ignore").splitlines():
|
|
100
|
+
m = re.match(r'\s*XDG_DESKTOP_DIR\s*=\s*"(.*)"\s*$', line)
|
|
101
|
+
if m:
|
|
102
|
+
p = Path(os.path.expandvars(m.group(1).replace("$HOME", str(home))))
|
|
103
|
+
if p != home:
|
|
104
|
+
return p
|
|
105
|
+
except OSError:
|
|
106
|
+
pass
|
|
107
|
+
return None
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def desktop_dir():
|
|
111
|
+
found = None
|
|
112
|
+
if sys.platform == "win32":
|
|
113
|
+
found = _windows_desktop()
|
|
114
|
+
elif sys.platform.startswith(("linux", "freebsd", "openbsd")):
|
|
115
|
+
found = _xdg_desktop()
|
|
116
|
+
return found or Path.home() / "Desktop"
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
# ------------------------------------------------------------------ roll number
|
|
120
|
+
|
|
121
|
+
_BAD_CHARS = set('<>:"/\\|?*')
|
|
122
|
+
_RESERVED = {"CON", "PRN", "AUX", "NUL"} | {"COM%d" % i for i in range(1, 10)} \
|
|
123
|
+
| {"LPT%d" % i for i in range(1, 10)}
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def check_roll(raw):
|
|
127
|
+
"""Return (roll, error). The roll number becomes a folder name."""
|
|
128
|
+
roll = (raw or "").strip()
|
|
129
|
+
if not roll:
|
|
130
|
+
return None, "Roll number cannot be empty."
|
|
131
|
+
bad = sorted({ch for ch in roll if ch in _BAD_CHARS or ord(ch) < 32})
|
|
132
|
+
if bad:
|
|
133
|
+
shown = " ".join(repr(ch) if ord(ch) < 32 else ch for ch in bad)
|
|
134
|
+
return None, "Roll number cannot contain: %s (use - or _ instead)" % shown
|
|
135
|
+
if roll.endswith("."):
|
|
136
|
+
return None, "Roll number cannot end with a dot."
|
|
137
|
+
if roll.split(".")[0].upper() in _RESERVED:
|
|
138
|
+
return None, "'%s' is a reserved name on Windows. Use your real roll number." % roll
|
|
139
|
+
if len(roll) > 60:
|
|
140
|
+
return None, "Roll number is too long (max 60 characters)."
|
|
141
|
+
return roll, None
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
# ------------------------------------------------------------------ saving programs
|
|
145
|
+
|
|
146
|
+
def save_file(f, roll, base_dir, overwrite):
|
|
147
|
+
"""Write one program file. ``overwrite`` is True/False or a function asked
|
|
148
|
+
when the file exists. Returns the path, or None if skipped."""
|
|
149
|
+
folder = Path(base_dir) / roll
|
|
150
|
+
folder.mkdir(parents=True, exist_ok=True)
|
|
151
|
+
path = folder / f["name"]
|
|
152
|
+
if path.exists():
|
|
153
|
+
ok = overwrite(path) if callable(overwrite) else overwrite
|
|
154
|
+
if not ok:
|
|
155
|
+
return None
|
|
156
|
+
with open(path, "w", encoding="utf-8", newline="\n") as fh:
|
|
157
|
+
fh.write(f["code"])
|
|
158
|
+
return path
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def save_items(items, roll, base_dir, overwrite, show_hints=True):
|
|
162
|
+
saved = []
|
|
163
|
+
for item in items:
|
|
164
|
+
for f in item["files"]:
|
|
165
|
+
try:
|
|
166
|
+
path = save_file(f, roll, base_dir, overwrite)
|
|
167
|
+
except OSError as e:
|
|
168
|
+
print(red(" Could not write %s: %s" % (f["name"], e)))
|
|
169
|
+
return saved
|
|
170
|
+
if path is None:
|
|
171
|
+
print(dim(" Skipped %s" % f["name"]))
|
|
172
|
+
else:
|
|
173
|
+
saved.append((path, f))
|
|
174
|
+
print(green(" Saved: ") + str(path))
|
|
175
|
+
if not saved:
|
|
176
|
+
return saved
|
|
177
|
+
folder = saved[0][0].parent
|
|
178
|
+
if show_hints and len(saved) <= 3:
|
|
179
|
+
print(dim("\n To compile and run:"))
|
|
180
|
+
print(" cd \"%s\"" % folder)
|
|
181
|
+
for _, f in saved:
|
|
182
|
+
print(" " + f["build"])
|
|
183
|
+
print(" " + f["run"])
|
|
184
|
+
else:
|
|
185
|
+
print(green("\n Done! %d files saved in %s" % (len(saved), folder)))
|
|
186
|
+
print(dim(" Compile with g++ file.cpp -o name (add -pthread for os11)"))
|
|
187
|
+
if sys.platform == "win32" and any(f["name"].startswith("os") for _, f in saved):
|
|
188
|
+
print(yellow(" Note: the OS programs use Linux system calls. Compile and run them on Linux or in WSL."))
|
|
189
|
+
return saved
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
# ------------------------------------------------------------------ Linux commands
|
|
193
|
+
|
|
194
|
+
def launch_commands(part_ids, here=False):
|
|
195
|
+
script = write_script(build_script(part_ids), "dulab_os%s.sh" % "_".join(part_ids))
|
|
196
|
+
if here:
|
|
197
|
+
try:
|
|
198
|
+
run_here(script)
|
|
199
|
+
except TerminalError as e:
|
|
200
|
+
print(yellow(str(e)))
|
|
201
|
+
return
|
|
202
|
+
try:
|
|
203
|
+
name = open_in_new_terminal(script)
|
|
204
|
+
print(green(" Opened a new terminal window ") + dim("(%s)" % name))
|
|
205
|
+
except TerminalError as e:
|
|
206
|
+
print(yellow(" " + str(e).replace("\n", "\n ")))
|
|
207
|
+
if sys.platform != "win32" and _confirm(" Run the commands in this window instead?", True):
|
|
208
|
+
run_here(script)
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
# ------------------------------------------------------------------ parsing ids
|
|
212
|
+
|
|
213
|
+
_ROMAN = {"i": "i", "ii": "ii", "iii": "iii", "1": "i", "2": "ii", "3": "iii", "a": "i", "b": "ii", "c": "iii"}
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def parse_target(text):
|
|
217
|
+
"""'os8' -> ('items', [item]); 'os' -> all OS programs; 'all' -> every program;
|
|
218
|
+
'os2' / 'os2ii' -> ('commands', [part ids])."""
|
|
219
|
+
key = re.sub(r"[\s()\.\-_]", "", str(text).lower())
|
|
220
|
+
if key in SUBJECTS:
|
|
221
|
+
return "items", [i for i in SUBJECTS[key]["items"] if i["kind"] == "code"]
|
|
222
|
+
if key == "all":
|
|
223
|
+
return "items", [i for s in SUBJECTS.values() for i in s["items"] if i["kind"] == "code"]
|
|
224
|
+
m = re.match(r"^(os|ds)0*(\d+)(i{1,3})?$", key)
|
|
225
|
+
if not m:
|
|
226
|
+
raise ValueError("Unknown practical %r. Examples: os8, ds3, os2, os2ii, os, ds, all" % text)
|
|
227
|
+
item = get(m.group(1) + m.group(2))
|
|
228
|
+
if item["kind"] == "commands":
|
|
229
|
+
if m.group(3):
|
|
230
|
+
return "commands", ["%d%s" % (item["number"], m.group(3))]
|
|
231
|
+
return "commands", list(item["parts"])
|
|
232
|
+
if m.group(3):
|
|
233
|
+
raise ValueError("%s has no parts." % item["id"])
|
|
234
|
+
return "items", [item]
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
# ------------------------------------------------------------------ interactive menu
|
|
238
|
+
|
|
239
|
+
def _ask(prompt):
|
|
240
|
+
return input(yellow(prompt))
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def _confirm(prompt, default=False):
|
|
244
|
+
hint = " [Y/n]: " if default else " [y/N]: "
|
|
245
|
+
ans = _ask(prompt + hint).strip().lower()
|
|
246
|
+
return default if not ans else ans in ("y", "yes")
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _ask_overwrite(path):
|
|
250
|
+
return _confirm(" %s already exists. Overwrite?" % path.name)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
class _Quit(Exception):
|
|
254
|
+
pass
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def _banner(base_dir):
|
|
258
|
+
line = "=" * 64
|
|
259
|
+
print(cyan(line))
|
|
260
|
+
print(cyan(" DULAB") + dim(" v%s OS and DS lab practicals" % __version__))
|
|
261
|
+
print(cyan(line))
|
|
262
|
+
print(dim("Programs are saved in: %s" % (Path(base_dir) / "<roll number>")))
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def _ask_roll(state):
|
|
266
|
+
last = state.get("roll")
|
|
267
|
+
while True:
|
|
268
|
+
prompt = "Enter your roll number" + ((" [%s]: " % last) if last else ": ")
|
|
269
|
+
raw = _ask(prompt)
|
|
270
|
+
if not raw.strip() and last:
|
|
271
|
+
return last
|
|
272
|
+
roll, err = check_roll(raw)
|
|
273
|
+
if err:
|
|
274
|
+
print(red(" " + err))
|
|
275
|
+
continue
|
|
276
|
+
state["roll"] = roll
|
|
277
|
+
return roll
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def _choose_part(item):
|
|
281
|
+
print()
|
|
282
|
+
for pid in item["parts"]:
|
|
283
|
+
roman = pid[len(str(item["number"])):]
|
|
284
|
+
print(" %s %s" % (bold("%-4s" % (roman + ".")), PARTS[pid]["label"]))
|
|
285
|
+
print(" %s All three" % bold("A. "))
|
|
286
|
+
print(" %s Back" % bold("B. "))
|
|
287
|
+
while True:
|
|
288
|
+
ans = _ask("Choose a part (i, ii, iii, A = all, B = back): ").strip().lower().rstrip(".")
|
|
289
|
+
if ans in ("b", "back"):
|
|
290
|
+
return None
|
|
291
|
+
if ans in ("a", "all", ""):
|
|
292
|
+
return list(item["parts"])
|
|
293
|
+
if ans in _ROMAN and ans not in ("a", "b"):
|
|
294
|
+
return ["%d%s" % (item["number"], _ROMAN[ans])]
|
|
295
|
+
print(red(" Please type i, ii, iii, A or B."))
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _subject_menu(key, base_dir, state, here):
|
|
299
|
+
subject = SUBJECTS[key]
|
|
300
|
+
items = subject["items"]
|
|
301
|
+
numbers = [i["number"] for i in items]
|
|
302
|
+
show = True
|
|
303
|
+
while True:
|
|
304
|
+
if show:
|
|
305
|
+
print()
|
|
306
|
+
print(bold(" %s (%s)" % (subject["name"].upper(), subject["language"])))
|
|
307
|
+
for item in items:
|
|
308
|
+
tag = dim(" [opens a terminal]") if item["kind"] == "commands" else ""
|
|
309
|
+
print(" %s %s%s" % (bold("%3d." % item["number"]), item["title"], tag))
|
|
310
|
+
print(" %s Save ALL programs of this subject" % bold(" A."))
|
|
311
|
+
print(" %s Back to subjects" % bold(" B."))
|
|
312
|
+
print(" %s Quit" % bold(" Q."))
|
|
313
|
+
print()
|
|
314
|
+
show = True
|
|
315
|
+
ans = _ask("Choose (%d-%d, A, B, Q): " % (numbers[0], numbers[-1])).strip().lower().rstrip(".")
|
|
316
|
+
if ans in ("q", "quit", "exit"):
|
|
317
|
+
raise _Quit()
|
|
318
|
+
if ans in ("b", "back"):
|
|
319
|
+
return
|
|
320
|
+
if ans in ("a", "all"):
|
|
321
|
+
chosen = [i for i in items if i["kind"] == "code"]
|
|
322
|
+
roll = _ask_roll(state)
|
|
323
|
+
save_items(chosen, roll, base_dir, _ask_overwrite)
|
|
324
|
+
continue
|
|
325
|
+
if not (ans.isdigit() and int(ans) in numbers):
|
|
326
|
+
print(red(" Please type a number from the list, A, B or Q."))
|
|
327
|
+
show = False
|
|
328
|
+
continue
|
|
329
|
+
|
|
330
|
+
item = get("%s%s" % (key, ans))
|
|
331
|
+
print(bold("\n %s %d: %s" % (key.upper(), item["number"], item["title"])))
|
|
332
|
+
print(dim(textwrap.fill(item["aim"], 78, initial_indent=" ", subsequent_indent=" ")))
|
|
333
|
+
if item["kind"] == "commands":
|
|
334
|
+
parts = _choose_part(item)
|
|
335
|
+
if parts:
|
|
336
|
+
launch_commands(parts, here)
|
|
337
|
+
else:
|
|
338
|
+
roll = _ask_roll(state)
|
|
339
|
+
save_items([item], roll, base_dir, _ask_overwrite)
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def interactive(base_dir, here=False):
|
|
343
|
+
_banner(base_dir)
|
|
344
|
+
state = {}
|
|
345
|
+
try:
|
|
346
|
+
while True:
|
|
347
|
+
print()
|
|
348
|
+
print(" %s Operating Systems (DSC08) - C++ programs + Linux commands" % bold("1."))
|
|
349
|
+
print(" %s Data Structures - C++ programs" % bold("2."))
|
|
350
|
+
print(" %s Quit" % bold("Q."))
|
|
351
|
+
print()
|
|
352
|
+
ans = _ask("Choose a subject (1, 2, Q): ").strip().lower()
|
|
353
|
+
if ans in ("q", "quit", "exit"):
|
|
354
|
+
raise _Quit()
|
|
355
|
+
if ans in ("1", "os"):
|
|
356
|
+
_subject_menu("os", base_dir, state, here)
|
|
357
|
+
elif ans in ("2", "ds"):
|
|
358
|
+
_subject_menu("ds", base_dir, state, here)
|
|
359
|
+
else:
|
|
360
|
+
print(red(" Please type 1, 2 or Q."))
|
|
361
|
+
except _Quit:
|
|
362
|
+
print("Bye!")
|
|
363
|
+
return 0
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
# ------------------------------------------------------------------ entry point
|
|
367
|
+
|
|
368
|
+
def _list_all():
|
|
369
|
+
for key, subject in SUBJECTS.items():
|
|
370
|
+
print("%s (%s)" % (subject["name"], subject["language"]))
|
|
371
|
+
for item in subject["items"]:
|
|
372
|
+
extra = " [opens a terminal; parts: %s]" % ", ".join("os" + p for p in item["parts"]) if item["kind"] == "commands" else ""
|
|
373
|
+
print(" %-5s %s%s" % (item["id"], item["title"], extra))
|
|
374
|
+
print()
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
def _parser():
|
|
378
|
+
ap = argparse.ArgumentParser(
|
|
379
|
+
prog="dulab",
|
|
380
|
+
description="OS and DS lab practicals. Run with no arguments for the menu.",
|
|
381
|
+
epilog="examples: dulab os8 -r 23CS045 | dulab ds -r 23CS045 | dulab os2ii")
|
|
382
|
+
ap.add_argument("target", nargs="?",
|
|
383
|
+
help="practical to save or run: os2-os12, ds1-ds7, os2i/os2ii/..., os, ds or all")
|
|
384
|
+
ap.add_argument("-r", "--roll", help="roll number (folder name on the Desktop)")
|
|
385
|
+
ap.add_argument("-l", "--list", action="store_true", help="list all practicals")
|
|
386
|
+
ap.add_argument("-s", "--show", metavar="ID", help="print the code of a practical, e.g. --show ds6")
|
|
387
|
+
ap.add_argument("-d", "--dir", metavar="PATH", help="save under this folder instead of the Desktop")
|
|
388
|
+
ap.add_argument("-f", "--force", action="store_true", help="overwrite files without asking")
|
|
389
|
+
ap.add_argument("--here", action="store_true",
|
|
390
|
+
help="run Linux commands in this window instead of opening a new one")
|
|
391
|
+
ap.add_argument("-V", "--version", action="version", version="%(prog)s " + __version__)
|
|
392
|
+
return ap
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def main(argv=None):
|
|
396
|
+
_init_color()
|
|
397
|
+
args = _parser().parse_args(argv)
|
|
398
|
+
base_dir = Path(args.dir).expanduser() if args.dir else desktop_dir()
|
|
399
|
+
|
|
400
|
+
try:
|
|
401
|
+
if args.list:
|
|
402
|
+
_list_all()
|
|
403
|
+
return 0
|
|
404
|
+
|
|
405
|
+
if args.show:
|
|
406
|
+
try:
|
|
407
|
+
kind, items = parse_target(args.show)
|
|
408
|
+
except ValueError as e:
|
|
409
|
+
print(red(str(e)), file=sys.stderr)
|
|
410
|
+
return 2
|
|
411
|
+
if kind == "commands":
|
|
412
|
+
print(build_script(items), end="")
|
|
413
|
+
return 0
|
|
414
|
+
for item in items:
|
|
415
|
+
for f in item["files"]:
|
|
416
|
+
if len(items) > 1 or len(item["files"]) > 1:
|
|
417
|
+
print("=" * 20 + " " + f["name"] + " " + "=" * 20)
|
|
418
|
+
print(f["code"], end="")
|
|
419
|
+
return 0
|
|
420
|
+
|
|
421
|
+
if args.target:
|
|
422
|
+
try:
|
|
423
|
+
kind, items = parse_target(args.target)
|
|
424
|
+
except ValueError as e:
|
|
425
|
+
print(red(str(e)), file=sys.stderr)
|
|
426
|
+
return 2
|
|
427
|
+
if kind == "commands":
|
|
428
|
+
launch_commands(items, args.here)
|
|
429
|
+
return 0
|
|
430
|
+
roll, err = check_roll(args.roll if args.roll else _ask("Enter your roll number: "))
|
|
431
|
+
if err:
|
|
432
|
+
print(red(err), file=sys.stderr)
|
|
433
|
+
return 2
|
|
434
|
+
save_items(items, roll, base_dir, True if args.force else _ask_overwrite)
|
|
435
|
+
return 0
|
|
436
|
+
|
|
437
|
+
return interactive(base_dir, args.here)
|
|
438
|
+
|
|
439
|
+
except KeyboardInterrupt:
|
|
440
|
+
print("\nBye!")
|
|
441
|
+
return 130
|
|
442
|
+
except EOFError:
|
|
443
|
+
print("\nBye!")
|
|
444
|
+
return 0
|
|
445
|
+
except BrokenPipeError:
|
|
446
|
+
try:
|
|
447
|
+
sys.stdout = open(os.devnull, "w")
|
|
448
|
+
except OSError:
|
|
449
|
+
pass
|
|
450
|
+
return 0
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
if __name__ == "__main__":
|
|
454
|
+
sys.exit(main())
|