import sys import os import subprocess 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=""): print("set "+name+" "+options+" \""+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 file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 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.")