import pathlib import subprocess class compiler: """ This class is responsible for building and bundling source code into result file. This could return to command line after error, or raise exception to handle it in build script. """ def __init__(self, source: pathlib.Path, throw: bool = False) -> None: """ This function create new compiler instance. Parameters: source (pathlib.Path) - Source file to build throw (bool) - When True failed compilation raise Exception """ self.__source = source self.__throw = throw @property def throw(self) -> bool: """ When throw is True, failed command would raise Exception. """ return self.__throw @property def source(self) -> pathlib.Path: """ This return source file to build. """ return self.__source def build(self, result: pathlib.Path) -> None: """ This function is responsible for building process. Parameters: result (pathlib.Path): Result file to store compiled code """ if result.is_dir(): self._error("Build file \"" + str(result) + "\" is directory.") if result.exists(): result.unlink() command = self._command(self.source, result) returned = subprocess.run(command, capture_output = True) if returned.returncode == 0: return failed = result.stdout.decode("UTF-8") failed = failed + returned.stderr.decode("UTF-8") self._error(failed) def _error(self, content: str) -> None: """ This function raise Exception if throw flag is set, or print error to command line, and return there. Parameters: content (str): Content of the error """ if self.throw: raise Exception(content) print("Error while compilation: ") print("\"" + content + "\"") exit(-1) def _command(self, source: pathlib.Path, result: pathlib.Path) -> list: """ This function is responsible for creating command for compilation process. Parameters: source (pathlib.Path) - Source file to compile result (pathlib.Path) - Result compiled file Returns: (list) - List of strings, for subprocess creation """ raise TypeError("This is abstract class. Overwrite this function.") class sass_compiler(compiler): def _command(self, source: pathlib.Path, result: pathlib.Path) -> list: """ This function is responsible for creating command for compilation process. Parameters: source (pathlib.Path) - Source file to compile result (pathlib.Path) - Result compiled file Returns: (list) - List of strings, for subprocess creation """ return [ "sass", "--sourcemap=none", "-t compressed", str(source), str(result) ] class esbuild_compiler(compiler): def _command(self, source: pathlib.Path, result: pathlib.Path) -> list: """ This function is responsible for creating command for compilation process. Parameters: source (pathlib.Path) - Source file to compile result (pathlib.Path) - Result compiled file Returns: (list) - List of strings, for subprocess creation """ return [ "esbuild", str(source), "--bundle", "--outfile=" + str(result) ]