Skip to content

Commit

Permalink
F1 shows man page for current query
Browse files Browse the repository at this point in the history
  • Loading branch information
serpent7776 committed Apr 29, 2024
1 parent c6c5f04 commit 2791a30
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
17 changes: 17 additions & 0 deletions pgcli/key_bindings.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import logging
import click
import re
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding import KeyBindings
from prompt_toolkit.filters import (
Expand All @@ -8,6 +10,7 @@
has_selection,
vi_mode,
)
from .man import man

from .pgbuffer import buffer_should_be_handled, safe_multi_line_mode

Expand All @@ -20,6 +23,20 @@ def pgcli_bindings(pgcli):

tab_insert_text = " " * 4

@kb.add("f1")
def _(event):
"""Show man page for current command."""
_logger.debug("Detected <F1> key.")

m = re.match(r"^[\w\s]+", event.app.current_buffer.text)
if not m:
return
click.clear()
text = m.group()
_logger.debug(f"Launching man page for {text}")
if not man(text):
_logger.debug("Failed to show man page")

@kb.add("f2")
def _(event):
"""Enable/Disable SmartCompletion Mode."""
Expand Down
44 changes: 44 additions & 0 deletions pgcli/man.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import subprocess

IGNORED = [
"OR",
"REPLACE",
"DEFAULT",
"UNIQUE",
"TRUSTED",
"PROCEDURAL",
"TEMP",
"TEMPORARY",
"UNLOGGED",
"GLOBAL",
"LOCAL",
"CONSTRAINT",
"RECURSIVE",
"WORK",
"TRANSACTION",
"SESSION",
]


def try_man(page):
try:
subprocess.run(
f"man -I 7 {page}", shell=True, check=True, universal_newlines=True

Check warning

Code scanning / CodeQL

Unsafe shell command constructed from library input Medium

This f-string which depends on
library input
is later used in a
shell command
.
)
return True
except subprocess.CalledProcessError:
return False


def man(query):
words = query.strip().split()[:6]
words = map(lambda e: e.upper(), words)
words = list(filter(lambda e: e not in IGNORED, words))
if not words:
return True
if words[0] == "RELEASE":
words.insert(1, "SAVEPOINT")
for i in [2, 1, 3, 4]:
if try_man("_".join(words[0 : i + 1])):
return True
return False

0 comments on commit 2791a30

Please sign in to comment.