Search code examples
gitautomationaliascommit

How to add custom prefix to your git commit messages using git aliases?


Let's say I want to make my commits more fancy. Every single commit would have a special prefix type included in "-" symbol. For example :

-feat- : Added new feature
-fix- : Fixed this annoying bug
-refactor- : Refactored this piece of code
-chore- : Wrote some tests

I want to automate all those prefixes using git aliases i. e. create custom commands for each of the type : comfeat, comfix, comref and comchore.

So far I've tried doing something like this:

comfeat = "!f() { git add --all && git commit -am '-feat- : ${1}'; }; f"

And when I try to call this command I would get this :

PS D:\Projects\Test> git comfeat "Added new feature"
[master 9fcb0c9] -feat- : ${1}

P.S. I have no prior knowledge in bash/shell so any help will be much appreciated.

P.S.S. I've seen people using git hooks for extracting branch names and prepending them to commits, but I am working alone on the project, so I don't have many branches for each feature I'm working on.


Solution

  • So, after some digging and with the help of ChatGPT thingie I actually found a solution to this problem. My finalized version of alias part of .gitconfig file looks like this:

    [alias]
        comfeat = !sh -c 'git add -A && git commit -m \"-feat- : $1\"' -
        comfix = !sh -c 'git add -A && git commit -m \"-fix- : $1\"' -
        comchore = !sh -c 'git add -A && git commit -m \"-chore- : $1\"' -
        comref = !sh -c 'git add -A && git commit -m \"-refactor- : $1\"' -
    

    Now I can type:

    git comref "Refactored user class."
    

    and my commit message would look like:

    [master 0ba3e4c] -refactor- : Refactored user class.