211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420 | @task(
help={
"package-dir": (
"Relative path to package dir from the repository root, "
"e.g. 'src/my_package'."
),
"pre-clean": "Remove the 'api_reference' sub directory prior to (re)creation.",
"pre-commit": "Return a non-zero error code if changes were made.",
"repo-folder": (
"The folder name of the repository, wherein the package dir is located. "
"This defaults to 'main', as this will be used in the callable workflows."
),
"docs-folder": (
"The folder name for the documentation root folder. "
"This defaults to 'docs'."
),
"unwanted-dirs": (
"Comma-separated list of directories to avoid including in the Python API "
"reference documentation. Note, only directory names, not paths, may be "
"included. Note, all folders and their contents with these names will be "
"excluded. Defaults to '__pycache__'."
),
"unwanted-files": (
"Comma-separated list of files to avoid including the Python API reference"
" documentation. Note, only full file names, not paths, may be included, "
"i.e., filename + file extension. Note, all files with these names will "
"be excluded. Defaults to '__init__.py'."
),
"full-docs-dirs": (
"Comma-separated list of directories in which to include everything - even"
" those without documentation strings. This may be useful for a module "
"full of data models or to ensure all class attributes are listed."
),
"debug": "Whether or not to print debug statements.",
}
)
def create_api_reference_docs( # pylint: disable=too-many-locals,too-many-branches,too-many-statements,line-too-long
context,
package_dir,
pre_clean=False,
pre_commit=False,
repo_folder="main",
docs_folder="docs",
unwanted_dirs="__pycache__",
unwanted_files="__init__.py",
full_docs_dirs="",
debug=False,
):
"""Create the Python API Reference in the documentation."""
import os
import shutil
def write_file(full_path: Path, content: str) -> None:
"""Write file with `content` to `full_path`"""
if full_path.exists():
cached_content = full_path.read_text(encoding="utf8")
if content == cached_content:
del cached_content
return
del cached_content
full_path.write_text(content, encoding="utf8")
package_dir: Path = REPO_PARENT_DIR / repo_folder / package_dir
docs_api_ref_dir: Path = (
REPO_PARENT_DIR / repo_folder / docs_folder / "api_reference"
)
if debug:
print("package_dir:", package_dir, flush=True)
print("docs_api_ref_dir:", docs_api_ref_dir, flush=True)
print(
"unwanted_dirs + unwanted_files:",
unwanted_dirs + unwanted_files,
flush=True,
)
if "/" in unwanted_dirs + unwanted_files:
sys.exit(
"Unwanted directories and files may NOT be paths. A forward slash (/) was "
f"found in them. Given\n\n --unwanted-dirs={unwanted_dirs},\n "
f"--unwanted-files={unwanted_files}"
)
unwanted_subdirs: list[str] = unwanted_dirs.split(",")
unwanted_subfiles: list[str] = unwanted_files.split(",")
no_docstring_dirs: list[str] = full_docs_dirs.split(",")
if debug:
print("unwanted_subdirs:", unwanted_subdirs, flush=True)
print("unwanted_subfiles:", unwanted_subfiles, flush=True)
print("no_docstring_dirs:", no_docstring_dirs, flush=True)
pages_template = 'title: "{name}"\n'
md_template = "# {name}\n\n::: {py_path}\n"
no_docstring_template = (
md_template + f"{' ' * 4}options:\n{' ' * 6}show_if_no_docstring: true\n"
)
if docs_api_ref_dir.exists() and pre_clean:
if debug:
print(f"Removing {docs_api_ref_dir}", flush=True)
shutil.rmtree(docs_api_ref_dir, ignore_errors=True)
if docs_api_ref_dir.exists():
sys.exit(f"{docs_api_ref_dir} should have been removed!")
docs_api_ref_dir.mkdir(exist_ok=True)
if debug:
print(f"Writing file: {docs_api_ref_dir / '.pages'}", flush=True)
write_file(
full_path=docs_api_ref_dir / ".pages",
content=pages_template.format(name="API Reference"),
)
for dirpath, dirnames, filenames in os.walk(package_dir):
for unwanted_dir in unwanted_subdirs:
if debug:
print("unwanted_dir:", unwanted_dir, flush=True)
print("dirnames:", dirnames, flush=True)
if unwanted_dir in dirnames:
# Avoid walking into or through unwanted directories
dirnames.remove(unwanted_dir)
relpath = Path(dirpath).relative_to(package_dir)
abspath = (package_dir / relpath).resolve()
if debug:
print("relpath:", relpath, flush=True)
print("abspath:", abspath, flush=True)
if not (abspath / "__init__.py").exists():
# Avoid paths that are not included in the public Python API
print("does not exist:", abspath / "__init__.py", flush=True)
continue
# Create `.pages`
docs_sub_dir = docs_api_ref_dir / relpath
docs_sub_dir.mkdir(exist_ok=True)
if debug:
print("docs_sub_dir:", docs_sub_dir, flush=True)
if str(relpath) != ".":
if debug:
print(f"Writing file: {docs_sub_dir / '.pages'}", flush=True)
write_file(
full_path=docs_sub_dir / ".pages",
content=pages_template.format(
name=str(relpath).rsplit("/", maxsplit=1)[-1]
),
)
# Create markdown files
for filename in filenames:
if re.match(r".*\.py$", filename) is None or filename in unwanted_subfiles:
# Not a Python file: We don't care about it!
# Or filename is in the tuple of unwanted files:
# We don't want it!
if debug:
print(
f"{filename} is not a Python file or is in unwanted_subfiles. Skipping it.",
flush=True,
)
continue
basename = filename[: -len(".py")]
py_path = (
f"{package_dir.name}/{relpath}/{basename}".replace("/", ".")
if str(relpath) != "."
else f"{package_dir.name}/{basename}".replace("/", ".")
)
md_filename = filename.replace(".py", ".md")
if debug:
print("basename:", basename, flush=True)
print("py_path:", py_path, flush=True)
print("md_filename:", md_filename, flush=True)
# For special folders we want to include EVERYTHING, even if it doesn't
# have a doc-string
template = (
no_docstring_template
if str(relpath) in no_docstring_dirs
else md_template
)
if debug:
print("template:", template, flush=True)
print(f"Writing file: {docs_sub_dir / md_filename}", flush=True)
write_file(
full_path=docs_sub_dir / md_filename,
content=template.format(name=basename, py_path=py_path),
)
if pre_commit:
# Check if there have been any changes.
# List changes if yes.
if TYPE_CHECKING: # pragma: no cover
context: "Context" = context
# NOTE: grep returns an exit code of 1 if it doesn't find anything
# (which will be good in this case).
# Concerning the weird last grep command see:
# http://manpages.ubuntu.com/manpages/precise/en/man1/git-status.1.html
result: "Result" = context.run(
f'git -C "{REPO_PARENT_DIR / repo_folder}" status --porcelain '
f"{docs_api_ref_dir.relative_to(REPO_PARENT_DIR / repo_folder)} | "
"grep -E '^[? MARC][?MD]' || exit 0",
hide=True,
)
if result.stdout:
sys.exit(
"The following files have been changed/added, please stage "
f"them:\n\n{result.stdout}"
)
|