Skip to content

Commit

Permalink
fix: correct config export (#1212)
Browse files Browse the repository at this point in the history
  • Loading branch information
Nytelife26 authored Aug 18, 2021
1 parent 935d53a commit 94edc9b
Show file tree
Hide file tree
Showing 6 changed files with 168 additions and 127 deletions.
85 changes: 0 additions & 85 deletions proselint/.proselintrc

This file was deleted.

29 changes: 21 additions & 8 deletions proselint/command_line.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""Command line utility for proselint."""

import json
import os
import shutil
import subprocess
Expand All @@ -8,11 +9,12 @@

import click

from .config import default
from .tools import (close_cache_shelves, close_cache_shelves_after,
errors_to_json, lint)
errors_to_json, lint, load_options)
from .version import __version__

CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
CONTEXT_SETTINGS = {"help_option_names": ['-h', '--help']}
base_url = "proselint.com/"
proselint_path = os.path.dirname(os.path.realpath(__file__))
demo_file = os.path.join(proselint_path, "demo.md")
Expand Down Expand Up @@ -95,11 +97,23 @@ def print_errors(filename, errors, output_json=False, compact=False):
@click.option('--time', '-t', is_flag=True, help="Time on a corpus.")
@click.option('--demo', is_flag=True, help="Run over demo file.")
@click.option('--compact', is_flag=True, help="Shorten output.")
@click.option('--dump-config', is_flag=True, help="Prints current config.")
@click.option('--dump-default-config', is_flag=True,
help="Prints default config.")
@click.argument('paths', nargs=-1, type=click.Path())
@close_cache_shelves_after
def proselint(paths=None, config=None, version=None, clean=None, debug=None,
output_json=None, time=None, demo=None, compact=None):
def proselint(paths=None, config=None, version=None, clean=None,
debug=None, output_json=None, time=None, demo=None, compact=None,
dump_config=None, dump_default_config=None):
"""Create the CLI for proselint, a linter for prose."""
if dump_default_config:
return print(json.dumps(default, sort_keys=True, indent=4))

config = load_options(config, default)
if dump_config:
print(json.dumps(config, sort_keys=True, indent=4))
return

if time:
# click.echo(timing_test())
print("This option does not work for the time being.")
Expand Down Expand Up @@ -129,14 +143,13 @@ def proselint(paths=None, config=None, version=None, clean=None, debug=None,
f = sys.stdin
else:
try:
f = click.open_file(
fp, 'r', encoding="utf-8", errors="replace")
f = click.open_file(fp, 'r', "utf-8", "replace")
except Exception:
traceback.print_exc()
sys.exit(2)
errors = lint(f, debug=debug, config_file_path=config)
errors = lint(f, debug, config)
num_errors += len(errors)
print_errors(fp, errors, output_json, compact=compact)
print_errors(fp, errors, output_json, compact)

# Return an exit code
close_cache_shelves()
Expand Down
87 changes: 87 additions & 0 deletions proselint/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
"""Proselint config - replacement for default .proselintrc since #1212."""

default = {
"max_errors": 1000,
"checks": {
"airlinese.misc": True,
"annotations.misc": True,
"archaism.misc": True,
"cliches.hell": True,
"cliches.misc": True,
"consistency.spacing": True,
"consistency.spelling": True,
"corporate_speak.misc": True,
"cursing.filth": True,
"cursing.nfl": False,
"cursing.nword": True,
"dates_times.am_pm": True,
"dates_times.dates": True,
"hedging.misc": True,
"hyperbole.misc": True,
"jargon.misc": True,
"lexical_illusions.misc": True,
"lgbtq.offensive_terms": True,
"lgbtq.terms": True,
"links.broken": False,
"malapropisms.misc": True,
"misc.apologizing": True,
"misc.back_formations": True,
"misc.bureaucratese": True,
"misc.but": True,
"misc.capitalization": True,
"misc.chatspeak": True,
"misc.commercialese": True,
"misc.composition": True,
"misc.currency": True,
"misc.debased": True,
"misc.false_plurals": True,
"misc.illogic": True,
"misc.inferior_superior": True,
"misc.institution_name": True,
"misc.latin": True,
"misc.many_a": True,
"misc.metaconcepts": True,
"misc.metadiscourse": True,
"misc.narcissism": True,
"misc.not_guilty": True,
"misc.phrasal_adjectives": True,
"misc.preferred_forms": True,
"misc.pretension": True,
"misc.professions": True,
"misc.punctuation": True,
"misc.scare_quotes": True,
"misc.suddenly": True,
"misc.tense_present": True,
"misc.waxed": True,
"misc.whence": True,
"mixed_metaphors.misc": True,
"mondegreens.misc": True,
"needless_variants.misc": True,
"nonwords.misc": True,
"oxymorons.misc": True,
"psychology.misc": True,
"redundancy.misc": True,
"redundancy.ras_syndrome": True,
"skunked_terms.misc": True,
"spelling.able_atable": True,
"spelling.able_ible": True,
"spelling.athletes": True,
"spelling.em_im_en_in": True,
"spelling.er_or": True,
"spelling.in_un": True,
"spelling.misc": True,
"security.credit_card": True,
"security.password": True,
"sexism.misc": True,
"terms.animal_adjectives": True,
"terms.denizen_labels": True,
"terms.eponymous_adjectives": True,
"terms.venery": True,
"typography.diacritical_marks": True,
"typography.exclamation": True,
"typography.symbols": True,
"uncomparables.misc": True,
"weasel_words.misc": True,
"weasel_words.very": True
}
}
52 changes: 24 additions & 28 deletions proselint/tools.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
"""General-purpose tools shared across linting checks."""


import copy
import dbm
import functools
Expand All @@ -13,6 +12,7 @@
import shelve
import sys
import traceback
from warnings import showwarning as warn

_cache_shelves = dict()
proselint_path = os.path.dirname(os.path.realpath(__file__))
Expand All @@ -22,7 +22,7 @@

def close_cache_shelves():
"""Close previously opened cache shelves."""
for _, cache in _cache_shelves.items():
for cache in _cache_shelves.values():
cache.close()
_cache_shelves.clear()

Expand Down Expand Up @@ -138,8 +138,7 @@ def get_checks(options):
"""Extract the checks."""
sys.path.append(proselint_path)
checks = []
check_names = [key for (key, val)
in list(options["checks"].items()) if val]
check_names = [key for (key, val) in options["checks"].items() if val]

for check_name in check_names:
module = importlib.import_module("checks." + check_name)
Expand All @@ -163,24 +162,18 @@ def deepmerge_dicts(dict1, dict2):
return result


def load_options(config_file_path=None):
def load_options(config_file_path=None, conf_default=None):
"""Read various proselintrc files, allowing user overrides."""
system_config_paths = (
'/etc/proselintrc',
os.path.join(proselint_path, '.proselintrc'),
)

system_options = {}
for path in system_config_paths:
if os.path.isfile(path):
system_options = json.load(open(path))
break
conf_default = conf_default or {}
if os.path.isfile("/etc/proselintrc"):
conf_default = json.load(open("/etc/proselintrc"))

user_config_paths = [
os.path.join(cwd, '.proselintrc'),
os.path.join(_get_xdg_config_home(), 'proselint', 'config'),
os.path.join(home_dir, '.proselintrc')
os.path.join(cwd, '.proselintrc.json'),
os.path.join(_get_xdg_config_home(), 'proselint', 'config.json'),
os.path.join(home_dir, '.proselintrc.json')
]

if config_file_path:
if not os.path.isfile(config_file_path):
raise FileNotFoundError(
Expand All @@ -192,10 +185,14 @@ def load_options(config_file_path=None):
if os.path.isfile(path):
user_options = json.load(open(path))
break
oldpath = path.replace(".json", "")
if os.path.isfile(oldpath):
warn(f"{oldpath} was found instead of a JSON file."
f" Rename to {path}.", DeprecationWarning, "", 0)
user_options = json.load(open(oldpath))
break

options = deepmerge_dicts(system_options, user_options)

return options
return deepmerge_dicts(conf_default, user_options)


def errors_to_json(errors):
Expand All @@ -215,7 +212,7 @@ def errors_to_json(errors):
})

return json.dumps(
dict(status="success", data={"errors": out}), sort_keys=True)
{"status": "success", "data": {"errors": out}}, sort_keys=True)


def line_and_column(text, position):
Expand All @@ -230,17 +227,16 @@ def line_and_column(text, position):
return (line_no, position - position_counter)


def lint(input_file, debug=False, config_file_path=None):
def lint(input_file, debug=False, config=None):
"""Run the linter on the input file."""
options = load_options(config_file_path)

config = config or {}
if isinstance(input_file, str):
text = input_file
else:
text = input_file.read()

# Get the checks.
checks = get_checks(options)
checks = get_checks(config)

# Apply all the checks.
errors = []
Expand All @@ -255,11 +251,11 @@ def lint(input_file, debug=False, config_file_path=None):
errors += [(check, message, line, column, start, end,
end - start, "warning", replacements)]

if len(errors) > options["max_errors"]:
if len(errors) > config["max_errors"]:
break

# Sort the errors by line and column number.
errors = sorted(errors[:options["max_errors"]], key=lambda e: (e[2], e[3]))
errors = sorted(errors[:config["max_errors"]], key=lambda e: (e[2], e[3]))

return errors

Expand Down
Loading

0 comments on commit 94edc9b

Please sign in to comment.