LoginSignup
8

More than 5 years have passed since last update.

Prettier で整形した結果の diff があったときに CI を落とす方法

Last updated at Posted at 2018-09-20

よく使い回すのでメモ。
仕事上ほとんど CircleCI なので例は config.yml だけど、どこでも変わらない。

TL;DR

Prettier 1.16 以降

prettier 1.16 から --check オプションが追加された。変なことをしなくても以下で OK。

package.json
{
  "scripts": {
    "lint:prettier": "prettier --check './src/**/*.{js,ts}'"
  }
}

以下のような CircleCI で動くという具合。

.circleci/config.yml
version: 2
jobs:
  build:
    working_directory: ~/app
    docker:
      - image: circleci/node:8.10.0
    steps:
      - checkout
      - restore_cache:
          keys:
          - v1-dependencies-{{ checksum "yarn.lock" }}
          - v1-dependencies-
      - run: yarn
      - save_cache:
          paths:
            - node_modules
          key: v1-dependencies-{{ checksum "yarn.lock" }}
      - run: yarn lint:format

Prettier 1.16 以前 

prettier の -l オプションを使う。以下のような package.json がある場合に……

package.json
{
  "scripts": {
    "format": "prettier './src/**/*.{js,ts}'"
  }
}

以下のような CircleCI で動くという具合。 -l オプションをつけると、変更があった場合に exit code 1 を返してくれる。

.circleci/config.yml
version: 2
jobs:
  build:
    working_directory: ~/app
    docker:
      - image: circleci/node:8.10.0
    steps:
      - checkout
      - restore_cache:
          keys:
          - v1-dependencies-{{ checksum "yarn.lock" }}
          - v1-dependencies-
      - run: yarn
      - save_cache:
          paths:
            - node_modules
          key: v1-dependencies-{{ checksum "yarn.lock" }}
      - run: yarn -s format -l

prettier の変更検知について

その他いくつかの変遷をたどったのでメモ。

prettier -> git diff

以前まで使っていた方法。

Pros

  • 楽。見たらやっていることがわかるほか、 prettier 以外の依存が入らない。

Cons

  • package-lock.json や yarn.lock が CI で書き換わったら頓死する。
  • -l オプションを知った結果不要になった。

prettier-check を使う

https://github.com/hexacta/prettier-check を使う。

Pros

  • -l オプションでやりたかったことが実現できている。
  • -l がない頃は使われていた様子。

Cons

  • この程度のことで依存を増やしたくないので prettier からの git diff のときは使わずにいた。
  • 今はそもそも不要になった。

資料

公式ドキュメントにあった。

--list-different
Another useful flag is --list-different (or -l) which prints the filenames of files that are different from > Prettier formatting. If there are differences the script errors out, which is useful in a CI scenario.

-l が導入された時の議論はここ。

追記: --check オプション

1.16 からは --check オプションができたのでこれで良い。

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
8