Skip to content

Commit 5eac429

Browse files
authored
fix: Patched ruff warnings, applied ruff format, better integrated/configured ruff into the contribution process (jxmorris12#118)
* refactor (__init__.py) : declared imports in __all__ (ruff patch) * refactor : ruff format * fix (CONTRIBUTING.md) : replacing black by ruff as formatting tool * fix: ruff auto fix (type I) * fix: ruff fix (type B) * fix: ruff fix (type SIM) * fix: ruff fix (type RET) * feat (pyproject.toml) : adding ruff lint config to checks specific rules
1 parent cb964c5 commit 5eac429

File tree

12 files changed

+770
-457
lines changed

12 files changed

+770
-457
lines changed

CONTRIBUTING.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ Before creating your pull request, when you have made all your commits, you need
3434
ruff check language_tool_python tests
3535

3636
# Format code
37-
black language_tool_python tests
37+
ruff format language_tool_python tests
3838

3939
# Tests
4040
pytest

extract_long_description.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
1-
import toml
21
import os
32

3+
import toml
4+
45
with open("pyproject.toml", "rb") as f:
5-
pyproject = toml.loads(f.read().decode('utf-8'))
6+
pyproject = toml.loads(f.read().decode("utf-8"))
67

78
readme_path = pyproject["project"]["readme"]
89

language_tool_python/__init__.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,14 @@
11
"""LanguageTool API for Python."""
22

3+
__all__ = [
4+
"LanguageTool",
5+
"LanguageToolPublicAPI",
6+
"LanguageTag",
7+
"Match",
8+
"utils",
9+
]
10+
11+
from . import utils
312
from .language_tag import LanguageTag
413
from .match import Match
514
from .server import LanguageTool, LanguageToolPublicAPI
6-
from . import utils

language_tool_python/__main__.py

Lines changed: 110 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -4,18 +4,19 @@
44
import locale
55
import re
66
import sys
7-
from importlib.metadata import version, PackageNotFoundError
8-
import toml
7+
from importlib.metadata import PackageNotFoundError, version
98
from typing import Any, Optional, Set, Union
109

10+
import toml
11+
1112
from .server import LanguageTool
1213
from .utils import LanguageToolError
1314

1415
try:
1516
__version__ = version("language_tool_python")
16-
except PackageNotFoundError: # If the package is not installed in the environment, read the version from pyproject.toml
17+
except PackageNotFoundError: # If the package is not installed in the environment, read the version from pyproject.toml
1718
with open("pyproject.toml", "rb") as f:
18-
__version__ = toml.loads(f.read().decode('utf-8'))["project"]["version"]
19+
__version__ = toml.loads(f.read().decode("utf-8"))["project"]["version"]
1920

2021

2122
def parse_args() -> argparse.Namespace:
@@ -27,50 +28,88 @@ def parse_args() -> argparse.Namespace:
2728
"""
2829
parser = argparse.ArgumentParser(
2930
description=__doc__.strip() if __doc__ else None,
30-
prog='language_tool_python')
31-
parser.add_argument('files', nargs='+',
32-
help='plain text file or "-" for stdin')
33-
parser.add_argument('-c', '--encoding',
34-
help='input encoding')
35-
parser.add_argument('-l', '--language', metavar='CODE',
36-
help='language code of the input or "auto"')
37-
parser.add_argument('-m', '--mother-tongue', metavar='CODE',
38-
help='language code of your first language')
39-
parser.add_argument('-d', '--disable', metavar='RULES', type=get_rules,
40-
action=RulesAction, default=set(),
41-
help='list of rule IDs to be disabled')
42-
parser.add_argument('-e', '--enable', metavar='RULES', type=get_rules,
43-
action=RulesAction, default=set(),
44-
help='list of rule IDs to be enabled')
45-
parser.add_argument('--enabled-only', action='store_true',
46-
help='disable all rules except those specified in '
47-
'--enable')
48-
parser.add_argument('-p', '--picky', action='store_true',
49-
help='If set, additional rules will be activated.')
31+
prog="language_tool_python",
32+
)
33+
parser.add_argument("files", nargs="+", help='plain text file or "-" for stdin')
34+
parser.add_argument("-c", "--encoding", help="input encoding")
35+
parser.add_argument(
36+
"-l",
37+
"--language",
38+
metavar="CODE",
39+
help='language code of the input or "auto"',
40+
)
41+
parser.add_argument(
42+
"-m",
43+
"--mother-tongue",
44+
metavar="CODE",
45+
help="language code of your first language",
46+
)
47+
parser.add_argument(
48+
"-d",
49+
"--disable",
50+
metavar="RULES",
51+
type=get_rules,
52+
action=RulesAction,
53+
default=set(),
54+
help="list of rule IDs to be disabled",
55+
)
56+
parser.add_argument(
57+
"-e",
58+
"--enable",
59+
metavar="RULES",
60+
type=get_rules,
61+
action=RulesAction,
62+
default=set(),
63+
help="list of rule IDs to be enabled",
64+
)
65+
parser.add_argument(
66+
"--enabled-only",
67+
action="store_true",
68+
help="disable all rules except those specified in --enable",
69+
)
5070
parser.add_argument(
51-
'--version', action='version',
52-
version=f'%(prog)s {__version__}',
53-
help='show version')
54-
parser.add_argument('-a', '--apply', action='store_true',
55-
help='automatically apply suggestions if available')
56-
parser.add_argument('-s', '--spell-check-off', dest='spell_check',
57-
action='store_false',
58-
help='disable spell-checking rules')
59-
parser.add_argument('--ignore-lines',
60-
help='ignore lines that match this regular expression')
61-
parser.add_argument('--remote-host',
62-
help='hostname of the remote LanguageTool server')
63-
parser.add_argument('--remote-port',
64-
help='port of the remote LanguageTool server')
71+
"-p",
72+
"--picky",
73+
action="store_true",
74+
help="If set, additional rules will be activated.",
75+
)
76+
parser.add_argument(
77+
"--version",
78+
action="version",
79+
version=f"%(prog)s {__version__}",
80+
help="show version",
81+
)
82+
parser.add_argument(
83+
"-a",
84+
"--apply",
85+
action="store_true",
86+
help="automatically apply suggestions if available",
87+
)
88+
parser.add_argument(
89+
"-s",
90+
"--spell-check-off",
91+
dest="spell_check",
92+
action="store_false",
93+
help="disable spell-checking rules",
94+
)
95+
parser.add_argument(
96+
"--ignore-lines",
97+
help="ignore lines that match this regular expression",
98+
)
99+
parser.add_argument(
100+
"--remote-host",
101+
help="hostname of the remote LanguageTool server",
102+
)
103+
parser.add_argument("--remote-port", help="port of the remote LanguageTool server")
65104

66105
args = parser.parse_args()
67106

68107
if args.enabled_only:
69108
if args.disable:
70-
parser.error('--enabled-only cannot be used with --disable')
109+
parser.error("--enabled-only cannot be used with --disable")
71110

72111
if not args.enable:
73-
parser.error('--enabled-only requires --enable')
112+
parser.error("--enabled-only requires --enable")
74113

75114
return args
76115

@@ -85,7 +124,14 @@ class RulesAction(argparse.Action):
85124
Attributes:
86125
dest (str): the destination attribute to update
87126
"""
88-
def __call__(self, parser: argparse.ArgumentParser, namespace: Any, values: Any, option_string: Optional[str] = None):
127+
128+
def __call__(
129+
self,
130+
parser: argparse.ArgumentParser,
131+
namespace: Any,
132+
values: Any,
133+
option_string: Optional[str] = None,
134+
):
89135
"""
90136
This method is called when the action is triggered. It updates the set of rules
91137
in the namespace with the provided values. The method is invoked automatically
@@ -115,7 +161,11 @@ def get_rules(rules: str) -> Set[str]:
115161
return {rule.upper() for rule in re.findall(r"[\w\-]+", rules)}
116162

117163

118-
def get_text(filename: Union[str, int], encoding: Optional[str], ignore: Optional[str]) -> str:
164+
def get_text(
165+
filename: Union[str, int],
166+
encoding: Optional[str],
167+
ignore: Optional[str],
168+
) -> str:
119169
"""
120170
Read the content of a file and return it as a string, optionally ignoring lines that match a regular expression.
121171
@@ -129,9 +179,10 @@ def get_text(filename: Union[str, int], encoding: Optional[str], ignore: Optiona
129179
:rtype: str
130180
"""
131181
with open(filename, encoding=encoding) as f:
132-
text = ''.join('\n' if (ignore and re.match(ignore, line)) else line
133-
for line in f.readlines())
134-
return text
182+
return "".join(
183+
"\n" if (ignore and re.match(ignore, line)) else line
184+
for line in f.readlines()
185+
)
135186

136187

137188
def main() -> int:
@@ -149,20 +200,21 @@ def main() -> int:
149200
if len(args.files) > 1:
150201
print(filename, file=sys.stderr)
151202

152-
if filename == '-':
203+
if filename == "-":
153204
filename = sys.stdin.fileno()
154205
encoding = args.encoding or (
155-
sys.stdin.encoding if sys.stdin.isatty()
206+
sys.stdin.encoding
207+
if sys.stdin.isatty()
156208
else locale.getpreferredencoding()
157209
)
158210
else:
159-
encoding = args.encoding or 'utf-8'
211+
encoding = args.encoding or "utf-8"
160212

161213
remote_server = None
162214
if args.remote_host is not None:
163215
remote_server = args.remote_host
164216
if args.remote_port is not None:
165-
remote_server += f':{args.remote_port}'
217+
remote_server += f":{args.remote_port}"
166218
lang_tool = LanguageTool(
167219
language=args.language,
168220
motherTongue=args.mother_tongue,
@@ -172,7 +224,7 @@ def main() -> int:
172224
try:
173225
text = get_text(filename, encoding, ignore=args.ignore_lines)
174226
except UnicodeError as exception:
175-
print(f'{filename}: {exception}', file=sys.stderr)
227+
print(f"{filename}: {exception}", file=sys.stderr)
176228
continue
177229

178230
if not args.spell_check:
@@ -192,24 +244,24 @@ def main() -> int:
192244
for match in lang_tool.check(text):
193245
rule_id = match.ruleId
194246

195-
replacement_text = ', '.join(
196-
f"'{word}'"
197-
for word in match.replacements).strip()
247+
replacement_text = ", ".join(
248+
f"'{word}'" for word in match.replacements
249+
).strip()
198250

199251
message = match.message
200252

201253
# Messages that end with punctuation already include the
202254
# suggestion.
203-
if replacement_text and not message.endswith('?'):
204-
message += ' Suggestions: ' + replacement_text
205-
255+
if replacement_text and not message.endswith("?"):
256+
message += " Suggestions: " + replacement_text
257+
206258
line, column = match.get_line_and_column(text)
207259

208-
print(f'{filename}:{line}:{column}: {rule_id}: {message}')
260+
print(f"{filename}:{line}:{column}: {rule_id}: {message}")
209261

210262
status = 2
211263
except LanguageToolError as exception:
212-
print(f'{filename}: {exception}', file=sys.stderr)
264+
print(f"{filename}: {exception}", file=sys.stderr)
213265
continue
214266

215267
return status

0 commit comments

Comments
 (0)