# git pushしたときにFTPしたりgruntタスクを実行する。

- リンク: https://torounit.com/blog/git-push%e3%81%97%e3%81%9f%e3%81%a8%e3%81%8d%e3%81%abftp%e3%81%97%e3%81%9f%e3%82%8agrunt%e3%82%bf%e3%82%b9%e3%82%af%e3%82%92%e5%ae%9f%e8%a1%8c%e3%81%99%e3%82%8b%e3%80%82/
- 公開日: 2014-12-03T09:30:37+09:00
- 作成者: Toro\_Unit

FTPしか使えないレンタルサーバーでの案件でGitを入れようとするとき、ソースの管理って
結構大変だったりします。なので、git pushしたときに自動でFTPすると、非常に便利でした。

 * [Gitフックを仕込むgrunt-githooksについて紹介するよ – Qiita [キータ]](http://qiita.com/shoito/items/0cd10e14f437a0cab9a9)
 * [[ツール/エディタ]grunt-ftpushを使って変更されたファイルをFTPで自動でアップロードする | Wood-Roots.blog](http://wood-roots.com/web%E5%88%B6%E4%BD%9C/%E3%83%84%E3%83%BC%E3%83%AB%E3%82%A8%E3%83%87%E3%82%A3%E3%82%BF/grunt-ftpush%E3%82%92%E4%BD%BF%E3%81%A3%E3%81%A6%E5%A4%89%E6%9B%B4%E3%81%95%E3%82%8C%E3%81%9F%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB%E3%82%92ftp%E3%81%A7%E8%87%AA%E5%8B%95%E3%81%A7%E3%82%A2%E3%83%83)

このgrunt-githooksと、grunt-ftpushを使ってこんなGruntfileを作ります。

    ```decode:true
    module.exports = (grunt) ->


      grunt.loadNpmTasks "grunt-ftpush"
      grunt.loadNpmTasks "grunt-githooks"


      grunt.initConfig

        ftpush: {
          build: {
            auth: {
              host: 'example.com',
              port: 21,
              authKey: 'pass'
            },
            src: '',
            dest: '/path/to/dir',
            exclusions: ['.*','node_modules/*','.sass-cache/']
            keep: [],
            simple: true,
            useList: false
          }
        }

        githooks: {
          options: {
            dest: '.git/hooks',
            hashbang: '#!/bin/bash',
            template: './node_modules/grunt-githooks/templates/shell.hb',
            startMarker: '## GRUNT-GRUNTHOOKS START',
            endMarker: '## GRUNT-GRUNTHOOKS END'
          },
          setup: {
            'pre-push': 'deploy'
          }
        }

      grunt.registerTask 'deploy', ["ftpush"]
    ```

これを設定したら、以下のコマンドを実行します。

    ```decode:true
    $ grunt githooks
    ```

これで.git/hooks/pre-pushが作成され、pushしたときにgrunt deployが実行されるように
なります。grunt deployにこのコードだとFTPしか設定してありませんが、サーバーにアップ
ロードする前にCSSやJSのコンパイル・結合・圧縮などを実行するとより、使い勝手がいい
と思います。

例：[https://github.com/torounit/torounit2015/blob/master/Gruntfile.coffee](https://github.com/torounit/torounit2015/blob/master/Gruntfile.coffee)

サーバーによってはftpushではなく、[grunt-rsync](http://dev.classmethod.jp/tool/node-js-grunt-rsync-deploy/)
等を使ったほうが良い場合も多いですが基本はこんな感じで、push時にサーバーと同期を
取る事ができます。

やっぱりいろいろ自動化しておくと便利で良いですね。ファイルの同期は手動でやるとだいたい
ろくな事が無いので、自動化の威力がいろいろ感じられて良いかなと思います。

#### note

 * gitにsourcetreeを使う場合、環境変数が読まれないので、command not found: grunt
   とか言われる場合があります。その場合、githooksのテンプレートをいじって、bashrc
   とかをexportすると良い感じになります。

 
