@@ -57,36 +57,28 @@ jobs:
5757 git config --global user.name "github-actions[bot]"
5858 git config --global user.email "github-actions[bot]@users.noreply.github.com"
5959
60- # Pre-commit changes before any branch switching to avoid overwriting local changes
61- - name : Pre-commit local changes
60+ # Checkout to correct branch before commit
61+ - name : Checkout to correct branch (PR or main)
6262 run : |
63- git add "*.md" metrics.json || true
64- git commit -m "Auto-commit local changes before branch switch" || echo "No changes to commit"
63+ BRANCH="${{ github.head_ref || github.ref_name }}"
64+ git fetch origin
65+ git checkout "$BRANCH" || git checkout -b "$BRANCH" "origin/$BRANCH"
6566
66- # Commit and push logic for PR events (merge, not rebase)
67- - name : Commit and push changes (PR)
68- if : github.event_name == 'pull_request'
69- env :
70- TOKEN : ${{ secrets.GITHUB_TOKEN }}
67+ - name : Pre-commit local changes
7168 run : |
72- git fetch origin
73- git checkout ${{ github.head_ref }}
74- git pull origin ${{ github.head_ref }} || echo "No merge needed"
75- git add "*.md" metrics.json
76- git commit -m "Update visitor count" || echo "No changes to commit"
77- git remote set-url origin https://x-access-token:${TOKEN}@github.com/${{ github.repository }}
78- git push origin HEAD:${{ github.head_ref }}
69+ # Only add files that exist
70+ [ -f metrics.json ] && git add metrics.json || true
71+ git add "*.md" || true
72+ git commit -m "Auto-commit local changes before pull/merge" || echo "No changes to commit"
7973
80- # Commit and push logic for non-PR events (merge, not rebase)
81- - name : Commit and push changes (non-PR)
82- if : github.event_name != 'pull_request'
74+ - name : Pull (merge) and push changes
8375 env :
8476 TOKEN : ${{ secrets.GITHUB_TOKEN }}
8577 run : |
86- git fetch origin
87- git checkout ${{ github.ref_name }} || git checkout -b ${{ github.ref_name }} origin/${{ github.ref_name }}
88- git pull origin ${{ github.ref_name }} || echo "No merge needed"
89- git add "*.md" metrics.json
90- git commit -m "Update visitor count" || echo "No changes to commit"
78+ BRANCH="${{ github.head_ref || github.ref_name }}"
9179 git remote set-url origin https://x-access-token:${TOKEN}@github.com/${{ github.repository }}
92- git push origin HEAD:${{ github.ref_name }}
80+ git pull origin "$BRANCH" || echo "No merge needed"
81+ [ -f metrics.json ] && git add metrics.json || true
82+ git add "*.md" || true
83+ git commit -m "Update visitor count" || echo "No changes to commit"
84+ git push origin HEAD:"$BRANCH"
0 commit comments