Skip to content

Commit

Permalink
Support username and password from keyring
Browse files Browse the repository at this point in the history
  • Loading branch information
stollero committed Sep 25, 2024
1 parent 5352e44 commit d475221
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
11 changes: 9 additions & 2 deletions src/hatch/publish/auth.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from __future__ import annotations

import keyring

from hatch.utils.fs import Path


Expand Down Expand Up @@ -44,8 +46,6 @@ def __get_password(self) -> str:
if password is not None:
return password

import keyring

password = keyring.get_password(self._repo, self.username)
if password is not None:
return password
Expand All @@ -62,6 +62,7 @@ def __get_username(self) -> str:
or self._repo_config.get('user')
or self._read_pypirc()
or self._read_previous_working_user_data()
or self._read_keyring()
)
if username is not None:
return username
Expand All @@ -72,6 +73,12 @@ def __get_username(self) -> str:
self.__username_was_read = True
return self._app.prompt(f"Username for '{self._repo_config['url']}' [__token__]") or '__token__'

def _read_keyring(self) -> str | None:
creds = keyring.get_credential(self._repo, None)
if not creds:
return None
return creds.username

def _read_previous_working_user_data(self) -> str | None:
if self._pwu_path.is_file():
contents = self._pwu_path.read_text()
Expand Down
28 changes: 28 additions & 0 deletions tests/utils/test_auth.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import hatch.publish.auth
from hatch.publish.auth import AuthenticationCredentials
from hatch.utils.fs import Path

Expand Down Expand Up @@ -42,3 +43,30 @@ def test_pypirc(fs):
)
assert credentials.username == 'guido'
assert credentials.password == 'gat'


def test_keyring_credentials(monkeypatch):
class MockKeyring:
@staticmethod
def get_credential(*_):
class Credential:
username = 'gat'

return Credential()

@staticmethod
def get_password(*_):
return 'guido'

monkeypatch.setattr(hatch.publish.auth, 'keyring', MockKeyring)

credentials = AuthenticationCredentials(
app=None,
cache_dir=Path('/none'),
options={},
repo='arbitrary',
repo_config={'url': 'https://kaashandel.nl/'},
)

assert credentials.username == 'gat'
assert credentials.password == 'guido'

0 comments on commit d475221

Please sign in to comment.