Skip to content

Commit 06c89b5

Browse files
committed
Preserve encoding with edit_config
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.
1 parent d8b901b commit 06c89b5

File tree

1 file changed

+16
-1
lines changed

1 file changed

+16
-1
lines changed

setuptools/command/setopt.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,11 @@
22
from distutils import log
33
from distutils.errors import DistutilsOptionError
44
import distutils
5+
import io
56
import os
7+
from ..unicode_utils import detect_encoding
68

9+
from setuptools.extern import six
710
from setuptools.extern.six.moves import configparser
811

912
from setuptools import Command
@@ -40,7 +43,17 @@ def edit_config(filename, settings, dry_run=False):
4043
"""
4144
log.debug("Reading configuration from %s", filename)
4245
opts = configparser.RawConfigParser()
43-
opts.read([filename])
46+
try:
47+
with io.open(filename, 'rb') as fp:
48+
encoding = detect_encoding(fp)
49+
log.debug("Reading %s [%s]" % (filename, encoding or 'locale'))
50+
reader = io.TextIOWrapper(fp, encoding=encoding)
51+
(opts.read_file if six.PY3 else opts.readfp)(reader)
52+
except IOError:
53+
encoding = None
54+
except LookupError:
55+
encoding = None
56+
opts.read([filename])
4457
for section, options in settings.items():
4558
if options is None:
4659
log.info("Deleting section [%s] from %s", section, filename)
@@ -70,6 +83,8 @@ def edit_config(filename, settings, dry_run=False):
7083
log.info("Writing %s", filename)
7184
if not dry_run:
7285
with open(filename, 'w') as f:
86+
if encoding:
87+
f.write("# coding: %s\n" % encoding)
7388
opts.write(f)
7489

7590

0 commit comments

Comments
 (0)