Skip to content

Commit

Permalink
Preserve encoding with edit_config
Browse files Browse the repository at this point in the history
PR pypa#1180 and 24be5ab changed the way we read setup.cfg, but when
editing setup.cfg we might still lose the encoding hint on the file,
which can cause failures in subsequent steps.
This change detectes the encoding like in `_parse_config_files` and
writes an encoding hint header if the file encoding was detected.
Fixes jaraco/configparser#37.
  • Loading branch information
itsadok committed Mar 31, 2019
1 parent d8b901b commit a812b37
Showing 1 changed file with 13 additions and 1 deletion.
14 changes: 13 additions & 1 deletion setuptools/command/setopt.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@
from distutils import log
from distutils.errors import DistutilsOptionError
import distutils
import io
import os
from ..unicode_utils import detect_encoding

from setuptools.extern import six
from setuptools.extern.six.moves import configparser

from setuptools import Command
Expand Down Expand Up @@ -40,7 +43,14 @@ def edit_config(filename, settings, dry_run=False):
"""
log.debug("Reading configuration from %s", filename)
opts = configparser.RawConfigParser()
opts.read([filename])
try:
with io.open(filename, 'rb') as fp:
encoding = detect_encoding(fp)
log.debug("Reading %s [%s]" % (filename, encoding or 'locale'))
reader = io.TextIOWrapper(fp, encoding=encoding)
(opts.read_file if six.PY3 else opts.readfp)(reader)
except IOError:
encoding = 'locale'
for section, options in settings.items():
if options is None:
log.info("Deleting section [%s] from %s", section, filename)
Expand Down Expand Up @@ -70,6 +80,8 @@ def edit_config(filename, settings, dry_run=False):
log.info("Writing %s", filename)
if not dry_run:
with open(filename, 'w') as f:
if encoding != 'locale':
f.write("# coding: %s\n" % encoding)
opts.write(f)


Expand Down

0 comments on commit a812b37

Please sign in to comment.