iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🤖

Building a System to Automatically Sync Google Sheets Content to a GitHub Repository

に公開

Overview

I happened to take on the development of a portal site for a Splatoon 3 tournament held over a period of two to three months.
Team information and match data are managed in Google Sheets, and I created a mechanism to reflect that content on the portal site, which I'll introduce here.

Specifically, I built a system like this.

To put it simply, I treated Google Sheets as a CMS and used GitHub Actions to synchronize the CMS with the repository.

How it Works

Google Sheets Difference Detection

I decided on an approach of converting the Google Sheets content into a JSON file and committing that JSON file. This allows detecting changes by checking if there is a git diff result.

Converting Spreadsheet Content to JSON

First, let's consider converting the spreadsheet content into JSON.
For example, if we have data like the following:

Team Name Member 1 Member 2 Member 3 Member 4
Team A Person A Person B Person C Person D

It is converted into a JSON format like this:

[{ "teamName": "チームA", "players": ["Aさん", "Bさん", "Cさん", "Dさん"] }]

Retrieving Spreadsheet Content with Node.js

I used @googleapis/sheets to retrieve the spreadsheet content with Node.js.
https://www.npmjs.com/package/@googleapis/sheets

I assumed that Application Default Credentials (ADC) are configured. You need to grant viewing permissions for the spreadsheet to the email address associated with the credentials beforehand.

This allows you to retrieve the spreadsheet content with the following code:

const sheetId = "";
const auth = new GoogleAuth({
  scopes: [
    "https://www.googleapis.com/auth/spreadsheets",
    "https://www.googleapis.com/auth/spreadsheets.readonly",
  ],
});
const sheets = getSheets({
  version: "v4",
  auth,
});
const res = await sheets.spreadsheets.values.get({
  spreadsheetId: sheetId,
  range: "チーム!A1:B",
});

console.log(res.data.value);

Running the Difference Detection Mechanism on GitHub Actions

I wanted the difference detection to run periodically, so I used the cron setting of the GitHub Actions schedule event.
For the authentication information in Actions, I used the service account that was already in use for the existing mechanism that automatically deploys the portal site to Firebase Hosting.
google-github-actions/auth is convenient for using a service account stored in secrets.

      - name: Authenticate to Google Cloud
        uses: google-github-actions/auth@v1
        with:
          credentials_json: "${{ secrets.FIREBASE_SERVICE_ACCOUNT_ROOKIE_LEAGUE_PORTAL }}"

Since it sets up the authentication information in environment variables, programs that assume ADC will work without needing to modify the code.

Creating a Pull Request to Commit Detected Differences

Up to this point, we have completed the part where we detect differences from the spreadsheet on GitHub Actions, convert them to JSON, and a git diff is generated if there are any differences.
Next, we will build a mechanism to create a pull request containing these differences.

When creating pull requests with GitHub Actions, peter-evans/create-pull-request is very useful.
https://github.com/peter-evans/create-pull-request

It features functions such as creating a pull request only when there are differences, or overwriting with a force-push if a pull request already exists.

Due to GitHub Actions' specifications, the pull_request event is not triggered for pull requests created by the default GitHub Actions token. This is to prevent infinite loops where GitHub Actions are called indefinitely. This specification also applies to pull requests created by peter-evans/create-pull-request.

For this portal site, a mechanism was already in place where a preview environment is created and operation checks can be performed whenever a pull request is created. Therefore, an extra step was needed to verify the spreadsheet differences in the preview environment.

The solution to this issue is mentioned in the documentation for peter-evans/create-pull-request. There are various approaches, but for this project, I chose "Authenticating with GitHub App generated tokens."

Overall View

Finally, I will introduce the GitHub Actions configuration file and wrap up.

name: Synchronize Sheets

on:
  workflow_dispatch:
  schedule:
    - cron: "0 * * * *"

env:
  TZ: "Asia/Tokyo"

jobs:
  sync-sheets:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v3
        with:
          node-version: 18.12.1
          cache: "npm"

      - name: Authenticate to Google Cloud
        uses: google-github-actions/auth@v1
        with:
          credentials_json: "${{ secrets.FIREBASE_SERVICE_ACCOUNT_ROOKIE_LEAGUE_PORTAL }}"

      - uses: tibdex/github-app-token@v1
        id: generate-token
        with:
          app_id: ${{ secrets.APP_ID }}
          private_key: ${{ secrets.APP_PRIVATE_KEY }}

      - run: npm ci
      - run: npm run sync-sheets
        working-directory: packages/sync-sheets

      - run: git status

      - name: Create Pull Request
        uses: peter-evans/create-pull-request@v4
        with:
          add-paths: |
            packages/app/src/data
          branch: sync-sheets
          title: Sync sheets
          body: |
            This pull request synchronizes the data from the master sheet to a JSON file.
            Please check the diff and the preview environment to see if the changes are as intended, and merge if it looks good.
          commit-message: Sync sheets
          labels: |
            sync-sheets
          reviewers: |
            odanado
          delete-branch: true
          token: ${{ steps.generate-token.outputs.token }}

Discussion