Analysis Software
Documentation for sPHENIX simulation software
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
filter.py
Go to the documentation of this file. Or view the newest version in sPHENIX GitHub for file filter.py
1 import sys
2 import yaml
3 import re
4 import argparse
5 from collections import namedtuple
6 
7 
8 Config = namedtuple(
9  "Config", ["remove_lines", "replace_lines", "ignore_files"], defaults=[[], [], []]
10 )
11 
12 
13 class State:
14  skip_file: bool = False
15 
16 
17 def parse_config(config: Config):
18  remove_lines = []
19  for s in config["remove_lines"]:
20  remove_lines.append(re.compile(s))
21 
22  replace_lines = []
23  for s in config["replace_lines"]:
24  s, r = list(s.items())[0]
25  replace_lines.append((re.compile(s), r))
26 
27  ignore_files = []
28  for s in config["ignore_files"]:
29  ignore_files.append(re.compile(s))
30 
31  return Config(
32  remove_lines=remove_lines,
33  replace_lines=replace_lines,
34  ignore_files=ignore_files,
35  )
36 
37 
38 def filter(line: str, config: Config, state: State):
39  if state.skip_file:
40  if line.endswith("---\n"):
41  state.skip_file = False
42  return None
43 
44  if line.endswith(" should add these lines:\n"):
45  for s in config.ignore_files:
46  if s.search(line):
47  state.skip_file = True
48  return None
49 
50  for s in config.remove_lines:
51  if s.search(line):
52  return None
53 
54  for s, r in config.replace_lines:
55  if s.search(line):
56  return s.sub(r, line)
57 
58  return line
59 
60 
61 parser = argparse.ArgumentParser()
62 parser.add_argument("config")
63 parser.add_argument("input")
64 parser.add_argument("output")
65 args = parser.parse_args()
66 
67 with open(args.config, "r") as config_file:
68  try:
69  config = yaml.safe_load(config_file)
70  config = parse_config(config)
71  except yaml.YAMLError as exc:
72  print(exc)
73  sys.exit(1)
74 
75 with open(args.input, "r") as input_file, open(args.output, "w") as output_file:
76  state = State()
77 
78  for line in input_file:
79  filtered_line = filter(line, config, state)
80  if filtered_line is not None:
81  output_file.write(filtered_line)
82 
83 sys.exit(0)