Challenge - 5 Problems
Pre-commit Hook Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 Command Output
intermediate2:00remaining
Output of a simple pre-commit hook script
What will be the output when you try to commit with this pre-commit hook script in
.git/hooks/pre-commit?Git
#!/bin/sh echo "Checking commit message length..." MSG=$(head -n1 .git/COMMIT_EDITMSG) LEN=$(echo -n "$MSG" | wc -c) if [ $LEN -lt 10 ]; then echo "Commit message too short. Please write at least 10 characters." exit 1 fi exit 0
Attempts:
2 left
💡 Hint
Think about what happens if the commit message is shorter than 10 characters.
✗ Incorrect
The script checks the first line of the commit message. If it is shorter than 10 characters, it prints an error and exits with status 1, blocking the commit.
🧠 Conceptual
intermediate1:30remaining
Purpose of pre-commit hooks in Git
Which of the following best describes the main purpose of a pre-commit hook in Git?
Attempts:
2 left
💡 Hint
Think about what happens right before a commit is saved.
✗ Incorrect
Pre-commit hooks run scripts or checks before the commit is finalized, allowing you to prevent bad commits or enforce rules.
❓ Troubleshoot
advanced2:00remaining
Why does the pre-commit hook not run?
You created a pre-commit hook script in
.git/hooks/pre-commit but it does not run when committing. What is the most likely reason?Attempts:
2 left
💡 Hint
Check the file permissions of the hook script.
✗ Incorrect
Git only runs hook scripts that have execute permissions. Without it, the script is ignored.
🔀 Workflow
advanced2:30remaining
Order of operations in a pre-commit hook script
You want to create a pre-commit hook that first checks code style with
flake8 and then runs tests with pytest. Which order of commands in the script ensures the commit is blocked if either check fails?Git
#!/bin/sh # Commands to run
Attempts:
2 left
💡 Hint
The script should stop at the first failure to block the commit.
✗ Incorrect
Running
flake8 first and then pytest ensures style is checked before tests. If either fails, the script exits with non-zero status, blocking the commit.✅ Best Practice
expert3:00remaining
Best practice for sharing pre-commit hooks across a team
What is the best practice to ensure all team members use the same pre-commit hooks without manually copying scripts into their
.git/hooks directories?Attempts:
2 left
💡 Hint
Think about automation and consistency for teams.
✗ Incorrect
The
pre-commit framework allows defining hooks in a config file that is version controlled, so all team members can install and run the same hooks easily.