restructure gcd

This commit is contained in:
ville rantanen
2018-11-08 12:39:12 +02:00
parent 5e1dd8fa52
commit 1a7855242c

View File

@@ -4,106 +4,125 @@ import sys,os,re
import difflib as dl import difflib as dl
# Define color codes # Define color codes
Green="\033[32;1m" Green = "\033[32;1m"
Red="\033[31;1m" Red = "\033[31;1m"
Reset="\033[0m" Reset = "\033[0m"
# Available shortcut keys # Available shortcut keys
key_list="1234567890qwertyuiop" key_list = "1234567890qwertyuiop"
class getch: class getch:
def get(self): def get(self):
import termios, tty
fd = sys.stdin.fileno() fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd) old_settings = termios.tcgetattr(fd)
try: try:
tty.setraw(sys.stdin.fileno()) tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1) ch = sys.stdin.read(1)
finally: finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) termios.tcsetattr(
fd,
termios.TCSADRAIN,
old_settings
)
return ch return ch
def printerr(s): def printerr(s):
sys.stderr.write(s+"\n") sys.stderr.write(s + "\n")
sys.stderr.flush() sys.stderr.flush()
def colorize_matches(directories,repl): def errexit(s):
return [repl.sub("%s\g<1>%s"%(Green,Reset),d) for d in directories] printerr(s)
sys.exit(1)
def colorize_matches(directories, repl):
return [repl.sub("%s\g<1>%s"%(Green, Reset), d) for d in directories]
def search_close_match(directories, key): def search_close_match(directories, key):
""" Return a list of Components whose name closely matches key """ """ Return a list of Components whose name closely matches key """
match=[] match = []
key=key.lower() key = key.lower()
for name in directories: for name in directories:
s=dl.SequenceMatcher(None, name.lower(), key) s = dl.SequenceMatcher(
s_ratio=s.ratio() None,
if s_ratio > 0: name.lower(),
match.append(( s_ratio, name )) key
match.sort(key=lambda x:x[0], reverse=True) )
if s.ratio() > 0:
match.append(( s.ratio(), name ))
match.sort(key = lambda x: x[0], reverse = True)
best_matches=[x[1] for x in match[0:10]] best_matches=[x[1] for x in match[0:10]]
return best_matches return best_matches
# Print help def get_dirs(pat_dir):
if len(sys.argv)==1 or sys.argv[-1]=="-h":
printerr("Guess cd: Find first match in folder, interactive if multiple matches\n Arguments: [dir/]pattern_to_match_folders")
sys.exit(0)
pattern=".".join(sys.argv[1:]) # list sub-folders in the folder
pat_base=os.path.basename(pattern) current_folders = [d for d in os.listdir(pat_dir) if os.path.isdir(os.path.join(pat_dir, d))]
pat_dir=os.path.dirname(pattern) current_folders = [d for d in current_folders if not d.startswith(".")]
current_folders.sort()
return current_folders
if pat_dir=="": def main():
pat_dir="." # Print help
if len(sys.argv) == 1 or sys.argv[-1] == "-h":
errexit("Guess cd: Find first match in folder, interactive if multiple matches\n Arguments: [dir/]pattern_to_match_folders")
if not os.path.exists(pat_dir): pattern = ".".join(sys.argv[1:])
printerr("%s: %sNo such folder%s"%(pat_dir,Red,Reset)) pat_base = os.path.basename(pattern)
sys.exit(1) pat_dir = os.path.dirname(pattern)
# list sub-folders in the folder if pat_dir == "":
current_folders=[d for d in os.listdir(pat_dir) if os.path.isdir(os.path.join(pat_dir,d))] pat_dir = "."
current_folders=[d for d in current_folders if not d.startswith(".")]
current_folders.sort()
# no sub-folders if not os.path.exists(pat_dir):
if len(current_folders)==0: errexit("%s: %sNo such folder%s"%(pat_dir, Red, Reset))
printerr("There are no subfolders in %s"%(pat_dir,))
sys.exit(0)
# find matches # list sub-folders in the folder
match_case=re.compile(".*"+pat_base+".*") current_folders = get_dirs(pat_dir)
repl_case=re.compile("("+pat_base+")")
matching_folders=[d for d in current_folders if match_case.match(d)] # no sub-folders
matches=colorize_matches(matching_folders, repl_case) if len(current_folders) == 0:
errexit("There are no subfolders in %s"%( pat_dir,))
# no matches, try case insensitive # find matches
if len(matching_folders)==0: match_case = re.compile(".*" + pat_base + ".*")
match_nocase=re.compile(".*"+pat_base+".*",re.I) repl_case = re.compile("(" + pat_base + ")")
repl_nocase=re.compile("("+pat_base+")",re.I)
matching_folders=[d for d in current_folders if match_nocase.match(d)]
matches=colorize_matches(matching_folders, repl_nocase)
# No matches, try close match matching_folders = [d for d in current_folders if match_case.match(d)]
if len(matching_folders)==0: matches = colorize_matches(matching_folders, repl_case)
matching_folders=search_close_match(current_folders, pat_base)
matches=[d for d in matching_folders]
# One match, print and return # no matches, try case insensitive
if len(matching_folders)==1: if len(matching_folders) == 0:
printerr(matches[0]) match_nocase = re.compile(".*" + pat_base + ".*",re.I)
print(os.path.join(pat_dir,matching_folders[0])) repl_nocase = re.compile("(" + pat_base + ")",re.I)
sys.exit(0) matching_folders = [d for d in current_folders if match_nocase.match(d)]
matches = colorize_matches(matching_folders, repl_nocase)
# Many matches, ask the user for folder index # No matches, try close match
for i,m in enumerate(matches[0:len(key_list)]): if len(matching_folders) == 0:
printerr(key_list[i]+": "+m) matching_folders = search_close_match(current_folders, pat_base)
if len(matches)>len(key_list): matches = [d for d in matching_folders]
printerr("Skipping the rest...")
import termios,tty # One match, print and return
ch=getch() if len(matching_folders) == 1:
key_in=ch.get() printerr(matches[0])
try: print(os.path.join(pat_dir, matching_folders[0]))
key_index=key_list.index(key_in) sys.exit(0)
key_match=matching_folders[key_index]
except (ValueError,IndexError) as err: # Many matches, ask the user for folder index
printerr("%s'%s' Not in the list%s"%(Red,key_in,Reset)) for i,m in enumerate(matches[0:len(key_list)]):
sys.exit(1) printerr(key_list[i] + ": " + m)
print(os.path.join(pat_dir,key_match))
if len(matches) > len(key_list):
printerr("Skipping the rest...")
key_in = getch().get()
try:
key_index = key_list.index(key_in)
key_match = matching_folders[key_index]
except (ValueError, IndexError) as err:
errexit("%s'%s' Not in the list%s"%(Red, key_in, Reset))
print(os.path.join(pat_dir, key_match))
if __name__ == "__main__":
main()