Skip to content

Commit

Permalink
Merge pull request #567 from pypa/catch-keyring-errors
Browse files Browse the repository at this point in the history
Catch errors getting/setting password with keyring
  • Loading branch information
takluyver committed Aug 2, 2022
2 parents 0850387 + 73d251b commit fd209d7
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 14 deletions.
18 changes: 12 additions & 6 deletions flit/upload.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,14 +145,17 @@ def get_password(repo, prefer_env):
return repo['password']

try:
import keyring
import keyring, keyring.errors
except ImportError: # pragma: no cover
log.warning("Install keyring to store passwords securely")
keyring = None
else:
stored_pw = keyring.get_password(repo['url'], repo['username'])
if stored_pw is not None:
return stored_pw
try:
stored_pw = keyring.get_password(repo['url'], repo['username'])
if stored_pw is not None:
return stored_pw
except keyring.errors.KeyringError as e:
log.warning("Could not get password from keyring (%s)", e)

if sys.stdin.isatty():
pw = None
Expand All @@ -164,8 +167,11 @@ def get_password(repo, prefer_env):
raise Exception("Could not find password for upload.")

if keyring is not None:
keyring.set_password(repo['url'], repo['username'], pw)
log.info("Stored password with keyring")
try:
keyring.set_password(repo['url'], repo['username'], pw)
log.info("Stored password with keyring")
except keyring.errors.KeyringError as e:
log.warning("Could not store password in keyring (%s)", e)

return pw

Expand Down
14 changes: 6 additions & 8 deletions tests/test_upload.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,21 +77,19 @@ def test_get_repository_env():

@contextmanager
def _fake_keyring(pw):
real_keyring = sys.modules.get('keyring', None)
class FakeKeyring:
@staticmethod
def get_password(service_name, username):
return pw

sys.modules['keyring'] = FakeKeyring()
class FakeKeyringErrMod:
class KeyringError(Exception):
pass

try:
with patch.dict('sys.modules', {
'keyring': FakeKeyring(), 'keyring.errors': FakeKeyringErrMod(),
}):
yield
finally:
if real_keyring is None:
del sys.modules['keyring']
else:
sys.modules['keyring'] = real_keyring

pypirc2 = """
[distutils]
Expand Down

0 comments on commit fd209d7

Please sign in to comment.