summaryrefslogtreecommitdiff
path: root/sphinx/builders
diff options
context:
space:
mode:
authorTakeshi KOMIYA <i.tkomiya@gmail.com>2016-05-26 00:27:07 +0900
committerTakeshi KOMIYA <i.tkomiya@gmail.com>2016-05-26 00:50:57 +0900
commit698a715d0c905079b215034d04cb3f1d8e809dd5 (patch)
treeb78c56a74ce3960214c6e51d775846c09e0d288f /sphinx/builders
parentebc888d709ec8812bf6e158f919f6da23d38595c (diff)
downloadsphinx-git-698a715d0c905079b215034d04cb3f1d8e809dd5.tar.gz
Refactor code using ``with`` syntax
Diffstat (limited to 'sphinx/builders')
-rw-r--r--sphinx/builders/applehelp.py5
-rw-r--r--sphinx/builders/changes.py31
-rw-r--r--sphinx/builders/devhelp.py5
-rw-r--r--sphinx/builders/epub.py20
-rw-r--r--sphinx/builders/epub3.py10
-rw-r--r--sphinx/builders/gettext.py6
-rw-r--r--sphinx/builders/html.py32
-rw-r--r--sphinx/builders/htmlhelp.py20
-rw-r--r--sphinx/builders/qthelp.py10
-rw-r--r--sphinx/builders/texinfo.py5
-rw-r--r--sphinx/builders/text.py5
-rw-r--r--sphinx/builders/xml.py5
12 files changed, 37 insertions, 117 deletions
diff --git a/sphinx/builders/applehelp.py b/sphinx/builders/applehelp.py
index 53a0c99ad..d3ad861dc 100644
--- a/sphinx/builders/applehelp.py
+++ b/sphinx/builders/applehelp.py
@@ -178,14 +178,11 @@ class AppleHelpBuilder(StandaloneHTMLBuilder):
# Build the access page
self.info(bold('building access page...'), nonl=True)
- f = codecs.open(path.join(language_dir, '_access.html'), 'w')
- try:
+ with codecs.open(path.join(language_dir, '_access.html'), 'w') as f:
f.write(access_page_template % {
'toc': htmlescape(toc, quote=True),
'title': htmlescape(self.config.applehelp_title)
})
- finally:
- f.close()
self.info('done')
# Generate the help index
diff --git a/sphinx/builders/changes.py b/sphinx/builders/changes.py
index c077b7dd2..ed9edc403 100644
--- a/sphinx/builders/changes.py
+++ b/sphinx/builders/changes.py
@@ -101,16 +101,10 @@ class ChangesBuilder(Builder):
'show_copyright': self.config.html_show_copyright,
'show_sphinx': self.config.html_show_sphinx,
}
- f = codecs.open(path.join(self.outdir, 'index.html'), 'w', 'utf8')
- try:
+ with codecs.open(path.join(self.outdir, 'index.html'), 'w', 'utf8') as f:
f.write(self.templates.render('changes/frameset.html', ctx))
- finally:
- f.close()
- f = codecs.open(path.join(self.outdir, 'changes.html'), 'w', 'utf8')
- try:
+ with codecs.open(path.join(self.outdir, 'changes.html'), 'w', 'utf8') as f:
f.write(self.templates.render('changes/versionchanges.html', ctx))
- finally:
- f.close()
hltext = ['.. versionadded:: %s' % version,
'.. versionchanged:: %s' % version,
@@ -126,27 +120,22 @@ class ChangesBuilder(Builder):
self.info(bold('copying source files...'))
for docname in self.env.all_docs:
- f = codecs.open(self.env.doc2path(docname), 'r',
- self.env.config.source_encoding)
- try:
- lines = f.readlines()
- except UnicodeDecodeError:
- self.warn('could not read %r for changelog creation' % docname)
- continue
- finally:
- f.close()
+ with codecs.open(self.env.doc2path(docname), 'r',
+ self.env.config.source_encoding) as f:
+ try:
+ lines = f.readlines()
+ except UnicodeDecodeError:
+ self.warn('could not read %r for changelog creation' % docname)
+ continue
targetfn = path.join(self.outdir, 'rst', os_path(docname)) + '.html'
ensuredir(path.dirname(targetfn))
- f = codecs.open(targetfn, 'w', 'utf-8')
- try:
+ with codecs.open(targetfn, 'w', 'utf-8') as f:
text = ''.join(hl(i+1, line) for (i, line) in enumerate(lines))
ctx = {
'filename': self.env.doc2path(docname, None),
'text': text
}
f.write(self.templates.render('changes/rstsource.html', ctx))
- finally:
- f.close()
themectx = dict(('theme_' + key, val) for (key, val) in
iteritems(self.theme.get_options({})))
copy_static_entry(path.join(package_dir, 'themes', 'default',
diff --git a/sphinx/builders/devhelp.py b/sphinx/builders/devhelp.py
index 5ebaf2dc5..9f95de0e1 100644
--- a/sphinx/builders/devhelp.py
+++ b/sphinx/builders/devhelp.py
@@ -127,8 +127,5 @@ class DevhelpBuilder(StandaloneHTMLBuilder):
write_index(title, refs, subitems)
# Dump the XML file
- f = comp_open(path.join(outdir, outname + '.devhelp'), 'w')
- try:
+ with comp_open(path.join(outdir, outname + '.devhelp'), 'w') as f:
tree.write(f, 'utf-8')
- finally:
- f.close()
diff --git a/sphinx/builders/epub.py b/sphinx/builders/epub.py
index cc839d757..349574ae0 100644
--- a/sphinx/builders/epub.py
+++ b/sphinx/builders/epub.py
@@ -496,11 +496,8 @@ class EpubBuilder(StandaloneHTMLBuilder):
def build_mimetype(self, outdir, outname):
"""Write the metainfo file mimetype."""
self.info('writing %s file...' % outname)
- f = codecs.open(path.join(outdir, outname), 'w', 'utf-8')
- try:
+ with codecs.open(path.join(outdir, outname), 'w', 'utf-8') as f:
f.write(self.mimetype_template)
- finally:
- f.close()
def build_container(self, outdir, outname):
"""Write the metainfo file META-INF/cointainer.xml."""
@@ -511,11 +508,8 @@ class EpubBuilder(StandaloneHTMLBuilder):
except OSError as err:
if err.errno != EEXIST:
raise
- f = codecs.open(path.join(outdir, outname), 'w', 'utf-8')
- try:
+ with codecs.open(path.join(outdir, outname), 'w', 'utf-8') as f:
f.write(self.container_template)
- finally:
- f.close()
def content_metadata(self, files, spine, guide):
"""Create a dictionary with all metadata for the content.opf
@@ -652,12 +646,9 @@ class EpubBuilder(StandaloneHTMLBuilder):
guide = '\n'.join(guide)
# write the project file
- f = codecs.open(path.join(outdir, outname), 'w', 'utf-8')
- try:
+ with codecs.open(path.join(outdir, outname), 'w', 'utf-8') as f:
f.write(content_tmpl %
self.content_metadata(projectfiles, spine, guide))
- finally:
- f.close()
def new_navpoint(self, node, level, incr=True):
"""Create a new entry in the toc from the node at given level."""
@@ -749,11 +740,8 @@ class EpubBuilder(StandaloneHTMLBuilder):
navpoints = self.build_navpoints(refnodes)
level = max(item['level'] for item in self.refnodes)
level = min(level, self.config.epub_tocdepth)
- f = codecs.open(path.join(outdir, outname), 'w', 'utf-8')
- try:
+ with codecs.open(path.join(outdir, outname), 'w', 'utf-8') as f:
f.write(self.toc_template % self.toc_metadata(level, navpoints))
- finally:
- f.close()
def build_epub(self, outdir, outname):
"""Write the epub file.
diff --git a/sphinx/builders/epub3.py b/sphinx/builders/epub3.py
index 0fd347735..b243486f6 100644
--- a/sphinx/builders/epub3.py
+++ b/sphinx/builders/epub3.py
@@ -203,11 +203,9 @@ class Epub3Builder(EpubBuilder):
# 'includehidden'
refnodes = self.refnodes
navlist = self.build_navlist(refnodes)
- f = codecs.open(path.join(outdir, outname), 'w', 'utf-8')
- try:
+ with codecs.open(path.join(outdir, outname), 'w', 'utf-8') as f:
f.write(self.navigation_doc_template %
self.navigation_doc_metadata(navlist))
- finally:
- f.close()
- # Add nav.xhtml to epub file
- self.files.append(outname)
+
+ # Add nav.xhtml to epub file
+ self.files.append(outname)
diff --git a/sphinx/builders/gettext.py b/sphinx/builders/gettext.py
index 1c4789392..c8f4dab4f 100644
--- a/sphinx/builders/gettext.py
+++ b/sphinx/builders/gettext.py
@@ -211,8 +211,7 @@ class MessageCatalogBuilder(I18nBuilder):
ensuredir(path.join(self.outdir, path.dirname(textdomain)))
pofn = path.join(self.outdir, textdomain + '.pot')
- pofile = open(pofn, 'w', encoding='utf-8')
- try:
+ with open(pofn, 'w', encoding='utf-8') as pofile:
pofile.write(POHEADER % data)
for message in catalog.messages:
@@ -234,6 +233,3 @@ class MessageCatalogBuilder(I18nBuilder):
replace('"', r'\"'). \
replace('\n', '\\n"\n"')
pofile.write('msgid "%s"\nmsgstr ""\n\n' % message)
-
- finally:
- pofile.close()
diff --git a/sphinx/builders/html.py b/sphinx/builders/html.py
index f541daa1a..dbde1972b 100644
--- a/sphinx/builders/html.py
+++ b/sphinx/builders/html.py
@@ -175,8 +175,7 @@ class StandaloneHTMLBuilder(Builder):
self.tags_hash = get_stable_hash(sorted(self.tags))
old_config_hash = old_tags_hash = ''
try:
- fp = open(path.join(self.outdir, '.buildinfo'))
- try:
+ with open(path.join(self.outdir, '.buildinfo')) as f:
version = fp.readline()
if version.rstrip() != '# Sphinx build info version 1':
raise ValueError
@@ -187,8 +186,6 @@ class StandaloneHTMLBuilder(Builder):
tag, old_tags_hash = fp.readline().strip().split(': ')
if tag != 'tags':
raise ValueError
- finally:
- fp.close()
except ValueError:
self.warn('unsupported build info format in %r, building all' %
path.join(self.outdir, '.buildinfo'))
@@ -657,15 +654,12 @@ class StandaloneHTMLBuilder(Builder):
def write_buildinfo(self):
# write build info file
- fp = open(path.join(self.outdir, '.buildinfo'), 'w')
- try:
+ with open(path.join(self.outdir, '.buildinfo'), 'w') as fp:
fp.write('# Sphinx build info version 1\n'
'# This file hashes the configuration used when building'
' these files. When it is not found, a full rebuild will'
' be done.\nconfig: %s\ntags: %s\n' %
(self.config_hash, self.tags_hash))
- finally:
- fp.close()
def cleanup(self):
# clean up theme stuff
@@ -705,10 +699,8 @@ class StandaloneHTMLBuilder(Builder):
f = codecs.open(searchindexfn, 'r', encoding='utf-8')
else:
f = open(searchindexfn, 'rb')
- try:
+ with f:
self.indexer.load(f, self.indexer_format)
- finally:
- f.close()
except (IOError, OSError, ValueError):
if keep:
self.warn('search index couldn\'t be loaded, but not all '
@@ -812,11 +804,8 @@ class StandaloneHTMLBuilder(Builder):
# outfilename's path is in general different from self.outdir
ensuredir(path.dirname(outfilename))
try:
- f = codecs.open(outfilename, 'w', encoding, 'xmlcharrefreplace')
- try:
+ with codecs.open(outfilename, 'w', encoding, 'xmlcharrefreplace') as f:
f.write(output)
- finally:
- f.close()
except (IOError, OSError) as err:
self.warn("error writing file %s: %s" % (outfilename, err))
if self.copysource and ctx.get('sourcename'):
@@ -833,8 +822,7 @@ class StandaloneHTMLBuilder(Builder):
def dump_inventory(self):
self.info(bold('dumping object inventory... '), nonl=True)
- f = open(path.join(self.outdir, INVENTORY_FILENAME), 'wb')
- try:
+ with open(path.join(self.outdir, INVENTORY_FILENAME), 'wb') as f:
f.write((u'# Sphinx inventory version 2\n'
u'# Project: %s\n'
u'# Version: %s\n'
@@ -856,8 +844,6 @@ class StandaloneHTMLBuilder(Builder):
(u'%s %s:%s %s %s %s\n' % (name, domainname, type,
prio, uri, dispname)).encode('utf-8')))
f.write(compressor.flush())
- finally:
- f.close()
self.info('done')
def dump_search_index(self):
@@ -872,10 +858,8 @@ class StandaloneHTMLBuilder(Builder):
f = codecs.open(searchindexfn + '.tmp', 'w', encoding='utf-8')
else:
f = open(searchindexfn + '.tmp', 'wb')
- try:
+ with f:
self.indexer.dump(f, self.indexer_format)
- finally:
- f.close()
movefile(searchindexfn + '.tmp', searchindexfn)
self.info('done')
@@ -1086,10 +1070,8 @@ class SerializingHTMLBuilder(StandaloneHTMLBuilder):
f = codecs.open(filename, 'w', encoding='utf-8')
else:
f = open(filename, 'wb')
- try:
+ with f:
self.implementation.dump(context, f, *self.additional_dump_args)
- finally:
- f.close()
def handle_page(self, pagename, ctx, templatename='page.html',
outfilename=None, event_arg=None):
diff --git a/sphinx/builders/htmlhelp.py b/sphinx/builders/htmlhelp.py
index f4003c4c9..b1a5d7dda 100644
--- a/sphinx/builders/htmlhelp.py
+++ b/sphinx/builders/htmlhelp.py
@@ -198,16 +198,12 @@ class HTMLHelpBuilder(StandaloneHTMLBuilder):
def build_hhx(self, outdir, outname):
self.info('dumping stopword list...')
- f = self.open_file(outdir, outname+'.stp')
- try:
+ with self.open_file(outdir, outname+'.stp') as f:
for word in sorted(stopwords):
print(word, file=f)
- finally:
- f.close()
self.info('writing project file...')
- f = self.open_file(outdir, outname+'.hhp')
- try:
+ with self.open_file(outdir, outname+'.hhp') as f:
f.write(project_template % {'outname': outname,
'title': self.config.html_title,
'version': self.config.version,
@@ -223,12 +219,9 @@ class HTMLHelpBuilder(StandaloneHTMLBuilder):
fn.endswith('.html'):
print(path.join(root, fn)[olen:].replace(os.sep, '\\'),
file=f)
- finally:
- f.close()
self.info('writing TOC file...')
- f = self.open_file(outdir, outname+'.hhc')
- try:
+ with self.open_file(outdir, outname+'.hhc') as f:
f.write(contents_header)
# special books
f.write('<LI> ' + object_sitemap % (self.config.html_short_title,
@@ -266,13 +259,10 @@ class HTMLHelpBuilder(StandaloneHTMLBuilder):
for node in tocdoc.traverse(istoctree):
write_toc(node)
f.write(contents_footer)
- finally:
- f.close()
self.info('writing index file...')
index = self.env.create_index(self)
- f = self.open_file(outdir, outname+'.hhk')
- try:
+ with self.open_file(outdir, outname+'.hhk') as f:
f.write('<UL>\n')
def write_index(title, refs, subitems):
@@ -302,5 +292,3 @@ class HTMLHelpBuilder(StandaloneHTMLBuilder):
for title, (refs, subitems, key_) in group:
write_index(title, refs, subitems)
f.write('</UL>\n')
- finally:
- f.close()
diff --git a/sphinx/builders/qthelp.py b/sphinx/builders/qthelp.py
index 0a7e85c92..4139c92c6 100644
--- a/sphinx/builders/qthelp.py
+++ b/sphinx/builders/qthelp.py
@@ -179,8 +179,7 @@ class QtHelpBuilder(StandaloneHTMLBuilder):
nspace = nspace.lower()
# write the project file
- f = codecs.open(path.join(outdir, outname+'.qhp'), 'w', 'utf-8')
- try:
+ with codecs.open(path.join(outdir, outname+'.qhp'), 'w', 'utf-8') as f:
f.write(project_template % {
'outname': htmlescape(outname),
'title': htmlescape(self.config.html_title),
@@ -191,23 +190,18 @@ class QtHelpBuilder(StandaloneHTMLBuilder):
'sections': sections,
'keywords': keywords,
'files': projectfiles})
- finally:
- f.close()
homepage = 'qthelp://' + posixpath.join(
nspace, 'doc', self.get_target_uri(self.config.master_doc))
startpage = 'qthelp://' + posixpath.join(nspace, 'doc', 'index.html')
self.info('writing collection project file...')
- f = codecs.open(path.join(outdir, outname+'.qhcp'), 'w', 'utf-8')
- try:
+ with codecs.open(path.join(outdir, outname+'.qhcp'), 'w', 'utf-8') as f:
f.write(collection_template % {
'outname': htmlescape(outname),
'title': htmlescape(self.config.html_short_title),
'homepage': htmlescape(homepage),
'startpage': htmlescape(startpage)})
- finally:
- f.close()
def isdocnode(self, node):
if not isinstance(node, nodes.list_item):
diff --git a/sphinx/builders/texinfo.py b/sphinx/builders/texinfo.py
index dec278c86..8c4bd2419 100644
--- a/sphinx/builders/texinfo.py
+++ b/sphinx/builders/texinfo.py
@@ -220,11 +220,8 @@ class TexinfoBuilder(Builder):
fn = path.join(self.outdir, 'Makefile')
self.info(fn, nonl=1)
try:
- mkfile = open(fn, 'w')
- try:
+ with open(fn, 'w') as mkfile:
mkfile.write(TEXINFO_MAKEFILE)
- finally:
- mkfile.close()
except (IOError, OSError) as err:
self.warn("error writing file %s: %s" % (fn, err))
self.info(' done')
diff --git a/sphinx/builders/text.py b/sphinx/builders/text.py
index 85da4a1a2..202ec20db 100644
--- a/sphinx/builders/text.py
+++ b/sphinx/builders/text.py
@@ -60,11 +60,8 @@ class TextBuilder(Builder):
outfilename = path.join(self.outdir, os_path(docname) + self.out_suffix)
ensuredir(path.dirname(outfilename))
try:
- f = codecs.open(outfilename, 'w', 'utf-8')
- try:
+ with codecs.open(outfilename, 'w', 'utf-8') as f:
f.write(self.writer.output)
- finally:
- f.close()
except (IOError, OSError) as err:
self.warn("error writing file %s: %s" % (outfilename, err))
diff --git a/sphinx/builders/xml.py b/sphinx/builders/xml.py
index 91cb273f5..589e8a63a 100644
--- a/sphinx/builders/xml.py
+++ b/sphinx/builders/xml.py
@@ -77,11 +77,8 @@ class XMLBuilder(Builder):
outfilename = path.join(self.outdir, os_path(docname) + self.out_suffix)
ensuredir(path.dirname(outfilename))
try:
- f = codecs.open(outfilename, 'w', 'utf-8')
- try:
+ with codecs.open(outfilename, 'w', 'utf-8') as f:
f.write(self.writer.output)
- finally:
- f.close()
except (IOError, OSError) as err:
self.warn("error writing file %s: %s" % (outfilename, err))