How to use commit-filter in CGIT to add a link to the bug number

2020-12-31 15:57:23 — by Kevin Suo


Cgit is a great tool. If you want to make it better to add a link to the bug number if the commit message contains a given pattern (e.g., tdf#123456), then you should:

First, Create an executable script file which accepts STDIN as input and generate an output to STDOUT. For instance, I use the following python code, and place it in anywhere (e.g., /home/bin/cgit-commit-filter.py)

#!/usr/bin/env python3
import sys
import re

regs = [
        {"exp": r"tdf\#([0-9]+)", "replace_to": r"<a href='https://bugs.documentfoundation.org/show_bug.cgi?id=\1'>tdf#\1</a>"},
    ]

for s in sys.stdin:
    s = s.strip()
    for reg in regs:
        if re.findall(reg["exp"], s):
            s = re.sub(reg["exp"], reg["replace_to"], s)
            break
    print(s)

The above code stores the string accepted from STDIN in variable s, then defines some sets of regular expression as well as the replacement rule in variable regs. Then, it tests whether we can find the text in s; if it finds, then the text is replaced according to the defined rule and print the replaced text in STDOUT; otherwise, the original text is printed. You can define several pattern and replacement rule pairs in “regs” above.

Then make the script executable:

$ chmod +x /home/bin/cgit-commit-filter.py

To test, run this script from command line, type in some test strings, hit ENTER to see the result:

$ ./cgit-commit-filter.py 
tdf#12345 make libreoffice better with this commit
<a href='https://bugs.documentfoundation.org/show_bug.cgi?id=12345'>tdf#12345</a> make libreoffice better with this commit

And finally, add the following line in /etc/cgitrc:

commit-filter=/home/bin/cgit-commit-filter.py

Wait several minutes, then I can see that every commit message with the pattern “tdf#123456” will have a link which goes to the TDF bug tracker.

Here I used python code. You may use shell script if you want, see: https://git.zx2c4.com/cgit/commit/cgit.h?id=f35db1cd2b75aac6952aa07713e44ca01fd89727