Skip to content

Commit 303f8d3

Browse files
feat(func/github/token): 支持从多个源读取 Token,具体从哪读由配置文件指定 (#224)
1 parent 64cce32 commit 303f8d3

1 file changed

Lines changed: 31 additions & 12 deletions

File tree

src/function/github/token.py

Lines changed: 31 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,41 @@
1-
import keyring
1+
from colorama import Fore
22
from typing import cast, Any
33
from catfood.functions.print import 消息头
4+
from function.maintain.config import 读取配置
45
from catfood.functions.github.api import 请求GitHubAPI
6+
from catfood.exceptions.operation import OperationFailed
57

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"""
810

911
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:
1736
if not silent:
18-
print(f"{消息头.错误} 读取Token时出错:\n{e}")
19-
return 0
37+
print(f"{消息头.错误} 读取 Token 失败: {Fore.RED}{e}{Fore.RESET}")
38+
return None
2039

2140
def 这是谁的Token(token: str | int | None) -> str | None:
2241
"""

0 commit comments

Comments
 (0)