1# Copyright (c) 2019-2022 Intel Corporation.
2#
3# SPDX-License-Identifier: Apache-2.0
4
5# based on http://protips.readthedocs.io/link-roles.html
6
7from __future__ import print_function
8from __future__ import unicode_literals
9import re
10import os
11import os.path
12from os import path
13import subprocess
14from docutils import nodes
15
16
17def run_cmd_get_output(cmd):
18    try:
19        with open(os.devnull, 'w') as devnull:
20            output = subprocess.check_output(cmd, stderr=devnull, shell=True).strip()
21    except subprocess.CalledProcessError as e:
22        output = e.output.decode('ascii')
23
24    return output
25
26def get_github_rev():
27    tag = run_cmd_get_output('git describe --exact-match')
28    if tag:
29        return tag.decode("utf-8")
30    else:
31        return 'master'
32
33
34def setup(app):
35    rev = get_github_rev()
36
37    baseurl = 'https://github.com/projectacrn/acrn-hypervisor'
38
39    app.add_role('acrn_file', autolink('{}/blob/{}/%s'.format(baseurl, rev)))
40    app.add_role('acrn_raw', autolink('{}/raw/{}/%s'.format(baseurl, rev)))
41
42    # The role just creates new nodes based on information in the
43    # arguments; its behavior doesn't depend on any other documents.
44    return {
45        'parallel_read_safe': True,
46        'parallel_write_safe': True,
47    }
48
49
50def autolink(pattern):
51    def role(name, rawtext, text, lineno, inliner, options={}, content=[]):
52        m = re.search(r'(.*)\s*<(.*)>', text)
53        if m:
54            link_text = m.group(1)
55            link = m.group(2)
56        else:
57            link_text = text
58            link = text
59        url = pattern % (link,)
60        node = nodes.reference(rawtext, link_text, refuri=url, **options)
61        return [node], []
62    return role
63