Skip to content

Commit af919e1

Browse files
author
Buck Ryan
committed
Custom segment support
Closes #407 The changes in 407 were on the right track, but didn't take it all the way. Some issues it had: - Did not call `expanduser` to handle paths like `~/segment.py` - Did not appear to work on both Python 2 and Python 3 - Did not show a meaningful message when a segment cannot be found This commit repurposes the code written to import custom themes for segments.
1 parent ee5776f commit af919e1

File tree

1 file changed

+26
-13
lines changed

1 file changed

+26
-13
lines changed

powerline_shell/__init__.py

Lines changed: 26 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -167,21 +167,26 @@ def find_config():
167167
}
168168

169169

170-
class ThemeNotFoundException(Exception):
170+
class ModuleNotFoundException(Exception):
171171
pass
172172

173173

174-
def read_theme(config):
175-
theme_name = config.get("theme", "default")
176-
try:
177-
mod = importlib.import_module("powerline_shell.themes." + theme_name)
178-
except ImportError:
174+
class CustomImporter(object):
175+
def __init__(self):
176+
self.file_import_count = 0
177+
178+
def import_(self, module_prefix, module_or_file, description):
179179
try:
180-
mod = import_file("custom_theme", os.path.expanduser(theme_name))
180+
mod = importlib.import_module(module_prefix + module_or_file)
181181
except ImportError:
182-
raise ThemeNotFoundException(
183-
"Theme " + theme_name + " cannot be found")
184-
return getattr(mod, "Color")
182+
try:
183+
module_name = "_custom_mod_{0}".format(self.file_import_count)
184+
mod = import_file(module_name, os.path.expanduser(module_or_file))
185+
self.file_import_count += 1
186+
except (ImportError, IOError):
187+
msg = "{0} {1} cannot be found".format(description, module_or_file)
188+
raise ModuleNotFoundException( msg)
189+
return mod
185190

186191

187192
def main():
@@ -211,13 +216,21 @@ def main():
211216
else:
212217
config = DEFAULT_CONFIG
213218

214-
theme = read_theme(config)
219+
custom_importer = CustomImporter()
220+
theme_mod = custom_importer.import_(
221+
"powerline_shell.themes.",
222+
config.get("theme", "default"),
223+
"Theme")
224+
theme = getattr(theme_mod, "Color")
215225

216226
powerline = Powerline(args, config, theme)
217227
segments = []
218228
for seg_name in config["segments"]:
219-
mod = importlib.import_module("powerline_shell.segments." + seg_name)
220-
segment = getattr(mod, "Segment")(powerline)
229+
seg_mod = custom_importer.import_(
230+
"powerline_shell.segments.",
231+
seg_name,
232+
"Segment")
233+
segment = getattr(seg_mod, "Segment")(powerline)
221234
segment.start()
222235
segments.append(segment)
223236
for segment in segments:

0 commit comments

Comments
 (0)