commit:     ef36e16b22c99440d58185216cb1e34cd610d338
Author:     John R. Graham <john_r_graham <AT> gentoo <DOT> org>
AuthorDate: Mon Aug  4 16:57:15 2025 +0000
Commit:     Sam James <sam <AT> gentoo <DOT> org>
CommitDate: Thu Oct  9 05:32:40 2025 +0000
URL:        https://gitweb.gentoo.org/proj/portage.git/commit/?id=ef36e16b

writemsg: Use the proper base class TextIOBase instead of... ...StringIO for 
identifying all text I/O streams.

When passing a regular text file descriptor to writemsg(), some bug-avoidance
code was not identifying all of the file descriptor types that don't need
Unicode encoding. The file descriptor was being tested for being an instance of
io.StringIO instead of the base class for text streams (io.TextIOBase). As such,
passing a file descriptor that was opened in the most natural way for a text
file, for example

    fd = open(logfile, "w")
    writemsg("Hello, world!\n", fd=fd)

would cause an exception because Unicode encoding would be applied 
unnecessarily,
creating a binary object on which fd.write() would raise an exception.

Signed-off-by: John R. Graham <john_r_graham <AT> gentoo.org>
Part-of: https://github.com/gentoo/portage/pull/1462
Closes: https://github.com/gentoo/portage/pull/1462
Signed-off-by: Sam James <sam <AT> gentoo.org>

 lib/portage/util/__init__.py | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/lib/portage/util/__init__.py b/lib/portage/util/__init__.py
index 50fa1680ff..55cd69c02e 100644
--- a/lib/portage/util/__init__.py
+++ b/lib/portage/util/__init__.py
@@ -112,7 +112,7 @@ def writemsg(mystr: str, noiselevel: int = 0, fd: 
Optional[TextIO] = None) -> No
         fd = sys.stderr
     if noiselevel <= noiselimit:
         # avoid potential UnicodeEncodeError
-        if isinstance(fd, io.StringIO):
+        if isinstance(fd, io.TextIOBase):
             mystr = _unicode_decode(
                 mystr, encoding=_encodings["content"], errors="replace"
             )

Reply via email to