|
| 1 | +name: traffic-snapshot |
| 2 | + |
| 3 | +on: |
| 4 | + schedule: |
| 5 | + - cron: '0 2 * * *' |
| 6 | + workflow_dispatch: |
| 7 | + |
| 8 | +permissions: |
| 9 | + contents: write |
| 10 | + |
| 11 | +jobs: |
| 12 | + snapshot: |
| 13 | + if: ${{ secrets.TRAFFIC_PAT != '' }} |
| 14 | + runs-on: ubuntu-latest |
| 15 | + env: |
| 16 | + TRAFFIC_TOKEN: ${{ secrets.TRAFFIC_PAT }} |
| 17 | + steps: |
| 18 | + - uses: actions/checkout@v4 |
| 19 | + with: |
| 20 | + fetch-depth: 0 |
| 21 | + persist-credentials: false |
| 22 | + - name: Configure git credentials |
| 23 | + run: | |
| 24 | + git config user.name "github-actions[bot]" |
| 25 | + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" |
| 26 | + git remote set-url origin https://x-access-token:${TRAFFIC_TOKEN}@github.com/${{ github.repository }}.git |
| 27 | + - name: Snapshot traffic metrics |
| 28 | + env: |
| 29 | + REPO: ${{ github.repository }} |
| 30 | + run: | |
| 31 | + set -euo pipefail |
| 32 | + if [ -z "${TRAFFIC_TOKEN}" ]; then |
| 33 | + echo "TRAFFIC_PAT secret is not configured; skipping snapshot." >&2 |
| 34 | + exit 0 |
| 35 | + fi |
| 36 | + DATE="$(date -u +"%Y-%m-%dT%H-%M-%SZ")" |
| 37 | + mkdir -p analytics |
| 38 | + for endpoint in views clones popular/referrers popular/paths; do |
| 39 | + slug="${endpoint//\//-}" |
| 40 | + file="analytics/${DATE}-${slug}.json" |
| 41 | + echo "Fetching ${endpoint} -> ${file}" |
| 42 | + curl -sSf \ |
| 43 | + -H "Accept: application/vnd.github+json" \ |
| 44 | + -H "Authorization: Bearer ${TRAFFIC_TOKEN}" \ |
| 45 | + -H "X-GitHub-Api-Version: 2022-11-28" \ |
| 46 | + "https://api.github.com/repos/${REPO}/traffic/${endpoint}" | jq '.' > "${file}" |
| 47 | + done |
| 48 | + if git status --short | grep -q "."; then |
| 49 | + git add analytics |
| 50 | + git commit -m "chore: snapshot traffic ${DATE}" |
| 51 | + BRANCH="${GITHUB_REF##*/}" |
| 52 | + git push origin HEAD:"${BRANCH}" |
| 53 | + else |
| 54 | + echo "No changes to commit" |
| 55 | + fi |
0 commit comments