From 0882b73ef3d1ab939672f586f48203bae8d6f79b Mon Sep 17 00:00:00 2001 From: Prafyl <86287866+Prafyl@users.noreply.github.com> Date: Thu, 1 Oct 2026 17:04:57 +0545 Subject: [PATCH] gh-158560: Quote values in netrc.__repr__() so the output can be parsed back --- Lib/netrc.py | 13 ++++++++++--- Lib/test/test_netrc.py | 14 ++++++++++++++ .../2026-10-01-11-19-57.gh-issue-158560.IEhNAe.rst | 3 +++ 3 files changed, 27 insertions(+), 3 deletions(-) create mode 100644 Misc/NEWS.d/next/Library/2026-10-01-11-19-57.gh-issue-158560.IEhNAe.rst diff --git a/Lib/netrc.py b/Lib/netrc.py index 67a287237cbf8b..1c70aa1744fdaa 100644 --- a/Lib/netrc.py +++ b/Lib/netrc.py @@ -77,6 +77,13 @@ def push_token(self, token): self.pushback.append(token) +def _quote(token): + """Quote a token so that _netrclex reads back the same value.""" + if token and not any(ch in token for ch in ' \t\r\n"\\'): + return token + return '"' + token.replace('\\', '\\\\').replace('"', '\\"') + '"' + + class netrc: def __init__(self, file=None): default_netrc = file is None @@ -190,10 +197,10 @@ def __repr__(self): rep = "" for host in self.hosts.keys(): attrs = self.hosts[host] - rep += f"machine {host}\n\tlogin {attrs[0]}\n" + rep += f"machine {_quote(host)}\n\tlogin {_quote(attrs[0])}\n" if attrs[1]: - rep += f"\taccount {attrs[1]}\n" - rep += f"\tpassword {attrs[2]}\n" + rep += f"\taccount {_quote(attrs[1])}\n" + rep += f"\tpassword {_quote(attrs[2])}\n" for macro in self.macros.keys(): rep += f"macdef {macro}\n" for line in self.macros[macro]: diff --git a/Lib/test/test_netrc.py b/Lib/test/test_netrc.py index bbb49bf15ce8f1..1816a1f2238a1c 100644 --- a/Lib/test/test_netrc.py +++ b/Lib/test/test_netrc.py @@ -38,6 +38,20 @@ def test_toplevel_tokens(self): self.assertEqual(nrc.hosts['host.domain.com'], ('log1', 'acct1', 'pass1')) self.assertEqual(nrc.hosts['default'], ('log2', 'acct2', 'pass2')) + def test_repr_roundtrip(self): + # __repr__() writes the data in .netrc format, so parsing its output + # should give back the same entries. + values = ['pass', 'pass word', ' pass', 'pass\tword', 'pass\nword', + 'pass"word', 'pass\\word', ''] + for value in values: + with self.subTest(value=value): + nrc = self.make_nrc("""\ + machine host.domain.com login log password pass + """) + nrc.hosts['host.domain.com'] = (value, 'acct', value) + nrc2 = self.make_nrc(repr(nrc)) + self.assertEqual(nrc2.hosts, nrc.hosts) + def test_macros(self): data = """\ macdef macro1 diff --git a/Misc/NEWS.d/next/Library/2026-10-01-11-19-57.gh-issue-158560.IEhNAe.rst b/Misc/NEWS.d/next/Library/2026-10-01-11-19-57.gh-issue-158560.IEhNAe.rst new file mode 100644 index 00000000000000..9b514031f50431 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-10-01-11-19-57.gh-issue-158560.IEhNAe.rst @@ -0,0 +1,3 @@ +Fix :meth:`!netrc.netrc.__repr__` writing values without quotes, so that an +empty value or one containing whitespace, a quote or a backslash could not be +parsed back correctly.