-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
jinja2_git.py
35 lines (26 loc) · 1.03 KB
/
jinja2_git.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import subprocess # noqa: S404
from jinja2 import nodes
from jinja2.ext import Extension
from jinja2.parser import Parser
class GitExtension(Extension):
"""This class represents jinja2 extension to render current commit hash."""
tags = {'gitcommit'}
def parse(self, parser: Parser) -> nodes.Output:
"""Main method to render data into the template."""
lineno = next(parser.stream).lineno
if parser.stream.skip_if('name:short'):
parser.stream.skip(1)
short = parser.parse_expression()
else:
short = nodes.Const(False) # noqa: WPS425
commit = self.call_method('_commit_hash', [short], [], lineno=lineno)
return nodes.Output([commit], lineno=lineno)
def _commit_hash(self, short: bool) -> str:
command = [
'git',
'rev-parse',
'--short' if short else '--verify',
'HEAD',
]
output = subprocess.check_output(command) # noqa: S603
return output.decode('utf-8').strip()