|
1 | | -import keyring |
| 1 | +from colorama import Fore |
2 | 2 | from typing import cast, Any |
3 | 3 | from catfood.functions.print import 消息头 |
| 4 | +from function.maintain.config import 读取配置 |
4 | 5 | from catfood.functions.github.api import 请求GitHubAPI |
| 6 | +from catfood.exceptions.operation import OperationFailed |
5 | 7 |
|
6 | | -def read_token(silent: bool = False): |
7 | | - """尝试从钥匙环中读取 github-access-token.glm 密钥 (aka GitHub Token)""" |
| 8 | +def read_token(silent: bool = False) -> str | None: |
| 9 | + """尝试从配置文件中指定的源读取 Token,读取失败返回 None""" |
8 | 10 |
|
9 | 11 | try: |
10 | | - token = keyring.get_password("github-access-token.glm", "github-access-token") |
11 | | - if not token: |
12 | | - if not silent: |
13 | | - print("你可能还没设置glm的Token, 请尝试使用以下命令设置Token:\n glm config --token <YOUR-TOKEN>\n") |
14 | | - return 0 |
15 | | - return token |
16 | | - except Exception as e: |
| 12 | + source: None | str | tuple[str, str] | bool = 读取配置("github.token") |
| 13 | + if not isinstance(source, str): |
| 14 | + raise OperationFailed("未能从配置文件中获取读取源") |
| 15 | + |
| 16 | + if source == "env": |
| 17 | + import os |
| 18 | + if token := os.getenv("GITHUB_TOKEN"): |
| 19 | + return token |
| 20 | + else: |
| 21 | + raise OperationFailed("没有读取到 Token,请确保您设置了 GITHUB_TOKEN 环境变量") |
| 22 | + else: |
| 23 | + import keyring |
| 24 | + if source == "glm": |
| 25 | + service_name, username = ("github-access-token.glm", "github-access-token") |
| 26 | + elif source == "komac": |
| 27 | + service_name, username = ("github-access-token.komac", "github-access-token") |
| 28 | + else: |
| 29 | + raise OperationFailed(f"未知的读取源 {source}") |
| 30 | + |
| 31 | + if token := keyring.get_password(service_name, username): |
| 32 | + return token |
| 33 | + else: |
| 34 | + raise OperationFailed(f"没有读取到 Token,请确保您设置了 {source} 的 Token ({service_name}, {username})") |
| 35 | + except OperationFailed as e: |
17 | 36 | if not silent: |
18 | | - print(f"{消息头.错误} 读取Token时出错:\n{e}") |
19 | | - return 0 |
| 37 | + print(f"{消息头.错误} 读取 Token 失败: {Fore.RED}{e}{Fore.RESET}") |
| 38 | + return None |
20 | 39 |
|
21 | 40 | def 这是谁的Token(token: str | int | None) -> str | None: |
22 | 41 | """ |
|
0 commit comments