diff --git a/third_party/blink/renderer/bindings/.style.yapf b/third_party/blink/renderer/.style.yapf similarity index 100% rename from third_party/blink/renderer/bindings/.style.yapf rename to third_party/blink/renderer/.style.yapf diff --git a/third_party/blink/renderer/build/scripts/.style.yapf b/third_party/blink/renderer/build/scripts/.style.yapf deleted file mode 100644 index 557fa7bf84c087..00000000000000 --- a/third_party/blink/renderer/build/scripts/.style.yapf +++ /dev/null @@ -1,2 +0,0 @@ -[style] -based_on_style = pep8 diff --git a/third_party/blink/renderer/build/scripts/blinkbuild/PRESUBMIT.py b/third_party/blink/renderer/build/scripts/blinkbuild/PRESUBMIT.py index 393539ef97e2ec..e0735b1d31d983 100644 --- a/third_party/blink/renderer/build/scripts/blinkbuild/PRESUBMIT.py +++ b/third_party/blink/renderer/build/scripts/blinkbuild/PRESUBMIT.py @@ -13,8 +13,8 @@ def _RunBindingsTests(input_api, output_api): print('Running ' + cmd_name) else: cmd.append('--suppress-diff') - test_cmd = input_api.Command(name=cmd_name, cmd=cmd, - kwargs={}, message=output_api.PresubmitError) + test_cmd = input_api.Command( + name=cmd_name, cmd=cmd, kwargs={}, message=output_api.PresubmitError) return input_api.RunTests([test_cmd]) diff --git a/third_party/blink/renderer/build/scripts/blinkbuild/name_style_converter.py b/third_party/blink/renderer/build/scripts/blinkbuild/name_style_converter.py index 194090449aaa5f..dd1978df233c1b 100644 --- a/third_party/blink/renderer/build/scripts/blinkbuild/name_style_converter.py +++ b/third_party/blink/renderer/build/scripts/blinkbuild/name_style_converter.py @@ -66,7 +66,9 @@ 'XR', ] -_SPECIAL_TOKENS_WITH_NUMBERS = [token for token in SPECIAL_TOKENS if re.search(r'[0-9]', token)] +_SPECIAL_TOKENS_WITH_NUMBERS = [ + token for token in SPECIAL_TOKENS if re.search(r'[0-9]', token) +] # Applying _TOKEN_PATTERNS repeatedly should capture any sequence of a-z, A-Z, # 0-9. @@ -80,7 +82,8 @@ '[0-9]+', ] -_TOKEN_RE = re.compile(r'(' + '|'.join(SPECIAL_TOKENS + _TOKEN_PATTERNS) + r')') +_TOKEN_RE = re.compile(r'(' + '|'.join(SPECIAL_TOKENS + _TOKEN_PATTERNS) + + r')') def tokenize_name(name): @@ -103,7 +106,8 @@ def tokenize_name(name): # In case |name| is written in lowerCamelCase, we try to match special # tokens that contains numbers ignoring cases only at the first step. tokens = [] - match = re.search(r'^(' + '|'.join(_SPECIAL_TOKENS_WITH_NUMBERS) + r')', name, re.IGNORECASE) + match = re.search(r'^(' + '|'.join(_SPECIAL_TOKENS_WITH_NUMBERS) + r')', + name, re.IGNORECASE) if match: tokens.append(match.group(0)) name = name[match.end(0):] @@ -176,7 +180,8 @@ def to_lower_camel_case(self): """ if not self.tokens: return '' - return self.tokens[0].lower() + ''.join([token[0].upper() + token[1:] for token in self.tokens[1:]]) + return self.tokens[0].lower() + ''.join( + [token[0].upper() + token[1:] for token in self.tokens[1:]]) def to_macro_case(self): """Macro case is the macro name style per Google C++ Style Guide: diff --git a/third_party/blink/renderer/build/scripts/blinkbuild/name_style_converter_test.py b/third_party/blink/renderer/build/scripts/blinkbuild/name_style_converter_test.py index 4b5e717046263a..5102efa57e19da 100644 --- a/third_party/blink/renderer/build/scripts/blinkbuild/name_style_converter_test.py +++ b/third_party/blink/renderer/build/scripts/blinkbuild/name_style_converter_test.py @@ -3,7 +3,6 @@ # found in the LICENSE file. # pylint: disable=import-error,print-statement,relative-import,protected-access - """Unit tests for name_style_converter.py.""" import unittest @@ -29,118 +28,178 @@ def test_simple_cases(self): self.assertEqual(tokenize_name('foo2'), ['foo', '2']) def test_tricky_cases(self): - self.assertEqual(tokenize_name('XMLHttpRequest'), ['XML', 'Http', 'Request']) + self.assertEqual( + tokenize_name('XMLHttpRequest'), ['XML', 'Http', 'Request']) self.assertEqual(tokenize_name('HTMLElement'), ['HTML', 'Element']) - self.assertEqual(tokenize_name('WebGLRenderingContext'), - ['WebGL', 'Rendering', 'Context']) + self.assertEqual( + tokenize_name('WebGLRenderingContext'), + ['WebGL', 'Rendering', 'Context']) - self.assertEqual(tokenize_name('CanvasRenderingContext2D'), - ['Canvas', 'Rendering', 'Context', '2D']) - self.assertEqual(tokenize_name('CanvasRenderingContext2DAPITest'), - ['Canvas', 'Rendering', 'Context', '2D', 'API', 'Test']) + self.assertEqual( + tokenize_name('CanvasRenderingContext2D'), + ['Canvas', 'Rendering', 'Context', '2D']) + self.assertEqual( + tokenize_name('CanvasRenderingContext2DAPITest'), + ['Canvas', 'Rendering', 'Context', '2D', 'API', 'Test']) - self.assertEqual(tokenize_name('SVGSVGElement'), ['SVG', 'SVG', 'Element']) + self.assertEqual( + tokenize_name('SVGSVGElement'), ['SVG', 'SVG', 'Element']) - self.assertEqual(tokenize_name('CanvasRenderingContext2D'), - ['Canvas', 'Rendering', 'Context', '2D']) + self.assertEqual( + tokenize_name('CanvasRenderingContext2D'), + ['Canvas', 'Rendering', 'Context', '2D']) - self.assertEqual(tokenize_name('CSSURLImageValue'), ['CSS', 'URL', 'Image', 'Value']) - self.assertEqual(tokenize_name('CSSPropertyAPID'), ['CSS', 'Property', 'API', 'D']) - self.assertEqual(tokenize_name('AXARIAGridCell'), ['AX', 'ARIA', 'Grid', 'Cell']) + self.assertEqual( + tokenize_name('CSSURLImageValue'), + ['CSS', 'URL', 'Image', 'Value']) + self.assertEqual( + tokenize_name('CSSPropertyAPID'), ['CSS', 'Property', 'API', 'D']) + self.assertEqual( + tokenize_name('AXARIAGridCell'), ['AX', 'ARIA', 'Grid', 'Cell']) self.assertEqual(tokenize_name('CDATASection'), ['CDATA', 'Section']) self.assertEqual(tokenize_name('ASCIICType'), ['ASCII', 'CType']) - self.assertEqual(tokenize_name('HTMLDListElement'), ['HTML', 'DList', 'Element']) - self.assertEqual(tokenize_name('HTMLOListElement'), ['HTML', 'OList', 'Element']) - self.assertEqual(tokenize_name('HTMLIFrameElement'), ['HTML', 'IFrame', 'Element']) - self.assertEqual(tokenize_name('HTMLPlugInElement'), ['HTML', 'PlugIn', 'Element']) + self.assertEqual( + tokenize_name('HTMLDListElement'), ['HTML', 'DList', 'Element']) + self.assertEqual( + tokenize_name('HTMLOListElement'), ['HTML', 'OList', 'Element']) + self.assertEqual( + tokenize_name('HTMLIFrameElement'), ['HTML', 'IFrame', 'Element']) + self.assertEqual( + tokenize_name('HTMLPlugInElement'), ['HTML', 'PlugIn', 'Element']) # No special handling for OptGroup, FieldSet, and TextArea. - self.assertEqual(tokenize_name('HTMLOptGroupElement'), ['HTML', 'Opt', 'Group', 'Element']) - self.assertEqual(tokenize_name('HTMLFieldSetElement'), ['HTML', 'Field', 'Set', 'Element']) - self.assertEqual(tokenize_name('HTMLTextAreaElement'), ['HTML', 'Text', 'Area', 'Element']) + self.assertEqual( + tokenize_name('HTMLOptGroupElement'), + ['HTML', 'Opt', 'Group', 'Element']) + self.assertEqual( + tokenize_name('HTMLFieldSetElement'), + ['HTML', 'Field', 'Set', 'Element']) + self.assertEqual( + tokenize_name('HTMLTextAreaElement'), + ['HTML', 'Text', 'Area', 'Element']) self.assertEqual(tokenize_name('Path2D'), ['Path', '2D']) self.assertEqual(tokenize_name('Point2D'), ['Point', '2D']) - self.assertEqual(tokenize_name('CanvasRenderingContext2DState'), - ['Canvas', 'Rendering', 'Context', '2D', 'State']) - self.assertEqual(tokenize_name('Accelerated2dCanvas'), ['Accelerated', '2d', 'Canvas']) - - self.assertEqual(tokenize_name('RTCDTMFSender'), ['RTC', 'DTMF', 'Sender']) - - self.assertEqual(tokenize_name('WebGLCompressedTextureS3TCsRGB'), - ['WebGL', 'Compressed', 'Texture', 'S3TC', 'sRGB']) - self.assertEqual(tokenize_name('WebGL2CompressedTextureETC1'), - ['WebGL2', 'Compressed', 'Texture', 'ETC1']) + self.assertEqual( + tokenize_name('CanvasRenderingContext2DState'), + ['Canvas', 'Rendering', 'Context', '2D', 'State']) + self.assertEqual( + tokenize_name('Accelerated2dCanvas'), + ['Accelerated', '2d', 'Canvas']) + + self.assertEqual( + tokenize_name('RTCDTMFSender'), ['RTC', 'DTMF', 'Sender']) + + self.assertEqual( + tokenize_name('WebGLCompressedTextureS3TCsRGB'), + ['WebGL', 'Compressed', 'Texture', 'S3TC', 'sRGB']) + self.assertEqual( + tokenize_name('WebGL2CompressedTextureETC1'), + ['WebGL2', 'Compressed', 'Texture', 'ETC1']) self.assertEqual(tokenize_name('EXTsRGB'), ['EXT', 'sRGB']) # 'PVRTC' contains a special token 'RTC', but it should be a # single token. - self.assertEqual(tokenize_name('WebGLCompressedTexturePVRTC'), - ['WebGL', 'Compressed', 'Texture', 'PVRTC']) - - self.assertEqual(tokenize_name('SVGFEBlendElement'), ['SVG', 'FE', 'Blend', 'Element']) - self.assertEqual(tokenize_name('SVGMPathElement'), ['SVG', 'MPath', 'Element']) - self.assertEqual(tokenize_name('SVGTSpanElement'), ['SVG', 'TSpan', 'Element']) - self.assertEqual(tokenize_name('SVGURIReference'), ['SVG', 'URI', 'Reference']) - - self.assertEqual(tokenize_name('UTF16TextIterator'), ['UTF16', 'Text', 'Iterator']) + self.assertEqual( + tokenize_name('WebGLCompressedTexturePVRTC'), + ['WebGL', 'Compressed', 'Texture', 'PVRTC']) + + self.assertEqual( + tokenize_name('SVGFEBlendElement'), + ['SVG', 'FE', 'Blend', 'Element']) + self.assertEqual( + tokenize_name('SVGMPathElement'), ['SVG', 'MPath', 'Element']) + self.assertEqual( + tokenize_name('SVGTSpanElement'), ['SVG', 'TSpan', 'Element']) + self.assertEqual( + tokenize_name('SVGURIReference'), ['SVG', 'URI', 'Reference']) + + self.assertEqual( + tokenize_name('UTF16TextIterator'), ['UTF16', 'Text', 'Iterator']) self.assertEqual(tokenize_name('UTF8Decoder'), ['UTF8', 'Decoder']) self.assertEqual(tokenize_name('Uint8Array'), ['Uint8', 'Array']) - self.assertEqual(tokenize_name('DOMWindowBase64'), ['DOM', 'Window', 'Base64']) - self.assertEqual(tokenize_name('TextCodecLatin1'), ['Text', 'Codec', 'Latin1']) - self.assertEqual(tokenize_name('V8BindingForCore'), ['V8', 'Binding', 'For', 'Core']) + self.assertEqual( + tokenize_name('DOMWindowBase64'), ['DOM', 'Window', 'Base64']) + self.assertEqual( + tokenize_name('TextCodecLatin1'), ['Text', 'Codec', 'Latin1']) + self.assertEqual( + tokenize_name('V8BindingForCore'), + ['V8', 'Binding', 'For', 'Core']) self.assertEqual(tokenize_name('V8DOMRect'), ['V8', 'DOM', 'Rect']) - self.assertEqual(tokenize_name('String16MojomTraits'), ['String16', 'Mojom', 'Traits']) - - self.assertEqual(tokenize_name('V0InsertionPoint'), ['V0', 'Insertion', 'Point']) - self.assertEqual(tokenize_name('ShadowDOMV0Test'), ['Shadow', 'DOM', 'V0', 'Test']) - self.assertEqual(tokenize_name('ElementShadowV0'), ['Element', 'Shadow', 'V0']) - self.assertEqual(tokenize_name('StubChromeClientForSPv2'), - ['Stub', 'Chrome', 'Client', 'For', 'SPv2']) - - self.assertEqual(tokenize_name('SQLiteAuthorizer'), ['SQLite', 'Authorizer']) - self.assertEqual(tokenize_name('XPathEvaluator'), ['XPath', 'Evaluator']) - - self.assertEqual(tokenize_name('IsXHTMLDocument'), ['Is', 'XHTML', 'Document']) - self.assertEqual(tokenize_name('isHTMLDocument'), ['is', 'HTML', 'Document']) + self.assertEqual( + tokenize_name('String16MojomTraits'), + ['String16', 'Mojom', 'Traits']) + + self.assertEqual( + tokenize_name('V0InsertionPoint'), ['V0', 'Insertion', 'Point']) + self.assertEqual( + tokenize_name('ShadowDOMV0Test'), ['Shadow', 'DOM', 'V0', 'Test']) + self.assertEqual( + tokenize_name('ElementShadowV0'), ['Element', 'Shadow', 'V0']) + self.assertEqual( + tokenize_name('StubChromeClientForSPv2'), + ['Stub', 'Chrome', 'Client', 'For', 'SPv2']) + + self.assertEqual( + tokenize_name('SQLiteAuthorizer'), ['SQLite', 'Authorizer']) + self.assertEqual( + tokenize_name('XPathEvaluator'), ['XPath', 'Evaluator']) + + self.assertEqual( + tokenize_name('IsXHTMLDocument'), ['Is', 'XHTML', 'Document']) + self.assertEqual( + tokenize_name('isHTMLDocument'), ['is', 'HTML', 'Document']) self.assertEqual(tokenize_name('matrix3d'), ['matrix', '3d']) - self.assertEqual(tokenize_name('uint8ArrayMember'), ['uint8', 'Array', 'Member']) + self.assertEqual( + tokenize_name('uint8ArrayMember'), ['uint8', 'Array', 'Member']) self.assertEqual(tokenize_name('webgl2Element'), ['webgl2', 'Element']) self.assertEqual(tokenize_name('webGL2Element'), ['webGL2', 'Element']) self.assertEqual(tokenize_name('xssError'), ['xss', 'Error']) self.assertEqual(tokenize_name('FileURLs'), ['File', 'URLs']) - self.assertEqual(tokenize_name('XRDOMOverlay'), ['XR', 'DOM', 'Overlay']) + self.assertEqual( + tokenize_name('XRDOMOverlay'), ['XR', 'DOM', 'Overlay']) def test_ignoring_characters(self): self.assertEqual(tokenize_name('Animation.idl'), ['Animation', 'idl']) - self.assertEqual(tokenize_name('-webkit-appearance'), ['webkit', 'appearance']) + self.assertEqual( + tokenize_name('-webkit-appearance'), ['webkit', 'appearance']) self.assertEqual(tokenize_name(' foo_bar!#"$'), ['foo', 'bar']) class NameStyleConverterTest(unittest.TestCase): def test_original(self): - self.assertEqual(NameStyleConverter('-webkit-appearance').original, '-webkit-appearance') + self.assertEqual( + NameStyleConverter('-webkit-appearance').original, + '-webkit-appearance') def test_snake_case(self): converter = NameStyleConverter('HTMLElement') self.assertEqual(converter.to_snake_case(), 'html_element') - self.assertEqual(NameStyleConverter('FileURLs').to_snake_case(), 'file_urls') + self.assertEqual( + NameStyleConverter('FileURLs').to_snake_case(), 'file_urls') def test_to_class_data_member(self): converter = NameStyleConverter('HTMLElement') self.assertEqual(converter.to_class_data_member(), 'html_element_') - self.assertEqual(converter.to_class_data_member(prefix='is'), 'is_html_element_') - self.assertEqual(converter.to_class_data_member(suffix='enabled'), 'html_element_enabled_') - self.assertEqual(converter.to_class_data_member(prefix='is', suffix='enabled'), 'is_html_element_enabled_') - self.assertEqual(converter.to_class_data_member(prefix='fooBar', suffix='V0V8'), 'foobar_html_element_v0v8_') + self.assertEqual( + converter.to_class_data_member(prefix='is'), 'is_html_element_') + self.assertEqual( + converter.to_class_data_member(suffix='enabled'), + 'html_element_enabled_') + self.assertEqual( + converter.to_class_data_member(prefix='is', suffix='enabled'), + 'is_html_element_enabled_') + self.assertEqual( + converter.to_class_data_member(prefix='fooBar', suffix='V0V8'), + 'foobar_html_element_v0v8_') def test_upper_camel_case(self): converter = NameStyleConverter('someSuperThing') @@ -148,7 +207,8 @@ def test_upper_camel_case(self): converter = NameStyleConverter('SVGElement') self.assertEqual(converter.to_upper_camel_case(), 'SVGElement') converter = NameStyleConverter('cssExternalScannerPreload') - self.assertEqual(converter.to_upper_camel_case(), 'CSSExternalScannerPreload') + self.assertEqual(converter.to_upper_camel_case(), + 'CSSExternalScannerPreload') converter = NameStyleConverter('xpathExpression') self.assertEqual(converter.to_upper_camel_case(), 'XPathExpression') converter = NameStyleConverter('feDropShadow') @@ -156,9 +216,14 @@ def test_upper_camel_case(self): def test_to_class_name(self): self.assertEqual(NameStyleConverter('').to_class_name(), '') - self.assertEqual(NameStyleConverter('').to_class_name(prefix='s', suffix='d'), 'SD') - self.assertEqual(NameStyleConverter('').to_class_name(prefix='style', suffix='data'), 'StyleData') - self.assertEqual(NameStyleConverter('foo').to_class_name(prefix='style', suffix='data'), 'StyleFooData') + self.assertEqual( + NameStyleConverter('').to_class_name(prefix='s', suffix='d'), 'SD') + self.assertEqual( + NameStyleConverter('').to_class_name( + prefix='style', suffix='data'), 'StyleData') + self.assertEqual( + NameStyleConverter('foo').to_class_name( + prefix='style', suffix='data'), 'StyleFooData') self.assertEqual(NameStyleConverter('xpath').to_class_name(), 'XPath') def test_to_function_name(self): @@ -166,11 +231,17 @@ def test_to_function_name(self): self.assertEqual(converter.to_function_name(), 'FooBar') self.assertEqual(converter.to_function_name(prefix='is'), 'IsFooBar') self.assertEqual(converter.to_function_name(suffix='BAZ'), 'FooBarBaz') - self.assertEqual(converter.to_function_name(prefix='IS', suffix='baz'), 'IsFooBarBaz') - self.assertEqual(converter.to_function_name(prefix='prefixPrefix', suffix=['a', 'b']), 'PrefixprefixFooBarAB') + self.assertEqual( + converter.to_function_name(prefix='IS', suffix='baz'), + 'IsFooBarBaz') + self.assertEqual( + converter.to_function_name( + prefix='prefixPrefix', suffix=['a', 'b']), + 'PrefixprefixFooBarAB') def test_to_enum_value(self): - self.assertEqual(NameStyleConverter('fooBar').to_enum_value(), 'kFooBar') + self.assertEqual( + NameStyleConverter('fooBar').to_enum_value(), 'kFooBar') def test_lower_camel_case(self): converter = NameStyleConverter('someSuperThing') @@ -182,7 +253,8 @@ def test_lower_camel_case(self): converter = NameStyleConverter('-webkit-margin-start') self.assertEqual(converter.to_lower_camel_case(), 'webkitMarginStart') converter = NameStyleConverter('Accelerated2dCanvas') - self.assertEqual(converter.to_lower_camel_case(), 'accelerated2dCanvas') + self.assertEqual(converter.to_lower_camel_case(), + 'accelerated2dCanvas') def test_macro_case(self): converter = NameStyleConverter('WebGLBaz2D') @@ -190,15 +262,19 @@ def test_macro_case(self): def test_all_cases(self): converter = NameStyleConverter('SVGScriptElement') - self.assertEqual(converter.to_all_cases(), { - 'snake_case': 'svg_script_element', - 'upper_camel_case': 'SVGScriptElement', - 'macro_case': 'SVG_SCRIPT_ELEMENT', - }) + self.assertEqual( + converter.to_all_cases(), { + 'snake_case': 'svg_script_element', + 'upper_camel_case': 'SVGScriptElement', + 'macro_case': 'SVG_SCRIPT_ELEMENT', + }) def test_to_header_guard(self): - converter = NameStyleConverter('third_party/blink/renderer/bindings/modules/v8/v8_path_2d.h') - self.assertEqual(converter.to_header_guard(), 'THIRD_PARTY_BLINK_RENDERER_BINDINGS_MODULES_V8_V8_PATH_2D_H_') + converter = NameStyleConverter( + 'third_party/blink/renderer/bindings/modules/v8/v8_path_2d.h') + self.assertEqual( + converter.to_header_guard(), + 'THIRD_PARTY_BLINK_RENDERER_BINDINGS_MODULES_V8_V8_PATH_2D_H_') def test_equality(self): a_1 = NameStyleConverter('a') diff --git a/third_party/blink/renderer/build/scripts/core/css/css_properties.py b/third_party/blink/renderer/build/scripts/core/css/css_properties.py index 9a4bcaf08fcd44..1c3cfe3579a1bc 100755 --- a/third_party/blink/renderer/build/scripts/core/css/css_properties.py +++ b/third_party/blink/renderer/build/scripts/core/css/css_properties.py @@ -10,16 +10,10 @@ from name_utilities import enum_key_for_css_property, id_for_css_property from name_utilities import enum_key_for_css_property_alias, id_for_css_property_alias - # These values are converted using CSSPrimitiveValue in the setter function, # if applicable. PRIMITIVE_TYPES = [ - 'short', - 'unsigned short', - 'int', - 'unsigned int', - 'unsigned', - 'float', + 'short', 'unsigned short', 'int', 'unsigned int', 'unsigned', 'float', 'LineClampValue' ] @@ -104,7 +98,8 @@ def __init__(self, file_paths): for feature in origin_trials_writer.origin_trial_features: origin_trial_features[str(feature['name'])] = True - self.add_properties(css_properties_file.name_dictionaries, origin_trial_features) + self.add_properties(css_properties_file.name_dictionaries, + origin_trial_features) assert self._first_enum_value + len(self._properties_by_id) < \ self._alias_offset, \ @@ -117,8 +112,7 @@ def __init__(self, file_paths): self._extra_fields = [] for i in range(3, len(file_paths)): fields = json5_generator.Json5File.load_from_files( - [file_paths[i]], - default_parameters=self._default_parameters) + [file_paths[i]], default_parameters=self._default_parameters) self._extra_fields.extend(fields.name_dictionaries) for field in self._extra_fields: self.expand_parameters(field) @@ -134,12 +128,15 @@ def add_properties(self, properties, origin_trial_features): self.expand_surrogate(property_) self._aliases = [ - property_ for property_ in properties if property_['alias_for']] + property_ for property_ in properties if property_['alias_for'] + ] self._shorthands = [ - property_ for property_ in properties if property_['longhands']] + property_ for property_ in properties if property_['longhands'] + ] self._longhands = [ - property_ for property_ in properties if ( - not property_['alias_for'] and not property_['longhands'])] + property_ for property_ in properties + if (not property_['alias_for'] and not property_['longhands']) + ] # Sort the properties by priority, then alphabetically. Ensure that # the resulting order is deterministic. @@ -215,14 +212,15 @@ def expand_aliases(self): "Property '{}' is an alias with a runtime_flag, "\ "but runtime flags do not currently work for aliases.".format( alias['name']) - aliased_property = self._properties_by_id[ - id_for_css_property(alias['alias_for'])] + aliased_property = self._properties_by_id[id_for_css_property( + alias['alias_for'])] aliased_property.setdefault('aliases', []) aliased_property['aliases'].append(alias['name'].original) updated_alias = aliased_property.copy() updated_alias['name'] = alias['name'] updated_alias['alias_for'] = alias['alias_for'] - updated_alias['aliased_property'] = aliased_property['name'].to_upper_camel_case() + updated_alias['aliased_property'] = aliased_property[ + 'name'].to_upper_camel_case() updated_alias['property_id'] = id_for_css_property_alias( alias['name']) updated_alias['enum_key'] = enum_key_for_css_property_alias( @@ -256,24 +254,26 @@ def set_if_none(property_, key, value): set_if_none(property_, 'name_for_methods', method_name) set_if_none(property_, 'type_name', 'E' + method_name) set_if_none( - property_, - 'getter', - method_name if simple_type_name != method_name else 'Get' + method_name) + property_, 'getter', method_name + if simple_type_name != method_name else 'Get' + method_name) set_if_none(property_, 'setter', 'Set' + method_name) if property_['inherited']: - property_['is_inherited_setter'] = 'Set' + method_name + 'IsInherited' - property_['is_animation_property'] = property_['priority'] == 'Animation' + property_['is_inherited_setter'] = ( + 'Set' + method_name + 'IsInherited') + property_['is_animation_property'] = ( + property_['priority'] == 'Animation') # Figure out whether this property should have style builders at all. # E.g. shorthands do not get style builders. - property_['style_builder_declare'] = (property_['is_property'] and - not property_['longhands']) + property_['style_builder_declare'] = (property_['is_property'] + and not property_['longhands']) # Figure out whether we should generate style builder implementations. for x in ['initial', 'inherit', 'value']: suppressed = x in property_['style_builder_custom_functions'] declared = property_['style_builder_declare'] - property_['style_builder_generate_%s' % x] = declared and not suppressed + property_['style_builder_generate_%s' % x] = (declared + and not suppressed) # Expand StyleBuilderConverter params where necessary. if property_['type_name'] in PRIMITIVE_TYPES: @@ -281,7 +281,8 @@ def set_if_none(property_, key, value): else: set_if_none(property_, 'converter', 'CSSIdentifierValue') - assert not property_['alias_for'], 'Use expand_aliases to expand aliases' + assert not property_['alias_for'], \ + 'Use expand_aliases to expand aliases' if not property_['longhands']: property_['superclass'] = 'Longhand' property_['namespace_group'] = 'Longhand' @@ -294,13 +295,13 @@ def set_if_none(property_, key, value): self._field_alias_expander.expand_field_alias(property_) type_name = property_['type_name'] - if (property_['field_template'] == 'keyword' or - property_['field_template'] == 'multi_keyword'): + if (property_['field_template'] == 'keyword' + or property_['field_template'] == 'multi_keyword'): default_value = (type_name + '::' + NameStyleConverter( property_['default_value']).to_enum_value()) - elif (property_['field_template'] == 'external' or - property_['field_template'] == 'primitive' or - property_['field_template'] == 'pointer'): + elif (property_['field_template'] == 'external' + or property_['field_template'] == 'primitive' + or property_['field_template'] == 'pointer'): default_value = property_['default_value'] else: assert property_['field_template'] == 'monotonic_flag', \ @@ -329,7 +330,8 @@ def set_if_none(property_, key, value): assert 'resolver' in options, 'resolver option is required' assert 'physical_group' in options, 'physical_group option is required' options['resolver_name'] = NameStyleConverter(options['resolver']) - options['physical_group_name'] = NameStyleConverter(options['physical_group']) + options['physical_group_name'] = NameStyleConverter( + options['physical_group']) @property def default_parameters(self): @@ -353,7 +355,9 @@ def longhands(self): @property def longhands_including_aliases(self): - return self._longhands + [x for x in self._aliases if not x['longhands']] + return self._longhands + [ + x for x in self._aliases if not x['longhands'] + ] @property def properties_by_id(self): diff --git a/third_party/blink/renderer/build/scripts/core/css/field_alias_expander.py b/third_party/blink/renderer/build/scripts/core/css/field_alias_expander.py index d4b4cf8f3a61f6..d714d5b3f5e88c 100644 --- a/third_party/blink/renderer/build/scripts/core/css/field_alias_expander.py +++ b/third_party/blink/renderer/build/scripts/core/css/field_alias_expander.py @@ -13,10 +13,12 @@ class FieldAliasExpander(object): should point to core/css/computed_style_field_aliases.json5) and uses that to inform which fields in a given property should be set. """ + def __init__(self, file_path): loaded_file = json5_generator.Json5File.load_from_files([file_path]) - self._field_aliases = dict([(alias["name"], alias) - for alias in loaded_file.name_dictionaries]) + self._field_aliases = dict([ + (alias["name"], alias) for alias in loaded_file.name_dictionaries + ]) def expand_field_alias(self, property_): """ diff --git a/third_party/blink/renderer/build/scripts/core/css/make_css_primitive_value_unit_trie.py b/third_party/blink/renderer/build/scripts/core/css/make_css_primitive_value_unit_trie.py index 318d1136300fce..16edce10957857 100755 --- a/third_party/blink/renderer/build/scripts/core/css/make_css_primitive_value_unit_trie.py +++ b/third_party/blink/renderer/build/scripts/core/css/make_css_primitive_value_unit_trie.py @@ -12,13 +12,17 @@ class UnitTrieWriter(json5_generator.Writer): def __init__(self, json5_file_paths, output_dir): super(UnitTrieWriter, self).__init__(json5_file_paths, output_dir) - self._units = {entry['name'].original: entry['unit_type'] for entry in self.json5_file.name_dictionaries} + self._units = { + entry['name'].original: entry['unit_type'] + for entry in self.json5_file.name_dictionaries + } self._outputs = { 'css_primitive_value_unit_trie.cc': self.generate_implementation } - @template_expander.use_jinja('core/css/templates/css_primitive_value_unit_trie.cc.tmpl') + @template_expander.use_jinja( + 'core/css/templates/css_primitive_value_unit_trie.cc.tmpl') def generate_implementation(self): return { 'input_files': self._input_files, diff --git a/third_party/blink/renderer/build/scripts/core/css/make_css_property_names.py b/third_party/blink/renderer/build/scripts/core/css/make_css_property_names.py index 016215cb90404e..e20639af8cb036 100755 --- a/third_party/blink/renderer/build/scripts/core/css/make_css_property_names.py +++ b/third_party/blink/renderer/build/scripts/core/css/make_css_property_names.py @@ -11,7 +11,8 @@ class CSSPropertyNamesWriter(json5_generator.Writer): file_basename = "css_property_names" def __init__(self, json5_file_path, output_dir): - super(CSSPropertyNamesWriter, self).__init__(json5_file_path, output_dir) + super(CSSPropertyNamesWriter, self).__init__(json5_file_path, + output_dir) self._outputs = { (self.file_basename + ".h"): self.generate_header, (self.file_basename + ".cc"): self.generate_implementation, @@ -24,32 +25,40 @@ def _enum_declaration(self, property_): def _array_item(self, property_): return " CSSPropertyID::%(enum_key)s," % property_ - @template_expander.use_jinja('core/css/templates/css_property_names.h.tmpl') + @template_expander.use_jinja( + 'core/css/templates/css_property_names.h.tmpl') def generate_header(self): return { - 'alias_offset': self._css_properties.alias_offset, - 'class_name': self.class_name, - 'property_enums': "\n".join(map( - self._enum_declaration, - self._css_properties.properties_including_aliases)), - 'property_aliases': "\n".join( - map(self._array_item, self._css_properties.aliases)), - 'first_property_id': self._css_properties.first_property_id, + 'alias_offset': + self._css_properties.alias_offset, + 'class_name': + self.class_name, + 'property_enums': + "\n".join( + map(self._enum_declaration, + self._css_properties.properties_including_aliases)), + 'property_aliases': + "\n".join(map(self._array_item, self._css_properties.aliases)), + 'first_property_id': + self._css_properties.first_property_id, 'properties_count': - len(self._css_properties.properties_including_aliases), - 'last_property_id': self._css_properties.last_property_id, + len(self._css_properties.properties_including_aliases), + 'last_property_id': + self._css_properties.last_property_id, 'last_unresolved_property_id': - self._css_properties.last_unresolved_property_id, + self._css_properties.last_unresolved_property_id, 'max_name_length': - max(map(len, self._css_properties.properties_by_id)), + max(map(len, self._css_properties.properties_by_id)), } - @gperf.use_jinja_gperf_template('core/css/templates/css_property_names.cc.tmpl', - ['-Q', 'CSSPropStringPool']) + @gperf.use_jinja_gperf_template( + 'core/css/templates/css_property_names.cc.tmpl', + ['-Q', 'CSSPropStringPool']) def generate_implementation(self): enum_value_to_name = {} for property_ in self._css_properties.properties_including_aliases: - enum_value_to_name[property_['enum_value']] = property_['name'].original + enum_value_to_name[property_['enum_value']] = \ + property_['name'].original property_offsets = [] property_names = [] current_offset = 0 @@ -64,7 +73,8 @@ def generate_implementation(self): css_name_and_enum_pairs = [ (property_['name'].original, 'static_cast(CSSPropertyID::' + property_['enum_key'] + ')') - for property_ in self._css_properties.properties_including_aliases] + for property_ in self._css_properties.properties_including_aliases + ] property_keys = [ property_['enum_key'] @@ -72,15 +82,21 @@ def generate_implementation(self): ] return { - 'class_name': 'CSSPropertyNames', - 'file_basename': self.file_basename, - 'property_keys': property_keys, - 'property_names': property_names, - 'property_offsets': property_offsets, + 'class_name': + 'CSSPropertyNames', + 'file_basename': + self.file_basename, + 'property_keys': + property_keys, + 'property_names': + property_names, + 'property_offsets': + property_offsets, 'property_to_enum_map': - '\n'.join('%s, %s' % property_ - for property_ in css_name_and_enum_pairs), - 'gperf_path': self.gperf_path, + '\n'.join( + '%s, %s' % property_ for property_ in css_name_and_enum_pairs), + 'gperf_path': + self.gperf_path, } diff --git a/third_party/blink/renderer/build/scripts/core/css/make_css_tokenizer_codepoints.py b/third_party/blink/renderer/build/scripts/core/css/make_css_tokenizer_codepoints.py index a51c5917d33b3a..3c76325cdbbff8 100755 --- a/third_party/blink/renderer/build/scripts/core/css/make_css_tokenizer_codepoints.py +++ b/third_party/blink/renderer/build/scripts/core/css/make_css_tokenizer_codepoints.py @@ -27,31 +27,32 @@ def token_type(i): - codepoints = {'(': 'LeftParenthesis', - ')': 'RightParenthesis', - '[': 'LeftBracket', - ']': 'RightBracket', - '{': 'LeftBrace', - '}': 'RightBrace', - '+': 'PlusOrFullStop', - '.': 'PlusOrFullStop', - '-': 'HyphenMinus', - '*': 'Asterisk', - '<': 'LessThan', - ',': 'Comma', - '/': 'Solidus', - '\\': 'ReverseSolidus', - ':': 'Colon', - ';': 'SemiColon', - '#': 'Hash', - '^': 'CircumflexAccent', - '$': 'DollarSign', - '|': 'VerticalLine', - '~': 'Tilde', - '@': 'CommercialAt', - 'u': 'LetterU', - 'U': 'LetterU', - } + codepoints = { + '(': 'LeftParenthesis', + ')': 'RightParenthesis', + '[': 'LeftBracket', + ']': 'RightBracket', + '{': 'LeftBrace', + '}': 'RightBrace', + '+': 'PlusOrFullStop', + '.': 'PlusOrFullStop', + '-': 'HyphenMinus', + '*': 'Asterisk', + '<': 'LessThan', + ',': 'Comma', + '/': 'Solidus', + '\\': 'ReverseSolidus', + ':': 'Colon', + ';': 'SemiColon', + '#': 'Hash', + '^': 'CircumflexAccent', + '$': 'DollarSign', + '|': 'VerticalLine', + '~': 'Tilde', + '@': 'CommercialAt', + 'u': 'LetterU', + 'U': 'LetterU', + } c = chr(i) if c in codepoints: return codepoints[c] @@ -79,10 +80,15 @@ def __init__(self, in_file_path): def generate(self): array_size = 128 # SCHAR_MAX + 1 - token_lines = [' &CSSTokenizer::%s,' % token_type(i) - if token_type(i) else ' 0,' - for i in range(array_size)] - return CPP_TEMPLATE.format(array_size=array_size, token_lines='\n'.join(token_lines), module_pyname=module_pyname) + token_lines = [ + ' &CSSTokenizer::%s,' % token_type(i) + if token_type(i) else ' 0,' for i in range(array_size) + ] + return CPP_TEMPLATE.format( + array_size=array_size, + token_lines='\n'.join(token_lines), + module_pyname=module_pyname) + if __name__ == '__main__': in_generator.Maker(MakeCSSTokenizerCodePointsWriter).main(sys.argv) diff --git a/third_party/blink/renderer/build/scripts/core/css/make_css_value_id_mappings.py b/third_party/blink/renderer/build/scripts/core/css/make_css_value_id_mappings.py index 6b1b676f524115..996b82dc46f1dc 100755 --- a/third_party/blink/renderer/build/scripts/core/css/make_css_value_id_mappings.py +++ b/third_party/blink/renderer/build/scripts/core/css/make_css_value_id_mappings.py @@ -40,8 +40,8 @@ def _find_continuous_segment(numbers): for i in range(len(number_list_sorted) - 1): # continuous segment is a segment which the number in pair is 1 unit # more than the previous pair - if (number_list_sorted[i + 1][0] - number_list_sorted[i][0] != 1 - or number_list_sorted[i + 1][1] - number_list_sorted[i][1] != 1): + if (number_list_sorted[i + 1][0] - number_list_sorted[i][0] != 1 or + number_list_sorted[i + 1][1] - number_list_sorted[i][1] != 1): segments.append(i + 1) segments.append(len(number_list_sorted)) return segments, number_list_sorted @@ -62,7 +62,8 @@ def _find_largest_segment(segments): return max(segment_list, key=lambda x: x[1] - x[0]) -def _find_enum_longest_continuous_segment(property_, name_to_position_dictionary): +def _find_enum_longest_continuous_segment(property_, + name_to_position_dictionary): """Find the longest continuous segment in the list of keywords Finding the continuous segment will allows us to do the subtraction between keywords so that the distance between 2 keywords in this @@ -85,7 +86,9 @@ def _find_enum_longest_continuous_segment(property_, name_to_position_dictionary segment. Enums in the segment will be computed in default clause. """ property_enum_order = range(len(property_['keywords'])) - css_enum_order = [name_to_position_dictionary[x] for x in property_['keywords']] + css_enum_order = [ + name_to_position_dictionary[x] for x in property_['keywords'] + ] enum_pair_list = zip(css_enum_order, property_enum_order) enum_segment, enum_pair_list = _find_continuous_segment(enum_pair_list) longest_segment = _find_largest_segment(enum_segment) @@ -99,9 +102,11 @@ def _find_enum_longest_continuous_segment(property_, name_to_position_dictionary class CSSValueIDMappingsWriter(make_style_builder.StyleBuilderWriter): def __init__(self, json5_file_paths, output_dir): - super(CSSValueIDMappingsWriter, self).__init__(json5_file_paths, output_dir) + super(CSSValueIDMappingsWriter, self).__init__(json5_file_paths, + output_dir) self._outputs = { - 'css_value_id_mappings_generated.h': self.generate_css_value_mappings, + 'css_value_id_mappings_generated.h': + self.generate_css_value_mappings, } self.css_values_dictionary_file = json5_file_paths[3] css_properties = self.css_properties.longhands @@ -114,24 +119,28 @@ def __init__(self, json5_file_paths, output_dir): css_properties = keyword_utils.sort_keyword_properties_by_canonical_order( css_properties, json5_file_paths[3], self.default_parameters) - @template_expander.use_jinja('core/css/templates/css_value_id_mappings_generated.h.tmpl') + @template_expander.use_jinja( + 'core/css/templates/css_value_id_mappings_generated.h.tmpl') def generate_css_value_mappings(self): mappings = {} include_paths = set() css_values_dictionary = json5_generator.Json5File.load_from_files( [self.css_values_dictionary_file], - default_parameters=self.default_parameters - ).name_dictionaries - name_to_position_dictionary = dict(zip([x['name'].original for x in css_values_dictionary], - range(len(css_values_dictionary)))) + default_parameters=self.default_parameters).name_dictionaries + name_to_position_dictionary = dict( + zip([x['name'].original for x in css_values_dictionary], + range(len(css_values_dictionary)))) for property_ in self.css_properties.properties_including_aliases: include_paths.update(property_['include_paths']) if property_['field_template'] == 'multi_keyword': mappings[property_['type_name']] = { - 'default_value': property_['default_value'], - 'mapping': [enum_key_for_css_keyword(k) - for k in property_['keywords']], + 'default_value': + property_['default_value'], + 'mapping': [ + enum_key_for_css_keyword(k) + for k in property_['keywords'] + ], } elif property_['field_template'] == 'keyword': enum_pair_list, enum_segment, p_segment = _find_enum_longest_continuous_segment( @@ -151,5 +160,6 @@ def generate_css_value_mappings(self): 'mappings': mappings, } + if __name__ == '__main__': json5_generator.Maker(CSSValueIDMappingsWriter).main() diff --git a/third_party/blink/renderer/build/scripts/core/css/make_css_value_keywords.py b/third_party/blink/renderer/build/scripts/core/css/make_css_value_keywords.py index 077bb9a1762b0f..eabb6aeeaa5796 100755 --- a/third_party/blink/renderer/build/scripts/core/css/make_css_value_keywords.py +++ b/third_party/blink/renderer/build/scripts/core/css/make_css_value_keywords.py @@ -33,14 +33,21 @@ def __init__(self, file_paths, output_dir): 'value keywords should have the prefix "-internal-".' self._keyword_count = len(self._value_keywords) + first_keyword_id - @template_expander.use_jinja('core/css/templates/css_value_keywords.h.tmpl') + @template_expander.use_jinja( + 'core/css/templates/css_value_keywords.h.tmpl') def generate_header(self): return { - 'value_keywords': self._value_keywords, - 'value_keywords_count': self._keyword_count, + 'value_keywords': + self._value_keywords, + 'value_keywords_count': + self._keyword_count, 'max_value_keyword_length': - max(len(keyword['name'].original) for keyword in self._value_keywords), - 'header_guard': self.make_header_guard(self._relative_output_dir + self._FILE_BASENAME + '.h') + max( + len(keyword['name'].original) + for keyword in self._value_keywords), + 'header_guard': + self.make_header_guard(self._relative_output_dir + + self._FILE_BASENAME + '.h') } def _value_keywords_with_mode(self, mode): @@ -60,14 +67,18 @@ def generate_implementation(self): current_offset += len(keyword["name"].original) + 1 return { - 'value_keywords': self._value_keywords, - 'value_keyword_offsets': keyword_offsets, + 'value_keywords': + self._value_keywords, + 'value_keyword_offsets': + keyword_offsets, 'ua_sheet_mode_values_keywords': - self._value_keywords_with_mode('UASheet'), + self._value_keywords_with_mode('UASheet'), 'quirks_mode_or_ua_sheet_mode_values_keywords': - self._value_keywords_with_mode('QuirksOrUASheet'), - 'gperf_path': self.gperf_path, + self._value_keywords_with_mode('QuirksOrUASheet'), + 'gperf_path': + self.gperf_path, } + if __name__ == "__main__": json5_generator.Maker(CSSValueKeywordsWriter).main() diff --git a/third_party/blink/renderer/build/scripts/core/css/make_cssom_types.py b/third_party/blink/renderer/build/scripts/core/css/make_cssom_types.py index e16d7a3e8942bf..ef5c5f57bca6ee 100755 --- a/third_party/blink/renderer/build/scripts/core/css/make_cssom_types.py +++ b/third_party/blink/renderer/build/scripts/core/css/make_cssom_types.py @@ -15,6 +15,7 @@ class CSSOMTypesWriter(json5_generator.Writer): utility methods for determining whether a given CSSStyleValue is valid for a given CSS property. The header files live in core/css/cssom. """ + def __init__(self, json5_file_paths, output_dir): super(CSSOMTypesWriter, self).__init__([], output_dir) @@ -30,8 +31,8 @@ def __init__(self, json5_file_paths, output_dir): property_['typedom_types'] = types # Generate CSSValueID values from keywords. - property_['keywordIDs'] = map( - enum_key_for_css_keyword, property_['keywords']) + property_['keywordIDs'] = map(enum_key_for_css_keyword, + property_['keywords']) self._outputs = { 'cssom_types.cc': self.generate_types, @@ -52,5 +53,6 @@ def generate_keywords(self): 'properties': self._properties, } + if __name__ == '__main__': json5_generator.Maker(CSSOMTypesWriter).main() diff --git a/third_party/blink/renderer/build/scripts/core/css/make_media_feature_names.py b/third_party/blink/renderer/build/scripts/core/css/make_media_feature_names.py index e58585b91b5fac..6ae5b44f8b89fd 100755 --- a/third_party/blink/renderer/build/scripts/core/css/make_media_feature_names.py +++ b/third_party/blink/renderer/build/scripts/core/css/make_media_feature_names.py @@ -10,11 +10,12 @@ class MakeMediaFeatureNamesWriter(make_names.MakeNamesWriter): - def __init__(self, json5_file_path, output_dir): - super(MakeMediaFeatureNamesWriter, self).__init__(json5_file_path, output_dir) + super(MakeMediaFeatureNamesWriter, self).__init__( + json5_file_path, output_dir) MakeMediaFeatureNamesWriter.filters['symbol'] = ( - media_feature_symbol.getMediaFeatureSymbolWithSuffix('MediaFeature')) + media_feature_symbol.getMediaFeatureSymbolWithSuffix( + 'MediaFeature')) if __name__ == "__main__": diff --git a/third_party/blink/renderer/build/scripts/core/css/make_media_features.py b/third_party/blink/renderer/build/scripts/core/css/make_media_features.py index 7e8aeecfa45d7a..5ea622f7b29a67 100755 --- a/third_party/blink/renderer/build/scripts/core/css/make_media_features.py +++ b/third_party/blink/renderer/build/scripts/core/css/make_media_features.py @@ -16,26 +16,35 @@ class MakeMediaFeaturesWriter(json5_generator.Writer): 'export': '', } filters = { - 'symbol': media_feature_symbol.getMediaFeatureSymbolWithSuffix(''), + 'symbol': + media_feature_symbol.getMediaFeatureSymbolWithSuffix(''), # symbol[1:] removes the leading 'k' produced by the above function. - 'to_function_name': lambda symbol: NameStyleConverter(symbol[1:]).to_function_name(), + 'to_function_name': + lambda symbol: NameStyleConverter(symbol[1:]).to_function_name(), } def __init__(self, json5_file_path, output_dir): - super(MakeMediaFeaturesWriter, self).__init__(json5_file_path, output_dir) + super(MakeMediaFeaturesWriter, self).__init__(json5_file_path, + output_dir) self._outputs = { ('media_features.h'): self.generate_header, } self._template_context = { - 'entries': self.json5_file.name_dictionaries, - 'input_files': self._input_files, - 'header_guard': self.make_header_guard(self._relative_output_dir + 'media_features.h') + 'entries': + self.json5_file.name_dictionaries, + 'input_files': + self._input_files, + 'header_guard': + self.make_header_guard(self._relative_output_dir + + 'media_features.h') } - @template_expander.use_jinja('core/css/templates/media_features.h.tmpl', filters=filters) + @template_expander.use_jinja( + 'core/css/templates/media_features.h.tmpl', filters=filters) def generate_header(self): return self._template_context + if __name__ == '__main__': json5_generator.Maker(MakeMediaFeaturesWriter).main() diff --git a/third_party/blink/renderer/build/scripts/core/css/make_style_shorthands.py b/third_party/blink/renderer/build/scripts/core/css/make_style_shorthands.py index 3a18d15ac1a9c7..a3cab6f8bb4852 100755 --- a/third_party/blink/renderer/build/scripts/core/css/make_style_shorthands.py +++ b/third_party/blink/renderer/build/scripts/core/css/make_style_shorthands.py @@ -43,9 +43,9 @@ def __init__(self, json5_file_paths, output_dir): self._input_files = json5_file_paths self._outputs = { (self._FILE_BASENAME + '.cc'): - self.generate_style_property_shorthand_cpp, + self.generate_style_property_shorthand_cpp, (self._FILE_BASENAME + '.h'): - self.generate_style_property_shorthand_h + self.generate_style_property_shorthand_h } json5_properties = css_properties.CSSProperties(json5_file_paths) @@ -53,10 +53,10 @@ def __init__(self, json5_file_paths, output_dir): self._longhand_dictionary = defaultdict(list) for property_ in json5_properties.shorthands: - property_['longhand_enum_keys'] = map( - enum_key_for_css_property, property_['longhands']) - property_['longhand_property_ids'] = map( - id_for_css_property, property_['longhands']) + property_['longhand_enum_keys'] = map(enum_key_for_css_property, + property_['longhands']) + property_['longhand_property_ids'] = map(id_for_css_property, + property_['longhands']) for longhand_enum_key in property_['longhand_enum_keys']: self._longhand_dictionary[longhand_enum_key].append(property_) @@ -64,8 +64,8 @@ def __init__(self, json5_file_paths, output_dir): # Sort first by number of longhands in decreasing order, then # alphabetically longhands.sort( - key=lambda property_: ( - -len(property_['longhand_property_ids']), property_['name'].original) + key= + lambda property_: (-len(property_['longhand_property_ids']), property_['name'].original) ) @template_expander.use_jinja( @@ -81,10 +81,15 @@ def generate_style_property_shorthand_cpp(self): 'core/css/templates/style_property_shorthand.h.tmpl') def generate_style_property_shorthand_h(self): return { - 'input_files': self._input_files, - 'properties': self._shorthands, - 'header_guard': self.make_header_guard(self._relative_output_dir + self._FILE_BASENAME + '.h') + 'input_files': + self._input_files, + 'properties': + self._shorthands, + 'header_guard': + self.make_header_guard(self._relative_output_dir + + self._FILE_BASENAME + '.h') } + if __name__ == '__main__': json5_generator.Maker(StylePropertyShorthandWriter).main() diff --git a/third_party/blink/renderer/build/scripts/core/css/parser/make_atrule_names.py b/third_party/blink/renderer/build/scripts/core/css/parser/make_atrule_names.py index 2a7d636556e320..57af289c4742a8 100755 --- a/third_party/blink/renderer/build/scripts/core/css/parser/make_atrule_names.py +++ b/third_party/blink/renderer/build/scripts/core/css/parser/make_atrule_names.py @@ -13,6 +13,7 @@ class AtRuleNamesWriter(json5_generator.Writer): Generates AtRuleNames. This class provides utility methods for parsing @rules (e.g. @font-face, @viewport, etc) """ + def __init__(self, json5_file_paths, output_dir): super(AtRuleNamesWriter, self).__init__(json5_file_paths, output_dir) @@ -36,8 +37,7 @@ def __init__(self, json5_file_paths, output_dir): self._character_offsets.append(chars_used) chars_used += len(descriptor['name'].original) self._longest_name_length = max( - len(descriptor['name'].original), - len(descriptor['alias']), + len(descriptor['name'].original), len(descriptor['alias']), self._longest_name_length) @template_expander.use_jinja( @@ -59,5 +59,6 @@ def generate_implementation(self): 'gperf_path': self.gperf_path } + if __name__ == '__main__': json5_generator.Maker(AtRuleNamesWriter).main() diff --git a/third_party/blink/renderer/build/scripts/core/css/properties/make_css_property_instances.py b/third_party/blink/renderer/build/scripts/core/css/properties/make_css_property_instances.py index 3d408bba282280..75030ac577eb8c 100755 --- a/third_party/blink/renderer/build/scripts/core/css/properties/make_css_property_instances.py +++ b/third_party/blink/renderer/build/scripts/core/css/properties/make_css_property_instances.py @@ -9,8 +9,12 @@ from collections import namedtuple from core.css import css_properties + class PropertyClassData( - namedtuple('PropertyClassData', 'enum_key,enum_value,property_id,classname,namespace_group,filename')): + namedtuple( + 'PropertyClassData', + 'enum_key,enum_value,property_id,classname,namespace_group,filename' + )): pass @@ -19,17 +23,16 @@ def __init__(self, json5_file_paths, output_dir): super(CSSPropertyInstancesWriter, self).__init__([], output_dir) self._input_files = json5_file_paths self._outputs = { - 'css_property_instances.h': self.generate_property_instances_header, + 'css_property_instances.h': + self.generate_property_instances_header, 'css_property_instances.cc': - self.generate_property_instances_implementation + self.generate_property_instances_implementation } # These files are no longer generated. If the files are present from # a previous build, we remove them. This avoids accidentally #including # a stale generated header. self._cleanup = set([ - 'css_property.cc', - 'css_property.h', - 'css_unresolved_property.cc', + 'css_property.cc', 'css_property.h', 'css_unresolved_property.cc', 'css_unresolved_property.h' ]) @@ -85,5 +88,6 @@ def generate_property_instances_implementation(self): 'alias_classes_by_property_id': self._alias_classes_by_id, } + if __name__ == '__main__': json5_generator.Maker(CSSPropertyInstancesWriter).main() diff --git a/third_party/blink/renderer/build/scripts/core/css/properties/make_css_property_subclasses.py b/third_party/blink/renderer/build/scripts/core/css/properties/make_css_property_subclasses.py index a5a2352a561660..2730c966a064fd 100755 --- a/third_party/blink/renderer/build/scripts/core/css/properties/make_css_property_subclasses.py +++ b/third_party/blink/renderer/build/scripts/core/css/properties/make_css_property_subclasses.py @@ -28,7 +28,8 @@ def __init__(self, json5_file_paths, output_dir): property_methods = json5_generator.Json5File.load_from_files( [json5_file_paths[3]]) for property_method in property_methods.name_dictionaries: - self._property_methods[property_method['name'].original] = property_method + self._property_methods[property_method['name']. + original] = property_method all_properties = self._css_properties.properties_including_aliases @@ -86,5 +87,6 @@ def generate_shorthands_cc(self): 'is_longhand': False, } + if __name__ == '__main__': json5_generator.Maker(CSSPropertiesWriter).main() diff --git a/third_party/blink/renderer/build/scripts/core/style/computed_style_fields.py b/third_party/blink/renderer/build/scripts/core/style/computed_style_fields.py index f7bf935109e723..6de3f6a365c3fa 100644 --- a/third_party/blink/renderer/build/scripts/core/style/computed_style_fields.py +++ b/third_party/blink/renderer/build/scripts/core/style/computed_style_fields.py @@ -35,6 +35,7 @@ class Group(object): fields: List of Field instances stored directly under this group. parent: The parent group, or None if this is the root group. """ + def __init__(self, name, subgroups, fields): self.name = name self.subgroups = subgroups @@ -45,12 +46,11 @@ def __init__(self, name, subgroups, fields): self.type_name = converter.to_class_name(prefix='style', suffix='data') self.member_name = converter.to_class_data_member(suffix='data') self.num_32_bit_words_for_bit_fields = _num_32_bit_words_for_bit_fields( - field for field in fields if field.is_bit_field - ) + field for field in fields if field.is_bit_field) # Recursively get all the fields in the subgroups as well - self.all_fields = _flatten_list( - subgroup.all_fields for subgroup in subgroups) + fields + self.all_fields = _flatten_list(subgroup.all_fields + for subgroup in subgroups) + fields # Ensure that all fields/subgroups on this group link to it for field in fields: @@ -75,10 +75,12 @@ def path_without_root(self): class Enum(object): """Represents a generated enum in ComputedStyleBaseConstants.""" + def __init__(self, type_name, keywords, is_set): self.type_name = type_name - self.values = [NameStyleConverter(keyword).to_enum_value() - for keyword in keywords] + self.values = [ + NameStyleConverter(keyword).to_enum_value() for keyword in keywords + ] self.is_set = is_set @@ -92,6 +94,7 @@ class DiffGroup(object): expressions: List of expression that are on this group that need to be diffed. """ + def __init__(self, group): self.group = group self.subgroups = [] @@ -155,11 +158,15 @@ def __init__(self, field_role, name_for_methods, property_name, type_name, # Method names self.getter_method_name = getter_method_name self.setter_method_name = setter_method_name - self.internal_getter_method_name = name_source.to_function_name(suffix='internal') - self.internal_mutable_method_name = name_source.to_function_name(prefix='mutable', suffix='internal') - self.internal_setter_method_name = NameStyleConverter(setter_method_name).to_function_name(suffix='internal') + self.internal_getter_method_name = name_source.to_function_name( + suffix='internal') + self.internal_mutable_method_name = name_source.to_function_name( + prefix='mutable', suffix='internal') + self.internal_setter_method_name = NameStyleConverter( + setter_method_name).to_function_name(suffix='internal') self.initial_method_name = initial_method_name - self.resetter_method_name = name_source.to_function_name(prefix='reset') + self.resetter_method_name = name_source.to_function_name( + prefix='reset') self.computed_style_custom_functions = computed_style_custom_functions # Only bitfields have sizes. self.is_bit_field = self.size is not None @@ -176,6 +183,7 @@ def __init__(self, field_role, name_for_methods, property_name, type_name, assert self.is_inherited or not self.is_independent, \ 'Only inherited fields can be independent' - self.is_inherited_method_name = name_source.to_function_name(suffix=['is', 'inherited']) + self.is_inherited_method_name = name_source.to_function_name( + suffix=['is', 'inherited']) assert len(kwargs) == 0, \ 'Unexpected arguments provided to Field: ' + str(kwargs) diff --git a/third_party/blink/renderer/build/scripts/core/style/make_computed_style_base.py b/third_party/blink/renderer/build/scripts/core/style/make_computed_style_base.py index 4375d751159879..160d3a6b2e7b94 100755 --- a/third_party/blink/renderer/build/scripts/core/style/make_computed_style_base.py +++ b/third_party/blink/renderer/build/scripts/core/style/make_computed_style_base.py @@ -88,6 +88,7 @@ # FIXME: Improve documentation and add docstrings. + def _flatten_list(x): """Flattens a list of lists into a single list.""" return list(chain.from_iterable(x)) @@ -109,6 +110,7 @@ def _create_groups(properties): Returns: Group: The root group of the tree. The name of the group is set to None. """ + # We first convert properties into a dictionary structure. Each dictionary # represents a group. The None key corresponds to the fields directly stored # on that group. The other keys map from group name to another dictionary. @@ -127,8 +129,9 @@ def _create_groups(properties): def _dict_to_group(name, group_dict): fields_in_current_group = group_dict.pop(None) subgroups = [ - _dict_to_group(subgroup_name, subgroup_dict) for subgroup_name, - subgroup_dict in group_dict.items()] + _dict_to_group(subgroup_name, subgroup_dict) + for subgroup_name, subgroup_dict in group_dict.items() + ] return Group(name, subgroups, _reorder_fields(fields_in_current_group)) root_group_dict = {None: []} @@ -171,32 +174,32 @@ def _list_field_dependencies(entries_with_field_dependencies): return field_dependencies -def _create_diff_groups(fields_to_diff, - methods_to_diff, - predicates_to_test, +def _create_diff_groups(fields_to_diff, methods_to_diff, predicates_to_test, root_group): diff_group = DiffGroup(root_group) - field_dependencies = _list_field_dependencies( - methods_to_diff + predicates_to_test) + field_dependencies = _list_field_dependencies(methods_to_diff + + predicates_to_test) for subgroup in root_group.subgroups: - if any(field.property_name in (fields_to_diff + field_dependencies) - for field in subgroup.all_fields): - diff_group.subgroups.append(_create_diff_groups( - fields_to_diff, methods_to_diff, predicates_to_test, subgroup)) + if any( + field.property_name in (fields_to_diff + field_dependencies) + for field in subgroup.all_fields): + diff_group.subgroups.append( + _create_diff_groups(fields_to_diff, methods_to_diff, + predicates_to_test, subgroup)) for entry in fields_to_diff: for field in root_group.fields: if not field.is_inherited_flag and entry == field.property_name: diff_group.fields.append(field) for entry in methods_to_diff: for field in root_group.fields: - if (not field.is_inherited_flag and - field.property_name in entry['field_dependencies'] and - entry['method'] not in diff_group.expressions): + if (not field.is_inherited_flag + and field.property_name in entry['field_dependencies'] + and entry['method'] not in diff_group.expressions): diff_group.expressions.append(entry['method']) for entry in predicates_to_test: for field in root_group.fields: - if (not field.is_inherited_flag and - field.property_name in entry['field_dependencies'] + if (not field.is_inherited_flag + and field.property_name in entry['field_dependencies'] and entry['predicate'] not in diff_group.predicates): diff_group.predicates.append(entry['predicate']) return diff_group @@ -208,10 +211,12 @@ def _create_enums(properties): for property_ in properties: # Only generate enums for keyword properties that do not # require includes. - if (property_['field_template'] in ('keyword', 'multi_keyword') and - len(property_['include_paths']) == 0): - enum = Enum(property_['type_name'], property_['keywords'], - is_set=(property_['field_template'] == 'multi_keyword')) + if (property_['field_template'] in ('keyword', 'multi_keyword') + and len(property_['include_paths']) == 0): + enum = Enum( + property_['type_name'], + property_['keywords'], + is_set=(property_['field_template'] == 'multi_keyword')) if property_['field_template'] == 'multi_keyword': assert property_['keywords'][0] == 'none', \ "First keyword in a 'multi_keyword' field must be " \ @@ -290,7 +295,9 @@ def _create_inherited_flag_field(property_): Create the field used for an inheritance fast path from an independent CSS property, and return the Field object. """ - name_for_methods = NameStyleConverter(property_['name_for_methods']).to_function_name(suffix=['is', 'inherited']) + name_for_methods = NameStyleConverter( + property_['name_for_methods']).to_function_name( + suffix=['is', 'inherited']) name_source = NameStyleConverter(name_for_methods) return Field( 'inherited_flag', @@ -365,8 +372,10 @@ def _reorder_non_bit_fields(non_bit_fields): assert field.alignment_type in ALIGNMENT_ORDER, \ "Type {} has unknown alignment. Please update ALIGNMENT_ORDER " \ "to include it.".format(field.name) - return list(sorted( - non_bit_fields, key=lambda f: ALIGNMENT_ORDER.index(f.alignment_type))) + return list( + sorted( + non_bit_fields, + key=lambda f: ALIGNMENT_ORDER.index(f.alignment_type))) def _reorder_fields(fields): @@ -378,12 +387,12 @@ def _reorder_fields(fields): non_bit_fields = [field for field in fields if not field.is_bit_field] # Non bit fields go first, then the bit fields. - return _reorder_non_bit_fields( - non_bit_fields) + _reorder_bit_fields(bit_fields) + return _reorder_non_bit_fields(non_bit_fields) + _reorder_bit_fields( + bit_fields) -def _get_properties_ranking_using_partition_rule( - properties_ranking, partition_rule): +def _get_properties_ranking_using_partition_rule(properties_ranking, + partition_rule): """Take the contents of the properties ranking file and produce a dictionary of css properties with their group number based on the partition_rule @@ -398,9 +407,10 @@ def _get_properties_ranking_using_partition_rule( """ return dict( zip(properties_ranking, [ - bisect.bisect_left( - partition_rule, float(i) / len(properties_ranking)) + 1 - for i in range(len(properties_ranking))])) + bisect.bisect_left(partition_rule, + float(i) / len(properties_ranking)) + 1 + for i in range(len(properties_ranking)) + ])) def _best_rank(prop, ranking_map): @@ -418,8 +428,10 @@ def _best_rank(prop, ranking_map): return best_rank if best_rank != worst_rank else -1 -def _evaluate_rare_non_inherited_group(properties, properties_ranking, - num_layers, partition_rule=None): +def _evaluate_rare_non_inherited_group(properties, + properties_ranking, + num_layers, + partition_rule=None): """Re-evaluate the grouping of RareNonInherited groups based on each property's popularity. @@ -432,15 +444,15 @@ def _evaluate_rare_non_inherited_group(properties, properties_ranking, """ if partition_rule is None: partition_rule = [ - 1.0 * (i + 1) / num_layers for i in range(num_layers)] + 1.0 * (i + 1) / num_layers for i in range(num_layers) + ] assert num_layers == len(partition_rule), \ "Length of rule and num_layers mismatch" layers_name = [ "rare-non-inherited-usage-less-than-{}-percent".format( - int(round(partition_rule[i] * 100))) - for i in range(num_layers) + int(round(partition_rule[i] * 100))) for i in range(num_layers) ] properties_ranking = _get_properties_ranking_using_partition_rule( properties_ranking, partition_rule) @@ -464,8 +476,10 @@ def _evaluate_rare_non_inherited_group(properties, properties_ranking, property_["field_group"] = "->".join(group_tree) -def _evaluate_rare_inherit_group(properties, properties_ranking, - num_layers, partition_rule=None): +def _evaluate_rare_inherit_group(properties, + properties_ranking, + num_layers, + partition_rule=None): """Re-evaluate the grouping of RareInherited groups based on each property's popularity. @@ -486,8 +500,7 @@ def _evaluate_rare_inherit_group(properties, properties_ranking, layers_name = [ "rare-inherited-usage-less-than-{}-percent".format( - int(round(partition_rule[i] * 100))) - for i in range(num_layers) + int(round(partition_rule[i] * 100))) for i in range(num_layers) ] properties_ranking = _get_properties_ranking_using_partition_rule( @@ -526,8 +539,7 @@ def __init__(self, json5_file_paths, output_dir): # css_properties.json5 and we can get the longest continuous segment. # Thereby reduce the switch case statement to the minimum. properties = keyword_utils.sort_keyword_properties_by_canonical_order( - self._css_properties.longhands, - json5_file_paths[5], + self._css_properties.longhands, json5_file_paths[5], self.default_parameters) self._properties = properties + self._css_properties.extra_fields @@ -535,41 +547,43 @@ def __init__(self, json5_file_paths, output_dir): # Organise fields into a tree structure where the root group # is ComputedStyleBase. - group_parameters = dict([ - (conf["name"], conf["cumulative_distribution"]) for conf in - json5_generator.Json5File.load_from_files( - [json5_file_paths[7]]).name_dictionaries]) + group_parameters = dict( + [(conf["name"], conf["cumulative_distribution"]) + for conf in json5_generator.Json5File.load_from_files( + [json5_file_paths[7]]).name_dictionaries]) properties_ranking = [ - x["name"].original for x in json5_generator.Json5File.load_from_files( - [json5_file_paths[6]]).name_dictionaries + x["name"].original for x in json5_generator.Json5File. + load_from_files([json5_file_paths[6]]).name_dictionaries ] _evaluate_rare_non_inherited_group( - self._properties, - properties_ranking, + self._properties, properties_ranking, len(group_parameters["rare_non_inherited_properties_rule"]), group_parameters["rare_non_inherited_properties_rule"]) _evaluate_rare_inherit_group( - self._properties, - properties_ranking, + self._properties, properties_ranking, len(group_parameters["rare_inherited_properties_rule"]), group_parameters["rare_inherited_properties_rule"]) self._root_group = _create_groups(self._properties) self._diff_functions_map = _create_diff_groups_map( json5_generator.Json5File.load_from_files( - [json5_file_paths[4]]).name_dictionaries, - self._root_group) + [json5_file_paths[4]]).name_dictionaries, self._root_group) self._include_paths = _get_include_paths(self._properties) self._outputs = { - 'computed_style_base.h': self.generate_base_computed_style_h, - 'computed_style_base.cc': self.generate_base_computed_style_cpp, + 'computed_style_base.h': + self.generate_base_computed_style_h, + 'computed_style_base.cc': + self.generate_base_computed_style_cpp, 'computed_style_base_constants.h': - self.generate_base_computed_style_constants, + self.generate_base_computed_style_constants, } @template_expander.use_jinja( - 'core/style/templates/computed_style_base.h.tmpl', tests={'in': lambda a, b: a in b}) + 'core/style/templates/computed_style_base.h.tmpl', + tests={ + 'in': lambda a, b: a in b + }) def generate_base_computed_style_h(self): return { 'input_files': self._input_files, @@ -582,7 +596,9 @@ def generate_base_computed_style_h(self): @template_expander.use_jinja( 'core/style/templates/computed_style_base.cc.tmpl', - tests={'in': lambda a, b: a in b}) + tests={ + 'in': lambda a, b: a in b + }) def generate_base_computed_style_cpp(self): return { 'input_files': self._input_files, @@ -593,7 +609,8 @@ def generate_base_computed_style_cpp(self): 'diff_functions_map': self._diff_functions_map, } - @template_expander.use_jinja('core/style/templates/computed_style_base_constants.h.tmpl') + @template_expander.use_jinja( + 'core/style/templates/computed_style_base_constants.h.tmpl') def generate_base_computed_style_constants(self): return { 'input_files': self._input_files, @@ -601,5 +618,6 @@ def generate_base_computed_style_constants(self): 'enums': self._generated_enums, } + if __name__ == '__main__': json5_generator.Maker(ComputedStyleBaseWriter).main() diff --git a/third_party/blink/renderer/build/scripts/make_event_factory.py b/third_party/blink/renderer/build/scripts/make_event_factory.py index 39f664a4a37255..0050b386cce1f2 100755 --- a/third_party/blink/renderer/build/scripts/make_event_factory.py +++ b/third_party/blink/renderer/build/scripts/make_event_factory.py @@ -84,14 +84,10 @@ class EventFactoryWriter(json5_generator.Writer): 'suffix': '', } filters = { - 'cpp_name': - name_utilities.cpp_name, - 'name': - lambda entry: entry['name'].original, - 'create_event_ignore_case_list': - create_event_ignore_case_list, - 'measure_name': - measure_name, + 'cpp_name': name_utilities.cpp_name, + 'name': lambda entry: entry['name'].original, + 'create_event_ignore_case_list': create_event_ignore_case_list, + 'measure_name': measure_name, } def __init__(self, json5_file_path, output_dir): diff --git a/third_party/blink/renderer/core/html/forms/resources/PRESUBMIT.py b/third_party/blink/renderer/core/html/forms/resources/PRESUBMIT.py index f28465828fa54e..26b84f5fb5df33 100644 --- a/third_party/blink/renderer/core/html/forms/resources/PRESUBMIT.py +++ b/third_party/blink/renderer/core/html/forms/resources/PRESUBMIT.py @@ -2,13 +2,15 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. + def _CheckChangeOnUploadOrCommit(input_api, output_api): - return input_api.canned_checks.CheckPatchFormatted(input_api, output_api, - check_js=True) + return input_api.canned_checks.CheckPatchFormatted( + input_api, output_api, check_js=True) + def CheckChangeOnUpload(input_api, output_api): - return _CheckChangeOnUploadOrCommit(input_api, output_api) + return _CheckChangeOnUploadOrCommit(input_api, output_api) def CheckChangeOnCommit(input_api, output_api): - return _CheckChangeOnUploadOrCommit(input_api, output_api) + return _CheckChangeOnUploadOrCommit(input_api, output_api) diff --git a/third_party/blink/renderer/core/streams/PRESUBMIT.py b/third_party/blink/renderer/core/streams/PRESUBMIT.py index c3243c4d5d4009..7935e32c18d488 100644 --- a/third_party/blink/renderer/core/streams/PRESUBMIT.py +++ b/third_party/blink/renderer/core/streams/PRESUBMIT.py @@ -3,7 +3,6 @@ # found in the LICENSE file. # pylint: disable=invalid-name,import-error - """Run eslint on the Streams API Javascript files. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts @@ -23,8 +22,8 @@ def CheckChangeOnCommit(input_api, output_api): def common_checks(input_api, output_api): import sys - web_dev_style_path = input_api.os_path.join(input_api.change.RepositoryRoot(), - 'tools') + web_dev_style_path = input_api.os_path.join( + input_api.change.RepositoryRoot(), 'tools') oldpath = sys.path sys.path = [input_api.PresubmitLocalPath(), web_dev_style_path] + sys.path from web_dev_style import js_checker @@ -33,5 +32,5 @@ def common_checks(input_api, output_api): def is_resource(maybe_resource): return maybe_resource.AbsoluteLocalPath().endswith('.js') - return js_checker.JSChecker(input_api, output_api, - file_filter=is_resource).RunChecks() + return js_checker.JSChecker( + input_api, output_api, file_filter=is_resource).RunChecks() diff --git a/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/PRESUBMIT.py b/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/PRESUBMIT.py index 39bd8055efd248..9c3f101ac51c4e 100644 --- a/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/PRESUBMIT.py +++ b/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/PRESUBMIT.py @@ -1,7 +1,6 @@ # Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. - """Script that runs tests before uploading a patch.""" @@ -10,10 +9,7 @@ def _RunTests(input_api, output_api): cmd_name = 'all_python_tests' cmd = ['python', '-m', 'unittest', 'discover', '-p', '*test.py'] test_cmd = input_api.Command( - name=cmd_name, - cmd=cmd, - kwargs={}, - message=output_api.PresubmitError) + name=cmd_name, cmd=cmd, kwargs={}, message=output_api.PresubmitError) if input_api.verbose: print 'Running ' + cmd_name return input_api.RunTests([test_cmd]) diff --git a/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/constraints.py b/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/constraints.py index 11c31764dabe8c..01e2f10c39d737 100644 --- a/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/constraints.py +++ b/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/constraints.py @@ -1,7 +1,6 @@ # Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. - """Module to get random numbers, strings, etc. The values returned by the various functions can be replaced in @@ -23,7 +22,6 @@ import gatt_aliases import wbt_fakes - # Strings that are used to generate the beginning of a test. The replacement # fields are replaced by Get*Base() functions below to generate valid test # cases. @@ -102,8 +100,8 @@ def _get_array_of_random_ints(max_length, max_value): length = utils.UniformExpoInteger(0, math.log(max_length, 2)) exp_max_value = math.log(max_value, 2) return '[{}]'.format(', '.join( - str(utils.UniformExpoInteger(0, exp_max_value)) for _ in xrange(length)) - ) + str(utils.UniformExpoInteger(0, exp_max_value)) + for _ in xrange(length))) def _get_typed_array(): @@ -133,10 +131,10 @@ def _get_typed_array(): A string made up of a randomly chosen type and argument type from the lists above. """ - array_type = random.choice(['Int8Array', 'Int16Array', 'Int32Array', - 'Uint8Array', 'Uint16Array', 'Uint32Array', - 'Uint8ClampedArray', 'Float32Array', - 'Float64Array']) + array_type = random.choice([ + 'Int8Array', 'Int16Array', 'Int32Array', 'Uint8Array', 'Uint16Array', + 'Uint32Array', 'Uint8ClampedArray', 'Float32Array', 'Float64Array' + ]) # Choose an argument type at random. arguments = random.choice([ @@ -147,13 +145,13 @@ def _get_typed_array(): # typedArray e.g. new Uint8Array([1,2,3]) _get_typed_array, # object e.g. [1,2,3] - lambda: _get_array_of_random_ints(max_length=1000, max_value=2 ** 64), + lambda: _get_array_of_random_ints(max_length=1000, max_value=2**64), # buffer e.g. new Uint8Array(10).buffer lambda: _get_typed_array() + '.buffer', ]) - return 'new {array_type}({arguments})'.format(array_type=array_type, - arguments=arguments()) + return 'new {array_type}({arguments})'.format( + array_type=array_type, arguments=arguments()) def GetAdvertisedServiceUUIDFromFakes(): @@ -343,8 +341,8 @@ def get_characteristics_retrieved_base(): optional_service_uuid = random.choice(['', service_uuid]) optional_characteristic_uuid = random.choice(['', characteristic_uuid]) - services_base = random.choice([SERVICE_RETRIEVED_BASE, - SERVICES_RETRIEVED_BASE]) + services_base = random.choice( + [SERVICE_RETRIEVED_BASE, SERVICES_RETRIEVED_BASE]) characteristics_base = services_base + random.choice([ CHARACTERISTIC_RETRIEVED_BASE, @@ -360,8 +358,10 @@ def get_characteristics_retrieved_base(): def get_get_primary_services_call(): - call = random.choice([u'getPrimaryService({service_uuid})', - u'getPrimaryServices({optional_service_uuid})']) + call = random.choice([ + u'getPrimaryService({service_uuid})', + u'getPrimaryServices({optional_service_uuid})' + ]) return call.format( service_uuid=get_service_uuid(), diff --git a/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/fuzz_integration_test.py b/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/fuzz_integration_test.py index 4080b8a28701a2..9b37e5a1a496a9 100644 --- a/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/fuzz_integration_test.py +++ b/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/fuzz_integration_test.py @@ -1,7 +1,6 @@ # Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. - """Test that the fuzzer works the way ClusterFuzz invokes it.""" import glob @@ -15,7 +14,6 @@ class WebBluetoothFuzzerTest(unittest.TestCase): - def setUp(self): self._output_dir = tempfile.mkdtemp() self._resources_path = setup.RetrieveResources() @@ -25,9 +23,10 @@ def tearDown(self): shutil.rmtree(self._resources_path) def testCanGenerate100Files(self): - sys.argv = ['fuzz_main_run.py', '--no_of_files=100', - '--input_dir={}'.format(self._output_dir), - '--output_dir={}'.format(self._output_dir)] + sys.argv = [ + 'fuzz_main_run.py', '--no_of_files=100', '--input_dir={}'.format( + self._output_dir), '--output_dir={}'.format(self._output_dir) + ] import fuzz_main_run fuzz_main_run.main() @@ -40,5 +39,6 @@ def testCanGenerate100Files(self): for test_case in written_files: self.assertFalse('TRANSFORM' in open(test_case).read()) + if __name__ == '__main__': unittest.main() diff --git a/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/fuzz_main_run.py b/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/fuzz_main_run.py index d4f2f055f3873f..1703291f93923f 100644 --- a/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/fuzz_main_run.py +++ b/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/fuzz_main_run.py @@ -1,7 +1,6 @@ # Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. - """Script to generate Web Bluetooth web tests that can be run in ClusterFuzz. This script uses templates in the templates/ directory to generate html files @@ -21,10 +20,10 @@ import parameter_fuzzer import test_case_fuzzer -JS_FILES_AND_PARAMETERS = ( - ('testharness.js', 'INCLUDE_TESTHARNESS'), - ('testharnessreport.js', 'INCLUDE_REPORT'), - ('bluetooth-helpers.js', 'INCLUDE_BLUETOOTH_HELPERS')) +JS_FILES_AND_PARAMETERS = (('testharness.js', 'INCLUDE_TESTHARNESS'), + ('testharnessreport.js', + 'INCLUDE_REPORT'), ('bluetooth-helpers.js', + 'INCLUDE_BLUETOOTH_HELPERS')) SCRIPT_PREFIX = '\n' @@ -39,20 +38,30 @@ def _GetArguments(): parser = argparse.ArgumentParser() # Arguments used by ClusterFuzz: - parser.add_argument('-n', '--no_of_files', type=int, required=True, - help='The number of test cases that the fuzzer is ' - 'expected to generate') - parser.add_argument('-i', '--input_dir', - help='The directory containing the fuzzer\'s data ' - 'bundle.') - parser.add_argument('-o', '--output_dir', required=True, - help='The directory where test case files should be ' - 'written to.') - - parser.add_argument('--content_shell_dir', - help='The directory of content shell. If present the ' - 'program will print a command to run the ' - 'generated test file.') + parser.add_argument( + '-n', + '--no_of_files', + type=int, + required=True, + help='The number of test cases that the fuzzer is ' + 'expected to generate') + parser.add_argument( + '-i', + '--input_dir', + help='The directory containing the fuzzer\'s data ' + 'bundle.') + parser.add_argument( + '-o', + '--output_dir', + required=True, + help='The directory where test case files should be ' + 'written to.') + + parser.add_argument( + '--content_shell_dir', + help='The directory of content shell. If present the ' + 'program will print a command to run the ' + 'generated test file.') return parser.parse_args() @@ -93,9 +102,10 @@ def FuzzTemplate(template_path, resources_path): js_file_data = (SCRIPT_PREFIX + js_file_data + SCRIPT_SUFFIX) - fuzzed_file_data = FillInParameter(include_parameter, - lambda data=js_file_data: data, - fuzzed_file_data) + fuzzed_file_data = FillInParameter( + include_parameter, + lambda data=js_file_data: data, + fuzzed_file_data) return fuzzed_file_data.encode('utf-8') @@ -113,13 +123,11 @@ def WriteTestFile(test_file_data, test_file_prefix, output_dir): """ file_descriptor, file_path = tempfile.mkstemp( - prefix=test_file_prefix, - suffix='.html', - dir=output_dir) + prefix=test_file_prefix, suffix='.html', dir=output_dir) with os.fdopen(file_descriptor, 'wb') as output: - print 'Writing {} bytes to \'{}\''.format(len(test_file_data), - file_path) + print 'Writing {} bytes to \'{}\''.format( + len(test_file_data), file_path) output.write(test_file_data) return file_path @@ -135,9 +143,8 @@ def main(): # Get Templates current_path = os.path.dirname(os.path.realpath(__file__)) - available_templates = glob.glob(os.path.join(current_path, - 'templates', - '*.html')) + available_templates = glob.glob( + os.path.join(current_path, 'templates', '*.html')) # Generate Test Files resources_path = os.path.join(current_path, 'resources') @@ -149,12 +156,10 @@ def main(): # Get Test File template_name = os.path.splitext(os.path.basename(template_path))[0] - test_file_name = 'fuzz-{}-{}-{}'.format(template_name, - int(start_time), + test_file_name = 'fuzz-{}-{}-{}'.format(template_name, int(start_time), int(file_no)) - test_file_path = WriteTestFile(test_file_data, - test_file_name, + test_file_path = WriteTestFile(test_file_data, test_file_name, args.output_dir) if args.content_shell_dir: diff --git a/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/fuzzer_helpers.py b/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/fuzzer_helpers.py index 798fe86306d617..9b6ccceb254ac4 100644 --- a/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/fuzzer_helpers.py +++ b/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/fuzzer_helpers.py @@ -1,7 +1,6 @@ # Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. - """Module that includes classes and functions used by fuzzers.""" diff --git a/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/gatt_aliases.py b/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/gatt_aliases.py index e28d502d137e19..86ce0100f7538b 100644 --- a/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/gatt_aliases.py +++ b/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/gatt_aliases.py @@ -1,7 +1,6 @@ # Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. - """Contains Services, Characteristics and Descriptor aliases. These values are copied from: @@ -11,7 +10,6 @@ https://www.bluetooth.com/specifications/gatt/characteristics """ - SERVICES = [ 'alert_notification', 'automation_io', @@ -51,7 +49,6 @@ 'weight_scale', ] - CHARACTERISTICS = [ 'aerobic_heart_rate_lower_limit', 'aerobic_heart_rate_upper_limit', diff --git a/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/parameter_fuzzer.py b/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/parameter_fuzzer.py index 0c9bdb502e600c..cb06b6e76942d8 100644 --- a/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/parameter_fuzzer.py +++ b/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/parameter_fuzzer.py @@ -1,7 +1,6 @@ # Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. - """Module to fuzz parameters of a template.""" import constraints @@ -23,8 +22,7 @@ def FuzzParameters(test_file_data): """ test_file_data = FillInParameter('TRANSFORM_BASIC_BASE', - constraints.GetBasicBase, - test_file_data) + constraints.GetBasicBase, test_file_data) test_file_data = FillInParameter('TRANSFORM_DEVICE_DISCOVERY_BASE', constraints.GetDeviceDiscoveryBase, @@ -38,9 +36,9 @@ def FuzzParameters(test_file_data): constraints.get_services_retrieved_base, test_file_data) - test_file_data = FillInParameter('TRANSFORM_CHARACTERISTICS_RETRIEVED_BASE', - constraints.get_characteristics_retrieved_base, - test_file_data) + test_file_data = FillInParameter( + 'TRANSFORM_CHARACTERISTICS_RETRIEVED_BASE', + constraints.get_characteristics_retrieved_base, test_file_data) test_file_data = FillInParameter('TRANSFORM_REQUEST_DEVICE_OPTIONS', constraints.GetRequestDeviceOptions, @@ -62,12 +60,10 @@ def FuzzParameters(test_file_data): constraints.get_pick_a_characteristic, test_file_data) - test_file_data = FillInParameter('TRANSFORM_VALUE', - constraints.get_buffer_source, - test_file_data) + test_file_data = FillInParameter( + 'TRANSFORM_VALUE', constraints.get_buffer_source, test_file_data) test_file_data = FillInParameter('TRANSFORM_RELOAD_ID', - constraints.get_reload_id, - test_file_data) + constraints.get_reload_id, test_file_data) return test_file_data diff --git a/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/setup.py b/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/setup.py index 3805fbc026b2ea..c54da3cfa4c879 100644 --- a/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/setup.py +++ b/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/setup.py @@ -1,7 +1,6 @@ # Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. - """Script that helps run the fuzzer locally and in ClusterFuzz. To prepare to run the fuzzer locally, this script copies the necessary @@ -19,15 +18,15 @@ import sys # src path from this file's path. -SRC_PATH = os.path.join( - os.pardir, os.pardir, os.pardir, os.pardir, os.pardir, os.pardir, os.pardir) -WEB_TESTS_RESOURCES_PATH = os.path.join( - SRC_PATH, 'third_party', 'blink', 'web_tests', 'resources') +SRC_PATH = os.path.join(os.pardir, os.pardir, os.pardir, os.pardir, os.pardir, + os.pardir, os.pardir) +WEB_TESTS_RESOURCES_PATH = os.path.join(SRC_PATH, 'third_party', 'blink', + 'web_tests', 'resources') WEB_PLATFORM_TESTS_RESOURCES_PATH = os.path.join( SRC_PATH, 'third_party', 'blink', 'web_tests', 'external', 'wpt', 'bluetooth', 'resources') -COMMON_FUZZER_RESOURCES_PATH = os.path.join( - SRC_PATH, 'testing', 'clusterfuzz', 'common') +COMMON_FUZZER_RESOURCES_PATH = os.path.join(SRC_PATH, 'testing', 'clusterfuzz', + 'common') RESOURCES = [ os.path.join(WEB_TESTS_RESOURCES_PATH, 'testharness.js'), os.path.join(WEB_TESTS_RESOURCES_PATH, 'testharnessreport.js'), @@ -69,13 +68,19 @@ def main(): # Get arguments. parser = argparse.ArgumentParser() - parser.add_argument('-c', '--cluster_fuzz', action='store_true', - help='If present, this script generates tar.bz2 file ' - 'containing the fuzzer. This file can be uploaded ' - 'and run on ClusterFuzz.') - parser.add_argument('-l', '--local', action='store_true', - help='If present, this script retrieves the files ' - 'necessary to run the fuzzer locally.') + parser.add_argument( + '-c', + '--cluster_fuzz', + action='store_true', + help='If present, this script generates tar.bz2 file ' + 'containing the fuzzer. This file can be uploaded ' + 'and run on ClusterFuzz.') + parser.add_argument( + '-l', + '--local', + action='store_true', + help='If present, this script retrieves the files ' + 'necessary to run the fuzzer locally.') args = parser.parse_args() @@ -107,5 +112,6 @@ def main(): base_dir='clusterfuzz') print 'File wrote to: ' + compressed_file_path + '.tar.bz2' + if __name__ == '__main__': sys.exit(main()) diff --git a/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/test_case_fuzzer.py b/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/test_case_fuzzer.py index c4932709eefe9f..8e6bb147148488 100644 --- a/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/test_case_fuzzer.py +++ b/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/test_case_fuzzer.py @@ -1,7 +1,6 @@ # Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. - """Module to generate a test file with random calls to the Web Bluetooth API.""" import random @@ -27,9 +26,7 @@ '.then(() => {', ], # Request Device Tokens - [ - ' requestDeviceWithKeyDown(TRANSFORM_REQUEST_DEVICE_OPTIONS);' - ], + [' requestDeviceWithKeyDown(TRANSFORM_REQUEST_DEVICE_OPTIONS);'], [ ' return requestDeviceWithKeyDown(TRANSFORM_REQUEST_DEVICE_OPTIONS);', '})', @@ -194,5 +191,4 @@ def GenerateTestFile(template_file_data): """ return FillInParameter('TRANSFORM_RANDOM_TOKENS', - _GenerateSequenceOfRandomTokens, - template_file_data) + _GenerateSequenceOfRandomTokens, template_file_data) diff --git a/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/wbt_fakes.py b/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/wbt_fakes.py index dddb407fe50de1..1f582aeeda0e1a 100644 --- a/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/wbt_fakes.py +++ b/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/wbt_fakes.py @@ -1,7 +1,6 @@ # Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. - """Module that contains information about Web Bluetooth's Fake Adapters.""" BLOCKLISTED_UUID = '611c954a-263b-4f4a-aab6-01ddb953f985' @@ -67,13 +66,11 @@ ] # Tuples of common service uuid and their characteristics uuids. -GENERIC_ACCESS_SERVICE = ( - 'generic_access', ['gap.device_name', 'gap.peripheral_privacy_flag'] -) +GENERIC_ACCESS_SERVICE = ('generic_access', + ['gap.device_name', 'gap.peripheral_privacy_flag']) -HEART_RATE_SERVICE = ( - 'heart_rate', ['heart_rate_measurement', 'body_sensor_location'] -) +HEART_RATE_SERVICE = ('heart_rate', + ['heart_rate_measurement', 'body_sensor_location']) # List of available fake adapters. ALL_ADAPTERS = [ @@ -123,8 +120,10 @@ ), ( 'BlocklistTestAdapter', - [BLOCKLISTED_UUID, 'device_information', 'generic_access', - 'heart_rate', 'human_interface_device'], + [ + BLOCKLISTED_UUID, 'device_information', 'generic_access', + 'heart_rate', 'human_interface_device' + ], ), ( 'FailingConnectionsAdapter', @@ -140,7 +139,9 @@ ), ( 'DeviceNameLongerThan29BytesAdapter', - ['a_device_name_that_is_longer_than_29_bytes_but_shorter_than_248_bytes'], + [ + 'a_device_name_that_is_longer_than_29_bytes_but_shorter_than_248_bytes' + ], ), ] @@ -164,17 +165,16 @@ ), ( 'BlocklistTestAdapter', - [BLOCKLISTED_UUID, 'device_information', 'generic_access', - 'heart_rate', 'human_interface_device'], + [ + BLOCKLISTED_UUID, 'device_information', 'generic_access', + 'heart_rate', 'human_interface_device' + ], ), ( 'FailingGATTOperationsAdapter', [GATT_ERROR_UUID], ), - ( - 'DelayedServicesDiscoveryAdapter', - ['heart_rate'] - ), + ('DelayedServicesDiscoveryAdapter', ['heart_rate']), ] ADAPTERS_WITH_CHARACTERISTICS = [ @@ -186,19 +186,20 @@ 'TwoHeartRateServicesAdapter', [HEART_RATE_SERVICE], ), - ( - 'DisconnectingHeartRateAdapter', - [GENERIC_ACCESS_SERVICE, HEART_RATE_SERVICE, - (DISCONNECTION_UUID, ['01d7d88a-7451-419f-aeb8-d65e7b9277af'])] - ), - ( - 'BlocklistTestAdapter', - [GENERIC_ACCESS_SERVICE, HEART_RATE_SERVICE, ( - BLOCKLISTED_UUID, ['bad1c9a2-9a5b-4015-8b60-1579bbbf2135'], + ('DisconnectingHeartRateAdapter', [ + GENERIC_ACCESS_SERVICE, HEART_RATE_SERVICE, + (DISCONNECTION_UUID, ['01d7d88a-7451-419f-aeb8-d65e7b9277af']) + ]), + ('BlocklistTestAdapter', [ + GENERIC_ACCESS_SERVICE, HEART_RATE_SERVICE, + ( + BLOCKLISTED_UUID, + ['bad1c9a2-9a5b-4015-8b60-1579bbbf2135'], ), ( - 'device_information', ['serial_number_string'], - )] - ), + 'device_information', + ['serial_number_string'], + ) + ]), ( 'FailingGATTOperationsAdapter', [(GATT_ERROR_UUID, [ diff --git a/third_party/blink/renderer/platform/PRESUBMIT.py b/third_party/blink/renderer/platform/PRESUBMIT.py index e053782b759baf..fe39215b5b2a3b 100644 --- a/third_party/blink/renderer/platform/PRESUBMIT.py +++ b/third_party/blink/renderer/platform/PRESUBMIT.py @@ -1,7 +1,6 @@ # Copyright 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. - """Presubmit script for changes affecting Source/platform. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts @@ -42,9 +41,12 @@ def _CheckRuntimeEnabledFeaturesSorted(input_api, output_api): # Diff the sorted/unsorted versions. differ = difflib.Differ() diff = differ.compare(features, features_sorted) - return [output_api.PresubmitError( - 'runtime_enabled_features.json5 features must be sorted alphabetically. ' - 'Diff of feature order follows:', long_text='\n'.join(diff))] + return [ + output_api.PresubmitError( + 'runtime_enabled_features.json5 features must be sorted alphabetically. ' + 'Diff of feature order follows:', + long_text='\n'.join(diff)) + ] def _CommonChecks(input_api, output_api):