Skip to content

Commit 7401ecd

Browse files
committed
Preserve encoding with edit_config
PR #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 7401ecd

File tree

1 file changed

+10
-1
lines changed

1 file changed

+10
-1
lines changed

setuptools/command/setopt.py

Lines changed: 10 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,11 @@ 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+
with io.open(filename, 'rb') as fp:
47+
encoding = detect_encoding(fp)
48+
log.debug("Reading %s [%s]" % (filename, encoding or 'locale'))
49+
reader = io.TextIOWrapper(fp, encoding=encoding)
50+
(opts.read_file if six.PY3 else opts.readfp)(reader)
4451
for section, options in settings.items():
4552
if options is None:
4653
log.info("Deleting section [%s] from %s", section, filename)
@@ -70,6 +77,8 @@ def edit_config(filename, settings, dry_run=False):
7077
log.info("Writing %s", filename)
7178
if not dry_run:
7279
with open(filename, 'w') as f:
80+
if encoding != 'locale':
81+
f.write("# coding: %s\n" % encoding)
7382
opts.write(f)
7483

7584

0 commit comments

Comments
 (0)