コード例 #1
0
ファイル: devenv.py プロジェクト: wiedzmin/nixos-config
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)
コード例 #2
0
ファイル: devenv.py プロジェクト: wiedzmin/nixos-config
def import_devenv(current_dir, backup_root):
    prefix = project_prefix(current_dir)
    envs = [
        os.path.basename(env) for env in glob.glob(f"{backup_root}/{prefix}*")
    ]
    env = get_selection_rofi(envs, "envs: ")
    if env:
        copyfile(f"{backup_root}/{env}", f"{current_dir}/{env}")
    else:
        print("nothing selected")
コード例 #3
0
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:
        port_result = port_number
コード例 #4
0
ファイル: gittags.py プロジェクト: wiedzmin/nixos-config
if not is_repo(os.getcwd()):
    log_error("Not a git repo")
    sys.exit(1)

repo = Repository(os.getcwd() + "/.git")
config = repo.config

remote_url = repo.remotes[args.remote].url
pass_path = None
for glob in credentials_mapping.keys():
    if fnmatch.fnmatch(remote_url, glob):
        pass_path = credentials_mapping[glob]["target"]

if args.tags_sync:
    remote = resolve_remote(repo, args.remote)
    if not remote:
        log_error(f"cannot find remote '{args.remote}'")
        sys.exit(1)
    remote.fetch(refspecs=["refs/tags/*:refs/tags/*"])
    remote.push(specs=collect_tags(repo),
                callbacks=build_auth_callbacks(repo, pass_path))
elif args.tags_checkout:
    tag_name = args.tags_name
    if is_interactive:
        tag_name = get_selection_rofi(collect_tags(repo), "")
    if not tag_name:
        log_error("No tag to checkout")
        sys.exit(1)
    repo.checkout(tag_name)
コード例 #5
0
ファイル: ifconfless.py プロジェクト: wiedzmin/nixos-config
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)
コード例 #6
0
from pystdlib.uishim import get_selection_rofi, notify, URGENCY_CRITICAL
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:
コード例 #7
0
parser = argparse.ArgumentParser(description="Containers traits")
parser.add_argument('--selector-font', dest="selector_font", type=str, help="Selector font")
args = parser.parse_args()

hostnames = []

with open("/etc/hosts", "r") as hosts:
    for host in hosts:
        host_list = list(reversed(host.strip(";\n").split()))
        if host_list:
            hostnames.extend(host_list[:-1])

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")
コード例 #8
0
ファイル: passctl.py プロジェクト: wiedzmin/nixos-config
                    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]}")
コード例 #9
0
ファイル: snippets.py プロジェクト: wiedzmin/nixos-config
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}")
コード例 #10
0
service_modes = [
    "status",
    "logs"
]

parser = argparse.ArgumentParser(description="Docker Swarm services info")
parser.add_argument('--tmux-session', dest="tmux_session", default="main", type=str, help="Fallback tmux session name")
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)
extra_hosts_data = json.loads(r.get("net/extra_hosts"))

swarm_meta = json.loads(r.get("virt/swarm_meta"))
swarm = get_selection_rofi(swarm_meta.keys(), "swarm")
if not swarm:
    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"vpn --start {host_vpn}")
コード例 #11
0
parser.add_argument(
    "--ignore-tmux",
    dest="ignore_tmux",
    action="store_true",
    default=False,
    help="open connection in new terminal window rather than tmux pane")
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)
extra_hosts_data = json.loads(r.get("net/extra_hosts"))

host = get_selection_rofi(extra_hosts_data.keys(), "ssh to")

if host:
    host_meta = extra_hosts_data[host]
    host_vpn = host_meta.get("vpn")
    if host_vpn:
        shell_cmd(f"vpn --start {host_vpn}")
    jump_hosts = list_jump_hosts(host_meta, extra_hosts_data)
    cmd = f"ssh {' '.join(['-J ' + format_host_meta(host_meta['host'], host_meta, terse=True) for host_meta in jump_hosts])} {format_host_meta(host, host_meta)}"
    if args.show_choices:
        command_choices = json.loads(r.get("net/command_choices"))
        choice = get_selection_rofi(command_choices, "execute")
        if choice:
            cmd += f" -t '{choice}'"
        else:
            sys.exit(1)
コード例 #12
0
        kb["modebinding"] = modebindings.get(kb["mode"], "")
        keybindings_by_mode.setdefault(kb["mode"], []).append(kb)
    else:
        kb["modebinding"] = ""
        dangling_keybindings_by_mode.setdefault(kb["mode"], []).append(kb)

for mode_name in keybindings_by_mode:
    if not args.fuzzy:
        legend.append(format_modebinding(mode_name,
                                         binding=modebindings[mode_name]
                                         if mode_name != "root" else "non-prefix"))
    for kb in keybindings_by_mode[mode_name]:
        legend.append(format_keybinding(kb, fuzzy=args.fuzzy))

if len(dangling_keybindings_by_mode):
    if not args.fuzzy:
        legend.append("================== DANGLING KEYBINDINGS ==================")
    for mode_name in dangling_keybindings_by_mode:
        if not args.fuzzy:
            legend.append(format_modebinding(mode_name))
        for kb in dangling_keybindings_by_mode[mode_name]:
            legend.append(format_keybinding(kb, fuzzy=args.fuzzy, dangling=True))

if args.fuzzy:
    get_selection_rofi(legend, "")
else:
    try:
        show_text_dialog(text=legend, title="keybindings")
    except ValueError:
        print("Canceled")
コード例 #13
0
ファイル: xrandrutil.py プロジェクト: wiedzmin/nixos-config
parser.add_argument('--selector-font',
                    dest="selector_font",
                    type=str,
                    help="Selector font")
# TODO: add orthogonal output format selection
# TODO: consider adding option for dmenu + yad selection/output

args = parser.parse_args()

if args.switch_profile:
    for root, dirs, files in os.walk(args.profiles_root):
        for dir in dirs:
            if not dir.endswith(".d"):
                profiles.append(dir)

    result = get_selection_rofi(profiles, 'profile')
    if result:
        shell_cmd(f"autorandr --load {result}", oneshot=True)
elif args.get_fingerprint:
    print(json.dumps({"fingerprint": get_fingerprint()}, indent=2))
elif args.get_apptraits:
    ewmh = EWMH()
    UTF8_STRING = ewmh.display.intern_atom('UTF8_STRING')
    STRING = ewmh.display.intern_atom('STRING')
    NET_WM_NAME = ewmh.display.intern_atom('_NET_WM_NAME')
    WM_WINDOW_ROLE = ewmh.display.intern_atom('WM_WINDOW_ROLE')

    windows = ewmh.getClientList()
    for window in windows:
        meta = []
        title = window.get_full_text_property(NET_WM_NAME, UTF8_STRING)
コード例 #14
0
import argparse
import json
import os
import re

import redis

from pystdlib.uishim import get_selection_rofi
from pystdlib import shell_cmd

parser = argparse.ArgumentParser(description="Searchengines")
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)

documents = r.get("paperworks/docs")
if documents:
    documents = json.loads(documents)

result = get_selection_rofi(documents, 'document')
if result:
    shell_cmd(f"libreoffice {re.escape(result)}")
コード例 #15
0
ファイル: modedit.py プロジェクト: wiedzmin/nixos-config
if not (os.path.exists(go_mod_path) and os.path.isfile(go_mod_path)):
    notify("[modedit]",
           "No go.mod found",
           urgency=URGENCY_CRITICAL,
           timeout=5000)
    sys.exit(1)

with open(go_mod_path, "r") as f:
    deps_list = re.search(pattern, f.read(),
                          re.DOTALL).group(0).split("\n")[1:-1]
    deps_list = [dep for dep in deps_list if not dep.startswith("//")]
    deps_list = [dep for dep in deps_list if dep.startswith("\t")]
    for dep in deps_list:
        deps_dict[dep.split()[0]] = dep.split()[1]

dep_path = get_selection_rofi(deps_dict.keys(), "replace")

if not dep_path:
    notify("[modedit]", "Nothing selected", timeout=5000)
    sys.exit(0)

dep_path_local = f"{args.workspace_root}/{dep_path}"
if dep_path_local.endswith(".git"):
    dep_path_local = dep_path_local[:-4]

if not (os.path.exists(dep_path_local) and os.path.isdir(dep_path_local)):
    notify("[modedit]",
           "No dependency repo found locally",
           urgency=URGENCY_CRITICAL,
           timeout=5000)
    sys.exit(1)
コード例 #16
0
ファイル: docker_shell.py プロジェクト: wiedzmin/nixos-config
                    dest="selector_font",
                    type=str,
                    help="Selector font")
args = parser.parse_args()

r = redis.Redis(host='localhost', port=6379, db=0)
extra_hosts_data = json.loads(r.get("net/extra_hosts"))

with open("/etc/hosts", "r") as hosts:
    for host in hosts:
        host_list = list(reversed(host.strip(";\n").split()))
        if host_list:
            hostnames.extend(host_list[:-1])
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}")