LoginSignup
2
1

More than 1 year has passed since last update.

[GAS] clasp push による上書きを安全にする方法

Last updated at Posted at 2023-03-30

概要

Google Apps Script(GAS)を開発する際には、クライアント側にある GAS エディタ上で作業を行い、clasp コマンドでサーバー側にアップロードします。clasp push コマンドを使うことで、サーバー側のスクリプトを更新することができます。しかし、誤って重要なスクリプトを上書きしてしまうことがあるため、注意が必要です。
そこで、今回は clasp push による上書きを安全にする方法を紹介します。

手順

具体的には、以下のような手順を踏みます。

  1. ローカルのリポジトリに変更を一時保存するために、一時的なコミットを行います。
  2. バックアップ用のブランチを作成し、現在のHEAD^(1つ前のコミット)をリセットします。
  3. clasp pull コマンドで、サーバー側のスクリプトをローカルにダウンロードします。
  4. 変更を追加して、バックアップ用のブランチにコミットします。
  5. 変更を GitHub に push して、バックアップ用のブランチに保存します。
  6. main ブランチに戻り、先ほどの一時的なコミットを取り消します。
  7. clasp push コマンドで、変更をサーバー側にアップロードします。
  8. 以下は、シェルスクリプトの例です。上記の手順を自動化しているため、手動で行う必要はありません。
backup_and_push.sh
#!/bin/bash

set -eu

function error_exit() {
  echo "[ERROR] $1"
  exit 1
}

# clasp push バックアップ用
git add .
git commit -m "仮コミット" || error_exit "failed to commit changes"

# backupブランチにGASエディタのデータバックアップ
if git checkout -b "backup"; then
  git reset --hard HEAD^ || error_exit "failed to reset HEAD"
  clasp pull || error_exit "failed to pull scripts from the Clasp server"
  git add . || error_exit "failed to add changes"
  git commit -m "push時のバックアップ" || error_exit "failed to commit changes"
  git push origin HEAD || error_exit "failed to push changes"
else
  error_exit "failed to create backup branch"
fi

# 元に戻してclasp push
if git checkout main; then
  git reset --soft HEAD^ || error_exit "failed to reset HEAD"
  clasp push || error_exit "failed to push scripts to the Clasp server"
else
  error_exit "failed to switch to main branch"
fi

# 全て成功したらbackupブランチを削除する
git branch -D backup || true

最後に

上記のシェルファイルを下記のようにpackage.jsonで独自のコマンドにしてあげてpushする時は、npm run pushなどをしてあげたら、誤ってスクリプトエディタ上のコードを消してしまうことがなくなります!
余談ですが、.clasp.jsonファイルなどを別で管理することで既存のclasp pushを実行できないにしてより安全性を保つとかが良いのかなと思いました。

package.json
{
	"scripts": {
		"push": "bash backup_and_push.sh"
	},
}

ローカル環境下での、よきGAS開発を!!

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1