Skip to content

Commit 08500cb

Browse files
committed
new tool (beta): wc
1 parent a6430b0 commit 08500cb

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

darkbox/commands/wc.py

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
"""darkbox cat command"""
2+
3+
from darkbox.commands.template import Command
4+
5+
6+
class wc(Command):
7+
"""darkbox wc
8+
9+
count characters or lines in files
10+
11+
Designed to be similar to wc from GNU coreutils.
12+
Resource: https://www.gnu.org/software/coreutils/wc
13+
"""
14+
15+
def __init__(self):
16+
self.version = '0.0.1'
17+
18+
def get_parser(self):
19+
parser = super().get_parser(description='darkbox wc')
20+
parser.add_argument('-c', '--bytes', action='store_true')
21+
parser.add_argument('-l', '--lines', action='store_true')
22+
parser.add_argument('-w', '--words', action='store_true')
23+
parser.add_argument('files', nargs='+', help='input file')
24+
return parser
25+
26+
def run(self):
27+
args = self.get_args()
28+
29+
# if none are chosen, then choose all (per GNU behavior)
30+
if not any([args['lines'], args['bytes'], args['words']]):
31+
args['lines'] = True
32+
args['bytes'] = True
33+
args['words'] = True
34+
35+
totals = {'words': 0, 'lines': 0, 'chars': 0}
36+
37+
for i in args['files']:
38+
try:
39+
with open(i, 'rb') as f:
40+
file_metrics = {'lines': 0, 'bytes': 0, 'words': 0}
41+
42+
curr_char = f.read(1)
43+
while curr_char != b'':
44+
file_metrics['bytes'] += 1
45+
if curr_char == b'\n': file_metrics['lines'] += 1
46+
if curr_char in b'\n\t ': file_metrics['words'] += 1
47+
curr_char = f.read(1)
48+
49+
print("{} {} {} {}".format(file_metrics['lines'], file_metrics['words'], file_metrics['bytes'], i))
50+
51+
except FileNotFoundError:
52+
self.file_not_found_error(i)
53+
54+
except IsADirectoryError:
55+
self.directory_error(i)

0 commit comments

Comments
 (0)