Ejemplo n.º 1
0
def select_identity():
    identity = get_selection(identities.keys(),
                             'identity',
                             case_insensitive=True,
                             lines=5,
                             font="@wmFontDmenu@")
    return identities.get(identity, None)
Ejemplo n.º 2
0
def select_issue(issues):
    issues_map = {}
    for issue in issues:
        issues_map[issue.key + " | " + issue.fields.summary + " | " +
                   issue.fields.created] = issue
    selected_issue = get_selection(issues_map.keys(),
                                   'issue',
                                   case_insensitive=True,
                                   lines=5,
                                   font="@wmFontDmenu@")
    return issues_map.get(selected_issue, None)
Ejemplo n.º 3
0
def issue_log_work(issue):
    unloddeg_dates = [
        datetime.strftime(d, "%d/%m/%y")
        for d in issue_get_unlogged_dates(issue)
    ]
    date_to_log = get_selection(sorted(unloddeg_dates),
                                'date',
                                case_insensitive=True,
                                lines=15,
                                font="@wmFontDmenu@")
    if not date_to_log:
        notify("[jira]",
               f"Cancelled logging work for `{issue.key}`",
               urgency=URGENCY_CRITICAL)
        sys.exit(1)

    started = datetime.combine(datetime.strptime(date_to_log, "%d/%m/%y"),
                               datetime.now().time())
    amount, comment = None, None
    while not comment:
        result = worklog_get_amount_and_comment()
        if result:
            amount, comment = result.split("|")[:-1]
            if not comment:
                notify("[jira]",
                       f"comment in worklog is mandatory'",
                       urgency=URGENCY_CRITICAL)
        else:
            break
    if amount and comment:
        tz = pytz.timezone("@systemTimeZone@")
        started_with_tz = tz.localize(started)
        wlog = client.add_worklog(issue,
                                  timeSpent=amount,
                                  started=started_with_tz,
                                  comment=comment)
        notify(
            "[jira]",
            f"Logged `{amount}` of work for `{issue.key}` at {date_to_log}'",
            urgency=URGENCY_NORMAL)
Ejemplo n.º 4
0
from pystdlib import shell_cmd

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(" ", "+")
import redis

from pystdlib.uishim import get_selection, notify, show_text_dialog, URGENCY_CRITICAL
from pystdlib.shell import tmux_create_window
from pystdlib import shell_cmd

service_modes = ["status", "logs"]

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(swarm_meta.keys(),
                      "swarm",
                      case_insensitive=True,
                      lines=5,
                      font="@wmFontDmenu@")
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)
Ejemplo n.º 6
0
CONTAINER_STATUSES = [
    "alive",
    "all"
]

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(hostnames, "host", case_insensitive=True, lines=10, 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_status = get_selection(CONTAINER_STATUSES, "status", case_insensitive=True, lines=3, font="@wmFontDmenu@")
Ejemplo n.º 7
0
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)
Ejemplo n.º 8
0
from pystdlib.uishim import get_selection, show_text_dialog
from pystdlib import shell_cmd


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(iface_names, "describe", case_insensitive=True, lines=10, font="@wmFontDmenu@")
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)
Ejemplo n.º 9
0
from pystdlib import shell_cmd

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 = get_selection([],
Ejemplo n.º 10
0
deps_dict = {}


go_mod_path = os.getcwd() + "/go.mod"
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(deps_dict.keys(), "replace", case_insensitive=True, lines=10, font="@wmFontDmenu@")

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

dep_path_local = "@globalWorkspaceRoot@/" + 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)

with open(go_mod_path, "a") as f:
    f.write(f"\nreplace {dep_path} => {dep_path_local}")
Ejemplo n.º 11
0
import redis

from pystdlib.uishim import get_selection, notify, URGENCY_CRITICAL
from pystdlib.shell import tmux_create_window
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)
Ejemplo n.º 12
0
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,
                            'add tag',
                            lines=15,
                            font="@wmFontDmenu@")
        if tag:
            bookmark_tags.append(tag)
            tags_cloud.remove(tag)
        else:
            break
Ejemplo n.º 13
0
import redis

from pystdlib import shell_cmd
from pystdlib.shell import tmux_create_window
from pystdlib.uishim import get_selection, notify, URGENCY_CRITICAL
from pystdlib.xlib import switch_named_desktop

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

if not len(bookmarks):
    notify("[bookmarks]", "No entries", urgency=URGENCY_CRITICAL, timeout=5000)
    sys.exit(1)

bookmark = get_selection(bookmarks.keys(), "", lines=15, font="@wmFontDmenu@")
if bookmark:
    meta = bookmarks[bookmark]
    path = meta["path"]
    shell = meta.get("shell", None)
    if shell:
        tmux_session = meta.get("tmux", "@tmuxDefaultSession@")
        tmux_create_window(None,
                           tmux_session,
                           window_title=path.split("/")[-1],
                           attach=True,
                           start_directory=path)
    elisp_cmd = f'(dired "{path}")'
    emacs_cmd = f'emacsclient -c -s /run/user/1000/emacs/server -e \'{elisp_cmd}\' &'  # TODO: make SPOT for socket path
    shell_cmd(emacs_cmd, oneshot=True)
Ejemplo n.º 14
0
                    action="store_true",
                    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'))
Ejemplo n.º 15
0
identity = select_identity()
if not identity:
    notify("[jira]", "invalid identity", urgency=URGENCY_CRITICAL)
    sys.exit(1)

client = get_client(server=identity["jira"]["server"],
                    auth=tuple(identity["jira"]["creds"]))
issues = get_issues(client, identity["jira"]["project"])

issue = select_issue(issues)
if not issue:
    notify("[jira]", "No issue selected", urgency=URGENCY_NORMAL)
    sys.exit(0)

op = get_selection(OPS.keys(),
                   '>',
                   case_insensitive=True,
                   lines=5,
                   font="@wmFontDmenu@")
if not op:
    notify("[timetracking]", "No operation selected", urgency=URGENCY_NORMAL)
    sys.exit(0)
if op not in OPS:
    notify("[timetracking]",
           "Invalid operation `{op}`",
           urgency=URGENCY_NORMAL)
    sys.exit(0)

OPS[op](issue)
Ejemplo n.º 16
0
from pystdlib.browser import collect_sessions, collect_sessions_with_size, \
    collect_session_urls, init_mgmt_argparser, rotate_sessions

parser = init_mgmt_argparser("qutebrowser-session-auto")
args = parser.parse_args()

if not args.sessions_path:
    notify("[qutebrowser]",
           f"No sessions base path provided",
           urgency=URGENCY_CRITICAL,
           timeout=5000)
    sys.exit(1)
if args.save_session:
    session_name = get_selection([],
                                 "save as",
                                 case_insensitive=True,
                                 lines=1,
                                 font="@wmFontDmenu@")
    if session_name:
        shell_cmd(f"qb-dump-session {session_name}")
elif args.open_session:
    session_name = get_selection(sorted(collect_sessions(args.sessions_path)),
                                 "open",
                                 case_insensitive=True,
                                 lines=15,
                                 font="@wmFontDmenu@")
    if session_name:
        urls, _ = collect_session_urls(args.sessions_path, session_name)
        shell_cmd(f"emacsclient -c {args.sessions_path}/{session_name}")
        # NOTE: direct opening is not implemented yet because of non-flat session layout
elif args.delete_session:
Ejemplo n.º 17
0
import os

from pystdlib import shell_cmd
from pystdlib.shell import tmuxp_load_session, tmuxp_collect_sessions
from pystdlib.uishim import get_selection

result = get_selection(sorted(tmuxp_collect_sessions()),
                       'config',
                       lines=10,
                       font="@wmFontDmenu@")

if result:
    shell_cmd(f"tmuxp load -y -d {os.getenv('HOME')}/.tmuxp/{result}.yml")
Ejemplo n.º 18
0
import json
import sys

import redis

from pystdlib.uishim import get_selection
from pystdlib import shell_cmd


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(snippets.keys(), "", lines=15, font="@wmFontDmenu@")
if snippet:
    snippet_data = snippets[snippet]
    shell_cmd(["xsel", "-ib"], universal_newlines=True,
              input=f"{snippet_data}")
Ejemplo n.º 19
0
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("@passwordStorePath@")
    path = get_selection(pass_files, ">", lines=10, font="@wmFontDmenu@")

    if path:
        annotated = annotate_entry(read_entry_raw(path))
        field = get_selection(annotated.keys(),
                              "type >",
                              lines=3,
                              font="@wmFontDmenu@")
        if field:
            shell_cmd(f"xdotool type {annotated[field]}")
    "80": "@defaultBrowser@",
    "8080": "@defaultBrowser@",
    "8000": "@defaultBrowser@"
}

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(container_names,
                                   "container",
                                   case_insensitive=True,
                                   lines=10,
                                   font="@wmFontDmenu@")
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]
Ejemplo n.º 21
0
from bs4 import BeautifulSoup

from pystdlib.uishim import get_selection, notify
from pystdlib import shell_cmd


def is_valid_url(url):
    return re.search("@urlRegexPy@", url) is not None


page_url = shell_cmd("xsel -o -b")
if page_url is not None:
    if is_valid_url(page_url):
        session_name = get_selection([],
                                     "save as",
                                     lines=1,
                                     font="@wmFontDmenu@")
        if not session_name:
            sys.exit(1)

        page_content = urlopen(page_url)
        soup = BeautifulSoup(page_content, "html.parser")
        tags = soup.findAll("a", attrs={"href": re.compile("^https?://")})
        org_content = [
            f"#+TITLE: {soup.title.string}\n", f"#+PROPERTY: url {page_url}\n"
        ]
        for tag in tags:
            org_content.append(f"* {tag.get('href')}\n")
        with open(f"@firefoxSessionsPath@/{session_name}.org", "w") as f:
            f.writelines(org_content)
        notify("[scrape]",
Ejemplo n.º 22
0
                    help="show predefined command choices")
parser.add_argument(
    "--ignore-tmux",
    dest="ignore_tmux",
    action="store_true",
    default=False,
    help="open connection in new terminal window rather than tmux pane")

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",
Ejemplo n.º 23
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@")
if not service:
    sys.exit(1)
operation = get_selection(operations, '> ', lines=5, font="@wmFontDmenu@")
if not operation:
    sys.exit(1)

if operation in ["journal", "status"]:
    unit_show(service,
              operation,
              user=('user' in service),
              shell=["@defaultTerminal@", "-e"],
              tmux_session="@tmuxDefaultSession@")
Ejemplo n.º 24
0
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)}")
Ejemplo n.º 25
0
import json
import redis

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

from pystdlib import shell_cmd
from pystdlib.shell import tmux_create_window
from pystdlib.uishim import get_selection
from pystdlib.xlib import switch_named_desktop

left_pane_path = get_selection(bookmarks.keys(), "left >", lines=15, font="@wmFontDmenu@") or " "
right_pane_path = get_selection(bookmarks.keys(), "right >", lines=15, font="@wmFontDmenu@") or " "

cmd = f"@mcCmd@ {left_pane_path} {right_pane_path}".strip(" ")

tmux_create_window(cmd, "main", window_title="copier", create_if_not=True, attach=True)
# shell_cmd(cmd, oneshot=True)