Skip to content

Commit 9fa8069

Browse files
committed
numbering across files
1 parent d0e9187 commit 9fa8069

1 file changed

Lines changed: 16 additions & 16 deletions

File tree

  • implement-shell-tools/cat

‎implement-shell-tools/cat/cat.py‎

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -28,31 +28,29 @@ def read_file(path):
2828

2929
# -b (number the non-empty lines) takes priority over -n (number all lines)
3030
# if both are present
31-
def format_lines(lines, number_all=False, number_nonempty=False):
31+
def format_lines(lines, line_num, number_all=False, number_nonempty=False):
3232
"""Returns a list of formatted output lines"""
3333
output = []
34-
3534
if number_nonempty:
36-
line_num = 0
3735
for line in lines:
3836
if line == "":
3937
output.append("")
4038
else:
41-
line_num += 1
4239
# {line_num:6} right justied number, length of at least 6
4340
# {some_str:6} left justifed string, length fo at least 6
4441
output.append(f"{line_num:6}\t{line}")
42+
line_num += 1
4543
elif number_all:
46-
for i, line in enumerate(lines, start=1):
47-
output.append(f"{i:6}\t{line}")
44+
for _, line in enumerate(lines, start=1):
45+
output.append(f"{line_num:6}\t{line}")
46+
line_num += 1
4847
else:
4948
output = lines
5049

5150
return output
5251

5352

54-
# TODO: runner function to call read_file, and feed it into formatLines, then print
55-
def cat_file(path, number_all=False, number_nonempty=False):
53+
def cat_file(path, line_num, number_all=False, number_nonempty=False):
5654
"""
5755
Calls read_file -> format_lines -> prints formatted line.
5856
Returns True if file read successfully, else returns False
@@ -62,27 +60,29 @@ def cat_file(path, number_all=False, number_nonempty=False):
6260
content, error = read_file(path)
6361
if (error):
6462
print(error, file=sys.stderr)
65-
return False
63+
return -1
6664

6765
# splitlines automatically trims trailing empty lines
6866
lines = content.splitlines()
69-
for line in format_lines(lines, number_all, number_nonempty):
67+
for line in format_lines(lines, line_num, number_all, number_nonempty):
7068
print(line)
7169

72-
return True
70+
return len(lines) + line_num
7371

7472

7573
def main():
7674
# cat exits with error code 1 if any file read fails
7775
file_error = False
7876

79-
for path in args.paths:
80-
line_num = 1
81-
is_success = cat_file(path, args.n, args.b)
82-
83-
if not is_success:
77+
line_num = 1
78+
for path in args.paths:
79+
result = cat_file(path, line_num, args.n, args.b)
80+
if result < 0:
8481
file_error = True
8582

83+
if result > 0:
84+
line_num = result
85+
8686
# if at any point, file reading failed file error is set to True,
8787
# and program exist with code 1 after all tasks completed
8888
sys.exit(1 if file_error else 0)

0 commit comments

Comments
 (0)