2323# This is a copy of https://github.com/HyperionGray/python-chrome-devtools-protocol/blob/master/generator/generate.py
2424# The license above is theirs and MUST be preserved.
2525
26-
2726import builtins
28- from dataclasses import dataclass
29- from enum import Enum
3027import itertools
3128import json
3229import logging
3330import operator
3431import os
35- from pathlib import Path
3632import re
37- from textwrap import dedent , indent as tw_indent
38- from typing import Optional , cast , List , Union
39-
4033from collections .abc import Iterator
34+ from dataclasses import dataclass
35+ from enum import Enum
36+ from pathlib import Path
37+ from textwrap import dedent
38+ from textwrap import indent as tw_indent
39+ from typing import Union , cast
4140
4241import inflection # type: ignore
4342
44-
4543log_level = getattr (logging , os .environ .get ("LOG_LEVEL" , "warning" ).upper ())
4644logging .basicConfig (level = log_level )
4745logger = logging .getLogger ("generate" )
@@ -90,16 +88,16 @@ def parse_json_event(json: T_JSON_DICT) -> typing.Any:
9088
9189
9290def indent (s , n ):
93- """A shortcut for `` textwrap.indent` ` that always uses spaces."""
91+ """A shortcut for `textwrap.indent` that always uses spaces."""
9492 return tw_indent (s , n * " " )
9593
9694
9795BACKTICK_RE = re .compile (r"`([^`]+)`(\w+)?" )
9896
9997
10098def escape_backticks (docstr ):
101- """
102- Escape backticks in a docstring by doubling them up.
99+ """Escape backticks in a docstring by doubling them up.
100+
103101 This is a little tricky because RST requires a non-letter character after
104102 the closing backticks, but some CDPs docs have things like "`AxNodeId`s".
105103 If we double the backticks in that string, then it won't be valid RST. The
@@ -121,12 +119,12 @@ def replace_one(match):
121119
122120
123121def inline_doc (description ):
124- """Generate an inline doc, e.g. `` #: This type is a ...`` """
122+ """Generate an inline doc, e.g. `#: This type is a ...`. """
125123 if not description :
126124 return ""
127125
128126 description = escape_backticks (description )
129- lines = [f"#: { l } " for l in description .split ("\n " )]
127+ lines = [f"#: { line } " for line in description .split ("\n " )]
130128 return "\n " .join (lines )
131129
132130
@@ -140,7 +138,7 @@ def docstring(description):
140138
141139
142140def is_builtin (name ):
143- """Return True if `` name` ` would shadow a builtin."""
141+ """Return True if `name` would shadow a builtin."""
144142 try :
145143 getattr (builtins , name )
146144 return True
@@ -149,17 +147,19 @@ def is_builtin(name):
149147
150148
151149def snake_case (name ):
152- """Convert a camel case name to snake case. If the name would shadow a
153- Python builtin, then append an underscore."""
150+ """Convert a camel case name to snake case.
151+
152+ If the name would shadow a Python builtin, then append an underscore.
153+ """
154154 name = inflection .underscore (name )
155155 if is_builtin (name ):
156156 name += "_"
157157 return name
158158
159159
160160def ref_to_python (ref ):
161- """
162- Convert a CDP ``$ref`` to the name of a Python type.
161+ """Convert a CDP `$ref` to the name of a Python type.
162+
163163 For a dotted ref, the part before the dot is snake cased.
164164 """
165165 if "." in ref :
@@ -270,8 +270,7 @@ def generate_decl(self):
270270 return code
271271
272272 def generate_to_json (self , dict_ , use_self = True ):
273- """Generate the code that exports this property to the specified JSON
274- dict."""
273+ """Generate the code that exports this property to the specified JSON dict."""
275274 self_ref = "self." if use_self else ""
276275 assign = f"{ dict_ } ['{ self .name } '] = "
277276 if self .items :
@@ -293,13 +292,11 @@ def generate_to_json(self, dict_, use_self=True):
293292 return code
294293
295294 def generate_from_json (self , dict_ ):
296- """Generate the code that creates an instance from a JSON dict named
297- ``dict_``."""
295+ """Generate the code that creates an instance from a JSON dict named `dict_`."""
298296 if self .items :
299297 if self .items .ref :
300298 py_ref = ref_to_python (self .items .ref )
301299 expr = f"[{ py_ref } .from_json(i) for i in { dict_ } ['{ self .name } ']]"
302- expr
303300 else :
304301 cons = CdpPrimitiveType .get_constructor (self .items .type , "i" )
305302 expr = f"[{ cons } for i in { dict_ } ['{ self .name } ']]"
@@ -384,11 +381,11 @@ def __repr__(self):
384381 return code
385382
386383 def generate_enum_code (self ):
387- """
388- Generate an "enum" type.
384+ """Generate an "enum" type.
385+
389386 Enums are handled by making a python class that contains only class
390387 members. Each class member is upper snaked case, e.g.
391- `` MyTypeClass.MY_ENUM_VALUE` ` and is assigned a string value from the
388+ `MyTypeClass.MY_ENUM_VALUE` and is assigned a string value from the
392389 CDP metadata.
393390 """
394391 def_to_json = dedent ("""\
@@ -414,12 +411,11 @@ def from_json(cls, json):
414411 return code
415412
416413 def generate_class_code (self ):
417- """
418- Generate a class type.
419- Top-level types that are defined as a CDP `` object` ` are turned into Python
414+ """Generate a class type.
415+
416+ Top-level types that are defined as a CDP `object` are turned into Python
420417 dataclasses.
421418 """
422- # children = set()
423419 code = dedent (f"""\
424420 @dataclass
425421 class { self .id } :\n """ )
@@ -536,9 +532,7 @@ def generate_doc(self):
536532 return doc
537533
538534 def generate_from_json (self , dict_ ):
539- """
540- Generate the code to instantiate this parameter from a JSON dict.
541- """
535+ """Generate the code to instantiate this parameter from a JSON dict."""
542536 code = super ().generate_from_json (dict_ )
543537 return f"{ self .py_name } ={ code } "
544538
@@ -836,10 +830,9 @@ def generate_code(self):
836830 return code
837831
838832 def generate_imports (self ):
839- """
840- Determine which modules this module depends on and emit the code to
841- import those modules.
842- Notice that CDP defines a ``dependencies`` field for each domain, but
833+ """Determine which modules this module depends on and emit the code to import those modules.
834+
835+ Notice that CDP defines a `dependencies` field for each domain, but
843836 these dependencies are a subset of the modules that we actually need to
844837 import to make our Python code work correctly and type safe. So we
845838 ignore the CDP's declared dependencies and compute them ourselves.
@@ -864,9 +857,7 @@ def generate_imports(self):
864857 return code
865858
866859 def generate_sphinx (self ):
867- """
868- Generate a Sphinx document for this domain.
869- """
860+ """Generate a Sphinx document for this domain."""
870861 docs = self .domain + "\n "
871862 docs += "=" * len (self .domain ) + "\n \n "
872863 if self .description :
@@ -928,8 +919,8 @@ def generate_sphinx(self):
928919
929920
930921def parse (json_path , output_path ):
931- """
932- Parse JSON protocol description and return domain objects.
922+ """Parse JSON protocol description and return domain objects.
923+
933924 :param Path json_path: path to a JSON CDP schema
934925 :param Path output_path: a directory path to create the modules in
935926 :returns: a list of CDP domain objects
@@ -947,8 +938,8 @@ def parse(json_path, output_path):
947938
948939
949940def generate_init (init_path , domains ):
950- """
951- Generate an ``__init__.py`` that exports the specified modules.
941+ """Generate an `__init__.py` that exports the specified modules.
942+
952943 :param Path init_path: a file path to create the init file in
953944 :param list[tuple] modules: a list of modules each represented as tuples
954945 of (name, list_of_exported_symbols)
@@ -961,9 +952,7 @@ def generate_init(init_path, domains):
961952
962953
963954def generate_docs (docs_path , domains ):
964- """
965- Generate Sphinx documents for each domain.
966- """
955+ """Generate Sphinx documents for each domain."""
967956 logger .info ("Generating Sphinx documents" )
968957
969958 # Remove generated documents
0 commit comments