Skip to content

build

napt.build

PSADT package building for NAPT.

Builds PSAppDeployToolkit packages from recipes and downloaded installers: PSADT release management, script generation, file copying, and branding application.

Modules:

Name Description
manager

Package building orchestration (build_package).

installer

Finding the installer to build and reading it once.

layout

The versioned build folder, PSADT copy, installer copy, branding.

commands

Install/uninstall commands for MSI and MSIX installers.

template

Invoke-AppDeployToolkit.ps1 generation.

scripts

Detection and requirements scripts written beside a build.

manifest

The build manifest written by build and read by package and upload.

packager

.intunewin package creation (create_intunewin).

icons

Icon extraction from installers.

registry_scripts

Detection/requirements script generation (registry).

msix_scripts

Detection/requirements script generation (MSIX).

napt.build.manager

Build manager for PSADT package creation.

Sequences a build from a recipe and a downloaded installer. The steps live in the modules they belong to:

  • installer: the release to build, the installer file whose hash matches it, and what that file says about itself.
  • layout: the versioned build folder, the PSADT template and installer copied into it, and the brand pack.
  • commands: the install and uninstall commands for MSI and MSIX installers.
  • template: the generated Invoke-AppDeployToolkit.ps1.
  • scripts: the detection and requirements scripts.
  • manifest: the record left beside the build.
Design Principles
  • The release to build comes from deployment state; the installer is the file in that version's download folder whose SHA-256 matches
  • The installer is read once; every later step uses what was read
  • Entire PSADT Template_v4 structure copied unmodified
  • Invoke-AppDeployToolkit.ps1 is generated from template (not copied)
  • Build directories are versioned: {app_id}/{version}/
  • Branding applied by replacing files in root Assets/ directory (v4 structure)

BuildResult dataclass

Result from building a PSADT package.

Attributes:

Name Type Description
app_id str

Unique application identifier.

app_name str

Application display name.

version str

Application version.

build_dir Path

Path to the build directory (packagefiles subdirectory).

psadt_version str

PSADT version used for the build.

Source code in napt/build/manager.py
@dataclass(frozen=True)
class BuildResult:
    """Result from building a PSADT package.

    Attributes:
        app_id: Unique application identifier.
        app_name: Application display name.
        version: Application version.
        build_dir: Path to the build directory (packagefiles subdirectory).
        psadt_version: PSADT version used for the build.
    """

    app_id: str
    app_name: str
    version: str
    build_dir: Path
    psadt_version: str

build_package

build_package(
    recipe_path: Path,
    downloads_dir: Path | None = None,
    output_dir: Path | None = None,
    state_dir: Path | None = None,
) -> BuildResult

Builds a PSADT package from a recipe and downloaded installer.

This is the main entry point for the build process. It:

  1. Loads the recipe configuration
  2. Finds the downloaded installer of the recorded release
  3. Inspects the installer: confirms its version against its folder, reads its metadata once, resolves the detection name and architecture, and checks an EXE recipe's required fields, all before anything is written
  4. Gets/downloads PSADT release
  5. Creates the build directory, copies PSADT unmodified, generates Invoke-AppDeployToolkit.ps1 from the template, and copies the installer to Files/
  6. Applies custom branding
  7. Generates the detection script (used by the App and Update entries)
  8. Generates the requirements script (when build_types is "both" or "update_only")

Parameters:

Name Type Description Default
recipe_path Path

Path to the recipe YAML file.

required
downloads_dir Path | None

Directory containing the downloaded installer. Default: directories.discover from config.

None
output_dir Path | None

Base directory for build output. Default: directories.build from config.

None
state_dir Path | None

State root whose deployment/ subfolder holds the release to build. Default: directories.state from config.

None

Returns:

Type Description
BuildResult

Build result naming the app, the version, the packagefiles directory, and the PSADT version used.

Raises:

Type Description
ConfigError

If the recipe cannot be loaded or lacks a field the installer type needs, or a configured brand pack path does not exist.

PackagingError

If the installer is missing or does not match the recorded release, its metadata cannot be read, or a build step fails.

StateError

If the deployment state file is corrupted.

NetworkError

If the PSADT release cannot be downloaded.

Example

Basic build:

result = build_package(Path("recipes/Google/chrome.yaml"))
print(result.build_dir)
# builds/google-chrome/141.0.7390.123/packagefiles

Custom output directory:

result = build_package(
    Path("recipes/Google/chrome.yaml"),
    output_dir=Path("custom/builds")
)

Note

Requires installer to be downloaded first (run 'napt discover'). The version is the name of the download folder, checked against the installer's own version for MSI and MSIX. Overwrites existing build directory if it exists. PSADT files are copied unmodified from cache. Invoke-AppDeployToolkit.ps1 is generated (not copied). Scripts are generated as siblings to the packagefiles directory (not included in .intunewin package - must be uploaded separately to Intune). Detection script is always generated. The build_types setting controls requirements script only: "both" (default) generates detection and requirements, "app_only" generates only detection, "update_only" generates detection and requirements.

Source code in napt/build/manager.py
def build_package(
    recipe_path: Path,
    downloads_dir: Path | None = None,
    output_dir: Path | None = None,
    state_dir: Path | None = None,
) -> BuildResult:
    """Builds a PSADT package from a recipe and downloaded installer.

    This is the main entry point for the build process. It:

    1. Loads the recipe configuration
    2. Finds the downloaded installer of the recorded release
    3. Inspects the installer: confirms its version against its folder,
       reads its metadata once, resolves the detection name and
       architecture, and checks an EXE recipe's required fields, all before
       anything is written
    4. Gets/downloads PSADT release
    5. Creates the build directory, copies PSADT unmodified, generates
       Invoke-AppDeployToolkit.ps1 from the template, and copies the
       installer to Files/
    6. Applies custom branding
    7. Generates the detection script (used by the App and Update entries)
    8. Generates the requirements script (when build_types is "both" or
       "update_only")

    Args:
        recipe_path: Path to the recipe YAML file.
        downloads_dir: Directory containing the downloaded
            installer. Default: ``directories.discover`` from config.
        output_dir: Base directory for build output.
            Default: ``directories.build`` from config.
        state_dir: State root whose ``deployment/`` subfolder holds the
            release to build. Default: ``directories.state`` from config.

    Returns:
        Build result naming the app, the version, the packagefiles
            directory, and the PSADT version used.

    Raises:
        ConfigError: If the recipe cannot be loaded or lacks a field the
            installer type needs, or a configured brand pack path does not
            exist.
        PackagingError: If the installer is missing or does not match the
            recorded release, its metadata cannot be read, or a build step
            fails.
        StateError: If the deployment state file is corrupted.
        NetworkError: If the PSADT release cannot be downloaded.

    Example:
        Basic build:
            ```python
            result = build_package(Path("recipes/Google/chrome.yaml"))
            print(result.build_dir)
            # builds/google-chrome/141.0.7390.123/packagefiles
            ```

        Custom output directory:
            ```python
            result = build_package(
                Path("recipes/Google/chrome.yaml"),
                output_dir=Path("custom/builds")
            )
            ```

    Note:
        Requires installer to be downloaded first (run 'napt discover').
        The version is the name of the download folder, checked against
        the installer's own version for MSI and MSIX.
        Overwrites existing build directory if it exists.
        PSADT files are copied unmodified from cache.
        Invoke-AppDeployToolkit.ps1 is generated (not copied).
        Scripts are generated as siblings to the packagefiles directory
        (not included in .intunewin package - must be uploaded separately to Intune).
        Detection script is always generated.
        The build_types setting controls requirements script only: "both" (default)
        generates detection and requirements, "app_only" generates only detection,
        "update_only" generates detection and requirements.
    """
    logger = get_global_logger()

    logger.step(1, 8, "Loading configuration...")
    config = load_effective_config(recipe_path)
    app_id = config["id"]
    app_name = config["name"]
    if downloads_dir is None:
        downloads_dir = Path(config["directories"]["discover"])
    if output_dir is None:
        output_dir = Path(config["directories"]["build"])

    logger.step(2, 8, "Finding installer...")
    installer_file, installer_sha256 = find_installer_file(
        downloads_dir, app_id, release_to_build(config, state_dir)
    )

    logger.step(3, 8, "Inspecting installer...")
    installer = inspect_installer(installer_file, installer_sha256, config)
    logger.info("BUILD", f"Building {app_name} v{installer.version}")

    # Best-effort: a failed extraction warns and the build continues.
    ensure_app_icon(config, installer.path, app_id)

    logger.step(4, 8, "Getting PSADT release...")
    psadt_cache_dir = get_psadt_release(
        config["psadt"]["release"], Path(config["directories"]["cache"]) / "psadt"
    )
    psadt_version = psadt_cache_dir.name  # Directory name is the version
    logger.info("BUILD", f"Using PSADT {psadt_version}")

    logger.step(5, 8, "Creating build structure...")
    build_dir = create_build_directory(output_dir, app_id, installer.version)
    copy_psadt_template(psadt_cache_dir, build_dir)
    apply_install_commands(config, installer)
    invoke_script = generate_invoke_script(
        psadt_cache_dir / "Invoke-AppDeployToolkit.ps1",
        config,
        installer.version,
        psadt_version,
        installer.architecture,
        installer.path.name,
    )
    write_build_file(
        build_dir / "Invoke-AppDeployToolkit.ps1", invoke_script, PS_SCRIPT_ENCODING
    )
    logger.verbose("BUILD", "[OK] Generated Invoke-AppDeployToolkit.ps1")
    copy_installer(installer.path, build_dir)

    logger.step(6, 8, "Applying branding...")
    apply_branding(config, build_dir)

    build_types = config["intune"]["build_types"]

    logger.step(7, 8, "Generating detection script...")
    detection_script_path = write_detection_script(installer, config, build_dir)
    logger.verbose("BUILD", "[OK] Detection script generated")

    requirements_script_path: Path | None = None
    if build_types in ("both", "update_only"):
        logger.step(8, 8, "Generating requirements script...")
        requirements_script_path = write_requirements_script(
            installer, config, build_dir
        )
        logger.verbose("BUILD", "[OK] Requirements script generated")
    else:
        logger.step(8, 8, "Skipping requirements script (build_types=app_only)...")

    write_build_manifest(
        build_dir=build_dir,
        app_id=app_id,
        app_name=app_name,
        version=installer.version,
        build_types=build_types,
        architecture=installer.architecture,
        installer_sha256=installer.sha256,
        detection_script_path=detection_script_path,
        requirements_script_path=requirements_script_path,
    )

    logger.verbose("BUILD", f"[OK] Build complete: {build_dir}")

    return BuildResult(
        app_id=app_id,
        app_name=app_name,
        version=installer.version,
        build_dir=build_dir,
        psadt_version=psadt_version,
    )

napt.build.installer

The installer a build is made from: finding it and reading it once.

napt build resolves its installer in three steps that all live here: the release deployment state records, the file in that version's download folder whose hash matches, and what that file says about itself. The result is one InstallerInfo that the rest of the build reads instead of opening the installer again.

InstallerInfo dataclass

What the build knows about its installer after reading it once.

Attributes:

Name Type Description
path Path

The installer file under the downloads directory.

sha256 str

Its hex digest, the one recorded at discovery.

version str

The version being built, the name of the download folder.

app_name str

The display name the detection scripts look for: the MSI ProductName or MSIX DisplayName, or the recipe's intune.detection.display_name.

architecture ArchitectureMode

The registry view the scripts check, read from the installer for MSI and MSIX and from intune.detection.architecture for EXE.

msi MSIMetadata | None

The MSI metadata, for an MSI installer.

msix MSIXMetadata | None

The MSIX metadata, for an MSIX installer.

Source code in napt/build/installer.py
@dataclass(frozen=True)
class InstallerInfo:
    """What the build knows about its installer after reading it once.

    Attributes:
        path: The installer file under the downloads directory.
        sha256: Its hex digest, the one recorded at discovery.
        version: The version being built, the name of the download folder.
        app_name: The display name the detection scripts look for: the MSI
            ProductName or MSIX DisplayName, or the recipe's
            ``intune.detection.display_name``.
        architecture: The registry view the scripts check, read from the
            installer for MSI and MSIX and from
            ``intune.detection.architecture`` for EXE.
        msi: The MSI metadata, for an MSI installer.
        msix: The MSIX metadata, for an MSIX installer.
    """

    path: Path
    sha256: str
    version: str
    app_name: str
    architecture: ArchitectureMode
    msi: MSIMetadata | None = None
    msix: MSIXMetadata | None = None

    @property
    def kind(self) -> str:
        """The installer type as its lowercase suffix: ".msi", ".msix", or ".exe"."""
        return self.path.suffix.lower()

kind property

kind: str

The installer type as its lowercase suffix: ".msi", ".msix", or ".exe".

release_to_build

release_to_build(
    config: dict[str, Any], state_dir: Path | None = None
) -> dict[str, Any] | None

Reads the release to build from the app's deployment state.

That is the pending release (awaiting publication), or the published release when nothing is pending, which is the case when rebuilding the current version. Deployment state is committed alongside recipes, so this works on machines that never ran discover, such as a CI publish job restoring downloads from a cache.

Parameters:

Name Type Description Default
config dict[str, Any]

Recipe configuration.

required
state_dir Path | None

State root, or None for directories.state.

None

Returns:

Type Description
dict[str, Any] | None

The release entry (version, sha256, url), or None when no release is recorded.

Raises:

Type Description
StateError

If the deployment state file exists but is corrupted or has an unsupported schema version.

Source code in napt/build/installer.py
def release_to_build(
    config: dict[str, Any], state_dir: Path | None = None
) -> dict[str, Any] | None:
    """Reads the release to build from the app's deployment state.

    That is the pending release (awaiting publication), or the published
    release when nothing is pending, which is the case when rebuilding the
    current version. Deployment state is committed alongside recipes, so
    this works on machines that never ran discover, such as a CI publish
    job restoring downloads from a cache.

    Args:
        config: Recipe configuration.
        state_dir: State root, or None for ``directories.state``.

    Returns:
        The release entry (``version``, ``sha256``, ``url``), or None when
            no release is recorded.

    Raises:
        StateError: If the deployment state file exists but is corrupted
            or has an unsupported schema version.
    """
    if state_dir is None:
        state_dir = Path(config["directories"]["state"])
    return working_release(state_dir, config["id"])

find_installer_file

find_installer_file(
    downloads_dir: Path, app_id: str, release: dict[str, Any] | None
) -> tuple[Path, str]

Finds the installer to build and returns it with its SHA-256.

Discover saves each download to downloads/<id>/<version>/. With a recorded release, the installer is the file in that version's folder whose hash matches the recorded one, so a file that was swapped or corrupted since discovery is refused rather than packaged.

Without a recorded release (a stateless discover and no deployment state), there is nothing to match against, and the single installer found in one of the app's version folders is used.

Parameters:

Name Type Description Default
downloads_dir Path

Downloads directory to search.

required
app_id str

Recipe id.

required
release dict[str, Any] | None

The release to build (version and sha256), from release_to_build, or None when no release is recorded.

required

Returns:

Type Description
tuple[Path, str]

A tuple (installer_path, sha256), where installer_path is the installer file, sha256 is its hex digest.

Raises:

Type Description
StateError

If the recorded version is not a plain folder name.

PackagingError

If no file matches the recorded release, or, with no recorded release, if there is not exactly one installer.

Source code in napt/build/installer.py
def find_installer_file(
    downloads_dir: Path, app_id: str, release: dict[str, Any] | None
) -> tuple[Path, str]:
    """Finds the installer to build and returns it with its SHA-256.

    Discover saves each download to ``downloads/<id>/<version>/``. With a
    recorded release, the installer is the file in that version's folder
    whose hash matches the recorded one, so a file that was swapped or
    corrupted since discovery is refused rather than packaged.

    Without a recorded release (a stateless discover and no deployment
    state), there is nothing to match against, and the single installer
    found in one of the app's version folders is used.

    Args:
        downloads_dir: Downloads directory to search.
        app_id: Recipe id.
        release: The release to build (``version`` and ``sha256``), from
            [release_to_build][napt.build.installer.release_to_build], or
            None when no release is recorded.

    Returns:
        A tuple (installer_path, sha256), where
            installer_path is the installer file,
            sha256 is its hex digest.

    Raises:
        StateError: If the recorded version is not a plain folder name.
        PackagingError: If no file matches the recorded release, or, with
            no recorded release, if there is not exactly one installer.
    """
    logger = get_global_logger()
    app_dir = downloads_dir / app_id

    if release is not None:
        # State files are hand-editable and reviewed through pull requests, so
        # the recorded version is not trusted to stay inside the app's folder.
        if not is_safe_path_component(release["version"]):
            raise StateError(
                f"Deployment state for {app_id} records version "
                f"{release['version']!a}, which cannot be used as a folder name. "
                "Run 'napt discover' to record the release again."
            )
        version_dir = app_dir / release["version"]
        candidates = (
            [
                p
                for p in version_dir.iterdir()
                if p.is_file() and p.suffix.lower() in _INSTALLER_SUFFIXES
            ]
            if version_dir.is_dir()
            else []
        )
        for candidate in candidates:
            digest = sha256_file(candidate)
            if digest == release["sha256"]:
                logger.verbose("BUILD", f"Found installer: {candidate}")
                return candidate, digest
        raise PackagingError(
            f"No file in {version_dir} matches the recorded release of {app_id} "
            f"(version {release['version']}, sha256 {release['sha256']}). "
            f"Run 'napt discover' to download it."
        )

    # Only folders named like a version count. That skips ".incoming", where
    # an interrupted discover can leave a finished download behind.
    installers = sorted(
        p
        for p in app_dir.glob("*/*")
        if p.is_file()
        and p.suffix.lower() in _INSTALLER_SUFFIXES
        and is_safe_path_component(p.parent.name)
    )
    if len(installers) == 1:
        logger.verbose("BUILD", f"Found installer: {installers[0]}")
        return installers[0], sha256_file(installers[0])
    if not installers:
        raise PackagingError(
            f"No installer found for {app_id} under {app_dir}. "
            f"Run 'napt discover' first."
        )
    listing = ", ".join(str(p.relative_to(app_dir)) for p in installers)
    raise PackagingError(
        f"No release is recorded for {app_id}, and {app_dir} holds more than one "
        f"installer ({listing}). Run 'napt discover' without --stateless so "
        f"the release to build is recorded."
    )

inspect_installer

inspect_installer(
    installer_file: Path, sha256: str, config: dict[str, Any]
) -> InstallerInfo

Reads the installer once and resolves what the build needs from it.

The version is the name of the folder discover filed the installer in (downloads/<id>/<version>/). An MSI or MSIX reports its own version, architecture, and name, and discover names the folder after the version, so the two must agree: a file moved into the wrong folder by hand would otherwise be built and detected under a version it does not carry. An EXE carries no usable metadata, so its recipe must supply the display name, the architecture, and both install commands. Recipe fields the installer type makes no use of draw one warning each.

Parameters:

Name Type Description Default
installer_file Path

The installer found by find_installer_file.

required
sha256 str

Its hex digest.

required
config dict[str, Any]

Recipe configuration.

required

Returns:

Type Description
InstallerInfo

Everything later build steps read about the installer.

Raises:

Type Description
PackagingError

If the installer's metadata cannot be read, its version differs from its folder's name, or an MSI has no ProductName.

ConfigError

If an EXE recipe lacks intune.detection.display_name, intune.detection.architecture, or psadt.install and psadt.uninstall, or override_msi_display_name is set without a display_name.

Source code in napt/build/installer.py
def inspect_installer(
    installer_file: Path, sha256: str, config: dict[str, Any]
) -> InstallerInfo:
    """Reads the installer once and resolves what the build needs from it.

    The version is the name of the folder discover filed the installer in
    (``downloads/<id>/<version>/``). An MSI or MSIX reports its own version,
    architecture, and name, and discover names the folder after the
    version, so the two must agree: a file moved into the wrong folder by
    hand would otherwise be built and detected under a version it does not
    carry. An EXE carries no usable metadata, so its recipe must supply the
    display name, the architecture, and both install commands. Recipe
    fields the installer type makes no use of draw one warning each.

    Args:
        installer_file: The installer found by
            [find_installer_file][napt.build.installer.find_installer_file].
        sha256: Its hex digest.
        config: Recipe configuration.

    Returns:
        Everything later build steps read about the installer.

    Raises:
        PackagingError: If the installer's metadata cannot be read, its
            version differs from its folder's name, or an MSI has no
            ProductName.
        ConfigError: If an EXE recipe lacks ``intune.detection.display_name``,
            ``intune.detection.architecture``, or ``psadt.install`` and
            ``psadt.uninstall``, or ``override_msi_display_name`` is set
            without a ``display_name``.
    """
    logger = get_global_logger()
    version = installer_file.parent.name
    kind = installer_file.suffix.lower()
    detection = config["intune"]["detection"]

    msi: MSIMetadata | None = None
    msix: MSIXMetadata | None = None
    if kind == ".msi":
        logger.verbose("BUILD", f"Reading MSI metadata: {installer_file.name}")
        msi = extract_msi_metadata(installer_file)
        _check_version(installer_file, msi.product_version, version)
    elif kind == ".msix":
        logger.verbose("BUILD", f"Reading MSIX manifest: {installer_file.name}")
        msix = extract_msix_metadata(installer_file)
        _check_version(installer_file, msix.version, version)
    else:
        logger.verbose("BUILD", f"Using discovered version: {version}")

    _warn_ignored_fields(kind, detection)
    app_name, architecture = _resolve_app_info(kind, detection, version, msi, msix)
    if kind == ".exe":
        _require_exe_scripts(config)

    # The name is written into a comment line and the script filenames, where
    # a line break would end the comment or break the name.
    cleaned = strip_control_characters(app_name)
    if cleaned != app_name:
        logger.warning(
            "BUILD",
            f"App name {app_name!a} contains control characters; using "
            f"{cleaned!a} for scripts and filenames",
        )

    return InstallerInfo(
        path=installer_file,
        sha256=sha256,
        version=version,
        app_name=cleaned,
        architecture=architecture,
        msi=msi,
        msix=msix,
    )

napt.build.layout

The build folder and what goes into it.

Creates builds/<id>/<version>/packagefiles/, copies the PSADT template and the installer into it, applies the brand pack, and writes generated files with a failure reported by path.

write_build_file

write_build_file(path: Path, text: str, encoding: str) -> None

Writes a generated build file, reporting a refused write by path.

Parameters:

Name Type Description Default
path Path

Where to write.

required
text str

The file's content.

required
encoding str

Text encoding; generated scripts use PS_SCRIPT_ENCODING.

required

Raises:

Type Description
PackagingError

If the file cannot be written.

Source code in napt/build/layout.py
def write_build_file(path: Path, text: str, encoding: str) -> None:
    """Writes a generated build file, reporting a refused write by path.

    Args:
        path: Where to write.
        text: The file's content.
        encoding: Text encoding; generated scripts use
            ``PS_SCRIPT_ENCODING``.

    Raises:
        PackagingError: If the file cannot be written.
    """
    try:
        path.write_text(text, encoding=encoding)
    except OSError as err:
        raise PackagingError(f"Cannot write {path}: {err}") from err

create_build_directory

create_build_directory(base_dir: Path, app_id: str, version: str) -> Path

Creates the build directory structure.

Creates {base_dir}/{app_id}/{version}/packagefiles/, replacing an existing build of that version. The packagefiles/ subdirectory holds the PSADT files that are packaged into the .intunewin file; detection scripts are saved as its siblings so they stay out of the package.

Parameters:

Name Type Description Default
base_dir Path

Base builds directory.

required
app_id str

Application ID.

required
version str

Application version.

required

Returns:

Type Description
Path

Path to the packagefiles subdirectory where PSADT files will be copied (build_dir/packagefiles/).

Raises:

Type Description
PackagingError

If the version cannot be used as a folder name, or the directory cannot be created.

Source code in napt/build/layout.py
def create_build_directory(base_dir: Path, app_id: str, version: str) -> Path:
    """Creates the build directory structure.

    Creates ``{base_dir}/{app_id}/{version}/packagefiles/``, replacing an
    existing build of that version. The packagefiles/ subdirectory holds
    the PSADT files that are packaged into the .intunewin file; detection
    scripts are saved as its siblings so they stay out of the package.

    Args:
        base_dir: Base builds directory.
        app_id: Application ID.
        version: Application version.

    Returns:
        Path to the packagefiles subdirectory where PSADT files will be copied
            (build_dir/packagefiles/).

    Raises:
        PackagingError: If the version cannot be used as a folder name, or
            the directory cannot be created.
    """
    logger = get_global_logger()
    # An existing build directory is deleted below, so whatever names it must
    # never be allowed to point that delete somewhere else.
    if not is_safe_path_component(version):
        raise PackagingError(
            f"Version {version!a} for {app_id} cannot be used as a folder name. "
            "Versions may contain only letters, digits, '.', '-', '_', and '+'."
        )
    version_dir = base_dir / app_id / version
    packagefiles_dir = version_dir / "packagefiles"

    try:
        if version_dir.exists():
            logger.info("BUILD", f"Replacing the earlier build of {version}")
            shutil.rmtree(version_dir)
        packagefiles_dir.mkdir(parents=True, exist_ok=True)
    except OSError as err:
        raise PackagingError(
            f"Cannot create build directory {packagefiles_dir}: {err}"
        ) from err

    logger.verbose("BUILD", f"Created build directory: {packagefiles_dir}")
    return packagefiles_dir

copy_psadt_template

copy_psadt_template(psadt_cache_dir: Path, build_dir: Path) -> None

Copies the PSADT template from the cache into the build unmodified.

Copies the entire v4 template structure: PSAppDeployToolkit/ (module), Invoke-AppDeployToolkit.exe, Invoke-AppDeployToolkit.ps1 (the template, overwritten by the generated script), Assets/, Config/, Strings/, Files/, SupportFiles/, and PSAppDeployToolkit.Extensions/.

Parameters:

Name Type Description Default
psadt_cache_dir Path

Path to cached PSADT version directory (root of Template_v4 extraction).

required
build_dir Path

Build directory (packagefiles subdirectory) where PSADT should be copied.

required

Raises:

Type Description
PackagingError

If PSADT cache directory or required files don't exist, or the copy fails.

Source code in napt/build/layout.py
def copy_psadt_template(psadt_cache_dir: Path, build_dir: Path) -> None:
    """Copies the PSADT template from the cache into the build unmodified.

    Copies the entire v4 template structure: PSAppDeployToolkit/ (module),
    Invoke-AppDeployToolkit.exe, Invoke-AppDeployToolkit.ps1 (the template,
    overwritten by the generated script), Assets/, Config/, Strings/,
    Files/, SupportFiles/, and PSAppDeployToolkit.Extensions/.

    Args:
        psadt_cache_dir: Path to cached PSADT version directory (root
            of Template_v4 extraction).
        build_dir: Build directory (packagefiles subdirectory) where PSADT
            should be copied.

    Raises:
        PackagingError: If PSADT cache directory or required files don't
            exist, or the copy fails.
    """
    logger = get_global_logger()
    if not psadt_cache_dir.exists():
        raise PackagingError(f"PSADT cache directory not found: {psadt_cache_dir}")

    logger.verbose("BUILD", f"Copying PSADT template from cache: {psadt_cache_dir}")

    try:
        for item in psadt_cache_dir.iterdir():
            dest = build_dir / item.name
            if item.is_dir():
                shutil.copytree(item, dest)
                logger.verbose("BUILD", f"  Copied directory: {item.name}/")
            else:
                shutil.copy2(item, dest)
                logger.verbose("BUILD", f"  Copied file: {item.name}")
    except OSError as err:
        raise PackagingError(
            f"Cannot copy the PSADT template into {build_dir}: {err}"
        ) from err

    logger.verbose("BUILD", "[OK] PSADT template copied")

copy_installer

copy_installer(installer_file: Path, build_dir: Path) -> None

Copies the installer to the build's Files/ directory.

Parameters:

Name Type Description Default
installer_file Path

Path to the installer file.

required
build_dir Path

Build directory (packagefiles subdirectory).

required

Raises:

Type Description
PackagingError

If the copy fails.

Source code in napt/build/layout.py
def copy_installer(installer_file: Path, build_dir: Path) -> None:
    """Copies the installer to the build's Files/ directory.

    Args:
        installer_file: Path to the installer file.
        build_dir: Build directory (packagefiles subdirectory).

    Raises:
        PackagingError: If the copy fails.
    """
    logger = get_global_logger()
    files_dir = build_dir / "Files"
    dest = files_dir / installer_file.name

    logger.verbose("BUILD", f"Copying installer: {installer_file.name}")

    try:
        shutil.copy2(installer_file, dest)
    except OSError as err:
        raise PackagingError(
            f"Cannot copy installer {installer_file.name} to {files_dir}: {err}"
        ) from err

    logger.verbose("BUILD", "[OK] Installer copied to Files/")

apply_branding

apply_branding(config: dict[str, Any], build_dir: Path) -> None

Replaces PSADT's default assets with the configured brand pack.

Each mapping copies the first file matching its source glob to its target under the build, keeping the source file's extension. A mapping whose glob matches nothing leaves the default asset in place.

Parameters:

Name Type Description Default
config dict[str, Any]

Merged configuration with brand_pack settings.

required
build_dir Path

Build directory (packagefiles subdirectory) containing PSAppDeployToolkit/.

required

Raises:

Type Description
ConfigError

If the configured brand_pack.path does not exist.

PackagingError

If a brand asset cannot be copied.

Source code in napt/build/layout.py
def apply_branding(config: dict[str, Any], build_dir: Path) -> None:
    """Replaces PSADT's default assets with the configured brand pack.

    Each mapping copies the first file matching its ``source`` glob to its
    ``target`` under the build, keeping the source file's extension. A
    mapping whose glob matches nothing leaves the default asset in place.

    Args:
        config: Merged configuration with brand_pack settings.
        build_dir: Build directory (packagefiles subdirectory) containing
            PSAppDeployToolkit/.

    Raises:
        ConfigError: If the configured ``brand_pack.path`` does not exist.
        PackagingError: If a brand asset cannot be copied.
    """
    logger = get_global_logger()
    brand_pack = config["psadt"]["brand_pack"]

    if not brand_pack["path"]:
        logger.verbose("BUILD", "No brand pack configured, using PSADT defaults")
        return

    brand_path = Path(brand_pack["path"])
    if not brand_path.is_dir():
        raise ConfigError(
            f"psadt.brand_pack.path {brand_path} does not exist. Fix the path "
            "or remove the brand pack to build with PSADT's default assets."
        )

    logger.verbose("BUILD", f"Applying branding from: {brand_path}")

    for mapping in brand_pack["mappings"]:
        source_pattern = mapping["source"]
        source_files = list(brand_path.glob(source_pattern))
        if not source_files:
            logger.verbose("BUILD", f"No files match pattern: {source_pattern}")
            continue

        # The target is written without an extension; the source's is kept.
        source_file = source_files[0]
        target = build_dir / mapping["target"]
        target_with_ext = Path(str(target) + source_file.suffix)

        try:
            target_with_ext.parent.mkdir(parents=True, exist_ok=True)
            shutil.copy2(source_file, target_with_ext)
        except OSError as err:
            raise PackagingError(
                f"Cannot copy brand asset {source_file.name} to "
                f"{target_with_ext}: {err}"
            ) from err
        logger.verbose("BUILD", f"  {source_file.name} -> {target_with_ext.name}")

    logger.verbose("BUILD", "[OK] Branding applied")

napt.build.commands

Install and uninstall commands for the generated deployment script.

MSI and MSIX installers carry enough metadata to generate both commands; the recipe's own psadt.install and psadt.uninstall are used only when the matching override flag is set. EXE recipes always supply their own, so there is nothing to generate for them.

apply_install_commands

apply_install_commands(
    config: dict[str, Any], installer: InstallerInfo
) -> None

Sets the install and uninstall commands the deployment script runs.

Parameters:

Name Type Description Default
config dict[str, Any]

Recipe configuration, mutated in place for MSI and MSIX.

required
installer InstallerInfo

The inspected installer.

required

Raises:

Type Description
ConfigError

If an override flag is set without a command to use.

PackagingError

If an MSI has no ProductName to uninstall by.

Source code in napt/build/commands.py
def apply_install_commands(config: dict[str, Any], installer: InstallerInfo) -> None:
    """Sets the install and uninstall commands the deployment script runs.

    Args:
        config: Recipe configuration, mutated in place for MSI and MSIX.
        installer: The inspected installer.

    Raises:
        ConfigError: If an override flag is set without a command to use.
        PackagingError: If an MSI has no ProductName to uninstall by.
    """
    if installer.kind == ".msi":
        assert installer.msi is not None  # set by inspect_installer
        _apply_msi_commands(config, installer.msi, installer.path)
    elif installer.kind == ".msix":
        assert installer.msix is not None  # set by inspect_installer
        _apply_msix_commands(config, installer.msix, installer.path)

napt.build.scripts

The detection and requirements scripts written beside a build.

Both scripts are named after the app and version and saved as siblings of the packagefiles/ folder, so they stay out of the .intunewin file and napt upload can send them to Intune separately. MSIX installers get the AppX package queries; MSI and EXE installers get the registry scripts.

sanitize_filename

sanitize_filename(name: str, app_id: str) -> str

Makes an app name safe to use in a Windows filename.

Spaces become hyphens, the characters Windows forbids (< > : " | ? * \ /) are dropped, runs of hyphens collapse, and leading or trailing hyphens and dots are trimmed. A name with nothing left falls back to the app id.

Parameters:

Name Type Description Default
name str

String to sanitize (e.g., "Google Chrome").

required
app_id str

Fallback when nothing usable is left.

required

Returns:

Type Description
str

Sanitized filename-safe string (e.g., "Google-Chrome").

Example

Basic sanitization:

sanitize_filename("Google Chrome", "google-chrome")  # "Google-Chrome"
sanitize_filename("Test<>App", "vendor-test")        # "TestApp"
sanitize_filename("  ", "vendor-app")                # "vendor-app"

Source code in napt/build/scripts.py
def sanitize_filename(name: str, app_id: str) -> str:
    r"""Makes an app name safe to use in a Windows filename.

    Spaces become hyphens, the characters Windows forbids (< > : " | ? * \ /)
    are dropped, runs of hyphens collapse, and leading or trailing hyphens
    and dots are trimmed. A name with nothing left falls back to the app id.

    Args:
        name: String to sanitize (e.g., "Google Chrome").
        app_id: Fallback when nothing usable is left.

    Returns:
        Sanitized filename-safe string (e.g., "Google-Chrome").

    Example:
        Basic sanitization:
            ```python
            sanitize_filename("Google Chrome", "google-chrome")  # "Google-Chrome"
            sanitize_filename("Test<>App", "vendor-test")        # "TestApp"
            sanitize_filename("  ", "vendor-app")                # "vendor-app"
            ```

    """
    sanitized = name.replace(" ", "-")
    for char in '<>:"|?*\\/':
        sanitized = sanitized.replace(char, "")
    sanitized = re.sub(r"-+", "-", sanitized).strip(".-")
    return sanitized or app_id

write_detection_script

write_detection_script(
    installer: InstallerInfo, config: dict[str, Any], build_dir: Path
) -> Path

Writes the detection script Intune runs to see whether the app is installed.

Parameters:

Name Type Description Default
installer InstallerInfo

The inspected installer.

required
config dict[str, Any]

Recipe configuration.

required
build_dir Path

Build directory (packagefiles subdirectory).

required

Returns:

Type Description
Path

Path to the generated detection script.

Raises:

Type Description
PackagingError

If the script cannot be written.

Source code in napt/build/scripts.py
def write_detection_script(
    installer: InstallerInfo, config: dict[str, Any], build_dir: Path
) -> Path:
    """Writes the detection script Intune runs to see whether the app is installed.

    Args:
        installer: The inspected installer.
        config: Recipe configuration.
        build_dir: Build directory (packagefiles subdirectory).

    Returns:
        Path to the generated detection script.

    Raises:
        PackagingError: If the script cannot be written.
    """
    return _write_script("Detection", installer, config, build_dir)

write_requirements_script

write_requirements_script(
    installer: InstallerInfo, config: dict[str, Any], build_dir: Path
) -> Path

Writes the requirements script that scopes the update entry to older installs.

Parameters:

Name Type Description Default
installer InstallerInfo

The inspected installer.

required
config dict[str, Any]

Recipe configuration.

required
build_dir Path

Build directory (packagefiles subdirectory).

required

Returns:

Type Description
Path

Path to the generated requirements script.

Raises:

Type Description
PackagingError

If the script cannot be written.

Source code in napt/build/scripts.py
def write_requirements_script(
    installer: InstallerInfo, config: dict[str, Any], build_dir: Path
) -> Path:
    """Writes the requirements script that scopes the update entry to older installs.

    Args:
        installer: The inspected installer.
        config: Recipe configuration.
        build_dir: Build directory (packagefiles subdirectory).

    Returns:
        Path to the generated requirements script.

    Raises:
        PackagingError: If the script cannot be written.
    """
    return _write_script("Requirements", installer, config, build_dir)

napt.build.manifest

The build manifest: what a build records about itself for later stages.

napt build writes build-manifest.json beside packagefiles/. napt package reads it to verify the build and copies it into the package folder with the .intunewin name and hash added; napt upload reads that copy. The key names live here so every stage spells them the same way.

write_build_manifest

write_build_manifest(
    build_dir: Path,
    app_id: str,
    app_name: str,
    version: str,
    build_types: str,
    architecture: str,
    installer_sha256: str,
    detection_script_path: Path,
    requirements_script_path: Path | None,
) -> Path

Writes the build manifest beside the packagefiles folder.

Parameters:

Name Type Description Default
build_dir Path

Build directory (packagefiles subdirectory).

required
app_id str

Application ID.

required
app_name str

Application display name.

required
version str

Application version.

required
build_types str

The build_types setting used ("both", "app_only", "update_only").

required
architecture str

Resolved installer architecture ("x86", "x64", "arm64", "any"): from the installer for MSI and MSIX, from the recipe for EXE.

required
installer_sha256 str

SHA-256 hex digest of the source installer file, carried through so 'napt upload' can verify provenance.

required
detection_script_path Path

The detection script.

required
requirements_script_path Path | None

The requirements script, or None when build_types is "app_only".

required

Returns:

Type Description
Path

Path to the written manifest.

Raises:

Type Description
PackagingError

If the manifest cannot be written.

Source code in napt/build/manifest.py
def write_build_manifest(
    build_dir: Path,
    app_id: str,
    app_name: str,
    version: str,
    build_types: str,
    architecture: str,
    installer_sha256: str,
    detection_script_path: Path,
    requirements_script_path: Path | None,
) -> Path:
    """Writes the build manifest beside the packagefiles folder.

    Args:
        build_dir: Build directory (packagefiles subdirectory).
        app_id: Application ID.
        app_name: Application display name.
        version: Application version.
        build_types: The build_types setting used ("both", "app_only",
            "update_only").
        architecture: Resolved installer architecture ("x86", "x64",
            "arm64", "any"): from the installer for MSI and MSIX, from the
            recipe for EXE.
        installer_sha256: SHA-256 hex digest of the source installer file,
            carried through so 'napt upload' can verify provenance.
        detection_script_path: The detection script.
        requirements_script_path: The requirements script, or None when
            build_types is "app_only".

    Returns:
        Path to the written manifest.

    Raises:
        PackagingError: If the manifest cannot be written.
    """
    manifest: dict[str, Any] = {
        "app_id": app_id,
        "app_name": app_name,
        "version": version,
        "win32_build_types": build_types,
        "architecture": architecture,
        "installer_sha256": installer_sha256,
        # Script names only, so the manifest stays valid wherever the build
        # folder is moved to.
        "detection_script_path": detection_script_path.name,
    }
    if requirements_script_path is not None:
        manifest["requirements_script_path"] = requirements_script_path.name

    manifest_path = build_dir.parent / MANIFEST_NAME
    try:
        write_text_atomic(manifest_path, json.dumps(manifest, indent=2) + "\n")
    except OSError as err:
        raise PackagingError(f"Cannot write {manifest_path}: {err}") from err
    get_global_logger().verbose("BUILD", f"Build manifest written to: {manifest_path}")
    return manifest_path

read_build_manifest

read_build_manifest(
    directory: Path, required: tuple[str, ...], remedy: str
) -> dict[str, Any]

Reads a build manifest and checks the keys the caller relies on.

Parameters:

Name Type Description Default
directory Path

The folder holding build-manifest.json: the build's version directory, or the package directory it was copied to.

required
required tuple[str, ...]

Keys that must be present as non-empty strings.

required
remedy str

What to run to get a good manifest, appended to every error message.

required

Returns:

Type Description
dict[str, Any]

The parsed manifest.

Raises:

Type Description
PackagingError

If the manifest is missing, not JSON, not an object, or lacks a required key.

Source code in napt/build/manifest.py
def read_build_manifest(
    directory: Path, required: tuple[str, ...], remedy: str
) -> dict[str, Any]:
    """Reads a build manifest and checks the keys the caller relies on.

    Args:
        directory: The folder holding ``build-manifest.json``: the build's
            version directory, or the package directory it was copied to.
        required: Keys that must be present as non-empty strings.
        remedy: What to run to get a good manifest, appended to every
            error message.

    Returns:
        The parsed manifest.

    Raises:
        PackagingError: If the manifest is missing, not JSON, not an
            object, or lacks a required key.
    """
    manifest_path = directory / MANIFEST_NAME
    if not manifest_path.is_file():
        raise PackagingError(f"Build manifest not found: {manifest_path}. {remedy}")
    try:
        manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
    except (OSError, ValueError) as err:
        raise PackagingError(
            f"Cannot read {MANIFEST_NAME} in {directory}: {err}. {remedy}"
        ) from err
    if not isinstance(manifest, dict):
        raise PackagingError(
            f"{MANIFEST_NAME} in {directory} is not a JSON object. {remedy}"
        )
    for key in required:
        if not isinstance(manifest.get(key), str) or not manifest[key]:
            raise PackagingError(
                f"{MANIFEST_NAME} in {directory} has no {key}. {remedy}"
            )
    return manifest