1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
|
"""YAML Summariser
The flang plugin ``flang-omp-report`` takes one Fortran
file in and returns a YAML report file of the input file.
This becomes an issue when you want to analyse an entire project
into one final report.
The purpose of this Python script is to generate a final YAML
summary from all of the files generated by ``flang-omp-report``.
Currently, it requires ``ruamel.yaml``,
which can be installed with:
``pip3 install ruamel.yaml``
By default it scans the directory it is ran in
for any YAML files and outputs a summary to
stdout. It can be ran as:
``python3 yaml_summarizer.py``
Parameters:
-d --directory Specify which directory to scan. Multiple directories can be searched by
providing a semicolon seperated list of directories.
-l --log Combine all yaml files into one log (instead of generating a summary)
-o --output Specify a directory in which to save the summary file
-r --recursive Recursively search directory for all yaml files
Examples:
``python3 yaml_summarizer.py -d ~/llvm-project/build/ -r``
``python3 yaml_summarizer.py -d "~/llvm-project/build/;~/llvm-project/flang/test/Examples"``
``python3 yaml_summarizer.py -l -o ~/examples/report.yaml``
Pseudo-examples:
Summary:
$ python3 yaml_summarizer.py file_1.yaml file_2.yaml
<Unique OMP constructs with there grouped clauses from file_1.yaml and file_2.yaml>
Constructs are in the form:
- construct: someOMPconstruct
count: 8
clauses:
- clause: clauseOne
count: 4
- clause: ClauseTwo
count: 2
Log:
$ python3 yaml_summarizer.py -l file_1.yaml file_2.yaml
file_1.yaml
<OMP clauses and constructs from file_1.yaml>
file_2.yaml
<OMP clauses and constructs from file_2.yaml>
Constructs are in the form:
- construct: someOMPConstruct
line: 12
clauses:
- clause: clauseOne
details: 'someDetailForClause'
"""
import sys
import glob
import argparse
from pathlib import Path
from os.path import isdir
from ruamel.yaml import YAML
def find_yaml_files(search_directory: Path, search_pattern: str):
"""
Find all '.yaml' files and returns an iglob iterator to them.
Keyword arguments:
search_pattern -- Search pattern for 'iglob' to use for finding '.yaml' files.
If this is set to 'None', then it will default to just searching
for all '.yaml' files in the current directory.
"""
# @TODO: Currently *all* yaml files are read - regardless of whether they have
# been generated with 'flang-omp-report' or not. This might result in the script
# reading files that it should ignore.
if search_directory:
return glob.iglob(
str(search_directory.joinpath(search_pattern)), recursive=True
)
return glob.iglob(str("/" + search_pattern), recursive=True)
def process_log(data, result: list):
"""
Process the data input as a 'log' to the result array. This esssentially just
stitches together all of the input '.yaml' files into one result.
Keyword arguments:
data -- Data from yaml.load() for a yaml file. So the type can be 'Any'.
result -- Array to add the processed data to.
"""
for datum in data:
items = result.get(datum["file"], [])
items.append(
{
"construct": datum["construct"],
"line": datum["line"],
"clauses": datum["clauses"],
}
)
result[datum["file"]] = items
def add_clause(datum, construct):
"""
Add clauses to the construct if they're missing
Otherwise increment their count by one.
Keyword arguments:
datum -- Data construct containing clauses to check.
construct -- Construct to add or increment clause count.
"""
to_check = [i["clause"] for i in construct["clauses"]]
to_add = [i["clause"] for i in datum["clauses"]]
clauses = construct["clauses"]
for item in to_add:
if item in to_check:
for clause in clauses:
if clause["clause"] == item:
clause["count"] += 1
else:
clauses.append({"clause": item, "count": 1})
def process_summary(data, result: dict):
"""
Process the data input as a 'summary' to the 'result' dictionary.
Keyword arguments:
data -- Data from yaml.load() for a yaml file. So the type can be 'Any'.
result -- Dictionary to add the processed data to.
"""
for datum in data:
construct = next(
(item for item in result if item["construct"] == datum["construct"]), None
)
clauses = []
# Add the construct and clauses to the summary if
# they haven't been seen before
if not construct:
for i in datum["clauses"]:
clauses.append({"clause": i["clause"], "count": 1})
result.append(
{"construct": datum["construct"], "count": 1, "clauses": clauses}
)
else:
construct["count"] += 1
add_clause(datum, construct)
def clean_summary(result):
"""Cleans the result after processing the yaml files with summary format."""
# Remove all "clauses" that are empty to keep things compact
for construct in result:
if construct["clauses"] == []:
construct.pop("clauses")
def clean_log(result):
"""Cleans the result after processing the yaml files with log format."""
for constructs in result.values():
for construct in constructs:
if construct["clauses"] == []:
construct.pop("clauses")
def output_result(yaml: YAML, result, output_file: Path):
"""
Outputs result to either 'stdout' or to a output file.
Keyword arguments:
result -- Format result to output.
output_file -- File to output result to. If this is 'None' then result will be
outputted to 'stdout'.
"""
if output_file:
with open(output_file, "w+", encoding="utf-8") as file:
if output_file.suffix == ".yaml":
yaml.dump(result, file)
else:
file.write(result)
else:
yaml.dump(result, sys.stdout)
def process_yaml(
search_directories: list, search_pattern: str, result_format: str, output_file: Path
):
"""
Reads each yaml file, calls the appropiate format function for
the file and then ouputs the result to either 'stdout' or to an output file.
Keyword arguments:
search_directories -- List of directory paths to search for '.yaml' files in.
search_pattern -- String pattern formatted for use with glob.iglob to find all
'.yaml' files.
result_format -- String representing output format. Current supported strings are: 'log'.
output_file -- Path to output file (If value is None, then default to outputting to 'stdout').
"""
if result_format == "log":
result = {}
action = process_log
clean_report = clean_log
else:
result = []
action = process_summary
clean_report = clean_summary
yaml = YAML()
for search_directory in search_directories:
for file in find_yaml_files(search_directory, search_pattern):
with open(file, "r", encoding="utf-8") as yaml_file:
data = yaml.load(yaml_file)
action(data, result)
if clean_report is not None:
clean_report(result)
output_result(yaml, result, output_file)
def create_arg_parser():
"""Create and return a argparse.ArgumentParser modified for script."""
parser = argparse.ArgumentParser()
parser.add_argument(
"-d", "--directory", help="Specify a directory to scan", dest="dir", type=str
)
parser.add_argument(
"-o",
"--output",
help="Writes to a file instead of\
stdout",
dest="output",
type=str,
)
parser.add_argument(
"-r",
"--recursive",
help="Recursive search for .yaml files",
dest="recursive",
type=bool,
nargs="?",
const=True,
default=False,
)
exclusive_parser = parser.add_mutually_exclusive_group()
exclusive_parser.add_argument(
"-l",
"--log",
help="Modifies report format: " "Combines the log '.yaml' files into one file.",
action="store_true",
dest="log",
)
return parser
def parse_arguments():
"""Parses arguments given to script and returns a tuple of processed arguments."""
parser = create_arg_parser()
args = parser.parse_args()
if args.dir:
search_directory = [Path(path) for path in args.dir.split(";")]
else:
search_directory = [Path.cwd()]
if args.recursive:
search_pattern = "**/*.yaml"
else:
search_pattern = "*.yaml"
if args.log:
result_format = "log"
else:
result_format = "summary"
if args.output:
if isdir(args.output):
output_file = Path(args.output).joinpath("summary.yaml")
elif isdir(Path(args.output).resolve().parent):
output_file = Path(args.output)
else:
output_file = None
return (search_directory, search_pattern, result_format, output_file)
def main():
"""Main function of script."""
(search_directory, search_pattern, result_format, output_file) = parse_arguments()
process_yaml(search_directory, search_pattern, result_format, output_file)
return 0
if __name__ == "__main__":
sys.exit(main())
|