Cleanup: declare __all__ for Python scripts

Declare all to make public public API's explicit and
help detect unused code.
This commit is contained in:
Campbell Barton 2025-01-06 16:45:36 +11:00
parent 6ac52551d3
commit 4f1817cc18
31 changed files with 285 additions and 140 deletions

View file

@ -5,6 +5,10 @@
# macOS utility to remove all `rpaths` and add a new one.
__all__ = (
"main",
)
import os
import pathlib
import re

View file

@ -3,6 +3,10 @@
#
# SPDX-License-Identifier: GPL-2.0-or-later
__all__ = (
"main",
)
import logging
import os
import re

View file

@ -2,18 +2,20 @@
#
# SPDX-License-Identifier: Apache-2.0
# Simple utility that prints all WITH_* options in a CMakeLists.txt
# Called by 'make help_features'
# Simple utility that prints all `WITH_*` options in a `CMakeLists.txt`.
# Called by `make help_features`.
__all__ = (
"main",
)
import re
import sys
from typing import (
Union,
Optional,
)
cmakelists_file = sys.argv[-1]
def count_backslashes_before_pos(file_data: str, pos: int) -> int:
slash_count = 0
@ -26,7 +28,7 @@ def count_backslashes_before_pos(file_data: str, pos: int) -> int:
return slash_count
def extract_cmake_string_at_pos(file_data: str, pos_beg: int) -> Union[str, None]:
def extract_cmake_string_at_pos(file_data: str, pos_beg: int) -> Optional[str]:
assert file_data[pos_beg - 1] == '"'
pos = pos_beg
@ -73,19 +75,23 @@ def extract_cmake_string_at_pos(file_data: str, pos_beg: int) -> Union[str, None
return text
def main() -> None:
def main() -> int:
cmakelists_file = sys.argv[-1]
options = []
with open(cmakelists_file, 'r', encoding="utf-8") as fh:
file_data = fh.read()
for m in re.finditer(r"^\s*option\s*\(\s*(WITH_[a-zA-Z0-9_]+)\s+(\")", file_data, re.MULTILINE):
option_name = m.group(1)
option_descr = extract_cmake_string_at_pos(file_data, m.span(2)[1])
if option_descr is None:
# Possibly a parsing error, at least show something.
option_descr = "(UNDOCUMENTED)"
options.append("{:s}: {:s}".format(option_name, option_descr))
for m in re.finditer(r"^\s*option\s*\(\s*(WITH_[a-zA-Z0-9_]+)\s+(\")", file_data, re.MULTILINE):
option_name = m.group(1)
option_descr = extract_cmake_string_at_pos(file_data, m.span(2)[1])
if option_descr is None:
# Possibly a parsing error, at least show something.
option_descr = "(UNDOCUMENTED)"
options.append("{:s}: {:s}".format(option_name, option_descr))
print('\n'.join(options))
return 0
if __name__ == "__main__":

View file

@ -3,6 +3,10 @@
#
# SPDX-License-Identifier: GPL-2.0-or-later
__all__ = (
"main",
)
import os
import shutil
import subprocess

View file

@ -27,6 +27,9 @@ NOTE:
Some type annotations are quoted to avoid errors in Python 3.9.
These can be unquoted eventually.
"""
__all__ = (
"main",
)
import argparse
import make_utils

View file

@ -7,6 +7,10 @@
"make test" for all platforms, running automated tests.
"""
__all__ = (
"main",
)
import argparse
import os
import sys

View file

@ -53,6 +53,9 @@ API dump format:
]
"""
__all__ = (
"main",
)
import json
import os

View file

@ -3,50 +3,60 @@
#
# SPDX-License-Identifier: GPL-2.0-or-later
__all__ = (
"__all__",
)
import sys
argv = sys.argv[:]
strip_byte = False
if "--strip-byte" in argv:
argv.remove("--strip-byte")
strip_byte = True
def main():
argv = sys.argv[:]
if len(argv) < 2:
sys.stdout.write("Usage: ctodata <c_file> [--strip-byte]\n")
sys.exit(1)
strip_byte = False
if "--strip-byte" in argv:
argv.remove("--strip-byte")
strip_byte = True
filename = argv[1]
if len(argv) < 2:
sys.stdout.write("Usage: ctodata <c_file> [--strip-byte]\n")
sys.exit(1)
try:
fpin = open(filename, "r")
except:
sys.stdout.write("Unable to open input {:s}\n".format(argv[1]))
sys.exit(1)
filename = argv[1]
data_as_str = fpin.read().rsplit("{")[-1].split("}")[0]
data_as_str = data_as_str.replace(",", " ")
data_as_list = [int(v) for v in data_as_str.split()]
del data_as_str
try:
fpin = open(filename, "r")
except:
sys.stdout.write("Unable to open input {:s}\n".format(argv[1]))
sys.exit(1)
if strip_byte:
# String data gets trailing byte.
last = data_as_list.pop()
assert last == 0
data_as_str = fpin.read().rsplit("{")[-1].split("}")[0]
data_as_str = data_as_str.replace(",", " ")
data_as_list = [int(v) for v in data_as_str.split()]
del data_as_str
data = bytes(data_as_list)
del data_as_list
if strip_byte:
# String data gets trailing byte.
last = data_as_list.pop()
assert last == 0
dname = filename + ".ctodata"
data = bytes(data_as_list)
del data_as_list
sys.stdout.write("Making DATA file <{:s}>\n".format(dname))
dname = filename + ".ctodata"
try:
fpout = open(dname, "wb")
except:
sys.stdout.write("Unable to open output {:s}\n".format(dname))
sys.exit(1)
sys.stdout.write("Making DATA file <{:s}>\n".format(dname))
size = fpout.write(data)
try:
fpout = open(dname, "wb")
except:
sys.stdout.write("Unable to open output {:s}\n".format(dname))
sys.exit(1)
sys.stdout.write("{:d}\n".format(size))
size = fpout.write(data)
sys.stdout.write("{:d}\n".format(size))
if __name__ == "__main__":
sys.exit(main())

View file

@ -3,50 +3,62 @@
#
# SPDX-License-Identifier: GPL-2.0-or-later
"""
This python script is used to generate the release notes and
download URLs which we can copy-paste directly into the CMS of
www.blender.org and stores.
"""
__all__ = (
"main",
)
import argparse
import sys
import lts_issue
import lts_download
DESCRIPTION = ("This python script is used to generate the release notes and "
"download URLs which we can copy-paste directly into the CMS of "
"www.blender.org and stores.")
# Parse arguments
parser = argparse.ArgumentParser(description=DESCRIPTION)
parser.add_argument(
"--version",
required=True,
help="Version string in the form of {major}.{minor}.{patch} (e.g. 3.3.2)")
parser.add_argument(
"--issue",
help="Task that contains the release notes information (e.g. #77348)")
parser.add_argument(
"--format",
help="Format the result in `text`, `steam`, `markdown` or `html`",
default="text")
args = parser.parse_args()
def main() -> int:
# Parse arguments
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--version",
required=True,
help="Version string in the form of {major}.{minor}.{patch} (e.g. 3.3.2)")
parser.add_argument(
"--issue",
help="Task that contains the release notes information (e.g. #77348)")
parser.add_argument(
"--format",
help="Format the result in `text`, `steam`, `markdown` or `html`",
default="text")
args = parser.parse_args()
# Determine issue number
version = args.version
issue = args.issue
if not issue:
if version.startswith("2.83."):
issue = "#77348"
elif version.startswith("2.93."):
issue = "#88449"
elif version.startswith("3.3."):
issue = "#100749"
elif version.startswith("3.6."):
issue = "#109399"
elif version.startswith("4.2."):
issue = "#124452"
else:
raise ValueError("Specify --issue or update script to include issue number for this version")
# Determine issue number
version = args.version
issue = args.issue
if not issue:
if version.startswith("2.83."):
issue = "#77348"
elif version.startswith("2.93."):
issue = "#88449"
elif version.startswith("3.3."):
issue = "#100749"
elif version.startswith("3.6."):
issue = "#109399"
elif version.startswith("4.2."):
issue = "#124452"
else:
raise ValueError("Specify --issue or update script to include issue number for this version")
# Print
if args.format == "html":
lts_download.print_urls(version=version)
print("")
# Print
if args.format == "html":
lts_download.print_urls(version=version)
print("")
lts_issue.print_notes(version=version, format=args.format, issue=issue)
lts_issue.print_notes(version=version, format=args.format, issue=issue)
if __name__ == "__main__":
sys.exit(main())

View file

@ -2,6 +2,9 @@
# SPDX-FileCopyrightText: 2020-2023 Blender Authors
#
# SPDX-License-Identifier: GPL-2.0-or-later
__all__ = (
"print_urls",
)
import datetime

View file

@ -2,6 +2,9 @@
# SPDX-FileCopyrightText: 2023 Blender Authors
#
# SPDX-License-Identifier: GPL-2.0-or-later
__all__ = (
"print_notes",
)
import requests

View file

@ -3,6 +3,10 @@
#
# SPDX-License-Identifier: GPL-2.0-or-later
__all__ = (
"main",
)
import argparse
import glob
import pathlib
@ -12,59 +16,65 @@ import tempfile
import urllib.request
import zipfile
parser = argparse.ArgumentParser(description="Check and upload bpy module to PyPI")
parser.add_argument(
"--version",
required=True,
help="Version string in the form of {major}.{minor}.{patch} (e.g. 3.6.0)")
parser.add_argument(
"--git-hash",
required=True,
help="Git hash matching the version")
parser.add_argument(
"--check",
action="store_true",
help="Only check wheels for errors, don't upload")
args = parser.parse_args()
platforms = [
"darwin.x86_64",
"darwin.arm64",
"linux.x86_64",
"windows.amd64"]
def main():
parser = argparse.ArgumentParser(description="Check and upload bpy module to PyPI")
parser.add_argument(
"--version",
required=True,
help="Version string in the form of {major}.{minor}.{patch} (e.g. 3.6.0)")
parser.add_argument(
"--git-hash",
required=True,
help="Git hash matching the version")
parser.add_argument(
"--check",
action="store_true",
help="Only check wheels for errors, don't upload")
args = parser.parse_args()
with tempfile.TemporaryDirectory() as tmp_dir:
tmp_dir = pathlib.Path(tmp_dir)
platforms = [
"darwin.x86_64",
"darwin.arm64",
"linux.x86_64",
"windows.amd64"]
print("Download:")
for platform in platforms:
# Download from buildbot.
version = args.version
version_tokens = version.split(".")
short_version = version_tokens[0] + version_tokens[1]
git_hash = args.git_hash
with tempfile.TemporaryDirectory() as tmp_dir:
tmp_dir = pathlib.Path(tmp_dir)
url = f"https://builder.blender.org/download/daily/bpy-{version}-stable+v{short_version}.{git_hash}-{platform}-release.zip"
filepath = tmp_dir / f"{platform}.zip"
print(url)
urllib.request.urlretrieve(url, filepath)
print("Download:")
for platform in platforms:
# Download from buildbot.
version = args.version
version_tokens = version.split(".")
short_version = version_tokens[0] + version_tokens[1]
git_hash = args.git_hash
# Unzip.
with zipfile.ZipFile(filepath, "r") as zipf:
zipf.extractall(path=tmp_dir)
print("")
url = f"https://builder.blender.org/download/daily/bpy-{version}-stable+v{short_version}.{git_hash}-{platform}-release.zip"
filepath = tmp_dir / f"{platform}.zip"
print(url)
urllib.request.urlretrieve(url, filepath)
wheels = glob.glob(str(tmp_dir / "*.whl"))
print("Wheels:")
print("\n".join(wheels))
# Unzip.
with zipfile.ZipFile(filepath, "r") as zipf:
zipf.extractall(path=tmp_dir)
print("")
if len(platforms) != len(wheels):
sys.stderr.write("Unexpected number of whl files.")
sys.exit(1)
print("")
wheels = glob.glob(str(tmp_dir / "*.whl"))
print("Wheels:")
print("\n".join(wheels))
# Check and upload.
print("Twine:")
subprocess.run(["twine", "check"] + wheels, check=True)
if not args.check:
subprocess.run(["twine", "upload", "--repository", "bpy", "--verbose"] + wheels, check=True)
if len(platforms) != len(wheels):
sys.stderr.write("Unexpected number of whl files.")
sys.exit(1)
print("")
# Check and upload.
print("Twine:")
subprocess.run(["twine", "check"] + wheels, check=True)
if not args.check:
subprocess.run(["twine", "upload", "--repository", "bpy", "--verbose"] + wheels, check=True)
if __name__ == "__main__":
sys.exit(main())

View file

@ -8,6 +8,9 @@ rna values in fcurves and drivers.
Currently unused, but might become useful later again.
"""
__all__ = (
"update_data_paths",
)
import sys
import bpy

View file

@ -7,6 +7,11 @@
# When the version is `(0, 0, 0)`, the key-map being loaded didn't contain any versioning information.
# This will older than `(2, 92, 0)`.
__all__ = (
"keyconfig_update",
)
def keyconfig_update(keyconfig_data, keyconfig_version):
from bpy.app import version_file as blender_version
if keyconfig_version >= blender_version:

View file

@ -3,6 +3,10 @@
#
# SPDX-License-Identifier: GPL-2.0-or-later
__all__ = (
"main",
)
import argparse
import os
import shutil

View file

@ -2,16 +2,19 @@
#
# SPDX-License-Identifier: GPL-2.0-or-later
"""
blender -b --factory-startup --python tests/python/bl_animation_drivers.py -- --testdir /path/to/tests/data/animation
"""
__all__ = (
"main",
)
import unittest
import bpy
import pathlib
import sys
from rna_prop_ui import rna_idprop_quote_path
"""
blender -b --factory-startup --python tests/python/bl_animation_drivers.py -- --testdir /path/to/tests/data/animation
"""
class AbstractEmptyDriverTest:
def setUp(self):

View file

@ -2,7 +2,13 @@
#
# SPDX-License-Identifier: Apache-2.0
# ./blender.bin --background --python tests/python/bl_blendfile_liblink.py
"""
./blender.bin --background --python tests/python/bl_blendfile_liblink.py
"""
__all__ = (
"main",
)
import bpy
import os
import sys

View file

@ -9,6 +9,10 @@
#
# This needs to be investigated!
__all__ = (
"main",
)
import os
import platform
import sys

View file

@ -2,6 +2,10 @@
#
# SPDX-License-Identifier: GPL-2.0-or-later
__all__ = (
"main",
)
import os
import pathlib
import sys

View file

@ -3,6 +3,10 @@
#
# SPDX-License-Identifier: Apache-2.0
__all__ = (
"main",
)
import argparse
import os
import sys

View file

@ -7,6 +7,9 @@
"""
./blender.bin --background --factory-startup --python tests/python/bl_load_addons.py
"""
__all__ = (
"main",
)
import bpy
import addon_utils

View file

@ -5,6 +5,10 @@
# Simple script to check mash validate code.
# XXX Should be extended with many more "wrong cases"!
__all__ = (
"main",
)
import bpy
import random

View file

@ -3,6 +3,11 @@
# SPDX-License-Identifier: Apache-2.0
# ./blender.bin --background --python tests/python/bl_pyapi_bpy_utils_units.py -- --verbose
__all__ = (
"main",
)
import unittest
from bpy.utils import units
@ -93,7 +98,11 @@ class UnitsTesting(unittest.TestCase):
)
if __name__ == '__main__':
def main():
import sys
sys.argv = [__file__] + (sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else [])
unittest.main()
if __name__ == '__main__':
main()

View file

@ -2,6 +2,10 @@
#
# SPDX-License-Identifier: GPL-2.0-or-later
__all__ = (
"AbstractImBufTest",
)
import os
import pathlib
import shutil

View file

@ -2,6 +2,10 @@
#
# SPDX-License-Identifier: GPL-2.0-or-later
__all__ = (
"main",
)
r"""
Example usage:

View file

@ -7,6 +7,10 @@
#
# only error checked for here is a segfault.
__all__ = (
"main",
)
import bpy
import sys

View file

@ -82,7 +82,9 @@ or the context for executing the actions is not properly set (the case for timer
This utility executes actions as if the user initiated them from a key shortcut.
"""
__all__ = (
"main",
)
import os
import sys

View file

@ -39,6 +39,10 @@ WAYLAND Environment Variables:
Currently only WAYLAND is supported, other systems could be added.
"""
__all__ = (
"main",
)
import subprocess
import sys
import signal

View file

@ -5,6 +5,10 @@
# generate svn rev-sha1 mapping
__all__ = (
"main",
)
import os
import sys

View file

@ -2,6 +2,10 @@
#
# SPDX-License-Identifier: GPL-2.0-or-later
__all__ = (
"data",
)
data = {
2: "12315f4d0e0ae993805f141f64cb8c73c5297311",
16: "599dc60f6dc97d3ef8efdd294ca2e89fbf498f54",

View file

@ -2,6 +2,10 @@
#
# SPDX-License-Identifier: GPL-2.0-or-later
__all__ = (
"data",
)
data = {
"12315f4d0e0ae993805f141f64cb8c73c5297311": 2,
"599dc60f6dc97d3ef8efdd294ca2e89fbf498f54": 16,