dc-ops/dc-ops

72 lines
1.9 KiB
Python
Executable file

#!/usr/bin/env python3
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# Author: Sebastian Mark
# CC-BY-SA (https://creativecommons.org/licenses/by-sa/4.0/deed.de)
# for civil use only
import logging as log
import subprocess
from pathlib import Path
import yaml
from git import GitCommandError, NoSuchPathError, Repo
# read config file
configfile = Path(__file__).with_name("config.yml")
with configfile.open("r") as f:
cfg = yaml.safe_load(f.read())
# init logging
loglevel = cfg.get("loglevel", "INFO").upper()
log.basicConfig(format="%(message)s", level=loglevel)
# iterate all stacks
for stack in cfg["stacks"]:
# skip disabled stacks
if "enabled" in stack and not stack["enabled"]:
continue
# header
stackdir = stack["dir"]
log.info(f"* processing {stackdir}")
# create repo instance if it exists
try:
repo = Repo(stackdir)
except NoSuchPathError:
log.error("directory not found")
continue
# try to fetch latest changes
try:
repo.git.fetch()
except GitCommandError as e:
log.error(str(e))
continue
# check for new commits
if repo.rev_parse("HEAD") == repo.rev_parse(f"origin/{repo.active_branch}"):
log.info("no changes - skipping")
continue
# pull remote changes to local branch
try:
log.info(repo.git.pull())
except GitCommandError as e:
log.error(str(e))
continue
# run `docker compose` for all compose-files
# (or just for the directory if no compose-file defined)
composefiles = stack.get("compose-files", ["docker-compose.yml"])
for composefile in composefiles:
try:
subprocess.run(
f"docker compose --file {composefile} up --build --detach --remove-orphans", # noqa
cwd=stackdir,
shell=True,
text=True,
)
except subprocess.CalledProcessError:
pass