Skip to content

Commit bd2955c

Browse files
smcclure15MongoDB Bot
authored and
MongoDB Bot
committed
SERVER-90571: Enable python formatting checks for buildscripts/idl directory (#22293)
GitOrigin-RevId: a2fbc8ed83f576703cce96ebb5e680cc70aac4d8
1 parent 83fa212 commit bd2955c

31 files changed

+8451
-4523
lines changed

buildscripts/idl/check_stable_api_commands_have_idl_definitions.py

+38-21
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@
4040
from pymongo import MongoClient
4141

4242
# Permit imports from "buildscripts".
43-
sys.path.append(os.path.normpath(os.path.join(os.path.abspath(__file__), '../../..')))
43+
sys.path.append(os.path.normpath(os.path.join(os.path.abspath(__file__), "../../..")))
4444

4545
# pylint: disable=wrong-import-position
4646
from idl import syntax
@@ -53,7 +53,7 @@
5353
from buildscripts.resmokelib.testing.fixtures.standalone import MongoDFixture
5454
# pylint: enable=wrong-import-position
5555

56-
LOGGER_NAME = 'check-idl-definitions'
56+
LOGGER_NAME = "check-idl-definitions"
5757
LOGGER = logging.getLogger(LOGGER_NAME)
5858

5959

@@ -68,8 +68,9 @@ def is_test_or_third_party_idl(idl_path: str) -> bool:
6868
return False
6969

7070

71-
def get_command_definitions(api_version: str, directory: str,
72-
import_directories: List[str]) -> Dict[str, syntax.Command]:
71+
def get_command_definitions(
72+
api_version: str, directory: str, import_directories: List[str]
73+
) -> Dict[str, syntax.Command]:
7374
"""Get parsed IDL definitions of commands in a given API version."""
7475

7576
LOGGER.info("Searching for command definitions in %s", directory)
@@ -109,22 +110,30 @@ def list_commands_for_api(api_version: str, mongod_or_mongos: str, install_dir:
109110
logger = loggers.new_fixture_logger("ShardedClusterFixture", 0)
110111
logger.parent = LOGGER
111112
fixture = fixturelib.make_fixture(
112-
"ShardedClusterFixture", logger, 0, dbpath_prefix=dbpath.name,
113-
mongos_executable=mongos_executable, mongod_executable=mongod_executable,
114-
mongod_options={"set_parameters": {}})
113+
"ShardedClusterFixture",
114+
logger,
115+
0,
116+
dbpath_prefix=dbpath.name,
117+
mongos_executable=mongos_executable,
118+
mongod_executable=mongod_executable,
119+
mongod_options={"set_parameters": {}},
120+
)
115121

116122
fixture.setup()
117123
fixture.await_ready()
118124

119125
try:
120126
client = MongoClient(fixture.get_driver_connection_url()) # type: MongoClient
121-
reply = client.admin.command('listCommands') # type: Mapping[str, Any]
127+
reply = client.admin.command("listCommands") # type: Mapping[str, Any]
122128
commands = {
123-
name
124-
for name, info in reply['commands'].items() if api_version in info['apiVersions']
129+
name for name, info in reply["commands"].items() if api_version in info["apiVersions"]
125130
}
126-
logging.info("Found %s commands in API Version %s on %s", len(commands), api_version,
127-
mongod_or_mongos)
131+
logging.info(
132+
"Found %s commands in API Version %s on %s",
133+
len(commands),
134+
api_version,
135+
mongod_or_mongos,
136+
)
128137
return commands
129138
finally:
130139
fixture.teardown()
@@ -144,13 +153,16 @@ def assert_command_sets_equal(api_version: str, command_sets: Dict[str, Set[str]
144153
for other_name, other_commands in it:
145154
if commands != other_commands:
146155
if commands - other_commands:
147-
LOGGER.error("%s has commands not in %s: %s", name, other_name,
148-
commands - other_commands)
156+
LOGGER.error(
157+
"%s has commands not in %s: %s", name, other_name, commands - other_commands
158+
)
149159
if other_commands - commands:
150-
LOGGER.error("%s has commands not in %s: %s", other_name, name,
151-
other_commands - commands)
160+
LOGGER.error(
161+
"%s has commands not in %s: %s", other_name, name, other_commands - commands
162+
)
152163
raise AssertionError(
153-
f"{name} and {other_name} have different commands in API Version {api_version}")
164+
f"{name} and {other_name} have different commands in API Version {api_version}"
165+
)
154166

155167

156168
def remove_skipped_commands(command_sets: Dict[str, Set[str]]):
@@ -173,10 +185,15 @@ def remove_skipped_commands(command_sets: Dict[str, Set[str]]):
173185
def main():
174186
"""Run the script."""
175187
arg_parser = argparse.ArgumentParser(description=__doc__)
176-
arg_parser.add_argument("--include", type=str, action="append",
177-
help="Directory to search for IDL import files")
178-
arg_parser.add_argument("--install-dir", dest="install_dir", required=True,
179-
help="Directory to search for MongoDB binaries")
188+
arg_parser.add_argument(
189+
"--include", type=str, action="append", help="Directory to search for IDL import files"
190+
)
191+
arg_parser.add_argument(
192+
"--install-dir",
193+
dest="install_dir",
194+
required=True,
195+
help="Directory to search for MongoDB binaries",
196+
)
180197
arg_parser.add_argument("-v", "--verbose", action="count", help="Enable verbose logging")
181198
arg_parser.add_argument("api_version", metavar="API_VERSION", help="API Version to check")
182199
args = arg_parser.parse_args()

buildscripts/idl/checkout_idl_files_from_past_releases.py

+15-10
Original file line numberDiff line numberDiff line change
@@ -41,20 +41,24 @@
4141
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
4242

4343
# pylint: disable=wrong-import-position
44-
from buildscripts.resmokelib.multiversionconstants import LAST_LTS_FCV, LAST_CONTINUOUS_FCV, LATEST_FCV
44+
from buildscripts.resmokelib.multiversionconstants import (
45+
LAST_LTS_FCV,
46+
LAST_CONTINUOUS_FCV,
47+
LATEST_FCV,
48+
)
4549
# pylint: enable=wrong-import-position
4650

47-
LOGGER_NAME = 'checkout-idl'
51+
LOGGER_NAME = "checkout-idl"
4852
LOGGER = logging.getLogger(LOGGER_NAME)
4953

5054

5155
def get_tags() -> List[str]:
5256
"""Get a list of git tags that the IDL compatibility script should check against."""
5357

5458
def gen_versions_and_tags():
55-
for tag in check_output(['git', 'tag']).decode().split():
59+
for tag in check_output(["git", "tag"]).decode().split():
5660
# Releases are like "r5.6.7". Older ones aren't r-prefixed but we don't care about them.
57-
if not tag.startswith('r'):
61+
if not tag.startswith("r"):
5862
continue
5963

6064
try:
@@ -110,23 +114,24 @@ def make_idl_directories(tags: List[str], destination: str) -> None:
110114
for tag in tags:
111115
LOGGER.info("Checking out IDL files in %s", tag)
112116
directory = os.path.join(destination, tag)
113-
for path in check_output(['git', 'ls-tree', '--name-only', '-r', tag]).decode().split():
114-
if not path.endswith('.idl'):
117+
for path in check_output(["git", "ls-tree", "--name-only", "-r", tag]).decode().split():
118+
if not path.endswith(".idl"):
115119
continue
116120

117-
contents = check_output(['git', 'show', f'{tag}:{path}']).decode()
121+
contents = check_output(["git", "show", f"{tag}:{path}"]).decode()
118122
output_path = os.path.join(directory, path)
119123
os.makedirs(os.path.dirname(output_path), exist_ok=True)
120-
with open(output_path, 'w+') as fd:
124+
with open(output_path, "w+") as fd:
121125
fd.write(contents)
122126

123127

124128
def main():
125129
"""Run the script."""
126130
arg_parser = argparse.ArgumentParser(description=__doc__)
127131
arg_parser.add_argument("-v", "--verbose", action="count", help="Enable verbose logging")
128-
arg_parser.add_argument("destination", metavar="DESTINATION",
129-
help="Directory to check out past IDL file versions")
132+
arg_parser.add_argument(
133+
"destination", metavar="DESTINATION", help="Directory to check out past IDL file versions"
134+
)
130135
args = arg_parser.parse_args()
131136

132137
logging.basicConfig(level=logging.WARNING)

buildscripts/idl/gen_all_feature_flag_list.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@
3838
import yaml
3939

4040
# Permit imports from "buildscripts".
41-
sys.path.append(os.path.normpath(os.path.join(os.path.abspath(__file__), '../../..')))
41+
sys.path.append(os.path.normpath(os.path.join(os.path.abspath(__file__), "../../..")))
4242

4343
# pylint: disable=wrong-import-position
4444
from buildscripts.idl import lib
@@ -60,7 +60,7 @@ def get_all_feature_flags(idl_dirs: List[str] = None):
6060
# Most IDL files do not contain feature flags.
6161
# We can discard these quickly without expensive YAML parsing.
6262
with open(idl_path) as idl_file:
63-
if 'feature_flags' not in idl_file.read():
63+
if "feature_flags" not in idl_file.read():
6464
continue
6565
with open(idl_path) as idl_file:
6666
doc = parser.parse_file(idl_file, idl_path)
@@ -100,5 +100,5 @@ def main():
100100
gen_all_feature_flags_file()
101101

102102

103-
if __name__ == '__main__':
103+
if __name__ == "__main__":
104104
main()

buildscripts/idl/gen_all_server_params_list.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@
3636
from typing import List
3737

3838
# Permit imports from "buildscripts".
39-
sys.path.append(os.path.normpath(os.path.join(os.path.abspath(__file__), '../../..')))
39+
sys.path.append(os.path.normpath(os.path.join(os.path.abspath(__file__), "../../..")))
4040

4141
# pylint: disable=wrong-import-position
4242
from buildscripts.idl import lib
@@ -58,7 +58,7 @@ def gen_all_server_params(idl_dirs: List[str] = None):
5858
# Most IDL files do not contain server parameters.
5959
# We can discard these quickly without expensive YAML parsing.
6060
with open(idl_path) as idl_file:
61-
if 'server_parameters' not in idl_file.read():
61+
if "server_parameters" not in idl_file.read():
6262
continue
6363
with open(idl_path) as idl_file:
6464
doc = parser.parse_file(idl_file, idl_path)
@@ -80,5 +80,5 @@ def main():
8080
gen_all_server_params_file()
8181

8282

83-
if __name__ == '__main__':
83+
if __name__ == "__main__":
8484
main()

buildscripts/idl/idl/ast.py

+6-3
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
This is a lossy translation from the IDL Syntax tree as the IDL AST only contains information about
3434
the enums and structs that need code generated for them, and just enough information to do that.
3535
"""
36+
3637
from abc import ABCMeta, abstractmethod
3738
import enum
3839
from typing import Any, Dict, List, Optional
@@ -46,8 +47,9 @@ class IDLBoundSpec(object):
4647
def __init__(self, spec, error_collection):
4748
# type: (IDLAST, errors.ParserErrorCollection) -> None
4849
"""Must specify either an IDL document or errors, not both."""
49-
assert (spec is None and error_collection is not None) or (spec is not None
50-
and error_collection is None)
50+
assert (spec is None and error_collection is not None) or (
51+
spec is not None and error_collection is None
52+
)
5153
self.spec = spec
5254
self.errors = error_collection
5355

@@ -292,7 +294,8 @@ def should_serialize_with_options(self):
292294
# type: () -> bool
293295
"""Returns true if the IDL compiler should add a call to serialization options for this field."""
294296
return self.query_shape is not None and self.query_shape in [
295-
QueryShapeFieldType.LITERAL, QueryShapeFieldType.ANONYMIZE
297+
QueryShapeFieldType.LITERAL,
298+
QueryShapeFieldType.ANONYMIZE,
296299
]
297300

298301
@property

0 commit comments

Comments
 (0)