"Fossies" - the Fresh Open Source Software Archive  

Source code changes of the file "codespell_lib/_codespell.py" between
codespell-1.17.1.tar.gz and codespell-2.0.0.tar.gz

About: codespell checks source code and other text files for common misspellings.

_codespell.py  (codespell-1.17.1):_codespell.py  (codespell-2.0.0)
skipping to change at line 24 skipping to change at line 24
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html. # http://www.gnu.org/licenses/old-licenses/gpl-2.0.html.
""" """
Copyright (C) 2010-2011 Lucas De Marchi <lucas.de.marchi@gmail.com> Copyright (C) 2010-2011 Lucas De Marchi <lucas.de.marchi@gmail.com>
Copyright (C) 2011 ProFUSION embedded systems Copyright (C) 2011 ProFUSION embedded systems
""" """
from __future__ import print_function from __future__ import print_function
import argparse import argparse
import codecs import codecs
import configparser
import fnmatch import fnmatch
import os import os
import re import re
import sys import sys
import textwrap
word_regex_def = u"[\\w\\-'’`]+" word_regex_def = u"[\\w\\-'’`]+"
encodings = ('utf-8', 'iso-8859-1') encodings = ('utf-8', 'iso-8859-1')
USAGE = """ USAGE = """
\t%prog [OPTIONS] [file1 file2 ... fileN] \t%prog [OPTIONS] [file1 file2 ... fileN]
""" """
VERSION = '1.17.1' VERSION = '2.0.0'
supported_languages_en = ('en', 'en_GB', 'en_US', 'en_CA', 'en_AU')
supported_languages = supported_languages_en
# Users might want to link this file into /usr/local/bin, so we resolve the # Users might want to link this file into /usr/local/bin, so we resolve the
# symbolic link path to the real path if necessary. # symbolic link path to the real path if necessary.
_data_root = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data') _data_root = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data')
_builtin_dictionaries = ( _builtin_dictionaries = (
# name, desc, name, err in aspell, correction in aspell # name, desc, name, err in aspell, correction in aspell, \
# err dictionary array, rep dictionary array
# The arrays must contain the names of aspell dictionaries
# The aspell tests here aren't the ideal state, but the None's are # The aspell tests here aren't the ideal state, but the None's are
# realistic for obscure words # realistic for obscure words
('clear', 'for unambiguous errors', '', False, None), ('clear', 'for unambiguous errors', '',
('rare', 'for rare but valid words', '_rare', None, None), False, None, supported_languages_en, None),
('informal', 'for informal words', '_informal', True, True), ('rare', 'for rare but valid words', '_rare',
('code', 'for words common to code and/or mathematics', '_code', None, None) None, None, None, None),
, # noqa: E501 ('informal', 'for informal words', '_informal',
('names', 'for valid proper names that might be typos', '_names', None, None True, True, supported_languages_en, supported_languages_en),
), # noqa: E501 ('usage', 'for recommended terms', '_usage',
('en-GB_to_en-US', 'for corrections from en-GB to en-US', '_en-GB_to_en-US', None, None, None, None),
True, True), # noqa: E501 ('code', 'for words common to code and/or mathematics', '_code',
None, None, None, None,),
('names', 'for valid proper names that might be typos', '_names',
None, None, None, None,),
('en-GB_to_en-US', 'for corrections from en-GB to en-US', '_en-GB_to_en-US',
# noqa: E501
True, True, ('en_GB',), ('en_US',)),
) )
_builtin_default = 'clear,rare' _builtin_default = 'clear,rare'
# docs say os.EX_USAGE et al. are only available on Unix systems, so to be safe
# we protect and just use the values they are on macOS and Linux
EX_OK = 0
EX_USAGE = 64
EX_DATAERR = 65
# OPTIONS: # OPTIONS:
# #
# ARGUMENTS: # ARGUMENTS:
# dict_filename The file containing the dictionary of misspellings. # dict_filename The file containing the dictionary of misspellings.
# If set to '-', it will be read from stdin # If set to '-', it will be read from stdin
# file1 .. fileN Files to check spelling # file1 .. fileN Files to check spelling
class QuietLevels(object): class QuietLevels(object):
NONE = 0 NONE = 0
ENCODING = 1 ENCODING = 1
skipping to change at line 159 skipping to change at line 180
for line in f: for line in f:
self.encdetector.feed(line) self.encdetector.feed(line)
if self.encdetector.done: if self.encdetector.done:
break break
self.encdetector.close() self.encdetector.close()
encoding = self.encdetector.result['encoding'] encoding = self.encdetector.result['encoding']
try: try:
f = codecs.open(filename, 'r', encoding=encoding) f = codecs.open(filename, 'r', encoding=encoding)
except UnicodeDecodeError: except UnicodeDecodeError:
print('ERROR: Could not detect encoding: %s' % filename, print("ERROR: Could not detect encoding: %s" % filename,
file=sys.stderr) file=sys.stderr)
raise raise
except LookupError: except LookupError:
print('ERROR: %s -- Don\'t know how to handle encoding %s' print("ERROR: Don't know how to handle encoding %s: %s"
% (filename, encoding), file=sys.stderr) % (encoding, filename,), file=sys.stderr)
raise raise
else: else:
lines = f.readlines() lines = f.readlines()
f.close() f.close()
return lines, encoding return lines, encoding
def open_with_internal(self, filename): def open_with_internal(self, filename):
curr = 0 curr = 0
while True: while True:
try: try:
f = codecs.open(filename, 'r', encoding=encodings[curr]) f = codecs.open(filename, 'r', encoding=encodings[curr])
except UnicodeDecodeError: except UnicodeDecodeError:
if not self.quiet_level & QuietLevels.ENCODING: if not self.quiet_level & QuietLevels.ENCODING:
print('WARNING: Decoding file %s' % filename, print("WARNING: Decoding file using encoding=%s failed: %s"
file=sys.stderr) % (encodings[curr], filename,), file=sys.stderr)
print('WARNING: using encoding=%s failed. '
% encodings[curr], file=sys.stderr)
try: try:
print('WARNING: Trying next encoding: %s' print("WARNING: Trying next encoding %s"
% encodings[curr + 1], file=sys.stderr) % encodings[curr + 1], file=sys.stderr)
except IndexError: except IndexError:
pass pass
curr += 1 curr += 1
else: else:
lines = f.readlines() lines = f.readlines()
f.close() f.close()
break break
if not lines: if not lines:
raise Exception('Unknown encoding') raise Exception('Unknown encoding')
encoding = encodings[curr] encoding = encodings[curr]
return lines, encoding return lines, encoding
# -.-:-.-:-.-:-.:-.-:-.-:-.-:-.-:-.:-.-:-.-:-.-:-.-:-.:-.-:- # -.-:-.-:-.-:-.:-.-:-.-:-.-:-.-:-.:-.-:-.-:-.-:-.-:-.:-.-:-
# If someday this breaks, we can just switch to using RawTextHelpFormatter,
# but it has the disadvantage of not wrapping our long lines.
class NewlineHelpFormatter(argparse.HelpFormatter):
"""Help formatter that preserves newlines and deals with lists."""
def _split_lines(self, text, width):
parts = text.split('\n')
out = list()
for pi, part in enumerate(parts):
# Eventually we could allow others...
indent_start = '- '
if part.startswith(indent_start):
offset = len(indent_start)
else:
offset = 0
part = part[offset:]
part = self._whitespace_matcher.sub(' ', part).strip()
parts = textwrap.wrap(part, width - offset)
parts = [' ' * offset + p for p in parts]
if offset:
parts[0] = indent_start + parts[0][offset:]
out.extend(parts)
return out
def parse_options(args): def parse_options(args):
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser(formatter_class=NewlineHelpFormatter)
parser.set_defaults(colors=sys.stdout.isatty()) parser.set_defaults(colors=sys.stdout.isatty())
parser.add_argument('--version', action='version', version=VERSION) parser.add_argument('--version', action='version', version=VERSION)
parser.add_argument('-d', '--disable-colors', parser.add_argument('-d', '--disable-colors',
action='store_false', dest='colors', action='store_false', dest='colors',
help='disable colors, even when printing to terminal ' help='disable colors, even when printing to terminal '
'(always set for Windows)') '(always set for Windows)')
parser.add_argument('-c', '--enable-colors', parser.add_argument('-c', '--enable-colors',
action='store_true', dest='colors', action='store_true', dest='colors',
help='enable colors, even when not printing to ' help='enable colors, even when not printing to '
'terminal') 'terminal')
parser.add_argument('-w', '--write-changes', parser.add_argument('-w', '--write-changes',
action='store_true', default=False, action='store_true', default=False,
help='write changes in place if possible') help='write changes in place if possible')
parser.add_argument('-D', '--dictionary', parser.add_argument('-D', '--dictionary',
action='append', action='append',
help='Custom dictionary file that contains spelling ' help='custom dictionary file that contains spelling '
'corrections. If this flag is not specified or ' 'corrections. If this flag is not specified or '
'equals "-" then the default dictionary is used. ' 'equals "-" then the default dictionary is used. '
'This option can be specified multiple times.') 'This option can be specified multiple times.')
builtin_opts = ', '.join( builtin_opts = '\n- '.join([''] + [
'%r %s' % (d[0], d[1]) for d in _builtin_dictionaries) '%r %s' % (d[0], d[1]) for d in _builtin_dictionaries])
parser.add_argument('--builtin', parser.add_argument('--builtin',
dest='builtin', default=_builtin_default, dest='builtin', default=_builtin_default,
metavar='BUILTIN-LIST', metavar='BUILTIN-LIST',
help='Comma-separated list of builtin dictionaries ' help='comma-separated list of builtin dictionaries '
'to include (when "-D -" or no "-D" is passed). ' 'to include (when "-D -" or no "-D" is passed). '
'Current options are:\n%s. The default is ' 'Current options are:' + builtin_opts + '\n'
'"--builtin %s".' 'The default is %(default)r.')
% (builtin_opts, _builtin_default)) parser.add_argument('--ignore-regex',
action='store', type=str,
help='regular expression which is used to find '
'patterns to ignore by treating as whitespace. '
'When writing regexes, consider ensuring there '
'are boundary non-word chars, e.g., '
'"\\Wmatch\\W". Defaults to empty/disabled.')
parser.add_argument('-I', '--ignore-words', parser.add_argument('-I', '--ignore-words',
action='append', metavar='FILE', action='append', metavar='FILE',
help='File that contains words which will be ignored ' help='file that contains words which will be ignored '
'by codespell. File must contain 1 word per line.' 'by codespell. File must contain 1 word per line.'
' Words are case sensitive based on how they are ' ' Words are case sensitive based on how they are '
'written in the dictionary file') 'written in the dictionary file')
parser.add_argument('-L', '--ignore-words-list', parser.add_argument('-L', '--ignore-words-list',
action='append', metavar='WORDS', action='append', metavar='WORDS',
help='Comma separated list of words to be ignored ' help='comma separated list of words to be ignored '
'by codespell. Words are case sensitive based on ' 'by codespell. Words are case sensitive based on '
'how they are written in the dictionary file') 'how they are written in the dictionary file')
parser.add_argument('-r', '--regex', parser.add_argument('-r', '--regex',
action='store', type=str, action='store', type=str,
help='Regular expression which is used to find words. ' help='regular expression which is used to find words. '
'By default any alphanumeric character, the ' 'By default any alphanumeric character, the '
'underscore, the hyphen, and the apostrophe is ' 'underscore, the hyphen, and the apostrophe is '
'used to build words. This option cannot be ' 'used to build words. This option cannot be '
'specified together with --write-changes.') 'specified together with --write-changes.')
parser.add_argument('-s', '--summary', parser.add_argument('-s', '--summary',
action='store_true', default=False, action='store_true', default=False,
help='print summary of fixes') help='print summary of fixes')
parser.add_argument('--count',
action='store_true', default=False,
help='print the number of errors as the last line of '
'stderr')
parser.add_argument('-S', '--skip', parser.add_argument('-S', '--skip',
action='append', action='append',
help='Comma-separated list of files to skip. It ' help='comma-separated list of files to skip. It '
'accepts globs as well. E.g.: if you want ' 'accepts globs as well. E.g.: if you want '
'codespell to skip .eps and .txt files, ' 'codespell to skip .eps and .txt files, '
'you\'d give "*.eps,*.txt" to this option.') 'you\'d give "*.eps,*.txt" to this option.')
parser.add_argument('-x', '--exclude-file', type=str, metavar='FILE', parser.add_argument('-x', '--exclude-file', type=str, metavar='FILE',
help='FILE with lines that should not be changed') help='FILE with lines that should not be checked for '
'errors or changed')
parser.add_argument('-i', '--interactive', parser.add_argument('-i', '--interactive',
action='store', type=int, default=0, action='store', type=int, default=0,
help='Set interactive mode when writing changes. ' help='set interactive mode when writing changes:\n'
'0: no interactivity. 1: ask for confirmation. ' '- 0: no interactivity.\n'
'2 ask user to choose one fix when more than one ' '- 1: ask for confirmation.\n'
'is available. 3: both 1 and 2') '- 2: ask user to choose one fix when more than one
is available.\n' # noqa: E501
'- 3: both 1 and 2')
parser.add_argument('-q', '--quiet-level', parser.add_argument('-q', '--quiet-level',
action='store', type=int, default=0, action='store', type=int, default=2,
help='Bitmask that allows codespell to run quietly. ' help='bitmask that allows suppressing messages:\n'
'0: the default, in which all messages are ' '- 0: print all messages.\n'
'printed. 1: disable warnings about wrong ' '- 1: disable warnings about wrong encoding.\n'
'encoding. 2: disable warnings about binary ' '- 2: disable warnings about binary files.\n'
'file. 4: shut down warnings about automatic ' '- 4: omit warnings about automatic fixes that were
'fixes that were disabled in dictionary. ' disabled in the dictionary.\n' # noqa: E501
'8: don\'t print anything for non-automatic ' '- 8: don\'t print anything for non-automatic fixes
'fixes. 16: don\'t print fixed files.') .\n' # noqa: E501
'- 16: don\'t print the list of fixed files.\n'
'As usual with bitmasks, these levels can be '
'combined; e.g. use 3 for levels 1+2, 7 for '
'1+2+4, 23 for 1+2+4+16, etc. '
'The default mask is %(default)s.')
parser.add_argument('-e', '--hard-encoding-detection', parser.add_argument('-e', '--hard-encoding-detection',
action='store_true', default=False, action='store_true', default=False,
help='Use chardet to detect the encoding of each ' help='use chardet to detect the encoding of each '
'file. This can slow down codespell, but is more ' 'file. This can slow down codespell, but is more '
'reliable in detecting encodings other than ' 'reliable in detecting encodings other than '
'utf-8, iso8859-1, and ascii.') 'utf-8, iso8859-1, and ascii.')
parser.add_argument('-f', '--check-filenames', parser.add_argument('-f', '--check-filenames',
action='store_true', default=False, action='store_true', default=False,
help='check file names as well') help='check file names as well')
parser.add_argument('-H', '--check-hidden', parser.add_argument('-H', '--check-hidden',
action='store_true', default=False, action='store_true', default=False,
help='check hidden files (those starting with ".") as ' help='check hidden files and directories (those '
'well') 'starting with ".") as well.')
parser.add_argument('-A', '--after-context', type=int, metavar='LINES', parser.add_argument('-A', '--after-context', type=int, metavar='LINES',
help='print LINES of trailing context') help='print LINES of trailing context')
parser.add_argument('-B', '--before-context', type=int, metavar='LINES', parser.add_argument('-B', '--before-context', type=int, metavar='LINES',
help='print LINES of leading context') help='print LINES of leading context')
parser.add_argument('-C', '--context', type=int, metavar='LINES', parser.add_argument('-C', '--context', type=int, metavar='LINES',
help='print LINES of surrounding context') help='print LINES of surrounding context')
parser.add_argument('--config', type=str,
help='path to config file.')
parser.add_argument('files', nargs='*', parser.add_argument('files', nargs='*',
help='files or directories to check') help='files or directories to check')
# Parse command line options.
options = parser.parse_args(list(args)) options = parser.parse_args(list(args))
# Load config files and look for ``codespell`` options.
cfg_files = ['setup.cfg', '.codespellrc']
if options.config:
cfg_files.append(options.config)
config = configparser.ConfigParser()
config.read(cfg_files)
if config.has_section('codespell'):
# Build a "fake" argv list using option name and value.
cfg_args = []
for key in config['codespell']:
# Add option as arg.
cfg_args.append("--%s" % key)
# If value is blank, skip.
val = config['codespell'][key]
if val != "":
cfg_args.append(val)
# Parse config file options.
options = parser.parse_args(cfg_args)
# Re-parse command line options to override config.
options = parser.parse_args(list(args), namespace=options)
if not options.files: if not options.files:
options.files.append('.') options.files.append('.')
return options, parser return options, parser
def build_exclude_hashes(filename, exclude_lines): def build_exclude_hashes(filename, exclude_lines):
with codecs.open(filename, 'r') as f: with codecs.open(filename, 'r') as f:
for line in f: for line in f:
exclude_lines.add(line) exclude_lines.add(line)
skipping to change at line 435 skipping to change at line 522
misspelling.data = r misspelling.data = r
return misspelling.fix, fix_case(wrongword, misspelling.data) return misspelling.fix, fix_case(wrongword, misspelling.data)
def print_context(lines, index, context): def print_context(lines, index, context):
# context = (context_before, context_after) # context = (context_before, context_after)
for i in range(index - context[0], index + context[1] + 1): for i in range(index - context[0], index + context[1] + 1):
if 0 <= i < len(lines): if 0 <= i < len(lines):
print('%s %s' % ('>' if i == index else ':', lines[i].rstrip())) print('%s %s' % ('>' if i == index else ':', lines[i].rstrip()))
def extract_words(text, word_regex, ignore_word_regex):
if ignore_word_regex:
text = ignore_word_regex.sub(' ', text)
return word_regex.findall(text)
def parse_file(filename, colors, summary, misspellings, exclude_lines, def parse_file(filename, colors, summary, misspellings, exclude_lines,
file_opener, word_regex, context, options): file_opener, word_regex, ignore_word_regex, context, options):
bad_count = 0 bad_count = 0
lines = None lines = None
changed = False changed = False
encoding = encodings[0] # if not defined, use UTF-8 encoding = encodings[0] # if not defined, use UTF-8
if filename == '-': if filename == '-':
f = sys.stdin f = sys.stdin
lines = f.readlines() lines = f.readlines()
else: else:
# ignore binary files
if not os.path.isfile(filename):
return 0
if options.check_filenames: if options.check_filenames:
for word in word_regex.findall(filename): for word in extract_words(filename, word_regex, ignore_word_regex):
lword = word.lower() lword = word.lower()
if lword not in misspellings: if lword not in misspellings:
continue continue
fix = misspellings[lword].fix fix = misspellings[lword].fix
fixword = fix_case(word, misspellings[lword].data) fixword = fix_case(word, misspellings[lword].data)
if summary and fix: if summary and fix:
summary.update(lword) summary.update(lword)
cfilename = "%s%s%s" % (colors.FILE, filename, colors.DISABLE) cfilename = "%s%s%s" % (colors.FILE, filename, colors.DISABLE)
skipping to change at line 483 skipping to change at line 572
creason = '' creason = ''
bad_count += 1 bad_count += 1
print("%(FILENAME)s: %(WRONGWORD)s" print("%(FILENAME)s: %(WRONGWORD)s"
" ==> %(RIGHTWORD)s%(REASON)s" " ==> %(RIGHTWORD)s%(REASON)s"
% {'FILENAME': cfilename, % {'FILENAME': cfilename,
'WRONGWORD': cwrongword, 'WRONGWORD': cwrongword,
'RIGHTWORD': crightword, 'REASON': creason}) 'RIGHTWORD': crightword, 'REASON': creason})
# ignore irregular files
if not os.path.isfile(filename):
return bad_count
text = is_text_file(filename) text = is_text_file(filename)
if not text: if not text:
if not options.quiet_level & QuietLevels.BINARY_FILE: if not options.quiet_level & QuietLevels.BINARY_FILE:
print("WARNING: Binary file: %s " % filename, file=sys.stderr) print("WARNING: Binary file: %s" % filename, file=sys.stderr)
return 0 return bad_count
try: try:
lines, encoding = file_opener.open(filename) lines, encoding = file_opener.open(filename)
except Exception: except Exception:
return 0 return bad_count
for i, line in enumerate(lines): for i, line in enumerate(lines):
if line in exclude_lines: if line in exclude_lines:
continue continue
fixed_words = set() fixed_words = set()
asked_for = set() asked_for = set()
for word in word_regex.findall(line): for word in extract_words(line, word_regex, ignore_word_regex):
lword = word.lower() lword = word.lower()
if lword in misspellings: if lword in misspellings:
context_shown = False context_shown = False
fix = misspellings[lword].fix fix = misspellings[lword].fix
fixword = fix_case(word, misspellings[lword].data) fixword = fix_case(word, misspellings[lword].data)
if options.interactive and lword not in asked_for: if options.interactive and lword not in asked_for:
if context is not None: if context is not None:
context_shown = True context_shown = True
print_context(lines, i, context) print_context(lines, i, context)
skipping to change at line 593 skipping to change at line 686
def _script_main(): def _script_main():
"""Wrap to main() for setuptools.""" """Wrap to main() for setuptools."""
return main(*sys.argv[1:]) return main(*sys.argv[1:])
def main(*args): def main(*args):
"""Contains flow control""" """Contains flow control"""
options, parser = parse_options(args) options, parser = parse_options(args)
if options.regex and options.write_changes: if options.regex and options.write_changes:
print('ERROR: --write-changes cannot be used together with ' print("ERROR: --write-changes cannot be used together with "
'--regex') "--regex")
parser.print_help() parser.print_help()
return 1 return EX_USAGE
word_regex = options.regex or word_regex_def word_regex = options.regex or word_regex_def
try: try:
word_regex = re.compile(word_regex) word_regex = re.compile(word_regex)
except re.error as err: except re.error as err:
print('ERROR: invalid regular expression "%s" (%s)' % print("ERROR: invalid --regex \"%s\" (%s)" %
(word_regex, err), file=sys.stderr) (word_regex, err), file=sys.stderr)
parser.print_help() parser.print_help()
return 1 return EX_USAGE
if options.ignore_regex:
try:
ignore_word_regex = re.compile(options.ignore_regex)
except re.error as err:
print("ERROR: invalid --ignore-regex \"%s\" (%s)" %
(options.ignore_regex, err), file=sys.stderr)
parser.print_help()
return EX_USAGE
else:
ignore_word_regex = None
ignore_words_files = options.ignore_words or [] ignore_words_files = options.ignore_words or []
ignore_words = set() ignore_words = set()
for ignore_words_file in ignore_words_files: for ignore_words_file in ignore_words_files:
if not os.path.isfile(ignore_words_file): if not os.path.isfile(ignore_words_file):
print('ERROR: cannot find ignore-words file: %s' % print("ERROR: cannot find ignore-words file: %s" %
ignore_words_file, file=sys.stderr) ignore_words_file, file=sys.stderr)
parser.print_help() parser.print_help()
return 1 return EX_USAGE
build_ignore_words(ignore_words_file, ignore_words) build_ignore_words(ignore_words_file, ignore_words)
ignore_words_list = options.ignore_words_list or [] ignore_words_list = options.ignore_words_list or []
for comma_separated_words in ignore_words_list: for comma_separated_words in ignore_words_list:
for word in comma_separated_words.split(','): for word in comma_separated_words.split(','):
ignore_words.add(word.strip()) ignore_words.add(word.strip())
if options.dictionary: if options.dictionary:
dictionaries = options.dictionary dictionaries = options.dictionary
else: else:
skipping to change at line 638 skipping to change at line 742
# figure out which builtin dictionaries to use # figure out which builtin dictionaries to use
use = sorted(set(options.builtin.split(','))) use = sorted(set(options.builtin.split(',')))
for u in use: for u in use:
for builtin in _builtin_dictionaries: for builtin in _builtin_dictionaries:
if builtin[0] == u: if builtin[0] == u:
use_dictionaries.append( use_dictionaries.append(
os.path.join(_data_root, 'dictionary%s.txt' os.path.join(_data_root, 'dictionary%s.txt'
% (builtin[2],))) % (builtin[2],)))
break break
else: else:
print('ERROR: Unknown builtin dictionary: %s' % (u,), print("ERROR: Unknown builtin dictionary: %s" % (u,),
file=sys.stderr) file=sys.stderr)
parser.print_help() parser.print_help()
return 1 return EX_USAGE
else: else:
if not os.path.isfile(dictionary): if not os.path.isfile(dictionary):
print('ERROR: cannot find dictionary file: %s' % dictionary, print("ERROR: cannot find dictionary file: %s" % dictionary,
file=sys.stderr) file=sys.stderr)
parser.print_help() parser.print_help()
return 1 return EX_USAGE
use_dictionaries.append(dictionary) use_dictionaries.append(dictionary)
misspellings = dict() misspellings = dict()
for dictionary in use_dictionaries: for dictionary in use_dictionaries:
build_dict(dictionary, misspellings, ignore_words) build_dict(dictionary, misspellings, ignore_words)
colors = TermColors() colors = TermColors()
if not options.colors or sys.platform == 'win32': if not options.colors or sys.platform == 'win32':
colors.disable() colors.disable()
if options.summary: if options.summary:
summary = Summary() summary = Summary()
else: else:
summary = None summary = None
context = None context = None
if options.context is not None: if options.context is not None:
if (options.before_context is not None) or \ if (options.before_context is not None) or \
(options.after_context is not None): (options.after_context is not None):
print('ERROR: --context/-C cannot be used together with ' print("ERROR: --context/-C cannot be used together with "
'--context-before/-B or --context-after/-A') "--context-before/-B or --context-after/-A")
parser.print_help() parser.print_help()
return 1 return EX_USAGE
context_both = max(0, options.context) context_both = max(0, options.context)
context = (context_both, context_both) context = (context_both, context_both)
elif (options.before_context is not None) or \ elif (options.before_context is not None) or \
(options.after_context is not None): (options.after_context is not None):
context_before = 0 context_before = 0
context_after = 0 context_after = 0
if options.before_context is not None: if options.before_context is not None:
context_before = max(0, options.before_context) context_before = max(0, options.before_context)
if options.after_context is not None: if options.after_context is not None:
context_after = max(0, options.after_context) context_after = max(0, options.after_context)
skipping to change at line 700 skipping to change at line 804
for filename in options.files: for filename in options.files:
# ignore hidden files # ignore hidden files
if is_hidden(filename, options.check_hidden): if is_hidden(filename, options.check_hidden):
continue continue
if os.path.isdir(filename): if os.path.isdir(filename):
for root, dirs, files in os.walk(filename): for root, dirs, files in os.walk(filename):
if glob_match.match(root): # skip (absolute) directories if glob_match.match(root): # skip (absolute) directories
del dirs[:] del dirs[:]
continue continue
if is_hidden(root, options.check_hidden): # dir itself hidden
continue
for file_ in files: for file_ in files:
# ignore hidden files in directories
if is_hidden(file_, options.check_hidden):
continue
if glob_match.match(file_): # skip files if glob_match.match(file_): # skip files
continue continue
fname = os.path.join(root, file_) fname = os.path.join(root, file_)
if glob_match.match(fname): # skip paths if glob_match.match(fname): # skip paths
continue continue
if not os.path.isfile(fname) or not os.path.getsize(fname):
continue
bad_count += parse_file( bad_count += parse_file(
fname, colors, summary, misspellings, exclude_lines, fname, colors, summary, misspellings, exclude_lines,
file_opener, word_regex, context, options) file_opener, word_regex, ignore_word_regex, context,
options)
# skip (relative) directories # skip (relative) directories
dirs[:] = [dir_ for dir_ in dirs if not glob_match.match(dir_)] dirs[:] = [dir_ for dir_ in dirs if not glob_match.match(dir_)]
else: else:
bad_count += parse_file( bad_count += parse_file(
filename, colors, summary, misspellings, exclude_lines, filename, colors, summary, misspellings, exclude_lines,
file_opener, word_regex, context, options) file_opener, word_regex, ignore_word_regex, context, options)
if summary: if summary:
print("\n-------8<-------\nSUMMARY:") print("\n-------8<-------\nSUMMARY:")
print(summary) print(summary)
return bad_count if options.count:
print(bad_count, file=sys.stderr)
return EX_DATAERR if bad_count else EX_OK
 End of changes. 55 change blocks. 
75 lines changed or deleted 184 lines changed or added

Home  |  About  |  Features  |  All  |  Newest  |  Dox  |  Diffs  |  RSS Feeds  |  Screenshots  |  Comments  |  Imprint  |  Privacy  |  HTTP(S)