Skip to content

Commit fcac82c

Browse files
replace -n/-b flags with Numbering Enum
1 parent ff86f10 commit fcac82c

File tree

1 file changed

+23
-6
lines changed
  • implement-shell-tools/cat

1 file changed

+23
-6
lines changed

implement-shell-tools/cat/cat.py

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,23 @@
11
import glob
22
import argparse
3+
from enum import Enum
34

4-
def cat(filepath, n=False, b=False, line_counter=None):
5+
class Numbering(Enum):
6+
NONE = 0
7+
ALL = 1
8+
NONEMPTY = 2
9+
10+
def cat(filepath, numbering=Numbering.NONE, line_counter=None):
511
try:
612
with open(filepath) as f:
713
for line in f:
8-
if b:
14+
if numbering == Numbering.NONEMPTY:
915
if line.strip():
1016
print(f"{line_counter[0]:6}\t{line}", end='')
1117
line_counter[0] += 1
1218
else:
1319
print(line, end='')
14-
elif n:
20+
elif numbering == Numbering.ALL:
1521
print(f"{line_counter[0]:6}\t{line}", end='')
1622
line_counter[0] += 1
1723
else:
@@ -20,7 +26,7 @@ def cat(filepath, n=False, b=False, line_counter=None):
2026
print(f"cat: {filepath}: No such file or directory")
2127

2228
def main():
23-
parser = argparse.ArgumentParser(description = "Concatenate files and print on the standard output.")
29+
parser = argparse.ArgumentParser(description="Concatenate files and print on the standard output.")
2430
parser.add_argument('-n', action='store_true', help='number all output lines')
2531
parser.add_argument('-b', action='store_true', help='number non-empty output lines')
2632
parser.add_argument('files', nargs='+', help='files to concatenate')
@@ -31,8 +37,19 @@ def main():
3137
files.extend(glob.glob(pattern) or [pattern])
3238

3339
line_counter = [1]
40+
41+
# Determine numbering mode (mutually exclusive)
42+
if args.n and args.b:
43+
parser.error("options -n and -b are mutually exclusive")
44+
elif args.n:
45+
numbering = Numbering.ALL
46+
elif args.b:
47+
numbering = Numbering.NONEMPTY
48+
else:
49+
numbering = Numbering.NONE
50+
3451
for file in sorted(files):
35-
cat(file, args.n, args.b, line_counter)
52+
cat(file, numbering=numbering, line_counter=line_counter)
3653

3754
if __name__ == "__main__":
38-
main()
55+
main()

0 commit comments

Comments
 (0)