How to Use Git Annotate to Track Line Changes
Use
git annotate <file> to show who last changed each line of a file along with the commit info. This helps track line-by-line changes and authorship in your code.Syntax
The basic syntax of git annotate is:
git annotate <file>: Shows the last commit and author for each line in the file.git annotate -L <start,end> <file>: Limits annotation to specific line numbers.git annotate --date=short <file>: Shows commit dates in short format.
bash
git annotate <file> git annotate -L <start>,<end> <file> git annotate --date=short <file>
Example
This example shows how to use git annotate on a file named app.js. It displays the commit hash, author, and the line content for each line in the file.
bash
git annotate app.js
Output
e3a1b2c4 (Alice 2024-06-01 12:34:56 +0000 1) const greet = () => {
e3a1b2c4 (Alice 2024-06-01 12:34:56 +0000 2) console.log('Hello, world!');
7f9d8e1a (Bob 2024-06-05 09:20:10 +0000 3) }
Common Pitfalls
Common mistakes when using git annotate include:
- Trying to annotate a file not tracked by git, which will cause an error.
- Confusing
git annotatewithgit blame; they are aliases butgit blameis more commonly used. - Not specifying line ranges when you want to limit output, leading to overwhelming information.
Always ensure the file exists in the repository and use line limits for large files.
bash
git annotate non_existent_file.js # Error: fatal: no such path 'non_existent_file.js' in HEAD git annotate -L 10,20 app.js # Shows only lines 10 to 20 annotated
Output
fatal: no such path 'non_existent_file.js' in HEAD
7f9d8e1a (Bob 2024-06-05 09:20:10 +0000 10) console.log('Line 10 content');
7f9d8e1a (Bob 2024-06-05 09:20:10 +0000 11) console.log('Line 11 content');
... (lines 12 to 20 similarly annotated)
Quick Reference
| Option | Description |
|---|---|
<file> | File to annotate |
-L <start,end> | Annotate only lines from start to end |
--date=short | Show commit dates in short format |
--show-email | Show author email instead of name |
--reverse | Show oldest commits first |
Key Takeaways
Use
git annotate <file> to see who last changed each line in a file.Limit output with
-L to focus on specific lines.Ensure the file is tracked by git to avoid errors.
git annotate and git blame are the same command; git blame is more common.Use options like
--date=short for clearer date formats.