Skip to content
This repository was archived by the owner on Jul 13, 2019. It is now read-only.

Commit 2563fa1

Browse files
mattyclarksontkruse
authored andcommitted
Added support for Python3000
1 parent c33842f commit 2563fa1

File tree

2 files changed

+70
-16
lines changed

2 files changed

+70
-16
lines changed

cpplint.py

+33-8
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,9 @@
5757
_valid_extensions = set(['c', 'cc', 'cpp', 'cxx', 'c++', 'h', 'hpp', 'hxx',
5858
'h++'])
5959

60+
Py3k = (sys.version_info[0] == 3)
61+
"""A boolean to check if we are running Python3000"""
62+
6063
_USAGE = """
6164
Syntax: cpplint.py [--verbose=#] [--output=vs7] [--filter=-x,+y,...]
6265
[--counting=total|toplevel|detailed] [--root=subdir]
@@ -502,6 +505,19 @@
502505
# This is set by --linelength flag.
503506
_line_length = 80
504507

508+
try:
509+
xrange(0,1)
510+
except NameError:
511+
xrange = range
512+
try:
513+
unicode
514+
except NameError:
515+
basestring = unicode = str
516+
try:
517+
long
518+
except NameError:
519+
long = int
520+
505521
def ParseNolintSuppressions(filename, raw_line, linenum, error):
506522
"""Updates the global list of error-suppressions.
507523
@@ -841,7 +857,11 @@ def IncrementErrorCount(self, category):
841857

842858
def PrintErrorCounts(self):
843859
"""Print a summary of errors by category, and the total."""
844-
for category, count in self.errors_by_category.iteritems():
860+
try:
861+
items = self.errors_by_category.iteritems()
862+
except AttributeError:
863+
items = self.errors_by_category.items()
864+
for category, count in items:
845865
sys.stderr.write('Category \'%s\' errors found: %d\n' %
846866
(category, count))
847867
sys.stderr.write('Total errors found: %d\n' % self.error_count)
@@ -1816,7 +1836,7 @@ def CheckForBadCharacters(filename, lines, error):
18161836
error: The function to call with any errors found.
18171837
"""
18181838
for linenum, line in enumerate(lines):
1819-
if u'\ufffd' in line:
1839+
if unicode(b'\xef\xbf\xbd', 'utf-8') in line:
18201840
error(filename, linenum, 'readability/utf8', 5,
18211841
'Line contains invalid UTF-8 (or Unicode replacement character).')
18221842
if '\0' in line:
@@ -4702,7 +4722,10 @@ def _GetTextInside(text, start_pattern):
47024722

47034723
# Give opening punctuations to get the matching close-punctuations.
47044724
matching_punctuation = {'(': ')', '{': '}', '[': ']'}
4705-
closing_punctuation = set(matching_punctuation.itervalues())
4725+
try:
4726+
closing_punctuation = set(matching_punctuation.values())
4727+
except AttributeError:
4728+
closing_punctuation = set(matching_punctuation.itervalues())
47064729

47074730
# Find the position to start extracting text.
47084731
match = re.search(start_pattern, text, re.M)
@@ -5672,7 +5695,7 @@ def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error,
56725695

56735696
# include_dict is modified during iteration, so we iterate over a copy of
56745697
# the keys.
5675-
header_keys = include_dict.keys()
5698+
header_keys = list(include_dict.keys())
56765699
for header in header_keys:
56775700
(same_module, common_path) = FilesBelongToSameModule(abs_filename, header)
56785701
fullpath = common_path + header
@@ -6307,10 +6330,11 @@ def main():
63076330

63086331
# Change stderr to write with replacement characters so we don't die
63096332
# if we try to print something containing non-ASCII characters.
6310-
sys.stderr = codecs.StreamReaderWriter(sys.stderr,
6311-
codecs.getreader('utf8'),
6312-
codecs.getwriter('utf8'),
6313-
'replace')
6333+
if not Py3k:
6334+
sys.stderr = codecs.StreamReaderWriter(sys.stderr,
6335+
codecs.getreader('utf8'),
6336+
codecs.getwriter('utf8'),
6337+
'replace')
63146338

63156339
_cpplint_state.ResetErrorCounts()
63166340
for filename in filenames:
@@ -6322,3 +6346,4 @@ def main():
63226346

63236347
if __name__ == '__main__':
63246348
main()
6349+

cpplint_unittest.py

+37-8
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,26 @@
4343
import shutil
4444

4545
import cpplint
46+
import sys
4647

48+
try:
49+
xrange(0,1)
50+
except NameError:
51+
xrange = range
52+
try:
53+
unicode
54+
except NameError:
55+
basestring = unicode = str
56+
try:
57+
long
58+
except NameError:
59+
long = int
60+
Py3k = (sys.version_info[0] == 3)
61+
if Py3k:
62+
chrstr = bytes
63+
else:
64+
def chrstr(l):
65+
return ''.join([chr(x) for x in l])
4766

4867
# This class works as an error collector and replaces cpplint.Error
4968
# function for the unit tests. We also verify each category we see
@@ -307,8 +326,11 @@ def testFalsePositivesNoError(self):
307326
# Test get line width.
308327
def testGetLineWidth(self):
309328
self.assertEquals(0, cpplint.GetLineWidth(''))
310-
self.assertEquals(10, cpplint.GetLineWidth(u'x' * 10))
311-
self.assertEquals(16, cpplint.GetLineWidth(u'都|道|府|県|支庁'))
329+
self.assertEquals(10, cpplint.GetLineWidth(unicode('x') * 10))
330+
try:
331+
self.assertEquals(16, cpplint.GetLineWidth('都|道|府|県|支庁'.decode('utf-8')))
332+
except AttributeError:
333+
self.assertEquals(16, cpplint.GetLineWidth('都|道|府|県|支庁'))
312334

313335
def testGetTextInside(self):
314336
self.assertEquals('', cpplint._GetTextInside('fun()', r'fun\('))
@@ -2930,7 +2952,7 @@ def DoTest(self, raw_bytes, has_invalid_utf8):
29302952
error_collector = ErrorCollector(self.assert_)
29312953
cpplint.ProcessFileData(
29322954
'foo.cc', 'cc',
2933-
unicode(raw_bytes, 'utf8', 'replace').split('\n'),
2955+
raw_bytes.decode('utf-8', 'replace').split('\n'),
29342956
error_collector)
29352957
# The warning appears only once.
29362958
self.assertEquals(
@@ -2940,12 +2962,19 @@ def DoTest(self, raw_bytes, has_invalid_utf8):
29402962
' (or Unicode replacement character).'
29412963
' [readability/utf8] [5]'))
29422964

2943-
DoTest(self, 'Hello world\n', False)
2944-
DoTest(self, '\xe9\x8e\xbd\n', False)
2945-
DoTest(self, '\xe9x\x8e\xbd\n', True)
2965+
# For Python 2/3 compatibility we must use the chrstr shim to create the
2966+
# the byte strings because Python3 automatically trys to encode it to
2967+
# UTF-8. Normal strings must be encoded to ascii to make the DoTest
2968+
# function correctly work on Python3
2969+
DoTest(self, 'Hello world\n'.encode('ascii'), False)
2970+
# '\xe9 \x8e \xbd \n'
2971+
DoTest(self, chrstr([233, 142, 189, 10]), False)
2972+
# '\xe9 x \x8e \xbd \n'
2973+
DoTest(self, chrstr([233, 120, 142, 189, 10]), True)
29462974
# This is the encoding of the replacement character itself (which
29472975
# you can see by evaluating codecs.getencoder('utf8')(u'\ufffd')).
2948-
DoTest(self, '\xef\xbf\xbd\n', True)
2976+
# '\xef \xbf \xbd \n'
2977+
DoTest(self, chrstr([239, 191, 189, 10]), True)
29492978

29502979
def testBadCharacters(self):
29512980
# Test for NUL bytes only
@@ -2963,7 +2992,7 @@ def testBadCharacters(self):
29632992
cpplint.ProcessFileData(
29642993
'nul_utf8.cc', 'cc',
29652994
['// Copyright 2014 Your Company.',
2966-
unicode('\xe9x\0', 'utf8', 'replace'), ''],
2995+
chrstr([233, 120, 0]).decode('utf-8', 'replace'), ''],
29672996
error_collector)
29682997
self.assertEquals(
29692998
error_collector.Results(),

0 commit comments

Comments
 (0)