Skip to content

Commit dab4e11

Browse files
authored
Merge pull request #60 from SimpleITK/PylintFixes
Fixes for Pylint and test refactoring
2 parents 59d771f + 0a47a41 commit dab4e11

File tree

3 files changed

+63
-37
lines changed

3 files changed

+63
-37
lines changed

comment_spell_check/comment_spell_check.py

Lines changed: 42 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818
#
1919
# ==========================================================================*/
2020

21+
""" spell check the comments in code. """
22+
2123
import sys
2224
import os
2325
import fnmatch
@@ -33,7 +35,10 @@
3335

3436
from comment_parser import comment_parser
3537

36-
from comment_spell_check.lib import bibtex_loader
38+
try:
39+
from comment_spell_check.lib import bibtex_loader
40+
except ImportError:
41+
from lib import bibtex_loader
3742

3843
__version__ = "unknown"
3944

@@ -61,7 +66,7 @@
6166
CONTRACTIONS = ["'d", "'s", "'th"]
6267

6368

64-
def splitCamelCase(word):
69+
def split_camel_case(word):
6570
"""Split a camel case string into individual words."""
6671

6772
result = []
@@ -75,16 +80,16 @@ def splitCamelCase(word):
7580
current_word = ""
7681
current_word = current_word + x
7782

78-
if len(current_word):
83+
if len(current_word) > 0:
7984
result.append(current_word)
8085

8186
return result
8287

8388

84-
def getMimeType(filepath):
89+
def get_mime_type(filepath):
8590
"""Map ``filepath`` extension to file type."""
86-
name, ext = os.path.splitext(filepath)
87-
return SUFFIX2MIME.get(ext, "text/plain")
91+
parts = os.path.splitext(filepath)
92+
return SUFFIX2MIME.get(parts[1], "text/plain")
8893

8994

9095
def load_text_file(filename):
@@ -96,7 +101,7 @@ def load_text_file(filename):
96101

97102
output = []
98103
lc = 0
99-
with open(filename) as fp:
104+
with open(filename, encoding="utf-8") as fp:
100105
for line in fp:
101106
line = line.strip()
102107
lc = lc + 1
@@ -116,7 +121,7 @@ def spell_check_words(spell_checker: SpellChecker, words: list[str]):
116121
def spell_check_comment(
117122
spell_checker: SpellChecker,
118123
c: comment_parser.common.Comment,
119-
prefixes: list[str] = [],
124+
prefixes: list[str] = None,
120125
output_lvl=2,
121126
) -> list[str]:
122127
"""Check comment and return list of identified issues if any."""
@@ -131,7 +136,7 @@ def spell_check_comment(
131136
error_word = error.word
132137

133138
if output_lvl > 1:
134-
print(f"Error: {error_word}")
139+
print(f" Error: {error_word}")
135140

136141
valid = False
137142

@@ -142,7 +147,8 @@ def spell_check_comment(
142147
error_word = error_word[: -len(contraction)]
143148
if output_lvl > 1:
144149
print(
145-
f"Stripping contraction: {original_error_word} -> {error_word}"
150+
" Stripping contraction: "
151+
+ f"{original_error_word} -> {error_word}"
146152
)
147153
if spell_checker.check(error_word):
148154
valid = True
@@ -151,62 +157,69 @@ def spell_check_comment(
151157
if valid:
152158
continue
153159

160+
if prefixes is None:
161+
prefixes = []
162+
154163
# Check if the bad word starts with a prefix.
155164
# If so, spell check the word without that prefix.
165+
156166
for pre in prefixes:
157167
if error_word.startswith(pre):
158168
# check if the word is only the prefix
159169
if len(pre) == len(error_word):
160170
if output_lvl > 1:
161-
print(f"Prefix '{pre}' matches word")
171+
print(f" Prefix '{pre}' matches word")
162172
valid = True
163173
break
164174

165175
# remove the prefix
166176
wrd = error_word[len(pre) :]
167177
if output_lvl > 1:
168-
print(f"Trying without '{pre}' prefix: {error_word} -> {wrd}")
178+
print(f" Trying without '{pre}' prefix: {error_word} -> {wrd}")
169179
try:
170180
if spell_checker.check(wrd):
171181
valid = True
172-
break
173182
else:
174183
# Try splitting camel case words and checking each sub-words
175184
if output_lvl > 1:
176-
print("Trying splitting camel case word: {wrd}")
177-
sub_words = splitCamelCase(wrd)
185+
print(f" Trying splitting camel case word: {wrd}")
186+
sub_words = split_camel_case(wrd)
187+
if output_lvl > 1:
188+
print(" Sub-words: ", sub_words)
178189
if len(sub_words) > 1 and spell_check_words(
179190
spell_checker, sub_words
180191
):
181192
valid = True
182193
break
183-
except BaseException:
184-
print(f"Caught an exception for word {error_word} {wrd}")
194+
except TypeError:
195+
print(f" Caught an exception for word {error_word} {wrd}")
185196

186197
if valid:
187198
continue
188199

189200
# Try splitting camel case words and checking each sub-word
190201
if output_lvl > 1:
191-
print(f"Trying splitting camel case word: {error_word}")
192-
sub_words = splitCamelCase(error_word)
202+
print(f" Trying splitting camel case word: {error_word}")
203+
sub_words = split_camel_case(error_word)
193204
if len(sub_words) > 1 and spell_check_words(spell_checker, sub_words):
194205
continue
195206

196207
if output_lvl > 1:
197-
msg = f"error: '{error_word}', suggestions: {spell_checker.suggest()}"
208+
msg = f" Error: '{error_word}', suggestions: {spell_checker.suggest()}"
198209
else:
199210
msg = error_word
200211
mistakes.append(msg)
201212

202213
return mistakes
203214

204215

205-
def spell_check_file(filename, spell_checker, mime_type="", output_lvl=1, prefixes=[]):
216+
def spell_check_file(
217+
filename, spell_checker, mime_type="", output_lvl=1, prefixes=None
218+
):
206219
"""Check spelling in ``filename``."""
207220

208221
if len(mime_type) == 0:
209-
mime_type = getMimeType(filename)
222+
mime_type = get_mime_type(filename)
210223

211224
if output_lvl > 0:
212225
print(f"spell_check_file: {filename}, {mime_type}")
@@ -217,7 +230,7 @@ def spell_check_file(filename, spell_checker, mime_type="", output_lvl=1, prefix
217230
else:
218231
try:
219232
clist = comment_parser.extract_comments(filename, mime=mime_type)
220-
except BaseException:
233+
except TypeError:
221234
print(f"Parser failed, skipping file {filename}")
222235
return []
223236

@@ -227,7 +240,7 @@ def spell_check_file(filename, spell_checker, mime_type="", output_lvl=1, prefix
227240
mistakes = spell_check_comment(
228241
spell_checker, c, prefixes=prefixes, output_lvl=output_lvl
229242
)
230-
if len(mistakes):
243+
if len(mistakes) > 0:
231244
if output_lvl > 0:
232245
print(f"\nLine number {c.line_number()}")
233246
if output_lvl > 0:
@@ -253,7 +266,7 @@ def exclude_check(name, exclude_list):
253266
if exclude_list is None:
254267
return False
255268
for pattern in exclude_list:
256-
match = re.findall("%s" % pattern, name)
269+
match = re.findall(pattern, name)
257270
if len(match) > 0:
258271
return True
259272
return False
@@ -271,6 +284,7 @@ def skip_check(name, skip_list):
271284

272285

273286
def parse_args():
287+
"""parse the command-line arguments."""
274288
parser = argparse.ArgumentParser()
275289

276290
parser.add_argument("filenames", nargs="*")
@@ -398,7 +412,7 @@ def add_dict(enchant_dict, filename, verbose=False):
398412
if verbose:
399413
print(f"Additional dictionary: {filename}")
400414

401-
with open(filename) as f:
415+
with open(filename, encoding="utf-8") as f:
402416
lines = f.read().splitlines()
403417

404418
# You better not have more than 1 word in a line
@@ -435,13 +449,14 @@ def create_spell_checker(args, output_lvl):
435449
for bib in args.bibtex:
436450
bibtex_loader.add_bibtex(my_dict, bib, any([args.brief, output_lvl >= 0]))
437451

438-
# Create the SpellChecker
452+
# Create the spell checking object
439453
spell_checker = SpellChecker(my_dict, filters=[EmailFilter, URLFilter])
440454

441455
return spell_checker
442456

443457

444458
def main():
459+
"""comment_spell_check main function."""
445460
args = parse_args()
446461

447462
# Set the amount of debugging messages to print.

comment_spell_check/lib/bibtex_loader.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
""" Load Bibtex files into a spell checking dictionary. """
2+
13
import bibtexparser
24

35

tests/test_comment_spell_check.py

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -33,14 +33,16 @@ def test_basic(self):
3333
"""Basic test"""
3434
runresult = subprocess.run(
3535
[
36-
"comment_spell_check",
37-
"--miss",
36+
"python",
37+
"comment_spell_check.py",
38+
"--verbose",
3839
"--dict",
39-
"tests/dict.txt",
40+
"../tests/dict.txt",
4041
"--prefix",
4142
"myprefix",
42-
"tests/example.h",
43+
"../tests/example.h",
4344
],
45+
cwd="comment_spell_check",
4446
stdout=subprocess.PIPE,
4547
)
4648
self.assertEqual(runresult.returncode, 0, runresult.stdout)
@@ -49,8 +51,9 @@ def test_codebase(self):
4951
"""Code base test"""
5052
runresult = subprocess.run(
5153
[
52-
"comment_spell_check",
53-
"--miss",
54+
"python",
55+
"comment_spell_check.py",
56+
"--verbose",
5457
"--prefix",
5558
"myprefix",
5659
"--suffix",
@@ -59,6 +62,7 @@ def test_codebase(self):
5962
".md",
6063
".",
6164
],
65+
cwd="comment_spell_check",
6266
stdout=subprocess.PIPE,
6367
)
6468
self.assertEqual(runresult.returncode, 0, runresult.stdout)
@@ -67,9 +71,11 @@ def test_version(self):
6771
"""Version test"""
6872
runresult = subprocess.run(
6973
[
70-
"comment_spell_check",
74+
"python",
75+
"comment_spell_check.py",
7176
"--version",
7277
],
78+
cwd="comment_spell_check",
7379
stdout=subprocess.PIPE,
7480
)
7581
self.assertEqual(runresult.returncode, 0)
@@ -83,11 +89,14 @@ def test_bibtex(self):
8389
"""Bibtext test"""
8490
runresult = subprocess.run(
8591
[
86-
"comment_spell_check",
92+
"python",
93+
"comment_spell_check.py",
94+
"--verbose",
8795
"--bibtex",
88-
"tests/itk.bib",
89-
"tests/bibtest.py",
96+
"../tests/itk.bib",
97+
"../tests/bibtest.py",
9098
],
99+
cwd="comment_spell_check",
91100
stdout=subprocess.PIPE,
92101
)
93102
self.assertEqual(runresult.returncode, 0, runresult.stdout)

0 commit comments

Comments
 (0)