Skip to content

icons

napt.build.icons

App icon extraction from installers for NAPT builds.

Extracts a Company Portal-ready PNG icon from MSI, EXE, and MSIX installers at build time. Only icon frames that are already PNG-encoded are used (no image re-encoding), and frames must be at least 128px wide and no larger than 700KB. Among qualifying frames, the one closest to Intune's recommended 256px is selected.

Extraction sources per installer type:

  • MSI: the Icon table (preferring the row named by ARPPRODUCTICON), then a fallback administrative extract of the MSI contents scanned for icons in the contained executables.
  • EXE: RT_GROUP_ICON/RT_ICON resources parsed directly from the PE file.
  • MSIX: logo assets declared in AppxManifest.xml, including scale and targetsize variants.

Backend Priority (MSI only):

  • Windows: PowerShell COM (Windows Installer COM API, always available)
  • Linux/macOS: msiinfo/msiextract (from the msitools package)
Note

Icon extraction is best-effort by design. The public entry point extract_icon_png never raises; a failure is reported through the returned result so the build can warn and continue. ensure_app_icon is the build step that keeps one icon per app in the icons directory.

IconExtraction dataclass

Represents the outcome of an icon extraction attempt.

Attributes:

Name Type Description
png bytes | None

PNG file bytes ready to write to disk, or None if no qualifying icon frame was found.

width int | None

Pixel width of the selected frame, or None on failure.

detail str

Source description on success (e.g. the MSI Icon table row or MSIX asset used), or the failure cause on failure.

Source code in napt/build/icons.py
@dataclass(frozen=True)
class IconExtraction:
    """Represents the outcome of an icon extraction attempt.

    Attributes:
        png: PNG file bytes ready to write to disk, or None if no
            qualifying icon frame was found.
        width: Pixel width of the selected frame, or None on failure.
        detail: Source description on success (e.g. the MSI Icon table row
            or MSIX asset used), or the failure cause on failure.
    """

    png: bytes | None
    width: int | None
    detail: str

extract_icon_png

extract_icon_png(installer_path: str | Path) -> IconExtraction

Extracts the best available PNG icon from an installer file.

Dispatches on the installer suffix (.msi, .msix, .exe) and applies the module's frame selection policy. This function never raises; failures of any kind are reported through the returned result's detail field.

Parameters:

Name Type Description Default
installer_path str | Path

Path to the installer file.

required

Returns:

Type Description
IconExtraction

Extraction outcome with PNG bytes and frame width on success, or a failure cause in detail when no qualifying icon was found.

Example

Extract and save an icon:

result = extract_icon_png("installer.msi")
if result.png is not None:
    Path("icon.png").write_bytes(result.png)

Source code in napt/build/icons.py
def extract_icon_png(installer_path: str | Path) -> IconExtraction:
    """Extracts the best available PNG icon from an installer file.

    Dispatches on the installer suffix (.msi, .msix, .exe) and applies the
    module's frame selection policy. This function never raises; failures
    of any kind are reported through the returned result's `detail` field.

    Args:
        installer_path: Path to the installer file.

    Returns:
        Extraction outcome with PNG bytes and frame width on success, or a
            failure cause in `detail` when no qualifying icon was found.

    Example:
        Extract and save an icon:
            ```python
            result = extract_icon_png("installer.msi")
            if result.png is not None:
                Path("icon.png").write_bytes(result.png)
            ```

    """
    logger = get_global_logger()
    path = Path(installer_path)
    suffix = path.suffix.lower()
    logger.verbose("BUILD", f"Extracting icon from: {path.name}")
    try:
        if suffix == ".msi":
            return _extract_from_msi(path)
        if suffix == ".msix":
            return _extract_from_msix(path)
        if suffix == ".exe":
            return _extract_from_exe(path)
        return IconExtraction(None, None, f"unsupported installer type '{suffix}'")
    except Exception as err:  # noqa: BLE001 - extraction must never fail the build
        logger.debug("BUILD", f"Icon extraction failed: {err!r}")
        return IconExtraction(None, None, f"extraction failed: {err}")

ensure_app_icon

ensure_app_icon(
    config: dict[str, Any], installer_file: Path, app_id: str
) -> None

Extracts the app icon from the installer into the icons directory.

Best-effort side task that never raises: a failed extraction warns and the build continues. Skipped when intune.logo_path is set (the explicit icon wins at upload) or when the icon file already exists (users may drop curated replacements into the icons directory; NAPT never overwrites them).

A failed extraction is recorded in a {app_id}.no-icon marker so expensive MSI extraction is not repeated every build. The marker invalidates itself when the installer file changes and is removed on a successful extraction.

Parameters:

Name Type Description Default
config dict[str, Any]

Merged effective configuration.

required
installer_file Path

Path to the downloaded installer.

required
app_id str

Recipe id; the icon is written to {directories.icons}/{app_id}.png.

required
Source code in napt/build/icons.py
def ensure_app_icon(config: dict[str, Any], installer_file: Path, app_id: str) -> None:
    """Extracts the app icon from the installer into the icons directory.

    Best-effort side task that never raises: a failed extraction warns and
    the build continues. Skipped when intune.logo_path is set (the explicit
    icon wins at upload) or when the icon file already exists (users may
    drop curated replacements into the icons directory; NAPT never
    overwrites them).

    A failed extraction is recorded in a ``{app_id}.no-icon`` marker so
    expensive MSI extraction is not repeated every build. The marker
    invalidates itself when the installer file changes and is removed on a
    successful extraction.

    Args:
        config: Merged effective configuration.
        installer_file: Path to the downloaded installer.
        app_id: Recipe id; the icon is written to
            ``{directories.icons}/{app_id}.png``.
    """
    logger = get_global_logger()

    if config["intune"].get("logo_path"):
        logger.info("BUILD", "Skipping icon extraction: intune.logo_path is set")
        return

    icons_dir = Path(config["directories"]["icons"])
    icon_path = icons_dir / f"{app_id}.png"
    if icon_path.exists():
        logger.info("BUILD", f"Skipping icon extraction: {icon_path} already exists")
        return

    marker_path = icons_dir / f"{app_id}.no-icon"
    stat = installer_file.stat()
    fingerprint = f"{installer_file.name}|{stat.st_size}|{stat.st_mtime_ns}"
    if marker_path.exists():
        try:
            marker_matches = (
                marker_path.read_text(encoding="utf-8").strip() == fingerprint
            )
        except OSError:
            marker_matches = False
        if marker_matches:
            logger.info(
                "BUILD",
                "Skipping icon extraction: no icon was found in this "
                "installer previously",
            )
            return

    result = extract_icon_png(installer_file)
    if result.png is None:
        try:
            icons_dir.mkdir(parents=True, exist_ok=True)
            marker_path.write_text(fingerprint, encoding="utf-8")
        except OSError:
            pass
        logger.warning(
            "BUILD",
            f"No app icon extracted from {installer_file.name}: {result.detail}. "
            f"The Intune app entry will be created without a logo. Place a PNG "
            f"at {icon_path} or set intune.logo_path to provide an icon "
            f"manually.",
        )
        return

    try:
        icon_path.parent.mkdir(parents=True, exist_ok=True)
        icon_path.write_bytes(result.png)
        marker_path.unlink(missing_ok=True)
    except OSError as err:
        logger.warning("BUILD", f"Could not write app icon to {icon_path}: {err}")
        return
    logger.info("BUILD", f"Extracted app icon ({result.width}px): {icon_path}")
    logger.verbose("BUILD", f"Icon source: {result.detail}")