Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions functional_tests/NameLengthTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
class checkSuperLongClassName {
}

let checkElementNameLength:(ename:Int, veryLongElementName:Int) = (1, 2)

enum PrettyLongExampleEnum: Int {
case A, BIsAVeryLongEnumCaseName, C = 5, D
}

func myFunctionNameIsTooLong(longExternalParameterName aLongLocalParameterName: Int) -> Bool {
return true
}

let myString = "hello"
mySwitchLabel: switch myString {
case "hello":
print("yes")
case "hi":
print("no")
default:
print("both")
}

protocol TooLongProtocolHere {
}

struct RectIsAPrettyLongName {
var mid: Int {
get {
return 1
}
set(newCenterTooLong) {
mid = newCenterTooLong
}
}
}

typealias LongNameMusicalNote = String

var thisIsALongVariableName = 0
let thisIsALongConstantName = 1
23 changes: 18 additions & 5 deletions tailor/listeners/filelistener.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,33 @@
from tailor.types.location import Location
from tailor.utils.sourcefile import file_too_long, num_lines_in_file
from tailor.utils.sourcefile import file_too_long, lines_too_long, \
num_lines_in_file


class FileListener:
# pylint: disable=too-few-public-methods

def __init__(self, printer, filepath):
def __init__(self, printer, filepath, max_lengths):
self.__printer = printer
self.__filepath = filepath
self.__max_lengths = max_lengths

def verify(self, max_lines):
self.__verify_file_length(max_lines)
def verify(self):
self.__verify_file_length(self.__max_lengths.max_file_length)
self.__verify_line_lengths(self.__max_lengths.max_line_length)

def __verify_file_length(self, max_lines):
if file_too_long(self.__filepath, max_lines):
self.__printer.error('File is over maximum line limit (' +
str(num_lines_in_file(self.__filepath)) +
'/' + str(max_lines) + ')',
loc=Location(max_lines, 1))
# Mark error on first character of next line
# TODO: Use printer method without column
loc=Location(max_lines + 1, 1))

def __verify_line_lengths(self, max_line_length):
for line in lines_too_long(self.__filepath, max_line_length):
self.__printer.error('Line is over maximum character limit (' +
str(line.column) + '/' +
str(max_line_length) + ')',
# Mark error on first character beyond limit
loc=Location(line.line, max_line_length + 1))
57 changes: 56 additions & 1 deletion tailor/listeners/mainlistener.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@
from tailor.swift.swiftlistener import SwiftListener
from tailor.types.location import Location
from tailor.utils.charformat import is_upper_camel_case
from tailor.utils.sourcefile import construct_too_long
from tailor.utils.sourcefile import construct_too_long, name_too_long


class MainListener(SwiftListener):
# pylint: disable=too-many-public-methods

def __init__(self, printer, max_lengths):
self.__printer = printer
Expand All @@ -16,22 +17,32 @@ def __init__(self, printer, max_lengths):
def enterClassName(self, ctx):
self.__verify_upper_camel_case(
ctx, 'Class names should be in UpperCamelCase')
self.__verify_name_length(
ctx, 'Class', self.__max_lengths.max_name_length)

def enterEnumName(self, ctx):
self.__verify_upper_camel_case(
ctx, 'Enum names should be in UpperCamelCase')
self.__verify_name_length(
ctx, 'Enum', self.__max_lengths.max_name_length)

def enterEnumCaseName(self, ctx):
self.__verify_upper_camel_case(
ctx, 'Enum case names should be in UpperCamelCase')
self.__verify_name_length(
ctx, 'Enum Case', self.__max_lengths.max_name_length)

def enterStructName(self, ctx):
self.__verify_upper_camel_case(
ctx, 'Struct names should be in UpperCamelCase')
self.__verify_name_length(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could refactor this to a function called checkName that would check length and case. It could be overdoing it though. Thoughts?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe that enterStructName() and similar functions currently play the role of checkName(), however not all of these functions need both case and length checks (e.g. labels) so adding another layer of abstraction would potentially complicate things.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

They arguably should have both name and length checks though right? We just haven't implemented them. I'm okay with moving this to another PR though.

ctx, 'Struct', self.__max_lengths.max_name_length)

def enterProtocolName(self, ctx):
self.__verify_upper_camel_case(
ctx, 'Protocol names should be in UpperCamelCase')
self.__verify_name_length(
ctx, 'Protocol', self.__max_lengths.max_name_length)

def enterStatement(self, ctx):
self.__verify_not_semicolon_terminated(ctx)
Expand Down Expand Up @@ -121,6 +132,44 @@ def __evaluate_tuple_pattern(self, tuple_pattern, walker):
tuple_pattern.tuplePatternElementList().tuplePatternElement():
self.__evaluate_pattern(tuple_pattern_element.pattern(), walker)

def enterElementName(self, ctx):
self.__verify_name_length(
ctx, 'Element', self.__max_lengths.max_name_length)

def enterExternalParameterName(self, ctx):
self.__verify_name_length(
ctx, 'External Parameter', self.__max_lengths.max_name_length)

def enterFunctionName(self, ctx):
self.__verify_name_length(
ctx, 'Function', self.__max_lengths.max_name_length)

def enterLabelName(self, ctx):
self.__verify_name_length(
ctx, 'Label', self.__max_lengths.max_name_length)

def enterLocalParameterName(self, ctx):
self.__verify_name_length(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So currently we do case checks for constants inside ConstantDeclListener. With doing this you're handling local function parameter names for params that are either variables or constants. I think that eventually you will need to add a check for length inside ConstantDeclListener, which will flag this error twice. So maybe its worth just moving this check inside ConstantDeclListener for now (that will not handle vars, but you can add that in when we eventually have VarDeclListener).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As discussed with @a4sriniv offline, we will be modifying this when it becomes an issue in completing #13 (for variable names).

ctx, 'Local Parameter', self.__max_lengths.max_name_length)

# TODO: #41 Fix grammar for setter declarations
def enterSetterName(self, ctx):
self.__verify_name_length(
ctx, 'Setter', self.__max_lengths.max_name_length)

def enterTypealiasName(self, ctx):
self.__verify_name_length(
ctx, 'Typealias', self.__max_lengths.max_name_length)

def enterTypeName(self, ctx):
self.__verify_name_length(
ctx, 'Type', self.__max_lengths.max_name_length)

# TODO: #13 Handle all cases for variable name declarations
def enterVariableName(self, ctx):
self.__verify_name_length(
ctx, 'Variable', self.__max_lengths.max_name_length)

def __verify_upper_camel_case(self, ctx, err_msg):
construct_name = ctx.getText()
if not is_upper_camel_case(construct_name):
Expand All @@ -139,3 +188,9 @@ def __verify_construct_length(self, ctx, construct_type, max_length):
construct_type + ' is over maximum line limit (' +
str(ctx.stop.line - ctx.start.line) + '/' + str(max_length) +
')', ctx)

def __verify_name_length(self, ctx, construct_type, max_length):
if name_too_long(ctx, max_length):
self.__printer.error(
construct_type + ' name is over maximum character limit (' +
str(len(ctx.getText())) + '/' + str(max_length) + ')', ctx)
15 changes: 11 additions & 4 deletions tailor/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,18 @@ def parse_args():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('infile', type=os.path.abspath,
help='Swift source file')
parser.add_argument('-l', '--max-file-length', type=int, default=0,
help='maximum file length (in lines)')
parser.add_argument('--max-class-length', type=int, default=0,
help='maximum class length (in lines)')
parser.add_argument('--max-closure-length', type=int, default=0,
help='maximum closure length (in lines)')
parser.add_argument('--max-file-length', type=int, default=0,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should probably move out arg parsing/config parsing to a different class. Maybe do it when porting to java?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, should we use Commons CLI?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah it looks ok.

help='maximum file length (in lines)')
parser.add_argument('--max-function-length', type=int, default=0,
help='maximum function length (in lines)')
parser.add_argument('-l', '--max-line-length', type=int, default=0,
help='maximum line length (in characters)')
parser.add_argument('--max-name-length', type=int, default=0,
help='maximum identifier name length (in characters)')
parser.add_argument('--max-struct-length', type=int, default=0,
help='maximum struct length (in lines)')
return parser.parse_args()
Expand All @@ -38,7 +42,10 @@ def main():
args = parse_args()
max_lengths = MaxLengths(args.max_class_length,
args.max_closure_length,
args.max_file_length,
args.max_function_length,
args.max_line_length,
args.max_name_length,
args.max_struct_length)

printer = Printer(filepath=args.infile)
Expand All @@ -50,8 +57,8 @@ def main():
walker = ParseTreeWalker()
walker.walk(listener, tree)

file_listener = FileListener(printer, args.infile)
file_listener.verify(args.max_file_length)
file_listener = FileListener(printer, args.infile, max_lengths)
file_listener.verify()

if __name__ == '__main__':
main()
57 changes: 53 additions & 4 deletions tailor/tests/utils/sourcefile_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,21 @@
import unittest
from unittest.mock import Mock, mock_open, patch

from tailor.types.location import Location
from tailor.utils import sourcefile


class SourceFileTestCase(unittest.TestCase):
class SourceFileLengthTestCase(unittest.TestCase):

def setUp(self):
self.patcher = patch.object(
builtins, 'open', mock_open(read_data='\n'*100))
builtins, 'open', mock_open(read_data='\n' * 100))
self.patcher.start()
self.addCleanup(self.patcher.stop)

@patch.object(builtins, 'open', mock_open(read_data=''))
def num_lines_in_file_test_empty_file(self):
with patch.object(builtins, 'open', mock_open(read_data='')):
self.assertEqual(0, sourcefile.num_lines_in_file('0Lines'))
self.assertEqual(0, sourcefile.num_lines_in_file('0Lines'))

def num_lines_in_file_test_normal_file(self):
self.assertEqual(100, sourcefile.num_lines_in_file('100Lines'))
Expand All @@ -35,6 +36,9 @@ def file_too_long_test_file_equal_to_limit(self):
def file_too_long_test_file_under_limit(self):
self.assertFalse(sourcefile.file_too_long('100Lines', max_length=101))


class SourceFileConstructTestCase(unittest.TestCase):

def construct_too_long_test_max_length_zero_or_less(self):
ctx = Mock()
ctx.start.line = 1
Expand All @@ -60,5 +64,50 @@ def construct_too_long_test_construct_over_limit(self):
ctx.stop.line = 10
self.assertTrue(sourcefile.construct_too_long(ctx, 5))


class SourceFileLineLengthTestCase(unittest.TestCase):

def setUp(self):
mopen = mock_open(read_data=''.join(['a' * 100 + '\n'] * 5))
# __iter__ and __next__ must be provided for iteration over mock file
mopen.return_value.__iter__ = lambda self: self
mopen.return_value.__next__ = lambda self: self.readline()
self.patcher = patch.object(builtins, 'open', mopen)
self.patcher.start()
self.addCleanup(self.patcher.stop)

def lines_too_long_test_negative_max_length(self):
self.assertListEqual(
[], sourcefile.lines_too_long('100Characters', -10))

def lines_too_long_test_zero_max_length(self):
self.assertListEqual([], sourcefile.lines_too_long('100Characters', 0))

def lines_too_long_test_zero_lines_over_limit(self):
self.assertListEqual(
[Location(1, 100), Location(2, 100), Location(3, 100),
Location(4, 100), Location(5, 100)],
sourcefile.lines_too_long('100Characters', 50))


class SourceFileNameLengthTestCase(unittest.TestCase):

def name_too_long_test_max_length_zero_or_less(self):
ctx = Mock()
ctx.getText = '6Chars'
self.assertFalse(sourcefile.name_too_long(ctx, -10))
self.assertFalse(sourcefile.name_too_long(ctx, 0))

def name_too_long_test_max_length_less_or_equal_limit(self):
ctx = Mock()
ctx.getText.return_value = '6Chars'
self.assertFalse(sourcefile.name_too_long(ctx, 10))
self.assertFalse(sourcefile.name_too_long(ctx, 6))

def name_too_long_test_max_length_over_limit(self):
ctx = Mock()
ctx.getText.return_value = '6Chars'
self.assertTrue(sourcefile.name_too_long(ctx, 4))

if __name__ == '__main__':
unittest.main()
11 changes: 7 additions & 4 deletions tailor/types/maxlengths.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
from collections import namedtuple

MaxLengths = namedtuple('MaxLines', ['max_class_length',
'max_closure_length',
'max_function_length',
'max_struct_length'])
MaxLengths = namedtuple('MaxLengths', ['max_class_length',
'max_closure_length',
'max_file_length',
'max_function_length',
'max_line_length',
'max_name_length',
'max_struct_length'])
17 changes: 17 additions & 0 deletions tailor/utils/sourcefile.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
from tailor.types.location import Location


def num_lines_in_file(filepath):
with open(filepath) as file:
return len(file.readlines())
Expand All @@ -9,3 +12,17 @@ def file_too_long(filepath, max_length):

def construct_too_long(ctx, max_length):
return 0 < max_length < (ctx.stop.line - ctx.start.line)


def lines_too_long(filepath, max_length):
long_lines = []
if 0 < max_length:
with open(filepath) as file:
long_lines = [Location(lineno + 1, len(line.rstrip('\r\n')))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice! 🐍

for lineno, line in enumerate(file)
if max_length < len(line.rstrip('\r\n'))]
return long_lines


def name_too_long(ctx, max_length):
return 0 < max_length < len(ctx.getText())

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

so what happens if the max_length is negative? Are we assuming that a negative max length means users don't care about max length?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, I made the assumption that when a user sets the max_length value to zero or less, they would not expect any lint errors to be reported. I was originally thinking that we would prefer not to throw any errors, but once we formalize the command-line input we could conceivably present usage messages and quit if the input values are malformed in any way.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sounds good.