Debian Codegraph @

proselint/command_line.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
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_compiled_python_files()
45 _delete_cache()
46
47
48 def _delete_compiled_python_files():
49 """Remove files with a 'pyc' extension."""
50 for path, _, files in os.walk(os.getcwd()):
51 for fname in [f for f in files if os.path.splitext(f)[1] == ".pyc"]:
52 try:
53 os.remove(os.path.join(path, fname))
54 except OSError:
55 pass
56
57
58 def _delete_cache():
59 """Remove the proselint cache."""
60 proselint_cache = os.path.join("proselint", "cache")
61 try:
62 shutil.rmtree(proselint_cache)
63 except OSError:
64 pass
65
66
67 def print_errors(filename, errors, output_json=False, compact=False):
68 """Print the errors, resulting from lint, for filename."""
69 if output_json:
70 click.echo(errors_to_json(errors))
71
72 else:
73 for error in errors:
74
75 (check, message, line, column, start, end,
76 extent, severity, replacements) = error
77
78 if compact:
79 filename = "-"
80
81 click.echo(
82 filename + ":" +
83 str(1 + line) + ":" +
84 str(1 + column) + ": " +
85 check + " " +
86 message)
87
88
89 @click.command(context_settings=CONTEXT_SETTINGS)
90 @click.version_option(__version__, '--version', '-v', message='%(version)s')
91 @click.option('--config', is_flag=False, type=click.Path(),
92 help="Path to configuration file.")
93 @click.option('--debug', '-d', is_flag=True, help="Give verbose output.")
94 @click.option('--clean', '-c', is_flag=True, help="Clear the cache.")
95 @click.option('--json', '-j', 'output_json', is_flag=True,
96 help="Output as JSON.")
97 @click.option('--time', '-t', is_flag=True, help="Time on a corpus.")
98 @click.option('--demo', is_flag=True, help="Run over demo file.")
99 @click.option('--compact', is_flag=True, help="Shorten output.")
100 @click.option('--dump-config', is_flag=True, help="Prints current config.")
101 @click.option('--dump-default-config', is_flag=True,
102 help="Prints default config.")
103 @click.argument('paths', nargs=-1, type=click.Path())
104 @close_cache_shelves_after
105 def proselint(paths=None, config=None, version=None, clean=None,
106 debug=None, output_json=None, time=None, demo=None, compact=None,
107 dump_config=None, dump_default_config=None):
108 """Create the CLI for proselint, a linter for prose."""
109 if dump_default_config:
110 return print(json.dumps(default, sort_keys=True, indent=4))
111
112 config = load_options(config, default)
113 if dump_config:
114 print(json.dumps(config, sort_keys=True, indent=4))
115 return
116
117 if time:
118 # click.echo(timing_test())
119 print("This option does not work for the time being.")
120 return
121
122 # In debug or clean mode, delete cache & *.pyc files before running.
123 if debug or clean:
124 clear_cache()
125
126 # Use the demo file by default.
127 if demo:
128 paths = [demo_file]
129
130 # Expand the list of directories and files.
131 filepaths = extract_files(list(paths))
132
133 # Lint the files
134 num_errors = 0
135
136 # Use stdin if no paths were specified
137 if len(paths) == 0:
138 filepaths.append('-')
139
140 for fp in filepaths:
141 if fp == '-':
142 fp = '<stdin>'
143 f = sys.stdin
144 else:
145 try:
146 f = click.open_file(fp, 'r', "utf-8", "replace")
147 except Exception:
148 traceback.print_exc()
149 sys.exit(2)
150 errors = lint(f, debug, config)
151 num_errors += len(errors)
152 print_errors(fp, errors, output_json, compact)
153
154 # Return an exit code
155 close_cache_shelves()
156 if num_errors > 0:
157 sys.exit(1)
158 else:
159 sys.exit(0)
160
161
162 def extract_files(files):
163 """Expand list of paths to include all text files matching the pattern."""
164 expanded_files = []
165 legal_extensions = [".md", ".txt", ".rtf", ".html", ".tex", ".markdown"]
166
167 for f in files:
168 # If it's a directory, recursively walk through it and find the files.
169 if os.path.isdir(f):
170 for dir_, _, filenames in os.walk(f):
171 for filename in filenames:
172 fn, file_extension = os.path.splitext(filename)
173 if file_extension in legal_extensions:
174 joined_file = os.path.join(dir_, filename)
175 expanded_files.append(joined_file)
176
177 # Otherwise add the file directly.
178 else:
179 expanded_files.append(f)
180
181 return expanded_files
182
183
184 if __name__ == '__main__':
185 proselint()