File: generate_allowlist_from_histograms_file.py

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (146 lines) | stat: -rwxr-xr-x 4,754 bytes parent folder | download | duplicates (8)
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
#!/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_allowlist_from_histograms_file.py"
_FILE = """// Generated from {script_name}. Do not edit!

#ifndef {include_guard}
#define {include_guard}

#include <algorithm>
#include <string_view>

namespace {namespace} {{

inline constexpr std::string_view k{allow_list_name}AllowList[] = {{
{values}
}};

constexpr bool IsValid{allow_list_name}(std::string_view s) {{
  return std::binary_search(
    std::cbegin(k{allow_list_name}AllowList),
    std::cend(k{allow_list_name}AllowList),
    s);
}}

}}  // namespace {namespace}

#endif  // {include_guard}
"""


class Error(Exception):
  pass


def _GenerateStaticFile(file_path, namespace, values, allow_list_name):
  """Generates a header file with constexpr facilities to check for the
    existence of a variant or enum in a histograms.xml file.

  Args:
    namespace: A namespace to contain generated array.
    values(List[str|int]]): A list of variant or enum values.
    allow_list_name: A name of the variant list for an allow list.
  Returns:
    String with the generated header file content.
  """
  values = sorted(values, key=lambda d: str(d))
  include_guard = file_path.replace('\\', '_').replace('/', '_').replace(
      '.', '_').upper() + "_"

  values_string = "\n".join(
      ["  \"{name}\",".format(name=value) for value in values])
  return _FILE.format(script_name=_SCRIPT_NAME,
                      include_guard=include_guard,
                      namespace=namespace,
                      values=values_string,
                      allow_list_name=allow_list_name)


def _GenerateValueList(histograms, tag, allow_list_name):
  if tag == "variant":
    values, had_errors = extract_histograms.ExtractVariantsFromXmlTree(
        histograms)
  elif tag == "enum":
    values, had_errors = extract_histograms.ExtractEnumsFromXmlTree(histograms)
  else:
    raise Error("'tag' must be either 'variant' or 'enum'")

  if had_errors:
    raise Error("Error parsing inputs.")

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

  if tag == "variant":
    return [value["name"] for value in values[allow_list_name]]
  else:
    return list(values[allow_list_name]["values"].keys())


def _GenerateFile(arguments):
  """Generates C++ header file containing values of a variant or enum from
  a .xml file.

  Args:
    arguments: An object with the following attributes:
      arguments.input: An xml file with histogram descriptions.
      arguments.file: A filename of the generated source file.
      arguments.tag: A XML tag, can be "enum" or "variant".
      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 or enum list.
  """
  histograms = xml.dom.minidom.parse(arguments.input)
  values = _GenerateValueList(histograms, arguments.tag,
                              arguments.allow_list_name)

  static_check_header_file_content = _GenerateStaticFile(
      arguments.file, arguments.namespace, values, arguments.allow_list_name)
  with open(os.path.join(arguments.output_dir, arguments.file),
            "w") as generated_file:
    generated_file.write(static_check_header_file_content)


def _ParseArguments():
  """Defines and parses arguments from the command line."""
  arg_parser = argparse.ArgumentParser(
      description="Generate an array of allowlist from a histograms.xml file."
  )
  arg_parser.add_argument("--output_dir",
                          required=True,
                          help="Base directory to for generated files.")
  arg_parser.add_argument("--file",
                          required=True,
                          help="File name of the generated file.")
  arg_parser.add_argument(
      "--allow_list_name",
      required=True,
      help="Name of the variant / enum list in the histograms.xml file.")
  arg_parser.add_argument("--namespace",
                          required=True,
                          help="Namespace of the allow list array.")
  arg_parser.add_argument("--tag",
                          required=True,
                          help="XML tag name of either 'enum' or 'variant'.")
  arg_parser.add_argument("--input",
                          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())