Dang SDK
Dang is Dagger's native DSL. It maps directly to the Dagger API, so what you write is what runs. There is no codegen, no generated client files to commit, no build step, and no language runtime to carry around. In the common case a Dang module is one main.dang file plus a dagger-module.toml.
Use Dang when your module mostly orchestrates the Dagger API: containers, files, directories, services, secrets, and other modules. If you need external libraries (a Go parser, a Python ML library, a Node.js bundler API), use the Go, Python, or TypeScript SDK instead. Those give you a full host language alongside the Dagger client.
Every SDK shares a few platform concepts. Read these first if they are new to you:
- SDKs overview explains what a module is and how it fits into a workspace.
- Types covers the types your functions accept and return.
- Generating code shows how Dagger represents file diffs.
initand generators both use them.
A note on tooling: Dang is delivered as a Dagger module
The Dang SDK is a Dagger module, dagger.io/sdk/dang. Install it once, then create and maintain modules with the CLI module commands:
# Install the Dang SDK into your workspace (once)
dagger module install dagger.io/sdk/dang
# Create a module
dagger module init dang --name my-ci
The commands you will use most often:
| Command | Purpose |
|---|---|
dagger module init dang | Create a module and generate its configuration. |
dagger module client add, rm, update, list | Manage module clients from the module directory. |
dagger generate | Regenerate configuration for registered modules. |
dagger sdk scope list --sdk=dang --is-module | List Dang modules. |
Create a module
Run these commands from inside a Git repository. That is where Dagger creates the new module.
Install the Dang SDK into your workspace, then create a new module with dagger module init. By default it creates the module beside the active dagger.toml:
<dagger.toml directory>/.dagger/modules/<name>
dagger module install dagger.io/sdk/dang
dagger module init dang --name my-ci
dagger module init returns a changeset. Dagger shows it to you for review before writing any files into your workspace. Pass -y to apply it without the prompt. A headless run, such as CI or a coding agent, has no prompt and fails without -y.
init takes these arguments:
--nameis optional. Without--nameor--path, Dagger infers<project>-devand installs the module as the workspace main.--pathselects a directory relative to the current directory. A custom path is registered for generation but is not installed; usedagger module install <path>to install it.--templateselects the starter template.minimalis the only template and the default. Despite the name, it is a small working module with a Check, a test environment, a service, and a generator, shown below.--fatalso generates adagger.jsonfile for older engines. It is disabled by default.
Generated layout
.dagger/
modules/
my-ci/
dagger-module.toml
main.dang
The generated dagger-module.toml:
name = "my-ci"
engineVersion = "v1.0.0-beta.32"
[runtime]
source = "dang"
Setting runtime.source to "dang" tells Dagger to run this module with the Dang runtime. engineVersion declares the engine version the module requires. See Engine version.
The generated main.dang entry point is a working example of the things a module does. It has a base container, a Check, a test environment that mounts workspace files and binds a service, a service that dagger start can start, and a generator that writes a test script:
"""
Starter Dang module generated by dang-sdk.
"""
type MyCi {
"""
Activate chaos mode.
"""
chaosMode: Boolean! = false
"""
Base container for the test environment.
"""
base: Container! = container
.from("alpine:3.22.1")
.withExec(["apk", "add", "--no-cache", "curl"])
"""
Check this module.
"""
myCheck: Void @check {
if (chaosMode) {
raise "chaos mode!"
}
null
}
"""
Return a shell environment with test scripts and the backend service.
"""
myTestEnv(ws: Workspace!): Container! {
base
.withWorkdir("/work")
.withMountedDirectory(
".",
ws.directory(".", include: ["**/my-tests.sh"]),
)
.withServiceBinding("my-backend", backend)
.withDefaultTerminalCmd(["/bin/sh"])
}
"""
Start a small web backend.
"""
@up
myBackend: Service! {
backend
}
"""
Generate an example backend test.
"""
myGenerate(ws: Workspace!): Changeset! @generate {
ws.withNewFile(
"my-tests.sh",
```sh
#!/bin/sh
set -eu
test "$(curl --fail --silent http://my-backend)" = "hello"
echo "OK"
```,
).changes(ws)
}
"""
Build the backend service used by the test environment.
"""
let backend: Service! {
container
.from("nginx:alpine")
.withNewFile("/usr/share/nginx/html/index.html", "hello\n")
.withExposedPort(80)
.asService
}
}
Replace it with your own type once you have seen it run. Because --name installs the module into the workspace, its Checks and services appear as soon as the changeset is applied:
dagger check -l
MODULE CHECK DESCRIPTION
dang-sdk stale staleness check: re-generate modules and clients managed by the Dang SDK
my-ci my-check Check this module.
my-ci stale staleness check: generate an example backend test
dagger check dag://my-ci/my-check
A module created with --path is not installed. Call it by pointing -m at its directory instead, or install it with dagger module install <path>.
Language basics
Dang is small on purpose. The whole language fits in a short list:
- Types. Declare one with
type Name { ... }at the top level of a file. The type whose name matches the module name is the main type and its entry point. - Visibility. Members are public by default.
letmakes a member private to its type. Older modules mark public members withpub, which has no effect. - Functions. A function is a member with a body:
build: Container! { ... }. The last expression in the body is the result, so there is noreturnfor the normal result. - Arguments. They go in parentheses:
build(source: Directory!): Container! { ... }. Callers pass them by name or position:build(source: src). - Zero-argument calls. They take no parentheses, so a field and a function read the same:
container.from("alpine").stdout. - Non-null. Mark it with
!. Nullable is the default and has no marker. - Directives. They mark functions for Dagger:
@check,@generate,@up,@cache. - Descriptions. Put a triple-quoted string (
""" ... """) above the thing it describes. - Strings. Double quotes process escapes, triple double quotes are raw, and backticks interpolate
${...}. See Strings. - Blocks. A trailing
{ x => ... }passes a block to a function:paths.map { p => `${p}.bak` }. - Records. Double braces build an anonymous record:
{{ name: "app", port: 8080 }}. - Comments. Start them with
#. - Module metadata. A triple-quoted docstring at the top of the file, above the main
type.
A minimal module is a type with at least one public function:
"""
CI for my project.
"""
type MyCi {
"""
Say hello.
"""
hello: String! {
"Hello from Dagger!"
}
}
hello is public, so callers see it. The docstring at the top of the file is the module's summary. dagger api functions and dagger api call --help show it. Per-member docstrings document individual functions and arguments.
Try it. An installed module is called by its install name, and the workspace's main module is called without one:
dagger api call my-ci hello
# Hello from Dagger!
Expressions and chaining
Dang chains method calls on the Dagger API. A function body is a sequence of expressions separated by newlines, and the function returns the value of the last one. The chain reads top to bottom:
container
.from("node:20")
.withDirectory("/app", source)
.withWorkdir("/app")
.withExec(["npm", "install"])
Every method returns a new immutable value. Nothing mutates in place. Dagger caches each step by its inputs, so a re-run skips unchanged work. It is the same model as Docker layer caching, applied to the entire API. See the type reference for the underlying model.
Strings
Dang has four ways to write a string. They differ in whether they span lines, process escapes, and interpolate:
| Form | Spans lines | Escapes | Interpolates ${...} |
|---|---|---|---|
| Double quotes | No | Yes | No |
| Triple double quotes | Yes | None, the text is raw | No |
| Backticks | No | Only \${ | Yes |
| Triple backticks | Yes | Only \${ | Yes |
Double quotes hold one line and process escapes:
| Escape | Meaning |
|---|---|
\n \r \t | Line feed, carriage return, tab |
\" \\ | A double quote, a backslash |
\a \b \f \v | Bell, backspace, form feed, vertical tab |
\ooo \xNN | A byte in octal or hex |
\uNNNN \UNNNNNNNN | A Unicode code point |
Any other backslash sequence is kept as written, so "\d+" is the three characters \d+. ${name} inside double quotes is literal text. A line break inside double quotes is a parse error:
no match found, expected: "\"", "\\" or [^\\"\n]
Triple double quotes hold many lines and are raw: no escapes and no interpolation, so \n and ${name} come out exactly as typed. The indentation common to every line is removed, and so are the line break after the opening """ and the one before the closing """. This is the form docstrings use, and it suits a script or config file full of $ and backslashes.
Backticks interpolate. ${...} takes any Dang expression: an argument, a field, arithmetic, or a call that returns a value. Values that are not strings are rendered as the Dang literal they would be written as, so ${1 + 2} is 3 and a list reads ["a", "b"]. A Dagger object renders as the lazy query it is, such as <Container: container.from(address: …)>, without running it or showing argument values; select .id where you need its ID. The only escape is \${, which produces a literal ${. Every other backslash is literal, and so is a $ that is not followed by {, so a regular expression or $HOME needs no escaping.
Triple backticks are the multi-line form of backticks, with the same interpolation and the same indentation handling as triple double quotes. A language tag after the opening fence, as in a Markdown code block, is for editor highlighting and is not part of the value. When the text itself contains triple backticks, open and close with a longer fence of four or more:
type MyCi {
"""
A shell script that greets someone.
"""
script(name: String! = "world"): String! {
```sh
#!/bin/sh
echo "hello ${name}"
echo "home is \${HOME}, also $HOME"
```
}
}
dagger api call my-ci script --name=dagger
# #!/bin/sh
# echo "hello dagger"
# echo "home is ${HOME}, also $HOME"
In a backtick string, Dang reads a shell variable written as ${HOME} as a Dang expression, and the module fails to load:
Error: "HOME" not found
Write it as \${HOME} or $HOME. When the text needs no interpolation at all, use triple double quotes.
Define objects and functions
A module is a type. Functions are its public members. The function body returns a value of the declared return type:
"""
CI for my web application.
"""
type MyCi {
source: Directory!
new(ws: Workspace!) {
self.source = ws.directory("/")
self
}
build: Container! {
container
.from("node:20")
.withDirectory("/app", source)
.withWorkdir("/app")
.withExec(["npm", "install"])
.withExec(["npm", "run", "build"])
}
}
Private state with let
let defines a private member, such as internal state or a helper function that callers cannot see. Use let for shared setup that several functions reuse:
type Security {
source: Directory!
new(ws: Workspace!) {
self.source = ws.directory("/")
self
}
# Private: not callable by users
let trivyBase = container
.from("aquasec/trivy:0.68.2")
.withMountedCache(
path: "/root/.cache",
cache: cacheVolume("trivy-cache"),
sharing: CacheSharingMode.LOCKED,
)
.withWorkdir("/home/trivy")
# Public: callable by users
scanSource: Void {
trivyBase
.withMountedDirectory(".", source)
.withExec(["trivy", "fs", "--exit-code=1", "--severity=CRITICAL,HIGH", "."])
.sync
null
}
}
Custom types
Define additional types to model what your module produces, for example to return several related values from one function. Declare each one at the top level of a file, beside the main type. A type declared inside another type's body is not part of the module's API.
A type is also its constructor. Its fields without a default are the constructor's arguments, in declaration order:
type MyCi {
source: Directory!
new(ws: Workspace!) {
self.source = ws.directory("/")
self
}
build(platform: String! = "linux/amd64"): BuildResult! {
let bin = container
.from("golang:1.22")
.withDirectory("/app", source)
.withWorkdir("/app")
.withExec(["go", "build", "-o", "/out/app", "."])
.file("/out/app")
BuildResult(binary: bin, version: "1.0.0", platform: platform)
}
}
"""
Build result containing the binary and metadata.
"""
type BuildResult {
binary: File!
version: String!
platform: String!
}
Dagger prefixes custom type names in the API schema (for example MyCiBuildResult) to avoid conflicts when several modules load together. Callers reach a custom type by chaining from a function on the main type.
Enumerations
Use enum to restrict an argument to a fixed set of values. Declare it at the top level of a file, like a custom type. An enum value is not a String, so convert it with a template string where a string is expected:
type Security {
scan(ref: String!, severity: Severity!): String! {
container
.from("aquasec/trivy:latest")
.withExec(["trivy", "image", "--severity", `${severity}`, ref])
.stdout
}
}
enum Severity {
UNKNOWN
LOW
MEDIUM
HIGH
CRITICAL
}
Compare enum values with ==, as in severity == Severity.CRITICAL. An invalid value produces an error that lists the allowed choices:
dagger api call security scan --ref=alpine:latest --severity=FOO
# ! invalid argument "FOO" for "--severity" flag: value should be one of UNKNOWN,LOW,MEDIUM,HIGH,CRITICAL
Interfaces
Interfaces let your module accept types from other modules without depending on them. Declare an interface at the top level of the file. List the members you need as signatures only, with no body:
"""
Any object that can produce a container image.
"""
interface Buildable {
build: Container!
}
type Deployer {
deploy(app: Buildable!, registry: String!): String! {
app.build.publish(`${registry}/app:latest`)
}
}
A concrete type declares that it satisfies an interface with implements. It provides the interface's members. Dagger supplies the id field that every interface carries:
type WebApp implements Buildable {
source: Directory!
new(ws: Workspace!) {
self.source = ws.directory("/")
self
}
build: Container! {
container
.from("node:20")
.withDirectory("/app", source)
.withWorkdir("/app")
.withExec(["npm", "run", "build"])
}
}
Across module boundaries Dagger also matches structurally. You can pass any object from another module whose functions match Buildable where the interface is expected, even without an explicit implements declaration.
Arguments and return values
Functions accept typed arguments in parentheses. An argument with a default value is optional; an argument with a ! type and no default is required:
type MyCi {
source: Directory!
new(ws: Workspace!) {
self.source = ws.directory("/")
self
}
build(
"""
Node.js version to use.
"""
nodeVersion: String! = "20",
): Container! {
container
.from(`node:${nodeVersion}`)
.withDirectory("/app", source)
.withWorkdir("/app")
.withExec(["npm", "install"])
.withExec(["npm", "run", "build"])
}
}
An argument can carry:
- Types.
String!,Int!,Boolean!,Directory!,File!,Secret!,Container!, custom types, enums, interfaces, and so on. - Defaults.
= "20"makes the argument optional. Inside the body, aString! = "20"argument is still non-null, so it needs no null checks. - Descriptions. A triple-quoted string above the argument.
- Non-null markers.
!means required when there is no default. Without it the argument is nullable and optional:config: File = null.
dagger api call my-ci build
dagger api call my-ci build --node-version=18
Constructor arguments, which are members on the primary type set in new(...), give users knobs they can override globally. The constructor also receives the user's Workspace. Dagger fills that in, and the module reads project files from it:
type MyCi {
source: Directory!
nodeVersion: String!
registry: String!
new(
ws: Workspace!,
nodeVersion: String! = "20",
registry: String! = "ghcr.io",
) {
self.source = ws.directory("/")
self.nodeVersion = nodeVersion
self.registry = registry
self
}
build: Container! {
container
.from(`node:${nodeVersion}`)
.withDirectory("/app", source)
.withWorkdir("/app")
.withExec(["npm", "install"])
.withExec(["npm", "run", "build"])
}
publish(tag: String!): String! {
build.publish(`${registry}/myorg/myapp:${tag}`)
}
}
# CLI override
dagger api call my-ci --node-version=18 build
# Or in dagger.toml
# [modules.my-ci.settings]
# nodeVersion = "18"
# registry = "docker.io"
Working with core Dagger types
Dang exposes the full Dagger API directly. These are the types you will use most:
Containers
build: Container! {
container
.from("node:20")
.withDirectory("/app", source)
.withWorkdir("/app")
.withExec(["npm", "install"])
.withExec(["npm", "run", "build"])
}
Files and directories
Functions can return File! or Directory!, and accept them as arguments. Reach into a container's filesystem with .file(path) or .directory(path):
binary: File! {
build.file("/app/dist/server.js")
}
Secrets
Accept secrets as the Secret type, never as plain strings. Dagger scrubs secret values from all output streams, including crash reports:
deploy(
"""
API token for deployment.
"""
token: Secret!,
): Void {
container
.from("alpine")
.withSecretVariable("DEPLOY_TOKEN", token)
.withExec(["sh", "-c", "deploy --token=$DEPLOY_TOKEN"])
.sync
null
}
Callers supply secrets through providers:
dagger api call my-ci deploy --token=env://DEPLOY_TOKEN # environment variable
dagger api call my-ci deploy --token=file://./token.txt # file
dagger api call my-ci deploy --token="cmd://gh auth token" # command output
dagger api call my-ci deploy --token=op://vault/item/field # 1Password
dagger api call my-ci deploy --token=vault://path/to/secret # HashiCorp Vault
dagger api call my-ci deploy --token=gcp://secret-name # Google Cloud Secret Manager
A secret is scoped to the module that defines it. To share one across modules, pass it as a function argument.
Services
Start services for integration tests or dev environments. Services are content-addressed, so the same definition always gets the same hostname and there are no port conflicts:
type MyCi {
source: Directory!
new(ws: Workspace!) {
self.source = ws.directory("/")
self
}
let db: Service! {
container
.from("postgres:16")
.withEnvVariable("POSTGRES_PASSWORD", "test")
.withExposedPort(5432)
.asService
}
integrationTest: Void @check {
container
.from("golang:1.22")
.withDirectory("/app", source)
.withServiceBinding("db", db)
.withEnvVariable("DATABASE_URL", "postgres://postgres:test@db:5432/postgres")
.withExec(["go", "test", "-tags=integration", "./..."])
.sync
null
}
}
Cache volumes
Use cache volumes for package manager caches and other persistent data that should survive across runs. cacheVolume("name") is keyed by name:
build: Container! {
container
.from("node:20")
.withDirectory("/app", source)
.withWorkdir("/app")
.withMountedCache("/app/node_modules", cacheVolume("node-modules"))
.withExec(["npm", "install"])
.withExec(["npm", "run", "build"])
}
A cache volume is scoped to the module that defines it. To share one across modules, pass a reference as a function argument.
Module dependencies
A Dang module can depend on modules written in any SDK. Run the client commands from the module directory:
cd .dagger/modules/my-ci
dagger module client add github.com/shykes/daggerverse/hello@v0.3.0 --sdk=dang
dagger module client list --sdk=dang
dagger module client update --sdk=dang
dagger module client rm github.com/shykes/daggerverse/hello@v0.3.0 --sdk=dang
Client add and remove commands update targets in dagger.toml. Client update refreshes dagger.lock. All three regenerate the module configuration. Review and apply each changeset. The SDK writes the runtime dependencies shown below; generation replaces manual dependency edits in dagger-module.toml.
The result lands in dagger-module.toml:
name = "my-ci"
engineVersion = "v1.0.0-beta.32"
[runtime]
source = "dang"
[[dependencies]]
name = "hello"
source = "github.com/shykes/daggerverse/hello@v0.3.0"
[[dependencies]]
name = "local"
source = "./path/to/module"
A dependency reference follows [proto://]host/repo[/subpath][@version]:
github.com/shykes/daggerverse/hello@v0.3.0
# ^^^^^^ ^^^^^^^^^^^^^ ^^^^^ ^^^^^^
# host repo path version
proto://is optional (ssh://orhttps://). If you omit it, Dagger chooses based on the authentication available.@versioncan be a tag, branch, or commit. If you omit it, Dagger uses the default branch.- Local dependencies use a relative path (
./path/to/module).
Once added, call a dependency in your code by its name, like a function:
type MyCi {
"""
Greet the team.
"""
greeting: String! {
# 'hello' is the dependency module, called by its name
hello.hello(greeting: "hi", name: "team")
}
}
dagger api call my-ci greeting
# hi, team!
Generate and module metadata
Most SDKs use a generate step to produce client bindings from the Dagger API schema, which you then commit. Dang has no such step. Because Dang maps directly to the Dagger API, there are no generated client files and nothing language-specific to check in. What you write in main.dang is what runs.
dagger generate regenerates module configuration from the registered SDK scopes. Dang still produces no client source files.
dagger generate
dagger sdk scope list --sdk=dang --is-module
Engine version
Each module declares its required engine version with engineVersion in dagger-module.toml. The Dang SDK writes this field during generation. A manual edit can be replaced by the next generation. The value must be a concrete version (for example v1.0.0-beta.31).
Workspace inputs
A module reads the surrounding project's files through a Workspace argument on its constructor. Dagger fills in this argument from the current workspace. The caller passes nothing, and nothing uploads up front. The module reads project content lazily, only when it uses it:
type MyCi {
"""The source directory for the project."""
source: Directory!
new(ws: Workspace!) {
self.source = ws.directory("/")
self
}
}
Workspace has three readers:
ws.directory(path)reads a directory from the workspace.ws.file(path)reads a single file.ws.findUp(name:, from:)searches upward from a start path for a file or directory by name and returns a nullable path. Use it to locate a config file that may live in a parent directory.
A private let ws: Workspace! field with no default is a constructor argument too, and Dagger fills it the same way. Use it to keep the workspace and read from it in each function:
type MyCi {
let ws: Workspace!
lint: Void @check {
container
.from("koalaman/shellcheck-alpine:stable")
.withMountedDirectory("/src", ws.directory("/scripts"))
.withWorkdir("/src")
.withExec(["sh", "-c", "shellcheck *.sh"])
.sync
null
}
}
A function can also take its own Workspace! argument, as myTestEnv does in the generated module.
Relative paths resolve from the workspace cwd, where the user invoked dagger. Absolute paths, which begin with /, resolve from the workspace root.
type MyCi {
source: Directory!
config: File!
new(ws: Workspace!) {
# Absolute: from the workspace root
self.source = ws.directory("/src")
# Relative: from the workspace cwd
self.config = ws.file("tsconfig.json")
self
}
}
ws.directory accepts an exclude list to filter out files you don't need. This matters for caching. Excluding node_modules, .git, build output, and similar paths avoids needless cache invalidations:
type MyCi {
source: Directory!
new(ws: Workspace!) {
self.source = ws.directory("/", exclude: [
"node_modules",
".git",
"dist",
])
self
}
}
Read only what you need. Don't load the whole repo if you only need src/. Read specific paths and use tight exclude lists to keep cache invalidations down. Reads are lazy, so content the module never touches never uploads.
A complete example, modeled on dagger/eslint:
type Eslint {
"""The source directory for the project."""
source: Directory!
baseImageAddress: String!
new(
ws: Workspace!,
baseImageAddress: String! = "node:25-alpine",
) {
self.source = ws.directory("/")
self.baseImageAddress = baseImageAddress
self
}
lint: Void @check {
nodejs(source, baseImageAddress).base.withExec(["npx", "eslint", "."]).sync
null
}
}
Checks, generators, services, directives
Dang has three first-class function types, each run by a verb. Checks and generators are marked with a directive. A service needs no directive. A useful module provides at least one of them:
| Directive | Returns | Run by | Purpose |
|---|---|---|---|
@check | Void | dagger check | Validate something, such as a lint, test, or scan. |
@generate | Changeset | dagger generate | Produce a diff of generated files for review. |
| none | Service! | dagger start | Start a long-running service. |
Checks
A check validates something without requiring arguments. Mark it with @check and dagger check discovers and runs it. A check returns Void and passes if it completes without error. Run the container with .sync: a withExec that exits non-zero fails the check.
type MyCi {
source: Directory!
new(ws: Workspace!) {
self.source = ws.directory("/")
self
}
"""
Lint the code.
"""
lint: Void @check {
container
.from("golangci/golangci-lint:latest")
.withDirectory("/app", source)
.withWorkdir("/app")
.withExec(["golangci-lint", "run"])
.sync
null
}
}
Generators
A generator produces a changeset, a diff between the current source and freshly generated output. Mark it with @generate. .changes(source) computes the diff against the original source. dagger generate runs all generators and presents the combined changeset for review:
generateProto: Changeset! @generate {
container
.from("bufbuild/buf:latest")
.withDirectory("/app", source)
.withWorkdir("/app")
.withExec(["buf", "generate"])
.directory(".")
.changes(source)
}
These
@generategenerators are your module's own code generation pipelines, such as protobuf or OpenAPI. They have nothing to do with SDK client codegen, which Dang does not have.
Services
A service function returns a long-running Service!. dagger start starts every public function that returns Service! and takes no required arguments. Build the service from a container with .asService, and expose the ports it should listen on:
web: Service! {
container
.from("nginx:alpine")
.withExposedPort(80)
.asService
}
A module can expose several services, and dagger start starts each one. This differs from the private let db: Service! { ... } pattern shown under Services above. A let service is internal plumbing, such as a database wired into a check with withServiceBinding. A public service is an entry point that users start directly.
Caching directives
By default Dagger caches function results, keyed by inputs (arguments, parent state, module source). Tune it per function with @cache:
# Cache for 10 minutes (e.g. external data that changes)
latestRelease: String! @cache(ttl: "10m") { ... }
# Cache only for the current session
sessionId: String! @cache(policy: FunctionCachePolicy.PerSession) { ... }
# Never cache (always re-execute)
currentTime: String! @cache(policy: FunctionCachePolicy.Never) { ... }
policy takes a FunctionCachePolicy value: Default, PerSession, or Never. ttl takes a duration string and applies only to the Default policy. A function cache hit skips the function entirely. A miss runs it, but individual operations inside may still hit the layer cache. @cache(policy: FunctionCachePolicy.Never) forces the function to run every call but does not disable layer caching for the operations inside it.
Collections
A collection is a set of objects that a module discovers at run time, each with a unique key: the packages in a repository, the test files in a project, or the scripts in a directory. Return a collection when users should be able to run a check or generator on one item. Dagger adds a flag for each collection to dagger check and dagger generate, and users select items with it. See Select collection items.
Declare a collection
Mark a type with @collection. A collection has two members:
- A keys field, marked
@keys. It is a non-null list of a scalar or enum type, such as[String!]!, and holds one unique key per item. - A get function, marked
@get. It takes one key and returns the item for it.
Without the directives, the members must be named keys and get.
This module discovers the shell scripts in a workspace and lints them with ShellCheck. Scripts is the collection, keyed by path, and Script is the item:
"""
Lint shell scripts with ShellCheck.
"""
type Shellcheck {
"""
Shell scripts in the workspace, keyed by path.
"""
scripts(ws: Workspace!): Scripts! {
let source = ws.directory("/", include: ["**/*.sh"])
Scripts(paths: source.glob("**/*.sh"), source: source)
}
}
"""
Shell scripts, keyed by path.
"""
type Scripts @collection {
"""
Script paths, relative to the workspace root.
"""
paths: [String!]! @keys
let source: Directory!
"""
The script at this path.
"""
script(path: String!): Script! @get {
Script(path: path, source: source)
}
"""
Lint the selected scripts with one ShellCheck run.
"""
lint: Void @check {
container
.from("koalaman/shellcheck-alpine:stable")
.withMountedDirectory("/src", source)
.withWorkdir("/src")
.withExec(["shellcheck"] + paths)
.sync
null
}
}
"""
A shell script.
"""
type Script {
"""
Script path, relative to the workspace root.
"""
path: String!
let source: Directory!
"""
Lint this script.
"""
lint: Void @check {
container
.from("koalaman/shellcheck-alpine:stable")
.withMountedDirectory("/src", source)
.withWorkdir("/src")
.withExec(["shellcheck", path])
.sync
null
}
}
The flag is named after the item type, with the module name in front, so Script in the shellcheck module adds --shellcheck-script. Its placeholder comes from the get function's argument name:
dagger check --shellcheck-script=scripts/deploy.sh
dagger list shellcheck-scripts -a
Batch functions
Callers see the same API on every collection, whatever its type holds:
| Function | Returns |
|---|---|
keys | The keys, in the order the module returned them |
list | Every item |
get | The item with the given key |
subset | A collection of the items with the given keys |
batch | The collection's other functions |
Every other function on the collection is a batch function, reached through batch. Dagger calls it on a copy of the collection whose keys field holds only the selected keys, so paths above lists the scripts the user selected. The collection's other fields are internal to the module.
A batch check or generator replaces the check or generator with the same name on the item type. dagger check --shellcheck calls Scripts.lint once with every script, not Script.lint once per script. A batch function runs once for each parent item: the batch of a collection nested inside another collection's items runs once per parent. Without a batch function of the same name, the item's check runs once per selected item.
Collection delta
A batch function can tell whether the user narrowed the selection. Add a CollectionDelta field marked @delta, or named delta. Dagger fills it before each call with the keys added and removed since the module created the collection:
type Scripts @collection {
paths: [String!]! @keys
"""
Scripts selected in or out since discovery.
"""
selection: CollectionDelta @delta
}
selection!.addedKeys and selection!.removedKeys return the changes. When both are empty, the collection holds every item the module discovered. The Go module uses this to run go test on a whole package when every test is selected, and go test -run with the selected names otherwise.
Testing Dang modules
The most direct way to test a Dang module is to call its functions and run its checks:
# Smoke test. Does it build?
dagger api call my-ci build
# Run all checks
dagger check
# Run generators and verify there's no drift
dagger check --generated=true
For more thorough testing, write a separate test module (in any SDK) that depends on yours, exercises its functions, and asserts on the results.
CI
Wire dagger check into CI. Pin the engine version (see Engine version) for reproducibility:
jobs:
dagger:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: dagger/dagger-for-github@v6
with:
verb: check
dagger check runs every @check function in the module and fails the build if any check fails.
Packaging and release
A Dang module is just source: main.dang, dagger-module.toml, and any extra .dang files. There is no build step. Run dagger generate to update the module configuration before publishing.
To release:
- Commit
dagger-module.toml,main.dang, and any other source files. - Check the engine requirement in the generated
dagger-module.toml. - Tag the repository (
git tag v0.1.0 && git push --tags).
Consumers install your module into their workspace with the dagger CLI:
dagger module install github.com/yourorg/yourrepo/path@v0.1.0
They can then call its functions by its install name (dagger api call <name> ...) and run its checks (dagger check).
Troubleshooting
- Module not found. Check
dagger module list. A module created with--pathneeds a separatedagger module install <path>, or use-m <path>for one command. - SDK not found. Install
dagger.io/sdk/dang, then checkdagger sdk list. - Parser and type errors. Dang reports these straight from the module source. Check the non-null markers (
!), that the last expression in a function body matches the declared return type, and that every custom type and enum name you reference exists. - A type or enum is missing from the API. Only top-level declarations become module types. Move a
type,enum, orinterfaceout of another type's body to the top level of a file. no common type between Severity! and String!. An enum value is not a string. Convert it with a template string, such as`${severity}`."NAME" not foundin a string, or a string that fails to parse. A${...}in a backtick string is a Dang expression, and double quotes hold one line. See Strings.- A
Voidfunction must end innull. AVoidfunction usually calls.syncon a container or service to force evaluation, then returnsnullas its final expression. - Changeset not written.
dagger module init, module client commands, anddagger generatepresent a changeset. Review and apply it to write the files, or pass-yto apply it without the prompt. A headless run fails withinteractive prompts are unavailable in report modeuntil it does. - Stale generation expectations. Dang has no client codegen, so there are no generated bindings to regenerate. If a tutorial tells you to commit generated SDK files, skip that step.