dotfiles/install.py

74 lines
2 KiB
Python
Raw Normal View History

#!/usr/bin/env python3
import argparse
import os
2019-01-29 19:45:45 -06:00
import socket
import sys
from pathlib import Path
2019-01-29 19:45:45 -06:00
import mako.lookup
import mako.template
import toml
def main():
parser = argparse.ArgumentParser(
description='Generates and installs dotfiles for this host.',
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument(
'-d', '--dotfiles',
help='The base directory of the dotfiles repository.',
type=Path,
default=Path(sys.argv[0]).parent,
)
parser.add_argument(
'-n', '--hostname',
2019-01-29 19:45:45 -06:00
help='The hostname or other identifying name of this system that will'
' be used to retrieve the host-specific configuration.',
default=os.environ.get('HOSTNAME') or socket.gethostname(),
)
parser.add_argument(
'-o', '--home',
help='The home directory where generated dotfiles will be installed.',
2019-01-29 19:45:45 -06:00
type=Path,
default=os.environ.get('HOME') or Path.home(),
)
args = parser.parse_args()
2019-01-29 19:45:45 -06:00
templates_dir = args.dotfiles / 'templates'
include_dir = args.dotfiles / 'include'
host_filename = args.dotfiles / 'hosts' / '{}.toml'.format(args.hostname)
2019-01-29 19:45:45 -06:00
if host_filename.exists():
with open(host_filename) as host_file:
host_config = toml.load(host_file)
else:
host_config = {}
2019-01-29 19:45:45 -06:00
lookup = mako.lookup.TemplateLookup(
directories=[
str(templates_dir),
str(include_dir),
],
)
for template_path in templates_dir.glob('**/*'):
if not template_path.is_file():
continue
template = mako.template.Template(
filename=str(template_path),
strict_undefined=True,
lookup=lookup,
)
output = template.render(
host=host_config
2019-01-29 19:45:45 -06:00
)
output_path = args.home / template_path.relative_to(templates_dir)
2019-03-10 08:30:17 +00:00
output_path.parent.mkdir(parents=True, exist_ok=True)
2019-01-29 19:45:45 -06:00
with open(output_path, 'w+') as output_file:
output_file.write(output)
main()