ポンコツエンジニアのごじゃっぺ開発日記。

いろいろポンコツだけど、気にするな。エンジニアの日々の開発などの記録を残していきます。 自動で収入を得られるサービスやシステムを作ることが目標!!

Github Actionsを使ってgit commitとgit pushを自動化しよう。

Github Actionsで作業の自動化をするのって楽しいですよね。 今回は、actions上でファイルを変更したり追加して、最後にgitコマンドでコミット&プッシュをしたいと思います。

GITHUB_TOKENの設定

不要です! 自分も初めてGithub Actions上でgitコマンドを操作するときは必要なのかなと思ってたんですが、どうやら不要なようです。 なので、GITHUB_TOKENの存在は一旦忘れます。

もしかしたら他のリポジトリを扱う場合とかは必要なのかも。

以下で紹介するymlファイルを作成するだけでした!

workflowのyml定義

さて、早速定義ファイルを紹介したいと思います。

name: Test

on:
  push:
    branches:
      - '*'
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
    - name: Checkout
      uses: actions/checkout@master
    - name: Installing PHP
      uses: shivammathur/setup-php@master
      with:
        php-version: 7.3
        extension-csv: mbstring, xdebug
    - name: Add Plugin
      run: sudo apt install -y php7.3-xml
    - name: check php
      run: php -v
    - name: composer install
      run: |
        cd app
        composer install
    - name: ごにょごにょ
      run: |
        cd app
        php calculate.php
    - name: git setting
      run: |
        git config --local user.email "メールアドレスをここに入力"
        git config --local user.name "Githubのアカウントをここに入力"
    - name: Commit files
      run: |
        git add .
        git commit -m "Add csv" -a
        git pull
        git push origin master

ざっくりと内容を説明すると

  • PHPの実行環境を用意する
  • ごにょごにょする(ここではcsvファイルを計算して出力している)
  • git configをする
  • commit & pushする

という感じです。

トリガーはテスト用にブランチのpushにしているので、定義ファイルを更新したりしたらすぐに実行してくれています。

このactionsでpushするときは実行されません。よくできてますね。

git configって必要なの?

ここの設定項目(git settingのところ)を削除して実行したらエラーになりました。

Run

  git config --global user.email "you@example.com"
  git config --global user.name "Your Name"

to set your account's default identity.
Omit --global to set the identity only in this repository.

f:id:ponkotsu0605:20200725110425p:plain

git pullでwarningが出るかも?

自分も一部の環境では以下のようなエラーになったなりました。

warning: Pulling without specifying how to reconcile divergent branches is
discouraged. You can squelch this message by running one of the following
commands sometime before your next pull:

  git config pull.rebase false  # merge (the default strategy)
  git config pull.rebase true   # rebase
  git config pull.ff only       # fast-forward only

You can replace "git config" with "git config --global" to set a default
preference for all repositories. You can also pass --rebase, --no-rebase,
or --ff-only on the command line to override the configured default per
invocation.

これについては以下の記事が参考になったので、pullのオプションを設定しないといけないみたいです。

blog.agile.esm.co.jp

実行結果

プッシュすると以下のように「Add csv」というコミットメッセージとともに計算結果を自動でプッシュしてくれました。

f:id:ponkotsu0605:20200725110630p:plain

Actions側の実行ログはこんな感じです。

f:id:ponkotsu0605:20200725111523p:plain

無事、gitコマンドのcommitとpushをすることができました。

お問い合わせプライバシーポリシー制作物