diff --git a/tools/py/build_spark.py b/tools/py/build_spark.py index 7d79976aa..a2889cf1d 100644 --- a/tools/py/build_spark.py +++ b/tools/py/build_spark.py @@ -1,245 +1,9 @@ -from abc import ABC, abstractmethod import argparse -from pathlib import Path +import os import subprocess -from core.argparse_utils import add_toggle_opt, get_arg -from core.file_utils import SparkPaths, copy, create_dir -from core.table_formatter import fmt_table -from core.logging import exit_msg -from core.iter_utils import at_bounded, join_t -from typing import Optional - - -class VisualStudioContext: - def __init__( - self, - version, - year, - prompt_path: Path, - msbuild_path: Path, - msbuild_arg_prefix, - ): - self.version = version - self.year = year - self.prompt_path = prompt_path - self.msbuild_path = msbuild_path - self._msbuild_arg_prefix = msbuild_arg_prefix - - def prompt_cmd(self): - return f'{self.prompt_path} -arch=x64 -host_arch=x64' - - def msbuild_flag(self, flag): - return f'{self._msbuild_arg_prefix}{flag}' - - def msbuild_clp(self, key, value=None): - rv = f'{self._msbuild_arg_prefix}clp:{key}' - if value is not None: - rv = f'{rv}={value}' - return rv - - def msbuild_target(self, target): - return f'{self._msbuild_arg_prefix}t:{target}' - - def msbuild_prop(self, key, value): - return f'{self._msbuild_arg_prefix}p:{key}={value}' - - -def _get_supported_vs_contexts(): - '''Gets a list of supported Visual Studio contexts (versions)''' - # vs 17 - vs17_path = Path('C:/Program Files/Microsoft Visual Studio/2022/Community') - vs17 = VisualStudioContext( - 17, - 2022, - vs17_path.joinpath('Common7/Tools/VsDevCmd.bat'), - vs17_path.joinpath('Msbuild/Current/Bin/amd64/MSBuild.exe'), - '-', - ) - - # vs 16 - vs16_path = Path( - 'C:/Program Files (x86)/Microsoft Visual Studio/2019/Community') - vs16 = VisualStudioContext( - 16, - 2019, - vs16_path.joinpath('Common7/Tools/VsDevCmd.bat'), - vs16_path.joinpath('MSBuild/Current/Bin/MSBuild.exe'), - '/', - ) - return [vs17, vs16] - - -def _get_preferred_vs_context(): - '''Gets the most preferred Visual Studio context (version) on this computer''' - vs_ctxs = _get_supported_vs_contexts() - for vs_context in vs_ctxs: - if vs_context.prompt_path.exists(): - return vs_context - supported_versions = ', '.join([str(v.version) for v in vs_ctxs]) - raise ValueError( - f'Failed to find supported Visual Studio version (works with {supported_versions})' - ) - - -class BuildTarget(ABC): - def __init__( - self, - name, - source_path: Optional[Path], - out_path: Optional[Path], - aliases=[]): - self.name = name - self.source_path = source_path - self.out_path = out_path - self.aliases = aliases - - @abstractmethod - def configure(self): - pass - - @abstractmethod - def build(self): - pass - - def is_match(self, targets): - return any( - t.lower() == self.name.lower() or t in self.aliases - for t in targets) - - -class CMakeTarget(BuildTarget): - def __init__( - self, - name, - preset='spark', - build_preset='spark-debug', - source_path=SparkPaths.root(), - out_path=SparkPaths.default_build(), - aliases=[], - verbosity: Optional[str] = None, - ): - if out_path is None: - raise ValueError('out_path is None') - if source_path is None: - raise ValueError('source_path is None') - BuildTarget.__init__(self, name, source_path, out_path, aliases) - self.preset = preset - self.build_preset = build_preset - self.verbosity = verbosity - - def _get_configure_cmd(self): - cmd_parts = ['cmake'] - if self.preset is not None: - cmd_parts.append(f'--preset {self.preset}') - if self.verbosity is not None: - cmd_parts.append(f'-DCMAKE_MESSAGE_LOG_LEVEL={self.verbosity}') - if self.source_path is not None: - cmd_parts.append(f'-S {self.source_path}') - if self.out_path is not None: - cmd_parts.append(f'-B {self.out_path}') - return ' '.join(cmd_parts) - - def _get_build_cmd(self): - cmd_parts = ['cmake --build'] - # In CMake, the build dir arg (-B) can't be combined w/ --preset - if self.build_preset is not None: - cmd_parts.append(f'--preset {self.build_preset}') - elif self.out_path is not None: - cmd_parts.append(f'{self.out_path}') - return ' '.join(cmd_parts) - - def configure(self): - cmd = self._get_configure_cmd() - print(f'configure_cmd: {cmd}') - subprocess.run(cmd).check_returncode() - if self.out_path is not None: - copy( - SparkPaths.tools().joinpath('cpp.build.props'), - self.out_path.joinpath('Directory.Build.Props')) - - def build(self): - cmd = self._get_build_cmd() - print(f'build_cmd: {cmd}') - subprocess.run(cmd).check_returncode() - - def __str__(self): - return fmt_table( - { - 'name': self.name, - 'configure_cmd': self._get_configure_cmd(), - 'build_cmd': self._get_build_cmd(), - }) - - -class CsprojTarget(BuildTarget): - def __init__( - self, - name: str, - source_path: Path, - out_path: Path, - aliases=[], - configuration: str = 'debug', - verbosity: str = 'minimal', - vs_context: Optional[VisualStudioContext] = None, - restore=True, - ): - BuildTarget.__init__(self, name, source_path, out_path, aliases) - self.configuration = configuration - self.verbosity = verbosity - self.restore = restore - self.vs_context = vs_context or _get_preferred_vs_context() - - def _get_build_cmd(self): - cfg = self.configuration - build_cmd_steps = [self.vs_context.prompt_cmd()] - base_output_path_arg = self.vs_context.msbuild_prop( - 'BaseOutputPath', self.out_path.joinpath(cfg.title())) - if self.restore: - # Restore build (download nugets) - restore_cmd_args = [ - f'"{self.vs_context.msbuild_path}"', - f"{self.vs_context.msbuild_flag('m')}", - f"{self.vs_context.msbuild_prop('platform', 'x64')}", - f"{self.vs_context.msbuild_prop('configuration', cfg.title())}", - f"{self.vs_context.msbuild_target('restore')}", - f"{self.vs_context.msbuild_clp('verbosity', self.verbosity)}", - f"{self.vs_context.msbuild_clp('summary')}", - base_output_path_arg, - self.source_path, - ] - restore_cmd = join_t(' ', restore_cmd_args) - build_cmd_steps.append(restore_cmd) - - # Main build - dbg_type = 'portable' if cfg.lower() == 'debug' else 'none' - build_cmd_prefix = ' '.join( - [ - f'"{self.vs_context.msbuild_path}"', - f"{self.vs_context.msbuild_flag('m')}", - f"{self.vs_context.msbuild_prop('platform', 'x64')}", - f"{self.vs_context.msbuild_prop('GenerateFullPaths', 'true')}", - f"{self.vs_context.msbuild_prop('configuration', cfg.title())}", - f"{self.vs_context.msbuild_prop('debugtype', dbg_type)}", - f"{self.vs_context.msbuild_clp('verbosity', self.verbosity)}", - f"{self.vs_context.msbuild_clp('summary')}" - ]) - build_cmd_steps.append( - f'{build_cmd_prefix} {base_output_path_arg} {self.source_path}') - return ' && '.join(build_cmd_steps) - - def configure(self): - pass - - def build(self): - subprocess.run(self._get_build_cmd()).check_returncode() - - def __str__(self): - return fmt_table( - { - 'name': self.name, - 'build_cmd': self._get_build_cmd() - }) +from core.file_utils import SparkPaths +from core.iter_utils import at_bounded def _get_arg_parser(): @@ -247,47 +11,34 @@ def _get_arg_parser(): parser.add_argument( '--configuration', metavar='debug|release', - type=str, - nargs='?', help='The build configuration', - default='Debug') + ) parser.add_argument( - '-o', - '--output-dir', - metavar='path', - type=str, - nargs='?', - help='The directory in which to build') - parser.add_argument( - '-t', - '--target', - metavar='targets', - type=str, - action='append', - nargs='+', - help='The target(s) to build') - add_toggle_opt( - parser, 'restore', help='Whether or not to run msbuild /t:restore') - add_toggle_opt( - parser, - 'clean', - help= - 'Whether or not to delete and overwrite an existing build directory') + '--clean', + action='store_true', + help='Perform a clean build (remove artifacts from previous build)', + ) parser.add_argument( '--verbosity', metavar='{0-5}', choices=range(0, 6), type=int, - help='The output verbosity level') + help='The output verbosity level', + ) + parser.add_argument( + '--dry-run', + action='store_true', + help='Preview the build commands without running them', + ) parser.set_defaults( - restore=True, + configuration='debug', clean=False, verbosity=1, ) return parser -def _msbuild_verbosity(level): +def _dotnet_verbosity(level): names = ['quiet', 'minimal', 'normal', 'detailed', 'diagnostic'] return at_bounded(names, level) @@ -295,7 +46,7 @@ def _msbuild_verbosity(level): def _cmake_verbosity(level): # Skip 'WARNING' and 'NOTICE' levels, since the default CMake verbosity, # 'STATUS', doesn't produce that much output. This also better normalizes - # numeric representation of verbosity w/ msbuild, which only has 5 levels. + # numeric representation of verbosity w/ dotnet, which only has 5 levels. names = [ 'ERROR', # 'WARNING', @@ -308,105 +59,44 @@ def _cmake_verbosity(level): return at_bounded(names, level) -def _get_targets( - build_type, - build_dir=SparkPaths.default_build(), - vs_context: Optional[VisualStudioContext] = None, - verbosity=1, - restore=True, - names=Optional[list[str]], -) -> list[BuildTarget]: - def mk_csproj(name): - return CsprojTarget( - name=name, - source_path=SparkPaths.root().joinpath('src', 'client', name), - out_path=build_dir, - aliases=['all'], - configuration=build_type, - verbosity=_msbuild_verbosity(verbosity), - vs_context=vs_context, - restore=restore, - ) - - def mk_cmake(name): - return CMakeTarget( - name, - preset='spark', - build_preset='spark-' + build_type.lower(), - source_path=SparkPaths.root(), - out_path=build_dir, - aliases=['all'], - verbosity=_cmake_verbosity(verbosity), - ) - - tgts = [ - mk_cmake('libspark'), - mk_csproj('spark'), - mk_csproj('spark_api'), - mk_csproj('spark_core'), - mk_csproj('spark_sdk'), - mk_csproj('spark_test'), - mk_csproj('Spark.Console') - ] - if names is not None: - include_tgt = lambda t: any( - n.lower() == t.name.lower() or n in t.aliases for n in names) - tgts = list(filter(include_tgt, tgts)) - return tgts - - -def build( - targets: list[BuildTarget] | None = None, - build_dir: Path | None = None, - clean: bool = False, -) -> list[subprocess.CompletedProcess]: - '''Builds the spark client''' - - # check if explicit no-op - if targets is not None and len(targets) == 0: - return [] - - # init unspecified args w/ defaults - if targets is None: - targets = _get_targets() - if build_dir is None: - build_dir = SparkPaths.default_build() - - try: - build_dir = build_dir.absolute() - create_dir(build_dir, clean) - for t in targets: - t.configure() - t.build() - except Exception as e: - exit_msg(1, e) - - def _main(): parser = _get_arg_parser() args = parser.parse_args() - def flatten_arglist(arglist): - return None if arglist is None else [a for grp in arglist for a in grp] + def run(cmd): + print(cmd) + if args.dry_run: + return + subprocess.run(cmd).check_returncode() - args_dict = vars(args) - build_dir = SparkPaths.default_build() - if args.output_dir is not None: - build_dir = Path(args.output_dir).absolute() - tgt_names = flatten_arglist(get_arg(args_dict, 'target')) - if tgt_names is None or len(tgt_names) == 0: - tgt_names = ['libspark', 'spark'] + def dotnet_cmd(action='build'): + return ' '.join([ + f'dotnet {action} spark_client.sln', + f'--configuration {args.configuration.title()}', + f'--verbosity {_dotnet_verbosity(args.verbosity)}', + ]) - vs_context = _get_preferred_vs_context() - tgts = _get_targets( - build_type=args.configuration, - build_dir=build_dir, - vs_context=vs_context, - verbosity=int(args.verbosity), - restore=args.restore, - names=tgt_names) - build(tgts, build_dir, args.clean) + os.chdir(SparkPaths.root()) + cmake_configure_cmd = ' '.join([ + f'cmake', + f'--preset spark', + f'-DCMAKE_MESSAGE_LOG_LEVEL={_cmake_verbosity(args.verbosity)}', + ]) + cmake_build_cmd = ' '.join([ + f'cmake', + f'--build', + f'--preset spark-{args.configuration.lower()}', + ]) + if args.clean: + run(f'{cmake_build_cmd} --target clean') + run(dotnet_cmd('clean')) + run(cmake_configure_cmd) + run(cmake_build_cmd) + run(dotnet_cmd('build')) if __name__ == "__main__": - _main() + try: + _main() + except Exception as e: + print(f'build_spark.py failed: {e}')