From bcaa7e6e4dddf27acdb37757d02a5e360bdf455c Mon Sep 17 00:00:00 2001 From: Buck Ryan Date: Sun, 28 Jan 2018 22:37:46 -0500 Subject: [PATCH] A possible solution for allowing custom themes --- powerline_shell/__init__.py | 23 +++++++++++++++++++---- powerline_shell/utils.py | 18 ++++++++++++++++++ 2 files changed, 37 insertions(+), 4 deletions(-) diff --git a/powerline_shell/__init__.py b/powerline_shell/__init__.py index 8434285..d572817 100644 --- a/powerline_shell/__init__.py +++ b/powerline_shell/__init__.py @@ -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 = [] diff --git a/powerline_shell/utils.py b/powerline_shell/utils.py index aea7754..e41a151 100644 --- a/powerline_shell/utils.py +++ b/powerline_shell/utils.py @@ -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)