A possible solution for allowing custom themes

This commit is contained in:
Buck Ryan 2018-01-28 22:37:46 -05:00
parent ad27ed4ccc
commit bcaa7e6e4d
2 changed files with 37 additions and 4 deletions

View file

@ -6,7 +6,7 @@ import os
import sys
import importlib
import json
from .utils import warn, py3
from .utils import warn, py3, import_file
import re
@ -168,6 +168,23 @@ DEFAULT_CONFIG = {
}
class ThemeNotFoundException(Exception):
pass
def read_theme(config):
theme_name = config.get("theme", "default")
try:
mod = importlib.import_module("powerline_shell.themes." + theme_name)
except ImportError:
try:
mod = import_file("custom_theme", os.path.expanduser(theme_name))
except ImportError:
raise ThemeNotFoundException(
"Theme " + theme_name + " cannot be found")
return getattr(mod, "Color")
def main():
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument('--generate-config', action='store_true',
@ -190,9 +207,7 @@ def main():
else:
config = DEFAULT_CONFIG
theme_name = config.get("theme", "default")
mod = importlib.import_module("powerline_shell.themes." + theme_name)
theme = getattr(mod, "Color")
theme = read_theme(config)
powerline = Powerline(args, config, theme)
segments = []

View file

@ -98,3 +98,21 @@ class ThreadedSegment(threading.Thread):
def __init__(self, powerline):
super(ThreadedSegment, self).__init__()
self.powerline = powerline
def import_file(module_name, path):
# An implementation of https://stackoverflow.com/a/67692/683436
if py3 and sys.version_info[1] >= 5:
import importlib.util
spec = importlib.util.spec_from_file_location(module_name, path)
if not spec:
raise ImportError()
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod
elif py3:
from importlib.machinery import SourceFileLoader
return SourceFileLoader(module_name, path).load_module()
else:
import imp
return imp.load_source(module_name, path)