Created
July 17, 2022 19:26
-
-
Save chongchonghe/8ed7774d8ac96e26abb0f98ce6197e70 to your computer and use it in GitHub Desktop.
A simply fuzzy search extension to cheat/cheat
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
""" | |
Make this file executable, link it to your PATH and rename it as ch. | |
Usage: ch arg1 [arg2 ...] | |
If arg1 starts with '-', execute cheat from https://github.com/cheat/cheat: | |
`cheat arg1 [arg2 ...]`. | |
Otherwise, do a fuzzy search for arg1 which returns 'tag', then execute `cheat tag`. | |
""" | |
import os | |
import sys | |
from glob import glob | |
COMMUNITY = os.path.expanduser("~/.config/cheat/cheatsheets/community") | |
PERSONAL = os.path.expanduser("~/.config/cheat/cheatsheets/personal") | |
def find_match(target, elements): | |
"""Find the matching string in a list of elements. | |
Args | |
elements (list): a list of strings to search from | |
target (str): target string | |
e.g. | |
>>> find_match('good', ['good-stuff', 'bad-stuff']] | |
""" | |
exact_match = [] | |
fuzzy_match = [] | |
for ele in elements: | |
try: | |
if ele[:len(target)].lower() == target.lower(): | |
if len(ele) == len(target): | |
exact_match.append(ele) | |
else: | |
fuzzy_match.append(ele) | |
except IndexError: | |
continue | |
if len(exact_match) > 0: | |
return exact_match[0], 1 | |
else: | |
if len(fuzzy_match) > 0: | |
# return the shortest match | |
lens = [len(i) for i in fuzzy_match] | |
pick = lens.index(min(lens)) | |
return fuzzy_match[pick], 0 | |
else: | |
return None, 0 | |
def main(): | |
cheats_com = [os.path.basename(i) for i in glob(COMMUNITY + "/*")] | |
cheats_per = [os.path.basename(i) for i in glob(PERSONAL + "/*")] | |
if len(sys.argv) >= 2: | |
if sys.argv[1][0] == '-': | |
sys.exit(os.system("cheat " + " ".join(sys.argv[1:]))) | |
tag = sys.argv[1] | |
else: | |
sys.exit(print("Usage: ch tag")) | |
name, exact = find_match(tag, cheats_per + cheats_com) | |
# name = pick_best(tag, cheats_per) | |
if name is None: | |
sys.exit(print("Couldn't find any match")) | |
if exact: | |
sys.exit(os.system("cheat " + name)) | |
else: | |
confirm = input(f"{name} ([y]/n)? ") | |
if confirm in ['', 'y', 'Y']: | |
sys.exit(os.system("cheat " + name)) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment