Debian Codegraph @

configure

raw
1 #!/usr/bin/env python3
2 import datetime
3 import argparse
4 import subprocess
5 import os
6 import sys
7 import shutil
8 import platform
9 from collections.abc import Callable
10 from dataclasses import dataclass
11
12 # constants
13 VERSION = '4.2.2'
14 TAG_TIME = '2026-6-8'
15
16 # color escape code definition
17 if not os.getenv('NO_COLOR'):
18 def TXT_RED(s): return f'\x1b[31m{s}\x1b[0m'
19 def TXT_GREEN(s): return f'\x1b[32m{s}\x1b[0m'
20 def TXT_YELLOW(s): return f'\x1b[33m{s}\x1b[0m'
21 def TXT_BLUE(s): return f'\x1b[34m{s}\x1b[0m'
22 def TXT_MAGENTA(s): return f'\x1b[35m{s}\x1b[0m'
23 def TXT_CYAN(s): return f'\x1b[36m{s}\x1b[0m'
24 def TXT_GRAY(s): return f'\x1b[90m{s}\x1b[0m'
25 else:
26 def TXT_RED(s): return s
27 def TXT_GREEN(s): return s
28 def TXT_YELLOW(s): return s
29 def TXT_BLUE(s): return s
30 def TXT_MAGENTA(s): return s
31 def TXT_CYAN(s): return s
32 def TXT_GRAY(s): return s
33
34 # error handling
35 def info(*args, **kwargs):
36 print(*args, **kwargs, flush=True)
37
38 def warn(msg: any):
39 print(TXT_YELLOW(f'[WARN] {msg}'), flush=True, file=sys.stderr)
40
41 def error(msg: any):
42 print(TXT_RED(f'[ERR!] {msg}'), file=sys.stderr)
43 sys.exit(1)
44
45 # build option parsing
46 class GNUStyleHelpFormatter(argparse.RawDescriptionHelpFormatter):
47 """Custom help formatter that forces --opt=VALUE style"""
48 def _format_action_invocation(self, action):
49 # only long options, no short option
50 if not action.option_strings:
51 return super()._format_action_invocation(action)
52 return ', '.join(f'{opt}={action.metavar}' if action.metavar else opt
53 for opt in action.option_strings)
54
55 def parse_args() -> tuple[argparse.Namespace, list[str]]:
56 epilog = '''Some influential environment variables:
57 CC C compiler command
58 CFLAGS Extra C compiler flags
59 LDFLAGS Extra linker flags
60 ASCIIDOC Asciidoc document compiler
61
62 Please report bug at https://github.com/dbgbgtf1/Ceccomp
63 Copyright (C) 2025-present, distributed under GPLv3 or later
64 '''
65 parser = argparse.ArgumentParser(
66 prog='configure.py',
67 description='Configure build flags for Ceccomp, written in Python',
68 epilog=epilog,
69 formatter_class=GNUStyleHelpFormatter,
70 )
71
72 config_grp = parser.add_argument_group('Configure-time options (fixed once Makefile is generated)')
73 config_grp.add_argument('--enable-verbose', action='store_true', help='Enable verbose output')
74 config_grp.add_argument('--without-doc', action='store_true', help='Do not install documentation')
75 config_grp.add_argument('--without-i18n', action='store_true', help='Do not generate locale mo files')
76 config_grp.add_argument('--devmode', action='store_true', help='Allow you to compile against any commit (only work in git mode)')
77 config_grp.add_argument('--packager', type=str, metavar='BY', default=None,
78 help='Who build the package (default: manual or OS name if setting prefix to /usr)')
79 config_grp.add_argument('--disable-option-checking', action='store_true', help='Whether to throw an error when unknown options found')
80 config_grp.add_argument('--build', type=str, metavar='TARGET',
81 help='Which target to build against, optional. For instance, x86_64-linux-gnu')
82 config_grp.add_argument('--includedir', type=str, metavar='DIR', help='Optional system include directory')
83 config_grp.add_argument('--libdir', type=str, metavar='DIR', help='Optional system library directory')
84 # argp is dynamically tested
85
86 make_grp = parser.add_argument_group('Make-time options (can be overridden by make cli) [make var]')
87 make_grp.add_argument('--prefix', type=str, metavar='PREFIX', default='/usr/local',
88 help='Installation prefix (default: /usr/local) [PREFIX]')
89 make_grp.add_argument('--bindir', type=str, metavar='DIR',
90 help='User executables directory (default: PREFIX/bin) [BIN_DIR]')
91 make_grp.add_argument('--zshfpath', type=str, metavar='DIR',
92 help='Zsh functions path (default: PREFIX/share/zsh/site-functions) [ZSH_FPATH]')
93 make_grp.add_argument('--docdir', type=str, metavar='DIR',
94 help='Documentation directory (default: PREFIX/share/doc/ceccomp) [DOC_DIR]')
95 make_grp.add_argument('--mandir', type=str, metavar='DIR',
96 help='Man pages directory (default: PREFIX/share/man) [MAN_DIR]')
97 make_grp.add_argument('--localedir', type=str, metavar='DIR',
98 help='Localization directory (default: PREFIX/share/locale) [LOCALE_DIR]')
99 make_grp.add_argument('--destdir', type=str, metavar='DIR',
100 help='Optional dir to install software, useful for package managers [DESTDIR]')
101 make_grp.add_argument('--debug-level', type=int, metavar='LEVEL', default=1,
102 help='Set debug symbol level (0: -O2 -s|1: -O2 -g, default|2: -O0 -g3 -DDEBUG) [DEBUG]')
103 make_grp.add_argument('--version', type=str, metavar='VER',
104 help=f'Set ceccomp version (default: {VERSION}) [VERSION]')
105 make_grp.add_argument('--tag-time', type=str, metavar='TIME',
106 help=f'Set the time of current tag. Use "CONFIG" for the time when running configure; or write in YYYY-mm-dd like default value {TAG_TIME} [TAG_TIME]')
107 make_grp.add_argument('--enable-static', action='store_true', help='Enable static build [STATIC]')
108
109 return parser.parse_known_args()
110
111 @dataclass
112 class BuildOptions:
113 prefix: str
114 bindir: str
115 zshfpath: str
116 docdir: str
117 mandir: str
118 localedir: str
119 destdir: str
120 debug_level: int
121 version: str
122 tag_time: str
123 is_static: bool
124
125 verbose: bool
126 doc: bool
127 i18n: bool
128 devmode: bool
129 builder: str | None
130 check_option: bool
131 target: str
132 sys_includedir: str
133 sys_libdir: str
134
135 cc: list[str] | None
136 asciidoc: str | None
137 cflags: str
138 ldflags: str
139
140 unknown_options: list[str]
141
142 has_set_packager: bool = False
143 is_official_package: bool = False
144 git_install: bool = True
145
146 def __post_init__(self):
147 if self.bindir is None:
148 self.bindir = os.path.join(self.prefix, 'bin')
149 if self.zshfpath is None:
150 self.zshfpath = os.path.join(self.prefix, 'share', 'zsh', 'site-functions')
151 if self.docdir is None:
152 self.docdir = os.path.join(self.prefix, 'share', 'doc', 'ceccomp')
153 if self.mandir is None:
154 self.mandir = os.path.join(self.prefix, 'share', 'man')
155 if self.localedir is None:
156 self.localedir = os.path.join(self.prefix, 'share', 'locale')
157
158 def replace_prefix(dirent: str | None) -> str:
159 return dirent.replace('${prefix}', self.prefix) if dirent else ''
160
161 self.bindir = replace_prefix(self.bindir)
162 self.zshfpath = replace_prefix(self.zshfpath)
163 self.docdir = replace_prefix(self.docdir)
164 self.mandir = replace_prefix(self.mandir)
165 self.localedir = replace_prefix(self.localedir)
166 self.destdir = replace_prefix(self.destdir)
167
168 self.sys_includedir = replace_prefix(self.sys_includedir)
169 self.sys_libdir = replace_prefix(self.sys_libdir)
170
171 if self.debug_level not in (0, 1, 2):
172 error('debug_level option can only be 0, 1 or 2!')
173
174 def check_cmd(env: str, *candidates: list[str]) -> str | None:
175 """enumerate available command in system"""
176 var = getattr(self, env)
177 if var is not None:
178 if isinstance(var, str) and shutil.which(var) is None:
179 error(f'{var} provided by environment {env.upper()} is not runnable!')
180 elif isinstance(var, list) and shutil.which(var[0]) is None:
181 error(f'{var[0]} provided by environment {env.upper()} is not runnable!')
182 else:
183 return var
184 # no such environment variable
185 for candidate in candidates:
186 if shutil.which(candidate) is not None:
187 return candidate
188 return None
189
190 self.cc = self.cc.strip().split() if self.cc else None
191 if isinstance(self.cc, list) and len(self.cc) == 1:
192 self.cc = self.cc[0]
193
194 # the None value will be processed in check
195 if self.target:
196 self.cc = check_cmd('cc', f'{self.target}-cc', f'{self.target}-gcc', f'{self.target}-clang')
197 if not self.cc:
198 warn(f'No C compiler with prefix {self.target} found, append it in CC')
199 self.cc = check_cmd('cc', 'clang', 'gcc', 'cc')
200 # clang and zig cc adds target to back
201 if not (isinstance(self.cc, str) and self.target in self.cc):
202 if isinstance(self.cc, str):
203 self.cc = [self.cc, '-target', self.target]
204 elif isinstance(self.cc, list): # could be None
205 self.cc.extend(['-target', self.target])
206 else: # cc may be passed from environ, so we shall not merge the logic
207 self.cc = check_cmd('cc', 'cc', 'gcc', 'clang')
208 if isinstance(self.cc, str):
209 self.cc = [self.cc]
210 self.asciidoc = check_cmd('asciidoc', 'asciidoctor')
211 if self.cflags is None:
212 self.cflags = ''
213 if self.ldflags is None:
214 self.ldflags = ''
215 if self.tag_time == 'CONFIG':
216 self.tag_time = datetime.datetime.today().strftime('%Y-%m-%d')
217 elif self.tag_time:
218 try:
219 datetime.datetime.strptime(self.tag_time, '%Y-%m-%d')
220 except ValueError:
221 error(f'Invalid tag-time {self.tag_time}, format is YYYY-mm-dd')
222
223 # check the options
224 if self.unknown_options:
225 if self.check_option:
226 error(f'Unrecognized options: {" ".join(self.unknown_options)}, please pass --help to see correct options!')
227 else:
228 for opt in self.unknown_options:
229 info(TXT_GRAY(f'Ignoring unknown option {opt}'))
230 warn(f'Discarding {len(self.unknown_options)} unknown options!')
231
232 self.is_official_package = self.prefix == '/usr'
233 self.has_set_packager = self.builder is not None
234 try:
235 if not self.has_set_packager:
236 if self.is_official_package:
237 self.builder = platform.freedesktop_os_release()['NAME']
238 else:
239 self.builder = 'manual'
240 except (OSError, KeyError):
241 self.builder = 'manual'
242
243
244 args, unknown = parse_args()
245 buildopts = BuildOptions(
246 prefix=args.prefix,
247 bindir=args.bindir,
248 zshfpath=args.zshfpath,
249 docdir=args.docdir,
250 mandir=args.mandir,
251 localedir=args.localedir,
252 destdir=args.destdir,
253 debug_level=args.debug_level,
254 version=args.version,
255 tag_time=args.tag_time,
256 is_static=args.enable_static,
257
258 verbose=args.enable_verbose,
259 doc=not args.without_doc,
260 i18n=not args.without_i18n,
261 devmode=args.devmode,
262 builder=args.packager,
263 check_option=not args.disable_option_checking,
264 target=args.build,
265 sys_includedir=args.includedir,
266 sys_libdir=args.libdir,
267
268 cc=os.getenv('CC'),
269 asciidoc=os.getenv('ASCIIDOC'),
270 cflags=os.getenv('CFLAGS'),
271 ldflags=os.getenv('LDFLAGS'),
272
273 unknown_options=unknown,
274 )
275 del args, unknown
276
277 # gathering system information and check
278 @dataclass
279 class Makefile:
280 s: str
281 def inject(self, placeholder: str, filler: str | list[str] | bool) -> None:
282 if isinstance(filler, str):
283 self.s = self.s.replace(f'{{{{{placeholder}}}}}', filler) # {{PLACEHOLDER}}
284 return
285 if isinstance(filler, bool):
286 # automatically loop from 0 to perform substitution
287 keep = filler
288 i = 0
289 while True:
290 if self.s.find(f'{{{{{placeholder}_IF}}}}') == -1:
291 break
292 if keep:
293 self.s = self.s.replace(f'{{{{{placeholder}_IF}}}}', '') # {{PLACEHOLDER_IF}}
294 self.s = self.s.replace(f'{{{{{placeholder}_ENDIF}}}}', '')
295 else:
296 begin = self.s.find(f'{{{{{placeholder}_IF}}}}')
297 end = self.s.find(f'{{{{{placeholder}_ENDIF}}}}')
298 assert begin != -1
299 assert end != -1
300 end += len(f'{{{{{placeholder}_ENDIF}}}}')
301 self.s = self.s[:begin] + self.s[end:]
302 i += 1
303 return
304 for i, e in enumerate(filler):
305 self.s = self.s.replace(f'{{{{{placeholder}{i}}}}}', e) # {{PLACEHOLDER0}}
306
307 class TaskManager:
308 tasks: list[Callable[[Makefile], None]]
309 makefile: Makefile
310
311 def __init__(self, makefile_name: str) -> None:
312 self.tasks = []
313 if not os.path.isfile(makefile_name):
314 error(f'Reading Makefile {makefile_name}, but it\'s not a file!')
315 try:
316 with open(makefile_name) as file:
317 self.makefile = Makefile(file.read())
318 except OSError as e:
319 error(f'Can not open Makefile: {e}')
320
321 def run_tasks(self):
322 width = len(str(len(self.tasks)))
323 total = len(self.tasks)
324 for seq, handler in enumerate(self.tasks, start=1):
325 # no need to flush as stdout will be flushed in handler
326 info(f'[{seq:>{width}}/{total}] ', end='')
327 handler(self.makefile)
328
329 def add_task(self, handler: Callable[[Makefile], None]):
330 self.tasks.append(handler)
331
332 taskmgr = TaskManager('Makefile.in')
333
334
335 def pcheck(txt: str):
336 info(f'Checking {txt}... ', end='')
337
338 def run_command(argv: list[str], stdin: str | None=None, push_sys_dir: bool=False) -> tuple[int, str, str]:
339 """
340 Run command with given argv and input, return process returncode, stdout and stderr
341 Return -1, '', exception message if exception raised is known, or else return -2, '', message.
342 """
343 try:
344 argv[0] = shutil.which(argv[0])
345 if push_sys_dir: # using C compiler!
346 if buildopts.sys_includedir: # in case some include/lib is not accessible for current compiler
347 argv.append(f'-I{buildopts.sys_includedir}')
348 if buildopts.sys_libdir:
349 argv.append(f'-L{buildopts.sys_libdir}')
350 if buildopts.is_static:
351 argv.append('-static')
352 proc = subprocess.run(argv, input=stdin, capture_output=True, text=True)
353 except subprocess.SubprocessError as e:
354 return -1, '', str(e)
355 except UnicodeDecodeError as e:
356 return -1, '', 'UnicodeDecodeError: program output contains non-utf-8 bytes'
357 except Exception as e:
358 return -2, '', str(e)
359 else:
360 return proc.returncode, proc.stdout, proc.stderr
361
362 def new_task(func: Callable) -> Callable:
363 taskmgr.add_task(func)
364 return func
365
366
367 # color definition:
368 # green: well-tested
369 # cyan: should work
370 # blue: not work and have to take fallback choice
371 # magenta: unexpected or no fallback choice
372 @new_task
373 def check_platform(_: Makefile):
374 pcheck('system platform')
375 if sys.platform == 'linux':
376 info(TXT_GREEN('linux'))
377 elif sys.platform == 'android':
378 info(TXT_CYAN('android'))
379 else:
380 info(TXT_MAGENTA(sys.platform))
381 error(f'Ceccomp only support Linux!')
382
383 TIER_1_ARCH = [ # tested
384 'x86_64', 'i386', 'i686', 'riscv64', 'loongarch64', 'aarch64',
385 'ppc', 'ppc64le', 's390x', 'armv8l', 'armv7l',
386 ]
387 TIER_2_ARCH = [ # untested, but listed in libseccomp
388 'x32', 'parisc', 'parisc64', 'mips', 'm68k', 's390', 'ppc64', 'arm',
389 ]
390 @new_task
391 def check_architecture(_: Makefile):
392 pcheck('current architecture')
393 bits = platform.architecture()[0]
394 arch = platform.machine()
395 mach = f'{bits}, {arch}'
396 if arch in TIER_1_ARCH:
397 info(TXT_GREEN(mach))
398 elif arch in TIER_2_ARCH:
399 info(TXT_CYAN(mach))
400 else:
401 info(TXT_BLUE(mach))
402 warn('Current architecture is not supported by libseccomp')
403
404 @new_task
405 def check_flock(makefile: Makefile):
406 pcheck('if flock in system')
407 if shutil.which('flock') is None:
408 makefile.inject('VERBOSE', '1')
409 info(TXT_BLUE('no'))
410 warn('flock not found in system, Makefile verbose is set to true. You may need util-linux package')
411 else:
412 makefile.inject('VERBOSE', '1' if buildopts.verbose else '0')
413 info(TXT_GREEN('yes'))
414
415 @new_task
416 def check_i18n(makefile: Makefile):
417 pcheck('internationalization support')
418 if not buildopts.i18n:
419 makefile.inject('I18N', False)
420 makefile.inject('LOCALEDIR', buildopts.localedir)
421 makefile.inject('LOCALE_SED', 's|@@LOCALEDIR@@||')
422 info(TXT_BLUE('no'))
423 return
424 if shutil.which('xgettext') is None:
425 info(TXT_MAGENTA('no gettext'))
426 error('xgettext and other tools not found, pass --without-i18n to disable l10n generation or install gettext package!')
427 makefile.inject('I18N', True)
428 makefile.inject('LOCALEDIR', buildopts.localedir)
429 makefile.inject('LOCALE_SED', f's|@@LOCALEDIR@@|#define LOCALEDIR "{buildopts.localedir}"|')
430 info(TXT_GREEN('yes'))
431
432 @new_task
433 def check_doc(makefile: Makefile):
434 pcheck('documentation settings')
435 if not buildopts.doc:
436 makefile.inject('DOC', False)
437 info(TXT_BLUE('no doc'))
438 return
439 if buildopts.asciidoc is None:
440 info(TXT_MAGENTA('no asciidoc found'))
441 error('Asciidoc compiler not found, pass --without-doc to disable documentation generation or install asciidoctor package!')
442 makefile.inject('DOC', True)
443 makefile.inject('ASCIIDOC', buildopts.asciidoc)
444 if 'asciidoctor' in buildopts.asciidoc:
445 info(TXT_GREEN(buildopts.asciidoc))
446 else:
447 info(TXT_CYAN(buildopts.asciidoc))
448 warn(f'Your asciidoc compiler {buildopts.asciidoc} is not tested and may fail to generate docs')
449
450 standard_c = '''
451 #include <stdio.h>
452 void leaf(void) {}
453 int main() {
454 puts("");
455 leaf();
456 return 0;
457 }
458 '''
459 @new_task
460 def check_cc(makefile: Makefile):
461 pcheck('C compiler')
462 if buildopts.cc is None:
463 info(TXT_MAGENTA('no cc found'))
464 error('C compiler command not found in system!')
465 code, _, stderr = run_command([*buildopts.cc, '-x', 'c', '-', '-o', '/dev/null'], standard_c)
466 if code:
467 info(TXT_MAGENTA(' '.join(buildopts.cc)))
468 if code == -1:
469 error(f'C compiler is not working: {stderr}')
470 if code == -2:
471 error(f'Unexpected error: {stderr}')
472 info(f'Compiler returned non-zero returncode with message:\n{stderr}', end='')
473 error(f'C compiler can not compile minimum C unit')
474 # code == 0
475 makefile.inject('CC', ' '.join(buildopts.cc))
476 info(TXT_GREEN(' '.join(buildopts.cc)))
477
478
479 linux_headers = '''
480 #include <unistd.h>
481 #include <linux/filter.h>
482 #include <sys/mman.h>
483 int main() {
484 struct sock_fprog *addr = (struct sock_fprog *)mmap(NULL, 0x1000, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0);
485 *addr = (struct sock_fprog){ .len = 0, .filter = NULL };
486 return 0;
487 }
488 '''
489 @new_task
490 def check_linux_headers(_: Makefile):
491 pcheck('Linux-related headers')
492 code, _, stderr = run_command([*buildopts.cc, '-x', 'c', '-', '-o', '/dev/null'], linux_headers, push_sys_dir=True)
493 if code:
494 info(TXT_MAGENTA('no'))
495 if code == -1:
496 error(f'C compiler is not working: {stderr}')
497 if code == -2:
498 error(f'Unexpected error: {stderr}')
499 info(f'Compiler returned non-zero returncode with message:\n{stderr}', end='')
500 error(f'Can not compile Linux-related unit, you may install linux-headers package')
501 info(TXT_GREEN('yes'))
502
503
504 libseccomp = '''
505 #include <stdio.h>
506 #include <seccomp.h>
507 int main() {
508 printf("%d", seccomp_version()->major);
509 return 0;
510 }
511 '''
512 @new_task
513 def check_libseccomp(_: Makefile):
514 pcheck('libseccomp')
515 code, _, stderr = run_command([*buildopts.cc, '-x', 'c', '-', '-lseccomp', '-o', '/dev/null'], libseccomp, push_sys_dir=True)
516 if code:
517 info(TXT_MAGENTA('no'))
518 if code == -1:
519 error(f'C compiler is not working: {stderr}')
520 if code == -2:
521 error(f'Unexpected error: {stderr}')
522 info(f'Compiler returned non-zero returncode with message:\n{stderr}', end='')
523 error(f'Can not compile libseccomp unit, you may install libseccomp package')
524 info(TXT_GREEN('yes'))
525
526
527 argp = '''
528 #include <argp.h>
529 int main(int argc, char **argv) {
530 return argp_parse(0, argc, argv, 0, 0, 0);
531 }
532 '''
533 @new_task
534 def check_argp(makefile: Makefile):
535 pcheck('argp parser')
536 code, _, stderr = run_command([*buildopts.cc, '-x', 'c', '-', '-o', '/dev/null'], argp, push_sys_dir=True)
537 if code:
538 if code == -1:
539 info(TXT_MAGENTA('no'))
540 error(f'C compiler is not working: {stderr}')
541 if code == -2:
542 info(TXT_MAGENTA('no'))
543 error(f'Unexpected error: {stderr}')
544 # code > 0
545 # some system need external argp package, so we try to link
546 code, _, stderr = run_command([*buildopts.cc, '-x', 'c', '-', '-largp', '-o', '/dev/null'], argp)
547 if code:
548 info(TXT_MAGENTA('no'))
549 if code == -1:
550 info(TXT_MAGENTA('no'))
551 error(f'C compiler is not working: {stderr}')
552 if code == -2:
553 info(TXT_MAGENTA('no'))
554 error(f'Unexpected error: {stderr}')
555 info(f'Compiler returned non-zero returncode with message:\n{stderr}', end='')
556 error(f'Can not compile argp unit, you may install argp package')
557 # code == 0 and link argp
558 makefile.inject('LIBARGP', '-largp')
559 info(TXT_CYAN('external'))
560 return
561 # code == 0
562 makefile.inject('LIBARGP', '')
563 info(TXT_GREEN('builtin'))
564
565 @new_task
566 def check_source(_: Makefile):
567 pcheck('source code type')
568 if os.path.isdir('.git'):
569 buildopts.git_install = True
570 info(TXT_GREEN('git install'))
571 else:
572 buildopts.git_install = False
573 info(TXT_CYAN('tarball install'))
574
575 @new_task
576 def check_version(makefile: Makefile):
577 pcheck('target version')
578 if buildopts.git_install:
579 if not buildopts.devmode:
580 code, stdout, stderr = run_command(['git', 'describe', '--exact-match'])
581 if code < 0:
582 info(TXT_MAGENTA('git failed'))
583 info(f'Git not accessible? {stderr}')
584 error('Can not run git, you may install git package')
585
586 elif code == 0: # we are at a tag, adopt it
587 tag = stdout.strip()
588 buildopts.version = tag if not tag.startswith('v') else tag[1:]
589 code, stdout, _ = run_command(['git', 'log', '-1', '--format=format:%as', tag])
590 if code:
591 info(TXT_MAGENTA('get tag time failed'))
592 info(stderr, end='' if stderr[-1] == '\n' else '\n')
593 error('Can not get tag-time for the latest tag')
594 buildopts.tag_time = stdout.strip()
595
596 else: # we are not at a tag, try to go to a tag
597 code, stdout, _ = run_command(['git', 'rev-list', '--tags', '--max-count=1'])
598 if code:
599 info(TXT_MAGENTA('git failed'))
600 info(stderr, end='' if stderr[-1] == '\n' else '\n')
601 error('Can not determine the latest tag by git, to build from git, you need to pull the whole repo!')
602 code, stdout, _ = run_command(['git', 'describe', '--tags', stdout.strip()])
603 if code:
604 info(TXT_MAGENTA('git failed'))
605 info(stderr, end='' if stderr[-1] == '\n' else '\n')
606 error('Can not determine the latest tag by git')
607 tag = stdout.strip()
608 code, stdout, _ = run_command(['git', 'checkout', tag]) # checkout to that tag
609 if code:
610 info(TXT_MAGENTA('checkout failed'))
611 info(stderr, end='' if stderr[-1] == '\n' else '\n')
612 error('Could not checkout the latest tag. Do you need to `git stash` changes?')
613 info(TXT_CYAN(tag))
614 warn('Checked out to new tag, please rerun me to build stable version of ceccomp! '
615 '(or use --devmode to build on an arbitrary commit)')
616 sys.exit(0)
617
618 else: # devmode is True
619 code, stdout, stderr = run_command(['git', 'describe', '--long'])
620 if code < 0:
621 info(TXT_MAGENTA('git failed'))
622 info(f'Git not accessible? {stderr}')
623 error('Can not run git, you may install git package')
624
625 elif code == 0: # current commit get correctly resolved (tag-rev-gcommit or tag)
626 # --long mode display in TAG-COMMITS-gCOMMIT
627 tag, revision, commit = stdout.strip().split('-')
628 ver = tag if not tag.startswith('v') else tag[1:]
629 buildopts.version = f'{ver}.r{revision}_{commit[1:]}' # skip g
630 code, stdout, _ = run_command(['git', 'log', '-1', '--format=format:%as'])
631 if code:
632 info(TXT_MAGENTA('get tag time failed'))
633 info(stderr, end='' if stderr[-1] == '\n' else '\n')
634 error('Can not get tag-time for the latest tag')
635 buildopts.tag_time = stdout.strip()
636
637 else: # git failed to describe
638 info(TXT_MAGENTA('describe failed'))
639 info(stderr, end='' if stderr[-1] == '\n' else '\n')
640 error('Can not determine the latest tag by git, to build from git, you need to pull the whole repo!')
641
642 else: # tarball install
643 if not buildopts.version:
644 buildopts.version = VERSION
645 if not buildopts.tag_time:
646 buildopts.tag_time = TAG_TIME
647
648 makefile.inject('VERSION', buildopts.version)
649 makefile.inject('TAG_TIME', buildopts.tag_time)
650 if buildopts.git_install and not buildopts.devmode:
651 info(TXT_GREEN(buildopts.version))
652 elif buildopts.git_install and buildopts.devmode:
653 info(TXT_BLUE(buildopts.version))
654 else:
655 info(TXT_CYAN(buildopts.version))
656
657 @new_task
658 def check_builder_name(makefile: Makefile):
659 pcheck('builder name')
660 if '^' in buildopts.builder:
661 info(TXT_MAGENTA(buildopts.builder))
662 error(f"Found '^' in builder name {buildopts.builder}, which is not allowed.")
663 if not buildopts.builder.strip():
664 info(TXT_MAGENTA('(empty)'))
665 error(f'Empty builder name is not accepted.')
666 makefile.inject('BUILDER', buildopts.builder)
667 if buildopts.has_set_packager:
668 info(TXT_CYAN(buildopts.builder))
669 elif buildopts.is_official_package and buildopts.builder != 'manual':
670 info(TXT_GREEN(buildopts.builder))
671 else:
672 info(TXT_BLUE(buildopts.builder))
673
674 @new_task
675 def check_omit_leaf_frame_pointer_flag(makefile: Makefile):
676 pcheck('if compiler support -mno-omit-leaf-frame-pointer')
677 code, _, _ = run_command([*buildopts.cc, '-x', 'c', '-Werror', '-',
678 '-mno-omit-leaf-frame-pointer', '-o', '/dev/null'],
679 standard_c, push_sys_dir=True)
680 if code:
681 info(TXT_CYAN('no'))
682 makefile.inject('ARCH_PRESERVE_FP', '')
683 else:
684 info(TXT_GREEN('yes'))
685 makefile.inject('ARCH_PRESERVE_FP', '-mno-omit-leaf-frame-pointer')
686
687 taskmgr.run_tasks()
688 # vars not injected: EXTRA_CFLAGS EXTRA_LDFLAGS DEBUG_LEVEL PREFIX BINDIR ZSH_FPATH MANDIR DOCDIR DESTDIR SYS_INC_DIR SYS_LIB_DIR IS_STATIC
689 taskmgr.makefile.inject('EXTRA_CFLAGS', buildopts.cflags)
690 taskmgr.makefile.inject('EXTRA_LDFLAGS', buildopts.ldflags)
691 taskmgr.makefile.inject('DEBUG_LEVEL', str(buildopts.debug_level))
692 taskmgr.makefile.inject('PREFIX', buildopts.prefix)
693 taskmgr.makefile.inject('BINDIR', buildopts.bindir)
694 taskmgr.makefile.inject('ZSH_FPATH', buildopts.zshfpath)
695 taskmgr.makefile.inject('MANDIR', buildopts.mandir)
696 taskmgr.makefile.inject('DOCDIR', buildopts.docdir)
697 taskmgr.makefile.inject('DESTDIR', buildopts.destdir)
698 taskmgr.makefile.inject('IS_STATIC', '1' if buildopts.is_static else '0')
699
700 taskmgr.makefile.inject('SYS_INC_DIR', f'-I{buildopts.sys_includedir}' if buildopts.sys_includedir else '')
701 taskmgr.makefile.inject('SYS_LIB_DIR', f'-L{buildopts.sys_libdir}' if buildopts.sys_libdir else '')
702
703 assert taskmgr.makefile.s.find('{{') == -1
704
705 info('Writting back to Makefile... ', end='')
706 try:
707 with open('Makefile', 'w') as f:
708 f.write(taskmgr.makefile.s)
709 except Exception as e:
710 info(TXT_RED('failed'))
711 error(f'Unexpected error when write back: {e}')
712 else:
713 info(TXT_GREEN('ok'))