in noxfile.py [0:0]
def format(session):
"""
Run isort to sort imports. Then run black
to format code to uniform standard.
"""
# Sort Spelling Allowlist
spelling_allow_file = ".github/actions/spelling/allow.txt"
with open(spelling_allow_file, encoding="utf-8") as file:
unique_words = sorted(set(file))
with open(spelling_allow_file, "w", encoding="utf-8") as file:
file.writelines(unique_words)
format_all = False
if format_all:
lint_paths_py = ["."]
lint_paths_nb = ["."]
else:
target_branch = "main"
unstaged_files = subprocess.run(
["git", "diff", "--name-only", "--diff-filter=ACMRTUXB", target_branch],
stdout=subprocess.PIPE,
text=True,
).stdout.splitlines()
staged_files = subprocess.run(
[
"git",
"diff",
"--cached",
"--name-only",
"--diff-filter=ACMRTUXB",
target_branch,
],
stdout=subprocess.PIPE,
text=True,
).stdout.splitlines()
committed_files = subprocess.run(
[
"git",
"diff",
"HEAD",
target_branch,
"--name-only",
"--diff-filter=ACMRTUXB",
],
stdout=subprocess.PIPE,
text=True,
).stdout.splitlines()
changed_files = sorted(
set(
file
for file in (unstaged_files + staged_files + committed_files)
if os.path.isfile(file)
)
)
lint_paths_py = [
f for f in changed_files if f.endswith(".py") and f != "noxfile.py"
]
lint_paths_nb = [f for f in changed_files if f.endswith(".ipynb")]
if not lint_paths_py and not lint_paths_nb:
session.log("No changed Python or notebook files to lint.")
return
session.install(
"types-requests",
BLACK_VERSION,
"blacken-docs",
"pyupgrade",
ISORT_VERSION,
"autoflake",
"ruff",
)
if lint_paths_py:
session.run(
"autoflake",
"-i",
"-r",
"--remove-all-unused-imports",
*lint_paths_py,
)
session.run(
"ruff",
"check",
"--fix-only",
*lint_paths_py,
)
# Use the --fss option to sort imports using strict alphabetical order.
session.run(
"isort",
"--fss",
*lint_paths_py,
)
session.run(
"black",
*lint_paths_py,
)
if lint_paths_nb:
session.install(
"git+https://github.com/tensorflow/docs",
"ipython",
"jupyter",
"nbconvert",
"nbqa",
"nbformat",
)
session.run("python3", ".github/workflows/update_notebook_links.py", ".")
session.run(
"nbqa",
"pyupgrade",
"--exit-zero-even-if-changed",
"--py310-plus",
*lint_paths_nb,
)
session.run(
"nbqa",
"autoflake",
"-i",
"--remove-all-unused-imports",
"-r",
*lint_paths_nb,
)
session.run(
"nbqa",
"isort",
"--fss",
*lint_paths_nb,
"--profile",
"black",
)
session.run("nbqa", "black", *lint_paths_nb)
session.run("nbqa", "blacken-docs", "--nbqa-md", *lint_paths_nb)
session.run("python3", "-m", "tensorflow_docs.tools.nbfmt", *lint_paths_nb)