def seed_devenv(current_dir): if not markers_exist(current_dir, [".git"]): print("initialize git repo first") sys.exit(1) if markers_exist(current_dir, json.loads(r.get("projectenv/root_markers"))): print("project already initialized") sys.exit(1) settings = json.loads(r.get("projectenv/settings")) token = get_selection_rofi(settings.keys(), "settings: ") if not token: print("no settings to instantiate") sys.exit(1) with open(f"{current_dir}/{settings_file}", "w") as f: f.write(dump(settings[token])) project_templates = json.loads(r.get("projectenv/templates")) template = get_selection_rofi(project_templates.keys(), "template: ") if template: template_source_path = project_templates[template] devenv_template_files = os.listdir(template_source_path) for f in devenv_template_files: shell_cmd( f"renderizer --settings={settings_file} {template_source_path}/{f} > {current_dir}/{f}" ) shell_cmd(f"git add -- {' '.join(get_devenv_files(current_dir))}", ) os.remove(current_dir + "/" + settings_file) sys.exit(0)
def open_urls_firefox(urls): if not urls or len(urls) == 0: raise ValueError("invalid urls provided") shell_cmd(f"firefox --new-window {urls[0]}") time.sleep(0.5) urls_remainder = " --new-tab ".join(urls[1:]) if len(urls_remainder): shell_cmd(f"firefox --new-tab {urls_remainder}")
def term_create_window(cmd, term_cmd=None): if type(term_cmd) not in [list, str]: raise ValueError(f"invalid `term_cmd` type: {type(term_cmd)}") if type(term_cmd) is str: term_cmd = term_cmd.split() if len(cmd) > 0: term_cmd.extend(cmd.split(" ")) shell_cmd(" ".join(term_cmd))
def execute_commands(path, commands, fail=True): os.chdir(path) for cmd in commands: try: shell_cmd(cmd) except: print(f"'{cmd}' failed") if fail: sys.exit(1)
def list_units(system=True, user=True): units = [] if user: result = shell_cmd("systemctl --user list-unit-files") units.extend([f"{unit.split()[0]} [user]" for unit in result.split("\n")[1:-3] if unit.split()[0].endswith(("service", "timer"))]) if system: result = shell_cmd("systemctl list-unit-files") units.extend([f"{unit.split()[0]} [system]" for unit in result.split("\n")[1:-3] if unit.split()[0].endswith(("service", "timer"))]) return units
def is_idle_enough(xprintidle_binary, idle_time_treshold=3600): idle_time = shell_cmd(xprintidle_binary, env={ "DISPLAY": os.getenv("DISPLAY"), "XAUTHORITY": os.getenv("XAUTHORITY") }) return int(idle_time) >= idle_time_treshold * 1000
def get_devenv_stash_token(path): os.chdir(path) devenv_stash_output = shell_cmd( f'git stash list --max-count=1 --grep="{args.stash_name}"').strip() if args.stash_name in devenv_stash_output: return devenv_stash_output.split(": ")[0] return ""
def construct_proto_uri(template=None, url=None, title=None, body=None, dont_encode=None, in_tmux=False): if not url: print("error: no URL provided") sys.exit(1) raw_inputs = dont_encode.split(",") params = [f"url={urlencode(url) if url not in raw_inputs else url}"] if template: params.append(f"template={template}") if title: actual_title = title if in_tmux: actual_title = shell_cmd("tmux display-message -p '#S'") params.append(f"title={urlencode(actual_title) if actual_title not in raw_inputs else actual_title}") if body: actual_body = body if in_tmux: actual_body = shell_cmd('tmux send -X copy-pipe-and-cancel "xsel -i --primary"') params.append(f"body={urlencode(body) if body not in raw_inputs else body}") return f"org-protocol://capture?{'&'.join(params)}"
def show_text_dialog(text=None, cmd=None, title=None, path=None, keep=False): if not text and not cmd: raise ValueError("[show_text_dialog] nothing to display") output = None if cmd: output = shell_cmd(cmd) if not output: raise ValueError("[show_text_dialog] '{cmd}' returned nothing") elif text: output = text dump_path = path if path else "/tmp/dialog_text" if not os.path.exists(dump_path): with open(dump_path, "w") as f: if type(output) is list: f.write("\n".join(output)) else: f.write(output) shell_cmd( f"yad --filename {dump_path} {'--title {title} ' if title else ''}--text-info", ignore_error_codes=[252]) if not keep: os.remove(dump_path)
def get_fingerprint(): output = shell_cmd("xrandr --prop", split_output="\n") edids_map = {} head = None edid = None for i, line in enumerate(output): if " connected " in line: head = line.split(" ")[0] if "EDID:" in line: edid = "".join([s.strip() for s in output[i + 1:i + 9]]) if head and edid: edids_map[head] = edid head = None edid = None return edids_map
args = parser.parse_args() r = redis.Redis(host='localhost', port=6379, db=0) extra_hosts_data = json.loads(r.get("net/extra_hosts")) host = get_selection(extra_hosts_data.keys(), "ssh to", case_insensitive=True, lines=10, font="@wmFontDmenu@") if host: host_meta = extra_hosts_data[host] host_vpn = host_meta.get("vpn", None) if host_vpn: shell_cmd(f"vpnctl --start {host_vpn}") ssh_user = host_meta.get("user", None) ssh_port = host_meta.get("port", None) cmd = f"ssh{' -l ' + ssh_user if ssh_user else ''}{' -p ' + str(ssh_port) if ssh_port else ''} {host_meta['ips'][0]}" if args.show_choices: command_choices = json.loads(r.get("net/command_choices")) choice = get_selection(command_choices, "execute", case_insensitive=True, lines=5, font="@wmFontDmenu@") if choice: cmd += f" -t '{choice}'" else: sys.exit(1)
from pystdlib import shell_cmd r = redis.Redis(host='localhost', port=6379, db=0) dbms_meta = json.loads(r.get("misc/dbms_meta")) extra_hosts_data = json.loads(r.get("net/extra_hosts")) if not len(dbms_meta): notify("[dbms]", "No entries", urgency=URGENCY_CRITICAL, timeout=5000) sys.exit(1) dbms_entry = get_selection(dbms_meta.keys(), "", lines=5, font="@wmFontDmenu@") if dbms_entry: dbms_pass = None if dbms_meta[dbms_entry].get("passwordPassPath"): # using pass dbms_pass = shell_cmd( f'pass {dbms_meta[dbms_entry]["passwordPassPath"]}', split_output="\n")[0] elif dbms_meta[dbms_entry].get("password"): # password in plaintext dbms_pass = dbms_meta[dbms_entry].get("password") else: notify("[dbms]", f"No password provided for '{dbms_entry}'", urgency=URGENCY_CRITICAL, timeout=5000) sys.exit(1) host = dbms_meta[dbms_entry]["host"] dbms_vpn = extra_hosts_data[host].get("vpn", None) if dbms_vpn: shell_cmd(f"vpnctl --start {dbms_vpn}")
default=False, help="Use fallback browser to open URL") parser.add_argument("--copy", dest="copy_url", action="store_true", default=False, help="Copy webjump's url to clipboard") args = parser.parse_args() r = redis.Redis(host='localhost', port=6379, db=0) webjumps = json.loads(r.get("nav/webjumps")) webjump = get_selection(webjumps.keys(), "jump to", case_insensitive=True, lines=15, font="@wmFontDmenu@") if webjump: vpn = webjumps[webjump].get("vpn", None) if vpn: shell_cmd(f"vpnctl --start {vpn}") browser_cmd = webjumps[webjump].get("browser", "@defaultBrowser@") if args.use_fallback: browser_cmd = "@fallbackBrowser@" url = webjumps[webjump]['url'] if not args.copy_url: shell_cmd(f"{browser_cmd} {url}", oneshot=True) shell_cmd(["xsel", "-ib"], input=url.encode('utf-8'))
dest="selector_font", type=str, help="Selector font") args = parser.parse_args() # provide copying to clipboard # provide option to use (py)fzf if args.add_entry: # how to: # iterate over nested levels, collecting nodes under previously selected nodes # full entry path should be accumulated during this loop # on every level we check if current input exists as path part # if it exists we are going deeper # otherwise we create inexistent node and starting the loop over # there should be a show-stopper keybinding to be able to end this loop # afterwards we get last component of accumelated path and assuming it to be # leaf(gpg) node, that will actually contain secret data # then ask password type - manual or autogenerated # think of how to provide password length in autogenerated case though print("add entry") else: pass_files = collect_entries(args.store_path) path = get_selection_rofi(pass_files, "entry") if path: annotated = annotate_entry(read_entry_raw(path)) field = get_selection_rofi(annotated.keys(), "field") if field: shell_cmd(f"xdotool type {annotated[field]}")
parser = argparse.ArgumentParser(description="Searchengines") parser.add_argument("--fallback", dest="use_fallback", action="store_true", default=False, help="Use fallback browser to open URL") args = parser.parse_args() r = redis.Redis(host='localhost', port=6379, db=0) searchengines = json.loads(r.get("nav/searchengines")) searchengine = get_selection(searchengines.keys(), "search with", case_insensitive=True, lines=15, font="@wmFontDmenu@") if searchengine: meta = searchengines[searchengine] url = meta["url"] browser_cmd = meta.get("browser", "@defaultBrowser@") if args.use_fallback: browser_cmd = "@fallbackBrowser@" vpn = meta.get("vpn", None) if vpn: shell_cmd(f"vpnctl --start {vpn}") search_term = shell_cmd("xsel -o").replace(" ", "+") shell_cmd(f'{browser_cmd} {url}{search_term}'.split(), shell=False)
import argparse import json import sys import redis from pystdlib.uishim import get_selection_rofi from pystdlib import shell_cmd parser = argparse.ArgumentParser(description="Snippets") parser.add_argument('--selector-font', dest="selector_font", type=str, help="Selector font") args = parser.parse_args() r = redis.Redis(host='localhost', port=6379, db=0) snippets = json.loads(r.get("nav/snippets")) if not len(snippets): notify("[snippets]", "No entries", urgency=URGENCY_CRITICAL, timeout=5000) sys.exit(1) snippet = get_selection_rofi(snippets.keys(), "") if snippet: snippet_data = snippets[snippet] shell_cmd(["xsel", "-ib"], universal_newlines=True, input=f"{snippet_data}")
] parser = argparse.ArgumentParser(description="SystemD services management.") parser.add_argument("--invalidate-cache", "-i", dest="invalidate", action="store_true", help="drop units cache from Redis") args = parser.parse_args() r = redis.Redis(host='localhost', port=6379, db=0) if args.invalidate: shell_cmd("pkexec systemctl daemon-reload", shell=True, stdout=sys.stdout, stderr=sys.stdout) r.delete("system/services") sys.exit(0) if not r.exists("system/services"): r.lpush("system/services", *list_units()) service = get_selection(sorted( list( dict.fromkeys([ service.decode() for service in r.lrange("system/services", 0, -1) ]))), 'service', lines=20, font="@wmFontDmenu@")
import argparse from pystdlib.uishim import get_selection_rofi, show_text_dialog from pystdlib import shell_cmd parser = argparse.ArgumentParser(description="Repository overview search") parser.add_argument('--selector-font', dest="selector_font", type=str, help="Selector font") args = parser.parse_args() ifconfig_result = shell_cmd("ifconfig -s", split_output="\n") iface_names = [iface_meta.split()[0] for iface_meta in ifconfig_result[1:]] iface_name = get_selection_rofi(iface_names, "describe") iface_traits = shell_cmd(f"ifconfig {iface_name}") shell_cmd(["xsel", "-ib"], universal_newlines=True, input=f"{iface_traits.encode('utf-8')}") show_text_dialog(text=iface_traits)
def fetch_tags_cloud(): tags_cloud = shell_cmd("buku --np --st", split_output="\n") return [ " ".join(tag.strip().split(" ")[1:-1]) for tag in tags_cloud if tag ]
import json import redis from pystdlib import shell_cmd r = redis.Redis(host='localhost', port=6379, db=0) roots = json.loads(r.get("content/ebook_roots")) books = [] for root in roots: books.extend(shell_cmd(f"@booksSearchCommand@ {root}", split_output="\n")) r.set("content/ebooks_list", json.dumps(books))
if in_tmux: actual_body = shell_cmd('tmux send -X copy-pipe-and-cancel "xsel -i --primary"') params.append(f"body={urlencode(body) if body not in raw_inputs else body}") return f"org-protocol://capture?{'&'.join(params)}" DEBUG_FILE = f'{os.environ["HOME"]}/org-capture.log' parser = argparse.ArgumentParser(description="Org-capture proxy.") parser.add_argument("--debug", "-d", dest="debug", action="store_true", help="dump org-protocol URI to <DEBUG_FILE>") parser.add_argument("--template", "-k", dest="template", help="org-capture template key") parser.add_argument("--url", "-u", dest="url", help="url to store") parser.add_argument("--title", "-t", dest="title", help="title to store") parser.add_argument("--body", "-b", dest="body", help="selection to attach") parser.add_argument("--dont-encode", "-e", dest="dont_encode", help="comma-separated list of fields that should be used as is") args = parser.parse_args() in_tmux = os.environ.get("TMUX", None) capture_uri = construct_proto_uri(template=args.template, url=args.url, title=args.title, body=args.body, dont_encode=args.dont_encode) if args.debug: with open(DEBUG_FILE, "w") as debug: debug.write(capture_uri + "\n") shell_cmd(f'emacsclient -s @emacsServerSocketPath@ "{capture_uri}"')
hostnames = sorted(list(set(hostnames))) hostname = get_selection_rofi(hostnames, "host") host_meta = extra_hosts_data.get(hostname, None) if not host_meta: notify("[docker]", f"Host '{hostname}' not found", urgency=URGENCY_CRITICAL, timeout=5000) sys.exit(1) if hostname == "localhost": os.environ["DOCKER_HOST"] = "unix:///var/run/docker.sock" else: os.environ["DOCKER_HOST"] = f"ssh://{hostname}" host_vpn = host_meta.get("vpn", None) if host_vpn: shell_cmd(f"vpn --start {host_vpn}") container_status = get_selection_rofi(CONTAINER_STATUSES, "status") if not container_status: sys.exit(1) select_container_result = shell_cmd( f"docker ps {'-a ' if container_status == 'all' else ''}--format '{{.Names}}'", split_output="\n") selected_container = get_selection_rofi(select_container_result, "container") selected_trait = get_selection_rofi(CONTAINER_TRAITS.keys(), "inspect") docker_inspect_cmd = f'docker inspect {selected_container} --format "{CONTAINER_TRAITS[selected_trait]}"' inspect_result = shell_cmd(["xsel", "-ib"], universal_newlines=True, input=docker_inspect_cmd env={"DOCKER_HOST": os.environ['DOCKER_HOST']})
URL_REGEX = "(https?|ftp|file)://[-A-Za-z0-9\+&@#/%?=~_|!:,.;]*[-A-Za-z0-9\+&@#/%=~_|]" def is_valid_url(url): return re.search(URL_REGEX, url) is not None def fetch_tags_cloud(): tags_cloud = shell_cmd("buku --np --st", split_output="\n") return [ " ".join(tag.strip().split(" ")[1:-1]) for tag in tags_cloud if tag ] bookmark_text = shell_cmd("xsel -o -b") if bookmark_text is not None: if not is_valid_url(bookmark_text): notify("error", "URL is not valid", urgency=URGENCY_CRITICAL, timeout=5000) sys.exit(1) result = get_selection([bookmark_text], 'bookmark', font="@wmFontDmenu@") if not result: notify("OK", "Aborted adding bookmark", timeout=5000) sys.exit(1) tags_cloud = fetch_tags_cloud() bookmark_tags = [] while True: tag = get_selection(tags_cloud,
import json import redis from pystdlib.uishim import notify, URGENCY_NORMAL, URGENCY_CRITICAL from pystdlib import shell_cmd r = redis.Redis(host='localhost', port=6379, db=0) macs = json.loads(r.get("networking/wireless/headsets")) notify(f"[BT battery]", "Please wait...", urgency=URGENCY_NORMAL, timeout=5000) result = [] for mac in sorted(macs): output = shell_cmd(f"bluetooth_battery {mac}").strip() if "offline" in output: result.append(f"{mac}: offline") else: result.append(f"{mac}: {output.split(' ')[-1]}") if result: notify(f"[BT battery]", "\n".join(result), urgency=URGENCY_NORMAL, timeout=3000) else: notify(f"[BT battery]", "error getting headset(s) battery level(s)", urgency=URGENCY_CRITICAL, timeout=3000)
import json import os import re import redis from pystdlib.uishim import get_selection from pystdlib import shell_cmd r = redis.Redis(host='localhost', port=6379, db=0) ebooks = r.get("content/ebooks_list") if ebooks: ebooks = json.loads(ebooks) result = get_selection(ebooks, 'book', case_insensitive=True, lines=30, font="@wmFontDmenu@") if result: shell_cmd(f"zathura {re.escape(result)}")
import sys from pystdlib.uishim import get_selection, notify, URGENCY_CRITICAL from pystdlib.shell import tmux_create_window from pystdlib import shell_cmd keyword_result = get_selection([], 'keyword', font="@wmFontDmenu@") if not keyword_result: notify("[search repos]", "no keyword provided", urgency=URGENCY_CRITICAL, timeout=5000) sys.exit(1) matching_repos = shell_cmd(f"fd -t d -d @searchDepth@ {keyword_result} @searchReposRoot@", split_output="\n") selected_repo = get_selection(matching_repos, 'repo', case_insensitive=True, lines=10, font="@wmFontDmenu@") if not selected_repo: notify("[search repos]", "no repository selected", timeout=5000) sys.exit(0) elisp_cmd = f'(dired "{selected_repo}")' emacs_cmd = f'emacsclient -c -s /run/user/1000/emacs/server -e \'{elisp_cmd}\'' # TODO: make SPOT for socket path shell_cmd(emacs_cmd)
from pystdlib import shell_cmd from pystdlib.browser import collect_sessions, collect_sessions_with_size, \ collect_session_urls, init_mgmt_argparser, open_urls_firefox, rotate_sessions parser = init_mgmt_argparser() parser.add_argument('--selector-font', dest="selector_font", type=str, help="Selector font") args = parser.parse_args() if not args.sessions_path: notify("[Firefox]", f"No sessions base path provided", urgency=URGENCY_CRITICAL, timeout=5000) sys.exit(1) if args.save_session: session_name = get_selection_rofi([], "save as") if session_name: shell_cmd(f"dump_firefox_session {session_name}") elif args.open_session: session_name = get_selection_rofi(sorted(collect_sessions(args.sessions_path)), "open") if session_name: urls, _ = collect_session_urls(args.sessions_path, session_name) if len(urls) > 0: shell_cmd(f"emacsclient -c {args.sessions_path}/{session_name}") elif args.edit_session: session_name = get_selection_rofi(sorted(collect_sessions(args.sessions_path)), "edit") if session_name: shell_cmd(f"emacsclient -c {args.sessions_path}/{session_name}") elif args.delete_session: session_name = get_selection_rofi(sorted(collect_sessions(args.sessions_path)), "delete") if session_name: shell_cmd(f"rm {args.sessions_path}/{session_name}") notify("[Firefox]", f"Removed {session_name}", timeout=5000)
notify("[virt]", "No swarm selected") sys.exit(0) swarm_host = swarm_meta[swarm] os.environ["DOCKER_HOST"] = f"ssh://{swarm_host}" host_meta = extra_hosts_data.get(swarm_host, None) if not host_meta: notify("[docker]", f"Host '{swarm_host}' not found", urgency=URGENCY_CRITICAL, timeout=5000) sys.exit(1) host_vpn = host_meta.get("vpn", None) if host_vpn: shell_cmd(f"vpnctl --start {host_vpn}") services_meta = shell_cmd( "docker service ls --format '{{.Name}} | {{.Mode}} | {{.Replicas}} | {{.Image}}'", split_output="\n") selected_service_meta = get_selection(services_meta, "service", case_insensitive=True, lines=10, font="@wmFontDmenu@") selected_service_name = selected_service_meta.split("|")[0].strip() selected_mode = get_selection(service_modes, "show", case_insensitive=True, lines=5,
} if not (args.default_browser and args.fallback_browser): notify(f"[containers]", f"Browsers not set, exiting...", urgency=URGENCY_CRITICAL, timeout=5000) sys.exit(1) ip_address_format = "{{range $network, $settings :=.NetworkSettings.Networks}}{{$settings.IPAddress}}{{end}}" ports_format = "{{range $port, $mappings :=.NetworkSettings.Ports}}{{$port}}{{end}}" if "DOCKER_HOST" in os.environ: del os.environ["DOCKER_HOST"] # ensure we cosidering only local containers container_names = shell_cmd("docker ps --format '{{.Names}}'", split_output="\n") selected_container = get_selection_rofi(container_names, "container") if not selected_container: sys.exit(1) container_ip = shell_cmd( f"docker inspect {selected_container} --format='{ip_address_format}'") container_ports = shell_cmd( f"docker inspect {selected_container} --format='{ports_format}'", split_output="\n") port_result = None for port in container_ports_result: port_number = port.split("/")[0] if port_number in port_cmd_mapping:
font="@wmFontDmenu@") host_meta = extra_hosts_data.get(hostname, None) if not host_meta: notify("[docker]", f"Host '{hostname}' not found", urgency=URGENCY_CRITICAL, timeout=5000) sys.exit(1) if hostname == "localhost": os.environ["DOCKER_HOST"] = "unix:///var/run/docker.sock" else: os.environ["DOCKER_HOST"] = f"ssh://{hostname}" host_vpn = host_meta.get("vpn", None) if host_vpn: shell_cmd(f"vpnctl --start {host_vpn}") container_names = shell_cmd("docker ps --format '{{.Names}}'", split_output="\n") selected_container = get_selection(container_names, "container", case_insensitive=True, lines=10, font="@wmFontDmenu@") if not selected_container: sys.exit(1) get_shell_cmd = f"export DOCKER_HOST={os.environ['DOCKER_HOST']} && docker exec -it {selected_container} @defaultContainerShell@" tmux_create_window(get_shell_cmd, session_name=host_meta.get("tmux", "@tmuxDefaultSession@"), window_title=f"{selected_container} shell")