0
0
Gitdevops~10 mins

pre-commit hook in Git - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a pre-commit hook script that runs before a commit.

Git
#!/bin/sh

[1]
Drag options to blanks, or click blank then click option'
Aecho "Running pre-commit checks..."
Bgit commit -m 'auto commit'
Cgit push origin main
Drm -rf /
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to run git commit inside the pre-commit hook causes recursion.
Using destructive commands like rm in the hook.
2fill in blank
medium

Complete the code to prevent a commit if a Python file contains syntax errors.

Git
for file in $(git diff --cached --name-only --diff-filter=ACM | grep '\.py$'); do
  python -m py_compile $[1] || exit 1
 done
Drag options to blanks, or click blank then click option'
Afilename
Bfiles
Cfile
Dfilepath
Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable name not defined in the loop.
Forgetting to exit with code 1 to stop the commit.
3fill in blank
hard

Fix the error in the pre-commit hook that tries to run tests but fails due to wrong command.

Git
echo "Running tests..."
[1]
if [ $? -ne 0 ]; then
  echo "Tests failed, aborting commit."
  exit 1
fi
Drag options to blanks, or click blank then click option'
Anpm test
Bnpm tests
Cnpm testing
Dnpm run test
Attempts:
3 left
💡 Hint
Common Mistakes
Using npm test which may work but is less explicit.
Using commands that do not exist like npm tests.
4fill in blank
hard

Fill both blanks to create a pre-commit hook that checks for trailing whitespace and aborts commit if found.

Git
if git diff --cached --check | grep [1]; then
  echo "Trailing whitespace found in [2]. Commit aborted."
  exit 1
fi
Drag options to blanks, or click blank then click option'
A--quiet
B--cached
Cfiles
Dstaged files
Attempts:
3 left
💡 Hint
Common Mistakes
Using grep without options prints lines but does not help conditionally.
Referring to unstaged files instead of staged files.
5fill in blank
hard

Fill all three blanks to create a pre-commit hook that formats Python files with black and adds them back to staging.

Git
for file in $(git diff --cached --name-only --diff-filter=ACM | grep '\.py$'); do
  black [1]
  git add [2]
done

exit [3]
Drag options to blanks, or click blank then click option'
A$file
Bfile
C0
D1
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting the $ before the variable name.
Exiting with 1 which aborts the commit even if formatting succeeded.