Debian Codegraph @

proselint/command_line.py

raw ◀ ▶
1 Debian patch touch this file
1 """Command line utility for proselint."""
2
3 import json
4 import os
5 import shutil
6 import subprocess
7 import sys
8 import traceback
9
10 import click
11
12 from .config import default
13 from .tools import (close_cache_shelves, close_cache_shelves_after,
14 errors_to_json, lint, load_options)
15 from .version import __version__
16
17 CONTEXT_SETTINGS = {"help_option_names": ['-h', '--help']}
18 base_url = "proselint.com/"
19 proselint_path = os.path.dirname(os.path.realpath(__file__))
20 demo_file = os.path.join(proselint_path, "demo.md")
21
22
23 # TODO: fix broken corpus
24 def timing_test(corpus="0.1.0"):
25 """Measure timing performance on the named corpus."""
26 import time
27 dirname = os.path.dirname
28 corpus_path = os.path.join(
29 dirname(dirname(os.path.realpath(__file__))), "corpora", corpus)
30 start = time.time()
31 for file in os.listdir(corpus_path):
32 filepath = os.path.join(corpus_path, file)
33 if ".md" == filepath[-3:]:
34 subprocess.call(["proselint", filepath, ">/dev/null"])
35
36 return time.time() - start
37
38
39 def clear_cache():
40 """Delete the contents of the cache."""
41 click.echo("Deleting the cache...")
42
43 # see issue #624
44 _delete_cache()
45
46
47 def _delete_compiled_python_files():
48 """Remove files with a 'pyc' extension."""
49 for path, _, files in os.walk(os.getcwd()):
50 for fname in [f for f in files if os.path.splitext(f)[1] == ".pyc"]:
51 try:
52 os.remove(os.path.join(path, fname))
53 except OSError:
54 pass
55
56
57 def _delete_cache():
58 """Remove the proselint cache."""
59 proselint_cache = os.path.join("proselint", "cache")
60 try:
61 shutil.rmtree(proselint_cache)
62 except OSError:
63 pass
64
65
66 def print_errors(filename, errors, output_json=False, compact=False):
67 """Print the errors, resulting from lint, for filename."""
68 if output_json:
69 click.echo(errors_to_json(errors))
70
71 else:
72 for error in errors:
73
74 (check, message, line, column, start, end,
75 extent, severity, replacements) = error
76
77 if compact:
78 filename = "-"
79
80 click.echo(
81 filename + ":" +
82 str(1 + line) + ":" +
83 str(1 + column) + ": " +
84 check + " " +
85 message)
86
87
88 @click.command(context_settings=CONTEXT_SETTINGS)
89 @click.version_option(__version__, '--version', '-v', message='%(version)s')
90 @click.option('--config', is_flag=False, type=click.Path(),
91 help="Path to configuration file.")
92 @click.option('--debug', '-d', is_flag=True, help="Give verbose output.")
93 @click.option('--clean', '-c', is_flag=True, help="Clear the cache.")
94 @click.option('--json', '-j', 'output_json', is_flag=True,
95 help="Output as JSON.")
96 @click.option('--time', '-t', is_flag=True, help="Time on a corpus.")
97 @click.option('--demo', is_flag=True, help="Run over demo file.")
98 @click.option('--compact', is_flag=True, help="Shorten output.")
99 @click.option('--dump-config', is_flag=True, help="Prints current config.")
100 @click.option('--dump-default-config', is_flag=True,
101 help="Prints default config.")
102 @click.argument('paths', nargs=-1, type=click.Path())
103 @close_cache_shelves_after
104 def proselint(paths=None, config=None, version=None, clean=None,
105 debug=None, output_json=None, time=None, demo=None, compact=None,
106 dump_config=None, dump_default_config=None):
107 """Create the CLI for proselint, a linter for prose."""
108 if dump_default_config:
109 return print(json.dumps(default, sort_keys=True, indent=4))
110
111 config = load_options(config, default)
112 if dump_config:
113 print(json.dumps(config, sort_keys=True, indent=4))
114 return
115
116 if time:
117 # click.echo(timing_test())
118 print("This option does not work for the time being.")
119 return
120
121 # In debug or clean mode, delete cache & *.pyc files before running.
122 if debug or clean:
123 clear_cache()
124
125 # Use the demo file by default.
126 if demo:
127 paths = [demo_file]
128
129 # Expand the list of directories and files.
130 filepaths = extract_files(list(paths))
131
132 # Lint the files
133 num_errors = 0
134
135 # Use stdin if no paths were specified
136 if len(paths) == 0:
137 filepaths.append('-')
138
139 for fp in filepaths:
140 if fp == '-':
141 fp = '<stdin>'
142 f = sys.stdin
143 else:
144 try:
145 f = click.open_file(fp, 'r', "utf-8", "replace")
146 except Exception:
147 traceback.print_exc()
148 sys.exit(2)
149 errors = lint(f, debug, config)
150 num_errors += len(errors)
151 print_errors(fp, errors, output_json, compact)
152
153 # Return an exit code
154 close_cache_shelves()
155 if num_errors > 0:
156 sys.exit(1)
157 else:
158 sys.exit(0)
159
160
161 def extract_files(files):
162 """Expand list of paths to include all text files matching the pattern."""
163 expanded_files = []
164 legal_extensions = [".md", ".txt", ".rtf", ".html", ".tex", ".markdown"]
165
166 for f in files:
167 # If it's a directory, recursively walk through it and find the files.
168 if os.path.isdir(f):
169 for dir_, _, filenames in os.walk(f):
170 for filename in filenames:
171 fn, file_extension = os.path.splitext(filename)
172 if file_extension in legal_extensions:
173 joined_file = os.path.join(dir_, filename)
174 expanded_files.append(joined_file)
175
176 # Otherwise add the file directly.
177 else:
178 expanded_files.append(f)
179
180 return expanded_files
181
182
183 if __name__ == '__main__':
184 proselint()