# Generated from xtask::workflows::extension_workflow_rollout
# Rebuild with `cargo xtask workflows`.
name: extension_workflow_rollout
env:
  CARGO_TERM_COLOR: always
on:
  workflow_dispatch:
    inputs:
      filter-repos:
        description: Comma-separated list of repository names to rollout to. Leave empty for all repos.
        type: string
        default: ''
      change-description:
        description: Description for the changes to be expected with this rollout
        type: string
        default: ''
jobs:
  fetch_extension_repos:
    if: (github.repository_owner == 'zed-industries' || github.repository_owner == 'zed-extensions') && github.ref == 'refs/heads/main'
    runs-on: namespace-profile-2x4-ubuntu-2404
    steps:
    - name: checkout_zed_repo
      uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd
      with:
        clean: false
        fetch-depth: 0
    - id: prev-tag
      name: extension_workflow_rollout::fetch_extension_repos::get_previous_tag_commit
      run: |
        PREV_COMMIT=$(git rev-parse "extension-workflows^{commit}" 2>/dev/null || echo "")
        if [ -z "$PREV_COMMIT" ]; then
            echo "::error::No previous rollout tag 'extension-workflows' found. Cannot determine file changes."
            exit 1
        fi
        echo "Found previous rollout at commit: $PREV_COMMIT"
        echo "prev_commit=$PREV_COMMIT" >> "$GITHUB_OUTPUT"
    - id: calc-changes
      name: extension_workflow_rollout::fetch_extension_repos::get_removed_files
      run: |
        for workflow_type in "ci" "shared"; do
            if [ "$workflow_type" = "ci" ]; then
                WORKFLOW_DIR="extensions/workflows"
            else
                WORKFLOW_DIR="extensions/workflows/shared"
            fi

            REMOVED=$(git diff --name-status -M "$PREV_COMMIT" HEAD -- "$WORKFLOW_DIR" | \
                awk '/^D/ { print $2 } /^R/ { print $2 }' | \
                xargs -I{} basename {} 2>/dev/null | \
                tr '\n' ' ' || echo "")
            REMOVED=$(echo "$REMOVED" | xargs)

            echo "Removed files for $workflow_type: $REMOVED"
            echo "removed_${workflow_type}=$REMOVED" >> "$GITHUB_OUTPUT"
        done
      env:
        PREV_COMMIT: ${{ steps.prev-tag.outputs.prev_commit }}
    - id: list-repos
      name: extension_workflow_rollout::fetch_extension_repos::get_repositories
      uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b
      with:
        script: |
          const repos = await github.paginate(github.rest.repos.listForOrg, {
              org: 'zed-extensions',
              type: 'public',
              per_page: 100,
          });

          let filteredRepos = repos
              .filter(repo => !repo.archived)
              .map(repo => repo.name);

          const filterInput = `${{ inputs.filter-repos }}`.trim();
          if (filterInput.length > 0) {
              const allowedNames = filterInput.split(',').map(s => s.trim()).filter(s => s.length > 0);
              filteredRepos = filteredRepos.filter(name => allowedNames.includes(name));
              console.log(`Filter applied. Matched ${filteredRepos.length} repos from ${allowedNames.length} requested.`);
          }

          console.log(`Found ${filteredRepos.length} extension repos`);
          return filteredRepos;
        result-encoding: json
    - name: steps::cache_rust_dependencies_namespace
      uses: namespacelabs/nscloud-cache-action@a90bb5d4b27522ce881c6e98eebd7d7e6d1653f9
      with:
        cache: rust
        path: ~/.rustup
    - name: extension_workflow_rollout::fetch_extension_repos::generate_workflow_files
      run: |
        cargo xtask workflows "$COMMIT_SHA"
      env:
        COMMIT_SHA: ${{ github.sha }}
    - name: extension_workflow_rollout::fetch_extension_repos::upload_workflow_files
      uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4
      with:
        name: extension-workflow-files
        path: extensions/workflows/**/*.yml
        if-no-files-found: error
    outputs:
      repos: ${{ steps.list-repos.outputs.result }}
      prev_commit: ${{ steps.prev-tag.outputs.prev_commit }}
      removed_ci: ${{ steps.calc-changes.outputs.removed_ci }}
      removed_shared: ${{ steps.calc-changes.outputs.removed_shared }}
    timeout-minutes: 10
  rollout_workflows_to_extension:
    needs:
    - fetch_extension_repos
    if: needs.fetch_extension_repos.outputs.repos != '[]'
    runs-on: namespace-profile-2x4-ubuntu-2404
    strategy:
      matrix:
        repo: ${{ fromJson(needs.fetch_extension_repos.outputs.repos) }}
      fail-fast: false
      max-parallel: 10
    steps:
    - id: generate-token
      name: steps::generate_token
      uses: actions/create-github-app-token@f8d387b68d61c58ab83c6c016672934102569859
      with:
        app-id: ${{ secrets.ZED_ZIPPY_APP_ID }}
        private-key: ${{ secrets.ZED_ZIPPY_APP_PRIVATE_KEY }}
        owner: zed-extensions
        repositories: ${{ matrix.repo }}
        permission-pull-requests: write
        permission-contents: write
        permission-workflows: write
    - name: checkout_extension_repo
      uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd
      with:
        clean: false
        path: extension
        repository: zed-extensions/${{ matrix.repo }}
        token: ${{ steps.generate-token.outputs.token }}
    - name: extension_workflow_rollout::rollout_workflows_to_extension::download_workflow_files
      uses: actions/download-artifact@018cc2cf5baa6db3ef3c5f8a56943fffe632ef53
      with:
        name: extension-workflow-files
        path: workflow-files
    - name: extension_workflow_rollout::rollout_workflows_to_extension::sync_workflow_files
      run: |
        mkdir -p extension/.github/workflows

        if [ "$MATRIX_REPO" = "workflows" ]; then
            REMOVED_FILES="$REMOVED_CI"
        else
            REMOVED_FILES="$REMOVED_SHARED"
        fi

        cd extension/.github/workflows

        if [ -n "$REMOVED_FILES" ]; then
            for file in $REMOVED_FILES; do
                if [ -f "$file" ]; then
                    rm -f "$file"
                fi
            done
        fi

        cd - > /dev/null

        if [ "$MATRIX_REPO" = "workflows" ]; then
            cp workflow-files/*.yml extension/.github/workflows/
        else
            cp workflow-files/shared/*.yml extension/.github/workflows/
        fi
      env:
        REMOVED_CI: ${{ needs.fetch_extension_repos.outputs.removed_ci }}
        REMOVED_SHARED: ${{ needs.fetch_extension_repos.outputs.removed_shared }}
        MATRIX_REPO: ${{ matrix.repo }}
    - id: short-sha
      name: extension_workflow_rollout::rollout_workflows_to_extension::get_short_sha
      run: |
        echo "sha_short=$(echo "$GITHUB_SHA" | cut -c1-7)" >> "$GITHUB_OUTPUT"
    - id: create-pr
      name: extension_workflow_rollout::rollout_workflows_to_extension::create_pull_request
      uses: peter-evans/create-pull-request@98357b18bf14b5342f975ff684046ec3b2a07725
      with:
        path: extension
        title: Update CI workflows to `${{ steps.short-sha.outputs.sha_short }}`
        body: |
          This PR updates the CI workflow files from the main Zed repository
          based on the commit zed-industries/zed@${{ github.sha }}

          ${{ inputs.change-description }}
        commit-message: Update CI workflows to `${{ steps.short-sha.outputs.sha_short }}`
        branch: update-workflows
        committer: zed-zippy[bot] <234243425+zed-zippy[bot]@users.noreply.github.com>
        author: zed-zippy[bot] <234243425+zed-zippy[bot]@users.noreply.github.com>
        base: main
        delete-branch: true
        token: ${{ steps.generate-token.outputs.token }}
        sign-commits: true
    - name: extension_workflow_rollout::rollout_workflows_to_extension::enable_auto_merge
      run: |
        if [ -n "$PR_NUMBER" ]; then
            gh pr merge "$PR_NUMBER" --auto --squash
        fi
      env:
        GH_TOKEN: ${{ steps.generate-token.outputs.token }}
        PR_NUMBER: ${{ steps.create-pr.outputs.pull-request-number }}
      working-directory: extension
    timeout-minutes: 10
  create_rollout_tag:
    needs:
    - rollout_workflows_to_extension
    if: inputs.filter-repos == ''
    runs-on: namespace-profile-2x4-ubuntu-2404
    steps:
    - id: generate-token
      name: steps::generate_token
      uses: actions/create-github-app-token@f8d387b68d61c58ab83c6c016672934102569859
      with:
        app-id: ${{ secrets.ZED_ZIPPY_APP_ID }}
        private-key: ${{ secrets.ZED_ZIPPY_APP_PRIVATE_KEY }}
        permission-contents: write
    - name: steps::checkout_repo
      uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd
      with:
        clean: false
        fetch-depth: 0
        token: ${{ steps.generate-token.outputs.token }}
    - name: extension_workflow_rollout::create_rollout_tag::configure_git
      run: |
        git config user.name "zed-zippy[bot]"
        git config user.email "234243425+zed-zippy[bot]@users.noreply.github.com"
    - name: extension_workflow_rollout::create_rollout_tag::update_rollout_tag
      run: |
        if git rev-parse "extension-workflows" >/dev/null 2>&1; then
            git tag -d "extension-workflows"
            git push origin ":refs/tags/extension-workflows" || true
        fi

        echo "Creating new tag 'extension-workflows' at $(git rev-parse --short HEAD)"
        git tag "extension-workflows"
        git push origin "extension-workflows"
    timeout-minutes: 1
defaults:
  run:
    shell: bash -euxo pipefail {0}
