Skip to content
Snippets Groups Projects
create_mounts.py 2.38 KiB
#!/usr/bin/env python3

import argparse
import logging as log
import os
import re
import yaml

from pathlib import Path


def main(args):

    compose_yml = os.path.abspath('./docker-compose.yml')
    if not os.path.isfile(compose_yml):
        raise Exception("Could not find docker-compose.yml at %s" % compose_yml)

    with open(compose_yml) as f:
        compose = yaml.safe_load(f)

    if 'services' not in compose:
        raise Exception("Could not find services tag in docker-compose.yml")

    for service in compose['services']:
        log.info("Service '%s'" % service)
        if 'volumes' in compose['services'][service]:
            for volume in compose['services'][service]['volumes']:
                log.info("  Volume '%s'" % (volume))
                reg = re.match(r"^(\./[^:]+/):[^:]+(:\w+)?$", volume)
                if reg:
                    vol_dir = os.path.abspath('./' + reg.group(1))
                    log.info("    mkdir '%s' (from %s)" % (vol_dir, volume))
                    if not args.dry_run and not os.path.exists(vol_dir):
                        os.makedirs(vol_dir, exist_ok=True)
                else:
                    reg = re.match(r"^(\./[^:]+):[^:]+(:\w+)?$", volume)
                    if reg:
                        vol_file = os.path.abspath('./' + reg.group(1))
                        vol_dir = os.path.dirname(vol_file)
                        log.info("    mkdir '%s' (from %s)" % (vol_dir, volume))
                        if not args.dry_run and not os.path.exists(vol_dir):
                            os.makedirs(vol_dir, exist_ok=True)
                        log.info("    touch '%s' (from %s)" % (vol_file, volume))
                        if not args.dry_run and not os.path.exists(vol_file):
                            Path(vol_file).touch()
                    else:
                        log.info("    skip")


if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description='Create local volume directories.'
    )
    parser.add_argument("-v", "--verbose", help="Increase output verbosity.",
                        action="store_true")
    parser.add_argument("-d", "--dry-run", help="Dry run: no modification will be done, for testing purpose.",
                        action="store_true")

    args = parser.parse_args()
    log.basicConfig(level=log.INFO)
    if args.verbose:
        log.basicConfig(level=log.DEBUG)

    main(args)