pre-commit hook in Git - Time & Space Complexity
We want to understand how the time taken by a pre-commit hook changes as the project size grows.
Specifically, how does running checks before each commit scale with the number of files or changes?
Analyze the time complexity of this simple pre-commit hook script.
#!/bin/sh
# Run lint on all staged files
files=$(git diff --cached --name-only --diff-filter=ACM | grep '\.js$')
for file in $files; do
eslint "$file"
done
This hook runs a linter on each staged JavaScript file before allowing a commit.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping over each staged JavaScript file to run eslint.
- How many times: Once for each staged .js file in the commit.
As the number of staged JavaScript files increases, the number of eslint runs grows linearly.
| Input Size (n files) | Approx. Operations (eslint runs) |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The work grows directly in proportion to the number of files checked.
Time Complexity: O(n)
This means the time to run the pre-commit hook grows linearly with the number of staged files.
[X] Wrong: "The pre-commit hook runs in constant time regardless of files."
[OK] Correct: Each file adds work because the hook runs eslint on every staged file, so more files mean more time.
Understanding how pre-commit hooks scale helps you write efficient checks that keep your workflow smooth as projects grow.
"What if the hook ran eslint once on all files together instead of one by one? How would the time complexity change?"