Skip to content

Instantly share code, notes, and snippets.

@gitcrtn
Created December 18, 2021 09:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gitcrtn/81011a63b08d947c70b1427c525ad340 to your computer and use it in GitHub Desktop.
Save gitcrtn/81011a63b08d947c70b1427c525ad340 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
"""
Mac Tool Menu
Usage:
python3 mac_tool_menu.py conf.yaml
Example of conf.yaml:
tool_name: command line string
aaa: date
bbb:
ccc: date
ddd: date
Requirements:
Python 3.8+
rumps
pyyaml
"""
import os
import sys
import textwrap
import functools
import rumps
import yaml
class ToolLauncher(rumps.App):
def __init__(self):
super().__init__('+', quit_button=None)
self._items_yaml_path = sys.argv[1]
self._construct_menu_items()
def _make_cmdline_item(self, name, cmdline):
return rumps.MenuItem(name, callback=functools.partial(self._open_terminal, cmdline))
def _make_expandable_item(self, name):
return rumps.MenuItem(name, callback=self._dummy)
def _dummy(self, unused_):
pass
def _construct_menu_items(self):
self.menu.clear()
menu_items = []
with open(self._items_yaml_path) as f:
data = yaml.safe_load(f)
# support only 1 nested depth
for name, content in data.items():
if isinstance(content, dict):
subitems = []
for subname, subcontent in content.items():
if isinstance(subcontent, str):
subitems.append(self._make_cmdline_item(subname, subcontent))
if subitems:
menu_items.append([self._make_expandable_item(name), subitems])
elif isinstance(content, str):
menu_items.append(self._make_cmdline_item(name, content))
if menu_items:
menu_items.append(None)
menu_items.append(rumps.MenuItem('Refresh', callback=self._refresh))
self.menu = menu_items
def _refresh(self, unused_):
self._construct_menu_items()
def _open_terminal(self, cmdline, unused_):
script = textwrap.dedent(f"""\
tell Application "Terminal"
activate
do script "{cmdline}"
end tell
""")
os.system(f"osascript -e '{script}'")
if __name__ == "__main__":
ToolLauncher().run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment