Files
smy-skills/github-gh-skill/scripts/check_gh.py
2026-06-12 17:48:53 +08:00

85 lines
2.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
模块GitHub CLIgh跨平台环境检测脚本。
说明:跨平台单文件,仅依赖 Python 标准库;
供 Agent 或本地一键验证 gh 是否可用、版本与登录用户(不打印 token
"""
from __future__ import annotations
import shutil
import subprocess
import sys
# 区域:配置常量
GH_SKILL_PREFIX = "github-gh-skill:"
def resolve_gh_executable() -> str:
"""检测 gh 是否在 PATH 中,返回可执行路径。"""
path = shutil.which("gh")
if not path:
print("未找到 gh请先安装https://cli.github.com/", file=sys.stderr)
sys.exit(127)
return path
def get_gh_version_line(gh: str) -> str:
"""获取 gh --version 的首行输出。"""
proc = subprocess.run(
[gh, "--version"],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
)
if proc.returncode != 0:
print("gh --version 执行失败", file=sys.stderr)
sys.exit(proc.returncode)
first = (proc.stdout or "").splitlines()
return first[0].strip() if first else ""
def get_github_login(gh: str) -> str | None:
"""
仅查询当前登录用户名gh api避免打印 gh auth status 中的 token 行。
未登录或失败时返回 None。
"""
proc = subprocess.run(
[gh, "api", "user", "--jq", ".login"],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
)
if proc.returncode != 0:
return None
login = (proc.stdout or "").strip()
return login or None
def print_auth_summary(gh: str) -> None:
"""输出登录摘要或警告到 stderr。"""
login = get_github_login(gh)
if login:
print(f"{GH_SKILL_PREFIX} 已登录 GitHub 用户: {login}")
else:
print(
"WARNING: gh 未登录或 token 无效,请执行 gh auth login",
file=sys.stderr,
)
def main() -> None:
"""入口:路径、版本、登录状态(不泄露 token"""
gh_path = resolve_gh_executable()
print(f"{GH_SKILL_PREFIX} gh 路径: {gh_path}")
print(f"{GH_SKILL_PREFIX} {get_gh_version_line(gh_path)}")
print_auth_summary(gh_path)
if __name__ == "__main__":
main()