|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | + |
| 3 | +""" |
| 4 | +Git credentials provider |
| 5 | +""" |
| 6 | + |
| 7 | +from typing import Any, Optional |
| 8 | + |
| 9 | +from pygit2 import KeypairFromAgent |
| 10 | +from pygit2 import RemoteCallbacks as _RemoteCallbacks |
| 11 | +from pygit2 import UserPass |
| 12 | +from pygit2.enums import CredentialType |
| 13 | + |
| 14 | + |
| 15 | +class RemoteCallbacks(_RemoteCallbacks): # type: ignore[misc] |
| 16 | + """ |
| 17 | + pygit2.org: Base class for pygit2 remote callbacks. |
| 18 | +
|
| 19 | + :author: Garden Linux Maintainers |
| 20 | + :copyright: Copyright 2024 SAP SE |
| 21 | + :package: gardenlinux |
| 22 | + :subpackage: git |
| 23 | + :since: 1.0.0 |
| 24 | + :license: https://www.apache.org/licenses/LICENSE-2.0 |
| 25 | + Apache License, Version 2.0 |
| 26 | + """ |
| 27 | + |
| 28 | + def __init__( |
| 29 | + self, |
| 30 | + *args: Any, |
| 31 | + username: Optional[str] = None, |
| 32 | + password: Optional[str] = None, |
| 33 | + **kwargs: Any, |
| 34 | + ): |
| 35 | + """ |
| 36 | + Constructor __init__(RemoteCallbacks) |
| 37 | +
|
| 38 | + :param token: GitHub/Git access token for HTTPS authentication. |
| 39 | + Falls back to the GITHUB_TOKEN environment variable if not provided. |
| 40 | +
|
| 41 | + :since: 1.0.0 |
| 42 | + """ |
| 43 | + |
| 44 | + self._username = "" |
| 45 | + self._password = "" |
| 46 | + |
| 47 | + if username and password: |
| 48 | + self._username = username |
| 49 | + self._password = password |
| 50 | + |
| 51 | + def credentials( |
| 52 | + self, |
| 53 | + url: str, |
| 54 | + username_from_url: Optional[str], |
| 55 | + allowed_types: CredentialType, |
| 56 | + ) -> Optional[UserPass | KeypairFromAgent]: |
| 57 | + """ |
| 58 | + pygit2.org: Credentials callback. If the remote server requires |
| 59 | + authentication, this function will be called and its return value |
| 60 | + used for authentication. |
| 61 | +
|
| 62 | + :param url: The URL being accessed (after any insteadOf rewrites) |
| 63 | + :param username_from_url: Username extracted from the URL, if any |
| 64 | + :param allowed_types: Bitmask of credential types the server accepts |
| 65 | +
|
| 66 | + :return: A pygit2 credential object |
| 67 | + :since: 1.0.0 |
| 68 | + """ |
| 69 | + |
| 70 | + if allowed_types & CredentialType.USERPASS_PLAINTEXT: |
| 71 | + if self._password: |
| 72 | + return UserPass(self._username, self._password) |
| 73 | + |
| 74 | + if allowed_types & CredentialType.SSH_KEY: |
| 75 | + return KeypairFromAgent(username_from_url or "git") |
| 76 | + |
| 77 | + return _RemoteCallbacks.credentials(url, username_from_url, allowed_types) |
0 commit comments