-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathflake8_coding.py
73 lines (62 loc) · 2.56 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
64
65
66
67
68
69
70
71
72
73
# -*- coding: utf-8 -*-
import re
__version__ = '1.3.2'
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.add_option(
'--no-accept-encodings', action='store_true', parse_from_config=True,
help="Warn for files containing a `coding:` magic comment"
)
if hasattr(parser, 'config_options'): # for flake8 < 3.0
parser.config_options.append('accept-encodings')
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):
if self.filename in ('stdin', '-', None):
try:
# flake8 >= v3.0
from flake8.engine import pep8 as stdin_utils
except ImportError:
from flake8 import utils as stdin_utils
return stdin_utils.stdin_get_value().splitlines(True)[:2]
else:
try:
import pycodestyle
except ImportError:
import pep8 as pycodestyle
return pycodestyle.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:
return
for lineno, line in enumerate(lines, start=1):
matched = re.search(r'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 1, 0, "C101 Coding magic comment not found", type(self)
except IOError:
pass