Skip to content

Instantly share code, notes, and snippets.

@ryanhanks-bestow
Last active May 9, 2024 22:28
Show Gist options
  • Save ryanhanks-bestow/db0c4b3c901465fcbe6651d02dc44e2c to your computer and use it in GitHub Desktop.
Save ryanhanks-bestow/db0c4b3c901465fcbe6651d02dc44e2c to your computer and use it in GitHub Desktop.
Git pre-commit hook for dart package using dart_pre_commit

Git pre-commit hook setup for dart / flutter package

Activate globally

dart pub global activate dart_pre_commit

Per-package clone

# 1. make .git/hooks/precommit
# 2. it gotta be executable

Run this:

echo '#!/bin/sh\nexec dart_pre_commit # specify custom options here\n' > .git/hooks/pre-commit
chmod a+x .git/hooks/pre-commit

Shell Helper Functions

Alternatively, you can use these:

dart_pre_commit_add_hook() {
    # Check if we're in a Git repository
    if ! git rev-parse --is-inside-work-tree > /dev/null 2>&1; then
        echo "Error: This script must be run in the root of a Git repository." >&2
        return 1  # Exit with a non-zero status
    fi

    # Check if pubspec.yaml exists in the current directory
    if [ ! -f "pubspec.yaml" ]; then
        echo "Error: No pubspec.yaml found in the current directory." >&2
        return 1  # Exit with a non-zero status
    fi

    # Create pre-commit hook
    echo -e '#!/bin/sh\nexec dart_pre_commit # specify custom options here\n' > .git/hooks/pre-commit
    chmod a+x .git/hooks/pre-commit

    echo "Pre-commit hook created successfully."
}

dart_pre_commit_rm_hook() {
    # Check if we're in a Git repository
    if ! git rev-parse --is-inside-work-tree > /dev/null 2>&1; then
        echo "Error: This script must be run in a Git repository." >&2
        return 1  # Exit with a non-zero status
    fi

    # Check if the pre-commit hook exists
    if [ -f ".git/hooks/pre-commit" ]; then
        # Remove the pre-commit hook
        rm .git/hooks/pre-commit
        echo "Pre-commit hook removed successfully."
    else
        echo "No pre-commit hook found to remove." >&2
        return 1  # Exit with a non-zero status
    fi
}

To Remove

For a configured clone:

rm .git/hooks/pre-commit
#!/bin/sh
exec dart_pre_commit # specify custom options here
## - Below comment from original script generated via dart_pre_commit - ##
# exec flutter pub run dart_pre_commit # Use this instead when working on a flutter project
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment