diff --git a/.github/workflows/python-package.yml b/.github/workflows/python-package.yml
index 4494c35de..34e527063 100644
--- a/.github/workflows/python-package.yml
+++ b/.github/workflows/python-package.yml
@@ -14,7 +14,7 @@ jobs:
strategy:
fail-fast: false
matrix:
- python-version: [3.8, 3.9, 3.10, 3.11, 3.12]
+ python-version: [3.9, 3.10, 3.11, 3.12, 3.13, 3.14, 3.15]
runs-on: ubuntu-latest
steps:
@@ -47,13 +47,15 @@ jobs:
- name: Test with pytest
uses: addnab/docker-run-action@v3
with:
- image: fluxrm/flux-core:focal
+ image: fluxrm/flux-core:noble
options: -v ${{ github.workspace }}:/workspace -u root
run: |
+ set -x
+ set -e
cd /workspace
echo "Running in ${PWD}"
sudo apt update
- sudo apt install -y openssh-server openssh-client netcat-traditional
+ sudo apt install -y openssh-server openssh-client netcat-traditional python3.12-venv
mkdir -p "$HOME/.ssh"
chmod 0755 "$HOME"
chmod 0700 "$HOME/.ssh"
@@ -62,9 +64,14 @@ jobs:
chmod 600 "$HOME/.ssh/authorized_keys"
ls -la /etc/init.d/
sudo /etc/init.d/ssh start
+ which python3
+ python3 -m venv .venv
+ . .venv/bin/activate
pip install -r requirements.txt
pip install -r requirements-dev.txt
+ pip install -r requirements-tests.txt
pip install -r requirements-connector-radical.txt
- make launcher-scripts
+ # See above
+ pip uninstall -y psij-python
make install
- PYTHONPATH=$(flux env | grep PYTHONPATH | sed -E 's/.*PYTHONPATH="(.*)"/\1/') OMPI_ALLOW_RUN_AS_ROOT=1 OMPI_ALLOW_RUN_AS_ROOT_CONFIRM=1 make tests
+ PYTHONPATH=$(flux env | grep PYTHONPATH | sed -E 's/.*PYTHONPATH="(.*)"/\1/'):$PWD/tests/plugins1:$PWD/tests/plugins2 OMPI_ALLOW_RUN_AS_ROOT=1 OMPI_ALLOW_RUN_AS_ROOT_CONFIRM=1 make tests
diff --git a/Makefile b/Makefile
index 0c5c07623..dca8948c6 100644
--- a/Makefile
+++ b/Makefile
@@ -58,7 +58,7 @@ web-docs:
rm -rf docs/.generated
rm -rf docs/.web-build
git fetch --all --tags
- PSIJ_WEB_DOCS=1 sphinx-multiversion docs docs/.web-build
+ PSIJ_WEB_DOCS=1 ${PYTHON} web/build-versions
PSIJ_WEB_DOCS=1 sphinx-build --keep-going -n -W -b html docs docs/.web-build/v/dev
.PHONY: web-docs-dev
diff --git a/docs/_static/extras.js b/docs/_static/extras.js
index e8473a08d..f2aed8964 100644
--- a/docs/_static/extras.js
+++ b/docs/_static/extras.js
@@ -42,6 +42,19 @@ $(document).ready(function() {
$("dl.attribute > dt.sig").each(function() {
$(this).prepend("attribute");
});
+ // Parameters seem a bit messed up when using the typechecked decorator from
+ // typeguard
+ $("em.sig-param > .n > .pre").each(function() {
+ let text = $(this).text();
+ let ix = text.indexOf("=");
+ if (ix > 0) {
+ let name = text.substring(0, ix);
+ let rest = text.substring(ix + 1);
+ $(this).text(name);
+ $(this).parent().parent().append($("").addClass("o").append($("").addClass("pre").text("=")));
+ $(this).parent().parent().append($("").addClass("default_value").append($("").addClass("pre").text(rest)));
+ }
+ });
});
function detectAll(selectorType) {
diff --git a/docs/api.tree b/docs/api.tree
index 78a8d0f60..7a4249b31 100644
--- a/docs/api.tree
+++ b/docs/api.tree
@@ -1,51 +1,50 @@
-PSI/J Core
- psij.Job
- psij.JobSpec
- psij.JobAttributes
- psij.ResourceSpec
- psij.ResourceSpecV1
- psij.JobStatus
- psij.JobState
-
- Serialization
- psij.serialize.Export
- psij.serialize.Import
-
- Miscellaneous
- psij.utils
- psij.version
- psij.descriptor.Descriptor
-
- Exceptions
- psij.exceptions
-
-Executors
- "The concrete executor implementations provided by this version of PSI/J Python are:"
-
- .. _available-executors:
-
- +executors
-
-Executor Infrastructure
- psij.JobExecutor
- psij.JobExecutorConfig
- psij.executors.batch.batch_scheduler_executor
- psij.executors.batch.batch_scheduler_executor.BatchSchedulerExecutor
- psij.executors.batch.batch_scheduler_executor.BatchSchedulerExecutorConfig
- ~psij.executors.batch.batch_scheduler_executor.check_status_exit_code
- psij.executors.batch.script_generator.SubmitScriptGenerator
- psij.executors.batch.script_generator.TemplatedScriptGenerator
- psij.executors.batch.template_function_library
-
-
-Launchers
-
- .. _available-launchers:
-
- +launchers
-
-
-Launcher Infrastructure
- psij.Launcher
- psij.launchers.script_based_launcher.ScriptBasedLauncher
+The PSI/J API
+
+ PSI/J Core
+ psij.Job
+ psij.JobSpec
+ psij.JobAttributes
+ psij.ResourceSpec
+ psij.ResourceSpecV1
+ psij.JobStatus
+ psij.JobState
+
+ Serialization
+ psij.serialize.Export
+ psij.serialize.Import
+
+ Miscellaneous
+ psij.utils
+ psij.version
+ psij.descriptor.Descriptor
+
+ Exceptions
+ psij.exceptions
+
+ Executors
+ "The concrete executor implementations provided by this version of PSI/J Python are:"
+
+ .. _available-executors:
+
+ +executors
+
+ Executor Infrastructure
+ psij.JobExecutor
+ psij.JobExecutorConfig
+ psij.executors.batch.batch_scheduler_executor
+ psij.executors.batch.script_generator.SubmitScriptGenerator
+ psij.executors.batch.script_generator.TemplatedScriptGenerator
+ psij.executors.batch.template_function_library
+
+
+ Launchers
+
+ .. _available-launchers:
+
+ +launchers
+
+
+ Launcher Infrastructure
+ psij.Launcher
+ psij.launchers.script_based_launcher.ScriptBasedLauncher
diff --git a/docs/conf.py b/docs/conf.py
index a64ca6a88..db0b2869e 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -1,10 +1,11 @@
import os
-from typing import List, Tuple
import subprocess
+
+import docutils.nodes
+import sphinx.domains.python
import sys
-import sphinx_rtd_theme
from sphinx.ext.apidoc import main
web_docs = False
@@ -19,10 +20,9 @@
project = u'PSI/J'
copyright = u'The ExaWorks Team'
if web_docs:
- html_theme = 'cloud'
+ html_theme = 'cloud'
else:
html_theme = 'sphinx_rtd_theme'
- html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
html_favicon = 'favicon.ico'
autoclass_content = 'both'
add_module_names = False
@@ -46,11 +46,6 @@
# so we can display that where the broken version would otherwise
# have appeared.
html_title = "PSI/J"
- # Multi-version
- smv_branch_whitelist = '^matchmeifyoucan$'
- smv_remote_whitelist = None
- smv_released_pattern = r'^\d+\.\d+\.\d+(\..*)?$'
- smv_outputdir_format = 'v/{ref.name}'
html_sidebars = {'**': ['globaltoc.html', 'relations.html', 'sourcelink.html', 'searchbox.html']}
@@ -62,21 +57,29 @@
# Setup Sphinx extensions (and associated variables)
extensions = [
- 'sphinx.ext.napoleon',
'sphinx.ext.autodoc',
- 'sphinx.ext.autodoc.typehints',
+ 'sphinx.ext.napoleon',
'sphinx.ext.intersphinx',
- 'sphinx.ext.viewcode',
+ 'sphinx.ext.viewcode'
]
-if web_docs:
- extensions.append('sphinx_multiversion')
autodoc_typehints = "description"
autodoc_typehints_format = "short"
autodoc_default_options = {
'show-inheritance': True
}
+autodoc_typehints_description_target = "documented"
+autodoc_preserve_defaults = True
+typehints_use_signature_return = True
+
+if web_docs:
+ # properties and attributes before methods
+ from sphinx.ext import autodoc
+ autodoc.AttributeDocumenter.member_order = 40
+ autodoc.PropertyDocumenter.member_order = 40
+ autodoc.MethodDocumenter.member_order = 50
+
release = None
version = None
@@ -97,7 +100,7 @@ def read_version(docs_dir):
read_version(my_dir)
intersphinx_mapping = {
- 'python': ('https://docs.python.org/3', None),
+ 'python': (f'https://docs.python.org/3.8', None),
}
# -- Setup for Sphinx API Docs -----------------------------------------------
@@ -119,25 +122,7 @@ def run_apidoc(sphinx):
main(['-f', '-t', os.path.join(my_dir, '_sphinx'), '-o', output_path, src_dir])
-# The following is a hack to allow returns in numpy style doctstrings to
-# not duplicate the return type specified by the normal type hints.
-# This was taken from https://github.com/svenevs/elba
-# It was submitted as a patch to the napoleon extension. Unfortunately,
-# it was rejected by the maintainers of napoleon
-# (see https://github.com/sphinx-doc/sphinx/issues/7077).
-def _consume_returns_section(self) -> List[Tuple[str, str, List[str]]]:
- self._consume_empty()
- desc_lines = []
- while not self._is_section_break():
- desc_lines.append(next(self._line_iter))
-
- return [("", "", desc_lines)]
-
-from sphinx.ext.napoleon.docstring import NumpyDocstring
-NumpyDocstring._consume_returns_section = _consume_returns_section
-
-
-# And this is for "More than one target found for cross-reference"
+# This is for "More than one target found for cross-reference"
# See https://github.com/sphinx-doc/sphinx/issues/3866
from sphinx.domains.python import PythonDomain
@@ -157,7 +142,45 @@ def find_obj(self, env, modname, classname, name, type, searchmode=0):
else:
return orig_matches
+
+def _check_children(node, recurse):
+ replace = {}
+ found = False
+ for i in range(len(node)):
+ item = node[i]
+ if found and isinstance(item, docutils.nodes.Text) and item.astext() == ')':
+ replace[i] = ''
+ if found and isinstance(item, docutils.nodes.Text) and item.astext() == ' -- ':
+ replace[i] = '\n'
+ para = docutils.nodes.paragraph()
+ for j in range(i + 1, len(node)):
+ para += node[j]
+ node.remove(node[j])
+ node += para
+
+ if isinstance(item, docutils.nodes.Text) and item.astext() == ' (':
+ replace[i] = ': '
+ found = True
+ if recurse and isinstance(item, docutils.nodes.list_item):
+ _check_children(item[0], False)
+
+ for i, t in replace.items():
+ node[i] = docutils.nodes.Text(t)
+
+
+def make_field(self, types, domain, items, env = None, inliner = None, location = None):
+ field = self.make_field_prev(types, domain, items, env=env, inliner=inliner, location=location)
+ bodynode = field[1][0]
+ _check_children(bodynode, True)
+
+ return field
+
+
# launch setup
def setup(app):
app.add_domain(MyPythonDomain, override=True)
+ if web_docs:
+ sphinx.domains.python.PyTypedField.make_field_prev = sphinx.domains.python.PyTypedField.make_field
+ sphinx.domains.python.PyTypedField.make_field = make_field
app.connect('builder-inited', run_apidoc)
+
diff --git a/docs/generate.py b/docs/generate.py
index 6662ba545..3c32f0112 100755
--- a/docs/generate.py
+++ b/docs/generate.py
@@ -13,7 +13,7 @@
import psij
-HEADING_CHARS = ['-', '^', '~', '"', '*']
+HEADING_CHARS = ['=', '-', '^', '~', '"', '*']
seen_names = set()
@@ -50,6 +50,10 @@ def is_function(name: str) -> bool:
return inspect.isfunction(get_object(name))
+def get_module_name(fqn: str) -> str:
+ return fqn.split('.')[-1]
+
+
def get_module_classes(name: str) -> List[str]:
try:
classes = set()
@@ -101,7 +105,7 @@ def generate_tree() -> None:
out.write('.. toctree::\n %s\n\n' % name[:-4])
elif is_module(name):
print('Module: %s' % name)
- write_heading(out, name + ' module', indent_level)
+ write_heading(out, get_module_name(name) + ' module', indent_level)
out.write('.. automodule:: %s\n :members:\n\n' % name)
print('%s -> %s' % (name, get_module_classes(name)))
seen_names.update(get_module_classes(name))
@@ -118,7 +122,7 @@ def generate_tree() -> None:
print('Class: %s' % name)
cls = get_object(name)
write_heading(out, cls.__name__, indent_level)
- out.write('.. autoclass:: %s\n :members:\n' % name)
+ autoclass(out, name, end=False)
if name in seen_names or cls.__name__ in seen_names:
out.write(' :noindex:\n')
out.write('\n')
@@ -128,6 +132,14 @@ def generate_tree() -> None:
write_heading(out, name, indent_level)
+def autoclass(out: TextIOBase, name: str, end=True) -> None:
+ out.write(f'.. autoclass:: {name}\n')
+ out.write(' :members:\n')
+ out.write(' :member-order: groupwise\n')
+ if end:
+ out.write('\n')
+
+
def generate_executors(out: TextIOBase) -> None:
from psij import JobExecutor
@@ -135,17 +147,17 @@ def generate_executors(out: TextIOBase) -> None:
versions = JobExecutor._executors[name.lower()]
assert len(versions) == 1
qname = versions[0].desc.cls
- write_heading(out, versions[0].desc.nice_name, 1)
- out.write('.. autoclass:: %s\n\n' % qname)
+ write_heading(out, versions[0].desc.nice_name, 2)
+ autoclass(out, qname)
seen_names.add(qname)
module_name, class_name = split_class_name(qname)
classes = get_module_classes(module_name)
for cls in classes:
if cls != class_name:
- write_heading(out, cls, 2)
+ write_heading(out, cls, 3)
qname = module_name + '.' + cls
- out.write('.. autoclass:: %s\n\n' % qname)
+ autoclass(out, qname)
seen_names.add(cls)
@@ -156,8 +168,8 @@ def generate_launchers(out: TextIOBase) -> None:
versions = Launcher._launchers[name.lower()]
assert len(versions) == 1
qname = versions[0].desc.cls
- write_heading(out, versions[0].desc.nice_name, 1)
- out.write('.. autoclass:: %s\n\n' % qname)
+ write_heading(out, versions[0].desc.nice_name, 2)
+ autoclass(out, qname)
seen_names.add(qname)
@@ -200,7 +212,7 @@ def generate_index() -> None:
for name, val in _sorted_names(classes):
write_heading(out, name, 2)
qname = val.__module__ + '.' + name
- out.write('.. autoclass:: %s\n' % qname)
+ autoclass(out, qname, end=False)
if qname in seen_names or name in seen_names:
out.write(' :noindex:\n')
out.write('\n\n')
diff --git a/docs/index.rst b/docs/index.rst
index daba1c642..3558a5808 100644
--- a/docs/index.rst
+++ b/docs/index.rst
@@ -30,7 +30,7 @@ computational scientists and workflow developers a common API for interacting
.. toctree::
- :maxdepth: 3
+ :maxdepth: 4
getting_started
user_guide
diff --git a/requirements-dev.txt b/requirements-dev.txt
index 088b8869b..2e212ccad 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -11,3 +11,4 @@ flake8
flake8-docstrings
autopep8
types-requests
+setuptools
\ No newline at end of file
diff --git a/requirements-docs.txt b/requirements-docs.txt
index 4da7ced58..97bc3e084 100644
--- a/requirements-docs.txt
+++ b/requirements-docs.txt
@@ -7,20 +7,18 @@
# Docs
six
-Sphinx==4.5.0
+Sphinx>=7.0,<9.0
sphinx_rtd_theme
-sphinx-tabs==3.2.0
-sphinx-multiversion
+sphinx-tabs>=3.4.7,<=3.5.0
-# These are not requirements for PSI/J, but we must pin the version
-# since Sphinx 4.5.0 does not properly do so and later versions of
-# these plugins require Sphinx >= 5.0.0
-sphinxcontrib-applehelp==1.0.4
-sphinxcontrib-devhelp==1.0.2
-sphinxcontrib-htmlhelp==2.0.1
-sphinxcontrib-serializinghtml==1.1.5
-sphinxcontrib-qthelp==1.0.3
+# These are not requirements for PSI/J, but we pin the version
+# for compatibility reasons
+sphinxcontrib-applehelp==2.0.0
+sphinxcontrib-devhelp==2.0.0
+sphinxcontrib-htmlhelp==2.1.0
+sphinxcontrib-serializinghtml==2.0.0
+sphinxcontrib-qthelp==2.0.0
# For the web version of the docs
cloud_sptheme == 1.10.1.post20200504175005
-# sphinx-autodoc-typehints
+sphinx-autodoc-typehints
diff --git a/src/psij/descriptor.py b/src/psij/descriptor.py
index 16dd3de85..5becbd345 100644
--- a/src/psij/descriptor.py
+++ b/src/psij/descriptor.py
@@ -47,10 +47,10 @@ class Descriptor(object):
This class is used to enable PSI/J to discover and register executors and/or launchers.
Executors wanting to register with PSI/J must place an instance of this class in a global
- module list named `__PSI_J_EXECUTORS__` or `__PSI_J_LAUNCHERS__` in a module placed in the
- `psij-descriptors` *namespace package*. In other words, in order to automatically register an
- executor or launcher, a python file should be created inside a `psij-descriptors` package, such
- as:
+ module list named ``__PSI_J_EXECUTORS__`` or ``__PSI_J_LAUNCHERS__`` in a module placed in the
+ ``psij-descriptors`` *namespace package*. In other words, in order to automatically register an
+ executor or launcher, a python file should be created inside a ``psij-descriptors`` package,
+ such as:
.. code-block:: none
@@ -59,12 +59,12 @@ class Descriptor(object):
psij-descriptors/
descriptors_for_project.py
- It is *essential* that the `psij-descriptors` package not contain an `__init__.py` file in
+ It is *essential* that the ``psij-descriptors`` package not contain an ``__init__.py`` file in
order for Python to treat the package as a namespace package. This allows Python to combine
- multiple `psij-descriptors` directories into one, which, in turn, allows PSI/J to detect and
+ multiple ``psij-descriptors`` directories into one, which, in turn, allows PSI/J to detect and
load all descriptors that can be found in Python's library search path.
- The contents of `descriptors_for_project.py` could then be as follows:
+ The contents of ``descriptors_for_project.py`` could then be as follows:
.. code-block:: python
@@ -83,10 +83,10 @@ class Descriptor(object):
...
]
- where `` stands for the name used to instantiate the executor or launcher,
- `` is a version string such as `1.0.2`, and `` is the fully qualified
- class name that implements the executor or launcher such as
- `psij.executors.local.LocalJobExecutor`.
+ where ```` stands for the name used to instantiate the executor or launcher,
+ ```` is a version string such as ``1.0.2``, and ```` is the fully
+ qualified class name that implements the executor or launcher such as
+ ``psij.executors.local.LocalJobExecutor``.
"""
def __init__(self, name: str, version: Version, cls: str,
@@ -107,11 +107,12 @@ def __init__(self, name: str, version: Version, cls: str,
A fully qualified name pointing to the class implementing an executor or launcher.
aliases:
An optional set of alternative names to make the executor available under as if
- its `name` was the alias.
+ its ``name`` was the alias.
nice_name:
An optional string to use whenever a user-friendly name needs to be displayed to
- a user. For example, a nice name for `pbs` would be `PBS` or `Portable Batch System`.
- If not specified, the `nice_name` defaults to the value of the `name` parameter.
+ a user. For example, a nice name for ``pbs`` would be ``PBS`` or
+ ``Portable Batch System``. If not specified, the ``nice_name`` defaults to the value of
+ the ``name`` parameter.
"""
self.name = name
self.version = version
diff --git a/src/psij/exceptions.py b/src/psij/exceptions.py
index 8e543d9d1..1559047b8 100644
--- a/src/psij/exceptions.py
+++ b/src/psij/exceptions.py
@@ -49,7 +49,7 @@ def __init__(self, message: str, exception: Optional[Exception] = None,
"""
self.transient = transient
"""
- Returns `True` if the underlying condition that triggered this exception is transient.
+ Returns ``True`` if the underlying condition that triggered this exception is transient.
Jobs that cannot be submitted due to a transient exceptional condition have chance of being
successfully re-submitted at a later time, which is a suggestion to client code that it
could re-attempt the operation that triggered this exception. However, the exact chances of
diff --git a/src/psij/executors/batch/batch_scheduler_executor.py b/src/psij/executors/batch/batch_scheduler_executor.py
index 5d320566a..800246a3a 100644
--- a/src/psij/executors/batch/batch_scheduler_executor.py
+++ b/src/psij/executors/batch/batch_scheduler_executor.py
@@ -145,7 +145,7 @@ class BatchSchedulerExecutor(JobExecutor):
that of :func:`~generate_submit_script`. Besides an opened file which points to where the
contents of the submit script are to be written, the parameters to
:func:`~generate_submit_script` are the :class:`~psij.Job` that is being submitted and a
- `context`, which is a dictionary with the following structure::
+ ``context``, which is a dictionary with the following structure::
{
'job':
@@ -156,7 +156,7 @@ class BatchSchedulerExecutor(JobExecutor):
}
}
- The *script directory* is a directory (typically `~/.psij/work`) where submit scripts are
+ The *script directory* is a directory (typically ``~/.psij/work``) where submit scripts are
written; it is also used for auxiliary files, such as the *exit code file* (see below) or the
*script output file*.
@@ -169,11 +169,11 @@ class BatchSchedulerExecutor(JobExecutor):
The submit script *must* perform two essential actions:
1. redirect the output of the executable part of the script to the *script output file*,
- which is a file in `` named `.out`, where `` is the id
- given to the job by the queuing system.
+ which is a file in ```` named ``.out``, where ```` is the
+ id given to the job by the queuing system.
2. store the exit code of the launch command in the *exit code file* named
- `.ec`, also inside ``.
+ ``.ec``, also inside ````.
Additionally, where appropriate, the submit script should set the environment variable named
``PSIJ_NODEFILE`` to point to a file containing a list of nodes that are allocated for the job,
@@ -181,12 +181,12 @@ class BatchSchedulerExecutor(JobExecutor):
Once the submit script is generated, the executor renders the submit command using
:func:`~get_submit_command` and executes it. Its output is then parsed using
- :func:`~job_id_from_submit_output` to retrieve the `native_id` of the job. Subsequently, the
+ :func:`~job_id_from_submit_output` to retrieve the ``native_id`` of the job. Subsequently, the
job is registered with the queue polling thread.
The queue polling thread regularly polls the batch scheduler queue for updates to job states.
It builds the command for polling the queue using :func:`~get_status_command`, which takes a
- list of `native_id` strings corresponding to all registered jobs. Implementations are
+ list of ``native_id`` strings corresponding to all registered jobs. Implementations are
strongly encouraged to restrict the query of job states to the specified jobs in order to reduce
the load on the queuing system. The output of the status command is then parsed using
:func:`~parse_status_output` and the status of each job is updated accordingly. If the status
@@ -261,8 +261,8 @@ def _get_launcher_from_job(self, job: Job) -> Launcher:
def cancel(self, job: Job) -> None:
"""Cancels a job if it has not otherwise completed.
- A command is constructed using :func:`~get_cancel_command` and executed in order to cancel
- the job. Also see :func:`~psij.JobExecutor.cancel`.
+ A command is constructed using :meth:`~.BatchSchedulerExecutor.get_cancel_command` and
+ executed in order to cancel the job. Also see :func:`~psij.JobExecutor.cancel`.
"""
if job.native_id is None:
raise SubmitException('Job does not have a native ID.')
@@ -283,7 +283,7 @@ def cancel(self, job: Job) -> None:
def attach(self, job: Job, native_id: str) -> None:
"""Attaches a job to a native job.
- Attempts to connect `job` to a native job with `native_id` such that the job correctly
+ Attempts to connect ``job`` to a native job with ``native_id`` such that the job correctly
reflects updates to the status of the native job. If the native job was previously
submitted using this executor (hence having an *exit code file* and a *script output file*),
the executor will attempt to retrieve the exit code and errors from the job. Otherwise, it
@@ -338,7 +338,7 @@ def get_submit_command(self, job: Job, submit_file_path: Path) -> List[str]:
Returns
-------
A list of strings representing the command and arguments to execute in order to submit
- the job, such as `['qsub', str(submit_file_path)]`.
+ the job, such as ``['qsub', str(submit_file_path)]``.
"""
pass
@@ -358,7 +358,8 @@ def job_id_from_submit_output(self, out: str) -> str:
Returns
-------
- A string representing the native id of the newly submitted job.
+ :
+ A string representing the native id of the newly submitted job.
"""
pass
@@ -376,7 +377,7 @@ def get_cancel_command(self, native_id: str) -> List[str]:
Returns
-------
A list of strings representing the command and arguments to execute in order to cancel
- the job, such as, e.g., `['qdel', native_id]`.
+ the job, such as, e.g., ``['qdel', native_id]``.
"""
pass
@@ -451,7 +452,7 @@ def parse_status_output(self, exit_code: int, out: str) -> Dict[str, JobStatus]:
-------
A dictionary mapping native job ids to :class:`~psij.JobStatus` objects. The
implementation of this method need not process the *exit code file* or the *script
- output file* since it is done by the base `BatchSchedulerExecutor` implementation.
+ output file* since it is done by the base ``BatchSchedulerExecutor`` implementation.
"""
pass
@@ -470,7 +471,8 @@ def get_list_command(self) -> List[str]:
pass
def parse_list_output(self, out: str) -> List[str]:
- """Parses the output of the command obtained from :func:`~get_list_command`.
+ """Parses the output of the command obtained from
+ :meth:`~~.BatchSchedulerExecutor.get_list_command`.
The default implementation of this method assumes that the output has no header and
consists of native IDs, one per line, possibly surrounded by whitespace. Concrete
@@ -479,7 +481,8 @@ def parse_list_output(self, out: str) -> List[str]:
Parameters
----------
out
- The output from the "list" command as returned by :func:`~get_list_command`.
+ The output from the "list" command as returned by
+ :meth:`~.BatchSchedulerExecutor.get_list_command`.
Returns
-------
A list of strings representing the native IDs of the jobs known to the LRM for the current
@@ -639,7 +642,7 @@ def list(self) -> List[str]:
"""Returns a list of jobs known to the underlying implementation.
See :func:`~psij.JobExecutor.list`.
- The returned list is a list of `native_id` strings representing jobs known to the
+ The returned list is a list of ``native_id`` strings representing jobs known to the
underlying batch scheduler implementation, whether submitted through this executor or not.
Implementations are encouraged to restrict the results to jobs accessible by the current
user.
diff --git a/src/psij/executors/batch/escape_functions.py b/src/psij/executors/batch/escape_functions.py
index 7bfd2e400..7db1da511 100644
--- a/src/psij/executors/batch/escape_functions.py
+++ b/src/psij/executors/batch/escape_functions.py
@@ -17,7 +17,8 @@ def bash_escape(o: object) -> str:
Returns
-------
- An escaped representation of the object that can be substituted in bash scripts.
+ :
+ An escaped representation of the object that can be substituted in bash scripts.
"""
if isinstance(o, int):
return str(o)
diff --git a/src/psij/executors/batch/lsf.py b/src/psij/executors/batch/lsf.py
index 2a91b45a2..37c098db1 100644
--- a/src/psij/executors/batch/lsf.py
+++ b/src/psij/executors/batch/lsf.py
@@ -36,10 +36,10 @@ class LsfJobExecutor(BatchSchedulerExecutor):
Creates a batch script with #BSUB directives when submitting a job.
- Renders all custom attributes of the form `lsf.` into the corresponding
+ Renders all custom attributes of the form ``lsf.`` into the corresponding
LSF directive. For example, setting
- `job.spec.attributes.custom_attributes['lsf.core_isolation'] = '0' results in a
- `#BSUB -core_isolation 0` directive being placed in the submit script.
+ ``job.spec.attributes.custom_attributes['lsf.core_isolation'] = '0'`` results in a
+ ``#BSUB -core_isolation 0`` directive being placed in the submit script.
"""
# see https://www.ibm.com/docs/en/spectrum-lsf/10.1.0?topic=bjobs-description
diff --git a/src/psij/executors/batch/pbs_classic.py b/src/psij/executors/batch/pbs_classic.py
index baa0f1f1a..cae933c11 100644
--- a/src/psij/executors/batch/pbs_classic.py
+++ b/src/psij/executors/batch/pbs_classic.py
@@ -9,7 +9,7 @@ class PBSClassicJobExecutor(GenericPBSJobExecutor):
"""A :class:`~psij.JobExecutor` for classic PBS systems.
This executor uses resource specifications specific to Open PBS. Specifically,
- this executor uses the `-l nodes=n:ppn=m` way of specifying nodes, which
+ this executor uses the ``-l nodes=n:ppn=m`` way of specifying nodes, which
differs from the scheme used by PBS Pro.
"""
diff --git a/src/psij/executors/batch/slurm.py b/src/psij/executors/batch/slurm.py
index a9198a044..4a7238132 100644
--- a/src/psij/executors/batch/slurm.py
+++ b/src/psij/executors/batch/slurm.py
@@ -29,10 +29,10 @@ class SlurmJobExecutor(BatchSchedulerExecutor):
Creates a batch script with #SBATCH directives when submitting a job.
- Renders all custom attributes set on a job's attributes with a `slurm.` prefix into
+ Renders all custom attributes set on a job's attributes with a ``slurm.`` prefix into
corresponding Slurm directives with long-form parameters. For example,
- `job.spec.attributes.custom_attributes['slurm.qos'] = 'debug'` causes a directive
- `#SBATCH --qos=debug` to be placed in the submit script.
+ ``job.spec.attributes.custom_attributes['slurm.qos'] = 'debug'`` causes a directive
+ ``#SBATCH --qos=debug`` to be placed in the submit script.
"""
# see https://slurm.schedmd.com/squeue.html
diff --git a/src/psij/executors/flux.py b/src/psij/executors/flux.py
index 25aeeb4ae..b7909a64e 100644
--- a/src/psij/executors/flux.py
+++ b/src/psij/executors/flux.py
@@ -56,7 +56,7 @@ def __init__(
) -> None:
"""
:param url: Not used, but required by the spec for automatic initialization.
- :param config: The `FluxJobExecutor` does not have any configuration options.
+ :param config: The ``FluxJobExecutor`` does not have any configuration options.
"""
# TODO: url is not passed
# if not url.startswith('flux://'):
diff --git a/src/psij/executors/local.py b/src/psij/executors/local.py
index 976217e19..81aab5488 100644
--- a/src/psij/executors/local.py
+++ b/src/psij/executors/local.py
@@ -212,20 +212,20 @@ class LocalJobExecutor(JobExecutor):
In Linux, attached jobs always appear to complete with a zero exit code regardless
of the actual exit code.
.. warning::
- Instantiation of a local executor from both parent process and a `fork()`-ed process
- is not guaranteed to work. In general, using `fork()` and multi-threading in Linux is
- unsafe, as suggested by the `fork()` man page. While PSI/J attempts to minimize problems
- that can arise when `fork()` is combined with threads (which are used by PSI/J), no
+ Instantiation of a local executor from both parent process and a ``fork()``-ed process
+ is not guaranteed to work. In general, using ``fork()`` and multi-threading in Linux is
+ unsafe, as suggested by the ``fork()`` man page. While PSI/J attempts to minimize problems
+ that can arise when ``fork()`` is combined with threads (which are used by PSI/J), no
guarantees can be made and the chances of unexpected behavior are high. Please do not use
- PSI/J with `fork()`. If you do, please be mindful that support for using PSI/J with
- `fork()` will be limited.
+ PSI/J with ``fork()``. If you do, please be mindful that support for using PSI/J with
+ ``fork()`` will be limited.
"""
def __init__(self, url: Optional[str] = None,
config: Optional[JobExecutorConfig] = None) -> None:
"""
:param url: Not used, but required by the spec for automatic initialization.
- :param config: The `LocalJobExecutor` does not have any configuration options.
+ :param config: The ``LocalJobExecutor`` does not have any configuration options.
:type config: psij.JobExecutorConfig
"""
super().__init__(url=url, config=config if config else JobExecutorConfig())
@@ -263,9 +263,9 @@ def submit(self, job: Job) -> None:
Successful return of this method indicates that the job has been started locally and all
changes in the job status, including failures, are reported using notifications. If the job
- specification is invalid, an :class:`~psij.InvalidJobException` is thrown. If
+ specification is invalid, an :class:`~psij.exceptions.InvalidJobException` is thrown. If
the actual submission fails for reasons outside the validity of the job,
- a :class:`~psij.SubmitException` is thrown.
+ a :class:`~psij.exceptions.SubmitException` is thrown.
:param job: The job to be submitted.
"""
@@ -360,10 +360,10 @@ def list(self) -> List[str]:
"""
Return a list of ids representing jobs that are running on the underlying implementation.
- Specifically for the `LocalJobExecutor`, this returns a list of `~psij.NativeId` objects
+ Specifically for the ``LocalJobExecutor``, this returns a list of `~psij.NativeId` objects
corresponding to the processes running under the current user on the local machine. These
- processes need not correspond to jobs statrted by calling the `submit()` method of an
- instance of a `LocalJobExecutor`.
+ processes need not correspond to jobs statrted by calling the ``submit()`` method of an
+ instance of a ``LocalJobExecutor``.
:return: The list of `~psij.NativeId` objects corresponding to the current user's
processes running locally.
@@ -378,11 +378,11 @@ def attach(self, job: Job, native_id: str) -> None:
The job must be in the :attr:`~psij.JobState.NEW` state. The exit code of the attached job
will not be available upon completion and a zero exit code will always be returned for jobs
- attached by the `LocalJobExecutor`.
+ attached by the ``LocalJobExecutor``.
:param job: The job to attach.
:param native_id: The native ID of the process to attached to, as obtained through
- :func:`~psij.executors.LocalJobExecutor.list` method.
+ :meth:`~.JobExecutor.list` method.
"""
if job.status.state != JobState.NEW:
raise InvalidJobException('Job must be in the NEW state')
diff --git a/src/psij/executors/rp.py b/src/psij/executors/rp.py
index 1b0b303b7..78717e5a2 100644
--- a/src/psij/executors/rp.py
+++ b/src/psij/executors/rp.py
@@ -96,9 +96,9 @@ def submit(self, job: Job) -> None:
Successful return of this method indicates that the job has been
submitted to RP and all changes in the job status, including failures,
are reported using notifications. If the job specification is invalid,
- an :class:`~psij.InvalidJobException` is thrown. If the actual
+ an :class:`~psij.exceptions.InvalidJobException` is thrown. If the actual
submission fails for reasons outside the validity of the job,
- a :class:`~psij.SubmitException` is thrown.
+ a :class:`~psij.exceptions.SubmitException` is thrown.
:param job: The job to be submitted.
"""
@@ -168,7 +168,7 @@ def attach(self, job: Job, native_id: str) -> None:
:param job: The job to attach.
:param native_id: The native ID of the process to attached to, as
- obtained through :func:`~list` method.
+ obtained through :meth:`~psij.JobExecutor.list` method.
"""
if job.status.state != JobState.NEW:
raise InvalidJobException('Job must be in the NEW state')
diff --git a/src/psij/job.py b/src/psij/job.py
index b36730692..a0ed6dcbb 100644
--- a/src/psij/job.py
+++ b/src/psij/job.py
@@ -27,7 +27,7 @@ class Job(object):
"""
This class represents a PSI/J job.
- It encapsulates all of the information needed to run a job as well as the job’s state.
+ It encapsulates all the information needed to run a job as well as the job’s state.
"""
def __init__(self, spec: Optional[JobSpec] = None) -> None:
@@ -55,10 +55,10 @@ def id(self) -> str:
"""
A read-only property containing the PSI/J job ID.
- The ID is assigned automatically by the implementation when this `Job` object is
- constructed. The ID is guaranteed to be unique on the machine on which the `Job` object
+ The ID is assigned automatically by the implementation when this ``Job`` object is
+ constructed. The ID is guaranteed to be unique on the machine on which the ``Job`` object
was instantiated. The ID does not have to match the ID of the underlying LRM job, but is
- used to identify `Job` instances as seen by a client application.
+ used to identify ``Job`` instances as seen by a client application.
"""
return self._id
@@ -82,9 +82,9 @@ def status(self) -> JobStatus:
It is guaranteed that the status returned by this method is monotonic in time with respect
to the partial ordering of :class:`~psij.JobStatus` types. That is, if
- `job_status_1.state` and `job_status_2.state` are comparable and
- `job_status_1.state < job_status_2.state`, then it is impossible for `job_status_2` to be
- returned by a call placed prior to a call that returns `job_status_1` if both calls are
+ ``job_status_1.state`` and ``job_status_2.state`` are comparable and
+ ``job_status_1.state < job_status_2.state``, then it is impossible for ``job_status_2`` to
+ be returned by a call placed prior to a call that returns ``job_status_1`` if both calls are
placed from the same thread or if a proper memory barrier is placed between the calls.
Furthermore the job is guaranteed to go through all intermediate states in the
`state model `_ before
@@ -176,19 +176,19 @@ def wait(self, timeout: Optional[timedelta] = None,
"""
Waits for the job to reach certain states.
- This method returns either when the job reaches one of the `target_states`, a state
- following one of the `target_states`, a final state, or when an amount of time indicated by
- the `timeout` parameter, if specified, passes. Returns the :class:`~psij.JobStatus` object
- that has one of the desired states or `None` if the timeout is reached. For example,
- `wait(target_states = [JobState.QUEUED]` waits until the job is in any of the `QUEUED`,
- `ACTIVE`, `COMPLETED`, `FAILED`, or `CANCELED` states.
+ This method returns either when the job reaches one of the ``target_states``, a state
+ following one of the ``target_states``, a final state, or when an amount of time indicated
+ by the ``timeout`` parameter, if specified, passes. Returns the :class:`~psij.JobStatus`
+ object that has one of the desired states or ``None`` if the timeout is reached. For
+ example, ``wait(target_states = [JobState.QUEUED])`` waits until the job is in any of the
+ ``QUEUED``, ``ACTIVE``, ``COMPLETED``, ``FAILED``, or ``CANCELED`` states.
:param timeout: An optional timeout after which this method returns even if none of the
- `target_states` was reached. If not specified, wait indefinitely.
+ ``target_states`` was reached. If not specified, wait indefinitely.
:param target_states: A set of states to wait for. If not specified, wait for any
of the :attr:`~psij.JobState.final` states.
:return: returns the :class:`~psij.JobStatus` object that caused the caused this call to
- complete or `None` if the timeout is specified and reached.
+ complete or ``None`` if the timeout is specified and reached.
"""
start = datetime.now()
if not timeout:
@@ -238,7 +238,7 @@ def job_status_changed(self, job: Job, job_status: JobStatus) -> None:
Client code interested in receiving status notifications must implement this method. It is
entirely possible that :attr:`psij.Job.status` when referenced from the body of this
- method would return something different from the `status` passed to this callback. This is
+ method would return something different from the ``status`` passed to this callback. This is
because the status of the job can be updated during the execution of the body of this
method and, in particular, before the potential dereference to :attr:`psij.Job.status` is
made.
@@ -260,5 +260,5 @@ def __init__(self, fn: Callable[[Job, 'psij.JobStatus'], None]):
self.fn = fn
def job_status_changed(self, job: Job, job_status: 'psij.JobStatus') -> None:
- """See :func:`~psij.JobStatusCallback.job_status_changed`."""
+ """See :meth:`~.JobStatusCallback.job_status_changed`."""
self.fn(job, job_status)
diff --git a/src/psij/job_attributes.py b/src/psij/job_attributes.py
index d060fa30e..bb3eaeb85 100644
--- a/src/psij/job_attributes.py
+++ b/src/psij/job_attributes.py
@@ -29,7 +29,7 @@ def __init__(self, duration: timedelta = timedelta(minutes=10),
instruct the backend to send this job to a particular queue.
:param account: An account to use for billing purposes. Please note that the executor
implementation (or batch scheduler) may use a different term for the option used for
- accounting/billing purposes, such as `project`. However, scheduler must map this
+ accounting/billing purposes, such as ``project``. However, scheduler must map this
attribute to the accounting/billing option in the underlying execution mechanism.
:param reservation_id: Allows specifying an advanced reservation ID. Advanced reservations
enable the pre-allocation of a set of resources/compute nodes for a certain duration
@@ -42,11 +42,11 @@ def __init__(self, duration: timedelta = timedelta(minutes=10),
or underlying job execution mechanism that cannot otherwise be passed using the classes
and properties provided by PSI/J. A specific example is that of the subclasses of
:class:`~psij.executors.batch.batch_scheduler_executor.BatchSchedulerExecutor`, which
- look for custom attributes prefixed with their name and a dot (e.g., `slurm.constraint`,
- `pbs.c`, `lsf.core_isolation`) and translate them into the corresponding batch
- scheduler directives (e.g., `#SLURM --constraint=...`, `#PBS -c ...`,
- `#BSUB -core_isolation ...`).
- :param project_name: Deprecated. Please use the `account` attribute.
+ look for custom attributes prefixed with their name and a dot (e.g.,
+ ``slurm.constraint``, ``pbs.c``, ``lsf.core_isolation``) and translate them into the
+ corresponding batch scheduler directives (e.g., ``#SLURM --constraint=...``,
+ ``#PBS -c ...``, ``#BSUB -core_isolation ...``).
+ :param project_name: Deprecated. Please use the ``account`` attribute.
All constructor parameters are accessible as properties.
"""
@@ -59,13 +59,23 @@ def __init__(self, duration: timedelta = timedelta(minutes=10),
self._custom_attributes = custom_attributes
def set_custom_attribute(self, name: str, value: object) -> None:
- """Sets a custom attribute."""
+ """
+ Sets a custom attribute.
+
+ :param name: The attribute name
+ :param value: The attribute value
+ """
if self._custom_attributes is None:
self._custom_attributes = {}
self._custom_attributes[name] = value
def get_custom_attribute(self, name: str) -> Optional[object]:
- """Retrieves the value of a custom attribute."""
+ """
+ Retrieves the value of a custom attribute.
+
+ :param name: The name of the attribute.
+ :return: The value of the attribute.
+ """
if self._custom_attributes is None:
return None
if name not in self._custom_attributes:
@@ -82,13 +92,10 @@ def custom_attributes(self, attrs: Optional[Dict[str, object]]) -> None:
"""
Sets all custom attributes from the given dictionary.
- Existing custom attributes defined on this instance of `JobAttributes`
+ Existing custom attributes defined on this instance of ``JobAttributes``
are removed.
- Parameters
- ----------
- attrs
- A dictionary with the custom attributes to set.
+ :param attrs: A dictionary with the custom attributes to set.
"""
self._custom_attributes = attrs
@@ -120,10 +127,19 @@ def parse_walltime(walltime: str) -> timedelta:
Parses a walltime string into a :class:`~datetime.timedelta`.
The accepted walltime strings formats are:
+
* hh:mm:ss
* hh:mm
* mm
- * n\s*[y|M|d|h|m\s]
+ * n\\s*[y|M|d|h|m\s]
+
+ That is, three numeric groups separated by a ``:`` are interpreted
+ as hours, minutes, and seconds. If there are two such groups separated by a ``:``, then
+ they are interpreted as hours and minutes. If a single number is specified, it is
+ considered to be minutes unless one of the units (``y``, ``M``, ``d``, ``h``, ``m``, or
+ ``s``) are added with or without whitespaces between the number or the unit (e.g., `
+ `10 d``), in which case the number is interpreted as being a multiple of the specified unit
+ (years, months, days, hours, minutes, or seconds, respectively).
Parameters
----------
@@ -161,7 +177,7 @@ def parse_walltime(walltime: str) -> timedelta:
@property
def project_name(self) -> Optional[str]:
- """Deprecated. Please use the `account` attribute."""
+ """Deprecated. Please use the ``account`` attribute."""
return self.account
@project_name.setter
diff --git a/src/psij/job_executor.py b/src/psij/job_executor.py
index 286fc315b..ac1e8ad84 100644
--- a/src/psij/job_executor.py
+++ b/src/psij/job_executor.py
@@ -31,13 +31,13 @@ class JobExecutor(ABC):
def __init__(self, url: Optional[str] = None,
config: Optional[JobExecutorConfig] = None):
"""
- :param url: The URL is a string that a `JobExecutor` implementation can interpret as the
+ :param url: The URL is a string that a ``JobExecutor`` implementation can interpret as the
location of a backend.
- :param config: An configuration specific to each `JobExecutor` implementation. This
- parameter is marked as optional such that concrete `JobExecutor` classes can be
- instantiated with no `config` parameter. However, concrete `JobExecutor` classes
+ :param config: An configuration specific to each ``JobExecutor`` implementation. This
+ parameter is marked as optional such that concrete ``JobExecutor`` classes can be
+ instantiated with no ``config`` parameter. However, concrete ``JobExecutor`` classes
must pass a default configuration up the inheritance tree and ensure that the
- `config` parameter of the ABC constructor is non-null.
+ ``config`` parameter of the ABC constructor is non-null.
"""
self.url = url
assert config
@@ -77,7 +77,7 @@ def _check_job(self, job: Job) -> JobSpec:
These checks are meant to trigger common runtime type errors somewhat early and with clear
error messages. In production software, these checks can be disabled by invoking Python
- with one of the optimization flags (`-O` or `-OO`).
+ with one of the optimization flags (``-O`` or ``-OO``).
Upon completion, this method sets the :attr:`~psij.Job.executor` attribute of the job and
returns the job specification.
@@ -125,11 +125,11 @@ def submit(self, job: Job) -> None:
has not been successfully sent to the underlying implementation, the job status remains
unchanged, and no status notifications about the job will be fired.
- A successful return of this method guarantees that the job's `native_id` property is set.
+ A successful return of this method guarantees that the job's ``native_id`` property is set.
:raises InvalidJobException: Thrown if the job specification cannot be understood.
This exception is fatal in that submitting another job with the exact same details will
- also fail with an `InvalidJobException`. In principle, the underlying
+ also fail with an ``InvalidJobException``. In principle, the underlying
implementation / LRM is the entity ultimately responsible for interpreting a
specification and reporting any errors associated with it. However, in many cases, this
reporting may come after a significant delay. In the interest of failing fast, library
@@ -137,7 +137,7 @@ def submit(self, job: Job) -> None:
this exception as soon as possible if that validation fails.
:raises SubmitException: Thrown if the request cannot be sent to the underlying
- implementation. Unlike `InvalidJobException`, this exception can occur for
+ implementation. Unlike ``InvalidJobException``, this exception can occur for
reasons that are transient.
"""
pass
@@ -152,13 +152,13 @@ def cancel(self, job: Job) -> None:
discretion of the implementation, which may be at some later time. A successful
cancellation is reflected in a change of status of the respective job to
:attr:`~psij.JobState.CANCELED`. User code can synchronously wait until the
- :attr:`~psij.JobState.CANCELED` state is reached using `job.wait(JobState.CANCELED)` or
- even `job.wait()`, since the latter would wait for all final states, including
- `JobState.CANCELED`. In fact, it is recommended that `job.wait()` be used because it is
+ :attr:`~psij.JobState.CANCELED` state is reached using ``job.wait(JobState.CANCELED)`` or
+ even ``job.wait()``, since the latter would wait for all final states, including
+ ``JobState.CANCELED``. In fact, it is recommended that `job.wait()` be used because it is
entirely possible for the job to complete before the cancellation is communicated to the
underlying implementation and before the client code receives the completion notification.
- In such a case, the job will never enter the `CANCELED` state and
- `job.wait(JobState.CANCELED)` would hang indefinitely.
+ In such a case, the job will never enter the ``CANCELED`` state and
+ ``job.wait(JobState.CANCELED)`` would hang indefinitely.
:param job: The job to be canceled.
@@ -197,7 +197,7 @@ def set_job_status_callback(self,
The callback will be invoked whenever a status change occurs for any of the jobs submitted
to this job executor, whether they were submitted with an individual job status callback or
- not. To remove the callback, set it to `None`.
+ not. To remove the callback, set it to ``None``.
:param cb: An instance of :class:`~psij.job.JobStatusCallback` or a callable with two
parameters: job of type :class:`~psij.Job` and job_status of type
@@ -222,15 +222,15 @@ def __str__(self) -> str:
def get_instance(name: str, version_constraint: Optional[str] = None, url: Optional[str] = None,
config: Optional[JobExecutorConfig] = None) -> 'JobExecutor':
"""
- Returns an instance of a `JobExecutor`.
+ Returns an instance of a ``JobExecutor``.
:param name: The name of the executor to return. This must be one of the values returned
- by :func:`~psij.JobExecutor.get_executor_names`. If the value of the `name` parameter
+ by :func:`~psij.JobExecutor.get_executor_names`. If the value of the ``name`` parameter
is not one of the valid values returned by
- :func:`~psij.JobExecutor.get_executor_names`, `ValueError` is raised.
+ :func:`~psij.JobExecutor.get_executor_names`, ``ValueError`` is raised.
:param version_constraint: A version constraint for the executor in the form
'(' [, 0.0.2, != 0.0.4)".
- :param url: An optional URL to pass to the `JobExecutor` instance.
+ :param url: An optional URL to pass to the ``JobExecutor`` instance.
:param config: An optional configuration to pass to the instance.
:return: A JobExecutor.
"""
@@ -247,7 +247,7 @@ def get_instance(name: str, version_constraint: Optional[str] = None, url: Optio
@staticmethod
def register_executor(desc: Descriptor, root: str) -> None:
"""
- Registers a `JobExecutor` class through a :class:`~psij.descriptor.Descriptor`.
+ Registers a ``JobExecutor`` class through a :class:`~psij.descriptor.Descriptor`.
The class can then be later instantiated using :func:`~psij.JobExecutor.get_instance`.
@@ -280,11 +280,12 @@ def get_executor_names() -> Set[str]:
Returns a set of registered executor names.
Names returned by this method can be passed to :func:`~psij.JobExecutor.get_instance` as
- the `name` parameter.
+ the ``name`` parameter.
Returns
-------
- A set of executor names corresponding to the known executors.
+ :
+ A set of executor names corresponding to the known executors.
"""
return set(JobExecutor._executors.keys())
diff --git a/src/psij/job_executor_config.py b/src/psij/job_executor_config.py
index 588f54837..6d9c3361f 100644
--- a/src/psij/job_executor_config.py
+++ b/src/psij/job_executor_config.py
@@ -5,11 +5,19 @@
class JobExecutorConfig(object):
"""An abstract configuration class for :class:`~psij.JobExecutor` instances."""
- #: A default `JobExecutorConfig` used when none is specified.
DEFAULT: 'JobExecutorConfig' = None # type: ignore
+ """A default ``JobExecutorConfig`` used when none is specified.
+
+ :meta hide-value:
+ """
- #: The default work directory when a work directory is not explicitly specified.
DEFAULT_WORK_DIRECTORY = Path.home() / '.psij' / 'work'
+ """The default work directory when a work directory is not explicitly specified.
+
+ Defaults to ``~/.psij/work``.
+
+ :meta hide-value:
+ """
def __init__(self, launcher_log_file: Optional[Path] = None,
work_directory: Optional[Path] = None) -> None:
@@ -53,12 +61,12 @@ def launcher_log_file(self, value: Optional[Union[str, Path]]) -> None:
@property
def work_directory(self) -> Path:
"""
- Configure the execor's work directory.
+ Configure the executor's work directory.
Parameters
----------
work_directory
- A directory where submit scripts and auxiliary job files will be generated. In a,
+ A directory where submit scripts and auxiliary job files will be generated. In a
cluster this directory needs to point to a directory on a shared filesystem. This is so
that the exit code file, likely written on a service node, can be accessed by PSI/J,
likely running on a head node.
diff --git a/src/psij/job_launcher.py b/src/psij/job_launcher.py
index 1e7aae3b6..42b6bd718 100644
--- a/src/psij/job_launcher.py
+++ b/src/psij/job_launcher.py
@@ -89,6 +89,7 @@ def get_launcher_names() -> Set[str]:
Returns
-------
- A set of launcher names corresponding to the known executors.
+ :
+ A set of launcher names corresponding to the known executors.
"""
return set(Launcher._launchers.keys())
diff --git a/src/psij/job_spec.py b/src/psij/job_spec.py
index f544458cc..690444815 100644
--- a/src/psij/job_spec.py
+++ b/src/psij/job_spec.py
@@ -74,16 +74,16 @@ def __init__(self, executable: Optional[str] = None, arguments: Optional[List[st
cleanup_flags: StageOutFlags = StageOutFlags.ALWAYS):
"""
:param executable: An executable, such as "/bin/date".
- :param arguments: The argument list to be passed to the executable. Unlike with execve(),
- the first element of the list will correspond to `argv[1]` when accessed by the invoked
- executable.
+ :param arguments: The argument list to be passed to the executable. Unlike with
+ ``execve()``, the first element of the list will correspond to ``argv[1]`` when accessed
+ by the invoked executable.
:param directory: The directory, on the compute side, in which the executable is to be run
:param name: A name for the job. The name plays no functional role except that
:class:`~psij.JobExecutor` implementations may attempt to use the name to label the
job as presented by the underlying implementation.
- :param inherit_environment: If this flag is set to `False`, the job starts with an empty
+ :param inherit_environment: If this flag is set to ``False``, the job starts with an empty
environment. The only environment variables that will be accessible to the job are the
- ones specified by this property. If this flag is set to `True`, which is the default,
+ ones specified by this property. If this flag is set to ``True``, which is the default,
the job will also have access to variables inherited from the environment in which the
job is run.
:param environment: A mapping of environment variable names to their respective values.
@@ -108,10 +108,10 @@ def __init__(self, executable: Optional[str] = None, arguments: Optional[List[st
:param stage_in: Specifies a set of files to be staged in before the job is launched.
:param stage_out: Specifies a set of files to be staged out after the job terminates.
:param cleanup: Specifies a set of files to remove after the stage out process.
- :param cleanup_flags: Specifies the conditions under which the files in `cleanup` should
+ :param cleanup_flags: Specifies the conditions under which the files in ``cleanup`` should
be removed, such as when the job completes successfully. The flag
- `StageOutFlags.IF_PRESENT` is ignored and no error condition is triggered if a file
- specified by the `cleanup` argument is not present.
+ ``StageOutFlags.IF_PRESENT`` is ignored and no error condition is triggered if a file
+ specified by the ``cleanup`` argument is not present.
All constructor parameters are accessible as properties.
@@ -119,7 +119,7 @@ def __init__(self, executable: Optional[str] = None, arguments: Optional[List[st
.. note::
A note about paths.
- It is strongly recommended that paths to `std*_path`, `directory`, etc. be specified
+ It is strongly recommended that paths to ``std*_path``, ``directory``, etc. be specified
as absolute. While paths can be relative, and there are cases when it is desirable to
specify them as relative, it is important to understand what the implications are.
@@ -129,11 +129,11 @@ def __init__(self, executable: Optional[str] = None, arguments: Optional[List[st
or may not point to the same file in both the location where the job is running and the
location where the job is launched from.
- For example, if launching jobs from a login node of a cluster, the path `/tmp/foo.txt`
+ For example, if launching jobs from a login node of a cluster, the path ``/tmp/foo.txt``
will likely refer to locally mounted drives on both the login node and the compute
node(s) where the job is running. However, since they are local mounts, the file
- `/tmp/foo.txt` written by a job running on the compute node will not be visible by
- opening `/tmp/foo.txt` on the login node. If an output file written on a compute node
+ ``/tmp/foo.txt`` written by a job running on the compute node will not be visible by
+ opening ``/tmp/foo.txt`` on the login node. If an output file written on a compute node
needs to be accessed on a login node, that file should be placed on a shared filesystem.
However, even by doing so, there is no guarantee that the shared filesystem is mounted
under the same mount point on both login and compute nodes. While this is an unlikely
@@ -143,15 +143,15 @@ def __init__(self, executable: Optional[str] = None, arguments: Optional[List[st
as seen from the submission side (i.e., login node), the job working directory may be
different from the working directory of the application that is launching the job. For
example, an application that uses PSI/J to launch jobs on a cluster may be invoked from
- (and have its working directory set to) `/home/foo`, where `/home` is a mount point for
- a shared filesystem accessible by compute nodes. The launched job may specify
- `stdout_path=Path('bar.txt')`, which would resolve to `/home/foo/bar.txt`. However, the
- job may start in `/tmp` on the compute node, and its standard output will be redirected
- to `/tmp/bar.txt`.
+ (and have its working directory set to) ``/home/foo``, where ``/home`` is a mount point
+ for a shared filesystem accessible by compute nodes. The launched job may specify
+ ``stdout_path=Path('bar.txt')``, which would resolve to ``/home/foo/bar.txt``. However,
+ the job may start in ``/tmp`` on the compute node, and its standard output will be
+ redirected to ``/tmp/bar.txt``.
Relative paths are useful when there is a need to refer to the job directory that the
scheduler chooses for the job, which is not generally known until the job is started by
- the scheduler. In such a case, one must leave the `spec.directory` attribute empty and
+ the scheduler. In such a case, one must leave the ``spec.directory`` attribute empty and
refer to files inside the job directory using relative paths.
"""
self._name = name
diff --git a/src/psij/job_state.py b/src/psij/job_state.py
index 0904e900a..b437c1289 100644
--- a/src/psij/job_state.py
+++ b/src/psij/job_state.py
@@ -8,7 +8,8 @@ class JobState(bytes, Enum):
"""
An enumeration holding the possible job states.
- The possible states are: `NEW`, `QUEUED`, `ACTIVE`, `COMPLETED`, `FAILED`, and `CANCELED`.
+ The possible states are: ``NEW``, ``QUEUED``, ``ACTIVE``, ``COMPLETED``, ``FAILED``, and
+ ``CANCELED``.
"""
def __new__(cls, index: int, order: int, name: str, final: bool) -> 'JobState': # noqa: D102
@@ -55,7 +56,7 @@ def __init__(self, *args: object) -> None: # noqa: D107
COMPLETED = (6, 6, 'COMPLETED', True)
"""
This state represents a job that has completed *successfully* (i.e., with a zero exit code).
- In other words, a job with the executable set to `/bin/false` cannot enter this state.
+ In other words, a job with the executable set to ``/bin/false`` cannot enter this state.
"""
FAILED = (7, 6, 'FAILED', True)
"""
@@ -71,11 +72,11 @@ def is_greater_than(self, other: 'JobState') -> Optional[bool]:
Not all states are comparable. State transitions cannot violate this ordering.
- :param other: the other `JobState` to compare to
- :return: if this state is comparable with `other`, this method returns `True` or
- `False` depending on the relative order between this state and `other`. That is,
- `True` is returned if and only if this state can come after `other`. If this state
- is not comparable with `other`, this method returns `None`.
+ :param other: the other ``JobState`` to compare to
+ :return: if this state is comparable with ``other``, this method returns ``True`` or
+ ``False`` depending on the relative order between this state and ``other``. That is,
+ ``True`` is returned if and only if this state can come after ``other``. If this state
+ is not comparable with ``other``, this method returns ``None``.
"""
if self._order == other._order:
if self._value_ == other._value_:
@@ -90,11 +91,11 @@ def is_greater_than(self, other: 'JobState') -> Optional[bool]:
@property
def final(self) -> bool:
"""
- Returns `True` if this state final.
+ Returns ``True`` if this state final.
A state is final when no other state transition can occur after that state has been reached.
- :return: `True` if this is a final state and `False` otherwise
+ :return: ``True`` if this is a final state and ``False`` otherwise
"""
return self._final
@@ -107,14 +108,14 @@ def __repr__(self) -> str:
return self._name
def __eq__(self, other: object) -> bool:
- """Returns true if `other` represents the same state as this state."""
+ """Returns true if ``other`` represents the same state as this state."""
if isinstance(other, JobState):
return bool(self._value_ == other._value_)
else:
return False
def __ne__(self, other: object) -> bool:
- """Returns false only if `other` represents the same state as this state."""
+ """Returns false only if ``other`` represents the same state as this state."""
if isinstance(other, JobState):
return bool(self._value_ != other._value_)
else:
@@ -131,9 +132,9 @@ def __hash__(self) -> int:
@staticmethod
def from_name(name: str) -> 'JobState':
"""
- Returns a `JobState` object corresponding to its string representation.
+ Returns a ``JobState`` object corresponding to its string representation.
- This method is such that `state == JobState.from_name(str(state))`.
+ This method is such that ``state == JobState.from_name(str(state))``.
"""
return _NAME_MAP[name]
diff --git a/src/psij/job_status.py b/src/psij/job_status.py
index 42576194a..d6e1a3ffc 100644
--- a/src/psij/job_status.py
+++ b/src/psij/job_status.py
@@ -13,7 +13,7 @@ def __init__(self, state: JobState, time: Optional[float] = None,
"""
:param state: The :class:`~psij.JobState` of this status.
:param time: The time, as would be returned by :func:`time.time()`, at which the
- transition to the new state occurred. If not specified, the time when this `JobStatus`
+ transition to the new state occurred. If not specified, the time when this ``JobStatus``
was instantiated will be used.
:param message: An optional message associated with the transition.
:param exit_code: An optional exit code for the job, if the job has completed.
@@ -33,14 +33,14 @@ def __init__(self, state: JobState, time: Optional[float] = None,
@property
def final(self) -> bool:
"""
- Returns the `final` property of the underlying state.
+ Returns the ``final`` property of the underlying state.
- :return: `True` if the state is final and `False` otherwise.
+ :return: ``True`` if the state is final and ``False`` otherwise.
"""
return self.state.final
def __str__(self) -> str:
- """Returns a string representation of this `JobStatus` instance."""
+ """Returns a string representation of this ``JobStatus`` instance."""
s = 'JobStatus[{!s}, time={}'.format(self.state, self.time)
if self.message is not None:
s = s + ', message={}'.format(self.message)
diff --git a/src/psij/launchers/script_based_launcher.py b/src/psij/launchers/script_based_launcher.py
index 45519ff7f..ef24cd424 100644
--- a/src/psij/launchers/script_based_launcher.py
+++ b/src/psij/launchers/script_based_launcher.py
@@ -48,7 +48,7 @@ class ScriptBasedLauncher(Launcher):
* the job ID
* a launcher log file, which is taken from the launcher_log_file configuration setting and
- defaults to `/dev/null`
+ defaults to ``/dev/null``
* the pre- and post- launcher scripts, or empty strings if they are not specified
Additional positional arguments to the script can be specified by subclasses by overriding
@@ -58,7 +58,7 @@ class ScriptBasedLauncher(Launcher):
A simple script library is provided in scripts/launcher_lib.sh. Its use is optional and it is
intended to be included at the beginning of a main launcher script using
- `source $(dirname "$0")/launcher_lib.sh`. It does the following:
+ ``source $(dirname "$0")/launcher_lib.sh``. It does the following:
* sets '-e' mode (exit on error)
* sets the variables _PSI_J_JOB_ID, _PSI_J_LOG_FILE, _PSI_J_PRE_LAUNCH, and
@@ -118,12 +118,12 @@ def _files_to_deploy(self) -> List[Path]:
def _deploy_files(self, paths: List[Path]) -> Path:
"""
- Deploys all files in a list to the same subdirectory of `config.work_directory`.
+ Deploys all files in a list to the same subdirectory of ``config.work_directory``.
The directory is guaranteed to be unique for each distinct list of files. That is,
- two invocations of this method with byte-by-byte identical files pointed to by `paths`
+ two invocations of this method with byte-by-byte identical files pointed to by ``paths``
and in the same order, will lead to the same subdirectory; changing the order of files
- in `paths` or changing the contents of one or more files in the list will lead to
+ in ``paths`` or changing the contents of one or more files in the list will lead to
a different subdirectory.
This allows files deployed together through this method to maintain relative references
to each other while ensuring that different processes using different files do not interfere
diff --git a/src/psij/resource_spec.py b/src/psij/resource_spec.py
index 753228c70..ccea6f292 100644
--- a/src/psij/resource_spec.py
+++ b/src/psij/resource_spec.py
@@ -18,7 +18,7 @@ class ResourceSpec(ABC):
"""
A base class for resource specifications.
- The `ResourceSpec` class is an abstract base class for all possible resource specification
+ The ``ResourceSpec`` class is an abstract base class for all possible resource specification
classes in PSI/J.
"""
@@ -31,13 +31,13 @@ def version(self) -> int:
@staticmethod
def get_instance(version: int) -> 'ResourceSpec':
"""
- Creates an instance of a `ResourceSpec` of the specified version.
+ Creates an instance of a ``ResourceSpec`` of the specified version.
Parameters
----------
version
- The version of `ResourceSpec` to instantiate. For example, if `version == 1`, this
- method will return a new instance of `ResourceSpecV1`.
+ The version of ``ResourceSpec`` to instantiate. For example, if ``version == 1``, this
+ method will return a new instance of ``ResourceSpecV1``.
"""
if version == 1:
return ResourceSpecV1()
@@ -58,26 +58,27 @@ def __init__(self, node_count: Optional[int] = None,
memory: Optional[int] = None) -> None:
"""
Some of the properties of this class are constrained. Specifically,
- `process_count = node_count * processes_per_node`. Specifying all constrained properties
+ ``process_count = node_count * processes_per_node``. Specifying all constrained properties
in a way that does not satisfy the constraint will result in an error. Specifying some
of the constrained properties will result in the remaining one being inferred based on
the constraint. This inference is done by this class. However, executor implementations
- may chose to delegate this inference to an underlying implementation and ignore the
+ may chpose to delegate this inference to an underlying implementation and ignore the
values inferred by this class.
:param node_count: If specified, request that the backend allocate this many compute nodes
for the job.
:param process_count: If specified, instruct the backend to start this many process
- instances. This defaults to `1`.
+ instances. This defaults to ``1``.
:param processes_per_node: Instruct the backend to run this many process instances on each
node.
:param cpu_cores_per_process: Request this many CPU cores for each process instance. This
- property is used by a backend to calculate the number of nodes from the `process_count`
+ property is used by a backend to calculate the number of nodes from the
+ ``process_count``
:param gpu_cores_per_process: Request this many GPU cores for each process instance.
- :param exclusive_node_use: If this parameter is set to `True`, the LRM is instructed to
+ :param exclusive_node_use: If this parameter is set to ``True``, the LRM is instructed to
allocate to this job only nodes that are not running any other jobs, even if this job
is requesting fewer cores than the total number of cores on a node. With this parameter
- set to `False`, which is the default, the LRM is free to co-schedule multiple jobs
+ set to ``False``, which is the default, the LRM is free to co-schedule multiple jobs
on a given node if the number of cores requested by those jobs total less than the
amount available on the node.
:param memory: The total amount, in bytes, of memory requested for the job.
@@ -151,8 +152,8 @@ def computed_node_count(self) -> int:
"""
Returns or calculates a node count.
- If the `node_count` property is specified, this method returns it. If not, a node
- count is calculated from `process_count` and `processes_per_node`.
+ If the ``node_count`` property is specified, this method returns it. If not, a node
+ count is calculated from ``process_count`` and ``processes_per_node``.
:return: An integer value with the specified or calculated node count.
"""
@@ -164,8 +165,8 @@ def computed_process_count(self) -> int:
"""
Returns or calculates a process count.
- If the `process_count` property is specified, this method returns it, otherwise it
- returns 1.
+ If the ``process_count`` property is specified, this method returns it, otherwise it
+ returns ``1``.
:return: An integer value with either the value of `process_count` or one if the
former is not specified.
@@ -178,10 +179,11 @@ def computed_processes_per_node(self) -> int:
"""
Returns or calculates the number of processes per node.
- If the `processes_per_node` property is specified, this method returns it, otherwise
- calculates it based on `process_count` and `node_count` if possible, or defaults to 1.
+ If the ``processes_per_node`` property is specified, this method returns it, otherwise
+ calculates it based on ``process_count`` and ``node_count`` if possible, or defaults to
+ ``1``.
- :return: An integer value with either the value of `processes_per_node` or one if the
+ :return: An integer value with either the value of ``processes_per_node`` or one if the
former cannot be determined.
"""
assert self._computed_ppn is not None
@@ -190,10 +192,10 @@ def computed_processes_per_node(self) -> int:
@property
def memory_kb(self) -> Optional[int]:
"""
- Returns the memory limit specified by the `memory` property, but in KB.
+ Returns the memory limit specified by the ``memory`` property, but in KB.
- :return: If the `memory` property is set on this object, returns `memory // 1024`. If the
- `memory` property is `None`, this method returns `None`.
+ :return: If the ``memory`` property is set on this object, returns ``memory // 1024``. If
+ the ``memory`` property is ``None``, this method returns ``None``.
"""
if self.memory:
return self.memory // 1024
@@ -202,7 +204,7 @@ def memory_kb(self) -> Optional[int]:
@property
def version(self) -> int:
- """Returns the version of this `ResourceSpec`, which is 1 for this class."""
+ """Returns the version of this ``ResourceSpec``, which is ``1`` for this class."""
return 1
def __eq__(self, o: object) -> bool:
diff --git a/src/psij/utils.py b/src/psij/utils.py
index 17ae2256a..f3fd258cf 100644
--- a/src/psij/utils.py
+++ b/src/psij/utils.py
@@ -32,7 +32,7 @@ class SingletonThread(threading.Thread):
safer for when users really really want to take the risk against all advice.
This class is meant as an abstract class and should be used by subclassing and implementing
- the `run` method.
+ the ``run`` method.
"""
_instances: Dict[int, Dict[type, 'SingletonThread']] = {}
@@ -41,7 +41,7 @@ class SingletonThread(threading.Thread):
def __init__(self, name: Optional[str] = None, daemon: bool = False) -> None:
"""
Instantiation of this class or one of its subclasses should be done through the
- :meth:`get_instance` method rather than directly.
+ :meth:``get_instance`` method rather than directly.
Parameters
----------
diff --git a/web/Gemfile b/web/Gemfile
index 80945e7c7..03a1bee11 100644
--- a/web/Gemfile
+++ b/web/Gemfile
@@ -34,3 +34,5 @@ gem "wdm", "~> 0.1.1", :platforms => [:mingw, :x64_mingw, :mswin]
# Lock `http_parser.rb` gem to `v0.6.x` on JRuby builds since newer versions of the gem
# do not have a Java counterpart.
gem "http_parser.rb", "~> 0.6.0", :platforms => [:jruby]
+
+gem "webrick", "~> 1.9"
diff --git a/web/_config.yml b/web/_config.yml
index 0a7384882..99438ed13 100644
--- a/web/_config.yml
+++ b/web/_config.yml
@@ -58,6 +58,8 @@ exclude:
- Gemfile.lock
- .gitignore
- README.md
+ - .bundle
+ - vendor
include:
- _static
- _images
diff --git a/web/build-versions b/web/build-versions
new file mode 100644
index 000000000..f268ebdd7
--- /dev/null
+++ b/web/build-versions
@@ -0,0 +1,105 @@
+#!/usr/bin/env python
+import os
+import re
+import shutil
+import subprocess
+import tarfile
+import tempfile
+from pathlib import Path
+from typing import Dict, List, Optional, Union
+
+from packaging.version import Version
+
+# The different versions used to be built with sphinx-multiversion. However,
+# that requires a single Sphinx toolchain version for all tags, which means
+# that we can never upgrade Sphinx. This script allows installing the respective
+# docs requirements for each version that is being built.
+
+VERSION_FILTER = r'^\d+\.\d+\.\d+(\..*)?$'
+
+
+def _run(argv: List[str], cwd: Optional[Union[str, Path]] = None,
+ env: Optional[Dict[str, str]] = None) -> str:
+ crt_env = os.environ.copy()
+ if env:
+ crt_env.update(env)
+ p = subprocess.run(argv, capture_output=True, text=True, cwd=cwd, env=crt_env)
+ if p.returncode != 0:
+ print(p.stdout)
+ print(p.stderr)
+ raise Exception(f'Command {" ".join(argv)} failed')
+ else:
+ return p.stdout
+
+
+def get_git_versions() -> Dict[str, str]:
+ versions = _run(['git', 'tag'])
+ v_arr = [Version(v) for v in versions.split() if re.match(VERSION_FILTER, v)]
+ v_arr.sort()
+ r = {}
+ for v in v_arr:
+ r[v.base_version] = str(v)
+ return r
+
+
+def get_tree(dst: Path, tag: str) -> None:
+ tar = f'{dst}.tar'
+ _run(['git', 'archive', '--format', 'tar', '--output', tar, tag])
+ with tarfile.TarFile(tar) as tf:
+ tf.extractall(dst)
+
+
+def check_deps(dst: Path) -> None:
+ # Manually check and adjust Sphinx dependencies
+ reqs_path = dst / 'requirements-docs.txt'
+ with open(reqs_path) as f:
+ reqs = f.read()
+
+ if 'Sphinx==4.5.0' in reqs and 'sphinxcontrib-applehelp' not in reqs:
+ with open(reqs_path, 'w') as f:
+ f.write(reqs)
+ f.write('''
+sphinxcontrib-applehelp==1.0.4
+sphinxcontrib-devhelp==1.0.2
+sphinxcontrib-htmlhelp==2.0.1
+sphinxcontrib-serializinghtml==1.1.5
+sphinxcontrib-qthelp==1.0.3
+ ''')
+
+
+def install_packages(dst: Path) -> None:
+ check_deps(dst.parent)
+ _run(['pip', 'install', '-r', 'requirements-docs.txt', '-t', str(dst)], cwd=dst.parent)
+ shutil.rmtree(dst / 'psij')
+ shutil.rmtree(dst / 'psij-descriptors')
+ shutil.rmtree(next(dst.glob('psij_python-*.dist-info')))
+
+
+def build(dst: Path, pd: Path, out: Path) -> None:
+ _run(['python', '-m', 'sphinx', '--keep-going', '-b', 'html', 'docs', str(out)],
+ cwd=dst, env={'PYTHONPATH': f'{pd}:{dst}/src', 'TYPEGUARD_DISABLE': '1'})
+
+
+def run() -> None:
+ v_dict = get_git_versions()
+
+ with tempfile.TemporaryDirectory() as wd:
+ wdp = Path(wd)
+ for label, tag in v_dict.items():
+ print(f'Building docs for {label}.', end='')
+ dst = wdp / label
+ get_tree(dst, tag)
+ print('.', end='')
+ pd = dst / '.packages'
+ pd.mkdir(parents=True, exist_ok=True)
+ install_packages(pd)
+ print('.', end='')
+ out = Path('docs').absolute() / '.web-build' / 'v' / label
+ out.mkdir(parents=True, exist_ok=True)
+ build(dst, pd, out)
+ print()
+
+
+if __name__ == '__main__':
+ run()
+
diff --git a/web/docs/_static/cloud.base.js b/web/docs/_static/cloud.base.js
new file mode 100644
index 000000000..8b5a03dc0
--- /dev/null
+++ b/web/docs/_static/cloud.base.js
@@ -0,0 +1,154 @@
+/* ~~~~~~~~~~~~~~
+ * cloud.base.js
+ *~~~~~~~~~~~~~~
+ *
+ * Base JS utils needed by cloud js instrumentation.
+ * Split out so they can be used by theme-independant extensions (e.g. auto_redirect)
+ *
+ * This initializes a "window.CSP.utils" object
+ *
+ * :copyright: Copyright 2017 by Assurance Technologies
+ * :license: BSD
+ */
+
+// begin encapsulation
+(function (window, $) {
+
+ /*==========================================================================
+ * internal helpers
+ *==========================================================================*/
+ var location = document.location,
+ // hosturl is url to root of host, without trailing '/'
+ // NOTE: regex allows netloc segment to be empty, to support 'file:///' urls
+ hosturl = location.href.match(/^[a-z0-9]+:(?:\/\/)?(?:[^@/]*@)?[^/]*/)[0],
+ docpath = location.pathname,
+ sphinx = window.DOCUMENTATION_OPTIONS;
+
+ /*==========================================================================
+ * utils
+ *==========================================================================*/
+ var utils = {
+
+ /*==========================================================================
+ * url helpers
+ *==========================================================================*/
+
+ // helper to generate an absolute url path from a relative one.
+ // absolute paths passed through unchanged.
+ // paths treated as relative to ,
+ // if base is omitted, uses directory of current document.
+ abspath: function (path, base) {
+ var parts = path.split("/"),
+ stack = [];
+ if (parts[0]) {
+ // if path is relative, put base on stack
+ stack = (base || location.pathname).split("/");
+ // remove blank from leading '/'
+ if (!stack[0]) {
+ stack.shift();
+ }
+ // discard filename & blank from trailing '/'
+ if (stack.length && !(base && stack[stack.length - 1])) {
+ stack.pop();
+ }
+ }
+ for (var i = 0; i < parts.length; ++i) {
+ if (parts[i] && parts[i] != '.') {
+ if (parts[i] == '..') {
+ stack.pop();
+ } else {
+ stack.push(parts[i]);
+ }
+ }
+ }
+ return "/" + stack.join("/");
+ },
+
+ // return subpath of url, if it starts with base ("" or non-empty string)
+ // returns undefined if url doesn't start with base.
+ // base url search params & fragments are ignored.
+ getSubUrl: function(url, base){
+ base = base.replace(/(?:\/|[#?].*)$/, '');
+ if(url.startsWith(base)) {
+ var suffix = url.slice(base.length);
+ if(suffix == '' || suffix.match(/^[/#?]/)){ return suffix; }
+ }
+ return;
+ },
+
+ // helper to normalize urls for comparison
+ // * strips current document's scheme, host, & path from local document links (just fragment will be left)
+ // * strips current document's scheme & host from internal urls (just path + fragment will be left)
+ // * makes all internal url paths absolute
+ // * external urls returned unchanged.
+ shortenUrl: function(url) {
+ if (!url){
+ return "";
+ } else if (url.indexOf(hosturl) == 0) {
+ // absolute path to same host
+ url = url.substr(hosturl.length) || '/';
+ } else if (url[0] == '.') {
+ // relative path
+ url = utils.abspath(url);
+ } else if (!url.match(/^[/#?]|[a-z0-9]+:/)) {
+ // not abs path, or fragment, or query, or uri:// --
+ // another page in current dir
+ url = utils.abspath('./' + url);
+ }
+
+ if (url.indexOf(docpath) == 0) {
+ // strip current doc's url; only thing left will be e.g. #anchor
+ url = url.substr(docpath.length);
+ }
+ if (url == "#" || url == "#top") {
+ // normalize to empty string
+ url = "";
+ }
+ return url;
+ },
+
+ // url w/ query params & hash stripped
+ baseUrl: function(url){
+ return utils.shortenUrl(url).replace(/[#?].*$/, '');
+ }
+ };
+
+ /*==========================================================================
+ * misc es5 polyfills
+ *==========================================================================*/
+ var StrProto = String.prototype;
+ if (!StrProto.startsWith) {
+ StrProto.startsWith = function(search, pos){
+ return this.substr(pos || 0, search.length) === search;
+ };
+ }
+
+ /*==========================================================================
+ * jquery patches
+ *==========================================================================*/
+
+ // custom helper to toggle visibility
+ $.fn.toggleVis = function (state){
+ if(state) { this.show(); } else { this.hide(); }
+ return this;
+ };
+
+ /*==========================================================================
+ * initialize namespace
+ *==========================================================================*/
+
+ window.CST = window.CloudSphinxTheme = {
+ // url to root of host, without trailing "/"
+ hosturl: hosturl,
+ // path to root of document dir, without trailing "/" or index.html
+ rootpath: sphinx && utils.abspath(sphinx.URL_ROOT || ""),
+ utils: utils
+ };
+
+ /*==========================================================================
+ * eof
+ *==========================================================================*/
+
+// end encapsulation
+// NOTE: sphinx provides underscore.js as $u
+}(window, jQuery));
diff --git a/web/docs/_static/cloud.css b/web/docs/_static/cloud.css
index 4dfd140bb..3ecd5708e 100644
--- a/web/docs/_static/cloud.css
+++ b/web/docs/_static/cloud.css
@@ -106,14 +106,15 @@ div.body {
min-height: 6in;
line-height: 1.5em;
padding: 30px 20px;
+ padding-top: 4pt;
min-width: 0;
- max-width: calc(8in + max((100% - 14in) / 2, 8pt));
+ max-width: calc(8in + max((100% - 10in) / 2, 12pt));
border-left: 1px solid var(--color-fg-lines);
- padding-left: calc(max((100% - 14in) / 2, 8pt));
+ padding-left: calc(max((100% - 13in) / 2, 12pt));
}
div.sphinxsidebar {
- margin-top: 4pt;
+ margin-top: 16pt;
width: 3in;
font-size: 90%;
line-height: 1.25em;
@@ -260,7 +261,8 @@ div.sphinxglobaltoc ul a[href="#"] {
div.sphinxglobaltoc ul a:not([href*="#"]) {
font-size: 0.95em;
- font-style: italic;
+ font-style: normal;
+ font-weight: 600 !important;
}
div.sphinx-toc li {
@@ -281,7 +283,8 @@ div.sphinx-toc li.current.active:not(.focus):before {
div.sphinx-toc li.focus.local {
border-left: 4pt solid;
- border-left-color: var(--color-bg-inv-2)
+ margin-left: 5pt;
+ border-left-color: #00000020;
}
@@ -485,7 +488,7 @@ div.body h1 {
div.body > section > h1 {
- margin: 48pt 0 8pt 0;
+ margin: 8pt 0 8pt 0;
}
@@ -529,6 +532,10 @@ h1#search-documentation {
margin: 1.2em 1px 0.2em 1px;
}
+div.body h2:has(+dl.class), div.body h3:has(+dl.class) {
+ display: none;
+}
+
.section.emphasize-children > .section > h3 {
margin: 0.923em 1px 0.923em 1px;
@@ -695,7 +702,7 @@ div.body .clear-none > h3 { clear: none; }
div.body p {
text-align: justify;
- margin: 1.5em 0 1.5em 0;
+ margin: 0.1em 0 0.3em 0;
}
div.body li, div.body dd {
@@ -881,6 +888,11 @@ div.warning {
background-color: #ffe4e4; background-image: url("icon-warning.png");
}
+div.admonition.warning {
+ background-color: #fb8c0040 !important;
+ border: thin solid;
+}
+
div.danger, div.admonition.error {
background-color: #ffe4e4; background-image: url("icon-danger.png");
}
@@ -1183,6 +1195,17 @@ dl.staticmethod > dt {
border-radius: 3px;
}
+dl.class > dt {
+ padding: 0.7em 1em 0.7em 0.6em;
+ margin-top: 8pt;
+}
+
+
+dl.class > dt.sig {
+ position: sticky;
+ top: 48px;
+}
+
em.property:first-child > span.w,
em.attribute:first-child > span.w {
display: inline-block;
@@ -1195,14 +1218,14 @@ code.xref.py-meth > .pre,
code.xref.py-mod > .pre,
code.xref.py-attr > .pre {
font-family: var(--code-font), sans-serif;
- font-size: 12pt;
+ font-size: 14pt;
color: #6060ff;
}
code.sig-name > .pre,
dl.method > dt > code {
font-family: var(--code-font), sans-serif;
- font-size: 12pt;
+ font-size: 14pt;
}
dl.has-headerlink > dt,
@@ -1220,12 +1243,73 @@ dl.function > dt,
dl.method > dt,
dl.classmethod > dt,
dl.staticmethod > dt {
- background-color: #ffb88c;
+ border: none;
+}
+
+dl.method > dt::before {
+ display: inline-block;
+ content: "method ";
+ border: none;
+ padding: 0pt 3pt 0pt 3pt;
+ margin-right: 2pt;
+ font-family: var(--code-font), sans-serif;
+ font-weight: normal !important;
+ font-size: 13pt !important;
+}
+
+dl.method > dt.sig {
+ background-color: #ffb88c30;
+ border-radius: 4pt;
+ border: none;
+ border-left: 5pt solid #ffb88c;
}
+dl.method > dt.sig > .property > .k > .pre {
+ font-size: 13pt !important;
+}
+
+dl.property > dt.sig, dl.attribute > dt.sig {
+ background-color: #fae19930;
+ border-radius: 4pt;
+ border: none;
+ border-left: 5pt solid #fae199;
+}
+
+dl.property > dt.sig > .property > .p:first-child > .pre::after {
+ content: " ";
+}
+
+dl.property > dt.sig > .property > .w {
+ margin: 0 1.5pt 0 1.5pt;
+}
+
+dl.attribute > dt.sig > .property > .w {
+ margin: 0 1.5pt 0 1.5pt;
+}
+
+dl.property > dt.sig > .property > .k > .pre,
+dl.attribute > dt.sig > .attribute > .pre {
+ font-family: var(--code-font), sans-serif;
+ font-weight: normal !important;
+ font-size: 13pt !important;
+ color: rgba(0, 0, 0, 0.6);
+ font-style: italic;
+}
+
+
dl.class > dt {
- background-color: #f5a080;
+ background-color: #fdede7;
border-width: 0 0 0 6px;
+ border-left: 6px solid #f5a080;
+ width: 100%;
+ padding-right: 4pt;
+ text-indent: -12pt;
+ margin-left: 2pt;
+ padding-left: 18pt;
+}
+
+dl.class > dt * {
+ font-size: 14pt;
}
dl.exception > dt {
@@ -1247,11 +1331,36 @@ dl.field-list ul li {
dl.field-list ul li strong,
dl.field-list dd strong {
- background-color: #f0f0f0;
+ color: #600000;
padding-left: 2pt;
padding-right: 2pt;
}
+dl.class > dd > dl.field-list > dd > ul > li > p:not(:first-child) {
+ margin-left: 16pt;
+}
+
+dl.class dl.field-list > dd {
+ margin-left: 2pt;
+ padding-left: 2pt;
+}
+
+dl.class dl.field-list > dt {
+ font-weight: bold !important;
+ color: #606060;
+ padding-left: 0;
+}
+
+dl.class dl.field-list {
+ margin-bottom: 4pt;
+}
+
+dl.class > dd > dl.method {
+ margin-top: 8pt;
+ margin-bottom: 8pt;
+}
+
+
em.sig-param,
dl.field-list em {
font-style: normal;
@@ -1259,13 +1368,23 @@ dl.field-list em {
color: #401000;
}
+em.sig-param > .n > .pre {
+ color: #600000;
+ padding-left: 2px;
+ padding-right: 2px;
+}
+
+em.sig-param > .o > .pre, em.sig-param > .default_value > .pre {
+ color: #606060;
+}
+
em.property, em.attribute {
font-style: normal;
font-weight: 400;
}
dl.property > dt, dl.attribute > dt {
- background-color: #fae199;
+ /*background-color: #fae199;*/
display: inline-block;
}
@@ -1292,7 +1411,7 @@ dl.staticmethod > dt > .property:first-child {
dt.sig, .sig-name {
font-family: var(--code-font), sans-serif;
- font-size: 12pt;
+ font-size: 14pt;
}
.desc-section dl.attribute > dt:before {
@@ -1308,6 +1427,7 @@ dt.sig, .sig-name {
.desc-section dl.method:not([subtype]) > dt:before {
content: "method";
padding-right: 0.6em;
+ font-weight: normal;
}
dl > dt.highlighted {
diff --git a/web/docs/_static/cloud.js b/web/docs/_static/cloud.js
new file mode 100644
index 000000000..1173e521a
--- /dev/null
+++ b/web/docs/_static/cloud.js
@@ -0,0 +1,982 @@
+/* ~~~~~~~~~~~~~~
+ * cloud.js_t
+ *~~~~~~~~~~~~~~
+ *
+ * Various bits of javascript driving the moving parts behind various
+ * parts of the cloud theme. Handles things such as toggleable sections,
+ * collapsing the sidebar, etc.
+ *
+ * :copyright: Copyright 2011-2012 by Assurance Technologies
+ * :license: BSD
+ */
+
+
+
+
+
+// begin encapsulation
+(function (window, $, CST) {
+
+ const isUndefined = function(x) {
+ return typeof x === "undefined";
+ }
+
+ /*==========================================================================
+ * common helpers
+ *==========================================================================*/
+ var isUndef = isUndefined,
+ TEXT_NODE = 3, // could use Node.TEXT_NODE, but IE doesn't define it :(
+ $window = $(window),
+ utils = CST.utils,
+ shorten_url = utils.shortenUrl,
+ baseUrl = utils.baseUrl;
+
+ // helper that retrieves css property in pixels
+ function csspx(elem, prop) {
+ return parseInt($(elem).css(prop).replace("px", ""), 10);
+ }
+
+ // NOTE: would use $().offset(), but it's document-relative,
+ // and we need viewport-relative... which means getBoundingClientRect().
+ // NOTE: 'window.frameElement' will only work we're embedded in an iframe on same domain.
+ var parentFrame = window.frameElement;
+ if (window.parent && window.parent !== window) {
+ $(window.parent).scroll(function () {
+ $window.scroll();
+ });
+ }
+
+ function leftFrameOffset() {
+ return parentFrame ? parentFrame.getBoundingClientRect().left : 0;
+ }
+
+ function topFrameOffset() {
+ return parentFrame ? parentFrame.getBoundingClientRect().top : 0;
+ }
+
+ function leftViewOffset($node) {
+ return ($node && $node.length > 0) ? $node[0].getBoundingClientRect().left + leftFrameOffset() : 0;
+ }
+
+ function topViewOffset($node) {
+ return ($node && $node.length > 0) ? $node[0].getBoundingClientRect().top + topFrameOffset() : 0;
+ }
+
+ function bottomViewOffset($node) {
+ return ($node && $node.length > 0) ? $node[0].getBoundingClientRect().bottom + topFrameOffset() : 0;
+ }
+
+
+ function topOffset($target, $parent) {
+ if (!($target && $target[0])) {
+ return 0;
+ }
+ var offset = $target[0].getBoundingClientRect().top;
+ if ($parent && $parent[0]) {
+ offset -= $parent[0].getBoundingClientRect().top;
+ }
+ else {
+ offset += topFrameOffset();
+ }
+ return offset;
+ }
+
+ // return normalized nodename, takes in node or jquery selector
+ // (can't trust nodeName, per http://ejohn.org/blog/nodename-case-sensitivity/)
+ function nodeName(elem) {
+ if (elem && elem.length) {
+ elem = elem[0];
+ }
+ return elem && elem.nodeName.toUpperCase();
+ }
+
+ /*==========================================================================
+ * Synthesize 'cloud-breakpoint' event
+ *==========================================================================
+ * Event emitted when crossing small <-> medium media breakpoint
+ *==========================================================================*/
+ var smallScreen;
+
+ $(function (){
+ var $smallDiv = $('').appendTo("body"),
+ $html = $("html");
+ function update(){
+ var test = $smallDiv.css("display") == "none";
+ if(test !== smallScreen){
+ smallScreen = test;
+ $html.toggleClass("small-screen", test)
+ .toggleClass("medium-up-screen", !test);
+ $window.trigger("cloud-breakpoint");
+ }
+ }
+ $window.on("DOMContentLoaded load resize", update);
+ update();
+ });
+
+ /*==========================================================================
+ * Highlighter Assist
+ *==========================================================================
+ * Sphinx's highlighter marks some objects when user follows link,
+ * but doesn't include section names, etc. This catches those.
+ *==========================================================================*/
+ $(function () {
+ // helper to locate highlight target based on #fragment
+ function locate_target() {
+ // find id referenced by #fragment
+ var hash = document.location.hash;
+ if (!hash) return null;
+ var section = document.getElementById(hash.substr(1));
+ if (!section) return null;
+
+ // could be div.section, or hidden span at top of div.section
+ var name = nodeName(section);
+ if (name != "DIV") {
+ if (name == "SPAN" && section.innerHTML == "" &&
+ nodeName(section.parentNode) == "DIV") {
+ section = section.parentNode;
+ }
+ else if (name == "DT" && section.children.length &&
+ $(section).children("tt.descname, code.descname").length > 0) {
+ // not a section, but an object definition, e.g. a class, func, or attr
+ return $(section);
+ }
+ }
+ // now at section div and either way we have to find title element - h2, h3, etc.
+ var header = $(section).children("h2, h3, h4, h5, h6").first();
+ return header.length ? header : null;
+ }
+
+ // init highlight
+ var target = locate_target();
+ if (target) target.addClass("highlighted");
+
+ // update highlight if hash changes
+ $window.on("hashchange", function () {
+ if (target) target.removeClass("highlighted");
+ target = locate_target();
+ if (target) target.addClass("highlighted");
+ });
+ });
+
+ /*==========================================================================
+ * Toggleable Sections
+ *==========================================================================
+ * Added expand/collapse button to any collapsible RST sections.
+ * Looks for sections with CSS class "html-toggle",
+ * along with the optional classes "expanded" or "collapsed".
+ * Button toggles "html-toggle.expanded/collapsed" classes,
+ * and relies on CSS to do the rest of the job displaying them as appropriate.
+ *==========================================================================*/
+
+ // given "#hash-name-with.periods", escape so it's usable as CSS selector
+ // (e.g. "#hash-name-with\\.periods")
+ // XXX: replace this with proper CSS.escape polyfill?
+ function escapeHash(hash) {
+ return hash.replace(/\./g, "\\.");
+ }
+
+ $(function () {
+ function init() {
+ // get header & section, and add static classes
+ var header = $(this);
+ var section = header.parent();
+ header.addClass("html-toggle-button");
+
+ // helper to test if url hash is within this section
+ function contains_hash() {
+ var hash = document.location.hash;
+ return hash && (section[0].id == hash.substr(1) ||
+ section.find(escapeHash(hash)).length > 0);
+ }
+
+ // helper to control toggle state
+ function set_state(expanded) {
+ expanded = !!expanded; // toggleClass et al need actual boolean
+ section.toggleClass("expanded", expanded);
+ section.toggleClass("collapsed", !expanded);
+ section.children().toggle(expanded);
+ if (!expanded) {
+ section.children("span:first-child:empty").show();
+ /* for :ref: span tag */
+ header.show();
+ }
+ }
+
+ // initialize state
+ set_state(section.hasClass("expanded") || contains_hash());
+
+ // bind toggle callback
+ header.click(function (evt) {
+ var state = section.hasClass("expanded")
+ if (state && $(evt.target).is(".headerlink")) {
+ return;
+ }
+ set_state(!state);
+ $window.trigger('cloud-section-toggled', section[0]);
+ });
+
+ // open section if user jumps to it from w/in page
+ $window.on("hashchange", function () {
+ if (contains_hash()) set_state(true);
+ });
+ }
+
+ $(".html-toggle.section > h2, .html-toggle.section > h3, .html-toggle.section > h4, .html-toggle.section > h5, .html-toggle.section > h6").each(init);
+ });
+
+ /*==========================================================================
+ * mobile menu / collapsible sidebar
+ *==========================================================================
+ * Instruments sidebar toggle buttons. Relies on applying classes
+ * to div.document in order to trigger css rules that show/hide sidebar.
+ * Persists sidebar state via session cookie.
+ * Sidebar state for small screens is tracked separately,
+ * and is NOT persisted.
+ *==========================================================================*/
+ $(function () {
+ // get nodes
+ if (!$(".sphinxsidebar").length) { return; }
+
+ var $doc = $('div.document'),
+ $hide = $('button#sidebar-hide'),
+ $show = $('button#sidebar-show'),
+ copts = {
+ // expires: 7,
+ path: utils.rootpath
+ };
+
+ // set sidebar state for current media size
+ var lastSmall = false,
+ smallState = false,
+ largeState = false;
+ function setState(visible){
+ $doc.toggleClass("sidebar-hidden", !smallScreen && !visible)
+ .toggleClass("document-hidden", smallScreen && visible);
+ $hide.toggleVis(visible);
+ $show.toggleVis(!visible);
+ lastSmall = smallScreen;
+ if(smallScreen) {
+ smallState = visible;
+ if(visible) { largeState = true; }
+ } else {
+ largeState = visible;
+ if(!visible) { smallState = false; }
+ $.cookie("sidebar", visible ? "expanded" : "collapsed", copts);
+ }
+ $window.trigger("cloud-sidebar-toggled", visible);
+ }
+
+ // change when buttons clicked
+ $show.click(function () { setState(true); });
+ $hide.click(function () { setState(false); });
+
+ // refresh sidebar state when crossing breakpoints
+ $window.on("cloud-breakpoint", function (){
+ setState(smallScreen ? smallState : largeState);
+ });
+
+ // load initial state
+ if(smallScreen){
+ setState(false);
+ } else {
+ var value = $.cookie("sidebar");
+
+ setState(value != "collapsed");
+ }
+
+ // make buttons visible now that they're instrumented
+ $(".sidebar-toggle-group").removeClass("no-js");
+ });
+ /*==========================================================================
+ * sticky sidebar
+ *==========================================================================
+ * Instrument sidebar so that it sticks in place as page is scrolled.
+ *==========================================================================*/
+
+ function resetStickyState($target){
+ $target.css({
+ position: "",
+ marginLeft: "",
+ top: "",
+ left: "",
+ bottom: ""
+ });
+ }
+
+ // helper to update 'sticky' state of target --
+ // tried to make this generic, but some bits are specific to sidebar
+ function setStickyState($target, top, start, end, $container){
+ if (top >= start) {
+ // top of sidebar is above stickyStart -- scroll with document
+ resetStickyState($target);
+ } else if (top > end) {
+ $target.css({
+ position: "fixed",
+ marginLeft: 0,
+ top: start - topFrameOffset(),
+ left: leftViewOffset($container),
+ bottom: ""
+ });
+ } else {
+ // bottom of sidebar is below stickyEnd -- scroll with document,
+ // but place at bottom of container
+ $target.css({
+ position: "absolute",
+ marginLeft: 0,
+ top: "",
+ left: 0,
+ bottom: 0
+ });
+ }
+ }
+
+ $(function () {
+ // initialize references to relevant elements,
+ // and internal state
+ var $bodywrapper = $(".bodywrapper"), // element that contains content
+ $bodytoc = $('.sphinxglobaltoc a[href="#"]').parent(), // element containing toc for page
+ $container = $('.document'), // element to stick within
+ $target = $('.sphinxsidebar'), // element to sticky
+ $toggle = $(".sidebar-toggle-group"), // extra element to sticky
+ targetMargin = 0, // $target top margin
+ windowHeight = 0, // cache of window height
+ disable = false, // whether sticky is disabled for given window size
+ start = 0, // start sticking when top of target goes above this point
+ lastTop = null, // tracks last offset for scroll+hover handling
+ containerOffset = 0, // top margin of target (included)
+ offset = 0, // offset within target
+ offsetMin = Math.max(0, start); // min offset
+
+ // func to update sidebar position based on scrollbar & container positions
+ function update_sticky(evt) {
+ if (disable) { return; }
+
+ // calc stats
+ // HACK: using $container for offset so we don't have to reset_sticky() for calc.
+ // then add cached container-relative offset to get topViewOffset($target).
+ var top = topViewOffset($container),
+ targetHeight = $target.outerHeight(true),
+ end = targetHeight - $container.height();
+
+ // adjust offset if users scrolls while hovering over sidebar
+ if (evt && evt.type == "scroll" && ($target.first().is(":hover") ||
+ // make sure local toc scrolls into view
+ // XXX: will this still work right if window height < bodytoc height?
+ ($bodytoc.length && bottomViewOffset($bodytoc) + 16 >= windowHeight))) {
+ offset -= top - lastTop;
+ }
+ lastTop = top;
+
+ // see note in top init (above), but doing this here
+ // so it doesn't affect offset adjustment
+ top += containerOffset;
+
+ // limit offset to container bounds
+ if (offset < offsetMin) {
+ offset = offsetMin;
+ } else {
+ var offsetMax = targetHeight - windowHeight - start;
+ offset = Math.max(offsetMin, Math.min(offset, -top, offsetMax));
+ }
+
+ // offset = 0;
+ // console.debug("sticky sidebar: top=%o offset=%o start=%o end=%o",
+ // top, offset, start, end);
+
+ // set sticky state
+ setStickyState($target, top, start - offset, end - offset, $container);
+
+ // set button sticky state -- has to stay at top of screen
+ setStickyState($toggle, top, start - Math.min(offset, targetMargin), -1e9, $container);
+ }
+
+ // func to update sidebar measurements, and then call update_sticky()
+ function update_measurements() {
+ // if body shorter than sidebar, setting sidebar to 'fixed' would cause doc
+ // to shrink below sidebar height, so have to disable sticky mode in this case.
+ resetStickyState($target);
+ resetStickyState($toggle);
+ disable = (smallScreen || $bodywrapper.height() < $target.height());
+ if (disable) {
+ return;
+ }
+
+ // calc stats
+ windowHeight = $window.height();
+ targetMargin = csspx($target, "margin-top");
+ if($target.css("display") == "none"){
+ // so toggle positioned correctly on collapsed sidebar
+ containerOffset = 0;
+ } else {
+ // NOTE: this includes margin-top since it's not removed by sticky code above
+ containerOffset = topOffset($target, $container) - targetMargin;
+ }
+
+ // update state
+ update_sticky();
+ }
+
+ // run function now, and every time window scrolls
+ // XXX: would it help to throttle/raf() scroll & resize calls?
+ $window.scroll(update_sticky)
+ .on("resize hashchange cloud-section-toggled cloud-sidebar-toggled", update_measurements);
+ update_measurements();
+
+ // hack to fix errant initial-layout issue
+ $window.on("load", update_sticky);
+ });
+
+
+ // flag set by smooth scroller to temporarily disable toc sliding.
+ var scrollingActive = false;
+ /*==========================================================================
+ * sidebar toc highlighter
+ *==========================================================================
+ * highlights toc entry for current section being viewed;
+ * as well as expands & collapses entries for sections that aren't onscreen.
+ *==========================================================================*/
+ $(function () {
+ // scan all links, gathering info about their relationships
+ var $sbody = $("div.body"),
+ localDB = [], // entries that are part of local page OR child page
+ toggleDB = []; // subset of localDB which has $ul defined
+
+ // scan all links w/o TOCs
+ $(".sphinxlocaltoc ul a, .sphinxglobaltoc ul a").each(function (idx, link) {
+ // grab basic info about link
+ var $link = $(link),
+ // NOTE: reading link.attr() so highlight parameter
+ // from current location isn't included...
+ href = shorten_url($link.attr("href")) || "#",
+ isLocal = (href[0] == "#"),
+ isTop = (href == "#"),
+ $li = $link.parent("li"),
+ parent = $li.parent("ul").prev("a").data("toc"),
+ $target;
+
+ // determine type of link & target element for visibility calc
+ if (isLocal) {
+ // css code relies on all local links starting with "#"
+ // so make sure links use right representation
+ $link.attr("href", href);
+
+ // needing for styling
+ $li.addClass("local");
+
+ // link points to section in current document.
+ // use that section as visibility target
+ if(isTop){
+ $target = $sbody;
+
+ // don't bother traversing to parent entry if outside page
+ parent = null;
+ } else {
+ $target = $(document.getElementById(href.slice(1)));
+
+ // XXX: what about rare border case where there's
+ // multiple toplevel entries? not sure *how* to handle that.
+ // (parent will be null in this case)
+ }
+
+ } else if (parent) {
+ // needing for styling
+ $li.addClass("child");
+
+ // parent (or some ancestor) is part of page,
+ // so this is link for child page.
+ // prefer to use actual link in document as visibility target
+ $target = parent.$target.find("a").filter(function () {
+ return shorten_url(this.href) == href;
+ });
+ if (!$target.length) {
+ // target link not actually visible in document
+ // XXX: what if target has multiple links, but to subfragments
+ // e.g. (passlib.hash manpage's link to passlib.hash.ldap_std)?
+ return;
+ }
+ if (($target.parent("li").attr("class") || '').search(/(^|\w)toctree-/) == 0) {
+ // it's part of embedded toc tree, use whole LI as target.
+ $target = $target.parent("li");
+ }
+ // XXX: what if target link is w/in subsection,
+ // even though it belongs at this level in TOC?
+ // *think* active_child code below will prevent spurious highlighting.
+ } else {
+ // this link isn't local, nor is any ancestor, so ignore this one.
+ return;
+ }
+
+ // add to update list
+ var entry = {
+ //
+ // static vars
+ //
+ $target: $target, // section/object controlling link's visibility
+ $li: $li, // list item we're instrumenting
+ parent: parent, // reference to parent entry
+ children: [], // list of child nodes
+ href: href, // normalized copy of li > a[href]
+ isLocal: isLocal, // whether href points to local page
+
+ // filled by $ul pass, below
+ $ul: null, // list of child items if we're doing collapse checking, else null
+ openSize: 0, // avg # of child items expecting to be visible at a time.
+
+ //
+ // state vars modified by updateTOC()
+ //
+ rect: null, // cache of client bounding rect
+ visible: false, // whether target is onscreen
+ active: false, // whether this entry (or child) is marked active
+ justOpened: false // whether toc-toggle was opened during this updateTOC() pass
+ };
+ localDB.push(entry);
+ if(parent) { parent.children.push(entry); }
+ $link.data("toc", entry); // used to get parent entry (above), and for debugging
+ });
+
+ // if no local links found, don't bother w/ update hook
+ //console.debug("localDB: %o", localDB);
+ if (!localDB.length) return;
+
+ // figure out which nodes should be collapsible.
+ // go in reverse order, so we have count available for parent elements.
+ // fills in $ul & viewCount in entries
+ for(var i=localDB.length - 1; i>=0; --i){
+ // don't fill in $ul for toplevel, or ones w/ no entries.
+ var entry = localDB[i],
+ $ul = entry.$li.children("ul");
+ if(!i || !$ul.length){ continue; }
+
+ // calculate how many children will be visible at a time
+ // when $ul is open. this is # of children, plus number
+ // of descendants always visible in non-collapsing children,
+ // plus the largest visibility count of all collapsing children.
+ var weight = entry.children.length,
+ dynamic = 0;
+ entry.children.forEach(function (child){
+ if(!child.$ul) {
+ // always open
+ weight += child.openSize;
+ } else if(child.openSize > dynamic){
+ // largest collapsible child seen so far
+ dynamic = child.openSize;
+ }
+ });
+ entry.openSize = (weight += dynamic);
+
+ // determine if this one should actually be collapsible
+ // TODO: this max weight should really depend on how much
+ // room is available; and/or be decided when parent
+ // is comparing all the children.
+ // NOTE: 'toc-always-open' and 'toc-always-toggle' are control
+ // flags that can be applied via rst-class to section header.
+ if((weight > 3 && !entry.$target.hasClass("toc-always-open") ||
+ entry.$target.hasClass("toc-always-toggle")))
+ {
+ entry.$ul = $ul;
+ entry.$li.addClass("toc-toggle");
+ toggleDB.push(entry);
+ }
+ }
+
+ // debugging helper
+// var cutoffPrefix = 'pointer-events: none; position: fixed; left: 0; right: 0; background: ',
+// $cutoff = $('', {style: cutoffPrefix + 'rgba(0,0,255,0.3)'}).appendTo("body"),
+// $cutoff2 = $('', {style: cutoffPrefix + 'rgba(0,255,0,0.3)'}).appendTo("body");
+
+ // function to update cutoff settings
+ var winHeight, // window height
+ lineHeight, // sbody's line height (px)
+ minCutoff, // minimum viewport offset where we assume user is reading
+ curHash; // hash of current highlighted section
+
+ function updateConfig(_evt, first_run){
+ // determine viewable range
+ lineHeight = csspx($sbody, "line-height");
+ winHeight = $window.height();
+ minCutoff = Math.floor(Math.min(winHeight * 0.2, 7 * lineHeight));
+ curHash = shorten_url(document.location.hash) || "#";
+
+ // update TOC markers
+ updateTOC(_evt, first_run);
+ }
+
+ // function to update toc markers
+ function updateTOC(_evt, first_run) {
+ // recalc readline -- attempt to estimate where user who's
+ // scanning through docs is "reading". We start w/ minCutoff,
+ // but when at bottom of screen, may have a bunch of sections visible,
+ // and want to have them expand as last bit of document scrolls into view,
+ // so the readline moves down page when document gets to the end.
+ var readline = minCutoff,
+ bodyBottom = $sbody[0].getBoundingClientRect().bottom,
+ useMaxRatio = (2 * winHeight - bodyBottom - minCutoff) / (winHeight - minCutoff);
+ if (useMaxRatio > 0) {
+ var maxCutoff = Math.min(bodyBottom - 3 * lineHeight, winHeight);
+ readline = minCutoff + (maxCutoff - minCutoff) * Math.min(useMaxRatio, 1);
+ }
+ if (winHeight > $sbody.height()) {
+ readline = 0;
+ }
+
+ // debug stats
+// console.debug("useMaxRatio=%o", useMaxRatio);
+// $cutoff.css({height: readline, top: 0});
+// $cutoff2.css({height: minCutoff, top: 0});
+
+ // reset entries -- recalc .rect & .visible; clear .active flag;
+ // clear active/focus styling classes
+ localDB.forEach(function (entry){
+ var rect = entry.rect = entry.$target[0].getBoundingClientRect();
+ entry.visible = (rect.top <= winHeight && rect.bottom >= 0 &&
+ (rect.width || rect.height));
+ entry.active = false;
+ entry.$li.removeClass("active focus");
+ });
+
+ // pick focus at top TOC level, then check if one of it's
+ // children would be better choice, and so on until
+ // there are no children that could hold focus.
+ // NOTE: assumes children are listed in reading order.
+ var focus = localDB[0];
+ while (true) {
+ var best = null,
+ children = focus.children,
+ cutoff = readline;
+ for(var i = 0, e = children.length; i < e; ++i){
+ var child = children[i];
+ // skip hidden children
+ if(!child.visible) { continue; }
+
+ // pick bottom-most child which starts above readline.
+ else if (child.rect.top <= cutoff) {
+ best = child;
+
+ // if child is highlighted, keep it open longer,
+ // by raising the readline up to minCutoff.
+ if(child.href == curHash){
+ cutoff = minCutoff;
+ }
+ }
+ }
+ var $li = focus.$li;
+ focus.active = true;
+ $li.addClass("active");
+ if (best) {
+ if(!best.isLocal && focus.isLocal){
+ // set focus on final local section
+ // as well as child link
+ $li.addClass("focus");
+ }
+ focus = best;
+ } else {
+ $li.addClass("focus");
+ break;
+ }
+ }
+
+ // update open/closed status of nested ULs
+ // TODO: would like to do cleaner job tracking
+ // which sections are being animated open/close,
+ // and sync it w/ smooth-scrolling code (below).
+ // for now, only have '.justOpened' hack to detect
+ // if we're currently animating a parent element.
+ toggleDB.forEach(function (entry){
+ var $li = entry.$li,
+ $ul = entry.$ul,
+ closed = (!entry.visible || !entry.active ||
+ entry.$target.hasClass("collapsed"));
+ if(smallScreen) { closed = false; first_run = true; }
+ entry.justOpened = false;
+ if ($li.hasClass("closed") == closed) { return; }
+ if (closed) {
+ if (first_run) {
+ $ul.hide(); // don't animate things on first run
+ } else {
+ $ul.slideUp();
+ }
+ } else {
+ var parent = entry.parent;
+ if (first_run || (parent && parent.justOpened)) {
+ $ul.show(); // don't animate if parent is animated.
+ } else {
+ $ul.slideDown();
+ }
+ entry.justOpened = true;
+ }
+ $li.toggleClass("closed", closed);
+ });
+ }
+
+ // run function now, and every time window is resized
+ // TODO: disable when sidebar isn't sticky (including when window is too small)
+ // and when sidebar is collapsed / invisible
+ function scrollWrapper(evt){
+ if(scrollingActive) { return; }
+ return updateTOC(evt);
+ }
+ $window.on("scroll", scrollWrapper)
+ .on('resize hashchange cloud-section-toggled cloud-sidebar-toggled',
+ updateConfig);
+ updateConfig(null, true);
+ });
+
+
+ /* ==========================================================================
+ * header breaker
+ * ==========================================================================
+ * attempts to intelligently insert linebreaks into page titles, where possible.
+ * currently only handles titles such as "module - description",
+ * adding a break after the "-".
+ * ==========================================================================*/
+ $(function () {
+ // get header's content, insert linebreaks
+ var header = $("h1");
+ var orig = header[0].innerHTML;
+ var shorter = orig;
+ if ($("h1 > a:first > tt > span.pre").length > 0) {
+ shorter = orig.replace(/(<\/tt><\/a>\s*[-\u2013\u2014:]\s+)/im, "$1 ");
+ }
+ else if ($("h1 > tt.literal:first").length > 0) {
+ shorter = orig.replace(/(<\/tt>\s*[-\u2013\u2014:]\s+)/im, "$1 ");
+ }
+ if (shorter == orig) {
+ return;
+ }
+
+ // hack to determine full width of header
+ header.css({whiteSpace: "nowrap", position: "absolute"});
+ var header_width = header.width();
+ header.css({whiteSpace: "", position: ""});
+
+ // func to insert linebreaks when needed
+ function layout_header() {
+ header[0].innerHTML = (header_width > header.parent().width()) ? shorter : orig;
+ }
+
+ // run function now, and every time window is resized
+ layout_header();
+ $window.on('resize cloud-sidebar-toggled', layout_header);
+ });
+
+
+
+
+ /*==========================================================================
+ * smooth scrolling
+ * instrument toc links w/in same page to use smooth scrolling
+ *==========================================================================*/
+ var scrollSpeed = 500;
+ $(function () {
+ $('.sphinxsidebar a[href^="#"]').click(function (event) {
+ var hash = this.hash;
+ event.preventDefault();
+ scrollingActive = true; // disable toc focus calc
+ $('html,body').animate({
+ // NOTE: hash == "" for top of document
+ scrollTop: hash ? $(escapeHash(hash)).offset().top : 0
+ }, scrollSpeed).promise().always(function (){
+ // enable & redraw toc focus
+ // xxx: would really like to update *before* animation starts,
+ // so it's animation happened in parallel to scrolling animation
+ scrollingActive = false;
+ $window.trigger("cloud-sidebar-toggled");
+ });
+ if (window.history.pushState) {
+ window.history.pushState(null, "", hash || "#");
+ }
+ $window.trigger("hashchange"); // for toggle section code
+ });
+ });
+
+
+
+ /*==========================================================================
+ * auto determine when admonition should have inline / block title
+ * under this mode, the css will default to styling everything like a block,
+ * so we just mark everything that shouldn't be blocked out.
+ *==========================================================================*/
+ $(function () {
+ $("div.body div.admonition:not(.inline-title):not(.block-title)" +
+ ":not(.danger):not(.error)" +
+ ":has(p:first-child + p:last-child)").addClass("inline-title");
+ });
+
+
+ /*==========================================================================
+ * patch sphinx search code to try to and prevent rest markup from showing up
+ * in search results
+ *==========================================================================*/
+ var Search = window.Search;
+ if (Search && Search.makeSearchSummary) {
+ var sphinxSummary = Search.makeSearchSummary;
+ Search.makeSearchSummary = function (text, keywords, hlwords) {
+ /* very primitive regex hack to turn headers into dots */
+ text = text.replace(/^(\s|\n)*([-#=.])\2{6,}\s*\n/, '');
+ text = text.replace(/^([-#=.])\1{6,}\s*$/mg, '\u26AB');
+ text = text.replace(/^\s*#\.\s*/mg, '\u2022 ');
+ //console.debug("makeSearchSummary: text=%o keywords=%o hlwords=%o", text, keywords, hlwords);
+ return sphinxSummary.call(this, text, keywords, hlwords);
+ }
+ }
+
+ /*==========================================================================
+ * toc page styling
+ *==========================================================================
+ * adds some classes to TOC page so items can be styled.
+ * sets li.page and div.highlight-pages markers
+ *==========================================================================*/
+ $(function () {
+ $("div.body div.toctree-wrapper").each(function (){
+ var $div = $(this),
+ highlight = false;
+ $div.find("li").each(function (){
+ var $li = $(this),
+ url = baseUrl($li.children("a").attr("href")),
+ $parent = $li.parent("ul").prev("a"),
+ parentUrl = baseUrl($parent.attr("href"));
+ if(!$parent.length || parentUrl != url){
+ $li.addClass("page");
+ } else {
+ highlight = true;
+ }
+ });
+ if(highlight) { $div.addClass("highlight-pages"); }
+ });
+
+ var $toc = $("#table-of-contents div.toctree-wrapper.highlight-pages");
+ if($toc.length){
+ $('')
+ .insertBefore($toc).find("input")
+ .change(function (evt){
+ $toc.toggleClass("hide-sections", evt.target.checked);
+ }).change();
+ $(".sphinxglobaltoc > h3").css("margin-top", "4px").wrap('
');
+ }
+ });
+
+ /* ==========================================================================
+ * codeblock lineno aligner
+ * if document contains multiple codeblocks, and some have different counts
+ * (e.g. 10 lines vs 300 lines), the alignment will look off, since the
+ * 300 line block will be indented 1 extra space to account for the hundreds.
+ * this unifies the widths of all such blocks (issue 19)
+ *==========================================================================*/
+ $(function () {
+ var $lines = $(".linenodiv pre");
+ if (!$lines.length) {
+ return;
+ }
+ // NOTE: using ems so this holds under font size changes
+ var largest = Math.max.apply(null, $lines.map(function () {
+ return $(this).innerWidth();
+ })),
+ em_to_px = csspx($lines, "font-size");
+ $lines.css("width", (largest / em_to_px) + "em").css("text-align", "right");
+ });
+
+ /*==========================================================================
+ * codeblock copy helper button
+ *==========================================================================
+ *
+ * Add a [>>>] button on the top-right corner of code samples to hide
+ * the '>>>' and '...' prompts and the output and thus make the code
+ * copyable. Also hides linenumbers.
+ *
+ * Adapted from copybutton.js,
+ * Copyright 2014 PSF. Licensed under the PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
+ * File originates from the cpython source found in Doc/tools/sphinxext/static/copybutton.js
+ *==========================================================================*/
+ $(function () {
+ // TODO: enhance this to hide linenos for ALL highlighted code blocks,
+ // and only perform python-specific hiding as-needed.
+
+ // static text
+ var hide_text = 'Hide the prompts and output',
+ show_text = 'Show the prompts and output';
+
+ // helper which sets button & codeblock state
+ function setButtonState($button, active) {
+ $button.parent().find('.go, .gp, .gt').toggle(!active);
+ $button.next('pre').find('.gt').nextUntil('.gp, .go').css('visibility', active ? 'hidden' : 'visible');
+ $button.closest(".highlighttable").find(".linenos pre").css('visibility', active ? 'hidden' : 'visible');
+ $button.attr('title', active ? show_text : hide_text);
+ $button.toggleClass("active", active);
+ }
+
+ // create and add the button to all the code blocks containing a python prompt
+ var $blocks = $('.highlight-python, .highlight-python3');
+ $blocks.find(".highlight:has(pre .gp)").each(function () {
+ var $block = $(this);
+
+ // tracebacks (.gt) contain bare text elements that need to be
+ // wrapped in a span to work with .nextUntil() call in setButtonState()
+ $block.find('pre:has(.gt)').contents().filter(function () {
+ return ((this.nodeType == TEXT_NODE) && (this.data.trim().length > 0));
+ }).wrap('');
+
+ // insert button into block
+ var $button = $('');
+ $block.css("position", "relative").prepend($button);
+ setButtonState($button, false);
+ });
+
+ // toggle button state when clicked
+ $('.copybutton').click(
+ function () {
+ var $button = $(this);
+ setButtonState($button, !$button.hasClass("active"));
+ });
+ });
+
+ /*==========================================================================
+ * nested section helper
+ *==========================================================================
+ * fills out 'data-nested-label' for nested sections (e.g. those w/in a class def)
+ * based on name of containing class. this is used to generate a "return to top"
+ * link w/in nested section header.
+ *==========================================================================*/
+
+ $(function () {
+ var template = ({name}) => `${name} \u2014\u0020`;
+
+ $(".desc-section > .section-header").each(function (idx, header) {
+ var $header = $(header),
+ $parent = $header.closest("dd").prev("dt"),
+ name = $parent.find(".descname").text();
+ if (!name) {
+ return;
+ }
+ $header.attr("data-nested-label", template({name: name, parent: $parent}));
+ });
+ });
+
+
+ /*==========================================================================
+ * field definition markup
+ * XXX: could try to do this via an extension
+ *==========================================================================*/
+ $(function () {
+ // sphinx2 doesn't distinguish classmethod/staticmethod, so add helper class for styling.
+ $("dl.method").each(function (){
+ var $item = $(this),
+ type = $item.find("> dt > em.property:first-child").text().trim();
+ if(type){
+ $item.attr("subtype", type);
+ }
+ });
+
+ // detect which ones end w/ headerlink, to adjust markup
+ // NOTE: .classmethod & .staticmethod can be removed when sphinx 1.x is dropped.
+ $("dl.object, dl.data, dl.function, dl.method, dl.attribute, dl.class , dl.exception, dl.classmethod, dl.staticmethod")
+ .filter(":has(> dt > a.headerlink:last-child)").addClass("has-headerlink");
+ });
+
+ /*==========================================================================
+ * eof
+ *==========================================================================*/
+
+// end encapsulation
+// NOTE: sphinx provides underscore.js as $u
+}(window, jQuery, CST));
\ No newline at end of file
diff --git a/web/theme-4.css b/web/theme-4.css
index 7bf548bf4..e2af162b5 100644
--- a/web/theme-4.css
+++ b/web/theme-4.css
@@ -15,8 +15,12 @@
--code-font: "Nunito Sans" !important;
}
+body {
+ font-size: 14pt;
+}
+
#psij-app * {
- font-weight: 300 !important;
+ font-weight: 400;
}
#psij-app .fas,
@@ -67,6 +71,10 @@
font-size: 1.2em;
}
+#version-selector .v-text-field__prefix, #version-selector .v-select__selections {
+ font-size: 14pt !important;
+}
+
#psij-app h2,
#psij-app h2 *,
#psij-app h3,