22
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

レガシーなPHPプロジェクトをボットでコーディング規約に沿っているか調べさせる

Last updated at Posted at 2016-02-05

経緯

現在会社ではレガシーなPHPが使われたプロジェクトの保守が続けられています。日本ではおそらく多くのWebサイトでレガシーなPHPが使われていると思います。モダンな最新のプロジェクトとは違い、ユニットテストの自動化、CI、コードの静的解析などとは程遠いです。長い間保守されているのでコーディング規約の統一もされていません。

そこで!
新しいものを使ってレガシープロジェクトをモダンなものにしましょう!

ということでまずインデントにタブが使われているかどうかをチェクするだけのボットを作りました。僕のいる会社の言い伝えによりますとインデントはタブらしいのでスペースが入っているかどうかを判定します。

GitHubのWebhooksからpushのイベントを飛ばしてもらって、そこからコミットを取得しに行きます。

コード

checkIndentation.coffee
token = 'token'
apiUrl = "https://api.github.com/repos/[Organization名]"
repository = "hoge"

module.exports = (robot) ->
  robot.router.post("/github/check/commits", (req, response) ->
    data = req.body
    for commit in data.commits
      request = robot.http("#{apiUrl}/#{repository}/commits/#{commit.id}")
        .query(access_token: token)
        .get()

      request((err, res, body) ->
        if err
          robot.messageRoom("チャンネル名", "何かエラーになっちゃいました...")
          return

        commit = JSON.parse body

        if commit.message == "Not Found"
          robot.messageRoom("チャンネル名", "#{repository}が見つかりませんでした..")
          return

        fileNames = []
        for file in commit.files
          if file.status == 'modified' || file.status == 'added'
            if file.filename.match(/^.*\.php$/g) != null
              if !checkIndentation(file.patch)
                fileNames.push(file.filename)

        if fileNames.length != 0
          respond = "#{commit.committer.login}さん!\nスペースのインデントが混じってますよ!\n\n"
          respond += "#{commit.commit.message}\n\n"
          respond += "#{fileNames.join('\n')}"
          respond += "\n\n#{commit.html_url}"
          robot.messageRoom("チャンネル名", respond)
      )
    response.end('')
  )

checkIndentation = (patch) ->
  index = patch.indexOf("\n")
  while 1
    nextIndex = patch.indexOf("\n", index + 1)
    if nextIndex == -1
      break
    string = patch.slice(index + 1, nextIndex)
    if (string.slice(0, 1) == '+')
      if (string.substr(1).match(/^ +\S+/) != null)
        return false
    index = nextIndex
  return true

これでGitHubの設定からWebhooksを[ボットのURL]/github/check/commitsを設定すればできるはずです。

今回はGitHub APIでファイルごとの差分をパッチ形式で取得してインデントを調べています。

実行した感じ

slack.jpg

膨大なコードを全部PHP Code Snifferとかかけたらとんでもないことになりますけど、今後の変更箇所だけ指摘してくれるのでかなり有効だと思います。

22
20
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
22
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?