|
1 | 1 | pnpm lint-staged |
| 2 | + |
| 3 | +#!/bin/sh |
| 4 | +# Exit on any error |
| 5 | +set -e |
| 6 | + |
| 7 | +# Check if there are any staged files |
| 8 | +if [ -z "$(git diff --cached --name-only)" ]; then |
| 9 | + echo "No staged files to format" |
| 10 | + exit 0 |
| 11 | +fi |
| 12 | + |
| 13 | +# Store the hash of staged changes to detect modifications |
| 14 | +STAGED_HASH=$(git diff --cached | sha256sum | cut -d' ' -f1) |
| 15 | + |
| 16 | +# Save list of staged files (handling all file states) |
| 17 | +STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACMR) |
| 18 | +PARTIALLY_STAGED=$(git diff --name-only) |
| 19 | + |
| 20 | +# Stash unstaged changes to preserve working directory |
| 21 | +# --keep-index keeps staged changes in working tree |
| 22 | +git stash push --quiet --keep-index --message "pre-commit-stash" || true |
| 23 | +STASHED=$? |
| 24 | + |
| 25 | +# Run formatter on the staged files |
| 26 | +pnpm dlx ultracite fix |
| 27 | +FORMAT_EXIT_CODE=$? |
| 28 | + |
| 29 | +# Restore working directory state |
| 30 | +if [ $STASHED -eq 0 ]; then |
| 31 | + # Re-stage the formatted files |
| 32 | + if [ -n "$STAGED_FILES" ]; then |
| 33 | + echo "$STAGED_FILES" | while IFS= read -r file; do |
| 34 | + if [ -f "$file" ]; then |
| 35 | + git add "$file" |
| 36 | + fi |
| 37 | + done |
| 38 | + fi |
| 39 | + |
| 40 | + # Restore unstaged changes |
| 41 | + git stash pop --quiet || true |
| 42 | + |
| 43 | + # Restore partial staging if files were partially staged |
| 44 | + if [ -n "$PARTIALLY_STAGED" ]; then |
| 45 | + for file in $PARTIALLY_STAGED; do |
| 46 | + if [ -f "$file" ] && echo "$STAGED_FILES" | grep -q "^$file$"; then |
| 47 | + # File was partially staged - need to unstage the unstaged parts |
| 48 | + git restore --staged "$file" 2>/dev/null || true |
| 49 | + git add -p "$file" < /dev/null 2>/dev/null || git add "$file" |
| 50 | + fi |
| 51 | + done |
| 52 | + fi |
| 53 | +else |
| 54 | + # No stash was created, just re-add the formatted files |
| 55 | + if [ -n "$STAGED_FILES" ]; then |
| 56 | + echo "$STAGED_FILES" | while IFS= read -r file; do |
| 57 | + if [ -f "$file" ]; then |
| 58 | + git add "$file" |
| 59 | + fi |
| 60 | + done |
| 61 | + fi |
| 62 | +fi |
| 63 | + |
| 64 | +# Check if staged files actually changed |
| 65 | +NEW_STAGED_HASH=$(git diff --cached | sha256sum | cut -d' ' -f1) |
| 66 | +if [ "$STAGED_HASH" != "$NEW_STAGED_HASH" ]; then |
| 67 | + echo "✨ Files formatted by Ultracite" |
| 68 | +fi |
| 69 | + |
| 70 | +exit $FORMAT_EXIT_CODE |
0 commit comments