File: generate_histograms_variants_allowlist.py

package info (click to toggle)
chromium 120.0.6099.224-1~deb11u1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 6,112,112 kB
  • sloc: cpp: 32,907,025; ansic: 8,148,123; javascript: 3,679,536; python: 2,031,248; asm: 959,718; java: 804,675; xml: 617,256; sh: 111,417; objc: 100,835; perl: 88,443; cs: 53,032; makefile: 29,579; fortran: 24,137; php: 21,162; tcl: 21,147; sql: 20,809; ruby: 17,735; pascal: 12,864; yacc: 8,045; lisp: 3,388; lex: 1,323; ada: 727; awk: 329; jsp: 267; csh: 117; exp: 43; sed: 37
file content (170 lines) | stat: -rwxr-xr-x 5,789 bytes parent folder | download
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
#!/usr/bin/env python
# Copyright 2023 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import argparse
import os
import sys

import extract_histograms
import xml.dom.minidom

_SCRIPT_NAME = "generate_histograms_variants_allowlist.py"
_HEADER = """// Generated from {script_name}. Do not edit!

#ifndef {include_guard}
#define {include_guard}

namespace {namespace} {{

extern const char* k{variant_name}VariantAllowList[];

}}  // namespace {namespace}

#endif  // {include_guard}
"""
_SOURCE = """// Generated from {script_name}. Do not edit!
#include "{header_filepath}"

namespace {namespace} {{

const char* k{variant_name}VariantAllowList[] = {{
{variants}
}};

}}  // namespace {namespace}
"""


class Error(Exception):
  pass


def _GenerateHeaderFileContent(header_filename, namespace, allow_list_name):
  """Generates header file content.

  Args:
    header_filename: A filename of the generated header file.
    namespace: A namespace to contain generated array.
    allow_list_name: A name of the variant list for an allow list.
  Returns:
    String with the generated content.
  """
  include_guard = header_filename.replace('\\', '_').replace('/', '_').replace(
      '.', '_').upper() + "_"

  return _HEADER.format(script_name=_SCRIPT_NAME,
                        include_guard=include_guard,
                        namespace=namespace,
                        variant_name=allow_list_name)


def _GenerateSourceFileContent(header_filename, namespace, variant_list,
                               allow_list_name):
  """Generates source file content.

  Args:
    source_filename: A filename of the generated source file.
    namespace: A namespace to contain generated array.
    variant_list(List[Dict]]):
      A list of variant objects [{variant: {name, summary, ...}}]
    allow_list_name: A name of the variant list for an allow list.
  Returns:
    String with the generated content.
  """
  variant_list = sorted(variant_list, key=lambda d: d['name'])

  variants = "\n".join(
      ["  \"{name}\",".format(name=value['name']) for value in variant_list])
  return _SOURCE.format(script_name=_SCRIPT_NAME,
                        header_filepath=header_filename,
                        namespace=namespace,
                        variants=variants,
                        variant_name=allow_list_name)


def _GenerateVariantList(histograms, allow_list_name):
  all_variants, had_errors = extract_histograms.ExtractVariantsFromXmlTree(
      histograms)
  if had_errors:
    raise Error("Error parsing inputs.")

  if (allow_list_name not in all_variants):
    raise Error("AllowListName is missing in variants list")

  return all_variants[allow_list_name]


def _GenerateFile(arguments):
  """Generates header file containing array with Variant names.

  Args:
    arguments: An object with the following attributes:
      arguments.input: An xml file with histogram descriptions.
      arguments.header_filename: A filename of the generated header file.
      arguments.source_filename: A filename of the generated source file.
      arguments.namespace: A namespace to contain generated array.
      arguments.output_dir: A directory to put the generated file.
      arguments.allow_list_name: A name of the variant list for an allow list.
  """
  histograms = xml.dom.minidom.parse(arguments.input)
  variants = _GenerateVariantList(histograms, arguments.allow_list_name)

  # Write the header file.
  header_file_content = _GenerateHeaderFileContent(arguments.header_filename,
                                                   arguments.namespace,
                                                   arguments.allow_list_name)

  with open(os.path.join(arguments.output_dir, arguments.header_filename),
            "w") as generated_file:
    generated_file.write(header_file_content)

  # Write the source file.
  source_file_content = _GenerateSourceFileContent(arguments.header_filename,
                                                   arguments.namespace,
                                                   variants,
                                                   arguments.allow_list_name)
  with open(os.path.join(arguments.output_dir, arguments.source_filename),
            "w") as generated_file:
    generated_file.write(source_file_content)


def _ParseArguments():
  """Defines and parses arguments from the command line."""
  arg_parser = argparse.ArgumentParser(
      description="Generate an array of AllowList based on variants.")
  arg_parser.add_argument("--output_dir",
                          "-o",
                          required=True,
                          help="Base directory to for generated files.")
  arg_parser.add_argument("--header_filename",
                          "-H",
                          required=True,
                          help="File name of the generated header file.")
  arg_parser.add_argument("--source_filename",
                          "-s",
                          required=True,
                          help="File name of the generated source file.")
  arg_parser.add_argument(
      "--allow_list_name",
      "-a",
      required=True,
      help="Name of variant list that should be part of the allow list.")
  arg_parser.add_argument("--namespace",
                          "-n",
                          required=True,
                          help="Namespace of the allow list array.")
  arg_parser.add_argument("--input",
                          "-f",
                          help="Path to .xml file with histogram descriptions.")
  return arg_parser.parse_args()


def main():
  arguments = _ParseArguments()
  _GenerateFile(arguments)


if __name__ == "__main__":
  sys.exit(main())