From 9ef6c039983e7fa60dd25fb11fbbd32d492a176d Mon Sep 17 00:00:00 2001 From: glmdev Date: Wed, 28 Nov 2018 21:49:27 -0600 Subject: [PATCH] add support for custom path locators --- do_what.py | 30 ++++++++++++++++++++++-------- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/do_what.py b/do_what.py index 5ebc87e..e3ee5df 100644 --- a/do_what.py +++ b/do_what.py @@ -14,6 +14,7 @@ list_directory="ls --color=auto" change_dir="cd" print_dir="pwd" help_command="man" +path_locator="which" # general function for setting a shell's environment variable def set_runtime_var(name, value, options=""): @@ -34,8 +35,20 @@ def is_binary_file(filepathname): # check if a given program is in the path environment using which def env_has(program): - whichcall = subprocess.Popen(['which', program], stdout=subprocess.PIPE) - return whichcall.returncode + def is_exe(fpath): + return os.path.isfile(fpath) and os.access(fpath, os.X_OK) + + fpath, fname = os.path.split(program) + if fpath: + if is_exe(program): + return True + else: + for path in os.environ["PATH"].split(os.pathsep): + exe_file = os.path.join(path, program) + if is_exe(exe_file): + return True + + return None # get the number of lines in a file def file_len(fname): @@ -62,6 +75,8 @@ if ( os.path.isfile(ENV_HOME+'/.config/do_what/what.config') ): list_directory = config['DEFAULT']['list_directory'] if ( 'help_command' in config['DEFAULT'] ): help_command = config['DEFAULT']['help_command'] + if ( 'path_locator' in config['DEFAULT'] ): + path_locator = config['DEFAULT']['path_locator'] else: config = configparser.ConfigParser() config['DEFAULT'] = { @@ -70,6 +85,7 @@ else: 'pretty_print_file': pretty_print_file, 'print_file': print_file, 'help_command': help_command, + 'path_locator': path_locator, } print("echo Default config loaded.") with open(ENV_HOME+'/.config/do_what/what.config', 'w') as configfile: @@ -129,14 +145,12 @@ elif ( (not active and len(sys.argv) == 2) or (active and len(sys.argv) == 3) ): else: # check if file is a path program, then list using which/man on active - whichcall = subprocess.Popen(['which', filearg], stdout=subprocess.PIPE) - result = whichcall.communicate()[0] - statuscode = whichcall.returncode + path_has = env_has(filearg) # print the location of the program - if ( int(statuscode) == 0 and not active ): - print("echo "+result.decode('utf-8')) + if ( path_has and not active ): + print(path_locator+" "+filearg) # display the help page for the program (active) - elif ( int(statuscode) == 0 and active ): + elif ( path_has and active ): print(help_command+" "+filearg) else: print("echo Unknown file/directory.")