diff --git a/sphinx/builders/gettext.py b/sphinx/builders/gettext.py index 70b27327c..31a4b22db 100644 --- a/sphinx/builders/gettext.py +++ b/sphinx/builders/gettext.py @@ -270,28 +270,34 @@ class MessageCatalogBuilder(I18nBuilder): ensuredir(path.join(self.outdir, path.dirname(textdomain))) pofn = path.join(self.outdir, textdomain + '.pot') - with open(pofn, 'w', encoding='utf-8') as pofile: # type: ignore - pofile.write(POHEADER % data) # type: ignore + output = StringIO() + output.write(POHEADER % data) - for message in catalog.messages: - positions = catalog.metadata[message] + for message in catalog.messages: + positions = catalog.metadata[message] - if self.config.gettext_location: - # generate "#: file1:line1\n#: file2:line2 ..." - pofile.write("#: %s\n" % "\n#: ".join( # type: ignore - "%s:%s" % (canon_path( - safe_relpath(source, self.outdir)), line) - for source, line, _ in positions)) - if self.config.gettext_uuid: - # generate "# uuid1\n# uuid2\n ..." - pofile.write("# %s\n" % "\n# ".join( # type: ignore - uid for _, _, uid in positions)) + if self.config.gettext_location: + # generate "#: file1:line1\n#: file2:line2 ..." + output.write("#: %s\n" % "\n#: ".join( + "%s:%s" % (canon_path( + safe_relpath(source, self.outdir)), line) + for source, line, _ in positions)) + if self.config.gettext_uuid: + # generate "# uuid1\n# uuid2\n ..." + output.write("# %s\n" % "\n# ".join( + uid for _, _, uid in positions)) - # message contains *one* line of text ready for translation - message = message.replace('\\', r'\\'). \ - replace('"', r'\"'). \ - replace('\n', '\\n"\n"') - pofile.write('msgid "%s"\nmsgstr ""\n\n' % message) # type: ignore + # message contains *one* line of text ready for translation + message = message.replace('\\', r'\\'). \ + replace('"', r'\"'). \ + replace('\n', '\\n"\n"') + output.write('msgid "%s"\nmsgstr ""\n\n' % message) + + content = output.getvalue() + + if should_write(pofn, content): + with open(pofn, 'w', encoding='utf-8') as pofile: + pofile.write(content) def setup(app):