Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
312 changes: 310 additions & 2 deletions .dagger/modules/e2e/main.dang

Large diffs are not rendered by default.

18 changes: 18 additions & 0 deletions .dagger/modules/e2e/tool_wheels.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
from pathlib import Path
from zipfile import ZipFile, ZipInfo

Path('/wheels').mkdir()
for name, version, requirements in [
('conflicting_tool', '0.2.0', ['packaging<25']),
('packaging', '25.0', []),
]:
info = f'{name}-{version}.dist-info'
files = {
f'{info}/METADATA': f'Metadata-Version: 2.1\nName: {name}\nVersion: {version}\n' +
''.join(f'Requires-Dist: {req}\n' for req in requirements),
f'{info}/WHEEL': 'Wheel-Version: 1.0\nRoot-Is-Purelib: true\nTag: py3-none-any\n',
f'{info}/RECORD': '',
}
with ZipFile(f'/wheels/{name}-{version}-py3-none-any.whl', 'w') as wheel:
for path, contents in files.items():
wheel.writestr(ZipInfo(path), contents)
67 changes: 49 additions & 18 deletions mypy/main.dang
Original file line number Diff line number Diff line change
Expand Up @@ -93,9 +93,7 @@ type Mypy {
MypyProjects(
paths: lib
.rootsOwning(ws, ["*.py"])
.map { root => mypyProject(root) }.{{path, skip}}
.filter { project => includeSkipped or project.skip == false }
.map { project => project.path },
.filter { root => includeSkipped or mypyProject(root).skip == false },
tool: self,
)
}
Expand Down Expand Up @@ -207,10 +205,19 @@ type MypyProject {
outside the configured scope, or holds no Python source of its own.
"""
let typeCheckFailure(ws: Workspace!): String {
if (skip or hasSources(ws) == false) {
let inputs = checkInputs(ws, tool.scope)
if (inputs.skip or inputs.hasSources == false) {
null
} else {
{ typeCheckExec(ws).sync; null } rescue {
{
typeCheckExec(
ws,
inputs.version ?? tool.defaultVersion,
filesConfigured(inputs.configKeys.{{exists, hasSection, setsKey}}),
inputs.excludeNestedFlags,
).sync
null
} rescue {
err: Error => err.message.replace(old: "evaluating receiver: ", new: "").replace(
old: "reduce function: ",
new: "",
Expand All @@ -219,20 +226,24 @@ type MypyProject {
}
}

let typeCheckExec(ws: Workspace!): Container! {
let typeCheckExec(
ws: Workspace!,
version: String!,
configured: Boolean!,
excludes: [String!]!,
): Container! {
let project = tool.lib.at(path)
let packages = ["mypy==" + version(ws)]
let packages = ["mypy==" + version]
# A project whose config names its files is checked as configured: a path
# on the command line would override `files` and check everything else.
let targets = if (configuresFiles(ws)) { [] } else { ["."] }
let targets = if (configured) { [] } else { ["."] }
# The environment comes from the library, so the dependency layer
# underneath is the same one pytest and the other checker get.
# The project itself is not installed: the checker reads first-party code
# from the source, so it needs no build backend or compiler.
project.step(
project.env(ws, with: packages, installProject: false),
project.uvRun(packages) + ["mypy"] + tool.args + targets
+ project.excludeNestedFlags(ws, "--exclude", regex: true),
project.uvRun(packages) + ["mypy"] + tool.args + targets + excludes,
"mypy",
)
}
Expand All @@ -243,15 +254,35 @@ type MypyProject {
and setup.cfg ([mypy]) that configures it, and so does this.
"""
configuresFiles(ws: Workspace!): Boolean! {
let project = tool.lib.at(path)
if (project.hasFile(ws, "mypy.ini")) {
project.setsKey(ws, "mypy.ini", "mypy", "files")
} else if (project.hasFile(ws, ".mypy.ini")) {
project.setsKey(ws, ".mypy.ini", "mypy", "files")
} else if (project.fileContents(ws, "pyproject.toml").contains("[tool.mypy]")) {
project.setsKey(ws, "pyproject.toml", "tool.mypy", "files")
filesConfigured(checkInputs(ws).configKeys.{{exists, hasSection, setsKey}})
}

let filesConfigured(
probes: [{{exists: Boolean!, hasSection: Boolean!, setsKey: Boolean!}}!]!,
): Boolean! {
if (probes[0].exists == true) {
probes[0].setsKey ?? false
} else if (probes[1].exists == true) {
probes[1].setsKey ?? false
} else if (probes[2].hasSection == true) {
probes[2].setsKey ?? false
} else {
project.setsKey(ws, "setup.cfg", "mypy", "files")
probes[3].setsKey ?? false
}
}

let checkInputs(ws: Workspace!, scope: [String!]! = ["**"]): PyprojectCheckInputs! {
tool.lib.at(path).checkInputs(
ws,
"mypy",
scope: scope,
configKeys: [
["mypy.ini", "mypy", "files"],
[".mypy.ini", "mypy", "files"],
["pyproject.toml", "tool.mypy", "files"],
["setup.cfg", "mypy", "files"],
],
excludeRegex: true,
)
}
}
28 changes: 28 additions & 0 deletions pyproject/check_environment.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
from pathlib import Path
import re
import subprocess
import sys
import sysconfig
import tempfile

requirements = [req for req in sys.argv[1:] if re.match(
r'^[A-Za-z0-9][A-Za-z0-9._-]*\s*(?:\[[^\]]+\]\s*)?(?:\(\s*)?[<>=!~]', req.strip())]
with tempfile.TemporaryDirectory(prefix='dagger_tools_', suffix='x-0.dist-info', dir=sysconfig.get_path('purelib')) as info:
name = re.sub(r'[-_.]+', '-', Path(info).name[:-len('-0.dist-info')]).lower()
Path(info, 'METADATA').write_text('Metadata-Version: 2.1\nName: '+name+'\nVersion: 0\n'+
''.join('Requires-Dist: '+req+'\n' for req in requirements))
Path(info, 'WHEEL').write_text('Wheel-Version: 1.0\nRoot-Is-Purelib: true\nTag: py3-none-any\n')
Path(info, 'RECORD').touch()
check = subprocess.run(['uv', '--color', 'never', 'pip', 'check', '--python', sys.executable],
capture_output=True, text=True)
if check.returncode not in (0, 1):
sys.exit(check.stdout + check.stderr)
problems = []
for line in (check.stdout + check.stderr).splitlines():
if not line.startswith('The package '):
continue
requested = line.startswith('The package `'+name+'`')
if requested or re.search(r', but `[^`]+` is installed$', line):
problems.append(line.replace('The package `'+name+'` requires', 'The requested tools require'))
if problems:
sys.exit('\n'.join(problems))
133 changes: 117 additions & 16 deletions pyproject/main.dang
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,8 @@ type Pyproject {
# default hardlink install mode falls back to a copy with a warning.
.withEnvVariable("UV_LINK_MODE", "copy")
.withEnvVariable("UV_NO_PROGRESS", "1")
.withEnvVariable("UV_COMPILE_BYTECODE", "1")
.withEnvVariable("PYC_INVALIDATION_MODE", "CHECKED_HASH")
.withDirectory("/usr/local/bin", uvBinary, include: ["uv", "uvx"])
}

Expand Down Expand Up @@ -774,6 +776,51 @@ type PythonProject {
ws.glob(subpath(relativePath)).isEmpty == false
}

"""
Project metadata for a tool run, returned together to avoid a module call
for each source, version, configuration and exclusion probe. Each configKeys
entry names a file, section and key, in that order.
"""
pub checkInputs(
ws: Workspace!,
tool: String!,
scope: [String!]! = ["**"],
sourceGlobs: [String!]! = ["*.py"],
sourcePattern: String! = "",
configKeys: [[String!]!]! = [],
excludeFlag: String! = "--exclude",
excludeRegex: Boolean! = false,
): CheckInputs! {
let skip = selected(scope) == false
CheckInputs(
skip: skip,
hasSources: if (skip or sourceGlobs.isEmpty) { false } else {
hasOwnFiles(ws, sourceGlobs, pattern: sourcePattern)
},
version: if (skip) { null } else { toolVersion(ws, tool) },
configKeys: if (skip) { [] } else {
configKeys.map { probe =>
if (probe.length != 3) {
raise "a config key probe must name a file, section and key"
}
let file = probe[0] ?? ""
let section = probe[1] ?? ""
let key = probe[2] ?? ""
ConfigKeyResult(
exists: hasFile(ws, file),
hasSection: fileContents(ws, file).contains("[" + section + "]"),
setsKey: setsKey(ws, file, section, key),
)
}
},
hasLockfile: if (skip) { false } else { hasFile(ws, "uv.lock") },
nestedProjects: if (skip) { [] } else { nestedProjects(ws) },
excludeNestedFlags: if (skip or excludeFlag == "") { [] } else {
excludeNestedFlags(ws, excludeFlag, regex: excludeRegex)
},
)
}

"""
Built-in workspace include patterns for this project's own tree.

Expand Down Expand Up @@ -868,14 +915,18 @@ type PythonProject {
if (hasFile(ws, "uv.lock")) { ["--locked"] } else { [] }
}

let environmentPython: String! {
(baseImage.envVariable("UV_PROJECT_ENVIRONMENT") ?? ".venv") + "/bin/python"
}

"""
Container with this project's dependencies installed, but not the project
itself or its local path dependencies, from `installInputs` alone.

`with` names extra packages the caller needs on top of the project's own.
They are resolved against the project's environment here, not installed
over the top of a finished one, so a conflict fails here, while building the
environment. `mount` is placed at `mountPath` for an extra package named
They are installed into its environment under constraints from the lockfile,
or the installed dependencies when there is no lock, so a conflict fails
while building the environment. `mount` is placed at `mountPath` for an extra package named
by path, after the dependency sync, so every tool shares that layer.
"""
dependencies(
Expand All @@ -893,13 +944,28 @@ type PythonProject {
["uv", "sync"] + syncFlags(ws) + ["--no-install-workspace", "--no-install-local"],
"environment",
)
let mounted = if (mount == null) { synced } else {
synced.withDirectory(mountPath, mount)
}
if (with.isEmpty) {
mounted
if (mount == null) { synced } else { synced.withDirectory(mountPath, mount) }
} else {
step(mounted, uvRun(with) + ["python", "-c", ""], "environment")
let constraints = "/tmp/dagger-python-constraints.txt"
let constrained = step(
synced,
if (hasFile(ws, "uv.lock")) {
["uv", "export", "--frozen", "--no-hashes", "--no-emit-project",
"--no-emit-workspace", "--no-emit-local", "--output-file", constraints]
} else {
["sh", "-c", "uv pip freeze --python \"$1\" > \"$2\"", "sh", environmentPython, constraints]
},
"environment",
)
let mounted = if (mount == null) { constrained } else {
constrained.withDirectory(mountPath, mount)
}
step(
mounted,
["uv", "pip", "install", "--python", environmentPython, "--constraint", constraints] + with,
"environment",
)
}
}

Expand All @@ -921,6 +987,8 @@ type PythonProject {
project's build backend nor a compiler for a native extension, and a
source edit rebuilds nothing. Its uv workspace members and path sources are
still installed, when it has any, since its imports of them resolve there.

Installing the project must leave the extra tools' dependencies compatible.
"""
env(
ws: Workspace!,
Expand All @@ -929,25 +997,37 @@ type PythonProject {
mountPath: String! = "/opt/extra",
installProject: Boolean! = true,
): Container! {
# uv sync recompiles all site-packages, including unchanged dependencies.
# Their bytecode is already cached; project code can compile on import.
let sourced = dependencies(ws, with: with, mount: mount, mountPath: mountPath)
.withEnvVariable("UV_COMPILE_BYTECODE", "0")
.withWorkdir("/ws")
.withDirectory(".", source(ws))
.withWorkdir(path)
if (installProject) {
step(sourced, ["uv", "sync"] + syncFlags(ws), "environment")
} else if (hasLocalDependencies(ws)) {
step(sourced, ["uv", "sync"] + syncFlags(ws) + ["--no-install-project"], "environment")
let local = hasLocalDependencies(ws)
let installed = if (installProject) {
step(sourced, ["uv", "sync"] + syncFlags(ws) + ["--inexact"], "environment")
} else if (local) {
step(sourced, ["uv", "sync"] + syncFlags(ws) + ["--inexact", "--no-install-project"], "environment")
} else {
sourced
}
if (with.isEmpty == false) {
# Missing dependencies are ignored because sync omits packages deliberately;
# extras-only conflicts are undetected, and requested-version checks skip URLs/paths.
step(installed.withFile("/tmp/check_environment.py", currentModule.source.file("check_environment.py")),
[environmentPython, "-I", "-B", "/tmp/check_environment.py"] + with, "environment")
} else {
installed
}
}

"""
The start of a `uv run` command for a tool in `env`: no re-sync, and the
extra packages `env` already resolved.
extra packages `env` already installed.
"""
uvRun(packages: [String!]!): [String!]! {
["uv", "run", "--no-sync"] + withFlags(packages)
["uv", "run", "--no-sync"]
}

"""
Expand Down Expand Up @@ -980,8 +1060,7 @@ type PythonProject {
"""
`--with` flags naming extra packages for a uv invocation.

A caller runs its own command with the same flags, against the resolution
`env` already made and cached.
Tools installed by `env` need only `uvRun`.
"""
withFlags(packages: [String!]!): [String!]! {
packages.reduce([]) { flags, package => flags + ["--with", package] }
Expand Down Expand Up @@ -1198,3 +1277,25 @@ type PythonProject {
}
}
}

"""
Values a tool needs to select, configure and run a project.
"""
type CheckInputs {
skip: Boolean!
hasSources: Boolean!
version: String
configKeys: [ConfigKeyResult!]!
hasLockfile: Boolean!
nestedProjects: [String!]!
excludeNestedFlags: [String!]!
}

"""
The presence of a configuration file, section and key.
"""
type ConfigKeyResult {
exists: Boolean!
hasSection: Boolean!
setsKey: Boolean!
}
Loading