Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 0 additions & 39 deletions src/function/github/token.py

This file was deleted.

8 changes: 4 additions & 4 deletions src/function/maintain/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ class 配置信息:
"maintainer_can_modify": False,
"mention_self_when_reviewer": False
},
"token": "glm",
"token": "keyring",
},
"tools": {
"autoremove": {
Expand Down Expand Up @@ -145,7 +145,7 @@ def 验证配置(配置项: 所有配置项 | str, 配置值: str | bool | int)
elif (配置项 == "i18n.lang") and (配置值 not in ["zh-cn", "en-us"]):
return f"不支持的语言 {Fore.BLUE}{配置值}{Fore.RESET}"

elif (配置项 == "github.token") and (配置值 not in ["glm", "komac", "env"]):
elif (配置项 == "github.token") and (配置值 not in ["keyring", "glm", "komac", "env"]):
return "未知的 Token 读取源"

elif (配置项 == "git.retry_interval") and (not isinstance(配置值, int)):
Expand Down Expand Up @@ -266,7 +266,7 @@ def 获取配置schema(版本: str) -> dict[str, Any] | None:
# NOTE 这里的导入不要放顶级,会出现循环导入
from catfood.functions.github.api import get_github_file_content

from function.github.token import read_token
from tools.maintain.token import read_token

print(f"{MSHead.Information} 尝试从 GitHub API 获取配置文件 schema ...")
schema文件 = get_github_file_content("DuckDuckStudio/yazicbs.github.io", f"Tools/Sundry/config/schema/{版本}.json", read_token(silent=True))
Expand Down Expand Up @@ -321,7 +321,7 @@ def 转换配置值(配置项: 所有配置项 | str, 配置值: str) -> str | b
if not 配置值:
# 使用默认配置值
if 配置项 == "github.token":
配置值 = "glm"
配置值 = "keyring"
elif 配置项 == "i18n.lang":
配置值 = "zh-cn"
else:
Expand Down
2 changes: 1 addition & 1 deletion src/tools/ignore.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@

from function.constant.general import REQUEST_TIMEOUT, RETRY_INTERVAL
from function.git.format import branchName
from function.github.token import read_token
from function.maintain.config import 读取配置
from tools.maintain.token import read_token


def 追加忽略字段(检测程序路径: str, 忽略字段: str, 理由: str) -> bool | str:
Expand Down
2 changes: 1 addition & 1 deletion src/tools/logsAnalyse.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@
)
from function.constant.paths import VALIDATION_LOGS_DIR, VALIDATION_LOGS_ZIP_DIR
from function.constant.regexes import LOGS_ZIP_DOWNLOAD_URL
from function.github.token import read_token
from function.maintain.config import 读取配置
from tools.maintain.token import read_token


def main(args: list[str]) -> Literal[0, 1]:
Expand Down
13 changes: 12 additions & 1 deletion src/tools/maintain/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from pygments.formatters.terminal import TerminalFormatter
from pygments.lexers.data import JsonLexer # pyright: ignore[reportMissingTypeStubs]

import tools.maintain.token
from function.maintain.config import (
获取配置schema,
读取配置,
Expand Down Expand Up @@ -76,7 +77,15 @@ def 获取用户输入(配置项: str) -> str | bool | int:
while True:
配置值 = input(提示消息).strip()
try:
return 转换配置值(配置项, 配置值)
配置值 = 转换配置值(配置项, 配置值)
if (
(配置项 == "github.token") and (配置值 == "keyring") and
(tools.maintain.token.read_token() is None) and
tools.maintain.token.set_token()
):
continue

return 配置值
except OperationFailed as e:
print(f"{MSHead.Error} 无法转换配置值: {Fore.RED}{e}{Fore.RESET}")

Expand Down Expand Up @@ -317,6 +326,8 @@ def main(args: list[str]) -> int:
print(f"{MSHead.Information} 配置文件 config.json 位于 {配置信息.所在位置}")
print(f"{MSHead.Information} 尝试打开配置文件 config.json ...")
return open_file(配置信息.所在位置)
elif args[0] == "token":
return tools.maintain.token.main(args[1] if len(args) > 1 else "")
elif len(args) == 2:
return 修改配置项(args[0], args[1])
else:
Expand Down
135 changes: 135 additions & 0 deletions src/tools/maintain/token.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
"""
有关 GitHub Token 管理的函数。
"""

import os
from getpass import getpass
from typing import Literal

import keyring
import keyring.errors
from catfood.exceptions.operation import OperationFailed
from catfood.functions.print import MSHead
from colorama import Fore

from function.maintain.config import 读取配置


def main(operation: str) -> Literal[0, 1]:
"""
``sundry config token <set/remove>``

此函数本质上就是一个中转站,如果你知道具体的操作,可以直接调用 ``set_token()`` 或 ``remove_token()``。

:param operation: "set" 设置 Token,"remove" 移除设置的 Token。
:type operation: str
:return: 退出代码
:rtype: Literal[0, 1]
"""

match operation:
case "set":
return set_token()
case "remove":
return remove_token()
case "":
print(f"{MSHead.Error} 请告诉我你要做什么")
return 1
case _:
print(f"{MSHead.Error} 未知的操作")
return 1

def remove_token() -> Literal[0, 1]:
"""
``sundry config token remove`` 的实现。

:return: 退出代码
:rtype: Literal[0, 1]
"""

try:
keyring.delete_password(
service_name="DuckStudio.Sundry-GitHubToken",
username="GitHubToken"
)
print(f"{MSHead.Success} 成功移除设置的 Token")
return 0
except keyring.errors.PasswordDeleteError:
print(f"{MSHead.Warning} 没有找到已设置的 Token")
return 0
except keyring.errors.KeyringError as e:
print(f"{MSHead.Error} 移除 Token 时发生异常: ({type(e)}) {e}")
return 1

def set_token() -> Literal[0, 1]:
"""
``sundry config token set`` 的实现。

:return: 退出代码
:rtype: Literal[0, 1]
"""

token = getpass("请粘贴 Token: ")
if not token.startswith(("ghp_", "github_pat_")):
print(f"{MSHead.Error} Token 格式不正确,GitHub Token 应以 \"ghp_\" 或 \"github_pat_\" 开头。")
return 1

try:
keyring.set_password(
service_name="DuckStudio.Sundry-GitHubToken",
username="GitHubToken",
password=token
)
del token
print(f"{MSHead.Success} 成功设置 Token")
return 0
except keyring.errors.KeyringError as e:
print(f"{MSHead.Error} 设置 Token 时发生异常: ({type(e)}) {e}")
return 1

def read_token(silent: bool = False) -> str | None:
"""
尝试从配置文件中指定的源读取 GitHub Token,读取失败返回 ``None``。

:pram silent: 是否在读取失败时保持沉默(不输出错误信息)
:type silent: bool
:return: 读取到的 Token,或 ``None``(如果读取失败)
:rtype: str | None
"""

try:
source = 读取配置("github.token")
if not isinstance(source, str):
raise OperationFailed("未能从配置文件中获取 GitHub Token 读取源")

if source == "env":
if token := os.getenv("GITHUB_TOKEN"):
return token
else:
raise OperationFailed("未能从环境变量 GITHUB_TOKEN 中读取 GitHub Token")
else:
token: str | None
match source:
case "keyring":
token = keyring.get_password(
"DuckStudio.Sundry-GitHubToken", "GitHubToken"
)
case "komac":
token = keyring.get_password(
"github-access-token.komac", "github-access-token"
)
case "glm":
token = keyring.get_password(
"github-access-token.glm", "github-access-token"
)
case _:
raise OperationFailed(f"未知的 GitHub Token 读取源: {source}")

if token:
return token
else:
raise OperationFailed(f"未能从 {source} 源中读取 GitHub Token")
except (OperationFailed, keyring.errors.KeyringError) as e:
if not silent:
print(f"{MSHead.Error} 读取 GitHub Token 失败: {Fore.RED}{e}{Fore.RESET}")
return None
2 changes: 1 addition & 1 deletion src/tools/modify.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@
from function.constant.general import PR_TOOL_NOTE, REQUEST_TIMEOUT, RETRY_INTERVAL
from function.files.manifest import FormatManifest, 获取清单目录
from function.git.format import branchName
from function.github.token import read_token
from function.maintain.config import 读取配置
from tools.maintain.token import read_token


def main(args: list[str]) -> Literal[1] | Literal[0]:
Expand Down
2 changes: 1 addition & 1 deletion src/tools/remove.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@
from function.constant.general import PR_TOOL_NOTE, REQUEST_TIMEOUT, RETRY_INTERVAL
from function.files.manifest import 获取清单目录, 获取现有包版本
from function.git.format import branchName
from function.github.token import read_token
from function.maintain.config import 读取配置
from tools import cat, sync
from tools.maintain.token import read_token


# 创建拉取请求
Expand Down
2 changes: 1 addition & 1 deletion src/tools/verify.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@

from function.constant.paths import VERIFY_TEMP_DIR
from function.files.manifest import 获取PR清单, 获取清单目录
from function.github.token import read_token
from function.maintain.config import 读取配置
from tools.maintain.token import read_token


def main(args: list[str]) -> int:
Expand Down
Loading
Loading