1
0
mirror of https://github.com/deadc0de6/dotdrop.git synced 2026-02-12 16:25:13 +00:00

better provide template variables as global in templategen

This commit is contained in:
deadc0de6
2018-09-01 18:48:59 +02:00
parent 7c4ef310b1
commit 89198eddb6
4 changed files with 33 additions and 35 deletions

View File

@@ -81,8 +81,8 @@ def install(opts, conf):
msg = 'no dotfiles defined for this profile (\"{}\")' msg = 'no dotfiles defined for this profile (\"{}\")'
LOG.err(msg.format(opts['profile'])) LOG.err(msg.format(opts['profile']))
return False return False
t = Templategen(base=opts['dotpath'], variables=opts['variables'], t = Templategen(opts['profile'], base=opts['dotpath'],
debug=opts['debug']) variables=opts['variables'], debug=opts['debug'])
inst = Installer(create=opts['create'], backup=opts['backup'], inst = Installer(create=opts['create'], backup=opts['backup'],
dry=opts['dry'], safe=opts['safe'], base=opts['dotpath'], dry=opts['dry'], safe=opts['safe'], base=opts['dotpath'],
diff=opts['installdiff'], debug=opts['debug']) diff=opts['installdiff'], debug=opts['debug'])
@@ -108,7 +108,7 @@ def install(opts, conf):
if not tmp: if not tmp:
continue continue
src = tmp src = tmp
r = inst.install(t, opts['profile'], src, dotfile.dst) r = inst.install(t, src, dotfile.dst)
if tmp: if tmp:
tmp = os.path.join(opts['dotpath'], tmp) tmp = os.path.join(opts['dotpath'], tmp)
if os.path.exists(tmp): if os.path.exists(tmp):
@@ -185,8 +185,8 @@ def compare(opts, conf, tmp, focus=None, ignore=[]):
if len(selected) < 1: if len(selected) < 1:
return False return False
t = Templategen(base=opts['dotpath'], variables=opts['variables'], t = Templategen(opts['profile'], base=opts['dotpath'],
debug=opts['debug']) variables=opts['variables'], debug=opts['debug'])
inst = Installer(create=opts['create'], backup=opts['backup'], inst = Installer(create=opts['create'], backup=opts['backup'],
dry=opts['dry'], base=opts['dotpath'], dry=opts['dry'], base=opts['dotpath'],
debug=opts['debug']) debug=opts['debug'])
@@ -209,8 +209,7 @@ def compare(opts, conf, tmp, focus=None, ignore=[]):
continue continue
src = tmpsrc src = tmpsrc
# install dotfile to temporary dir # install dotfile to temporary dir
ret, insttmp = inst.install_to_temp(t, tmp, opts['profile'], ret, insttmp = inst.install_to_temp(t, tmp, src, dotfile.dst)
src, dotfile.dst)
if not ret: if not ret:
# failed to install to tmp # failed to install to tmp
continue continue

View File

@@ -29,7 +29,7 @@ class Installer:
self.comparing = False self.comparing = False
self.log = Logger() self.log = Logger()
def install(self, templater, profile, src, dst): def install(self, templater, src, dst):
"""install the src to dst using a template""" """install the src to dst using a template"""
src = os.path.join(self.base, os.path.expanduser(src)) src = os.path.join(self.base, os.path.expanduser(src))
dst = os.path.join(self.base, os.path.expanduser(dst)) dst = os.path.join(self.base, os.path.expanduser(dst))
@@ -40,8 +40,8 @@ class Installer:
if self.debug: if self.debug:
self.log.dbg('install {} to {}'.format(src, dst)) self.log.dbg('install {} to {}'.format(src, dst))
if os.path.isdir(src): if os.path.isdir(src):
return self._handle_dir(templater, profile, src, dst) return self._handle_dir(templater, src, dst)
return self._handle_file(templater, profile, src, dst) return self._handle_file(templater, src, dst)
def link(self, src, dst): def link(self, src, dst):
"""set src as the link target of dst""" """set src as the link target of dst"""
@@ -76,7 +76,7 @@ class Installer:
self.log.sub('linked {} to {}'.format(dst, src)) self.log.sub('linked {} to {}'.format(dst, src))
return [(src, dst)] return [(src, dst)]
def _handle_file(self, templater, profile, src, dst): def _handle_file(self, templater, src, dst):
"""install src to dst when is a file""" """install src to dst when is a file"""
if self.debug: if self.debug:
self.log.dbg('generate template for {}'.format(src)) self.log.dbg('generate template for {}'.format(src))
@@ -84,7 +84,7 @@ class Installer:
# symlink loop # symlink loop
self.log.err('dotfile points to itself: {}'.format(dst)) self.log.err('dotfile points to itself: {}'.format(dst))
return [] return []
content = templater.generate(src, profile) content = templater.generate(src)
if content is None: if content is None:
self.log.err('generate from template \"{}\"'.format(src)) self.log.err('generate from template \"{}\"'.format(src))
return [] return []
@@ -106,7 +106,7 @@ class Installer:
return [(src, dst)] return [(src, dst)]
return [] return []
def _handle_dir(self, templater, profile, src, dst): def _handle_dir(self, templater, src, dst):
"""install src to dst when is a directory""" """install src to dst when is a directory"""
ret = [] ret = []
self._create_dirs(dst) self._create_dirs(dst)
@@ -114,12 +114,10 @@ class Installer:
for entry in os.listdir(src): for entry in os.listdir(src):
f = os.path.join(src, entry) f = os.path.join(src, entry)
if not os.path.isdir(f): if not os.path.isdir(f):
res = self._handle_file( res = self._handle_file(templater, f, os.path.join(dst, entry))
templater, profile, f, os.path.join(dst, entry))
ret.extend(res) ret.extend(res)
else: else:
res = self._handle_dir( res = self._handle_dir(templater, f, os.path.join(dst, entry))
templater, profile, f, os.path.join(dst, entry))
ret.extend(res) ret.extend(res)
return ret return ret
@@ -186,15 +184,15 @@ class Installer:
self.log.log('backup {} to {}'.format(path, dst)) self.log.log('backup {} to {}'.format(path, dst))
os.rename(path, dst) os.rename(path, dst)
def _install_to_temp(self, templater, profile, src, dst, tmpdir): def _install_to_temp(self, templater, src, dst, tmpdir):
"""install a dotfile to a tempdir for comparing""" """install a dotfile to a tempdir for comparing"""
sub = dst sub = dst
if dst[0] == os.sep: if dst[0] == os.sep:
sub = dst[1:] sub = dst[1:]
tmpdst = os.path.join(tmpdir, sub) tmpdst = os.path.join(tmpdir, sub)
return self.install(templater, profile, src, tmpdst), tmpdst return self.install(templater, src, tmpdst), tmpdst
def install_to_temp(self, templater, tmpdir, profile, src, dst): def install_to_temp(self, templater, tmpdir, src, dst):
"""compare a temporary generated dotfile with the local one""" """compare a temporary generated dotfile with the local one"""
ret = False ret = False
tmpdst = '' tmpdst = ''
@@ -212,8 +210,7 @@ class Installer:
if self.debug: if self.debug:
self.log.dbg('tmp install {} to {}'.format(src, dst)) self.log.dbg('tmp install {} to {}'.format(src, dst))
# install the dotfile to a temp directory for comparing # install the dotfile to a temp directory for comparing
ret, tmpdst = self._install_to_temp(templater, profile, ret, tmpdst = self._install_to_temp(templater, src, dst, tmpdir)
src, dst, tmpdir)
if self.debug: if self.debug:
self.log.dbg('tmp installed in {}'.format(tmpdst)) self.log.dbg('tmp installed in {}'.format(tmpdst))
# reset flags # reset flags

View File

@@ -22,7 +22,7 @@ COMMENT_END = '@@#}'
class Templategen: class Templategen:
def __init__(self, base='.', variables={}, debug=False): def __init__(self, profile, base='.', variables={}, debug=False):
self.base = base.rstrip(os.sep) self.base = base.rstrip(os.sep)
self.debug = debug self.debug = debug
loader = FileSystemLoader(self.base) loader = FileSystemLoader(self.base)
@@ -36,19 +36,21 @@ class Templategen:
comment_start_string=COMMENT_START, comment_start_string=COMMENT_START,
comment_end_string=COMMENT_END) comment_end_string=COMMENT_END)
self.env.globals['header'] = self._header self.env.globals['header'] = self._header
self.env.globals['env'] = os.environ
self.env.globals['profile'] = profile
self.env.globals.update(variables) self.env.globals.update(variables)
self.log = Logger() self.log = Logger()
def generate(self, src, profile): def generate(self, src):
if not os.path.exists(src): if not os.path.exists(src):
return '' return ''
return self._handle_file(src, profile) return self._handle_file(src)
def _header(self, prepend=''): def _header(self, prepend=''):
"""add a comment usually in the header of a dotfile""" """add a comment usually in the header of a dotfile"""
return '{}{}'.format(prepend, utils.header()) return '{}{}'.format(prepend, utils.header())
def _handle_file(self, src, profile): def _handle_file(self, src):
"""generate the file content from template""" """generate the file content from template"""
filetype = utils.run(['file', '-b', src], raw=False, debug=self.debug) filetype = utils.run(['file', '-b', src], raw=False, debug=self.debug)
filetype = filetype.strip() filetype = filetype.strip()
@@ -58,24 +60,24 @@ class Templategen:
if self.debug: if self.debug:
self.log.dbg('\"{}\" is text: {}'.format(src, istext)) self.log.dbg('\"{}\" is text: {}'.format(src, istext))
if not istext: if not istext:
return self._handle_bin_file(src, profile) return self._handle_bin_file(src)
return self._handle_text_file(src, profile) return self._handle_text_file(src)
def _handle_text_file(self, src, profile): def _handle_text_file(self, src):
"""write text to file""" """write text to file"""
template_rel_path = os.path.relpath(src, self.base) template_rel_path = os.path.relpath(src, self.base)
try: try:
template = self.env.get_template(template_rel_path) template = self.env.get_template(template_rel_path)
content = template.render(profile=profile, env=os.environ) content = template.render()
except UnicodeDecodeError: except UnicodeDecodeError:
data = self._read_bad_encoded_text(src) data = self._read_bad_encoded_text(src)
template = self.env.from_string(data) template = self.env.from_string(data)
content = template.render(profile=profile, env=os.environ) content = template.render()
content = content.encode('UTF-8') content = content.encode('UTF-8')
return content return content
def _handle_bin_file(self, src, profile): def _handle_bin_file(self, src):
"""write binary to file""" """write binary to file"""
# this is dirty # this is dirty
if not src.startswith(self.base): if not src.startswith(self.base):

View File

@@ -30,14 +30,14 @@ class TestCompare(unittest.TestCase):
def compare(self, opts, conf, tmp, nbdotfiles): def compare(self, opts, conf, tmp, nbdotfiles):
dotfiles = conf.get_dotfiles(opts['profile']) dotfiles = conf.get_dotfiles(opts['profile'])
self.assertTrue(len(dotfiles) == nbdotfiles) self.assertTrue(len(dotfiles) == nbdotfiles)
t = Templategen(base=opts['dotpath'], debug=True) t = Templategen(opts['profile'], base=opts['dotpath'], debug=True)
inst = Installer(create=opts['create'], backup=opts['backup'], inst = Installer(create=opts['create'], backup=opts['backup'],
dry=opts['dry'], base=opts['dotpath'], debug=True) dry=opts['dry'], base=opts['dotpath'], debug=True)
comp = Comparator() comp = Comparator()
results = {} results = {}
for dotfile in dotfiles: for dotfile in dotfiles:
ret, insttmp = inst.install_to_temp(t, tmp, opts['profile'], ret, insttmp = inst.install_to_temp(t, tmp, dotfile.src,
dotfile.src, dotfile.dst) dotfile.dst)
if not ret: if not ret:
results[path] = False results[path] = False
continue continue