Aucune description

test_wrappers.py 5.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. import re
  2. import json
  3. def parse_nested_param(string, level):
  4. """
  5. Generate strings contained in nested (), indexing i = level
  6. """
  7. if len(re.findall("\(", string)) == len(re.findall("\)", string)):
  8. LeftRightIndex = [x for x in zip(
  9. [Left.start()+1 for Left in re.finditer('\(', string)],
  10. reversed([Right.start() for Right in re.finditer('\)', string)]))]
  11. elif len(re.findall("\(", string)) > len(re.findall("\)", string)):
  12. return parse_nested_param(string + ')', level)
  13. elif len(re.findall("\(", string)) < len(re.findall("\)", string)):
  14. return parse_nested_param('(' + string, level)
  15. else:
  16. return 'Failed to parse params'
  17. try:
  18. return [string[LeftRightIndex[level][0]:LeftRightIndex[level][1]]]
  19. except IndexError:
  20. return [string[LeftRightIndex[level+1][0]:LeftRightIndex[level+1][1]]]
  21. # Parses the deepest part
  22. def maxDepth(S):
  23. current_max = 0
  24. max = 0
  25. n = len(S)
  26. # Traverse the input string
  27. for i in range(n):
  28. if S[i] == '(':
  29. current_max += 1
  30. if current_max > max:
  31. max = current_max
  32. elif S[i] == ')':
  33. if current_max > 0:
  34. current_max -= 1
  35. else:
  36. return -1
  37. # finally check for unbalanced string
  38. if current_max != 0:
  39. return -1
  40. return max-1
  41. def parse_type(data, thistype):
  42. if data == None:
  43. return "Empty"
  44. if "int" in thistype:
  45. try:
  46. return int(data)
  47. except ValueError:
  48. print("ValueError while casting %s" % data)
  49. return data
  50. if "lower" in thistype:
  51. return data.lower()
  52. if "upper" in thistype:
  53. return data.upper()
  54. if "trim" in thistype:
  55. return data.strip()
  56. if "strip" in thistype:
  57. return data.strip()
  58. if "split" in thistype:
  59. # Should be able to split anything
  60. return data.split()
  61. if "len" in thistype or "length" in thistype:
  62. return len(data)
  63. if "parse" in thistype:
  64. splitvalues = []
  65. default_error = """Error. Expected syntax: parse(["hello","test1"],0:1)"""
  66. if "," in data:
  67. splitvalues = data.split(",")
  68. for item in range(len(splitvalues)):
  69. splitvalues[item] = splitvalues[item].strip()
  70. else:
  71. return default_error
  72. lastsplit = []
  73. if ":" in splitvalues[-1]:
  74. lastsplit = splitvalues[-1].split(":")
  75. else:
  76. try:
  77. lastsplit = [int(splitvalues[-1])]
  78. except ValueError:
  79. return default_error
  80. try:
  81. parsedlist = ",".join(splitvalues[0:-1])
  82. print(parsedlist)
  83. print(lastsplit)
  84. if len(lastsplit) > 1:
  85. tmp = json.loads(parsedlist)[int(lastsplit[0]):int(lastsplit[1])]
  86. else:
  87. tmp = json.loads(parsedlist)[lastsplit[0]]
  88. print(tmp)
  89. return tmp
  90. except IndexError as e:
  91. return default_error
  92. # Parses the INNER value and recurses until everything is done
  93. def parse_wrapper(data):
  94. try:
  95. if "(" not in data or ")" not in data:
  96. return data
  97. except TypeError:
  98. return data
  99. print("Running %s" % data)
  100. # Look for the INNER wrapper first, then move out
  101. wrappers = ["int", "number", "lower", "upper", "trim", "strip", "split", "parse", "len", "length"]
  102. found = False
  103. for wrapper in wrappers:
  104. if wrapper not in data.lower():
  105. continue
  106. found = True
  107. break
  108. if not found:
  109. return data
  110. # Do stuff here.
  111. innervalue = parse_nested_param(data, maxDepth(data)-0)
  112. outervalue = parse_nested_param(data, maxDepth(data)-1)
  113. print("INNER: ", outervalue)
  114. print("OUTER: ", outervalue)
  115. if outervalue != innervalue:
  116. #print("Outer: ", outervalue, " inner: ", innervalue)
  117. for key in range(len(innervalue)):
  118. # Replace OUTERVALUE[key] with INNERVALUE[key] in data.
  119. print("Replace %s with %s in %s" % (outervalue[key], innervalue[key], data))
  120. data = data.replace(outervalue[key], innervalue[key])
  121. else:
  122. for thistype in wrappers:
  123. if thistype not in data.lower():
  124. continue
  125. parsed_value = parse_type(innervalue[0], thistype)
  126. return parsed_value
  127. print("DATA: %s\n" % data)
  128. return parse_wrapper(data)
  129. def parse_wrapper_start(data):
  130. newdata = []
  131. newstring = ""
  132. record = True
  133. paranCnt = 0
  134. for char in data:
  135. if char == "(":
  136. paranCnt += 1
  137. if not record:
  138. record = True
  139. if record:
  140. newstring += char
  141. if paranCnt == 0 and char == " ":
  142. newdata.append(newstring)
  143. newstring = ""
  144. record = True
  145. if char == ")":
  146. paranCnt -= 1
  147. if paranCnt == 0:
  148. record = False
  149. if len(newstring) > 0:
  150. newdata.append(newstring)
  151. parsedlist = []
  152. non_string = False
  153. for item in newdata:
  154. ret = parse_wrapper(item)
  155. if not isinstance(ret, str):
  156. non_string = True
  157. parsedlist.append(ret)
  158. if len(parsedlist) > 0 and not non_string:
  159. return " ".join(parsedlist)
  160. elif len(parsedlist) == 1 and non_string:
  161. return parsedlist[0]
  162. else:
  163. print("Casting back to string because multi: ", parsedlist)
  164. newlist = []
  165. for item in parsedlist:
  166. try:
  167. newlist.append(str(item))
  168. except ValueError:
  169. newlist.append("parsing_error")
  170. return " ".join(newlist)
  171. data = "split(hello there)"
  172. data = """parse(["testing", "what", "is this"], 0:2)"""
  173. #data = "int(int(2))"
  174. print("RET: ", parse_wrapper_start(data))