From d01648d637a350af0cb81470f956cc5edd18a9a4 Mon Sep 17 00:00:00 2001 From: Kagami Sascha Rosylight Date: Sun, 21 Jun 2020 03:34:22 +0200 Subject: [PATCH] Fix remaining flake8 warnings --- .../net/tests/cookie_http_state_utils.py | 1 + .../dom/bindings/codegen/CodegenRust.py | 337 +++++++++--------- .../dom/bindings/codegen/Configuration.py | 77 ++-- components/style/properties/data.py | 10 +- etc/ci/check_dynamic_symbols.py | 2 +- etc/ci/performance/gecko_driver.py | 78 ++-- etc/ci/performance/runner.py | 10 +- etc/ci/performance/submit_to_perfherder.py | 4 +- etc/ci/performance/test_differ.py | 1 + .../performance/test_submit_to_perfherder.py | 4 +- etc/servo_automation_screenshot.py | 6 +- etc/servo_gdb.py | 1 + etc/taskcluster/mock.py | 7 +- etc/wpt-summarize.py | 12 +- etc/wpt-timing.py | 1 + python/mach_bootstrap.py | 4 +- python/servo/bootstrap_commands.py | 8 +- python/servo/devenv_commands.py | 4 +- python/servo/mutation/mutator.py | 4 +- python/servo/package_commands.py | 22 +- python/servo/post_build_commands.py | 8 +- python/servo/testing_commands.py | 4 +- tests/dromaeo/run_dromaeo.py | 14 +- tests/jquery/run_jquery.py | 3 +- tests/power/PowerMeasure.py | 9 +- tests/wpt/grouping_formatter.py | 4 +- tests/wpt/run.py | 6 +- tests/wpt/update.py | 5 +- 28 files changed, 332 insertions(+), 314 deletions(-) diff --git a/components/net/tests/cookie_http_state_utils.py b/components/net/tests/cookie_http_state_utils.py index 9e5995d63932..30ee99f7f86b 100644 --- a/components/net/tests/cookie_http_state_utils.py +++ b/components/net/tests/cookie_http_state_utils.py @@ -170,5 +170,6 @@ def update_test_file(cachedir): return 0 + if __name__ == "__main__": update_test_file(tempfile.gettempdir()) diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 1f0e09639c87..610da4abdbd4 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -359,17 +359,17 @@ def pickFirstSignature(condition, filterLambda): # First check for null or undefined pickFirstSignature("%s.get().is_null_or_undefined()" % distinguishingArg, - lambda s: (s[1][distinguishingIndex].type.nullable() or - s[1][distinguishingIndex].type.isDictionary())) + lambda s: (s[1][distinguishingIndex].type.nullable() + or s[1][distinguishingIndex].type.isDictionary())) # Now check for distinguishingArg being an object that implements a # non-callback interface. That includes typed arrays and # arraybuffers. interfacesSigs = [ s for s in possibleSignatures - if (s[1][distinguishingIndex].type.isObject() or - s[1][distinguishingIndex].type.isUnion() or - s[1][distinguishingIndex].type.isNonCallbackInterface())] + if (s[1][distinguishingIndex].type.isObject() + or s[1][distinguishingIndex].type.isUnion() + or s[1][distinguishingIndex].type.isNonCallbackInterface())] # There might be more than one of these; we need to check # which ones we unwrap to. @@ -424,24 +424,24 @@ def pickFirstSignature(condition, filterLambda): pickFirstSignature("%s.get().is_object() && is_array_like(*cx, %s)" % (distinguishingArg, distinguishingArg), lambda s: - (s[1][distinguishingIndex].type.isSequence() or - s[1][distinguishingIndex].type.isObject())) + (s[1][distinguishingIndex].type.isSequence() + or s[1][distinguishingIndex].type.isObject())) # Check for vanilla JS objects # XXXbz Do we need to worry about security wrappers? pickFirstSignature("%s.get().is_object()" % distinguishingArg, - lambda s: (s[1][distinguishingIndex].type.isCallback() or - s[1][distinguishingIndex].type.isCallbackInterface() or - s[1][distinguishingIndex].type.isDictionary() or - s[1][distinguishingIndex].type.isObject())) + lambda s: (s[1][distinguishingIndex].type.isCallback() + or s[1][distinguishingIndex].type.isCallbackInterface() + or s[1][distinguishingIndex].type.isDictionary() + or s[1][distinguishingIndex].type.isObject())) # The remaining cases are mutually exclusive. The # pickFirstSignature calls are what change caseBody # Check for strings or enums if pickFirstSignature(None, - lambda s: (s[1][distinguishingIndex].type.isString() or - s[1][distinguishingIndex].type.isEnum())): + lambda s: (s[1][distinguishingIndex].type.isString() + or s[1][distinguishingIndex].type.isEnum())): pass # Check for primitives elif pickFirstSignature(None, @@ -482,9 +482,9 @@ def define(self): def dictionaryHasSequenceMember(dictionary): return (any(typeIsSequenceOrHasSequenceMember(m.type) for m in - dictionary.members) or - (dictionary.parent and - dictionaryHasSequenceMember(dictionary.parent))) + dictionary.members) + or (dictionary.parent + and dictionaryHasSequenceMember(dictionary.parent))) def typeIsSequenceOrHasSequenceMember(type): @@ -618,22 +618,22 @@ def firstCap(string): def onFailureNotAnObject(failureCode): return CGWrapper( CGGeneric( - failureCode or - ('throw_type_error(*cx, "%s is not an object.");\n' - '%s' % (firstCap(sourceDescription), exceptionCode))), + failureCode + or ('throw_type_error(*cx, "%s is not an object.");\n' + '%s' % (firstCap(sourceDescription), exceptionCode))), post="\n") def onFailureInvalidEnumValue(failureCode, passedVarName): return CGGeneric( - failureCode or - ('throw_type_error(*cx, &format!("\'{}\' is not a valid enum value for enumeration \'%s\'.", %s)); %s' - % (type.name, passedVarName, exceptionCode))) + failureCode + or ('throw_type_error(*cx, &format!("\'{}\' is not a valid enum value for enumeration \'%s\'.", %s)); %s' + % (type.name, passedVarName, exceptionCode))) def onFailureNotCallable(failureCode): return CGGeneric( - failureCode or - ('throw_type_error(*cx, \"%s is not callable.\");\n' - '%s' % (firstCap(sourceDescription), exceptionCode))) + failureCode + or ('throw_type_error(*cx, \"%s is not callable.\");\n' + '%s' % (firstCap(sourceDescription), exceptionCode))) # A helper function for handling default values. def handleDefault(nullValue): @@ -660,16 +660,16 @@ def wrapObjectTemplate(templateBody, nullValue, isDefinitelyObject, type, # Handle the non-object cases by wrapping up the whole # thing in an if cascade. templateBody = ( - "if ${val}.get().is_object() {\n" + - CGIndenter(CGGeneric(templateBody)).define() + "\n") + "if ${val}.get().is_object() {\n" + + CGIndenter(CGGeneric(templateBody)).define() + "\n") if type.nullable(): templateBody += ( "} else if ${val}.get().is_null_or_undefined() {\n" " %s\n") % nullValue templateBody += ( - "} else {\n" + - CGIndenter(onFailureNotAnObject(failureCode)).define() + - "}") + "} else {\n" + + CGIndenter(onFailureNotAnObject(failureCode)).define() + + "}") return templateBody assert not (isEnforceRange and isClamp) # These are mutually exclusive @@ -713,9 +713,9 @@ def wrapObjectTemplate(templateBody, nullValue, isDefinitelyObject, type, for memberType in type.unroll().flatMemberTypes if memberType.isDictionary() ] - if (defaultValue and - not isinstance(defaultValue, IDLNullValue) and - not isinstance(defaultValue, IDLDefaultDictionaryValue)): + if (defaultValue + and not isinstance(defaultValue, IDLNullValue) + and not isinstance(defaultValue, IDLDefaultDictionaryValue)): tag = defaultValue.type.tag() if tag is IDLType.Tags.bool: default = "%s::Boolean(%s)" % ( @@ -1626,13 +1626,13 @@ def generateGuardedArray(self, array, name, specTemplate, specTerminator, prefableSpecs.append( prefableTemplate % (cond, name + "_specs", len(specs) - 1)) - specsArray = ("const %s_specs: &'static [&'static[%s]] = &[\n" + - ",\n".join(specs) + "\n" + - "];\n") % (name, specType) + specsArray = ("const %s_specs: &'static [&'static[%s]] = &[\n" + + ",\n".join(specs) + "\n" + + "];\n") % (name, specType) - prefArray = ("const %s: &'static [Guard<&'static [%s]>] = &[\n" + - ",\n".join(prefableSpecs) + "\n" + - "];\n") % (name, specType) + prefArray = ("const %s: &'static [Guard<&'static [%s]>] = &[\n" + + ",\n".join(prefableSpecs) + "\n" + + "];\n") % (name, specType) return specsArray + prefArray @@ -1660,9 +1660,9 @@ def __init__(self, descriptor, name, static, unforgeable): # Ignore non-static methods for callback interfaces if not descriptor.interface.isCallback() or static: methods = [m for m in descriptor.interface.members if - m.isMethod() and m.isStatic() == static and - not m.isIdentifierLess() and - MemberIsUnforgeable(m, descriptor) == unforgeable] + m.isMethod() and m.isStatic() == static + and not m.isIdentifierLess() + and MemberIsUnforgeable(m, descriptor) == unforgeable] else: methods = [] self.regular = [{"name": m.identifier.name, @@ -1683,10 +1683,10 @@ def __init__(self, descriptor, name, static, unforgeable): # Generate the keys/values/entries aliases for value iterables. maplikeOrSetlikeOrIterable = descriptor.interface.maplikeOrSetlikeOrIterable - if (not static and not unforgeable and - (maplikeOrSetlikeOrIterable and - maplikeOrSetlikeOrIterable.isIterable() and - maplikeOrSetlikeOrIterable.isValueIterator())): + if (not static and not unforgeable + and maplikeOrSetlikeOrIterable + and maplikeOrSetlikeOrIterable.isIterable() + and maplikeOrSetlikeOrIterable.isValueIterator()): m = maplikeOrSetlikeOrIterable # Add our keys/values/entries/forEach @@ -1805,8 +1805,8 @@ def __init__(self, descriptor, name, static, unforgeable): self.regular = [ m for m in descriptor.interface.members if - m.isAttr() and m.isStatic() == static and - MemberIsUnforgeable(m, descriptor) == unforgeable + m.isAttr() and m.isStatic() == static + and MemberIsUnforgeable(m, descriptor) == unforgeable ] self.static = static self.unforgeable = unforgeable @@ -1902,6 +1902,7 @@ def specData(const): 'ConstantSpec', PropertyDefiner.getControllingCondition, specData) + # We'll want to insert the indent at the beginnings of lines, but we # don't want to indent empty lines. So only indent lines that have a # non-newline character on them. @@ -2003,8 +2004,8 @@ def componentTypes(type): def isImportable(type): if not type.isType(): - assert (type.isInterface() or type.isDictionary() or - type.isEnum() or type.isNamespace()) + assert (type.isInterface() or type.isDictionary() + or type.isEnum() or type.isNamespace()) return True return not (type.builtin or type.isSequence() or type.isUnion()) @@ -2878,8 +2879,8 @@ def __init__(self, descriptor): def define(self): interface = self.descriptor.interface name = self.descriptor.concreteType - if (interface.getUserData("hasConcreteDescendant", False) or - interface.getUserData("hasProxyDescendant", False)): + if (interface.getUserData("hasConcreteDescendant", False) + or interface.getUserData("hasProxyDescendant", False)): depth = self.descriptor.prototypeDepth check = "class.interface_chain[%s] == PrototypeList::ID::%s" % (depth, name) elif self.descriptor.proxy: @@ -3466,9 +3467,9 @@ def definition_body(self): def needCx(returnType, arguments, considerTypes): - return (considerTypes and - (typeNeedsCx(returnType, True) or - any(typeNeedsCx(a.type) for a in arguments))) + return (considerTypes + and (typeNeedsCx(returnType, True) + or any(typeNeedsCx(a.type) for a in arguments))) class CGCallGenerator(CGThing): @@ -3775,10 +3776,10 @@ def definition_body(self): self.method) return CGWrapper(CGMethodCall([], nativeName, self.method.isStatic(), self.descriptor, self.method), - pre="let cx = SafeJSContext::from_ptr(cx);\n" + - ("let this = &*(this as *const %s);\n" % self.descriptor.concreteType) + - "let args = &*args;\n" - "let argc = args.argc_;\n") + pre="let cx = SafeJSContext::from_ptr(cx);\n" + + ("let this = &*(this as *const %s);\n" % self.descriptor.concreteType) + + "let args = &*args;\n" + "let argc = args.argc_;\n") @staticmethod def makeNativeName(descriptor, method): @@ -3868,8 +3869,8 @@ def definition_body(self): return CGWrapper(CGGetterCall([], self.attr.type, nativeName, self.descriptor, self.attr), - pre="let cx = SafeJSContext::from_ptr(cx);\n" + - ("let this = &*(this as *const %s);\n" % self.descriptor.concreteType)) + pre="let cx = SafeJSContext::from_ptr(cx);\n" + + ("let this = &*(this as *const %s);\n" % self.descriptor.concreteType)) @staticmethod def makeNativeName(descriptor, attr): @@ -3924,8 +3925,8 @@ def definition_body(self): self.attr) return CGWrapper(CGSetterCall([], self.attr.type, nativeName, self.descriptor, self.attr), - pre="let cx = SafeJSContext::from_ptr(cx);\n" + - ("let this = &*(this as *const %s);\n" % self.descriptor.concreteType)) + pre="let cx = SafeJSContext::from_ptr(cx);\n" + + ("let this = &*(this as *const %s);\n" % self.descriptor.concreteType)) @staticmethod def makeNativeName(descriptor, attr): @@ -4191,8 +4192,8 @@ def mayBeMovable(self): # don't want them coalesced with each other or loop-hoisted, since # their return value can change even if nothing is going on from our # point of view. - return (affects == "Nothing" and - (dependsOn != "Everything" and dependsOn != "DeviceState")) + return (affects == "Nothing" + and (dependsOn != "Everything" and dependsOn != "DeviceState")) def aliasSet(self): """Returns the alias set to store in the jitinfo. This may not be the @@ -4282,10 +4283,10 @@ def getSingleReturnType(existingType, t): if type == existingType: return existingType - if ((type == "JSVAL_TYPE_DOUBLE" and - existingType == "JSVAL_TYPE_INT32") or - (existingType == "JSVAL_TYPE_DOUBLE" and - type == "JSVAL_TYPE_INT32")): + if ((type == "JSVAL_TYPE_DOUBLE" + and existingType == "JSVAL_TYPE_INT32") + or (existingType == "JSVAL_TYPE_DOUBLE" + and type == "JSVAL_TYPE_INT32")): # Promote INT32 to DOUBLE as needed return "JSVAL_TYPE_DOUBLE" # Different types @@ -5206,8 +5207,8 @@ def define(self): argName = self.arguments[0].identifier.name return ("let %s = jsid_to_string(*cx, Handle::from_raw(id)).expect(\"Not a string-convertible JSID?\");\n" "let this = UnwrapProxy(proxy);\n" - "let this = &*this;\n" % argName + - CGProxySpecialOperation.define(self)) + "let this = &*this;\n" % argName + + CGProxySpecialOperation.define(self)) class CGProxyNamedGetter(CGProxyNamedOperation): @@ -5288,11 +5289,11 @@ def getBody(self): 'successCode': fillDescriptor, 'pre': 'rooted!(in(*cx) let mut result_root = UndefinedValue());' } - get += ("if let Some(index) = index {\n" + - " let this = UnwrapProxy(proxy);\n" + - " let this = &*this;\n" + - CGIndenter(CGProxyIndexedGetter(self.descriptor, templateValues)).define() + "\n" + - "}\n") + get += ("if let Some(index) = index {\n" + + " let this = UnwrapProxy(proxy);\n" + + " let this = &*this;\n" + + CGIndenter(CGProxyIndexedGetter(self.descriptor, templateValues)).define() + "\n" + + "}\n") namedGetter = self.descriptor.operations['NamedGetter'] if namedGetter: @@ -5373,16 +5374,16 @@ def getBody(self): indexedSetter = self.descriptor.operations['IndexedSetter'] if indexedSetter: - set += ("let index = get_array_index_from_id(*cx, Handle::from_raw(id));\n" + - "if let Some(index) = index {\n" + - " let this = UnwrapProxy(proxy);\n" + - " let this = &*this;\n" + - CGIndenter(CGProxyIndexedSetter(self.descriptor)).define() + - " return (*opresult).succeed();\n" + - "}\n") + set += ("let index = get_array_index_from_id(*cx, Handle::from_raw(id));\n" + + "if let Some(index) = index {\n" + + " let this = UnwrapProxy(proxy);\n" + + " let this = &*this;\n" + + CGIndenter(CGProxyIndexedSetter(self.descriptor)).define() + + " return (*opresult).succeed();\n" + + "}\n") elif self.descriptor.operations['IndexedGetter']: - set += ("if get_array_index_from_id(*cx, Handle::from_raw(id)).is_some() {\n" + - " return (*opresult).failNoIndexedSetter();\n" + + set += ("if get_array_index_from_id(*cx, Handle::from_raw(id)).is_some() {\n" + " return (*opresult).failNoIndexedSetter();\n" "}\n") namedSetter = self.descriptor.operations['NamedSetter'] @@ -5390,17 +5391,17 @@ def getBody(self): if self.descriptor.hasUnforgeableMembers: raise TypeError("Can't handle a named setter on an interface that has " "unforgeables. Figure out how that should work!") - set += ("if RUST_JSID_IS_STRING(id) || RUST_JSID_IS_INT(id) {\n" + - CGIndenter(CGProxyNamedSetter(self.descriptor)).define() + - " return (*opresult).succeed();\n" + - "}\n") + set += ("if RUST_JSID_IS_STRING(id) || RUST_JSID_IS_INT(id) {\n" + + CGIndenter(CGProxyNamedSetter(self.descriptor)).define() + + " return (*opresult).succeed();\n" + + "}\n") elif self.descriptor.operations['NamedGetter']: - set += ("if RUST_JSID_IS_STRING(id) || RUST_JSID_IS_INT(id) {\n" + - CGIndenter(CGProxyNamedGetter(self.descriptor)).define() + - " if result.is_some() {\n" - " return (*opresult).failNoNamedSetter();\n" - " }\n" - "}\n") + set += ("if RUST_JSID_IS_STRING(id) || RUST_JSID_IS_INT(id) {\n" + + CGIndenter(CGProxyNamedGetter(self.descriptor)).define() + + " if result.is_some() {\n" + " return (*opresult).failNoNamedSetter();\n" + " }\n" + "}\n") set += "return proxyhandler::define_property(*cx, %s);" % ", ".join(a.name for a in self.args[1:]) return set @@ -5488,8 +5489,8 @@ def definition_body(self): class CGDOMJSProxyHandler_getOwnEnumerablePropertyKeys(CGAbstractExternMethod): def __init__(self, descriptor): - assert (descriptor.operations["IndexedGetter"] and - descriptor.interface.getExtendedAttribute("LegacyUnenumerableNamedProperties")) + assert (descriptor.operations["IndexedGetter"] + and descriptor.interface.getExtendedAttribute("LegacyUnenumerableNamedProperties")) args = [Argument('*mut JSContext', 'cx'), Argument('RawHandleObject', 'proxy'), Argument('RawMutableHandleIdVector', 'props')] @@ -5543,14 +5544,14 @@ def getBody(self): indexedGetter = self.descriptor.operations['IndexedGetter'] indexed = "let cx = SafeJSContext::from_ptr(cx);\n" if indexedGetter: - indexed += ("let index = get_array_index_from_id(*cx, Handle::from_raw(id));\n" + - "if let Some(index) = index {\n" + - " let this = UnwrapProxy(proxy);\n" + - " let this = &*this;\n" + - CGIndenter(CGProxyIndexedGetter(self.descriptor)).define() + "\n" + - " *bp = result.is_some();\n" + - " return true;\n" + - "}\n\n") + indexed += ("let index = get_array_index_from_id(*cx, Handle::from_raw(id));\n" + + "if let Some(index) = index {\n" + + " let this = UnwrapProxy(proxy);\n" + + " let this = &*this;\n" + + CGIndenter(CGProxyIndexedGetter(self.descriptor)).define() + "\n" + + " *bp = result.is_some();\n" + + " return true;\n" + + "}\n\n") namedGetter = self.descriptor.operations['NamedGetter'] condition = "RUST_JSID_IS_STRING(id) || RUST_JSID_IS_INT(id)" @@ -5624,11 +5625,11 @@ def getBody(self): indexedGetter = self.descriptor.operations['IndexedGetter'] if indexedGetter: - getIndexedOrExpando = ("let index = get_array_index_from_id(*cx, id_lt);\n" + - "if let Some(index) = index {\n" + - " let this = UnwrapProxy(proxy);\n" + - " let this = &*this;\n" + - CGIndenter(CGProxyIndexedGetter(self.descriptor, templateValues)).define()) + getIndexedOrExpando = ("let index = get_array_index_from_id(*cx, id_lt);\n" + + "if let Some(index) = index {\n" + + " let this = UnwrapProxy(proxy);\n" + + " let this = &*this;\n" + + CGIndenter(CGProxyIndexedGetter(self.descriptor, templateValues)).define()) getIndexedOrExpando += """\ // Even if we don't have this index, we don't forward the // get on to our expando object. @@ -5648,9 +5649,9 @@ def getBody(self): # 3. Set ignoreNamedProps to true. if indexedGetter: condition = "index.is_none() && (%s)" % condition - getNamed = ("if %s {\n" + - CGIndenter(CGProxyNamedGetter(self.descriptor, templateValues)).define() + - "}\n") % condition + getNamed = ("if %s {\n" + + CGIndenter(CGProxyNamedGetter(self.descriptor, templateValues)).define() + + "}\n") % condition else: getNamed = "" @@ -5852,10 +5853,10 @@ def attribute_arguments(needCx, argument=None, inRealm=False): def members(): for m in descriptor.interface.members: - if (m.isMethod() and not m.isStatic() and - not m.isMaplikeOrSetlikeOrIterableMethod() and - (not m.isIdentifierLess() or (m.isStringifier() and not m.underlyingAttr)) and - not m.isDefaultToJSON()): + if (m.isMethod() and not m.isStatic() + and not m.isMaplikeOrSetlikeOrIterableMethod() + and (not m.isIdentifierLess() or (m.isStringifier() and not m.underlyingAttr)) + and not m.isDefaultToJSON()): name = CGSpecializedMethod.makeNativeName(descriptor, m) infallible = 'infallible' in descriptor.getExtendedAttributes(m) for idx, (rettype, arguments) in enumerate(m.signatures()): @@ -6254,8 +6255,8 @@ def reexportedName(name): defaultToJSONMethod = None unscopableNames = [] for m in descriptor.interface.members: - if (m.isMethod() and - (not m.isIdentifierLess() or m == descriptor.operations["Stringifier"])): + if (m.isMethod() + and (not m.isIdentifierLess() or m == descriptor.operations["Stringifier"])): if m.getExtendedAttribute("Unscopable"): assert not m.isStatic() unscopableNames.append(m.identifier.name) @@ -6506,14 +6507,14 @@ def struct(self): return (string.Template( "#[derive(${derive})]\n" - "${mustRoot}" + - "pub struct ${selfName} {\n" + - "${inheritance}" + - "\n".join(memberDecls) + "\n" + - "}").substitute({"selfName": self.makeClassName(d), - "inheritance": inheritance, - "mustRoot": mustRoot, - "derive": ', '.join(derive)})) + + "${mustRoot}" + + "pub struct ${selfName} {\n" + + "${inheritance}" + + "\n".join(memberDecls) + "\n" + + "}").substitute({"selfName": self.makeClassName(d), + "inheritance": inheritance, + "mustRoot": mustRoot, + "derive": ', '.join(derive)})) def impl(self): d = self.dictionary @@ -6769,15 +6770,15 @@ def __init__(self, config): descriptors = config.getDescriptors(proxy=True) self.root = CGList([ CGGeneric( - "#[allow(non_upper_case_globals)]\n" + - "pub mod proxy_handlers {\n" + + "#[allow(non_upper_case_globals)]\n" + "pub mod proxy_handlers {\n" "".join( " pub static %s: std::sync::atomic::AtomicPtr =\n" " std::sync::atomic::AtomicPtr::new(std::ptr::null_mut());\n" % desc.name for desc in descriptors - ) + - "}\n" + ) + + "}\n" ), CGRegisterProxyHandlersMethod(descriptors), ], "\n") @@ -7004,8 +7005,8 @@ def __init__(self, descriptorProvider, member, name, signature, extendedAttrs, static=member.isStatic(), # Mark our getters, which are attrs that # have a non-void return type, as const. - const=(not member.isStatic() and member.isAttr() and - not signature[0].isVoid()), + const=(not member.isStatic() and member.isAttr() + and not signature[0].isVoid()), breakAfterSelf=breakAfterSelf, unsafe=unsafe, visibility=visibility) @@ -7087,23 +7088,23 @@ def getMethodImpls(self, method): setupCall = "let s = CallSetup::new(self, aExceptionHandling);\n" bodyWithThis = string.Template( - setupCall + - "rooted!(in(*s.get_context()) let mut thisObjJS = ptr::null_mut::());\n" - "wrap_call_this_object(s.get_context(), thisObj, thisObjJS.handle_mut());\n" - "if thisObjJS.is_null() {\n" - " return Err(JSFailed);\n" - "}\n" - "unsafe { ${methodName}(${callArgs}) }").substitute({ - "callArgs": ", ".join(argnamesWithThis), - "methodName": 'self.' + method.name, - }) + setupCall + + "rooted!(in(*s.get_context()) let mut thisObjJS = ptr::null_mut::());\n" + "wrap_call_this_object(s.get_context(), thisObj, thisObjJS.handle_mut());\n" + "if thisObjJS.is_null() {\n" + " return Err(JSFailed);\n" + "}\n" + "unsafe { ${methodName}(${callArgs}) }").substitute({ + "callArgs": ", ".join(argnamesWithThis), + "methodName": 'self.' + method.name, + }) bodyWithoutThis = string.Template( - setupCall + - "rooted!(in(*s.get_context()) let thisObjJS = ptr::null_mut::());\n" - "unsafe { ${methodName}(${callArgs}) }").substitute({ - "callArgs": ", ".join(argnamesWithoutThis), - "methodName": 'self.' + method.name, - }) + setupCall + + "rooted!(in(*s.get_context()) let thisObjJS = ptr::null_mut::());\n" + "unsafe { ${methodName}(${callArgs}) }").substitute({ + "callArgs": ", ".join(argnamesWithoutThis), + "methodName": 'self.' + method.name, + }) return [ClassMethod(method.name + '_', method.returnType, args, bodyInHeader=True, templateArgs=["T: DomObject"], @@ -7314,28 +7315,28 @@ def getArgConversion(self, i, arg): conversion = wrapForType( "argv_root.handle_mut()", result=argval, - successCode=("{\n" + - "let arg = &mut argv[%s];\n" + - "*arg = Heap::default();\n" + - "arg.set(argv_root.get());\n" + + successCode=("{\n" + "let arg = &mut argv[%s];\n" + "*arg = Heap::default();\n" + "arg.set(argv_root.get());\n" "}") % jsvalIndex, pre="rooted!(in(*cx) let mut argv_root = UndefinedValue());") if arg.variadic: conversion = string.Template( - "for idx in 0..${arg}.len() {\n" + - CGIndenter(CGGeneric(conversion)).define() + "\n" - "}" + "for idx in 0..${arg}.len() {\n" + + CGIndenter(CGGeneric(conversion)).define() + "\n" + + "}" ).substitute({"arg": arg.identifier.name}) elif arg.optional and not arg.defaultValue: conversion = ( CGIfWrapper("%s.is_some()" % arg.identifier.name, - CGGeneric(conversion)).define() + - " else if argc == %d {\n" - " // This is our current trailing argument; reduce argc\n" - " argc -= 1;\n" - "} else {\n" - " argv[%d] = Heap::default();\n" - "}" % (i + 1, i)) + CGGeneric(conversion)).define() + + " else if argc == %d {\n" + " // This is our current trailing argument; reduce argc\n" + " argc -= 1;\n" + "} else {\n" + " argv[%d] = Heap::default();\n" + "}" % (i + 1, i)) return conversion def getArgs(self, returnType, argList): @@ -7464,8 +7465,8 @@ def getCallableDecl(self): return 'rooted!(in(*cx) let callable =\n' + getCallableFromProp + ');\n' return ( 'let isCallable = IsCallable(self.callback());\n' - 'rooted!(in(*cx) let callable =\n' + - CGIndenter( + 'rooted!(in(*cx) let callable =\n' + + CGIndenter( CGIfElseWrapper('isCallable', CGGeneric('ObjectValue(self.callback())'), CGGeneric(getCallableFromProp))).define() + ');\n') @@ -7676,9 +7677,9 @@ def leafModule(d): return getModuleFromObject(d).split('::')[-1] descriptors = config.getDescriptors(register=True, isIteratorInterface=False) - descriptors = (set(toBindingNamespace(d.name) for d in descriptors) | - set(leafModule(d) for d in config.callbacks) | - set(leafModule(d) for d in config.getDictionaries())) + descriptors = (set(toBindingNamespace(d.name) for d in descriptors) + | set(leafModule(d) for d in config.callbacks) + | set(leafModule(d) for d in config.getDictionaries())) curr = CGList([CGGeneric("pub mod %s;\n" % name) for name in sorted(descriptors)]) curr = CGWrapper(curr, pre=AUTOGENERATED_WARNING_COMMENT) return curr diff --git a/components/script/dom/bindings/codegen/Configuration.py b/components/script/dom/bindings/codegen/Configuration.py index b3e1e0c8289d..98fce57afe47 100644 --- a/components/script/dom/bindings/codegen/Configuration.py +++ b/components/script/dom/bindings/codegen/Configuration.py @@ -63,7 +63,8 @@ def __init__(self, filename, parseData): c.isCallback() and not c.isInterface()] # Keep the descriptor list sorted for determinism. - cmp = lambda x, y: (x > y) - (x < y) + def cmp(x, y): + return (x > y) - (x < y) self.descriptors.sort(key=functools.cmp_to_key(lambda x, y: cmp(x.name, y.name))) def getInterface(self, ifname): @@ -74,25 +75,35 @@ def getDescriptors(self, **filters): curr = self.descriptors for key, val in filters.iteritems(): if key == 'webIDLFile': - getter = lambda x: x.interface.filename() + def getter(x): + return x.interface.filename() elif key == 'hasInterfaceObject': - getter = lambda x: x.interface.hasInterfaceObject() + def getter(x): + return x.interface.hasInterfaceObject() elif key == 'isCallback': - getter = lambda x: x.interface.isCallback() + def getter(x): + return x.interface.isCallback() elif key == 'isNamespace': - getter = lambda x: x.interface.isNamespace() + def getter(x): + return x.interface.isNamespace() elif key == 'isJSImplemented': - getter = lambda x: x.interface.isJSImplemented() + def getter(x): + return x.interface.isJSImplemented() elif key == 'isGlobal': - getter = lambda x: x.isGlobal() + def getter(x): + return x.isGlobal() elif key == 'isInline': - getter = lambda x: x.interface.getExtendedAttribute('Inline') is not None + def getter(x): + return x.interface.getExtendedAttribute('Inline') is not None elif key == 'isExposedConditionally': - getter = lambda x: x.interface.isExposedConditionally() + def getter(x): + return x.interface.isExposedConditionally() elif key == 'isIteratorInterface': - getter = lambda x: x.interface.isIteratorInterface() + def getter(x): + return x.interface.isIteratorInterface() else: - getter = lambda x: getattr(x, key) + def getter(x): + return getattr(x, key) curr = filter(lambda x: getter(x) == val, curr) return curr @@ -125,8 +136,8 @@ def getDescriptor(self, interfaceName): # We should have exactly one result. if len(descriptors) != 1: - raise NoSuchDescriptorError("For " + interfaceName + " found " + - str(len(descriptors)) + " matches") + raise NoSuchDescriptorError("For " + interfaceName + " found " + + str(len(descriptors)) + " matches") return descriptors[0] def getDescriptorProvider(self): @@ -157,10 +168,10 @@ def getDescriptor(self, interfaceName): def MemberIsUnforgeable(member, descriptor): - return ((member.isAttr() or member.isMethod()) and - not member.isStatic() and - (member.isUnforgeable() or - bool(descriptor.interface.getExtendedAttribute("Unforgeable")))) + return ((member.isAttr() or member.isMethod()) + and not member.isStatic() + and (member.isUnforgeable() + or bool(descriptor.interface.getExtendedAttribute("Unforgeable")))) class Descriptor(DescriptorProvider): @@ -228,14 +239,14 @@ def __init__(self, config, interface, desc): # If we're concrete, we need to crawl our ancestor interfaces and mark # them as having a concrete descendant. - self.concrete = (not self.interface.isCallback() and - not self.interface.isNamespace() and - not self.interface.getExtendedAttribute("Abstract") and - not self.interface.getExtendedAttribute("Inline") and - not spiderMonkeyInterface) - self.hasUnforgeableMembers = (self.concrete and - any(MemberIsUnforgeable(m, self) for m in - self.interface.members)) + self.concrete = (not self.interface.isCallback() + and not self.interface.isNamespace() + and not self.interface.getExtendedAttribute("Abstract") + and not self.interface.getExtendedAttribute("Inline") + and not spiderMonkeyInterface) + self.hasUnforgeableMembers = (self.concrete + and any(MemberIsUnforgeable(m, self) for m in + self.interface.members)) self.operations = { 'IndexedGetter': None, @@ -391,8 +402,8 @@ def getParentName(self): return None def hasDescendants(self): - return (self.interface.getUserData("hasConcreteDescendant", False) or - self.interface.getUserData("hasProxyDescendant", False)) + return (self.interface.getUserData("hasConcreteDescendant", False) + or self.interface.getUserData("hasProxyDescendant", False)) def hasHTMLConstructor(self): ctor = self.interface.ctor() @@ -402,8 +413,8 @@ def shouldHaveGetConstructorObjectMethod(self): assert self.interface.hasInterfaceObject() if self.interface.getExtendedAttribute("Inline"): return False - return (self.interface.isCallback() or self.interface.isNamespace() or - self.hasDescendants() or self.hasHTMLConstructor()) + return (self.interface.isCallback() or self.interface.isNamespace() + or self.hasDescendants() or self.hasHTMLConstructor()) def shouldCacheConstructor(self): return self.hasDescendants() or self.hasHTMLConstructor() @@ -416,8 +427,8 @@ def isGlobal(self): Returns true if this is the primary interface for a global object of some sort. """ - return bool(self.interface.getExtendedAttribute("Global") or - self.interface.getExtendedAttribute("PrimaryGlobal")) + return bool(self.interface.getExtendedAttribute("Global") + or self.interface.getExtendedAttribute("PrimaryGlobal")) # Some utility methods @@ -428,8 +439,8 @@ def MakeNativeName(name): def getModuleFromObject(object): - return ('crate::dom::bindings::codegen::Bindings::' + - os.path.basename(object.location.filename()).split('.webidl')[0] + 'Binding') + return ('crate::dom::bindings::codegen::Bindings::' + + os.path.basename(object.location.filename()).split('.webidl')[0] + 'Binding') def getTypesFromDescriptor(descriptor): diff --git a/components/style/properties/data.py b/components/style/properties/data.py index 9ab3a40ca668..718b47716636 100644 --- a/components/style/properties/data.py +++ b/components/style/properties/data.py @@ -198,11 +198,11 @@ def __init__(self, style_struct, name, spec=None, animation_value_type=None, key self.gecko_pref = gecko_pref self.has_effect_on_gecko_scrollbars = has_effect_on_gecko_scrollbars assert ( - has_effect_on_gecko_scrollbars in [None, False, True] and - not style_struct.inherited or - (gecko_pref is None) == (has_effect_on_gecko_scrollbars is None)), ( - "Property " + name + ": has_effect_on_gecko_scrollbars must be " + - "specified, and must have a value of True or False, iff a " + + has_effect_on_gecko_scrollbars in [None, False, True] + and not style_struct.inherited + or (gecko_pref is None) == (has_effect_on_gecko_scrollbars is None)), ( + "Property " + name + ": has_effect_on_gecko_scrollbars must be " + "specified, and must have a value of True or False, iff a " "property is inherited and is behind a Gecko pref") # For enabled_in, the setup is as follows: # It needs to be one of the four values: ["", "ua", "chrome", "content"] diff --git a/etc/ci/check_dynamic_symbols.py b/etc/ci/check_dynamic_symbols.py index 9bf637aa964f..9e2d8aad060b 100644 --- a/etc/ci/check_dynamic_symbols.py +++ b/etc/ci/check_dynamic_symbols.py @@ -14,7 +14,7 @@ import subprocess import sys -symbol_regex = re.compile(b"D \*UND\*\t(.*) (.*)$") +symbol_regex = re.compile(br"D \*UND\*\t(.*) (.*)$") allowed_symbols = frozenset([ b'unshare', b'malloc_usable_size', diff --git a/etc/ci/performance/gecko_driver.py b/etc/ci/performance/gecko_driver.py index 62864eda380a..b10c5432f1de 100644 --- a/etc/ci/performance/gecko_driver.py +++ b/etc/ci/performance/gecko_driver.py @@ -31,44 +31,44 @@ def create_gecko_session(): def generate_placeholder(testcase): - # We need to still include the failed tests, otherwise Treeherder will - # consider the result to be a new test series, and thus a new graph. So we - # use a placeholder with values = -1 to make Treeherder happy, and still be - # able to identify failed tests (successful tests have time >=0). - - timings = { - "testcase": testcase, - "title": "" - } - - timing_names = [ - "navigationStart", - "unloadEventStart", - "domLoading", - "fetchStart", - "responseStart", - "loadEventEnd", - "connectStart", - "domainLookupStart", - "redirectStart", - "domContentLoadedEventEnd", - "requestStart", - "secureConnectionStart", - "connectEnd", - "loadEventStart", - "domInteractive", - "domContentLoadedEventStart", - "redirectEnd", - "domainLookupEnd", - "unloadEventEnd", - "responseEnd", - "domComplete", - ] - - for name in timing_names: - timings[name] = 0 if name == "navigationStart" else -1 - - return [timings] + # We need to still include the failed tests, otherwise Treeherder will + # consider the result to be a new test series, and thus a new graph. So we + # use a placeholder with values = -1 to make Treeherder happy, and still be + # able to identify failed tests (successful tests have time >=0). + + timings = { + "testcase": testcase, + "title": "" + } + + timing_names = [ + "navigationStart", + "unloadEventStart", + "domLoading", + "fetchStart", + "responseStart", + "loadEventEnd", + "connectStart", + "domainLookupStart", + "redirectStart", + "domContentLoadedEventEnd", + "requestStart", + "secureConnectionStart", + "connectEnd", + "loadEventStart", + "domInteractive", + "domContentLoadedEventStart", + "redirectEnd", + "domainLookupEnd", + "unloadEventEnd", + "responseEnd", + "domComplete", + ] + + for name in timing_names: + timings[name] = 0 if name == "navigationStart" else -1 + + return [timings] def run_gecko_test(testcase, url, date, timeout, is_async): @@ -91,7 +91,7 @@ def run_gecko_test(testcase, url, date, timeout, is_async): "return JSON.stringify(performance.timing)" ) )) - except: + except Exception: # We need to return a timing object no matter what happened. # See the comment in generate_placeholder() for explanation print("Failed to get a valid timing measurement.") diff --git a/etc/ci/performance/runner.py b/etc/ci/performance/runner.py index 226bb506fa23..b5cdddedb303 100644 --- a/etc/ci/performance/runner.py +++ b/etc/ci/performance/runner.py @@ -116,7 +116,7 @@ def parse_block(block): for line in block: try: (_, key, value) = line.split(",") - except: + except ValueError: print("[DEBUG] failed to parse the following line:") print(line) print('[DEBUG] log:') @@ -133,10 +133,10 @@ def parse_block(block): return timing def valid_timing(timing, url=None): - if (timing is None or - testcase is None or - timing.get('title') == 'Error loading page' or - timing.get('testcase') != url): + if (timing is None + or testcase is None + or timing.get('title') == 'Error loading page' + or timing.get('testcase') != url): return False else: return True diff --git a/etc/ci/performance/submit_to_perfherder.py b/etc/ci/performance/submit_to_perfherder.py index c5d2a5fe0db6..fe1ee57f86bf 100644 --- a/etc/ci/performance/submit_to_perfherder.py +++ b/etc/ci/performance/submit_to_perfherder.py @@ -19,8 +19,8 @@ def geometric_mean(iterable): - filtered = list(filter(lambda x: x > 0, iterable)) - return (reduce(operator.mul, filtered)) ** (1.0 / len(filtered)) + filtered = list(filter(lambda x: x > 0, iterable)) + return (reduce(operator.mul, filtered)) ** (1.0 / len(filtered)) def format_testcase_name(name): diff --git a/etc/ci/performance/test_differ.py b/etc/ci/performance/test_differ.py index 16646223be97..567a46cfe61b 100644 --- a/etc/ci/performance/test_differ.py +++ b/etc/ci/performance/test_differ.py @@ -29,6 +29,7 @@ def load_data(filename): results[key] = round(totals[key] / counts[key]) return results + data1 = load_data(args.file1) data2 = load_data(args.file2) keys = set(data1.keys()).union(data2.keys()) diff --git a/etc/ci/performance/test_submit_to_perfherder.py b/etc/ci/performance/test_submit_to_perfherder.py index e19e511216b1..a23fae8a3b22 100644 --- a/etc/ci/performance/test_submit_to_perfherder.py +++ b/etc/ci/performance/test_submit_to_perfherder.py @@ -14,8 +14,8 @@ def test_format_testcase_name(): 'http://localhost:8000/page_load_test/163.com/p.mail.163.com/' 'mailinfo/shownewmsg_www_1222.htm.html'))) assert(('1234567890223456789032345678904234567890' - '5234567890623456789072345678908234567890') == - submit_to_perfherder.format_testcase_name(( + '5234567890623456789072345678908234567890') + == submit_to_perfherder.format_testcase_name(( '1234567890223456789032345678904234567890' '52345678906234567890723456789082345678909234567890'))) assert('news.ycombinator.com' == submit_to_perfherder.format_testcase_name( diff --git a/etc/servo_automation_screenshot.py b/etc/servo_automation_screenshot.py index f514536566e9..cc7b7110329c 100644 --- a/etc/servo_automation_screenshot.py +++ b/etc/servo_automation_screenshot.py @@ -10,15 +10,14 @@ """ Created on Mon Mar 26 20:08:25 2018 @author: Pranshu Sinha, Abhay Soni, Aayushi Agrawal -""" -""" The below program is intended to test rendering mismatches in servo by taking screenshots of rendered html files. Here is the breakdown of how our code works: * A session is started on localhost:7002 * The randomly generated webpage's (html files) data is sent as JSON to this session * Using curl request, we load the html files for this session ID based on the session we just created. """ + import os import json import requests @@ -72,7 +71,7 @@ def render_html_files(num_of_files, url, file_url, json_string, headers, cwd): image_file.write(base64.decodebytes(image_data_encoded.encode('utf-8'))) print("################################") print("The screenshot is stored in the location: {0}/screenshots/" - + " with filename: output_image_{1}.png".format(cwd, str(x))) + " with filename: output_image_{1}.png".format(cwd, str(x))) print("################################") @@ -124,6 +123,7 @@ def main(argv): # take inputs from command line by considering the options para # Render each HTML file and take a screenshot render_html_files(num_of_files, url, file_url, json_string, headers, cwd) + if __name__ == "__main__": if len(sys.argv) < 8: print_help() diff --git a/etc/servo_gdb.py b/etc/servo_gdb.py index 31f2a8962d92..0d535b1b2791 100644 --- a/etc/servo_gdb.py +++ b/etc/servo_gdb.py @@ -128,6 +128,7 @@ def __init__(self, val): def to_string(self): return "[UNKNOWN - type = {0}]".format(str(self.val.type)) + type_map = [ ('struct Au', AuPrinter), ('FlowFlags', BitFieldU8Printer), diff --git a/etc/taskcluster/mock.py b/etc/taskcluster/mock.py index f06f7bcb147b..37c4b9cccb62 100755 --- a/etc/taskcluster/mock.py +++ b/etc/taskcluster/mock.py @@ -13,15 +13,14 @@ python3 -m coverage run $0 python3 -m coverage report -m --fail-under 100 exit -''' -""" Run the decision task with fake Taskcluster APIs, to catch Python errors before pushing. -""" +''' import os import sys from unittest.mock import MagicMock +import decision_task class TaskclusterRestFailure(Exception): @@ -47,7 +46,7 @@ def findTask(self, path): os.environ["TASKCLUSTER_ROOT_URL"] = "https://community-tc.services.mozilla.com" os.environ["TASKCLUSTER_PROXY_URL"] = "http://taskcluster" os.environ["NEW_AMI_WORKER_TYPE"] = "-" -import decision_task + decision_task.decisionlib.subprocess = MagicMock() print("\n# Push:") diff --git a/etc/wpt-summarize.py b/etc/wpt-summarize.py index 14cf6c4067ca..2b3fb8a07169 100644 --- a/etc/wpt-summarize.py +++ b/etc/wpt-summarize.py @@ -34,13 +34,13 @@ if "action" in entry and entry["action"] == "test_end": thread = None else: - if ("action" in entry and - entry["action"] == "test_start" and - entry["test"] == sys.argv[2]): + if ("action" in entry + and entry["action"] == "test_start" + and entry["test"] == sys.argv[2]): thread = entry["thread"] print(json.dumps(entry)) - elif (full_search and - "command" in entry and - sys.argv[2] in entry["command"]): + elif (full_search + and "command" in entry + and sys.argv[2] in entry["command"]): thread = entry["thread"] print(json.dumps(entry)) diff --git a/etc/wpt-timing.py b/etc/wpt-timing.py index cc5d81aad9ad..7dc50532bf2f 100644 --- a/etc/wpt-timing.py +++ b/etc/wpt-timing.py @@ -51,6 +51,7 @@ def process_log(data): return test_results + test_results = { "SKIP": [], "OK": [], diff --git a/python/mach_bootstrap.py b/python/mach_bootstrap.py index 049dff4b7e73..0c5eb0056945 100644 --- a/python/mach_bootstrap.py +++ b/python/mach_bootstrap.py @@ -155,7 +155,6 @@ def wptserve_path(is_firefox, topdir, *paths): def _activate_virtualenv(topdir, is_firefox): virtualenv_path = os.path.join(topdir, "python", "_virtualenv%d.%d" % (sys.version_info[0], sys.version_info[1])) - check_exec_path = lambda path: path.startswith(virtualenv_path) python = sys.executable # If there was no python, mach wouldn't have run at all! if not python: sys.exit('Failed to find python executable for starting virtualenv.') @@ -177,7 +176,8 @@ def _activate_virtualenv(topdir, is_firefox): exec(compile(open(activate_path).read(), activate_path, 'exec'), dict(__file__=activate_path)) - python = _get_exec_path(PYTHON_NAMES, is_valid_path=check_exec_path) + python = _get_exec_path(PYTHON_NAMES, + is_valid_path=lambda path: path.startswith(virtualenv_path)) if not python: sys.exit("Python executable in virtualenv failed to activate.") diff --git a/python/servo/bootstrap_commands.py b/python/servo/bootstrap_commands.py index b8a88314609d..684dfc41dbe6 100644 --- a/python/servo/bootstrap_commands.py +++ b/python/servo/bootstrap_commands.py @@ -244,7 +244,7 @@ def bootstrap_hsts_preload(self, force=False): with open(path.join(preload_path, preload_filename), 'w') as fd: json.dump(entries, fd, indent=4) - except ValueError as e: + except ValueError: print("Unable to parse chromium HSTS preload list, has the format changed?") sys.exit(1) @@ -262,8 +262,8 @@ def bootstrap_pub_suffix(self, force=False): print("Unable to download the public suffix list; are you connected to the internet?") sys.exit(1) - lines = [l.strip() for l in content.decode("utf8").split("\n")] - suffixes = [l for l in lines if not l.startswith("//") and not l == ""] + lines = [line.strip() for line in content.decode("utf8").split("\n")] + suffixes = [line for line in lines if not line.startswith("//") and not line == ""] with open(dst_filename, "wb") as fo: for suffix in suffixes: @@ -475,7 +475,7 @@ def get_size(path): if os.path.exists(crate_path): try: delete(crate_path) - except: + except (FileNotFoundError, PermissionError): print(traceback.format_exc()) print("Delete %s failed!" % crate_path) else: diff --git a/python/servo/devenv_commands.py b/python/servo/devenv_commands.py index bc7152055239..abcab4b616da 100644 --- a/python/servo/devenv_commands.py +++ b/python/servo/devenv_commands.py @@ -93,8 +93,8 @@ def cargo_update(self, params=None, package=None, all_packages=None, dry_run=Non help='Updates the selected package') @CommandArgument( '--all-packages', '-a', action='store_true', - help='Updates all packages. NOTE! This is very likely to break your ' + - 'working copy, making it impossible to build servo. Only do ' + + help='Updates all packages. NOTE! This is very likely to break your ' + 'working copy, making it impossible to build servo. Only do ' 'this if you really know what you are doing.') @CommandArgument( '--dry-run', '-d', action='store_true', diff --git a/python/servo/mutation/mutator.py b/python/servo/mutation/mutator.py index 8018ddc6116a..0f359cb5107c 100644 --- a/python/servo/mutation/mutator.py +++ b/python/servo/mutation/mutator.py @@ -138,8 +138,8 @@ def __init__(self): plus_equals_statement = r".+?\s\+\=\s.*" minus_equals_statement = r".+?\s\-\=\s.*" self._replace_strategy = { - 'regex': (append_statement + '|' + remove_statement + '|' + push_statement + - '|' + pop_statement + '|' + plus_equals_statement + '|' + minus_equals_statement), + 'regex': (append_statement + '|' + remove_statement + '|' + push_statement + + '|' + pop_statement + '|' + plus_equals_statement + '|' + minus_equals_statement), 'replaceString': r"\g<0>\n\g<0>", } diff --git a/python/servo/package_commands.py b/python/servo/package_commands.py index a9e77709cfb4..e4fca52516f7 100644 --- a/python/servo/package_commands.py +++ b/python/servo/package_commands.py @@ -30,9 +30,6 @@ Command, ) from mach.registrar import Registrar -# Note: mako cannot be imported at the top level because it breaks mach bootstrap -sys.path.append(path.join(path.dirname(__file__), "..", "..", - "components", "style", "properties", "Mako-1.1.2-py2.py3-none-any.whl")) from servo.command_base import ( archive_deterministically, @@ -44,6 +41,9 @@ ) from servo.util import delete +# Note: mako cannot be imported at the top level because it breaks mach bootstrap +sys.path.append(path.join(path.dirname(__file__), "..", "..", + "components", "style", "properties", "Mako-1.1.2-py2.py3-none-any.whl")) PACKAGES = { 'android': [ @@ -96,18 +96,18 @@ def TemporaryDirectory(**kwargs): def get_taskcluster_secret(name): url = ( - os.environ.get("TASKCLUSTER_PROXY_URL", "http://taskcluster") + - "/api/secrets/v1/secret/project/servo/" + - name + os.environ.get("TASKCLUSTER_PROXY_URL", "http://taskcluster") + + "/api/secrets/v1/secret/project/servo/" + + name ) return json.load(urllib.request.urlopen(url))["secret"] def otool(s): o = subprocess.Popen(['/usr/bin/otool', '-L', s], stdout=subprocess.PIPE) - for l in o.stdout: - if l[0] == '\t': - yield l.split(' ', 1)[0][1:] + for line in o.stdout: + if line[0] == '\t': + yield line.split(' ', 1)[0][1:] def listfiles(directory): @@ -781,7 +781,7 @@ def run_powershell_cmd(cmd): print("Packaging on TC. Using secret certificate") pfx = get_taskcluster_secret("windows-codesign-cert/latest")["pfx"] open("servo.pfx", "wb").write(base64.b64decode(pfx["base64"])) - run_powershell_cmd('Import-PfxCertificate -FilePath .\servo.pfx -CertStoreLocation Cert:\CurrentUser\My') + run_powershell_cmd('Import-PfxCertificate -FilePath .\\servo.pfx -CertStoreLocation Cert:\\CurrentUser\\My') os.remove("servo.pfx") # Powershell command that lists all certificates for publisher @@ -796,7 +796,7 @@ def run_powershell_cmd(cmd): # PowerShell command that creates and install signing certificate for publisher cmd = '(New-SelfSignedCertificate -Type Custom -Subject ' + publisher + \ ' -FriendlyName "Allizom Signing Certificate (temporary)"' + \ - ' -KeyUsage DigitalSignature -CertStoreLocation "Cert:\CurrentUser\My"' + \ + ' -KeyUsage DigitalSignature -CertStoreLocation "Cert:\\CurrentUser\\My"' + \ ' -TextExtension @("2.5.29.37={text}1.3.6.1.5.5.7.3.3", "2.5.29.19={text}")).Thumbprint' thumbprint = run_powershell_cmd(cmd) elif len(certs) > 1: diff --git a/python/servo/post_build_commands.py b/python/servo/post_build_commands.py index 520358509616..9b38c584fd0f 100644 --- a/python/servo/post_build_commands.py +++ b/python/servo/post_build_commands.py @@ -161,8 +161,8 @@ def run(self, params, release=False, dev=False, android=None, debug=False, debug command = rustCommand # Prepend the debugger args. - args = ([command] + self.debuggerInfo.args + - args + params) + args = ([command] + self.debuggerInfo.args + + args + params) else: args = args + params @@ -208,8 +208,8 @@ def rr_record(self, release=False, dev=False, bin=None, nightly=None, params=[]) env = self.build_env() env["RUST_BACKTRACE"] = "1" - servo_cmd = [bin or self.get_nightly_binary_path(nightly) or - self.get_binary_path(release, dev)] + params + servo_cmd = [bin or self.get_nightly_binary_path(nightly) + or self.get_binary_path(release, dev)] + params rr_cmd = ['rr', '--fatal-errors', 'record'] try: check_call(rr_cmd + servo_cmd) diff --git a/python/servo/testing_commands.py b/python/servo/testing_commands.py index b5b2160fee05..ec3a74ffdfa0 100644 --- a/python/servo/testing_commands.py +++ b/python/servo/testing_commands.py @@ -117,8 +117,8 @@ def __init__(self, context): help="Optionally select test based on " "test file directory") @CommandArgument('--render-mode', '-rm', default=DEFAULT_RENDER_MODE, - help="The render mode to be used on all tests. " + - HELP_RENDER_MODE) + help="The render mode to be used on all tests. " + + HELP_RENDER_MODE) @CommandArgument('--release', default=False, action="store_true", help="Run with a release build of servo") @CommandArgument('--tidy-all', default=False, action="store_true", diff --git a/tests/dromaeo/run_dromaeo.py b/tests/dromaeo/run_dromaeo.py index 1618751e70ba..3a12652021fd 100755 --- a/tests/dromaeo/run_dromaeo.py +++ b/tests/dromaeo/run_dromaeo.py @@ -65,15 +65,15 @@ def log_message(self, format, *args): while not server.got_post: server.handle_request() data = json.loads(server.post_data[0]) - n = 0 - l = 0 + number = 0 + length = 0 for test in data: - n = max(n, len(data[test])) - l = max(l, len(test)) - print("\n Test{0} | Time".format(" " * (l - len("Test")))) - print("-{0}-|-{1}-".format("-" * l, "-" * n)) + number = max(number, len(data[test])) + length = max(length, len(test)) + print("\n Test{0} | Time".format(" " * (length - len("Test")))) + print("-{0}-|-{1}-".format("-" * length, "-" * number)) for test in data: - print(" {0}{1} | {2}".format(test, " " * (l - len(test)), data[test])) + print(" {0}{1} | {2}".format(test, " " * (length - len(test)), data[test])) proc.kill() else: print_usage() diff --git a/tests/jquery/run_jquery.py b/tests/jquery/run_jquery.py index cb5b4490c6a5..e9d50deed7be 100755 --- a/tests/jquery/run_jquery.py +++ b/tests/jquery/run_jquery.py @@ -183,7 +183,7 @@ def send_head(self): self.send_header("Last-Modified", self.date_time_string(fs.st_mtime)) self.end_headers() return f - except: + except IOError: f.close() raise @@ -195,6 +195,7 @@ def log_message(self, format, *args): sys.stdout.flush() server.handle_request() + if __name__ == '__main__': if len(sys.argv) == 4: cmd = sys.argv[1] diff --git a/tests/power/PowerMeasure.py b/tests/power/PowerMeasure.py index 6c49ce639af7..83b177bc618d 100755 --- a/tests/power/PowerMeasure.py +++ b/tests/power/PowerMeasure.py @@ -134,10 +134,10 @@ def PowerParser(OutputDir, LayoutThreads): TotalPower = PowerGen / float(ExperimentNum - 1) TotalTime = TimeGen / float(ExperimentNum - 1) - ResultFile.write(str(layoutT) + " , " + str(TotalPower) + " , " + - str(MaxPower) + " , " + str(MinPower) + " , " + - str(TotalTime) + " , " + str(MaxTime) + " , " + - str(MinTime) + "\n") + ResultFile.write(str(layoutT) + " , " + str(TotalPower) + " , " + + str(MaxPower) + " , " + str(MinPower) + " , " + + str(TotalTime) + " , " + str(MaxTime) + " , " + + str(MinTime) + "\n") ResultFile.close() Opener = ResultFile = open(ResultTable, "r") for line in Opener: @@ -180,5 +180,6 @@ def main(): PowerCollector(OutputDir, Benchmarks, LayoutThreads, Renderer) PowerParser(OutputDir, LayoutThreads) + if __name__ == "__main__": main() diff --git a/tests/wpt/grouping_formatter.py b/tests/wpt/grouping_formatter.py index 24073e10fe7b..4f188909e0a8 100644 --- a/tests/wpt/grouping_formatter.py +++ b/tests/wpt/grouping_formatter.py @@ -75,8 +75,8 @@ def get_move_up_and_clear_eol_codes(self): def text_to_erase_display(self): if not self.interactive or not self.current_display: return "" - return ((self.move_up + self.clear_eol) * - self.current_display.count('\n')) + return ((self.move_up + self.clear_eol) + * self.current_display.count('\n')) def generate_output(self, text=None, new_display=None, unexpected_in_test=None): if not self.interactive: diff --git a/tests/wpt/run.py b/tests/wpt/run.py index 33a9b7106198..3fc43fb3f13a 100644 --- a/tests/wpt/run.py +++ b/tests/wpt/run.py @@ -19,6 +19,7 @@ def wpt_path(*args): def servo_path(*args): return os.path.join(servo_root, *args) + paths = {"include_manifest": wpt_path("include.ini"), "config": wpt_path("config.ini"), "ca-cert-path": wpt_path("web-platform-tests/tools/certs/cacert.pem"), @@ -26,8 +27,8 @@ def servo_path(*args): "host-cert-path": wpt_path("web-platform-tests/tools/certs/web-platform.test.pem")} # Imports sys.path.append(wpt_path("web-platform-tests", "tools")) -import localpaths # noqa: flake8 -from wptrunner import wptrunner, wptcommandline +import localpaths # noqa: F401,E402 +from wptrunner import wptrunner, wptcommandline # noqa: E402 def run_tests(**kwargs): @@ -106,5 +107,6 @@ def main(): kwargs = vars(parser.parse_args()) return run_tests(**kwargs) + if __name__ == "__main__": sys.exit(0 if main() else 1) diff --git a/tests/wpt/update.py b/tests/wpt/update.py index 28697d5d9041..8e7100a13d72 100644 --- a/tests/wpt/update.py +++ b/tests/wpt/update.py @@ -5,6 +5,7 @@ import os import sys from wptrunner import wptcommandline +from update import updatecommandline here = os.path.split(__file__)[0] @@ -12,9 +13,6 @@ def wpt_path(*args): return os.path.join(here, *args) -# Imports -from update import updatecommandline - def update_tests(**kwargs): import update @@ -45,5 +43,6 @@ def main(): kwargs = vars(parser.parse_args()) return update_tests(**kwargs) + if __name__ == "__main__": sys.exit(0 if main() else 1)