Skip to content

cli

napt.cli

Command-line interface for NAPT.

Commands:

init: Initialize a new NAPT project
validate: Validate recipe syntax and configuration
discover: Discover latest version and download installer
build: Build PSADT package from recipe
package: Create .intunewin package for Intune (recipe-based)
upload: Upload .intunewin package to Microsoft Intune
auth: Sign in to Microsoft Graph and inspect credentials
promote: Plan and apply deployment ring promotion
status: Show deployment state across all apps

Each command lives in its own module named after it (napt/cli/validate.py owns napt validate), holding the command's cmd_* handlers and a register(subparsers) hook that adds its parser. napt/cli/common.py holds what every command shares: the output flags, the logger setup, and the one error wrapper. napt/cli/main.py assembles the top-level parser, calls each command's register, and dispatches to the selected handler through that wrapper.

A command module imports the subsystem it drives inside its handler, not at the top of the module, so building the parser for napt --help or napt validate never loads the Azure or HTTP libraries.

Exit Codes:

  • 0: Success
  • 1: Error (configuration, download, or validation failure)
  • 2: Usage error (unknown flag, missing argument)
  • 130: Interrupted with Ctrl-C
Note

The CLI uses argparse for command parsing (stdlib, zero dependencies). Verbose mode shows full tracebacks on errors for debugging. Debug mode implies verbose mode and shows detailed configuration dumps.

napt.cli.main

CLI entry point: parser assembly and dispatch.

Builds the top-level napt argument parser, calls each command module's register hook to add its subparser, and dispatches to the selected command's handler. Registered as the napt console script in pyproject.toml.

build_parser

build_parser() -> argparse.ArgumentParser

Assembles the top-level parser with every command registered.

Returns:

Type Description
ArgumentParser

The parser; parsing sets func to the selected handler.

Source code in napt/cli/main.py
def build_parser() -> argparse.ArgumentParser:
    """Assembles the top-level parser with every command registered.

    Returns:
        The parser; parsing sets ``func`` to the selected handler.
    """
    parser = argparse.ArgumentParser(
        prog="napt",
        description="NAPT - Not a Pkg Tool for Windows/Intune packaging with PSADT",
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )

    parser.add_argument(
        "--version",
        action="version",
        version=f"napt {get_version()}",
    )

    subparsers = parser.add_subparsers(
        dest="command",
        help="Available commands",
        required=True,
    )

    validate.register(subparsers)
    discover.register(subparsers)
    build.register(subparsers)
    package.register(subparsers)
    init.register(subparsers)
    upload.register(subparsers)
    auth.register(subparsers)
    promote.register(subparsers)
    status.register(subparsers)
    upstream.register(subparsers)
    return parser

main

main(argv: list[str] | None = None) -> None

Main entry point for the napt CLI.

This function is registered as the 'napt' console script in pyproject.toml.

Parameters:

Name Type Description Default
argv list[str] | None

Arguments to parse instead of the process's own.

None
Source code in napt/cli/main.py
def main(argv: list[str] | None = None) -> None:
    """Main entry point for the napt CLI.

    This function is registered as the 'napt' console script in pyproject.toml.

    Args:
        argv: Arguments to parse instead of the process's own.
    """
    args = build_parser().parse_args(argv)
    setup_logging(args)
    sys.exit(run_handler(args.func, args))

napt.cli.common

What every napt command shares: flags, logger setup, errors, results.

A command module's register adds the shared flags with add_output_flags and add_state_dir; napt/cli/main.py calls setup_logging once and runs the selected handler through run_handler, so a handler raises NAPT errors instead of catching them. A handler prints its result through print_results, supplying the title, the rows, and the success line.

EXIT_INTERRUPTED module-attribute

EXIT_INTERRUPTED = 130

Exit code for a run stopped with Ctrl-C: 128 plus SIGINT's signal number.

add_output_flags

add_output_flags(parser: ArgumentParser) -> None

Adds the -v/--verbose and -d/--debug flags to a command's parser.

Parameters:

Name Type Description Default
parser ArgumentParser

The command's (or subcommand's) parser.

required
Source code in napt/cli/common.py
def add_output_flags(parser: argparse.ArgumentParser) -> None:
    """Adds the -v/--verbose and -d/--debug flags to a command's parser.

    Args:
        parser: The command's (or subcommand's) parser.
    """
    parser.add_argument(
        "-v",
        "--verbose",
        action="store_true",
        help="Show progress and high-level status updates",
    )
    parser.add_argument(
        "-d",
        "--debug",
        action="store_true",
        help="Show detailed debugging output (implies --verbose)",
    )

add_state_dir

add_state_dir(parser: ArgumentParser, help_text: str) -> None

Adds the --state-dir override to a command's parser.

The flag is a path that defaults to None, which every command reads as "use directories.state from configuration".

Parameters:

Name Type Description Default
parser ArgumentParser

The command's (or subcommand's) parser.

required
help_text str

What the command does with the directory.

required
Source code in napt/cli/common.py
def add_state_dir(parser: argparse.ArgumentParser, help_text: str) -> None:
    """Adds the --state-dir override to a command's parser.

    The flag is a path that defaults to None, which every command reads as
    "use ``directories.state`` from configuration".

    Args:
        parser: The command's (or subcommand's) parser.
        help_text: What the command does with the directory.
    """
    parser.add_argument(
        "--state-dir",
        type=Path,
        default=None,
        help=help_text,
    )

setup_logging

setup_logging(args: Namespace) -> Logger

Configures the global logger from the parsed output flags.

Parameters:

Name Type Description Default
args Namespace

Parsed command-line arguments carrying verbose and debug.

required

Returns:

Type Description
Logger

The logger now installed as the global logger.

Source code in napt/cli/common.py
def setup_logging(args: argparse.Namespace) -> Logger:
    """Configures the global logger from the parsed output flags.

    Args:
        args: Parsed command-line arguments carrying ``verbose`` and
            ``debug``.

    Returns:
        The logger now installed as the global logger.
    """
    logger = get_logger(verbose=args.verbose, debug=args.debug)
    set_global_logger(logger)
    return logger

print_results

print_results(
    title: str,
    rows: Iterable[tuple[str, object]],
    success: str,
    *,
    failure: str | None = None
) -> None

Prints a command's results block.

The block is a banner, the title, one aligned Label: value line per row, a closing banner, a blank line, and the success line. Labels pad to the longest label in the block. A row whose value is None is left out, so an optional field needs no branch in the handler. A command that finished with partial results and will exit non-zero passes failure and the block ends with [FAIL] instead.

Parameters:

Name Type Description Default
title str

Heading for the block (e.g., "BUILD RESULTS").

required
rows Iterable[tuple[str, object]]

Label and value pairs in display order.

required
success str

What was accomplished, printed after [SUCCESS].

required
failure str | None

What went wrong, printed after [FAIL] in place of the success line.

None
Source code in napt/cli/common.py
def print_results(
    title: str,
    rows: Iterable[tuple[str, object]],
    success: str,
    *,
    failure: str | None = None,
) -> None:
    """Prints a command's results block.

    The block is a banner, the title, one aligned ``Label: value`` line per
    row, a closing banner, a blank line, and the success line. Labels pad to
    the longest label in the block. A row whose value is None is left out,
    so an optional field needs no branch in the handler. A command that
    finished with partial results and will exit non-zero passes ``failure``
    and the block ends with ``[FAIL]`` instead.

    Args:
        title: Heading for the block (e.g., "BUILD RESULTS").
        rows: Label and value pairs in display order.
        success: What was accomplished, printed after ``[SUCCESS]``.
        failure: What went wrong, printed after ``[FAIL]`` in place of the
            success line.
    """
    shown = [(label, value) for label, value in rows if value is not None]
    width = max((len(label) for label, _ in shown), default=0) + 1
    banner = "=" * 70
    print(banner)
    print(title)
    print(banner)
    for label, value in shown:
        print(f"{label + ':':<{width}} {value}")
    print(banner)
    print()
    if failure is not None:
        print(f"[FAIL] {failure}")
    else:
        print(f"[SUCCESS] {success}")

run_handler

run_handler(handler: Callable[[Namespace], int], args: Namespace) -> int

Runs a command handler, reporting failures the same way for every command.

A NAPT error or an OS error becomes one line on stdout (with the traceback on stderr under -v or -d) and exit code 1; the label names authentication failures. Ctrl-C ends the run with exit code 130 and no traceback. Anything else is a bug and propagates.

Parameters:

Name Type Description Default
handler Callable[[Namespace], int]

The command's cmd_* function.

required
args Namespace

Parsed command-line arguments to hand to it.

required

Returns:

Type Description
int

The process exit code.

Source code in napt/cli/common.py
def run_handler(
    handler: Callable[[argparse.Namespace], int], args: argparse.Namespace
) -> int:
    """Runs a command handler, reporting failures the same way for every command.

    A NAPT error or an OS error becomes one line on stdout (with the
    traceback on stderr under -v or -d) and exit code 1; the label names
    authentication failures. Ctrl-C ends the run with exit code 130 and no
    traceback. Anything else is a bug and propagates.

    Args:
        handler: The command's ``cmd_*`` function.
        args: Parsed command-line arguments to hand to it.

    Returns:
        The process exit code.
    """
    try:
        return handler(args)
    except KeyboardInterrupt:
        print()
        print("Interrupted.")
        return EXIT_INTERRUPTED
    except (NAPTError, OSError) as err:
        label = "Authentication error" if isinstance(err, AuthError) else "Error"
        print(f"{label}: {err}")
        if args.verbose or args.debug:
            traceback.print_exc()
        return 1

napt.cli.auth

The napt auth command.

Manages the credential NAPT uses for Intune through the login, logout, status, and setup subcommands.

cmd_auth_login

cmd_auth_login(args: Namespace) -> int

Handler for 'napt auth login' command.

Signs in interactively through the OS broker or the browser and caches the session so later commands authenticate silently.

Parameters:

Name Type Description Default
args Namespace

Parsed command-line arguments containing optional client and tenant IDs and the --no-broker flag.

required

Returns:

Type Description
int

Exit code (0 for success).

Note

Failures raise NAPT errors for run_handler to report.

Source code in napt/cli/auth.py
def cmd_auth_login(args: argparse.Namespace) -> int:
    """Handler for 'napt auth login' command.

    Signs in interactively through the OS broker or the browser and caches
    the session so later commands authenticate silently.

    Args:
        args: Parsed command-line arguments containing optional client and
            tenant IDs and the --no-broker flag.

    Returns:
        Exit code (0 for success).

    Note:
        Failures raise NAPT errors for
        [run_handler][napt.cli.common.run_handler] to report.

    """
    from napt.auth.credentials import login

    status = login(
        client_id=args.client_id,
        tenant_id=args.tenant_id,
        use_broker=not args.no_broker,
    )

    print()
    print(f"[OK] Signed in as {status.account or '(unknown account)'}")
    print()
    _print_auth_status(status)
    return 0

cmd_auth_logout

cmd_auth_logout(args: Namespace) -> int

Handler for 'napt auth logout' command.

Removes the active tenant's cached session, or every tenant's with --all. Client and tenant IDs are kept for the next login.

Parameters:

Name Type Description Default
args Namespace

Parsed command-line arguments containing the --all flag and debug flags.

required

Returns:

Type Description
int

Exit code (0 for success).

Note

Failures raise NAPT errors for run_handler to report.

Source code in napt/cli/auth.py
def cmd_auth_logout(args: argparse.Namespace) -> int:
    """Handler for 'napt auth logout' command.

    Removes the active tenant's cached session, or every tenant's with
    --all. Client and tenant IDs are kept for the next login.

    Args:
        args: Parsed command-line arguments containing the --all flag and
            debug flags.

    Returns:
        Exit code (0 for success).

    Note:
        Failures raise NAPT errors for
        [run_handler][napt.cli.common.run_handler] to report.

    """
    from napt.auth.credentials import logout

    removed = logout(all_tenants=args.all)

    if removed:
        print(
            f"[OK] Signed out of {len(removed)} tenant(s): {', '.join(removed)}. "
            "Run 'napt auth login' to sign in again."
        )
    else:
        print("No interactive session to sign out of.")
    return 0

cmd_auth_status

cmd_auth_status(args: Namespace) -> int

Handler for 'napt auth status' command.

Shows which credential NAPT would use right now (the same resolution 'napt upload' performs) and flags missing Graph permissions.

Parameters:

Name Type Description Default
args Namespace

Parsed command-line arguments containing debug flags.

required

Returns:

Type Description
int

Exit code (0 when a credential is available, 1 otherwise).

Note

Failures raise NAPT errors for run_handler to report.

Source code in napt/cli/auth.py
def cmd_auth_status(args: argparse.Namespace) -> int:
    """Handler for 'napt auth status' command.

    Shows which credential NAPT would use right now (the same resolution
    'napt upload' performs) and flags missing Graph permissions.

    Args:
        args: Parsed command-line arguments containing debug flags.

    Returns:
        Exit code (0 when a credential is available, 1 otherwise).

    Note:
        Failures raise NAPT errors for
        [run_handler][napt.cli.common.run_handler] to report.

    """
    from napt.auth.credentials import get_status

    status = get_status()

    if status is None:
        print("Not authenticated.")
        print()
        print("  Interactive:  run 'napt auth login'")
        print("  CI/CD:        set AZURE_CLIENT_ID, AZURE_TENANT_ID and either")
        print("                AZURE_CLIENT_SECRET / AZURE_CLIENT_CERTIFICATE_PATH,")
        print("                or sign in with 'az login' (e.g. azure/login in CI)")
        _print_known_tenants()
        return 1

    _print_auth_status(status)
    if status.method.startswith("interactive"):
        _print_known_tenants()
    return 0 if not status.missing else 1

cmd_auth_setup

cmd_auth_setup(args: Namespace) -> int

Handler for 'napt auth setup' command.

Creates or completes the NAPT app registration in a tenant through Microsoft Graph, or with --print-only prints the equivalent portal checklist without signing in.

Parameters:

Name Type Description Default
args Namespace

Parsed command-line arguments containing the tenant ID, optional name, client ID, federated credential settings, and flags.

required

Returns:

Type Description
int

Exit code (0 for success, 1 when an existing registration needs

int

--adopt).

Note

Failures raise NAPT errors for run_handler to report.

Source code in napt/cli/auth.py
def cmd_auth_setup(args: argparse.Namespace) -> int:
    """Handler for 'napt auth setup' command.

    Creates or completes the NAPT app registration in a tenant through
    Microsoft Graph, or with --print-only prints the equivalent portal
    checklist without signing in.

    Args:
        args: Parsed command-line arguments containing the tenant ID,
            optional name, client ID, federated credential settings, and flags.

    Returns:
        Exit code (0 for success, 1 when an existing registration needs
        --adopt).

    Note:
        Failures raise NAPT errors for
        [run_handler][napt.cli.common.run_handler] to report.

    """
    from napt.auth.registration import SetupSpec, setup_app_registration

    spec = SetupSpec(
        tenant_id=args.tenant_id,
        display_name=args.name,
        client_id=args.client_id,
        federated_issuer=args.federated_issuer,
        federated_subject=args.federated_subject,
        federated_audience=args.federated_audience,
        federated_name=args.federated_name,
        adopt=args.adopt,
    )

    if args.print_only:
        _print_setup_checklist(spec)
        return 0

    result = setup_app_registration(spec)

    print()
    if result.needs_adopt:
        print(
            f"[WARNING] Found existing registration '{result.display_name}' "
            f"({result.client_id}) that NAPT did not create."
        )
        print("          Re-run with --adopt to manage it. Adopting adds NAPT's")
        print("          redirect URIs, Microsoft Graph permissions, and admin")
        print("          consent, and stamps the registration's internal notes;")
        print("          it never removes existing settings.")
        print(
            "          To create a new registration instead, re-run with "
            f"--name <a name other than '{result.display_name}'>."
        )
        return 1

    if result.adopted:
        print(
            f"[OK] Adopted '{result.display_name}' ({result.client_id}) -- "
            f"stamped as napt/v1 spec={SPEC_VERSION}. Changes made:"
        )
    elif result.changes:
        print("[OK] App registration is ready. Changes made:")
    else:
        print(
            f"[OK] App registration '{result.display_name}' is at spec "
            f"{SPEC_VERSION}; nothing to change."
        )
    for change in result.changes:
        print(f"  - {change}")
    print()
    print(f"Name:       {result.display_name}")
    print(f"Tenant ID:  {result.tenant_id}")
    print(f"Client ID:  {result.client_id}")
    print()
    print("Next steps:")
    print("  Interactive: napt auth login")
    print("  CI/CD:       set AZURE_TENANT_ID and AZURE_CLIENT_ID to the values above")
    if spec.federated_subject:
        print("               and let your CI platform's OIDC login mint the token")
        print("               (e.g. azure/login on GitHub Actions) -- no secret needed")
    else:
        print("               plus AZURE_CLIENT_SECRET, or re-run with")
        print("               --federated-issuer/--federated-subject to add an OIDC")
        print("               federated credential instead")
    return 0

register

register(subparsers: _SubParsersAction) -> None

Registers the 'auth' command parser and its subcommands.

Parameters:

Name Type Description Default
subparsers _SubParsersAction

The CLI's subparsers action to add the command to.

required
Source code in napt/cli/auth.py
def register(subparsers: argparse._SubParsersAction) -> None:
    """Registers the 'auth' command parser and its subcommands.

    Args:
        subparsers: The CLI's subparsers action to add the command to.
    """
    parser_auth = subparsers.add_parser(
        "auth",
        help="Sign in to Microsoft Graph and inspect credentials",
        description=(
            "Manage the credential NAPT uses for Intune.\n\n"
            "Examples:\n"
            "  napt auth setup --tenant-id <id>\n"
            "  napt auth login --tenant-id <id> --client-id <id>\n"
            "  napt auth login\n"
            "  napt auth status\n"
            "  napt auth logout\n\n"
            "See docs for app registration setup."
        ),
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    auth_sub = parser_auth.add_subparsers(
        dest="subcommand",
        help="Auth subcommands",
        required=True,
    )

    parser_auth_login = auth_sub.add_parser(
        "login",
        help="Sign in interactively (browser or OS broker)",
        description=(
            "Sign in interactively and cache the session so later commands\n"
            "authenticate silently. Uses the Windows broker (WAM) when\n"
            "available, otherwise the system browser.\n\n"
            "The tenant, client ID, and account are remembered after the first\n"
            "login. Pass --tenant-id to switch between signed-in tenants (no\n"
            "prompt when that tenant's session is still valid)."
        ),
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    parser_auth_login.add_argument(
        "--tenant-id",
        default=None,
        help=(
            "Directory (tenant) ID, or the default domain of a tenant you have "
            "signed in to before (defaults to the active tenant)"
        ),
    )
    parser_auth_login.add_argument(
        "--client-id",
        default=None,
        help=(
            "Application (client) ID of the NAPT app registration "
            "(needed the first time you sign in to a tenant)"
        ),
    )
    parser_auth_login.add_argument(
        "--no-broker",
        action="store_true",
        help="Use the browser even when the OS broker is available",
    )
    add_output_flags(parser_auth_login)
    parser_auth_login.set_defaults(func=cmd_auth_login)

    parser_auth_logout = auth_sub.add_parser(
        "logout",
        help="Remove the cached interactive session",
        description=(
            "Sign out of the active tenant's cached session (or every "
            "tenant's with --all)."
        ),
    )
    parser_auth_logout.add_argument(
        "--all",
        action="store_true",
        help="Sign out of every remembered tenant",
    )
    add_output_flags(parser_auth_logout)
    parser_auth_logout.set_defaults(func=cmd_auth_logout)

    parser_auth_status = auth_sub.add_parser(
        "status",
        help="Show which credential NAPT would use and its permissions",
        description=(
            "Show the credential NAPT would use right now (the same resolution\n"
            "'napt upload' performs), the account and tenant it belongs to, and\n"
            "the Graph permissions it carries. Exits 1 when no credential is\n"
            "available or a required permission is missing."
        ),
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    add_output_flags(parser_auth_status)
    parser_auth_status.set_defaults(func=cmd_auth_status)

    parser_auth_setup = auth_sub.add_parser(
        "setup",
        help="Create or complete the NAPT app registration in a tenant",
        description=(
            "Create the NAPT app registration in Microsoft Entra ID, or bring an\n"
            "existing one up to spec: redirect URIs, Microsoft Graph permissions\n"
            "(application and delegated), service principal, and admin consent.\n"
            "Optionally adds a federated credential so a CI/CD platform can obtain\n"
            "tokens through OIDC without a client secret.\n\n"
            "Requires an account holding at least the Application Administrator\n"
            "role. NAPT does not store that account or its tokens (your browser\n"
            "may keep its own sign-in). Re-running is safe: NAPT compares the\n"
            "registration with what this version needs and adds what is missing,\n"
            "never removing anything.\n\n"
            "Examples:\n"
            "  napt auth setup --tenant-id <id>\n"
            "  napt auth setup --tenant-id <id> \\\n"
            "      --federated-issuer https://token.actions.githubusercontent.com \\\n"
            "      --federated-subject repo:contoso/intune-apps:ref:refs/heads/main\n"
            "  napt auth setup --tenant-id <id> --print-only"
        ),
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    parser_auth_setup.add_argument(
        "--tenant-id",
        required=True,
        help="Directory (tenant) ID to provision in",
    )
    parser_auth_setup.add_argument(
        "--name",
        default="NAPT",
        help="Display name of the app registration to find or create (default: NAPT)",
    )
    parser_auth_setup.add_argument(
        "--client-id",
        default=None,
        help="Bring this existing registration up to spec instead of matching by name",
    )
    parser_auth_setup.add_argument(
        "--federated-issuer",
        default=None,
        metavar="URL",
        help=(
            "OIDC issuer of a CI platform to trust, e.g. "
            "https://token.actions.githubusercontent.com (requires --federated-subject)"
        ),
    )
    parser_auth_setup.add_argument(
        "--federated-subject",
        default=None,
        metavar="SUBJECT",
        help=(
            "Subject claim the platform presents for the trusted workflow, in the "
            "platform's format, e.g. repo:owner/name:ref:refs/heads/main"
        ),
    )
    parser_auth_setup.add_argument(
        "--federated-audience",
        default=FEDERATED_AUDIENCE_DEFAULT,
        metavar="AUDIENCE",
        help=f"Audience claim (default: {FEDERATED_AUDIENCE_DEFAULT})",
    )
    parser_auth_setup.add_argument(
        "--federated-name",
        default=None,
        metavar="NAME",
        help="Name of the federated credential (default: derived from the subject)",
    )
    parser_auth_setup.add_argument(
        "--adopt",
        action="store_true",
        help=(
            "Manage a registration matched by name that NAPT did not create "
            "(adds what is missing, never removes anything)"
        ),
    )
    parser_auth_setup.add_argument(
        "--print-only",
        action="store_true",
        help="Print the portal checklist instead of changing anything",
    )
    add_output_flags(parser_auth_setup)
    parser_auth_setup.set_defaults(func=cmd_auth_setup)

napt.cli.build

The napt build command.

Creates a PSADT deployment package from a recipe and a downloaded installer.

cmd_build

cmd_build(args: Namespace) -> int

Handler for 'napt build' command.

Builds a PSADT package from a recipe and downloaded installer. This command loads the recipe configuration, reads the release to build from deployment state, finds the installer by its recorded hash, checks an MSI or MSIX version against its folder, downloads/caches the specified PSADT release, creates build directory structure, copies PSADT files pristine from cache, generates Invoke-AppDeployToolkit.ps1 with recipe values, copies installer to Files/ directory, and applies custom branding.

Parameters:

Name Type Description Default
args Namespace

Parsed command-line arguments containing recipe path, downloads directory, output directory, and flags.

required

Returns:

Type Description
int

Exit code (0 for success).

Note

Creates build directory structure. Downloads PSADT release if not cached. Generates Invoke-AppDeployToolkit.ps1. Copies files to build directory. Prints progress and results to stdout. Failures raise NAPT errors for run_handler to report.

Source code in napt/cli/build.py
def cmd_build(args: argparse.Namespace) -> int:
    """Handler for 'napt build' command.

    Builds a PSADT package from a recipe and downloaded installer. This command
    loads the recipe configuration, reads the release to build from
    deployment state, finds the installer by its recorded hash, checks an MSI
    or MSIX version against its folder, downloads/caches the specified PSADT
    release, creates build directory structure, copies
    PSADT files pristine from cache, generates Invoke-AppDeployToolkit.ps1
    with recipe values, copies installer to Files/ directory, and applies
    custom branding.

    Args:
        args: Parsed command-line arguments containing
            recipe path, downloads directory, output directory, and flags.

    Returns:
        Exit code (0 for success).

    Note:
        Creates build directory structure. Downloads PSADT release if not cached.
        Generates Invoke-AppDeployToolkit.ps1. Copies files to build directory.
        Prints progress and results to stdout. Failures raise NAPT errors
        for [run_handler][napt.cli.common.run_handler] to report.

    """
    from napt.build.manager import build_package

    recipe_path = args.recipe.resolve()
    downloads_dir = args.downloads_dir.resolve() if args.downloads_dir else None
    output_dir = args.output_dir

    print(f"Building PSADT package for recipe: {recipe_path}")
    if downloads_dir:
        print(f"Downloads directory: {downloads_dir}")
    if output_dir:
        print(f"Output directory: {output_dir}")
    print()

    result = build_package(
        recipe_path,
        downloads_dir=downloads_dir,
        output_dir=output_dir,
        state_dir=args.state_dir,
    )

    print_results(
        "BUILD RESULTS",
        [
            ("App Name", result.app_name),
            ("App ID", result.app_id),
            ("Version", result.version),
            ("PSADT Version", result.psadt_version),
            ("Build Directory", result.build_dir),
        ],
        "PSADT package built successfully!",
    )
    return 0

register

register(subparsers: _SubParsersAction) -> None

Registers the 'build' command parser.

Parameters:

Name Type Description Default
subparsers _SubParsersAction

The CLI's subparsers action to add the command to.

required
Source code in napt/cli/build.py
def register(subparsers: argparse._SubParsersAction) -> None:
    """Registers the 'build' command parser.

    Args:
        subparsers: The CLI's subparsers action to add the command to.
    """
    parser_build = subparsers.add_parser(
        "build",
        help="Build PSADT package from recipe and installer",
        description=(
            "Create a PSADT deployment package from a recipe and "
            "downloaded installer.\n\n"
            "Examples:\n"
            "  napt build recipes/Google/chrome.yaml\n"
            "  napt build recipes/Google/chrome.yaml --verbose\n"
            "  napt build recipes/Google/chrome.yaml --output-dir ./builds\n\n"
            "See docs for more examples and workflows."
        ),
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    parser_build.add_argument(
        "recipe",
        type=Path,
        help="Path to the recipe YAML file",
    )
    parser_build.add_argument(
        "--downloads-dir",
        type=Path,
        default=None,
        help=(
            "Directory containing the downloaded installer "
            "(default: from config or ./downloads)"
        ),
    )
    parser_build.add_argument(
        "--output-dir",
        type=Path,
        default=None,
        help="Base directory for build output (default: from config or ./builds)",
    )
    add_state_dir(
        parser_build,
        "State root; the release to build is read from <dir>/deployment/ "
        "(default: directories.state, ./state)",
    )
    add_output_flags(parser_build)
    parser_build.set_defaults(func=cmd_build)

napt.cli.discover

The napt discover command.

Finds the latest version of an application with the configured discovery strategy and downloads the installer.

cmd_discover

cmd_discover(args: Namespace) -> int

Handler for 'napt discover' command.

Discovers the latest version of an application by querying the source and downloading the installer. This command validates the recipe YAML, uses the configured discovery strategy to find the latest version, downloads the installer (or reuses the one an earlier run downloaded), extracts version information, and records the release as a pending publication candidate in deployment state when it differs from the published version.

Parameters:

Name Type Description Default
args Namespace

Parsed command-line arguments containing recipe path, output directory, deployment state directory, and flags.

required

Returns:

Type Description
int

Exit code (0 for success).

Note

Downloads installer file to output_dir (or reuses an earlier download). Updates the app's deployment state file with the pending release. Prints progress and results to stdout. Failures raise NAPT errors for run_handler to report.

Source code in napt/cli/discover.py
def cmd_discover(args: argparse.Namespace) -> int:
    """Handler for 'napt discover' command.

    Discovers the latest version of an application by querying the source
    and downloading the installer. This command validates the recipe YAML,
    uses the configured discovery strategy to find the latest version,
    downloads the installer (or reuses the one an earlier run downloaded),
    extracts version information, and records the release as a pending
    publication candidate in deployment state when it differs from the
    published version.

    Args:
        args: Parsed command-line arguments containing
            recipe path, output directory, deployment state directory,
            and flags.

    Returns:
        Exit code (0 for success).

    Note:
        Downloads installer file to output_dir (or reuses an earlier
        download). Updates the app's deployment state file with the
        pending release. Prints progress and results to stdout. Failures
        raise NAPT errors for [run_handler][napt.cli.common.run_handler]
        to report.

    """
    from napt.discovery.manager import discover_recipe

    recipe_path = args.recipe.resolve()
    output_dir = args.output_dir.resolve() if args.output_dir else None

    print(f"Discovering version for recipe: {recipe_path}")
    if output_dir:
        print(f"Output directory: {output_dir}")
    print()

    result = discover_recipe(
        recipe_path,
        output_dir,
        state_dir=args.state_dir,
        stateless=args.stateless,
    )

    print_results(
        "DISCOVERY RESULTS",
        [
            ("App Name", result.app_name),
            ("App ID", result.app_id),
            ("Strategy", result.strategy),
            ("Version", result.version),
            ("Version Source", result.version_source),
            ("File Path", result.file_path),
            ("SHA-256", result.sha256),
        ],
        "Version discovered successfully!",
    )
    return 0

register

register(subparsers: _SubParsersAction) -> None

Registers the 'discover' command parser.

Parameters:

Name Type Description Default
subparsers _SubParsersAction

The CLI's subparsers action to add the command to.

required
Source code in napt/cli/discover.py
def register(subparsers: argparse._SubParsersAction) -> None:
    """Registers the 'discover' command parser.

    Args:
        subparsers: The CLI's subparsers action to add the command to.
    """
    parser_discover = subparsers.add_parser(
        "discover",
        help="Discover latest version and download installer",
        description=(
            "Find the latest version using the configured discovery strategy "
            "and download the installer.\n\n"
            "Examples:\n"
            "  napt discover recipes/Google/chrome.yaml\n"
            "  napt discover recipes/Google/chrome.yaml --verbose\n"
            "  napt discover recipes/Google/chrome.yaml --stateless\n\n"
            "See docs for more examples and workflows."
        ),
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    parser_discover.add_argument(
        "recipe",
        type=Path,
        help="Path to the recipe YAML file",
    )
    parser_discover.add_argument(
        "--output-dir",
        type=Path,
        default=None,
        help="Directory to save downloaded files (default: from config or ./downloads)",
    )
    add_state_dir(
        parser_discover,
        "State root; deployment state is written to <dir>/deployment/ "
        "(default: directories.state, ./state)",
    )
    parser_discover.add_argument(
        "--stateless",
        action="store_true",
        help="Do not read or write deployment state (no pending release is recorded)",
    )
    add_output_flags(parser_discover)
    parser_discover.set_defaults(func=cmd_discover)

napt.cli.init

The napt init command.

Creates a new NAPT project structure with default configuration.

cmd_init

cmd_init(args: Namespace) -> int

Handler for 'napt init' command.

Initializes a new NAPT project by creating the directory structure and default configuration files. This command creates the recipes/ directory, defaults/ directory with org.yaml template, defaults/vendors/ directory, and state/deployment/ directory for per-app deployment state.

Parameters:

Name Type Description Default
args Namespace

Parsed command-line arguments containing directory path, force flag, and debug flags.

required

Returns:

Type Description
int

Exit code (0 for success).

Note

By default, existing files are skipped (not overwritten). Use --force to backup existing files and create fresh ones. Failures raise NAPT errors for run_handler to report.

Source code in napt/cli/init.py
def cmd_init(args: argparse.Namespace) -> int:
    """Handler for 'napt init' command.

    Initializes a new NAPT project by creating the directory structure and
    default configuration files. This command creates the recipes/ directory,
    defaults/ directory with org.yaml template, defaults/vendors/ directory,
    and state/deployment/ directory for per-app deployment state.

    Args:
        args: Parsed command-line arguments containing
            directory path, force flag, and debug flags.

    Returns:
        Exit code (0 for success).

    Note:
        By default, existing files are skipped (not overwritten).
        Use --force to backup existing files and create fresh ones.
        Failures raise NAPT errors for
        [run_handler][napt.cli.common.run_handler] to report.

    """
    target_dir = args.directory.resolve()

    print(f"Initializing NAPT project in: {target_dir}")
    print()

    created, skipped, backed_up = _create_layout(target_dir, args.force)

    # Display results
    print()
    print("=" * 70)
    print("INITIALIZATION RESULTS")
    print("=" * 70)
    print(f"Project Root:    {target_dir}")
    print()

    if created:
        print(f"Created ({len(created)}):")
        for item in created:
            print(f"  [OK] {item}")
        print()

    if backed_up:
        print(f"Backed Up ({len(backed_up)}):")
        for item in backed_up:
            print(f"  [OK] {item}")
        print()

    if skipped:
        print(f"Skipped ({len(skipped)}):")
        for item in skipped:
            print(f"  [SKIP] {item}")
        print()

    print("=" * 70)
    print()

    if skipped and not args.force:
        print("Note: Existing files were preserved. Use --force to overwrite.")
        print()

    print("[SUCCESS] Project initialized!")
    return 0

register

register(subparsers: _SubParsersAction) -> None

Registers the 'init' command parser.

Parameters:

Name Type Description Default
subparsers _SubParsersAction

The CLI's subparsers action to add the command to.

required
Source code in napt/cli/init.py
def register(subparsers: argparse._SubParsersAction) -> None:
    """Registers the 'init' command parser.

    Args:
        subparsers: The CLI's subparsers action to add the command to.
    """
    parser_init = subparsers.add_parser(
        "init",
        help="Initialize a new NAPT project",
        description=(
            "Create a new NAPT project structure with default configuration.\n\n"
            "Creates:\n"
            "  - recipes/              Directory for recipe YAML files\n"
            "  - defaults/org.yaml     Organization defaults template\n"
            "  - defaults/vendors/     Directory for vendor-specific defaults\n"
            "  - state/deployment/     Per-app deployment state files\n\n"
            "Examples:\n"
            "  napt init\n"
            "  napt init ./my-project\n"
            "  napt init --force\n\n"
            "See docs for more examples and workflows."
        ),
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    parser_init.add_argument(
        "directory",
        nargs="?",
        type=Path,
        default=Path("."),
        help="Directory to initialize (default: current directory)",
    )
    parser_init.add_argument(
        "--force",
        action="store_true",
        help="Backup and overwrite existing configuration files",
    )
    add_output_flags(parser_init)
    parser_init.set_defaults(func=cmd_init)

napt.cli.package

The napt package command.

Packages a PSADT build into a .intunewin file for Intune deployment. The build to package is the one for the release deployment state records (pending, else published), the same release napt build built, so the command never has to guess among the builds on disk.

cmd_package

cmd_package(args: Namespace) -> int

Handler for 'napt package' command.

Creates a .intunewin package from a PSADT build for the given recipe. Packages the build of the release deployment state records, verifies it against the recorded installer hash, replaces that version's package folder, and copies the detection scripts alongside the .intunewin file so 'napt upload' is self-contained.

Parameters:

Name Type Description Default
args Namespace

Parsed command-line arguments containing recipe path, version, directories, and debug flags.

required

Returns:

Type Description
int

Exit code (0 for success).

Note

Run 'napt build' before 'napt package'. Downloads IntuneWinAppUtil.exe if not cached. Failures raise NAPT errors for run_handler to report.

Source code in napt/cli/package.py
def cmd_package(args: argparse.Namespace) -> int:
    """Handler for 'napt package' command.

    Creates a .intunewin package from a PSADT build for the given recipe.
    Packages the build of the release deployment state records, verifies
    it against the recorded installer hash, replaces that version's package
    folder, and copies the detection scripts alongside the .intunewin file
    so 'napt upload' is self-contained.

    Args:
        args: Parsed command-line arguments containing recipe path, version,
            directories, and debug flags.

    Returns:
        Exit code (0 for success).

    Note:
        Run 'napt build' before 'napt package'. Downloads IntuneWinAppUtil.exe
        if not cached. Failures raise NAPT errors for
        [run_handler][napt.cli.common.run_handler] to report.

    """
    from napt.build.packager import create_intunewin
    from napt.config.loader import load_effective_config

    recipe_path = args.recipe.resolve()
    builds_dir = args.builds_dir.resolve() if args.builds_dir else None
    state_dir = args.state_dir.resolve() if args.state_dir else None

    config = load_effective_config(recipe_path)
    build_dir, expected_sha256 = _resolve_build(
        config,
        version=args.version,
        builds_dir=builds_dir,
        state_dir=state_dir,
    )

    output_dir = (
        args.output_dir if args.output_dir else Path(config["directories"]["package"])
    )
    tool_release = config["intunewin"]["release"]

    print(f"Creating .intunewin package from: {build_dir}")
    print(f"Output directory: {output_dir}")
    print()

    result = create_intunewin(
        build_dir,
        cache_dir=Path(config["directories"]["cache"]),
        output_dir=output_dir,
        tool_release=tool_release,
        expected_sha256=expected_sha256,
    )

    print_results(
        "PACKAGE RESULTS",
        [
            ("App ID", result.app_id),
            ("Version", result.version),
            ("Package Path", result.package_path),
            ("Build Directory", result.build_dir),
        ],
        ".intunewin package created successfully!",
    )
    return 0

register

register(subparsers: _SubParsersAction) -> None

Registers the 'package' command parser.

Parameters:

Name Type Description Default
subparsers _SubParsersAction

The CLI's subparsers action to add the command to.

required
Source code in napt/cli/package.py
def register(subparsers: argparse._SubParsersAction) -> None:
    """Registers the 'package' command parser.

    Args:
        subparsers: The CLI's subparsers action to add the command to.
    """
    parser_package = subparsers.add_parser(
        "package",
        help="Create .intunewin package from a PSADT build",
        description=(
            "Package a PSADT build for a recipe into a .intunewin file for "
            "Intune deployment. Packages the build of the release recorded in "
            "deployment state (pending, else published); with no recorded "
            "release, the only build, or the one named by --version. The "
            "version's package folder is replaced; other versions are left "
            "alone.\n\n"
            "Examples:\n"
            "  napt package recipes/Google/chrome.yaml\n"
            "  napt package recipes/Google/chrome.yaml --version 130.0.6723.116\n"
            "  napt package recipes/Google/chrome.yaml --verbose\n\n"
            "See docs for more examples and workflows."
        ),
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    parser_package.add_argument(
        "recipe",
        type=Path,
        help="Path to the recipe YAML file",
    )
    parser_package.add_argument(
        "--version",
        default=None,
        metavar="VERSION",
        help="Build version to package (default: the recorded release)",
    )
    parser_package.add_argument(
        "--builds-dir",
        type=Path,
        default=None,
        help=(
            "Directory containing the PSADT build " "(default: from config or ./builds)"
        ),
    )
    parser_package.add_argument(
        "--output-dir",
        type=Path,
        default=None,
        help=(
            "Parent directory for package output "
            "(default: from config or ./packages)"
        ),
    )
    add_state_dir(
        parser_package,
        "State root whose deployment/ folder records the release "
        "(default: from config or ./state)",
    )
    add_output_flags(parser_package)
    parser_package.set_defaults(func=cmd_package)

napt.cli.promote

The napt promote command.

Plans and applies ring-based promotion of published apps through the plan and apply subcommands.

cmd_promote_plan

cmd_promote_plan(args: Namespace) -> int

Handler for 'napt promote plan' command.

Computes promotion actions for all recipes (or one recipe) as a pure function of deployment state, configuration, and the clock, and writes one plan file per app with work. Read-only with respect to Intune, and to deployment state unless --reconcile recovers a lost publication writeback first; an app's stale plan file is removed when none of its actions remain eligible.

Parameters:

Name Type Description Default
args Namespace

Parsed command-line arguments containing the recipes path, state directory, and flags.

required

Returns:

Type Description
int

Exit code (0 for success, with or without planned actions).

Note

Failures raise NAPT errors for run_handler to report.

Source code in napt/cli/promote.py
def cmd_promote_plan(args: argparse.Namespace) -> int:
    """Handler for 'napt promote plan' command.

    Computes promotion actions for all recipes (or one recipe) as a pure
    function of deployment state, configuration, and the clock, and
    writes one plan file per app with work. Read-only with respect to
    Intune, and to deployment state unless --reconcile recovers a lost
    publication writeback first; an app's stale plan file is removed when
    none of its actions remain eligible.

    Args:
        args: Parsed command-line arguments containing the recipes path,
            state directory, and flags.

    Returns:
        Exit code (0 for success, with or without planned actions).

    Note:
        Failures raise NAPT errors for
        [run_handler][napt.cli.common.run_handler] to report.

    """
    from napt.auth.credentials import get_access_token
    from napt.graph.intune import list_mobile_apps
    from napt.promote.drift import detect_drift
    from napt.promote.planner import (
        load_recipe_configs,
        plan_promotions,
        plans_dir_for,
        write_plan_files,
    )
    from napt.promote.preflight import unresolvable_groups
    from napt.promote.reconcile import reconcile_publications
    from napt.state.deployment import load_deployment_states

    logger = get_global_logger()
    recipes = args.recipes

    print(f"Planning promotions for: {recipes}")
    print()

    # Each recipe and each state file is read once; every step below
    # works from these two dicts.
    configs = load_recipe_configs(recipes)
    state_dir = _state_dir(args, configs)
    deployment_dir = state_dir / "deployment"
    states = load_deployment_states(deployment_dir, configs)
    recovered: list[dict[str, Any]] = []
    drift: list[dict[str, Any]] = []
    existing_apps: list[dict[str, Any]] = []
    group_id_cache: dict[str, str] = {}

    # One authenticated session serves reconciliation, plan validation, and
    # the drift check. Reconciliation runs before planning so recovered
    # releases are promotable this run; drift runs after it so repaired
    # state is compared.
    access_token = get_access_token() if args.reconcile or args.check_drift else None
    if access_token is not None:
        existing_apps = list_mobile_apps(access_token)
        if args.reconcile:
            recovered = reconcile_publications(
                access_token, configs, states, deployment_dir, existing_apps
            )

    actions = plan_promotions(configs, states)

    if access_token is None:
        if actions:
            logger.warning(
                "PROMOTE",
                "Plan groups not validated against Entra ID (offline "
                "run); apply validates them before assigning.",
            )
    else:
        # A plan with an unresolvable group must never become a
        # reviewable promotion PR: fail hard instead of writing it.
        problems = unresolvable_groups(access_token, actions, group_id_cache)
        if problems:
            raise ConfigError(
                "Plan validation failed; no plan was written. "
                "Unresolvable groups:\n  "
                + "\n  ".join(problems)
                + "\nFix the group configuration and re-run."
            )
        if args.check_drift:
            drift = detect_drift(
                access_token,
                configs,
                states,
                existing_apps,
                group_id_cache=group_id_cache,
                report_unknown_apps=recipes.is_dir(),
            )
    written = write_plan_files(actions, state_dir, configs)

    print("=" * 70)
    print("PROMOTION PLAN")
    print("=" * 70)
    if actions:
        for action in actions:
            print(f"  {_describe_action(action)}")
        print("=" * 70)
        print()
        print(
            f"[OK] Plan written: {len(written)} file(s) in "
            f"{plans_dir_for(state_dir)} ({len(actions)} action(s))"
        )
    else:
        print("  No promotions eligible.")
        print("=" * 70)
        print()
        print("[OK] Nothing to promote. No plan files needed.")

    if args.reconcile:
        _print_recovered(recovered)
    if args.check_drift:
        _print_drift(drift)

    return 0

cmd_promote_apply

cmd_promote_apply(args: Namespace) -> int

Handler for 'napt promote apply' command.

Executes promotion plans against Intune: assigns install entries, promotes releases through rings, displaces the older releases they replace, and retires them per the retention policy. Executes only the plan files written by napt promote plan, consuming each per-app file after its app applies fully; with no plan file there is nothing to apply. One app's failure keeps its plan file for retry and never blocks the others, and stale or already-applied actions are skipped with a warning, so re-running after a partial failure is safe.

Parameters:

Name Type Description Default
args Namespace

Parsed command-line arguments containing the recipes path, state directory, plan file, and flags.

required

Returns:

Type Description
int

Exit code (0 for success, including nothing to apply;

int

1 when any app's plan failed to apply).

Note

Failures raise NAPT errors for run_handler to report.

Source code in napt/cli/promote.py
def cmd_promote_apply(args: argparse.Namespace) -> int:
    """Handler for 'napt promote apply' command.

    Executes promotion plans against Intune: assigns install entries,
    promotes releases through rings, displaces the older releases they
    replace, and retires them per the retention policy. Executes only
    the plan files written by ``napt promote plan``, consuming each
    per-app file after its app applies fully; with no plan file there
    is nothing to apply. One app's failure keeps its plan file for
    retry and never blocks the others, and stale or already-applied
    actions are skipped with a warning, so re-running after a partial
    failure is safe.

    Args:
        args: Parsed command-line arguments containing the recipes path,
            state directory, plan file, and flags.

    Returns:
        Exit code (0 for success, including nothing to apply;
        1 when any app's plan failed to apply).

    Note:
        Failures raise NAPT errors for
        [run_handler][napt.cli.common.run_handler] to report.

    """
    from napt.promote.applier import apply_plan
    from napt.promote.planner import load_recipe_configs

    recipes = args.recipes

    print(f"Applying promotions for: {recipes}")
    print()

    configs = load_recipe_configs(recipes)
    summary = apply_plan(
        configs,
        state_dir=_state_dir(args, configs),
        plan_file=args.plan_file,
        report_unknown_apps=recipes.is_dir(),
    )

    applied = summary.applied
    skipped = summary.skipped
    failed = summary.failed

    print("=" * 70)
    print("PROMOTION APPLY")
    print("=" * 70)
    if not applied and not skipped and not failed:
        print("  Nothing to apply.")
    for action in applied:
        print(f"  [OK] {_describe_action(action)}")
    for entry in skipped:
        print(f"  [SKIP] {_describe_action(entry['action'])} ({entry['reason']})")
    for entry in failed:
        print(f"  [FAIL] {entry['app_id']}: {entry['error']}")
    print("=" * 70)

    if summary.recovered:
        _print_recovered(summary.recovered)
    if summary.drift:
        _print_drift(summary.drift)

    print()
    if failed:
        print(
            f"[FAIL] Applied {len(applied)} action(s), skipped "
            f"{len(skipped)}; {len(failed)} app(s) failed and kept "
            "their plan files. Fix the errors and re-run."
        )
        return 1
    print(f"[SUCCESS] Applied {len(applied)} action(s), " f"skipped {len(skipped)}.")

    return 0

register

register(subparsers: _SubParsersAction) -> None

Registers the 'promote' command parser and its subcommands.

Parameters:

Name Type Description Default
subparsers _SubParsersAction

The CLI's subparsers action to add the command to.

required
Source code in napt/cli/promote.py
def register(subparsers: argparse._SubParsersAction) -> None:
    """Registers the 'promote' command parser and its subcommands.

    Args:
        subparsers: The CLI's subparsers action to add the command to.
    """
    parser_promote = subparsers.add_parser(
        "promote",
        help="Plan and apply deployment ring promotion",
        description=(
            "Plan and apply ring-based promotion of published apps.\n\n"
            "Examples:\n"
            "  napt promote plan\n"
            "  napt promote apply\n"
            "  napt promote plan recipes/Google/chrome.yaml\n\n"
            "See docs for the promotion model and workflows."
        ),
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    promote_sub = parser_promote.add_subparsers(
        dest="subcommand",
        help="Promotion subcommands",
        required=True,
    )
    parser_promote_plan = promote_sub.add_parser(
        "plan",
        help="Compute eligible promotions and write per-app plan files",
        description=(
            "Compute which releases are ready to promote through deployment "
            "rings, and write one state/plans/<app>.json file per app with "
            "work. "
            "Never modifies Intune. Read-only for deployment state too, "
            "except that --reconcile writes it when recovering a lost "
            "publication writeback. With --check-drift or --reconcile, "
            "every group in the plan is validated against Entra ID and an "
            "unresolvable group fails the run without writing any plan. "
            "An app's stale plan file is removed when nothing is eligible "
            "for it."
        ),
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    parser_promote_plan.add_argument(
        "recipes",
        nargs="?",
        type=Path,
        default=Path("recipes"),
        help="Recipe file or directory to plan for (default: recipes/)",
    )
    add_state_dir(
        parser_promote_plan,
        "State directory holding deployment/ and plans/ "
        "(default: directories.state from config)",
    )
    parser_promote_plan.add_argument(
        "--check-drift",
        action="store_true",
        help=(
            "Also compare Intune assignments against deployment state "
            "(requires Graph credentials); findings are warnings only"
        ),
    )
    parser_promote_plan.add_argument(
        "--reconcile",
        action="store_true",
        help=(
            "Before planning, record publications that are committed in "
            "Intune but whose deployment state writeback was lost, so "
            "they are promotable in this run (requires Graph credentials; "
            "writes deployment state)"
        ),
    )
    add_output_flags(parser_promote_plan)
    parser_promote_plan.set_defaults(func=cmd_promote_plan)

    parser_promote_apply = promote_sub.add_parser(
        "apply",
        help="Execute promotion plans against Intune",
        description=(
            "Execute promotion actions: assign install entries, promote "
            "releases through rings, displace the older releases they "
            "replace, and retire them per deployment.retain_versions. "
            "Executes only the plan files written by 'napt promote plan', "
            "consuming each per-app file in state/plans/ after its app "
            "applies fully. One app's failure keeps its plan "
            "file and never blocks the others, and stale or "
            "already-applied actions are skipped, so re-running is safe."
        ),
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    parser_promote_apply.add_argument(
        "recipes",
        nargs="?",
        type=Path,
        default=Path("recipes"),
        help="Recipe file or directory to apply for (default: recipes/)",
    )
    add_state_dir(
        parser_promote_apply,
        "State directory holding deployment/ and plans/ "
        "(default: directories.state from config)",
    )
    parser_promote_apply.add_argument(
        "--plan-file",
        type=Path,
        default=None,
        help=(
            "Single plan file to execute (default: the given recipes' plan "
            "files in <state-dir>/plans/; other apps' files are left alone)"
        ),
    )
    add_output_flags(parser_promote_apply)
    parser_promote_apply.set_defaults(func=cmd_promote_apply)

napt.cli.status

The napt status command.

Aggregates per-app deployment state into one view: published version, pending release, and ring positions.

cmd_status

cmd_status(args: Namespace) -> int

Handler for 'napt status' command.

Aggregates all per-app deployment state files into one view: the published version, pending release, and which version holds each ring. Without --state-dir, the directory comes from the recipes' directories.state setting, the same one the pipeline wrote to.

Parameters:

Name Type Description Default
args Namespace

Parsed command-line arguments containing the recipes path, state directory, output format, and flags.

required

Returns:

Type Description
int

Exit code (0 for success).

Note

Failures raise NAPT errors for run_handler to report.

Source code in napt/cli/status.py
def cmd_status(args: argparse.Namespace) -> int:
    """Handler for 'napt status' command.

    Aggregates all per-app deployment state files into one view: the
    published version, pending release, and which version holds each ring.
    Without --state-dir, the directory comes from the recipes'
    ``directories.state`` setting, the same one the pipeline wrote to.

    Args:
        args: Parsed command-line arguments containing the recipes path,
            state directory, output format, and flags.

    Returns:
        Exit code (0 for success).

    Note:
        Failures raise NAPT errors for
        [run_handler][napt.cli.common.run_handler] to report.

    """
    from napt.config.loader import resolve_state_dir
    from napt.state.deployment import summarize_deployment_states

    state_dir = (
        args.state_dir
        if args.state_dir is not None
        else resolve_state_dir(args.recipes)
    )
    deployment_dir = state_dir / "deployment"

    rows = summarize_deployment_states(deployment_dir)

    if args.format == "json":
        print(json.dumps(rows, indent=2, sort_keys=True))
        return 0

    if not rows:
        print(f"No deployment state found in {deployment_dir}")
        return 0

    headers = ("App", "Published", "Pending", "Rings")
    table = [
        (
            row["app_id"],
            row["published"] or "-",
            (row["pending"] or "-")
            + (" [DOWNGRADE]" if row["pending_is_downgrade"] else ""),
            ", ".join(f"{name}={ver}" for name, ver in row["rings"].items()) or "-",
        )
        for row in rows
    ]
    widths = [
        max(len(headers[col]), *(len(line[col]) for line in table))
        for col in range(len(headers))
    ]
    print("  ".join(h.ljust(widths[i]) for i, h in enumerate(headers)))
    print("  ".join("-" * w for w in widths))
    for line in table:
        print("  ".join(cell.ljust(widths[i]) for i, cell in enumerate(line)))

    return 0

register

register(subparsers: _SubParsersAction) -> None

Registers the 'status' command parser.

Parameters:

Name Type Description Default
subparsers _SubParsersAction

The CLI's subparsers action to add the command to.

required
Source code in napt/cli/status.py
def register(subparsers: argparse._SubParsersAction) -> None:
    """Registers the 'status' command parser.

    Args:
        subparsers: The CLI's subparsers action to add the command to.
    """
    parser_status = subparsers.add_parser(
        "status",
        help="Show deployment state across all apps",
        description=(
            "Aggregate per-app deployment state into one view: published "
            "version, pending release, and ring positions.\n\n"
            "Examples:\n"
            "  napt status\n"
            "  napt status --format json\n\n"
            "See docs for more examples and workflows."
        ),
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    parser_status.add_argument(
        "recipes",
        nargs="?",
        type=Path,
        default=Path("recipes"),
        help=(
            "Recipe file or directory whose configuration names the state "
            "directory (default: recipes/)"
        ),
    )
    add_state_dir(
        parser_status,
        "State directory holding deployment/ "
        "(default: directories.state from config)",
    )
    parser_status.add_argument(
        "--format",
        choices=["text", "json"],
        default="text",
        help="Output format (default: text)",
    )
    add_output_flags(parser_status)
    parser_status.set_defaults(func=cmd_status)

napt.cli.upload

The napt upload command.

Uploads the .intunewin package of the release recorded in deployment state for a recipe to Microsoft Intune via the Graph API.

cmd_upload

cmd_upload(args: Namespace) -> int

Handler for 'napt upload' command.

Uploads the .intunewin package of the release deployment state records (pending, else published) for a recipe to Microsoft Intune via the Graph API; with no recorded release, the only package. Authentication uses service principal / OIDC environment variables when set, otherwise the session saved by 'napt auth login'.

Parameters:

Name Type Description Default
args Namespace

Parsed command-line arguments containing recipe path, directory overrides, and debug flags.

required

Returns:

Type Description
int

Exit code (0 for success).

Note

Run 'napt package' before this command to create the .intunewin file. Re-running an upload adopts existing NAPT-stamped apps instead of creating duplicates; --force re-sends metadata and content to them. Developers: run 'napt auth login' once. CI/CD: set AZURE_CLIENT_ID, AZURE_TENANT_ID and AZURE_CLIENT_SECRET, or use OIDC federation. Failures raise NAPT errors for run_handler to report.

Source code in napt/cli/upload.py
def cmd_upload(args: argparse.Namespace) -> int:
    """Handler for 'napt upload' command.

    Uploads the .intunewin package of the release deployment state records
    (pending, else published) for a recipe to Microsoft Intune via the
    Graph API; with no recorded release, the only package. Authentication
    uses service principal / OIDC environment variables when set, otherwise
    the session saved by 'napt auth login'.

    Args:
        args: Parsed command-line arguments containing recipe path,
            directory overrides, and debug flags.

    Returns:
        Exit code (0 for success).

    Note:
        Run 'napt package' before this command to create the .intunewin file.
        Re-running an upload adopts existing NAPT-stamped apps instead of
        creating duplicates; --force re-sends metadata and content to them.
        Developers: run 'napt auth login' once. CI/CD: set AZURE_CLIENT_ID,
        AZURE_TENANT_ID and AZURE_CLIENT_SECRET, or use OIDC federation.
        Failures raise NAPT errors for
        [run_handler][napt.cli.common.run_handler] to report.

    """
    from napt.upload.manager import upload_package

    recipe_path = args.recipe.resolve()

    print(f"Uploading package for recipe: {recipe_path}")
    print()

    result = upload_package(
        recipe_path,
        force=args.force,
        state_dir=args.state_dir,
        packages_dir=args.packages_dir,
    )

    print_results(
        "UPLOAD RESULTS",
        [
            ("App ID", result.app_id),
            ("App Name", result.app_name),
            ("Version", result.version),
            ("Intune Win32 App ID", result.intune_app_id),
            ("Intune Win32 Update ID", result.intune_update_app_id),
            ("Package", result.package_path),
        ],
        "Package uploaded to Intune successfully!",
    )
    return 0

register

register(subparsers: _SubParsersAction) -> None

Registers the 'upload' command parser.

Parameters:

Name Type Description Default
subparsers _SubParsersAction

The CLI's subparsers action to add the command to.

required
Source code in napt/cli/upload.py
def register(subparsers: argparse._SubParsersAction) -> None:
    """Registers the 'upload' command parser.

    Args:
        subparsers: The CLI's subparsers action to add the command to.
    """
    parser_upload = subparsers.add_parser(
        "upload",
        help="Upload .intunewin package to Microsoft Intune",
        description=(
            "Upload the .intunewin package of the release recorded in "
            "deployment state (pending, else published) for a recipe to "
            "Microsoft Intune via the Graph API; with no recorded release, "
            "the only package.\n\n"
            "Authentication:\n"
            "  CI/CD:       AZURE_CLIENT_ID + AZURE_TENANT_ID + AZURE_CLIENT_SECRET,\n"
            "               or OIDC federation (azure/login)\n"
            "  Interactive: run 'napt auth login' once\n\n"
            "Examples:\n"
            "  napt upload recipes/Google/chrome.yaml\n"
            "  napt upload recipes/Google/chrome.yaml --verbose\n\n"
            "See docs for auth setup and full configuration guide."
        ),
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    parser_upload.add_argument(
        "recipe",
        type=Path,
        help="Path to the recipe YAML file",
    )
    parser_upload.add_argument(
        "--force",
        action="store_true",
        help=(
            "Re-upload metadata and content to existing NAPT-managed apps "
            "for this release instead of adopting them as-is "
            "(never creates duplicates)"
        ),
    )
    parser_upload.add_argument(
        "--packages-dir",
        type=Path,
        default=None,
        help="Directory containing the packages (default: from config or ./packages)",
    )
    add_state_dir(
        parser_upload,
        "State root whose deployment/ folder records the release "
        "(default: from config or ./state)",
    )
    add_output_flags(parser_upload)
    parser_upload.set_defaults(func=cmd_upload)

napt.cli.upstream

The napt upstream command: recipes imported from other git repositories.

napt upstream add imports upstream recipes from a repository as pinned copies and writes the overrides that run them; napt upstream remove takes one out again; napt upstream check reports which pinned copies drifted from their upstream recipes and napt upstream update rewrites them. The engines live in napt.upstream.add, napt.upstream.remove, and napt.upstream.refresh; this module parses arguments and prints results.

cmd_upstream_add

cmd_upstream_add(args: Namespace) -> int

Handler for 'napt upstream add'.

Imports the selected recipes from a repository: writes each one byte-identical as a pinned copy under upstream/, writes an override in recipes/ that names it as parent, and records each recipe's commit and hashes in upstream.yaml. Nothing is written if any recipe fails validation.

Parameters:

Name Type Description Default
args Namespace

Parsed command-line arguments carrying the clone URL, paths, ref, destination, id, exclude globs, and the dry-run flag.

required

Returns:

Type Description
int

Exit code (0 for success).

Note

Failures raise NAPT errors for run_handler to report.

Source code in napt/cli/upstream.py
def cmd_upstream_add(args: argparse.Namespace) -> int:
    """Handler for 'napt upstream add'.

    Imports the selected recipes from a repository: writes each one
    byte-identical as a pinned copy under upstream/, writes an override in
    recipes/ that names it as parent, and records each recipe's commit and
    hashes in upstream.yaml. Nothing is written if any recipe fails validation.

    Args:
        args: Parsed command-line arguments carrying the clone URL, paths,
            ref, destination, id, exclude globs, and the dry-run flag.

    Returns:
        Exit code (0 for success).

    Note:
        Failures raise NAPT errors for
        [run_handler][napt.cli.common.run_handler] to report.
    """
    from napt.upstream.add import add_recipes

    result = add_recipes(
        Path.cwd(),
        args.url,
        args.path,
        ref=args.ref,
        dest=args.dest,
        app_id=args.id,
        excludes=args.exclude,
        dry_run=args.dry_run,
    )

    print()
    for recipe in result.recipes:
        marker = "[PLAN]" if result.dry_run else "[OK]"
        print(f"{marker} {recipe.path} -> {recipe.override} (id {recipe.app_id})")
    for path in result.skipped:
        print(f"[SKIP] {path} (already imported; napt upstream update refreshes it)")
    print()
    rows = [
        ("Repository", result.url),
        ("Ref", result.ref),
        ("Commit", result.commit),
        ("Recipes", str(len(result.recipes))),
        ("Skipped", str(len(result.skipped)) if result.skipped else None),
    ]
    count = len(result.recipes)
    if result.dry_run:
        print_results("UPSTREAM ADD (DRY RUN)", rows, "Nothing written.")
    elif count == 0:
        print_results("UPSTREAM ADD RESULTS", rows, "Nothing new to import.")
    else:
        print_results(
            "UPSTREAM ADD RESULTS",
            rows,
            f"Imported {count} recipe(s); run 'napt validate recipes/' to confirm.",
        )
    return 0

cmd_upstream_remove

cmd_upstream_remove(args: Namespace) -> int

Handler for 'napt upstream remove'.

Deletes a pinned copy and its lockfile entry, and the repository's entry once nothing of it remains. The override stays unless --delete-override is given.

Parameters:

Name Type Description Default
args Namespace

Parsed command-line arguments carrying the path and the delete-override flag.

required

Returns:

Type Description
int

Exit code (0 for success).

Note

Failures raise NAPT errors for run_handler to report.

Source code in napt/cli/upstream.py
def cmd_upstream_remove(args: argparse.Namespace) -> int:
    """Handler for 'napt upstream remove'.

    Deletes a pinned copy and its lockfile entry, and the repository's
    entry once nothing of it remains. The override stays unless
    --delete-override is given.

    Args:
        args: Parsed command-line arguments carrying the path and the
            delete-override flag.

    Returns:
        Exit code (0 for success).

    Note:
        Failures raise NAPT errors for
        [run_handler][napt.cli.common.run_handler] to report.
    """
    from napt.upstream.remove import remove_recipe

    result = remove_recipe(Path.cwd(), args.path, delete_override=args.delete_override)

    override_state = None
    if result.override is not None:
        override_state = "deleted" if result.override_deleted else "kept"
    print_results(
        "UPSTREAM REMOVE RESULTS",
        [
            ("Removed", result.path),
            ("Override", result.override),
            ("Override State", override_state),
            ("Repository Entry", "removed" if result.repo_removed else "kept"),
        ],
        "Removed the pinned copy.",
    )
    return 0

cmd_upstream_check

cmd_upstream_check(args: Namespace) -> int

Handler for 'napt upstream check'.

Compares each pinned copy to the upstream recipe at the branch or tag tip and to its own lockfile entry, writing nothing.

Parameters:

Name Type Description Default
args Namespace

Parsed command-line arguments carrying optional paths, the output format, and the exit-code flag.

required

Returns:

Type Description
int

Exit code: 0 when the check completed; 1 with --exit-code when any

int

recipe is changed or missing upstream.

Note

Failures raise NAPT errors for run_handler to report.

Source code in napt/cli/upstream.py
def cmd_upstream_check(args: argparse.Namespace) -> int:
    """Handler for 'napt upstream check'.

    Compares each pinned copy to the upstream recipe at the branch or tag
    tip and to its own lockfile entry, writing nothing.

    Args:
        args: Parsed command-line arguments carrying optional paths, the
            output format, and the exit-code flag.

    Returns:
        Exit code: 0 when the check completed; 1 with --exit-code when any
        recipe is changed or missing upstream.

    Note:
        Failures raise NAPT errors for
        [run_handler][napt.cli.common.run_handler] to report.
    """
    from napt.upstream.refresh import refresh

    as_json = args.format == "json"
    result = refresh(Path.cwd(), write=False, paths=args.path, quiet=as_json)
    _print_refresh(result, as_json=as_json, title="UPSTREAM CHECK RESULTS")
    if args.exit_code and result.drifted:
        return 1
    return 0

cmd_upstream_update

cmd_upstream_update(args: Namespace) -> int

Handler for 'napt upstream update'.

Rewrites the pinned copies whose upstream recipe changed, each with its own new commit in upstream.yaml; other entries keep their pins.

Parameters:

Name Type Description Default
args Namespace

Parsed command-line arguments carrying optional paths, the output format, and the force flag.

required

Returns:

Type Description
int

Exit code: 0 when every selected recipe was handled; 1 when a

int

locally modified pinned copy was left alone.

Note

Failures raise NAPT errors for run_handler to report.

Source code in napt/cli/upstream.py
def cmd_upstream_update(args: argparse.Namespace) -> int:
    """Handler for 'napt upstream update'.

    Rewrites the pinned copies whose upstream recipe changed, each with its
    own new commit in upstream.yaml; other entries keep their pins.

    Args:
        args: Parsed command-line arguments carrying optional paths, the
            output format, and the force flag.

    Returns:
        Exit code: 0 when every selected recipe was handled; 1 when a
        locally modified pinned copy was left alone.

    Note:
        Failures raise NAPT errors for
        [run_handler][napt.cli.common.run_handler] to report.
    """
    from napt.upstream.refresh import refresh

    as_json = args.format == "json"
    result = refresh(
        Path.cwd(), write=True, paths=args.path, force=args.force, quiet=as_json
    )
    _print_refresh(result, as_json=as_json, title="UPSTREAM UPDATE RESULTS")
    return 1 if result.refused else 0

register

register(subparsers: _SubParsersAction) -> None

Registers the 'upstream' command parser and its subcommands.

Parameters:

Name Type Description Default
subparsers _SubParsersAction

The CLI's subparsers action to add the command to.

required
Source code in napt/cli/upstream.py
def register(subparsers: argparse._SubParsersAction) -> None:
    """Registers the 'upstream' command parser and its subcommands.

    Args:
        subparsers: The CLI's subparsers action to add the command to.
    """
    parser_upstream = subparsers.add_parser(
        "upstream",
        help="Import recipes from other git repositories",
        description=(
            "Import upstream recipes from any git repository as pinned copies. "
            "An imported "
            "recipe is a byte-identical pinned copy under upstream/, run through an "
            "override in recipes/ that names it as parent, and recorded in "
            "upstream.yaml with its commit and hashes.\n\n"
            "Examples:\n"
            "  napt upstream add https://github.com/org/recipes.git "
            "--path recipes/Google/chrome.yaml\n"
            "  napt upstream add https://github.com/org/recipes.git "
            "--path recipes --exclude 'Beta/*'\n"
            "  napt upstream remove recipes/Google/chrome.override.yaml"
        ),
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    upstream_sub = parser_upstream.add_subparsers(
        dest="upstream_command",
        help="Upstream subcommands",
        required=True,
    )

    parser_add = upstream_sub.add_parser(
        "add",
        help="Import recipes from a repository",
        description=(
            "Fetch the recipes under each --path at the branch or tag, write "
            "them as pinned copies under upstream/, write one <app>.override.yaml "
            "per recipe "
            "under recipes/ (mirroring the path after the repository's own "
            "recipes/ segment), and record them in upstream.yaml. Keys an "
            "upstream recipe may not set (deployment, directories, intune "
            "policy) are ignored at load and named once here. Nothing is "
            "written if any recipe fails validation.\n\n"
            "Examples:\n"
            "  napt upstream add https://github.com/org/recipes.git "
            "--path recipes/Google/chrome.yaml\n"
            "  napt upstream add git@github.com:org/recipes.git --path recipes "
            "--ref v2 --dry-run\n"
            "  napt upstream add https://gitlab.com/g/sub/recipes.git "
            "--path apps/x.yaml --dest recipes/Vendor --id vendor-x"
        ),
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    parser_add.add_argument("url", help="Clone URL in any form git accepts")
    parser_add.add_argument(
        "--path",
        action="append",
        required=True,
        metavar="PATH",
        help=(
            "File or directory inside the repository to import; repeatable. "
            "A directory imports every .yaml and .yml beneath it"
        ),
    )
    parser_add.add_argument(
        "--ref",
        default=None,
        help="Branch or tag to import from (default: the repository's default branch)",
    )
    parser_add.add_argument(
        "--dest",
        default=None,
        metavar="DIR",
        help=(
            "Directory for the overrides, relative to the project root; required "
            "when the upstream path has no recipes/ segment to mirror"
        ),
    )
    parser_add.add_argument(
        "--id",
        default=None,
        help="Override id instead of the upstream recipe's (single-file imports)",
    )
    parser_add.add_argument(
        "--exclude",
        action="append",
        default=[],
        metavar="GLOB",
        help=(
            "Skip files matching the glob, relative to the imported directory; "
            "repeatable"
        ),
    )
    parser_add.add_argument(
        "--dry-run",
        action="store_true",
        help="Show what would be written and write nothing",
    )
    add_output_flags(parser_add)
    parser_add.set_defaults(func=cmd_upstream_add)

    parser_remove = upstream_sub.add_parser(
        "remove",
        help="Remove an imported recipe",
        description=(
            "Delete a pinned copy and its upstream.yaml entry, and the "
            "repository's entry once nothing of it remains. The override is "
            "kept, with its parent now dangling, unless --delete-override is "
            "given.\n\n"
            "Examples:\n"
            "  napt upstream remove recipes/Google/chrome.override.yaml\n"
            "  napt upstream remove upstream/github.com/org/recipes/recipes/"
            "Google/chrome.yaml --delete-override"
        ),
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    parser_remove.add_argument(
        "path",
        type=Path,
        help="The override, or the pinned copy under upstream/",
    )
    parser_remove.add_argument(
        "--delete-override",
        action="store_true",
        help="Delete the override as well",
    )
    add_output_flags(parser_remove)
    parser_remove.set_defaults(func=cmd_upstream_remove)

    parser_check = upstream_sub.add_parser(
        "check",
        help="Report pinned copies that differ from their upstream recipes",
        description=(
            "Compare each pinned copy to the upstream recipe at the branch or "
            "tag tip (changed, missing) and to its upstream.yaml entry "
            "(modified-locally). Writes nothing. Exits 0 when the check "
            "completed; with --exit-code, exits 1 when anything is changed or "
            "missing, like git diff --exit-code.\n\n"
            "Examples:\n"
            "  napt upstream check\n"
            "  napt upstream check --format json\n"
            "  napt upstream check recipes/Google/chrome.override.yaml --exit-code"
        ),
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    _add_refresh_arguments(parser_check)
    parser_check.add_argument(
        "--exit-code",
        action="store_true",
        help="Exit 1 when any recipe is changed or missing upstream",
    )
    add_output_flags(parser_check)
    parser_check.set_defaults(func=cmd_upstream_check)

    parser_update = upstream_sub.add_parser(
        "update",
        help="Rewrite pinned copies whose upstream recipe changed",
        description=(
            "Run the same scan as check, then rewrite each changed pinned copy "
            "from the upstream recipe at the tip and record its new commit in "
            "upstream.yaml. Other entries keep their pins, so passing one "
            "override or pinned copy refreshes that recipe alone. A pinned copy "
            "edited locally is left alone and the command exits 1, unless "
            "--force overwrites it. Overrides are never touched.\n\n"
            "Examples:\n"
            "  napt upstream update\n"
            "  napt upstream update recipes/Google/chrome.override.yaml\n"
            "  napt upstream update --format json"
        ),
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    _add_refresh_arguments(parser_update)
    parser_update.add_argument(
        "--force",
        action="store_true",
        help="Overwrite pinned copies that were edited locally",
    )
    add_output_flags(parser_update)
    parser_update.set_defaults(func=cmd_upstream_update)

napt.cli.validate

The napt validate command.

Checks a recipe's effective configuration (org.yaml, vendor defaults, parent, recipe) for syntax errors and configuration issues without downloading files or making network calls. Given a directory, checks every recipe under it and reports two files that resolve to the same id.

cmd_validate

cmd_validate(args: Namespace) -> int

Handler for 'napt validate' command.

Validates recipe syntax and configuration without downloading files or making network calls. This is useful for quick feedback during recipe development and for CI/CD pre-checks.

Parameters:

Name Type Description Default
args Namespace

Parsed command-line arguments containing the recipe or directory path and verbose flag.

required

Returns:

Type Description
int

Exit code (0 when every recipe is valid, 1 otherwise).

Note

Prints validation results, errors, and warnings to stdout.

Source code in napt/cli/validate.py
def cmd_validate(args: argparse.Namespace) -> int:
    """Handler for 'napt validate' command.

    Validates recipe syntax and configuration without downloading files or
    making network calls. This is useful for quick feedback during recipe
    development and for CI/CD pre-checks.

    Args:
        args: Parsed command-line arguments containing
            the recipe or directory path and verbose flag.

    Returns:
        Exit code (0 when every recipe is valid, 1 otherwise).

    Note:
        Prints validation results, errors, and warnings to stdout.

    """
    from napt.validation import validate_recipe, validate_recipes

    recipe_path = args.recipe.resolve()

    if recipe_path.is_dir():
        print(f"Validating recipes under: {recipe_path}")
        print()
        results = validate_recipes(recipe_path)
        _print_directory(results, recipe_path)
        if args.debug:
            for result in results:
                if result.is_valid:
                    print()
                    print(f"Recipe: {_display_path(result, recipe_path)}")
                    _print_provenance_block(result)
        failed = sum(1 for result in results if not result.is_valid)
        print()
        print("=" * 70)
        if failed:
            print(f"[FAILED] {failed} of {len(results)} recipe(s) failed validation.")
            return 1
        print(f"[SUCCESS] All {len(results)} recipe(s) are valid.")
        return 0

    print(f"Validating recipe: {recipe_path}")
    print()

    result = validate_recipe(recipe_path)
    _print_single(result)

    # Show provenance in debug mode, from the same merge that was validated.
    if args.debug:
        _print_provenance_block(result)

    if result.is_valid:
        print()
        print("[SUCCESS] Recipe is valid!")
        return 0
    print()
    print(f"[FAILED] Recipe validation failed with {len(result.errors)} error(s).")
    return 1

register

register(subparsers: _SubParsersAction) -> None

Registers the 'validate' command parser.

Parameters:

Name Type Description Default
subparsers _SubParsersAction

The CLI's subparsers action to add the command to.

required
Source code in napt/cli/validate.py
def register(subparsers: argparse._SubParsersAction) -> None:
    """Registers the 'validate' command parser.

    Args:
        subparsers: The CLI's subparsers action to add the command to.
    """
    parser_validate = subparsers.add_parser(
        "validate",
        help="Validate recipe syntax and configuration (no downloads)",
        description=(
            "Check a recipe's effective configuration (org.yaml, vendor "
            "defaults, parent, recipe) for syntax errors and configuration "
            "issues without making network calls. Given a directory, check "
            "every recipe under it.\n\n"
            "Examples:\n"
            "  napt validate recipes/Google/chrome.yaml\n"
            "  napt validate recipes/\n"
            "  napt validate recipes/Google/chrome.yaml --verbose\n\n"
            "See docs for more examples and workflows."
        ),
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    parser_validate.add_argument(
        "recipe",
        type=Path,
        help="Path to a recipe YAML file, or a directory of recipes",
    )
    add_output_flags(parser_validate)
    parser_validate.set_defaults(func=cmd_validate)