pre-push hook in Git - Time & Space Complexity
We want to understand how the time taken by a git pre-push hook changes as the amount of work it does grows.
Specifically, how does the hook's execution time grow when it checks many files or runs many commands before pushing?
Analyze the time complexity of the following pre-push hook script.
#!/bin/sh
# pre-push hook example
while read local_ref local_sha remote_ref remote_sha ; do
git diff --name-only $local_sha $remote_sha | while read file ; do
echo "Checking $file"
# simulate check command
done
done
This hook reads refs being pushed, then lists changed files and checks each one before allowing the push.
- Primary operation: Loop over changed files to check each one.
- How many times: Once per changed file in the push.
As the number of changed files increases, the hook runs more checks, so time grows roughly in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 changed files | 10 checks |
| 100 changed files | 100 checks |
| 1000 changed files | 1000 checks |
Pattern observation: The time grows linearly with the number of changed files.
Time Complexity: O(n)
This means the hook's running time increases directly with the number of files it checks before pushing.
[X] Wrong: "The hook always runs in constant time no matter how many files change."
[OK] Correct: The hook checks each changed file one by one, so more files mean more work and longer time.
Understanding how hooks scale helps you write efficient checks that keep your code safe without slowing down your workflow too much.
"What if the hook ran a single command that checked all files at once instead of one by one? How would the time complexity change?"