File: build_embedded_go.py

package info (click to toggle)
gobgp 3.36.0-2
  • links: PTS, VCS
  • area: main
  • in suites: experimental, forky, sid, trixie, trixie-proposed-updates
  • size: 5,916 kB
  • sloc: python: 11,743; sh: 3,653; makefile: 90; cpp: 70
file content (63 lines) | stat: -rw-r--r-- 1,758 bytes parent folder | download
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import sys
import os
from subprocess import call

def build_embedded_go_codes(filename):
    """
    Extract embedded Go code snippets from a Markdown file and compile each of them.

    Args:
        filename (str): The path to the Markdown file containing embedded Go code snippets.

    Returns:
        list: A list of output Go file names that were created and compiled.

    Raises:
        ValueError: If no Go code block is found in the file.
    """

    with open(filename, 'r') as f:
        flag = False  # Tracks if inside Go block
        codes = []   # Go codes from embedded
        snippet_counter = 1
        out_files = []

        for line in f.readlines():
            if line.strip() == '```go':
                flag = True
                codes = []
            elif line.strip() == '```' and flag:
                out = f'temporary_{snippet_counter}.go'
                out_files.append(out)

                if os.path.exists(out):
                    os.remove(out)

                with open(out, 'w') as g:
                    g.write("".join(codes))

                snippet_counter += 1
                flag = False
            elif flag:
                codes.append(line)

        if not out_files:
            raise ValueError("No Go code block found in the markdown file (argument).")

        return out_files


if __name__ == '__main__':
    filename = sys.argv[1]
    out_files = build_embedded_go_codes(filename)

    ret_code = 0
    for out in out_files:
        ret = call(['go', 'build', '-o', out.replace('.go', ''), out])
        if ret != 0:
            ret_code = ret
        os.remove(out)
        if os.path.exists(out.replace('.go', '')):
            os.remove(out.replace('.go', ''))

    sys.exit(ret_code)