Debian Codegraph @

proselint/tools.py

raw
1 """General-purpose tools shared across linting checks."""
2
3 import copy
4 import dbm
5 import functools
6 import hashlib
7 import importlib
8 import inspect
9 import json
10 import os
11 import re
12 import shelve
13 import sys
14 import traceback
15 from warnings import showwarning as warn
16
17 from . import config
18
19 _cache_shelves = dict()
20 proselint_path = os.path.dirname(os.path.realpath(__file__))
21 home_dir = os.path.expanduser("~")
22 cwd = os.getcwd()
23
24
25 def close_cache_shelves():
26 """Close previously opened cache shelves."""
27 for cache in _cache_shelves.values():
28 cache.close()
29 _cache_shelves.clear()
30
31
32 def close_cache_shelves_after(f):
33 """Decorate a function to ensure cache shelves are closed after call."""
34 @functools.wraps(f)
35 def wrapped(*args, **kwargs):
36 f(*args, **kwargs)
37 close_cache_shelves()
38 return wrapped
39
40
41 def _get_xdg_path(variable_name, default_path):
42 path = os.environ.get(variable_name)
43 if path is None or path == '':
44 return default_path
45 else:
46 return path
47
48
49 def _get_xdg_config_home():
50 return _get_xdg_path('XDG_CONFIG_HOME', os.path.join(home_dir, '.config'))
51
52
53 def _get_xdg_cache_home():
54 return _get_xdg_path('XDG_CACHE_HOME', os.path.join(home_dir, '.cache'))
55
56
57 def _get_cache(cachepath):
58 if cachepath in _cache_shelves:
59 return _cache_shelves[cachepath]
60
61 try:
62 cache = shelve.open(cachepath, protocol=2)
63 except dbm.error:
64 # dbm error on open - delete and retry
65 print('Error (%s) opening %s - will attempt to delete and re-open.' %
66 (sys.exc_info()[1], cachepath))
67 try:
68 os.remove(cachepath)
69 cache = shelve.open(cachepath, protocol=2)
70 except Exception:
71 print('Error on re-open: %s' % sys.exc_info()[1])
72 cache = None
73 except Exception:
74 # unknown error
75 print('Could not open cache file %s, maybe name collision. '
76 'Error: %s' % (cachepath, traceback.format_exc()))
77 cache = None
78
79 # Don't fail on bad caches
80 if cache is None:
81 print('Using in-memory shelf for cache file %s' % cachepath)
82 cache = shelve.Shelf(dict())
83
84 _cache_shelves[cachepath] = cache
85 return cache
86
87
88 def memoize(f):
89 """Cache results of computations on disk."""
90 # Determine the location of the cache.
91 cache_dirname = os.path.join(_get_xdg_cache_home(), 'proselint')
92 legacy_cache_dirname = os.path.join(home_dir, ".proselint")
93
94 if not os.path.isdir(cache_dirname):
95 # Migrate the cache from the legacy path to XDG compliant location.
96 if os.path.isdir(legacy_cache_dirname):
97 os.rename(legacy_cache_dirname, cache_dirname)
98 # Create the cache if it does not already exist.
99 else:
100 os.makedirs(cache_dirname)
101
102 cache_filename = f.__module__ + "." + f.__name__
103 cachepath = os.path.join(cache_dirname, cache_filename)
104
105 @functools.wraps(f)
106 def wrapped(*args, **kwargs):
107
108 # handle instance methods
109 if hasattr(f, '__self__'):
110 args = args[1:]
111
112 signature = cache_filename.encode("utf-8")
113
114 tempargdict = inspect.getcallargs(f, *args, **kwargs)
115
116 for item in list(tempargdict.items()):
117 if item[0] == "text":
118 signature += item[1].encode("utf-8")
119
120 key = hashlib.sha256(signature).hexdigest()
121 cache = _get_cache(cachepath)
122
123 try:
124 return cache[key]
125 except KeyError:
126 value = f(*args, **kwargs)
127 cache[key] = value
128 cache.sync()
129 return value
130 except TypeError:
131 call_to = f.__module__ + '.' + f.__name__
132 print('Warning: could not disk cache call to %s;'
133 'it probably has unhashable args. Error: %s' %
134 (call_to, traceback.format_exc()))
135 return f(*args, **kwargs)
136
137 return wrapped
138
139
140 def get_checks(options):
141 """Extract the checks."""
142 sys.path.append(proselint_path)
143 checks = []
144 check_names = [key for (key, val) in options["checks"].items() if val]
145
146 for check_name in check_names:
147 module = importlib.import_module("checks." + check_name)
148 for d in dir(module):
149 if re.match("check", d):
150 checks.append(getattr(module, d))
151
152 return checks
153
154
155 def deepmerge_dicts(dict1, dict2):
156 """Deep merge dictionaries, second dict will take priority."""
157 result = copy.deepcopy(dict1)
158
159 for key, value in dict2.items():
160 if isinstance(value, dict):
161 result[key] = deepmerge_dicts(result[key] or {}, value)
162 else:
163 result[key] = value
164
165 return result
166
167
168 def load_options(config_file_path=None, conf_default=None):
169 """Read various proselintrc files, allowing user overrides."""
170 conf_default = conf_default or {}
171 if os.path.isfile("/etc/proselintrc"):
172 conf_default = json.load(open("/etc/proselintrc"))
173
174 user_config_paths = [
175 os.path.join(cwd, '.proselintrc.json'),
176 os.path.join(_get_xdg_config_home(), 'proselint', 'config.json'),
177 os.path.join(home_dir, '.proselintrc.json')
178 ]
179
180 if config_file_path:
181 if not os.path.isfile(config_file_path):
182 raise FileNotFoundError(
183 f"Config file {config_file_path} does not exist")
184 user_config_paths.insert(0, config_file_path)
185
186 user_options = {}
187 for path in user_config_paths:
188 if os.path.isfile(path):
189 user_options = json.load(open(path))
190 break
191 oldpath = path.replace(".json", "")
192 if os.path.isfile(oldpath):
193 warn(f"{oldpath} was found instead of a JSON file."
194 f" Rename to {path}.", DeprecationWarning, "", 0)
195 user_options = json.load(open(oldpath))
196 break
197
198 return deepmerge_dicts(conf_default, user_options)
199
200
201 def errors_to_json(errors):
202 """Convert the errors to JSON."""
203 out = []
204 for e in errors:
205 out.append({
206 "check": e[0],
207 "message": e[1],
208 "line": 1 + e[2],
209 "column": 1 + e[3],
210 "start": 1 + e[4],
211 "end": 1 + e[5],
212 "extent": e[6],
213 "severity": e[7],
214 "replacements": e[8],
215 })
216
217 return json.dumps(
218 {"status": "success", "data": {"errors": out}}, sort_keys=True)
219
220
221 def line_and_column(text, position):
222 """Return the line number and column of a position in a string."""
223 position_counter = 0
224 line_no = 0
225 for line in text.splitlines(True):
226 if (position_counter + len(line.rstrip())) >= position:
227 break
228 position_counter += len(line)
229 line_no += 1
230 return (line_no, position - position_counter)
231
232
233 def lint(input_file, debug=False, config=config.default):
234 """Run the linter on the input file."""
235 if isinstance(input_file, str):
236 text = input_file
237 else:
238 text = input_file.read()
239
240 # Get the checks.
241 checks = get_checks(config)
242
243 # Apply all the checks.
244 errors = []
245 for check in checks:
246
247 result = check(text)
248
249 for error in result:
250 (start, end, check, message, replacements) = error
251 (line, column) = line_and_column(text, start)
252 if not is_quoted(start, text):
253 errors += [(check, message, line, column, start, end,
254 end - start, "warning", replacements)]
255
256 if len(errors) > config["max_errors"]:
257 break
258
259 # Sort the errors by line and column number.
260 errors = sorted(errors[:config["max_errors"]], key=lambda e: (e[2], e[3]))
261
262 return errors
263
264
265 def assert_error(text, check, n=1):
266 """Assert that text has n errors of type check."""
267 assert_error.description = f"No {check} error for '{text}'"
268 assert len([error[0] for error in lint(text) if error[0] == check]) == n
269
270
271 def consistency_check(text, word_pairs, err, msg, offset=0):
272 """Build a consistency checker for the given word_pairs."""
273 errors = []
274
275 msg = " ".join(msg.split())
276
277 for w in word_pairs:
278 matches = [
279 [m for m in re.finditer(w[0], text)],
280 [m for m in re.finditer(w[1], text)]
281 ]
282
283 if len(matches[0]) > 0 and len(matches[1]) > 0:
284
285 idx_minority = len(matches[0]) > len(matches[1])
286
287 for m in matches[idx_minority]:
288 errors.append((
289 m.start() + offset,
290 m.end() + offset,
291 err,
292 msg.format(w[~idx_minority], m.group(0)),
293 w[~idx_minority]))
294
295 return errors
296
297
298 def preferred_forms_check(text, list, err, msg, ignore_case=True, offset=0):
299 """Build a checker that suggests the preferred form."""
300 if ignore_case:
301 flags = re.IGNORECASE
302 else:
303 flags = 0
304
305 msg = " ".join(msg.split())
306
307 errors = []
308 regex = r"[\W^]{}[\W$]"
309 for p in list:
310 for r in p[1]:
311 for m in re.finditer(regex.format(r), text, flags=flags):
312 txt = m.group(0).strip()
313 errors.append((
314 m.start() + 1 + offset,
315 m.end() + offset,
316 err,
317 msg.format(p[0], txt),
318 p[0]))
319
320 return errors
321
322
323 def existence_check(text, list, err, msg, ignore_case=True, str=False,
324 offset=0, require_padding=True, dotall=False,
325 excluded_topics=None, exceptions=(), join=False):
326 """Build a checker that prohibits certain words or phrases."""
327 flags = 0
328
329 msg = " ".join(msg.split())
330
331 if ignore_case:
332 flags = flags | re.IGNORECASE
333
334 if str:
335 flags = flags | re.UNICODE
336
337 if dotall:
338 flags = flags | re.DOTALL
339
340 if require_padding:
341 regex = r"(?:^|\W){}[\W$]"
342 else:
343 regex = r"{}"
344
345 errors = []
346
347 # If the topic of the text is in the excluded list, return immediately.
348 if excluded_topics:
349 tps = topics(text)
350 if any([t in excluded_topics for t in tps]):
351 return errors
352
353 rx = "|".join(regex.format(w) for w in list)
354 for m in re.finditer(rx, text, flags=flags):
355 txt = m.group(0).strip()
356 if any([re.search(exception, txt) for exception in exceptions]):
357 continue
358 errors.append((
359 m.start() + 1 + offset,
360 m.end() + offset,
361 err,
362 msg.format(txt),
363 None))
364
365 return errors
366
367
368 def max_errors(limit):
369 """Decorate a check to truncate error output to a specified limit."""
370 def wrapper(f):
371 @functools.wraps(f)
372 def wrapped(*args, **kwargs):
373 return truncate_errors(f(*args, **kwargs), limit)
374 return wrapped
375 return wrapper
376
377
378 def truncate_errors(errors, limit=float("inf")):
379 """If limit was specified, truncate the list of errors.
380
381 Give the total number of times that the error was found elsewhere.
382 """
383 if len(errors) > limit:
384 start1, end1, err1, msg1, replacements = errors[0]
385
386 if len(errors) == limit + 1:
387 msg1 += " Found once elsewhere."
388 else:
389 msg1 += f" Found {len(errors)} times elsewhere."
390
391 errors = [(start1, end1, err1, msg1, replacements)] + errors[1:limit]
392
393 return errors
394
395
396 def ppm_threshold(threshold):
397 """Decorate a check to error if the PPM threshold is surpassed."""
398 def wrapped(f):
399 @functools.wraps(f)
400 def wrapper(*args, **kwargs):
401 return threshold_check(f(*args, **kwargs), threshold, len(args[0]))
402 return wrapper
403 return wrapped
404
405
406 def threshold_check(errors, threshold, length):
407 """Check that returns an error if the PPM threshold is surpassed."""
408 if length > 0:
409 errcount = len(errors)
410 ppm = (errcount / length) * 1e6
411
412 if ppm >= threshold and errcount >= 1:
413 return [errors[0]]
414 return []
415
416
417 def is_quoted(position, text):
418 """Determine if the position in the text falls within a quote."""
419 def matching(quotemark1, quotemark2):
420 straight = '\"\''
421 curly = '“”'
422 if quotemark1 in straight and quotemark2 in straight:
423 return True
424 if quotemark1 in curly and quotemark2 in curly:
425 return True
426 else:
427 return False
428
429 def find_ranges(text):
430 s = 0
431 q = pc = ''
432 start = None
433 ranges = []
434 seps = " .,:;-\r\n"
435 quotes = ['\"', '“', '”', "'"]
436 for i, c in enumerate(text + "\n"):
437 if s == 0 and c in quotes and pc in seps:
438 start = i
439 s = 1
440 q = c
441 elif s == 1 and matching(c, q):
442 s = 2
443 elif s == 2:
444 if c in seps:
445 ranges.append((start+1, i-1))
446 start = None
447 s = 0
448 else:
449 s = 1
450 pc = c
451 return ranges
452
453 def position_in_ranges(ranges, position):
454 for start, end in ranges:
455 if start <= position < end:
456 return True
457 return False
458
459 return position_in_ranges(find_ranges(text), position)
460
461
462 def detector_50_Cent(text):
463 """Determine whether 50 Cent is a topic."""
464 keywords = [
465 "50 Cent",
466 "rap",
467 "hip hop",
468 "Curtis James Jackson III",
469 "Curtis Jackson",
470 "Eminem",
471 "Dre",
472 "Get Rich or Die Tryin'",
473 "G-Unit",
474 "Street King Immortal",
475 "In da Club",
476 "Interscope",
477 ]
478 num_keywords = sum(word in text for word in keywords)
479 return ("50 Cent", float(num_keywords > 2))
480
481
482 def topics(text):
483 """Return a list of topics."""
484 detectors = [
485 detector_50_Cent
486 ]
487 ts = []
488 for detector in detectors:
489 ts.append(detector(text))
490
491 return [t[0] for t in ts if t[1] > 0.95]
492
493
494 def context(text, position, level="paragraph"):
495 """Get sentence or paragraph that surrounds the given position."""
496 if level == "sentence":
497 pass
498 elif level == "paragraph":
499 pass
500
501 return ""