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/coreutils.py ADDED
@@ -0,0 +1,837 @@
1
+ """Portable in-process versions of common Unix tools, so the shell works on every OS.
2
+
3
+ Each command takes (state, args, stdout, stderr) and returns an exit status:
4
+ 0 ok, 1 failure (or no match for grep), 2 usage error. Input comes from
5
+ state.input_stream(), never from sys.stdin directly."""
6
+ import bisect
7
+ import contextlib
8
+ import math
9
+ import os
10
+ import re
11
+ import shutil
12
+ import stat
13
+ import string
14
+ import time
15
+ from typing import Callable, Dict, Iterator, List, Optional, TextIO, Tuple
16
+
17
+ from .state import ShellState
18
+
19
+ Command = Callable[[ShellState, List[str], TextIO, TextIO], int]
20
+
21
+ Parsed = Tuple[set, Dict[str, List[str]], List[str]]
22
+
23
+
24
+ # ---------------------------------------------------------------- helpers
25
+
26
+ def _parse(name: str, args: List[str], allowed: str, stderr: TextIO,
27
+ valued: str = "", numeric: bool = False) -> Optional[Parsed]:
28
+ """Split args into (flags, option values, operands). Returns None after
29
+ printing an error. Handles -abc clusters, -- and options after operands."""
30
+ flags = set() # type: set
31
+ values = {} # type: Dict[str, List[str]]
32
+ rest = [] # type: List[str]
33
+ i = 0
34
+ while i < len(args):
35
+ arg = args[i]
36
+ i += 1
37
+ if arg == "--":
38
+ rest.extend(args[i:])
39
+ break
40
+ if numeric and re.fullmatch(r"-\d+", arg):
41
+ values.setdefault("n", []).append(arg[1:]) # head -5
42
+ continue
43
+ if arg.startswith("--"):
44
+ print(f"{name}: unrecognized option '{arg}'", file=stderr)
45
+ return None
46
+ if len(arg) > 1 and arg[0] == "-":
47
+ j = 1
48
+ while j < len(arg):
49
+ ch = arg[j]
50
+ j += 1
51
+ if ch in valued:
52
+ if j < len(arg):
53
+ val = arg[j:] # -n5
54
+ elif i < len(args):
55
+ val = args[i] # -n 5
56
+ i += 1
57
+ else:
58
+ print(f"{name}: option requires an argument -- '{ch}'", file=stderr)
59
+ return None
60
+ values.setdefault(ch, []).append(val)
61
+ break
62
+ if ch not in allowed:
63
+ print(f"{name}: invalid option -- '{ch}'", file=stderr)
64
+ return None
65
+ flags.add(ch)
66
+ else:
67
+ rest.append(arg)
68
+ return flags, values, rest
69
+
70
+
71
+ def _oserr(name: str, path: str, exc: OSError, stderr: TextIO) -> None:
72
+ print(f"{name}: {path}: {exc.strerror or exc}", file=stderr)
73
+
74
+
75
+ def _open_text(path: str) -> TextIO:
76
+ return open(path, encoding="utf-8", errors="replace", newline="")
77
+
78
+
79
+ @contextlib.contextmanager
80
+ def _open_input(state: ShellState, path: str) -> Iterator[TextIO]:
81
+ """Yield a text stream for a file name, or the input stream for '-'."""
82
+ if path == "-":
83
+ yield state.input_stream()
84
+ else:
85
+ with _open_text(path) as f:
86
+ yield f
87
+
88
+
89
+ # ---------------------------------------------------------------- ls
90
+
91
+ def _human_size(size: int) -> str:
92
+ if size < 1024:
93
+ return str(size)
94
+ value = float(size)
95
+ for unit in "KMGTP":
96
+ value /= 1024
97
+ if value < 1024 or unit == "P":
98
+ break
99
+ value = math.ceil(value * 10) / 10
100
+ return f"{value:.1f}{unit}" if value < 10 else f"{math.ceil(value)}{unit}"
101
+
102
+
103
+ def _name_key(name: str) -> Tuple[str, str]:
104
+ return (name.lower(), name)
105
+
106
+
107
+ def _pack_columns(names: List[str], width: int) -> List[str]:
108
+ """Lay names out in columns, filled top to bottom like ls."""
109
+ best = [[n] for n in names] # fallback: one column
110
+ for ncols in range(len(names), 0, -1):
111
+ rows = math.ceil(len(names) / ncols)
112
+ cols = [names[i * rows:(i + 1) * rows] for i in range(ncols)]
113
+ cols = [c for c in cols if c]
114
+ widths = [max(len(n) for n in c) + 2 for c in cols]
115
+ if sum(widths) - 2 <= width:
116
+ best = cols
117
+ break
118
+ else:
119
+ widths = [0]
120
+ rows = len(best[0])
121
+ widths = [max(len(n) for n in c) + 2 for c in best]
122
+ lines = []
123
+ for r in range(rows):
124
+ cells = [c[r].ljust(w) for c, w in zip(best, widths) if r < len(c)]
125
+ lines.append("".join(cells).rstrip())
126
+ return lines
127
+
128
+
129
+ def _ls_emit(entries: List[Tuple[str, str]], flags: set, stdout: TextIO, stderr: TextIO) -> int:
130
+ """Print (display name, real path) entries. Returns a status."""
131
+ status = 0
132
+ if "l" in flags:
133
+ rows = []
134
+ for display, path in entries:
135
+ try:
136
+ st = os.lstat(path)
137
+ except OSError as e:
138
+ print(f"ls: cannot access '{display}': {e.strerror or e}", file=stderr)
139
+ status = 2
140
+ continue
141
+ size = _human_size(st.st_size) if "h" in flags else str(st.st_size)
142
+ date = time.strftime("%b %d %H:%M", time.localtime(st.st_mtime))
143
+ label = display
144
+ if stat.S_ISLNK(st.st_mode):
145
+ try:
146
+ label += " -> " + os.readlink(path)
147
+ except OSError:
148
+ pass
149
+ rows.append((stat.filemode(st.st_mode), size, date, label))
150
+ width = max((len(r[1]) for r in rows), default=0)
151
+ for mode, size, date, label in rows:
152
+ print(f"{mode} {size.rjust(width)} {date} {label}", file=stdout)
153
+ return status
154
+ names = [d for d, _ in entries]
155
+ is_tty = getattr(stdout, "isatty", lambda: False)()
156
+ if is_tty and "1" not in flags and names:
157
+ for line in _pack_columns(names, shutil.get_terminal_size().columns):
158
+ print(line, file=stdout)
159
+ else:
160
+ for n in names:
161
+ print(n, file=stdout)
162
+ return status
163
+
164
+
165
+ def ls(state: ShellState, args: List[str], stdout: TextIO, stderr: TextIO) -> int:
166
+ parsed = _parse("ls", args, "al1hd", stderr)
167
+ if parsed is None:
168
+ return 2
169
+ flags, _, paths = parsed
170
+ paths = paths or ["."]
171
+ status = 0
172
+ files = [] # type: List[Tuple[str, str]]
173
+ dirs = [] # type: List[str]
174
+ for p in paths:
175
+ try:
176
+ st = os.stat(p)
177
+ except OSError:
178
+ try:
179
+ st = os.lstat(p) # a broken link still exists
180
+ except OSError as e:
181
+ print(f"ls: cannot access '{p}': {e.strerror or e}", file=stderr)
182
+ status = 2
183
+ continue
184
+ if stat.S_ISDIR(st.st_mode) and "d" not in flags:
185
+ dirs.append(p)
186
+ else:
187
+ files.append((p, p))
188
+ files.sort(key=lambda e: _name_key(e[0]))
189
+ dirs.sort(key=_name_key)
190
+ printed = False
191
+ if files:
192
+ if _ls_emit(files, flags, stdout, stderr):
193
+ status = 2
194
+ printed = True
195
+ for d in dirs:
196
+ try:
197
+ names = os.listdir(d)
198
+ except OSError as e:
199
+ print(f"ls: cannot open directory '{d}': {e.strerror or e}", file=stderr)
200
+ status = 2
201
+ continue
202
+ if "a" in flags:
203
+ names += [".", ".."]
204
+ else:
205
+ names = [n for n in names if not n.startswith(".")]
206
+ names.sort(key=_name_key)
207
+ if printed:
208
+ print(file=stdout)
209
+ if len(paths) > 1:
210
+ print(f"{d}:", file=stdout)
211
+ printed = True
212
+ if _ls_emit([(n, os.path.join(d, n)) for n in names], flags, stdout, stderr):
213
+ status = 2
214
+ return status
215
+
216
+
217
+ # ---------------------------------------------------------------- cat
218
+
219
+ def cat(state: ShellState, args: List[str], stdout: TextIO, stderr: TextIO) -> int:
220
+ parsed = _parse("cat", args, "n", stderr)
221
+ if parsed is None:
222
+ return 2
223
+ flags, _, files = parsed
224
+ status = 0
225
+ number = 0
226
+ for f in files or ["-"]:
227
+ try:
228
+ with _open_input(state, f) as src:
229
+ for line in src:
230
+ if "n" in flags:
231
+ number += 1
232
+ stdout.write(f"{number:6}\t")
233
+ stdout.write(line)
234
+ except OSError as e:
235
+ _oserr("cat", f, e, stderr)
236
+ status = 1
237
+ return status
238
+
239
+
240
+ # ---------------------------------------------------------------- head
241
+
242
+ def head(state: ShellState, args: List[str], stdout: TextIO, stderr: TextIO) -> int:
243
+ parsed = _parse("head", args, "", stderr, valued="n", numeric=True)
244
+ if parsed is None:
245
+ return 2
246
+ _, values, files = parsed
247
+ count = 10
248
+ if "n" in values:
249
+ text = values["n"][-1]
250
+ try:
251
+ count = int(text)
252
+ except ValueError:
253
+ count = -1
254
+ if count < 0:
255
+ print(f"head: invalid number of lines: '{text}'", file=stderr)
256
+ return 1
257
+ files = files or ["-"]
258
+ status = 0
259
+ first = True
260
+ for f in files:
261
+ try:
262
+ with _open_input(state, f) as src:
263
+ if len(files) > 1:
264
+ if not first:
265
+ stdout.write("\n")
266
+ stdout.write(f"==> {'standard input' if f == '-' else f} <==\n")
267
+ first = False
268
+ for _ in range(count):
269
+ line = src.readline() # stop early, do not read the rest
270
+ if not line:
271
+ break
272
+ stdout.write(line)
273
+ except OSError as e:
274
+ _oserr("head", f, e, stderr)
275
+ status = 1
276
+ return status
277
+
278
+
279
+ # ---------------------------------------------------------------- tr
280
+
281
+ _CLASSES = {
282
+ "lower": string.ascii_lowercase,
283
+ "upper": string.ascii_uppercase,
284
+ "digit": string.digits,
285
+ "alpha": string.ascii_letters,
286
+ "alnum": string.ascii_letters + string.digits,
287
+ "space": "\t\n\v\f\r ",
288
+ "punct": string.punctuation,
289
+ }
290
+ _ESCAPES = {"n": "\n", "t": "\t", "r": "\r", "\\": "\\", "a": "\a", "b": "\b", "f": "\f", "v": "\v"}
291
+
292
+
293
+ def _tr_atom(s: str, i: int) -> Tuple[str, bool, int]:
294
+ """Read one item at s[i]: a char, an escape or a [:class:]. Returns (chars, is_class, next)."""
295
+ c = s[i]
296
+ if c == "\\" and i + 1 < len(s):
297
+ d = s[i + 1]
298
+ if d in "01234567":
299
+ j = i + 1
300
+ while j < len(s) and j < i + 4 and s[j] in "01234567":
301
+ j += 1
302
+ return chr(int(s[i + 1:j], 8)), False, j
303
+ return _ESCAPES.get(d, d), False, i + 2
304
+ if s.startswith("[:", i):
305
+ j = s.find(":]", i + 2)
306
+ if j > 0:
307
+ name = s[i + 2:j]
308
+ if name not in _CLASSES:
309
+ raise ValueError(f"invalid character class '{s[i:j + 2]}'")
310
+ return _CLASSES[name], True, j + 2
311
+ return c, False, i + 1
312
+
313
+
314
+ def _tr_expand(s: str) -> List[str]:
315
+ out = [] # type: List[str]
316
+ i = 0
317
+ while i < len(s):
318
+ chars, is_class, i = _tr_atom(s, i)
319
+ if not is_class and i + 1 < len(s) and s[i] == "-":
320
+ end, end_is_class, j = _tr_atom(s, i + 1)
321
+ if not end_is_class:
322
+ if ord(end) < ord(chars):
323
+ raise ValueError(f"range-endpoints of '{chars}-{end}' are in reverse "
324
+ "collating sequence order")
325
+ out.extend(chr(x) for x in range(ord(chars), ord(end) + 1))
326
+ i = j
327
+ continue
328
+ out.extend(chars)
329
+ return out
330
+
331
+
332
+ def tr(state: ShellState, args: List[str], stdout: TextIO, stderr: TextIO) -> int:
333
+ parsed = _parse("tr", args, "dsc", stderr)
334
+ if parsed is None:
335
+ return 2
336
+ flags, _, sets = parsed
337
+ delete, squeeze, comp = "d" in flags, "s" in flags, "c" in flags
338
+ if not sets:
339
+ print("tr: missing operand", file=stderr)
340
+ return 2
341
+ if len(sets) > 2 or (delete and not squeeze and len(sets) > 1):
342
+ print(f"tr: extra operand '{sets[2] if len(sets) > 2 else sets[1]}'", file=stderr)
343
+ return 2
344
+ translate = not delete and len(sets) == 2
345
+ if not delete and not squeeze and len(sets) == 1:
346
+ print(f"tr: missing operand after '{sets[0]}'", file=stderr)
347
+ print("Two strings must be given when translating.", file=stderr)
348
+ return 2
349
+ try:
350
+ set1 = _tr_expand(sets[0])
351
+ set2 = _tr_expand(sets[1]) if len(sets) == 2 else []
352
+ except ValueError as e:
353
+ print(f"tr: {e}", file=stderr)
354
+ return 2
355
+ if translate and not set2 and set1:
356
+ print("tr: when not truncating set1, string2 must be non-empty", file=stderr)
357
+ return 2
358
+
359
+ members = set(set1)
360
+ sorted_ords = sorted(ord(ch) for ch in members)
361
+
362
+ def in_set1(ch: str) -> bool:
363
+ return (ch in members) != comp
364
+
365
+ def translate_char(ch: str) -> str:
366
+ if not in_set1(ch):
367
+ return ch
368
+ if comp:
369
+ rank = ord(ch) - bisect.bisect_left(sorted_ords, ord(ch)) # place among the complement
370
+ return set2[min(rank, len(set2) - 1)]
371
+ return mapping.get(ch, ch)
372
+
373
+ mapping = {} # type: Dict[str, str]
374
+ if translate and not comp:
375
+ for k, ch in enumerate(set1):
376
+ mapping[ch] = set2[min(k, len(set2) - 1)]
377
+ squeeze_set = set(set2) if (squeeze and set2) else None
378
+
379
+ out = [] # type: List[str]
380
+ last = None # type: Optional[str]
381
+ for ch in state.input_stream().read():
382
+ if delete and in_set1(ch):
383
+ continue
384
+ if translate:
385
+ ch = translate_char(ch)
386
+ if squeeze and ch == last:
387
+ if (ch in squeeze_set) if squeeze_set is not None else in_set1(ch):
388
+ continue
389
+ out.append(ch)
390
+ last = ch
391
+ stdout.write("".join(out))
392
+ return 0
393
+
394
+
395
+ # ---------------------------------------------------------------- sleep
396
+
397
+ def sleep(state: ShellState, args: List[str], stdout: TextIO, stderr: TextIO) -> int:
398
+ if args and args[0] == "--":
399
+ args = args[1:]
400
+ if not args:
401
+ print("sleep: missing operand", file=stderr)
402
+ return 1
403
+ total = 0.0
404
+ units = {"s": 1, "m": 60, "h": 3600, "d": 86400}
405
+ for a in args:
406
+ scale = 1
407
+ text = a
408
+ if a and a[-1] in units:
409
+ scale = units[a[-1]]
410
+ text = a[:-1]
411
+ try:
412
+ value = float(text)
413
+ except ValueError:
414
+ value = -1.0
415
+ if not (0 <= value < float("inf")):
416
+ print(f"sleep: invalid time interval '{a}'", file=stderr)
417
+ return 1
418
+ total += value * scale
419
+ time.sleep(total) # KeyboardInterrupt propagates
420
+ return 0
421
+
422
+
423
+ # ---------------------------------------------------------------- mkdir
424
+
425
+ def mkdir(state: ShellState, args: List[str], stdout: TextIO, stderr: TextIO) -> int:
426
+ parsed = _parse("mkdir", args, "p", stderr)
427
+ if parsed is None:
428
+ return 2
429
+ flags, _, dirs = parsed
430
+ if not dirs:
431
+ print("mkdir: missing operand", file=stderr)
432
+ return 2
433
+ status = 0
434
+ for d in dirs:
435
+ try:
436
+ if "p" in flags:
437
+ os.makedirs(d, exist_ok=True)
438
+ else:
439
+ os.mkdir(d)
440
+ except OSError as e:
441
+ print(f"mkdir: cannot create directory '{d}': {e.strerror or e}", file=stderr)
442
+ status = 1
443
+ return status
444
+
445
+
446
+ # ---------------------------------------------------------------- rm
447
+
448
+ def _remove_file(path: str) -> None:
449
+ try:
450
+ os.remove(path)
451
+ except OSError:
452
+ if os.name != "nt":
453
+ raise
454
+ if os.path.isdir(path):
455
+ os.rmdir(path) # a directory link on Windows
456
+ else:
457
+ os.chmod(path, stat.S_IWRITE) # clear the read-only flag and retry once
458
+ os.remove(path)
459
+
460
+
461
+ def _remove_tree(path: str) -> None:
462
+ try:
463
+ shutil.rmtree(path)
464
+ except PermissionError:
465
+ if os.name != "nt":
466
+ raise
467
+ for root, dirnames, filenames in os.walk(path):
468
+ for n in dirnames + filenames:
469
+ try:
470
+ os.chmod(os.path.join(root, n), stat.S_IWRITE)
471
+ except OSError:
472
+ pass
473
+ shutil.rmtree(path)
474
+
475
+
476
+ def _is_dangerous(path: str) -> bool:
477
+ """True for a filesystem root or the home folder."""
478
+ if os.path.islink(path):
479
+ return False # removing a link does not touch its target
480
+ real = os.path.normcase(os.path.realpath(path))
481
+ if os.path.dirname(real) == real:
482
+ return True
483
+ homes = [os.environ.get("HOME"), os.path.expanduser("~")]
484
+ return any(h and os.path.normcase(os.path.realpath(h)) == real for h in homes)
485
+
486
+
487
+ def rm(state: ShellState, args: List[str], stdout: TextIO, stderr: TextIO) -> int:
488
+ parsed = _parse("rm", args, "rRf", stderr)
489
+ if parsed is None:
490
+ return 2
491
+ flags, _, paths = parsed
492
+ force = "f" in flags
493
+ recursive = "r" in flags or "R" in flags
494
+ if not paths:
495
+ if force:
496
+ return 0
497
+ print("rm: missing operand", file=stderr)
498
+ return 1
499
+ status = 0
500
+ for p in paths:
501
+ if os.path.basename(p.rstrip("/\\")) in (".", ".."):
502
+ print(f"rm: refusing to remove '.' or '..' directory: skipping '{p}'", file=stderr)
503
+ status = 1
504
+ continue
505
+ if not os.path.lexists(p):
506
+ if not force:
507
+ print(f"rm: cannot remove '{p}': No such file or directory", file=stderr)
508
+ status = 1
509
+ continue
510
+ if _is_dangerous(p):
511
+ print(f"rm: it is dangerous to operate recursively on '{p}'", file=stderr)
512
+ status = 1
513
+ continue
514
+ is_dir = os.path.isdir(p) and not os.path.islink(p)
515
+ if is_dir and not recursive:
516
+ print(f"rm: cannot remove '{p}': Is a directory", file=stderr)
517
+ status = 1
518
+ continue
519
+ try:
520
+ if is_dir:
521
+ _remove_tree(p)
522
+ else:
523
+ _remove_file(p)
524
+ except OSError as e:
525
+ print(f"rm: cannot remove '{p}': {e.strerror or e}", file=stderr)
526
+ status = 1
527
+ return status
528
+
529
+
530
+ # ---------------------------------------------------------------- cp and mv
531
+
532
+ def _pairs(name: str, operands: List[str], stderr: TextIO) -> Tuple[List[Tuple[str, str]], int]:
533
+ """Turn SRC... DEST into (source, target) pairs. Status is nonzero on a usage error."""
534
+ if not operands:
535
+ print(f"{name}: missing file operand", file=stderr)
536
+ return [], 2
537
+ if len(operands) == 1:
538
+ print(f"{name}: missing destination file operand after '{operands[0]}'", file=stderr)
539
+ return [], 2
540
+ dest = operands[-1]
541
+ srcs = operands[:-1]
542
+ if os.path.isdir(dest):
543
+ pairs = []
544
+ for s in srcs:
545
+ base = os.path.basename(os.path.abspath(s)) or s
546
+ pairs.append((s, os.path.join(dest, base)))
547
+ return pairs, 0
548
+ if len(srcs) > 1:
549
+ print(f"{name}: target '{dest}' is not a directory", file=stderr)
550
+ return [], 1
551
+ return [(srcs[0], dest)], 0
552
+
553
+
554
+ def _same_file(a: str, b: str) -> bool:
555
+ try:
556
+ return os.path.exists(b) and os.path.samefile(a, b)
557
+ except OSError:
558
+ return False
559
+
560
+
561
+ def cp(state: ShellState, args: List[str], stdout: TextIO, stderr: TextIO) -> int:
562
+ parsed = _parse("cp", args, "rRfn", stderr)
563
+ if parsed is None:
564
+ return 2
565
+ flags, _, operands = parsed
566
+ pairs, status = _pairs("cp", operands, stderr)
567
+ if status:
568
+ return status
569
+ recursive = "r" in flags or "R" in flags
570
+ for src, dst in pairs:
571
+ if not os.path.lexists(src):
572
+ print(f"cp: cannot stat '{src}': No such file or directory", file=stderr)
573
+ status = 1
574
+ continue
575
+ if _same_file(src, dst):
576
+ print(f"cp: '{src}' and '{dst}' are the same file", file=stderr)
577
+ status = 1
578
+ continue
579
+ src_is_dir = os.path.isdir(src)
580
+ if src_is_dir and not recursive:
581
+ print(f"cp: -r not specified; omitting directory '{src}'", file=stderr)
582
+ status = 1
583
+ continue
584
+ if "n" in flags and os.path.lexists(dst):
585
+ continue
586
+ try:
587
+ if src_is_dir:
588
+ if os.path.lexists(dst) and not os.path.isdir(dst):
589
+ print(f"cp: cannot overwrite non-directory '{dst}' with directory '{src}'",
590
+ file=stderr)
591
+ status = 1
592
+ continue
593
+ inside = os.path.realpath(dst) + os.sep
594
+ if inside.startswith(os.path.realpath(src) + os.sep):
595
+ print(f"cp: cannot copy a directory, '{src}', into itself, '{dst}'",
596
+ file=stderr)
597
+ status = 1
598
+ continue
599
+ shutil.copytree(src, dst, dirs_exist_ok=True)
600
+ elif os.path.isdir(dst):
601
+ print(f"cp: cannot overwrite directory '{dst}' with non-directory", file=stderr)
602
+ status = 1
603
+ else:
604
+ try:
605
+ shutil.copy2(src, dst)
606
+ except PermissionError:
607
+ if "f" not in flags or not os.path.lexists(dst):
608
+ raise
609
+ os.remove(dst) # -f: replace a file we cannot write
610
+ shutil.copy2(src, dst)
611
+ except (OSError, shutil.Error) as e:
612
+ print(f"cp: cannot copy '{src}' to '{dst}': {getattr(e, 'strerror', None) or e}",
613
+ file=stderr)
614
+ status = 1
615
+ return status
616
+
617
+
618
+ def mv(state: ShellState, args: List[str], stdout: TextIO, stderr: TextIO) -> int:
619
+ parsed = _parse("mv", args, "fn", stderr)
620
+ if parsed is None:
621
+ return 2
622
+ flags, _, operands = parsed
623
+ pairs, status = _pairs("mv", operands, stderr)
624
+ if status:
625
+ return status
626
+ for src, dst in pairs:
627
+ if not os.path.lexists(src):
628
+ print(f"mv: cannot stat '{src}': No such file or directory", file=stderr)
629
+ status = 1
630
+ continue
631
+ if _same_file(src, dst):
632
+ print(f"mv: '{src}' and '{dst}' are the same file", file=stderr)
633
+ status = 1
634
+ continue
635
+ if "n" in flags and os.path.lexists(dst):
636
+ continue
637
+ src_is_dir = os.path.isdir(src) and not os.path.islink(src)
638
+ try:
639
+ if os.path.isdir(dst) and not os.path.islink(dst):
640
+ if not src_is_dir:
641
+ print(f"mv: cannot overwrite directory '{dst}' with non-directory",
642
+ file=stderr)
643
+ status = 1
644
+ continue
645
+ os.rmdir(dst) # only an empty folder can be replaced
646
+ elif os.path.lexists(dst):
647
+ if src_is_dir:
648
+ print(f"mv: cannot overwrite non-directory '{dst}' with directory '{src}'",
649
+ file=stderr)
650
+ status = 1
651
+ continue
652
+ if os.name == "nt":
653
+ _remove_file(dst) # rename does not replace on Windows
654
+ shutil.move(src, dst)
655
+ except (OSError, shutil.Error) as e:
656
+ print(f"mv: cannot move '{src}' to '{dst}': {getattr(e, 'strerror', None) or e}",
657
+ file=stderr)
658
+ status = 1
659
+ return status
660
+
661
+
662
+ # ---------------------------------------------------------------- touch
663
+
664
+ def touch(state: ShellState, args: List[str], stdout: TextIO, stderr: TextIO) -> int:
665
+ parsed = _parse("touch", args, "c", stderr)
666
+ if parsed is None:
667
+ return 2
668
+ flags, _, files = parsed
669
+ if not files:
670
+ print("touch: missing file operand", file=stderr)
671
+ return 2
672
+ status = 0
673
+ for f in files:
674
+ try:
675
+ if os.path.exists(f):
676
+ os.utime(f, None)
677
+ elif "c" not in flags:
678
+ open(f, "a").close()
679
+ except OSError as e:
680
+ print(f"touch: cannot touch '{f}': {e.strerror or e}", file=stderr)
681
+ status = 1
682
+ return status
683
+
684
+
685
+ # ---------------------------------------------------------------- wc
686
+
687
+ def wc(state: ShellState, args: List[str], stdout: TextIO, stderr: TextIO) -> int:
688
+ parsed = _parse("wc", args, "lwcm", stderr)
689
+ if parsed is None:
690
+ return 2
691
+ flags, _, files = parsed
692
+ if not flags:
693
+ flags = {"l", "w", "c"}
694
+ status = 0
695
+ rows = [] # type: List[Tuple[List[int], str]]
696
+ for f in files or ["-"]:
697
+ try:
698
+ if f == "-":
699
+ text = state.input_stream().read()
700
+ size = len(text.encode("utf-8", errors="replace"))
701
+ else:
702
+ with open(f, "rb") as fh:
703
+ raw = fh.read()
704
+ size = len(raw)
705
+ text = raw.decode("utf-8", errors="replace")
706
+ except OSError as e:
707
+ _oserr("wc", f, e, stderr)
708
+ status = 1
709
+ continue
710
+ # order matches GNU: lines, words, characters, bytes
711
+ counts = {"l": text.count("\n"), "w": len(text.split()), "m": len(text), "c": size}
712
+ rows.append(([counts[k] for k in "lwmc" if k in flags], "" if not files else f))
713
+ if len(files) > 1:
714
+ totals = [sum(r[0][k] for r in rows) for k in range(len([k for k in "lwmc" if k in flags]))]
715
+ rows.append((totals, "total"))
716
+ width = max((len(str(n)) for r in rows for n in r[0]), default=1)
717
+ for counts_list, label in rows:
718
+ line = " ".join(str(n).rjust(width) for n in counts_list)
719
+ print(f"{line} {label}" if label else line, file=stdout)
720
+ return status
721
+
722
+
723
+ # ---------------------------------------------------------------- grep
724
+
725
+ def _grep_stream(src: TextIO, label: str, rx: "re.Pattern", flags: set, show_name: bool,
726
+ stdout: TextIO) -> int:
727
+ """Search one stream. Prints matching lines unless -c/-l/-q. Returns the match count."""
728
+ quiet = bool({"c", "l", "q"} & flags)
729
+ count = 0
730
+ for lineno, line in enumerate(src, 1):
731
+ content = line.rstrip("\r\n")
732
+ if bool(rx.search(content)) == ("v" in flags):
733
+ continue
734
+ count += 1
735
+ if "l" in flags or "q" in flags:
736
+ break # one match is enough
737
+ if not quiet:
738
+ prefix = (label + ":" if show_name else "") + (f"{lineno}:" if "n" in flags else "")
739
+ stdout.write(prefix + line + ("" if line.endswith("\n") else "\n"))
740
+ return count
741
+
742
+
743
+ def _grep_targets(path: str, recursive: bool, stderr: TextIO) -> Iterator[Tuple[str, bool]]:
744
+ """Yield (file name, from_walk). A folder is walked only with -r."""
745
+ if os.path.isdir(path):
746
+ if not recursive:
747
+ print(f"grep: {path}: Is a directory", file=stderr)
748
+ yield path, False # reported below as an error
749
+ return
750
+ for root, dirnames, filenames in os.walk(path):
751
+ dirnames.sort()
752
+ for n in sorted(filenames):
753
+ p = os.path.join(root, n)
754
+ yield (os.path.normpath(p) if path == "." else p), True
755
+ else:
756
+ yield path, False
757
+
758
+
759
+ def grep(state: ShellState, args: List[str], stdout: TextIO, stderr: TextIO) -> int:
760
+ parsed = _parse("grep", args, "ivnclqwFErHhR", stderr, valued="e")
761
+ if parsed is None:
762
+ return 2
763
+ flags, values, operands = parsed
764
+ patterns = [] # type: List[str]
765
+ for p in values.get("e", []):
766
+ patterns.extend(p.split("\n"))
767
+ if "e" not in values:
768
+ if not operands:
769
+ print("Usage: grep [OPTION]... PATTERNS [FILE]...", file=stderr)
770
+ return 2
771
+ patterns = operands[0].split("\n")
772
+ operands = operands[1:]
773
+ parts = [re.escape(p) if "F" in flags else p for p in patterns]
774
+ body = "|".join(f"(?:{p})" for p in parts)
775
+ if "w" in flags:
776
+ body = rf"(?<!\w)(?:{body})(?!\w)"
777
+ try:
778
+ rx = re.compile(body, re.IGNORECASE if "i" in flags else 0)
779
+ except re.error:
780
+ print("grep: invalid regular expression", file=stderr)
781
+ return 2
782
+
783
+ recursive = "r" in flags or "R" in flags
784
+ files = operands
785
+ if not files:
786
+ files = ["."] if recursive else ["-"]
787
+ # prefix lines with the file name when several files can be searched
788
+ if "H" in flags:
789
+ show_name = True
790
+ elif "h" in flags:
791
+ show_name = False
792
+ else:
793
+ show_name = len(files) > 1 or (recursive and any(os.path.isdir(f) for f in files))
794
+
795
+ matched = False
796
+ error = False
797
+ for arg in files:
798
+ for path, walked in _grep_targets(arg, recursive, stderr):
799
+ if os.path.isdir(path) and not walked:
800
+ error = True
801
+ continue
802
+ label = "(standard input)" if path == "-" else path
803
+ try:
804
+ with _open_input(state, path) as src:
805
+ count = _grep_stream(src, label, rx, flags, show_name, stdout)
806
+ except OSError as e:
807
+ if not walked: # skip unreadable files found by -r
808
+ _oserr("grep", path, e, stderr)
809
+ error = True
810
+ continue
811
+ if count:
812
+ matched = True
813
+ if "q" in flags:
814
+ return 0
815
+ if "l" in flags:
816
+ print(label, file=stdout)
817
+ if "c" in flags and "l" not in flags:
818
+ print((label + ":" if show_name else "") + str(count), file=stdout)
819
+ if error:
820
+ return 2
821
+ return 0 if matched else 1
822
+
823
+
824
+ PORTABLE = {
825
+ "ls": ls,
826
+ "cat": cat,
827
+ "head": head,
828
+ "tr": tr,
829
+ "sleep": sleep,
830
+ "mkdir": mkdir,
831
+ "rm": rm,
832
+ "cp": cp,
833
+ "mv": mv,
834
+ "touch": touch,
835
+ "wc": wc,
836
+ "grep": grep,
837
+ } # type: Dict[str, Command]