Skip to content

Commit fe1acd6

Browse files
committed
✨ implement CountableFile
1 parent beca9e7 commit fe1acd6

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

code_counter/core/countable/__init__.py

Whitespace-only changes.
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
import os
5+
from code_counter.conf.config import Config
6+
7+
8+
class CountableFile:
9+
def __init__(self, url_path: str):
10+
self._url_path = url_path
11+
self._format_output = []
12+
self._comment_symbol = tuple(Config().comment)
13+
14+
self.file_type = os.path.splitext(url_path)[1][1:]
15+
self.file_lines = 0
16+
self.code_lines = 0
17+
self.blank_lines = 0
18+
self.comment_lines = 0
19+
20+
def __file_content(self):
21+
with open(self._url_path, 'rb') as content:
22+
return content.readlines()
23+
24+
def count(self):
25+
single = {
26+
'file_lines': 0,
27+
'code_lines': 0,
28+
'blank_lines': 0,
29+
'comment_lines': 0,
30+
}
31+
32+
for line_number, raw_line in enumerate(self.__file_content()):
33+
try:
34+
line = raw_line.strip().decode('utf8')
35+
except UnicodeDecodeError:
36+
try:
37+
# If the code line contain Chinese string, decode it as gbk
38+
line = raw_line.strip().decode('gbk')
39+
except UnicodeDecodeError:
40+
self._format_output.append(
41+
'\n\t{:>10} | decode line occurs a problem, non-count it, at File "{}", line {}:'.format(
42+
'WARN', self._url_path, line_number))
43+
self._format_output.append('\t{:>10} | {}\n'.format(' ', raw_line))
44+
continue
45+
46+
single['file_lines'] += 1
47+
if not line:
48+
single['blank_lines'] += 1
49+
elif line.startswith(tuple(self._comment_symbol)):
50+
single['comment_lines'] += 1
51+
else:
52+
single['code_lines'] += 1
53+
54+
self.file_lines = single['file_lines']
55+
self.code_lines = single['code_lines']
56+
self.blank_lines = single['blank_lines']
57+
self.comment_lines = single['comment_lines']
58+
59+
def __str__(self):
60+
self._format_output.append(
61+
'\t{:>10} |{:>10} |{:>10} |{:>10} |{:>10} | {}'.format(self.file_type, self.file_lines,
62+
self.code_lines, self.blank_lines,
63+
self.comment_lines,
64+
self._url_path))
65+
return '\n'.join(self._format_output)

0 commit comments

Comments
 (0)