Skip to content

versioning

napt.versioning

Version extraction and ordering utilities for NAPT.

Extracts version information and other metadata from MSI and MSIX files, and orders version strings the way managed devices do.

Modules:

Name Description
ordering

Version ordering that mirrors the device-side comparison.

msi

MSI metadata extraction using PowerShell COM (Windows) or msitools (Linux/macOS).

msix

MSIX metadata extraction using zipfile and XML parsing (cross-platform).

napt.versioning.msi

MSI metadata extraction for NAPT.

This module extracts metadata from Windows Installer (MSI) database files, including ProductVersion, ProductName, and architecture (from Template).

Backend Priority:

  • Windows: PowerShell COM (Windows Installer COM API, always available)
  • Linux/macOS: msiinfo (from the msitools package, must be installed separately)

Installation Requirements:

  • Windows: No additional packages required (PowerShell is always available).
  • Linux/macOS: Install the msitools package (apt-get install msitools, dnf install msitools, or brew install msitools).
Note

This is pure file introspection; no network calls are made. The PowerShell COM backend reads both the Property table (ProductName, ProductVersion) and Summary Information stream (Template/architecture) in a single database open.

MSIMetadata dataclass

Represents metadata extracted from an MSI file.

Attributes:

Name Type Description
product_name str

ProductName from MSI Property table (display name).

product_version str

ProductVersion from MSI Property table.

architecture Architecture

Installer architecture from MSI Template Summary Information property. Always one of "x86", "x64", or "arm64".

Source code in napt/versioning/msi.py
@dataclass(frozen=True)
class MSIMetadata:
    """Represents metadata extracted from an MSI file.

    Attributes:
        product_name: ProductName from MSI Property table (display name).
        product_version: ProductVersion from MSI Property table.
        architecture: Installer architecture from MSI Template Summary
            Information property. Always one of "x86", "x64", or "arm64".
    """

    product_name: str
    product_version: str
    architecture: Architecture

extract_msi_metadata

extract_msi_metadata(file_path: str | Path) -> MSIMetadata

Extracts ProductName, ProductVersion, and architecture from an MSI file.

Reads the MSI Property table (ProductName, ProductVersion) and Summary Information stream (Template/architecture) in a single database open. On Windows, uses the PowerShell COM API. On Linux/macOS, requires msitools.

Parameters:

Name Type Description Default
file_path str | Path

Path to the MSI file.

required

Returns:

Type Description
MSIMetadata

MSI metadata including product name, version, and architecture.

Raises:

Type Description
PackagingError

If the MSI file does not exist, no backend can read it on this host, extraction fails, or the MSI platform is not supported by Intune.

Example

Extract MSI metadata:

from pathlib import Path
from napt.versioning.msi import extract_msi_metadata

meta = extract_msi_metadata(Path("chrome.msi"))
print(f"{meta.product_name} {meta.product_version} ({meta.architecture})")
# Google Chrome 131.0.6778.86 (x64)

Note

ProductName may be an empty string when the MSI has none. The build refuses such an MSI unless the recipe overrides both the display name and the uninstall command, since detection matches on it.

Source code in napt/versioning/msi.py
def extract_msi_metadata(file_path: str | Path) -> MSIMetadata:
    """Extracts ProductName, ProductVersion, and architecture from an MSI file.

    Reads the MSI Property table (ProductName, ProductVersion) and Summary
    Information stream (Template/architecture) in a single database open.
    On Windows, uses the PowerShell COM API. On Linux/macOS, requires msitools.

    Args:
        file_path: Path to the MSI file.

    Returns:
        MSI metadata including product name, version, and architecture.

    Raises:
        PackagingError: If the MSI file does not exist, no backend can read
            it on this host, extraction fails, or the MSI platform is not
            supported by Intune.

    Example:
        Extract MSI metadata:
            ```python
            from pathlib import Path
            from napt.versioning.msi import extract_msi_metadata

            meta = extract_msi_metadata(Path("chrome.msi"))
            print(f"{meta.product_name} {meta.product_version} ({meta.architecture})")
            # Google Chrome 131.0.6778.86 (x64)
            ```

    Note:
        ProductName may be an empty string when the MSI has none. The build
        refuses such an MSI unless the recipe overrides both the display
        name and the uninstall command, since detection matches on it.

    """
    logger = get_global_logger()
    msi_path = Path(file_path)
    if not msi_path.exists():
        raise PackagingError(f"MSI not found: {msi_path}")

    logger.verbose("MSI", f"Extracting metadata from: {msi_path.name}")

    # PowerShell COM (Windows only)
    if sys.platform.startswith("win"):
        logger.debug("MSI", "Trying backend: PowerShell COM...")
        quoted_path = ps_single_quote(str(msi_path))
        query = (
            "SELECT Property, Value FROM Property "
            "WHERE Property = 'ProductName' OR Property = 'ProductVersion'"
        )
        # The values come back through a UTF-8 file, never stdout (see
        # run_powershell_lines). An empty Template is written as an empty
        # line; _architecture_from_template decides what it means, the
        # same as for the msiinfo backend.
        ps_script = f"""
$installer = New-Object -ComObject WindowsInstaller.Installer
$db = $installer.OpenDatabase({quoted_path}, 0)
if ($null -eq $db) {{
    Write-Error "Failed to open database"
    exit 1
}}
$view = $db.OpenView("{query}")
$view.Execute()
$props = @{{}}
while ($record = $view.Fetch()) {{
    $props[$record.StringData(1)] = $record.StringData(2)
}}
$view.Close()
if (-not $props['ProductVersion']) {{
    Write-Error "ProductVersion not found"
    exit 1
}}
$sumInfo = $db.SummaryInformation(0)
$template = $sumInfo.Property(7)
$db.Close()
$utf8 = New-Object System.Text.UTF8Encoding $false
[System.IO.File]::WriteAllLines(
    $env:NAPT_MSI_OUT,
    [string[]]@($props['ProductName'], $props['ProductVersion'], $template),
    $utf8
)
"""
        # The script exits 1 before writing when ProductVersion is missing,
        # so three lines are always present here.
        product_name, product_version, template = run_powershell_lines(
            ps_script,
            out_var="NAPT_MSI_OUT",
            timeout=10,
            what="PowerShell MSI query",
        )[:3]
        architecture = _architecture_from_template(template)
        logger.verbose(
            "MSI",
            f"[OK] Extracted: {product_name} {product_version} "
            f"({architecture}) (via PowerShell COM)",
        )
        return MSIMetadata(
            product_name=product_name,
            product_version=product_version,
            architecture=architecture,
        )

    # msiinfo (Linux/macOS)
    msiinfo_bin = shutil.which("msiinfo")
    if msiinfo_bin:
        logger.debug("MSI", "Trying backend: msiinfo (msitools)...")
        try:
            property_result = subprocess.run(
                [msiinfo_bin, "export", str(msi_path), "Property"],
                check=True,
                capture_output=True,
                text=True,
            )
            properties: dict[str, str] = {}
            for line in property_result.stdout.splitlines():
                columns = line.strip().split("\t", 1)
                if len(columns) == 2:
                    properties[columns[0]] = columns[1]

            product_version = properties.get("ProductVersion", "")
            if not product_version:
                raise PackagingError("ProductVersion not found in MSI Property output.")

            suminfo_result = subprocess.run(
                [msiinfo_bin, "suminfo", str(msi_path)],
                check=True,
                capture_output=True,
                text=True,
            )
            # A summary without a Template reads as empty, which
            # _architecture_from_template maps the same way for both backends.
            template = ""
            for line in suminfo_result.stdout.splitlines():
                if line.startswith("Template:"):
                    template = line.split(":", 1)[1].strip()
                    break

            architecture = _architecture_from_template(template)
            product_name = properties.get("ProductName", "")
            logger.verbose(
                "MSI",
                f"[OK] Extracted: {product_name} {product_version} "
                f"({architecture}) (via msiinfo)",
            )
            return MSIMetadata(
                product_name=product_name,
                product_version=product_version,
                architecture=architecture,
            )
        except subprocess.CalledProcessError as err:
            raise PackagingError(f"msiinfo failed: {err}") from err

    raise PackagingError(
        "MSI metadata extraction needs msitools on this host. Install the "
        "'msitools' package (msiinfo) and run the build again."
    )

napt.versioning.ordering

Version ordering as managed devices see it.

Whether a release installs over another is decided on the device by Compare-VersionString in napt/build/templates/_shared_functions.ps1, which the detection and requirements scripts call. This module mirrors that function, so that when NAPT calls a release a downgrade it means the same thing the device will: devices on the other version will not take it.

The mirror is deliberately no smarter than the original. Each . or - separated segment contributes its leading digits, a segment without leading digits counts as 0, and missing trailing segments count as 0. A v prefix or a prerelease tag is therefore not understood on either side. tests/test_version_ordering.py runs one table of cases through both implementations to keep them in step.

version_parts

version_parts(version: str) -> list[int]

Parses a version string into the numbers a device compares.

Parameters:

Name Type Description Default
version str

Version string, for example "140.0.7339.128".

required

Returns:

Type Description
list[int]

One integer per segment: its leading digits, or 0 when it has none.

Source code in napt/versioning/ordering.py
def version_parts(version: str) -> list[int]:
    """Parses a version string into the numbers a device compares.

    Args:
        version: Version string, for example ``"140.0.7339.128"``.

    Returns:
        One integer per segment: its leading digits, or 0 when it has none.

    """
    parts: list[int] = []
    for segment in _SEGMENT_SEPARATORS.split(version):
        match = _LEADING_DIGITS.match(segment)
        parts.append(int(match.group()) if match else 0)
    return parts

compare_versions

compare_versions(left: str, right: str) -> int

Compares two version strings the way a managed device does.

Parameters:

Name Type Description Default
left str

First version string.

required
right str

Second version string.

required

Returns:

Type Description
int

-1 when left is lower, 0 when they are equal, and 1 when left is higher.

Source code in napt/versioning/ordering.py
def compare_versions(left: str, right: str) -> int:
    """Compares two version strings the way a managed device does.

    Args:
        left: First version string.
        right: Second version string.

    Returns:
        -1 when ``left`` is lower, 0 when they are equal, and 1 when
            ``left`` is higher.

    """
    left_parts = version_parts(left)
    right_parts = version_parts(right)
    length = max(len(left_parts), len(right_parts))
    left_parts += [0] * (length - len(left_parts))
    right_parts += [0] * (length - len(right_parts))
    return (left_parts > right_parts) - (left_parts < right_parts)

is_downgrade

is_downgrade(candidate: str, current: str | None) -> bool

Reports whether a release is lower than the one it would replace.

Parameters:

Name Type Description Default
candidate str

Version of the release being considered.

required
current str | None

Version it would replace, or None when there is none.

required

Returns:

Type Description
bool

True when devices on current would not take candidate.

Source code in napt/versioning/ordering.py
def is_downgrade(candidate: str, current: str | None) -> bool:
    """Reports whether a release is lower than the one it would replace.

    Args:
        candidate: Version of the release being considered.
        current: Version it would replace, or None when there is none.

    Returns:
        True when devices on ``current`` would not take ``candidate``.

    """
    return current is not None and compare_versions(candidate, current) < 0

napt.versioning.msix

MSIX metadata extraction for NAPT.

This module extracts metadata from MSIX package files by reading the embedded AppxManifest.xml. MSIX files are ZIP archives containing a signed app package manifest with identity, display, and capability information.

Extraction Approach

Uses Python's zipfile and xml.etree.ElementTree to parse AppxManifest.xml directly from the archive. No external dependencies or platform-specific tools required.

Extracted Fields
  • Identity.Name: Package identity for Get-AppxPackage detection
  • Identity.Version: Four-part version string (e.g., "4.49.81.0")
  • Identity.ProcessorArchitecture: Mapped to NAPT architecture values
  • Properties.DisplayName: Human-readable application name
Note

This is pure file introspection; no network calls are made. Works cross-platform with no external dependencies.

MSIXMetadata dataclass

Represents metadata extracted from an MSIX file.

Attributes:

Name Type Description
display_name str

DisplayName from Properties element.

version str

Version from Identity element (four-part, e.g., "4.49.81.0").

architecture Architecture

Installer architecture from Identity ProcessorArchitecture attribute. One of "x86", "x64", "arm64", or "any" (for architecture-neutral packages).

identity_name str

Package identity name from Identity Name attribute. Used for Get-AppxPackage -Name queries in detection scripts.

Source code in napt/versioning/msix.py
@dataclass(frozen=True)
class MSIXMetadata:
    """Represents metadata extracted from an MSIX file.

    Attributes:
        display_name: DisplayName from Properties element.
        version: Version from Identity element (four-part, e.g.,
            "4.49.81.0").
        architecture: Installer architecture from Identity
            ProcessorArchitecture attribute. One of "x86", "x64",
            "arm64", or "any" (for architecture-neutral packages).
        identity_name: Package identity name from Identity Name attribute.
            Used for ``Get-AppxPackage -Name`` queries in detection scripts.
    """

    display_name: str
    version: str
    architecture: Architecture
    identity_name: str

extract_msix_metadata

extract_msix_metadata(file_path: str | Path) -> MSIXMetadata

Extracts metadata from an MSIX file's AppxManifest.xml.

Reads the MSIX archive (ZIP format) and parses AppxManifest.xml to extract identity, version, architecture, and display name.

Parameters:

Name Type Description Default
file_path str | Path

Path to the MSIX file.

required

Returns:

Type Description
MSIXMetadata

MSIX metadata including display name, version, architecture, and

MSIXMetadata

identity name.

Raises:

Type Description
PackagingError

If the MSIX file does not exist, is not a valid ZIP archive, does not contain AppxManifest.xml, holds one that is not well-formed XML, is missing required fields, or names an architecture Intune does not support.

Example

Extract MSIX metadata:

from pathlib import Path
from napt.versioning.msix import extract_msix_metadata

meta = extract_msix_metadata(Path("Slack.msix"))
print(f"{meta.display_name} {meta.version} ({meta.architecture})")
# Slack 4.49.81.0 (x64)

Note

DisplayName may reference an ms-resource string in some packages. It is returned as is, and the detection script then matches on it.

Source code in napt/versioning/msix.py
def extract_msix_metadata(file_path: str | Path) -> MSIXMetadata:
    """Extracts metadata from an MSIX file's AppxManifest.xml.

    Reads the MSIX archive (ZIP format) and parses AppxManifest.xml to
    extract identity, version, architecture, and display name.

    Args:
        file_path: Path to the MSIX file.

    Returns:
        MSIX metadata including display name, version, architecture, and
        identity name.

    Raises:
        PackagingError: If the MSIX file does not exist, is not a valid
            ZIP archive, does not contain AppxManifest.xml, holds one that
            is not well-formed XML, is missing required fields, or names an
            architecture Intune does not support.

    Example:
        Extract MSIX metadata:
            ```python
            from pathlib import Path
            from napt.versioning.msix import extract_msix_metadata

            meta = extract_msix_metadata(Path("Slack.msix"))
            print(f"{meta.display_name} {meta.version} ({meta.architecture})")
            # Slack 4.49.81.0 (x64)
            ```

    Note:
        DisplayName may reference an ms-resource string in some packages.
        It is returned as is, and the detection script then matches on it.

    """
    logger = get_global_logger()
    msix_path = Path(file_path)
    if not msix_path.exists():
        raise PackagingError(f"MSIX not found: {msix_path}")

    logger.verbose("MSIX", f"Extracting metadata from: {msix_path.name}")

    try:
        with zipfile.ZipFile(msix_path, "r") as zf:
            if "AppxManifest.xml" not in zf.namelist():
                raise PackagingError(
                    f"AppxManifest.xml not found in {msix_path.name}. "
                    f"File may not be a valid MSIX package."
                )
            manifest_bytes = zf.read("AppxManifest.xml")
    except zipfile.BadZipFile as err:
        raise PackagingError(
            f"Cannot read {msix_path.name}: not a valid ZIP/MSIX archive."
        ) from err

    try:
        root = ET.fromstring(manifest_bytes)
    except ET.ParseError as err:
        raise PackagingError(
            f"AppxManifest.xml in {msix_path.name} is not valid XML: {err}"
        ) from err

    # Parse Identity element
    identity = root.find(f"{{{MANIFEST_NS}}}Identity")
    if identity is None:
        raise PackagingError(
            f"Identity element not found in {msix_path.name} " f"AppxManifest.xml."
        )

    identity_name = identity.get("Name", "")
    version = identity.get("Version", "")
    proc_arch = identity.get("ProcessorArchitecture", "")

    if not identity_name:
        raise PackagingError(f"Identity Name attribute missing in {msix_path.name}.")
    if not version:
        raise PackagingError(f"Identity Version attribute missing in {msix_path.name}.")
    if not proc_arch:
        raise PackagingError(
            f"Identity ProcessorArchitecture attribute missing in " f"{msix_path.name}."
        )

    architecture = _architecture_from_manifest(proc_arch)

    # Parse Properties element
    properties = root.find(f"{{{MANIFEST_NS}}}Properties")
    if properties is None:
        raise PackagingError(
            f"Properties element not found in {msix_path.name} " f"AppxManifest.xml."
        )

    display_name_node = properties.find(f"{{{MANIFEST_NS}}}DisplayName")
    display_name = display_name_node.text if display_name_node is not None else ""

    if not display_name:
        raise PackagingError(f"Properties DisplayName not found in {msix_path.name}.")

    logger.verbose(
        "MSIX",
        f"[OK] Extracted: {display_name} {version} ({architecture}) "
        f"[{identity_name}]",
    )

    return MSIXMetadata(
        display_name=display_name,
        version=version,
        architecture=architecture,
        identity_name=identity_name,
    )