From 4df24e5f046f94a04b379fcd1d6d57ef49cfd6dc Mon Sep 17 00:00:00 2001
From: Lukas Eipert <leipert@gitlab.com>
Date: Fri, 21 Sep 2018 17:36:26 +0200
Subject: [PATCH] Danger check for unprettified JavaScript

This adds a Dangerfile which executes `prettier` to find out if someone
touched Frontend files and forgot to run it on their current branch.
---
 .gitlab-ci.yml             |  3 ++-
 Dangerfile                 |  1 +
 danger/prettier/Dangerfile | 39 ++++++++++++++++++++++++++++++++++++++
 3 files changed, 42 insertions(+), 1 deletion(-)
 create mode 100644 danger/prettier/Dangerfile

diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml
index 058cacb0774..5028aa98a85 100644
--- a/.gitlab-ci.yml
+++ b/.gitlab-ci.yml
@@ -444,10 +444,10 @@ setup-test-env:
       - vendor/gitaly-ruby
 
 danger-review:
+  <<: *pull-cache
   image: registry.gitlab.com/gitlab-org/gitlab-build-images:danger
   stage: test
   allow_failure: true
-  cache: {}
   dependencies: []
   before_script: []
   only:
@@ -461,6 +461,7 @@ danger-review:
       - $CI_COMMIT_REF_NAME =~ /.*-stable(-ee)?-prepare-.*/
   script:
     - git version
+    - yarn install --frozen-lockfile --cache-folder .yarn-cache
     - danger --fail-on-errors=true
 
 rspec-pg 0 30: *rspec-metadata-pg
diff --git a/Dangerfile b/Dangerfile
index 46e53edcac4..fe1e3d16ba5 100644
--- a/Dangerfile
+++ b/Dangerfile
@@ -7,3 +7,4 @@ danger.import_dangerfile(path: 'danger/database')
 danger.import_dangerfile(path: 'danger/documentation')
 danger.import_dangerfile(path: 'danger/frozen_string')
 danger.import_dangerfile(path: 'danger/commit_messages')
+danger.import_dangerfile(path: 'danger/prettier')
diff --git a/danger/prettier/Dangerfile b/danger/prettier/Dangerfile
new file mode 100644
index 00000000000..86f9f6af475
--- /dev/null
+++ b/danger/prettier/Dangerfile
@@ -0,0 +1,39 @@
+# frozen_string_literal: true
+
+def get_prettier_files(files)
+  files.select do |file|
+    file.end_with?('.js', '.scss', '.vue')
+  end
+end
+
+prettier_candidates = get_prettier_files(git.added_files + git.modified_files)
+
+return if prettier_candidates.empty?
+
+unpretty = `node_modules/prettier/bin-prettier.js --list-different #{prettier_candidates.join(" ")}`
+             .split(/$/)
+             .map(&:strip)
+             .reject(&:empty?)
+
+return if unpretty.empty?
+
+warn 'This merge request changed frontend files without pretty printing them.'
+
+markdown(<<~MARKDOWN)
+  ## Pretty print Frontend files
+
+  The following files should have been pretty printed with `prettier`:
+
+  * #{unpretty.map { |path| "`#{path}`" }.join("\n* ")}
+
+  Please run
+
+  ```
+  node_modules/.bin/prettier --write \\
+  #{unpretty.map { |path| "  '#{path}'" }.join(" \\\n")}
+  ```
+
+  Also consider auto-formatting [on-save].
+
+  [on-save]: https://docs.gitlab.com/ee/development/new_fe_guide/style/prettier.html
+MARKDOWN
-- 
2.30.9