Metadata-Version: 2.4
Name: gnbuild
Version: 0.1.3
Summary: Package build tool based on GN and Ninja
License-Expression: MIT
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Build Tools
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Dynamic: license-file

# gnb

English reference. The Chinese reference is `README_CN.md`, included in this repository and the source distribution.

gnb is a package build tool based on GN and Ninja. The current `gnbuild` package provides TOML parsing, semantic-version resolution, dependency solving into a build plan, and build backends (`GNBackend`, `CMakeBackend`, `MesonBackend`) that configure, build and clean the output directory. It requires Python >= 3.11 and uses the standard library. Version: 0.1.3.

The loaders in `gnbuild.plan.tomlparse` are `load_project(root)`, `load_profile(path)` and `load_recipe(root)`; the data types `Dependency`, `Project`, `Profile`, `Recipe` and `RecipeVersion`, with `select_version(recipe, spec)` and `pin_version(recipe, key)`, are in `gnbuild.plan.inputs`; table checks are in `gnbuild.plan.validate`. `gnbuild.plan.semver` provides `Constraint(parts, op)`, `SortKey`, `parse_constraint(spec)`, `satisfies(rule, version)` and `highest_satisfying(spec, versions)`.

Current code lives in `gnbuild/`; tests live in `gnbuild/tests/` (offline: local HTTP server and Git repositories; run `python -B -m pytest`, needs pytest; tests for aria2c, axel, curl and wget skip when the tool is missing). Layout: `utils.py` (shared helpers), `log.py` (all console output), `package/` (package sources: `repos` with `LocalRepo`/`GitRepo`/`ManifestRepo`, `download` with the `*Downloader` backends, `archive` with `TarArchive`/`ZipArchive`, `sources` (fetch one package source), `cache`), `backends/` (`BuildBackend` base in `__init__.py`, `gn/`, `cmake/`, `meson/`, `project.py` with `OutputDir`, shared `external.py`/`runner.py`/`interface.py`, `toolchain.py` with the target checks, `gntext.py` for GN text), `commands/` (CLI), `plan/` (`Plan`; input parsing in `tomlparse`, `inputs`, `validate` and `semver`; the platform and toolchain models in `target` and `toolchain`; `solver.py` with the `Solver`; `recipes.py` finding a recipe and fetching a package by name; `nodes.py` typed nodes), `profiles/` (bundled profiles), `toolchains/` (builtin toolchains). `gnb config` parses the inputs into one JSON build plan, fetches package sources and configures the output directory; `gnb build` and `gnb clean` run the backends; package sources are also fetched by `gnb package fetch`.

## Command entry

The executable `./gnb` and the installed `gnb` command share the same entry point, `gnbuild.main`.

```text
gnb config OUT [-b DIR] [-p FILE] [--configs KEY=TOML] [--options KEY=TOML]
               [-g] [-x PROXY] [-j N] [--skip] [-v]   # alias: f
gnb build OUT [-j N] [-c] [-v]            # alias: b; build the configured output directory
gnb clean OUT [-v]                        # alias: c; remove build products
gnb package list|fetch|clean|remove ...   # alias: p
```

All commands support `--help`; the top-level entry supports `--version`. `config` makes and writes the plan, then fetches every package source into the cache (dependencies first, through the same code as `gnb package fetch`; `-x/--proxy`, default `$GNB_URL_PROXY`; `-j/--jobs N` connections per download, default 8), then configures the output directory. Downloads use the first installed of aria2c, curl, wget, else a built-in urllib client; `GNB_DOWNLOADER=<name>` forces one (axel is used only this way, because it retries forever once a transfer has started). Each backend gets only what it supports natively: resume (all external tools) and parallel connections (aria2c, axel; `-j` is ignored by the others). Nothing is retried: a failed download is an error, and running the command again resumes the kept partial file. A transfer is abandoned only when it stalls (curl: under 1 KiB/s for 30 s; aria2c: under 1 KiB/s; wget: 30 s without data; built-in: 60 s without data), never because it took long in total. The sha256 check is always gnb's own. A failed fetch exits with status 2 but keeps the written `build.json`; rerunning `config` retries only what is missing. `config --skip` makes only the plan: no fetching and no backend configuration; `config -v` prints the resolved plan summary. Each command is a `gnbuild.commands.Command` subclass (`ConfigCommand`, `BuildCommand`, `CleanCommand`, `PackageCommand`); `gnbuild.main(argv, commands)` registers whatever command instances it is given, and a command with `subcommands` becomes a group.

## Build backends

The project itself is always built by GN. Each package is built by the backend its recipe `entry` selects: `BUILD.gn` joins the project's GN graph (options become GN args), `CMakeLists.txt` and `meson.build` are black boxes: one GN action runs the package's own ninja, and its public flags, include directories and libraries are exposed to GN consumers (CMake: read back through an injected export module; meson: declared in the recipe `exports` table, because `meson introspect` cannot tell public flags from private ones). `gnb config` runs each package's configure step (cmake or meson) and `gn gen`, writing `.gn` and `packages/<name>/BUILD.gn` into OUT; `--skip` only writes the plan. `gnb build` refreshes those registrations, builds each CMake/meson package first with its own ninja (output shown live), then runs the project's ninja; `-j N` is passed to every ninja it starts (default: ninja's own). `-c` cleans, then plans again from the arguments `gnb config` recorded in `build.json` (project directory, profile, cache, `--configs`/`--options`, and the proxy and connections `-x`/`-j` of the download), so edits to `gnb.toml`, the profile or the recipes take effect, and reconfigures; an invalid input is reported before anything is cleaned. Without `-c`, `gnb build` refuses a plan whose `gnb.toml`, profile, recipes or toolchain file changed since `gnb config`. `gnb clean` removes products but keeps configuration. Tools (gn, ninja, cmake, meson) are looked up on `PATH`; a missing one is an error naming it.

### Cross builds

A profile names the platform it builds for in GN's own vocabulary and gnb translates it for every backend:

```toml
[profile]
toolchain = "@arm-none-eabi-gcc"   # which tools to run: a builtin name, a toolchain .toml or @package

[platform]                        # what they build for; omitted: this host
os      = "none"                  # linux win mac android none (bare metal) wasm (Emscripten); with cpu, or neither
cpu     = "arm"                   # x86 x64 arm arm64 mipsel mips64el s390x riscv32 riscv64 loong64 wasm32
triple  = "thumbv7m-none-eabi"    # optional, clang-style compilers only: passed as --target=
```

Giving `os` and `cpu` in `[platform]` makes the build a cross build. GN gets them as its `target_os`/`target_cpu` (without them GN's own values default to the host's), CMake as `CMAKE_SYSTEM_NAME`/`CMAKE_SYSTEM_PROCESSOR` (and static-library try-compile), meson as a generated `gnb-cross.ini` cross file (`pkg_config_libdir` and `sys_root` name the sysroot, so the host's `.pc` files are never used; `needs_exe_wrapper` is true). The sysroot is where libraries and pkg-config files of the target are searched (CMake `find_*`, pkg-config, meson): the sysroot the toolchain declares, else the one the compiler reports with `-print-sysroot` (GCC cross toolchains such as Arm's), else nothing is found. It is a property of the toolchain, not of the profile, so a profile has no `sysroot`. Only a declared one is also passed to the compiler as `--sysroot` (GN's toolchain style reads it from build.json, so there is no GN argument for it); without one the compiler uses its own, which is why GN needs no probed value. The toolchain says which tools to run (and, optionally, the sysroot). `config` refuses mismatches instead of building for the wrong machine: a triple that disagrees with `os`/`cpu`, only one of them, an unsupported value, a missing sysroot, and a compiler whose `-dumpmachine` (with `--target=<triple>` when set) names another cpu or os than the profile targets, or than this host for a profile without a target. `ppc64` is not supported because GN's value does not say its byte order. A cross build also never finds host files: CMake gets `CMAKE_FIND_ROOT_PATH` set to the sysroot with libraries, includes and packages searched only there and programs only on the host (without one, the sysroot the compiler reports with `-print-sysroot`, which GCC cross toolchains such as Arm's do; for a compiler that reports none, an empty directory, so nothing is found), and CMake and meson see only the sysroot's pkg-config files.

## Configuration parsing

The `demos/` used below and in [Demos](#demos) are in the source repository only; the installed package and the wheel do not contain them.

```bash
./gnb config out/debug -b demos/pkg_app
./gnb config out/debug -b demos/pkg_app --profile demos/pkg_app/profiles/default.toml
```

Installation also provides the `gnb` command. The package cache (`gnbuild.package.cache.Cache`) is `.gnb` in the directory where `gnb config` runs (not necessarily the project directory); `-g/--global` uses `~/.gnb`. The location is fixed at config time and recorded as `cache` in `build.json`; later stages must use that value, not re-derive it from their own working directory. `Plan.create(..., cache=Path)` selects any location. Omitting `--profile` reads the bundled `gnbuild/profiles/none.toml`; an explicitly missing profile is an error. `--configs KEY=TOML` and `--options KEY=TOML` override the project only.

The API is `gnbuild.plan.Plan`: `Plan.create(root, out, profile=None, *, configs=None, options=None, cache=None, directories=None, settings=DownloadSettings())` builds the plan (it only reads: `Plan.fetch_repos(root, cache=None, settings=DownloadSettings())` is the step that fetches remote recipe repositories into the cache and returns the `directories` to pass; without them only local repositories work), `plan.write()` publishes it, and `Plan.load(out)` reads and validates an existing `build.json` (for later build/clean). The nodes are `ProfileNode`, `ProjectNode` and `PackageNode`. It emits only `out/build.json`, which holds the project data and the dependency plan: selected versions, dependency-first order, recipe declarations, paths and input hashes. Remote source paths are cache locations that `gnb config` fills (unless `--skip`).

Configuration scopes, low to high precedence:

| Output | Inputs |
|---|---|
| `project.configs` | shared profile configs → project configs → CLI configs |
| `project.options` | project options → profile options → CLI options |
| `packages.<name>.configs` | shared profile configs → selected recipe configs → dependency configs → profile's named dependency configs |
| `packages.<name>.options` | dependency options (nearer to the project wins) → profile's named dependency options |

Top-level profile `configs` are shared compile defaults; top-level profile `options` never reach packages. Project TOML accepts top-level `configs/options`. A recipe may carry `version.default.configs` (version pins override them by key) but no `options`: options are inputs to a package, set where it is depended on, in `[deps.<name>.options]` of the project, a profile or another recipe. Dependency tables accept `configs/options`, and profile `deps.<name>` overlays reachable packages, including transitive ones, without adding unused dependencies. Nearer project dependencies take precedence; unresolved same-depth scalar option conflicts fail. Config lists replace per key; option lists are concatenated higher precedence first and deduplicated.

```toml
[profile]
name = "debug"
toolchain = "gcc"

[configs]                 # shared compile defaults
cflags = ["-g"]
[options]                 # project only
APP_DEBUG = true
[deps.foo.configs]        # package foo only
cflags = ["-Os"]
[deps.foo.options]
FEATURE = true
```

`[profile] launcher` (a compiler launcher such as `ccache`) is resolved when `gnb config` runs and recorded in `build.json`: omitted → `sccache`, else `ccache`, else none, found on `PATH`; `""` disables it; a named launcher missing from `PATH` fails `config`. A recipe's `[package]` takes `name` and `kind` (`source` or `binary`, default `source`).

Known `${project_dir}`, `${pkgdir}`, `${srcdir}` and `${version}` placeholders are expanded with node-specific origins; unknown literal variables are preserved. Repository lookup supports local/file directories, Git and checksum-verified HTTP manifests. Remote repositories are cached under `repos/` of the package cache; package sources are fetched into the cache by `gnb config` (unless `--skip`) and `gnb package fetch`. Git repositories require Git; extended archive formats require optional `bsdtar`.

JSON publication is atomic and uses mode `0600`. A newly created output directory gets a `.gitignore` containing `*` (an existing one is kept). Existing malformed, linked or foreign-project snapshots are rejected. The JSON may contain sensitive URLs/options and should not be committed.


## Requirements

- Python >= 3.11 (standard library only; no `.pyc` files are generated at runtime).
- `gn` and `ninja`, found on `PATH`; `cmake` for CMake packages and `meson` for meson packages; a C/C++ compiler (the profile's toolchain, see below).
- Downloads use the first installed of `aria2c`, `curl`, `wget`, else a built-in urllib client; `git` for Git repositories and packages; `bsdtar` (optional) for extended archive formats.
- Optional: `sccache` or `ccache`, found automatically and used as the compiler launcher.

A missing tool produces `gnb: error: <tool> not found on PATH; ...` and exit code 2.

## Commands

- `gnb config OUT` (alias `f`): plan, fetch package sources, configure every package and run `gn gen` (see [Command entry](#command-entry)); `-b DIR` project directory (default: the current one), `-p FILE` profile, `-v` print the plan summary.
- `gnb build OUT` (alias `b`): `-j N` jobs, `-c` clean, plan again from the recorded arguments and reconfigure first, `-v` show commands. The directory must have been configured; without `-c` its inputs must be unchanged since.
- `gnb clean OUT` (alias `c`): remove build products, keep the configuration.
- `gnb package list|fetch|clean|remove` (alias `p`): manage the package cache; all take `-g` for `~/.gnb`. `fetch NAME [VERSION] --repos DIR_OR_URL ...` reads no project `gnb.toml`: the recipe repositories come only from `--repos` (required, repeatable, searched in order). `clean`/`remove` need an exact version or `--all`, never a constraint: `clean` deletes extracted sources and keeps downloads, `remove` deletes downloaded archives and keeps sources.
- `gnb --version`.

Errors are printed as `gnb: error: <message>` on stderr with exit code 2; Ctrl+C exits with 130. Results go to stdout, everything else to stderr. Every stage of a command is one line (`configuring X (cmake) ✓`, `generating build files (gn) ✓`, with a spinner on a terminal) and the tools' own output is captured: a failure prints it, a ninja failure from its first `FAILED:` line on. With `-v` each stage prints its heading first, then the command (`$ ...`) and the tool's output live. The final project build is the exception: ninja's own output is always shown (with its status line on a terminal), `-v` only makes it print full commands. On a terminal gnb's own lines are colored (stage headings cyan, `✓` green, `x` and errors red, warnings yellow, commands dim) so they stand out from the tools' output; `NO_COLOR` turns this off.

## Profiles

A profile is a TOML file chosen with `gnb config -p FILE` (default: the bundled `gnbuild/profiles/none.toml`, the host toolchain):

```toml
[profile]
name = "size"                  # default: the file name
toolchain = "gcc"              # builtin: host gcc clang emscripten; a .toml path (relative to this file); or @package
launcher = "sccache"           # omitted: sccache, else ccache, else none; "": none

[platform]                     # optional, see Cross builds
os = "none"
cpu = "arm"

[configs]                      # compile flags for the project and every package
cflags = ["-Os", "-g"]         # also cflags_c, cflags_cc, asmflags, ldflags, defines, include_dirs

[options]                      # project options only (GN arguments)
APP_DEBUG = true

[deps.mylib.options]           # overlay on one reachable package
FEATURE = true
```

A toolchain says which tools to run: `prefix`, the names `cc`, `cxx` and `ar` (required), an optional `sysroot` of what it builds for (only with a cross profile) and an optional `style` (default `gcc`). It is always a flat TOML file with those keys, found in one of three places:

- a builtin one by name: `gnbuild/toolchains/<name>.toml` (`host`, `gcc`, `clang`, `emscripten`);
- a `.toml` file of your own, named by path; a relative `sysroot` is relative to the file;
- `@name`: the `toolchain.toml` beside the recipe of package `name`, where `${srcdir}`, `${pkgdir}` and `${version}` expand as in the recipe, a relative `sysroot` is relative to the unpacked package, and the sysroot must stay inside the package. The package must be `kind = "binary"`. The profile then depends on that package (no `[deps]` entry needed, and other profiles never fetch it), and a `kind = "binary"` package puts its `exports.bindirs` on `PATH`, so the file names plain `cc = "gcc"` with `prefix = "arm-none-eabi-"`:

```toml
# packages/a/arm-none-eabi-gcc/toolchain.toml
prefix = "arm-none-eabi-"
cc = "gcc"
cxx = "g++"
ar = "ar"
sysroot = "arm-none-eabi"   # optional
```

CMake and meson get the tools from this definition (and recognise the compilers themselves). Only GN needs the `style`: the GN file `gnbuild/backends/gn/templates/styles/<style>.gni`, which knows the compiler's command lines and how it names files (`libx.a`, `x.elf`; `x.exe` for a Windows target, `x.wasm` for Emscripten's). File names are not part of a toolchain's configuration. Another compiler family (MSVC, IAR) is another style file.

The scopes and their precedence are in [Configuration parsing](#configuration-parsing).

## Project file: gnb.toml

A project is a directory with a `BUILD.gn`. Its optional `gnb.toml`:

```toml
[project]
name = "demo"                  # required; a package name (lowercase letters, digits, _ . -)
version = ""
repos = ["packages/"]          # recipe repositories, searched in order

[deps.mylib]                   # a package the project uses
version = "^1.2"               # semver constraint; "" = newest stable
options = { MYLIB_LEVEL = 2 }  # package options; ${project_dir} expands
configs = { defines = ["FEATURE"] }

[configs]                      # project-only compile flags
[options]                      # project-only options
```

A repository entry is a relative path (against the project directory), an absolute path, a `file://` URI, a Git URL (`git://`, `ssh://`, `https://...git`) or a checksum-verified HTTP manifest. Git repositories are cloned once at HEAD into the cache; their URLs carry no revision, since immutable pinning happens inside each package's recipe.

## Package recipes: gnb.toml

A recipe lives at `<repo>/<p>/<pkgname>/gnb.toml`, where `<p>` is the first letter of the package name (`packages/l/lvgl/gnb.toml`); a recipe directly under `<repo>/<pkgname>/` is not found:

```toml
[package]
name = "mylib"                 # must match the directory name
kind = "source"                # or "binary" (tools), "library" (prebuilt libraries)

[version.default]              # template for every version
url = "https://example.org/mylib-${version}.tar.gz"
entry = "CMakeLists.txt"       # selects the backend: BUILD.gn (default), CMakeLists.txt, meson.build

[version."1.2.0"]              # a pin, merged over default field by field
hash = "..."                   # sha256 (archive) or tag/full commit ID (Git)

[version.default.exports]
libs = ["mylib"]               # the library targets `default` exposes (optional for CMake)
```

- The URL decides the source kind: a Git URL (`git://`, `ssh://`, `git+...` or ending in `.git`) is shallow-cloned and detached at the pinned revision; a local directory (bare path or `file://`) is used in place and never inspected for `.git`; anything else is an archive that is downloaded and sha256-checked. `${version}` expands in `url`.
- Local directories have no version semantics: there is one fixed checkout. Use per-version `url` overrides for more.
- Git pins are tags or full commit IDs; branch names are never accepted, so a branch can never hijack a tag checkout.
- A package may depend on others with `[version.default.deps.<name>]` (same shape as the project's `[deps]`).
- `kind = "binary"` means gnb does not build the package, it only fetches it: no backend, no `BUILD.gn`. What it is used for follows from how it is referenced. A **tool** (a compiler, `ninja`, `cmake`) lists `exports.bindirs` (directories relative to the unpacked package, e.g. `["bin"]`), which are put first on `PATH` while `gnb config`, `gnb build` and `gnb clean` run; list the package in a `[deps]` table. A **toolchain** is a package with a `toolchain.toml` file beside its recipe, used by a profile with `toolchain = "@name"`.
- `kind = "library"` is a prebuilt library: headers and library files that nothing builds, for example a vendor SDK. It is registered with GN like a CMake package (the configs and groups described in "Using a package in BUILD.gn"), without an action. The files and the usage requirements are in `exports`: `libs` (files relative to the unpacked package, or absolute; each becomes a target named like the file without its `lib` prefix and extension, `lib/libvendor.a` is `vendor`), `include_dirs` (directories, also relative), `defines`, `cflags`, `ldflags` and `system_libs`. Whoever names one library gets all of them: they ship together and need each other, and GN links static libraries in a group, so the order does not matter. A package with neither `libs` nor `include_dirs` is refused; with only `include_dirs` it is a headers-only target named like the package. Missing files and directories fail at `gnb config`.
- Unlike a tool, a library is selected by the **target** of the profile (`[platform]`, the host when it is omitted), because it is linked into what the profile builds. Its `platform` table carries the files of each target, `exports` there adds to (and replaces by key) the version's own:

```toml
[version.default.exports]
include_dirs = ["include"]
defines = ["VENDOR_STATIC"]

[version."1.0.0".platform.none-arm]
url = "https://example.org/sdk-arm.tar.xz"
hash = "..."
[version."1.0.0".platform.none-arm.exports]
libs = ["lib/libvendor.a"]
```

A target without an entry is an error naming the target and the entries the recipe has.
- A version of a tool may carry one `platform` table per **host** (the machine gnb runs on) whose `url` and `hash` replace the version's own, because tools ship per platform. Keys are `<os>-<cpu>` in the profile `[platform]` vocabulary (`linux-x64`, `mac-arm64`, `win-x64`, ...). A package with a `platform` table needs an entry for the current host, or `gnb config` fails and lists the hosts it has. This is the host, not the profile's `[platform]` target.

```toml
[version."15.3.2".platform."linux-x64"]
url = "https://example.org/toolchain-linux-x64.tar.xz"
hash = "..."
```
- `exports`: CMake reports library targets, include directories, defines, compile and link options itself (through an injected export module), so a CMake recipe needs no `exports` at all. Without `libs` it exports every static or header-only library the project defines and `all` builds (not `EXCLUDE_FROM_ALL`, directly or through its directory, and not imported ones); name others, or restrict the set, with `libs`. Options decide which targets exist. A consumer can name any exported target: `gnb_package("p") { deps = [ "t" ] }`. meson cannot tell public flags from private ones and lists no targets, so its recipe must declare `libs` and the public flags next to it:

```toml
[version.default.exports]
libs = ["mylib"]                          # meson target names, in link order
include_dirs = ["include", "${builddir}"] # relative to the source directory; also ${srcdir}
defines = ["MYLIB_STATIC"]
cflags = ["-pthread"]
system_libs = ["m"]
```

GN packages (entry `BUILD.gn`) take a plain `exports = ["gnlib"]` list of target names, or `libs` in the `exports` table as above.

## Scripts shipped by a package

A recipe may list the GN files of its scripts, `scripts = ["${pkgdir}/lvgl_image.gni"]` (in `[version.default]` or a pin; paths use `${pkgdir}`, `${srcdir}`, `${version}`); each defines templates around the package's own scripts. `BUILDCONFIG.gn` imports the static `gnbuild/backends/gn/templates/package.gni`, which asks `build.json` for these files (dependencies first) and imports each, so every `BUILD.gn` can call the templates without importing anything; nothing is generated for this. Which scripts a template runs, and with which parameters, is the package's own business: gnb passes nothing through and checks nothing.

A template runs a script of its package with `gnb_action` (from `package.gni`), an `action` whose `package = "lvgl"` names the package and whose `script = "scripts/LVGLImage.py"` is relative to the package's source directory; everything else is `action`'s own. It looks the package up in `build.json`, which GN is told to watch, so nothing is stored twice and nothing grows with the number of packages. For other needs (`pkgdir`, `version`, or `gen_dir` = `<out>/packages/<name>/gen` for what a package generates for itself) a template can call `exec_script("${gnb_template_dir}/package_info.py", [ rebase_path("${gnb_output_dir}/build.json"), "lvgl" ], "json", [ "${gnb_output_dir}/build.json" ])` itself. (GN cannot `read_file` `build.json`: it rejects keys such as `arm-none-eabi-gcc` as invalid identifiers; GN has no functions that return a value, so a template cannot be called like `x = gnb_package(...)`.) A project target writes below `$target_gen_dir/$target_name` (`<out>/gen/<target>/` for the root `BUILD.gn`), as GN targets do. ## Using a package in BUILD.gn

The demo `demos/lvgl_sdl` ships two templates in its `lvgl` recipe that any project with an lvgl package can copy: `lvgl_image` and `lvgl_font`. They turn images and fonts into LVGL C files and compile them, and they are the same files that `lvgl_platform` uses (`lvgl_image.gni` and `lvgl_font.gni` with the wrappers `lvgl_image.py`, `lvgl_font.py` and `lvconf.py` beside them). `lvgl_image` runs LVGL's own `scripts/LVGLImage.py` (needs `pypng` and `lz4` in the Python that runs GN, and `pngquant` for the indexed formats of true-colour PNGs); `lvgl_font` runs `lv_font_conv` (pinned in `lvgl_font.py`) through `npx`, which needs Node.js. Both go through a small wrapper because GN runs the script of an action with Python.

```gn
gnb_package("lvgl") {
  deps = [ "lvgl" ]               # the core target, so `:lvgl` below names it
}

lvgl_image("assets") {
  inputs = [
    {
      src = "src/img/a.png"
      name = "img_a"              # the C symbol, and <name>.c (required)
    },
    {
      src = "src/img/b.png"
      name = "img_b"
      format = "I8"               # a key here overrides the default for this image
    },
  ]
  args = {                        # defaults for every image, forwarded to the converter
    format = "RGB565"             # --cf (default ARGB8888)
    premultiply = true
  }
  deps = [ ":lvgl" ]              # the generated sources include lvgl.h
}

lvgl_font("fonts") {
  inputs = [
    {
      src = "src/fonts/ui.ttf"
      name = "ui"                 # the symbol is <name>_<size>
      size = 32                   # logical size at 160 DPI
    },
  ]
  args = {
    bpp = 4
    range = "0x20-0x7F"
  }
  deps = [ ":lvgl" ]
}
```

The project's `lv_conf.h` (the `LV_BUILD_CONF_PATH` option of the lvgl package) decides two things, and a change to it converts again. An image without `compress` is compressed with LZ4, else RLE, when `LV_BIN_DECODER_RAM_LOAD` is on (otherwise not at all), and an explicit `compress` that the decoder lacks fails the build. A font is rasterized for `LV_DPI_DEF`, `max(1, (dpi * size + 80) / 160)` pixels, so DPI 260 turns `size = 32` into 52 px, while `dpi = 160` in `args` or in an input keeps the size as given. Without a `lv_conf.h` LVGL's defaults apply (160 DPI, no compression). Two inputs with the same symbol in one target fail `gn gen`, and a name that is not a C identifier fails the conversion. The keys are the converter's (images: `format`, `compress`, `align`, `background`, `premultiply`, `rgb565dither`, `nemagfx`; fonts: `bpp`, `range`, `symbols`, `dpi`, `compress`, `prefilter`, `kerning`, `autohint`, `force_fast_kern_format`, `fallback`); the comments at the top of the two `.gni` files list them.

## Using a package in BUILD.gn

```gn
gnb_package("mylib") {
}                                     # everything the package exports

gnb_package("mylib") {
  deps = [ "a" ]                      # only the exported target "a"
  configs = [ "b_public" ]            # also its config b_public (public_configs)
}

executable("app") {
  sources = [ "main.c" ]
  deps = [ ":mylib" ]
}
```

`gnb_package` (from `gnbuild/backends/gn/templates/package.gni`) points at `<out>/packages/<name>/BUILD.gn`, which `gnb config` generates. For a CMake or meson package that file holds one GN action (when the package builds a library), two `config`s and a `group` per exported library, and a `default` group. The action's outputs are the library files, and its depfile lists everything the package's own build read, so editing a package source or header rebuilds it. See [Build backends](#build-backends) for how the package is built.

## Output and cache layout

```text
<out>/                              # the output directory (GN's build directory)
  .gn  args.gn  build.json          # GN dotfile (written by gnb), GN's args.gn, the plan
  build.ninja  toolchain.ninja  obj/ ...
  packages/<name>/BUILD.gn          # registration of one package with the GN build
  packages/<name>/build/            # a CMake or meson package's own build directory
  packages/<name>/gen/              # the depfile of that package's GN action

./.gnb/  (or ~/.gnb with -g)        # the package cache, fixed at config time
  downloads/<pkg>/<version>/<sha256>.<ext>   # downloaded archives (.part while downloading)
  packages/<pkg>/<version>/         # extracted or checked-out source
  packages/<pkg>/<version>/.gnb     # identity marker (TOML: url, hash, version)
  repos/<sha256(url)>/              # cloned remote recipe repositories
    snapshots/<commit>/  refs.json
```

Only complete content with a matching identity (`.gnb` marker: url + hash) is reused; an identity conflict at the same version is an error asking you to delete the cache entry. Archive members are validated against symlink escapes and path traversal before extraction; hard links are accepted only when they name a regular file of the same archive (toolchains ship tools that way), devices and fifos are refused. Repositories are cloned once at HEAD and cached by URL; pushing a new commit upstream does not update the cache until it is deleted.

## Demos

Only in the source repository (not in the wheel or the source distribution); run them from the repository root.

- `demos/hello`: pure local build, no packages — `gnb config out -b demos/hello`, then `gnb build out`; `-p demos/hello/profiles/debug.toml` or `size.toml` selects a profile.
- `demos/pkg_app`: GN-native (`gnlib`) and CMake (`multi`, selective `deps = ["a"]`) packages mixed.
- `demos/meson_app`: meson package with a recipe `exports` table and a package option.
- `demos/host_app`: CMake package with a configure-time generated header (the exported include directories cover the build directory).
- `demos/arm_fw`: firmware lib using a CMake package; `-p demos/arm_fw/profiles/arm.toml` cross-builds it for bare-metal ARM with Arm's GCC toolchain package (`toolchain = "@arm-none-eabi-gcc"`, `[platform]`).
- `demos/lvgl_sdl`: real LVGL 9.6.0 acceptance demo (507-target scale, widgets demo from the full source archive, options such as `LV_BUILD_CONF_PATH`). `-p demos/lvgl_sdl/profiles/debug.toml` builds the native SDL2 app (needs cmake and SDL2 dev files); `-p demos/lvgl_sdl/profiles/html.toml` builds one `lvgl_demo.html` with Emscripten (`[platform] os = "wasm"`, `cpu = "wasm32"`, SDL2 from `-sUSE_SDL=2`; the first run makes emscripten build its system libraries). `gnb package fetch lvgl --repos demos/lvgl_sdl/packages` works standalone.

## License

MIT.
