python/mozbuild: Run 2to3.

This commit is contained in:
Vincent Povirk 2019-08-13 13:47:15 -05:00 committed by Jacek Caban
parent 8d4bad5455
commit 972ca45371
118 changed files with 533 additions and 532 deletions

View File

@ -2,7 +2,7 @@
# 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
from collections import OrderedDict
from itertools import groupby
@ -36,7 +36,7 @@ def dependency_map(lines):
deps = {}
for i, (indent, target) in enumerate(pairs):
if not deps.has_key(target):
if target not in deps:
deps[target] = []
for j in range(i+1, len(pairs)):
@ -68,7 +68,7 @@ def all_dependencies(*targets, **kwargs):
del all_targets[dependency]
all_targets[dependency] = True
return all_targets.keys()
return list(all_targets.keys())
def get_components(path):
"""Take a path and return all the components of the path."""
@ -114,7 +114,7 @@ def add_extra_dependencies(target_pairs, dependency_map):
make_dirs[make_dir] = True
all_components = []
for make_dir in make_dirs.iterkeys():
for make_dir in make_dirs.keys():
all_components.extend(get_components(make_dir))
for i in all_dependencies(*all_components, dependency_map=dependency_map):

View File

@ -1,7 +1,7 @@
# 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 unittest

View File

@ -7,7 +7,7 @@ if the entry does not already exist.
Usage: buildlist.py <filename> <entry> [<entry> ...]
'''
from __future__ import absolute_import, print_function
import sys
import os

View File

@ -2,7 +2,7 @@
# 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 ctypes
import os
@ -55,7 +55,7 @@ def InvokeClWithDependencyGeneration(cmdline):
break
if target is None:
print >>sys.stderr, "No target set"
print("No target set", file=sys.stderr)
return 1
# Assume the source file is the last argument

View File

@ -2,7 +2,7 @@
# 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 errno
@ -44,7 +44,7 @@ def explode(aar, destdir):
assets = mozpath.join(destdir, 'assets')
try:
os.rmdir(assets)
except OSError, e:
except OSError as e:
if e.errno in (errno.ENOTEMPTY, errno.ENOENT):
pass
else:

View File

@ -6,7 +6,7 @@
# the arguments that can be used to generate the output file, call the
# script's |main| method with appropriate arguments.
from __future__ import absolute_import, print_function
import argparse
import imp

View File

@ -26,7 +26,7 @@ write the result to suggestedsites.json on the locale-specific raw resource
directory e.g. raw/suggestedsites.json, raw-pt-rBR/suggestedsites.json.
'''
from __future__ import absolute_import, print_function
import argparse
import copy

View File

@ -2,12 +2,12 @@
# 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 buildconfig
import os
from StringIO import StringIO
from io import StringIO
from mozbuild.preprocessor import Preprocessor
from mozbuild.util import DefinesAction

View File

@ -2,7 +2,7 @@
# 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 sys

View File

@ -2,7 +2,7 @@
# 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 print_function
from mozbuild.base import MozbuildObject
from mozpack import dmg

View File

@ -8,7 +8,7 @@ Gecko library binaries. The AAR file is intended for use by local
developers using Gradle.
'''
from __future__ import absolute_import, print_function
import argparse
import hashlib

View File

@ -2,7 +2,7 @@
# 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 sys

View File

@ -2,7 +2,7 @@
# 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
@ -55,7 +55,7 @@ def process_define_file(output, input):
'CONFIGURE_DEFINE_FILE')
defines = '\n'.join(sorted(
'#define %s %s' % (name, val)
for name, val in config.defines.iteritems()
for name, val in config.defines.items()
if name not in config.non_global_defines))
l = l[:m.start('cmd') - 1] \
+ defines + l[m.end('name'):]

View File

@ -2,7 +2,7 @@
# 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

View File

@ -8,7 +8,7 @@
# It is defined inline because this was easiest to make test archive
# generation faster.
from __future__ import absolute_import, print_function, unicode_literals
import argparse
import itertools
@ -398,7 +398,7 @@ ARCHIVE_FILES = {
# "common" is our catch all archive and it ignores things from other archives.
# Verify nothing sneaks into ARCHIVE_FILES without a corresponding exclusion
# rule in the "common" archive.
for k, v in ARCHIVE_FILES.items():
for k, v in list(ARCHIVE_FILES.items()):
# Skip mozharness because it isn't staged.
if k in ('common', 'mozharness'):
continue

View File

@ -2,7 +2,7 @@
# 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 sys

View File

@ -8,7 +8,7 @@ corresponding .ini file.
Usage: xpccheck.py <directory> [<directory> ...]
'''
from __future__ import absolute_import
import sys
import os
@ -40,7 +40,7 @@ def verifyDirectory(initests, directory):
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("TEST-UNEXPECTED-FAIL | xpccheck | test %s is missing from test manifest %s!" % (name, os.path.join(directory, 'xpcshell.ini')), file=sys.stderr)
sys.exit(1)
def verifyIniFile(initests, directory):
@ -60,12 +60,12 @@ def verifyIniFile(initests, directory):
break
if not found:
print >>sys.stderr, "TEST-UNEXPECTED-FAIL | xpccheck | found %s in xpcshell.ini and not in directory '%s'" % (name, directory)
print("TEST-UNEXPECTED-FAIL | xpccheck | found %s in xpcshell.ini and not in directory '%s'" % (name, directory), file=sys.stderr)
sys.exit(1)
def main(argv):
if len(argv) < 2:
print >>sys.stderr, "Usage: xpccheck.py <topsrcdir> <directory> [<directory> ...]"
print("Usage: xpccheck.py <topsrcdir> <directory> [<directory> ...]", file=sys.stderr)
sys.exit(1)
topsrcdir = argv[0]

View File

@ -7,7 +7,7 @@
# input IDL file(s). It's purpose is to directly support the build
# system. The API will change to meet the needs of the build system.
from __future__ import absolute_import
import argparse
import os
@ -58,7 +58,7 @@ def process(input_dir, inc_paths, cache_dir, header_dir, xpt_dir, deps_dir, modu
# TODO use FileAvoidWrite once it supports binary mode.
xpt_path = os.path.join(xpt_dir, '%s.xpt' % module)
xpt_link(xpts.values()).write(xpt_path)
xpt_link(list(xpts.values())).write(xpt_path)
rule.add_targets([xpt_path])
if deps_dir:

View File

@ -5,7 +5,7 @@
# This script creates a zip file, but will also strip any binaries
# it finds before adding them to the zip.
from __future__ import absolute_import
from mozpack.files import FileFinder
from mozpack.copier import Jarrer

View File

@ -2,7 +2,7 @@
# 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 math

View File

@ -40,7 +40,7 @@ consumers will need to arrange this themselves.
'''
from __future__ import absolute_import, print_function, unicode_literals
import collections
import functools
@ -57,7 +57,7 @@ import stat
import subprocess
import tarfile
import tempfile
import urlparse
import urllib.parse
import zipfile
import pylru
@ -167,7 +167,7 @@ class ArtifactJob(object):
with JarWriter(file=processed_filename, optimize=False, compress_level=5) as writer:
reader = JarReader(filename)
for filename, entry in reader.entries.iteritems():
for filename, entry in reader.entries.items():
for pattern, (src_prefix, dest_prefix) in self.test_artifact_patterns:
if not mozpath.match(filename, pattern):
continue
@ -493,7 +493,7 @@ class CacheManager(object):
def print_cache(self):
with self:
for item in self._cache.items():
for item in list(self._cache.items()):
self.log(logging.INFO, 'artifact',
{'item': item},
'{item}')
@ -506,7 +506,7 @@ class CacheManager(object):
# We use the persisted LRU caches to our advantage. The first item is
# most recent.
with self:
item = next(self._cache.items(), None)
item = next(list(self._cache.items()), None)
if item is not None:
(name, args, sorted_kwargs), result = item
self.print_last_item(args, sorted_kwargs, result)
@ -560,10 +560,10 @@ class PushheadCache(CacheManager):
'changeset={changeset}&version=2&tipsonly=1')
req = requests.get(cset_url_tmpl.format(tree=tree, changeset=revision),
headers={'Accept': 'application/json'})
if req.status_code not in range(200, 300):
if req.status_code not in list(range(200, 300)):
raise ValueError
result = req.json()
[found_pushid] = result['pushes'].keys()
[found_pushid] = list(result['pushes'].keys())
return int(found_pushid)
@cachedmethod(operator.attrgetter('_cache'))
@ -576,7 +576,7 @@ class PushheadCache(CacheManager):
headers={'Accept': 'application/json'})
result = req.json()
return [
p['changesets'][-1] for p in result['pushes'].values()
p['changesets'][-1] for p in list(result['pushes'].values())
]
class TaskCache(CacheManager):
@ -799,7 +799,7 @@ class Artifacts(object):
continue
candidate_pushheads = []
for tree, pushid in found_pushids.iteritems():
for tree, pushid in found_pushids.items():
end = pushid
start = pushid - NUM_PUSHHEADS_TO_QUERY_PER_PARENT
@ -1009,7 +1009,7 @@ class Artifacts(object):
"""
if source and os.path.isfile(source):
return self.install_from_file(source, distdir)
elif source and urlparse.urlparse(source).scheme:
elif source and urllib.parse.urlparse(source).scheme:
return self.install_from_url(source, distdir)
else:
if source is None and 'MOZ_ARTIFACT_REVISION' in os.environ:

View File

@ -2,7 +2,7 @@
# 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 itertools
import os

View File

@ -2,7 +2,7 @@
# 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
from abc import (
ABCMeta,
@ -30,7 +30,7 @@ from .configenvironment import ConfigEnvironment
from mozbuild.base import ExecutionSummary
class BuildBackend(LoggingMixin):
class BuildBackend(LoggingMixin, metaclass=ABCMeta):
"""Abstract base class for build backends.
A build backend is merely a consumer of the build configuration (the output
@ -38,8 +38,6 @@ class BuildBackend(LoggingMixin):
is the discretion of the specific implementation.
"""
__metaclass__ = ABCMeta
def __init__(self, environment):
assert isinstance(environment, ConfigEnvironment)

View File

@ -2,7 +2,7 @@
# 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 itertools
import json

View File

@ -2,7 +2,7 @@
# 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 os
import sys
@ -17,7 +17,7 @@ from mozbuild.shellutil import quote as shell_quote
if sys.version_info.major == 2:
text_type = unicode
text_type = str
else:
text_type = str
@ -168,7 +168,7 @@ class ConfigEnvironment(object):
except UnicodeDecodeError:
return v.decode('utf-8', 'replace')
for k, v in self.substs.items():
for k, v in list(self.substs.items()):
if not isinstance(v, StringTypes):
if isinstance(v, Iterable):
type(v)(decode(i) for i in v)

View File

@ -2,7 +2,7 @@
# 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 random
@ -218,12 +218,12 @@ class CppEclipseBackend(CommonBackend):
cproject_header = cproject_header.replace('@MACH_COMMAND@', os.path.join(self.environment.topsrcdir, 'mach'))
fh.write(cproject_header)
for path, defines in self._paths_to_defines.items():
for path, defines in list(self._paths_to_defines.items()):
folderinfo = CPROJECT_TEMPLATE_FOLDER_INFO_HEADER
folderinfo = folderinfo.replace('@FOLDER_ID@', str(random.randint(1000000, 99999999999)))
folderinfo = folderinfo.replace('@FOLDER_NAME@', 'tree/' + path)
fh.write(folderinfo)
for k, v in defines.items():
for k, v in list(defines.items()):
define = ET.Element('listOptionValue')
define.set('builtIn', 'false')
define.set('value', str(k) + "=" + str(v))

View File

@ -2,7 +2,7 @@
# 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, print_function
from mozbuild.backend.base import PartialBackend
from mozbuild.backend.common import CommonBackend
@ -130,12 +130,12 @@ class FasterMakeBackend(CommonBackend, PartialBackend):
if value is not None:
mk.add_statement('%s = %s' % (var, value))
install_manifests_bases = self._install_manifests.keys()
install_manifests_bases = list(self._install_manifests.keys())
# Add information for chrome manifest generation
manifest_targets = []
for target, entries in self._manifest_entries.iteritems():
for target, entries in self._manifest_entries.items():
manifest_targets.append(target)
install_target = mozpath.basedir(target, install_manifests_bases)
self._install_manifests[install_target].add_content(
@ -144,16 +144,16 @@ class FasterMakeBackend(CommonBackend, PartialBackend):
# Add information for install manifests.
mk.add_statement('INSTALL_MANIFESTS = %s'
% ' '.join(self._install_manifests.keys()))
% ' '.join(list(self._install_manifests.keys())))
# Add dependencies we infered:
for target, deps in self._dependencies.iteritems():
for target, deps in self._dependencies.items():
mk.create_rule([target]).add_dependencies(
'$(TOPOBJDIR)/%s' % d for d in deps)
mk.add_statement('include $(TOPSRCDIR)/config/faster/rules.mk')
for base, install_manifest in self._install_manifests.iteritems():
for base, install_manifest in self._install_manifests.items():
with self._write_file(
mozpath.join(self.environment.topobjdir, 'faster',
'install_%s' % base.replace('/', '_'))) as fh:

View File

@ -2,7 +2,7 @@
# 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

View File

@ -2,7 +2,7 @@
# 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 logging
import os
@ -13,7 +13,7 @@ from collections import (
defaultdict,
namedtuple,
)
from StringIO import StringIO
from io import StringIO
from itertools import chain
from reftest import ReftestManifest
@ -76,6 +76,7 @@ from ..util import (
)
from ..makeutil import Makefile
from mozbuild.shellutil import quote as shell_quote
from functools import reduce
MOZBUILD_VARIABLES = [
b'ANDROID_APK_NAME',
@ -218,7 +219,7 @@ class BackendMakeFile(object):
self.fh.write(buf)
def write_once(self, buf):
if isinstance(buf, unicode):
if isinstance(buf, str):
buf = buf.encode('utf-8')
if b'\n' + buf not in self.fh.getvalue():
self.write(buf)
@ -289,8 +290,8 @@ class RecursiveMakeTraversal(object):
Helper function to call a filter from compute_dependencies and
traverse.
"""
return filter(current, self._traversal.get(current,
self.SubDirectories()))
return list(filter(current, self._traversal.get(current,
self.SubDirectories())))
def compute_dependencies(self, filter=None):
"""
@ -624,7 +625,7 @@ class RecursiveMakeBackend(CommonBackend):
convenience variables, and the other dependency definitions for a
hopefully proper directory traversal.
"""
for tier, no_skip in self._no_skip.items():
for tier, no_skip in list(self._no_skip.items()):
self.log(logging.DEBUG, 'fill_root_mk', {
'number': len(no_skip), 'tier': tier
}, 'Using {number} directories during {tier}')
@ -670,7 +671,7 @@ class RecursiveMakeBackend(CommonBackend):
for tier, filter in filters:
main, all_deps = \
self._traversal.compute_dependencies(filter)
for dir, deps in all_deps.items():
for dir, deps in list(all_deps.items()):
if deps is not None or (dir in self._idl_dirs \
and tier == 'export'):
rule = root_deps_mk.create_rule(['%s/%s' % (dir, tier)])
@ -683,7 +684,7 @@ class RecursiveMakeBackend(CommonBackend):
rule.add_dependencies('%s/%s' % (d, tier) for d in main)
all_compile_deps = reduce(lambda x,y: x|y,
self._compile_graph.values()) if self._compile_graph else set()
list(self._compile_graph.values())) if self._compile_graph else set()
compile_roots = set(self._compile_graph.keys()) - all_compile_deps
rule = root_deps_mk.create_rule(['recurse_compile'])
@ -825,7 +826,7 @@ class RecursiveMakeBackend(CommonBackend):
self._fill_root_mk()
# Make the master test manifest files.
for flavor, t in self._test_manifests.items():
for flavor, t in list(self._test_manifests.items()):
install_prefix, manifests = t
manifest_stem = mozpath.join(install_prefix, '%s.ini' % flavor)
self._write_master_test_manifest(mozpath.join(
@ -910,16 +911,16 @@ class RecursiveMakeBackend(CommonBackend):
backend_file.write_once('%s += %s\n' % (which, defines))
def _process_test_harness_files(self, obj, backend_file):
for path, files in obj.srcdir_files.iteritems():
for path, files in obj.srcdir_files.items():
for source in files:
dest = '%s/%s' % (path, mozpath.basename(source))
self._install_manifests['_tests'].add_symlink(source, dest)
for path, patterns in obj.srcdir_pattern_files.iteritems():
for path, patterns in obj.srcdir_pattern_files.items():
for p in patterns:
self._install_manifests['_tests'].add_pattern_symlink(p[0], p[1], path)
for path, files in obj.objdir_files.iteritems():
for path, files in obj.objdir_files.items():
self._no_skip['misc'].add(backend_file.relobjdir)
prefix = 'TEST_HARNESS_%s' % path.replace('/', '_')
backend_file.write("""
@ -954,7 +955,7 @@ INSTALL_TARGETS += %(prefix)s
for p in ('Makefile', 'backend.mk', '.deps/.mkdir.done'):
build_files.add_optional_exists(p)
for idl in manager.idls.values():
for idl in list(manager.idls.values()):
self._install_manifests['dist_idl'].add_symlink(idl['source'],
idl['basename'])
self._install_manifests['dist_include'].add_optional_exists('%s.h'
@ -1001,7 +1002,7 @@ INSTALL_TARGETS += %(prefix)s
interfaces_manifests = []
dist_dir = mozpath.join(self.environment.topobjdir, 'dist')
for manifest, entries in manager.interface_manifests.items():
for manifest, entries in list(manager.interface_manifests.items()):
interfaces_manifests.append(mozpath.join('$(DEPTH)', manifest))
for xpt in sorted(entries):
registered_xpt_files.add(mozpath.join(
@ -1061,7 +1062,7 @@ INSTALL_TARGETS += %(prefix)s
# Don't allow files to be defined multiple times unless it is allowed.
# We currently allow duplicates for non-test files or test files if
# the manifest is listed as a duplicate.
for source, (dest, is_test) in obj.installs.items():
for source, (dest, is_test) in list(obj.installs.items()):
try:
self._install_manifests['_tests'].add_symlink(source, dest)
except ValueError:
@ -1324,7 +1325,7 @@ INSTALL_TARGETS += %(prefix)s
man_dir = mozpath.join(self.environment.topobjdir, '_build_manifests',
dest)
for k, manifest in manifests.items():
for k, manifest in list(manifests.items()):
with self._write_file(mozpath.join(man_dir, k)) as fh:
manifest.write(fileobj=fh)

View File

@ -5,7 +5,7 @@
# This file contains a build backend for generating Visual Studio project
# files.
from __future__ import absolute_import, unicode_literals
import errno
import os
@ -206,7 +206,7 @@ class VisualStudioBackend(CommonBackend):
includes = [os.path.normpath(i) for i in includes]
defines = []
for k, v in self._paths_to_defines.get(path, {}).items():
for k, v in list(self._paths_to_defines.get(path, {}).items()):
if v is True:
defines.append(k)
else:

View File

@ -2,7 +2,7 @@
# 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 json
import logging
@ -521,7 +521,7 @@ class MozbuildObject(ProcessExecutionMixin):
for flag in flags:
if flag == '-j':
try:
flag = flags.next()
flag = next(flags)
except StopIteration:
break
try:

View File

@ -5,7 +5,7 @@
from collections import defaultdict
import json
import os
import urlparse
import urllib.parse
from mach.config import ConfigSettings
from mach.logging import LoggingManager
@ -42,7 +42,7 @@ class ChromeManifestHandler(object):
if isinstance(entry, (ManifestChrome, ManifestResource)):
if isinstance(entry, ManifestResource):
dest = entry.target
url = urlparse.urlparse(dest)
url = urllib.parse.urlparse(dest)
if not url.scheme:
dest = mozpath.normpath(mozpath.join(entry.base, dest))
if url.scheme == 'file':
@ -99,7 +99,7 @@ class ChromeMapBackend(CommonBackend):
chrome_mapping = self.manifest_handler.chrome_mapping
overrides = self.manifest_handler.overrides
json.dump([
{k: list(v) for k, v in chrome_mapping.iteritems()},
{k: list(v) for k, v in chrome_mapping.items()},
overrides,
self._install_mapping,
], fh, sort_keys=True, indent=2)

View File

@ -2,7 +2,7 @@
# 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 sys
@ -12,7 +12,7 @@ from mozpack.copier import Jarrer
def package_gcno_tree(root, output_file):
# XXX JarWriter doesn't support unicode strings, see bug 1056859
if isinstance(root, unicode):
if isinstance(root, str):
root = root.encode('utf-8')
finder = FileFinder(root)

View File

@ -4,7 +4,7 @@
# This modules provides functionality for dealing with code completion.
from __future__ import absolute_import
import os
@ -54,5 +54,5 @@ class Introspection(MachCommandBase):
if name not in build_vars:
return
print(' '.join(shell_quote(arg)
for arg in util.sanitize_cflags(shell_split(build_vars[name]))))
print((' '.join(shell_quote(arg)
for arg in util.sanitize_cflags(shell_split(build_vars[name])))))

View File

@ -128,7 +128,7 @@ class CompileDBBackend(CommonBackend):
db = []
for (directory, filename), cmd in self._db.iteritems():
for (directory, filename), cmd in self._db.items():
env = self._envs[directory]
cmd = list(cmd)
cmd.append(filename)
@ -161,7 +161,7 @@ class CompileDBBackend(CommonBackend):
a = expand_variables(a, variables).split()
if not a:
continue
if isinstance(a, types.StringTypes):
if isinstance(a, (str,)):
c.append(a)
else:
c.extend(a)
@ -226,7 +226,7 @@ class CompileDBBackend(CommonBackend):
value = cenv.substs.get(name)
if not value:
return
if isinstance(value, types.StringTypes):
if isinstance(value, (str,)):
value = value.split()
db.extend(value)

View File

@ -4,7 +4,7 @@
# This modules provides functionality for dealing with compiler warnings.
from __future__ import absolute_import, unicode_literals
import errno
import json
@ -123,18 +123,18 @@ class WarningsDatabase(object):
def __len__(self):
i = 0
for value in self._files.values():
for value in list(self._files.values()):
i += len(value['warnings'])
return i
def __iter__(self):
for value in self._files.values():
for value in list(self._files.values()):
for warning in value['warnings']:
yield warning
def __contains__(self, item):
for value in self._files.values():
for value in list(self._files.values()):
for warning in value['warnings']:
if warning == item:
return True
@ -144,7 +144,7 @@ class WarningsDatabase(object):
@property
def warnings(self):
"""All the CompilerWarning instances in this database."""
for value in self._files.values():
for value in list(self._files.values()):
for w in value['warnings']:
yield w
@ -152,7 +152,7 @@ class WarningsDatabase(object):
"""Returns a mapping of warning types to their counts."""
types = {}
for value in self._files.values():
for value in list(self._files.values()):
for warning in value['warnings']:
if dirpath and not mozpath.normsep(warning['filename']).startswith(dirpath):
continue
@ -210,7 +210,7 @@ class WarningsDatabase(object):
"""
# Need to calculate up front since we are mutating original object.
filenames = self._files.keys()
filenames = list(self._files.keys())
for filename in filenames:
if not os.path.exists(filename):
del self._files[filename]
@ -229,10 +229,10 @@ class WarningsDatabase(object):
obj = {'files': {}}
# All this hackery because JSON can't handle sets.
for k, v in self._files.iteritems():
for k, v in self._files.items():
obj['files'][k] = {}
for k2, v2 in v.iteritems():
for k2, v2 in v.items():
normalized = v2
if k2 == 'warnings':
@ -249,8 +249,8 @@ class WarningsDatabase(object):
self._files = obj['files']
# Normalize data types.
for filename, value in self._files.iteritems():
for k, v in value.iteritems():
for filename, value in self._files.items():
for k, v in value.items():
if k != 'warnings':
continue

View File

@ -6,7 +6,7 @@
# 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

View File

@ -6,7 +6,7 @@
# to a given compilation unit. This is used as a helper to find a bug in some
# versions of GNU ld.
from __future__ import absolute_import
import subprocess
import sys
@ -59,4 +59,4 @@ def main(bin, compilation_unit):
if __name__ == '__main__':
print main(*sys.argv[1:])
print(main(*sys.argv[1:]))

View File

@ -13,7 +13,7 @@
# will be used from shell, we just print the two assignments and evaluate
# them from shell.
from __future__ import absolute_import
import os
import subprocess
@ -76,6 +76,6 @@ def find_version(e):
if __name__ == '__main__':
cxx_env = os.environ['CXX']
print 'MOZ_LIBSTDCXX_TARGET_VERSION=%s' % find_version(cxx_env)
print('MOZ_LIBSTDCXX_TARGET_VERSION=%s' % find_version(cxx_env))
host_cxx_env = os.environ.get('HOST_CXX', cxx_env)
print 'MOZ_LIBSTDCXX_HOST_VERSION=%s' % find_version(host_cxx_env)
print('MOZ_LIBSTDCXX_HOST_VERSION=%s' % find_version(host_cxx_env))

View File

@ -2,7 +2,7 @@
# 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 getpass
import json
@ -104,7 +104,7 @@ class TierStatus(object):
"""
o = []
for tier, state in self.tiers.items():
for tier, state in list(self.tiers.items()):
t_entry = dict(
name=tier,
start=state['begin_time'],
@ -634,8 +634,8 @@ class CCacheStats(object):
return '\n'.join(lines)
def __nonzero__(self):
relative_values = [v for k, v in self._values.items()
def __bool__(self):
relative_values = [v for k, v in list(self._values.items())
if k not in self.ABSOLUTE_KEYS]
return (all(v >= 0 for v in relative_values) and
any(v > 0 for v in relative_values))
@ -657,8 +657,8 @@ class BuildDriver(MozbuildObject):
"""Install test files (through manifest)."""
if self.is_clobber_needed():
print(INSTALL_TESTS_CLOBBER.format(
clobber_file=os.path.join(self.topobjdir, 'CLOBBER')))
print((INSTALL_TESTS_CLOBBER.format(
clobber_file=os.path.join(self.topobjdir, 'CLOBBER'))))
sys.exit(1)
env = {}

View File

@ -2,7 +2,7 @@
# 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
r'''This module contains code for managing clobbering of the tree.'''

View File

@ -2,7 +2,7 @@
# 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 os
import subprocess
@ -91,7 +91,7 @@ class Doctor(object):
valid = False
while not valid and limit > 0:
try:
choice = strtobool(raw_input(prompt + '[Y/N]\n'))
choice = strtobool(input(prompt + '[Y/N]\n'))
valid = True
except ValueError:
print("ERROR! Please enter a valid option!")
@ -111,11 +111,11 @@ class Doctor(object):
if status == 'SKIPPED':
continue
self.results.append(result)
print('%s...\t%s\n' % (
print(('%s...\t%s\n' % (
result.get('desc', ''),
status
)
).expandtabs(40)
).expandtabs(40))
@property
def platform(self):
@ -220,7 +220,7 @@ class Doctor(object):
fsutil_output = subprocess.check_output(command)
status = 'GOOD, FIXED'
desc = '8dot3 disabled systemwide'
except subprocess.CalledProcessError, e:
except subprocess.CalledProcessError as e:
desc = '8dot3 enabled systemwide'
if e.output.find('denied') != -1:
status = 'BAD, FIX DENIED'
@ -297,7 +297,7 @@ class Doctor(object):
fsutil_output = subprocess.check_output(command)
status = 'GOOD, FIXED'
desc = 'lastaccess disabled systemwide'
except subprocess.CalledProcessError, e:
except subprocess.CalledProcessError as e:
desc = 'lastaccess enabled systemwide'
if e.output.find('denied') != -1:
status = 'BAD, FIX DENIED'

View File

@ -5,7 +5,7 @@
# This file contains utility functions for reading .properties files, like
# region.properties.
from __future__ import absolute_import, unicode_literals
import codecs
import re
@ -14,7 +14,7 @@ import sys
if sys.version_info[0] == 3:
str_type = str
else:
str_type = basestring
str_type = str
class DotProperties:
r'''A thin representation of a key=value .properties file.'''
@ -52,7 +52,7 @@ class DotProperties:
if not prefix.endswith('.'):
prefix = prefix + '.'
indexes = []
for k, v in self._properties.iteritems():
for k, v in self._properties.items():
if not k.startswith(prefix):
continue
key = k[len(prefix):]
@ -73,7 +73,7 @@ class DotProperties:
if not prefix.endswith('.'):
prefix = prefix + '.'
D = dict((k[len(prefix):], v) for k, v in self._properties.iteritems()
D = dict((k[len(prefix):], v) for k, v in self._properties.items()
if k.startswith(prefix) and '.' not in k[len(prefix):])
for required_key in required_keys:

View File

@ -14,7 +14,7 @@ If you are looking for the absolute authority on what moz.build files can
contain, you've come to the right place.
"""
from __future__ import absolute_import, unicode_literals
import os
@ -225,15 +225,15 @@ class Context(KeyedDefaultDict):
This function is transactional: if setitem fails for one of the values,
the context is not updated at all."""
if isinstance(iterable, dict):
iterable = iterable.items()
iterable = list(iterable.items())
update = {}
for key, value in itertools.chain(iterable, kwargs.items()):
for key, value in itertools.chain(iterable, list(kwargs.items())):
stored_type = self._validate(key, value)
# Don't create an instance of stored_type if coercion is needed,
# until all values are validated.
update[key] = (value, stored_type)
for key, (value, stored_type) in update.items():
for key, (value, stored_type) in list(update.items()):
if not isinstance(value, stored_type):
update[key] = stored_type(value)
else:
@ -288,7 +288,7 @@ class InitializedDefines(ContextDerivedValue, OrderedDict):
self.update(value)
class FinalTargetValue(ContextDerivedValue, unicode):
class FinalTargetValue(ContextDerivedValue, str):
def __new__(cls, context, value=""):
if not value:
value = 'dist/'
@ -298,7 +298,7 @@ class FinalTargetValue(ContextDerivedValue, unicode):
value += 'bin'
if context['DIST_SUBDIR']:
value += '/' + context['DIST_SUBDIR']
return unicode.__new__(cls, value)
return str.__new__(cls, value)
def Enum(*values):
@ -346,7 +346,7 @@ class PathMeta(type):
cls = SourcePath
return super(PathMeta, cls).__call__(context, value)
class Path(ContextDerivedValue, unicode):
class Path(ContextDerivedValue, str, metaclass=PathMeta):
"""Stores and resolves a source path relative to a given context
This class is used as a backing type for some of the sandbox variables.
@ -357,7 +357,6 @@ class Path(ContextDerivedValue, unicode):
- '!objdir/relative/paths'
- '%/filesystem/absolute/paths'
"""
__metaclass__ = PathMeta
def __new__(cls, context, value=None):
return super(Path, cls).__new__(cls, value)
@ -377,7 +376,7 @@ class Path(ContextDerivedValue, unicode):
def __cmp__(self, other):
if isinstance(other, Path) and self.srcdir != other.srcdir:
return cmp(self.full_path, other.full_path)
return cmp(unicode(self), other)
return cmp(str(self), other)
# __cmp__ is not enough because unicode has __eq__, __ne__, etc. defined
# and __cmp__ is only used for those when they don't exist.
@ -535,7 +534,7 @@ def ContextDerivedTypedRecord(*fields):
__slots__ = tuple([name for name, _ in fields])
def __init__(self, context):
for fname, ftype in self._fields.items():
for fname, ftype in list(self._fields.items()):
if issubclass(ftype, ContextDerivedValue):
setattr(self, fname, self._fields[fname](context))
else:
@ -574,16 +573,16 @@ def ContextDerivedTypedHierarchicalStringList(type):
BugzillaComponent = TypedNamedTuple('BugzillaComponent',
[('product', unicode), ('component', unicode)])
[('product', str), ('component', str)])
WebPlatformTestManifest = TypedNamedTuple("WebPlatformTestManifest",
[("manifest_path", unicode),
("test_root", unicode)])
[("manifest_path", str),
("test_root", str)])
OrderedSourceList = ContextDerivedTypedList(SourcePath, StrictOrderingOnAppendList)
OrderedTestFlavorList = TypedList(Enum(*all_test_flavors()),
StrictOrderingOnAppendList)
OrderedStringList = TypedList(unicode, StrictOrderingOnAppendList)
OrderedStringList = TypedList(str, StrictOrderingOnAppendList)
DependentTestsEntry = ContextDerivedTypedRecord(('files', OrderedSourceList),
('tags', OrderedStringList),
('flavors', OrderedTestFlavorList))
@ -721,7 +720,7 @@ class Files(SubContext):
self.test_tags |= other.test_tags
self.test_flavors |= other.test_flavors
for k, v in other.items():
for k, v in list(other.items()):
if k == 'IMPACTED_TESTS':
self.test_files |= set(mozpath.relpath(e.full_path, e.context.config.topsrcdir)
for e in v.files)
@ -775,7 +774,7 @@ class Files(SubContext):
bug_components = Counter()
for f in files.values():
for f in list(files.values()):
bug_component = f.get('BUG_COMPONENT')
if bug_component:
bug_components[bug_component] += 1
@ -846,11 +845,11 @@ VARIABLES = {
file.
"""),
'ANDROID_APK_NAME': (unicode, unicode,
'ANDROID_APK_NAME': (str, str,
"""The name of an Android APK file to generate.
"""),
'ANDROID_APK_PACKAGE': (unicode, unicode,
'ANDROID_APK_PACKAGE': (str, str,
"""The name of the Android package to generate R.java for, like org.mozilla.gecko.
"""),
@ -912,7 +911,7 @@ VARIABLES = {
"""),
'GENERATED_FILES': (StrictOrderingOnAppendListWithFlagsFactory({
'script': unicode,
'script': str,
'inputs': list }), list,
"""Generic generated files.
@ -1050,7 +1049,7 @@ VARIABLES = {
This works similarly to FINAL_TARGET_FILES.
"""),
'FINAL_LIBRARY': (unicode, unicode,
'FINAL_LIBRARY': (str, str,
"""Library in which the objects of the current directory will be linked.
This variable contains the name of a library, defined elsewhere with
@ -1101,7 +1100,7 @@ VARIABLES = {
"""A list of python unit tests.
"""),
'HOST_LIBRARY_NAME': (unicode, unicode,
'HOST_LIBRARY_NAME': (str, str,
"""Name of target library generated when cross compiling.
"""),
@ -1119,7 +1118,7 @@ VARIABLES = {
libraries that link into this library via FINAL_LIBRARY.
"""),
'LIBRARY_NAME': (unicode, unicode,
'LIBRARY_NAME': (str, str,
"""The code name of the library generated for a directory.
By default STATIC_LIBRARY_NAME and SHARED_LIBRARY_NAME take this name.
@ -1131,7 +1130,7 @@ VARIABLES = {
``example/components/xpcomsample.lib`` on Windows.
"""),
'SHARED_LIBRARY_NAME': (unicode, unicode,
'SHARED_LIBRARY_NAME': (str, str,
"""The name of the static library generated for a directory, if it needs to
differ from the library code name.
@ -1145,7 +1144,7 @@ VARIABLES = {
Implies FORCE_SHARED_LIB.
"""),
'STATIC_LIBRARY_NAME': (unicode, unicode,
'STATIC_LIBRARY_NAME': (str, str,
"""The name of the static library generated for a directory, if it needs to
differ from the library code name.
@ -1181,37 +1180,37 @@ VARIABLES = {
This variable contains a list of system libaries to link against.
"""),
'RCFILE': (unicode, unicode,
'RCFILE': (str, str,
"""The program .rc file.
This variable can only be used on Windows.
"""),
'RESFILE': (unicode, unicode,
'RESFILE': (str, str,
"""The program .res file.
This variable can only be used on Windows.
"""),
'RCINCLUDE': (unicode, unicode,
'RCINCLUDE': (str, str,
"""The resource script file to be included in the default .res file.
This variable can only be used on Windows.
"""),
'DEFFILE': (unicode, unicode,
'DEFFILE': (str, str,
"""The program .def (module definition) file.
This variable can only be used on Windows.
"""),
'LD_VERSION_SCRIPT': (unicode, unicode,
'LD_VERSION_SCRIPT': (str, str,
"""The linker version script for shared libraries.
This variable can only be used on Linux.
"""),
'SYMBOLS_FILE': (SourcePath, unicode,
'SYMBOLS_FILE': (SourcePath, str,
"""A file containing a list of symbols to export from a shared library.
The given file contains a list of symbols to be exported, and is
@ -1252,7 +1251,7 @@ VARIABLES = {
``BIN_SUFFIX``, the name will remain unchanged.
"""),
'SONAME': (unicode, unicode,
'SONAME': (str, str,
"""The soname of the shared object currently being linked
soname is the "logical name" of a shared object, often used to provide
@ -1308,7 +1307,7 @@ VARIABLES = {
``GENERATED_FILES``.
"""),
'PROGRAM' : (unicode, unicode,
'PROGRAM' : (str, str,
"""Compiled executable name.
If the configuration token ``BIN_SUFFIX`` is set, its value will be
@ -1316,7 +1315,7 @@ VARIABLES = {
``BIN_SUFFIX``, ``PROGRAM`` will remain unchanged.
"""),
'HOST_PROGRAM' : (unicode, unicode,
'HOST_PROGRAM' : (str, str,
"""Compiled host executable name.
If the configuration token ``HOST_BIN_SUFFIX`` is set, its value will be
@ -1354,7 +1353,7 @@ VARIABLES = {
files.
"""),
'XPIDL_MODULE': (unicode, unicode,
'XPIDL_MODULE': (str, str,
"""XPCOM Interface Definition Module Name.
This is the name of the ``.xpt`` file that is created by linking
@ -1509,14 +1508,14 @@ VARIABLES = {
"""),
# The following variables are used to control the target of installed files.
'XPI_NAME': (unicode, unicode,
'XPI_NAME': (str, str,
"""The name of an extension XPI to generate.
When this variable is present, the results of this directory will end up
being packaged into an extension instead of the main dist/bin results.
"""),
'DIST_SUBDIR': (unicode, unicode,
'DIST_SUBDIR': (str, str,
"""The name of an alternate directory to install files to.
When this variable is present, the results of this directory will end up
@ -1524,7 +1523,7 @@ VARIABLES = {
otherwise be placed.
"""),
'FINAL_TARGET': (FinalTargetValue, unicode,
'FINAL_TARGET': (FinalTargetValue, str,
"""The name of the directory to install targets to.
The directory is relative to the top of the object directory. The
@ -1555,7 +1554,7 @@ VARIABLES = {
'GYP_DIRS': (StrictOrderingOnAppendListWithFlagsFactory({
'variables': dict,
'input': unicode,
'input': str,
'sandbox_vars': dict,
'non_unified_sources': StrictOrderingOnAppendList,
}), list,
@ -1721,7 +1720,7 @@ VARIABLES = {
}
# Sanity check: we don't want any variable above to have a list as storage type.
for name, (storage_type, input_types, docs) in VARIABLES.items():
for name, (storage_type, input_types, docs) in list(VARIABLES.items()):
if storage_type == list:
raise RuntimeError('%s has a "list" storage type. Use "List" instead.'
% name)

View File

@ -15,7 +15,7 @@ contains the code for converting executed mozbuild files into these data
structures.
"""
from __future__ import absolute_import, unicode_literals
from mozbuild.util import StrictOrderingOnAppendList
from mozpack.chrome.manifest import ManifestEntry
@ -183,7 +183,7 @@ class BaseDefines(ContextDerived):
self.defines = defines
def get_defines(self):
for define, value in self.defines.iteritems():
for define, value in self.defines.items():
if value is True:
yield('-D%s' % define)
elif value is False:

View File

@ -2,7 +2,7 @@
# 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 itertools
import logging
@ -117,8 +117,8 @@ class TreeMetadataEmitter(LoggingMixin):
# arguments. This gross hack works around the problem until we
# rid ourselves of 2.6.
self.info = {}
for k, v in mozinfo.info.items():
if isinstance(k, unicode):
for k, v in list(mozinfo.info.items()):
if isinstance(k, str):
k = k.encode('ascii')
self.info[k] = v
@ -192,7 +192,7 @@ class TreeMetadataEmitter(LoggingMixin):
def _emit_libs_derived(self, contexts):
# First do FINAL_LIBRARY linkage.
for lib in (l for libs in self._libs.values() for l in libs):
for lib in (l for libs in list(self._libs.values()) for l in libs):
if not isinstance(lib, StaticLibrary) or not lib.link_into:
continue
if lib.link_into not in self._libs:
@ -252,12 +252,12 @@ class TreeMetadataEmitter(LoggingMixin):
lib.link_into == outerlib.basename):
propagate_defines(lib, defines)
for lib in (l for libs in self._libs.values() for l in libs):
for lib in (l for libs in list(self._libs.values()) for l in libs):
if isinstance(lib, Library):
propagate_defines(lib, lib.lib_defines)
yield lib
for obj in self._binaries.values():
for obj in list(self._binaries.values()):
yield obj
LIBRARY_NAME_VAR = {
@ -316,7 +316,7 @@ class TreeMetadataEmitter(LoggingMixin):
libs[key] = l
if key not in libs:
libs[key] = l
candidates = libs.values()
candidates = list(libs.values())
if force_static and not candidates:
if dir:
raise SandboxValidationError(
@ -623,7 +623,7 @@ class TreeMetadataEmitter(LoggingMixin):
assert not gen_sources['UNIFIED_SOURCES']
no_pgo = context.get('NO_PGO')
no_pgo_sources = [f for f, flags in all_flags.iteritems()
no_pgo_sources = [f for f, flags in all_flags.items()
if flags.no_pgo]
if no_pgo:
if no_pgo_sources:
@ -651,7 +651,7 @@ class TreeMetadataEmitter(LoggingMixin):
# The inverse of the above, mapping suffixes to their canonical suffix.
canonicalized_suffix_map = {}
for suffix, alternatives in suffix_map.iteritems():
for suffix, alternatives in suffix_map.items():
alternatives.add(suffix)
for a in alternatives:
canonicalized_suffix_map[a] = suffix
@ -668,7 +668,7 @@ class TreeMetadataEmitter(LoggingMixin):
UNIFIED_SOURCES=(UnifiedSources, None, ['.c', '.mm', '.cpp']),
)
for variable, (klass, gen_klass, suffixes) in varmap.items():
for variable, (klass, gen_klass, suffixes) in list(varmap.items()):
allowed_suffixes = set().union(*[suffix_map[s] for s in suffixes])
# First ensure that we haven't been given filetypes that we don't
@ -691,7 +691,7 @@ class TreeMetadataEmitter(LoggingMixin):
arglist.append(context['FILES_PER_UNIFIED_FILE'])
yield cls(*arglist)
for f, flags in all_flags.iteritems():
for f, flags in all_flags.items():
if flags.flags:
ext = mozpath.splitext(f)[1]
yield PerSourceFlag(context, f, flags.flags)
@ -912,10 +912,10 @@ class TreeMetadataEmitter(LoggingMixin):
for obj in self._process_jar_manifests(context):
yield obj
for name, jar in context.get('JAVA_JAR_TARGETS', {}).items():
for name, jar in list(context.get('JAVA_JAR_TARGETS', {}).items()):
yield ContextWrapped(context, jar)
for name, data in context.get('ANDROID_ECLIPSE_PROJECT_TARGETS', {}).items():
for name, data in list(context.get('ANDROID_ECLIPSE_PROJECT_TARGETS', {}).items()):
yield ContextWrapped(context, data)
for (symbol, cls) in [
@ -976,7 +976,7 @@ class TreeMetadataEmitter(LoggingMixin):
script = mozpath.join(mozpath.dirname(mozpath.dirname(__file__)),
'action', 'process_define_files.py')
yield GeneratedFile(context, script, 'process_define_file',
unicode(path),
str(path),
[mozpath.join(context.srcdir, path + '.in')])
generated_files = context.get('GENERATED_FILES')
@ -1060,7 +1060,7 @@ class TreeMetadataEmitter(LoggingMixin):
srcdir_pattern_files, objdir_files)
def _process_test_manifests(self, context):
for prefix, info in TEST_MANIFESTS.items():
for prefix, info in list(TEST_MANIFESTS.items()):
for path in context.get('%s_MANIFESTS' % prefix, []):
for obj in self._process_test_manifest(context, info, path):
yield obj
@ -1261,7 +1261,7 @@ class TreeMetadataEmitter(LoggingMixin):
paths_file = os.path.join(context.config.topsrcdir, "testing",
"web-platform", "tests", "tools", "localpaths.py")
_globals = {"__file__": paths_file}
execfile(paths_file, _globals)
exec(compile(open(paths_file, "rb").read(), paths_file, 'exec'), _globals)
import manifest as wptmanifest
finally:
sys.path = old_path

View File

@ -2,7 +2,7 @@
# 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 gyp
import sys
@ -69,7 +69,7 @@ class GypContext(TemplateContext):
def encode(value):
if isinstance(value, unicode):
if isinstance(value, str):
return value.encode('utf-8')
return value
@ -87,7 +87,7 @@ def read_from_gyp(config, path, output, vars, non_unified_sources = set()):
# gyp expects plain str instead of unicode. The frontend code gives us
# unicode strings, so convert them.
path = encode(path)
str_vars = dict((name, encode(value)) for name, value in vars.items())
str_vars = dict((name, encode(value)) for name, value in list(vars.items()))
params = {
b'parallel': False,
@ -221,7 +221,7 @@ def read_from_gyp(config, path, output, vars, non_unified_sources = set()):
if not f:
continue
# the result may be a string or a list.
if isinstance(f, types.StringTypes):
if isinstance(f, (str,)):
context[var].append(f)
else:
context[var].extend(f)

View File

@ -2,7 +2,7 @@
# 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 collections import defaultdict
import os
@ -105,13 +105,13 @@ class MozbuildFileCommands(MachCommandBase):
"""
components = defaultdict(set)
try:
for p, m in self._get_files_info(paths, rev=rev).items():
for p, m in list(self._get_files_info(paths, rev=rev).items()):
components[m.get('BUG_COMPONENT')].add(p)
except InvalidPathException as e:
print(e.message)
return 1
for component, files in sorted(components.items(), key=lambda x: (x is None, x)):
for component, files in sorted(list(components.items()), key=lambda x: (x is None, x)):
print('%s :: %s' % (component.product, component.component) if component else 'UNKNOWN')
for f in sorted(files):
print(' %s' % f)
@ -139,7 +139,7 @@ class MozbuildFileCommands(MachCommandBase):
help='Paths whose data to query')
def file_info_test_deps(self, paths, rev=None):
try:
for p, m in self._get_files_info(paths, rev=rev).items():
for p, m in list(self._get_files_info(paths, rev=rev).items()):
print('%s:' % mozpath.relpath(p, self.topsrcdir))
if m.test_files:
print('\tTest file patterns:')

View File

@ -16,7 +16,7 @@ The BuildReader contains basic logic for traversing a tree of mozbuild files.
It does this by examining specific variables populated during execution.
"""
from __future__ import absolute_import, print_function, unicode_literals
import ast
import inspect
@ -80,11 +80,12 @@ from .context import (
)
from mozbuild.base import ExecutionSummary
from functools import reduce
if sys.version_info.major == 2:
text_type = unicode
type_type = types.TypeType
text_type = str
type_type = type
else:
text_type = str
type_type = type
@ -126,7 +127,7 @@ class EmptyConfig(object):
b'JS_STANDALONE': b'1',
})
udict = {}
for k, v in self.substs.items():
for k, v in list(self.substs.items()):
if isinstance(v, str):
udict[k.decode('utf-8')] = v.decode('utf-8')
else:
@ -338,7 +339,7 @@ class MozbuildSandbox(Sandbox):
raise Exception('`template` is a function decorator. You must '
'use it as `@template` preceding a function declaration.')
name = func.func_name
name = func.__name__
if name in self.templates:
raise KeyError(
@ -417,7 +418,7 @@ class MozbuildSandbox(Sandbox):
klass = self._context.__class__
self._context.__class__ = TemplateContext
# The sandbox will do all the necessary checks for these merges.
for key, value in context.items():
for key, value in list(context.items()):
if isinstance(value, dict):
self[key].update(value)
elif isinstance(value, (list, HierarchicalStringList)):
@ -434,10 +435,10 @@ class MozbuildSandbox(Sandbox):
class TemplateFunction(object):
def __init__(self, func, sandbox):
self.path = func.func_code.co_filename
self.name = func.func_name
self.path = func.__code__.co_filename
self.name = func.__name__
code = func.func_code
code = func.__code__
firstlineno = code.co_firstlineno
lines = sandbox._current_source.splitlines(True)
lines = inspect.getblock(lines[firstlineno - 1:])
@ -476,8 +477,8 @@ class TemplateFunction(object):
compile(func_ast, self.path, 'exec'),
glob,
self.name,
func.func_defaults,
func.func_closure,
func.__defaults__,
func.__closure__,
)
func()
@ -491,11 +492,11 @@ class TemplateFunction(object):
'__builtins__': sandbox._builtins
}
func = types.FunctionType(
self._func.func_code,
self._func.__code__,
glob,
self.name,
self._func.func_defaults,
self._func.func_closure
self._func.__defaults__,
self._func.__closure__
)
sandbox.exec_function(func, args, kwargs, self.path,
becomes_current_path=False)
@ -511,7 +512,7 @@ class TemplateFunction(object):
def visit_Str(self, node):
# String nodes we got from the AST parser are str, but we want
# unicode literals everywhere, so transform them.
node.s = unicode(node.s)
node.s = str(node.s)
return node
def visit_Name(self, node):
@ -644,7 +645,7 @@ class BuildReaderError(Exception):
for l in traceback.format_exception(type(self.other), self.other,
self.trace):
s.write(unicode(l))
s.write(str(l))
return s.getvalue()
@ -794,7 +795,7 @@ class BuildReaderError(Exception):
s.write(' %s\n' % inner.args[2])
s.write('\n')
close_matches = difflib.get_close_matches(inner.args[2],
VARIABLES.keys(), 2)
list(VARIABLES.keys()), 2)
if close_matches:
s.write('Maybe you meant %s?\n' % ' or '.join(close_matches))
s.write('\n')
@ -1196,7 +1197,7 @@ class BuildReader(object):
recurse_info[d][key] = dict(sandbox.metadata[key])
for path, child_metadata in recurse_info.items():
for path, child_metadata in list(recurse_info.items()):
child_path = path.join('moz.build').full_path
# Ensure we don't break out of the topsrcdir. We don't do realpath
@ -1288,7 +1289,7 @@ class BuildReader(object):
# There is room to improve this code (and the code in
# _find_relevant_mozbuilds) to better handle multiple files in the same
# directory. Bug 1136966 tracks.
for path, mbpaths in relevants.items():
for path, mbpaths in list(relevants.items()):
path_mozbuilds[path] = [mozpath.join(topsrcdir, p) for p in mbpaths]
for i, mbpath in enumerate(mbpaths[0:-1]):
@ -1325,7 +1326,7 @@ class BuildReader(object):
all_contexts.append(context)
result = {}
for path, paths in path_mozbuilds.items():
for path, paths in list(path_mozbuilds.items()):
result[path] = reduce(lambda x, y: x + y, (contexts[p] for p in paths), [])
return result, all_contexts
@ -1353,7 +1354,7 @@ class BuildReader(object):
r = {}
test_ctx_reader = TestContextReader(self.config)
for path, ctxs in paths.items():
for path, ctxs in list(paths.items()):
flags = Files(Context())
for ctx in ctxs:

View File

@ -17,7 +17,7 @@ KeyError are machine parseable. This machine-friendly data is used to present
user-friendly error messages in the case of errors.
"""
from __future__ import absolute_import, unicode_literals
import os
import sys
@ -178,7 +178,7 @@ class Sandbox(dict):
# following error:
# SyntaxError: unqualified exec is not allowed in function
# 'execute' it is a nested function.
exec code in self
exec(code, self)
finally:
self._current_source = old_source

View File

@ -4,14 +4,14 @@
# This module contains code for running an HTTP server to view build info.
from __future__ import absolute_import, unicode_literals
import BaseHTTPServer
import http.server
import json
import os
class HTTPHandler(BaseHTTPServer.BaseHTTPRequestHandler):
class HTTPHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
s = self.server.wrapper
p = self.path
@ -92,7 +92,7 @@ class BuildViewerServer(object):
self.doc_root = doc_root
self.json_files = {}
self.server = BaseHTTPServer.HTTPServer((address, port), HTTPHandler)
self.server = http.server.HTTPServer((address, port), HTTPHandler)
self.server.wrapper = self
self.do_shutdown = False

View File

@ -8,7 +8,7 @@ processing jar.mn files.
See the documentation for jar.mn on MDC for further details on the format.
'''
from __future__ import absolute_import
import sys
import os
@ -17,7 +17,7 @@ import re
import logging
from time import localtime
from MozZipFile import ZipFile
from cStringIO import StringIO
from io import StringIO
from collections import defaultdict
from mozbuild.preprocessor import Preprocessor
@ -302,9 +302,9 @@ class JarMaker(object):
'''updateManifest replaces the % in the chrome registration entries
with the given chrome base path, and updates the given manifest file.
'''
myregister = dict.fromkeys(map(lambda s: s.replace('%',
chromebasepath), register))
addEntriesToListFile(manifestPath, myregister.iterkeys())
myregister = dict.fromkeys([s.replace('%',
chromebasepath) for s in register])
addEntriesToListFile(manifestPath, iter(myregister.keys()))
def makeJar(self, infile, jardir):
'''makeJar is the main entry point to JarMaker.
@ -322,7 +322,7 @@ class JarMaker(object):
elif self.relativesrcdir:
self.localedirs = \
self.generateLocaleDirs(self.relativesrcdir)
if isinstance(infile, basestring):
if isinstance(infile, str):
logging.info('processing ' + infile)
self.sourcedirs.append(_normpath(os.path.dirname(infile)))
pp = self.pp.clone()
@ -372,7 +372,7 @@ class JarMaker(object):
jarfilepath = jarfile + '.jar'
try:
os.makedirs(os.path.dirname(jarfilepath))
except OSError, error:
except OSError as error:
if error.errno != errno.EEXIST:
raise
jf = ZipFile(jarfilepath, 'a', lock=True)
@ -514,7 +514,7 @@ class JarMaker(object):
# remove previous link or file
try:
os.remove(out)
except OSError, e:
except OSError as e:
if e.errno != errno.ENOENT:
raise
return open(out, 'wb')
@ -525,7 +525,7 @@ class JarMaker(object):
if not os.path.isdir(outdir):
try:
os.makedirs(outdir)
except OSError, error:
except OSError as error:
if error.errno != errno.EEXIST:
raise
return out
@ -541,7 +541,7 @@ class JarMaker(object):
# remove previous link or file
try:
os.remove(out)
except OSError, e:
except OSError as e:
if e.errno != errno.ENOENT:
raise
if sys.platform != 'win32':

View File

@ -2,7 +2,7 @@
# 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 errno
@ -136,7 +136,7 @@ class BuildProgressFooter(object):
# terminal is a blessings.Terminal.
self._t = terminal
self._fh = sys.stdout
self.tiers = monitor.tiers.tier_status.viewitems()
self.tiers = monitor.tiers.tier_status.items()
def clear(self):
"""Removes the footer from the current terminal."""
@ -792,7 +792,7 @@ class Warnings(MachCommandBase):
dirpath = None
type_counts = database.type_counts(dirpath)
sorted_counts = sorted(type_counts.iteritems(),
sorted_counts = sorted(iter(type_counts.items()),
key=operator.itemgetter(1))
total = 0
@ -947,7 +947,7 @@ class GTestCommands(MachCommandBase):
processes[i].run()
exit_code = 0
for process in processes.values():
for process in list(processes.values()):
status = process.wait()
if status:
exit_code = status
@ -1407,16 +1407,16 @@ class MachDebug(MachCommandBase):
quoted_arg = quote(arg)
print("echo ' %s'" % quoted_arg, file=out)
print("""set -- "$@" '%s'""" % quoted_arg, file=out)
for key, value in self.mozconfig['env']['added'].items():
for key, value in list(self.mozconfig['env']['added'].items()):
print("export %s='%s'" % (key, quote(value)), file=out)
for key, (old, value) in self.mozconfig['env']['modified'].items():
for key, (old, value) in list(self.mozconfig['env']['modified'].items()):
print("export %s='%s'" % (key, quote(value)), file=out)
for key, value in self.mozconfig['vars']['added'].items():
for key, value in list(self.mozconfig['vars']['added'].items()):
print("%s='%s'" % (key, quote(value)), file=out)
for key, (old, value) in self.mozconfig['vars']['modified'].items():
for key, (old, value) in list(self.mozconfig['vars']['modified'].items()):
print("%s='%s'" % (key, quote(value)), file=out)
for key in self.mozconfig['env']['removed'].keys() + \
self.mozconfig['vars']['removed'].keys():
for key in list(self.mozconfig['env']['removed'].keys()) + \
list(self.mozconfig['vars']['removed'].keys()):
print("unset %s" % key, file=out)
def _environment_json(self, out, verbose):

View File

@ -2,7 +2,7 @@
# 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 os
import re
@ -66,7 +66,7 @@ class _SimpleOrderedSet(object):
self._list = []
self._set = set()
def __nonzero__(self):
def __bool__(self):
return bool(self._set)
def __iter__(self):

View File

@ -2,7 +2,7 @@
# 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

View File

@ -2,7 +2,7 @@
# 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 filecmp
import os
@ -302,7 +302,7 @@ class MozconfigLoader(object):
# Environment variables also appear as shell variables, but that's
# uninteresting duplication of information. Filter them out.
filt = lambda x, y: {k: v for k, v in x.items() if k not in y}
filt = lambda x, y: {k: v for k, v in list(x.items()) if k not in y}
result['vars'] = diff_vars(
filt(parsed['vars_before'], parsed['env_before']),
filt(parsed['vars_after'], parsed['env_after'])

View File

@ -5,7 +5,7 @@
# This module produces a JSON file that provides basic build info and
# configuration metadata.
from __future__ import absolute_import
import os
import re
@ -150,7 +150,7 @@ def write_mozinfo(file, config, env=os.environ):
and what keys are produced.
"""
build_conf = build_dict(config, env)
if isinstance(file, basestring):
if isinstance(file, str):
with open(file, "w") as f:
json.dump(build_conf, f)
else:

View File

@ -27,7 +27,8 @@ import os
import re
from optparse import OptionParser
import errno
from makeutil import Makefile
from .makeutil import Makefile
from functools import reduce
# hack around win32 mangling our line endings
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65443
@ -56,7 +57,7 @@ class Expression:
self.__ignore_whitespace()
self.e = self.__get_logical_or()
if self.content:
raise Expression.ParseError, self
raise Expression.ParseError(self)
def __get_logical_or(self):
"""
@ -157,7 +158,7 @@ class Expression:
if word_len:
rv = Expression.__ASTLeaf('string', self.content[:word_len])
else:
raise Expression.ParseError, self
raise Expression.ParseError(self)
self.__strip(word_len)
self.__ignore_whitespace()
return rv
@ -196,7 +197,7 @@ class Expression:
return left and right
elif tok[1].value == '||':
return left or right
raise Expression.ParseError, self
raise Expression.ParseError(self)
# Mapping from token types to evaluator functions
# Apart from (non-)equality, all these can be simple lambda forms.
@ -230,7 +231,7 @@ class Expression:
def __repr__(self):
return self.value.__repr__()
class ParseError(StandardError):
class ParseError(Exception):
"""
Error raised when parsing fails.
It has two members, offset and content, which give the offset of the
@ -278,7 +279,7 @@ class Preprocessor:
self.context = Context()
for k,v in {'FILE': '',
'LINE': 0,
'DIRECTORY': os.path.abspath('.')}.iteritems():
'DIRECTORY': os.path.abspath('.')}.items():
self.context[k] = v
self.actionLevel = 0
self.disableLevel = 0
@ -292,21 +293,21 @@ class Preprocessor:
self.cmds = {}
for cmd, level in {'define': 0,
'undef': 0,
'if': sys.maxint,
'ifdef': sys.maxint,
'ifndef': sys.maxint,
'if': sys.maxsize,
'ifdef': sys.maxsize,
'ifndef': sys.maxsize,
'else': 1,
'elif': 1,
'elifdef': 1,
'elifndef': 1,
'endif': sys.maxint,
'endif': sys.maxsize,
'expand': 0,
'literal': 0,
'filter': 0,
'unfilter': 0,
'include': 0,
'includesubst': 0,
'error': 0}.iteritems():
'error': 0}.items():
self.cmds[cmd] = (level, getattr(self, 'do_' + cmd))
self.out = sys.stdout
self.setMarker(marker)
@ -469,7 +470,7 @@ class Preprocessor:
raise Preprocessor.Error(self, "--depend doesn't work with stdout",
None)
try:
from makeutil import Makefile
from .makeutil import Makefile
except:
raise Preprocessor.Error(self, "--depend requires the "
"mozbuild.makeutil module", None)
@ -684,7 +685,7 @@ class Preprocessor:
current = dict(self.filters)
for f in filters:
current[f] = getattr(self, 'filter_' + f)
filterNames = current.keys()
filterNames = list(current.keys())
filterNames.sort()
self.filters = [(fn, current[fn]) for fn in filterNames]
return
@ -694,7 +695,7 @@ class Preprocessor:
for f in filters:
if f in current:
del current[f]
filterNames = current.keys()
filterNames = list(current.keys())
filterNames.sort()
self.filters = [(fn, current[fn]) for fn in filterNames]
return
@ -739,7 +740,7 @@ class Preprocessor:
args can either be a file name, or a file-like object.
Files should be opened, and will be closed after processing.
"""
isName = type(args) == str or type(args) == unicode
isName = type(args) == str or type(args) == str
oldCheckLineNumbers = self.checkLineNumbers
self.checkLineNumbers = False
if isName:

View File

@ -2,7 +2,7 @@
# 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 os
import sys
@ -11,7 +11,7 @@ import sys
def iter_modules_in_path(*paths):
paths = [os.path.abspath(os.path.normcase(p)) + os.sep
for p in paths]
for name, module in sys.modules.items():
for name, module in list(sys.modules.items()):
if not hasattr(module, '__file__'):
continue

View File

@ -15,7 +15,7 @@ def _tokens2re(**tokens):
# which matches the pattern and captures it in a named match group.
# The group names and patterns are given as arguments.
all_tokens = '|'.join('(?P<%s>%s)' % (name, value)
for name, value in tokens.iteritems())
for name, value in tokens.items())
nonescaped = r'(?<!\\)(?:%s)' % all_tokens
# The final pattern matches either the above pattern, or an escaped
@ -96,7 +96,7 @@ class _ClineSplitter(object):
self.cline = self.cline[m.end():]
match = {name: value
for name, value in m.groupdict().items() if value}
for name, value in list(m.groupdict().items()) if value}
if 'quote' in match:
# " or ' start a quoted string
if match['quote'] == '"':
@ -144,7 +144,7 @@ class _ClineSplitter(object):
self._push(self.cline[:m.start()])
self.cline = self.cline[m.end():]
match = {name: value
for name, value in m.groupdict().items() if value}
for name, value in list(m.groupdict().items()) if value}
if 'quote' in match:
# a double quote ends the quoted string, so go back to
# unquoted parsing

View File

@ -2,7 +2,7 @@
# 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 importlib
import os

View File

@ -38,11 +38,11 @@ class TestBuildList(unittest.TestCase):
lines = [line.rstrip() for line in f.readlines()]
f.close()
for line in lines:
self.assert_(len(l) > 0,
self.assertTrue(len(l) > 0,
"ran out of expected lines! (expected '{0}', got '{1}')"
.format(l, lines))
self.assertEqual(line, l.pop(0))
self.assert_(len(l) == 0,
self.assertTrue(len(l) == 0,
"not enough lines in file! (expected '{0}',"
" got '{1}'".format(l, lines))

View File

@ -3,7 +3,7 @@
# Any copyright is dedicated to the Public Domain.
# http://creativecommons.org/publicdomain/zero/1.0/
from __future__ import unicode_literals
import json
import os
@ -43,8 +43,8 @@ class TestGenerateBrowserSearch(unittest.TestCase):
def test_valid_unicode(self):
o = self._test_one('valid-zh-CN')
self.assertEquals(o['default'], '百度')
self.assertEquals(o['engines'], ['百度', 'Google'])
self.assertEqual(o['default'], '百度')
self.assertEqual(o['engines'], ['百度', 'Google'])
def test_invalid_unicode(self):
with self.assertRaises(UnicodeDecodeError):

View File

@ -2,7 +2,7 @@
# 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 unittest

View File

@ -2,7 +2,7 @@
# 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 json
import os

View File

@ -2,7 +2,7 @@
# 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, print_function
import buildconfig
import os

View File

@ -3,7 +3,7 @@
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import os, posixpath
from StringIO import StringIO
from io import StringIO
import unittest
from mozunit import main, MockedOpen
@ -29,7 +29,7 @@ class ConfigEnvironment(ConfigStatus.ConfigEnvironment):
self.substs = ReadOnlyDict(d)
d = dict(self.substs_unicode)
d[u'top_srcdir'] = top_srcdir.decode('utf-8')
d['top_srcdir'] = top_srcdir.decode('utf-8')
self.substs_unicode = ReadOnlyDict(d)

View File

@ -2,7 +2,7 @@
# 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 json
import os
@ -330,7 +330,7 @@ class TestRecursiveMakeBackend(BackendTester):
],
}
for var, val in expected.items():
for var, val in list(expected.items()):
# print("test_variable_passthru[%s]" % (var))
found = [str for str in lines if str.startswith(var)]
self.assertEqual(found, val)
@ -369,7 +369,7 @@ class TestRecursiveMakeBackend(BackendTester):
],
}
for var, val in expected.items():
for var, val in list(expected.items()):
found = [str for str in lines if str.startswith(var)]
self.assertEqual(found, val)
@ -531,7 +531,7 @@ class TestRecursiveMakeBackend(BackendTester):
# This is not the most robust test in the world, but it gets the job
# done.
entries = [e for e in m._dests.keys() if '**' in e]
entries = [e for e in list(m._dests.keys()) if '**' in e]
self.assertEqual(len(entries), 1)
self.assertIn('support/**', entries[0])
@ -705,7 +705,7 @@ class TestRecursiveMakeBackend(BackendTester):
expected[mozpath.join(env.topobjdir, 'final-target')] = [
'FINAL_TARGET = $(DEPTH)/random-final-target'
]
for key, expected_rules in expected.iteritems():
for key, expected_rules in expected.items():
backend_path = mozpath.join(key, 'backend.mk')
lines = [l.strip() for l in open(backend_path, 'rt').readlines()[2:]]
found = [str for str in lines if

View File

@ -2,7 +2,7 @@
# 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
from xml.dom.minidom import parse
import os

View File

@ -2,7 +2,7 @@
# 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
from mach.logging import LoggingManager
@ -34,7 +34,7 @@ class MockConfig(object):
}, **extra_substs)
self.substs_unicode = ReadOnlyDict({k.decode('utf-8'): v.decode('utf-8',
'replace') for k, v in self.substs.items()})
'replace') for k, v in list(self.substs.items())})
self.defines = self.substs

View File

@ -2,7 +2,7 @@
# 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 unittest

View File

@ -2,14 +2,14 @@
# 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 tempfile
import unittest
from StringIO import StringIO
from io import StringIO
from mozunit import main

View File

@ -36,7 +36,7 @@ class TestContext(unittest.TestCase):
'baz': (dict, dict, ''),
})
self.assertEqual(test.keys(), [])
self.assertEqual(list(test.keys()), [])
self.assertEqual(test['foo'], 0)
@ -84,12 +84,12 @@ class TestContext(unittest.TestCase):
'baz': (dict, list, ''),
})
self.assertEqual(test.keys(), [])
self.assertEqual(list(test.keys()), [])
with self.assertRaises(ValueError):
test.update(bar=True, foo={})
self.assertEqual(test.keys(), [])
self.assertEqual(list(test.keys()), [])
test.update(bar=True, foo=1)
@ -258,19 +258,19 @@ class TestSymbols(unittest.TestCase):
self.assertEqual(lines[-1].strip(), '')
def test_documentation_formatting(self):
for typ, inp, doc in VARIABLES.values():
for typ, inp, doc in list(VARIABLES.values()):
self._verify_doc(doc)
for attr, args, doc in FUNCTIONS.values():
for attr, args, doc in list(FUNCTIONS.values()):
self._verify_doc(doc)
for func, typ, doc in SPECIAL_VARIABLES.values():
for func, typ, doc in list(SPECIAL_VARIABLES.values()):
self._verify_doc(doc)
for name, cls in SUBCONTEXTS.items():
for name, cls in list(SUBCONTEXTS.items()):
self._verify_doc(cls.__doc__)
for name, v in cls.VARIABLES.items():
for name, v in list(cls.VARIABLES.items()):
self._verify_doc(v[2])
@ -631,7 +631,7 @@ class TestPaths(unittest.TestCase):
class TestTypedRecord(unittest.TestCase):
def test_fields(self):
T = ContextDerivedTypedRecord(('field1', unicode),
T = ContextDerivedTypedRecord(('field1', str),
('field2', list))
inst = T(None)
self.assertEqual(inst.field1, '')
@ -647,7 +647,7 @@ class TestTypedRecord(unittest.TestCase):
inst.field3 = []
def test_coercion(self):
T = ContextDerivedTypedRecord(('field1', unicode),
T = ContextDerivedTypedRecord(('field1', str),
('field2', list))
inst = T(None)
inst.field1 = 3
@ -673,45 +673,45 @@ class TestFiles(unittest.TestCase):
def test_single_bug_component(self):
c = Context({})
f = Files(c, pattern='**')
f['BUG_COMPONENT'] = (u'Product1', u'Component1')
f['BUG_COMPONENT'] = ('Product1', 'Component1')
files = {'moz.build': f}
self.assertEqual(Files.aggregate(files), {
'bug_component_counts': [((u'Product1', u'Component1'), 1)],
'recommended_bug_component': (u'Product1', u'Component1'),
'bug_component_counts': [(('Product1', 'Component1'), 1)],
'recommended_bug_component': ('Product1', 'Component1'),
})
def test_multiple_bug_components(self):
c = Context({})
f1 = Files(c, pattern='**')
f1['BUG_COMPONENT'] = (u'Product1', u'Component1')
f1['BUG_COMPONENT'] = ('Product1', 'Component1')
f2 = Files(c, pattern='**')
f2['BUG_COMPONENT'] = (u'Product2', u'Component2')
f2['BUG_COMPONENT'] = ('Product2', 'Component2')
files = {'a': f1, 'b': f2, 'c': f1}
self.assertEqual(Files.aggregate(files), {
'bug_component_counts': [
((u'Product1', u'Component1'), 2),
((u'Product2', u'Component2'), 1),
(('Product1', 'Component1'), 2),
(('Product2', 'Component2'), 1),
],
'recommended_bug_component': (u'Product1', u'Component1'),
'recommended_bug_component': ('Product1', 'Component1'),
})
def test_no_recommended_bug_component(self):
"""If there is no clear count winner, we don't recommend a bug component."""
c = Context({})
f1 = Files(c, pattern='**')
f1['BUG_COMPONENT'] = (u'Product1', u'Component1')
f1['BUG_COMPONENT'] = ('Product1', 'Component1')
f2 = Files(c, pattern='**')
f2['BUG_COMPONENT'] = (u'Product2', u'Component2')
f2['BUG_COMPONENT'] = ('Product2', 'Component2')
files = {'a': f1, 'b': f2}
self.assertEqual(Files.aggregate(files), {
'bug_component_counts': [
((u'Product1', u'Component1'), 1),
((u'Product2', u'Component2'), 1),
(('Product1', 'Component1'), 1),
(('Product2', 'Component2'), 1),
],
'recommended_bug_component': None,
})

View File

@ -2,7 +2,7 @@
# 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 unittest
@ -233,25 +233,25 @@ class TestEmitterBasic(unittest.TestCase):
o = objs[0]
self.assertIsInstance(o, GeneratedFile)
self.assertEqual(o.output, 'bar.c')
self.assertRegexpMatches(o.script, 'script.py$')
self.assertRegex(o.script, 'script.py$')
self.assertEqual(o.method, 'make_bar')
self.assertEqual(o.inputs, [])
def test_generated_files_no_script(self):
reader = self.reader('generated-files-no-script')
with self.assertRaisesRegexp(SandboxValidationError,
with self.assertRaisesRegex(SandboxValidationError,
'Script for generating bar.c does not exist'):
objs = self.read_topsrcdir(reader)
def test_generated_files_no_inputs(self):
reader = self.reader('generated-files-no-inputs')
with self.assertRaisesRegexp(SandboxValidationError,
with self.assertRaisesRegex(SandboxValidationError,
'Input for generating foo.c does not exist'):
objs = self.read_topsrcdir(reader)
def test_generated_files_no_python_script(self):
reader = self.reader('generated-files-no-python-script')
with self.assertRaisesRegexp(SandboxValidationError,
with self.assertRaisesRegex(SandboxValidationError,
'Script for generating bar.c does not end in .py'):
objs = self.read_topsrcdir(reader)
@ -280,7 +280,7 @@ class TestEmitterBasic(unittest.TestCase):
Missing files in EXPORTS is an error.
'''
reader = self.reader('exports-missing')
with self.assertRaisesRegexp(SandboxValidationError,
with self.assertRaisesRegex(SandboxValidationError,
'File listed in EXPORTS does not exist:'):
objs = self.read_topsrcdir(reader)
@ -289,7 +289,7 @@ class TestEmitterBasic(unittest.TestCase):
An objdir file in EXPORTS that is not in GENERATED_FILES is an error.
'''
reader = self.reader('exports-missing-generated')
with self.assertRaisesRegexp(SandboxValidationError,
with self.assertRaisesRegex(SandboxValidationError,
'Objdir file listed in EXPORTS not in GENERATED_FILES:'):
objs = self.read_topsrcdir(reader)
@ -319,14 +319,14 @@ class TestEmitterBasic(unittest.TestCase):
'testing/mochitest': ['mochitest.py', 'mochitest.ini'],
}
for path, strings in objs[0].srcdir_files.iteritems():
for path, strings in objs[0].srcdir_files.items():
self.assertTrue(path in expected)
basenames = sorted(mozpath.basename(s) for s in strings)
self.assertEqual(sorted(expected[path]), basenames)
def test_test_harness_files_root(self):
reader = self.reader('test-harness-files-root')
with self.assertRaisesRegexp(SandboxValidationError,
with self.assertRaisesRegex(SandboxValidationError,
'Cannot install files to the root of TEST_HARNESS_FILES'):
objs = self.read_topsrcdir(reader)
@ -363,14 +363,14 @@ class TestEmitterBasic(unittest.TestCase):
"""A missing manifest file should result in an error."""
reader = self.reader('test-manifest-missing-manifest')
with self.assertRaisesRegexp(SandboxValidationError, 'IOError: Missing files'):
with self.assertRaisesRegex(SandboxValidationError, 'IOError: Missing files'):
self.read_topsrcdir(reader)
def test_empty_test_manifest_rejected(self):
"""A test manifest without any entries is rejected."""
reader = self.reader('test-manifest-empty')
with self.assertRaisesRegexp(SandboxValidationError, 'Empty test manifest'):
with self.assertRaisesRegex(SandboxValidationError, 'Empty test manifest'):
self.read_topsrcdir(reader)
@ -378,7 +378,7 @@ class TestEmitterBasic(unittest.TestCase):
"""A test manifest with no tests but support-files is not supported."""
reader = self.reader('test-manifest-just-support')
with self.assertRaisesRegexp(SandboxValidationError, 'Empty test manifest'):
with self.assertRaisesRegex(SandboxValidationError, 'Empty test manifest'):
self.read_topsrcdir(reader)
def test_test_manifest_absolute_support_files(self):
@ -394,7 +394,7 @@ class TestEmitterBasic(unittest.TestCase):
mozpath.join(o.install_prefix, "absolute-support.ini"),
mozpath.join(o.install_prefix, "test_file.js"),
]
paths = sorted([v[0] for v in o.installs.values()])
paths = sorted([v[0] for v in list(o.installs.values())])
self.assertEqual(paths, expected)
def test_test_manifest_install_to_subdir(self):
@ -412,7 +412,7 @@ class TestEmitterBasic(unittest.TestCase):
mozpath.normpath(mozpath.join(o.install_prefix, "subdir/support.txt")),
mozpath.normpath(mozpath.join(o.install_prefix, "subdir/test_foo.html")),
]
paths = sorted([v[0] for v in o.installs.values()])
paths = sorted([v[0] for v in list(o.installs.values())])
self.assertEqual(paths, expected)
def test_test_manifest_install_includes(self):
@ -430,7 +430,7 @@ class TestEmitterBasic(unittest.TestCase):
mozpath.normpath(mozpath.join(o.install_prefix, "subdir/mochitest.ini")),
mozpath.normpath(mozpath.join(o.install_prefix, "subdir/test_foo.html")),
]
paths = sorted([v[0] for v in o.installs.values()])
paths = sorted([v[0] for v in list(o.installs.values())])
self.assertEqual(paths, expected)
def test_test_manifest_includes(self):
@ -537,7 +537,7 @@ class TestEmitterBasic(unittest.TestCase):
self.assertEqual(external_normalized, m.get('external', set()))
self.assertEqual(len(o.installs), len(m['installs']))
for path in o.installs.keys():
for path in list(o.installs.keys()):
self.assertTrue(path.startswith(o.directory))
relpath = path[len(o.directory)+1:]
@ -550,7 +550,7 @@ class TestEmitterBasic(unittest.TestCase):
def test_test_manifest_unmatched_generated(self):
reader = self.reader('test-manifest-unmatched-generated')
with self.assertRaisesRegexp(SandboxValidationError,
with self.assertRaisesRegex(SandboxValidationError,
'entry in generated-files not present elsewhere'):
self.read_topsrcdir(reader),
@ -574,7 +574,7 @@ class TestEmitterBasic(unittest.TestCase):
"""Missing test files should result in error."""
reader = self.reader('test-manifest-missing-test-file')
with self.assertRaisesRegexp(SandboxValidationError,
with self.assertRaisesRegex(SandboxValidationError,
'lists test that does not exist: test_missing.html'):
self.read_topsrcdir(reader)
@ -582,7 +582,7 @@ class TestEmitterBasic(unittest.TestCase):
"""Missing test files should result in error, even when the test list is not filtered."""
reader = self.reader('test-manifest-missing-test-file-unfiltered')
with self.assertRaisesRegexp(SandboxValidationError,
with self.assertRaisesRegex(SandboxValidationError,
'lists test that does not exist: missing.js'):
self.read_topsrcdir(reader)
@ -696,20 +696,20 @@ class TestEmitterBasic(unittest.TestCase):
self.assertIsInstance(obj.path, Path)
def test_jar_manifests_multiple_files(self):
with self.assertRaisesRegexp(SandboxValidationError, 'limited to one value'):
with self.assertRaisesRegex(SandboxValidationError, 'limited to one value'):
reader = self.reader('jar-manifests-multiple-files')
self.read_topsrcdir(reader)
def test_xpidl_module_no_sources(self):
"""XPIDL_MODULE without XPIDL_SOURCES should be rejected."""
with self.assertRaisesRegexp(SandboxValidationError, 'XPIDL_MODULE '
with self.assertRaisesRegex(SandboxValidationError, 'XPIDL_MODULE '
'cannot be defined'):
reader = self.reader('xpidl-module-no-sources')
self.read_topsrcdir(reader)
def test_missing_local_includes(self):
"""LOCAL_INCLUDES containing non-existent directories should be rejected."""
with self.assertRaisesRegexp(SandboxValidationError, 'Path specified in '
with self.assertRaisesRegex(SandboxValidationError, 'Path specified in '
'LOCAL_INCLUDES does not exist'):
reader = self.reader('missing-local-includes')
self.read_topsrcdir(reader)
@ -753,7 +753,7 @@ class TestEmitterBasic(unittest.TestCase):
'.S': ['g.S'],
'.s': ['h.s', 'i.asm'],
}
for suffix, files in expected.items():
for suffix, files in list(expected.items()):
sources = suffix_map[suffix]
self.assertEqual(
sources.files,
@ -782,7 +782,7 @@ class TestEmitterBasic(unittest.TestCase):
'.S': ['g.S'],
'.s': ['h.s', 'i.asm'],
}
for suffix, files in expected.items():
for suffix, files in list(expected.items()):
sources = suffix_map[suffix]
self.assertEqual(
sources.files,
@ -807,7 +807,7 @@ class TestEmitterBasic(unittest.TestCase):
'.c': ['d.c'],
'.mm': ['e.mm', 'f.mm'],
}
for suffix, files in expected.items():
for suffix, files in list(expected.items()):
sources = suffix_map[suffix]
self.assertEqual(
sources.files,
@ -832,7 +832,7 @@ class TestEmitterBasic(unittest.TestCase):
'.mm': ['objc1.mm', 'objc2.mm'],
'.c': ['c1.c', 'c2.c'],
}
for suffix, files in expected.items():
for suffix, files in list(expected.items()):
sources = suffix_map[suffix]
self.assertEqual(
sources.files,
@ -858,7 +858,7 @@ class TestEmitterBasic(unittest.TestCase):
'.mm': ['objc1.mm', 'objc2.mm'],
'.c': ['c1.c', 'c2.c'],
}
for suffix, files in expected.items():
for suffix, files in list(expected.items()):
sources = suffix_map[suffix]
self.assertEqual(
sources.files,
@ -881,11 +881,11 @@ class TestEmitterBasic(unittest.TestCase):
expected = {'install.rdf', 'main.js'}
for f in files:
self.assertTrue(unicode(f) in expected)
self.assertTrue(str(f) in expected)
def test_missing_final_target_pp_files(self):
"""Test that FINAL_TARGET_PP_FILES with missing files throws errors."""
with self.assertRaisesRegexp(SandboxValidationError, 'File listed in '
with self.assertRaisesRegex(SandboxValidationError, 'File listed in '
'FINAL_TARGET_PP_FILES does not exist'):
reader = self.reader('dist-files-missing')
self.read_topsrcdir(reader)
@ -893,7 +893,7 @@ class TestEmitterBasic(unittest.TestCase):
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,
with self.assertRaisesRegex(SandboxValidationError,
'Only source directory paths allowed in FINAL_TARGET_PP_FILES:'):
objs = self.read_topsrcdir(reader)
@ -911,7 +911,7 @@ class TestEmitterBasic(unittest.TestCase):
mozpath.join(reader.config.topobjdir, 'dir2'),
'/dir3',
]
self.assertEquals([p.full_path for p in objs[0].paths], expected)
self.assertEqual([p.full_path for p in objs[0].paths], expected)
def test_binary_components(self):
"""Test that IS_COMPONENT/NO_COMPONENTS_MANIFEST work properly."""

View File

@ -2,7 +2,7 @@
# 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 unittest
@ -29,7 +29,7 @@ class Fuga(object):
class Piyo(ContextDerivedValue):
def __init__(self, context, value):
if not isinstance(value, unicode):
if not isinstance(value, str):
raise ValueError
self.context = context
self.value = value
@ -48,9 +48,9 @@ class Piyo(ContextDerivedValue):
VARIABLES = {
'HOGE': (unicode, unicode, None),
'FUGA': (Fuga, unicode, None),
'PIYO': (Piyo, unicode, None),
'HOGE': (str, str, None),
'FUGA': (Fuga, str, None),
'PIYO': (Piyo, str, None),
'HOGERA': (ContextDerivedTypedList(Piyo, StrictOrderingOnAppendList),
list, None),
'HOGEHOGE': (ContextDerivedTypedListWithItems(
@ -104,7 +104,7 @@ class TestContext(unittest.TestCase):
self.assertEqual(e[1], 'set_type')
self.assertEqual(e[2], 'HOGE')
self.assertEqual(e[3], True)
self.assertEqual(e[4], unicode)
self.assertEqual(e[4], str)
def test_key_checking(self):
# Checking for existence of a key should not populate the key if it
@ -127,7 +127,7 @@ class TestContext(unittest.TestCase):
self.assertEqual(e[1], 'set_type')
self.assertEqual(e[2], 'FUGA')
self.assertEqual(e[3], False)
self.assertEqual(e[4], unicode)
self.assertEqual(e[4], str)
ns['FUGA'] = 'fuga'
self.assertIsInstance(ns['FUGA'], Fuga)
@ -150,7 +150,7 @@ class TestContext(unittest.TestCase):
self.assertEqual(e[1], 'set_type')
self.assertEqual(e[2], 'PIYO')
self.assertEqual(e[3], False)
self.assertEqual(e[4], unicode)
self.assertEqual(e[4], str)
ns['PIYO'] = 'piyo'
self.assertIsInstance(ns['PIYO'], Piyo)

View File

@ -2,7 +2,7 @@
# 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 sys
@ -423,7 +423,7 @@ class TestBuildReader(unittest.TestCase):
'simple/base.cpp',
])
for path, pattern_set in expected.items():
for path, pattern_set in list(expected.items()):
self.assertEqual(v[path].test_files,
expected[path])
@ -437,7 +437,7 @@ class TestBuildReader(unittest.TestCase):
'default/module.js': set(['default/tests/xpcshell/**']),
}
for path, pattern_set in expected.items():
for path, pattern_set in list(expected.items()):
self.assertEqual(v[path].test_files,
expected[path])
@ -453,7 +453,7 @@ class TestBuildReader(unittest.TestCase):
'tagged/src/bar.jsm': set(['tagged/**.js']),
}
for path, pattern_set in expected_patterns.items():
for path, pattern_set in list(expected_patterns.items()):
self.assertEqual(v[path].test_files,
expected_patterns[path])
@ -461,7 +461,7 @@ class TestBuildReader(unittest.TestCase):
'tagged/src/submodule/foo.js': set(['submodule']),
'tagged/src/bar.jsm': set([]),
}
for path, pattern_set in expected_tags.items():
for path, pattern_set in list(expected_tags.items()):
self.assertEqual(v[path].test_tags,
expected_tags[path])
@ -469,7 +469,7 @@ class TestBuildReader(unittest.TestCase):
'tagged/src/bar.jsm': set(['browser-chrome']),
'tagged/src/submodule/foo.js': set([]),
}
for path, pattern_set in expected_flavors.items():
for path, pattern_set in list(expected_flavors.items()):
self.assertEqual(v[path].test_flavors,
expected_flavors[path])

View File

@ -2,7 +2,7 @@
# 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
@ -345,7 +345,7 @@ class TestMozbuildSandbox(unittest.TestCase):
sandbox = MozbuildSandbox(Context(VARIABLES, config))
self.assertEqual(sandbox['CONFIG']['BAD_UTF8'],
u'\ufffd\ufffd\ufffd\ufffd:')
'\ufffd\ufffd\ufffd\ufffd:')
def test_invalid_exports_set_base(self):
sandbox = self.sandbox()
@ -525,7 +525,7 @@ def Template():
source = 'a = foo(1, 2)'
sandbox.exec_source(source, 'foo.mozbuild')
self.assertEquals(sandbox['a'], (Foo, int))
self.assertEqual(sandbox['a'], (Foo, int))
finally:
del FUNCTIONS['foo']

View File

@ -2,7 +2,7 @@
# 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 json
import os
@ -89,7 +89,7 @@ class TestMozbuildObject(unittest.TestCase):
mozconfig = os.path.join(d, 'mozconfig')
with open(mozconfig, 'wt') as fh:
fh.write('mk_add_options MOZ_OBJDIR=@TOPSRCDIR@/foo/@CONFIG_GUESS@')
print('Wrote mozconfig %s' % mozconfig)
print(('Wrote mozconfig %s' % mozconfig))
topobjdir = os.path.join(d, 'foo', guess)
os.makedirs(topobjdir)

View File

@ -124,7 +124,7 @@ class TestOrderedDefaultDict(unittest.TestCase):
self.assertEqual(test['foo'], 1)
self.assertEqual(test.keys(), ['foo', 'bar' ])
self.assertEqual(list(test.keys()), ['foo', 'bar' ])
def test_defaults(self):
test = OrderedDefaultDict(bool, {'foo': 1 })
@ -133,7 +133,7 @@ class TestOrderedDefaultDict(unittest.TestCase):
self.assertEqual(test['qux'], False)
self.assertEqual(test.keys(), ['foo', 'qux' ])
self.assertEqual(list(test.keys()), ['foo', 'qux' ])
class TestKeyedDefaultDict(unittest.TestCase):

View File

@ -1,11 +1,11 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
import unittest
from StringIO import StringIO
from io import StringIO
import mozpack.path as mozpath

View File

@ -25,8 +25,8 @@ class TestContext(unittest.TestCase):
def test_in(self):
"""test 'var in context' to not fall for fallback"""
self.assert_('FAIL' in self.c)
self.assert_('PASS' not in self.c)
self.assertTrue('FAIL' in self.c)
self.assertTrue('PASS' not in self.c)
class TestExpression(unittest.TestCase):
"""
@ -48,16 +48,16 @@ class TestExpression(unittest.TestCase):
def test_not(self):
"""Test for the ! operator"""
self.assert_(Expression('!0').evaluate(self.c))
self.assert_(not Expression('!1').evaluate(self.c))
self.assertTrue(Expression('!0').evaluate(self.c))
self.assertTrue(not Expression('!1').evaluate(self.c))
def test_equals(self):
""" Test for the == operator"""
self.assert_(Expression('FAIL == PASS').evaluate(self.c))
self.assertTrue(Expression('FAIL == PASS').evaluate(self.c))
def test_notequals(self):
""" Test for the != operator"""
self.assert_(Expression('FAIL != 1').evaluate(self.c))
self.assertTrue(Expression('FAIL != 1').evaluate(self.c))
def test_logical_and(self):
""" Test for the && operator"""

View File

@ -2,14 +2,14 @@
# 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 print_function
import unittest
import os, sys, os.path, time, inspect
from filecmp import dircmp
from tempfile import mkdtemp
from shutil import rmtree, copy2
from StringIO import StringIO
from io import StringIO
from zipfile import ZipFile
import mozunit
@ -117,12 +117,12 @@ class _TreeDiff(dircmp):
"""Helper to report rich results on difference between two directories.
"""
def _fillDiff(self, dc, rv, basepath="{0}"):
rv['right_only'] += map(lambda l: basepath.format(l), dc.right_only)
rv['left_only'] += map(lambda l: basepath.format(l), dc.left_only)
rv['diff_files'] += map(lambda l: basepath.format(l), dc.diff_files)
rv['funny'] += map(lambda l: basepath.format(l), dc.common_funny)
rv['funny'] += map(lambda l: basepath.format(l), dc.funny_files)
for subdir, _dc in dc.subdirs.iteritems():
rv['right_only'] += [basepath.format(l) for l in dc.right_only]
rv['left_only'] += [basepath.format(l) for l in dc.left_only]
rv['diff_files'] += [basepath.format(l) for l in dc.diff_files]
rv['funny'] += [basepath.format(l) for l in dc.common_funny]
rv['funny'] += [basepath.format(l) for l in dc.funny_files]
for subdir, _dc in dc.subdirs.items():
self._fillDiff(_dc, rv, basepath.format(subdir + "/{0}"))
def allResults(self, left, right):
rv = {'right_only':[], 'left_only':[],
@ -295,7 +295,7 @@ class TestJarMaker(unittest.TestCase):
('hoge', 'foo', '2'): ('qux', 'foo', '2'),
('hoge', 'baz'): ('qux', 'baz'),
}
for dest, src in expected_symlinks.iteritems():
for dest, src in expected_symlinks.items():
srcpath = os.path.join(self.srcdir, *src)
destpath = os.path.join(self.builddir, 'chrome', 'test', 'dir',
*dest)
@ -317,7 +317,7 @@ class Test_relativesrcdir(unittest.TestCase):
def test_en_US(self):
jm = self.jm
jm.makeJar(self.fake_empty_file, '/NO_OUTPUT_REQUIRED')
self.assertEquals(jm.localedirs,
self.assertEqual(jm.localedirs,
[
os.path.join(os.path.abspath('/TOPSOURCEDIR'),
'browser/locales', 'en-US')
@ -326,13 +326,13 @@ class Test_relativesrcdir(unittest.TestCase):
jm = self.jm
jm.l10nbase = '/L10N_BASE'
jm.makeJar(self.fake_empty_file, '/NO_OUTPUT_REQUIRED')
self.assertEquals(jm.localedirs, [os.path.join('/L10N_BASE', 'browser')])
self.assertEqual(jm.localedirs, [os.path.join('/L10N_BASE', 'browser')])
def test_l10n_merge(self):
jm = self.jm
jm.l10nbase = '/L10N_BASE'
jm.l10nmerge = '/L10N_MERGE'
jm.makeJar(self.fake_empty_file, '/NO_OUTPUT_REQUIRED')
self.assertEquals(jm.localedirs,
self.assertEqual(jm.localedirs,
[os.path.join('/L10N_MERGE', 'browser'),
os.path.join('/L10N_BASE', 'browser'),
os.path.join(os.path.abspath('/TOPSOURCEDIR'),
@ -346,7 +346,7 @@ relativesrcdir dom/locales:
''')
jarcontents.name = 'override.mn'
jm.makeJar(jarcontents, '/NO_OUTPUT_REQUIRED')
self.assertEquals(jm.localedirs,
self.assertEqual(jm.localedirs,
[
os.path.join(os.path.abspath('/TOPSOURCEDIR'),
'dom/locales', 'en-US')
@ -360,7 +360,7 @@ relativesrcdir dom/locales:
''')
jarcontents.name = 'override.mn'
jm.makeJar(jarcontents, '/NO_OUTPUT_REQUIRED')
self.assertEquals(jm.localedirs, [os.path.join('/L10N_BASE', 'dom')])
self.assertEqual(jm.localedirs, [os.path.join('/L10N_BASE', 'dom')])
if __name__ == '__main__':

View File

@ -1,6 +1,6 @@
import unittest
from StringIO import StringIO
from io import StringIO
import os
import sys
import os.path
@ -30,17 +30,17 @@ class TestLineEndings(unittest.TestCase):
def testMac(self):
self.createFile(['\x0D']*3)
self.pp.do_include(self.tempnam)
self.assertEquals(self.pp.out.getvalue(), 'a\nb\nc\n')
self.assertEqual(self.pp.out.getvalue(), 'a\nb\nc\n')
def testUnix(self):
self.createFile(['\x0A']*3)
self.pp.do_include(self.tempnam)
self.assertEquals(self.pp.out.getvalue(), 'a\nb\nc\n')
self.assertEqual(self.pp.out.getvalue(), 'a\nb\nc\n')
def testWindows(self):
self.createFile(['\x0D\x0A']*3)
self.pp.do_include(self.tempnam)
self.assertEquals(self.pp.out.getvalue(), 'a\nb\nc\n')
self.assertEqual(self.pp.out.getvalue(), 'a\nb\nc\n')
if __name__ == '__main__':
mozunit.main()

View File

@ -11,7 +11,7 @@ from mozbuild.makeutil import (
from mozunit import main
import os
import unittest
from StringIO import StringIO
from io import StringIO
class TestMakefile(unittest.TestCase):

View File

@ -2,7 +2,7 @@
# 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 unittest
@ -476,9 +476,9 @@ class TestMozconfigLoader(unittest.TestCase):
self.assertTrue(e.exception.message.startswith(
'Evaluation of your mozconfig exited with an error'))
self.assertEquals(e.exception.path,
self.assertEqual(e.exception.path,
mozconfig.name.replace(os.sep, '/'))
self.assertEquals(e.exception.output, ['hello world'])
self.assertEqual(e.exception.output, ['hello world'])
if __name__ == '__main__':

View File

@ -8,7 +8,7 @@ import os
import tempfile
import unittest
from StringIO import StringIO
from io import StringIO
import mozunit

View File

@ -4,7 +4,7 @@
import unittest
from StringIO import StringIO
from io import StringIO
import os
import shutil

View File

@ -12,7 +12,7 @@ class TestIterModules(unittest.TestCase):
def test_iter_modules_in_path(self):
mozbuild_path = os.path.normcase(os.path.dirname(os.path.dirname(__file__)))
paths = list(iter_modules_in_path(mozbuild_path))
self.assertEquals(sorted(paths), [
self.assertEqual(sorted(paths), [
os.path.join(os.path.abspath(mozbuild_path), '__init__.py'),
os.path.join(os.path.abspath(mozbuild_path), 'pythonutil.py'),
os.path.join(os.path.abspath(mozbuild_path), 'test', 'test_pythonutil.py'),

View File

@ -2,7 +2,7 @@
# 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

View File

@ -2,7 +2,7 @@
# 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 itertools
import hashlib
@ -104,7 +104,7 @@ class TestFileAvoidWrite(unittest.TestCase):
'''
def __call__(self, name, mode):
if 'w' in mode:
raise Exception, 'Unexpected open with write mode'
raise Exception('Unexpected open with write mode')
return MockedOpen.__call__(self, name, mode)
with MyMockedOpen({'file': 'content'}):
@ -454,7 +454,7 @@ class TestStrictOrderingOnAppendListWithFlagsFactory(unittest.TestCase):
def test_strict_ordering_on_append_list_with_flags_factory_extend(self):
FooList = StrictOrderingOnAppendListWithFlagsFactory({
'foo': bool, 'bar': unicode
'foo': bool, 'bar': str
})
foo = FooList(['a', 'b', 'c'])
foo['a'].foo = True
@ -462,7 +462,7 @@ class TestStrictOrderingOnAppendListWithFlagsFactory(unittest.TestCase):
# Don't allow extending lists with different flag definitions.
BarList = StrictOrderingOnAppendListWithFlagsFactory({
'foo': unicode, 'baz': bool
'foo': str, 'baz': bool
})
bar = BarList(['d', 'e', 'f'])
bar['d'].foo = 'foo'
@ -682,9 +682,9 @@ class TestTypedList(unittest.TestCase):
class TypedTestStrictOrderingOnAppendList(unittest.TestCase):
def test_init(self):
class Unicode(unicode):
class Unicode(str):
def __init__(self, other):
if not isinstance(other, unicode):
if not isinstance(other, str):
raise ValueError()
super(Unicode, self).__init__(other)
@ -706,14 +706,14 @@ class TypedTestStrictOrderingOnAppendList(unittest.TestCase):
class TestTypedNamedTuple(unittest.TestCase):
def test_simple(self):
FooBar = TypedNamedTuple('FooBar', [('foo', unicode), ('bar', int)])
FooBar = TypedNamedTuple('FooBar', [('foo', str), ('bar', int)])
t = FooBar(foo='foo', bar=2)
self.assertEquals(type(t), FooBar)
self.assertEquals(t.foo, 'foo')
self.assertEquals(t.bar, 2)
self.assertEquals(t[0], 'foo')
self.assertEquals(t[1], 2)
self.assertEqual(type(t), FooBar)
self.assertEqual(t.foo, 'foo')
self.assertEqual(t.bar, 2)
self.assertEqual(t[0], 'foo')
self.assertEqual(t[1], 2)
FooBar('foo', 2)
@ -726,7 +726,7 @@ class TestTypedNamedTuple(unittest.TestCase):
# arguments.
t1 = ('foo', 3)
t2 = FooBar(t1)
self.assertEquals(type(t2), FooBar)
self.assertEqual(type(t2), FooBar)
self.assertEqual(FooBar(t1), FooBar('foo', 3))

View File

@ -2,7 +2,7 @@
# 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 json
import os
@ -55,7 +55,7 @@ class TestMetadata(object):
with open(filename, 'rt') as fh:
d = json.load(fh)
for path, tests in d.items():
for path, tests in list(d.items()):
for metadata in tests:
self._tests_by_path[path].append(metadata)
self._test_dirs.add(os.path.dirname(path))
@ -285,6 +285,6 @@ REFTEST_FLAVORS = ('crashtest', 'reftest')
WEB_PATFORM_TESTS_FLAVORS = ('web-platform-tests',)
def all_test_flavors():
return ([v[0] for v in TEST_MANIFESTS.values()] +
return ([v[0] for v in list(TEST_MANIFESTS.values())] +
list(REFTEST_FLAVORS) +
list(WEB_PATFORM_TESTS_FLAVORS))

View File

@ -5,7 +5,7 @@
# This file contains miscellaneous utility functions that don't belong anywhere
# in particular.
from __future__ import absolute_import, unicode_literals
import argparse
import collections
@ -35,7 +35,7 @@ from io import (
if sys.version_info[0] == 3:
str_type = str
else:
str_type = basestring
str_type = str
if sys.platform == 'win32':
_kernel32 = ctypes.windll.kernel32
@ -61,7 +61,7 @@ def hash_file(path, hasher=None):
return h.hexdigest()
class EmptyValue(unicode):
class EmptyValue(str):
"""A dummy type that behaves like an empty string and sequence.
This type exists in order to support
@ -112,7 +112,7 @@ def ensureParentDir(path):
if d and not os.path.exists(path):
try:
os.makedirs(d)
except OSError, error:
except OSError as error:
if error.errno != errno.EEXIST:
raise
@ -184,7 +184,7 @@ class FileAvoidWrite(BytesIO):
self.mode = mode
def write(self, buf):
if isinstance(buf, unicode):
if isinstance(buf, str):
buf = buf.encode('utf-8')
BytesIO.write(self, buf)
@ -337,7 +337,7 @@ class ListMixin(object):
def __add__(self, other):
# Allow None and EmptyValue is a special case because it makes undefined
# variable references in moz.build behave better.
other = [] if isinstance(other, (types.NoneType, EmptyValue)) else other
other = [] if isinstance(other, (type(None), EmptyValue)) else other
if not isinstance(other, list):
raise ValueError('Only lists can be appended to lists.')
@ -346,7 +346,7 @@ class ListMixin(object):
return new_list
def __iadd__(self, other):
other = [] if isinstance(other, (types.NoneType, EmptyValue)) else other
other = [] if isinstance(other, (type(None), EmptyValue)) else other
if not isinstance(other, list):
raise ValueError('Only lists can be appended to lists.')
@ -449,14 +449,14 @@ def FlagsFactory(flags):
functions below.
"""
assert isinstance(flags, dict)
assert all(isinstance(v, type) for v in flags.values())
assert all(isinstance(v, type) for v in list(flags.values()))
class Flags(object):
__slots__ = flags.keys()
__slots__ = list(flags.keys())
_flags = flags
def update(self, **kwargs):
for k, v in kwargs.iteritems():
for k, v in kwargs.items():
setattr(self, k, v)
def __getattr__(self, name):
@ -983,14 +983,14 @@ def group_unified_files(files, unified_prefix, unified_suffix,
# issue. So we do a little dance to filter it out ourselves.
dummy_fill_value = ("dummy",)
def filter_out_dummy(iterable):
return itertools.ifilter(lambda x: x != dummy_fill_value,
return filter(lambda x: x != dummy_fill_value,
iterable)
# From the itertools documentation, slightly modified:
def grouper(n, iterable):
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return itertools.izip_longest(fillvalue=dummy_fill_value, *args)
return itertools.zip_longest(fillvalue=dummy_fill_value, *args)
for i, unified_group in enumerate(grouper(files_per_unified_file,
files)):
@ -1007,7 +1007,7 @@ def pair(iterable):
[(1,2), (3,4), (5,6)]
'''
i = iter(iterable)
return itertools.izip_longest(i, i)
return itertools.zip_longest(i, i)
VARIABLES_RE = re.compile('\$\((\w+)\)')
@ -1025,7 +1025,7 @@ def expand_variables(s, variables):
value = variables.get(name)
if not value:
continue
if not isinstance(value, types.StringTypes):
if not isinstance(value, (str,)):
value = ' '.join(value)
result += value
return result

View File

@ -5,7 +5,7 @@
# This file contains code for populating the virtualenv environment for
# Mozilla's build system. It is typically called as part of configure.
from __future__ import absolute_import, print_function, unicode_literals
import distutils.sysconfig
import os
@ -405,8 +405,8 @@ class VirtualenvManager(object):
and call .ensure() and .activate() to make the virtualenv active.
"""
execfile(self.activate_path, dict(__file__=self.activate_path))
if isinstance(os.environ['PATH'], unicode):
exec(compile(open(self.activate_path, "rb").read(), self.activate_path, 'exec'), dict(__file__=self.activate_path))
if isinstance(os.environ['PATH'], str):
os.environ['PATH'] = os.environ['PATH'].encode('utf-8')
def install_pip_package(self, package):

View File

@ -2,7 +2,7 @@
# 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 re
from distutils.version import LooseVersion
@ -250,7 +250,7 @@ class Flags(OrderedDict):
flags.match(application='foo', appversion='3.5') returns True
flags.match(application='foo', appversion='3.0') returns False
'''
for name, value in filter.iteritems():
for name, value in filter.items():
if not name in self:
continue
if not self[name].matches(value):

View File

@ -2,11 +2,11 @@
# 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 re
import os
from urlparse import urlparse
from urllib.parse import urlparse
import mozpack.path as mozpath
from mozpack.chrome.flags import Flags
from mozpack.errors import errors
@ -321,7 +321,7 @@ class ManifestContract(ManifestEntry):
return self.serialize(self.contractID, self.cid)
# All manifest classes by their type name.
MANIFESTS_TYPES = dict([(c.type, c) for c in globals().values()
MANIFESTS_TYPES = dict([(c.type, c) for c in list(globals().values())
if type(c) == type and issubclass(c, ManifestEntry)
and hasattr(c, 'type') and c.type])

View File

@ -2,7 +2,7 @@
# 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 os
import stat
@ -109,7 +109,7 @@ class FileRegistry(object):
'''
Return all paths stored in the container, in the order they were added.
'''
return self._files.keys()
return list(self._files.keys())
def __len__(self):
'''
@ -142,7 +142,7 @@ class FileRegistry(object):
for path, file in registry:
(...)
'''
return self._files.iteritems()
return iter(self._files.items())
def required_directories(self):
'''
@ -151,7 +151,7 @@ class FileRegistry(object):
unspecified (virtual) root directory (and do not include said root
directory).
'''
return set(k for k, v in self._required_directories.items() if v > 0)
return set(k for k, v in list(self._required_directories.items()) if v > 0)
class FileRegistrySubtree(object):
@ -263,7 +263,7 @@ class FileCopier(FileRegistry):
Returns a FileCopyResult that details what changed.
'''
assert isinstance(destination, basestring)
assert isinstance(destination, str)
assert not os.path.exists(destination) or os.path.isdir(destination)
result = FileCopyResult()
@ -324,9 +324,9 @@ class FileCopier(FileRegistry):
os.mkdir(d)
if not os.access(d, os.W_OK):
umask = os.umask(0077)
umask = os.umask(0o077)
os.umask(umask)
os.chmod(d, 0777 & ~umask)
os.chmod(d, 0o777 & ~umask)
if isinstance(remove_unaccounted, FileRegistry):
existing_files = set(os.path.normpath(os.path.join(destination, p))
@ -412,7 +412,7 @@ class FileCopier(FileRegistry):
if os.name == 'nt' and not os.access(f, os.W_OK):
# It doesn't matter what we set permissions to since we
# will remove this file shortly.
os.chmod(f, 0600)
os.chmod(f, 0o600)
os.remove(f)
result.removed_files.add(f)
@ -454,7 +454,7 @@ class FileCopier(FileRegistry):
if e.errno in (errno.EPERM, errno.EACCES):
# Permissions may not allow deletion. So ensure write
# access is in place before attempting to rmdir again.
os.chmod(d, 0700)
os.chmod(d, 0o700)
os.rmdir(d)
else:
raise
@ -525,7 +525,7 @@ class Jarrer(FileRegistry, BaseFile):
def exists(self):
return self.deflater is not None
if isinstance(dest, basestring):
if isinstance(dest, str):
dest = Dest(dest)
assert isinstance(dest, Dest)

View File

@ -2,7 +2,7 @@
# 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 sys
from contextlib import contextmanager
@ -97,7 +97,7 @@ class ErrorCollector(object):
if self._count is None:
raise ErrorMessage(msg)
self._count += 1
print >>self.out, msg
print(msg, file=self.out)
def fatal(self, msg):
self._handle(self.FATAL, msg)

View File

@ -2,7 +2,7 @@
# 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 os
import struct

View File

@ -2,7 +2,7 @@
# 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 os
@ -54,7 +54,7 @@ else:
def _copyfile(src, dest):
# False indicates `dest` should be overwritten if it exists already.
if isinstance(src, unicode) and isinstance(dest, unicode):
if isinstance(src, str) and isinstance(dest, str):
_CopyFileW(src, dest, False)
elif isinstance(src, str) and isinstance(dest, str):
_CopyFileA(src, dest, False)
@ -145,7 +145,7 @@ class BaseFile(object):
disabled when skip_if_older is False.
Returns whether a copy was actually performed (True) or not (False).
'''
if isinstance(dest, basestring):
if isinstance(dest, str):
dest = Dest(dest)
else:
assert isinstance(dest, Dest)
@ -228,13 +228,13 @@ class File(BaseFile):
# - keep file type (e.g. S_IFREG)
ret = stat.S_IFMT(mode)
# - expand user read and execute permissions to everyone
if mode & 0400:
ret |= 0444
if mode & 0100:
ret |= 0111
if mode & 0o400:
ret |= 0o444
if mode & 0o100:
ret |= 0o111
# - keep user write permissions
if mode & 0200:
ret |= 0200
if mode & 0o200:
ret |= 0o200
# - leave away sticky bit, setuid, setgid
return ret
@ -251,11 +251,11 @@ class ExecutableFile(File):
'''
def copy(self, dest, skip_if_older=True):
real_dest = dest
if not isinstance(dest, basestring):
if not isinstance(dest, str):
fd, dest = mkstemp()
os.close(fd)
os.remove(dest)
assert isinstance(dest, basestring)
assert isinstance(dest, str)
# If File.copy didn't actually copy because dest is newer, check the
# file sizes. If dest is smaller, it means it is already stripped and
# elfhacked, so we can skip.
@ -292,7 +292,7 @@ class AbsoluteSymlinkFile(File):
File.__init__(self, path)
def copy(self, dest, skip_if_older=True):
assert isinstance(dest, basestring)
assert isinstance(dest, str)
# The logic in this function is complicated by the fact that symlinks
# aren't universally supported. So, where symlinks aren't supported, we
@ -393,7 +393,7 @@ class ExistingFile(BaseFile):
self.required = required
def copy(self, dest, skip_if_older=True):
if isinstance(dest, basestring):
if isinstance(dest, str):
dest = Dest(dest)
else:
assert isinstance(dest, Dest)
@ -425,7 +425,7 @@ class PreprocessedFile(BaseFile):
'''
Invokes the preprocessor to create the destination file.
'''
if isinstance(dest, basestring):
if isinstance(dest, str):
dest = Dest(dest)
else:
assert isinstance(dest, Dest)
@ -539,7 +539,7 @@ class XPTFile(GeneratedFile):
the individual XPTs to link.
skip_if_older is ignored.
'''
if isinstance(dest, basestring):
if isinstance(dest, str):
dest = Dest(dest)
assert isinstance(dest, Dest)
@ -966,7 +966,7 @@ class ComposedFinder(BaseFinder):
from mozpack.copier import FileRegistry
self.files = FileRegistry()
for base, finder in sorted(finders.iteritems()):
for base, finder in sorted(finders.items()):
if self.files.contains(base):
self.files.remove(base)
for p, f in finder.find(''):

View File

@ -27,7 +27,7 @@
# do not wish to do so, delete this exception statement from your
# version.
from __future__ import absolute_import
import mercurial.error as error
import mercurial.hg as hg
@ -56,7 +56,7 @@ class MercurialNativeRevisionFinder(BaseFinder):
Accepts a Mercurial localrepo and changectx instance.
"""
if isinstance(repo, (str, unicode)):
if isinstance(repo, str):
path = repo
repo = hg.repository(hgui.ui(), repo)
else:
@ -85,7 +85,7 @@ class MercurialNativeRevisionFinder(BaseFinder):
return self._get(path)
def _get(self, path):
if isinstance(path, unicode):
if isinstance(path, str):
path = path.encode('utf-8', 'replace')
try:

Some files were not shown because too many files have changed in this diff Show More