| 
 | 1 | +"""Setuptools SCM integration for sphinx-polyversion."""  | 
 | 2 | + | 
 | 3 | +from __future__ import annotations  | 
 | 4 | + | 
 | 5 | +import dataclasses  | 
 | 6 | +import shlex  | 
 | 7 | +from logging import getLogger  | 
 | 8 | +from pathlib import Path  | 
 | 9 | +from typing import Tuple, TypeVar  | 
 | 10 | + | 
 | 11 | +from packaging.utils import canonicalize_name  | 
 | 12 | +from setuptools_scm import Configuration, _get_version  | 
 | 13 | +from setuptools_scm.git import DEFAULT_DESCRIBE  | 
 | 14 | + | 
 | 15 | +from sphinx_polyversion.driver import DefaultDriver  | 
 | 16 | +from sphinx_polyversion.git import GitRef  | 
 | 17 | +from sphinx_polyversion.pyvenv import VirtualPythonEnvironment  | 
 | 18 | +from sphinx_polyversion.utils import to_thread  | 
 | 19 | + | 
 | 20 | +logger = getLogger(__name__)  | 
 | 21 | + | 
 | 22 | + | 
 | 23 | +async def version_for_ref(repo_path: str | Path, ref: str) -> Tuple[str, str] | None:  | 
 | 24 | +    """  | 
 | 25 | +    Get version that `setuptools_scm` determined for a given revision.  | 
 | 26 | +
  | 
 | 27 | +    Calls `setuptools-scm` using the configuration in the `pyproject.toml`  | 
 | 28 | +    file. Alters the git describe command configured by appending  | 
 | 29 | +    the given :paramref:`ref`.  | 
 | 30 | +
  | 
 | 31 | +    .. warning::  | 
 | 32 | +
  | 
 | 33 | +        Only works when using git vcs.  | 
 | 34 | +
  | 
 | 35 | +    .. warning::  | 
 | 36 | +
  | 
 | 37 | +        Doesn't work for legacy python projects that do not use a `pyproject.toml`  | 
 | 38 | +        file.  | 
 | 39 | +
  | 
 | 40 | +
  | 
 | 41 | +    Parameters  | 
 | 42 | +    ----------  | 
 | 43 | +    repo_path : str | Path  | 
 | 44 | +        The location of the git repository.  | 
 | 45 | +    ref : str  | 
 | 46 | +        The reference of the revision.  | 
 | 47 | +
  | 
 | 48 | +    Returns  | 
 | 49 | +    -------  | 
 | 50 | +    Tuple[str, str] | None  | 
 | 51 | +        The version determined by `setuptools-scm`  | 
 | 52 | +        and the canonical distribution name, optional  | 
 | 53 | +
  | 
 | 54 | +    Raises  | 
 | 55 | +    ------  | 
 | 56 | +    FileNotFoundError  | 
 | 57 | +        No `pyproject.toml` file was found in the repo.  | 
 | 58 | +
  | 
 | 59 | +    """  | 
 | 60 | +    # Load project config for `setuptools-scm`  | 
 | 61 | +    repo_path = Path(repo_path)  | 
 | 62 | +    pyproject = repo_path / "pyproject.toml"  | 
 | 63 | +    if not pyproject.exists():  | 
 | 64 | +        raise FileNotFoundError(f"Could not find configuration file {pyproject}")  | 
 | 65 | +    config = Configuration.from_file(pyproject)  | 
 | 66 | + | 
 | 67 | +    # determine distribution name  | 
 | 68 | +    dist_name = canonicalize_name(config.dist_name)  | 
 | 69 | + | 
 | 70 | +    # Alter `git describe` command to use the ref  | 
 | 71 | +    cmd = config.scm.git.describe_command  | 
 | 72 | +    if cmd is None:  | 
 | 73 | +        # Use the `setuptools-scm`'s default describe command  | 
 | 74 | +        cmd = list(DEFAULT_DESCRIBE)  | 
 | 75 | +    elif isinstance(cmd, str):  | 
 | 76 | +        cmd = shlex.split(cmd)  | 
 | 77 | +    cmd = list(cmd)  | 
 | 78 | +    cmd.append(ref)  | 
 | 79 | + | 
 | 80 | +    # remove "--dirty" if present  | 
 | 81 | +    # its incompatible with describing a specific ref  | 
 | 82 | +    if "--dirty" in cmd:  | 
 | 83 | +        cmd.remove("--dirty")  | 
 | 84 | + | 
 | 85 | +    # Update configuration  | 
 | 86 | +    git_cfg = dataclasses.replace(config.scm.git, describe_command=cmd)  | 
 | 87 | +    scm_cfg = dataclasses.replace(config.scm, git=git_cfg)  | 
 | 88 | +    config = dataclasses.replace(config, scm=scm_cfg)  | 
 | 89 | + | 
 | 90 | +    # Get the version (don't write any version files).  | 
 | 91 | +    version = await to_thread(_get_version, config, force_write_version_files=False)  | 
 | 92 | +    if not version:  | 
 | 93 | +        return None  | 
 | 94 | +    return (version, dist_name)  | 
 | 95 | + | 
 | 96 | + | 
 | 97 | +RT = TypeVar("RT", bound=GitRef)  | 
 | 98 | +ENV = TypeVar("ENV", bound=VirtualPythonEnvironment)  | 
 | 99 | +S = TypeVar("S")  | 
 | 100 | + | 
 | 101 | + | 
 | 102 | +class SetuptoolsScmDriver(DefaultDriver[RT, ENV, S]):  | 
 | 103 | +    """  | 
 | 104 | +    Driver that uses `setuptools-scm` to determine the version of each revision.  | 
 | 105 | +
  | 
 | 106 | +    This driver requires that the project uses `setuptools-scm` and has a  | 
 | 107 | +    `pyproject.toml` file in the root of the repository.  | 
 | 108 | +
  | 
 | 109 | +    .. note::  | 
 | 110 | +
  | 
 | 111 | +        Must be used with  | 
 | 112 | +        :class:`~sphinx_polyversion.git.GitRef` (thus git vcs)  | 
 | 113 | +        and subclasses of :class:`~sphinx_polyversion.pyvenv.VirtualPythonEnvironment`  | 
 | 114 | +
  | 
 | 115 | +    .. note::  | 
 | 116 | +
  | 
 | 117 | +        Doesn't work for legacy python projects that do not use a `pyproject.toml`  | 
 | 118 | +        file.  | 
 | 119 | +
  | 
 | 120 | +    Parameters  | 
 | 121 | +    ----------  | 
 | 122 | +    cwd : Path  | 
 | 123 | +        The current working directory  | 
 | 124 | +    output_dir : Path  | 
 | 125 | +        The directory where to place the built docs.  | 
 | 126 | +    vcs : VersionProvider[RT]  | 
 | 127 | +        The version provider to use.  | 
 | 128 | +    builder : Builder[ENV, Any]  | 
 | 129 | +        The builder to use.  | 
 | 130 | +    env : Callable[[Path, str], ENV]  | 
 | 131 | +        A factory producing the environments to use.  | 
 | 132 | +    data_factory : Callable[[DefaultDriver[RT, ENV, S], RT, ENV], JSONable], optional  | 
 | 133 | +        A callable returning the data to pass to the builder.  | 
 | 134 | +    root_data_factory : Callable[[DefaultDriver[RT, ENV, S]], dict[str, Any]], optional  | 
 | 135 | +        A callable returning the variables to pass to the jinja templates.  | 
 | 136 | +    namer : Callable[[RT], str], optional  | 
 | 137 | +        A callable determining the name of a revision.  | 
 | 138 | +    selector: Callable[[RT, Iterable[S]], S | Coroutine[Any, Any, S]], optional  | 
 | 139 | +        The selector to use when either `env` or `builder` are a dict.  | 
 | 140 | +    encoder : Encoder, optional  | 
 | 141 | +        The encoder to use for dumping `versions.json` to the output dir.  | 
 | 142 | +    static_dir : Path, optional  | 
 | 143 | +        The source directory for root level static files.  | 
 | 144 | +    template_dir : Path, optional  | 
 | 145 | +        The source directory for root level templates.  | 
 | 146 | +    mock : MockData[RT] | None | Literal[False], optional  | 
 | 147 | +        Only build from local files and mock building all docs using the data provided.  | 
 | 148 | +
  | 
 | 149 | +    """  | 
 | 150 | + | 
 | 151 | +    async def init_environment(self, path: Path, rev: RT) -> ENV:  | 
 | 152 | +        """  | 
 | 153 | +        Initialize the build environment for a revision and path.  | 
 | 154 | +
  | 
 | 155 | +        The environment will be used to build the given revision and  | 
 | 156 | +        the path specifies the location where the revision is checked out.  | 
 | 157 | +
  | 
 | 158 | +        This implementation calls `setuptools-scm` to determine the version  | 
 | 159 | +        for the given revision and sets the environment variable  | 
 | 160 | +        `SETUPTOOLS_SCM_PRETEND_VERSION_FOR_<DIST_NAME>` in the returned  | 
 | 161 | +        environment.  | 
 | 162 | +
  | 
 | 163 | +        Parameters  | 
 | 164 | +        ----------  | 
 | 165 | +        path : Path  | 
 | 166 | +            The location of the revisions files.  | 
 | 167 | +        rev : GitRef  | 
 | 168 | +            The revision the environment is used for.  | 
 | 169 | +
  | 
 | 170 | +        Returns  | 
 | 171 | +        -------  | 
 | 172 | +        VirtualPythonEnvironment  | 
 | 173 | +
  | 
 | 174 | +        """  | 
 | 175 | +        f = await super().init_environment(path, rev)  | 
 | 176 | + | 
 | 177 | +        logger.info("Calling setuptools-scm to determine version for %s", rev.name)  | 
 | 178 | +        try:  | 
 | 179 | +            r = await version_for_ref(self.root, rev.obj)  | 
 | 180 | +        except FileNotFoundError:  | 
 | 181 | +            logger.warning(  | 
 | 182 | +                "Could not find pyproject.toml file in %s, "  | 
 | 183 | +                "skipping setuptools-scm integration",  | 
 | 184 | +                self.root,  | 
 | 185 | +            )  | 
 | 186 | +            r = None  | 
 | 187 | + | 
 | 188 | +        if r is None:  | 
 | 189 | +            logger.warning(  | 
 | 190 | +                "Couldn't determine `setuptools-scm` version for %s", rev.name  | 
 | 191 | +            )  | 
 | 192 | +            return f  | 
 | 193 | + | 
 | 194 | +        version, dist_name = r  | 
 | 195 | +        var_dist_name = dist_name.replace("-", "_").upper()  | 
 | 196 | + | 
 | 197 | +        f.env.setdefault(f"SETUPTOOLS_SCM_PRETEND_VERSION_FOR_{var_dist_name}", version)  | 
 | 198 | +        return f  | 
0 commit comments