Skip to content

Instantly share code, notes, and snippets.

@gtramontina
Created December 15, 2020 02:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gtramontina/a5af995ece8cb203de7a321e6b459a01 to your computer and use it in GitHub Desktop.
Save gtramontina/a5af995ece8cb203de7a321e6b459a01 to your computer and use it in GitHub Desktop.
Makefile-like Python script
#!/usr/bin/env python3
import sys
from inspect import getmembers, isfunction
from os.path import getmtime, exists
from pathlib import Path
from shutil import which
from subprocess import call
def pre_requisites():
"""Place all pre-requisite checks here"""
assert which("poetry") is not None, (
"This project requires `poetry`. Couldn't find it.\n"
"Please refer to https://python-poetry.org/ to install it."
)
if not exists("poetry.lock") or getmtime("pyproject.toml") > getmtime("poetry.lock"):
sh("poetry update")
Path("poetry.lock").touch()
def task_exec():
"""Executes the application"""
sh("poetry run python life.py")
def task_test():
"""Runs unit tests"""
sh("poetry run py.test")
def task_build():
"""Packages the build into an executable"""
sh("poetry run pyinstaller life.py")
def task_test_all():
"""Runs all tests (requires Docker)"""
sh("poetry run py.test -m ''")
def task_test_watch():
"""Runs unit tests in watch mode"""
sh("poetry run pytest-watch --clear --quiet -- --no-header --no-summary")
def task_lint():
"""Checks against configured lint rules"""
sh("poetry run pylint $(find . -name '*.py')")
def task_lint_fix():
"""Fixes lint issues (rewrites files)"""
sh("poetry run black $(find . -name '*.py')")
def task_help():
"""Prints this message"""
print("\nUsage: {} <task1>...\n".format(sys.argv[0]))
for name, func in tasks.items():
print("\033[1m{:15}\033[0m\t{}".format(name, func.__doc__))
# --------------------------------------------------------------------------------------------------
tasks = dict(
map(
lambda entry: (entry[0][len("task_") :].replace("_", "."), entry[1]),
getmembers(
sys.modules[__name__],
lambda m: isfunction(m)
and m.__module__ == __name__
and m.__name__.startswith("task_"),
),
)
)
def sh(command):
"""Runs a subprocess and fails if it is not successful"""
exit_code = call(command, shell=True)
assert exit_code == 0, "*** Command `{}` exited with {}.".format(command, exit_code)
# --------------------------------------------------------------------------------------------------
try:
pre_requisites()
task_names = sys.argv[1:]
if len(task_names) == 0:
task_names = ["help"]
for task_name in task_names:
task = tasks.get(task_name)
assert task is not None, "Task not found!"
task()
except AssertionError as error:
raise SystemExit(error)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment