name: Release

on:
  push:
    branches:
      - master

defaults:
  run:
    shell: bash

env:
  FORCE_COLOR: true

jobs:
  test:
    uses: ./.github/workflows/test.yml

  changelog:
    name: Changelog PR or Release
    if: ${{ github.repository_owner == 'openInula' }}
    needs: test
    runs-on: ubuntu-latest
    permissions:
      contents: write
      id-token: write
    steps:
      - uses: actions/checkout@v4

      - name: Install pnpm
        uses: pnpm/action-setup@v4

      - name: Install Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: 'pnpm'

      - name: Install dependencies
        run: pnpm install

      - name: Build Packages
        run: pnpm run build

      - name: Create Release Pull Request or Publish
        id: changesets
        uses: changesets/action@v1
        with:
          version: pnpm run version
          publish: pnpm exec changeset publish --access public
          commit: "chore(release): release in ci"
          title: "chore(release): release in ci"
        env:
          # Needs access to push to main
          GITHUB_TOKEN: ${{ secrets.BOT_GITHUB_TOKEN }}
          # Needs access to publish to npm
          NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
      # 只在成功发布后更新锁文件
      - name: Update lockfile after publish
        if: steps.changesets.outputs.published == 'true'
        run: |
          # 更新锁文件
          pnpm install --no-frozen-lockfile
          
          # 提交变更
          git config --global user.name 'github-actions[bot]'
          git config --global user.email 'github-actions[bot]@users.noreply.github.com'
          git add pnpm-lock.yaml
          git commit -m "chore(release): update lockfile after publish" || echo "No lockfile changes to commit"
          git push