fix build (linux): Port py3 build scripts over from spark_crypto.dev

This commit is contained in:
John Colvin committed 2022-09-29 17:47:23 -04:00
1 parent 45d6d0f673
commit 7c7aa727e2
11 files changed
+657

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
#!/usr/bin/env bash
tools_path=$(dirname $(readlink -f $0))
eval "$tools_path/venv_exec.sh python $tools_path/py/build_sparkd.py $@"
+271
View File
@@ -0,0 +1,271 @@
import argparse
from typing import cast
import subprocess
from core.argparse_utils import add_toggle_opt, get_arg
from core.file_utils import CWD, SparkPaths, as_path, create_dir, ensure_exists, link_dir, unlink
from core.iter_utils import flatten
from core.logging import exit_msg
class CMakeCompilerPair:
'''Represents a pair of c, cxx compilers'''
def __init__(self, name, c, cxx):
self.name = name
self.c = c
self.cxx = cxx
def to_opts(self):
opts = {}
if self.c:
opts['C_COMPILER'] = self.c
if self.cxx:
opts['CXX_COMPILER'] = self.cxx
return opts
def __str__(self):
return f'{self.name} ({self.c}, {self.cxx})'
class CMakeConfigureCommand:
def __init__(
self, src_dir, build_dir, generator, build_type, compiler: CMakeCompilerPair):
if src_dir is None:
raise ValueError('Source dir cannot be None')
self.cmd = 'cmake'
self.add_opt('-S', src_dir)
self.add_opt('-B', build_dir)
if generator is not None:
self.add_opt('-G', generator)
self.add_opt('BUILD_TYPE', build_type)
self.add_opt('C_COMPILER', compiler.c)
self.add_opt('CXX_COMPILER', compiler.cxx)
def add_opt(self, name: str, value):
if name is None:
raise ValueError('opt name cannot be None')
if value is None:
return self
if not name.startswith('-'):
name = f'-DCMAKE_{name}'
self.cmd = f'{self.cmd} {name}={value}'
else:
self.cmd = f'{self.cmd} {name} {value}'
return self
def __str__(self):
return self.cmd
def _parse_compiler(arg: str or None):
'''Parses compiler input (from cli) and returns a tuple of c, cxx compilers respectively'''
known_compilers = {
'gcc': CMakeCompilerPair('gcc', 'gcc', 'g++'),
'clang': CMakeCompilerPair('clang', 'clang', 'clang++')
}
if arg in known_compilers:
return known_compilers[arg]
raise ValueError(
f"Unexpected compiler '{arg}'. Please use one of [{' '.join(known_compilers)}]"
)
def _parse_target(t, targets, aliases) -> list:
if t in targets:
return [targets[t]]
elif aliases is not None and t in aliases:
alias_ts = aliases[t]
for a in alias_ts:
if a not in targets:
msg = f"Failed to find target for '{t}' (alias '{a}'). known targets: {targets}"
exit_msg(1, msg)
return [targets[alias_t] for alias_t in aliases[t]]
return []
def _parse_targets(targets, candidates, aliases=[]):
'''Parses target input (from cli)'''
if targets is None:
return None
# Always try to parse `t` as both cpp and csharp targets, since it
# could be an alias for a combination of csharp and cpp targets.
return flatten([_parse_target(t, candidates, aliases) for t in targets])
def _parse_build_dir(build_dir, build_type, compiler):
return build_dir or SparkPaths.root().joinpath('build', compiler.name, build_type.lower())
class BuildSparkdArgs:
def __init__(self, args):
args_dict = vars(args)
self.compiler = _parse_compiler(get_arg(args_dict, 'compiler', 'gcc'))
# Forcibly correct case (so user doesn't have to worry abt it)
self.build_type = str(args.build_type).lower()
if self.build_type not in ['debug', 'release']:
raise ValueError("Unexpected build_type '{args.build_type}'")
self.build_dir = _parse_build_dir(
args_dict.get('output_dir'), self.build_type, self.compiler)
self.clean = cast(bool, args.clean)
self.jobs=args.jobs
self.targets = _parse_targets(args_dict.get('targets'), ['all', 'install'])
def _get_arg_parser():
parser = argparse.ArgumentParser(description='Build spark_client.sln')
parser.add_argument(
'--build-type',
metavar='debug|release',
type=str,
nargs='?',
help='The build type')
parser.add_argument(
'--compiler',
metavar='gcc|clang',
type=str,
nargs='?',
help='The compiler')
parser.add_argument(
'-o',
'--output-dir',
metavar='path',
type=str,
nargs='?',
help=
'The directory in which to build (defaults to [repo_root]/build/<compiler>/<configuration>)'
)
parser.add_argument(
'-t',
'--target',
metavar='targets',
type=str,
action='append',
nargs='+',
help='The target(s) to build')
parser.add_argument(
'-j',
'--jobs',
type=int,
help='[CMake] The number of parallel jobs to run')
add_toggle_opt(
parser,
'clean',
help=
'Whether or not to delete and overwrite an existing build directory')
parser.set_defaults(build_type='Debug', compiler='gcc')
return parser
def _get_cmake_build_type(build_type: str):
'''
Converts a case-insensitive build-type str (from cli) to a case-sensitive CMAKE_BUILD_TYPE var
'''
# The 'build_type' arg is case-sensitive because 'CMAKE_BUILD_TYPE' is substitued for a folder
# in the externals-libs path. In order to match a real path, it must be 'Debug' or 'Release'.
# Keep the orig_build_type around for potential use in err msg.
orig_build_type = build_type
build_type = build_type or 'debug'
build_type = build_type.title()
if build_type not in ['Debug', 'Release']:
raise ValueError(f"Unexpected build_type '{orig_build_type}'")
return build_type
def _configure(
src_dir, build_dir, build_type, compiler: CMakeCompilerPair) -> subprocess.CompletedProcess:
'''Configures sparkd (server) build'''
cmake_build_type = _get_cmake_build_type(build_type)
cmd = CMakeConfigureCommand(
src_dir=src_dir,
build_dir=build_dir,
generator='Ninja',
build_type=cmake_build_type,
compiler=compiler)
if build_type.lower() == 'debug':
cmd.add_opt('EXPORT_COMPILE_COMMANDS', True)
print(f'configure_cmd: {cmd}')
with CWD(build_dir):
return subprocess.run(str(cmd), shell=True)
def _check_results(proc_results):
for res in proc_results:
if res.returncode != 0:
exit_msg(1, f'The following build subprocess failed: {res}')
def _build(
src_dir,
build_dir,
build_type=None,
compiler=None,
clean=False,
targets=None,
jobs=None) -> list:
'''Builds sparkd (server)'''
# check if explicit no-op
if targets is not None and len(targets) == 0:
return []
compiler = compiler or CMakeCompilerPair('gcc', 'gcc', 'g++')
build_type = build_type or 'release'
build_dir = as_path(build_dir).value().absolute()
proc_results = []
try:
print(f'creating build_dir (clean: {clean}): {build_dir}')
create_dir(build_dir, clean)
print(f'configuring build (clean: {clean}): {build_dir}')
cfg_res = _configure(
src_dir=src_dir,
build_dir=build_dir,
build_type=build_type,
compiler=compiler)
proc_results.append(cfg_res)
if cfg_res.returncode != 0:
# Don't bother executing build step since configure failed
return proc_results
except Exception as e:
exit_msg(1, e)
build_cmd_parts = [f'cmake --build {build_dir}']
if jobs is not None:
build_cmd_parts.append(f'-j {jobs}')
if targets is not None:
build_cmd_parts.append(' '.join([f"--target {t}" for t in targets]))
build_cmd = ' '.join(build_cmd_parts)
print(f'build_cmd: {build_cmd}')
build_res = subprocess.run(build_cmd, shell=True)
proc_results.append(build_res)
return proc_results
def _main():
parser = _get_arg_parser()
args = BuildSparkdArgs(parser.parse_args())
proc_results = _build(
src_dir=SparkPaths.root(),
build_dir=args.build_dir,
build_type=args.build_type,
compiler=args.compiler,
clean=args.clean,
targets=args.targets,
jobs=args.jobs)
_check_results(proc_results)
if __name__ == '__main__':
_main()
+13
View File
@@ -0,0 +1,13 @@
import argparse
def add_toggle_opt(parser: argparse.ArgumentParser, name, **kwargs):
parser.add_argument(f'--{name}', action=f'store_true', dest=name, **kwargs)
parser.add_argument(f'--no-{name}', action=f'store_false', dest=name)
return parser
def get_arg(args, name, value_or=None):
if name in args:
return args[name]
return value_or
+27
View File
@@ -0,0 +1,27 @@
import termcolor
class BuildStep:
def __init__(self, header, body=None, begin_color='green', end_color='cyan'):
self.header = header
self.body = body
self.begin_color = begin_color
self.end_color = end_color
def _desc_parts(self):
parts = [self.header]
if self.body is not None:
parts.append(self.body)
return parts
def __str__(self):
return ': '.join(self._desc_parts())
def __enter__(self):
termcolor.cprint(
f'\n* BEGIN {self.header}', color=self.begin_color, flush=True)
if self.body is not None:
print(f'{self.body}', flush=True)
def __exit__(self, exc_type, exc_val, exc_tb):
termcolor.cprint(
f'* END {self.header}', color=self.end_color, flush=True)
+14
View File
@@ -0,0 +1,14 @@
class Disposable:
def __init__(self, dispose):
self.dispose = dispose
def __enter__(self):
pass
def __exit__(self, exc_type, exc_val, exc_tb):
if self.dispose:
self.dispose()
self.dispose = None
+186
View File
@@ -0,0 +1,186 @@
import os
import datetime
from pathlib import Path
import shutil
import sys
class CWD:
def __init__(self, push_path, pop_path=os.getcwd()):
self.push_path = push_path
self.pop_path = pop_path
def __enter__(self):
if self.push_path is not None:
os.chdir(self.push_path)
def __exit__(self, exc_type, exc_val, exc_tb):
if self.pop_path is not None:
os.chdir(self.pop_path)
def _workspace_root():
return Path(os.path.realpath(__file__)).parent.parent.parent.parent.absolute()
def _default_build():
if sys.platform == 'win32':
return _workspace_root().joinpath('build')
elif sys.platform == 'linux':
return _workspace_root().joinpath('build', 'gcc', 'release')
raise ValueError(f"Unknown platform '{sys.platform}'")
class SparkPaths:
@staticmethod
def root():
return _workspace_root()
@staticmethod
def client_csproj(name):
return _workspace_root().joinpath('src', 'client', 'name', f'{name}.csproj')
@staticmethod
def client_bins(build_root=_default_build(), configuration='Release'):
return build_root.joinpath(configuration, 'bin', 'net6.0-windows', 'win-x64')
@staticmethod
def client_sln():
return _workspace_root().joinpath('spark_client.sln')
@staticmethod
def tools():
return _workspace_root().joinpath('tools')
@staticmethod
def default_build():
return _default_build()
@staticmethod
def externals():
return _workspace_root().joinpath('externals')
class PathOrNone:
def __init__(self, path):
self.path = path
def value(self):
if self.path is None:
raise ValueError('path is None')
return self.path
def __str__(self):
return '' if self.path is None else str(self.path)
def as_path(path):
return PathOrNone(
path if isinstance(path, Path) else
Path(str(path)) if isinstance(path, str) else
None)
def as_absolute_paths(relative_paths: list, with_respect_to = None):
if relative_paths is None:
raise ValueError('relative_path is None')
if len(relative_paths) == 0:
return []
def impl():
return [as_path(p).value().absolute() for p in relative_paths]
if with_respect_to is None:
return impl()
with CWD(with_respect_to):
return impl()
def ensure_exists(path):
if not os.path.exists(path):
raise ValueError(f"Path '{path}' does not exist")
def fmt_datetime_suffix(dt: datetime.datetime = None):
return (dt or datetime.datetime.now()).strftime("%Y-%m%d-%H%M")
def append_datetime_suffix(path, dt: datetime.datetime = None):
return f'{path}_{fmt_datetime_suffix(dt)}'
def get_unique_path(path: str, max_tries: int = 100):
if path is None or len(path) == 0:
raise ValueError("'path' is none or empty")
if not os.path.exists(path):
return path
max_tries = 100
i = 1
orig_path = path
while i < max_tries:
path = f'{orig_path}({i})'
if not os.path.exists(path):
break
i += 1
if i == max_tries:
raise ValueError(
f"Unable to make path unique by appending appending an incrementing integer. "
f"Maximum attempts exceeded ({max_tries})")
return path
def unlink(path):
if not os.path.exists(path):
return
if not os.path.islink(path):
raise ValueError(
'The specified path already exists and is not a symbolic link')
os.unlink(path)
def rmdir_or_unlink(dir):
if not os.path.exists(dir):
return
if os.path.islink(dir):
os.unlink(dir)
else:
shutil.rmtree(dir)
def link_dir(source_path, link_path):
if source_path is None:
raise TypeError('source_path is None')
if not os.path.isdir(source_path):
raise ValueError('source_path is not a directory')
if link_path is None:
raise TypeError('link_path is None')
if source_path == link_path:
return
if not os.path.exists(source_path):
os.makedirs(source_path)
if os.path.exists(link_path):
if os.path.islink(link_path):
if os.readlink(link_path) == source_path:
return
os.unlink(link_path)
elif os.path.isdir(link_path):
shutil.rmtree(link_path)
elif os.path.isfile(link_path):
os.remove(link_path)
else:
raise ValueError('link_path is an unexpected filetype')
os.symlink(source_path, link_path)
def create_dir(path, overwrite_if_exists=False):
if path is None:
raise TypeError('path is None')
if not os.path.exists(path):
os.makedirs(path)
elif overwrite_if_exists:
rmdir_or_unlink(path)
os.makedirs(path)
+86
View File
@@ -0,0 +1,86 @@
class HasNextIter(object):
"""An iterator wrapper that provides a 'has_next' fn"""
def __init__(self, it):
self.__it = iter(it)
self.__has_next = None
def __iter__(self):
return self
def next(self):
if self.__has_next:
result = self.__next
else:
result = next(self.__it)
self.__has_next = None
return result
def has_next(self):
if self.__has_next is None:
try:
self.__next = next(self.__it)
except StopIteration:
self.__has_next = False
else:
self.__has_next = True
return self.__has_next
def is_iterable(val, except_types=[str]):
t = type(val)
if except_types is not None and t in except_types:
return False
try:
iter(val)
return True
except TypeError:
return False
def is_none_or_empty(val):
return val is None or (is_iterable(val) and len(val) == 0)
def flatten(groups):
flatlist = []
for g in groups:
flatlist.extend(g)
return flatlist
def ensure_iterable(val, if_none=[]):
if is_iterable(val):
return val
return if_none if val is None else [val]
def ensure_len(val):
if val is None:
return 0
try:
return len(val)
except:
return 1
def fmt_iterable(
iterable, separator=', ', max_explicit_items=4, if_none='None'):
if iterable is None:
return if_none
if hasattr(iterable, '__len__'):
sz = len(iterable)
if sz <= max_explicit_items:
return separator.join(iterable)
rv = separator.join(
map(lambda x: str(x), iterable[0:max_explicit_items]))
rv += f'{separator}and {sz - max_explicit_items} others'
return rv
expl = []
it = HasNextIter(iter(iterable))
while len(expl) < max_explicit_items and it.has_next():
expl.append(it.next())
if it.has_next():
expl.append('...')
return separator.join(expl)
+33
View File
@@ -0,0 +1,33 @@
from typing import Callable
def exit_msg(code=0, msg=None):
if msg is not None:
print(msg)
exit(code)
def exec_and_log_error(exec: Callable, name=None, exit_on_err = True, reraise=False):
'''
Executes a callable within a 'try/except' block; if an exception occurs, logs it and optionally
exits the program, and/or re-raises the exception
'''
def fmt_name(name):
if name is None:
return 'anonymous fn'
try:
return str(name)
except:
return 'fn-name-caused-error'
try:
exec()
except Exception as e:
msg = f"Error executing '{fmt_name(name)}': {e}"
if exit_on_err:
exit_msg(1, msg=msg)
else:
print(msg)
if reraise:
raise e
+5
View File
@@ -0,0 +1,5 @@
def fmt_table(name_values):
if name_values is None or len(name_values) == 0:
raise ValueError("Invalid 'name_values'")
name_width = max(map(lambda name: len(name), name_values))
return '\n'.join(map(lambda nv: f'{nv[0]:<{name_width}} : {nv[1]}', name_values.items()))
+11
View File
@@ -0,0 +1,11 @@
from typing import Type
def _get_var_name(name=None):
return 'Variable' if name is None else f"'{name}'"
def notnone(x, name=None):
if x is None:
raise ValueError(f'{_get_var_name(name)} is None')
return x
+6
View File
@@ -0,0 +1,6 @@
#!/usr/bin/env bash
tools_dir=$(dirname $(readlink -f "${BASH_SOURCE[0]:-$0}"));
source "${tools_dir}/../.venv/bin/activate"
$@