import sys import os import subprocess import configparser # supported values: fish, bash shell="fish" print_file="cat" pretty_print_file="less -R" edit_file="vim" list_directory="ls --color=auto" def set_runtime_var(name, value, options=""): if ( shell == "fish" ): print("set "+name+" "+options+" \""+value+"\"") elif ( shell == "bash" ): print("export "+name+"="+"\""+value+"\"") def is_binary_file(filepathname): textchars = bytearray([7,8,9,10,12,13,27]) + bytearray(range(0x20, 0x7f)) + bytearray(range(0x80, 0x100)) is_binary_string = lambda bytes: bool(bytes.translate(None, textchars)) if is_binary_string(open(filepathname, 'rb').read(1024)): return True else: return False def env_has(program): whichcall = subprocess.Popen(['which', program], stdout=subprocess.PIPE) return whichcall.returncode def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 # bootstrap the config ENV_HOME=os.environ['HOME'] subprocess.call(['mkdir', '-p', ENV_HOME+'/.config']) if ( os.path.isfile(ENV_HOME+'/.config/what.config') ): config = configparser.ConfigParser() config.read(ENV_HOME+'/.config/what.config') if ( 'DEFAULT' in config ): if ( 'print_file' in config['DEFAULT'] ): print_file = config['DEFAULT']['print_file'] if ( 'pretty_print_file' in config['DEFAULT'] ): pretty_print_file = config['DEFAULT']['pretty_print_file'] if ( 'edit_file' in config['DEFAULT'] ): pretty_print_file = config['DEFAULT']['edit_file'] if ( 'list_directory' in config['DEFAULT'] ): list_directory = config['DEFAULT']['list_directory'] else: config = configparser.ConfigParser() config['DEFAULT'] = { 'list_directory': list_directory, 'edit_file': edit_file, 'pretty_print_file': pretty_print_file, 'print_file': print_file } print("echo Default config loaded.") with open(ENV_HOME+'/.config/what.config', 'w') as configfile: config.write(configfile) configfile.close() if ( len(sys.argv) == 1 ): # list the contents of the current directory print(list_directory) elif ( len(sys.argv) == 2 ): # absolutize the path for Python filearg = sys.argv[1] path = sys.argv[1] if ( path[0] != "/" and path[0] != "~" and path[0] != "." ): path = os.getcwd()+"/"+path # check if path is a file or directory if ( os.path.isdir(path) ): print(list_directory+" "+path) elif ( os.path.isfile(path) ): # check if file is binary if ( is_binary_file(path) ): print("echo Binary file.") else: trows, tcolumns = os.popen('stty size', 'r').read().split() if ( int(trows) - 5 < int(file_len(path)) ): set_runtime_var('LESSOPEN', '| /usr/share/source-highlight/src-hilite-lesspipe.sh %s') set_runtime_var('LESS', ' -R ') print(pretty_print_file+" "+path) else: print(print_file+" "+path) else: # check if file is a path program, then list using which whichcall = subprocess.Popen(['which', filearg], stdout=subprocess.PIPE) result = whichcall.communicate()[0] statuscode = whichcall.returncode if ( int(statuscode) == 0 ): print("echo "+filearg+": "+result.decode('utf-8')) else: print("echo Unknown file.")