remove 'six' name except importing line.

This commit is contained in:
Takayuki Shimizukawa 2014-04-30 21:30:46 +09:00
parent f31d9113ff
commit 1e58062692
44 changed files with 126 additions and 143 deletions

View File

@ -19,8 +19,8 @@ import posixpath
import traceback import traceback
from os import path from os import path
import six
from six import iteritems, itervalues from six import iteritems, itervalues
from six.moves import cStringIO
from docutils import nodes from docutils import nodes
from docutils.parsers.rst import convert_directive_function, \ from docutils.parsers.rst import convert_directive_function, \
directives, roles directives, roles
@ -85,14 +85,14 @@ class Sphinx(object):
self.parallel = parallel self.parallel = parallel
if status is None: if status is None:
self._status = six.cStringIO() self._status = cStringIO()
self.quiet = True self.quiet = True
else: else:
self._status = status self._status = status
self.quiet = False self.quiet = False
if warning is None: if warning is None:
self._warning = six.cStringIO() self._warning = cStringIO()
else: else:
self._warning = warning self._warning = warning
self._warncount = 0 self._warncount = 0

View File

@ -17,8 +17,7 @@ import posixpath
from os import path from os import path
from hashlib import md5 from hashlib import md5
import six from six import iteritems, itervalues, text_type, string_types
from six import iteritems, itervalues, text_type
from six.moves import cPickle as pickle from six.moves import cPickle as pickle
from docutils import nodes from docutils import nodes
from docutils.io import DocTreeInput, StringOutput from docutils.io import DocTreeInput, StringOutput
@ -297,7 +296,7 @@ class StandaloneHTMLBuilder(Builder):
if favicon and os.path.splitext(favicon)[1] != '.ico': if favicon and os.path.splitext(favicon)[1] != '.ico':
self.warn('html_favicon is not an .ico file') self.warn('html_favicon is not an .ico file')
if not isinstance(self.config.html_use_opensearch, six.string_types): if not isinstance(self.config.html_use_opensearch, string_types):
self.warn('html_use_opensearch config value must now be a string') self.warn('html_use_opensearch config value must now be a string')
self.relations = self.env.collect_relations() self.relations = self.env.collect_relations()
@ -715,7 +714,7 @@ class StandaloneHTMLBuilder(Builder):
if sidebars is None: if sidebars is None:
# keep defaults # keep defaults
pass pass
elif isinstance(sidebars, six.string_types): elif isinstance(sidebars, string_types):
# 0.x compatible mode: insert custom sidebar before searchbox # 0.x compatible mode: insert custom sidebar before searchbox
customsidebar = sidebars customsidebar = sidebars
sidebars = None sidebars = None

View File

@ -11,7 +11,7 @@
from os import path from os import path
import six from six import string_types
from docutils.io import FileOutput from docutils.io import FileOutput
from docutils.frontend import OptionParser from docutils.frontend import OptionParser
@ -55,7 +55,7 @@ class ManualPageBuilder(Builder):
for info in self.config.man_pages: for info in self.config.man_pages:
docname, name, description, authors, section = info docname, name, description, authors, section = info
if isinstance(authors, six.string_types): if isinstance(authors, string_types):
if authors: if authors:
authors = [authors] authors = [authors]
else: else:

View File

@ -16,8 +16,7 @@ import getopt
import traceback import traceback
from os import path from os import path
import six from six import text_type, binary_type
from six import text_type
from docutils.utils import SystemMessage from docutils.utils import SystemMessage
from sphinx import __version__ from sphinx import __version__
@ -185,7 +184,7 @@ def main(argv):
print('Error: -D option argument must be in the form name=value.', print('Error: -D option argument must be in the form name=value.',
file=sys.stderr) file=sys.stderr)
return 1 return 1
if likely_encoding and isinstance(val, six.binary_type): if likely_encoding and isinstance(val, binary_type):
try: try:
val = val.decode(likely_encoding) val = val.decode(likely_encoding)
except UnicodeError: except UnicodeError:
@ -201,7 +200,7 @@ def main(argv):
try: try:
val = int(val) val = int(val)
except ValueError: except ValueError:
if likely_encoding and isinstance(val, six.binary_type): if likely_encoding and isinstance(val, binary_type):
try: try:
val = val.decode(likely_encoding) val = val.decode(likely_encoding)
except UnicodeError: except UnicodeError:

View File

@ -13,8 +13,7 @@ import os
import re import re
from os import path from os import path
import six from six import PY3, iteritems, string_types, binary_type, integer_types
from six import iteritems, string_types
from sphinx.errors import ConfigError from sphinx.errors import ConfigError
from sphinx.locale import l_ from sphinx.locale import l_
@ -24,7 +23,7 @@ from sphinx.util.pycompat import b, execfile_
nonascii_re = re.compile(b(r'[\x80-\xff]')) nonascii_re = re.compile(b(r'[\x80-\xff]'))
CONFIG_SYNTAX_ERROR = "There is a syntax error in your configuration file: %s" CONFIG_SYNTAX_ERROR = "There is a syntax error in your configuration file: %s"
if six.PY3: if PY3:
CONFIG_SYNTAX_ERROR += "\nDid you change the syntax from 2.x to 3.x?" CONFIG_SYNTAX_ERROR += "\nDid you change the syntax from 2.x to 3.x?"
class Config(object): class Config(object):
@ -245,7 +244,7 @@ class Config(object):
# check all string values for non-ASCII characters in bytestrings, # check all string values for non-ASCII characters in bytestrings,
# since that can result in UnicodeErrors all over the place # since that can result in UnicodeErrors all over the place
for name, value in iteritems(self._raw_config): for name, value in iteritems(self._raw_config):
if isinstance(value, six.binary_type) and nonascii_re.search(value): if isinstance(value, binary_type) and nonascii_re.search(value):
warn('the config value %r is set to a string with non-ASCII ' warn('the config value %r is set to a string with non-ASCII '
'characters; this can lead to Unicode errors occurring. ' 'characters; this can lead to Unicode errors occurring. '
'Please use Unicode strings, e.g. %r.' % (name, u'Content') 'Please use Unicode strings, e.g. %r.' % (name, u'Content')
@ -270,7 +269,7 @@ class Config(object):
continue continue
elif isinstance(defvalue, list): elif isinstance(defvalue, list):
config[valname] = value.split(',') config[valname] = value.split(',')
elif isinstance(defvalue, six.integer_types): elif isinstance(defvalue, integer_types):
try: try:
config[valname] = int(value) config[valname] = int(value)
except ValueError: except ValueError:

View File

@ -22,8 +22,7 @@ from os import path
from glob import glob from glob import glob
from itertools import groupby from itertools import groupby
import six from six import iteritems, itervalues, text_type, class_types
from six import iteritems, itervalues, text_type
from six.moves import cPickle as pickle, zip from six.moves import cPickle as pickle, zip
from docutils import nodes from docutils import nodes
from docutils.io import FileInput, NullOutput from docutils.io import FileInput, NullOutput
@ -141,7 +140,7 @@ class BuildEnvironment:
if key.startswith('_') or \ if key.startswith('_') or \
isinstance(val, types.ModuleType) or \ isinstance(val, types.ModuleType) or \
isinstance(val, types.FunctionType) or \ isinstance(val, types.FunctionType) or \
isinstance(val, six.class_types): isinstance(val, class_types):
del self.config[key] del self.config[key]
try: try:
pickle.dump(self, picklefile, pickle.HIGHEST_PROTOCOL) pickle.dump(self, picklefile, pickle.HIGHEST_PROTOCOL)

View File

@ -17,8 +17,7 @@ import inspect
import traceback import traceback
from types import FunctionType, BuiltinFunctionType, MethodType from types import FunctionType, BuiltinFunctionType, MethodType
import six from six import PY3, iteritems, itervalues, text_type, class_types
from six import iteritems, itervalues, text_type
from docutils import nodes from docutils import nodes
from docutils.utils import assemble_option_dict from docutils.utils import assemble_option_dict
from docutils.statemachine import ViewList from docutils.statemachine import ViewList
@ -1029,7 +1028,7 @@ class ClassDocumenter(ModuleLevelDocumenter):
@classmethod @classmethod
def can_document_member(cls, member, membername, isattr, parent): def can_document_member(cls, member, membername, isattr, parent):
return isinstance(member, six.class_types) return isinstance(member, class_types)
def import_object(self): def import_object(self):
ret = ModuleLevelDocumenter.import_object(self) ret = ModuleLevelDocumenter.import_object(self)
@ -1163,7 +1162,7 @@ class ExceptionDocumenter(ClassDocumenter):
@classmethod @classmethod
def can_document_member(cls, member, membername, isattr, parent): def can_document_member(cls, member, membername, isattr, parent):
return isinstance(member, six.class_types) and \ return isinstance(member, class_types) and \
issubclass(member, BaseException) issubclass(member, BaseException)
@ -1213,7 +1212,7 @@ class MethodDocumenter(DocstringSignatureMixin, ClassLevelDocumenter):
return inspect.isroutine(member) and \ return inspect.isroutine(member) and \
not isinstance(parent, ModuleDocumenter) not isinstance(parent, ModuleDocumenter)
if six.PY3: if PY3:
def import_object(self): def import_object(self):
ret = ClassLevelDocumenter.import_object(self) ret = ClassLevelDocumenter.import_object(self)
obj_from_parent = self.parent.__dict__.get(self.object_name) obj_from_parent = self.parent.__dict__.get(self.object_name)
@ -1283,7 +1282,7 @@ class AttributeDocumenter(ClassLevelDocumenter):
"instancemethod") "instancemethod")
return isdatadesc or (not isinstance(parent, ModuleDocumenter) return isdatadesc or (not isinstance(parent, ModuleDocumenter)
and not inspect.isroutine(member) and not inspect.isroutine(member)
and not isinstance(member, six.class_types)) and not isinstance(member, class_types))
def document_members(self, all_members=False): def document_members(self, all_members=False):
pass pass

View File

@ -18,8 +18,7 @@ from os import path
# circumvent relative import # circumvent relative import
doctest = __import__('doctest') doctest = __import__('doctest')
import six from six import itervalues, StringIO, binary_type
from six import itervalues
from docutils import nodes from docutils import nodes
from docutils.parsers.rst import directives from docutils.parsers.rst import directives
@ -158,7 +157,7 @@ class TestCode(object):
class SphinxDocTestRunner(doctest.DocTestRunner): class SphinxDocTestRunner(doctest.DocTestRunner):
def summarize(self, out, verbose=None): def summarize(self, out, verbose=None):
string_io = six.StringIO() string_io = StringIO()
old_stdout = sys.stdout old_stdout = sys.stdout
sys.stdout = string_io sys.stdout = string_io
try: try:
@ -233,7 +232,7 @@ Results of doctest builder run on %s
self.info(text, nonl=True) self.info(text, nonl=True)
if self.app.quiet: if self.app.quiet:
self.warn(text) self.warn(text)
if isinstance(text, six.binary_type): if isinstance(text, binary_type):
text = force_decode(text, None) text = force_decode(text, None)
self.outfile.write(text) self.outfile.write(text)

View File

@ -11,8 +11,7 @@
import sys import sys
import six from six import PY2, iteritems
from six import iteritems
from sphinx.ext.napoleon.docstring import GoogleDocstring, NumpyDocstring from sphinx.ext.napoleon.docstring import GoogleDocstring, NumpyDocstring
@ -350,7 +349,7 @@ def _skip_member(app, what, name, obj, skip, options):
if name != '__weakref__' and name != '__init__' and has_doc and is_member: if name != '__weakref__' and name != '__init__' and has_doc and is_member:
cls_is_owner = False cls_is_owner = False
if what == 'class' or what == 'exception': if what == 'class' or what == 'exception':
if six.PY2: if PY2:
cls = getattr(obj, 'im_class', getattr(obj, '__objclass__', cls = getattr(obj, 'im_class', getattr(obj, '__objclass__',
None)) None))
cls_is_owner = (cls and hasattr(cls, name) and cls_is_owner = (cls and hasattr(cls, name) and

View File

@ -15,7 +15,7 @@ import collections
import inspect import inspect
import re import re
import six from six import string_types
from six.moves import range from six.moves import range
from sphinx.ext.napoleon.iterators import modify_iter from sphinx.ext.napoleon.iterators import modify_iter
@ -115,7 +115,7 @@ class GoogleDocstring(UnicodeMixin):
self._name = name self._name = name
self._obj = obj self._obj = obj
self._opt = options self._opt = options
if isinstance(docstring, six.string_types): if isinstance(docstring, string_types):
docstring = docstring.splitlines() docstring = docstring.splitlines()
self._lines = docstring self._lines = docstring
self._line_iter = modify_iter(docstring, modifier=lambda s: s.rstrip()) self._line_iter = modify_iter(docstring, modifier=lambda s: s.rstrip())
@ -730,7 +730,7 @@ class NumpyDocstring(GoogleDocstring):
def _is_section_header(self): def _is_section_header(self):
section, underline = self._line_iter.peek(2) section, underline = self._line_iter.peek(2)
section = section.lower() section = section.lower()
if section in self._sections and isinstance(underline, six.string_types): if section in self._sections and isinstance(underline, string_types):
pattern = r'[=\-`:\'"~^_*+#<>]{' + str(len(section)) + r'}$' pattern = r'[=\-`:\'"~^_*+#<>]{' + str(len(section)) + r'}$'
return bool(re.match(pattern, underline)) return bool(re.match(pattern, underline))
elif self._directive_sections: elif self._directive_sections:

View File

@ -13,10 +13,10 @@
import collections import collections
import six from six import PY3
if six.PY3: if PY3:
callable = lambda o: hasattr(o, '__call__') callable = lambda o: hasattr(o, '__call__')

View File

@ -18,8 +18,7 @@ except ImportError:
# parser is not available on Jython # parser is not available on Jython
parser = None parser = None
import six from six import PY2, text_type
from six import text_type
from sphinx.util.pycompat import htmlescape from sphinx.util.pycompat import htmlescape
from sphinx.util.texescape import tex_hl_escape_map_new from sphinx.util.texescape import tex_hl_escape_map_new
@ -133,7 +132,7 @@ class PygmentsBridge(object):
# lines beginning with "..." are probably placeholders for suite # lines beginning with "..." are probably placeholders for suite
src = re.sub(r"(?m)^(\s*)" + mark + "(.)", r"\1"+ mark + r"# \2", src) src = re.sub(r"(?m)^(\s*)" + mark + "(.)", r"\1"+ mark + r"# \2", src)
if six.PY2 and isinstance(src, text_type): if PY2 and isinstance(src, text_type):
# Non-ASCII chars will only occur in string literals # Non-ASCII chars will only occur in string literals
# and comments. If we wanted to give them to the parser # and comments. If we wanted to give them to the parser
# correctly, we'd have to find out the correct source # correctly, we'd have to find out the correct source

View File

@ -12,7 +12,7 @@
from os import path from os import path
from pprint import pformat from pprint import pformat
import six from six import string_types
from jinja2 import FileSystemLoader, BaseLoader, TemplateNotFound, \ from jinja2 import FileSystemLoader, BaseLoader, TemplateNotFound, \
contextfunction contextfunction
from jinja2.utils import open_if_exists from jinja2.utils import open_if_exists
@ -23,7 +23,7 @@ from sphinx.util.osutil import mtimes_of_files
def _tobool(val): def _tobool(val):
if isinstance(val, six.string_types): if isinstance(val, string_types):
return val.lower() in ('true', '1', 'yes', 'on') return val.lower() in ('true', '1', 'yes', 'on')
return bool(val) return bool(val)

View File

@ -11,8 +11,7 @@
import gettext import gettext
import six from six import PY3, text_type
from six import text_type
from six.moves import UserString from six.moves import UserString
@ -185,7 +184,7 @@ pairindextypes = {
translators = {} translators = {}
if six.PY3: if PY3:
def _(message): def _(message):
return translators['sphinx'].gettext(message) return translators['sphinx'].gettext(message)
else: else:

View File

@ -13,8 +13,7 @@ from __future__ import print_function
import sys import sys
from os import path from os import path
import six from six import iteritems, text_type, BytesIO, StringIO
from six import iteritems, text_type
from sphinx import package_dir from sphinx import package_dir
from sphinx.errors import PycodeError from sphinx.errors import PycodeError
@ -177,8 +176,8 @@ class ModuleAnalyzer(object):
@classmethod @classmethod
def for_string(cls, string, modname, srcname='<string>'): def for_string(cls, string, modname, srcname='<string>'):
if isinstance(string, bytes): if isinstance(string, bytes):
return cls(six.BytesIO(string), modname, srcname) return cls(BytesIO(string), modname, srcname)
return cls(six.StringIO(string), modname, srcname, decoded=True) return cls(StringIO(string), modname, srcname, decoded=True)
@classmethod @classmethod
def for_file(cls, filename, modname): def for_file(cls, filename, modname):

View File

@ -26,8 +26,7 @@ try:
except ImportError: except ImportError:
pass pass
import six from six import PY2, PY3, text_type
from six import text_type
from six.moves import input from six.moves import input
from docutils.utils import column_width from docutils.utils import column_width
@ -43,7 +42,7 @@ term_input = input
PROMPT_PREFIX = '> ' PROMPT_PREFIX = '> '
if six.PY3: if PY3:
# prevents that the file is checked for being written in Python 2.x syntax # prevents that the file is checked for being written in Python 2.x syntax
QUICKSTART_CONF = u'#!/usr/bin/env python3\n' QUICKSTART_CONF = u'#!/usr/bin/env python3\n'
else: else:
@ -996,7 +995,7 @@ def do_prompt(d, key, text, default=None, validator=nonempty):
prompt = PROMPT_PREFIX + '%s [%s]: ' % (text, default) prompt = PROMPT_PREFIX + '%s [%s]: ' % (text, default)
else: else:
prompt = PROMPT_PREFIX + text + ': ' prompt = PROMPT_PREFIX + text + ': '
if six.PY2: if PY2:
# for Python 2.x, try to get a Unicode string out of it # for Python 2.x, try to get a Unicode string out of it
if prompt.encode('ascii', 'replace').decode('ascii', 'replace') \ if prompt.encode('ascii', 'replace').decode('ascii', 'replace') \
!= prompt: != prompt:
@ -1036,7 +1035,7 @@ def do_prompt(d, key, text, default=None, validator=nonempty):
d[key] = x d[key] = x
if six.PY3: if PY3:
# remove Unicode literal prefixes # remove Unicode literal prefixes
def _convert_python_source(source, rex=re.compile(r"[uU]('.*?')")): def _convert_python_source(source, rex=re.compile(r"[uU]('.*?')")):
return rex.sub('\\1', source) return rex.sub('\\1', source)

View File

@ -12,8 +12,7 @@ from __future__ import with_statement
import re import re
import six from six import iteritems, itervalues, text_type, string_types
from six import iteritems, itervalues, text_type
from six.moves import cPickle as pickle from six.moves import cPickle as pickle
from docutils.nodes import raw, comment, title, Text, NodeVisitor, SkipNode from docutils.nodes import raw, comment, title, Text, NodeVisitor, SkipNode
@ -239,7 +238,7 @@ class IndexBuilder(object):
def load(self, stream, format): def load(self, stream, format):
"""Reconstruct from frozen data.""" """Reconstruct from frozen data."""
if isinstance(format, six.string_types): if isinstance(format, string_types):
format = self.formats[format] format = self.formats[format]
frozen = format.load(stream) frozen = format.load(stream)
# if an old index is present, we treat it as not existing. # if an old index is present, we treat it as not existing.
@ -264,7 +263,7 @@ class IndexBuilder(object):
def dump(self, stream, format): def dump(self, stream, format):
"""Dump the frozen index to a stream.""" """Dump the frozen index to a stream."""
if isinstance(format, six.string_types): if isinstance(format, string_types):
format = self.formats[format] format = self.formats[format]
format.dump(self.freeze(), stream) format.dump(self.freeze(), stream)

View File

@ -19,7 +19,7 @@ import types
from distutils.cmd import Command from distutils.cmd import Command
from distutils.errors import DistutilsOptionError from distutils.errors import DistutilsOptionError
import six from six import StringIO
from sphinx.application import Sphinx from sphinx.application import Sphinx
from sphinx.util.console import darkred, nocolor, color_terminal from sphinx.util.console import darkred, nocolor, color_terminal
@ -142,7 +142,7 @@ class BuildDoc(Command):
# Windows' poor cmd box doesn't understand ANSI sequences # Windows' poor cmd box doesn't understand ANSI sequences
nocolor() nocolor()
if not self.verbose: if not self.verbose:
status_stream = six.StringIO() status_stream = StringIO()
else: else:
status_stream = sys.stdout status_stream = sys.stdout
confoverrides = {} confoverrides = {}

View File

@ -15,8 +15,7 @@ import zipfile
import tempfile import tempfile
from os import path from os import path
import six from six import string_types, iteritems
from six import iteritems
from six.moves import configparser from six.moves import configparser
try: try:
@ -191,7 +190,7 @@ def load_theme_plugins():
except: except:
path = func_or_path path = func_or_path
if isinstance(path, six.string_types): if isinstance(path, string_types):
theme_paths.append(path) theme_paths.append(path)
else: else:
raise ThemeError('Plugin %r does not response correctly.' % raise ThemeError('Plugin %r does not response correctly.' %

View File

@ -21,8 +21,7 @@ from os import path
from codecs import open, BOM_UTF8 from codecs import open, BOM_UTF8
from collections import deque from collections import deque
import six from six import iteritems, text_type, binary_type
from six import iteritems, text_type
from six.moves import range from six.moves import range
import docutils import docutils
from docutils.utils import relative_path from docutils.utils import relative_path
@ -337,7 +336,7 @@ def parselinenos(spec, total):
def force_decode(string, encoding): def force_decode(string, encoding):
"""Forcibly get a unicode string out of a bytestring.""" """Forcibly get a unicode string out of a bytestring."""
if isinstance(string, six.binary_type): if isinstance(string, binary_type):
try: try:
if encoding: if encoding:
string = string.decode(encoding) string = string.decode(encoding)

View File

@ -13,12 +13,13 @@
# relatively import this module # relatively import this module
inspect = __import__('inspect') inspect = __import__('inspect')
import six from six import PY3, binary_type
from six.moves import builtins
from sphinx.util import force_decode from sphinx.util import force_decode
if six.PY3: if PY3:
from functools import partial from functools import partial
def getargspec(func): def getargspec(func):
"""Like inspect.getargspec but supports functools.partial as well.""" """Like inspect.getargspec but supports functools.partial as well."""
@ -128,7 +129,7 @@ def safe_repr(object):
s = repr(object) s = repr(object)
except Exception: except Exception:
raise ValueError raise ValueError
if isinstance(s, six.binary_type): if isinstance(s, binary_type):
return force_decode(s, None).replace('\n', ' ') return force_decode(s, None).replace('\n', ' ')
return s.replace('\n', ' ') return s.replace('\n', ' ')
@ -145,6 +146,6 @@ def is_builtin_class_method(obj, attr_name):
classes = [c for c in inspect.getmro(obj) if attr_name in c.__dict__] classes = [c for c in inspect.getmro(obj) if attr_name in c.__dict__]
cls = classes[0] if classes else object cls = classes[0] if classes else object
if not hasattr(six.moves.builtins, safe_getattr(cls, '__name__', '')): if not hasattr(builtins, safe_getattr(cls, '__name__', '')):
return False return False
return getattr(six.moves.builtins, safe_getattr(cls, '__name__', '')) is cls return getattr(builtins, safe_getattr(cls, '__name__', '')) is cls

View File

@ -12,8 +12,7 @@
import re import re
import six from six import iteritems, integer_types, string_types
from six import iteritems, integer_types
from sphinx.util.pycompat import u from sphinx.util.pycompat import u
@ -77,7 +76,7 @@ double in super""".split())
def dumps(obj, key=False): def dumps(obj, key=False):
if key: if key:
if not isinstance(obj, six.string_types): if not isinstance(obj, string_types):
obj = str(obj) obj = str(obj)
if _nameonly_re.match(obj) and obj not in reswords: if _nameonly_re.match(obj) and obj not in reswords:
return obj # return it as a bare word return obj # return it as a bare word
@ -96,7 +95,7 @@ def dumps(obj, key=False):
) for key, value in iteritems(obj)) ) for key, value in iteritems(obj))
elif isinstance(obj, (tuple, list, set)): elif isinstance(obj, (tuple, list, set)):
return '[%s]' % ','.join(dumps(x) for x in obj) return '[%s]' % ','.join(dumps(x) for x in obj)
elif isinstance(obj, six.string_types): elif isinstance(obj, string_types):
return encode_string(obj) return encode_string(obj)
raise TypeError(type(obj)) raise TypeError(type(obj))

View File

@ -20,8 +20,7 @@ import shutil
import gettext import gettext
from os import path from os import path
import six from six import PY2, text_type
from six import text_type
# Errnos that we need. # Errnos that we need.
EEXIST = getattr(errno, 'EEXIST', 0) EEXIST = getattr(errno, 'EEXIST', 0)
@ -150,7 +149,7 @@ no_fn_re = re.compile(r'[^a-zA-Z0-9_-]')
def make_filename(string): def make_filename(string):
return no_fn_re.sub('', string) or 'sphinx' return no_fn_re.sub('', string) or 'sphinx'
if six.PY2: if PY2:
# strftime for unicode strings # strftime for unicode strings
def ustrftime(format, *args): def ustrftime(format, *args):
# if a locale is set, the time strings are encoded in the encoding # if a locale is set, the time strings are encoded in the encoding
@ -190,7 +189,7 @@ def find_catalog_files(docname, srcdir, locale_dirs, lang, compaction):
fs_encoding = sys.getfilesystemencoding() or sys.getdefaultencoding() fs_encoding = sys.getfilesystemencoding() or sys.getdefaultencoding()
if six.PY2: if PY2:
bytes = str bytes = str
else: else:
bytes = bytes bytes = bytes

View File

@ -12,12 +12,12 @@
import sys import sys
import codecs import codecs
import six from six import PY3, text_type, exec_
# ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------
# Python 2/3 compatibility # Python 2/3 compatibility
if six.PY3: if PY3:
# Python 3 # Python 3
# the ubiquitous "bytes" helper functions # the ubiquitous "bytes" helper functions
def b(s): def b(s):
@ -45,7 +45,7 @@ if six.PY3:
lineno, offset = err.context[1] lineno, offset = err.context[1]
# try to match ParseError details with SyntaxError details # try to match ParseError details with SyntaxError details
raise SyntaxError(err.msg, (filepath, lineno, offset, err.value)) raise SyntaxError(err.msg, (filepath, lineno, offset, err.value))
return six.text_type(tree) return text_type(tree)
from html import escape as htmlescape # >= Python 3.2 from html import escape as htmlescape # >= Python 3.2
class UnicodeMixin: class UnicodeMixin:
@ -106,4 +106,4 @@ def execfile_(filepath, _globals):
code = compile(source, filepath_enc, 'exec') code = compile(source, filepath_enc, 'exec')
else: else:
raise raise
six.exec_(code, _globals) exec_(code, _globals)

View File

@ -14,7 +14,7 @@ import posixpath
import os import os
import copy import copy
import six from six import string_types
from docutils import nodes from docutils import nodes
from docutils.writers.html4css1 import Writer, HTMLTranslator as BaseTranslator from docutils.writers.html4css1 import Writer, HTMLTranslator as BaseTranslator
@ -75,7 +75,7 @@ class HTMLTranslator(BaseTranslator):
self.protect_literal_text = 0 self.protect_literal_text = 0
self.permalink_text = builder.config.html_add_permalinks self.permalink_text = builder.config.html_add_permalinks
# support backwards-compatible setting to a bool # support backwards-compatible setting to a bool
if not isinstance(self.permalink_text, six.string_types): if not isinstance(self.permalink_text, string_types):
self.permalink_text = self.permalink_text and u'\u00B6' or '' self.permalink_text = self.permalink_text and u'\u00B6' or ''
self.permalink_text = self.encode(self.permalink_text) self.permalink_text = self.encode(self.permalink_text)
self.secnumber_suffix = builder.config.html_secnumber_suffix self.secnumber_suffix = builder.config.html_secnumber_suffix

View File

@ -72,7 +72,7 @@ import token
import zipimport import zipimport
from socket import gethostname from socket import gethostname
import six from six import string_types
# 2. IMPLEMENTATION # 2. IMPLEMENTATION
@ -841,7 +841,7 @@ class coverage:
# On windows, the shell doesn't expand wildcards. Do it here. # On windows, the shell doesn't expand wildcards. Do it here.
globbed = [] globbed = []
for morf in morfs: for morf in morfs:
if isinstance(morf, six.string_types): if isinstance(morf, string_types):
globbed.extend(glob.glob(morf)) globbed.extend(glob.glob(morf))
else: else:
globbed.append(morf) globbed.append(morf)

View File

@ -81,7 +81,7 @@
from __future__ import generators from __future__ import generators
from __future__ import absolute_import from __future__ import absolute_import
import six from six import string_types
__all__ = [ __all__ = [
@ -831,7 +831,7 @@ def _namespaces(elem, encoding, default_namespace=None):
tag = elem.tag tag = elem.tag
if isinstance(tag, QName) and tag.text not in qnames: if isinstance(tag, QName) and tag.text not in qnames:
add_qname(tag.text) add_qname(tag.text)
elif isinstance(tag, six.string_types): elif isinstance(tag, string_types):
if tag not in qnames: if tag not in qnames:
add_qname(tag) add_qname(tag)
elif tag is not None and tag is not Comment and tag is not PI: elif tag is not None and tag is not Comment and tag is not PI:

View File

@ -12,8 +12,7 @@ import sys
import shutil import shutil
from codecs import open from codecs import open
import six from six import PY2, text_type
from six import text_type
FILESYSTEMENCODING = sys.getfilesystemencoding() or sys.getdefaultencoding() FILESYSTEMENCODING = sys.getfilesystemencoding() or sys.getdefaultencoding()
@ -23,7 +22,7 @@ class path(text_type):
""" """
Represents a path which behaves like a string. Represents a path which behaves like a string.
""" """
if six.PY2: if PY2:
def __new__(cls, s, encoding=FILESYSTEMENCODING, errors='strict'): def __new__(cls, s, encoding=FILESYSTEMENCODING, errors='strict'):
if isinstance(s, str): if isinstance(s, str):
s = s.decode(encoding, errors) s = s.decode(encoding, errors)

View File

@ -15,7 +15,7 @@ import sys
from os import path, chdir, listdir, environ from os import path, chdir, listdir, environ
import shutil import shutil
import six from six import PY3
testroot = path.dirname(__file__) or '.' testroot = path.dirname(__file__) or '.'
@ -29,7 +29,7 @@ else:
shutil.rmtree(newroot, ignore_errors=True) shutil.rmtree(newroot, ignore_errors=True)
if six.PY3: if PY3:
print('Copying and converting sources to build/lib/tests...') print('Copying and converting sources to build/lib/tests...')
from distutils.util import copydir_run_2to3 from distutils.util import copydir_run_2to3
copydir_run_2to3(testroot, newroot) copydir_run_2to3(testroot, newroot)

View File

@ -9,7 +9,7 @@
:license: BSD, see LICENSE for details. :license: BSD, see LICENSE for details.
""" """
import six from six import StringIO
from docutils import nodes from docutils import nodes
from sphinx.application import ExtensionError from sphinx.application import ExtensionError
@ -49,7 +49,7 @@ def test_emit_with_nonascii_name_node(app):
def test_output(): def test_output():
status, warnings = six.StringIO(), six.StringIO() status, warnings = StringIO(), StringIO()
app = TestApp(status=status, warning=warnings) app = TestApp(status=status, warning=warnings)
try: try:
status.truncate(0) # __init__ writes to status status.truncate(0) # __init__ writes to status
@ -70,7 +70,7 @@ def test_output():
def test_extensions(): def test_extensions():
status, warnings = six.StringIO(), six.StringIO() status, warnings = StringIO(), StringIO()
app = TestApp(status=status, warning=warnings) app = TestApp(status=status, warning=warnings)
try: try:
app.setup_extension('shutil') app.setup_extension('shutil')
@ -85,7 +85,7 @@ def test_domain_override():
name = 'foo' name = 'foo'
class C(Domain): class C(Domain):
name = 'foo' name = 'foo'
status, warnings = six.StringIO(), six.StringIO() status, warnings = StringIO(), StringIO()
app = TestApp(status=status, warning=warnings) app = TestApp(status=status, warning=warnings)
try: try:
# No domain know named foo. # No domain know named foo.

View File

@ -14,7 +14,7 @@
from util import TestApp, Struct, raises from util import TestApp, Struct, raises
from nose.tools import with_setup from nose.tools import with_setup
import six from six import StringIO
from docutils.statemachine import ViewList from docutils.statemachine import ViewList
from sphinx.ext.autodoc import AutoDirective, add_documenter, \ from sphinx.ext.autodoc import AutoDirective, add_documenter, \
@ -809,7 +809,7 @@ class Class(Base):
u"""should be documented as well - süß""" u"""should be documented as well - süß"""
# initialized to any class imported from another module # initialized to any class imported from another module
mdocattr = six.StringIO() mdocattr = StringIO()
"""should be documented as well - süß""" """should be documented as well - süß"""
roger = _funky_classmethod("roger", 2, 3, 4) roger = _funky_classmethod("roger", 2, 3, 4)

View File

@ -12,8 +12,7 @@
import os import os
import re import re
import six from six import PY3, iteritems, StringIO
from six import iteritems
from six.moves import html_entities from six.moves import html_entities
try: try:
@ -30,7 +29,7 @@ def teardown_module():
(test_root / '_build').rmtree(True) (test_root / '_build').rmtree(True)
html_warnfile = six.StringIO() html_warnfile = StringIO()
ENV_WARNINGS = """\ ENV_WARNINGS = """\
%(root)s/autodoc_fodder.py:docstring of autodoc_fodder\\.MarkupError:2: \ %(root)s/autodoc_fodder.py:docstring of autodoc_fodder\\.MarkupError:2: \
@ -55,7 +54,7 @@ None:\\d+: WARNING: citation not found: missing
%(root)s/markup.txt:: WARNING: invalid pair index entry u'keyword; ' %(root)s/markup.txt:: WARNING: invalid pair index entry u'keyword; '
""" """
if six.PY3: if PY3:
ENV_WARNINGS = remove_unicode_literals(ENV_WARNINGS) ENV_WARNINGS = remove_unicode_literals(ENV_WARNINGS)
HTML_WARNINGS = remove_unicode_literals(HTML_WARNINGS) HTML_WARNINGS = remove_unicode_literals(HTML_WARNINGS)

View File

@ -14,7 +14,7 @@ import os
import re import re
from subprocess import Popen, PIPE from subprocess import Popen, PIPE
import six from six import PY3, StringIO
from sphinx.writers.latex import LaTeXTranslator from sphinx.writers.latex import LaTeXTranslator
@ -26,7 +26,7 @@ def teardown_module():
(test_root / '_build').rmtree(True) (test_root / '_build').rmtree(True)
latex_warnfile = six.StringIO() latex_warnfile = StringIO()
LATEX_WARNINGS = ENV_WARNINGS + """\ LATEX_WARNINGS = ENV_WARNINGS + """\
None:None: WARNING: citation not found: missing None:None: WARNING: citation not found: missing
@ -35,7 +35,7 @@ WARNING: invalid pair index entry u''
WARNING: invalid pair index entry u'keyword; ' WARNING: invalid pair index entry u'keyword; '
""" """
if six.PY3: if PY3:
LATEX_WARNINGS = remove_unicode_literals(LATEX_WARNINGS) LATEX_WARNINGS = remove_unicode_literals(LATEX_WARNINGS)

View File

@ -14,7 +14,7 @@ import os
import re import re
from subprocess import Popen, PIPE from subprocess import Popen, PIPE
import six from six import PY3, StringIO
from sphinx.writers.texinfo import TexinfoTranslator from sphinx.writers.texinfo import TexinfoTranslator
@ -26,7 +26,7 @@ def teardown_module():
(test_root / '_build').rmtree(True) (test_root / '_build').rmtree(True)
texinfo_warnfile = six.StringIO() texinfo_warnfile = StringIO()
TEXINFO_WARNINGS = ENV_WARNINGS + """\ TEXINFO_WARNINGS = ENV_WARNINGS + """\
None:None: WARNING: citation not found: missing None:None: WARNING: citation not found: missing
@ -34,7 +34,7 @@ None:None: WARNING: no matching candidate for image URI u'foo.\\*'
None:None: WARNING: no matching candidate for image URI u'svgimg.\\*' None:None: WARNING: no matching candidate for image URI u'svgimg.\\*'
""" """
if six.PY3: if PY3:
TEXINFO_WARNINGS = remove_unicode_literals(TEXINFO_WARNINGS) TEXINFO_WARNINGS = remove_unicode_literals(TEXINFO_WARNINGS)

View File

@ -9,7 +9,7 @@
:copyright: Copyright 2007-2014 by the Sphinx team, see AUTHORS. :copyright: Copyright 2007-2014 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details. :license: BSD, see LICENSE for details.
""" """
import six from six import PY3
from util import TestApp, with_app, with_tempdir, raises, raises_msg from util import TestApp, with_app, with_tempdir, raises, raises_msg
@ -101,7 +101,7 @@ def test_errors_warnings(dir):
# test the warning for bytestrings with non-ascii content # test the warning for bytestrings with non-ascii content
# bytestrings with non-ascii content are a syntax error in python3 so we # bytestrings with non-ascii content are a syntax error in python3 so we
# skip the test there # skip the test there
if six.PY3: if PY3:
return return
(dir / 'conf.py').write_text( (dir / 'conf.py').write_text(
u'# -*- coding: latin-1\nproject = "fooä"\n', encoding='latin-1') u'# -*- coding: latin-1\nproject = "fooä"\n', encoding='latin-1')

View File

@ -12,12 +12,12 @@ from __future__ import print_function
import sys import sys
import six from six import StringIO
from util import with_app from util import with_app
status = six.StringIO() status = StringIO()
cleanup_called = 0 cleanup_called = 0
@with_app(buildername='doctest', status=status) @with_app(buildername='doctest', status=status)

View File

@ -13,12 +13,12 @@ import os
import re import re
from functools import wraps from functools import wraps
import six from six import StringIO
from util import test_roots, TestApp from util import test_roots, TestApp
html_warnfile = six.StringIO() html_warnfile = StringIO()
root = test_roots / 'test-docutilsconf' root = test_roots / 'test-docutilsconf'

View File

@ -8,7 +8,7 @@
:copyright: Copyright 2007-2014 by the Sphinx team, see AUTHORS. :copyright: Copyright 2007-2014 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details. :license: BSD, see LICENSE for details.
""" """
import six from six import PY3
from util import TestApp, remove_unicode_literals, path from util import TestApp, remove_unicode_literals, path
@ -57,7 +57,7 @@ def test_images():
htmlbuilder.imgpath = 'dummy' htmlbuilder.imgpath = 'dummy'
htmlbuilder.post_process_images(tree) htmlbuilder.post_process_images(tree)
image_uri_message = "no matching candidate for image URI u'foo.*'" image_uri_message = "no matching candidate for image URI u'foo.*'"
if six.PY3: if PY3:
image_uri_message = remove_unicode_literals(image_uri_message) image_uri_message = remove_unicode_literals(image_uri_message)
assert image_uri_message in app._warning.content[-1] assert image_uri_message in app._warning.content[-1]
assert set(htmlbuilder.images.keys()) == \ assert set(htmlbuilder.images.keys()) == \

View File

@ -12,7 +12,7 @@
import zlib import zlib
import posixpath import posixpath
import six from six import BytesIO
from docutils import nodes from docutils import nodes
from sphinx import addnodes from sphinx import addnodes
@ -45,7 +45,7 @@ a term std:term -1 glossary.html#term-a-term -
def test_read_inventory_v1(): def test_read_inventory_v1():
f = six.BytesIO(inventory_v1) f = BytesIO(inventory_v1)
f.readline() f.readline()
invdata = read_inventory_v1(f, '/util', posixpath.join) invdata = read_inventory_v1(f, '/util', posixpath.join)
assert invdata['py:module']['module'] == \ assert invdata['py:module']['module'] == \
@ -55,12 +55,12 @@ def test_read_inventory_v1():
def test_read_inventory_v2(): def test_read_inventory_v2():
f = six.BytesIO(inventory_v2) f = BytesIO(inventory_v2)
f.readline() f.readline()
invdata1 = read_inventory_v2(f, '/util', posixpath.join) invdata1 = read_inventory_v2(f, '/util', posixpath.join)
# try again with a small buffer size to test the chunking algorithm # try again with a small buffer size to test the chunking algorithm
f = six.BytesIO(inventory_v2) f = BytesIO(inventory_v2)
f.readline() f.readline()
invdata2 = read_inventory_v2(f, '/util', posixpath.join, bufsize=5) invdata2 = read_inventory_v2(f, '/util', posixpath.join, bufsize=5)

View File

@ -16,12 +16,12 @@ import re
from subprocess import Popen, PIPE from subprocess import Popen, PIPE
from xml.etree import ElementTree from xml.etree import ElementTree
import six from six import StringIO, string_types
from util import test_roots, path, with_app, SkipTest from util import test_roots, path, with_app, SkipTest
warnfile = six.StringIO() warnfile = StringIO()
root = test_roots / 'test-intl' root = test_roots / 'test-intl'
doctreedir = root / '_build' / 'doctree' doctreedir = root / '_build' / 'doctree'
@ -77,7 +77,7 @@ def elem_gettexts(elem):
# this function copied from Python-2.7 'ElementTree.itertext'. # this function copied from Python-2.7 'ElementTree.itertext'.
# for compatibility to Python-2.6 # for compatibility to Python-2.6
tag = self.tag tag = self.tag
if not isinstance(tag, six.string_types) and tag is not None: if not isinstance(tag, string_types) and tag is not None:
return return
if self.text: if self.text:
yield self.text yield self.text

View File

@ -12,8 +12,8 @@
import sys import sys
import time import time
import six from six import PY2, text_type, StringIO
from six import text_type from six.moves import input
from util import raises, with_tempdir, SkipTest from util import raises, with_tempdir, SkipTest
@ -23,7 +23,7 @@ from sphinx.util.console import nocolor, coloron
from sphinx.util.pycompat import execfile_ from sphinx.util.pycompat import execfile_
warnfile = six.StringIO() warnfile = StringIO()
def setup_module(): def setup_module():
@ -31,12 +31,12 @@ def setup_module():
def mock_input(answers, needanswer=False): def mock_input(answers, needanswer=False):
called = set() called = set()
def input(prompt): def input_(prompt):
if prompt in called: if prompt in called:
raise AssertionError('answer for %r missing and no default ' raise AssertionError('answer for %r missing and no default '
'present' % prompt) 'present' % prompt)
called.add(prompt) called.add(prompt)
if six.PY2: if PY2:
prompt = str(prompt) # Python2.x raw_input emulation prompt = str(prompt) # Python2.x raw_input emulation
# `raw_input` encode `prompt` by default encoding to print. # `raw_input` encode `prompt` by default encoding to print.
else: else:
@ -48,9 +48,9 @@ def mock_input(answers, needanswer=False):
if needanswer: if needanswer:
raise AssertionError('answer for %r missing' % prompt) raise AssertionError('answer for %r missing' % prompt)
return '' return ''
return input return input_
real_input = six.moves.input real_input = input
def teardown_module(): def teardown_module():
qs.term_input = real_input qs.term_input = real_input
@ -262,7 +262,7 @@ def test_quickstart_and_build(tempdir):
(tempdir / '_build' / 'html'), #outdir (tempdir / '_build' / 'html'), #outdir
(tempdir / '_build' / '.doctree'), #doctreedir (tempdir / '_build' / '.doctree'), #doctreedir
'html', #buildername 'html', #buildername
status=six.StringIO(), status=StringIO(),
warning=warnfile) warning=warnfile)
app.builder.build_all() app.builder.build_all()
warnings = warnfile.getvalue() warnings = warnfile.getvalue()

View File

@ -11,7 +11,7 @@
import os import os
import six from six import StringIO
from sphinx.websupport import WebSupport from sphinx.websupport import WebSupport
@ -32,8 +32,8 @@ def search_adapter_helper(adapter):
clear_builddir() clear_builddir()
settings = {'builddir': os.path.join(test_root, 'websupport'), settings = {'builddir': os.path.join(test_root, 'websupport'),
'status': six.StringIO(), 'status': StringIO(),
'warning': six.StringIO()} 'warning': StringIO()}
settings.update({'srcdir': test_root, settings.update({'srcdir': test_root,
'search': adapter}) 'search': adapter})
support = WebSupport(**settings) support = WebSupport(**settings)

View File

@ -12,7 +12,7 @@
import os import os
from functools import wraps from functools import wraps
import six from six import StringIO
from sphinx.websupport import WebSupport from sphinx.websupport import WebSupport
from sphinx.websupport.errors import DocumentNotFoundError, \ from sphinx.websupport.errors import DocumentNotFoundError, \
@ -31,8 +31,8 @@ from util import test_root, raises, skip_if
default_settings = {'builddir': os.path.join(test_root, 'websupport'), default_settings = {'builddir': os.path.join(test_root, 'websupport'),
'status': six.StringIO(), 'status': StringIO(),
'warning': six.StringIO()} 'warning': StringIO()}
def teardown_module(): def teardown_module():
(test_root / 'generated').rmtree(True) (test_root / 'generated').rmtree(True)

View File

@ -13,7 +13,7 @@ import shutil
import re import re
from functools import wraps from functools import wraps
import six from six import StringIO
from sphinx import application from sphinx import application
from sphinx.theming import Theme from sphinx.theming import Theme
@ -163,7 +163,7 @@ class TestApp(application.Sphinx):
if confoverrides is None: if confoverrides is None:
confoverrides = {} confoverrides = {}
if status is None: if status is None:
status = six.StringIO() status = StringIO()
if warning is None: if warning is None:
warning = ListOutput('stderr') warning = ListOutput('stderr')
if freshenv is None: if freshenv is None: