-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun.py
More file actions
executable file
·177 lines (145 loc) · 5.06 KB
/
Copy pathrun.py
File metadata and controls
executable file
·177 lines (145 loc) · 5.06 KB
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
#!/usr/bin/env python3
import subprocess, sys, os
from pathlib import Path
from datetime import datetime, timedelta
from dataclasses import dataclass
from enum import Enum
import platform
ROOT = Path(__file__).parent.resolve()
SRC_DIR = Path(f"{ROOT}/src")
PROJ_NAME = ROOT.name # env var
PROJ_REPO = f"https://github.com/simon-danielsson/{PROJ_NAME}" # env var
AUTH = "Simon Danielsson" # env var
AUTH_CONT = "contact@simondanielsson.se" # env var
C_STD = "c99" # c standard used to compile program
AUTO_RUN = True # if true, run binary after compile
AUTO_RUN_ARGS = ["~/notes/.mmry.md"] # program args used at auto run
PRINT_COMPILE_DETAILS = True # build-type, compiler, compile time
C_FLAGS_DEBUG = [ # used for both debug and test builds
"-O0",
"-DDEBUG",
"-fsanitize=address",
"-fsanitize=undefined",
"-fno-omit-frame-pointer",
"-Wall",
"-Wpedantic",
"-Wshadow",
"-Werror=format-security",
]
C_FLAGS_RELEASE = ["-flto", "-O2", "-DNDEBUG"]
BLD = "\033[1m"
RST = "\x1b[0m"
# classes & types -------------------------------------------------------------
class BuildType(Enum):
Release = "release"
Debug = "debug"
Test = "test"
@dataclass
class Args:
build: BuildType = BuildType.Debug
help: bool = False
prog: str = ""
@dataclass
class CmdExec:
process: subprocess.CompletedProcess[str]
exec_time: timedelta
# cmd exec --------------------------------------------------------------------
def run_cmd(cmd) -> CmdExec:
start = datetime.now()
process = subprocess.run(cmd, capture_output=True, text=True)
end = datetime.now()
exec_time = end - start
return CmdExec(exec_time=exec_time, process=process)
# git & env -------------------------------------------------------------------
def get_git_vers() -> str:
cmd = ["git", "describe", "--tags", "--abbrev=0"]
result = run_cmd(cmd)
if result.process.returncode != 0:
return "v0.0.0"
return result.process.stdout.strip()
def get_git_hash(short: bool) -> str:
cmd = ["git", "rev-parse", "HEAD"]
if short:
cmd.insert(2, "--short")
result = run_cmd(cmd)
if result.process.returncode != 0:
return "0".zfill(7)
return result.process.stdout.strip()
GIT_V = get_git_vers()
GIT_HASH_SH = get_git_hash(True)
GIT_HASH = get_git_hash(False)
ENV_FLAGS = [
f'-DENV_GITHASH="{GIT_HASH}"',
f'-DENV_GITTAG="{GIT_V}"',
f'-DENV_NAME="{PROJ_NAME}"',
f'-DENV_AUTHOR="{AUTH}"',
f'-DENV_CONTACT="{AUTH_CONT}"',
f'-DENV_REPO="{PROJ_REPO}"',
f"-std={C_STD}",
]
# build -----------------------------------------------------------------------
def collect_src_files(src: Path) -> list[str]:
return [f"{path}" for path in src.rglob("*.c")]
def build(a: Args) -> None:
build_dir = Path(f"{ROOT}/build/{a.build.value}")
bin_name = f"{PROJ_NAME}_{a.build.value}_{GIT_V}_{GIT_HASH_SH}"
c_flags: list[str] = ENV_FLAGS
match a.build:
case BuildType.Debug:
c_flags = c_flags + C_FLAGS_DEBUG
case BuildType.Release:
c_flags = c_flags + C_FLAGS_RELEASE
case BuildType.Test:
c_flags.append("-DTEST")
c_flags = c_flags + C_FLAGS_DEBUG
os.makedirs(build_dir, exist_ok=True)
build_cmd = c_flags + collect_src_files(SRC_DIR) + ["-o", f"{build_dir}/{bin_name}"]
try:
compiler = "clang"
output = run_cmd([compiler] + build_cmd)
except FileNotFoundError:
compiler = "gcc"
output = run_cmd([compiler] + build_cmd)
if PRINT_COMPILE_DETAILS:
print(f"{a.build.value} via " f"{compiler} ({C_STD}) {output.exec_time}")
if AUTO_RUN:
if output.process.returncode != 0:
print(output.process.stderr)
sys.exit(output.process.returncode)
env = os.environ.copy()
if platform.system() == "Darwin":
env["MallocNanoZone"] = "0"
exe_path = (build_dir / bin_name).resolve()
os.execvpe(str(exe_path), [str(exe_path)] + AUTO_RUN_ARGS, env)
# main ------------------------------------------------------------------------
def help() -> None:
print(
f"{BLD}run release{RST}\n"
f"-> ./build/release\n"
f"{BLD}run debug{RST}\n"
f"-> ./build/debug\n"
f"{BLD}run test{RST}\n"
f"-> ./build/test"
)
def get_args() -> Args:
a: Args = Args()
a.prog = sys.argv[0].rsplit("/")[-1]
for arg in sys.argv:
match arg:
case r if r.startswith("r"):
a.build = BuildType.Release
case d if d.startswith("d"):
a.build = BuildType.Debug
case t if t.startswith("t"):
a.build = BuildType.Test
case h if h.startswith("h"):
a.help = True
return a
def main():
a: Args = get_args()
if a.help:
help()
return
build(a)
if __name__ == "__main__":
main()