Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git commit revision id to be five chars long when using pretty format in Ruby script

My code is the following

system('git log --pretty=format:[%h]: %an')

where %h gives the revision id of the commit, and it is seven characters long and %an is the author name.

My problem is that I want to have a five-digits revision id and not seven, but I can't find any flag of the form.

--date=iso-strict

or whatever to do so.

How do I do it?

like image 957
hack-is-art Avatar asked Mar 26 '26 03:03

hack-is-art


2 Answers

7 digits is the default and is the generally accepted minimum to ensure uniqueness on moderate sized projects. Anything less runs the risk of collisions. If you want to trim it you can ask:

--abbrev=5

This may be overruled by the git command if the 5 digit values are not unique. Consider this value a minimum and not a maximum.

You can read more with git log --help.

As a note, you generally want to break out arguments to system to avoid confusion between them:

system("git", "--log", "--pretty-format=...")

That's especially necessary when passing in arbitrary filenames as those can be interpreted by the shell in ways that are hazardous.

like image 85
tadman Avatar answered Mar 28 '26 16:03

tadman


Tadman answer is almost complete. However I red the man page for git log and found something interesting in the format section (you can also have it here).

You can truncate any placeholder using a previous placeholder such as %<(5,trunc). Here the command will truncate right if length of the next placeholder is more than 5 or pad right otherwise.

So in your case, this will truncate to 5:

system("git log --pretty=format:'[%<(5,trunc)%h]: %an'")

The only issue here is that you will only have 3 usefull digits, because when it truncate, format add .. to show that your placeholder is not complete. So an example of result would be :

[8b9..]: Jack Johnson
[5fe..]: Popeye
[2cb..]: Jack Johnson
[e5d..]: Jack Johnson
[605..]: Plastic Bertrand
[20c..]: Plastic Bertrand

EDIT:

You can easily remove those last dots using:

system("git log --pretty=format:'[%<(7,trunc)%h]: %an' | tr -d .")

Then you would have the clean result expected:

[8b972]: Jack Johnson
[5fe3d]: Popeye
[2cbe0]: Jack Johnson
[e5d06]: Jack Johnson
[605d7]: Plastic Bertrand
[20cae]: Plastic Bertrand
like image 20
Ulysse BN Avatar answered Mar 28 '26 17:03

Ulysse BN



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!