Advertisement
Guest User

Untitled

a guest
Mar 19th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.50 KB | None | 0 0
  1. import sys, os
  2. from argparse import ArgumentParser, FileType
  3. #------------------------------------------------------------------------------
  4.  
  5. GREEN = '\033[32m'
  6. PRETTY_GREEN = '\033[92m'
  7. END_COLOR = '\033[0m'
  8.  
  9. def index_find(pattern, string, ignore_case):
  10. """Find index of pattern match in string. Returns -1 if not found."""
  11. if ignore_case:
  12. pattern = pattern.lower()
  13. string = string.lower()
  14.  
  15. for i in range(len(string)):
  16. for j in range(len(pattern)):
  17. if string[i+j] != pattern[j]:
  18. break
  19. elif j == len(pattern) - 1:
  20. return i
  21. return -1
  22.  
  23. def color_find(pattern, string, ignore_case):
  24. """Find all matches of pattern in string. Returns colored string, or empty string if not found."""
  25. result = ''
  26. index = index_find(pattern, string, ignore_case)
  27.  
  28. while index != -1:
  29. result += string[:index]
  30. result += PRETTY_GREEN + string[index:index + len(pattern)] + END_COLOR
  31. string = string[index + len(pattern):]
  32. index = index_find(pattern, string, ignore_case)
  33.  
  34. return result if result == '' else result + string
  35.  
  36. def get_match(pattern, string, color, ignore_case):
  37. """Find the pattern in the string. Returns the match result or the empty string if not found."""
  38. if color:
  39. return color_find(pattern, string, ignore_case)
  40. else:
  41. index = index_find(pattern, string, ignore_case)
  42. return string if index != -1 else ''
  43.  
  44. def print_result(print_header, header, print_lineno, lineno, print_line, line):
  45. """Print result to standard output."""
  46. result = ''
  47. if print_header:
  48. result += '%s' % header
  49. if print_lineno:
  50. if len(result) > 0:
  51. result += ':'
  52. result += '%d' % lineno
  53. if print_line:
  54. if len(result) > 0:
  55. result += ':'
  56. result += line
  57. sys.stdout.write('%s' % result.strip('\n'))
  58.  
  59. def grep_file(filename, pattern, color, ignore_case, print_headers,
  60. print_lineno, print_lines):
  61. """Search a single file or standard input."""
  62. text = sys.stdin if filename == '(standard input)' else open(filename, 'r')
  63.  
  64. line = text.readline()
  65. lineno = 1
  66. while line:
  67. result = get_match(pattern, line, color, ignore_case)
  68. if len(result) > 0:
  69. print_result(print_headers, filename, print_lineno, lineno,
  70. print_lines, result)
  71. if print_headers and not print_lines: # files-with-matches option
  72. break
  73. line = text.readline()
  74. lineno += 1
  75.  
  76. text.close()
  77.  
  78. def grep_files(paths, pattern, recurse, color, ignore_case, print_headers,
  79. print_lineno, print_line):
  80. """Search files and directories."""
  81. for path in paths:
  82. if os.path.isfile(path) or path == '(standard input)':
  83. grep_file(path, pattern, color, ignore_case, print_headers,
  84. print_lineno, print_line)
  85. else:
  86. if recurse:
  87. more_paths = [path + '/' + child for child in os.listdir(path)]
  88. grep_files(more_paths, pattern, recurse, color, ignore_case,
  89. print_headers, print_lineno, print_line)
  90. else:
  91. sys.stdout.write('grep: %s: Is a directory\n' % path)
  92.  
  93. def setup_parser():
  94. """Configure command line argument parser object."""
  95. parser = ArgumentParser(description='Find matches of a pattern in ' \
  96. 'lines of file(s).', add_help=False)
  97. parser.add_argument('--help', action='help', help='show this help ' \
  98. 'message and exit')
  99. parser.add_argument('pattern', type=str, help='the pattern to find')
  100. parser.add_argument('files', metavar='FILES', nargs='*', default=['-'],
  101. help='the files(s) to search')
  102. parser.add_argument('--color', '--colour', action='store_true',
  103. help='highlight matches')
  104. parser.add_argument('-h', '--no-filename', action='store_true',
  105. help='print without filename headers')
  106. parser.add_argument('-i', '--ignore-case', action='store_true',
  107. help='case-insensitive search')
  108. parser.add_argument('-l', '--files-with-matches', action='store_true',
  109. help='print only filenames with matches')
  110. parser.add_argument('-n', '--line-number', action='store_true',
  111. help='print line numbers, indexed from 1')
  112. parser.add_argument('-R', '-r', '--recursive', action='store_true',
  113. help='recursively search directories')
  114. return parser
  115.  
  116. DEFAULT_PRINT_OPTIONS = (False, False, True)
  117.  
  118. def main():
  119. #sys.argv = ['-r', 'dicks']
  120. # parser = setup_parser()
  121. # args = parser.parse_args()
  122. # pattern = args.pattern
  123. # files = [f if f!= '-' else '(standard input)' for f in args.files]
  124.  
  125. #print_headers, print_lineno, print_lines = DEFAULT_PRINT_OPTIONS
  126. #if args.files_with_matches:
  127. # print_headers = True
  128. # print_lines = False
  129. #else:
  130. # if args.recursive or len(files) > 1:
  131. # print_headers = True
  132. # if args.line_number:
  133. # print_lineno = True
  134. # if args.no_filename:
  135. # print_headers = False
  136.  
  137. grep_files('.', 'token', True, False, False,
  138. True, True, True)
  139. print "it works but doesn't find shit for some reason\n";
  140.  
  141. if __name__ == '__main__':
  142. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement