"debputy: version and paths computed at build time"

import functools
import pathlib
import re
import subprocess

# Replaced during install; must be a single line
# fmt: off
DEBPUTY_ROOT_DIR = pathlib.Path(__file__).parent.parent.parent
DEBPUTY_PLUGIN_ROOT_DIR = pathlib.Path(__file__).parent.parent.parent
_VERSION = ""
# fmt: on

DEBPUTY_IS_RUN_FROM_SOURCE = not _VERSION


def _from_git() -> str:
    try:
        v = subprocess.check_output(
            ("git", "describe", "--tags"),
            stderr=subprocess.DEVNULL,
            encoding="utf-8",
        )
    except (subprocess.CalledProcessError, FileNotFoundError):
        return ""
    v = v.rstrip()

    parts = v.split("-")
    if "-g" in v and len(parts) == 3:
        v = f"{parts[0]}.dev{parts[1]}+{parts[2]}"

    # Git tags contain a prefix like archive/debian/ or debian/.
    v = v.removeprefix("archive/")
    v = v.removeprefix("debian/")

    return v


def _from_dch() -> str:
    try:
        v = subprocess.check_output(
            ("dpkg-parsechangelog", "-SVersion"),
            stderr=subprocess.DEVNULL,
            encoding="utf-8",
        )
    except (subprocess.CalledProcessError, FileNotFoundError):
        return ""
    v = v.rstrip()

    v = re.sub(r"~bpo\d+[+]\d+$", "", v)

    m = re.match(r"(.+)~(\d+)[.]g(.+)", v)
    if m:
        v = f"{m.group(1)}.dev{m.group(2)}+{m.group(3)}"

    return v


@functools.cache
def version() -> str:
    "The debputy version, extracted from the Debian packaging or git."
    return _VERSION or _from_git() or _from_dch() or "N/A"


def debputy_doc_root_dir() -> str:
    """The doc URL differs in releases and development builds
    (including `gbp dch -S` snapshots)."""
    is_release_build = _VERSION and ".gbp" not in _VERSION
    blob = f"debian/{version()}" if is_release_build else "main"
    return f"https://salsa.debian.org/debian/debputy/-/blob/{blob}"
