diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..7e55644 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: false +contact_links: + - name: GitHub 官方 Git 教程 + url: https://docs.github.com/zh/get-started/using-git/about-git + about: 遇到一般 Git 概念问题时,可以先查阅官方教程。 diff --git a/.github/ISSUE_TEMPLATE/exercise-1.yml b/.github/ISSUE_TEMPLATE/exercise-1.yml new file mode 100644 index 0000000..3a605fb --- /dev/null +++ b/.github/ISSUE_TEMPLATE/exercise-1.yml @@ -0,0 +1,27 @@ +name: "Exercise 1 · 第一次贡献" +description: 练习 Fork、topic branch、commit、push 和第一次 Pull Request +title: "[Exercise 1] " +labels: + - exercise:1 +body: + - type: markdown + attributes: + value: | + 创建后,机器人会分配一个不会写入 `main` 的专属训练分支,并回复下一步命令。 + - type: checkboxes + id: preparation + attributes: + label: 开始前确认 + options: + - label: 我会使用自己的 Fork 和独立 topic branch,不直接在 main/master 上练习。 + required: true + - label: 我知道连续 14 天无活动时,临时训练分支会被自动清理。 + required: true + - type: textarea + id: goal + attributes: + label: 你希望通过本关熟悉什么? + description: 简短写一句即可,不影响自动判定。 + placeholder: 例如:我想完整走一次 Fork 到 PR 的流程。 + validations: + required: true diff --git a/.github/ISSUE_TEMPLATE/exercise-2.yml b/.github/ISSUE_TEMPLATE/exercise-2.yml new file mode 100644 index 0000000..a617148 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/exercise-2.yml @@ -0,0 +1,28 @@ +name: "Exercise 2 · 干净的提交历史" +description: 在一个 PR 中完成两条清晰、线性的提交 +title: "[Exercise 2] " +labels: + - exercise:2 +body: + - type: markdown + attributes: + value: | + 本关要求先完成 Exercise 1。机器人会检查本关恰好有两条提交且没有 merge commit。 + - type: checkboxes + id: preparation + attributes: + label: 开始前确认 + options: + - label: 我已经完成 Exercise 1。 + required: true + - label: 我会从机器人提供的新 base 创建新分支,不复用上一关分支。 + required: true + - label: 我知道 commit message 不规范只会收到 Warning,不会阻断练习。 + required: true + - type: textarea + id: question + attributes: + label: 当前对提交历史的疑问 + placeholder: 没有疑问时可以写“暂无”。 + validations: + required: true diff --git a/.github/ISSUE_TEMPLATE/exercise-3.yml b/.github/ISSUE_TEMPLATE/exercise-3.yml new file mode 100644 index 0000000..22e03d7 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/exercise-3.yml @@ -0,0 +1,28 @@ +name: "Exercise 3 · 响应 Code Review" +description: 在同一个 PR 中接收反馈、修改并继续 push +title: "[Exercise 3] " +labels: + - exercise:3 +body: + - type: markdown + attributes: + value: | + 本关要求先完成 Exercise 2。机器人会在第一次 PR 检查时提出一次必须处理的反馈。 + - type: checkboxes + id: preparation + attributes: + label: 开始前确认 + options: + - label: 我已经完成 Exercise 2。 + required: true + - label: 收到反馈后,我会继续更新原 PR,而不是新建 PR。 + required: true + - label: 我会在修改后留言说明如何处理反馈。 + required: true + - type: textarea + id: expectation + attributes: + label: 你认为收到 Review 后应该怎么做? + placeholder: 用自己的话简单描述。 + validations: + required: true diff --git a/.github/ISSUE_TEMPLATE/exercise-4.yml b/.github/ISSUE_TEMPLATE/exercise-4.yml new file mode 100644 index 0000000..b112249 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/exercise-4.yml @@ -0,0 +1,31 @@ +name: "Exercise 4 · 解决上游冲突" +description: 处理机器人在专属上游分支制造的真实冲突 +title: "[Exercise 4] " +labels: + - exercise:4 +body: + - type: markdown + attributes: + value: | + 本关要求先完成 Exercise 3。PR 创建后,机器人会更新上游同一行以制造真实冲突。 + - type: checkboxes + id: preparation + attributes: + label: 开始前确认 + options: + - label: 我已经完成 Exercise 3。 + required: true + - label: 我会在本地 fetch 上游,并使用 merge 或 rebase 解决冲突。 + required: true + - label: 我不会直接删除其中一方的内容来绕过冲突。 + required: true + - type: dropdown + id: strategy + attributes: + label: 计划使用的方式 + options: + - merge(更适合第一次练习) + - rebase + - 还不确定,等机器人提示 + validations: + required: true diff --git a/.github/ISSUE_TEMPLATE/exercise1.md b/.github/ISSUE_TEMPLATE/exercise1.md deleted file mode 100644 index dc8ac5b..0000000 --- a/.github/ISSUE_TEMPLATE/exercise1.md +++ /dev/null @@ -1,7 +0,0 @@ -练习一:认领 issue 完成第一次 PR - -提交一个以自己的用户名命名的 `.md` 文件,内容随意。 - -请注意查看 [`CONTRIBUTING.md`](https://github.com/FrogDar/code-contributing-practice/blob/main/CONTRIBUTING.md) 里的规范(比如 git message 要使用 [`angular` 规范](https://github.com/angular/angular/blob/main/CONTRIBUTING.md)) - -建议自己创建一个分支,并在分支上修改后提交 PR,具体做法和理由见练习二。 diff --git a/.github/ISSUE_TEMPLATE/exercise2.md b/.github/ISSUE_TEMPLATE/exercise2.md deleted file mode 100644 index ec490a2..0000000 --- a/.github/ISSUE_TEMPLATE/exercise2.md +++ /dev/null @@ -1,28 +0,0 @@ -## 任务 - -随机变更 md 里的内容 - -唯一的要求是:在 PR 里不要出现上次提交的 git 记录。 - -## 方法 - -### 法一 - -如果你的仓库单纯比上游仓库较慢(只有 `behind`),那么可以在仓库内点击同步,同步为最新后再开始编码。 - -![image](https://user-images.githubusercontent.com/20886330/206180947-76205c08-6c33-4dee-85a1-51e82f0d2b23.png) - -### 法二 - -如果又有 `behind` 又有 `ahead` 那么可以删除仓库,重新 Fork 。 - -### 法三 - -创建单独的分支,利用单独分支执行相关指令拉取最新请求。 - -(每次都创建一个新的分支,在那个分支上编码,完成之后就删除新创建的这个分支,保持主分支的干净,那么对于主分支来说就可以使用法一了) - -```git -git checkout -b new-branch-name -git pull upstream master -``` \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/improvement.yml b/.github/ISSUE_TEMPLATE/improvement.yml new file mode 100644 index 0000000..1ae0b20 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/improvement.yml @@ -0,0 +1,29 @@ +name: 改进这个训练仓库 +description: 报告文档问题、自动化缺陷或提出课程建议 +title: "[Improvement] " +labels: + - enhancement +body: + - type: dropdown + id: area + attributes: + label: 涉及范围 + options: + - 课程文档 + - GitHub Actions / 自动反馈 + - Issue / PR 模板 + - 其他 + validations: + required: true + - type: textarea + id: problem + attributes: + label: 当前问题 + description: 请描述你遇到的行为和期望行为。 + validations: + required: true + - type: textarea + id: proposal + attributes: + label: 建议方案 + description: 可选;不需要先写代码。 diff --git a/.github/PULL_REQUEST_TEMPLATE/exercise.md b/.github/PULL_REQUEST_TEMPLATE/exercise.md new file mode 100644 index 0000000..f78fa00 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE/exercise.md @@ -0,0 +1,19 @@ +## 练习说明 + +- 本次练习:Exercise +- 我完成了: + +## 关联 Issue + +Closes # + +## 自查 + +- [ ] base 是机器人提供的 `practice/ex...` 临时分支 +- [ ] head 是我 Fork 中的独立 topic branch,不是 `main`/`master` +- [ ] 只修改了 `.practice/workspace.md` +- [ ] 我会继续更新这个 PR,而不是为修复反馈新建 PR + +## 给维护者或机器人的备注 + + diff --git a/.github/PULL_REQUEST_TEMPLATE/maintenance.md b/.github/PULL_REQUEST_TEMPLATE/maintenance.md new file mode 100644 index 0000000..c9323fc --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE/maintenance.md @@ -0,0 +1,18 @@ +## Summary + +- 做了什么: +- 为什么这样做: + +## Related Issue + + + +## Test Plan + +- [ ] `npm test` +- [ ] `npm run check:source` +- [ ] 文档中的命令和链接已人工检查 + +## Notes + + diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..e627d48 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,9 @@ +version: 2 +updates: + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly + open-pull-requests-limit: 5 + commit-message: + prefix: "ci(deps)" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..68ae665 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,72 @@ +name: CI + +on: + push: + branches: + - main + pull_request: + workflow_dispatch: + +permissions: + contents: read + +jobs: + tests: + name: CI / Tests + runs-on: ubuntu-latest + steps: + - name: Check out repository + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + persist-credentials: false + + - name: Set up Node.js + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 + with: + node-version: "22" + cache: npm + + - name: Install dependencies + run: npm ci --ignore-scripts + + - name: Run unit and source checks + run: npm run check + + - name: Check whitespace errors + run: git diff --check + + workflow-lint: + name: CI / Workflow lint + runs-on: ubuntu-latest + steps: + - name: Check out repository + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + persist-credentials: false + + - name: Install pinned actionlint + env: + ACTIONLINT_VERSION: "1.7.12" + run: | + curl --fail --silent --show-error --location --remote-name "https://github.com/rhysd/actionlint/releases/download/v${ACTIONLINT_VERSION}/actionlint_${ACTIONLINT_VERSION}_linux_amd64.tar.gz" + curl --fail --silent --show-error --location --remote-name "https://github.com/rhysd/actionlint/releases/download/v${ACTIONLINT_VERSION}/actionlint_${ACTIONLINT_VERSION}_checksums.txt" + grep " actionlint_${ACTIONLINT_VERSION}_linux_amd64.tar.gz$" "actionlint_${ACTIONLINT_VERSION}_checksums.txt" | sha256sum --check --strict + tar --extract --gzip --file "actionlint_${ACTIONLINT_VERSION}_linux_amd64.tar.gz" actionlint + ./actionlint -color + + security: + name: CI / Workflow security + runs-on: ubuntu-latest + steps: + - name: Check out repository + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + persist-credentials: false + + - name: Set up Node.js + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 + with: + node-version: "22" + + - name: Verify privileged workflow boundaries and pinned actions + run: node scripts/practice/check-source.mjs diff --git a/.github/workflows/exercise.yml b/.github/workflows/exercise.yml deleted file mode 100644 index bdd13d9..0000000 --- a/.github/workflows/exercise.yml +++ /dev/null @@ -1,50 +0,0 @@ -name: Exercise -# on issues created or updated -on: - issues: - types: - - opened - - edited - -permissions: - issues: write - contents: read - -jobs: - ex1: - runs-on: ubuntu-latest - # if issue title is ex1 - if: ${{ github.event.issue.title == 'Ex1' || github.event.issue.title == 'ex1' || github.event.issue.title == '练习1' || github.event.issue.title == '练习一' }} - steps: - - uses: actions/checkout@v3 - - name: Comment on issue - uses: peter-evans/create-or-update-comment@v2 - with: - issue-number: ${{ github.event.issue.number }} - body-file: .github/ISSUE_TEMPLATE/exercise1.md - token: ${{ secrets.GITHUB_TOKEN }} - - name: Add label - uses: andymckay/labeler@master - with: - add-labels: "exercise1" - - name: Assign author to issue - uses: technote-space/assign-author@v1 - - ex2: - runs-on: ubuntu-latest - # if issue title is ex2 - if: ${{ github.event.issue.title == 'Ex2' || github.event.issue.title == 'ex2' || github.event.issue.title == '练习2' || github.event.issue.title == '练习二' }} - steps: - - uses: actions/checkout@v3 - - name: Comment on issue - uses: peter-evans/create-or-update-comment@v2 - with: - issue-number: ${{ github.event.issue.number }} - body-file: .github/ISSUE_TEMPLATE/exercise2.md - token: ${{ secrets.GITHUB_TOKEN }} - - name: Add label - uses: andymckay/labeler@master - with: - add-labels: "exercise2" - - name: Assign author to issue - uses: technote-space/assign-author@v1 diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml deleted file mode 100644 index f17fa27..0000000 --- a/.github/workflows/pr.yml +++ /dev/null @@ -1,39 +0,0 @@ -name: Pull Request Checker -on: - pull_request: - branches: - - main - -permissions: - pull-requests: read - -jobs: - commitlint: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - with: - fetch-depth: 0 - - uses: actions/setup-node@v2 - with: - node-version: '22' - - run: | - npm install --save-dev @commitlint/config-angular @commitlint/cli - echo "module.exports = {extends: ['@commitlint/config-angular']};" > commitlint.config.js - - # Run the commitlint action, considering its own dependencies and yours as well 🚀 - # `github.workspace` is the path to your repository. - - uses: wagoid/commitlint-github-action@v6 - env: - NODE_PATH: ${{ github.workspace }}/node_modules - with: - helpURL: 'https://github.com/FrogDar/code-contributing-practice/blob/main/CONTRIBUTING.md' - - # check if the PR close an issue in PR body - - name: Check if the PR close an issue in PR body - run: | - if ! echo "${{ github.event.pull_request.body }}" | grep -q "close" ; then - echo "No issue closed in the PR body. Please add a line like 'close #123' to the PR body." - exit 1 - fi - diff --git a/.github/workflows/practice-admin.yml b/.github/workflows/practice-admin.yml new file mode 100644 index 0000000..a290aa9 --- /dev/null +++ b/.github/workflows/practice-admin.yml @@ -0,0 +1,53 @@ +name: Practice / Administration + +on: + workflow_dispatch: + inputs: + operation: + description: Administrative operation + required: true + type: choice + options: + - bootstrap-labels + - close-legacy-sessions + confirmation: + description: Type CLOSE_LEGACY only when closing old sessions + required: false + type: string + +permissions: + contents: read + issues: write + pull-requests: write + +concurrency: + group: practice-administration + cancel-in-progress: false + +jobs: + run: + name: Practice / Administrative operation + runs-on: ubuntu-latest + steps: + - name: Check out trusted default branch + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + persist-credentials: false + + - name: Set up Node.js + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 + with: + node-version: "22" + + - name: Create or update managed labels + if: inputs.operation == 'bootstrap-labels' + env: + GITHUB_TOKEN: ${{ github.token }} + run: node scripts/practice/workflow.mjs bootstrap + + - name: Close legacy exercise sessions + if: inputs.operation == 'close-legacy-sessions' + env: + GITHUB_TOKEN: ${{ github.token }} + CONFIRM: ${{ inputs.confirmation }} + run: node scripts/practice/workflow.mjs migrate-legacy diff --git a/.github/workflows/practice-cleanup.yml b/.github/workflows/practice-cleanup.yml new file mode 100644 index 0000000..aa55fe0 --- /dev/null +++ b/.github/workflows/practice-cleanup.yml @@ -0,0 +1,35 @@ +name: Practice / Cleanup + +on: + schedule: + - cron: "17 3 * * *" + workflow_dispatch: + +permissions: + contents: write + issues: write + pull-requests: write + +concurrency: + group: practice-cleanup + cancel-in-progress: false + +jobs: + cleanup: + name: Practice / Expire inactive sessions + runs-on: ubuntu-latest + steps: + - name: Check out trusted default branch + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + persist-credentials: false + + - name: Set up Node.js + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 + with: + node-version: "22" + + - name: Remind or expire inactive sessions + env: + GITHUB_TOKEN: ${{ github.token }} + run: node scripts/practice/workflow.mjs cleanup diff --git a/.github/workflows/practice-grade.yml b/.github/workflows/practice-grade.yml new file mode 100644 index 0000000..633419b --- /dev/null +++ b/.github/workflows/practice-grade.yml @@ -0,0 +1,79 @@ +name: Practice / Grade + +on: + pull_request_target: + types: + - opened + - reopened + - synchronize + - edited + - ready_for_review + - labeled + - unlabeled + +permissions: {} + +concurrency: + group: practice-grade-${{ github.event.pull_request.number }} + cancel-in-progress: true + +jobs: + grade: + name: Practice / Grade + runs-on: ubuntu-latest + permissions: + contents: write + issues: write + pull-requests: write + outputs: + eligible: ${{ steps.grade.outputs.eligible }} + outcome: ${{ steps.grade.outputs.outcome }} + head_sha: ${{ steps.grade.outputs.head_sha }} + pr_number: ${{ steps.grade.outputs.pr_number }} + steps: + - name: Check out trusted default branch only + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + persist-credentials: false + + - name: Set up Node.js + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 + with: + node-version: "22" + + - name: Grade metadata and files as inert data + id: grade + env: + GITHUB_TOKEN: ${{ github.token }} + run: node scripts/practice/workflow.mjs grade-pr + + - name: Fail required practice checks + if: steps.grade.outputs.outcome == 'fail' + run: exit 1 + + merge: + name: Practice / Automatic squash merge + needs: grade + if: needs.grade.outputs.eligible == 'true' + runs-on: ubuntu-latest + permissions: + contents: write + issues: write + pull-requests: write + steps: + - name: Check out trusted default branch only + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + persist-credentials: false + + - name: Set up Node.js + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 + with: + node-version: "22" + + - name: Revalidate exact head and merge + env: + GITHUB_TOKEN: ${{ github.token }} + PR_NUMBER: ${{ needs.grade.outputs.pr_number }} + EXPECTED_HEAD: ${{ needs.grade.outputs.head_sha }} + run: node scripts/practice/workflow.mjs merge-pr diff --git a/.github/workflows/practice-session.yml b/.github/workflows/practice-session.yml new file mode 100644 index 0000000..b6a490c --- /dev/null +++ b/.github/workflows/practice-session.yml @@ -0,0 +1,36 @@ +name: Practice / Session + +on: + issues: + types: + - opened + - reopened + - labeled + +permissions: + contents: write + issues: write + +concurrency: + group: practice-session-user-${{ github.event.issue.user.id }} + cancel-in-progress: false + +jobs: + setup: + name: Practice / Create session + runs-on: ubuntu-latest + steps: + - name: Check out trusted default branch + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + persist-credentials: false + + - name: Set up Node.js + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 + with: + node-version: "22" + + - name: Create or resume exercise session + env: + GITHUB_TOKEN: ${{ github.token }} + run: node scripts/practice/workflow.mjs issue-opened diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 82b746a..a39f438 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,98 +1,56 @@ -## 任务 +# 贡献指南 -### 认领 issue +本仓库同时接受两类 Pull Request:用于学习的练习 PR,以及改进课程和自动化的维护 PR。两者的 base、权限和合并方式不同,请先确认自己属于哪一种。 -创建一个 issue 命名为 `Ex1` 或 `ex1` 或 `练习1` 或 `练习一`,机器人会自动更新任务并将这个 issue 分配给你,请你完成它哦~ +## 完成练习 -后续的其他任务就把 `1` 换成 `2`、`3`等其他编号。 - -### 开始编码(TODO) +练习 PR 必须从 Exercise Issue Form 开始。机器人会创建专属 `practice/ex...` base 分支并给出命令;不要把练习直接提交到 `main`。 -在点击仓库右上角的 Fork 按钮将在你的账号中创建该仓库的副本。前往你的 GitHub 中的相同仓库,地址通常为 `https://github.com/你的用户名/code-contributing-practice` 接下来将在你自己账号的仓库中操作。 +练习的硬性规则由每关目标决定,例如提交数量、是否复用原 PR、修改范围和冲突是否解决。以下项目属于推荐项,不会因为格式问题单独阻断练习: -> 如果你不知道以下说的是什么东西,你可能需要尝试 [GitHub Desktop](https://desktop.github.com/) ,这能帮助你少敲一堆命令,减轻学习 Git 的负担。(不过这不代表不用学习 Git)如果你遇到了困难,请向 mentor 求助。 +- Commit message 推荐 `type: summary` 或 `type(scope): summary`; +- PR 标题推荐使用简洁、动作明确的同类格式; +- 分支名推荐 `exercise/<关卡>-`; +- 收到 Review 后,建议留言说明自己如何处理了反馈。 -将仓库 clone 到本地,这样本地才有代码,才能对其修改。操作步骤参考 [Cloning a repository](https://docs.github.com/en/repositories/creating-and-managing-repositories/cloning-a-repository) +常用提交类型包括 `docs`、`feat`、`fix`、`test`、`refactor`、`build`、`ci`、`chore` 和 `revert`。示例: -对于本仓库而言,提交的内容具体见 [`records` 目录下的 `README`](https://github.com/FrogDar/code-contributing-practice/tree/main/records)。 - -### 创建 Pull Request - -参考 [Creating a pull request from a fork](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request-from-a-fork) - -> 同样,如果你遇到了困难,请向 mentor 求助。 - -在你创建 Pull Request 后,你会看到 checks running ,请留意失败的 checks ,这通常意味着你提交的代码可能存在问题。 - -在本仓库中主要是对规范性进行检查,如 git message 是否遵守规范?是否在 PR 中关闭对应的 issue 等。 - -### 等待 Code Review - -你提交的 Pull Request 将在 review 后合并入仓库。如果有需要改进的地方,你的 reviewer 会在 Pull Request 下留言,所以请留意你的 reviewer 给你的消息(不过也不用担心,你会收到邮件提醒)。 - -### Commit 规范 - -> 本节主要参考自 [`angular`](https://github.com/angular/angular/blob/main/CONTRIBUTING.md) 。 -> 更宽松地要求可以参见 [How to Write a Git Commit Message](https://cbea.ms/git-commit/) ,这里给出一些最基本的要求。 感谢 @derecknowayback 的分享。 - -每一个 Git commit message 由 **header** 和 **body** 组成。 - -``` -
- - -``` - -#### **header** - -header 是必须的,格式如下: - -``` -(): - │ │ │ │ - │ │ │ └─⫸ 原则上使用英文;使用动词原形开头,首字母不需要大写,句尾不需要句号(整句尽量不超过60词) - │ │ │ - │ │ └─⫸ 冒号后面需要一个半角空格 - │ │ - │ └─⫸ Commit Scope: 特定范围(对于本仓库而言一般为空) - │ - └─⫸ Commit Type: build|ci|docs|feat|fix|perf|refactor|test|style|chore|revert +```text +docs: complete exercise 1 +fix(ci): explain an invalid issue reference ``` -##### Commit Type +不符合推荐格式、使用 `WIP`/`fixup!`/`squash!` 或标题过于模糊时,机器人会给出 Warning 和修改示例,但仍会继续判断本关的真正目标。 -* **build**: 影响构建系统或者外部依赖的更改,例如修改 `pom.xml`, `Dockerfile`, `docker-compose.yml` 的更改 -* **ci**: 影响到 CI 配置或脚本的更改,例如修改 `gitlab-ci.yml`, Github Actions 的配置文件等 -* **docs**: 只修改了文档的更改 -* **feat**: 增加新功能的更改 -* **fix**: 修复 bug 的更改 -* **perf**: 提高了程序性能的更改 -* **refactor**: 既没有修复 bug 也没有增加新功能的更改(比如重构代码) -* **test**: 增加或改正测试代码 -* **style**: 不改变代码含义的修改(比如格式化代码) -* **chore**: 其他不改变 `src` 或测试代码的修改 -* **revert**: 撤回之前的 `commit` +## 改进训练仓库 -#### scope +课程文档、判题器、模板和工作流的改进 PR 应以 `main` 为 base,并经过人工 Review。建议流程: -commit 所属的范围,例如 `frontend`、`backend` 等。 +1. 使用 Improvement Issue Form 描述问题和期望行为; +2. 从最新 `upstream/main` 创建独立分支; +3. 修改判题规则时先补失败测试,再实现规则; +4. 更新会影响学员操作的相应文档; +5. 使用维护 PR 模板说明测试范围和安全影响。 -如果 commit 不属于特定范围,则不用加 scope 。 -#### body +本地检查: -body 是可选的,与 header 一样,需要使用动词原形。body 中可以书写比 header 中更详细的信息,比如: +```bash +npm ci --ignore-scripts +npm run check +git diff --check +``` -- 为什么做了这个更改 -- 受到了什么启发 -- 与之前版本的区别 -- 功能的详细说明 -- …… +CI 还会使用固定版本的 actionlint 检查工作流语法。修改高权限自动化时,必须保持以下安全边界: -#### 样例 +- `pull_request_target` 只能 checkout 并执行默认分支中的可信代码; +- 不得 checkout、安装或执行 Fork 中的脚本、依赖和配置; +- PR 标题、正文、分支名和文件内容必须作为数据传递,不能插入 shell; +- 自动合并前必须重新验证当前 head SHA、会话、Review 和允许路径; +- 权限按 job 最小化,所有第三方 Actions 固定到完整 commit SHA。 -``` -fix: address an issue where return value can be null +## Review 与合并 -if an incorrect request body is sent to the server, method xxx may respond with a empty body due to xxx -this issue is fixed by improving error handling in the request parser -``` +- 练习 PR:硬性检查通过后由机器人 squash merge 到临时 base,并自动清理。 +- 维护 PR:CI 通过且至少一名维护者批准后,人工 squash merge 到 `main`。 +- `automerge:disabled` 是练习 PR 的人工停止开关;存在该标签或人工 Changes requested 时,机器人不得合并。 +- 对现有行为有疑问时,优先保持改动小,并在 Issue 中确认方向。 diff --git a/README.md b/README.md index e9556f8..e88f2b9 100644 --- a/README.md +++ b/README.md @@ -1,90 +1,57 @@ -# code-contributing-practice - -> 欢迎来到开源贡献练习场!本仓库旨在帮助你熟悉并掌握向开源项目贡献代码的标准流程,包括 fork、git branch、pull request (PR) 等核心操作。 - -## 为仓库贡献代码应当怎么做? - -### 1. 准备工作 - -- **阅读贡献指南**:在项目根目录找到并阅读 `CONTRIBUTING.md` 文件,了解代码规范。 -- **认领 Issue**:找到或创建一个 `Issue`,评论表示你希望处理它,并等待分配。 - -### 2. 本地开发 - -1. **Fork 仓库**:点击原始仓库右上角的 `Fork` 按钮,复制一份到你的 GitHub 账号下。 - -2. **Clone 到本地**: - ```bash - # 将 YOUR_USERNAME 替换为你的 GitHub 用户名 - git clone [https://github.com/YOUR_USERNAME/code-contributing-practice.git](https://github.com/YOUR_USERNAME/code-contributing-practice.git) - cd code-contributing-practice - ``` - -3. **创建特性分支**:**不要在 `main` 分支上直接修改。** - ```bash - # 分支名应清晰并与任务相关,例如:fix/issue-123 - git checkout -b feature/my-first-contribution - ``` - -4. **(可选) 同步上游仓库**:在开始修改前,获取原始仓库的最新代码以避免冲突。 - ```bash - git remote add upstream [https://github.com/FrogDar/code-contributing-practice.git](https://github.com/FrogDar/code-contributing-practice.git) - git fetch upstream - git checkout main - git merge upstream/main - git checkout feature/my-first-contribution - git rebase main # 将你的分支变基到最新的 main 分支上 - ``` - -5. **修改与提交**:完成代码修改后,按照规范提交。 - ```bash - git add . - git commit -m "feat(records): add practice file for YOUR_NAME" - ``` - -6. **推送至你的 Fork 仓库**: - ```bash - git push origin feature/my-first-contribution - ``` - -### 3. 创建 Pull Request (PR) - -- **发起 PR**:在你的 Fork 仓库页面,点击 `Compare & pull request` 按钮。 -- **填写描述**: - - **标题**:清晰概括你的修改。 - - **关联 Issue**:在描述中写入 `close #123` (`123` 为对应的 Issue 编号),PR 合并后会自动关闭该 Issue。 - -### 4. 代码审查 - -- **等待审查**:维护者会对你的代码进行审查并提出修改意见。 -- **更新代码**:若有修改,直接在本地的同一分支上继续 `commit` 和 `push`,PR会自动同步更新。 -- **合并**:PR 被批准并合并后,你就完成了一次贡献! -## 练习 - -> 在练习中提交的内容没有限制,可以是在 `records` 文件夹下提交一个属于自己的 `.md` 文件,也可以是完善本仓库。 -> -> 需要注意的是,练习失败的那些产物对于新手来说只能是删掉再来一次。当然你也可以通过提升自己的 git 水平,用一些奇淫巧技拯救此前错误的练习结果。 - -### 练习一:完成第一次贡献 - -- **目标**:完整体验一次标准的 Fork & PR 流程。 -- **步骤**: - 1. 创建一个 Issue,标题为 `Ex1` 或 `练习一`,机器人会自动分配给你。 - 2. 严格遵循上述标准流程。 - 3. 遵守 [`CONTRIBUTING.md`](https://github.com/FrogDar/code-contributing-practice/blob/main/CONTRIBUTING.md) 中的规范(比如 git message 要使用[`angular` 规范](https://github.com/angular/angular/blob/main/CONTRIBUTING.md))。 - -### 练习二:处理多个提交 - -- **目标**:学习在同一 PR 中进行多次提交,并保持提交历史的干净。 -- **步骤**: - 1. 创建一个 Issue,标题为 `Ex2` 或 `练习二`。 - 2. **务必为本次练习创建一条新分支**。 - 3. 确保本次 PR 不包含上一次练习的提交记录。 - -## TODO - -- [x] 基本文字介绍 -- [x] 完成第一个贡献流程 -- [x] 完成一次手动评判 -- [x] 利用 `GitHub Actions` 自动评判流程并给予提示 -- [ ] 更为充实的文字介绍 +# Git / GitHub 开源贡献练习场 + +这是一个面向 Git 和 GitHub 初学者的自动化练习仓库。你会使用真实的 Fork、Issue、branch、commit、Pull Request、Review 和冲突解决流程;机器人会在 PR 中指出具体问题、给出修复命令,并在通过后自动完成练习。 + +## 为什么练习不会弄乱 main + +每个练习 Issue 都会获得一个专属的临时上游分支: + +```text +practice/ex<关卡>/issue-- +``` + +练习 PR 合入这个临时分支,而不是 `main`。通过后机器人会 squash merge、关闭 Issue 并删除临时分支。因此主干只保存课程与自动化代码,普通 clone 不会下载其他人的练习产物。 + +## 四关学习路线 + +| 关卡 | 目标 | 必须完成 | +| --- | --- | --- | +| Exercise 1 | 第一次贡献 | Fork、topic branch、一条提交、关联 Issue、创建 PR | +| Exercise 2 | 干净历史 | 新分支、恰好两条提交、无线性历史污染 | +| Exercise 3 | 响应 Review | 在原 PR 中继续 commit 和 push,落实反馈 | +| Exercise 4 | 解决冲突 | fetch 上游,使用 merge 或 rebase 解决真实冲突 | + +从仓库的 [New issue](https://github.com/lin594/code-contributing-practice/issues/new/choose) 页面选择 Exercise 1 开始。后续关卡必须按顺序完成。 + +## 开始前 + +你需要: + +- 一个 GitHub 账号; +- Git 2.23 或更高版本; +- 能够使用终端执行基础命令; +- 一个从本仓库创建的 Fork。 + +第一次使用请完整阅读[开始指南](docs/getting-started.md)。四关的任务和验收规则见[练习说明](docs/exercises.md)。 + +## 自动反馈怎么看 + +机器人会在 PR 中维护一条 `🤖 自动反馈` 评论: + +- **必须修复**:练习目标没有完成,检查会显示红灯,并给出准确修改方法; +- **改进建议**:以 Warning 显示,不阻止练习完成; +- **下一步**:告诉你应该继续 push、解决冲突还是等待自动合并。 + +Commit message 推荐使用 `type: summary` 或 `type(scope): summary`,例如 `docs: add my practice notes`。PR 标题也推荐采用同样风格。格式不规范只会收到 Warning,不会单独导致练习失败。 + +## 需要帮助 + +- 常见报错和恢复命令:[故障排查](docs/troubleshooting.md) +- 常用 Git 命令:[Git 速查表](docs/git-cheatsheet.md) +- 改进课程或自动化:[贡献指南](CONTRIBUTING.md) + +完成四关后,可以寻找带有 `good first issue`、`documentation` 或 `help wanted` 标签的真实开源仓库进行实战。先阅读目标仓库自己的贡献指南,并以它的规则为准。 + +## 给维护者 + +部署标签、仓库权限、分支保护、旧会话迁移和测试账号验收步骤见[维护者手册](docs/maintainers.md)。在完成初始化前,不要对外开放新的 Exercise Issue Forms。 diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..c043f60 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,7 @@ +# Security Policy + +如果发现自动合并、GitHub Actions 权限、命令注入或令牌泄露问题,请不要创建包含利用细节的公开 Issue。优先使用仓库 Security 页面中的私密漏洞报告功能;如果该功能不可用,请联系仓库维护者并只提供最小复现信息。 + +一般文档错误和不会造成越权的判题误报可以使用 Improvement Issue Form。 + +本仓库不会要求贡献者在 Issue、PR 或日志中提供密码、Personal Access Token、SSH 私钥或其他凭据。看到此类请求时请立即停止操作并联系维护者。 diff --git a/docs/exercises.md b/docs/exercises.md new file mode 100644 index 0000000..880776a --- /dev/null +++ b/docs/exercises.md @@ -0,0 +1,105 @@ +# 四关练习说明 + +所有关卡都只允许修改 `.practice/workspace.md`。`session.json`、工作流和仓库文档不属于练习产物,修改它们会被硬性检查阻止。 + +## Exercise 1:第一次贡献 + +目标是完整经历 Fork → branch → commit → push → Pull Request。 + +操作要求: + +1. 把 `workspace.md` 中的 GitHub 用户名改成当前账号; +2. 填写自己希望参与的开源方向; +3. 本关最终只能有一条 commit; +4. PR 正文包含 `Closes #本关Issue编号`。 + +Commit message 和 PR 标题推荐使用 `docs: complete exercise 1`。其他写法可能产生 Warning,但不会单独阻止通过。 + +## Exercise 2:干净的提交历史 + +本关使用全新临时 base 和 topic branch,不依赖上一关遗留的文件。 + +必须按顺序完成两条提交: + +1. 第一条填写“我学到的 Git 命令”; +2. 第二条填写“为什么要保持提交历史干净”。 + +最终 PR 必须恰好有两条 commit,且不能含 merge commit。如果不小心产生多余提交,可练习交互式 rebase: + +```bash +git rebase -i HEAD~3 +``` + +在真实使用前先阅读 `git rebase --help`。不确定时也可以删除当前 topic branch,从机器人 base 重新创建;不要删除 Fork 或练习 Issue。 + +## Exercise 3:响应 Code Review + +第一次 push 并创建 PR 后,机器人一定会提出一次修改要求。此时红灯是课程的一部分,不代表操作失败。 + +在原分支中: + +1. 把状态改为 `状态:已根据反馈修改`; +2. 删除剩余 `TODO`; +3. 新增 `## 修改说明` 并说明改了什么; +4. commit、push 到原分支; +5. 建议在 PR 评论中回复处理结果。 + +机器人会验证 head SHA 已变化,因此不能只编辑 PR 描述或重新运行检查。新建另一个 PR 也不会继承第一次 Review 状态。 + +## Exercise 4:解决上游冲突 + +创建 PR 前,把 `最终内容:待填写` 改为: + +```text +最终内容:我的修改 +``` + +PR 创建后,机器人会把上游 base 的同一行改成 `最终内容:上游更新`。GitHub 随后会显示冲突。 + +### 使用 merge(推荐第一次选择) + +```bash +git fetch upstream YOUR_PRACTICE_BASE +git merge upstream/YOUR_PRACTICE_BASE +``` + +打开冲突文件,会看到三段标记。下面用说明文字代替真实的七个符号,避免仓库自检把教学示例误判为尚未解决的冲突: + +```text +[当前分支开始:七个小于号 + HEAD] +最终内容:我的修改 +[分隔线:七个等号] +最终内容:上游更新 +[上游结束:七个大于号 + upstream/...] +``` + +删除冲突标记并同时保留双方内容: + +```text +最终内容:上游更新 + 我的修改 +``` + +然后执行: + +```bash +git add .practice/workspace.md +git commit +git push +``` + +### 使用 rebase(可选) + +```bash +git fetch upstream YOUR_PRACTICE_BASE +git rebase upstream/YOUR_PRACTICE_BASE +# 编辑并解决冲突 +git add .practice/workspace.md +git rebase --continue +git push --force-with-lease +``` + +只在自己的练习 topic branch 使用 `--force-with-lease`,不要对共享分支使用强制 push。机器人接受 merge 和 rebase 两种结果,并验证注入的上游 commit 已进入分支历史。 + +## 完成课程以后 + +去真实开源仓库寻找适合新贡献者的 Issue。开始前阅读该项目的 README、CONTRIBUTING、测试说明和已有 PR;不同项目对分支、提交、测试和 Review 的要求可能不同,应以目标项目规则为准。 diff --git a/docs/getting-started.md b/docs/getting-started.md new file mode 100644 index 0000000..d58e59a --- /dev/null +++ b/docs/getting-started.md @@ -0,0 +1,103 @@ +# 开始指南 + +本指南以 Git 命令行和 GitHub 网页为主。GitHub Desktop 用户可参考文末对照。 + +## 1. Fork 和 clone + +在仓库页面点击 **Fork**,把仓库复制到自己的 GitHub 账号。然后把 `YOUR_USERNAME` 替换成自己的用户名: + +```bash +git clone https://github.com/YOUR_USERNAME/code-contributing-practice.git +cd code-contributing-practice +git remote add upstream https://github.com/lin594/code-contributing-practice.git +git remote -v +``` + +推荐约定: + +- `origin` 指向你自己的 Fork,可以 push; +- `upstream` 指向本训练仓库,用来获取课程和临时训练分支。 + +如果 `git remote add upstream` 提示 `remote upstream already exists`,说明已经配置过,直接运行 `git remote -v` 检查即可。 + +## 2. 创建练习 Issue + +前往 [New issue](https://github.com/lin594/code-contributing-practice/issues/new/choose),选择当前关卡。创建后机器人会: + +1. 把 Issue 分配给你; +2. 检查上一关是否完成; +3. 创建专属的 `practice/ex...` 上游分支; +4. 评论本关准确命令和创建 PR 的链接。 + +不要自行猜测临时分支名,以机器人评论为准。 + +## 3. 建立 topic branch + +把机器人评论中的分支名代入: + +```bash +git fetch upstream practice/ex1/issue-123-YOUR_USERNAME +git switch -c exercise/1-123 upstream/practice/ex1/issue-123-YOUR_USERNAME +``` + +此时 `.practice/` 中会出现两个文件: + +- `session.json` 是机器人使用的会话清单,不要修改; +- `workspace.md` 是本关唯一需要修改的文件。 + +## 4. Commit 和 push + +```bash +git status +git add .practice/workspace.md +git commit -m "docs: complete exercise 1" +git push -u origin exercise/1-123 +``` + +Commit message 格式是建议而非硬门槛。命令执行前先用 `git diff` 和 `git diff --staged` 确认自己准备提交什么。 + +## 5. 创建 Pull Request + +优先使用机器人在 Issue 中提供的链接,它会预选临时 base 和练习模板。提交前确认: + +- base repository 是 `lin594/code-contributing-practice`; +- base branch 是机器人提供的 `practice/ex...`; +- head repository 是你的 Fork; +- compare branch 是刚才 push 的 topic branch; +- PR 正文包含 `Closes #Issue编号`。 + +练习 PR 指向非默认分支,GitHub 不会原生关闭 Issue;机器人会检查同样的语法,并在练习合并后代为关闭。真实开源仓库的默认分支 PR 通常会原生完成关联。 + +## 6. 处理自动反馈 + +PR 中出现红灯时,不要关闭 PR 或重新创建 PR: + +```bash +# 修改文件后 +git add .practice/workspace.md +git commit -m "docs: address review feedback" +git push +``` + +同一 PR 会自动更新,机器人也会编辑原有反馈评论。Warning 不阻止完成,但建议理解和采纳。 + +通过后,机器人会自动 squash merge、关闭 Issue 并删除上游临时分支。你可以删除自己的本地和 Fork topic branch,再开始下一关: + +```bash +git switch main +git branch -d exercise/1-123 +git push origin --delete exercise/1-123 +``` + +## GitHub Desktop 对照 + +| 命令行操作 | GitHub Desktop | +| --- | --- | +| `git clone` | File → Clone repository | +| `git remote add upstream` | Desktop 没有完整界面支持,建议在 Repository → Open in Terminal 中执行一次 | +| `git switch -c ...` | Current Branch → New Branch,并选择机器人分支作为起点 | +| `git add` + `git commit` | 勾选文件、填写 Summary、点击 Commit | +| `git push` | Push origin | +| 创建 PR | Branch → Create Pull Request | + +Exercise 4 的冲突处理仍建议打开终端完成,因为需要明确理解 upstream、merge/rebase 和冲突标记。 diff --git a/docs/git-cheatsheet.md b/docs/git-cheatsheet.md new file mode 100644 index 0000000..4ca51d1 --- /dev/null +++ b/docs/git-cheatsheet.md @@ -0,0 +1,59 @@ +# Git 速查表 + +## 查看状态和历史 + +```bash +git status +git diff +git diff --staged +git log --oneline --graph --decorate -10 +git branch --show-current +git remote -v +``` + +## 分支 + +```bash +git fetch upstream BRANCH_NAME +git switch -c NEW_BRANCH upstream/BRANCH_NAME +git switch EXISTING_BRANCH +git branch -d FINISHED_BRANCH +``` + +## 提交 + +```bash +git add PATH +git commit -m "docs: explain the change" +git commit --amend +git log --oneline BASE..HEAD +``` + +## 推送 + +```bash +git push -u origin BRANCH_NAME +git push +git push --force-with-lease # 仅用于自己已重写历史的 topic branch +git push origin --delete FINISHED_BRANCH +``` + +## 同步与冲突 + +```bash +git fetch upstream BASE_BRANCH +git merge upstream/BASE_BRANCH +git rebase upstream/BASE_BRANCH +git merge --abort +git rebase --abort +``` + +## 恢复误操作 + +```bash +git restore PATH # 丢弃未暂存的指定文件修改 +git restore --staged PATH # 取消暂存但保留文件修改 +git reflog # 查找近期 HEAD 位置 +``` + +执行恢复或历史重写前先运行 `git status` 和 `git log --oneline --graph`。不要复制自己不理解的 `reset --hard` 或普通 `--force` 命令。 diff --git a/docs/maintainers.md b/docs/maintainers.md new file mode 100644 index 0000000..77f8ce7 --- /dev/null +++ b/docs/maintainers.md @@ -0,0 +1,43 @@ +# 维护者手册 + +## 首次上线 + +1. 合并本次改造后,在 Actions 中运行 **Practice / Administration**,选择 `bootstrap-labels`。 +2. 在仓库 Settings → Actions → General 中允许工作流获得读写 `GITHUB_TOKEN`;每个 workflow 仍使用显式最小权限。 +3. 只启用 squash merge,关闭 merge commit 和 rebase merge。 +4. 为 `main` 建立 ruleset:禁止 force push 和删除,要求 Pull Request、至少一次批准,并要求 `CI / Tests`、`CI / Workflow lint`、`CI / Workflow security`。 +5. 确认 Issues 的自动关闭设置不影响普通维护 PR;练习 Issue 由机器人显式关闭。 +6. 使用测试账号从 Fork 完整走完四关,再公开 Issue Forms。 + +旧会话迁移必须显式运行 **Practice / Administration**:选择 `close-legacy-sessions`,并在 confirmation 输入 `CLOSE_LEGACY`。它只处理带旧 `exercise1`/`exercise2` 标签的 open Issue 及其指向 `main` 的关联 PR。 + +## 权限与安全边界 + +`Practice / Grade` 使用 `pull_request_target`,因为需要给 Fork PR 留言、更新标签和合并临时 base。修改它时必须保证: + +- checkout 始终来自默认分支,且 `persist-credentials: false`; +- 不 fetch、checkout、安装或执行 PR head; +- Fork 的 `workspace.md`、标题、正文和分支名只通过 GitHub API 读取为数据; +- 自动合并 job 重新运行完整判题,并用已判定的 exact head SHA 调用 merge API; +- 练习只能修改 `.practice/workspace.md`,任何工作流、脚本或 manifest 变更都会阻断; +- `automerge:disabled` 和人工 Changes requested 始终优先于机器人结论。 + +CI 中的 `check-source.mjs` 会阻止未固定 SHA 的 Actions 和常见 privileged-checkout 模式。actionlint 下载固定版本,并使用官方 checksums 文件校验归档。 + +## 日常运维 + +- 清理任务每天运行;10 天无学员活动时提醒,14 天时关闭会话并删除 base。 +- 清理失败时可重新运行 **Practice / Cleanup**;所有关闭、标签和删分支操作按幂等方式处理。 +- 学员遇到误判时先加 `automerge:disabled`,保留 PR 和分支现场,再检查反馈对应的 head SHA。 +- 修改纯判题规则必须同时更新 `tests/practice/`;修改操作步骤必须同步课程和排错文档。 +- Dependabot 每周检查 GitHub Actions。升级 Action 时仍必须保留完整 commit SHA,并更新旁边的版本注释。 + +## 验收清单 + +- Exercise 1:一条格式不规范的 commit 只产生 Warning,仍可通过。 +- Exercise 2:一条或三条 commit、merge commit、额外文件均会阻断。 +- Exercise 3:第一次必定请求修改;同一 PR push 新 head 后通过。 +- Exercise 4:PR 打开后确实变为冲突;merge 和 rebase 两种结果均可通过。 +- 通过后 PR 为 merged、Issue 为 completed/closed、临时 base 不存在。 +- 完成任意练习前后,`main` tree 不发生变化。 +- 普通 `main` 维护 PR 只收到建议,永不触发自动合并。 diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md new file mode 100644 index 0000000..44edf26 --- /dev/null +++ b/docs/troubleshooting.md @@ -0,0 +1,101 @@ +# 故障排查 + +## `remote upstream already exists` + +```bash +git remote -v +``` + +如果 URL 错误: + +```bash +git remote set-url upstream https://github.com/lin594/code-contributing-practice.git +``` + +## 找不到机器人提供的分支 + +确认复制了完整分支名: + +```bash +git fetch upstream +git branch -r --list "upstream/practice/*" +``` + +连续 14 天无活动的分支会被清理。已过期时请新建练习 Issue。 + +## PR 的 base 选成了 main + +不要关闭 PR。在 PR 标题旁点击 **Edit**,把 base 改成 Issue 评论中的 `practice/ex...` 分支。如果无法选择,先确认临时分支仍存在。 + +## 修改了不允许的文件 + +先查看变更: + +```bash +git status +git diff +``` + +恢复误改文件时,明确写出文件路径: + +```bash +git restore README.md +``` + +不要使用会丢弃整个工作区的命令。如果文件已经 commit,可从专属 base 重新建立 topic branch,或在了解影响后使用交互式 rebase。 + +## Commit 数量不正确 + +查看本 PR 相对 base 的提交: + +```bash +git log --oneline upstream/YOUR_PRACTICE_BASE..HEAD +``` + +Exercise 1 要求一条,Exercise 2 要求两条。需要修改最近一次 message: + +```bash +git commit --amend -m "docs: complete exercise 1" +git push --force-with-lease +``` + +格式本身只影响 Warning;不要仅为了消除 Warning 在不理解历史重写时强制 push。 + +## 出现 merge conflict + +```bash +git status +``` + +编辑 `both modified` 文件,删除 `<<<<<<<`、`=======`、`>>>>>>>`,决定最终内容后: + +```bash +git add .practice/workspace.md +git commit # merge 流程 +# 或 git rebase --continue +git push +``` + +想放弃当前 merge/rebase: + +```bash +git merge --abort +# 或 git rebase --abort +``` + +## 检查一直没有重新运行 + +确认新 commit 已 push 到 PR 的同一 head branch: + +```bash +git status +git branch --show-current +git log -1 --oneline +git push +``` + +只修改本地文件、只修改 PR 正文或 push 到另一个分支,都不会满足需要新 head SHA 的练习。 + +## 自动合并被暂停 + +如果存在 `automerge:disabled` 标签或维护者提交了 Changes requested,机器人会停止合并。处理人工反馈后请维护者重新确认;不要试图通过修改练习文件绕过。 diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..5de14fa --- /dev/null +++ b/package-lock.json @@ -0,0 +1,15 @@ +{ + "name": "code-contributing-practice", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "code-contributing-practice", + "version": "1.0.0", + "engines": { + "node": ">=22" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..cb665f1 --- /dev/null +++ b/package.json @@ -0,0 +1,14 @@ +{ + "name": "code-contributing-practice", + "version": "1.0.0", + "private": true, + "type": "module", + "engines": { + "node": ">=22" + }, + "scripts": { + "test": "node --test tests/practice/*.test.mjs", + "check:source": "node scripts/practice/check-source.mjs", + "check": "npm run test && npm run check:source" + } +} diff --git a/records/03130214.md b/records/03130214.md deleted file mode 100644 index e69de29..0000000 diff --git a/records/CapooL.md b/records/CapooL.md deleted file mode 100644 index 2fe1cb2..0000000 --- a/records/CapooL.md +++ /dev/null @@ -1 +0,0 @@ -He lived, he loved, he wrote. \ No newline at end of file diff --git a/records/Clear1ove.md b/records/Clear1ove.md deleted file mode 100644 index f06bc2c..0000000 --- a/records/Clear1ove.md +++ /dev/null @@ -1,4 +0,0 @@ -# QuQ - -asdfgjkh - diff --git a/records/FywOoie.md b/records/FywOoie.md deleted file mode 100644 index 2007ef6..0000000 --- a/records/FywOoie.md +++ /dev/null @@ -1,2 +0,0 @@ -Jam a man with fortune and J must seek my fortune --HENRY AEVERIEES 1994.1.11 \ No newline at end of file diff --git a/records/Gmorning730.md b/records/Gmorning730.md deleted file mode 100644 index 93b082a..0000000 --- a/records/Gmorning730.md +++ /dev/null @@ -1,3 +0,0 @@ -![image-20230321225513213](C:\Users\HONOR\AppData\Roaming\Typora\typora-user-images\image-20230321225513213.png) - -瓦达西哇八嘎() diff --git a/records/Gmorning800.md b/records/Gmorning800.md deleted file mode 100644 index 65e88ff..0000000 --- a/records/Gmorning800.md +++ /dev/null @@ -1,2 +0,0 @@ -二战 (._.) -上岸 diff --git a/records/LetMeFly666.md b/records/LetMeFly666.md deleted file mode 100644 index 6d005e4..0000000 --- a/records/LetMeFly666.md +++ /dev/null @@ -1,3 +0,0 @@ -你说的对,但是《原神》是由米哈游自主研发的一款全新开放世界冒险游戏。游戏发生在一个被称作「提瓦特」的幻想世界,在这里,被神选中的人将被授予「神之眼」,导引元素之力。你将扮演一位名为「旅行者」的神秘角色,在自由的旅行中邂逅性格各异、能力独特的同伴们,和他们一起击败强敌,找回失散的亲人——同时,逐步发掘「原神」的真相。 - -![八重神子.jpg](https://uploadstatic.mihoyo.com/ys-obc/2022/02/07/4328207/d91da42730562d579a7bb00b5715ab9a_4062516161434592213.png) diff --git a/records/README.md b/records/README.md deleted file mode 100644 index 668d7cb..0000000 --- a/records/README.md +++ /dev/null @@ -1,10 +0,0 @@ -## 说明 - -### 提交内容 - -以自己的用户名为名的 `markdown` 文件,内容不做限制。 - -### TODO - -- [ ] 多次 commit 之后的练习 -- [ ] 文件冲突的解决 diff --git a/records/Topology2333.md b/records/Topology2333.md deleted file mode 100644 index a502dff..0000000 --- a/records/Topology2333.md +++ /dev/null @@ -1,4 +0,0 @@ -# CEREATED ON 03/17/2023 -## CHINESE REFUSED - -不知道要写什么了,,大青蛙最棒 \ No newline at end of file diff --git a/records/UerLink.md b/records/UerLink.md deleted file mode 100644 index 1f0c066..0000000 --- a/records/UerLink.md +++ /dev/null @@ -1,8 +0,0 @@ -## 练习一 -1. 创建了一个uerlink分支,进行提交但是失败了,删除后再次尝试 -2. 原来不是手动关闭issues -3. doce: 后面有空格 - -## 练习二 -1. 创建了一个新分支 mian-uerlink -![](https://s1.ax1x.com/2022/04/05/qLO7l9.gif)ian \ No newline at end of file diff --git a/records/anchorcola.md b/records/anchorcola.md deleted file mode 100644 index c51ec35..0000000 --- a/records/anchorcola.md +++ /dev/null @@ -1,2 +0,0 @@ -劳动最光荣,本人最没用 -没关系情绪稳定一分钟也很厉害了没关系情绪稳定-一分钟也很厉害了 沒關係 情緒穩定一分鐘也很厲害 沒dhdhb精定神穩一分鐘也厲很害了 沒guan 沒關係精穩①分鐘也很厲shshbs了沒關係shbsjajaksnnx精神穩定一分鐘也很厲害了 沒關係精神穩定一v49'cds&uC5(dJef:,&/9支arfnzId;!&:2$上勾拳!下勾拳!左勾拳!扫堂腿!回旋踢!蜘蛛吃耳屎,龙卷风摧毁停车场!羚羊蹬,山羊跳!乌鸦坐飞机!老鼠走迷宫!大象踢腿!愤怒的章鱼!巨斧砍大树!彻底疯狂!彻底疯狂!彻底疯狂!彻底疯狂!彻底疯狂!彻底疯狂!彻底疯狂!彻底疯狂!彻底疯狂!!!!! diff --git a/records/babuzeer.md b/records/babuzeer.md deleted file mode 100644 index 309e1ca..0000000 --- a/records/babuzeer.md +++ /dev/null @@ -1,144 +0,0 @@ -#include -#include -#include -struct Node{ - int number,age; - char *name,*gender; - struct Node * next; -}; -typedef struct Node * PtrNode; -PtrNode initEmptyList();//初始化链表 -void insertBegin(PtrNode head, int a,char* name,char* gender,int age);//从头插入一个元素 -void printList(PtrNode head);//打印链表 -PtrNode reverselink(PtrNode head);//逆置链表 -void destroyList(PtrNode headPtr);//释放链表 -PtrNode checkout(int start,PtrNode head2);//寻找开始的位置,找到则返回指针 -int countremain(PtrNode head2);//记录剩余人数 -int main(){ - PtrNode head=NULL,head2=NULL; - int n,number,age,start,interval,remain,count=1; - char *name,*gender; - scanf("%d",&n); - head=initEmptyList(); - for(int i=0;iremain){//实际剩余人数大于目标剩余人数则持续进行 - count=1; - while(countnext; - else{ - count++; - control=control->next; - if(control==head2)//循环到头指针时跳过 - control=control->next; - } - } - while(controlfront->next!=control)//得到当前指针的前驱指针 - controlfront=controlfront->next; - controlfront->next=control->next;//记录将要删除节点的下一节点 - printf("%d %s %s %d\n",control->number,control->name,control->gender,control->age); - free(control); - control=controlfront->next;//当前指针指向下一个节点 - } - printList(head2); - destroyList(head2); - return 0; -} -PtrNode initEmptyList(){ - PtrNode head = malloc(sizeof(struct Node));//动态分配新节点 - if ( head != NULL){ - head->next = head; - } - return head; -} -void insertBegin(PtrNode head,int a,char* name,char* gender,int age){ - PtrNode p;//动态分配新节点,将新值存入 - p = malloc(sizeof(struct Node)); - if (p != NULL){ - p->number=a; - p->name=name; - p->gender=gender; - p->age=age; - p->next=head->next;//直接在空节点后链接新节点 - head->next=p; - } - else - printf("Not inserted. No memory avaliable.\n"); -} -void printList(PtrNode head){ - PtrNode cur=head->next; //跳过空节点 - if (cur==head) - printf("The list is empty.\n"); - else{ - printf("The list is:\n"); - while(cur!=head){ - printf("%d %s %s %d\n",cur->number,cur->name,cur->gender,cur->age); - cur = cur->next; - } - cur=cur->next; - } -} -void destroyList(PtrNode headPtr) -{ - PtrNode tempPtr; - while (headPtr->next!=headPtr){ - tempPtr=headPtr->next; - headPtr->next=tempPtr->next; - free(tempPtr); - } - tempPtr=headPtr; - free(tempPtr); - headPtr=NULL; -} -PtrNode reverselink(PtrNode head) -{ - PtrNode temp=head->next,track=NULL,head2=NULL; - head2=initEmptyList(); - while(temp!=head){ - track=head2->next;//记录链表2后继 - head2->next=temp;//读取链表1中元素 - temp=temp->next;//移向下一个节点 - head2->next->next=track;//将链表2后继连上去 - } - free(head); - return head2; -} -PtrNode checkout(int start,PtrNode head2) -{ - PtrNode check=NULL; - check=head2->next; - while(check->next!=head2){//遍历链表,按编号寻找开始位置 - if(check->number==start) - return check; - check=check->next; - } - if(check->number!=start) - return NULL; - return NULL; -} -int countremain(PtrNode head2) -{ - int num=1; - PtrNode temp=head2->next; - if(temp==head2) - num=0; - while(temp->next!=head2){ - num++; - temp=temp->next; - } - return num; -} \ No newline at end of file diff --git a/records/butteruni.md b/records/butteruni.md deleted file mode 100644 index 81403e4..0000000 --- a/records/butteruni.md +++ /dev/null @@ -1 +0,0 @@ -test 2 \ No newline at end of file diff --git a/records/cont1nu1ty.md b/records/cont1nu1ty.md deleted file mode 100644 index af6b537..0000000 --- a/records/cont1nu1ty.md +++ /dev/null @@ -1 +0,0 @@ -这是我的第一次 PR diff --git a/records/hyttest.md b/records/hyttest.md deleted file mode 100644 index d461bd7..0000000 --- a/records/hyttest.md +++ /dev/null @@ -1 +0,0 @@ -试一下。 diff --git a/records/kahakaha.md b/records/kahakaha.md deleted file mode 100644 index bb40e9c..0000000 --- a/records/kahakaha.md +++ /dev/null @@ -1 +0,0 @@ -你说得对,但是`<>`是由大青蛙自主研发的一款全新开放世界代码提交游戏。游戏发生在一个被称作`github`的幻想世界,在这里,被bot选中的人将被授予`issue`,导引开源之力。你将扮演一位名为`contributor`的神秘角色,在自由的旅行中邂逅性格各异、能力独特的coder们,和他们一起击败强敌,cv各种代码。同时,逐步发掘`github`的真相。 \ No newline at end of file diff --git a/records/lxirang.md b/records/lxirang.md deleted file mode 100644 index a733e4c..0000000 --- a/records/lxirang.md +++ /dev/null @@ -1,2 +0,0 @@ -01 -10 diff --git a/records/moyu.md b/records/moyu.md deleted file mode 100644 index 7b467a2..0000000 --- a/records/moyu.md +++ /dev/null @@ -1 +0,0 @@ -1111111111111111111111111 \ No newline at end of file diff --git a/records/mtzhao0827.md b/records/mtzhao0827.md deleted file mode 100644 index 9a80a22..0000000 --- a/records/mtzhao0827.md +++ /dev/null @@ -1,2 +0,0 @@ -hello - diff --git a/records/norton_lin.md b/records/norton_lin.md deleted file mode 100644 index 951b5df..0000000 --- a/records/norton_lin.md +++ /dev/null @@ -1,2 +0,0 @@ -# here is my profile - 事实上我也不知道青蛙要干嘛 \ No newline at end of file diff --git a/records/yyf123.md b/records/yyf123.md deleted file mode 100644 index d7950de..0000000 --- a/records/yyf123.md +++ /dev/null @@ -1,6 +0,0 @@ -### test - -username - -password - diff --git a/records/zzzYmq.md b/records/zzzYmq.md deleted file mode 100644 index f5672a4..0000000 --- a/records/zzzYmq.md +++ /dev/null @@ -1 +0,0 @@ -#1111 by zzzYmq second diff --git a/scripts/practice/check-source.mjs b/scripts/practice/check-source.mjs new file mode 100644 index 0000000..504fa94 --- /dev/null +++ b/scripts/practice/check-source.mjs @@ -0,0 +1,92 @@ +import fs from "node:fs"; +import path from "node:path"; +import { spawnSync } from "node:child_process"; + +const root = process.cwd(); +const errors = []; + +function walk(directory) { + return fs.readdirSync(directory, { withFileTypes: true }).flatMap((entry) => { + if ([".git", "node_modules"].includes(entry.name)) return []; + const full = path.join(directory, entry.name); + return entry.isDirectory() ? walk(full) : [full]; + }); +} + +const files = walk(root); +for (const file of files.filter((name) => name.endsWith(".mjs"))) { + const result = spawnSync(process.execPath, ["--check", file], { encoding: "utf8", shell: false }); + if (result.status !== 0) errors.push(`${path.relative(root, file)}: ${result.stderr.trim()}`); +} + +for (const file of files.filter((name) => name.endsWith(".md"))) { + const relative = path.relative(root, file); + const source = fs.readFileSync(file, "utf8"); + const lines = source.split("\n"); + const headings = []; + let fences = 0; + let inFence = false; + lines.forEach((line, index) => { + if (/[ \t]+$/.test(line)) errors.push(`${relative}:${index + 1}: trailing whitespace`); + if (line.includes("https://github.com/FrogDar/")) errors.push(`${relative}:${index + 1}: obsolete repository URL`); + if (/^```/.test(line)) { + fences += 1; + inFence = !inFence; + return; + } + if (inFence) return; + const heading = line.match(/^(#{1,6})\s+\S/); + if (heading) headings.push({ level: heading[1].length, line: index + 1 }); + }); + const isPullRequestTemplate = relative.startsWith(path.join(".github", "PULL_REQUEST_TEMPLATE")); + if (!isPullRequestTemplate && headings[0]?.level !== 1) errors.push(`${relative}: first heading must be H1`); + if (!isPullRequestTemplate && headings.filter((heading) => heading.level === 1).length !== 1) errors.push(`${relative}: exactly one H1 is required`); + headings.slice(1).forEach((heading, index) => { + if (heading.level > headings[index].level + 1) errors.push(`${relative}:${heading.line}: heading level jumps from H${headings[index].level} to H${heading.level}`); + }); + if (fences % 2 !== 0) errors.push(`${relative}: unbalanced fenced code block`); + + for (const match of source.matchAll(/\[[^\]]+\]\(([^)]+)\)/g)) { + const target = match[1].split("#", 1)[0].split("?", 1)[0]; + if (!target || /^(?:https?:|mailto:)/.test(target)) continue; + const resolved = path.resolve(path.dirname(file), decodeURIComponent(target)); + if (!fs.existsSync(resolved)) errors.push(`${relative}: broken local link ${match[1]}`); + } +} + +const workflowDirectory = path.join(root, ".github", "workflows"); +if (fs.existsSync(workflowDirectory)) { + for (const file of walk(workflowDirectory).filter((name) => /\.ya?ml$/.test(name))) { + const relative = path.relative(root, file); + const source = fs.readFileSync(file, "utf8"); + for (const [index, line] of source.split("\n").entries()) { + const uses = line.match(/^\s*-?\s*uses:\s*([^\s#]+)/); + if (uses && !uses[1].startsWith("./") && !/@[0-9a-f]{40}$/.test(uses[1])) { + errors.push(`${relative}:${index + 1}: action must be pinned to a full commit SHA`); + } + } + if (!/^permissions:/m.test(source)) errors.push(`${relative}: explicit permissions block is required`); + if (/pull_request_target:/.test(source)) { + const forbidden = [ + /github\.event\.pull_request\.head\.sha/, + /github\.event\.pull_request\.head\.ref/, + /gh\s+pr\s+checkout/, + /git\s+(?:fetch|checkout).*pull/, + /npm\s+(?:install|ci)/, + ]; + for (const pattern of forbidden) { + if (pattern.test(source)) errors.push(`${relative}: privileged workflow contains unsafe pattern ${pattern}`); + } + if (/uses:\s*actions\/checkout@/.test(source) && !/persist-credentials:\s*false/.test(source)) { + errors.push(`${relative}: privileged checkout must disable persisted credentials`); + } + } + } +} + +if (errors.length) { + console.error(errors.join("\n")); + process.exitCode = 1; +} else { + console.log(`Source checks passed for ${files.length} files.`); +} diff --git a/scripts/practice/constants.mjs b/scripts/practice/constants.mjs new file mode 100644 index 0000000..1581f07 --- /dev/null +++ b/scripts/practice/constants.mjs @@ -0,0 +1,34 @@ +export const SCHEMA_VERSION = 1; +export const SESSION_FILE = ".practice/session.json"; +export const WORKSPACE_FILE = ".practice/workspace.md"; +export const FEEDBACK_MARKER = "practice-feedback:v1"; +export const SESSION_MARKER = "practice-session:v1"; + +export const REQUIRED = "required"; +export const ADVISORY = "advisory"; + +export const EXERCISE_LABELS = new Map([ + [1, "exercise:1"], + [2, "exercise:2"], + [3, "exercise:3"], + [4, "exercise:4"], +]); + +export const STATUS_LABELS = [ + "session:active", + "session:blocked", + "session:needs-fix", + "session:ready", + "session:completed", + "session:expired", +]; + +export const ALL_MANAGED_LABELS = [ + ...EXERCISE_LABELS.values(), + ...STATUS_LABELS, + "automerge:disabled", +]; + +export const CONVENTIONAL_COMMIT = /^(build|ci|docs|feat|fix|perf|refactor|test|style|chore|revert)(\([a-z0-9][a-z0-9-]*\))?: \S.{0,100}$/; +export const CLOSING_REFERENCE = /\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s*:?\s*#(\d+)\b/gi; +export const SESSION_BRANCH = /^practice\/ex([1-4])\/issue-(\d+)-([A-Za-z0-9-]{1,39})$/; diff --git a/scripts/practice/feedback.mjs b/scripts/practice/feedback.mjs new file mode 100644 index 0000000..b50fca3 --- /dev/null +++ b/scripts/practice/feedback.mjs @@ -0,0 +1,71 @@ +import { ADVISORY, FEEDBACK_MARKER, REQUIRED } from "./constants.mjs"; + +function escapeCell(value) { + return String(value ?? "") + .replaceAll("&", "&") + .replaceAll("<", "<") + .replaceAll(">", ">") + .replaceAll("|", "\\|") + .replaceAll("\n", " ") + .replaceAll("`", "\\`"); +} + +function icon(status) { + return { pass: "✅", fail: "❌", warn: "⚠️", pending: "⏳" }[status] ?? "•"; +} + +function table(items) { + if (!items.length) return "_无_"; + const rows = items.map((item) => `| ${icon(item.status)} | \`${escapeCell(item.id)}\` | ${escapeCell(item.summary)} | ${escapeCell(item.remediation || "—")} |`); + return ["| 结果 | 检查项 | 说明 | 怎么做 |", "| --- | --- | --- | --- |", ...rows].join("\n"); +} + +export function encodeFeedbackState(state = {}) { + return Buffer.from(JSON.stringify(state), "utf8").toString("base64url"); +} + +export function parseFeedbackState(body = "") { + const match = body.match(//); + if (!match) return {}; + try { + return JSON.parse(Buffer.from(match[1], "base64url").toString("utf8")); + } catch { + return {}; + } +} + +export function renderFeedback(report, state = {}) { + const required = report.results.filter((item) => item.level === REQUIRED); + const advisory = report.results.filter((item) => item.level === ADVISORY); + const passed = report.outcome === "pass"; + const heading = report.outcome === "maintenance" + ? "## 🤖 维护 PR 自动建议" + : `## 🤖 练习 ${report.session.exercise} 自动反馈`; + const summary = report.outcome === "maintenance" + ? "这个 PR 需要维护者 Review,不会自动合并。" + : passed + ? report.warnings + ? "**练习已通过。** 以下 Warning 不阻止合并,但能帮助你适应真实开源仓库。" + : "**练习已通过。** 机器人将自动完成合并和清理。" + : "**练习尚未通过。** 请先处理“必须修复”中的失败项。"; + const next = report.nextActions.map((item, index) => `${index + 1}. ${item}`).join("\n"); + return ` +${heading} + +${summary} + +### 必须修复 + +${table(required)} + +### 改进建议 + +${table(advisory)} + +### 下一步 + +${next} + +反馈对应 head \`${report.headSha.slice(0, 12)}\`,更新当前分支后机器人会编辑这条评论。 +`; +} diff --git a/scripts/practice/github.mjs b/scripts/practice/github.mjs new file mode 100644 index 0000000..3bdf55e --- /dev/null +++ b/scripts/practice/github.mjs @@ -0,0 +1,151 @@ +const API_ROOT = "https://api.github.com"; + +export class GitHubApiError extends Error { + constructor(message, { status, body, method, path }) { + super(message); + this.name = "GitHubApiError"; + this.status = status; + this.body = body; + this.method = method; + this.path = path; + } +} + +export class GitHubClient { + constructor({ token, repository, fetchImpl = globalThis.fetch }) { + if (!repository || !repository.includes("/")) throw new Error("repository must be owner/name"); + if (typeof fetchImpl !== "function") throw new Error("fetch is unavailable"); + this.token = token; + this.repository = repository; + this.fetch = fetchImpl; + } + + repoPath(path, repository = this.repository) { + return `/repos/${repository}${path}`; + } + + async request(method, path, body) { + const url = path.startsWith("http") ? path : `${API_ROOT}${path}`; + const response = await this.fetch(url, { + method, + headers: { + Accept: "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28", + "User-Agent": "code-contributing-practice", + ...(this.token ? { Authorization: `Bearer ${this.token}` } : {}), + ...(body === undefined ? {} : { "Content-Type": "application/json" }), + }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), + }); + const text = await response.text(); + let payload = null; + if (text) { + try { + payload = JSON.parse(text); + } catch { + payload = text; + } + } + if (!response.ok) { + throw new GitHubApiError(`GitHub API ${method} ${path} failed with ${response.status}`, { + status: response.status, + body: payload, + method, + path, + }); + } + return payload; + } + + get(path) { return this.request("GET", path); } + post(path, body) { return this.request("POST", path, body); } + patch(path, body) { return this.request("PATCH", path, body); } + put(path, body) { return this.request("PUT", path, body); } + delete(path) { return this.request("DELETE", path); } + + async paginate(path, { maxPages = 10 } = {}) { + const join = path.includes("?") ? "&" : "?"; + const items = []; + for (let page = 1; page <= maxPages; page += 1) { + const payload = await this.get(`${path}${join}per_page=100&page=${page}`); + if (!Array.isArray(payload)) throw new Error(`Expected array from ${path}`); + items.push(...payload); + if (payload.length < 100) break; + } + return items; + } + + async getRef(branch) { + return this.get(this.repoPath(`/git/ref/heads/${encodeURIComponent(branch)}`)); + } + + async createRef(branch, sha) { + return this.post(this.repoPath("/git/refs"), { ref: `refs/heads/${branch}`, sha }); + } + + async deleteRef(branch) { + try { + await this.delete(this.repoPath(`/git/refs/heads/${encodeURIComponent(branch)}`)); + return true; + } catch (error) { + if (error instanceof GitHubApiError && error.status === 404) return false; + throw error; + } + } + + async commitFiles(branch, files, message) { + const ref = await this.getRef(branch); + const parentSha = ref.object.sha; + const parent = await this.get(this.repoPath(`/git/commits/${parentSha}`)); + const treeItems = []; + for (const [path, content] of Object.entries(files)) { + const blob = await this.post(this.repoPath("/git/blobs"), { + content: Buffer.from(content, "utf8").toString("base64"), + encoding: "base64", + }); + treeItems.push({ path, mode: "100644", type: "blob", sha: blob.sha }); + } + const tree = await this.post(this.repoPath("/git/trees"), { + base_tree: parent.tree.sha, + tree: treeItems, + }); + const commit = await this.post(this.repoPath("/git/commits"), { + message, + tree: tree.sha, + parents: [parentSha], + }); + await this.patch(this.repoPath(`/git/refs/heads/${encodeURIComponent(branch)}`), { + sha: commit.sha, + force: false, + }); + return commit; + } + + async getContent(path, ref, repository = this.repository) { + const payload = await this.get(this.repoPath(`/contents/${path}?ref=${encodeURIComponent(ref)}`, repository)); + if (Array.isArray(payload) || payload.type !== "file" || payload.encoding !== "base64") { + throw new Error(`${path} at ${ref} is not a base64 file`); + } + return Buffer.from(payload.content.replaceAll("\n", ""), "base64").toString("utf8"); + } + + async upsertComment(issueNumber, marker, body) { + const comments = await this.paginate(this.repoPath(`/issues/${issueNumber}/comments`)); + const existing = comments.find((comment) => comment.user?.type === "Bot" && comment.body?.includes(marker)); + if (existing) return this.patch(this.repoPath(`/issues/comments/${existing.id}`), { body }); + return this.post(this.repoPath(`/issues/${issueNumber}/comments`), { body }); + } + + async setStatusLabel(issueNumber, nextStatus) { + const issue = await this.get(this.repoPath(`/issues/${issueNumber}`)); + const labels = issue.labels.map((label) => label.name).filter((name) => !name.startsWith("session:")); + if (nextStatus) labels.push(nextStatus); + return this.put(this.repoPath(`/issues/${issueNumber}/labels`), { labels: [...new Set(labels)] }); + } +} + +export function parseRepository(repository) { + const [owner, name, ...rest] = String(repository ?? "").split("/"); + if (!owner || !name || rest.length) throw new Error("GITHUB_REPOSITORY must be owner/name"); + return { owner, name }; +} diff --git a/scripts/practice/grade.mjs b/scripts/practice/grade.mjs new file mode 100644 index 0000000..0489de7 --- /dev/null +++ b/scripts/practice/grade.mjs @@ -0,0 +1,206 @@ +import { + ADVISORY, + CLOSING_REFERENCE, + CONVENTIONAL_COMMIT, + EXERCISE_LABELS, + REQUIRED, + WORKSPACE_FILE, +} from "./constants.mjs"; +import { validateManifest } from "./session.mjs"; + +function rule(id, level, status, summary, remediation = "") { + return { id, level, status, summary, remediation }; +} + +function pass(id, level, summary) { + return rule(id, level, "pass", summary); +} + +function fail(id, summary, remediation) { + return rule(id, REQUIRED, "fail", summary, remediation); +} + +function warn(id, summary, remediation) { + return rule(id, ADVISORY, "warn", summary, remediation); +} + +function pending(id, summary, remediation) { + return rule(id, REQUIRED, "pending", summary, remediation); +} + +export function closingIssueNumbers(body = "") { + const numbers = new Set(); + for (const match of body.matchAll(CLOSING_REFERENCE)) numbers.add(Number(match[1])); + return [...numbers]; +} + +function labelsOf(value = []) { + return value.map((label) => (typeof label === "string" ? label : label.name)); +} + +function gradeCommon(input, results) { + const { pr, session, issue, files = [], commits = [] } = input; + + if (!validateManifest(session)) { + results.push(fail("session.valid", "训练会话清单无效或已损坏。", "请回到练习 Issue 重新创建会话,不要修改 session.json。")); + return false; + } + results.push(pass("session.valid", REQUIRED, "训练会话有效。")); + + const references = closingIssueNumbers(pr.body); + if (!references.includes(session.issueNumber)) { + results.push(fail("pr.closing-reference", `PR 正文没有正确引用练习 Issue #${session.issueNumber}。`, `在 PR 正文加入 \`Closes #${session.issueNumber}\`。`)); + } else { + results.push(pass("pr.closing-reference", REQUIRED, `PR 已引用 Issue #${session.issueNumber}。`)); + } + + const expectedLabel = EXERCISE_LABELS.get(session.exercise); + const issueLabels = labelsOf(issue.labels); + const sameOwner = pr.author.toLowerCase() === session.actor.toLowerCase() && issue.author.toLowerCase() === session.actor.toLowerCase(); + const assigned = issue.assignees.some((login) => login.toLowerCase() === session.actor.toLowerCase()); + if (issue.number !== session.issueNumber || issue.state !== "open" || !sameOwner || !assigned || !issueLabels.includes(expectedLabel)) { + results.push(fail("issue.ownership", "PR 没有关联到本人已认领的正确练习 Issue。", "请使用机器人创建的专属分支,并确认 PR 作者、Issue 作者和 assignee 是同一账号。")); + } else { + results.push(pass("issue.ownership", REQUIRED, "Issue、PR 和练习账号一致。")); + } + + if (pr.baseRef !== session.baseBranch) { + results.push(fail("branch.base", `PR base 当前是 ${pr.baseRef},不是专属训练分支。`, `在 PR 页面把 base 改为 \`${session.baseBranch}\`。`)); + } else { + results.push(pass("branch.base", REQUIRED, "PR 指向正确的专属训练分支。")); + } + + if (["main", "master"].includes(pr.headRef.toLowerCase())) { + results.push(fail("branch.head", "不要直接使用 Fork 的 main/master 分支提交练习。", `创建 topic branch,例如 \`exercise/${session.exercise}-${session.issueNumber}\`,再更新 PR。`)); + } else { + results.push(pass("branch.head", REQUIRED, "练习来自独立 topic branch。")); + } + + const changedPaths = files.map((file) => file.filename); + if (files.length !== 1 || changedPaths[0] !== WORKSPACE_FILE || files[0].status !== "modified") { + results.push(fail("files.scope", `练习只能修改 ${WORKSPACE_FILE},当前变更:${changedPaths.join(", ") || "无"}。`, `撤销其他文件的改动,并确保只修改 \`${WORKSPACE_FILE}\`。`)); + } else { + results.push(pass("files.scope", REQUIRED, "改动范围正确,session.json 保持不变。")); + } + + if (pr.draft) { + results.push(fail("pr.ready", "Draft PR 不会自动完成练习。", "准备好后在 PR 页面点击 “Ready for review”。")); + } else { + results.push(pass("pr.ready", REQUIRED, "PR 已进入可评审状态。")); + } + + const prLabels = labelsOf(pr.labels); + if (prLabels.includes("automerge:disabled") || input.humanChangesRequested) { + results.push(fail("merge.allowed", "维护者已暂停自动合并或提出必须处理的修改。", "先处理维护者反馈;确认无误后请维护者移除阻止状态。")); + } else { + results.push(pass("merge.allowed", REQUIRED, "没有人工阻止自动合并。")); + } + + const nonConventional = commits.filter((commit) => !CONVENTIONAL_COMMIT.test(commit.message.split("\n", 1)[0])); + if (nonConventional.length) { + results.push(warn("commits.message", `有 ${nonConventional.length} 条 commit message 不符合推荐格式。`, `推荐使用 \`type: summary\`,例如 \`docs: add my practice notes\`;最近一次可用 \`git commit --amend\` 修改。`)); + } else { + results.push(pass("commits.message", ADVISORY, "Commit message 符合推荐格式。")); + } + + const noisy = commits.filter((commit) => /^(?:wip\b|fixup!|squash!)/i.test(commit.message)); + if (noisy.length) { + results.push(warn("commits.polish", "提交历史中含 WIP、fixup! 或 squash! 标记。", "真实开源贡献前通常会整理这些临时提交;本练习不会因此失败。")); + } + + const title = pr.title.trim(); + if (title.length < 10 || title.length > 72 || /^(update|test|pr|练习|修改|提交)$/i.test(title) || !CONVENTIONAL_COMMIT.test(title)) { + results.push(warn("pr.title", `PR 标题“${title || "(空)"}”可以更清楚。`, `建议使用动作明确的标题,例如 \`docs: complete exercise ${session.exercise}\`;可直接在 GitHub PR 页面编辑。`)); + } else { + results.push(pass("pr.title", ADVISORY, "PR 标题清楚且符合推荐格式。")); + } + + if (!/^(?:exercise|docs|feat|fix)\//.test(pr.headRef)) { + results.push(warn("branch.name", `分支名“${pr.headRef}”可以表达得更清楚。`, `建议使用 \`exercise/${session.exercise}-${session.issueNumber}\`。`)); + } + + return true; +} + +function gradeExercise(input, results) { + const { session, commits = [], workspace = "", feedbackState = {} } = input; + const hasMergeCommit = commits.some((commit) => (commit.parents?.length ?? 1) > 1); + + if (session.exercise === 1) { + if (commits.length !== 1) results.push(fail("exercise1.commit-count", `练习 1 需要 1 条提交,当前有 ${commits.length} 条。`, "请使用交互式 rebase 或重新建立练习分支,把本关整理为一条提交。")); + else results.push(pass("exercise1.commit-count", REQUIRED, "练习 1 恰好包含一条提交。")); + if (hasMergeCommit) results.push(fail("exercise1.no-merge", "第一次贡献不应包含 merge commit。", "从专属 base 重新建立 topic branch,并用一条普通提交完成练习。")); + + const complete = !workspace.includes("TODO") && workspace.toLowerCase().includes(session.actor.toLowerCase()) && workspace.length >= 60; + if (!complete) results.push(fail("exercise1.workspace", "自我介绍仍有占位符,或没有填写当前 GitHub 用户名。", `把 TODO 替换为你的内容,并在“GitHub 用户名”中填写 ${session.actor}。`)); + else results.push(pass("exercise1.workspace", REQUIRED, "第一次贡献内容已填写完整。")); + } + + if (session.exercise === 2) { + if (commits.length !== 2) results.push(fail("exercise2.commit-count", `练习 2 需要 2 条提交,当前有 ${commits.length} 条。`, "请让第一个 commit 填写 Git 命令,第二个 commit 解释干净历史;多余提交可用 rebase 整理。")); + else results.push(pass("exercise2.commit-count", REQUIRED, "练习 2 恰好包含两条提交。")); + if (hasMergeCommit) results.push(fail("exercise2.no-merge", "练习 2 的历史中包含 merge commit。", "从专属 base 重新建立分支,或使用 rebase 整理为两条线性提交。")); + else results.push(pass("exercise2.no-merge", REQUIRED, "提交历史保持线性,没有混入 merge commit。")); + const complete = !workspace.includes("TODO") && workspace.includes("## 我学到的 Git 命令") && workspace.includes("## 为什么要保持提交历史干净"); + if (!complete) results.push(fail("exercise2.workspace", "两部分练习内容尚未填写完整。", "分别在第一、第二条提交中完成模板的两个 TODO。")); + else results.push(pass("exercise2.workspace", REQUIRED, "两次提交对应的内容均已完成。")); + } + + if (session.exercise === 3) { + if (!feedbackState.revisionRequestedSha) { + results.push(pending("exercise3.review", "机器人已完成第一次 Review,正在等待你修改。", "保留当前 PR,在同一分支继续修改、commit 和 push;不要新建 PR。")); + } else if (feedbackState.revisionRequestedSha === input.pr.headSha) { + results.push(pending("exercise3.review", "PR 还停留在机器人提出修改时的 commit。", "按照评论修改后,在当前分支 commit 并 push。")); + } else { + const complete = workspace.includes("状态:已根据反馈修改") && workspace.includes("## 修改说明") && !workspace.includes("TODO"); + if (!complete) results.push(fail("exercise3.review", "已经收到新提交,但指定的 Review 修改尚未完整落实。", "把状态改为“已根据反馈修改”,新增“## 修改说明”,并删除 TODO。")); + else results.push(pass("exercise3.review", REQUIRED, "已在同一 PR 中完成 Review 修改。")); + if (!input.authorResponded) results.push(warn("exercise3.response", "尚未看到你对机器人反馈的文字回应。", "建议在 PR 留言简要说明你修改了什么,这是良好的开源协作习惯。")); + } + if (hasMergeCommit) results.push(fail("exercise3.no-merge", "本关不需要 merge commit。", "继续在原 topic branch 上直接 commit/push,必要时用 rebase 整理历史。")); + } + + if (session.exercise === 4) { + if (!session.conflictBaseSha) { + results.push(pending("exercise4.injected", "机器人正在准备上游冲突。", "稍后刷新 PR,按评论执行 fetch 并解决冲突。")); + } else if (!input.conflictBaseIncluded) { + results.push(fail("exercise4.ancestry", "你的分支尚未包含机器人注入的上游更新。", `执行 \`git fetch upstream ${session.baseBranch}\`,再 merge 或 rebase 该分支并解决冲突。`)); + } else { + results.push(pass("exercise4.ancestry", REQUIRED, "分支已纳入最新上游提交。")); + } + if (!workspace.includes("上游更新") || !workspace.includes("我的修改")) { + results.push(fail("exercise4.resolution", "冲突结果没有同时保留“上游更新”和“我的修改”。", "编辑冲突标记之间的内容,保留双方文字,再 git add、commit 并 push。")); + } else { + results.push(pass("exercise4.resolution", REQUIRED, "冲突解决结果保留了双方内容。")); + } + } +} + +export function gradePractice(input) { + const results = []; + const validSession = gradeCommon(input, results); + if (validSession) gradeExercise(input, results); + const blocked = results.some((item) => item.level === REQUIRED && ["fail", "pending"].includes(item.status)); + const warnings = results.filter((item) => item.status === "warn").length; + return { + schemaVersion: 1, + outcome: blocked ? "fail" : "pass", + headSha: input.pr.headSha, + session: input.session, + results, + warnings, + nextActions: blocked + ? ["按“必须修复”表格逐项修改。", "继续 push 当前 PR 的分支,机器人会自动复查。"] + : ["练习已通过,机器人将自动 squash merge。", warnings ? "Warning 不阻止完成,但建议在真实开源贡献前采纳。" : "可以继续下一关。"], + }; +} + +export function maintenanceReport(pr, commits = []) { + const results = []; + const invalid = commits.filter((commit) => !CONVENTIONAL_COMMIT.test(commit.message.split("\n", 1)[0])); + if (invalid.length) results.push(warn("commits.message", "部分 commit message 不符合推荐格式。", "建议使用 type: summary,例如 docs: improve troubleshooting guide。")); + else results.push(pass("commits.message", ADVISORY, "Commit message 符合推荐格式。")); + if (!CONVENTIONAL_COMMIT.test(pr.title.trim())) results.push(warn("pr.title", "PR 标题可以更清楚。", "建议使用 type: summary;维护 PR 仍需人工 Review。")); + else results.push(pass("pr.title", ADVISORY, "PR 标题符合推荐格式。")); + return { schemaVersion: 1, outcome: "maintenance", headSha: pr.headSha, session: null, results, warnings: results.filter((r) => r.status === "warn").length, nextActions: ["这是维护 PR,不会自动合并。", "等待 CI 和维护者 Review。"] }; +} diff --git a/scripts/practice/lifecycle.mjs b/scripts/practice/lifecycle.mjs new file mode 100644 index 0000000..0d10244 --- /dev/null +++ b/scripts/practice/lifecycle.mjs @@ -0,0 +1,40 @@ +export function assertMergeEligible({ report, input, expectedHead }) { + if (report.outcome !== "pass" || !input?.session) { + throw new Error("PR no longer passes the practice rules"); + } + if (!expectedHead || report.headSha !== expectedHead) { + throw new Error("PR head changed after grading; refusing stale merge"); + } + return true; +} + +export function canInjectConflict({ pr, manifest, referencedIssues }) { + return ( + manifest?.exercise === 4 && + !manifest.conflictBaseSha && + pr?.base?.ref === manifest.baseBranch && + pr?.user?.login?.toLowerCase() === manifest.actor?.toLowerCase() && + referencedIssues.includes(manifest.issueNumber) + ); +} + +export function hasBlockingReview(reviews) { + const blocked = new Map(); + for (const review of reviews) { + if (review.user?.type === "Bot") continue; + const login = review.user?.login; + if (!login) continue; + if (review.state === "CHANGES_REQUESTED") blocked.set(login, true); + if (["APPROVED", "DISMISSED"].includes(review.state)) blocked.set(login, false); + } + return [...blocked.values()].some(Boolean); +} + +export function expiryDecision(lastActivity, { now = Date.now(), remindAfterDays = 10, expireAfterDays = 14 } = {}) { + const timestamp = Date.parse(lastActivity); + if (!Number.isFinite(timestamp)) throw new Error("lastActivity must be an ISO date"); + const inactiveDays = (now - timestamp) / 86_400_000; + if (inactiveDays >= expireAfterDays) return { action: "expire", inactiveDays }; + if (inactiveDays >= remindAfterDays) return { action: "remind", inactiveDays }; + return { action: "none", inactiveDays }; +} diff --git a/scripts/practice/session.mjs b/scripts/practice/session.mjs new file mode 100644 index 0000000..1daf5f5 --- /dev/null +++ b/scripts/practice/session.mjs @@ -0,0 +1,141 @@ +import { + EXERCISE_LABELS, + SCHEMA_VERSION, + SESSION_BRANCH, + SESSION_FILE, + WORKSPACE_FILE, +} from "./constants.mjs"; + +export function branchNameFor({ exercise, issueNumber, actor }) { + if (!Number.isInteger(exercise) || exercise < 1 || exercise > 4) { + throw new Error("exercise must be an integer from 1 to 4"); + } + if (!Number.isInteger(issueNumber) || issueNumber < 1) { + throw new Error("issueNumber must be a positive integer"); + } + if (!/^[A-Za-z0-9-]{1,39}$/.test(actor)) { + throw new Error("actor is not a valid GitHub login"); + } + return `practice/ex${exercise}/issue-${issueNumber}-${actor}`; +} + +export function parseSessionBranch(branch) { + const match = SESSION_BRANCH.exec(branch ?? ""); + if (!match) return null; + return { + exercise: Number(match[1]), + issueNumber: Number(match[2]), + actor: match[3], + }; +} + +export function createManifest({ exercise, issueNumber, actor, createdAt = new Date().toISOString() }) { + return { + schemaVersion: SCHEMA_VERSION, + exercise, + issueNumber, + actor, + baseBranch: branchNameFor({ exercise, issueNumber, actor }), + state: "active", + createdAt, + }; +} + +export function validateManifest(manifest) { + if (!manifest || manifest.schemaVersion !== SCHEMA_VERSION) return false; + try { + return ( + manifest.baseBranch === branchNameFor(manifest) && + ["active", "review-requested", "conflict-injected", "completed"].includes(manifest.state) + ); + } catch { + return false; + } +} + +export function workspaceTemplate(exercise) { + const templates = { + 1: `# 我的第一次开源贡献 + +- GitHub 用户名:TODO +- 我希望参与的开源方向:TODO + +请把两处 \`TODO\` 替换成你自己的内容。 +`, + 2: `# 干净的提交历史 + +## 我学到的 Git 命令 + +TODO:请在第一个 commit 中填写。 + +## 为什么要保持提交历史干净 + +TODO:请在第二个 commit 中填写。 +`, + 3: `# 响应 Code Review + +状态:初稿 + +## 本次修改 + +TODO:先写下你的初稿并创建 PR。机器人会在 PR 中提出修改要求。 +`, + 4: `# 解决上游冲突 + +## 最终决定 + +最终内容:待填写 + +创建 PR 前,请把“待填写”改成“我的修改”。机器人随后会更新上游的同一行。 +`, + }; + if (!templates[exercise]) throw new Error("unknown exercise"); + return templates[exercise]; +} + +export function sessionFiles(manifest) { + return { + [SESSION_FILE]: `${JSON.stringify(manifest, null, 2)}\n`, + [WORKSPACE_FILE]: workspaceTemplate(manifest.exercise), + }; +} + +export function issueInstructions({ manifest, repositoryUrl }) { + const branch = manifest.baseBranch; + const head = `exercise/${manifest.exercise}-${manifest.issueNumber}`; + const compareUrl = `${repositoryUrl}/compare/${encodeURIComponent(branch)}...${encodeURIComponent(`${manifest.actor}:${head}`)}?expand=1&template=exercise.md`; + return ` +## 练习 ${manifest.exercise} 已准备好 + +你的专属上游分支是 \`${branch}\`。请在本地执行: + +\`\`\`bash +git remote add upstream ${repositoryUrl}.git # 已添加过 upstream 时跳过 +git fetch upstream ${branch} +git switch -c ${head} upstream/${branch} +\`\`\` + +只修改 \`${WORKSPACE_FILE}\`,完成后 commit 并 push 到你 Fork 中的同名分支。然后[创建 Pull Request](${compareUrl}),确认 base 是 \`${branch}\`,并在正文保留 \`Closes #${manifest.issueNumber}\`。 + +> 练习 PR 合入临时分支,因此 Issue 的关闭由训练机器人代替 GitHub 完成;在真实开源仓库的默认分支 PR 中,同样的 \`Closes\` 写法会原生关联并关闭 Issue。 +`; +} + +export function exerciseFromLabels(labels = []) { + const names = labels.map((label) => (typeof label === "string" ? label : label.name)); + for (const [exercise, name] of EXERCISE_LABELS) { + if (names.includes(name)) return exercise; + } + return null; +} + +export function shouldHandleIssueEvent(event) { + if (!event?.issue || event.issue.state !== "open") return false; + if (["opened", "reopened"].includes(event.action)) return true; + if (event.action === "labeled") return [...EXERCISE_LABELS.values()].includes(event.label?.name); + return false; +} + +export function shouldSkipGradeEvent(event) { + return ["labeled", "unlabeled"].includes(event?.action) && event.label?.name?.startsWith("session:"); +} diff --git a/scripts/practice/workflow.mjs b/scripts/practice/workflow.mjs new file mode 100644 index 0000000..3eb77cf --- /dev/null +++ b/scripts/practice/workflow.mjs @@ -0,0 +1,402 @@ +#!/usr/bin/env node +import fs from "node:fs"; +import { + EXERCISE_LABELS, + FEEDBACK_MARKER, + SESSION_FILE, + SESSION_MARKER, + WORKSPACE_FILE, +} from "./constants.mjs"; +import { parseFeedbackState, renderFeedback } from "./feedback.mjs"; +import { closingIssueNumbers, gradePractice, maintenanceReport } from "./grade.mjs"; +import { GitHubApiError, GitHubClient } from "./github.mjs"; +import { assertMergeEligible, canInjectConflict, expiryDecision, hasBlockingReview } from "./lifecycle.mjs"; +import { + createManifest, + exerciseFromLabels, + issueInstructions, + parseSessionBranch, + sessionFiles, + shouldHandleIssueEvent, + shouldSkipGradeEvent, +} from "./session.mjs"; + +function loadEvent() { + const path = process.env.GITHUB_EVENT_PATH; + if (!path) throw new Error("GITHUB_EVENT_PATH is required"); + return JSON.parse(fs.readFileSync(path, "utf8")); +} + +function clientFromEnv() { + return new GitHubClient({ token: process.env.GITHUB_TOKEN, repository: process.env.GITHUB_REPOSITORY }); +} + +function repositoryUrl() { + return `${process.env.GITHUB_SERVER_URL ?? "https://github.com"}/${process.env.GITHUB_REPOSITORY}`; +} + +function writeOutput(values) { + if (!process.env.GITHUB_OUTPUT) return; + const safe = Object.entries(values).map(([key, value]) => `${key}=${String(value).replaceAll("\n", "")}`).join("\n"); + fs.appendFileSync(process.env.GITHUB_OUTPUT, `${safe}\n`); +} + +function writeSummary(markdown) { + if (process.env.GITHUB_STEP_SUMMARY) fs.appendFileSync(process.env.GITHUB_STEP_SUMMARY, `${markdown}\n`); +} + +function normalizePr(pr) { + return { + number: pr.number, + title: pr.title ?? "", + body: pr.body ?? "", + author: pr.user.login, + baseRef: pr.base.ref, + headRef: pr.head.ref, + headSha: pr.head.sha, + headRepository: pr.head.repo?.full_name, + draft: Boolean(pr.draft), + labels: pr.labels ?? [], + state: pr.state, + merged: Boolean(pr.merged), + }; +} + +function normalizeIssue(issue) { + return { + number: issue.number, + author: issue.user.login, + assignees: issue.assignees.map((user) => user.login), + labels: issue.labels, + state: issue.state, + }; +} + +async function replaceSessionState(client, manifest, changes) { + const updated = { ...manifest, ...changes }; + await client.commitFiles(manifest.baseBranch, { [SESSION_FILE]: `${JSON.stringify(updated, null, 2)}\n` }, `chore(practice): update exercise ${manifest.exercise} session`); + return updated; +} + +async function injectConflict(client, manifest) { + if (manifest.exercise !== 4 || manifest.conflictBaseSha) return manifest; + const current = await client.getContent(WORKSPACE_FILE, manifest.baseBranch); + if (!current.includes("最终内容:待填写")) throw new Error("Exercise 4 base workspace is not in the expected initial state"); + const changed = current.replace("最终内容:待填写", "最终内容:上游更新"); + const conflictCommit = await client.commitFiles(manifest.baseBranch, { [WORKSPACE_FILE]: changed }, "chore(practice): inject upstream conflict"); + return replaceSessionState(client, manifest, { state: "conflict-injected", conflictBaseSha: conflictCommit.sha }); +} + +async function prerequisiteComplete(client, actor, exercise) { + if (exercise === 1) return true; + const labelQuery = encodeURIComponent(`${EXERCISE_LABELS.get(exercise - 1)},session:completed`); + const issues = await client.paginate(client.repoPath(`/issues?state=closed&creator=${encodeURIComponent(actor)}&labels=${labelQuery}`)); + return issues.some((issue) => !issue.pull_request); +} + +async function handleIssueOpened() { + const event = loadEvent(); + if (!shouldHandleIssueEvent(event)) return; + const issue = event.issue; + const exercise = exerciseFromLabels(issue.labels); + if (!exercise) return; + const client = clientFromEnv(); + const actor = issue.user.login; + const statusLabels = issue.labels.map((label) => label.name).filter((name) => name.startsWith("session:")); + if (statusLabels.some((name) => ["session:completed", "session:expired"].includes(name))) { + await client.upsertComment(issue.number, SESSION_MARKER, `\n这个会话已经${statusLabels.includes("session:completed") ? "完成" : "过期"},请使用 Issue Form 新建练习会话。\n`); + await client.patch(client.repoPath(`/issues/${issue.number}`), { state: "closed", state_reason: "not_planned" }); + return; + } + if (!(await prerequisiteComplete(client, actor, exercise))) { + await client.patch(client.repoPath(`/issues/${issue.number}`), { assignees: [actor] }); + await client.setStatusLabel(issue.number, "session:blocked"); + await client.upsertComment(issue.number, SESSION_MARKER, `\n## 前置练习尚未完成\n\n请先完成练习 ${exercise - 1}。完成后重新打开本 Issue,机器人会再次检查。\n`); + await client.patch(client.repoPath(`/issues/${issue.number}`), { state: "closed", state_reason: "not_planned" }); + return; + } + + const labelQuery = encodeURIComponent(`${EXERCISE_LABELS.get(exercise)},session:active`); + const activeIssues = await client.paginate(client.repoPath(`/issues?state=open&creator=${encodeURIComponent(actor)}&labels=${labelQuery}`)); + const duplicate = activeIssues.find((item) => !item.pull_request && item.number !== issue.number); + if (duplicate) { + await client.patch(client.repoPath(`/issues/${issue.number}`), { assignees: [actor] }); + await client.setStatusLabel(issue.number, "session:blocked"); + await client.upsertComment(issue.number, SESSION_MARKER, `\n## 已有进行中的同关练习\n\n请先继续 Issue #${duplicate.number}。为避免创建重复分支,本 Issue 已关闭。\n`); + await client.patch(client.repoPath(`/issues/${issue.number}`), { state: "closed", state_reason: "not_planned" }); + return; + } + + const manifest = createManifest({ exercise, issueNumber: issue.number, actor }); + let exists = false; + try { + await client.getRef(manifest.baseBranch); + exists = true; + } catch (error) { + if (!(error instanceof GitHubApiError) || error.status !== 404) throw error; + } + if (!exists) { + const repo = await client.get(client.repoPath("")); + const source = await client.getRef(repo.default_branch); + await client.createRef(manifest.baseBranch, source.object.sha); + await client.commitFiles(manifest.baseBranch, sessionFiles(manifest), `chore(practice): start exercise ${exercise} for issue ${issue.number}`); + } else { + try { + JSON.parse(await client.getContent(SESSION_FILE, manifest.baseBranch)); + await client.getContent(WORKSPACE_FILE, manifest.baseBranch); + } catch (error) { + if (!(error instanceof GitHubApiError) || error.status !== 404) throw error; + await client.commitFiles(manifest.baseBranch, sessionFiles(manifest), `chore(practice): repair exercise ${exercise} session`); + } + } + await client.patch(client.repoPath(`/issues/${issue.number}`), { assignees: [actor] }); + await client.setStatusLabel(issue.number, "session:active"); + await client.upsertComment(issue.number, SESSION_MARKER, issueInstructions({ manifest, repositoryUrl: repositoryUrl() })); +} + +async function latestReviewsBlock(client, prNumber) { + const reviews = await client.paginate(client.repoPath(`/pulls/${prNumber}/reviews`)); + return hasBlockingReview(reviews); +} + +async function conflictBaseIncluded(client, manifest, pr) { + if (!manifest.conflictBaseSha) return false; + const head = `${pr.head.repo.owner.login}:${pr.head.ref}`; + try { + const compare = await client.get(client.repoPath(`/compare/${encodeURIComponent(manifest.conflictBaseSha)}...${encodeURIComponent(head)}`)); + return compare.status === "ahead" || compare.status === "identical"; + } catch (error) { + if (error instanceof GitHubApiError && [404, 422].includes(error.status)) return false; + throw error; + } +} + +async function collectPracticeInput(client, rawPr, manifest, feedbackComment) { + const [rawIssue, files, rawCommits, comments, humanChangesRequested, workspace] = await Promise.all([ + client.get(client.repoPath(`/issues/${manifest.issueNumber}`)), + client.paginate(client.repoPath(`/pulls/${rawPr.number}/files`)), + client.paginate(client.repoPath(`/pulls/${rawPr.number}/commits`)), + client.paginate(client.repoPath(`/issues/${rawPr.number}/comments`)), + latestReviewsBlock(client, rawPr.number), + client.getContent(WORKSPACE_FILE, rawPr.head.sha, rawPr.head.repo.full_name), + ]); + const feedbackState = parseFeedbackState(feedbackComment?.body ?? ""); + const requestedAt = feedbackState.revisionRequestedAt ? Date.parse(feedbackState.revisionRequestedAt) : Infinity; + const authorResponded = comments.some((comment) => comment.user?.login === manifest.actor && Date.parse(comment.created_at) > requestedAt); + return { + pr: normalizePr(rawPr), + session: manifest, + issue: normalizeIssue(rawIssue), + files: files.map((file) => ({ filename: file.filename, status: file.status, changes: file.changes })), + commits: rawCommits.map((commit) => ({ sha: commit.sha, message: commit.commit.message, parents: commit.parents })), + workspace, + feedbackState, + authorResponded, + humanChangesRequested, + conflictBaseIncluded: manifest.exercise === 4 ? await conflictBaseIncluded(client, manifest, rawPr) : false, + }; +} + +async function evaluatePullRequest(client, prNumber, { updateFeedback = true } = {}) { + let rawPr = await client.get(client.repoPath(`/pulls/${prNumber}`)); + const parsedBranch = parseSessionBranch(rawPr.base.ref); + const comments = await client.paginate(client.repoPath(`/issues/${prNumber}/comments`)); + const feedbackComment = comments.find((comment) => comment.user?.type === "Bot" && comment.body?.includes(FEEDBACK_MARKER)); + + if (!parsedBranch) { + const rawCommits = await client.paginate(client.repoPath(`/pulls/${prNumber}/commits`)); + const report = maintenanceReport(normalizePr(rawPr), rawCommits.map((commit) => ({ message: commit.commit.message }))); + if (updateFeedback) await client.upsertComment(prNumber, FEEDBACK_MARKER, renderFeedback(report)); + return { report, input: null }; + } + + let manifest; + try { + manifest = JSON.parse(await client.getContent(SESSION_FILE, rawPr.base.ref)); + } catch (error) { + const report = { + schemaVersion: 1, + outcome: "fail", + headSha: rawPr.head.sha, + session: { ...parsedBranch, baseBranch: rawPr.base.ref }, + results: [{ id: "session.load", level: "required", status: "fail", summary: "无法读取可信会话清单。", remediation: "回到练习 Issue 重新创建会话。" }], + warnings: 0, + nextActions: ["请联系维护者检查训练分支。"], + }; + if (updateFeedback) await client.upsertComment(prNumber, FEEDBACK_MARKER, renderFeedback(report)); + return { report, input: null }; + } + + if (canInjectConflict({ pr: rawPr, manifest, referencedIssues: closingIssueNumbers(rawPr.body ?? "") })) { + manifest = await injectConflict(client, manifest); + rawPr = await client.get(client.repoPath(`/pulls/${prNumber}`)); + } + + const input = await collectPracticeInput(client, rawPr, manifest, feedbackComment); + const report = gradePractice(input); + const state = { ...input.feedbackState }; + if (manifest.exercise === 3 && !state.revisionRequestedSha) { + state.revisionRequestedSha = rawPr.head.sha; + state.revisionRequestedAt = new Date().toISOString(); + } + if (updateFeedback) { + await client.upsertComment(prNumber, FEEDBACK_MARKER, renderFeedback(report, state)); + await client.setStatusLabel(prNumber, report.outcome === "pass" ? "session:ready" : "session:needs-fix"); + } + return { report, input }; +} + +async function handleGradePr() { + const event = loadEvent(); + if (shouldSkipGradeEvent(event)) { + writeOutput({ eligible: false, outcome: "skipped", head_sha: event.pull_request?.head?.sha ?? "", pr_number: event.pull_request?.number ?? "" }); + return; + } + const prNumber = event.pull_request?.number ?? event.issue?.number; + if (!prNumber) throw new Error("This event does not identify a pull request"); + const client = clientFromEnv(); + const { report, input } = await evaluatePullRequest(client, prNumber); + const eligible = report.outcome === "pass" && Boolean(input?.session); + writeOutput({ eligible, outcome: report.outcome, head_sha: report.headSha, pr_number: prNumber, issue_number: input?.session.issueNumber ?? "", base_branch: input?.session.baseBranch ?? "" }); + writeSummary(renderFeedback(report, input?.feedbackState ?? {})); +} + +async function handleMergePr() { + const prNumber = Number(process.env.PR_NUMBER); + const expectedHead = process.env.EXPECTED_HEAD; + if (!Number.isInteger(prNumber) || !expectedHead) throw new Error("PR_NUMBER and EXPECTED_HEAD are required"); + const client = clientFromEnv(); + const rawPr = await client.get(client.repoPath(`/pulls/${prNumber}`)); + if (rawPr.merged) { + const parsed = parseSessionBranch(rawPr.base.ref); + if (!parsed) return; + let manifest = { ...parsed, baseBranch: rawPr.base.ref }; + try { + manifest = JSON.parse(await client.getContent(SESSION_FILE, rawPr.base.ref)); + } catch (error) { + if (!(error instanceof GitHubApiError) || error.status !== 404) throw error; + } + await finalizeSession(client, { manifest, prNumber }); + return; + } + const { report, input } = await evaluatePullRequest(client, prNumber, { updateFeedback: false }); + assertMergeEligible({ report, input, expectedHead }); + + const merged = await client.put(client.repoPath(`/pulls/${prNumber}/merge`), { + merge_method: "squash", + sha: expectedHead, + commit_title: `chore(practice): complete exercise ${input.session.exercise} for ${input.session.actor}`, + }); + if (!merged.merged) throw new Error(`GitHub refused the merge: ${merged.message ?? "unknown reason"}`); + + await finalizeSession(client, { manifest: input.session, prNumber }); +} + +async function finalizeSession(client, { manifest, prNumber }) { + await client.deleteRef(manifest.baseBranch); + const prComments = await client.paginate(client.repoPath(`/issues/${prNumber}/comments`)); + const feedback = prComments.find((comment) => comment.user?.type === "Bot" && comment.body?.includes(FEEDBACK_MARKER)); + if (!feedback?.body?.includes("已自动 squash merge")) { + const completion = "\n\n✅ 已自动 squash merge;训练分支和 Issue 已清理。\n"; + if (feedback) await client.patch(client.repoPath(`/issues/comments/${feedback.id}`), { body: `${feedback.body}${completion}` }); + else await client.post(client.repoPath(`/issues/${prNumber}/comments`), { body: `\n## 🤖 练习自动反馈\n${completion}` }); + } + await client.upsertComment(manifest.issueNumber, "practice-completion:v1", `\n## 🎉 练习 ${manifest.exercise} 完成\n\nPR #${prNumber} 已合并,专属训练分支已清理。${manifest.exercise < 4 ? ` 现在可以开始练习 ${manifest.exercise + 1}。` : " 你已经完成核心训练,可以前往真实开源仓库寻找适合的问题参与。"}\n`); + await client.setStatusLabel(manifest.issueNumber, "session:completed"); + await client.patch(client.repoPath(`/issues/${manifest.issueNumber}`), { state: "closed", state_reason: "completed" }); +} + +async function lastLearnerActivity(client, issue, pulls) { + const dates = [issue.created_at]; + const issueComments = await client.paginate(client.repoPath(`/issues/${issue.number}/comments`)); + dates.push(...issueComments.filter((comment) => comment.user?.type !== "Bot").map((comment) => comment.created_at)); + for (const pr of pulls) { + dates.push(pr.created_at, pr.updated_at); + const comments = await client.paginate(client.repoPath(`/issues/${pr.number}/comments`)); + dates.push(...comments.filter((comment) => comment.user?.type !== "Bot").map((comment) => comment.created_at)); + } + return dates.sort().at(-1); +} + +async function handleCleanup() { + const client = clientFromEnv(); + const issues = await client.paginate(client.repoPath(`/issues?state=open&labels=${encodeURIComponent("session:active")}`)); + for (const issue of issues.filter((item) => !item.pull_request)) { + const exercise = exerciseFromLabels(issue.labels); + if (!exercise) continue; + const branch = `practice/ex${exercise}/issue-${issue.number}-${issue.user.login}`; + const pulls = await client.paginate(client.repoPath(`/pulls?state=open&base=${encodeURIComponent(branch)}`)); + const expiry = expiryDecision(await lastLearnerActivity(client, issue, pulls)); + if (expiry.action === "expire") { + for (const pr of pulls) { + await client.post(client.repoPath(`/issues/${pr.number}/comments`), { body: "此练习会话已连续 14 天无活动,机器人正在关闭 PR 并清理临时分支。需要继续时请重新创建练习 Issue。" }); + await client.patch(client.repoPath(`/pulls/${pr.number}`), { state: "closed" }); + } + await client.post(client.repoPath(`/issues/${issue.number}/comments`), { body: "此会话已过期并完成清理。你可以随时通过 Issue Form 重新开始。" }); + await client.deleteRef(branch); + await client.setStatusLabel(issue.number, "session:expired"); + await client.patch(client.repoPath(`/issues/${issue.number}`), { state: "closed", state_reason: "not_planned" }); + } else if (expiry.action === "remind") { + await client.upsertComment(issue.number, "practice-expiry-warning:v1", "\n## ⏰ 会话即将过期\n\n这个练习已有 10 天没有学员活动。连续 14 天无活动时,机器人会关闭 PR 并删除临时训练分支。\n"); + } + } +} + +const LABEL_DEFINITIONS = { + "exercise:1": ["1f883d", "练习 1:第一次贡献"], + "exercise:2": ["1f883d", "练习 2:干净的提交历史"], + "exercise:3": ["1f883d", "练习 3:响应 Code Review"], + "exercise:4": ["1f883d", "练习 4:解决上游冲突"], + "session:active": ["0969da", "训练会话正在进行"], + "session:blocked": ["d1242f", "训练会话被前置条件阻止"], + "session:needs-fix": ["d1242f", "自动检查发现必须修复项"], + "session:ready": ["1a7f37", "练习已通过,等待自动合并"], + "session:completed": ["8250df", "练习已完成"], + "session:expired": ["6e7781", "训练会话已过期"], + "automerge:disabled": ["b60205", "维护者暂停此 PR 的自动合并"], +}; + +async function handleBootstrap() { + const client = clientFromEnv(); + const existing = await client.paginate(client.repoPath("/labels")); + const names = new Set(existing.map((label) => label.name)); + for (const [name, [color, description]] of Object.entries(LABEL_DEFINITIONS)) { + if (names.has(name)) await client.patch(client.repoPath(`/labels/${encodeURIComponent(name)}`), { color, description }); + else await client.post(client.repoPath("/labels"), { name, color, description }); + } +} + +async function handleMigrateLegacy() { + if (process.env.CONFIRM !== "CLOSE_LEGACY") throw new Error("Set workflow input to CLOSE_LEGACY to perform migration"); + const client = clientFromEnv(); + const [issues, pulls] = await Promise.all([ + client.paginate(client.repoPath("/issues?state=open")), + client.paginate(client.repoPath("/pulls?state=open&base=main")), + ]); + const legacy = issues.filter((issue) => !issue.pull_request && issue.labels.some((label) => ["exercise1", "exercise2"].includes(label.name))); + for (const issue of legacy) { + for (const pr of pulls.filter((pull) => closingIssueNumbers(pull.body ?? "").includes(issue.number))) { + await client.post(client.repoPath(`/issues/${pr.number}/comments`), { body: "仓库练习系统已升级为临时会话分支。此旧版 PR 不再合入 main,请通过新的 Exercise Issue Form 重新开始。" }); + await client.patch(client.repoPath(`/pulls/${pr.number}`), { state: "closed" }); + } + await client.post(client.repoPath(`/issues/${issue.number}/comments`), { body: "仓库练习系统已升级。此旧会话现已结束,请通过新的 Exercise Issue Form 重新开始;原有内容仍保留在 GitHub 历史中。" }); + await client.patch(client.repoPath(`/issues/${issue.number}`), { state: "closed", state_reason: "not_planned" }); + } +} + +const handlers = { + "issue-opened": handleIssueOpened, + "grade-pr": handleGradePr, + "merge-pr": handleMergePr, + cleanup: handleCleanup, + bootstrap: handleBootstrap, + "migrate-legacy": handleMigrateLegacy, +}; + +const command = process.argv[2]; +if (!handlers[command]) { + console.error(`Usage: node scripts/practice/workflow.mjs <${Object.keys(handlers).join("|")}>`); + process.exitCode = 2; +} else { + await handlers[command](); +} diff --git a/tests/practice/feedback.test.mjs b/tests/practice/feedback.test.mjs new file mode 100644 index 0000000..dbd9ebf --- /dev/null +++ b/tests/practice/feedback.test.mjs @@ -0,0 +1,16 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { parseFeedbackState, renderFeedback } from "../../scripts/practice/feedback.mjs"; + +test("feedback state round trips through an inert HTML marker", () => { + const state = { revisionRequestedSha: "abc123", text: "`$(touch nope)` | 中文" }; + const body = renderFeedback({ outcome: "pass", headSha: "1234567890abcdef", session: { exercise: 3 }, warnings: 1, results: [], nextActions: ["继续"] }, state); + assert.deepEqual(parseFeedbackState(body), state); + assert.match(body, /Warning 不阻止合并/); +}); + +test("feedback escapes table delimiters and newlines", () => { + const body = renderFeedback({ outcome: "fail", headSha: "1234567890abcdef", session: { exercise: 1 }, warnings: 0, results: [{ id: "unsafe|id", level: "required", status: "fail", summary: "line1\nline2 |
", remediation: "use `code`" }], nextActions: ["fix"] }); + assert.match(body, /unsafe\\\|id/); + assert.match(body, /line1 line2 \\\| <details>/); +}); diff --git a/tests/practice/github.test.mjs b/tests/practice/github.test.mjs new file mode 100644 index 0000000..f59df67 --- /dev/null +++ b/tests/practice/github.test.mjs @@ -0,0 +1,49 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { GitHubApiError, GitHubClient } from "../../scripts/practice/github.mjs"; + +function response(status, payload) { + return { + ok: status >= 200 && status < 300, + status, + text: async () => payload === null ? "" : JSON.stringify(payload), + }; +} + +test("GitHub client sends JSON without evaluating untrusted strings", async () => { + const calls = []; + const client = new GitHubClient({ + token: "secret-token", + repository: "owner/repo", + fetchImpl: async (url, options) => { + calls.push({ url, options }); + return response(201, { id: 1 }); + }, + }); + const malicious = "$(touch /tmp/nope); `whoami`; ${HOME}"; + await client.post(client.repoPath("/issues/1/comments"), { body: malicious }); + assert.equal(JSON.parse(calls[0].options.body).body, malicious); + assert.equal(calls[0].options.headers.Authorization, "Bearer secret-token"); + assert.ok(!calls[0].url.includes(malicious)); +}); + +test("GitHub client reports structured API failures without token contents", async () => { + const client = new GitHubClient({ token: "top-secret", repository: "owner/repo", fetchImpl: async () => response(403, { message: "forbidden" }) }); + await assert.rejects(client.get(client.repoPath("/issues/1")), (error) => { + assert.ok(error instanceof GitHubApiError); + assert.equal(error.status, 403); + assert.doesNotMatch(error.message, /top-secret/); + return true; + }); +}); + +test("pagination is bounded and stops on a short page", async () => { + let calls = 0; + const client = new GitHubClient({ token: "x", repository: "owner/repo", fetchImpl: async () => { + calls += 1; + return response(200, calls === 1 ? Array.from({ length: 100 }, (_, id) => ({ id })) : [{ id: 100 }]); + } }); + const items = await client.paginate(client.repoPath("/issues")); + assert.equal(items.length, 101); + assert.equal(calls, 2); +}); diff --git a/tests/practice/grade.test.mjs b/tests/practice/grade.test.mjs new file mode 100644 index 0000000..e139c7f --- /dev/null +++ b/tests/practice/grade.test.mjs @@ -0,0 +1,99 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { gradePractice, closingIssueNumbers, maintenanceReport } from "../../scripts/practice/grade.mjs"; +import { createManifest } from "../../scripts/practice/session.mjs"; + +function inputFor(exercise, overrides = {}) { + const session = createManifest({ exercise, issueNumber: 42, actor: "octocat", createdAt: "2026-08-20T00:00:00.000Z" }); + const workspaces = { + 1: "# 我的第一次开源贡献\n\n- GitHub 用户名:octocat\n- 我希望参与的开源方向:改进开源项目文档并帮助其他初学者。\n", + 2: "# 干净的提交历史\n\n## 我学到的 Git 命令\n\ngit rebase -i\n\n## 为什么要保持提交历史干净\n\n让评审者容易理解每一步。\n", + 3: "# 响应 Code Review\n\n状态:已根据反馈修改\n\n## 本次修改\n\n补充说明。\n\n## 修改说明\n\n删除占位内容。\n", + 4: "# 解决上游冲突\n\n## 最终决定\n\n最终内容:上游更新 + 我的修改\n", + }; + const counts = { 1: 1, 2: 2, 3: 2, 4: 2 }; + const commits = Array.from({ length: counts[exercise] }, (_, index) => ({ sha: `sha${index}`, message: `docs: complete part ${index + 1}`, parents: ["parent"] })); + return { + pr: { number: 99, title: `docs: complete exercise ${exercise}`, body: "Closes #42", author: "octocat", baseRef: session.baseBranch, headRef: `exercise/${exercise}-42`, headSha: "headsha", draft: false, labels: [] }, + session: exercise === 4 ? { ...session, state: "conflict-injected", conflictBaseSha: "base-sha" } : session, + issue: { number: 42, author: "octocat", assignees: ["octocat"], labels: [`exercise:${exercise}`], state: "open" }, + files: [{ filename: ".practice/workspace.md", status: "modified" }], + commits, + workspace: workspaces[exercise], + feedbackState: exercise === 3 ? { revisionRequestedSha: "old-head" } : {}, + conflictBaseIncluded: exercise === 4, + authorResponded: true, + humanChangesRequested: false, + ...overrides, + }; +} + +test("extracts supported closing keywords", () => { + assert.deepEqual(closingIssueNumbers("Fixes: #12, resolves #14 and CLOSED #12"), [12, 14]); + assert.deepEqual(closingIssueNumbers("disclose #12"), []); +}); + +for (const exercise of [1, 2, 3, 4]) { + test(`exercise ${exercise} passes its complete fixture`, () => { + const report = gradePractice(inputFor(exercise)); + assert.equal(report.outcome, "pass", JSON.stringify(report.results, null, 2)); + }); +} + +test("commit and PR title style only produce warnings", () => { + const input = inputFor(1); + input.pr.title = "修改"; + input.commits[0].message = "WIP add notes"; + const report = gradePractice(input); + assert.equal(report.outcome, "pass"); + assert.ok(report.results.some((item) => item.id === "commits.message" && item.status === "warn")); + assert.ok(report.results.some((item) => item.id === "pr.title" && item.status === "warn")); +}); + +test("wrong commit count, merge history and extra files block", () => { + const input = inputFor(2); + input.commits.push({ sha: "merge", message: "merge branch", parents: ["a", "b"] }); + input.files.push({ filename: "README.md", status: "modified" }); + const report = gradePractice(input); + assert.equal(report.outcome, "fail"); + for (const id of ["exercise2.commit-count", "exercise2.no-merge", "files.scope"]) { + assert.ok(report.results.some((item) => item.id === id && item.status === "fail")); + } +}); + +test("exercise 3 requires a new head in the same PR", () => { + const first = inputFor(3, { feedbackState: {} }); + const firstReport = gradePractice(first); + assert.equal(firstReport.outcome, "fail"); + assert.equal(firstReport.results.find((item) => item.id === "exercise3.review").status, "pending"); + + const unchanged = inputFor(3, { feedbackState: { revisionRequestedSha: "headsha" } }); + assert.equal(gradePractice(unchanged).outcome, "fail"); +}); + +test("exercise 4 requires injected ancestry and both conflict sides", () => { + const missingBase = inputFor(4, { conflictBaseIncluded: false }); + assert.equal(gradePractice(missingBase).outcome, "fail"); + const lostSide = inputFor(4, { workspace: "最终内容:我的修改" }); + assert.equal(gradePractice(lostSide).outcome, "fail"); +}); + +test("ownership, base, issue reference and kill switch are hard gates", () => { + const input = inputFor(1); + input.pr.body = "See #41"; + input.pr.baseRef = "main"; + input.pr.labels = ["automerge:disabled"]; + input.issue.author = "someone-else"; + input.issue.state = "closed"; + const report = gradePractice(input); + assert.equal(report.outcome, "fail"); + for (const id of ["pr.closing-reference", "issue.ownership", "branch.base", "merge.allowed"]) { + assert.ok(report.results.some((item) => item.id === id && item.status === "fail")); + } +}); + +test("maintenance PRs never become practice passes", () => { + const report = maintenanceReport({ title: "update", headSha: "abc" }, [{ message: "anything" }]); + assert.equal(report.outcome, "maintenance"); + assert.equal(report.warnings, 2); +}); diff --git a/tests/practice/lifecycle.test.mjs b/tests/practice/lifecycle.test.mjs new file mode 100644 index 0000000..d1a1149 --- /dev/null +++ b/tests/practice/lifecycle.test.mjs @@ -0,0 +1,34 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { assertMergeEligible, canInjectConflict, expiryDecision, hasBlockingReview } from "../../scripts/practice/lifecycle.mjs"; + +test("merge eligibility rejects stale heads and non-practice reports", () => { + const valid = { report: { outcome: "pass", headSha: "abc" }, input: { session: { exercise: 1 } }, expectedHead: "abc" }; + assert.equal(assertMergeEligible(valid), true); + assert.throws(() => assertMergeEligible({ ...valid, expectedHead: "new-head" }), /head changed/); + assert.throws(() => assertMergeEligible({ ...valid, report: { outcome: "maintenance", headSha: "abc" } }), /no longer passes/); +}); + +test("session expiry has stable reminder and expiration boundaries", () => { + const now = Date.parse("2026-08-20T00:00:00Z"); + assert.equal(expiryDecision("2026-08-11T00:00:01Z", { now }).action, "none"); + assert.equal(expiryDecision("2026-08-10T00:00:00Z", { now }).action, "remind"); + assert.equal(expiryDecision("2026-08-06T00:00:00Z", { now }).action, "expire"); + assert.throws(() => expiryDecision("not-a-date", { now }), /ISO date/); +}); + +test("only the session owner can trigger the one-time conflict mutation", () => { + const manifest = { exercise: 4, issueNumber: 42, actor: "octocat", baseBranch: "practice/ex4/issue-42-octocat" }; + const pr = { user: { login: "octocat" }, base: { ref: manifest.baseBranch } }; + assert.equal(canInjectConflict({ pr, manifest, referencedIssues: [42] }), true); + assert.equal(canInjectConflict({ pr: { ...pr, user: { login: "attacker" } }, manifest, referencedIssues: [42] }), false); + assert.equal(canInjectConflict({ pr, manifest, referencedIssues: [41] }), false); + assert.equal(canInjectConflict({ pr, manifest: { ...manifest, conflictBaseSha: "done" }, referencedIssues: [42] }), false); +}); + +test("a comment review does not clear an outstanding change request", () => { + const user = { login: "maintainer", type: "User" }; + assert.equal(hasBlockingReview([{ user, state: "CHANGES_REQUESTED" }, { user, state: "COMMENTED" }]), true); + assert.equal(hasBlockingReview([{ user, state: "CHANGES_REQUESTED" }, { user, state: "APPROVED" }]), false); + assert.equal(hasBlockingReview([{ user: { login: "bot", type: "Bot" }, state: "CHANGES_REQUESTED" }]), false); +}); diff --git a/tests/practice/session.test.mjs b/tests/practice/session.test.mjs new file mode 100644 index 0000000..a54b1a8 --- /dev/null +++ b/tests/practice/session.test.mjs @@ -0,0 +1,27 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { branchNameFor, createManifest, parseSessionBranch, sessionFiles, shouldHandleIssueEvent, shouldSkipGradeEvent, validateManifest } from "../../scripts/practice/session.mjs"; + +test("session branch and manifest are deterministic", () => { + const manifest = createManifest({ exercise: 4, issueNumber: 123, actor: "octo-cat", createdAt: "2026-08-20T00:00:00Z" }); + assert.equal(manifest.baseBranch, "practice/ex4/issue-123-octo-cat"); + assert.deepEqual(parseSessionBranch(manifest.baseBranch), { exercise: 4, issueNumber: 123, actor: "octo-cat" }); + assert.equal(validateManifest(manifest), true); + assert.deepEqual(Object.keys(sessionFiles(manifest)).sort(), [".practice/session.json", ".practice/workspace.md"]); +}); + +test("invalid actors and tampered manifests are rejected", () => { + assert.throws(() => branchNameFor({ exercise: 1, issueNumber: 1, actor: "bad/name" })); + const manifest = createManifest({ exercise: 1, issueNumber: 1, actor: "octocat" }); + assert.equal(validateManifest({ ...manifest, baseBranch: "main" }), false); +}); + +test("session automation ignores its own status labels and closed issues", () => { + const issue = { state: "open" }; + assert.equal(shouldHandleIssueEvent({ action: "opened", issue }), true); + assert.equal(shouldHandleIssueEvent({ action: "labeled", label: { name: "exercise:1" }, issue }), true); + assert.equal(shouldHandleIssueEvent({ action: "labeled", label: { name: "session:active" }, issue }), false); + assert.equal(shouldHandleIssueEvent({ action: "reopened", issue: { state: "closed" } }), false); + assert.equal(shouldSkipGradeEvent({ action: "labeled", label: { name: "session:ready" } }), true); + assert.equal(shouldSkipGradeEvent({ action: "labeled", label: { name: "automerge:disabled" } }), false); +});