Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ which can seen by running ``sphinx-autobuild --help``:
--delay DELAY how long to wait before opening the browser
--watch DIR additional directories to watch
--pre-build COMMAND additional command(s) to run prior to building the documentation
--post-build COMMAND additional command(s) to run after building the documentation

Using with Makefile
-------------------
Expand Down Expand Up @@ -140,6 +141,18 @@ to avoid needing to manually manage ports and opening browser windows
sphinx-autobuild --port=0 --open-browser pikachu/docs pikachu/docs/_build/html &
sphinx-autobuild --port=0 --open-browser magikarp/docs magickarp/docs/_build/html &

Notifications for build cycles
------------------------------

When running sphinx-autobuild as a daemon, users may need to be notified when
the build starts and ends (require libnotify and a notification server).

.. code-block:: bash

sphinx-autobuild docs docs/_build/html/ \
--pre-build 'notify-send "sphinx-autobuild: build start"' \
--post-build 'notify-send "sphinx-autobuild: build end"'

Relevant Sphinx Bugs
====================

Expand Down
10 changes: 9 additions & 1 deletion sphinx_autobuild/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,12 @@ def main(argv=()):
url_host = f"{host_name}:{port_num}"

pre_build_commands = list(map(shlex.split, args.pre_build))

post_build_commands = list(map(shlex.split, args.post_build))
builder = Builder(
build_args,
url_host=url_host,
pre_build_commands=pre_build_commands,
post_build_commands=post_build_commands,
)

watch_dirs = [src_dir] + args.additional_watched_dirs
Expand Down Expand Up @@ -233,6 +234,13 @@ def _add_autobuild_arguments(parser):
default=[],
help="additional command(s) to run prior to building the documentation",
)
group.add_argument(
"--post-build",
action="append",
metavar="COMMAND",
default=[],
help="additional command(s) to run after building the documentation",
)
return group


Expand Down
53 changes: 34 additions & 19 deletions sphinx_autobuild/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,33 +15,24 @@


class Builder:
def __init__(self, sphinx_args, *, url_host, pre_build_commands):
def __init__(
self, sphinx_args, *, url_host, pre_build_commands, post_build_commands
):
self.sphinx_args = sphinx_args
self.pre_build_commands = pre_build_commands
self.post_build_commands = post_build_commands
self.uri = f"http://{url_host}"

def __call__(self, *, changed_paths: Sequence[Path]):
"""Generate the documentation using ``sphinx``."""
if changed_paths:
cwd = Path.cwd()
rel_paths = []
for changed_path in changed_paths[:5]:
if not changed_path.exists():
continue
with contextlib.suppress(ValueError):
changed_path = changed_path.relative_to(cwd)
rel_paths.append(changed_path.as_posix())
if rel_paths:
show_message(f"Detected changes ({', '.join(rel_paths)})")
show_message("Rebuilding...")

def _run_commands(self, commands, log_context):
try:
for command in self.pre_build_commands:
show_message("pre-build")
for command in commands:
show_message(log_context)
show_command(command)
subprocess.run(command, check=True)
except subprocess.CalledProcessError as e:
print(f"Pre-build command exited with exit code: {e.returncode}")
print(
f"{log_context.title()} command exited with exit code: {e.returncode}"
)
print(
"Please fix the cause of the error above or press Ctrl+C to stop the "
"server."
Expand All @@ -53,6 +44,26 @@ def __call__(self, *, changed_paths: Sequence[Path]):
"server."
)
traceback.print_exception(e)
return e.returncode
else:
return 0

def __call__(self, *, changed_paths: Sequence[Path]):
"""Generate the documentation using ``sphinx``."""
if changed_paths:
cwd = Path.cwd()
rel_paths = []
for changed_path in changed_paths[:5]:
if not changed_path.exists():
continue
with contextlib.suppress(ValueError):
changed_path = changed_path.relative_to(cwd)
rel_paths.append(changed_path.as_posix())
if rel_paths:
show_message(f"Detected changes ({', '.join(rel_paths)})")
show_message("Rebuilding...")

if self._run_commands(self.pre_build_commands, "pre-build") != 0:
return

if sphinx.version_info[:3] >= (7, 2, 3):
Expand All @@ -70,5 +81,9 @@ def __call__(self, *, changed_paths: Sequence[Path]):
"Please fix the cause of the error above or press Ctrl+C to stop the "
"server."
)
else:
# Run the post-build commands only if the build was successful
self._run_commands(self.post_build_commands, "post-build")

# Remind the user of the server URL for convenience.
show_message(f"Serving on {self.uri}")
5 changes: 4 additions & 1 deletion tests/test_application.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,10 @@ def test_application(tmp_path):
url_host = "127.0.0.1:7777"
ignore_handler = IgnoreFilter([out_dir], [])
builder = Builder(
[str(src_dir), str(out_dir)], url_host=url_host, pre_build_commands=[]
[str(src_dir), str(out_dir)],
url_host=url_host,
pre_build_commands=[],
post_build_commands=[],
)
app = _create_app([src_dir], ignore_handler, builder, out_dir, url_host)
client = TestClient(app)
Expand Down