跳至内容

GitHub

github 模块提供了多个辅助函数来查询GitHub,以及连接信息以供更高级的用法。

配置

github 配置会自动从环境和 git 中检测到。

  • GitHub令牌从GITHUB_TOKEN环境变量中读取。对于公共仓库,某些查询可能无需认证即可工作。

GitHub CodeSpaces

在GitHub CodeSpace中,GITHUB_TOKEN会被自动配置。

GitHub Actions

在GitHub Actions中,您可能需要为工作区添加权限以访问工作流日志和拉取请求。此外,您需要将secret.GITHUB_TOKEN传递给GenAIScript脚本运行。

genai.yml
permissions:
contents: read
actions: read
pull-requests: read # or write if you plan to create comments
...
- run: npx --yes genaiscript ...
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
...

功能

问题

您可以使用listIssueslistIssueComments来查询问题和问题评论。

const issues = await github.listIssues({ per_page: 5 })
console.log(issues.map((i) => i.title))
// Use issue number!
const issueComments = await github.listIssueComments(issues[0].number)
console.log(issueComments)

你也可以创建问题评论:

// Use issue number!
await github.createIssueComment(issues[0].number, "Hello, world!")

拉取请求

使用listPullRequestslistPullRequestReviewComments查询拉取请求和拉取请求审查评论。

const prs = await github.listPullRequests({ per_page: 5 })
console.log(prs.map((i) => i.title))
// Use pull request number!
const prcs = await github.listPullRequestReviewComments(prs[0].number)
console.log(prcs.map((i) => i.body))

在GitHub Actions中,确保授予pull-request: read权限。

工作流运行

访问工作流运行的日志,使用listWorkflowRuns来分析失败情况。

// List runs
const runs = await github.listWorkflowRuns("build.yml", { per_page: 5 })
console.log(runs.map((i) => i.status))
const jobs = await github.listWorkflowJobs(runs[0].id)
// Redacted job log
console.log(jobs[0].content)

在GitHub Actions中,授予actions: read权限。

搜索代码

使用searchCode在同一仓库的默认分支上进行代码搜索。

const res = await github.searchCode("HTMLToText")
console.log(res)

获取文件内容

使用getFile获取给定引用、标签或提交SHA的文件内容。

const pkg = await github.getFile("package.json", "main")
console.log(pkg.content.slice(0, 50) + "...")

获取仓库内容

列出远程仓库中某个路径下的文件或目录。默认情况下,不会加载目录中的文件内容。使用 downloadContent: true

// Get top-level markdown files
const files = await github.getRepositoryContent("", {
type: "file",
glob: "*.md",
downloadContent: true,
maxDownloadSize: 2_000,
})

语言

查询GitHub使用listRepositoryLanguages为代码库计算出的编程语言列表。

const languages = await github.listRepositoryLanguages()

分支

使用listBranches列出仓库中的分支。

const branches = await github.listBranches()
console.log(branches)

版本发布

使用listReleases列出仓库中的发布版本。

const releases = await github.listReleases()
console.log(releases)

Octokit 访问

利用 octokit 访问完整的 GitHub API。

import { Octokit } from "@octokit/core"
const { client }: { client: Octokit } = await github.api()
...

在您的软件包列表中安装octokit:

终端窗口
npm i -D octokit

正在处理不同的代码仓库

使用client可以通过相同的密钥在不同的代码库上打开一个github客户端。

const client = github.client("owner", "repo")