Skip to content

Instantly share code, notes, and snippets.

@oukayuka
Last active March 31, 2021 01:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oukayuka/bd8b2ac927afb9b3be26c1fefea885b5 to your computer and use it in GitHub Desktop.
Save oukayuka/bd8b2ac927afb9b3be26c1fefea885b5 to your computer and use it in GitHub Desktop.
Execute each lint-staged entry in sub-directories projects recursively
#!/bin/sh
# lint-staged-around
# execute each lint-staged entry in sub-directories projects recursively
#
# Riakuto! Project by Klemiwary Books
fileTypes="js|jsx|ts|tsx|html|css|less|sass|scss|gql|graphql|json"
target="src|public"
# detect git against tag
if git rev-parse --verify HEAD >/dev/null 2>&1
then
against=HEAD
else
# Initial commit: diff against an empty tree object
against=$(git hash-object -t tree /dev/null)
fi
# pick staged projects
stagedProjects=$( \
git diff --cached --name-only --diff-filter=AM $against | \
grep -E ".*($target)\/" | \
grep -E "^.*\/.*\.($fileTypes)$" | \
grep -vE "(package|tsconfig).*\.json" | \
sed -r "s/($target)\/.*$//g" | \
uniq \
)
# execute each lint-staged
rootDir=$(pwd | sed -r "s/\/\.git\/hooks//")
for project in ${stagedProjects[@]}; do
echo "Executing $project lint-staged entry..."
cd "$rootDir/$project"
npx lint-staged 2>/dev/null
done
@oukayuka
Copy link
Author

oukayuka commented Mar 31, 2021

Introducing Steps

For example, file structure like this...

awesome-project/  # Git repository root
  super-app/
    package.json
  fabulous-function/
    package.json

1. Put this script file on Git repository root

mv lint-staged-around awesome-project/
chmod ugo+x awesome-project/lint-staged-around

2. Install simple-git-hooks in each project

yarn add -D simple-git-hooks lint-staged prettier

3. Edit package.json

    "devDependencies": {
      "lint-staged": "^10.5.4",
      "prettier": "^2.2.1",
      "simple-git-hooks": "^2.0.3"
    },
+  "simple-git-hooks": {
+     "pre-commit": ". ./lint-staged-around"
+   },
+   "lint-staged": {
+     "*.{js,jsx,ts,tsx,json,md}": [
+       "prettier --write"
+     ]
    }

4. Overwrite Git hooks

npx simple-git-hooks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment