Bug 1542963 - Fix most flake8 issues in python/mozbuild/mozbuild/* r=#build
authorJustin Wood <Callek@gmail.com>
Sun, 07 Apr 2019 15:39:24 -0400
changeset 536060 11a714f491d56eb86b131505b12b9db240249179
parent 536059 2715bac40d2f2e90a60cb86a28308bfeb4fc34de
child 536061 14aa1bd254a48f74c05fccc4be7df847135ec090
push id2082
push userffxbld-merge
push dateMon, 01 Jul 2019 08:34:18 +0000
treeherdermozilla-release@2fb19d0466d2 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
bugs1542963
milestone68.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Bug 1542963 - Fix most flake8 issues in python/mozbuild/mozbuild/* r=#build Leaving one fix for an explicit review. Lint python/mozbuild/{mozbuild,mozpack}. r=#build Differential Revision: https://phabricator.services.mozilla.com/D26641
.flake8
python/mozbuild/mozbuild/action/buildlist.py
python/mozbuild/mozbuild/action/download_wpt_manifest.py
python/mozbuild/mozbuild/action/dumpsymbols.py
python/mozbuild/mozbuild/action/exe_7z_archive.py
python/mozbuild/mozbuild/action/file_generate.py
python/mozbuild/mozbuild/action/generate_searchjson.py
python/mozbuild/mozbuild/action/generate_suggestedsites.py
python/mozbuild/mozbuild/action/langpack_manifest.py
python/mozbuild/mozbuild/action/package_fennec_apk.py
python/mozbuild/mozbuild/action/package_generated_sources.py
python/mozbuild/mozbuild/action/process_define_files.py
python/mozbuild/mozbuild/action/tooltool.py
python/mozbuild/mozbuild/action/xpccheck.py
python/mozbuild/mozbuild/action/xpidl-process.py
python/mozbuild/mozbuild/analyze/graph.py
python/mozbuild/mozbuild/artifacts.py
python/mozbuild/mozbuild/backend/common.py
python/mozbuild/mozbuild/backend/configenvironment.py
python/mozbuild/mozbuild/backend/cpp_eclipse.py
python/mozbuild/mozbuild/backend/fastermake.py
python/mozbuild/mozbuild/backend/mach_commands.py
python/mozbuild/mozbuild/backend/recursivemake.py
python/mozbuild/mozbuild/backend/tup.py
python/mozbuild/mozbuild/backend/visualstudio.py
python/mozbuild/mozbuild/base.py
python/mozbuild/mozbuild/codecoverage/chrome_map.py
python/mozbuild/mozbuild/codecoverage/lcov_rewriter.py
python/mozbuild/mozbuild/codecoverage/packager.py
python/mozbuild/mozbuild/compilation/codecomplete.py
python/mozbuild/mozbuild/compilation/database.py
python/mozbuild/mozbuild/compilation/util.py
python/mozbuild/mozbuild/config_status.py
python/mozbuild/mozbuild/configure/util.py
python/mozbuild/mozbuild/controller/building.py
python/mozbuild/mozbuild/controller/clobber.py
python/mozbuild/mozbuild/doctor.py
python/mozbuild/mozbuild/dotproperties.py
python/mozbuild/mozbuild/faster_daemon.py
python/mozbuild/mozbuild/frontend/context.py
python/mozbuild/mozbuild/frontend/data.py
python/mozbuild/mozbuild/frontend/emitter.py
python/mozbuild/mozbuild/frontend/gyp_reader.py
python/mozbuild/mozbuild/frontend/sandbox.py
python/mozbuild/mozbuild/gn_processor.py
python/mozbuild/mozbuild/jar.py
python/mozbuild/mozbuild/mach_commands.py
python/mozbuild/mozbuild/makeutil.py
python/mozbuild/mozbuild/mozconfig.py
python/mozbuild/mozbuild/mozinfo.py
python/mozbuild/mozbuild/preprocessor.py
python/mozbuild/mozbuild/repackaging/installer.py
python/mozbuild/mozbuild/repackaging/msi.py
python/mozbuild/mozbuild/test/action/test_buildlist.py
python/mozbuild/mozbuild/test/action/test_node.py
python/mozbuild/mozbuild/test/action/test_process_install_manifest.py
python/mozbuild/mozbuild/test/backend/test_build.py
python/mozbuild/mozbuild/test/backend/test_configenvironment.py
python/mozbuild/mozbuild/test/backend/test_fastermake.py
python/mozbuild/mozbuild/test/backend/test_gn_processor.py
python/mozbuild/mozbuild/test/backend/test_partialconfigenvironment.py
python/mozbuild/mozbuild/test/backend/test_recursivemake.py
python/mozbuild/mozbuild/test/codecoverage/test_lcov_rewrite.py
python/mozbuild/mozbuild/test/configure/lint.py
python/mozbuild/mozbuild/test/configure/test_checks_configure.py
python/mozbuild/mozbuild/test/configure/test_configure.py
python/mozbuild/mozbuild/test/configure/test_lint.py
python/mozbuild/mozbuild/test/configure/test_moz_configure.py
python/mozbuild/mozbuild/test/configure/test_options.py
python/mozbuild/mozbuild/test/configure/test_toolkit_moz_configure.py
python/mozbuild/mozbuild/test/frontend/test_emitter.py
python/mozbuild/mozbuild/test/frontend/test_reader.py
python/mozbuild/mozbuild/test/frontend/test_sandbox.py
python/mozbuild/mozbuild/test/test_android_version_code.py
python/mozbuild/mozbuild/test/test_base.py
python/mozbuild/mozbuild/test/test_containers.py
python/mozbuild/mozbuild/test/test_expression.py
python/mozbuild/mozbuild/test/test_jarmaker.py
python/mozbuild/mozbuild/test/test_licenses.py
python/mozbuild/mozbuild/test/test_line_endings.py
python/mozbuild/mozbuild/test/test_mozconfig.py
python/mozbuild/mozbuild/test/test_util.py
python/mozbuild/mozbuild/testing.py
python/mozbuild/mozbuild/util.py
python/mozbuild/mozbuild/vendor_aom.py
python/mozbuild/mozbuild/vendor_dav1d.py
python/mozbuild/mozbuild/vendor_rust.py
python/mozbuild/mozbuild/virtualenv.py
--- a/.flake8
+++ b/.flake8
@@ -87,11 +87,13 @@ ignore =
     F632, F633, F811, E117, W504, W605, W606,
     # These are intentionally disabled (not necessarily for good reason).
     #   F723: syntax error in type comment
     #       text contains quotes which breaks our custom JSON formatter
     F723, E121, E123, E126, E129, E133, E226, E241, E242, E402, E704, E741, W503,
 
 per-file-ignores =
     ipc/ipdl/*: F403, F405
+    # cpp_eclipse has a lot of multi-line embedded XML which exceeds line length
+    python/mozbuild/mozbuild/backend/cpp_eclipse.py: E501
     testing/firefox-ui/**/__init__.py: F401
     testing/marionette/**/__init__.py: F401
     testing/mozharness/configs/*: E124, E127, E128, E131, E231, E261, E265, E266, E501, W391
--- a/python/mozbuild/mozbuild/action/buildlist.py
+++ b/python/mozbuild/mozbuild/action/buildlist.py
@@ -32,17 +32,17 @@ def addEntriesToListFile(listFile, entri
         else:
             existing = set()
         for e in entries:
             if e not in existing:
                 existing.add(e)
         with open(listFile, 'wb') as f:
             f.write("\n".join(sorted(existing))+"\n")
     finally:
-        lock = None
+        del lock  # Explicitly release the lock_file to free it
 
 
 def main(args):
     if len(args) < 2:
         print("Usage: buildlist.py <list file> <entry> [<entry> ...]",
               file=sys.stderr)
         return 1
 
--- a/python/mozbuild/mozbuild/action/download_wpt_manifest.py
+++ b/python/mozbuild/mozbuild/action/download_wpt_manifest.py
@@ -1,15 +1,14 @@
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 # This action is used to generate the wpt manifest
 
-import os
 import sys
 
 import buildconfig
 
 
 def main():
     print("Downloading wpt manifest")
     sys.path.insert(0, buildconfig.topsrcdir)
--- a/python/mozbuild/mozbuild/action/dumpsymbols.py
+++ b/python/mozbuild/mozbuild/action/dumpsymbols.py
@@ -54,18 +54,19 @@ def dump_symbols(target, tracking_file, 
                                                                      'dist_include'),
                                                         os.path.join(buildconfig.topobjdir,
                                                                      'dist',
                                                                      'include')))
     objcopy = buildconfig.substs.get('OBJCOPY')
     if objcopy:
         os.environ['OBJCOPY'] = objcopy
 
-    args = ([buildconfig.substs['PYTHON'], os.path.join(buildconfig.topsrcdir, 'toolkit',
-                                                        'crashreporter', 'tools', 'symbolstore.py')] +
+    args = ([buildconfig.substs['PYTHON'],
+             os.path.join(buildconfig.topsrcdir, 'toolkit',
+                          'crashreporter', 'tools', 'symbolstore.py')] +
             sym_store_args +
             ['-s', buildconfig.topsrcdir, dump_syms_bin, os.path.join(buildconfig.topobjdir,
                                                                       'dist',
                                                                       'crashreporter-symbols'),
              os.path.abspath(target)])
     if count_ctors:
         args.append('--count-ctors')
     print('Running: %s' % ' '.join(args))
--- a/python/mozbuild/mozbuild/action/exe_7z_archive.py
+++ b/python/mozbuild/mozbuild/action/exe_7z_archive.py
@@ -26,18 +26,20 @@ def archive_exe(pkg_dir, tagfile, sfx_pa
         else:
             final_sfx = sfx_package
 
         try:
             sevenz = buildconfig.config.substs['7Z']
         except BuildEnvironmentNotFoundException:
             # configure hasn't been run, just use the default
             sevenz = '7z'
-        subprocess.check_call([sevenz, 'a', '-r', '-t7z', mozpath.join(tmpdir, 'app.7z'), '-mx',
-                               '-m0=BCJ2', '-m1=LZMA:d25', '-m2=LZMA:d19', '-m3=LZMA:d19', '-mb0:1', '-mb0s1:2', '-mb0s2:3'])
+        subprocess.check_call([
+            sevenz, 'a', '-r', '-t7z', mozpath.join(tmpdir, 'app.7z'), '-mx',
+            '-m0=BCJ2', '-m1=LZMA:d25', '-m2=LZMA:d19', '-m3=LZMA:d19', '-mb0:1',
+            '-mb0s1:2', '-mb0s2:3'])
 
         with open(package, 'wb') as o:
             for i in [final_sfx, tagfile, mozpath.join(tmpdir, 'app.7z')]:
                 shutil.copyfileobj(open(i, 'rb'), o)
         os.chmod(package, 0o0755)
     finally:
         if pkg_dir:
             shutil.move('core', pkg_dir)
--- a/python/mozbuild/mozbuild/action/file_generate.py
+++ b/python/mozbuild/mozbuild/action/file_generate.py
@@ -64,17 +64,17 @@ def main(argv):
               file=sys.stderr)
         return 1
 
     ret = 1
     try:
         with FileAvoidWrite(args.output_file, mode='rb') as output:
             try:
                 ret = module.__dict__[method](output, *args.additional_arguments, **kwargs)
-            except:
+            except Exception:
                 # Ensure that we don't overwrite the file if the script failed.
                 output.avoid_writing_to_file()
                 raise
 
             # The following values indicate a statement of success:
             #  - a set() (see below)
             #  - 0
             #  - False
--- a/python/mozbuild/mozbuild/action/generate_searchjson.py
+++ b/python/mozbuild/mozbuild/action/generate_searchjson.py
@@ -20,33 +20,36 @@ with open(sys.argv[1]) as f:
 if locale in searchinfo["locales"]:
     localeSearchInfo = searchinfo["locales"][locale]
 else:
     localeSearchInfo = {}
     localeSearchInfo["default"] = searchinfo["default"]
 
 
 def validateDefault(key):
-    if (not key in searchinfo["default"]):
+    if key not in searchinfo["default"]:
         print >>sys.stderr, "Error: Missing default %s in list.json" % (key)
         sys.exit(1)
 
 
 validateDefault("searchDefault")
 validateDefault("visibleDefaultEngines")
 
 # If the selected locale doesn't have a searchDefault,
 # use the global one.
-if not "searchDefault" in localeSearchInfo["default"]:
+if "searchDefault" not in localeSearchInfo["default"]:
     localeSearchInfo["default"]["searchDefault"] = searchinfo["default"]["searchDefault"]
 
 # If the selected locale doesn't have a searchOrder,
 # use the global one if present.
 # searchOrder is NOT required.
-if not "searchOrder" in localeSearchInfo["default"] and "searchOrder" in searchinfo["default"]:
+if (
+    "searchOrder" not in localeSearchInfo["default"]
+    and "searchOrder" in searchinfo["default"]
+):
     localeSearchInfo["default"]["searchOrder"] = searchinfo["default"]["searchOrder"]
 
 # If we have region overrides, enumerate through them
 # and add the additional regions to the locale information.
 if "regionOverrides" in searchinfo:
     regionOverrides = searchinfo["regionOverrides"]
 
     for region in regionOverrides:
@@ -58,13 +61,14 @@ if "regionOverrides" in searchinfo:
             visibleDefaultEngines = localeSearchInfo["default"]["visibleDefaultEngines"]
         if set(visibleDefaultEngines) & enginesToOverride:
             if region not in localeSearchInfo:
                 localeSearchInfo[region] = {}
             localeSearchInfo[region]["visibleDefaultEngines"] = copy.deepcopy(
                 visibleDefaultEngines)
             for i, engine in enumerate(localeSearchInfo[region]["visibleDefaultEngines"]):
                 if engine in regionOverrides[region]:
-                    localeSearchInfo[region]["visibleDefaultEngines"][i] = regionOverrides[region][engine]
+                    localeSearchInfo[region]["visibleDefaultEngines"][i] = \
+                        regionOverrides[region][engine]
 
 output.write(json.dumps(localeSearchInfo, ensure_ascii=False).encode('utf8'))
 
 output.close()
--- a/python/mozbuild/mozbuild/action/generate_suggestedsites.py
+++ b/python/mozbuild/mozbuild/action/generate_suggestedsites.py
@@ -33,23 +33,19 @@ import copy
 import errno
 import json
 import sys
 import os
 
 from mozbuild.dotproperties import (
     DotProperties,
 )
-from mozbuild.util import (
-    FileAvoidWrite,
-)
 from mozpack.files import (
     FileFinder,
 )
-import mozpack.path as mozpath
 
 
 def merge_properties(paths):
     """Merges properties from the given paths."""
     properties = DotProperties()
     for path in paths:
         try:
             properties.update(path)
@@ -87,17 +83,18 @@ def main(output, *args, **kwargs):
         print('Fallback path {fallback} is not a file!'.format(fallback=opts.fallback))
         return 1
 
     # Use reversed order so that the first srcdir has higher priority to override keys.
     sources = [opts.fallback] + list(reversed(opts.inputs))
     properties = merge_properties(sources)
 
     # Keep these two in sync.
-    image_url_template = 'android.resource://%s/drawable/suggestedsites_{name}' % opts.android_package_name
+    image_url_template = \
+        'android.resource://%s/drawable/suggestedsites_{name}' % opts.android_package_name
     drawables_template = 'drawable*/suggestedsites_{name}.*'
 
     # Load properties corresponding to each site name and define their
     # respective image URL.
     sites = []
 
     def add_names(names, defaults={}):
         for name in names:
@@ -116,17 +113,19 @@ def main(output, *args, **kwargs):
             finder = FileFinder(resources)
             matches = [p for p, _ in finder.find(drawables_template.format(name=name))]
             if not matches:
                 raise Exception("Could not find drawable in '{resources}' for '{name}'"
                                 .format(resources=resources, name=name))
             else:
                 if opts.verbose:
                     print("Found {len} drawables in '{resources}' for '{name}': {matches}"
-                          .format(len=len(matches), resources=resources, name=name, matches=matches))
+                          .format(len=len(matches), resources=resources,
+                                  name=name, matches=matches)
+                          )
 
     # We want the lists to be ordered for reproducibility.  Each list has a
     # "default" JSON list item which will be extended by the properties read.
     lists = [
         ('browser.suggestedsites.list', {}),
         ('browser.suggestedsites.restricted.list', {'restricted': True}),
     ]
     if opts.verbose:
--- a/python/mozbuild/mozbuild/action/langpack_manifest.py
+++ b/python/mozbuild/mozbuild/action/langpack_manifest.py
@@ -21,17 +21,16 @@ import mozversioncontrol
 import mozpack.path as mozpath
 from mozpack.chrome.manifest import (
     Manifest,
     ManifestLocale,
     parse_manifest,
 )
 from mozbuild.configure.util import Version
 from mozbuild.preprocessor import Preprocessor
-import buildconfig
 
 
 def write_file(path, content):
     with io.open(path, 'w', encoding='utf-8') as out:
         out.write(content + '\n')
 
 
 pushlog_api_url = "{0}/json-rev/{1}"
--- a/python/mozbuild/mozbuild/action/package_fennec_apk.py
+++ b/python/mozbuild/mozbuild/action/package_fennec_apk.py
@@ -6,17 +6,16 @@
 Script to produce an Android package (.apk) for Fennec.
 '''
 
 from __future__ import absolute_import, print_function
 
 import argparse
 import buildconfig
 import os
-import subprocess
 import sys
 
 from mozpack.copier import Jarrer
 from mozpack.files import (
     DeflatedFile,
     File,
     FileFinder,
 )
--- a/python/mozbuild/mozbuild/action/package_generated_sources.py
+++ b/python/mozbuild/mozbuild/action/package_generated_sources.py
@@ -1,17 +1,15 @@
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 from __future__ import absolute_import, print_function, unicode_literals
 
 import argparse
-import json
-import os.path
 import sys
 
 import buildconfig
 import mozpack.path as mozpath
 from mozpack.archive import create_tar_gz_from_files
 from mozpack.files import BaseFile
 from mozbuild.generated_sources import get_generated_sources
 
@@ -25,17 +23,18 @@ def main(argv):
     objdir_abspath = mozpath.abspath(buildconfig.topobjdir)
 
     def is_valid_entry(entry):
         if isinstance(entry[1], BaseFile):
             entry_abspath = mozpath.abspath(entry[1].path)
         else:
             entry_abspath = mozpath.abspath(entry[1])
         if not entry_abspath.startswith(objdir_abspath):
-            print("Warning: omitting generated source [%s] from archive" % entry_abspath, file=sys.stderr)
+            print("Warning: omitting generated source [%s] from archive" % entry_abspath,
+                  file=sys.stderr)
             return False
         return True
 
     files = dict(filter(is_valid_entry, get_generated_sources()))
     with open(args.outputfile, 'wb') as fh:
         create_tar_gz_from_files(fh, files, compresslevel=5)
 
 
--- a/python/mozbuild/mozbuild/action/process_define_files.py
+++ b/python/mozbuild/mozbuild/action/process_define_files.py
@@ -5,17 +5,16 @@
 from __future__ import absolute_import, print_function, unicode_literals
 
 import argparse
 import os
 import re
 import sys
 from buildconfig import topsrcdir, topobjdir
 from mozbuild.backend.configenvironment import PartialConfigEnvironment
-from mozbuild.util import FileAvoidWrite
 import mozpack.path as mozpath
 
 
 def process_define_file(output, input):
     '''Creates the given config header. A config header is generated by
     taking the corresponding source file and replacing some #define/#undef
     occurences:
         "#undef NAME" is turned into "#define NAME VALUE"
@@ -46,22 +45,22 @@ def process_define_file(output, input):
                 name = m.group('name')
                 value = m.group('value')
                 if name:
                     if name == 'ALLDEFINES':
                         if cmd == 'define':
                             raise Exception(
                                 '`#define ALLDEFINES` is not allowed in a '
                                 'CONFIGURE_DEFINE_FILE')
-                        # WebRTC files like to define WINVER and _WIN32_WINNT
-                        # via the command line, which raises a mass of macro
-                        # redefinition warnings.  Just handle those macros
-                        # specially here.
 
                         def define_for_name(name, val):
+                            """WebRTC files like to define WINVER and _WIN32_WINNT
+                            via the command line, which raises a mass of macro
+                            redefinition warnings.  Just handle those macros
+                            specially here."""
                             define = "#define {name} {val}".format(name=name, val=val)
                             if name in ('WINVER', '_WIN32_WINNT'):
                                 return '#if !defined({name})\n{define}\n#endif' \
                                     .format(name=name, define=define)
                             return define
                         defines = '\n'.join(sorted(
                             define_for_name(name, val)
                             for name, val in config.defines['ALLDEFINES'].iteritems()))
--- a/python/mozbuild/mozbuild/action/tooltool.py
+++ b/python/mozbuild/mozbuild/action/tooltool.py
@@ -743,17 +743,17 @@ CHECKSUM_SUFFIX = ".checksum"
 def _cache_checksum_matches(base_file, checksum):
     try:
         with open(base_file + CHECKSUM_SUFFIX, "rb") as f:
             prev_checksum = f.read().strip()
             if prev_checksum == checksum:
                 log.info("Cache matches, avoiding extracting in '%s'" % base_file)
                 return True
             return False
-    except IOError as e:
+    except IOError:
         return False
 
 
 def _compute_cache_checksum(filename):
     with open(filename, "rb") as f:
         return digest_file(f, "sha256")
 
 
@@ -1017,17 +1017,17 @@ def _authorize(req, auth_file):
         return
 
     is_taskcluster_auth = False
     with open(auth_file) as f:
         auth_file_content = f.read().strip()
         try:
             auth_file_content = json.loads(auth_file_content)
             is_taskcluster_auth = True
-        except:
+        except Exception:
             pass
 
     if is_taskcluster_auth:
         taskcluster_header = make_taskcluster_header(auth_file_content, req)
         log.debug("Using taskcluster credentials in %s" % auth_file)
         req.add_unredirected_header('Authorization', taskcluster_header)
     else:
         log.debug("Using Bearer token in %s" % auth_file)
--- a/python/mozbuild/mozbuild/action/xpccheck.py
+++ b/python/mozbuild/mozbuild/action/xpccheck.py
@@ -37,18 +37,21 @@ def verifyDirectory(initests, directory)
 
         found = False
         for test in initests:
             if os.path.join(os.path.abspath(directory), name) == test['path']:
                 found = True
                 break
 
         if not found:
-            print >>sys.stderr, "TEST-UNEXPECTED-FAIL | xpccheck | test %s is missing from test manifest %s!" % (
-                name, os.path.join(directory, 'xpcshell.ini'))
+            print >>sys.stderr, ("TEST-UNEXPECTED-FAIL | xpccheck | test "
+                                 "%s is missing from test manifest %s!") % (
+                name,
+                os.path.join(directory, 'xpcshell.ini'),
+            )
             sys.exit(1)
 
 
 def verifyIniFile(initests, directory):
     files = glob(os.path.join(os.path.abspath(directory), "test_*"))
     for test in initests:
         name = test['path'].split('/')[-1]
 
@@ -59,27 +62,27 @@ def verifyIniFile(initests, directory):
             if fname.endswith('.in'):
                 fname = '.in'.join(fname.split('.in')[:-1])
 
             if os.path.join(os.path.abspath(directory), fname) == test['path']:
                 found = True
                 break
 
         if not found:
-            print >>sys.stderr, "TEST-UNEXPECTED-FAIL | xpccheck | found %s in xpcshell.ini and not in directory '%s'" % (
-                name, directory)
+            print >>sys.stderr, ("TEST-UNEXPECTED-FAIL | xpccheck | found "
+                                 "%s in xpcshell.ini and not in directory '%s'"
+                                 ) % (name, directory)
             sys.exit(1)
 
 
 def main(argv):
     if len(argv) < 2:
         print >>sys.stderr, "Usage: xpccheck.py <topsrcdir> <directory> [<directory> ...]"
         sys.exit(1)
 
-    topsrcdir = argv[0]
     for d in argv[1:]:
         # xpcshell-unpack is a copy of xpcshell sibling directory and in the Makefile
         # we copy all files (including xpcshell.ini from the sibling directory.
         if d.endswith('toolkit/mozapps/extensions/test/xpcshell-unpack'):
             continue
 
         initests = getIniTests(d)
         verifyDirectory(initests, d)
--- a/python/mozbuild/mozbuild/action/xpidl-process.py
+++ b/python/mozbuild/mozbuild/action/xpidl-process.py
@@ -8,18 +8,16 @@
 # system. The API will change to meet the needs of the build system.
 
 from __future__ import absolute_import
 
 import argparse
 import os
 import sys
 
-from io import BytesIO
-
 from xpidl import jsonxpt
 from buildconfig import topsrcdir
 from xpidl.header import print_header
 from xpidl.rust import print_rust_bindings
 from xpidl.rust_macros import print_rust_macros_bindings
 from xpidl.xpidl import IDLParser
 
 from mozbuild.makeutil import Makefile
--- a/python/mozbuild/mozbuild/analyze/graph.py
+++ b/python/mozbuild/mozbuild/analyze/graph.py
@@ -87,17 +87,17 @@ class Graph(object):
         self.node_dict[k] = v
 
     def get_id(self, filepath):
         nodeid = 1
         for part in filepath.split('/'):
             ret = self.query_arg('SELECT id FROM node \
                 WHERE dir=? AND name=?', (nodeid, part)).fetchone()
             # fetchone should be ok bc dir and and name combo is unique
-            if ret == None:
+            if ret is None:
                 print ("\nCould not find id number for '%s'" % filepath)
                 return None
             nodeid = ret[0]
         return nodeid
 
     def get_node(self, node_id):
         if node_id is not None:
             node = self.node_dict.get(node_id)
--- a/python/mozbuild/mozbuild/artifacts.py
+++ b/python/mozbuild/mozbuild/artifacts.py
@@ -333,28 +333,31 @@ class AndroidArtifactJob(ArtifactJob):
         import gzip
 
         with JarWriter(file=processed_filename, compress_level=5) as writer:
             reader = JarReader(filename)
             for filename in reader.entries:
                 if not filename.endswith('.gz'):
                     continue
 
-                # Uncompress "libxul.so/D3271457813E976AE7BF5DAFBABABBFD0/libxul.so.dbg.gz" into "libxul.so.dbg".
+                # Uncompress "libxul.so/D3271457813E976AE7BF5DAFBABABBFD0/libxul.so.dbg.gz"
+                # into "libxul.so.dbg".
                 #
-                # After `settings append target.debug-file-search-paths /path/to/topobjdir/dist/crashreporter-symbols`,
+                # After running `settings append target.debug-file-search-paths $file`,
+                # where file=/path/to/topobjdir/dist/crashreporter-symbols,
                 # Android Studio's lldb (7.0.0, at least) will find the ELF debug symbol files.
                 #
                 # There are other paths that will work but none seem more desireable.  See
                 # https://github.com/llvm-mirror/lldb/blob/882670690ca69d9dd96b7236c620987b11894af9/source/Host/common/Symbols.cpp#L324.
                 basename = os.path.basename(filename).replace('.gz', '')
                 destpath = mozpath.join('crashreporter-symbols', basename)
                 self.log(logging.INFO, 'artifact',
                          {'destpath': destpath},
-                         'Adding uncompressed ELF debug symbol file {destpath} to processed archive')
+                         'Adding uncompressed ELF debug symbol file '
+                         '{destpath} to processed archive')
                 writer.add(destpath.encode('utf-8'),
                            gzip.GzipFile(fileobj=reader[filename].uncompressed_data))
 
 
 class LinuxArtifactJob(ArtifactJob):
     package_re = r'public/build/target\.tar\.bz2'
     product = 'firefox'
 
@@ -651,17 +654,18 @@ def cachedmethod(cachefunc):
 class CacheManager(object):
     '''Maintain an LRU cache.  Provide simple persistence, including support for
     loading and saving the state using a "with" block.  Allow clearing the cache
     and printing the cache for debugging.
 
     Provide simple logging.
     '''
 
-    def __init__(self, cache_dir, cache_name, cache_size, cache_callback=None, log=None, skip_cache=False):
+    def __init__(self, cache_dir, cache_name, cache_size, cache_callback=None,
+                 log=None, skip_cache=False):
         self._skip_cache = skip_cache
         self._cache = pylru.lrucache(cache_size, callback=cache_callback)
         self._cache_filename = mozpath.join(cache_dir, cache_name + '-cache.pickle')
         self._log = log
         mkdir(cache_dir, not_indexed=True)
 
     def log(self, *args, **kwargs):
         if self._log:
@@ -955,17 +959,18 @@ class Artifacts(object):
                 num=NUM_REVISIONS_TO_QUERY)
         ], cwd=self._topsrcdir).splitlines()
 
         if len(last_revs) == 0:
             raise Exception("""\
 There are no public revisions.
 This can happen if the repository is created from bundle file and never pulled
 from remote.  Please run `hg pull` and build again.
-see https://developer.mozilla.org/en-US/docs/Mozilla/Developer_guide/Source_Code/Mercurial/Bundles""")
+see https://developer.mozilla.org/en-US/docs/Mozilla/Developer_guide/Source_Code/Mercurial/Bundles\
+""")
 
         self.log(logging.INFO, 'artifact',
                  {'len': len(last_revs)},
                  'hg suggested {len} candidate revisions')
 
         def to_pair(line):
             rev, node = line.split(':', 1)
             return (int(rev), node)
@@ -1000,20 +1005,21 @@ see https://developer.mozilla.org/en-US/
             if not rev:
                 continue
             if rev not in candidate_pushheads:
                 continue
             count += 1
             yield candidate_pushheads[rev], rev
 
         if not count:
-            raise Exception('Could not find any candidate pushheads in the last {num} revisions.\n'
-                            'Search started with {rev}, which must be known to Mozilla automation.\n\n'
-                            'see https://developer.mozilla.org/en-US/docs/Artifact_builds'.format(
-                                rev=last_revs[0], num=NUM_PUSHHEADS_TO_QUERY_PER_PARENT))
+            raise Exception(
+                'Could not find any candidate pushheads in the last {num} revisions.\n'
+                'Search started with {rev}, which must be known to Mozilla automation.\n\n'
+                'see https://developer.mozilla.org/en-US/docs/Artifact_builds'.format(
+                    rev=last_revs[0], num=NUM_PUSHHEADS_TO_QUERY_PER_PARENT))
 
     def find_pushhead_artifacts(self, task_cache, job, tree, pushhead):
         try:
             taskId, artifacts = task_cache.artifacts(
                 tree, job, self._artifact_job.__class__, pushhead)
         except ValueError:
             return None
 
@@ -1068,17 +1074,18 @@ see https://developer.mozilla.org/en-US/
             for info in zf.infolist():
                 if info.filename.endswith('.ini'):
                     continue
                 n = mozpath.join(distdir, info.filename)
                 fh = FileAvoidWrite(n, mode='rb')
                 shutil.copyfileobj(zf.open(info), fh)
                 file_existed, file_updated = fh.close()
                 self.log(logging.INFO, 'artifact',
-                         {'updating': 'Updating' if file_updated else 'Not updating', 'filename': n},
+                         {'updating': 'Updating' if file_updated else 'Not updating',
+                          'filename': n},
                          '{updating} {filename}')
                 if not file_existed or file_updated:
                     # Libraries and binaries may need to be marked executable,
                     # depending on platform.
                     perms = info.external_attr >> 16  # See http://stackoverflow.com/a/434689.
                     perms |= stat.S_IWUSR | stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH  # u+w, a+r.
                     os.chmod(n, perms)
         return 0
--- a/python/mozbuild/mozbuild/backend/common.py
+++ b/python/mozbuild/mozbuild/backend/common.py
@@ -28,17 +28,16 @@ from mozbuild.frontend.data import (
     Exports,
     FinalTargetPreprocessedFiles,
     FinalTargetFiles,
     GeneratedFile,
     GeneratedSources,
     GnProjectData,
     HostLibrary,
     HostGeneratedSources,
-    HostRustLibrary,
     IPDLCollection,
     LocalizedPreprocessedFiles,
     LocalizedFiles,
     RustLibrary,
     SharedLibrary,
     StaticLibrary,
     UnifiedSources,
     XPIDLModule,
@@ -48,17 +47,16 @@ from mozbuild.frontend.data import (
 from mozbuild.jar import (
     DeprecatedJarManifest,
     JarManifestParser,
 )
 from mozbuild.preprocessor import Preprocessor
 from mozpack.chrome.manifest import parse_manifest_line
 
 from mozbuild.util import (
-    group_unified_files,
     mkdir,
 )
 
 
 class XPIDLManager(object):
     """Helps manage XPCOM IDLs in the context of the build system."""
 
     class Module(object):
@@ -200,18 +198,19 @@ class CommonBackend(BuildBackend):
             return False
 
         return True
 
     def consume_finished(self):
         if len(self._idl_manager.modules):
             self._write_rust_xpidl_summary(self._idl_manager)
             self._handle_idl_manager(self._idl_manager)
-            self._handle_generated_sources(mozpath.join(self.environment.topobjdir, 'dist/include/%s.h' % stem)
-                                           for stem in self._idl_manager.idl_stems())
+            self._handle_generated_sources(
+                mozpath.join(self.environment.topobjdir, 'dist/include/%s.h' % stem)
+                for stem in self._idl_manager.idl_stems())
 
         for config in self._configs:
             self.backend_input_files.add(config.source)
 
         # Write out a machine-readable file describing binaries.
         topobjdir = self.environment.topobjdir
         with self._write_file(mozpath.join(topobjdir, 'binaries.json')) as fh:
             d = {
@@ -395,17 +394,17 @@ class CommonBackend(BuildBackend):
                             output_directory, poison_windows_h=False):
         with self._write_file(mozpath.join(output_directory, unified_file)) as f:
             f.write('#define MOZ_UNIFIED_BUILD\n')
             includeTemplate = '#include "%(cppfile)s"'
             if poison_windows_h:
                 includeTemplate += (
                     '\n'
                     '#if defined(_WINDOWS_) && !defined(MOZ_WRAPPED_WINDOWS_H)\n'
-                    '#pragma message("wrapper failure reason: " MOZ_WINDOWS_WRAPPER_DISABLED_REASON)\n'
+                    '#pragma message("wrapper failure reason: " MOZ_WINDOWS_WRAPPER_DISABLED_REASON)\n'  # noqa
                     '#error "%(cppfile)s included unwrapped windows.h"\n'
                     "#endif")
             includeTemplate += (
                 '\n'
                 '#ifdef PL_ARENA_CONST_ALIGN_MASK\n'
                 '#error "%(cppfile)s uses PL_ARENA_CONST_ALIGN_MASK, '
                 'so it cannot be built in unified mode."\n'
                 '#undef PL_ARENA_CONST_ALIGN_MASK\n'
--- a/python/mozbuild/mozbuild/backend/configenvironment.py
+++ b/python/mozbuild/mozbuild/backend/configenvironment.py
@@ -44,17 +44,17 @@ class BuildConfig(object):
     @classmethod
     def from_config_status(cls, path):
         """Create an instance from a config.status file."""
         code_cache = cls._CODE_CACHE
         mtime = os.path.getmtime(path)
 
         # cache the compiled code as it can be reused
         # we cache it the first time, or if the file changed
-        if not path in code_cache or code_cache[path][0] != mtime:
+        if path not in code_cache or code_cache[path][0] != mtime:
             # Add config.status manually to sys.modules so it gets picked up by
             # iter_modules_in_path() for automatic dependencies.
             mod = ModuleType('config.status')
             mod.__file__ = path
             sys.modules['config.status'] = mod
 
             with open(path, 'rt') as fh:
                 source = fh.read()
@@ -143,31 +143,45 @@ class ConfigEnvironment(object):
             self.import_prefix = self.lib_prefix
             self.import_suffix = '.%s' % self.substs['IMPORT_LIB_SUFFIX']
         else:
             self.import_prefix = self.dll_prefix
             self.import_suffix = self.dll_suffix
         self.bin_suffix = self.substs.get('BIN_SUFFIX', '')
 
         global_defines = [name for name in self.defines
-                          if not name in self.non_global_defines]
-        self.substs['ACDEFINES'] = ' '.join(['-D%s=%s' % (name,
-                                                          shell_quote(self.defines[name]).replace('$', '$$'))
-                                             for name in sorted(global_defines)])
+                          if name not in self.non_global_defines]
+        self.substs["ACDEFINES"] = ' '.join(
+            [
+                '-D%s=%s' % (name, shell_quote(self.defines[name]).replace('$', '$$'))
+                for name in sorted(global_defines)
+            ]
+        )
 
         def serialize(name, obj):
             if isinstance(obj, StringTypes):
                 return obj
             if isinstance(obj, Iterable):
                 return ' '.join(obj)
             raise Exception('Unhandled type %s for %s', type(obj), str(name))
-        self.substs['ALLSUBSTS'] = '\n'.join(sorted(['%s = %s' % (name,
-                                                                  serialize(name, self.substs[name])) for name in self.substs if self.substs[name]]))
-        self.substs['ALLEMPTYSUBSTS'] = '\n'.join(sorted(['%s =' % name
-                                                          for name in self.substs if not self.substs[name]]))
+        self.substs['ALLSUBSTS'] = '\n'.join(
+            sorted([
+                '%s = %s' % (
+                    name,
+                    serialize(name, self.substs[name])
+                    )
+                for name in self.substs if self.substs[name]
+                ])
+            )
+        self.substs['ALLEMPTYSUBSTS'] = '\n'.join(
+            sorted([
+                '%s =' % name
+                for name in self.substs if not self.substs[name]
+                ])
+            )
 
         self.substs = ReadOnlyDict(self.substs)
 
         self.external_source_dir = None
         external = self.substs.get('EXTERNAL_SOURCE_DIR', '')
         if external:
             external = mozpath.normpath(external)
             if not os.path.isabs(external):
--- a/python/mozbuild/mozbuild/backend/cpp_eclipse.py
+++ b/python/mozbuild/mozbuild/backend/cpp_eclipse.py
@@ -1,28 +1,24 @@
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 from __future__ import absolute_import
 
 import errno
 import glob
-import random
 import os
 import shutil
 import subprocess
-import types
 from xml.sax.saxutils import quoteattr
-import xml.etree.ElementTree as ET
 from .common import CommonBackend
 
 from ..frontend.data import (
     ComputedFlags,
-    Defines,
 )
 from mozbuild.base import ExecutionSummary
 
 # TODO Have ./mach eclipse generate the workspace and index it:
 # /Users/bgirard/mozilla/eclipse/eclipse/eclipse/eclipse -application org.eclipse.cdt.managedbuilder.core.headlessbuild -data $PWD/workspace -importAll $PWD/eclipse
 # Open eclipse:
 # /Users/bgirard/mozilla/eclipse/eclipse/eclipse/eclipse -data $PWD/workspace
 
@@ -190,17 +186,17 @@ class CppEclipseBackend(CommonBackend):
         if self._overwriting_workspace:
             return
 
         # We disable the indexer otherwise we're forced to index
         # the whole codebase when importing the project. Indexing the project can take 20 minutes.
         self._write_noindex()
 
         try:
-            process = subprocess.check_call(
+            subprocess.check_call(
                              ["eclipse", "-application", "-nosplash",
                               "org.eclipse.cdt.managedbuilder.core.headlessbuild",
                               "-data", self._workspace_dir, "-importAll", self._project_dir])
         except OSError as e:
             # Remove the workspace directory so we re-generate it and
             # try to import again when the backend is invoked again.
             shutil.rmtree(self._workspace_dir)
 
@@ -377,18 +373,18 @@ PROJECT_TEMPLATE = """<?xml version="1.0
                         <name>org.eclipse.cdt.managedbuilder.core.genmakebuilder</name>
                         <triggers>clean,full,incremental,</triggers>
                         <arguments>
                         </arguments>
                 </buildCommand>
                 <buildCommand>
                         <name>org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder</name>
                         <triggers></triggers>
-			<arguments>
-			</arguments>
+            <arguments>
+            </arguments>
                 </buildCommand>
         </buildSpec>
         <natures>
                 <nature>org.eclipse.cdt.core.cnature</nature>
                 <nature>org.eclipse.cdt.core.ccnature</nature>
                 <nature>org.eclipse.cdt.managedbuilder.core.managedBuildNature</nature>
                 <nature>org.eclipse.cdt.managedbuilder.core.ScannerConfigNature</nature>
         </natures>
@@ -476,33 +472,33 @@ CPROJECT_TEMPLATE_HEADER = """<?xml vers
                                         <extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
                                 </extensions>
                         </storageModule>
                         <storageModule moduleId="cdtBuildSystem" version="4.0.0">
                                 <configuration artifactName="${ProjName}" buildProperties="" description="" id="0.1674256904" name="Default" parent="org.eclipse.cdt.build.core.prefbase.cfg">
                                         <folderInfo id="0.1674256904." name="/" resourcePath="">
                                                 <toolChain id="cdt.managedbuild.toolchain.gnu.cross.exe.debug.1276586933" name="Cross GCC" superClass="cdt.managedbuild.toolchain.gnu.cross.exe.debug">
                                                         <targetPlatform archList="all" binaryParser="" id="cdt.managedbuild.targetPlatform.gnu.cross.710759961" isAbstract="false" osList="all" superClass="cdt.managedbuild.targetPlatform.gnu.cross"/>
-							<builder arguments="--log-no-times build" buildPath="@PROJECT_TOPSRCDIR@" command="@MACH_COMMAND@" enableCleanBuild="false" incrementalBuildTarget="binaries" id="org.eclipse.cdt.build.core.settings.default.builder.1437267827" keepEnvironmentInBuildfile="false" name="Gnu Make Builder" superClass="org.eclipse.cdt.build.core.settings.default.builder"/>
+                            <builder arguments="--log-no-times build" buildPath="@PROJECT_TOPSRCDIR@" command="@MACH_COMMAND@" enableCleanBuild="false" incrementalBuildTarget="binaries" id="org.eclipse.cdt.build.core.settings.default.builder.1437267827" keepEnvironmentInBuildfile="false" name="Gnu Make Builder" superClass="org.eclipse.cdt.build.core.settings.default.builder"/>
                                                 </toolChain>
                                         </folderInfo>
 """
 CPROJECT_TEMPLATE_FILEINFO = """                                        <fileInfo id="0.1674256904.474736658" name="Layers.cpp" rcbsApplicability="disable" resourcePath="tree/gfx/layers/Layers.cpp" toolsToInvoke="org.eclipse.cdt.build.core.settings.holder.582514939.463639939">
                                                 <tool id="org.eclipse.cdt.build.core.settings.holder.582514939.463639939" name="GNU C++" superClass="org.eclipse.cdt.build.core.settings.holder.582514939">
                                                         <option id="org.eclipse.cdt.build.core.settings.holder.symbols.232300236" superClass="org.eclipse.cdt.build.core.settings.holder.symbols" valueType="definedSymbols">
                                                                 <listOptionValue builtIn="false" value="BENWA=BENWAVAL"/>
                                                         </option>
                                                         <inputType id="org.eclipse.cdt.build.core.settings.holder.inType.1942876228" languageId="org.eclipse.cdt.core.g++" languageName="GNU C++" sourceContentType="org.eclipse.cdt.core.cxxSource,org.eclipse.cdt.core.cxxHeader" superClass="org.eclipse.cdt.build.core.settings.holder.inType"/>
                                                 </tool>
                                         </fileInfo>
 """
 CPROJECT_TEMPLATE_FOOTER = """
-					<sourceEntries>
-						<entry excluding="**/lib*|**/third_party/|tree/*.xcodeproj/|tree/.cargo/|tree/.vscode/|tree/build/|tree/extensions/|tree/gfx/angle/|tree/gfx/cairo/|tree/gfx/skia/skia/|tree/intl/icu/|tree/js/|tree/media/|tree/modules/freetype2|tree/modules/pdfium/|tree/netwerk/|tree/netwerk/sctp|tree/netwerk/srtp|tree/nsprpub/lib|tree/nsprpub/pr/src|tree/other-licenses/|tree/parser/|tree/python/|tree/security/nss/|tree/tools/" flags="VALUE_WORKSPACE_PATH" kind="sourcePath" name=""/>
-					</sourceEntries>
+                    <sourceEntries>
+                        <entry excluding="**/lib*|**/third_party/|tree/*.xcodeproj/|tree/.cargo/|tree/.vscode/|tree/build/|tree/extensions/|tree/gfx/angle/|tree/gfx/cairo/|tree/gfx/skia/skia/|tree/intl/icu/|tree/js/|tree/media/|tree/modules/freetype2|tree/modules/pdfium/|tree/netwerk/|tree/netwerk/sctp|tree/netwerk/srtp|tree/nsprpub/lib|tree/nsprpub/pr/src|tree/other-licenses/|tree/parser/|tree/python/|tree/security/nss/|tree/tools/" flags="VALUE_WORKSPACE_PATH" kind="sourcePath" name=""/>
+                    </sourceEntries>
                                 </configuration>
                         </storageModule>
                         <storageModule moduleId="org.eclipse.cdt.core.externalSettings"/>
                 </cconfiguration>
         </storageModule>
         <storageModule moduleId="cdtBuildSystem" version="4.0.0">
                 <project id="Empty.null.1281234804" name="Empty"/>
         </storageModule>
@@ -534,48 +530,48 @@ WORKSPACE_LANGUAGE_SETTINGS_TEMPLATE = "
 # The settings set via this template can be found in the UI by opening
 # the Properties for a directory in the Project Explorer tab, then going to
 # C/C++ General > Preprocessor Include Paths, Macros, etc., selecting the
 # C++ item from the Languages column, and then expanding the
 # CDT User Settings Entries item to the right.
 
 LANGUAGE_SETTINGS_TEMPLATE_HEADER = """<?xml version="1.0" encoding="UTF-8" standalone="no"?>
 <project>
-	<configuration id="0.1674256904" name="Default">
-		<extension point="org.eclipse.cdt.core.LanguageSettingsProvider">
-			<provider class="org.eclipse.cdt.core.language.settings.providers.LanguageSettingsGenericProvider" id="org.eclipse.cdt.ui.UserLanguageSettingsProvider" name="CDT User Setting Entries" prefer-non-shared="true" store-entries-with-project="true">
-				<language id="org.eclipse.cdt.core.g++">
+    <configuration id="0.1674256904" name="Default">
+        <extension point="org.eclipse.cdt.core.LanguageSettingsProvider">
+            <provider class="org.eclipse.cdt.core.language.settings.providers.LanguageSettingsGenericProvider" id="org.eclipse.cdt.ui.UserLanguageSettingsProvider" name="CDT User Setting Entries" prefer-non-shared="true" store-entries-with-project="true">
+                <language id="org.eclipse.cdt.core.g++">
 """
 
-LANGUAGE_SETTINGS_TEMPLATE_DIR_HEADER = """					<resource project-relative-path="@RELATIVE_PATH@">
-						<entry kind="includeFile" name="@PREINCLUDE_FILE_PATH@">
-							<flag value="LOCAL"/>
-						</entry>
+LANGUAGE_SETTINGS_TEMPLATE_DIR_HEADER = """                 <resource project-relative-path="@RELATIVE_PATH@">
+                        <entry kind="includeFile" name="@PREINCLUDE_FILE_PATH@">
+                            <flag value="LOCAL"/>
+                        </entry>
 """
 
-LANGUAGE_SETTINGS_TEMPLATE_DIR_INCLUDE = """						<entry kind="includePath" name="@INCLUDE_PATH@">
-							<flag value="LOCAL"/>
-						</entry>
+LANGUAGE_SETTINGS_TEMPLATE_DIR_INCLUDE = """                        <entry kind="includePath" name="@INCLUDE_PATH@">
+                            <flag value="LOCAL"/>
+                        </entry>
 """
 
-LANGUAGE_SETTINGS_TEMPLATE_DIR_DEFINE = """						<entry kind="macro" name="@NAME@" value=@VALUE@/>
+LANGUAGE_SETTINGS_TEMPLATE_DIR_DEFINE = """                        <entry kind="macro" name="@NAME@" value=@VALUE@/>
 """
 
-LANGUAGE_SETTINGS_TEMPLATE_DIR_FOOTER = """					</resource>
+LANGUAGE_SETTINGS_TEMPLATE_DIR_FOOTER = """                    </resource>
 """
 
-LANGUAGE_SETTINGS_TEMPLATE_FOOTER = """				</language>
-			</provider>
-			<provider class="org.eclipse.cdt.internal.build.crossgcc.CrossGCCBuiltinSpecsDetector" console="false" env-hash="-859273372804152468" id="org.eclipse.cdt.build.crossgcc.CrossGCCBuiltinSpecsDetector" keep-relative-paths="false" name="CDT Cross GCC Built-in Compiler Settings" parameter="@COMPILER_FLAGS@ -E -P -v -dD &quot;${INPUTS}&quot; -std=c++11" prefer-non-shared="true" store-entries-with-project="true">
-				<language-scope id="org.eclipse.cdt.core.gcc"/>
-				<language-scope id="org.eclipse.cdt.core.g++"/>
-			</provider>
-			<provider-reference id="org.eclipse.cdt.managedbuilder.core.MBSLanguageSettingsProvider" ref="shared-provider"/>
-		</extension>
-	</configuration>
+LANGUAGE_SETTINGS_TEMPLATE_FOOTER = """                </language>
+                </provider>
+            <provider class="org.eclipse.cdt.internal.build.crossgcc.CrossGCCBuiltinSpecsDetector" console="false" env-hash="-859273372804152468" id="org.eclipse.cdt.build.crossgcc.CrossGCCBuiltinSpecsDetector" keep-relative-paths="false" name="CDT Cross GCC Built-in Compiler Settings" parameter="@COMPILER_FLAGS@ -E -P -v -dD &quot;${INPUTS}&quot; -std=c++11" prefer-non-shared="true" store-entries-with-project="true">
+                <language-scope id="org.eclipse.cdt.core.gcc"/>
+                <language-scope id="org.eclipse.cdt.core.g++"/>
+            </provider>
+            <provider-reference id="org.eclipse.cdt.managedbuilder.core.MBSLanguageSettingsProvider" ref="shared-provider"/>
+        </extension>
+    </configuration>
 </project>
 """
 
 
 GECKO_LAUNCH_CONFIG_TEMPLATE = """<?xml version="1.0" encoding="UTF-8" standalone="no"?>
 <launchConfiguration type="org.eclipse.cdt.launch.applicationLaunchType">
 <booleanAttribute key="org.eclipse.cdt.dsf.gdb.AUTO_SOLIB" value="true"/>
 <listAttribute key="org.eclipse.cdt.dsf.gdb.AUTO_SOLIB_LIST"/>
--- a/python/mozbuild/mozbuild/backend/fastermake.py
+++ b/python/mozbuild/mozbuild/backend/fastermake.py
@@ -205,29 +205,36 @@ class FasterMakeBackend(CommonBackend, P
         # Add l10n dependencies we inferred:
         for target, deps in self._l10n_dependencies.iteritems():
             mk.create_rule([target]).add_dependencies(
                 '%s' % d[0] for d in deps)
             for (merge, ref_file, l10n_file) in deps:
                 rule = mk.create_rule([merge]).add_dependencies(
                     [ref_file, l10n_file] + python_deps)
                 rule.add_commands(
-                    ['$(PYTHON) -m mozbuild.action.l10n_merge --output {} --ref-file {} --l10n-file {}'.format(merge, ref_file, l10n_file)])
+                    [
+                        '$(PYTHON) -m mozbuild.action.l10n_merge '
+                        '--output {} --ref-file {} --l10n-file {}'.format(
+                            merge, ref_file, l10n_file
+                        )
+                    ]
+                )
                 # Add a dummy rule for the l10n file since it might not exist.
                 mk.create_rule([l10n_file])
 
         mk.add_statement('include $(TOPSRCDIR)/config/faster/rules.mk')
 
         for base, install_manifest in self._install_manifests.iteritems():
             with self._write_file(
                     mozpath.join(self.environment.topobjdir, 'faster',
                                  'install_%s' % base.replace('/', '_'))) as fh:
                 install_manifest.write(fileobj=fh)
 
-        # For artifact builds only, write a single unified manifest for consumption by |mach watch|.
+        # For artifact builds only, write a single unified manifest
+        # for consumption by |mach watch|.
         if self.environment.is_artifact_build:
             unified_manifest = InstallManifest()
             for base, install_manifest in self._install_manifests.iteritems():
                 # Expect 'dist/bin/**', which includes 'dist/bin' with no trailing slash.
                 assert base.startswith('dist/bin')
                 base = base[len('dist/bin'):]
                 if base and base[0] == '/':
                     base = base[1:]
--- a/python/mozbuild/mozbuild/backend/mach_commands.py
+++ b/python/mozbuild/mozbuild/backend/mach_commands.py
@@ -1,17 +1,16 @@
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 from __future__ import absolute_import, print_function, unicode_literals
 
 import argparse
 import os
-import sys
 import subprocess
 import which
 
 from mozbuild.base import (
     MachCommandBase,
 )
 
 from mach.decorators import (
@@ -53,19 +52,21 @@ class MachCommands(MachCommandBase):
         config_status = os.path.join(self.topobjdir, 'config.status')
         args = [python, config_status, '--backend=%s' % backend]
         res = self._run_command_in_objdir(args=args, pass_thru=True, ensure_exit_code=False)
         if res != 0:
             return 1
 
         if ide == 'eclipse':
             eclipse_workspace_dir = self.get_eclipse_workspace_path()
-            process = subprocess.check_call(['eclipse', '-data', eclipse_workspace_dir])
+            subprocess.check_call(['eclipse', '-data', eclipse_workspace_dir])
         elif ide == 'visualstudio':
             visual_studio_workspace_dir = self.get_visualstudio_workspace_path()
-            process = subprocess.check_call(['explorer.exe', visual_studio_workspace_dir])
+            subprocess.check_call(
+                ['explorer.exe', visual_studio_workspace_dir]
+            )
 
     def get_eclipse_workspace_path(self):
         from mozbuild.backend.cpp_eclipse import CppEclipseBackend
         return CppEclipseBackend.get_workspace_path(self.topsrcdir, self.topobjdir)
 
     def get_visualstudio_workspace_path(self):
         return os.path.join(self.topobjdir, 'msvc', 'mozilla.sln')
--- a/python/mozbuild/mozbuild/backend/recursivemake.py
+++ b/python/mozbuild/mozbuild/backend/recursivemake.py
@@ -46,17 +46,16 @@ from ..frontend.data import (
     HostGeneratedSources,
     HostLibrary,
     HostProgram,
     HostRustProgram,
     HostSimpleProgram,
     HostSources,
     InstallationTarget,
     JARManifest,
-    Library,
     Linkable,
     LocalInclude,
     LocalizedFiles,
     LocalizedPreprocessedFiles,
     ObjdirFiles,
     ObjdirPreprocessedFiles,
     PerSourceFlag,
     PgoGenerateOnlySources,
@@ -308,17 +307,17 @@ class RecursiveMakeTraversal(object):
         deps = {}
 
         def recurse(start_node, prev_nodes=None):
             current, parallel, sequential = self.call_filter(start_node, filter)
             if current is not None:
                 if start_node != '':
                     deps[start_node] = prev_nodes
                 prev_nodes = (start_node,)
-            if not start_node in self._traversal:
+            if start_node not in self._traversal:
                 return prev_nodes
             parallel_nodes = []
             for node in parallel:
                 nodes = recurse(node, prev_nodes)
                 if nodes and nodes != ('',):
                     parallel_nodes.extend(nodes)
             if parallel_nodes:
                 prev_nodes = tuple(parallel_nodes)
@@ -334,17 +333,17 @@ class RecursiveMakeTraversal(object):
         make traversal order.
         """
         if filter is None:
             filter = self.default_filter
 
         current, parallel, sequential = self.call_filter(start, filter)
         if current is not None:
             yield start
-        if not start in self._traversal:
+        if start not in self._traversal:
             return
         for node in parallel:
             for n in self.traverse(node, filter):
                 yield n
         for dir in sequential:
             for d in self.traverse(dir, filter):
                 yield d
 
@@ -599,35 +598,40 @@ class RecursiveMakeBackend(CommonBackend
                         # handling.
                         backend_file.write('%s:: %s\n' % (tier, stub_file))
                 for output in outputs:
                     backend_file.write('%s: %s ;\n' % (output, stub_file))
                     backend_file.write('GARBAGE += %s\n' % output)
                 backend_file.write('GARBAGE += %s\n' % stub_file)
                 backend_file.write('EXTRA_MDDEPEND_FILES += %s\n' % dep_file)
 
-                backend_file.write("""{stub}: {script}{inputs}{backend}{force}
+                backend_file.write((
+                    """{stub}: {script}{inputs}{backend}{force}
 \t$(REPORT_BUILD)
-\t$(call py_action,file_generate,{locale}{script} {method} {output} $(MDDEPDIR)/{dep_file} {stub}{inputs}{flags})
+\t$(call py_action,file_generate,{locale}{script} """  # wrap for E501
+                    """{method} {output} $(MDDEPDIR)/{dep_file} {stub}{inputs}{flags})
 \t@$(TOUCH) $@
 
-""".format(stub=stub_file,
+""").format(
+                    stub=stub_file,
                     output=first_output,
                     dep_file=dep_file,
                     inputs=' ' + ' '.join(inputs) if inputs else '',
                     flags=' ' + ' '.join(shell_quote(f) for f in obj.flags) if obj.flags else '',
                     backend=' backend.mk' if obj.flags else '',
                     # Locale repacks repack multiple locales from a single configured objdir,
                     # so standard mtime dependencies won't work properly when the build is re-run
                     # with a different locale as input. IS_LANGUAGE_REPACK will reliably be set
                     # in this situation, so simply force the generation to run in that case.
                     force=force,
                     locale='--locale=$(AB_CD) ' if obj.localized else '',
                     script=obj.script,
-                    method=obj.method))
+                    method=obj.method
+                    )
+                )
 
         elif isinstance(obj, JARManifest):
             self._no_skip['libs'].add(backend_file.relobjdir)
             backend_file.write('JAR_MANIFEST := %s\n' % obj.path.full_path)
 
         elif isinstance(obj, RustProgram):
             self._process_rust_program(obj, backend_file)
             self._rust_dirs.add(obj.relobjdir)
@@ -813,18 +817,20 @@ class RecursiveMakeBackend(CommonBackend
         compile_roots = [t for t, deps in self._compile_graph.iteritems()
                          if not deps or t not in all_compile_deps]
 
         def add_category_rules(category, roots, graph):
             rule = root_deps_mk.create_rule(['recurse_%s' % category])
             # Directories containing rust compilations don't generally depend
             # on other directories in the tree, so putting them first here will
             # start them earlier in the build.
-            rule.add_dependencies(chain((r for r in roots if mozpath.dirname(r) in self._rust_dirs),
-                                        (r for r in roots if mozpath.dirname(r) not in self._rust_dirs)))
+            rule.add_dependencies(
+                chain((r for r in roots if mozpath.dirname(r) in self._rust_dirs),
+                      (r for r in roots if mozpath.dirname(r) not in self._rust_dirs))
+                )
             for target, deps in sorted(graph.items()):
                 if deps:
                     rule = root_deps_mk.create_rule([target])
                     rule.add_dependencies(deps)
 
         non_default_roots = defaultdict(list)
         non_default_graphs = defaultdict(lambda: OrderedDefaultDict(set))
 
@@ -897,19 +903,20 @@ class RecursiveMakeBackend(CommonBackend
             "# compilation times and debug information size."
         makefile.add_statement(explanation)
 
         all_sources = ' '.join(source for source, _ in unified_source_mapping)
         makefile.add_statement('%s := %s' % (unified_files_makefile_variable,
                                              all_sources))
 
         if include_curdir_build_rules:
-            makefile.add_statement('\n'
-                                   '# Make sometimes gets confused between "foo" and "$(CURDIR)/foo".\n'
-                                   '# Help it out by explicitly specifiying dependencies.')
+            makefile.add_statement(
+                '\n'
+                '# Make sometimes gets confused between "foo" and "$(CURDIR)/foo".\n'
+                '# Help it out by explicitly specifiying dependencies.')
             makefile.add_statement('all_absolute_unified_files := \\\n'
                                    '  $(addprefix $(CURDIR)/,$(%s))'
                                    % unified_files_makefile_variable)
             rule = makefile.create_rule(['$(all_absolute_unified_files)'])
             rule.add_dependencies(['$(CURDIR)/%: %'])
 
     def _check_blacklisted_variables(self, makefile_in, makefile_content):
         if b'EXTERNALLY_MANAGED_MAKE_FILE' in makefile_content:
@@ -1063,20 +1070,20 @@ class RecursiveMakeBackend(CommonBackend
     def _process_directory_traversal(self, obj, backend_file):
         """Process a data.DirectoryTraversal instance."""
         fh = backend_file.fh
 
         def relativize(base, dirs):
             return (mozpath.relpath(d.translated, base) for d in dirs)
 
         if obj.dirs:
-            fh.write('DIRS := %s\n' % ' '.join(
-                relativize(backend_file.objdir, obj.dirs)))
-            self._traversal.add(backend_file.relobjdir,
-                                dirs=relativize(self.environment.topobjdir, obj.dirs))
+            fh.write('DIRS := %s\n' % ' '.join(relativize(backend_file.objdir, obj.dirs)))
+            self._traversal.add(
+                backend_file.relobjdir, dirs=relativize(self.environment.topobjdir, obj.dirs)
+            )
 
         # The directory needs to be registered whether subdirectories have been
         # registered or not.
         self._traversal.add(backend_file.relobjdir)
 
     def _process_defines(self, obj, backend_file, which='DEFINES'):
         """Output the DEFINES rules to the given backend file."""
         defines = list(obj.get_defines())
@@ -1091,33 +1098,34 @@ class RecursiveMakeBackend(CommonBackend
         if obj.xpiname:
             backend_file.write('XPI_NAME = %s\n' % (obj.xpiname))
         if obj.subdir:
             backend_file.write('DIST_SUBDIR = %s\n' % (obj.subdir))
         if obj.target and not obj.is_custom():
             backend_file.write('FINAL_TARGET = $(DEPTH)/%s\n' % (obj.target))
         else:
             backend_file.write(
-                'FINAL_TARGET = $(if $(XPI_NAME),$(DIST)/xpi-stage/$(XPI_NAME),$(DIST)/bin)$(DIST_SUBDIR:%=/%)\n')
+                'FINAL_TARGET = $(if $(XPI_NAME),$(DIST)/xpi-stage/$(XPI_NAME),'
+                '$(DIST)/bin)$(DIST_SUBDIR:%=/%)\n'
+                )
 
         if not obj.enabled:
             backend_file.write('NO_DIST_INSTALL := 1\n')
 
     def _handle_idl_manager(self, manager):
         build_files = self._install_manifests['xpidl']
 
         for p in ('Makefile', 'backend.mk', '.deps/.mkdir.done'):
             build_files.add_optional_exists(p)
 
         for stem in manager.idl_stems():
             self._install_manifests['dist_include'].add_optional_exists('%s.h' % stem)
 
         for module in manager.modules:
-            build_files.add_optional_exists(mozpath.join('.deps',
-                                                         '%s.pp' % module))
+            build_files.add_optional_exists(mozpath.join('.deps', '%s.pp' % module))
 
         modules = manager.modules
         xpt_modules = sorted(modules.keys())
 
         mk = Makefile()
         all_directories = set()
 
         for module_name in xpt_modules:
@@ -1297,18 +1305,19 @@ class RecursiveMakeBackend(CommonBackend
 
     def _process_per_source_flag(self, per_source_flag, backend_file):
         for flag in per_source_flag.flags:
             backend_file.write('%s_FLAGS += %s\n' %
                                (mozpath.basename(per_source_flag.file_name), flag))
 
     def _process_computed_flags(self, computed_flags, backend_file):
         for var, flags in computed_flags.get_flags():
-            backend_file.write('COMPUTED_%s += %s\n' % (var,
-                                                        ' '.join(make_quote(shell_quote(f)) for f in flags)))
+            backend_file.write(
+                'COMPUTED_%s += %s\n' % (var,
+                                         ' '.join(make_quote(shell_quote(f)) for f in flags)))
 
     def _process_non_default_target(self, libdef, target_name, backend_file):
         backend_file.write("%s:: %s\n" % (libdef.output_category, target_name))
         backend_file.write('MOZBUILD_NON_DEFAULT_TARGETS += %s\n' % target_name)
 
     def _process_shared_library(self, libdef, backend_file):
         backend_file.write_once('LIBRARY_NAME := %s\n' % libdef.basename)
         backend_file.write('FORCE_SHARED_LIB := 1\n')
@@ -1362,17 +1371,16 @@ class RecursiveMakeBackend(CommonBackend
         return '%s/%s' % (mozpath.relpath(obj.objdir,
                                           self.environment.topobjdir), target_name)
 
     def _process_linked_libraries(self, obj, backend_file):
         def pretty_relpath(lib, name):
             return os.path.normpath(mozpath.join(mozpath.relpath(lib.objdir, obj.objdir),
                                                  name))
 
-        topobjdir = mozpath.normsep(obj.topobjdir)
         # This will create the node even if there aren't any linked libraries.
         build_target = self._build_target_for_obj(obj)
         self._compile_graph[build_target]
 
         objs, pgo_gen_objs, no_pgo_objs, shared_libs, os_libs, static_libs = self._expand_libs(obj)
 
         obj_target = obj.name
         if isinstance(obj, Program):
@@ -1517,18 +1525,18 @@ class RecursiveMakeBackend(CommonBackend
             for f in files:
                 assert not isinstance(f, RenamedSourcePath)
                 dest = mozpath.join(reltarget, path, f.target_basename)
                 if not isinstance(f, ObjDirPath):
                     if '*' in f:
                         if f.startswith('/') or isinstance(f, AbsolutePath):
                             basepath, wild = os.path.split(f.full_path)
                             if '*' in basepath:
-                                raise Exception("Wildcards are only supported in the filename part of "
-                                                "srcdir-relative or absolute paths.")
+                                raise Exception("Wildcards are only supported in the filename part"
+                                                " of srcdir-relative or absolute paths.")
 
                             install_manifest.add_pattern_link(basepath, wild, path)
                         else:
                             install_manifest.add_pattern_link(f.srcdir, f, path)
                     else:
                         install_manifest.add_link(f.full_path, dest)
                 else:
                     install_manifest.add_optional_exists(dest)
@@ -1740,18 +1748,19 @@ class RecursiveMakeBackend(CommonBackend
 
         mk.add_statement('ALL_IPDLSRCS := %s %s' % (' '.join(sorted_nonstatic_ipdl_basenames),
                                                     ' '.join(sorted_static_ipdl_sources)))
 
         self._add_unified_build_rules(mk, unified_ipdl_cppsrcs_mapping,
                                       unified_files_makefile_variable='CPPSRCS')
 
         # Preprocessed ipdl files are generated in ipdl_dir.
-        mk.add_statement('IPDLDIRS := %s %s' % (ipdl_dir, ' '.join(sorted(set(mozpath.dirname(p)
-                                                                              for p in sorted_static_ipdl_sources)))))
+        mk.add_statement(
+            'IPDLDIRS := %s %s' % (ipdl_dir, ' '.join(sorted(set(mozpath.dirname(p)
+                                                      for p in sorted_static_ipdl_sources)))))
 
         with self._write_file(mozpath.join(ipdl_dir, 'ipdlsrcs.mk')) as ipdls:
             mk.dump(ipdls, removal_guard=False)
 
     def _handle_webidl_build(self, bindings_dir, unified_source_mapping,
                              webidls, expected_build_output_files,
                              global_define_files):
         include_dir = mozpath.join(self.environment.topobjdir, 'dist',
--- a/python/mozbuild/mozbuild/backend/tup.py
+++ b/python/mozbuild/mozbuild/backend/tup.py
@@ -7,22 +7,19 @@ from __future__ import absolute_import, 
 import os
 import gzip
 import itertools
 import json
 import sys
 import shutil
 
 import mozpack.path as mozpath
-from mozbuild import shellutil
 from mozbuild.analyze.graph import Graph
 from mozbuild.analyze.hg import Report
 from mozbuild.base import MozbuildObject
-from mozbuild.backend.base import PartialBackend, HybridBackend
-from mozbuild.backend.recursivemake import RecursiveMakeBackend
 from mozbuild.mozconfig import MozconfigLoader
 from mozbuild.shellutil import quote as shell_quote
 from mozbuild.util import OrderedDefaultDict
 from collections import defaultdict
 import multiprocessing
 
 from mozpack.files import (
     FileFinder,
@@ -54,17 +51,16 @@ from ..frontend.data import (
     RustProgram,
     SharedLibrary,
     Sources,
     StaticLibrary,
     VariablePassthru,
 )
 from ..util import (
     FileAvoidWrite,
-    expand_variables,
 )
 from ..frontend.context import (
     AbsolutePath,
     ObjDirPath,
     RenamedSourcePath,
 )
 from .cargo_build_defs import (
     cargo_extra_outputs,
@@ -142,17 +138,18 @@ class BackendTupfile(object):
             # same.
             flags += "o"
 
         if display:
             caret_text = flags + ' ' + display
         else:
             caret_text = flags
 
-        self.write(': %(inputs)s%(extra_inputs)s |> %(display)s%(cmd)s |> %(outputs)s%(output_group)s\n' % {
+        self.write((': %(inputs)s%(extra_inputs)s |> %(display)s%(cmd)s |> '
+                    '%(outputs)s%(output_group)s\n') % {
             'inputs': ' '.join(inputs),
             'extra_inputs': ' | ' + ' '.join(extra_inputs) if extra_inputs else '',
             'display': '^%s^ ' % caret_text if caret_text else '',
             'cmd': ' '.join(cmd),
             'outputs': ' '.join(outputs),
             'output_group': ' ' + output_group if output_group else '',
         })
 
@@ -267,17 +264,18 @@ class TupBackend(CommonBackend):
         self._early_generated_files = self._output_group('early-generated-files')
 
         self._shlibs = self._output_group('shlibs')
         self._default_group = self._output_group('default')
 
         self._rust_cmds = set()
 
         self._built_in_addons = set()
-        self._built_in_addons_file = 'dist/bin/browser/chrome/browser/content/browser/built_in_addons.json'
+        self._built_in_addons_file = \
+            'dist/bin/browser/chrome/browser/content/browser/built_in_addons.json'
 
     def _output_group(self, label):
         if label:
             return '$(MOZ_OBJ_ROOT)/<%s>' % label
 
     def _rust_output_group(self, label):
         if label:
             return self._output_group('rust-' + label)
@@ -667,35 +665,38 @@ class TupBackend(CommonBackend):
 
         if self._built_in_addons:
             with self._write_file(mozpath.join(self.environment.topobjdir,
                                                self._built_in_addons_file)) as fh:
                 json.dump({'system': sorted(list(self._built_in_addons))}, fh)
 
         for objdir, backend_file in sorted(self._backend_files.items()):
             backend_file.gen_sources_rules([self._installed_files])
-            for var, gen_method in ((backend_file.shared_lib, self._gen_shared_library),
-                                    (backend_file.static_lib and backend_file.static_lib.no_expand_lib,
-                                     self._gen_static_library),
-                                    (backend_file.programs, self._gen_programs),
-                                    (backend_file.host_programs, self._gen_host_programs)):
+            for var, gen_method in (
+                (backend_file.shared_lib, self._gen_shared_library),
+                (backend_file.static_lib and backend_file.static_lib.no_expand_lib,
+                 self._gen_static_library),
+                (backend_file.programs, self._gen_programs),
+                (backend_file.host_programs, self._gen_host_programs)
+            ):
                 if var:
                     backend_file.export_shell()
                     backend_file.export_icecc()
                     gen_method(backend_file)
             for obj in backend_file.delayed_generated_files:
                 self._process_generated_file(backend_file, obj)
             for path, output, output_group in backend_file.delayed_installed_files:
                 backend_file.symlink_rule(path, output=output, output_group=output_group)
             with self._write_file(fh=backend_file):
                 pass
 
         with self._write_file(mozpath.join(self.environment.topobjdir, 'Tuprules.tup')) as fh:
-            acdefines_flags = ' '.join(['-D%s=%s' % (name, shell_quote(value))
-                                        for (name, value) in sorted(self.environment.acdefines.iteritems())])
+            acdefines_flags = ' '.join(
+                ['-D%s=%s' % (name, shell_quote(value))
+                 for (name, value) in sorted(self.environment.acdefines.iteritems())])
             # TODO: AB_CD only exists in Makefiles at the moment.
             acdefines_flags += ' -DAB_CD=en-US'
 
             # Use BUILD_FASTER to avoid CXXFLAGS/CPPFLAGS in
             # toolkit/content/buildconfig.html
             acdefines_flags += ' -DBUILD_FASTER=1'
 
             fh.write('MOZ_OBJ_ROOT = $(TUP_CWD)\n')
@@ -804,23 +805,21 @@ class TupBackend(CommonBackend):
         return env
 
     def _gen_cargo_rules(self, obj,  build_plan, cargo_env, output_group):
         invocations = build_plan['invocations']
         processed = set()
 
         # Enable link-time optimization for release builds.
         cargo_library_flags = []
-        if (not obj.config.substs.get('DEVELOPER_OPTIONS') and
-            not obj.config.substs.get('MOZ_DEBUG_RUST')):
+        if not obj.config.substs.get('DEVELOPER_OPTIONS') and not obj.config.substs.get(
+            'MOZ_DEBUG_RUST'
+        ):
             cargo_library_flags += ['-C', 'lto']
 
-        rust_build_home = mozpath.join(self.environment.topobjdir,
-                                       'toolkit/library/rust')
-
         def display_name(invocation):
             output_str = ''
             if invocation['outputs']:
                 outputs = [os.path.basename(f) for f in invocation['outputs']]
                 output_str = ' -> [%s]' % self._trim_outputs(outputs)
             return '{name} v{version} {kind}{output}'.format(
                 name=invocation['package_name'],
                 version=invocation['package_version'],
@@ -864,17 +863,19 @@ class TupBackend(CommonBackend):
             if (invocation['target_kind'][0] == 'staticlib' and
                 obj.basename == shortname):
                 command += cargo_library_flags
 
             outputs = invocation['outputs']
 
             invocation['full-deps'] = set()
 
-            if os.path.basename(invocation['program']) in ['build-script-build', 'build-script-main']:
+            if os.path.basename(invocation['program']) in [
+                'build-script-build', 'build-script-main'
+            ]:
                 out_dir = invocation['env']['OUT_DIR']
                 for output in cargo_extra_outputs.get(shortname, []):
                     outputs.append(os.path.join(out_dir, output))
 
                 script_stdout = mozpath.join(out_dir,
                                              '%s_%s_build_out.txt' % (shortname,
                                                                       invocation['kind']))
                 command.extend(['>', script_stdout])
@@ -1114,18 +1115,19 @@ class TupBackend(CommonBackend):
                     output_group = self._installed_files
 
                 if not isinstance(f, ObjDirPath):
                     backend_file = self._get_backend_file(mozpath.join(target, path))
                     if '*' in f:
                         if f.startswith('/') or isinstance(f, AbsolutePath):
                             basepath, wild = os.path.split(f.full_path)
                             if '*' in basepath:
-                                raise Exception("Wildcards are only supported in the filename part of "
-                                                "srcdir-relative or absolute paths.")
+                                raise Exception(
+                                    "Wildcards are only supported in the filename part of "
+                                    "srcdir-relative or absolute paths.")
 
                             # TODO: This is only needed for Windows, so we can
                             # skip this for now.
                             pass
                         else:
                             def _prefix(s):
                                 for p in mozpath.split(s):
                                     if '*' not in p:
@@ -1144,29 +1146,29 @@ class TupBackend(CommonBackend):
                             # can rely on 'path' to be our destination path relative
                             # to any wildcard match. Otherwise, the output file may
                             # contribute to our destination directory.
                             if not isinstance(f, RenamedSourcePath):
                                 output_dir = ''.join(_prefix(mozpath.dirname(f)))
 
                             finder = FileFinder(prefix)
                             for p, _ in finder.find(f.full_path[len(prefix):]):
-                                install_dir = prefix[len(obj.srcdir) + 1:]
                                 output = p
                                 if f.target_basename and '*' not in f.target_basename:
                                     output = mozpath.join(f.target_basename, output)
                                 backend_file.symlink_rule(mozpath.join(prefix, p),
                                                           output=mozpath.join(output_dir, output),
                                                           output_group=output_group)
                     else:
                         backend_file.symlink_rule(
                             f.full_path, output=f.target_basename, output_group=output_group)
                 else:
                     if (self.environment.is_artifact_build and
-                        any(mozpath.match(f.target_basename, p) for p in self._compile_env_gen_files)):
+                        any(mozpath.match(f.target_basename, p)
+                            for p in self._compile_env_gen_files)):
                         # If we have an artifact build we never would have generated this file,
                         # so do not attempt to install it.
                         continue
 
                     output = mozpath.join('$(MOZ_OBJ_ROOT)', target, path,
                                           f.target_basename)
                     gen_backend_file = self._get_backend_file(f.context.relobjdir)
                     if gen_backend_file.requires_delay([f]):
--- a/python/mozbuild/mozbuild/backend/visualstudio.py
+++ b/python/mozbuild/mozbuild/backend/visualstudio.py
@@ -5,17 +5,16 @@
 # This file contains a build backend for generating Visual Studio project
 # files.
 
 from __future__ import absolute_import, unicode_literals
 
 import errno
 import os
 import re
-import types
 import uuid
 
 from xml.dom import getDOMImplementation
 
 from mozpack.files import FileFinder
 
 from .common import CommonBackend
 from ..frontend.data import (
@@ -143,26 +142,27 @@ class VisualStudioBackend(CommonBackend)
 
         # Generate projects that can be used to build common targets.
         for target in ('export', 'binaries', 'tools', 'full'):
             basename = 'target_%s' % target
             command = '$(SolutionDir)\\mach.bat build'
             if target != 'full':
                 command += ' %s' % target
 
-            project_id = self._write_vs_project(out_proj_dir, basename, target,
-                                                build_command=command,
-                                                clean_command='$(SolutionDir)\\mach.bat build clean')
+            project_id = self._write_vs_project(
+                out_proj_dir, basename, target, build_command=command,
+                clean_command='$(SolutionDir)\\mach.bat build clean')
 
             projects[basename] = (project_id, basename, target)
 
         # A project that can be used to regenerate the visual studio projects.
         basename = 'target_vs'
-        project_id = self._write_vs_project(out_proj_dir, basename, 'visual-studio',
-                                            build_command='$(SolutionDir)\\mach.bat build-backend -b VisualStudio')
+        project_id = self._write_vs_project(
+            out_proj_dir, basename, 'visual-studio',
+            build_command='$(SolutionDir)\\mach.bat build-backend -b VisualStudio')
         projects[basename] = (project_id, basename, 'visual-studio')
 
         # Write out a shared property file with common variables.
         props_path = os.path.join(out_proj_dir, 'mozilla.props')
         with self._write_file(props_path, mode='rb') as fh:
             self._write_props(fh)
 
         # Generate some wrapper scripts that allow us to invoke mach inside
@@ -234,24 +234,24 @@ class VisualStudioBackend(CommonBackend)
                     if self.environment.substs.get('MOZ_LAUNCHER_PROCESS', False):
                         app_args += ' -wait-for-browser'
                     debugger = ('$(TopObjDir)\\dist\\bin\\%s' % item, app_args)
                 else:
                     debugger = ('$(TopObjDir)\\dist\\bin\\%s' % item, '')
 
             basename = '%s_%s' % (prefix, item)
 
-            project_id = self._write_vs_project(out_dir, basename, item,
-                                                includes=includes,
-                                                forced_includes=[
-                                                    '$(TopObjDir)\\dist\\include\\mozilla-config.h'],
-                                                defines=defines,
-                                                headers=headers,
-                                                sources=sources,
-                                                debugger=debugger)
+            project_id = self._write_vs_project(
+                out_dir, basename, item,
+                includes=includes,
+                forced_includes=['$(TopObjDir)\\dist\\include\\mozilla-config.h'],
+                defines=defines,
+                headers=headers,
+                sources=sources,
+                debugger=debugger)
 
             projects[basename] = (project_id, basename, item)
 
         return projects
 
     def _write_solution(self, fh, projects):
         # Visual Studio appears to write out its current version in the
         # solution file. Instead of trying to figure out what version it will
@@ -457,18 +457,18 @@ class VisualStudioBackend(CommonBackend)
         fh.write(b'"%%MOZILLABUILD%%\\msys\\bin\\bash" '
                  b'-c "%s/mach --log-no-times %%1 %%2 %%3 %%4 %%5 %%6 %%7"' % relpath)
 
     def _write_vs_project(self, out_dir, basename, name, **kwargs):
         root = '%s.vcxproj' % basename
         project_id = get_id(basename.encode('utf-8'))
 
         with self._write_file(os.path.join(out_dir, root), mode='rb') as fh:
-            project_id, name = VisualStudioBackend.write_vs_project(fh,
-                                                                    self._version, project_id, name, **kwargs)
+            project_id, name = VisualStudioBackend.write_vs_project(
+                fh, self._version, project_id, name, **kwargs)
 
         with self._write_file(os.path.join(out_dir, '%s.user' % root), mode='rb') as fh:
             fh.write('<?xml version="1.0" encoding="utf-8"?>\r\n')
             fh.write('<Project ToolsVersion="4.0" xmlns="%s">\r\n' %
                      MSBUILD_NAMESPACE)
             fh.write('</Project>\r\n')
 
         return project_id
--- a/python/mozbuild/mozbuild/base.py
+++ b/python/mozbuild/mozbuild/base.py
@@ -32,17 +32,16 @@ from .configure import ConfigureSandbox
 from .controller.clobber import Clobberer
 from .mozconfig import (
     MozconfigFindException,
     MozconfigLoadException,
     MozconfigLoader,
 )
 from .pythonutil import find_python3_executable
 from .util import (
-    ReadOnlyNamespace,
     memoize,
     memoized_property,
 )
 from .virtualenv import VirtualenvManager
 
 
 def ancestors(path):
     """Emit the parent directories of a path."""
@@ -174,19 +173,20 @@ class MozbuildObject(ProcessExecutionMix
             raise BuildEnvironmentNotFoundException(
                 'Could not find Mozilla source tree or build environment.')
 
         topsrcdir = mozpath.normsep(topsrcdir)
         if topobjdir:
             topobjdir = mozpath.normsep(os.path.normpath(topobjdir))
 
             if topsrcdir == topobjdir:
-                raise BadEnvironmentException('The object directory appears '
-                                              'to be the same as your source directory (%s). This build '
-                                              'configuration is not supported.' % topsrcdir)
+                raise BadEnvironmentException(
+                    'The object directory appears '
+                    'to be the same as your source directory (%s). This build '
+                    'configuration is not supported.' % topsrcdir)
 
         # If we can't resolve topobjdir, oh well. We'll figure out when we need
         # one.
         return cls(topsrcdir, None, None, topobjdir=topobjdir,
                    mozconfig=mozconfig)
 
     def resolve_mozconfig_topobjdir(self, default=None):
         topobjdir = self.mozconfig['topobjdir'] or default
@@ -251,21 +251,23 @@ class MozbuildObject(ProcessExecutionMix
             self._topobjdir = self.resolve_mozconfig_topobjdir(
                 default='obj-@CONFIG_GUESS@')
 
         return self._topobjdir
 
     @property
     def virtualenv_manager(self):
         if self._virtualenv_manager is None:
-            self._virtualenv_manager = VirtualenvManager(self.topsrcdir,
-                                                         self.topobjdir, os.path.join(
-                                                             self.topobjdir, '_virtualenvs', 'init'),
-                                                         sys.stdout, os.path.join(self.topsrcdir, 'build',
-                                                                                  'virtualenv_packages.txt'))
+            self._virtualenv_manager = VirtualenvManager(
+                self.topsrcdir,
+                self.topobjdir,
+                os.path.join(self.topobjdir, '_virtualenvs', 'init'),
+                sys.stdout,
+                os.path.join(self.topsrcdir, 'build', 'virtualenv_packages.txt')
+                )
 
         return self._virtualenv_manager
 
     @staticmethod
     @memoize
     def get_mozconfig_and_target(topsrcdir, path, env_mozconfig):
         # env_mozconfig is only useful for unittests, which change the value of
         # the environment variable, which has an impact on autodetection (when
@@ -617,18 +619,18 @@ class MozbuildObject(ProcessExecutionMix
                     notifier = which.which('notify-send')
                 except which.WhichError:
                     raise Exception('Install notify-send (usually part of '
                                     'the libnotify package) to get a notification when '
                                     'the build finishes.')
                 self.run_process([notifier, '--app-name=Mozilla Build System',
                                   'Mozilla Build System', msg], ensure_exit_code=False)
         except Exception as e:
-            self.log(logging.WARNING, 'notifier-failed', {'error':
-                                                          e.message}, 'Notification center failed: {error}')
+            self.log(logging.WARNING, 'notifier-failed',
+                     {'error': e.message}, 'Notification center failed: {error}')
 
     def _ensure_objdir_exists(self):
         if os.path.isdir(self.statedir):
             return
 
         os.makedirs(self.statedir)
 
     def _ensure_state_subdir_exists(self, subdir):
@@ -863,18 +865,19 @@ class MachCommandBase(MozbuildObject):
         # more reliable than mozconfig when cwd is inside an objdir.
         topsrcdir = context.topdir
         topobjdir = None
         detect_virtualenv_mozinfo = True
         if hasattr(context, 'detect_virtualenv_mozinfo'):
             detect_virtualenv_mozinfo = getattr(context,
                                                 'detect_virtualenv_mozinfo')
         try:
-            dummy = MozbuildObject.from_environment(cwd=context.cwd,
-                                                    detect_virtualenv_mozinfo=detect_virtualenv_mozinfo)
+            dummy = MozbuildObject.from_environment(
+                cwd=context.cwd,
+                detect_virtualenv_mozinfo=detect_virtualenv_mozinfo)
             topsrcdir = dummy.topsrcdir
             topobjdir = dummy._topobjdir
             if topobjdir:
                 # If we're inside a objdir and the found mozconfig resolves to
                 # another objdir, we abort. The reasoning here is that if you
                 # are inside an objdir you probably want to perform actions on
                 # that objdir, not another one. This prevents accidental usage
                 # of the wrong objdir when the current objdir is ambiguous.
--- a/python/mozbuild/mozbuild/codecoverage/chrome_map.py
+++ b/python/mozbuild/mozbuild/codecoverage/chrome_map.py
@@ -1,17 +1,15 @@
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
-from collections import defaultdict
 import json
 import os
 import re
-import urlparse
 
 from mach.config import ConfigSettings
 from mach.logging import LoggingManager
 from mozbuild.backend.common import CommonBackend
 from mozbuild.base import MozbuildObject
 from mozbuild.frontend.data import (
     FinalTargetFiles,
     FinalTargetPreprocessedFiles,
@@ -115,19 +113,21 @@ class ChromeMapBackend(CommonBackend):
             else:
                 pp_info = None
             self._install_mapping[dest] = src.path, pp_info
 
         # Our result has four parts:
         #  A map from url prefixes to objdir directories:
         #  { "chrome://mozapps/content/": [ "dist/bin/chrome/toolkit/content/mozapps" ], ... }
         #  A map of overrides.
-        #  A map from objdir paths to sourcedir paths, and an object storing mapping information for preprocessed files:
+        #  A map from objdir paths to sourcedir paths, and an object storing mapping
+        #    information for preprocessed files:
         #  { "dist/bin/browser/chrome/browser/content/browser/aboutSessionRestore.js":
-        #    [ "$topsrcdir/browser/components/sessionstore/content/aboutSessionRestore.js", {} ], ... }
+        #    [ "$topsrcdir/browser/components/sessionstore/content/aboutSessionRestore.js", {} ],
+        #    ... }
         #  An object containing build configuration information.
         outputfile = os.path.join(self.environment.topobjdir, 'chrome-map.json')
         with self._write_file(outputfile) as fh:
             chrome_mapping = self.manifest_handler.chrome_mapping
             overrides = self.manifest_handler.overrides
             json.dump([
                 {k: list(v) for k, v in chrome_mapping.iteritems()},
                 overrides,
--- a/python/mozbuild/mozbuild/codecoverage/lcov_rewriter.py
+++ b/python/mozbuild/mozbuild/codecoverage/lcov_rewriter.py
@@ -61,18 +61,19 @@ class LcovRecord(object):
 
         self.resummarize()
         return self
 
     def resummarize(self):
         # Re-calculate summaries after generating or splitting a record.
         self.function_count = len(self.functions.keys())
         # Function records may have moved between files, so filter here.
-        self.function_exec_counts = {fn_name: count for fn_name, count in viewitems(self.function_exec_counts)
-                                     if fn_name in self.functions.values()}
+        self.function_exec_counts = {
+            fn_name: count for fn_name, count in viewitems(self.function_exec_counts)
+            if fn_name in self.functions.values()}
         self.covered_function_count = len([c for c in self.function_exec_counts.values() if c])
         self.line_count = len(self.lines)
         self.covered_line_count = len([c for c, _ in self.lines.values() if c])
         self.branch_count = len(self.branches)
         self.covered_branch_count = len([c for c in self.branches.values() if c])
 
 
 class RecordRewriter(object):
@@ -570,29 +571,31 @@ class UrlFinder(object):
 
         url_obj = urlparse.urlparse(url)
         if url_obj.scheme == 'jar':
             app_name = self.MOZ_APP_NAME
             omnijar_name = self.OMNIJAR_NAME
 
             if app_name in url:
                 if omnijar_name in url:
-                    # e.g. file:///home/worker/workspace/build/application/firefox/omni.ja!/components/MainProcessSingleton.js
+                    # e.g. file:///home/worker/workspace/build/application/firefox/omni.ja!/components/MainProcessSingleton.js  # noqa
                     parts = url_obj.path.split(omnijar_name + '!', 1)
                 elif '.xpi!' in url:
-                    # e.g. file:///home/worker/workspace/build/application/firefox/browser/features/e10srollout@mozilla.org.xpi!/bootstrap.js
+                    # e.g. file:///home/worker/workspace/build/application/firefox/browser/features/e10srollout@mozilla.org.xpi!/bootstrap.js  # noqa
                     parts = url_obj.path.split('.xpi!', 1)
                 else:
                     # We don't know how to handle this jar: path, so return it to the
                     # caller to make it print a warning.
                     return url_obj.path, None
 
                 dir_parts = parts[0].rsplit(app_name + '/', 1)
-                url = mozpath.normpath(mozpath.join(self.topobjdir, 'dist',
-                                                    'bin', dir_parts[1].lstrip('/'), parts[1].lstrip('/')))
+                url = mozpath.normpath(
+                    mozpath.join(self.topobjdir, 'dist',
+                                 'bin', dir_parts[1].lstrip('/'), parts[1].lstrip('/'))
+                    )
             elif '.xpi!' in url:
                 # This matching mechanism is quite brittle and based on examples seen in the wild.
                 # There's no rule to match the XPI name to the path in dist/xpi-stage.
                 parts = url_obj.path.split('.xpi!', 1)
                 addon_name = os.path.basename(parts[0])
                 if '-test@mozilla.org' in addon_name:
                     addon_name = addon_name[:-len('-test@mozilla.org')]
                 elif addon_name.endswith('@mozilla.org'):
@@ -614,17 +617,18 @@ class UrlFinder(object):
         result = self.find_files(url)
         self._final_mapping[url] = result
         return result
 
 
 class LcovFileRewriter(object):
     # Class for partial parses of LCOV format and rewriting to resolve urls
     # and preprocessed file lines.
-    def __init__(self, chrome_map_path, appdir='dist/bin/browser/', gredir='dist/bin/', extra_chrome_manifests=[]):
+    def __init__(self, chrome_map_path, appdir='dist/bin/browser/',
+                 gredir='dist/bin/', extra_chrome_manifests=[]):
         self.url_finder = UrlFinder(chrome_map_path, appdir, gredir, extra_chrome_manifests)
         self.pp_rewriter = RecordRewriter()
 
     def rewrite_files(self, in_paths, output_file, output_suffix):
         unknowns = set()
         found_valid = [False]
 
         def rewrite_source(url):
@@ -635,19 +639,21 @@ class LcovFileRewriter(object):
             except Exception as e:
                 if url not in unknowns:
                     print("Error: %s.\nCouldn't find source info for %s, removing record" %
                           (e, url))
                 unknowns.add(url)
                 return None
 
             source_file, pp_info = res
-            # We can't assert that the file exists here, because we don't have the source checkout available
-            # on test machines. We can bring back this assertion when bug 1432287 is fixed.
-            # assert os.path.isfile(source_file), "Couldn't find mapped source file %s at %s!" % (url, source_file)
+            # We can't assert that the file exists here, because we don't have the source
+            # checkout available on test machines. We can bring back this assertion when
+            # bug 1432287 is fixed.
+            # assert os.path.isfile(source_file), "Couldn't find mapped source file %s at %s!" % (
+            #     url, source_file)
 
             found_valid[0] = True
 
             return res
 
         in_paths = [os.path.abspath(in_path) for in_path in in_paths]
 
         if output_file:
@@ -661,38 +667,54 @@ class LcovFileRewriter(object):
                     lcov_file.print_file(out_fh, rewrite_source, self.pp_rewriter.rewrite_record)
 
         if not found_valid[0]:
             print("WARNING: No valid records found in %s" % in_paths)
             return
 
 
 def main():
-    parser = ArgumentParser(description="Given a set of gcov .info files produced "
-                            "by spidermonkey's code coverage, re-maps file urls "
-                            "back to source files and lines in preprocessed files "
-                            "back to their original locations.")
-    parser.add_argument("--chrome-map-path", default="chrome-map.json",
-                        help="Path to the chrome-map.json file.")
-    parser.add_argument("--app-dir", default="dist/bin/browser/",
-                        help="Prefix of the appdir in use. This is used to map "
-                             "urls starting with resource:///. It may differ by "
-                             "app, but defaults to the valid value for firefox.")
-    parser.add_argument("--gre-dir", default="dist/bin/",
-                        help="Prefix of the gre dir in use. This is used to map "
-                             "urls starting with resource://gre. It may differ by "
-                             "app, but defaults to the valid value for firefox.")
-    parser.add_argument("--output-suffix", default=".out",
-                        help="The suffix to append to output files.")
-    parser.add_argument("--extra-chrome-manifests", nargs='+',
-                        help="Paths to files containing extra chrome registration.")
-    parser.add_argument("--output-file", default="",
-                        help="The output file where the results are merged. Leave empty to make the rewriter not merge files.")
-    parser.add_argument("files", nargs='+',
-                        help="The set of files to process.")
+    parser = ArgumentParser(
+        description="Given a set of gcov .info files produced "
+        "by spidermonkey's code coverage, re-maps file urls "
+        "back to source files and lines in preprocessed files "
+        "back to their original locations."
+    )
+    parser.add_argument(
+        "--chrome-map-path", default="chrome-map.json", help="Path to the chrome-map.json file."
+    )
+    parser.add_argument(
+        "--app-dir",
+        default="dist/bin/browser/",
+        help="Prefix of the appdir in use. This is used to map "
+        "urls starting with resource:///. It may differ by "
+        "app, but defaults to the valid value for firefox.",
+    )
+    parser.add_argument(
+        "--gre-dir",
+        default="dist/bin/",
+        help="Prefix of the gre dir in use. This is used to map "
+        "urls starting with resource://gre. It may differ by "
+        "app, but defaults to the valid value for firefox.",
+    )
+    parser.add_argument(
+        "--output-suffix", default=".out", help="The suffix to append to output files."
+    )
+    parser.add_argument(
+        "--extra-chrome-manifests",
+        nargs='+',
+        help="Paths to files containing extra chrome registration.",
+    )
+    parser.add_argument(
+        "--output-file",
+        default="",
+        help="The output file where the results are merged. Leave empty to make the rewriter not "
+        "merge files.",
+    )
+    parser.add_argument("files", nargs='+', help="The set of files to process.")
 
     args = parser.parse_args()
 
     rewriter = LcovFileRewriter(args.chrome_map_path, args.app_dir, args.gre_dir,
                                 args.extra_chrome_manifests)
 
     files = []
     for f in args.files:
--- a/python/mozbuild/mozbuild/codecoverage/packager.py
+++ b/python/mozbuild/mozbuild/codecoverage/packager.py
@@ -1,15 +1,16 @@
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 from __future__ import absolute_import, print_function
 
 import argparse
+import errno
 import sys
 import json
 import buildconfig
 
 from mozpack.copier import Jarrer, FileRegistry
 from mozpack.files import FileFinder, GeneratedFile
 from mozpack.manifests import (
     InstallManifest,
--- a/python/mozbuild/mozbuild/compilation/codecomplete.py
+++ b/python/mozbuild/mozbuild/compilation/codecomplete.py
@@ -1,18 +1,16 @@
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this file,
 # You can obtain one at http://mozilla.org/MPL/2.0/.
 
 # This modules provides functionality for dealing with code completion.
 
 from __future__ import absolute_import
 
-import os
-
 from mach.decorators import (
     CommandArgument,
     CommandProvider,
     Command,
 )
 
 from mozbuild.base import MachCommandBase
 from mozbuild.shellutil import (
--- a/python/mozbuild/mozbuild/compilation/database.py
+++ b/python/mozbuild/mozbuild/compilation/database.py
@@ -8,21 +8,18 @@ import os
 import types
 
 from mozbuild.backend.common import CommonBackend
 from mozbuild.frontend.data import (
     ComputedFlags,
     Sources,
     GeneratedSources,
     DirectoryTraversal,
-    Linkable,
-    LocalInclude,
     PerSourceFlag,
     VariablePassthru,
-    SimpleProgram,
 )
 from mozbuild.shellutil import (
     quote as shell_quote,
 )
 from mozbuild.util import expand_variables
 import mozpack.path as mozpath
 from collections import (
     defaultdict,
--- a/python/mozbuild/mozbuild/compilation/util.py
+++ b/python/mozbuild/mozbuild/compilation/util.py
@@ -1,14 +1,13 @@
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this file,
 # You can obtain one at http://mozilla.org/MPL/2.0/.
 
 import os
-from mozbuild import shellutil
 
 
 def check_top_objdir(topobjdir):
     top_make = os.path.join(topobjdir, 'Makefile')
     if not os.path.exists(top_make):
         print('Your tree has not been built yet. Please run '
               '|mach build| with no arguments.')
         return False
--- a/python/mozbuild/mozbuild/config_status.py
+++ b/python/mozbuild/mozbuild/config_status.py
@@ -5,17 +5,16 @@
 # Combined with build/autoconf/config.status.m4, ConfigStatus is an almost
 # drop-in replacement for autoconf 2.13's config.status, with features
 # borrowed from autoconf > 2.5, and additional features.
 
 from __future__ import absolute_import, print_function
 
 import logging
 import os
-import subprocess
 import sys
 import time
 
 from argparse import ArgumentParser
 
 from mach.logging import LoggingManager
 from mozbuild.backend.configenvironment import ConfigEnvironment
 from mozbuild.base import MachCommandConditions
--- a/python/mozbuild/mozbuild/configure/util.py
+++ b/python/mozbuild/mozbuild/configure/util.py
@@ -150,17 +150,17 @@ class ConfigureOutputHandler(logging.Han
                     self._stdout.write('\n')
                     self._stdout.flush()
                 stream = self._stderr
                 msg = '%s\n' % self.format(record)
             stream.write(msg)
             stream.flush()
         except (KeyboardInterrupt, SystemExit, IOError):
             raise
-        except:
+        except Exception:
             self.handleError(record)
 
     @contextmanager
     def queue_debug(self):
         if self._queue_is_active:
             yield
             return
         self._queue_is_active = True
--- a/python/mozbuild/mozbuild/controller/building.py
+++ b/python/mozbuild/mozbuild/controller/building.py
@@ -1,17 +1,16 @@
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 from __future__ import absolute_import, unicode_literals
 
 import errno
 import getpass
-import glob
 import io
 import json
 import logging
 import os
 import subprocess
 import sys
 import time
 import which
@@ -300,17 +299,17 @@ class BuildMonitor(MozbuildObject):
 
             return BuildOutputResult(None, update_needed, message)
 
         warning = None
 
         try:
             warning = self._warnings_collector.process_line(line)
             message = line
-        except:
+        except Exception:
             pass
 
         return BuildOutputResult(warning, False, message)
 
     def stop_resource_recording(self):
         if self._resources_started:
             self.resources.stop()
 
@@ -897,17 +896,20 @@ class CCacheStats(object):
         elif unit in ('KB', 'Kbytes'):
             unit = CCacheStats.KiB
         else:
             unit = 1
 
         return int(numeric * unit)
 
     def hit_rate_message(self):
-        return 'ccache (direct) hit rate: {:.1%}; (preprocessed) hit rate: {:.1%}; miss rate: {:.1%}'.format(*self.hit_rates())
+        return ('ccache (direct) hit rate: {:.1%}; (preprocessed) hit rate: {:.1%};'
+                ' miss rate: {:.1%}'.format(
+                    *self.hit_rates()
+                ))
 
     def hit_rates(self):
         direct = self._values['cache_hit_direct']
         preprocessed = self._values['cache_hit_preprocessed']
         miss = self._values['cache_miss']
         total = float(direct + preprocessed + miss)
 
         if total > 0:
@@ -1139,22 +1141,23 @@ class BuildDriver(MozbuildObject):
 
                 # Build target pairs.
                 for make_dir, make_target in target_pairs:
                     # We don't display build status messages during partial
                     # tree builds because they aren't reliable there. This
                     # could potentially be fixed if the build monitor were more
                     # intelligent about encountering undefined state.
                     no_build_status = b'1' if make_dir is not None else b''
-                    status = self._run_make(directory=make_dir, target=make_target,
-                                            line_handler=output.on_line, log=False, print_directory=False,
-                                            ensure_exit_code=False, num_jobs=jobs, silent=not verbose,
-                                            append_env={
-                                                b'NO_BUILDSTATUS_MESSAGES': no_build_status},
-                                            keep_going=keep_going)
+                    status = self._run_make(
+                        directory=make_dir, target=make_target,
+                        line_handler=output.on_line, log=False, print_directory=False,
+                        ensure_exit_code=False, num_jobs=jobs, silent=not verbose,
+                        append_env={
+                            b'NO_BUILDSTATUS_MESSAGES': no_build_status},
+                        keep_going=keep_going)
 
                     if status != 0:
                         break
 
             elif status is None:
                 # If the backend doesn't specify a build() method, then just
                 # call client.mk directly.
                 status = self._run_client_mk(line_handler=output.on_line,
@@ -1294,18 +1297,20 @@ class BuildDriver(MozbuildObject):
         if not what:
             try:
                 # Fennec doesn't have useful output from just building. We should
                 # arguably make the build action useful for Fennec. Another day...
                 if self.substs['MOZ_BUILD_APP'] != 'mobile/android':
                     print('To take your build for a test drive, run: |mach run|')
                 app = self.substs['MOZ_BUILD_APP']
                 if app in ('browser', 'mobile/android'):
-                    print('For more information on what to do now, see '
-                          'https://developer.mozilla.org/docs/Developer_Guide/So_You_Just_Built_Firefox')
+                    print(
+                        'For more information on what to do now, see '
+                        'https://developer.mozilla.org/docs/Developer_Guide/So_You_Just_Built_Firefox'  # noqa
+                    )
             except Exception:
                 # Ignore Exceptions in case we can't find config.status (such
                 # as when doing OSX Universal builds)
                 pass
 
         return status
 
     def configure(self, options=None, buildstatus_messages=False,
--- a/python/mozbuild/mozbuild/controller/clobber.py
+++ b/python/mozbuild/mozbuild/controller/clobber.py
@@ -90,17 +90,17 @@ class Clobberer(object):
 
     def have_winrm(self):
         # `winrm -h` should print 'winrm version ...' and exit 1
         try:
             p = subprocess.Popen(['winrm.exe', '-h'],
                                  stdout=subprocess.PIPE,
                                  stderr=subprocess.STDOUT)
             return p.wait() == 1 and p.stdout.read().startswith('winrm')
-        except:
+        except Exception:
             return False
 
     def remove_objdir(self, full=True):
         """Remove the object directory.
 
         ``full`` controls whether to fully delete the objdir. If False,
         some directories (e.g. Visual Studio Project Files) will not be
         deleted.
--- a/python/mozbuild/mozbuild/doctor.py
+++ b/python/mozbuild/mozbuild/doctor.py
@@ -65,17 +65,17 @@ class Doctor(object):
             if result.get('status') != 'GOOD':
                 good = False
             if result.get('fixable', False):
                 fixable = True
             if result.get('denied', False):
                 denied = True
         if denied:
             print('run "mach doctor --fix" AS ADMIN to re-attempt fixing your system')
-        elif False:  # elif fixable:
+        elif False and fixable:  # elif fixable:  # 'and fixable' avoids flake8 error
             print('run "mach doctor --fix" as admin to attempt fixing your system')
         return int(not good)
 
     def getmount(self, path):
         while path != '/' and not os.path.ismount(path):
             path = mozpath.abspath(mozpath.join(path, os.pardir))
         return path
 
--- a/python/mozbuild/mozbuild/dotproperties.py
+++ b/python/mozbuild/mozbuild/dotproperties.py
@@ -73,12 +73,12 @@ class DotProperties:
 
         if not prefix.endswith('.'):
             prefix = prefix + '.'
 
         D = dict((k[len(prefix):], v) for k, v in self._properties.iteritems()
                  if k.startswith(prefix) and '.' not in k[len(prefix):])
 
         for required_key in required_keys:
-            if not required_key in D:
+            if required_key not in D:
                 raise ValueError('Required key %s not present' % required_key)
 
         return D
--- a/python/mozbuild/mozbuild/faster_daemon.py
+++ b/python/mozbuild/mozbuild/faster_daemon.py
@@ -199,17 +199,17 @@ class Daemon(object):
 
             input_to_outputs = self.file_copier.input_to_outputs_tree()
             for input, outputs in input_to_outputs.items():
                 if not outputs:
                     raise Exception("Refusing to watch input ({}) with no outputs".format(input))
 
             while True:
                 try:
-                    _watch_result = self.client.receive()
+                    self.client.receive()
 
                     changed = self.changed_files()
                     if not changed:
                         continue
 
                     result = FasterBuildChange()
 
                     for change in changed:
@@ -223,17 +223,17 @@ class Daemon(object):
                             if output not in result.output_to_inputs:
                                 result.output_to_inputs[output] = set()
                             result.output_to_inputs[output].add(input)
 
                     yield result
 
                 except pywatchman.SocketTimeout:
                     # Let's check to see if we're still functional.
-                    _version = self.client.query('version')
+                    self.client.query('version')
 
         except pywatchman.CommandError as e:
             # Abstract away pywatchman errors.
             raise FasterBuildException(e, 'Command error using pywatchman to watch {}'.format(
                 self.config_environment.topsrcdir))
 
         except pywatchman.SocketTimeout as e:
             # Abstract away pywatchman errors.
--- a/python/mozbuild/mozbuild/frontend/context.py
+++ b/python/mozbuild/mozbuild/frontend/context.py
@@ -1196,77 +1196,116 @@ SUBCONTEXTS = {cls.__name__: cls for cls
 
 # This defines the set of mutable global variables.
 #
 # Each variable is a tuple of:
 #
 #   (storage_type, input_types, docs)
 
 VARIABLES = {
-    'SOURCES': (ContextDerivedTypedListWithItems(Path, StrictOrderingOnAppendListWithFlagsFactory({'no_pgo': bool, 'flags': List, 'pgo_generate_only': bool})), list,
-                """Source code files.
+    'SOURCES': (
+        ContextDerivedTypedListWithItems(
+            Path,
+            StrictOrderingOnAppendListWithFlagsFactory(
+                {'no_pgo': bool,
+                 'flags': List,
+                 'pgo_generate_only': bool
+                 }
+                )
+            ),
+        list,
+        """Source code files.
 
         This variable contains a list of source code files to compile.
         Accepts assembler, C, C++, Objective C/C++.
-        """),
-
-    'FILES_PER_UNIFIED_FILE': (int, int,
-                               """The number of source files to compile into each unified source file.
-
-        """),
-
-    'IS_RUST_LIBRARY': (bool, bool,
-                        """Whether the current library defined by this moz.build is built by Rust.
+        """
+        ),
+
+    'FILES_PER_UNIFIED_FILE': (
+        int,
+        int,
+        """The number of source files to compile into each unified source file.
+
+        """
+        ),
+
+    'IS_RUST_LIBRARY': (
+        bool,
+        bool,
+        """Whether the current library defined by this moz.build is built by Rust.
 
         The library defined by this moz.build should have a build definition in
         a Cargo.toml file that exists in this moz.build's directory.
-        """),
-
-    'RUST_LIBRARY_FEATURES': (List, list,
-                              """Cargo features to activate for this library.
+        """
+        ),
+
+    'RUST_LIBRARY_FEATURES': (
+        List,
+        list,
+        """Cargo features to activate for this library.
 
         This variable should not be used directly; you should be using the
         RustLibrary template instead.
-        """),
-
-    'RUST_LIBRARY_TARGET_DIR': (unicode, unicode,
-                                """Where CARGO_TARGET_DIR should point when compiling this library.  If
+        """
+        ),
+
+    'RUST_LIBRARY_TARGET_DIR': (
+        unicode,
+        unicode,
+        """Where CARGO_TARGET_DIR should point when compiling this library.  If
         not set, it defaults to the current objdir.  It should be a relative path
         to the current objdir; absolute paths should not be used.
 
         This variable should not be used directly; you should be using the
         RustLibrary template instead.
-        """),
-
-    'HOST_RUST_LIBRARY_FEATURES': (List, list,
-                                   """Cargo features to activate for this host library.
+        """
+        ),
+
+    'HOST_RUST_LIBRARY_FEATURES': (
+        List,
+        list,
+        """Cargo features to activate for this host library.
 
         This variable should not be used directly; you should be using the
         HostRustLibrary template instead.
-        """),
-
-    'RUST_TESTS': (TypedList(unicode), list,
-                   """Names of Rust tests to build and run via `cargo test`.
+        """
+        ),
+
+    'RUST_TESTS': (
+        TypedList(unicode),
+        list,
+        """Names of Rust tests to build and run via `cargo test`.
         """),
 
-    'RUST_TEST_FEATURES': (TypedList(unicode), list,
-                           """Cargo features to activate for RUST_TESTS.
-        """),
-
-    'UNIFIED_SOURCES': (ContextDerivedTypedList(SourcePath, StrictOrderingOnAppendList), list,
-                        """Source code files that can be compiled together.
+    'RUST_TEST_FEATURES': (
+        TypedList(unicode),
+        list,
+        """Cargo features to activate for RUST_TESTS.
+        """
+        ),
+
+    'UNIFIED_SOURCES': (
+        ContextDerivedTypedList(
+            SourcePath,
+            StrictOrderingOnAppendList
+            ),
+        list,
+        """Source code files that can be compiled together.
 
         This variable contains a list of source code files to compile,
         that can be concatenated all together and built as a single source
         file. This can help make the build faster and reduce the debug info
         size.
-        """),
-
-    'GENERATED_FILES': (GeneratedFilesList, list,
-                        """Generic generated files.
+        """
+        ),
+
+    'GENERATED_FILES': (
+        GeneratedFilesList,
+        list,
+        """Generic generated files.
 
         This variable contains a list of files for the build system to
         generate at export time. The generation method may be declared
         with optional ``script``, ``inputs``, ``flags``, and ``force``
         attributes on individual entries.
         If the optional ``script`` attribute is not present on an entry, it
         is assumed that rules for generating the file are present in
         the associated Makefile.in.
@@ -1304,20 +1343,23 @@ VARIABLES = {
 
         When the ``flags`` attribute is present, the given list of flags is
         passed as extra arguments following the inputs.
 
         When the ``force`` attribute is present, the file is generated every
         build, regardless of whether it is stale.  This is special to the
         RecursiveMake backend and intended for special situations only (e.g.,
         localization).  Please consult a build peer before using ``force``.
-        """),
-
-    'DEFINES': (InitializedDefines, dict,
-                """Dictionary of compiler defines to declare.
+        """
+        ),
+
+    'DEFINES': (
+        InitializedDefines,
+        dict,
+        """Dictionary of compiler defines to declare.
 
         These are passed in to the compiler as ``-Dkey='value'`` for string
         values, ``-Dkey=value`` for numeric values, or ``-Dkey`` if the
         value is True. Note that for string values, the outer-level of
         single-quotes will be consumed by the shell. If you want to have
         a string-literal in the program, the value needs to have
         double-quotes.
 
@@ -1332,54 +1374,64 @@ VARIABLES = {
         respectively. These could also be combined into a single
         update::
 
            DEFINES.update({
                'NS_NO_XPCOM': True,
                'MOZ_EXTENSIONS_DB_SCHEMA': 15,
                'DLL_SUFFIX': '".so"',
            })
-        """),
-
-    'DELAYLOAD_DLLS': (List, list,
-                       """Delay-loaded DLLs.
+        """
+        ),
+
+    'DELAYLOAD_DLLS': (
+        List,
+        list,
+        """Delay-loaded DLLs.
 
         This variable contains a list of DLL files which the module being linked
         should load lazily.  This only has an effect when building with MSVC.
-        """),
-
-    'DIRS': (ContextDerivedTypedList(SourcePath), list,
-             """Child directories to descend into looking for build frontend files.
+        """
+        ),
+
+    'DIRS': (
+        ContextDerivedTypedList(SourcePath),
+        list,
+        """Child directories to descend into looking for build frontend files.
 
         This works similarly to the ``DIRS`` variable in make files. Each str
         value in the list is the name of a child directory. When this file is
         done parsing, the build reader will descend into each listed directory
         and read the frontend file there. If there is no frontend file, an error
         is raised.
 
         Values are relative paths. They can be multiple directory levels
         above or below. Use ``..`` for parent directories and ``/`` for path
         delimiters.
-        """),
-
-    'HAS_MISC_RULE': (bool, bool,
-                      """Whether this directory should be traversed in the ``misc`` tier.
+        """
+        ),
+
+    'HAS_MISC_RULE': (
+        bool,
+        bool,
+        """Whether this directory should be traversed in the ``misc`` tier.
 
         Many ``libs`` rules still exist in Makefile.in files. We highly prefer
         that these rules exist in the ``misc`` tier/target so that they can be
         executed concurrently during tier traversal (the ``misc`` tier is
         fully concurrent).
 
         Presence of this variable indicates that this directory should be
         traversed by the ``misc`` tier.
 
         Please note that converting ``libs`` rules to the ``misc`` tier must
         be done with care, as there are many implicit dependencies that can
         break the build in subtle ways.
-        """),
+        """
+        ),
 
     'FINAL_TARGET_FILES': (ContextDerivedTypedHierarchicalStringList(Path), list,
                            """List of files to be installed into the application directory.
 
         ``FINAL_TARGET_FILES`` will copy (or symlink, if the platform supports it)
         the contents of its files to the directory specified by
         ``FINAL_TARGET`` (typically ``dist/bin``). Files that are destined for a
         subdirectory can be specified by accessing a field, or as a dict access.
@@ -1676,33 +1728,45 @@ VARIABLES = {
 
     'HOST_RUST_PROGRAMS': (StrictOrderingOnAppendList, list,
                            """Compile a list of Rust executable names.
 
         Each name in this variable corresponds to an executable built from
         the Cargo.toml in the same directory.
         """),
 
-    'CONFIGURE_SUBST_FILES': (ContextDerivedTypedList(SourcePath, StrictOrderingOnAppendList), list,
-                              """Output files that will be generated using configure-like substitution.
+    'CONFIGURE_SUBST_FILES': (
+        ContextDerivedTypedList(
+            SourcePath,
+            StrictOrderingOnAppendList
+            ),
+        list,
+        """Output files that will be generated using configure-like substitution.
 
         This is a substitute for ``AC_OUTPUT`` in autoconf. For each path in this
         list, we will search for a file in the srcdir having the name
         ``{path}.in``. The contents of this file will be read and variable
         patterns like ``@foo@`` will be substituted with the values of the
         ``AC_SUBST`` variables declared during configure.
-        """),
-
-    'CONFIGURE_DEFINE_FILES': (ContextDerivedTypedList(SourcePath, StrictOrderingOnAppendList), list,
-                               """Output files generated from configure/config.status.
+        """
+        ),
+
+    'CONFIGURE_DEFINE_FILES': (
+        ContextDerivedTypedList(
+            SourcePath,
+            StrictOrderingOnAppendList
+            ),
+        list,
+        """Output files generated from configure/config.status.
 
         This is a substitute for ``AC_CONFIG_HEADER`` in autoconf. This is very
         similar to ``CONFIGURE_SUBST_FILES`` except the generation logic takes
         into account the values of ``AC_DEFINE`` instead of ``AC_SUBST``.
-        """),
+        """
+        ),
 
     'EXPORTS': (ContextDerivedTypedHierarchicalStringList(Path), list,
                 """List of files to be exported, and in which subdirectories.
 
         ``EXPORTS`` is generally used to list the include files to be exported to
         ``dist/include``, but it can be used for other files as well. This variable
         behaves as a list when appending filenames for export in the top-level
         directory. Files can also be appended to a field to indicate which
@@ -2419,56 +2483,67 @@ SPECIAL_VARIABLES = {
 
     'EXTRA_COMPONENTS': (lambda context: context['FINAL_TARGET_FILES'].components._strings, list,
                          """Additional component files to distribute.
 
        This variable contains a list of files to copy into
        ``$(FINAL_TARGET)/components/``.
         """),
 
-    'EXTRA_PP_COMPONENTS': (lambda context: context['FINAL_TARGET_PP_FILES'].components._strings, list,
-                            """Javascript XPCOM files.
+    'EXTRA_PP_COMPONENTS': (
+        lambda context: context['FINAL_TARGET_PP_FILES'].components._strings,
+        list,
+        """Javascript XPCOM files.
 
        This variable contains a list of files to preprocess.  Generated
        files will be installed in the ``/components`` directory of the distribution.
-        """),
-
-    'JS_PREFERENCE_FILES': (lambda context: context['FINAL_TARGET_FILES'].defaults.pref._strings, list,
-                            """Exported JavaScript files.
+        """
+        ),
+
+    'JS_PREFERENCE_FILES': (
+        lambda context: context['FINAL_TARGET_FILES'].defaults.pref._strings,
+        list,
+        """Exported JavaScript files.
 
         A list of files copied into the dist directory for packaging and installation.
         Path will be defined for gre or application prefs dir based on what is building.
         """),
 
-    'JS_PREFERENCE_PP_FILES': (lambda context: context['FINAL_TARGET_PP_FILES'].defaults.pref._strings, list,
-                               """Like JS_PREFERENCE_FILES, preprocessed..
-        """),
+    'JS_PREFERENCE_PP_FILES': (
+        lambda context: context['FINAL_TARGET_PP_FILES'].defaults.pref._strings,
+        list,
+        """Like JS_PREFERENCE_FILES, preprocessed..
+        """
+        ),
 
     'RESOURCE_FILES': (lambda context: context['FINAL_TARGET_FILES'].res, list,
                        """List of resources to be exported, and in which subdirectories.
 
         ``RESOURCE_FILES`` is used to list the resource files to be exported to
         ``dist/bin/res``, but it can be used for other files as well. This variable
         behaves as a list when appending filenames for resources in the top-level
         directory. Files can also be appended to a field to indicate which
         subdirectory they should be exported to. For example, to export
         ``foo.res`` to the top-level directory, and ``bar.res`` to ``fonts/``,
         append to ``RESOURCE_FILES`` like so::
 
            RESOURCE_FILES += ['foo.res']
            RESOURCE_FILES.fonts += ['bar.res']
         """),
 
-    'CONTENT_ACCESSIBLE_FILES': (lambda context: context['FINAL_TARGET_FILES'].contentaccessible, list,
-                                 """List of files which can be accessed by web content through resource:// URIs.
+    'CONTENT_ACCESSIBLE_FILES': (
+        lambda context: context['FINAL_TARGET_FILES'].contentaccessible,
+        list,
+        """List of files which can be accessed by web content through resource:// URIs.
 
         ``CONTENT_ACCESSIBLE_FILES`` is used to list the files to be exported
         to ``dist/bin/contentaccessible``. Files can also be appended to a
         field to indicate which subdirectory they should be exported to.
-        """),
+        """
+        ),
 
     'EXTRA_JS_MODULES': (lambda context: context['FINAL_TARGET_FILES'].modules, list,
                          """Additional JavaScript files to distribute.
 
         This variable contains a list of files to copy into
         ``$(FINAL_TARGET)/modules.
         """),
 
--- a/python/mozbuild/mozbuild/frontend/data.py
+++ b/python/mozbuild/mozbuild/frontend/data.py
@@ -16,23 +16,22 @@ structures.
 """
 
 from __future__ import absolute_import, unicode_literals
 
 from mozbuild.frontend.context import (
     ObjDirPath,
     SourcePath,
 )
-from mozbuild.util import StrictOrderingOnAppendList
 from mozpack.chrome.manifest import ManifestEntry
 
 import mozpack.path as mozpath
 from .context import FinalTargetValue
 
-from collections import defaultdict, OrderedDict
+from collections import defaultdict
 import itertools
 
 from ..util import (
     group_unified_files,
 )
 
 from ..testing import (
     all_test_flavors,
@@ -513,17 +512,18 @@ class BaseProgram(Linkable):
         if not program.endswith(bin_suffix):
             program += bin_suffix
         self.program = program
         self.is_unit_test = is_unit_test
 
     @property
     def output_path(self):
         if self.installed:
-            return ObjDirPath(self._context, '!/' + mozpath.join(self.install_target, self.program))
+            return ObjDirPath(self._context, '!/' + mozpath.join(
+                self.install_target, self.program))
         else:
             return ObjDirPath(self._context, '!' + self.program)
 
     def __repr__(self):
         return '<%s: %s/%s>' % (type(self).__name__, self.relobjdir, self.program)
 
     @property
     def name(self):
@@ -1037,20 +1037,22 @@ class UnifiedSources(BaseSources):
             # so avoid creating extremely long path names.
             unified_prefix = context.relsrcdir
             if len(unified_prefix) > 20:
                 unified_prefix = unified_prefix[-20:].split('/', 1)[-1]
             unified_prefix = unified_prefix.replace('/', '_')
 
             suffix = self.canonical_suffix[1:]
             unified_prefix = 'Unified_%s_%s' % (suffix, unified_prefix)
-            self.unified_source_mapping = list(group_unified_files(source_files,
-                                                                   unified_prefix=unified_prefix,
-                                                                   unified_suffix=suffix,
-                                                                   files_per_unified_file=files_per_unified_file))
+            self.unified_source_mapping = list(
+                group_unified_files(source_files,
+                                    unified_prefix=unified_prefix,
+                                    unified_suffix=suffix,
+                                    files_per_unified_file=files_per_unified_file)
+                )
 
 
 class InstallationTarget(ContextDerived):
     """Describes the rules that affect where files get installed to."""
 
     __slots__ = (
         'xpiname',
         'subdir',
@@ -1188,18 +1190,20 @@ class GeneratedFile(ContextDerived):
         suffixes = (
             '.asm',
             '.c',
             '.cpp',
             '.h',
             '.inc',
             '.py',
             '.rs',
-            'node.stub',  # To avoid VPATH issues with installing node files: https://bugzilla.mozilla.org/show_bug.cgi?id=1461714#c55
-            # We need to compile Java to generate JNI wrappers for native code compilation to consume.
+            'node.stub',  # To avoid VPATH issues with installing node files:
+                          # https://bugzilla.mozilla.org/show_bug.cgi?id=1461714#c55
+            # We need to compile Java to generate JNI wrappers for native code
+            # compilation to consume.
             'android_apks',
             '.profdata',
             '.webidl'
         )
         self.required_for_compile = [
             f for f in self.outputs if f.endswith(suffixes) or 'stl_wrappers/' in f]
 
 
--- a/python/mozbuild/mozbuild/frontend/emitter.py
+++ b/python/mozbuild/mozbuild/frontend/emitter.py
@@ -19,17 +19,16 @@ from mozbuild.util import (
 )
 
 import mozpack.path as mozpath
 import mozinfo
 import pytoml
 
 from .data import (
     BaseRustProgram,
-    BaseSources,
     ChromeManifestEntry,
     ComputedFlags,
     ConfigFileSubstitution,
     Defines,
     DirectoryTraversal,
     Exports,
     FinalTargetFiles,
     FinalTargetPreprocessedFiles,
@@ -88,17 +87,16 @@ from ..testing import (
 )
 
 from .context import (
     Context,
     SourcePath,
     ObjDirPath,
     Path,
     SubContext,
-    TemplateContext,
 )
 
 from mozbuild.base import ExecutionSummary
 
 
 class TreeMetadataEmitter(LoggingMixin):
     """Converts the executed mozbuild files into data structures.
 
@@ -443,18 +441,18 @@ class TreeMetadataEmitter(LoggingMixin):
                 'places:\n    %s' % (variable, path,
                                      self.LIBRARY_NAME_VAR[obj.KIND],
                                      '\n    '.join(paths)), context)
 
         elif force_static and not isinstance(candidates[0], StaticLibrary):
             raise SandboxValidationError(
                 '%s contains "static:%s", but there is only a shared "%s" '
                 'in %s. You may want to add FORCE_STATIC_LIB=True in '
-                '%s/moz.build, or remove "static:".' % (variable, path,
-                                                        name, candidates[0].relobjdir, candidates[0].relobjdir),
+                '%s/moz.build, or remove "static:".' % (
+                    variable, path, name, candidates[0].relobjdir, candidates[0].relobjdir),
                 context)
 
         elif isinstance(obj, StaticLibrary) and isinstance(candidates[0],
                                                            SharedLibrary):
             self._static_linking_shared.add(obj)
         obj.link_library(candidates[0])
 
     @memoize
@@ -581,18 +579,18 @@ class TreeMetadataEmitter(LoggingMixin):
                 host_linkables.append(prog)
             else:
                 linkables.append(prog)
 
         def check_unique_binary(program, kind):
             if program in self._binaries:
                 raise SandboxValidationError(
                     'Cannot use "%s" as %s name, '
-                    'because it is already used in %s' % (program, kind,
-                                                          self._binaries[program].relsrcdir), context)
+                    'because it is already used in %s' % (
+                        program, kind, self._binaries[program].relsrcdir), context)
         for kind, cls in [('PROGRAM', Program), ('HOST_PROGRAM', HostProgram)]:
             program = context.get(kind)
             if program:
                 check_unique_binary(program, kind)
                 self._binaries[program] = cls(context, program)
                 self._linkage.append((context, self._binaries[program],
                                       kind.replace('PROGRAM', 'USE_LIBS')))
                 add_program(self._binaries[program], kind)
@@ -631,32 +629,32 @@ class TreeMetadataEmitter(LoggingMixin):
         for kind, cls in [
                 ('SIMPLE_PROGRAMS', SimpleProgram),
                 ('CPP_UNIT_TESTS', SimpleProgram),
                 ('HOST_SIMPLE_PROGRAMS', HostSimpleProgram)]:
             for program in context[kind]:
                 if program in self._binaries:
                     raise SandboxValidationError(
                         'Cannot use "%s" in %s, '
-                        'because it is already used in %s' % (program, kind,
-                                                              self._binaries[program].relsrcdir), context)
+                        'because it is already used in %s' % (
+                            program, kind, self._binaries[program].relsrcdir), context)
                 self._binaries[program] = cls(context, program,
                                               is_unit_test=kind == 'CPP_UNIT_TESTS')
                 self._linkage.append((context, self._binaries[program],
                                       'HOST_USE_LIBS' if kind == 'HOST_SIMPLE_PROGRAMS'
                                       else 'USE_LIBS'))
                 add_program(self._binaries[program], kind)
 
         host_libname = context.get('HOST_LIBRARY_NAME')
         libname = context.get('LIBRARY_NAME')
 
         if host_libname:
             if host_libname == libname:
-                raise SandboxValidationError('LIBRARY_NAME and '
-                                             'HOST_LIBRARY_NAME must have a different value', context)
+                raise SandboxValidationError(
+                    'LIBRARY_NAME and HOST_LIBRARY_NAME must have a different value', context)
 
             is_rust_library = context.get('IS_RUST_LIBRARY')
             if is_rust_library:
                 lib = self._rust_library(context, host_libname, {}, cls=HostRustLibrary)
             elif context.get('FORCE_SHARED_LIB'):
                 lib = HostSharedLibrary(context, host_libname)
             else:
                 lib = HostLibrary(context, host_libname)
@@ -856,31 +854,32 @@ class TreeMetadataEmitter(LoggingMixin):
                 seen_sources.add(f)
                 full_path = f.full_path
                 if isinstance(f, SourcePath):
                     srcs.append(full_path)
                 else:
                     assert isinstance(f, Path)
                     gen_srcs.append(full_path)
                 if symbol == 'SOURCES':
-                    flags = context_srcs[f]
-                    if flags:
-                        all_flags[full_path] = flags
+                    context_flags = context_srcs[f]
+                    if context_flags:
+                        all_flags[full_path] = context_flags
                     # Files for the generation phase of PGO are unusual, so
                     # it's not unreasonable to require them to be special.
-                    if flags.pgo_generate_only:
+                    if context_flags.pgo_generate_only:
                         if not isinstance(f, Path):
-                            raise SandboxValidationError('pgo_generate_only file'
-                                                         'must not be a generated file: %s' % f, context)
+                            raise SandboxValidationError(
+                                'pgo_generate_only file must not be a generated file: %s' % f,
+                                context)
                         if mozpath.splitext(f)[1] != '.cpp':
                             raise SandboxValidationError('pgo_generate_only file'
                                                          'must be a .cpp file: %s' % f, context)
-                        if flags.no_pgo:
-                            raise SandboxValidationError('pgo_generate_only files'
-                                                         'cannot be marked no_pgo: %s' % f, context)
+                        if context_flags.no_pgo:
+                            raise SandboxValidationError(
+                                'pgo_generate_only files cannot be marked no_pgo: %s' % f, context)
                         pgo_generate_only.add(f)
 
                 if isinstance(f, SourcePath) and not os.path.exists(full_path):
                     raise SandboxValidationError('File listed in %s does not '
                                                  'exist: \'%s\'' % (symbol, full_path), context)
 
         # UNIFIED_SOURCES only take SourcePaths, so there should be no
         # generated source in here
@@ -1140,18 +1139,21 @@ class TreeMetadataEmitter(LoggingMixin):
             yield obj
 
         for path in context['CONFIGURE_SUBST_FILES']:
             sub = self._create_substitution(ConfigFileSubstitution, context,
                                             path)
             generated_files.add(str(sub.relpath))
             yield sub
 
-        for defines_var, cls, backend_flags in (('DEFINES', Defines, (computed_flags, computed_as_flags)),
-                                                ('HOST_DEFINES', HostDefines, (computed_host_flags,))):
+        for defines_var, cls, backend_flags in (('DEFINES', Defines,
+                                                 (computed_flags, computed_as_flags)),
+                                                ('HOST_DEFINES', HostDefines,
+                                                 (computed_host_flags,))
+                                                ):
             defines = context.get(defines_var)
             if defines:
                 defines_obj = cls(context, defines)
                 if isinstance(defines_obj, Defines):
                     # DEFINES have consumers outside the compile command line,
                     # HOST_DEFINES do not.
                     yield defines_obj
             else:
@@ -1182,28 +1184,30 @@ class TreeMetadataEmitter(LoggingMixin):
         for name in context.get('WEBIDL_EXAMPLE_INTERFACES', []):
             self._idls['WEBIDL_EXAMPLE_INTERFACES'].add(name)
 
         local_includes = []
         for local_include in context.get('LOCAL_INCLUDES', []):
             full_path = local_include.full_path
             if not isinstance(local_include, ObjDirPath):
                 if not os.path.exists(full_path):
-                    raise SandboxValidationError('Path specified in LOCAL_INCLUDES '
-                                                 'does not exist: %s (resolved to %s)' % (local_include,
-                                                                                          full_path), context)
+                    raise SandboxValidationError(
+                        'Path specified in LOCAL_INCLUDES does not exist: %s (resolved to %s)' %
+                        (local_include, full_path), context)
                 if not os.path.isdir(full_path):
                     raise SandboxValidationError('Path specified in LOCAL_INCLUDES '
                                                  'is a filename, but a directory is required: %s '
-                                                 '(resolved to %s)' % (local_include, full_path), context)
+                                                 '(resolved to %s)' % (local_include, full_path),
+                                                 context)
             if (full_path == context.config.topsrcdir or
                     full_path == context.config.topobjdir):
-                raise SandboxValidationError('Path specified in LOCAL_INCLUDES '
-                                             '(%s) resolves to the topsrcdir or topobjdir (%s), which is '
-                                             'not allowed' % (local_include, full_path), context)
+                raise SandboxValidationError(
+                    'Path specified in LOCAL_INCLUDES '
+                    '(%s) resolves to the topsrcdir or topobjdir (%s), which is '
+                    'not allowed' % (local_include, full_path), context)
             include_obj = LocalInclude(context, local_include)
             local_includes.append(include_obj.path.full_path)
             yield include_obj
 
         computed_flags.resolve_flags('LOCAL_INCLUDES', ['-I%s' % p for p in local_includes])
         computed_as_flags.resolve_flags('LOCAL_INCLUDES', ['-I%s' % p for p in local_includes])
         computed_host_flags.resolve_flags('LOCAL_INCLUDES', ['-I%s' % p for p in local_includes])
 
@@ -1288,18 +1292,23 @@ class TreeMetadataEmitter(LoggingMixin):
                                 raise SandboxValidationError(
                                     ('Objdir file listed in %s not in ' +
                                      'LOCALIZED_GENERATED_FILES: %s') % (var, f), context)
                         else:
                             # Additionally, don't allow LOCALIZED_GENERATED_FILES to be used
                             # in anything *but* LOCALIZED_FILES.
                             if f.target_basename in localized_generated_files:
                                 raise SandboxValidationError(
-                                    ('Outputs of LOCALIZED_GENERATED_FILES cannot be used in %s: ' +
-                                     '%s') % (var, f), context)
+                                    (
+                                        'Outputs of LOCALIZED_GENERATED_FILES cannot '
+                                        'be used in %s: %s'
+                                    )
+                                    % (var, f),
+                                    context,
+                                )
 
             # Addons (when XPI_NAME is defined) and Applications (when
             # DIST_SUBDIR is defined) use a different preferences directory
             # (default/preferences) from the one the GRE uses (defaults/pref).
             # Hence, we move the files from the latter to the former in that
             # case.
             if has_prefs and (context.get('XPI_NAME') or
                               context.get('DIST_SUBDIR')):
@@ -1526,19 +1535,20 @@ class TreeMetadataEmitter(LoggingMixin):
                 for source, dest in install_info.installs:
                     obj.installs[source] = (dest, False)
                 obj.external_installs |= install_info.external_installs
                 for install_path in install_info.deferred_installs:
                     if all(['*' not in install_path,
                             not os.path.isfile(mozpath.join(context.config.topsrcdir,
                                                             install_path[2:])),
                             install_path not in install_info.external_installs]):
-                        raise SandboxValidationError('Error processing test '
-                                                     'manifest %s: entry in support-files not present '
-                                                     'in the srcdir: %s' % (path, install_path), context)
+                        raise SandboxValidationError(
+                            'Error processing test '
+                            'manifest %s: entry in support-files not present '
+                            'in the srcdir: %s' % (path, install_path), context)
 
                 obj.deferred_installs |= install_info.deferred_installs
 
             for test in filtered:
                 obj.tests.append(test)
 
                 # Some test files are compiled and should not be copied into the
                 # test package. They function as identifiers rather than files.
@@ -1565,26 +1575,28 @@ class TreeMetadataEmitter(LoggingMixin):
             # reason. Here, we prune those files from the install set.
             # FUTURE we should be able to detect autogenerated files from
             # other build metadata. Once we do that, we can get rid of this.
             for f in defaults.get('generated-files', '').split():
                 # We re-raise otherwise the stack trace isn't informative.
                 try:
                     del obj.installs[mozpath.join(manifest_dir, f)]
                 except KeyError:
-                    raise SandboxValidationError('Error processing test '
-                                                 'manifest %s: entry in generated-files not present '
-                                                 'elsewhere in manifest: %s' % (path, f), context)
+                    raise SandboxValidationError(
+                        'Error processing test '
+                        'manifest %s: entry in generated-files not present '
+                        'elsewhere in manifest: %s' % (path, f), context)
 
             yield obj
         except (AssertionError, Exception):
-            raise SandboxValidationError('Error processing test '
-                                         'manifest file %s: %s' % (path,
-                                                                   '\n'.join(traceback.format_exception(*sys.exc_info()))),
-                                         context)
+            raise SandboxValidationError(
+                'Error processing test '
+                'manifest file %s: %s' % (path,
+                                          '\n'.join(traceback.format_exception(*sys.exc_info()))),
+                context)
 
     def _process_reftest_manifest(self, context, flavor, manifest_path, manifest):
         manifest_full_path = manifest_path.full_path
         manifest_reldir = mozpath.dirname(mozpath.relpath(manifest_full_path,
                                                           context.config.topsrcdir))
 
         # reftest manifests don't come from manifest parser. But they are
         # similar enough that we can use the same emitted objects. Note
--- a/python/mozbuild/mozbuild/frontend/gyp_reader.py
+++ b/python/mozbuild/mozbuild/frontend/gyp_reader.py
@@ -5,33 +5,29 @@
 from __future__ import absolute_import, unicode_literals
 
 import gyp
 import gyp.msvs_emulation
 import sys
 import os
 import time
 import types
-import warnings
 
 import mozpack.path as mozpath
 from mozpack.files import FileFinder
 from .sandbox import alphabetical_sorted
 from .context import (
     ObjDirPath,
     SourcePath,
     TemplateContext,
     VARIABLES,
 )
 from mozbuild.util import (
     expand_variables,
-    List,
-    memoize,
 )
-from .reader import SandboxValidationError
 
 # Define this module as gyp.generator.mozbuild so that gyp can use it
 # as a generator under the name "mozbuild".
 sys.modules['gyp.generator.mozbuild'] = sys.modules[__name__]
 
 # build/gyp_chromium does this:
 #   script_dir = os.path.dirname(os.path.realpath(__file__))
 #   chrome_src = os.path.abspath(os.path.join(script_dir, os.pardir))
@@ -89,17 +85,20 @@ def handle_actions(actions, context, act
             raise RuntimeError('GYP action %s not listed in action_overrides' % name)
         outputs = action['outputs']
         if len(outputs) > 1:
             raise NotImplementedError(
                 'GYP actions with more than one output not supported: %s' % name)
         output = outputs[0]
         if not output.startswith(idir):
             raise NotImplementedError(
-                'GYP actions outputting to somewhere other than <(INTERMEDIATE_DIR) not supported: %s' % output)
+                'GYP actions outputting to somewhere other than '
+                '<(INTERMEDIATE_DIR) not supported: %s'
+                % output
+            )
         output = output[len(idir):]
         context['GENERATED_FILES'] += [output]
         g = context['GENERATED_FILES'][output]
         g.script = action_overrides[name]
         g.inputs = action['inputs']
 
 
 def handle_copies(copies, context):
@@ -203,17 +202,18 @@ def process_gyp_result(gyp_result, gyp_d
                 if name.startswith('lib'):
                     name = name[3:]
                 # The context expects an unicode string.
                 context['LIBRARY_NAME'] = name.decode('utf-8')
             else:
                 context['PROGRAM'] = name.decode('utf-8')
             if spec['type'] == 'shared_library':
                 context['FORCE_SHARED_LIB'] = True
-            elif spec['type'] == 'static_library' and spec.get('variables', {}).get('no_expand_libs', '0') == '1':
+            elif spec['type'] == 'static_library' and \
+                    spec.get('variables', {}).get('no_expand_libs', '0') == '1':
                 # PSM links a NSS static library, but our folded libnss
                 # doesn't actually export everything that all of the
                 # objects within would need, so that one library
                 # should be built as a real static library.
                 context['NO_EXPAND_LIBS'] = True
             if use_libs:
                 context['USE_LIBS'] = sorted(use_libs, key=lambda s: s.lower())
             if os_libs:
@@ -251,17 +251,18 @@ def process_gyp_result(gyp_result, gyp_d
             if config.substs['CC_TYPE'] == 'clang-cl' and no_chromium:
                 msvs_settings = gyp.msvs_emulation.MsvsSettings(spec, {})
                 defines.extend(msvs_settings.GetComputedDefines(c))
             for define in defines:
                 if '=' in define:
                     name, value = define.split('=', 1)
                     # The NSS gyp file doesn't expose a way to override this
                     # currently, so we do so here.
-                    if name == 'NSS_ALLOW_SSLKEYLOGFILE' and config.substs.get('RELEASE_OR_BETA', False):
+                    if name == 'NSS_ALLOW_SSLKEYLOGFILE' and \
+                            config.substs.get('RELEASE_OR_BETA', False):
                         continue
                     context['DEFINES'][name] = value
                 else:
                     context['DEFINES'][define] = True
 
             product_dir_dist = '$PRODUCT_DIR/dist/'
             for include in target_conf.get('include_dirs', []):
                 if include.startswith(product_dir_dist):
--- a/python/mozbuild/mozbuild/frontend/sandbox.py
+++ b/python/mozbuild/mozbuild/frontend/sandbox.py
@@ -150,17 +150,17 @@ class Sandbox(dict):
         """Execute code at a path in the sandbox.
 
         The path must be absolute.
         """
         assert os.path.isabs(path)
 
         try:
             source = self._finder.get(path).read()
-        except Exception as e:
+        except Exception:
             raise SandboxLoadError(self._context.source_stack,
                                    sys.exc_info()[2], read_error=path)
 
         self.exec_source(source, path)
 
     def exec_source(self, source, path=''):
         """Execute Python code within a string.
 
--- a/python/mozbuild/mozbuild/gn_processor.py
+++ b/python/mozbuild/mozbuild/gn_processor.py
@@ -74,17 +74,19 @@ class MozbuildWriter(object):
                 self.write_mozbuild_value(k, v)
 
     def write_mozbuild_list(self, key, value):
         if value:
             self.write('\n')
             self.write(self.indent + key)
             self.write(' += [\n    ' + self.indent)
             self.write(
-                (',\n    ' + self.indent).join(alphabetical_sorted(self.mb_serialize(v) for v in value)))
+                (',\n    ' + self.indent).join(
+                    alphabetical_sorted(self.mb_serialize(v) for v in value))
+                )
             self.write('\n')
             self.write_ln(']')
 
     def write_mozbuild_value(self, key, value):
         if value:
             if key == 'LIBRARY_NAME':
                 self._library_name = value
             elif key == 'FORCE_SHARED_LIB':
@@ -272,17 +274,17 @@ def process_gn_config(gn_config, srcdir,
                 continue
             if not include.startswith('/'):
                 include = '/%s/%s' % (project_relsrcdir, include)
             context_attrs['LOCAL_INCLUDES'] += [include]
 
         context_attrs['ASFLAGS'] = spec.get('asflags_mozilla', [])
         if use_defines_in_asflags and defines:
             context_attrs['ASFLAGS'] += ['-D' + d for d in defines]
-        flags = [f for f in spec.get('cflags', []) if f in mozilla_flags]
+        flags = [_f for _f in spec.get('cflags', []) if _f in mozilla_flags]
         if flags:
             suffix_map = {
                 '.c': 'CFLAGS',
                 '.cpp': 'CXXFLAGS',
                 '.cc': 'CXXFLAGS',
                 '.m': 'CMFLAGS',
                 '.mm': 'CMMFLAGS',
             }
@@ -427,17 +429,16 @@ def write_mozbuild(config, srcdir, outpu
 
         target_mozbuild = mozpath.join(target_srcdir, 'moz.build')
         with open(target_mozbuild, 'w') as fh:
             mb = MozbuildWriter(fh)
             mb.write(license_header)
             mb.write('\n')
             mb.write(generated_header)
 
-            all_attr_sets = [attrs for _, attrs in configs]
             all_args = [args for args, _ in configs]
 
             # Start with attributes that will be a part of the mozconfig
             # for every configuration, then factor by other potentially useful
             # combinations.
             for attrs in ((),
                           ('MOZ_DEBUG',), ('OS_TARGET',), ('CPU_ARCH',),
                           ('MOZ_DEBUG', 'OS_TARGET',),
--- a/python/mozbuild/mozbuild/jar.py
+++ b/python/mozbuild/mozbuild/jar.py
@@ -13,17 +13,16 @@ from __future__ import absolute_import
 import sys
 import os
 import errno
 import re
 import logging
 from time import localtime
 from MozZipFile import ZipFile
 from cStringIO import StringIO
-from collections import defaultdict
 
 from mozbuild.preprocessor import Preprocessor
 from mozbuild.action.buildlist import addEntriesToListFile
 from mozpack.files import FileFinder
 import mozpack.path as mozpath
 if sys.platform == 'win32':
     from ctypes import windll, WinError
     CreateHardLink = windll.kernel32.CreateHardLinkA
@@ -103,19 +102,20 @@ class JarManifestParser(object):
             (?P<jarfile>[\w\d.\-\_\\\/{}]+).jar\:    # filename.jar:
         |
             (?:\s*(\#.*)?)                           # comment
         )\s*$                                        # whitespaces
         ''', re.VERBOSE)
     relsrcline = re.compile('relativesrcdir\s+(?P<relativesrcdir>.+?):')
     regline = re.compile('\%\s+(.*)$')
     entryre = '(?P<optPreprocess>\*)?(?P<optOverwrite>\+?)\s+'
-    entryline = re.compile(entryre
-                           + '(?P<output>[\w\d.\-\_\\\/\+\@]+)\s*(\((?P<locale>\%?)(?P<source>[\w\d.\-\_\\\/\@\*]+)\))?\s*$'
-                           )
+    entryline = re.compile(
+        entryre + ('(?P<output>[\w\d.\-\_\\\/\+\@]+)\s*'
+                   '(\((?P<locale>\%?)(?P<source>[\w\d.\-\_\\\/\@\*]+)\))?\s*$')
+        )
 
     def __init__(self):
         self._current_jar = None
         self._jars = []
 
     def write(self, line):
         # A Preprocessor instance feeds the parser through calls to this method.
 
@@ -240,17 +240,18 @@ class JarMaker(object):
                      help='source directory')
         p.add_option('-t', type='string', help='top source directory')
         p.add_option('-c', '--l10n-src', type='string',
                      action='append', help='localization directory')
         p.add_option('--l10n-base', type='string', action='store',
                      help='base directory to be used for localization (requires relativesrcdir)'
                      )
         p.add_option('--locale-mergedir', type='string', action='store',
-                     help='base directory to be used for l10n-merge (requires l10n-base and relativesrcdir)'
+                     help='base directory to be used for l10n-merge '
+                     '(requires l10n-base and relativesrcdir)'
                      )
         p.add_option('--relativesrcdir', type='string',
                      help='relativesrcdir to be used for localization')
         p.add_option('-d', type='string', help='base directory')
         p.add_option('--root-manifest-entry-appid', type='string',
                      help='add an app id specific root chrome manifest entry.'
                      )
         return p
@@ -496,17 +497,17 @@ class JarMaker(object):
 
         def __init__(self, jarfile):
             self.jarfile = jarfile
 
         def getDestModTime(self, aPath):
             try:
                 info = self.jarfile.getinfo(aPath)
                 return info.date_time
-            except:
+            except Exception:
                 return 0
 
         def getOutput(self, name):
             return ZipEntry(name, self.jarfile)
 
     class OutputHelper_flat(object):
         '''Provide getDestModTime and getOutput for a given flat
         output directory. The helper method ensureDirFor is used by
--- a/python/mozbuild/mozbuild/mach_commands.py
+++ b/python/mozbuild/mozbuild/mach_commands.py
@@ -103,30 +103,30 @@ class Watch(MachCommandBase):
              conditions=[conditions.is_firefox])
     @CommandArgument('-v', '--verbose', action='store_true',
                      help='Verbose output for what commands the watcher is running.')
     def watch(self, verbose=False):
         """Watch and re-build the source tree."""
 
         if not conditions.is_artifact_build(self):
             print('mach watch requires an artifact build. See '
-                  'https://developer.mozilla.org/docs/Mozilla/Developer_guide/Build_Instructions/Simple_Firefox_build')
+                  'https://developer.mozilla.org/docs/Mozilla/Developer_guide/Build_Instructions/Simple_Firefox_build')  # noqa
             return 1
 
         if not self.substs.get('WATCHMAN', None):
             print('mach watch requires watchman to be installed. See '
-                  'https://developer.mozilla.org/docs/Mozilla/Developer_guide/Build_Instructions/Incremental_builds_with_filesystem_watching')
+                  'https://developer.mozilla.org/docs/Mozilla/Developer_guide/Build_Instructions/Incremental_builds_with_filesystem_watching')  # noqa
             return 1
 
         self._activate_virtualenv()
         try:
             self.virtualenv_manager.install_pip_package('pywatchman==1.3.0')
         except Exception:
             print('Could not install pywatchman from pip. See '
-                  'https://developer.mozilla.org/docs/Mozilla/Developer_guide/Build_Instructions/Incremental_builds_with_filesystem_watching')
+                  'https://developer.mozilla.org/docs/Mozilla/Developer_guide/Build_Instructions/Incremental_builds_with_filesystem_watching')  # noqa
             return 1
 
         from mozbuild.faster_daemon import Daemon
         daemon = Daemon(self.config_environment)
 
         try:
             return daemon.watch()
         except KeyboardInterrupt:
@@ -305,17 +305,17 @@ class CargoProvider(MachCommandBase):
             'js': 'js/rust',
             'mozjs_sys': 'js/src',
             'baldrdash': 'js/src/wasm/cranelift',
             'geckodriver': 'testing/geckodriver',
         }
 
         if all_crates:
             crates = crates_and_roots.keys()
-        elif crates == None or crates == []:
+        elif crates is None or crates == []:
             crates = ['gkrust']
 
         for crate in crates:
             root = crates_and_roots.get(crate, None)
             if not root:
                 print('Cannot locate crate %s.  Please check your spelling or '
                       'add the crate information to the list.' % crate)
                 return 1
@@ -349,16 +349,17 @@ class Doctor(MachCommandBase):
         doctor = Doctor(self.topsrcdir, self.topobjdir, fix)
         return doctor.check_all()
 
 
 @CommandProvider
 class Clobber(MachCommandBase):
     NO_AUTO_LOG = True
     CLOBBER_CHOICES = ['objdir', 'python']
+
     @Command('clobber', category='build',
              description='Clobber the tree (delete the object directory).')
     @CommandArgument('what', default=['objdir'], nargs='*',
                      help='Target to clobber, must be one of {{{}}} (default objdir).'.format(
              ', '.join(CLOBBER_CHOICES)))
     @CommandArgument('--full', action='store_true',
                      help='Perform a full clobber')
     def clobber(self, what, full=False):
@@ -566,18 +567,19 @@ class Warnings(MachCommandBase):
 
             if directory and not filename.startswith(directory):
                 continue
 
             if flags and warning['flag'] not in flags:
                 continue
 
             if warning['column'] is not None:
-                print('%s:%d:%d [%s] %s' % (filename, warning['line'],
-                                            warning['column'], warning['flag'], warning['message']))
+                print('%s:%d:%d [%s] %s' % (
+                    filename, warning['line'], warning['column'],
+                    warning['flag'], warning['message']))
             else:
                 print('%s:%d [%s] %s' % (filename, warning['line'],
                                          warning['flag'], warning['message']))
 
     def join_ensure_dir(self, dir1, dir2):
         dir1 = mozpath.normpath(dir1)
         dir2 = mozpath.normsep(dir2)
         joined_path = mozpath.join(dir1, dir2)
@@ -587,18 +589,19 @@ class Warnings(MachCommandBase):
         return None
 
 
 @CommandProvider
 class GTestCommands(MachCommandBase):
     @Command('gtest', category='testing',
              description='Run GTest unit tests (C++ tests).')
     @CommandArgument('gtest_filter', default=b"*", nargs='?', metavar='gtest_filter',
-                     help="test_filter is a ':'-separated list of wildcard patterns (called the positive patterns),"
-                     "optionally followed by a '-' and another ':'-separated pattern list (called the negative patterns).")
+                     help="test_filter is a ':'-separated list of wildcard patterns "
+                     "(called the positive patterns), optionally followed by a '-' "
+                     "and another ':'-separated pattern list (called the negative patterns).")
     @CommandArgument('--jobs', '-j', default='1', nargs='?', metavar='jobs', type=int,
                      help='Run the tests in parallel using multiple processes.')
     @CommandArgument('--tbpl-parser', '-t', action='store_true',
                      help='Output test results in a format that can be parsed by TBPL.')
     @CommandArgument('--shuffle', '-s', action='store_true',
                      help='Randomize the execution order of tests.')
     @CommandArgument('--package',
                      default='org.mozilla.geckoview.test',
@@ -615,22 +618,24 @@ class GTestCommands(MachCommandBase):
                      dest='remote_test_root',
                      help='(Android only) Remote directory to use as test root '
                      '(eg. /mnt/sdcard/tests or /data/local/tests).')
     @CommandArgument('--libxul',
                      dest='libxul_path',
                      help='(Android only) Path to gtest libxul.so.')
     @CommandArgumentGroup('debugging')
     @CommandArgument('--debug', action='store_true', group='debugging',
-                     help='Enable the debugger. Not specifying a --debugger option will result in the default debugger being used.')
+                     help='Enable the debugger. Not specifying a --debugger option will result in '
+                     'the default debugger being used.')
     @CommandArgument('--debugger', default=None, type=str, group='debugging',
                      help='Name of debugger to use.')
     @CommandArgument('--debugger-args', default=None, metavar='params', type=str,
                      group='debugging',
-                     help='Command-line arguments to pass to the debugger itself; split as the Bourne shell would.')
+                     help='Command-line arguments to pass to the debugger itself; '
+                     'split as the Bourne shell would.')
     def gtest(self, shuffle, jobs, gtest_filter, tbpl_parser,
               package, adb_path, device_serial, remote_test_root, libxul_path,
               debug, debugger, debugger_args):
 
         # We lazy build gtest because it's slow to link
         try:
             config = self.config_environment
         except Exception:
@@ -659,17 +664,18 @@ class GTestCommands(MachCommandBase):
             os.makedirs(cwd)
 
         if conditions.is_android(self):
             if jobs != 1:
                 print("--jobs is not supported on Android and will be ignored")
             if debug or debugger or debugger_args:
                 print("--debug options are not supported on Android and will be ignored")
             return self.android_gtest(cwd, shuffle, gtest_filter,
-                                      package, adb_path, device_serial, remote_test_root, libxul_path)
+                                      package, adb_path, device_serial,
+                                      remote_test_root, libxul_path)
 
         if package or adb_path or device_serial or remote_test_root or libxul_path:
             print("One or more Android-only options will be ignored")
 
         app_path = self.get_binary_path('app')
         args = [app_path, '-unittest', '--gtest_death_test_style=threadsafe']
 
         if sys.platform.startswith('win') and \
@@ -743,17 +749,17 @@ class GTestCommands(MachCommandBase):
         return exit_code
 
     def android_gtest(self, test_dir, shuffle, gtest_filter,
                       package, adb_path, device_serial, remote_test_root, libxul_path):
         # setup logging for mozrunner
         from mozlog.commandline import setup_logging
         format_args = {'level': self._mach_context.settings['test']['level']}
         default_format = self._mach_context.settings['test']['format']
-        log = setup_logging('mach-gtest', {}, {default_format: sys.stdout}, format_args)
+        setup_logging('mach-gtest', {}, {default_format: sys.stdout}, format_args)
 
         # ensure that a device is available and test app is installed
         from mozrunner.devices.android_device import (verify_android_device, get_adb_path)
         verify_android_device(self, install=True, app=package, device_serial=device_serial)
 
         if not adb_path:
             adb_path = get_adb_path(self)
         if not libxul_path:
@@ -914,42 +920,51 @@ single quoted to force them to be string
 class RunProgram(MachCommandBase):
     """Run the compiled program."""
 
     prog_group = 'the compiled program'
 
     @Command('run', category='post-build',
              description='Run the compiled program, possibly under a debugger or DMD.')
     @CommandArgument('params', nargs='...', group=prog_group,
-                     help='Command-line arguments to be passed through to the program. Not specifying a --profile or -P option will result in a temporary profile being used.')
+                     help='Command-line arguments to be passed through to the program. Not '
+                     'specifying a --profile or -P option will result in a temporary profile '
+                     'being used.')
     @CommandArgumentGroup(prog_group)
     @CommandArgument('--remote', '-r', action='store_true', group=prog_group,
                      help='Do not pass the --no-remote argument by default.')
     @CommandArgument('--background', '-b', action='store_true', group=prog_group,
                      help='Do not pass the --foreground argument by default on Mac.')
     @CommandArgument('--noprofile', '-n', action='store_true', group=prog_group,
                      help='Do not pass the --profile argument by default.')
     @CommandArgument('--disable-e10s', action='store_true', group=prog_group,
                      help='Run the program with electrolysis disabled.')
     @CommandArgument('--enable-crash-reporter', action='store_true', group=prog_group,
                      help='Run the program with the crash reporter enabled.')
     @CommandArgument('--setpref', action='append', default=[], group=prog_group,
-                     help='Set the specified pref before starting the program. Can be set multiple times. Prefs can also be set in ~/.mozbuild/machrc in the [runprefs] section - see `./mach settings` for more information.')
+                     help='Set the specified pref before starting the program. Can be set '
+                     'multiple times. Prefs can also be set in ~/.mozbuild/machrc in the '
+                     '[runprefs] section - see `./mach settings` for more information.')
     @CommandArgument('--temp-profile', action='store_true', group=prog_group,
-                     help='Run the program using a new temporary profile created inside the objdir.')
+                     help='Run the program using a new temporary profile created inside '
+                     'the objdir.')
     @CommandArgument('--macos-open', action='store_true', group=prog_group,
-                     help="On macOS, run the program using the open(1) command. Per open(1), the browser is launched \"just as if you had double-clicked the file's icon\". The browser can not be launched under a debugger with this option.")
+                     help="On macOS, run the program using the open(1) command. Per open(1), "
+                     "the browser is launched \"just as if you had double-clicked the file's "
+                     "icon\". The browser can not be launched under a debugger with this option.")
     @CommandArgumentGroup('debugging')
     @CommandArgument('--debug', action='store_true', group='debugging',
-                     help='Enable the debugger. Not specifying a --debugger option will result in the default debugger being used.')
+                     help='Enable the debugger. Not specifying a --debugger option will result '
+                     'in the default debugger being used.')
     @CommandArgument('--debugger', default=None, type=str, group='debugging',
                      help='Name of debugger to use.')
     @CommandArgument('--debugger-args', default=None, metavar='params', type=str,
                      group='debugging',
-                     help='Command-line arguments to pass to the debugger itself; split as the Bourne shell would.')
+                     help='Command-line arguments to pass to the debugger itself; '
+                     'split as the Bourne shell would.')
     @CommandArgument('--debugparams', action=StoreDebugParamsAndWarnAction,
                      default=None, type=str, dest='debugger_args', group='debugging',
                      help=argparse.SUPPRESS)
     @CommandArgumentGroup('DMD')
     @CommandArgument('--dmd', action='store_true', group='DMD',
                      help='Enable DMD. The following arguments have no effect without this.')
     @CommandArgument('--mode', choices=['live', 'dark-matter', 'cumulative', 'scan'], group='DMD',
                      help='Profiling mode. The default is \'dark-matter\'.')
@@ -961,17 +976,20 @@ class RunProgram(MachCommandBase):
             enable_crash_reporter, setpref, temp_profile, macos_open, debug,
             debugger, debugger_args, dmd, mode, stacks, show_dump_stats):
 
         if conditions.is_android(self):
             # Running Firefox for Android is completely different
             if dmd:
                 print("DMD is not supported for Firefox for Android")
                 return 1
-            from mozrunner.devices.android_device import verify_android_device, run_firefox_for_android
+            from mozrunner.devices.android_device import (
+                verify_android_device,
+                run_firefox_for_android
+            )
             if not (debug or debugger or debugger_args):
                 verify_android_device(self, install=True)
                 return run_firefox_for_android(self, params)
             verify_android_device(self, install=True, debugger=True)
             args = ['']
 
         else:
             from mozprofile import Profile, Preferences
@@ -1731,17 +1749,17 @@ class StaticAnalysisMonitor(object):
     def warnings_db(self):
         return self._warnings_database
 
     def on_line(self, line):
         warning = None
 
         try:
             warning = self._warnings_collector.process_line(line)
-        except:
+        except Exception:
             pass
 
         if line.find('clang-tidy') != -1:
             filename = line.split(' ')[-1]
             if os.path.isfile(filename):
                 self._current = os.path.relpath(filename, self._srcdir)
             else:
                 self._current = None
@@ -1812,32 +1830,33 @@ class StaticAnalysis(MachCommandBase):
                           'output diagnostics from. Diagnostics from the main file '
                           'of each translation unit are always displayed')
     @CommandArgument('--output', '-o', default=None,
                      help='Write clang-tidy output in a file')
     @CommandArgument('--format', default='text', choices=('text', 'json'),
                      help='Output format to write in a file')
     @CommandArgument('--outgoing', default=False, action='store_true',
                      help='Run static analysis checks on outgoing files from mercurial repository')
-    def check(self, source=None, jobs=2, strip=1, verbose=False,
-              checks='-*', fix=False, header_filter='', output=None, format='text', outgoing=False):
+    def check(self, source=None, jobs=2, strip=1, verbose=False, checks='-*',
+              fix=False, header_filter='', output=None, format='text', outgoing=False):
         from mozbuild.controller.building import (
             StaticAnalysisFooter,
             StaticAnalysisOutputManager,
         )
 
         self._set_log_level(verbose)
         self.log_manager.enable_all_structured_loggers()
 
         rc = self._get_clang_tools(verbose=verbose)
         if rc != 0:
             return rc
 
         if self._is_version_eligible() is False:
-            self.log(logging.ERROR, 'static-analysis', {}, "You're using an old version of clang-format binary."
+            self.log(logging.ERROR, 'static-analysis', {},
+                     "You're using an old version of clang-format binary."
                      " Please update to a more recent one by running: './mach bootstrap'")
             return 1
 
         rc = self._build_compile_db(verbose=verbose)
         rc = rc or self._build_export(jobs=jobs, verbose=verbose)
         if rc != 0:
             return rc
 
@@ -1902,21 +1921,22 @@ class StaticAnalysis(MachCommandBase):
                               'It\'s result is stored as an json file on the artifacts server.')
     @CommandArgument('source', nargs='*', default=[],
                      help='Source files to be analyzed by Coverity Static Analysis Tool. '
                           'This is ran only in automation.')
     @CommandArgument('--output', '-o', default=None,
                      help='Write coverity output translated to json output in a file')
     @CommandArgument('--coverity_output_path', '-co', default=None,
                      help='Path where to write coverity results as cov-results.json. '
-                     'If no path is specified the default path from the coverity working directory, '
-                     '~./mozbuild/coverity is used.')
+                     'If no path is specified the default path from the coverity working '
+                     'directory, ~./mozbuild/coverity is used.')
     @CommandArgument('--outgoing', default=False, action='store_true',
                      help='Run coverity on outgoing files from mercurial or git repository')
-    def check_coverity(self, source=[], output=None, coverity_output_path=None, outgoing=False, verbose=False):
+    def check_coverity(self, source=[], output=None, coverity_output_path=None,
+                       outgoing=False, verbose=False):
         self._set_log_level(verbose)
         self.log_manager.enable_all_structured_loggers()
 
         if 'MOZ_AUTOMATION' not in os.environ:
             self.log(logging.INFO, 'static-analysis', {},
                      'Coverity based static-analysis cannot be ran outside automation.')
             return
 
@@ -2001,32 +2021,35 @@ class StaticAnalysis(MachCommandBase):
             self.log(logging.ERROR, 'static-analysis', {}, 'Coverity Analysis failed!')
 
         if output is not None:
             self.dump_cov_artifact(cov_result, source, output)
 
     def get_reliability_index_for_cov_checker(self, checker_name):
         if self._cov_config is None:
             self.log(logging.INFO, 'static-analysis', {}, 'Coverity config file not found, '
-                     'using default-value \'reliablity\' = medium. for checker {}'.format(checker_name))
+                     'using default-value \'reliablity\' = medium. for checker {}'.format(
+                        checker_name))
             return 'medium'
 
         checkers = self._cov_config['coverity_checkers']
         if checker_name not in checkers:
             self.log(logging.INFO, 'static-analysis', {},
                      'Coverity checker {} not found to determine reliability index. '
-                     'For the moment we shall use the default \'reliablity\' = medium.'.format(checker_name))
+                     'For the moment we shall use the default \'reliablity\' = medium.'.format(
+                        checker_name))
             return 'medium'
 
         if 'reliability' not in checkers[checker_name]:
             # This checker doesn't have a reliability index
             self.log(logging.INFO, 'static-analysis', {},
                      'Coverity checker {} doesn\'t have a reliability index set, '
                      'field \'reliability is missing\', please cosinder adding it. '
-                     'For the moment we shall use the default \'reliablity\' = medium.'.format(checker_name))
+                     'For the moment we shall use the default \'reliablity\' = medium.'.format(
+                        checker_name))
             return 'medium'
 
         return checkers[checker_name]['reliability']
 
     def dump_cov_artifact(self, cov_results, source, output):
         # Parse Coverity json into structured issues
         with open(cov_results) as f:
             result = json.load(f)
@@ -2040,39 +2063,46 @@ class StaticAnalysis(MachCommandBase):
                 # We look only for main event
                 event_path = next(
                     (event for event in issue['events'] if event['main'] is True), None)
 
                 dict_issue = {
                     'line': issue['mainEventLineNumber'],
                     'flag': issue['checkerName'],
                     'message': event_path['eventDescription'],
-                    'reliability': self.get_reliability_index_for_cov_checker(issue['checkerName']),
+                    'reliability': self.get_reliability_index_for_cov_checker(
+                        issue['checkerName']
+                        ),
                     'extra': {
                         'category': issue['checkerProperties']['category'],
                         'stateOnServer': issue['stateOnServer'],
                         'stack': []
                     }
                 }
 
                 # Embed all events into extra message
                 for event in issue['events']:
-                    dict_issue['extra']['stack'].append({'file_path': event['strippedFilePathname'],
-                                                         'line_number': event['lineNumber'],
-                                                         'path_type': event['eventTag'],
-                                                         'description': event['eventDescription']})
+                    dict_issue['extra']['stack'].append(
+                        {'file_path': event['strippedFilePathname'],
+                         'line_number': event['lineNumber'],
+                         'path_type': event['eventTag'],
+                         'description': event['eventDescription']})
 
                 return dict_issue
 
             for issue in result['issues']:
                 path = self.cov_is_file_in_source(issue['strippedMainEventFilePathname'], source)
                 if path is None:
                     # Since we skip a result we should log it
-                    self.log(logging.INFO, 'static-analysis', {}, 'Skipping CID: {0} from file: {1} since it\'s not related with the current patch.'.format(
-                        issue['stateOnServer']['cid'], issue['strippedMainEventFilePathname']))
+                    self.log(logging.INFO, 'static-analysis', {},
+                             'Skipping CID: {0} from file: {1} since it\'s not related '
+                             'with the current patch.'.format(
+                                issue['stateOnServer']['cid'],
+                                issue['strippedMainEventFilePathname'])
+                             )
                     continue
                 if path in files_list:
                     files_list[path]['warnings'].append(build_element(issue))
                 else:
                     files_list[path] = {'warnings': [build_element(issue)]}
 
             with open(output, 'w') as f:
                 json.dump(issues_dict, f)
@@ -2347,17 +2377,17 @@ class StaticAnalysis(MachCommandBase):
         with open(mozpath.join(self.topsrcdir, 'tools',
                                'infer', 'config.yaml')) as f:
             try:
                 config = yaml.safe_load(f)
                 for item in config['infer_checkers']:
                     if item['publish']:
                         checkers.append(item['name'])
                 tp_path = mozpath.join(self.topsrcdir, config['third_party'])
-            except Exception as e:
+            except Exception:
                 print('Looks like config.yaml is not valid, so we are unable '
                       'to determine default checkers, and which folder to '
                       'exclude, using defaults provided by infer')
         return checkers, tp_path
 
     def _get_infer_args(self, checks, third_party_path):
         '''Return the arguments which include the checkers <checks>, and
         excludes all folder in <third_party_path>.'''
@@ -2413,17 +2443,18 @@ class StaticAnalysis(MachCommandBase):
         cmd = [self._clang_format_path, '--version']
         try:
             output = subprocess.check_output(cmd, stderr=subprocess.STDOUT).decode('utf-8')
             version_string = 'clang-format version ' + version
             if output.startswith(version_string):
                 return True
         except subprocess.CalledProcessError as e:
             self.log(logging.ERROR, 'static-analysis', {},
-                     "Error determining the version clang-tidy/format binary, please see the attached exception: \n{}".format(e.output))
+                     "Error determining the version clang-tidy/format binary, please see the "
+                     "attached exception: \n{}".format(e.output))
 
         return False
 
     def _get_clang_tidy_command(self, checks, header_filter, sources, jobs, fix):
 
         if checks == '-*':
             checks = self._get_checks()
 
@@ -2557,18 +2588,21 @@ class StaticAnalysis(MachCommandBase):
 
         self._clang_tidy_base_path = mozpath.join(self.topsrcdir, "tools", "clang-tidy")
 
         # For each checker run it
         self._clang_tidy_config = self._get_clang_tidy_config()
         platform, _ = self.platform
 
         if platform not in self._clang_tidy_config['platforms']:
-            self.log(logging.ERROR, 'static-analysis', {},
-                     "RUNNING: clang-tidy autotest for platform {} not supported.".format(platform))
+            self.log(
+                logging.ERROR, 'static-analysis', {},
+                "RUNNING: clang-tidy autotest for platform {} not supported.".format(
+                    platform)
+                )
             return self.TOOLS_UNSUPORTED_PLATFORM
 
         import concurrent.futures
         import multiprocessing
 
         max_workers = multiprocessing.cpu_count()
 
         self.log(logging.INFO, 'static-analysis', {},
@@ -2588,17 +2622,18 @@ class StaticAnalysis(MachCommandBase):
         checkers_results = []
         with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
             futures = []
             for item in self._clang_tidy_config['clang_checkers']:
                 # Skip if any of the following statements is true:
                 # 1. Checker attribute 'publish' is False.
                 not_published = not bool(item.get('publish', True))
                 # 2. Checker has restricted-platforms and current platform is not of them.
-                ignored_platform = 'restricted-platforms' in item and platform not in item['restricted-platforms']
+                ignored_platform = ('restricted-platforms' in item and
+                                    platform not in item['restricted-platforms'])
                 # 3. Checker name is mozilla-* or -*.
                 ignored_checker = item['name'] in ['mozilla-*', '-*']
                 # 4. List checker_names is passed and the current checker is not part of the
                 #    list or 'publish' is False
                 checker_not_in_list = checker_names and (
                     item['name'] not in checker_names or not_published)
                 if not_published or \
                    ignored_platform or \
@@ -2626,30 +2661,39 @@ class StaticAnalysis(MachCommandBase):
                     checker_error = failure['checker-error']
                     checker_name = failure['checker-name']
                     info1 = failure['info1']
                     info2 = failure['info2']
                     info3 = failure['info3']
 
                     message_to_log = ''
                     if checker_error == self.TOOLS_CHECKER_NOT_FOUND:
-                        message_to_log = "\tChecker {} not present in this clang-tidy version.".format(
-                            checker_name)
+                        message_to_log = \
+                            "\tChecker {} not present in this clang-tidy version.".format(
+                                checker_name)
                     elif checker_error == self.TOOLS_CHECKER_NO_TEST_FILE:
-                        message_to_log = "\tChecker {0} does not have a test file - {0}.cpp".format(
-                            checker_name)
+                        message_to_log = \
+                            "\tChecker {0} does not have a test file - {0}.cpp".format(
+                                checker_name)
                     elif checker_error == self.TOOLS_CHECKER_RETURNED_NO_ISSUES:
-                        message_to_log = "\tChecker {0} did not find any issues in its test file, clang-tidy output for the run is:\n{1}".format(
-                            checker_name, info1)
+                        message_to_log = (
+                            "\tChecker {0} did not find any issues in its test file, "
+                            "clang-tidy output for the run is:\n{1}"
+                            ).format(checker_name, info1)
                     elif checker_error == self.TOOLS_CHECKER_RESULT_FILE_NOT_FOUND:
-                        message_to_log = "\tChecker {0} does not have a result file - {0}.json".format(
-                            checker_name)
+                        message_to_log = \
+                            "\tChecker {0} does not have a result file - {0}.json".format(
+                                checker_name)
                     elif checker_error == self.TOOLS_CHECKER_DIFF_FAILED:
-                        message_to_log = "\tChecker {0}\nExpected: {1}\nGot: {2}\nclang-tidy output for the run is:\n{3}".format(
-                            checker_name, info1, info2, info3)
+                        message_to_log = (
+                            "\tChecker {0}\nExpected: {1}\n"
+                            "Got: {2}\n"
+                            "clang-tidy output for the run is:\n"
+                            "{3}"
+                            ).format(checker_name, info1, info2, info3)
 
                     print('\n'+message_to_log)
 
                 # Also delete the tmp folder
                 shutil.rmtree(self._compilation_commands_path)
                 return error_code
 
             # Run the analysis on all checkers at the same time only if we don't dump results.
@@ -2681,18 +2725,21 @@ class StaticAnalysis(MachCommandBase):
         self.log(logging.INFO, 'static-analysis', {},
                  "RUNNING: clang-tidy checker batch analysis.")
         if not len(items):
             self.log(logging.ERROR, 'static-analysis', {},
                      "ERROR: clang-tidy checker list is empty!")
             return self.TOOLS_CHECKER_LIST_EMPTY
 
         issues, clang_output = self._run_analysis(
-            checks='-*,' + ",".join(items), header_filter='',
-            sources=[mozpath.join(self._clang_tidy_base_path, "test", checker) + '.cpp' for checker in items], print_out=True)
+            checks='-*,' + ",".join(items),
+            header_filter='',
+            sources=[mozpath.join(self._clang_tidy_base_path, "test", checker) + '.cpp'
+                     for checker in items],
+            print_out=True)
 
         if issues is None:
             return self.TOOLS_CHECKER_FAILED_FILE
 
         failed_checks = []
         failed_checks_baseline = []
         for checker in items:
             test_file_path_json = mozpath.join(
@@ -2712,17 +2759,18 @@ class StaticAnalysis(MachCommandBase):
         if len(failed_checks) > 0:
             self.log(logging.ERROR, 'static-analysis', {},
                      'The following check(s) failed for bulk analysis: ' + ' '.join(failed_checks))
 
             for failed_check, baseline_issue in zip(failed_checks, failed_checks_baseline):
                 print('\tChecker {0} expect following results: \n\t\t{1}'.format(
                     failed_check, baseline_issue))
 
-            print('This is the output generated by clang-tidy for the bulk build:\n{}'.format(clang_output))
+            print('This is the output generated by clang-tidy for the bulk build:\n{}'.format(
+                clang_output))
             return self.TOOLS_CHECKER_DIFF_FAILED
 
         return self.TOOLS_SUCCESS
 
     def _create_temp_compilation_db(self, config):
         directory = tempfile.mkdtemp(prefix='cc')
         with open(mozpath.join(directory, "compile_commands.json"), "wb") as file_handler:
             compile_commands = []
@@ -2873,19 +2921,21 @@ class StaticAnalysis(MachCommandBase):
                           'Can be omitted, in which case the latest clang-tools and infer '
                           'helper for the platform would be automatically detected and installed.')
     @CommandArgument('--skip-cache', action='store_true',
                      help='Skip all local caches to force re-fetching the helper tool.',
                      default=False)
     @CommandArgument('--force', action='store_true',
                      help='Force re-install even though the tool exists in mozbuild.',
                      default=False)
-    @CommandArgument('--minimal-install', action='store_true', help='Download only clang based tool.',
+    @CommandArgument('--minimal-install', action='store_true',
+                     help='Download only clang based tool.',
                      default=False)
-    def install(self, source=None, skip_cache=False, force=False, minimal_install=False, verbose=False):
+    def install(self, source=None, skip_cache=False, force=False, minimal_install=False,
+                verbose=False):
         self._set_log_level(verbose)
         rc = self._get_clang_tools(force=force, skip_cache=skip_cache,
                                    source=source, verbose=verbose)
         if rc == 0 and not minimal_install:
             # XXX ignore the return code because if it fails or not, infer is
             # not mandatory, but clang-tidy is
             self._get_infer(force=force, skip_cache=skip_cache, verbose=verbose)
         return rc
@@ -2939,22 +2989,24 @@ class StaticAnalysis(MachCommandBase):
                      help='Specify the path(s) to reformat')
     @CommandArgument('--commit', '-c', default=None,
                      help='Specify a commit to reformat from.'
                           'For git you can also pass a range of commits (foo..bar)'
                           'to format all of them at the same time.')
     @CommandArgument('--output', '-o', default=None, dest='output_path',
                      help='Specify a file handle to write clang-format raw output instead of '
                           'applying changes. This can be stdout or a file path.')
-    @CommandArgument('--format', '-f', choices=('diff', 'json'), default='diff', dest='output_format',
+    @CommandArgument('--format', '-f', choices=('diff', 'json'), default='diff',
+                     dest='output_format',
                      help='Specify the output format used: diff is the raw patch provided by '
                      'clang-format, json is a list of atomic changes to process.')
     @CommandArgument('--outgoing', default=False, action='store_true',
                      help='Run clang-format on outgoing files from mercurial repository')
-    def clang_format(self, assume_filename, path, commit, output_path=None, output_format='diff', verbose=False, outgoing=False):
+    def clang_format(self, assume_filename, path, commit, output_path=None, output_format='diff',
+                     verbose=False, outgoing=False):
         # Run clang-format or clang-format-diff on the local changes
         # or files/directories
         if path is None and outgoing:
             repo = get_repository_object(self.topsrcdir)
             path = repo.get_outgoing_files()
 
         if path:
             # Create the full path list
@@ -2985,26 +3037,28 @@ class StaticAnalysis(MachCommandBase):
                 print("clang-format: Unable to set locate clang-format tools.")
                 return 1
         else:
             rc = self._get_clang_tools(verbose=verbose)
             if rc != 0:
                 return rc
 
         if self._is_version_eligible() is False:
-            self.log(logging.ERROR, 'static-analysis', {}, "You're using an old version of clang-format binary."
+            self.log(logging.ERROR, 'static-analysis', {},
+                     "You're using an old version of clang-format binary."
                      " Please update to a more recent one by running: './mach bootstrap'")
             return 1
 
         if path is None:
             return self._run_clang_format_diff(self._clang_format_diff,
                                                self._clang_format_path, commit, output)
 
         if assume_filename:
-            return self._run_clang_format_in_console(self._clang_format_path, path, assume_filename)
+            return self._run_clang_format_in_console(self._clang_format_path,
+                                                     path, assume_filename)
 
         return self._run_clang_format_path(self._clang_format_path, path, output, output_format)
 
     def _verify_checker(self, item, checkers_results):
         check = item['name']
         test_file_path = mozpath.join(self._clang_tidy_base_path, "test", check)
         test_file_path_cpp = test_file_path + '.cpp'
         test_file_path_json = test_file_path + '.json'
@@ -3017,17 +3071,17 @@ class StaticAnalysis(MachCommandBase):
             'checker-name': check,
             'checker-error': '',
             'info1': '',
             'info2': '',
             'info3': ''
         }
 
         # Verify if this checker actually exists
-        if not check in self._clang_tidy_checks:
+        if check not in self._clang_tidy_checks:
             checker_error['checker-error'] = self.TOOLS_CHECKER_NOT_FOUND
             checkers_results.append(checker_error)
             return self.TOOLS_CHECKER_NOT_FOUND
 
         # Verify if the test file exists for this checker
         if not os.path.exists(test_file_path_cpp):
             checker_error['checker-error'] = self.TOOLS_CHECKER_NO_TEST_FILE
             checkers_results.append(checker_error)
@@ -3161,17 +3215,17 @@ class StaticAnalysis(MachCommandBase):
         except Exception:
             print('Looks like configure has not run yet, running it now...')
             rc = builder.configure()
             if rc != 0:
                 return (rc, config, ran_configure)
             ran_configure = True
             try:
                 config = self.config_environment
-            except Exception as e:
+            except Exception:
                 pass
 
         return (0, config, ran_configure)
 
     def _build_compile_db(self, verbose=False):
         self._compile_db = mozpath.join(self.topobjdir, 'compile_commands.json')
         if os.path.exists(self._compile_db):
             return 0
@@ -3223,20 +3277,20 @@ class StaticAnalysis(MachCommandBase):
         self._clang_tidy_path = mozpath.join(self._clang_tools_path, "clang-tidy", "bin",
                                              "clang-tidy" + config.substs.get('BIN_SUFFIX', ''))
         self._clang_format_path = mozpath.join(
             self._clang_tools_path, "clang-tidy", "bin",
             "clang-format" + config.substs.get('BIN_SUFFIX', ''))
         self._clang_apply_replacements = mozpath.join(
             self._clang_tools_path, "clang-tidy", "bin",
             "clang-apply-replacements" + config.substs.get('BIN_SUFFIX', ''))
-        self._run_clang_tidy_path = mozpath.join(self._clang_tools_path, "clang-tidy", "share", "clang",
-                                                 "run-clang-tidy.py")
-        self._clang_format_diff = mozpath.join(self._clang_tools_path, "clang-tidy", "share", "clang",
-                                               "clang-format-diff.py")
+        self._run_clang_tidy_path = mozpath.join(self._clang_tools_path, "clang-tidy",
+                                                 "share", "clang", "run-clang-tidy.py")
+        self._clang_format_diff = mozpath.join(self._clang_tools_path, "clang-tidy",
+                                               "share", "clang", "clang-format-diff.py")
         return 0
 
     def _do_clang_tools_exist(self):
         return os.path.exists(self._clang_tidy_path) and \
                os.path.exists(self._clang_format_path) and \
                os.path.exists(self._clang_apply_replacements) and \
                os.path.exists(self._run_clang_tidy_path)
 
@@ -3537,17 +3591,18 @@ class StaticAnalysis(MachCommandBase):
                     diff_command = ["diff", "-u", original_path, target_file]
                     try:
                         output = check_output(diff_command)
                     except CalledProcessError as e:
                         # diff -u returns 0 when no change
                         # here, we expect changes. if we are here, this means that
                         # there is a diff to show
                         if e.output:
-                            # Replace the temp path by the path relative to the repository to display a valid patch
+                            # Replace the temp path by the path relative to the repository to
+                            # display a valid patch
                             relative_path = os.path.relpath(original_path, self.topsrcdir)
                             patch = e.output.replace(target_file, relative_path)
                             patch = patch.replace(original_path, relative_path)
                             patches[original_path] = patch
 
             if output_format == 'json':
                 output = json.dumps(patches, indent=4)
             else:
@@ -3650,28 +3705,31 @@ class Vendor(MachCommandBase):
                      help='Permit overly-large files to be added to the repository',
                      default=False)
     def vendor_rust(self, **kwargs):
         from mozbuild.vendor_rust import VendorRust
         vendor_command = self._spawn(VendorRust)
         vendor_command.vendor(**kwargs)
 
     @SubCommand('vendor', 'aom',
-                description='Vendor av1 video codec reference implementation into the source repository.')
+                description='Vendor av1 video codec reference implementation into the '
+                'source repository.')
     @CommandArgument('-r', '--revision',
                      help='Repository tag or commit to update to.')
     @CommandArgument('--repo',
-                     help='Repository url to pull a snapshot from. Supports github and googlesource.')
+                     help='Repository url to pull a snapshot from. '
+                     'Supports github and googlesource.')
     @CommandArgument('--ignore-modified', action='store_true',
                      help='Ignore modified files in current checkout',
                      default=False)
     def vendor_aom(self, **kwargs):
         from mozbuild.vendor_aom import VendorAOM
         vendor_command = self._spawn(VendorAOM)
         vendor_command.vendor(**kwargs)
+
     @SubCommand('vendor', 'dav1d',
                 description='Vendor dav1d implementation of AV1 into the source repository.')
     @CommandArgument('-r', '--revision',
                      help='Repository tag or commit to update to.')
     @CommandArgument('--repo',
                      help='Repository url to pull a snapshot from. Supports gitlab.')
     @CommandArgument('--ignore-modified', action='store_true',
                      help='Ignore modified files in current checkout',
@@ -3681,17 +3739,21 @@ class Vendor(MachCommandBase):
         vendor_command = self._spawn(VendorDav1d)
         vendor_command.vendor(**kwargs)
 
     @SubCommand('vendor', 'python',
                 description='Vendor Python packages from pypi.org into third_party/python')
     @CommandArgument('--with-windows-wheel', action='store_true',
                      help='Vendor a wheel for Windows along with the source package',
                      default=False)
-    @CommandArgument('packages', default=None, nargs='*', help='Packages to vendor. If omitted, packages and their dependencies defined in Pipfile.lock will be vendored. If Pipfile has been modified, then Pipfile.lock will be regenerated. Note that transient dependencies may be updated when running this command.')
+    @CommandArgument('packages', default=None, nargs='*',
+                     help='Packages to vendor. If omitted, packages and their dependencies '
+                     'defined in Pipfile.lock will be vendored. If Pipfile has been modified, '
+                     'then Pipfile.lock will be regenerated. Note that transient dependencies '
+                     'may be updated when running this command.')
     def vendor_python(self, **kwargs):
         from mozbuild.vendor_python import VendorPython
         vendor_command = self._spawn(VendorPython)
         vendor_command.vendor(**kwargs)
 
     @SubCommand('vendor', 'manifest',
                 description='Vendor externally hosted repositories into this '
                             'repository.')
@@ -3705,26 +3767,29 @@ class Vendor(MachCommandBase):
         verify_manifests(files)
 
 
 @CommandProvider
 class WebRTCGTestCommands(GTestCommands):
     @Command('webrtc-gtest', category='testing',
              description='Run WebRTC.org GTest unit tests.')
     @CommandArgument('gtest_filter', default=b"*", nargs='?', metavar='gtest_filter',
-                     help="test_filter is a ':'-separated list of wildcard patterns (called the positive patterns),"
-                     "optionally followed by a '-' and another ':'-separated pattern list (called the negative patterns).")
+                     help="test_filter is a ':'-separated list of wildcard patterns "
+                     "(called the positive patterns), optionally followed by a '-' and "
+                     "another ':'-separated pattern list (called the negative patterns).")
     @CommandArgumentGroup('debugging')
     @CommandArgument('--debug', action='store_true', group='debugging',
-                     help='Enable the debugger. Not specifying a --debugger option will result in the default debugger being used.')
+                     help='Enable the debugger. Not specifying a --debugger option will '
+                     'result in the default debugger being used.')
     @CommandArgument('--debugger', default=None, type=str, group='debugging',
                      help='Name of debugger to use.')
     @CommandArgument('--debugger-args', default=None, metavar='params', type=str,
                      group='debugging',
-                     help='Command-line arguments to pass to the debugger itself; split as the Bourne shell would.')
+                     help='Command-line arguments to pass to the debugger itself; '
+                     'split as the Bourne shell would.')
     def gtest(self, gtest_filter, debug, debugger,
               debugger_args):
         app_path = self.get_binary_path('webrtc-gtest')
         args = [app_path]
 
         if debug or debugger or debugger_args:
             args = self.prepend_debugger_args(args, debugger, debugger_args)
 
@@ -3885,17 +3950,18 @@ class Analyze(MachCommandBase):
             g.file_summaries(files)
             g.close()
         else:
             res = 'Please make sure you have a local tup db *or* specify the location with --path.'
             print ('Could not find a valid tup db in ' + path, res, sep='\n')
             return 1
 
     @SubCommand('analyze', 'all',
-                description='Get a report of files changed within the last n days and their corresponding build cost.')
+                description='Get a report of files changed within the last n days and '
+                'their corresponding build cost.')
     @CommandArgument('--days', '-d', type=int, default=14,
                      help='Number of days to include in the report.')
     @CommandArgument('--format', default='pretty',
                      choices=['pretty', 'csv', 'json', 'html'],
                      help='Print or export data in the given format.')
     @CommandArgument('--limit', type=int, default=None,
                      help='Get the top n most expensive files from the report.')
     @CommandArgument('--path', help='Path to cost_dict.gz',
--- a/python/mozbuild/mozbuild/makeutil.py
+++ b/python/mozbuild/mozbuild/makeutil.py
@@ -124,17 +124,17 @@ class Rule(object):
     def targets(self):
         '''Return an iterator on the rule targets.'''
         # Ensure the returned iterator is actually just that, an iterator.
         # Avoids caller fiddling with the set itself.
         return iter(self._targets)
 
     def dependencies(self):
         '''Return an iterator on the rule dependencies.'''
-        return iter(d for d in self._dependencies if not d in self._targets)
+        return iter(d for d in self._dependencies if d not in self._targets)
 
     def commands(self):
         '''Return an iterator on the rule commands.'''
         return iter(self._commands)
 
     def dump(self, fh):
         '''
         Dump the rule to the given file handle.
--- a/python/mozbuild/mozbuild/mozconfig.py
+++ b/python/mozbuild/mozbuild/mozconfig.py
@@ -6,17 +6,16 @@ from __future__ import absolute_import, 
 
 import filecmp
 import os
 import re
 import sys
 import subprocess
 import traceback
 
-from collections import defaultdict
 from mozpack import path as mozpath
 
 
 MOZ_MYCONFIG_ERROR = '''
 The MOZ_MYCONFIG environment variable to define the location of mozconfigs
 is deprecated. If you wish to define the mozconfig path via an environment
 variable, use MOZCONFIG instead.
 '''.strip()
--- a/python/mozbuild/mozbuild/mozinfo.py
+++ b/python/mozbuild/mozbuild/mozinfo.py
@@ -125,17 +125,17 @@ def build_dict(config, env=os.environ):
         return 'opt'
 
     # if buildapp or bits are unknown, we don't have a configuration similar to
     # any in automation and the guesses are useless.
     if 'buildapp' in d and (d['os'] == 'mac' or 'bits' in d):
         d['platform_guess'] = guess_platform()
         d['buildtype_guess'] = guess_buildtype()
 
-    if 'buildapp' in d and d['buildapp'] == 'mobile/android' and 'MOZ_ANDROID_MIN_SDK_VERSION' in substs:
+    if d.get('buildapp', '') == 'mobile/android' and 'MOZ_ANDROID_MIN_SDK_VERSION' in substs:
         d['android_min_sdk'] = substs['MOZ_ANDROID_MIN_SDK_VERSION']
 
     return d
 
 
 def write_mozinfo(file, config, env=os.environ):
     """Write JSON data about the configuration specified in config and an
     environment variable dict to |file|, which may be a filename or file-like
--- a/python/mozbuild/mozbuild/preprocessor.py
+++ b/python/mozbuild/mozbuild/preprocessor.py
@@ -492,17 +492,17 @@ class Preprocessor:
                 raise Preprocessor.Error(self, "--depend doesn't work with stdin",
                                          None)
         if options.depend:
             if not options.output:
                 raise Preprocessor.Error(self, "--depend doesn't work with stdout",
                                          None)
             try:
                 from makeutil import Makefile
-            except:
+            except Exception:
                 raise Preprocessor.Error(self, "--depend requires the "
                                                "mozbuild.makeutil module", None)
             depfile = get_output_file(options.depend)
 
         if args:
             for f in args:
                 with open(f, 'rU') as input:
                     self.processFile(input=input, output=out)
@@ -593,17 +593,17 @@ class Preprocessor:
         m = re.match('(?P<name>\w+)(?:\s(?P<value>.*))?', args, re.U)
         if not m:
             raise Preprocessor.Error(self, 'SYNTAX_DEF', args)
         val = ''
         if m.group('value'):
             val = self.applyFilters(m.group('value'))
             try:
                 val = int(val)
-            except:
+            except Exception:
                 pass
         self.context[m.group('name')] = val
 
     def do_undef(self, args):
         m = re.match('(?P<name>\w+)$', args, re.U)
         if not m:
             raise Preprocessor.Error(self, 'SYNTAX_DEF', args)
         if args in self.context:
@@ -704,17 +704,16 @@ class Preprocessor:
         if self.disableLevel > 0:
             self.disableLevel -= 1
         if self.disableLevel == 0:
             self.ifStates.pop()
     # output processing
 
     def do_expand(self, args):
         lst = re.split('__(\w+)__', args, re.U)
-        do_replace = False
 
         def vsubst(v):
             if v in self.context:
                 return str(self.context[v])
             return ''
         for i in range(1, len(lst), 2):
             lst[i] = vsubst(lst[i])
         lst.append('\n')  # add back the newline
@@ -800,17 +799,17 @@ class Preprocessor:
                 args = str(args)
                 if filters:
                     args = self.applyFilters(args)
                 if not os.path.isabs(args):
                     args = os.path.join(self.curdir, args)
                 args = open(args, 'rU')
             except Preprocessor.Error:
                 raise
-            except:
+            except Exception:
                 raise Preprocessor.Error(self, 'FILE_NOT_FOUND', str(args))
         self.checkLineNumbers = bool(re.search('\.(js|jsm|java|webidl)(?:\.in)?$', args.name))
         oldFile = self.context['FILE']
         oldLine = self.context['LINE']
         oldDir = self.context['DIRECTORY']
         oldCurdir = self.curdir
         self.noteLineInfo()
 
--- a/python/mozbuild/mozbuild/repackaging/installer.py
+++ b/python/mozbuild/mozbuild/repackaging/installer.py
@@ -6,17 +6,18 @@ import os
 import tempfile
 import shutil
 import zipfile
 import mozpack.path as mozpath
 from mozbuild.action.exe_7z_archive import archive_exe
 from mozbuild.util import ensureParentDir
 
 
-def repackage_installer(topsrcdir, tag, setupexe, package, output, package_name, sfx_stub, use_upx):
+def repackage_installer(topsrcdir, tag, setupexe, package, output,
+                        package_name, sfx_stub, use_upx):
     if package and not zipfile.is_zipfile(package):
         raise Exception("Package file %s is not a valid .zip file." % package)
     if package is not None and package_name is None:
         raise Exception("Package name must be provided, if a package is provided.")
     if package is None and package_name is not None:
         raise Exception("Package name must not be provided, if a package is not provided.")
 
     # We need the full path for the tag and output, since we chdir later.
--- a/python/mozbuild/mozbuild/repackaging/msi.py
+++ b/python/mozbuild/mozbuild/repackaging/msi.py
@@ -52,17 +52,17 @@ def repackage_msi(topsrcdir, wsx, versio
     if not os.path.isfile(setupexe):
         raise Exception("%s does not exist." % setupexe)
     if candle is not None and not os.path.isfile(candle):
         raise Exception("%s does not exist." % candle)
     if light is not None and not os.path.isfile(light):
         raise Exception("%s does not exist." % light)
     embeddedVersion = '0.0.0.0'
     # Version string cannot contain 'a' or 'b' when embedding in msi manifest.
-    if not 'a' in version and not 'b' in version:
+    if 'a' not in version and 'b' not in version:
         if version.endswith('esr'):
             parts = version[:-3].split('.')
         else:
             parts = version.split('.')
         while len(parts) < 4:
             parts.append('0')
         embeddedVersion = '.'.join(parts)
 
--- a/python/mozbuild/mozbuild/test/action/test_buildlist.py
+++ b/python/mozbuild/mozbuild/test/action/test_buildlist.py
@@ -1,18 +1,16 @@
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 import unittest
 
 import os
-import sys
 import os.path
-import time
 from tempfile import mkdtemp
 from shutil import rmtree
 import mozunit
 
 from mozbuild.action.buildlist import addEntriesToListFile
 
 
 class TestBuildList(unittest.TestCase):
--- a/python/mozbuild/mozbuild/test/action/test_node.py
+++ b/python/mozbuild/mozbuild/test/action/test_node.py
@@ -32,17 +32,17 @@ class TestNode(unittest.TestCase):
     """
 
     def setUp(self):
         SCRIPT_ALLOWLIST.append(TEST_SCRIPT)
 
     def tearDown(self):
         try:
             SCRIPT_ALLOWLIST.remove(TEST_SCRIPT)
-        except:
+        except Exception:
             pass
 
     def test_generate_no_returned_deps(self):
         deps = generate("dummy_argument", TEST_SCRIPT)
 
         self.assertSetEqual(deps, set([]))
 
     def test_generate_returns_passed_deps(self):
--- a/python/mozbuild/mozbuild/test/action/test_process_install_manifest.py
+++ b/python/mozbuild/mozbuild/test/action/test_process_install_manifest.py
@@ -2,25 +2,18 @@
 
 # Any copyright is dedicated to the Public Domain.
 # http://creativecommons.org/publicdomain/zero/1.0/
 
 import os
 
 import mozunit
 
-from unittest import expectedFailure
-
-from mozpack.copier import (
-    FileCopier,
-    FileRegistry,
-)
 from mozpack.manifests import (
     InstallManifest,
-    UnreadableInstallManifest,
 )
 from mozpack.test.test_files import TestWithTmpDir
 
 import mozbuild.action.process_install_manifest as process_install_manifest
 
 
 class TestGenerateManifest(TestWithTmpDir):
     """
--- a/python/mozbuild/mozbuild/test/backend/test_build.py
+++ b/python/mozbuild/mozbuild/test/backend/test_build.py
@@ -53,32 +53,32 @@ class TestBuild(unittest.TestCase):
             emitter = TreeMetadataEmitter(config)
             moz_build = mozpath.join(config.topsrcdir, 'test.mozbuild')
             definitions = list(emitter.emit(
                 reader.read_mozbuild(moz_build, config)))
             for backend in backends:
                 backend(config).consume(definitions)
 
             yield config
-        except:
+        except Exception:
             raise
         finally:
             if not os.environ.get('MOZ_NO_CLEANUP'):
                 shutil.rmtree(topobjdir)
 
     @contextmanager
     def line_handler(self):
         lines = []
 
         def handle_make_line(line):
             lines.append(line)
 
         try:
             yield handle_make_line
-        except:
+        except Exception:
             print('\n'.join(lines))
             raise
 
         if os.environ.get('MOZ_VERBOSE_MAKE'):
             print('\n'.join(lines))
 
     def test_recursive_make(self):
         substs = list(BASE_SUBSTS)
--- a/python/mozbuild/mozbuild/test/backend/test_configenvironment.py
+++ b/python/mozbuild/mozbuild/test/backend/test_configenvironment.py
@@ -1,30 +1,28 @@
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 import os
-import posixpath
-from StringIO import StringIO
 import unittest
-from mozunit import main, MockedOpen
+from mozunit import main
 
 import mozbuild.backend.configenvironment as ConfigStatus
 
 from mozbuild.util import ReadOnlyDict
 
 import mozpack.path as mozpath
 
 
 class ConfigEnvironment(ConfigStatus.ConfigEnvironment):
     def __init__(self, *args, **kwargs):
         ConfigStatus.ConfigEnvironment.__init__(self, *args, **kwargs)
         # Be helpful to unit tests
-        if not 'top_srcdir' in self.substs:
+        if 'top_srcdir' not in self.substs:
             if os.path.isabs(self.topsrcdir):
                 top_srcdir = self.topsrcdir.replace(os.sep, '/')
             else:
                 top_srcdir = mozpath.relpath(self.topsrcdir, self.topobjdir).replace(os.sep, '/')
 
             d = dict(self.substs)
             d['top_srcdir'] = top_srcdir
             self.substs = ReadOnlyDict(d)
--- a/python/mozbuild/mozbuild/test/backend/test_fastermake.py
+++ b/python/mozbuild/mozbuild/test/backend/test_fastermake.py
@@ -1,18 +1,15 @@
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 from __future__ import unicode_literals
 
-import cPickle as pickle
-import json
 import os
-import unittest
 
 from mozpack.copier import FileRegistry
 from mozpack.manifests import InstallManifest
 from mozunit import main
 
 from mozbuild.backend.fastermake import FasterMakeBackend
 
 from mozbuild.test.backend.common import BackendTester
--- a/python/mozbuild/mozbuild/test/backend/test_gn_processor.py
+++ b/python/mozbuild/mozbuild/test/backend/test_gn_processor.py
@@ -16,17 +16,16 @@ from mozunit import main
 from mozbuild.test.backend.common import BackendTester
 
 import mozpack.path as mozpath
 
 from mozbuild.gn_processor import (
     GnMozbuildWriterBackend,
     find_common_attrs,
 )
-from mozbuild.backend.recursivemake import RecursiveMakeBackend
 
 from mozbuild.frontend.data import (
     ComputedFlags,
     StaticLibrary,
     Sources,
     UnifiedSources,
 )
 
--- a/python/mozbuild/mozbuild/test/backend/test_partialconfigenvironment.py
+++ b/python/mozbuild/mozbuild/test/backend/test_partialconfigenvironment.py
@@ -56,29 +56,29 @@ class TestPartial(unittest.TestCase):
     def test_remove_subst(self):
         '''Test removing a subst from the config. The file should be overwritten with 'None'
         '''
         env = PartialConfigEnvironment(self._objdir())
         path = mozpath.join(env.topobjdir, 'config.statusd', 'substs', 'MYSUBST')
         myconfig = config.copy()
         env.write_vars(myconfig)
         with self.assertRaises(KeyError):
-            x = env.substs['MYSUBST']
+            _ = env.substs['MYSUBST']
         self.assertFalse(os.path.exists(path))
 
         myconfig['substs']['MYSUBST'] = 'new'
         env.write_vars(myconfig)
 
         self.assertEqual(env.substs['MYSUBST'], 'new')
         self.assertTrue(os.path.exists(path))
 
         del myconfig['substs']['MYSUBST']
         env.write_vars(myconfig)
         with self.assertRaises(KeyError):
-            x = env.substs['MYSUBST']
+            _ = env.substs['MYSUBST']
         # Now that the subst is gone, the file still needs to be present so that
         # make can update dependencies correctly. Overwriting the file with
         # 'None' is the same as deleting it as far as the
         # PartialConfigEnvironment is concerned, but make can't track a
         # dependency on a file that doesn't exist.
         self.assertTrue(os.path.exists(path))
 
     def _assert_deps(self, env, deps):
@@ -102,17 +102,17 @@ class TestPartial(unittest.TestCase):
         # Getting a define again shouldn't add a redundant dependency
         self.assertEqual(env.defines['MOZ_FOO'], '1')
         self._assert_deps(env, ['defines/MOZ_FOO', 'defines/MOZ_BAR'])
 
         self.assertEqual(env.substs['MOZ_SUBST_1'], '1')
         self._assert_deps(env, ['defines/MOZ_FOO', 'defines/MOZ_BAR', 'substs/MOZ_SUBST_1'])
 
         with self.assertRaises(KeyError):
-            x = env.substs['NON_EXISTENT']
+            _ = env.substs['NON_EXISTENT']
         self._assert_deps(env, ['defines/MOZ_FOO', 'defines/MOZ_BAR',
                                 'substs/MOZ_SUBST_1', 'substs/NON_EXISTENT'])
         self.assertEqual(env.substs.get('NON_EXISTENT'), None)
 
     def test_set_subst(self):
         '''Test setting a subst
         '''
         env = PartialConfigEnvironment(self._objdir())
--- a/python/mozbuild/mozbuild/test/backend/test_recursivemake.py
+++ b/python/mozbuild/mozbuild/test/backend/test_recursivemake.py
@@ -1,16 +1,15 @@
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 from __future__ import unicode_literals
 
 import cPickle as pickle
-import json
 import os
 import unittest
 
 from mozpack.manifests import (
     InstallManifest,
 )
 from mozunit import main
 
@@ -403,27 +402,27 @@ class TestRecursiveMakeBackend(BackendTe
         expected = [
             'export:: $(MDDEPDIR)/bar.c.stub',
             'bar.c: $(MDDEPDIR)/bar.c.stub ;',
             'GARBAGE += bar.c',
             'GARBAGE += $(MDDEPDIR)/bar.c.stub',
             'EXTRA_MDDEPEND_FILES += bar.c.pp',
             '$(MDDEPDIR)/bar.c.stub: %s/generate-bar.py' % env.topsrcdir,
             '$(REPORT_BUILD)',
-            '$(call py_action,file_generate,%s/generate-bar.py baz bar.c $(MDDEPDIR)/bar.c.pp $(MDDEPDIR)/bar.c.stub)' % env.topsrcdir,
+            '$(call py_action,file_generate,%s/generate-bar.py baz bar.c $(MDDEPDIR)/bar.c.pp $(MDDEPDIR)/bar.c.stub)' % env.topsrcdir,  # noqa
             '@$(TOUCH) $@',
             '',
             'export:: $(MDDEPDIR)/foo.c.stub',
             'foo.c: $(MDDEPDIR)/foo.c.stub ;',
             'GARBAGE += foo.c',
             'GARBAGE += $(MDDEPDIR)/foo.c.stub',
             'EXTRA_MDDEPEND_FILES += foo.c.pp',
             '$(MDDEPDIR)/foo.c.stub: %s/generate-foo.py $(srcdir)/foo-data' % (env.topsrcdir),
             '$(REPORT_BUILD)',
-            '$(call py_action,file_generate,%s/generate-foo.py main foo.c $(MDDEPDIR)/foo.c.pp $(MDDEPDIR)/foo.c.stub $(srcdir)/foo-data)' % (env.topsrcdir),
+            '$(call py_action,file_generate,%s/generate-foo.py main foo.c $(MDDEPDIR)/foo.c.pp $(MDDEPDIR)/foo.c.stub $(srcdir)/foo-data)' % (env.topsrcdir),  # noqa
             '@$(TOUCH) $@',
             '',
         ]
 
         self.maxDiff = None
         self.assertEqual(lines, expected)
 
     def test_generated_files_force(self):
@@ -436,27 +435,27 @@ class TestRecursiveMakeBackend(BackendTe
         expected = [
             'export:: $(MDDEPDIR)/bar.c.stub',
             'bar.c: $(MDDEPDIR)/bar.c.stub ;',
             'GARBAGE += bar.c',
             'GARBAGE += $(MDDEPDIR)/bar.c.stub',
             'EXTRA_MDDEPEND_FILES += bar.c.pp',
             '$(MDDEPDIR)/bar.c.stub: %s/generate-bar.py FORCE' % env.topsrcdir,
             '$(REPORT_BUILD)',
-            '$(call py_action,file_generate,%s/generate-bar.py baz bar.c $(MDDEPDIR)/bar.c.pp $(MDDEPDIR)/bar.c.stub)' % env.topsrcdir,
+            '$(call py_action,file_generate,%s/generate-bar.py baz bar.c $(MDDEPDIR)/bar.c.pp $(MDDEPDIR)/bar.c.stub)' % env.topsrcdir,  # noqa
             '@$(TOUCH) $@',
             '',
             'export:: $(MDDEPDIR)/foo.c.stub',
             'foo.c: $(MDDEPDIR)/foo.c.stub ;',
             'GARBAGE += foo.c',
             'GARBAGE += $(MDDEPDIR)/foo.c.stub',
             'EXTRA_MDDEPEND_FILES += foo.c.pp',
             '$(MDDEPDIR)/foo.c.stub: %s/generate-foo.py $(srcdir)/foo-data' % (env.topsrcdir),
             '$(REPORT_BUILD)',
-            '$(call py_action,file_generate,%s/generate-foo.py main foo.c $(MDDEPDIR)/foo.c.pp $(MDDEPDIR)/foo.c.stub $(srcdir)/foo-data)' % (env.topsrcdir),
+            '$(call py_action,file_generate,%s/generate-foo.py main foo.c $(MDDEPDIR)/foo.c.pp $(MDDEPDIR)/foo.c.stub $(srcdir)/foo-data)' % (env.topsrcdir),  # noqa
             '@$(TOUCH) $@',
             '',
         ]
 
         self.maxDiff = None
         self.assertEqual(lines, expected)
 
     def test_localized_generated_files(self):
@@ -467,19 +466,19 @@ class TestRecursiveMakeBackend(BackendTe
         lines = [l.strip() for l in open(backend_path, 'rt').readlines()[2:]]
 
         expected = [
             'libs:: $(MDDEPDIR)/foo.xyz.stub',
             'foo.xyz: $(MDDEPDIR)/foo.xyz.stub ;',
             'GARBAGE += foo.xyz',
             'GARBAGE += $(MDDEPDIR)/foo.xyz.stub',
             'EXTRA_MDDEPEND_FILES += foo.xyz.pp',
-            '$(MDDEPDIR)/foo.xyz.stub: %s/generate-foo.py $(call MERGE_FILE,localized-input) $(srcdir)/non-localized-input $(if $(IS_LANGUAGE_REPACK),FORCE)' % env.topsrcdir,
+            '$(MDDEPDIR)/foo.xyz.stub: %s/generate-foo.py $(call MERGE_FILE,localized-input) $(srcdir)/non-localized-input $(if $(IS_LANGUAGE_REPACK),FORCE)' % env.topsrcdir,  # noqa
             '$(REPORT_BUILD)',
-            '$(call py_action,file_generate,--locale=$(AB_CD) %s/generate-foo.py main foo.xyz $(MDDEPDIR)/foo.xyz.pp $(MDDEPDIR)/foo.xyz.stub $(call MERGE_FILE,localized-input) $(srcdir)/non-localized-input)' % env.topsrcdir,
+            '$(call py_action,file_generate,--locale=$(AB_CD) %s/generate-foo.py main foo.xyz $(MDDEPDIR)/foo.xyz.pp $(MDDEPDIR)/foo.xyz.stub $(call MERGE_FILE,localized-input) $(srcdir)/non-localized-input)' % env.topsrcdir,  # noqa
             '@$(TOUCH) $@',
             '',
             'LOCALIZED_FILES_0_FILES += foo.xyz',
             'LOCALIZED_FILES_0_DEST = $(FINAL_TARGET)/',
             'LOCALIZED_FILES_0_TARGET := libs',
             'INSTALL_TARGETS += LOCALIZED_FILES_0',
         ]
 
@@ -494,29 +493,29 @@ class TestRecursiveMakeBackend(BackendTe
         lines = [l.strip() for l in open(backend_path, 'rt').readlines()[2:]]
 
         expected = [
             'libs:: $(MDDEPDIR)/foo.xyz.stub',
             'foo.xyz: $(MDDEPDIR)/foo.xyz.stub ;',
             'GARBAGE += foo.xyz',
             'GARBAGE += $(MDDEPDIR)/foo.xyz.stub',
             'EXTRA_MDDEPEND_FILES += foo.xyz.pp',
-            '$(MDDEPDIR)/foo.xyz.stub: %s/generate-foo.py $(call MERGE_FILE,localized-input) $(srcdir)/non-localized-input $(if $(IS_LANGUAGE_REPACK),FORCE)' % env.topsrcdir,
+            '$(MDDEPDIR)/foo.xyz.stub: %s/generate-foo.py $(call MERGE_FILE,localized-input) $(srcdir)/non-localized-input $(if $(IS_LANGUAGE_REPACK),FORCE)' % env.topsrcdir,  # noqa
             '$(REPORT_BUILD)',
-            '$(call py_action,file_generate,--locale=$(AB_CD) %s/generate-foo.py main foo.xyz $(MDDEPDIR)/foo.xyz.pp $(MDDEPDIR)/foo.xyz.stub $(call MERGE_FILE,localized-input) $(srcdir)/non-localized-input)' % env.topsrcdir,
+            '$(call py_action,file_generate,--locale=$(AB_CD) %s/generate-foo.py main foo.xyz $(MDDEPDIR)/foo.xyz.pp $(MDDEPDIR)/foo.xyz.stub $(call MERGE_FILE,localized-input) $(srcdir)/non-localized-input)' % env.topsrcdir,  # noqa
             '@$(TOUCH) $@',
             '',
             'libs:: $(MDDEPDIR)/abc.xyz.stub',
             'abc.xyz: $(MDDEPDIR)/abc.xyz.stub ;',
             'GARBAGE += abc.xyz',
             'GARBAGE += $(MDDEPDIR)/abc.xyz.stub',
             'EXTRA_MDDEPEND_FILES += abc.xyz.pp',
-            '$(MDDEPDIR)/abc.xyz.stub: %s/generate-foo.py $(call MERGE_FILE,localized-input) $(srcdir)/non-localized-input FORCE' % env.topsrcdir,
+            '$(MDDEPDIR)/abc.xyz.stub: %s/generate-foo.py $(call MERGE_FILE,localized-input) $(srcdir)/non-localized-input FORCE' % env.topsrcdir,  # noqa
             '$(REPORT_BUILD)',
-            '$(call py_action,file_generate,--locale=$(AB_CD) %s/generate-foo.py main abc.xyz $(MDDEPDIR)/abc.xyz.pp $(MDDEPDIR)/abc.xyz.stub $(call MERGE_FILE,localized-input) $(srcdir)/non-localized-input)' % env.topsrcdir,
+            '$(call py_action,file_generate,--locale=$(AB_CD) %s/generate-foo.py main abc.xyz $(MDDEPDIR)/abc.xyz.pp $(MDDEPDIR)/abc.xyz.stub $(call MERGE_FILE,localized-input) $(srcdir)/non-localized-input)' % env.topsrcdir,  # noqa
             '@$(TOUCH) $@',
             '',
         ]
 
         self.maxDiff = None
         self.assertEqual(lines, expected)
 
     def test_localized_generated_files_AB_CD(self):
@@ -528,38 +527,38 @@ class TestRecursiveMakeBackend(BackendTe
         lines = [l.strip() for l in open(backend_path, 'rt').readlines()[2:]]
 
         expected = [
             'libs:: $(MDDEPDIR)/foo$(AB_CD).xyz.stub',
             'foo$(AB_CD).xyz: $(MDDEPDIR)/foo$(AB_CD).xyz.stub ;',
             'GARBAGE += foo$(AB_CD).xyz',
             'GARBAGE += $(MDDEPDIR)/foo$(AB_CD).xyz.stub',
             'EXTRA_MDDEPEND_FILES += foo$(AB_CD).xyz.pp',
-            '$(MDDEPDIR)/foo$(AB_CD).xyz.stub: %s/generate-foo.py $(call MERGE_FILE,localized-input) $(srcdir)/non-localized-input $(if $(IS_LANGUAGE_REPACK),FORCE)' % env.topsrcdir,
+            '$(MDDEPDIR)/foo$(AB_CD).xyz.stub: %s/generate-foo.py $(call MERGE_FILE,localized-input) $(srcdir)/non-localized-input $(if $(IS_LANGUAGE_REPACK),FORCE)' % env.topsrcdir,  # noqa
             '$(REPORT_BUILD)',
-            '$(call py_action,file_generate,--locale=$(AB_CD) %s/generate-foo.py main foo$(AB_CD).xyz $(MDDEPDIR)/foo$(AB_CD).xyz.pp $(MDDEPDIR)/foo$(AB_CD).xyz.stub $(call MERGE_FILE,localized-input) $(srcdir)/non-localized-input)' % env.topsrcdir,
+            '$(call py_action,file_generate,--locale=$(AB_CD) %s/generate-foo.py main foo$(AB_CD).xyz $(MDDEPDIR)/foo$(AB_CD).xyz.pp $(MDDEPDIR)/foo$(AB_CD).xyz.stub $(call MERGE_FILE,localized-input) $(srcdir)/non-localized-input)' % env.topsrcdir,  # noqa
             '@$(TOUCH) $@',
             '',
             'include $(topsrcdir)/config/AB_rCD.mk',
             'bar$(AB_rCD).xyz: $(MDDEPDIR)/bar$(AB_rCD).xyz.stub ;',
             'GARBAGE += bar$(AB_rCD).xyz',
             'GARBAGE += $(MDDEPDIR)/bar$(AB_rCD).xyz.stub',
             'EXTRA_MDDEPEND_FILES += bar$(AB_rCD).xyz.pp',
-            '$(MDDEPDIR)/bar$(AB_rCD).xyz.stub: %s/generate-foo.py $(call MERGE_RELATIVE_FILE,localized-input,inner/locales) $(srcdir)/non-localized-input $(if $(IS_LANGUAGE_REPACK),FORCE)' % env.topsrcdir,
+            '$(MDDEPDIR)/bar$(AB_rCD).xyz.stub: %s/generate-foo.py $(call MERGE_RELATIVE_FILE,localized-input,inner/locales) $(srcdir)/non-localized-input $(if $(IS_LANGUAGE_REPACK),FORCE)' % env.topsrcdir,  # noqa
             '$(REPORT_BUILD)',
-            '$(call py_action,file_generate,--locale=$(AB_CD) %s/generate-foo.py main bar$(AB_rCD).xyz $(MDDEPDIR)/bar$(AB_rCD).xyz.pp $(MDDEPDIR)/bar$(AB_rCD).xyz.stub $(call MERGE_RELATIVE_FILE,localized-input,inner/locales) $(srcdir)/non-localized-input)' % env.topsrcdir,
+            '$(call py_action,file_generate,--locale=$(AB_CD) %s/generate-foo.py main bar$(AB_rCD).xyz $(MDDEPDIR)/bar$(AB_rCD).xyz.pp $(MDDEPDIR)/bar$(AB_rCD).xyz.stub $(call MERGE_RELATIVE_FILE,localized-input,inner/locales) $(srcdir)/non-localized-input)' % env.topsrcdir,  # noqa
             '@$(TOUCH) $@',
             '',
             'zot$(AB_rCD).xyz: $(MDDEPDIR)/zot$(AB_rCD).xyz.stub ;',
             'GARBAGE += zot$(AB_rCD).xyz',
             'GARBAGE += $(MDDEPDIR)/zot$(AB_rCD).xyz.stub',
             'EXTRA_MDDEPEND_FILES += zot$(AB_rCD).xyz.pp',
-            '$(MDDEPDIR)/zot$(AB_rCD).xyz.stub: %s/generate-foo.py $(call MERGE_RELATIVE_FILE,localized-input,locales) $(srcdir)/non-localized-input $(if $(IS_LANGUAGE_REPACK),FORCE)' % env.topsrcdir,
+            '$(MDDEPDIR)/zot$(AB_rCD).xyz.stub: %s/generate-foo.py $(call MERGE_RELATIVE_FILE,localized-input,locales) $(srcdir)/non-localized-input $(if $(IS_LANGUAGE_REPACK),FORCE)' % env.topsrcdir,  # noqa
             '$(REPORT_BUILD)',
-            '$(call py_action,file_generate,--locale=$(AB_CD) %s/generate-foo.py main zot$(AB_rCD).xyz $(MDDEPDIR)/zot$(AB_rCD).xyz.pp $(MDDEPDIR)/zot$(AB_rCD).xyz.stub $(call MERGE_RELATIVE_FILE,localized-input,locales) $(srcdir)/non-localized-input)' % env.topsrcdir,
+            '$(call py_action,file_generate,--locale=$(AB_CD) %s/generate-foo.py main zot$(AB_rCD).xyz $(MDDEPDIR)/zot$(AB_rCD).xyz.pp $(MDDEPDIR)/zot$(AB_rCD).xyz.stub $(call MERGE_RELATIVE_FILE,localized-input,locales) $(srcdir)/non-localized-input)' % env.topsrcdir,  # noqa
             '@$(TOUCH) $@',
             '',
         ]
 
         self.maxDiff = None
         self.assertEqual(lines, expected)
 
     def test_exports_generated(self):
@@ -752,35 +751,35 @@ class TestRecursiveMakeBackend(BackendTe
         for e in expected:
             full = mozpath.join(man_dir, e)
             self.assertTrue(os.path.exists(full))
 
             m2 = InstallManifest(path=full)
             self.assertEqual(m, m2)
 
     def test_ipdl_sources(self):
-        """Test that PREPROCESSED_IPDL_SOURCES and IPDL_SOURCES are written to ipdlsrcs.mk correctly."""
+        """Test that PREPROCESSED_IPDL_SOURCES and IPDL_SOURCES are written to
+        ipdlsrcs.mk correctly."""
         env = self._get_environment('ipdl_sources')
 
         # Make substs writable so we can set the value of IPDL_ROOT to reflect
         # the correct objdir.
         env.substs = dict(env.substs)
         env.substs['IPDL_ROOT'] = env.topobjdir
 
         self._consume('ipdl_sources', RecursiveMakeBackend, env)
 
         manifest_path = mozpath.join(env.topobjdir, 'ipdlsrcs.mk')
         lines = [l.strip() for l in open(manifest_path, 'rt').readlines()]
 
         # Handle Windows paths correctly
         topsrcdir = env.topsrcdir.replace(os.sep, '/')
 
         expected = [
-            "ALL_IPDLSRCS := bar1.ipdl foo1.ipdl %s/bar/bar.ipdl %s/bar/bar2.ipdlh %s/foo/foo.ipdl %s/foo/foo2.ipdlh" % tuple([
-                                                                                                                              topsrcdir] * 4),
+            "ALL_IPDLSRCS := bar1.ipdl foo1.ipdl %s/bar/bar.ipdl %s/bar/bar2.ipdlh %s/foo/foo.ipdl %s/foo/foo2.ipdlh" % tuple([topsrcdir] * 4),  # noqa
             "CPPSRCS := UnifiedProtocols0.cpp",
             "IPDLDIRS := %s %s/bar %s/foo" % (env.topobjdir, topsrcdir, topsrcdir),
         ]
 
         found = [str for str in lines if str.startswith(('ALL_IPDLSRCS',
                                                          'CPPSRCS',
                                                          'IPDLDIRS'))]
         self.assertEqual(found, expected)
@@ -815,18 +814,16 @@ class TestRecursiveMakeBackend(BackendTe
 
     def test_generated_includes(self):
         """Test that GENERATED_INCLUDES are written to backend.mk correctly."""
         env = self._consume('generated_includes', RecursiveMakeBackend)
 
         backend_path = mozpath.join(env.topobjdir, 'backend.mk')
         lines = [l.strip() for l in open(backend_path, 'rt').readlines()[2:]]
 
-        topobjdir = env.topobjdir.replace('\\', '/')
-
         expected = [
             'LOCAL_INCLUDES += -I$(CURDIR)/bar/baz',
             'LOCAL_INCLUDES += -I$(CURDIR)/foo',
         ]
 
         found = [str for str in lines if str.startswith('LOCAL_INCLUDES')]
         self.assertEqual(found, expected)
 
@@ -835,51 +832,51 @@ class TestRecursiveMakeBackend(BackendTe
         env = self._consume('rust-library', RecursiveMakeBackend)
 
         backend_path = mozpath.join(env.topobjdir, 'backend.mk')
         lines = [l.strip() for l in open(backend_path, 'rt').readlines()[2:]
                  # Strip out computed flags, they're a PITA to test.
                  if not l.startswith('COMPUTED_')]
 
         expected = [
-            'RUST_LIBRARY_FILE := %s/x86_64-unknown-linux-gnu/release/libtest_library.a' % env.topobjdir,
+            'RUST_LIBRARY_FILE := %s/x86_64-unknown-linux-gnu/release/libtest_library.a' % env.topobjdir,  # noqa
             'CARGO_FILE := $(srcdir)/Cargo.toml',
             'CARGO_TARGET_DIR := %s' % env.topobjdir,
         ]
 
         self.assertEqual(lines, expected)
 
     def test_host_rust_library(self):
         """Test that a Rust library is written to backend.mk correctly."""
         env = self._consume('host-rust-library', RecursiveMakeBackend)
 
         backend_path = mozpath.join(env.topobjdir, 'backend.mk')
         lines = [l.strip() for l in open(backend_path, 'rt').readlines()[2:]
                  # Strip out computed flags, they're a PITA to test.
                  if not l.startswith('COMPUTED_')]
 
         expected = [
-            'HOST_RUST_LIBRARY_FILE := %s/x86_64-unknown-linux-gnu/release/libhostrusttool.a' % env.topobjdir,
+            'HOST_RUST_LIBRARY_FILE := %s/x86_64-unknown-linux-gnu/release/libhostrusttool.a' % env.topobjdir,  # noqa
             'CARGO_FILE := $(srcdir)/Cargo.toml',
             'CARGO_TARGET_DIR := %s' % env.topobjdir,
         ]
 
         self.assertEqual(lines, expected)
 
     def test_host_rust_library_with_features(self):
         """Test that a host Rust library with features is written to backend.mk correctly."""
         env = self._consume('host-rust-library-features', RecursiveMakeBackend)
 
         backend_path = mozpath.join(env.topobjdir, 'backend.mk')
         lines = [l.strip() for l in open(backend_path, 'rt').readlines()[2:]
                  # Strip out computed flags, they're a PITA to test.
                  if not l.startswith('COMPUTED_')]
 
         expected = [
-            'HOST_RUST_LIBRARY_FILE := %s/x86_64-unknown-linux-gnu/release/libhostrusttool.a' % env.topobjdir,
+            'HOST_RUST_LIBRARY_FILE := %s/x86_64-unknown-linux-gnu/release/libhostrusttool.a' % env.topobjdir,  # noqa
             'CARGO_FILE := $(srcdir)/Cargo.toml',
             'CARGO_TARGET_DIR := %s' % env.topobjdir,
             'HOST_RUST_LIBRARY_FEATURES := musthave cantlivewithout',
         ]
 
         self.assertEqual(lines, expected)
 
     def test_rust_library_with_features(self):
@@ -887,17 +884,17 @@ class TestRecursiveMakeBackend(BackendTe
         env = self._consume('rust-library-features', RecursiveMakeBackend)
 
         backend_path = mozpath.join(env.topobjdir, 'backend.mk')
         lines = [l.strip() for l in open(backend_path, 'rt').readlines()[2:]
                  # Strip out computed flags, they're a PITA to test.
                  if not l.startswith('COMPUTED_')]
 
         expected = [
-            'RUST_LIBRARY_FILE := %s/x86_64-unknown-linux-gnu/release/libfeature_library.a' % env.topobjdir,
+            'RUST_LIBRARY_FILE := %s/x86_64-unknown-linux-gnu/release/libfeature_library.a' % env.topobjdir,  # noqa
             'CARGO_FILE := $(srcdir)/Cargo.toml',
             'CARGO_TARGET_DIR := %s' % env.topobjdir,
             'RUST_LIBRARY_FEATURES := musthave cantlivewithout',
         ]
 
         self.assertEqual(lines, expected)
 
     def test_rust_programs(self):
@@ -924,17 +921,17 @@ class TestRecursiveMakeBackend(BackendTe
         lines = [l.strip() for l in open(root_deps_path, 'rt').readlines()]
 
         self.assertTrue(any(l == 'recurse_compile: code/target code/host' for l in lines))
 
     def test_final_target(self):
         """Test that FINAL_TARGET is written to backend.mk correctly."""
         env = self._consume('final_target', RecursiveMakeBackend)
 
-        final_target_rule = "FINAL_TARGET = $(if $(XPI_NAME),$(DIST)/xpi-stage/$(XPI_NAME),$(DIST)/bin)$(DIST_SUBDIR:%=/%)"
+        final_target_rule = "FINAL_TARGET = $(if $(XPI_NAME),$(DIST)/xpi-stage/$(XPI_NAME),$(DIST)/bin)$(DIST_SUBDIR:%=/%)"  # noqa
         expected = dict()
         expected[env.topobjdir] = []
         expected[mozpath.join(env.topobjdir, 'both')] = [
             'XPI_NAME = mycrazyxpi',
             'DIST_SUBDIR = asubdir',
             final_target_rule
         ]
         expected[mozpath.join(env.topobjdir, 'dist-subdir')] = [
--- a/python/mozbuild/mozbuild/test/codecoverage/test_lcov_rewrite.py
+++ b/python/mozbuild/mozbuild/test/codecoverage/test_lcov_rewrite.py
@@ -1,14 +1,13 @@
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this file,
 # You can obtain one at http://mozilla.org/MPL/2.0/.
 
 import os
-import subprocess
 import unittest
 import shutil
 from StringIO import StringIO
 import json
 from tempfile import NamedTemporaryFile
 
 from mozbuild.codecoverage import chrome_map
 from mozbuild.codecoverage import lcov_rewriter
@@ -282,17 +281,18 @@ class TestUrlFinder(unittest.TestCase):
                 'resource://activity-stream/': [
                     'dist/bin/browser/chrome/browser/res/activity-stream',
                 ],
                 'chrome://browser/content/': [
                     'dist/bin/browser/chrome/browser/content/browser',
                 ],
             },
             {
-                'chrome://global/content/netError.xhtml': 'chrome://browser/content/aboutNetError.xhtml',
+                'chrome://global/content/netError.xhtml':
+                    'chrome://browser/content/aboutNetError.xhtml',
             },
             {
                 'dist/bin/components/MainProcessSingleton.js': [
                     'path1',
                     None
                 ],
                 'dist/bin/browser/features/firefox@getpocket.com/bootstrap.js': [
                     'path4',
@@ -340,19 +340,16 @@ class TestUrlFinder(unittest.TestCase):
              '/browser/features/firefox@getpocket.com.xpi!/bootstrap.js', 'path4'),
         ]
 
         url_finder = lcov_rewriter.UrlFinder(self._chrome_map_file, '', '', [])
         for path, expected in paths:
             self.assertEqual(url_finder.rewrite_url(path)[0], expected)
 
     def test_wrong_scheme_paths(self):
-        app_name = buildconfig.substs.get('MOZ_APP_NAME')
-        omnijar_name = buildconfig.substs.get('OMNIJAR_NAME')
-
         paths = [
             'http://www.mozilla.org/aFile.js',
             'https://www.mozilla.org/aFile.js',
             'data:something',
             'about:newtab',
             'javascript:something',
         ]
 
@@ -371,17 +368,17 @@ class TestUrlFinder(unittest.TestCase):
             # Path which is in url overrides
             ('chrome://global/content/netError.xhtml',
              ('browser/base/content/aboutNetError.xhtml', None)),
             # Path which ends with > eval
             ('resource://gre/modules/osfile/osfile_async_worker.js line 3 > eval', None),
             # Path which ends with > Function
             ('resource://gre/modules/osfile/osfile_async_worker.js line 3 > Function', None),
             # Path which contains "->"
-            ('resource://gre/modules/addons/XPIProvider.jsm -> resource://gre/modules/osfile/osfile_async_worker.js',
+            ('resource://gre/modules/addons/XPIProvider.jsm -> resource://gre/modules/osfile/osfile_async_worker.js',  # noqa
              ('toolkit/components/osfile/modules/osfile_async_worker.js', None)),
             # Path with pp_info
             ('resource://gre/modules/AppConstants.jsm', ('toolkit/modules/AppConstants.jsm', {
                 '101,102': [
                     'toolkit/modules/AppConstants.jsm',
                     135
                 ],
             })),
--- a/python/mozbuild/mozbuild/test/configure/lint.py
+++ b/python/mozbuild/mozbuild/test/configure/lint.py
@@ -1,17 +1,16 @@
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 from __future__ import absolute_import, print_function, unicode_literals
 
 import os
 import unittest
-from StringIO import StringIO
 from mozunit import main
 from buildconfig import (
     topobjdir,
     topsrcdir,
 )
 
 from mozbuild.configure.lint import LintSandbox
 
--- a/python/mozbuild/mozbuild/test/configure/test_checks_configure.py
+++ b/python/mozbuild/mozbuild/test/configure/test_checks_configure.py
@@ -469,17 +469,18 @@ class TestChecksConfigure(unittest.TestC
         ''' % self.KNOWN_A))
 
         config, out, status = self.get_result('check_prog("A", ("known-a",), paths="%s")' %
                                               os.path.dirname(self.OTHER_A))
 
         self.assertEqual(status, 1)
         self.assertEqual(config, {})
         self.assertEqual(out, textwrap.dedent('''\
-            checking for a... 
+            checking for a... '''  # noqa  # trailing whitespace...
+                '''
             DEBUG: a: Trying known-a
             ERROR: Paths provided to find_program must be a list of strings, not %r
         ''' % mozpath.dirname(self.OTHER_A)))
 
     def test_java_tool_checks(self):
         # A valid set of tools in a standard location.
         java = mozpath.abspath('/usr/bin/java')
         jarsigner = mozpath.abspath('/usr/bin/jarsigner')
@@ -615,18 +616,21 @@ class TestChecksConfigure(unittest.TestC
         self.assertEqual(status, 1)
         self.assertEqual(config, {
             'JAVA': java,
             'JARSIGNER': ':',
         })
         self.assertEqual(out, textwrap.dedent('''\
              checking for java... %s
              checking for jarsigner... not found
-             ERROR: The program jarsigner was not found.  Set $JAVA_HOME to your Java SDK directory or use '--with-java-bin-path={java-bin-dir}'
-        ''' % (java)))
+             ERROR: The program jarsigner was not found.  Set $JAVA_HOME to your \
+Java SDK directory or use '--with-java-bin-path={java-bin-dir}'
+        ''' % (java)
+            ),
+        )
 
     def test_pkg_check_modules(self):
         mock_pkg_config_version = '0.10.0'
         mock_pkg_config_path = mozpath.abspath('/usr/bin/pkg-config')
 
         def mock_pkg_config(_, args):
             if args[0:2] == ['--errors-to-stdout', '--print-errors']:
                 assert len(args) == 3
@@ -659,17 +663,16 @@ class TestChecksConfigure(unittest.TestC
                 include('%(topsrcdir)s/build/moz.configure/checks.configure')
                 include('%(topsrcdir)s/build/moz.configure/pkg.configure')
             ''' % {'topsrcdir': topsrcdir}) + cmd, args=args, extra_paths=extra_paths,
                                                    includes=())
 
         extra_paths = {
             mock_pkg_config_path: mock_pkg_config,
         }
-        includes = ('util.configure', 'checks.configure', 'pkg.configure')
 
         config, output, status = get_result("pkg_check_modules('MOZ_VALID', 'valid')")
         self.assertEqual(status, 1)
         self.assertEqual(output, textwrap.dedent('''\
             checking for pkg_config... not found
             ERROR: *** The pkg-config script could not be found. Make sure it is
             *** in your path, or set the PKG_CONFIG environment variable
             *** to the full path to pkg-config.
--- a/python/mozbuild/mozbuild/test/configure/test_configure.py
+++ b/python/mozbuild/mozbuild/test/configure/test_configure.py
@@ -634,28 +634,30 @@ class TestConfigure(unittest.TestCase):
 
         config = get_config([])
         self.assertEquals(config, {})
 
         config_path = mozpath.abspath(
             mozpath.join(test_data_path, 'imply_option', 'imm.configure'))
 
         with self.assertRaisesRegexp(InvalidOptionError,
-                                     "--enable-foo' implied by 'imply_option at %s:7' conflicts with "
-                                     "'--disable-foo' from the command-line" % config_path):
+                                     "--enable-foo' implied by 'imply_option at %s:7' conflicts "
+                                     "with '--disable-foo' from the command-line" % config_path):
             get_config(['--disable-foo'])
 
         with self.assertRaisesRegexp(InvalidOptionError,
-                                     "--enable-bar=foo,bar' implied by 'imply_option at %s:16' conflicts"
-                                     " with '--enable-bar=a,b,c' from the command-line" % config_path):
+                                     "--enable-bar=foo,bar' implied by 'imply_option at %s:16' "
+                                     "conflicts with '--enable-bar=a,b,c' from the command-line"
+                                     % config_path):
             get_config(['--enable-bar=a,b,c'])
 
         with self.assertRaisesRegexp(InvalidOptionError,
-                                     "--enable-baz=BAZ' implied by 'imply_option at %s:25' conflicts"
-                                     " with '--enable-baz=QUUX' from the command-line" % config_path):
+                                     "--enable-baz=BAZ' implied by 'imply_option at %s:25' "
+                                     "conflicts with '--enable-baz=QUUX' from the command-line"
+                                     % config_path):
             get_config(['--enable-baz=QUUX'])
 
     def test_imply_option_failures(self):
         with self.assertRaises(ConfigureError) as e:
             with self.moz_configure('''
                 imply_option('--with-foo', ('a',), 'bar')
             '''):
                 self.get_config()
@@ -805,27 +807,27 @@ class TestConfigure(unittest.TestCase):
 
             set_config('FOO', depends('--with-foo')(lambda x: x))
             set_config('QUX', depends('--with-qux')(lambda x: x))
         '''):
             # Note: no error is detected when the depends function in the
             # imply_options resolve to None, which disables the imply_option.
 
             with self.assertRaises(ConfigureError) as e:
-                config = self.get_config()
+                self.get_config()
 
             self.assertEquals(e.exception.message, message)
 
             with self.assertRaises(ConfigureError) as e:
-                config = self.get_config(['--with-qux'])
+                self.get_config(['--with-qux'])
 
             self.assertEquals(e.exception.message, message)
 
             with self.assertRaises(ConfigureError) as e:
-                config = self.get_config(['--without-foo', '--with-qux'])
+                self.get_config(['--without-foo', '--with-qux'])
 
             self.assertEquals(e.exception.message, message)
 
     def test_option_failures(self):
         with self.assertRaises(ConfigureError) as e:
             with self.moz_configure('option("--with-foo", help="foo")'):
                 self.get_config()
 
--- a/python/mozbuild/mozbuild/test/configure/test_lint.py
+++ b/python/mozbuild/mozbuild/test/configure/test_lint.py
@@ -1,15 +1,14 @@
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 from __future__ import absolute_import, print_function, unicode_literals
 
-from StringIO import StringIO
 import contextlib
 import os
 import sys
 import textwrap
 import traceback
 import unittest
 
 from mozunit import (
--- a/python/mozbuild/mozbuild/test/configure/test_moz_configure.py
+++ b/python/mozbuild/mozbuild/test/configure/test_moz_configure.py
@@ -1,16 +1,14 @@
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 from __future__ import absolute_import, print_function, unicode_literals
 
-import sys
-
 from mozunit import main
 from mozbuild.util import (
     exec_,
     ReadOnlyNamespace,
 )
 from common import BaseConfigureTest
 
 
@@ -151,20 +149,20 @@ class TestMozConfigure(BaseConfigureTest
                 return 0, self.version, ''
 
         def check_nsis_version(version):
             sandbox = self.get_sandbox(
                 {'/usr/bin/makensis': FakeNSIS(version)}, {}, [],
                 {'PATH': '/usr/bin', 'MAKENSISU': '/usr/bin/makensis'})
             return sandbox._value_for(sandbox['nsis_version'])
 
-        with self.assertRaises(SystemExit) as e:
+        with self.assertRaises(SystemExit):
             check_nsis_version('v2.5')
 
-        with self.assertRaises(SystemExit) as e:
+        with self.assertRaises(SystemExit):
             check_nsis_version('v3.0a2')
 
         self.assertEquals(check_nsis_version('v3.0b1'), '3.0b1')
         self.assertEquals(check_nsis_version('v3.0b2'), '3.0b2')
         self.assertEquals(check_nsis_version('v3.0rc1'), '3.0rc1')
         self.assertEquals(check_nsis_version('v3.0'), '3.0')
         self.assertEquals(check_nsis_version('v3.0-2'), '3.0')
         self.assertEquals(check_nsis_version('v3.0.1'), '3.0')
--- a/python/mozbuild/mozbuild/test/configure/test_options.py
+++ b/python/mozbuild/mozbuild/test/configure/test_options.py
@@ -870,21 +870,25 @@ class TestCommandLineHelper(unittest.Tes
                      possible_origins=('command-line',))
         value, option = helper.handle(foo)
         self.assertEquals(PositiveOptionValue(), value)
         self.assertEquals('command-line', value.origin)
         self.assertEquals('--foo', option)
 
         bar = Option('--bar',
                      possible_origins=('mozconfig',))
-        with self.assertRaisesRegexp(InvalidOptionError,
-                                     "--bar can not be set by command-line. Values are accepted from: mozconfig"):
+        with self.assertRaisesRegexp(
+            InvalidOptionError,
+            "--bar can not be set by command-line. Values are accepted from: mozconfig"
+        ):
             helper.handle(bar)
 
         baz = Option(env='BAZ',
                      possible_origins=('implied',))
-        with self.assertRaisesRegexp(InvalidOptionError,
-                                     "BAZ=1 can not be set by environment. Values are accepted from: implied"):
+        with self.assertRaisesRegexp(
+            InvalidOptionError,
+            "BAZ=1 can not be set by environment. Values are accepted from: implied"
+        ):
             helper.handle(baz)
 
 
 if __name__ == '__main__':
     main()
--- a/python/mozbuild/mozbuild/test/configure/test_toolkit_moz_configure.py
+++ b/python/mozbuild/mozbuild/test/configure/test_toolkit_moz_configure.py
@@ -115,35 +115,38 @@ class TestToolkitMozConfigure(BaseConfig
         func(Version('1.5'), Version('1.1'), Version('1.0'), False)
 
         out.truncate(0)
         with self.assertRaises(SystemExit):
             func(None, Version('1.0'), False, False)
 
         self.assertEqual(
             out.getvalue(),
-            'ERROR: Yasm is required to build with vpx, but you do not appear to have Yasm installed.\n'
+            ('ERROR: Yasm is required to build with vpx, but you do not appear '
+             'to have Yasm installed.\n'),
         )
 
         out.truncate(0)
         with self.assertRaises(SystemExit):
             func(None, Version('1.0'), Version('1.0'), False)
 
         self.assertEqual(
             out.getvalue(),
-            'ERROR: Yasm is required to build with jpeg and vpx, but you do not appear to have Yasm installed.\n'
+            ('ERROR: Yasm is required to build with jpeg and vpx, but you do not appear '
+             'to have Yasm installed.\n'),
         )
 
         out.truncate(0)
         with self.assertRaises(SystemExit):
             func(None, Version('1.0'), Version('1.0'), Version('1.0'))
 
         self.assertEqual(
             out.getvalue(),
-            'ERROR: Yasm is required to build with jpeg, libav and vpx, but you do not appear to have Yasm installed.\n'
+            ('ERROR: Yasm is required to build with jpeg, libav and vpx, but you do not appear '
+             'to have Yasm installed.\n'),
         )
 
         out.truncate(0)
         with self.assertRaises(SystemExit):
             func(Version('1.0'), Version('1.1'), Version('1.0'), False)
 
         self.assertEqual(
             out.getvalue(),
--- a/python/mozbuild/mozbuild/test/frontend/test_emitter.py
+++ b/python/mozbuild/mozbuild/test/frontend/test_emitter.py
@@ -9,26 +9,24 @@ import unittest
 
 from mozunit import main
 
 from mozbuild.frontend.context import (
     ObjDirPath,
     Path,
 )
 from mozbuild.frontend.data import (
-    ChromeManifestEntry,
     ComputedFlags,
     ConfigFileSubstitution,
     Defines,
     DirectoryTraversal,
     Exports,
     FinalTargetPreprocessedFiles,
     GeneratedFile,
     GeneratedSources,
-    HostDefines,
     HostProgram,
     HostRustLibrary,
     HostRustProgram,
     HostSources,
     IPDLCollection,
     JARManifest,
     LinkageMultipleRustLibrariesError,
     LocalInclude,
@@ -47,17 +45,16 @@ from mozbuild.frontend.data import (
     VariablePassthru,
 )
 from mozbuild.frontend.emitter import TreeMetadataEmitter
 from mozbuild.frontend.reader import (
     BuildReader,
     BuildReaderError,
     SandboxValidationError,
 )
-from mozpack.chrome import manifest
 
 from mozbuild.test.common import MockConfig
 
 import mozpack.path as mozpath
 
 
 data_path = mozpath.abspath(mozpath.dirname(__file__))
 data_path = mozpath.join(data_path, 'data')
@@ -528,28 +525,32 @@ class TestEmitterBasic(unittest.TestCase
         self.assertIsInstance(objs[0], GeneratedFile)
         self.assertIsInstance(objs[1], LocalizedFiles)
 
     def test_localized_files_not_localized_generated(self):
         """Test that using GENERATED_FILES and then putting the output in
         LOCALIZED_FILES as an objdir path produces an error.
         """
         reader = self.reader('localized-files-not-localized-generated')
-        with self.assertRaisesRegexp(SandboxValidationError,
-                                     'Objdir file listed in LOCALIZED_FILES not in LOCALIZED_GENERATED_FILES:'):
-            objs = self.read_topsrcdir(reader)
+        with self.assertRaisesRegexp(
+            SandboxValidationError,
+            'Objdir file listed in LOCALIZED_FILES not in LOCALIZED_GENERATED_FILES:'
+        ):
+            self.read_topsrcdir(reader)
 
     def test_localized_generated_files_final_target_files(self):
         """Test that using LOCALIZED_GENERATED_FILES and then putting the output in
         FINAL_TARGET_FILES as an objdir path produces an error.
         """
         reader = self.reader('localized-generated-files-final-target-files')
-        with self.assertRaisesRegexp(SandboxValidationError,
-                                     'Outputs of LOCALIZED_GENERATED_FILES cannot be used in FINAL_TARGET_FILES:'):
-            objs = self.read_topsrcdir(reader)
+        with self.assertRaisesRegexp(
+            SandboxValidationError,
+            'Outputs of LOCALIZED_GENERATED_FILES cannot be used in FINAL_TARGET_FILES:'
+        ):
+            self.read_topsrcdir(reader)
 
     def test_generated_files_method_names(self):
         reader = self.reader('generated-files-method-names')
         objs = self.read_topsrcdir(reader)
 
         self.assertEqual(len(objs), 2)
         for o in objs:
             self.assertIsInstance(o, GeneratedFile)
@@ -743,18 +744,21 @@ class TestEmitterBasic(unittest.TestCase
             self.read_topsrcdir(reader)
 
     def test_test_manifest_dupe_support_files(self):
         """A test manifest with dupe support-files in a single test is not
         supported.
         """
         reader = self.reader('test-manifest-dupes')
 
-        with self.assertRaisesRegexp(SandboxValidationError, 'bar.js appears multiple times '
-                                     'in a test manifest under a support-files field, please omit the duplicate entry.'):
+        with self.assertRaisesRegexp(
+            SandboxValidationError,
+            'bar.js appears multiple times '
+            'in a test manifest under a support-files field, please omit the duplicate entry.'
+        ):
             self.read_topsrcdir(reader)
 
     def test_test_manifest_absolute_support_files(self):
         """Support files starting with '/' are placed relative to the install root"""
         reader = self.reader('test-manifest-absolute-support')
 
         objs = self.read_topsrcdir(reader)
         self.assertEqual(len(objs), 1)
@@ -1051,34 +1055,34 @@ class TestEmitterBasic(unittest.TestCase
     def test_local_includes_invalid(self):
         """Test that invalid LOCAL_INCLUDES are properly detected."""
         reader = self.reader('local_includes-invalid/srcdir')
 
         with self.assertRaisesRegexp(
                 SandboxValidationError,
                 'Path specified in LOCAL_INCLUDES.*resolves to the '
                 'topsrcdir or topobjdir'):
-            objs = self.read_topsrcdir(reader)
+            self.read_topsrcdir(reader)
 
         reader = self.reader('local_includes-invalid/objdir')
 
         with self.assertRaisesRegexp(
                 SandboxValidationError,
                 'Path specified in LOCAL_INCLUDES.*resolves to the '
                 'topsrcdir or topobjdir'):
-            objs = self.read_topsrcdir(reader)
+            self.read_topsrcdir(reader)
 
     def test_local_includes_file(self):
         """Test that a filename can't be used in LOCAL_INCLUDES."""
         reader = self.reader('local_includes-filename')
 
         with self.assertRaisesRegexp(
                 SandboxValidationError,
                 'Path specified in LOCAL_INCLUDES is a filename'):
-            objs = self.read_topsrcdir(reader)
+            self.read_topsrcdir(reader)
 
     def test_generated_includes(self):
         """Test that GENERATED_INCLUDES is emitted correctly."""
         reader = self.reader('generated_includes')
         objs = self.read_topsrcdir(reader)
 
         generated_includes = [o.path for o in objs if isinstance(o, LocalInclude)]
         expected = [
@@ -1415,18 +1419,20 @@ class TestEmitterBasic(unittest.TestCase
         with self.assertRaisesRegexp(SandboxValidationError, 'File listed in '
                                      'FINAL_TARGET_PP_FILES does not exist'):
             reader = self.reader('dist-files-missing')
             self.read_topsrcdir(reader)
 
     def test_final_target_pp_files_non_srcdir(self):
         '''Test that non-srcdir paths in FINAL_TARGET_PP_FILES throws errors.'''
         reader = self.reader('final-target-pp-files-non-srcdir')
-        with self.assertRaisesRegexp(SandboxValidationError,
-                                     'Only source directory paths allowed in FINAL_TARGET_PP_FILES:'):
+        with self.assertRaisesRegexp(
+            SandboxValidationError,
+            'Only source directory paths allowed in FINAL_TARGET_PP_FILES:'
+        ):
             self.read_topsrcdir(reader)
 
     def test_localized_files(self):
         """Test that LOCALIZED_FILES works properly."""
         reader = self.reader('localized-files')
         objs = self.read_topsrcdir(reader)
 
         self.assertEqual(len(objs), 1)
@@ -1439,19 +1445,21 @@ class TestEmitterBasic(unittest.TestCase
             expected = {'en-US/bar.ini', 'en-US/code/*.js', 'en-US/foo.js'}
             for f in files:
                 self.assertTrue(unicode(f) in expected)
 
     def test_localized_files_no_en_us(self):
         """Test that LOCALIZED_FILES errors if a path does not start with
         `en-US/` or contain `locales/en-US/`."""
         reader = self.reader('localized-files-no-en-us')
-        with self.assertRaisesRegexp(SandboxValidationError,
-                                     'LOCALIZED_FILES paths must start with `en-US/` or contain `locales/en-US/`: foo.js'):
-            objs = self.read_topsrcdir(reader)
+        with self.assertRaisesRegexp(
+            SandboxValidationError,
+            'LOCALIZED_FILES paths must start with `en-US/` or contain `locales/en-US/`: foo.js'
+        ):
+            self.read_topsrcdir(reader)
 
     def test_localized_pp_files(self):
         """Test that LOCALIZED_PP_FILES works properly."""
         reader = self.reader('localized-pp-files')
         objs = self.read_topsrcdir(reader)
 
         self.assertEqual(len(objs), 1)
         self.assertIsInstance(objs[0], LocalizedPreprocessedFiles)
@@ -1660,15 +1668,17 @@ class TestEmitterBasic(unittest.TestCase
         self.assertIsInstance(shlib, SharedLibrary)
         self.assertEqual(shlib.symbols_file, 'foo.symbols')
 
     def test_symbols_file_objdir_missing_generated(self):
         """Test that a SYMBOLS_FILE in the objdir that's missing
         from GENERATED_FILES is an error.
         """
         reader = self.reader('test-symbols-file-objdir-missing-generated')
-        with self.assertRaisesRegexp(SandboxValidationError,
-                                     'Objdir file specified in SYMBOLS_FILE not in GENERATED_FILES:'):
+        with self.assertRaisesRegexp(
+            SandboxValidationError,
+            'Objdir file specified in SYMBOLS_FILE not in GENERATED_FILES:'
+        ):
             self.read_topsrcdir(reader)
 
 
 if __name__ == '__main__':
     main()
--- a/python/mozbuild/mozbuild/test/frontend/test_reader.py
+++ b/python/mozbuild/mozbuild/test/frontend/test_reader.py
@@ -242,17 +242,17 @@ class TestBuildReader(unittest.TestCase)
 
         e = bre.exception
         self.assertIn('A moz.build file called the error() function.', str(e))
         self.assertIn('    Some error.', str(e))
 
     def test_error_error_func_ok(self):
         reader = self.reader('reader-error-error-func', error_is_fatal=False)
 
-        contexts = list(reader.read_topsrcdir())
+        list(reader.read_topsrcdir())
 
     def test_error_empty_list(self):
         reader = self.reader('reader-error-empty-list')
 
         with self.assertRaises(BuildReaderError) as bre:
             list(reader.read_topsrcdir())
 
         e = bre.exception
--- a/python/mozbuild/mozbuild/test/frontend/test_sandbox.py
+++ b/python/mozbuild/mozbuild/test/frontend/test_sandbox.py
@@ -1,16 +1,14 @@
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 from __future__ import unicode_literals
 
-import os
-import shutil
 import unittest
 
 from mozunit import main
 
 from mozbuild.frontend.reader import (
     MozbuildSandbox,
     SandboxCalledError,
 )
@@ -25,17 +23,16 @@ from mozbuild.frontend.context import (
     Context,
     FUNCTIONS,
     SourcePath,
     SPECIAL_VARIABLES,
     VARIABLES,
 )
 
 from mozbuild.test.common import MockConfig
-from types import StringTypes
 
 import mozpack.path as mozpath
 
 test_data_path = mozpath.abspath(mozpath.dirname(__file__))
 test_data_path = mozpath.join(test_data_path, 'data')
 
 
 class TestSandbox(unittest.TestCase):
--- a/python/mozbuild/mozbuild/test/test_android_version_code.py
+++ b/python/mozbuild/mozbuild/test/test_android_version_code.py
@@ -44,30 +44,32 @@ class TestAndroidVersionCode(unittest.Te
         self.assertEqual(android_version_code_v1(
             buildid, cpu_arch='armeabi', min_sdk=9, max_sdk=None), arm_api9)
         with self.assertRaises(ValueError) as cm:
             underflow = '201507310000'  # Latest possible (valid) underflowing date.
             android_version_code_v1(underflow, cpu_arch='armeabi', min_sdk=9, max_sdk=None)
         self.assertTrue('underflow' in cm.exception.message)
 
     def test_android_version_code_v1_running_low(self):
-        '''Verify there is an informative message if one asks for v1 codes that are close to overflow.'''
+        '''Verify there is an informative message if one asks for v1
+        codes that are close to overflow.'''
         with self.assertRaises(ValueError) as cm:
             overflow = '20290801000000'
             android_version_code_v1(overflow, cpu_arch='armeabi', min_sdk=9, max_sdk=None)
         self.assertTrue('Running out of low order bits' in cm.exception.message)
 
     def test_android_version_code_v1_overflow(self):
         '''Verify that it is an error to ask for v1 codes that actually does overflow.'''
         with self.assertRaises(ValueError) as cm:
             overflow = '20310801000000'
             android_version_code_v1(overflow, cpu_arch='armeabi', min_sdk=9, max_sdk=None)
         self.assertTrue('overflow' in cm.exception.message)
 
     def test_android_version_code_v0_relative_v1(self):
         '''Verify that the first v1 code is greater than the equivalent v0 code.'''
         buildid = '20150801000000'
-        self.assertGreater(android_version_code_v1(buildid, cpu_arch='armeabi', min_sdk=9, max_sdk=None),
-                           android_version_code_v0(buildid, cpu_arch='armeabi', min_sdk=9, max_sdk=None))
+        self.assertGreater(
+            android_version_code_v1(buildid, cpu_arch='armeabi', min_sdk=9, max_sdk=None),
+            android_version_code_v0(buildid, cpu_arch='armeabi', min_sdk=9, max_sdk=None))
 
 
 if __name__ == '__main__':
     main()
--- a/python/mozbuild/mozbuild/test/test_base.py
+++ b/python/mozbuild/mozbuild/test/test_base.py
@@ -18,17 +18,16 @@ from mozfile.mozfile import NamedTempora
 from mozunit import main
 
 from mach.logging import LoggingManager
 
 from mozbuild.base import (
     BadEnvironmentException,
     MachCommandBase,
     MozbuildObject,
-    ObjdirMismatchException,
     PathArgument,
 )
 
 from mozbuild.backend.configenvironment import ConfigEnvironment
 from buildconfig import topsrcdir, topobjdir
 import mozpack.path as mozpath
 
 from mozbuild.test.common import prepare_tmp_topsrcdir
--- a/python/mozbuild/mozbuild/test/test_containers.py
+++ b/python/mozbuild/mozbuild/test/test_containers.py
@@ -25,17 +25,17 @@ class TestReadOnlyNamespace(unittest.Tes
 
         self.assertEqual(test.foo, 1)
         self.assertEqual(test.bar, 2)
         self.assertEqual(
             sorted(i for i in dir(test) if not i.startswith('__')),
             ['bar', 'foo'])
 
         with self.assertRaises(AttributeError):
-            value = test.missing
+            test.missing
 
         with self.assertRaises(Exception):
             test.foo = 2
 
         with self.assertRaises(Exception):
             del test.foo
 
         self.assertEqual(test, test)
@@ -51,17 +51,17 @@ class TestReadOnlyDict(unittest.TestCase
         original = {'foo': 1, 'bar': 2}
 
         test = ReadOnlyDict(original)
 
         self.assertEqual(original, test)
         self.assertEqual(test['foo'], 1)
 
         with self.assertRaises(KeyError):
-            value = test['missing']
+            test['missing']
 
         with self.assertRaises(Exception):
             test['baz'] = True
 
     def test_update(self):
         original = {'foo': 1, 'bar': 2}
 
         test = ReadOnlyDict(original)
--- a/python/mozbuild/mozbuild/test/test_expression.py
+++ b/python/mozbuild/mozbuild/test/test_expression.py
@@ -1,12 +1,10 @@
 import unittest
 
-import sys
-import os.path
 import mozunit
 
 from mozbuild.preprocessor import Expression, Context
 
 
 class TestContext(unittest.TestCase):
     """
     Unit tests for the Context class
--- a/python/mozbuild/mozbuild/test/test_jarmaker.py
+++ b/python/mozbuild/mozbuild/test/test_jarmaker.py
@@ -3,18 +3,16 @@
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 from __future__ import print_function
 import unittest
 
 import os
 import sys
 import os.path
-import time
-import inspect
 from filecmp import dircmp
 from tempfile import mkdtemp
 from shutil import rmtree, copy2
 from StringIO import StringIO
 from zipfile import ZipFile
 import mozunit
 
 from mozbuild.jar import JarMaker
--- a/python/mozbuild/mozbuild/test/test_licenses.py
+++ b/python/mozbuild/mozbuild/test/test_licenses.py
@@ -1,18 +1,12 @@
 import unittest
 
-from StringIO import StringIO
-import os
-import sys
-import os.path
 import mozunit
 
-from mozbuild.preprocessor import Preprocessor
-
 from mozbuild.vendor_rust import VendorRust
 
 
 class TestLicenses(unittest.TestCase):
     """
     Unit tests for the Rust Vendoring stuff
     """
 
--- a/python/mozbuild/mozbuild/test/test_line_endings.py
+++ b/python/mozbuild/mozbuild/test/test_line_endings.py
@@ -1,13 +1,12 @@
 import unittest
 
 from StringIO import StringIO
 import os
-import sys
 import os.path
 import mozunit
 
 from mozbuild.preprocessor import Preprocessor
 
 
 class TestLineEndings(unittest.TestCase):
     """
--- a/python/mozbuild/mozbuild/test/test_mozconfig.py
+++ b/python/mozbuild/mozbuild/test/test_mozconfig.py
@@ -134,17 +134,16 @@ class TestMozconfigLoader(unittest.TestC
 
     def test_find_relative_mozconfig(self):
         """Ensure a relative MOZCONFIG can be found in the srcdir."""
         relative_mozconfig = '.mconfig'
         os.environ[b'MOZCONFIG'] = relative_mozconfig
 
         srcdir = self.get_temp_dir()
         curdir = self.get_temp_dir()
-        dirs = [srcdir, curdir]
         loader = MozconfigLoader(srcdir)
 
         path = os.path.join(srcdir, relative_mozconfig)
         with open(path, 'w'):
             pass
 
         orig_dir = os.getcwd()
         try:
--- a/python/mozbuild/mozbuild/test/test_util.py
+++ b/python/mozbuild/mozbuild/test/test_util.py
@@ -272,34 +272,34 @@ class TestHierarchicalStringList(unittes
         with self.assertRaises(ValueError) as ve:
             self.EXPORTS += [True]
 
         self.assertEqual(str(ve.exception),
                          "Expected a list of strings, not an element of "
                          "<type 'bool'>")
 
     def test_del_exports(self):
-        with self.assertRaises(MozbuildDeletionError) as mde:
+        with self.assertRaises(MozbuildDeletionError):
             self.EXPORTS.foo += ['bar.h']
             del self.EXPORTS.foo
 
     def test_unsorted(self):
-        with self.assertRaises(UnsortedError) as ee:
+        with self.assertRaises(UnsortedError):
             self.EXPORTS += ['foo.h', 'bar.h']
 
-        with self.assertRaises(UnsortedError) as ee:
+        with self.assertRaises(UnsortedError):
             self.EXPORTS.foo = ['foo.h', 'bar.h']
 
-        with self.assertRaises(UnsortedError) as ee:
+        with self.assertRaises(UnsortedError):
             self.EXPORTS.foo += ['foo.h', 'bar.h']
 
     def test_reassign(self):
         self.EXPORTS.foo = ['foo.h']
 
-        with self.assertRaises(KeyError) as ee:
+        with self.assertRaises(KeyError):
             self.EXPORTS.foo = ['bar.h']
 
     def test_walk(self):
         l = HierarchicalStringList()
         l += ['root1', 'root2', 'root3']
         l.child1 += ['child11', 'child12', 'child13']
         l.child1.grandchild1 += ['grandchild111', 'grandchild112']
         l.child1.grandchild2 += ['grandchild121', 'grandchild122']
@@ -498,17 +498,17 @@ class TestStrictOrderingOnAppendListWith
 
         l = cls()
         l += ['a', 'b']
 
         with self.assertRaises(Exception):
             l['a'] = 'foo'
 
         with self.assertRaises(Exception):
-            c = l['c']
+            l['c']
 
         self.assertEqual(l['a'].foo, False)
         l['a'].foo = True
         self.assertEqual(l['a'].foo, True)
 
         with self.assertRaises(TypeError):
             l['a'].bar = 'bar'
 
--- a/python/mozbuild/mozbuild/testing.py
+++ b/python/mozbuild/mozbuild/testing.py
@@ -125,18 +125,19 @@ class SupportFilesConverter(object):
                 # We track uniqueness locally (per test) where duplicates are forbidden,
                 # and globally, where they are permitted. If a support file appears multiple
                 # times for a single test, there are unnecessary entries in the manifest. But
                 # many entries will be shared across tests that share defaults.
                 # We need to memoize on the basis of both the path and the output
                 # directory for the benefit of tests specifying 'install-to-subdir'.
                 key = field, pattern, out_dir
                 if key in info.seen:
-                    raise ValueError("%s appears multiple times in a test manifest under a %s field,"
-                                     " please omit the duplicate entry." % (pattern, field))
+                    raise ValueError(
+                        "%s appears multiple times in a test manifest under a %s field,"
+                        " please omit the duplicate entry." % (pattern, field))
                 info.seen.add(key)
                 if key in seen:
                     continue
                 seen.add(key)
 
                 if field == 'generated-files':
                     info.external_installs.add(mozpath.normpath(mozpath.join(out_dir, pattern)))
                 # '!' indicates our syntax for inter-directory support file
--- a/python/mozbuild/mozbuild/util.py
+++ b/python/mozbuild/mozbuild/util.py
@@ -18,17 +18,16 @@ import itertools
 import os
 import re
 import stat
 import sys
 import time
 import types
 
 from collections import (
-    defaultdict,
     Iterable,
     OrderedDict,
 )
 from io import (
     StringIO,
     BytesIO,
 )
 
@@ -656,18 +655,20 @@ def StrictOrderingOnAppendListWithFlagsF
                             self.__class__.__name__)
 
         def _update_flags(self, other):
             if self._flags_type._flags != other._flags_type._flags:
                 raise ValueError('Expected a list of strings with flags like %s, not like %s' %
                                  (self._flags_type._flags, other._flags_type._flags))
             intersection = set(self._flags.keys()) & set(other._flags.keys())
             if intersection:
-                raise ValueError('Cannot update flags: both lists of strings with flags configure %s' %
-                                 intersection)
+                raise ValueError(
+                    'Cannot update flags: both lists of strings with flags configure %s' %
+                    intersection
+                    )
             self._flags.update(other._flags)
 
         def extend(self, l):
             result = super(StrictOrderingOnAppendList, self).extend(l)
             if isinstance(l, StrictOrderingOnAppendListWithFlags):
                 self._update_flags(l)
             return result
 
--- a/python/mozbuild/mozbuild/vendor_aom.py
+++ b/python/mozbuild/mozbuild/vendor_aom.py
@@ -1,18 +1,16 @@
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, # You can obtain one at http://mozilla.org/MPL/2.0/.
 
 from __future__ import absolute_import, print_function, unicode_literals
 
-from distutils.version import LooseVersion
 import logging
 from mozbuild.base import (
-    BuildEnvironmentNotFoundException,
     MozbuildObject,
 )
 import mozfile
 import mozpack.path as mozpath
 import os
 import requests
 import re
 import sys
@@ -58,17 +56,17 @@ Please set a repository url with --repo 
         '''Query gitiles for a git commit and timestamp.'''
         url = mozpath.join(self.repo_url, '+', revision + '?format=JSON')
         self.log(logging.INFO, 'fetch', {'url': url},
                  'Fetching commit id from {url}')
         req = requests.get(url)
         req.raise_for_status()
         try:
             info = req.json()
-        except ValueError as e:
+        except ValueError:
             # As of 2017 May, googlesource sends 4 garbage characters
             # at the beginning of the json response. Work around this.
             # https://bugs.chromium.org/p/chromium/issues/detail?id=718550
             import json
             info = json.loads(req.text[4:])
         return (info['commit'], info['committer']['time'])
 
     def upstream_github_commit(self, revision):
--- a/python/mozbuild/mozbuild/vendor_dav1d.py
+++ b/python/mozbuild/mozbuild/vendor_dav1d.py
@@ -1,18 +1,16 @@
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, # You can obtain one at http://mozilla.org/MPL/2.0/.
 
 from __future__ import absolute_import, print_function, unicode_literals
 
-from distutils.version import LooseVersion
 import logging
 from mozbuild.base import (
-    BuildEnvironmentNotFoundException,
     MozbuildObject,
 )
 import mozfile
 import mozpack.path as mozpath
 import os
 import requests
 import re
 import sys
@@ -47,17 +45,17 @@ class VendorDav1d(MozbuildObject):
             self.log(logging.ERROR, 'upstream_url', {},
                      '''Unsupported git host %s; cannot fetch snapshots.
 
 Please set a repository url with --repo on either googlesource or github.''' % host)
             sys.exit(1)
 
     def upstream_gitlab_commit(self, revision):
         '''Query the github api for a git commit id and timestamp.'''
-        gitlab_api = 'https://code.videolan.org/api/v4/projects/videolan%2Fdav1d/repository/commits'
+        gitlab_api = 'https://code.videolan.org/api/v4/projects/videolan%2Fdav1d/repository/commits'  # noqa
         url = mozpath.join(gitlab_api, revision)
         self.log(logging.INFO, 'fetch', {'url': url},
                  'Fetching commit id from {url}')
         req = requests.get(url)
         req.raise_for_status()
         info = req.json()
         return (info['id'], info['committed_date'])
 
--- a/python/mozbuild/mozbuild/vendor_rust.py
+++ b/python/mozbuild/mozbuild/vendor_rust.py
@@ -6,17 +6,16 @@ from __future__ import absolute_import, 
 
 from distutils.version import LooseVersion
 import hashlib
 import logging
 from mozbuild.base import (
     BuildEnvironmentNotFoundException,
     MozbuildObject,
 )
-import mozfile
 import mozpack.path as mozpath
 import os
 import re
 import subprocess
 import sys
 
 
 class VendorRust(MozbuildObject):
@@ -119,18 +118,21 @@ Please commit or stash these changes bef
             [cargo, '--list']).splitlines())
         if not have_vendor:
             self.log(logging.INFO, 'installing', {},
                      'Installing cargo-vendor (this may take a few minutes)...')
             env = self.check_openssl()
             self.run_process(args=[cargo, 'install', 'cargo-vendor'],
                              append_env=env)
         elif not self.check_cargo_vendor_version(cargo):
-            self.log(logging.INFO, 'cargo_vendor', {
-                     }, 'cargo-vendor >= 0.1.23 required; force-reinstalling (this may take a few minutes)...')
+            self.log(
+                logging.INFO, 'cargo_vendor', {},
+                ('cargo-vendor >= 0.1.23 required; '
+                 'force-reinstalling (this may take a few minutes)...')
+                )
             env = self.check_openssl()
             self.run_process(args=[cargo, 'install', '--force', 'cargo-vendor'],
                              append_env=env)
         else:
             self.log(logging.DEBUG, 'cargo_vendor', {},
                      'sufficiently new cargo-vendor is already installed')
 
         return cargo
@@ -335,25 +337,27 @@ license file's hash.
         cargo = self._ensure_cargo()
         if not cargo:
             return
 
         relative_vendor_dir = 'third_party/rust'
         vendor_dir = mozpath.join(self.topsrcdir, relative_vendor_dir)
 
         # We use check_call instead of mozprocess to ensure errors are displayed.
-        # We do an |update -p| here to regenerate the Cargo.lock file with minimal changes. See bug 1324462
+        # We do an |update -p| here to regenerate the Cargo.lock file with minimal
+        # changes. See bug 1324462
         subprocess.check_call([cargo, 'update', '-p', 'gkrust'], cwd=self.topsrcdir)
 
         subprocess.check_call([cargo, 'vendor', '--quiet', '--sync',
                                'Cargo.lock'] + [vendor_dir], cwd=self.topsrcdir)
 
         if not self._check_licenses(vendor_dir):
-            self.log(logging.ERROR, 'license_check_failed', {},
-                     '''The changes from `mach vendor rust` will NOT be added to version control.''')
+            self.log(
+                logging.ERROR, 'license_check_failed', {},
+                '''The changes from `mach vendor rust` will NOT be added to version control.''')
             sys.exit(1)
 
         self.repository.add_remove_files(vendor_dir)
 
         # 100k is a reasonable upper bound on source file size.
         FILESIZE_LIMIT = 100 * 1024
         large_files = set()
         cumulative_added_size = 0
@@ -385,9 +389,11 @@ The changes from `mach vendor rust` will
         SIZE_WARN_THRESHOLD = 5 * 1024 * 1024
         if cumulative_added_size >= SIZE_WARN_THRESHOLD:
             self.log(logging.WARN, 'filesize_check', {},
                      '''Your changes add {size} bytes of added files.
 
 Please consider finding ways to reduce the size of the vendored packages.
 For instance, check the vendored packages for unusually large test or
 benchmark files that don't need to be published to crates.io and submit
-a pull request upstream to ignore those files when publishing.'''.format(size=cumulative_added_size))
+a pull request upstream to ignore those files when publishing.'''.format(
+                size=cumulative_added_size)
+            )
--- a/python/mozbuild/mozbuild/virtualenv.py
+++ b/python/mozbuild/mozbuild/virtualenv.py
@@ -325,17 +325,17 @@ class VirtualenvManager(object):
                         f.write("%s\n" % os.path.join(python_lib, path))
 
                 return True
 
             if package[0] == 'optional':
                 try:
                     handle_package(package[1:])
                     return True
-                except:
+                except Exception:
                     print('Error processing command. Ignoring',
                           'because optional. (%s)' % ':'.join(package),
                           file=self.log_handle)
                     return False
 
             if package[0] in ('windows', '!windows'):
                 for_win = not package[0].startswith('!')
                 is_win = sys.platform == 'win32'
@@ -654,17 +654,19 @@ def verify_python_version(log_handle):
         else:
             log_handle.write(UPGRADE_OTHER)
 
         sys.exit(1)
 
 
 if __name__ == '__main__':
     if len(sys.argv) < 5:
-        print('Usage: populate_virtualenv.py /path/to/topsrcdir /path/to/topobjdir /path/to/virtualenv /path/to/virtualenv_manifest')
+        print(
+            'Usage: populate_virtualenv.py /path/to/topsrcdir '
+            '/path/to/topobjdir /path/to/virtualenv /path/to/virtualenv_manifest')
         sys.exit(1)
 
     verify_python_version(sys.stdout)
 
     topsrcdir, topobjdir, virtualenv_path, manifest_path = sys.argv[1:5]
     populate = False
 
     # This should only be called internally.