clean_logs.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. import glob, re, os.path, textwrap
  2. from colorama import Fore, Back, Style
  3. def target_prefix(dir):
  4. if dir.startswith("net"):
  5. return "net"
  6. elif dir.startswith("serial"):
  7. return "serial"
  8. elif dir.startswith("util"):
  9. return "util"
  10. elif dir.startswith("runtime"):
  11. return "runtime"
  12. elif dir.startswith("zk"):
  13. return "zk"
  14. elif dir.startswith("raft"):
  15. return "raft"
  16. elif dir.startswith("sdk/src/crypto"):
  17. return "sdk::crypto"
  18. elif dir.startswith("sdk"):
  19. return "sdk"
  20. elif dir.startswith("contract/dao"):
  21. return "dao"
  22. elif dir.startswith("contract/money"):
  23. return "money"
  24. elif dir.startswith("rpc"):
  25. return "rpc"
  26. elif dir.startswith("system"):
  27. return "system"
  28. elif dir.startswith("dht"):
  29. return "dht"
  30. elif dir.startswith("consensus"):
  31. return "consensus"
  32. elif dir.startswith("zkas"):
  33. return "zkas"
  34. elif dir.startswith("blockchain"):
  35. return "blockchain"
  36. elif dir.startswith("wallet"):
  37. return "wallet"
  38. else:
  39. assert not dir or dir == "tx"
  40. return ""
  41. def target_suffix(prefix, base):
  42. if prefix in ("dao", "money"):
  43. # Just shorten the target to simply "dao" or "money"
  44. # We don't need the fine grained details
  45. return ""
  46. elif base in ("mod.rs", "lib.rs"):
  47. # Just use the module name as the target with these files
  48. return ""
  49. # Otherwise just use the filename as the target suffix
  50. return base.removesuffix(".rs")
  51. def log_target(fname):
  52. dir, base = os.path.dirname(fname), os.path.basename(fname)
  53. prefix = target_prefix(dir)
  54. suffix = target_suffix(prefix, base)
  55. # you don't need :: when the suffix is empty
  56. if not suffix and not prefix:
  57. return ""
  58. if not suffix:
  59. return prefix
  60. if not prefix:
  61. return suffix
  62. return f"{prefix}::{suffix}"
  63. def replace(fname, contents):
  64. target = log_target(fname)
  65. # You can debug like this:
  66. #if target != "consensus::proposal":
  67. # return ""
  68. print(f"Replacing {target}" + " "*(40 - len(target)) + f"[{fname}]")
  69. result = ""
  70. lines = contents.split("\n")
  71. i = 0
  72. while i < len(lines):
  73. line = lines[i]
  74. # Line number
  75. ln = lambda: i + 1
  76. # only used for debug output
  77. old_text = None
  78. new_text = None
  79. # This is used as a debug goto
  80. is_modified = False
  81. log_level = None
  82. if "trace!(" in line:
  83. log_level = "trace"
  84. elif "debug!(" in line:
  85. log_level = "debug"
  86. elif "info!(" in line:
  87. log_level = "info"
  88. elif "warn!(" in line:
  89. log_level = "warn"
  90. elif "error!(" in line:
  91. log_level = "error"
  92. if log_level is not None:
  93. # Walk backwards to find the function name
  94. # Range is (i, 0]
  95. function_name = None
  96. for j in range(i - 1, -1, -1):
  97. past_line = lines[j]
  98. if (match := re.search(
  99. f"fn ([a-zA-Z0-9_]+)(<[a-zA-Z: +']+>)?\\(",
  100. past_line
  101. )):
  102. function_name = match.group(1)
  103. break
  104. assert function_name is not None
  105. if target in (
  106. "consensus::protocol_proposal",
  107. "consensus::protocol_sync",
  108. "consensus::protocol_sync_consensus",
  109. "consensus::protocol_tx",
  110. "runtime::db",
  111. "net::hosts",
  112. "net::protocol_address",
  113. "net::protocol_ping",
  114. "net::protocol_seed",
  115. "net::protocol_version",
  116. "net::p2p",
  117. ):
  118. target += f"::{function_name}()"
  119. # No target exists for this file at all. Just ignore these
  120. # We would normally delete any target set for these files
  121. # but so far we have none of them, so just ignore them.
  122. if not target:
  123. print(
  124. " "
  125. + Back.RED + "Skip [no target]:" + Style.RESET_ALL
  126. + f" {line}"
  127. )
  128. # Single lines with a target that's a constant or string
  129. elif re.search(f'{log_level}!\\(target: ([A-Z_]+|"[a-zA-Z:_-]+"),', line):
  130. old_text = f"{ln()}: {line}"
  131. line = re.sub(
  132. 'target: ([A-Z_]+|"[a-zA-Z:_-]+"),',
  133. f'target: "{target}",',
  134. line
  135. )
  136. is_modified = True
  137. new_text = f"{ln()}: {line}"
  138. # Normal single lines with no target set
  139. elif f'{log_level}!("' in line:
  140. old_text = f"{ln()}: {line}"
  141. #print(f" No target: {line}")
  142. line = line.replace(f'{log_level}!(',
  143. f'{log_level}!(target: "{target}", ')
  144. is_modified = True
  145. new_text = f"{ln()}: {line}"
  146. # Multiline logs
  147. # We read the next line and check if there's a target set or not
  148. else:
  149. assert re.search(f"{log_level}!\\($", line)
  150. old_text = f"{ln()}: {line}"
  151. new_text = f"{ln()}: {line}"
  152. result += line + "\n"
  153. i += 1
  154. assert i < len(lines)
  155. line = lines[i]
  156. old_text += f"\n{ln()}: {line}"
  157. # Constants or target strings set
  158. if re.search('target: ([A-Z_]+|"[a-zA-Z:_-]+"),', line):
  159. line = re.sub(
  160. 'target: ([A-Z_]+|"[a-zA-Z:_-]+"),',
  161. f'target: "{target}",',
  162. line
  163. )
  164. new_text += f"\n{ln()}: {line}"
  165. # Multi-line logs with no target set
  166. # Insert an extra line with the target
  167. else:
  168. leading_space = lambda line: len(line) - len(line.lstrip())
  169. added_line = (" "*leading_space(line)
  170. + f'target: "{target}",')
  171. result += f"{added_line}\n"
  172. new_text += f"\n{ln()}: {added_line}\n{ln() + 1}: {line}"
  173. is_modified = True
  174. if is_modified:
  175. assert old_text is not None and new_text is not None
  176. print(
  177. Fore.RED
  178. + textwrap.indent(old_text, " < ")
  179. + Style.RESET_ALL
  180. )
  181. print(
  182. Fore.GREEN
  183. + textwrap.indent(new_text, " > ")
  184. + Style.RESET_ALL
  185. )
  186. print()
  187. result += f"{line}\n"
  188. i += 1
  189. return result
  190. def main():
  191. for fname in glob.glob("**/*.rs", root_dir="src/", recursive=True):
  192. with open(f"src/{fname}", "r") as f:
  193. contents = f.read()
  194. contents = replace(fname, contents)
  195. # Uncomment this to apply the changes
  196. #with open(f"src/{fname}", "w") as f:
  197. # f.write(contents)
  198. if __name__ == "__main__":
  199. main()