1
0
Fork 0

bang: add an option to provide a default handle

This commit is contained in:
Adrien Abraham 2023-11-07 14:01:02 +01:00
parent ec545d5e11
commit cdfae0009d

62
bang.py
View file

@ -72,7 +72,10 @@ def run_rofi(config, input_text="", title="bang", no_lines=False):
def open_bang(config, handle, query):
try:
bang = next(bang for bang in config["bangs"] if handle == bang["handle"])
bang = next(
bang for bang in config["bangs"]
if handle == bang["handle"]
)
except StopIteration:
print("Unknown handle.")
return
@ -85,10 +88,33 @@ def open_bang(config, handle, query):
def main():
ap = argparse.ArgumentParser()
ap.add_argument("-c", "--config", help="path to JSON config file")
ap.add_argument("-l", "--list", action="store_true", help="show available bangs")
ap.add_argument("-b", "--bang", nargs="+", help="launch with this bang already set")
ap.add_argument("-f", "--queries-file", help="file with one bang argument per line")
ap.add_argument(
"-c",
"--config",
help="path to JSON config file"
)
ap.add_argument(
"-l",
"--list",
action="store_true",
help="show available bangs"
)
ap.add_argument(
"-b",
"--bang",
nargs="+",
help="launch with this bang already set"
)
ap.add_argument(
"-f",
"--queries-file",
help="file with one bang argument per line"
)
ap.add_argument(
"-d",
"--default",
help="handle to use if the first word is not a known handle"
)
args = ap.parse_args()
config = load_config()
@ -107,26 +133,36 @@ def main():
except OSError:
exit("Can't load queries file.")
# If a bang is specified on the command line, use it, optionally with its args.
handles = [
bang["handle"]
for bang in sorted(config["bangs"], key=lambda bang: bang["handle"])
]
# If a bang is specified on the command line, use it,
# optionally with its args.
if bang_args := args.bang:
handle = bang_args[0]
if bang_args[1:]:
queries.append(" ".join(bang_args[1:]))
# Else show a Rofi with the list of available bangs.
else:
process_input = "\n".join(
i["handle"]
for i in sorted(config["bangs"], key=lambda bang: bang["handle"])
) + "\n"
process_input = "\n".join(handles) + "\n"
output = run_rofi(config, input_text=process_input)
parts = output.split(maxsplit=1)
if len(parts) < 1:
if len(parts) == 0:
exit("Bad Rofi output.")
handle = parts[0]
if len(parts) > 1:
if handle not in handles and (default_handle := args.default):
handle = default_handle
if len(parts) == 1:
queries.append(parts[0])
if len(parts) == 2:
queries.append(parts[1])
# If no queries were obtained during options parsing, show Rofi now to get a single query.
# If no queries were obtained during options parsing,
# show Rofi now to get a single query.
if not queries:
queries.append(run_rofi(config, title=handle, no_lines=True))