forked from tk0miya/flake8-coding
-
Notifications
You must be signed in to change notification settings - Fork 0
/
flake8_coding.py
63 lines (53 loc) · 2.23 KB
/
flake8_coding.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# -*- coding: utf-8 -*-
import re
__version__ = '1.2.1'
class CodingChecker(object):
name = 'flake8_coding'
version = __version__
def __init__(self, tree, filename):
self.filename = filename
@classmethod
def add_options(cls, parser):
parser.add_option(
'--accept-encodings', default='latin-1, utf-8', action='store',
help="Acceptable source code encodings for `coding:` magic comment"
)
parser.config_options.append('accept-encodings')
parser.add_option(
'--no-accept-encodings', action='store_true',
help="Warn for files containing a `coding:` magic comment"
)
parser.config_options.append('no-accept-encodings')
@classmethod
def parse_options(cls, options):
if options.no_accept_encodings:
cls.encodings = None
else:
cls.encodings = [e.strip().lower() for e in options.accept_encodings.split(',')]
def read_headers(self):
import pep8
if self.filename in ('stdin', '-', None):
return pep8.stdin_get_value().splitlines(True)[:2]
else:
return pep8.readlines(self.filename)[:2]
def run(self):
try:
# PEP-263 says: a magic comment must be placed into the source
# files either as first or second line in the file
lines = self.read_headers()
if len(lines) == 0:
raise StopIteration()
for lineno, line in enumerate(lines, start=1):
matched = re.search('coding[:=]\s*([-\w.]+)', line, re.IGNORECASE)
if matched:
if self.encodings:
if matched.group(1).lower() not in self.encodings:
yield lineno, 0, "C102 Unknown encoding found in coding magic comment", type(self)
else:
yield lineno, 0, "C103 Coding magic comment present", type(self)
break
else:
if self.encodings:
yield 0, 0, "C101 Coding magic comment not found", type(self)
except IOError:
pass