24 Commits
Author SHA1 Message Date
nandi f14a1900af Add debug build and install recipes
Rolling Release / build (push) Successful in 1m51s
Rolling Release / publish (push) Successful in 9s
- Add build-debug for a faster, unoptimised native build
- Add install-debug to install that build to ~/.local/bin
- Move the PATH setup into a _path recipe shared by both installs
2026-12-01 15:10:57 -08:00
nandi a00c87bf04 Show info for packages that aren't installed
Rolling Release / build (push) Successful in 1m49s
Rolling Release / publish (push) Successful in 8s
- `orbit info` finds a package that isn't installed, or a `channel::` / `@constraint` build, in the cached channel listings used by search
- Channel indexes record each version's manifest digest, so a repeated info needs no network
- Versions without a digest, or indexes built before digests were added, are resolved in the registry
- Show the docs link, channel, digest, bins and dependencies for available builds
2026-12-01 14:39:13 -08:00
nandiandClaude Opus 5.5 022898ed65 Lock hello from the example channel
Rolling Release / build (push) Successful in 2m0s
Rolling Release / publish (push) Successful in 8s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 06:01:02 -08:00
nandi a91f832f41 Declare hello from the example channel and add backlog collection
Rolling Release / build (push) Successful in 1m54s
Rolling Release / publish (push) Successful in 9s
- Pin the example project's `hello` dependency to the `example` channel in orbit.toml, matching `greet`
- Update the example project README to describe both dependencies as coming from `example`
- Add MEANS.md as the planning backlog collection and ignore `.means/` in .gitignore
2026-12-01 05:55:56 -08:00
nandiandClaude Opus 5.5 fec3c120f4 Move hello to the example channel
Rolling Release / build (push) Canceled after 0s
Rolling Release / publish (push) Canceled after 0s
The smoke test installs means instead, the smallest package left in main.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 05:54:51 -08:00
nandiandClaude Opus 5.5 58e271967b Show list as the same table as search
Rolling Release / build (push) Successful in 1m48s
Rolling Release / publish (push) Successful in 9s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 05:54:43 -08:00
nandiandClaude Opus 5.5 abd0dfca1e Show package details on install
Rolling Release / build (push) Successful in 1m39s
Rolling Release / publish (push) Successful in 8s
Installs, syncs and upgrades print each new build's paths, bins and
dependencies. orbit info prints the same, also for a project's packages.

Planning: y4x2r

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 05:30:41 -08:00
nandiandClaude Opus 5.5 cc47acb3e2 Add package conflicts
Rolling Release / build (push) Successful in 1m41s
Rolling Release / publish (push) Successful in 9s
Packages can declare conflicts in orbit.json. The solver keeps them apart,
and a global install offers to replace the installed ones in the way.
Rollback now checks for clashes before it unlinks anything.

Planning: 8m9kt

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 05:29:25 -08:00
nandiandClaude Opus 5.5 6d35f207fd Move the means package to orbit-packages
Rolling Release / build (push) Successful in 1m46s
Rolling Release / publish (push) Successful in 9s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 05:11:15 -08:00
nandiandClaude Opus 5.5 47a80fad04 Cache channel listings for search
Rolling Release / build (push) Successful in 1m46s
Rolling Release / publish (push) Successful in 9s
Search keeps each channel's list for an hour, so a repeat needs no
network, and uses the old copy with a warning if the registry fails.
`--refresh` skips the cache; publish, index, login and logout drop it.

A test command no longer writes to stdout, where it could corrupt the
test runner's results.

Planning: bnbr1

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 05:04:06 -08:00
nandiandClaude Opus 5.5 8f202290b9 Add a script to package means
Rolling Release / build (push) Successful in 1m41s
Rolling Release / publish (push) Successful in 9s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 05:02:07 -08:00
nandiandClaude Opus 5.5 ec0b6eaa0f Add --version
Rolling Release / build (push) Successful in 1m47s
Rolling Release / publish (push) Successful in 8s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 04:58:11 -08:00
nandiandClaude Opus 5.5 dfda555f9b Track the backlog with means
Rolling Release / build (push) Successful in 1m42s
Rolling Release / publish (push) Successful in 9s
Same setup as chattocorp/geordi: a planning/ collection, an MCP server for
agents, and AGENTS.md pointing at it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 04:56:36 -08:00
nandiandClaude Opus 5.5 e2f0ac27e1 Don't warn when an anonymous read succeeds
Rolling Release / build (push) Successful in 1m49s
Rolling Release / publish (push) Successful in 9s
A rejected login is now an error when it matters and silent otherwise.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 04:47:41 -08:00
nandiandClaude Opus 5.5 c8d7f59633 Upload large layers in chunks
Rolling Release / build (push) Successful in 1m54s
Rolling Release / publish (push) Successful in 8s
A registry's ingress can cut off one long request; moonbit-orbit needed a
separate uploader for that.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 21:00:37 -08:00
nandiandClaude Opus 5.5 4271a084b6 Give each channel a package index
Rolling Release / build (push) Successful in 1m48s
Rolling Release / publish (push) Successful in 9s
orbit-index:latest in a channel lists its packages. Search reads it and
falls back to the catalog; publish keeps it current and 'orbit index'
rebuilds it. Installs never use it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 20:48:31 -08:00
nandiandClaude Opus 5.5 2026319f61 Read anonymously when a saved login is rejected
Rolling Release / build (push) Successful in 1m38s
Rolling Release / publish (push) Successful in 8s
A stale login made every read fail, and search blamed the registry for
it. Reads now warn and retry without the login; publishing never does.
A refused or missing package after the fallback reports the rejected
login, so a private package can't be replaced from a lower channel.

Search shows the real error, and the README no longer says Gitea lacks
the catalog API.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 20:35:29 -08:00
nandiandClaude Opus 5.5 83e694c6c4 Prove the semver and solver kernel instead of testing it
Rolling Release / build (push) Successful in 1m39s
Rolling Release / publish (push) Successful in 8s
Move number parsing, version ordering and constraints, version sorting and
solver literals into src/kernel, with contracts checked by moon prove under
overflow-checked integers. Replace the semver behaviour tests with those
proofs, keep tests for string parsing, and run the proofs in CI.

Version numbers are now 64-bit: the old parser silently wrapped at 2^31.
Drop pick_tag, which only tests called.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 16:56:21 -08:00
nandiandClaude Opus 5.5 2d815bbb75 Add rolling release built with Zig's musl toolchain
Rolling Release / build (push) Successful in 1m40s
Rolling Release / publish (push) Successful in 8s
Build a static Linux x86_64 binary with zig cc, linking OpenSSL in and
serving it to moonbitlang/async through a dlopen shim. CI publishes it to
the rolling release on every push to main.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 16:50:10 -08:00
nandi 3ca9e8ed1d Add example project with locked dependencies and tasks
- Add examples/project with orbit.toml declaring hello and greet (example channel)
- Pin resolved versions and digests in orbit.lock
- Add demo.sh and a demo task that calls hello and greet from .orbit/bin
- Ignore the generated .orbit/ directory and document usage in its README
- Link the example from the main README
2026-11-28 12:13:00 -08:00
nandi 13aa7d7f77 Add Pixi-style project environments and SAT dependency solver
- Add orbit.toml project manifests, deterministic orbit.lock files, [tasks], and `orbit run`
- Add per-project .orbit/bin environments; `-g`/`--global` targets the global environment
- Replace greedy global resolution with a lazy CDCL SAT solver that explains conflicts
- Support channel::pkg dependency pins and comma-separated, comparison, and wildcard constraints
- Cache immutable sha256 manifests under ~/.orbit/cache/manifests
- Validate dependency keys and constraints in orbit.json
2026-11-28 01:43:04 -08:00
nandi 0919ce105c Replace oras with native OCI registry client and add login
- Talk to OCI Distribution v2 registries directly over HTTP/TLS; oras is no longer required on PATH
- Add `orbit login <host>` and `orbit logout <host>`; credentials go to $ORBIT_ROOT/auth.json (mode 0600)
- Fall back to Docker config (credHelpers and credsStore) when no Orbit credentials exist
- Verify layer downloads with streaming SHA-256
- Fall back to the next channel only on HTTP 404 instead of matching oras error text
- Update README and moon.mod to drop oras references
2026-11-27 15:46:41 -08:00
nandi f8c9b99ee3 Add orbit SVG favicon
- Add a 64x64 favicon.svg with the orbit logo mark
- Use a dark slate background with violet orbit rings
2026-11-27 13:14:25 -08:00
nandi e9e51459dc Merge pull request 'Show package before channel in orbit search' (#7) from search-columns into main 2026-11-27 21:11:23 +00:00
57 changed files with 10765 additions and 613 deletions

No files matched your search

+110
View File
@@ -0,0 +1,110 @@
name: Rolling Release
on:
push:
branches: [main]
pull_request:
workflow_dispatch:
# Never cancelled, so a newer push can't interrupt a release half way.
concurrency:
group: rolling-${{ github.ref }}
cancel-in-progress: false
permissions:
contents: read
env:
MOONBIT_VERSION: 0.10.20+65efd5b93
Z3_VERSION: 5.3.3
Z3_SHA256: d56f60b06f432f33de5810f7f1a384a339131f361e2d54d08ea83eea14326880
ZIG_VERSION: 0.17.1
ZIG_SHA256: 3581863e3cbcfd0fce0efc682ce7e9e93da96668a977791d356a26d2a7e9b17a
jobs:
build:
runs-on: depot-ubuntu-24.04-4
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
- name: Install build tools
run: |
missing=
for tool in gcc make perl readelf curl xz; do
command -v "$tool" >/dev/null || missing=1
done
if [ -n "$missing" ]; then
sudo apt-get update -qq
sudo apt-get install -y -qq --no-install-recommends build-essential perl curl xz-utils >/dev/null
fi
- name: Install MoonBit
run: |
curl -fsSL --retry 5 https://cli.moonbitlang.com/install/unix.sh | bash -s -- "$MOONBIT_VERSION"
echo "$HOME/.moon/bin" >> "$GITHUB_PATH"
"$HOME/.moon/bin/moon" update
"$HOME/.moon/bin/moon" version --all
- name: Install Zig
run: |
curl -fsSL --retry 5 -o "$RUNNER_TEMP/zig.tar.xz" \
"https://ziglang.org/download/$ZIG_VERSION/zig-x86_64-linux-$ZIG_VERSION.tar.xz"
echo "$ZIG_SHA256 $RUNNER_TEMP/zig.tar.xz" | sha256sum -c -
tar -xJf "$RUNNER_TEMP/zig.tar.xz" -C "$RUNNER_TEMP"
echo "$RUNNER_TEMP/zig-x86_64-linux-$ZIG_VERSION" >> "$GITHUB_PATH"
- name: Test
run: moon test --target native
# Proofs replace tests of src/kernel. The override checks for overflow;
# `just prove` runs the same command.
- name: Prove
run: |
z3="z3-$Z3_VERSION-x64-glibc-2.39"
curl -fsSL --retry 5 -o "$RUNNER_TEMP/z3.zip" \
"https://github.com/Z3Prover/z3/releases/download/z3-$Z3_VERSION/$z3.zip"
echo "$Z3_SHA256 $RUNNER_TEMP/z3.zip" | sha256sum -c -
python3 -m zipfile -e "$RUNNER_TEMP/z3.zip" "$RUNNER_TEMP"
chmod +x "$RUNNER_TEMP/$z3/bin/z3"
export Z3PATH="$RUNNER_TEMP/$z3/bin/z3"
export MOON_PROVE_PRELUDE_OVERRIDE="$HOME/.moon/lib/prelude_proof_machine_int"
moon prove src/kernel
- name: Build static binary
run: scripts/build-musl.sh
# A real HTTPS install: proves the linked-in OpenSSL and CA lookup work.
- name: Smoke test
run: |
export ORBIT_ROOT="$RUNNER_TEMP/orbit-smoke"
dist/orbit-linux-x86_64 install means
"$ORBIT_ROOT/bin/means" version
- uses: actions/upload-artifact@v3
with:
name: orbit-linux-x86_64
path: dist/
if-no-files-found: error
publish:
needs: build
if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main'
runs-on: depot-ubuntu-24.04
timeout-minutes: 10
permissions:
contents: write
steps:
- uses: actions/checkout@v4
- uses: actions/download-artifact@v3
with:
name: orbit-linux-x86_64
path: dist/
- name: Publish rolling release
env:
GITEA_TOKEN: ${{ github.token }}
run: |
(cd dist && sha256sum -c SHA256SUMS)
python3 scripts/publish-rolling.py
+2
View File
@@ -1,3 +1,5 @@
target/
.mooncakes/
_build/
dist/
.means/
+8
View File
@@ -0,0 +1,8 @@
{
"mcpServers": {
"planning": {
"command": "means",
"args": ["mcp", "--path", "./planning"]
}
}
}
+13
View File
@@ -0,0 +1,13 @@
# Orbit
A package manager in MoonBit that uses OCI registries as its repository. See
`README.md` for an overview, the source layout, and build commands.
## Before you start
- **Backlog:** list and read relevant items in `planning/` (a
[means](https://github.com/hmans/means) collection) and track progress there.
Use the `planning` MCP server when available (call `info` for schema and
workflow); otherwise `means info --path ./planning`.
Before finishing a task: `just test && means doctor --path ./planning`.
Symlink
+1
View File
@@ -0,0 +1 @@
AGENTS.md
+16
View File
@@ -0,0 +1,16 @@
---
title: orbit
schema:
$schema: https://json-schema.org/draft/2020-12/schema
type: object
properties:
tags:
type: array
description: Labels used to organize and find the document.
items:
type: string
additionalProperties: false
---
# Collection guidance
Describe this collection and its workflow here.
+157 -24
View File
@@ -1,19 +1,21 @@
# orbit
A small package manager written in MoonBit that uses any OCI registry (Gitea, GHCR, Harbor, `registry:2`, ...) as its repository, with [ORAS](https://github.com/oras-project/oras) as the transport.
A small package manager written in MoonBit that uses any OCI registry (Gitea, GHCR, Harbor, `registry:2`, ...) as its repository, speaking the OCI Distribution v2 protocol directly over HTTP/TLS.
> **Status:** builds cleanly (no warnings) with MoonBit `moonc v1.0.0-rc1` / `moon 0.1.20261126`, and the unit tests pass. publish, install (with dependencies), upgrade, rollback, remove and gc have been exercised end to end against a local `registry:2` with ORAS 1.2.3.
> **Status:** builds cleanly (no warnings) with MoonBit `moonc v1.0.0-rc1` / `moon 0.1.20261126`, and the unit tests pass. publish, install (with dependencies), upgrade, rollback, remove and gc have been exercised end to end against a local `registry:2` and Gitea.
## What it does
- **Publish:** `orbit publish <dir>` packs `<dir>/files/` into `pkg.tar.gz` and pushes it with `<dir>/orbit.json` as the OCI config blob.
- **Install with dependencies:** it reads only the small config blob (`oras manifest fetch-config`) to plan, then pulls the layers by digest.
- **Version constraints:** `1.2.3`, `1.2`, `^1.2.0`, `~1.2.0`, `>=1.2`, `*`. Prereleases match only when the constraint asks for one.
- **Content-addressed store:** packages unpack into `~/.orbit/store/<name>/<digest>/`, and their binaries are symlinked into `~/.orbit/bin/`.
- **Lazy CDCL SAT solver:** resolves global and project dependency graphs with backtracking, conflict explanations, and `channel::pkg` dependency pins, reading only needed config blobs and caching immutable `sha256` manifests under `~/.orbit/cache/manifests/`.
- **Pixi-style project environments:** `orbit new`, `orbit.toml` manifests, deterministic `orbit.lock` lockfiles, `[tasks]`, `orbit run`, and isolated `.orbit/bin/` environments symlinked from the shared store (`-g` / `--global` targets the global environment inside a project).
- **Version constraints:** `1.2.3`, `=1.2.3`, `==1.2.3`, `1.2`, `1.2.*`, `^1.2.0`, `~1.2.0`, `>=1.2`, `<=2.0`, `>1.0`, `<2.0`, `!=1.3.0`, `*`, and comma-separated ranges (`>=1.2.0, <2.0.0`). Prereleases match only when the constraint mentions a `-`.
- **Content-addressed store:** packages unpack into `~/.orbit/store/<name>/<digest>/`, and their binaries are symlinked into `~/.orbit/bin/` (global) or `<project>/.orbit/bin/` (project).
- **File ownership:** two packages can't provide the same binary.
- **Upgrade and rollback:** the previous two builds are kept, and `orbit rollback <name>` switches back instantly with no network.
- **Remove:** `orbit remove` refuses to delete what other packages need, then autoremoves orphaned dependencies.
- **gc** deletes builds that are neither current nor kept for rollback.
- **Conflicts:** packages can declare that they can't be installed together, and a global install offers to replace the one in the way.
- **Upgrade and rollback:** global installs keep the previous two builds, and `orbit rollback <name>` switches back instantly with no network.
- **Remove:** `orbit remove` refuses to delete what other global packages need and autoremoves orphaned dependencies; in projects it updates `orbit.toml` and `orbit.lock`.
- **gc** deletes store builds that are neither globally current nor kept for rollback.
## Package format
@@ -43,31 +45,119 @@ In a channel this becomes `<channel url>/mytool:1.4.0`, plus the `latest` tag. T
| config | `application/vnd.latha.orbit.config.v1+json` (`orbit.json`, with OCI labels for package-page metadata) |
| layer `pkg.tar.gz` | `application/vnd.latha.orbit.layer.v1.tar+gzip` |
### Conflicts
`conflicts` names packages that can't be installed beside this one, with the
versions it applies to (`*` for all):
```json
{
"name": "mytool-nightly",
"version": "1.5.0",
"bin": ["bin/mytool"],
"conflicts": { "mytool": "*", "oldplugin": "<2.0.0" }
}
```
- Only one of the two packages has to declare it, and the named package need not exist.
- Unlike dependencies, a conflict covers prereleases without naming one. It applies to a package name in any channel.
- The solver looks for versions that don't conflict, and explains the conflict if there are none.
- If a global `orbit install` can't be satisfied beside the installed packages, it asks before removing the ones it conflicts with. Without a terminal it fails unless you pass `--replace`. It never removes a package that another one needs, and downloads everything before removing anything.
- `orbit upgrade` and project commands never replace packages. In a project, `orbit remove` the old one first.
- `orbit rollback` refuses a build that conflicts with an installed package.
- Orbit versions from before this field ignore it, and can't read an `orbit.lock` that contains it.
### Registry details
The optional `description` and `documentation` fields supply Gitea's **About**
text and **Documentation** link. Use a public or otherwise accessible HTTP(S)
URL for the link. Gitea does not render a bundled README inline, but you can
ship one under `files/share/doc/<name>/README.md`, as the `greet` example does.
Layers over 4 MiB are uploaded in 4 MiB pieces, so a proxy's limit on one request doesn't stop a large package.
Because these are ordinary OCI artifacts, you can sign them with `cosign` or `notation` and attach SBOMs using the registry's own tooling.
### Channel index
A channel can hold an index of its packages at `<channel url>/orbit-index:latest` (the name is reserved), so `orbit search` takes two requests per channel, matches descriptions too, and needs no catalog API. Each namespace (a Gitea user or organisation) has its own index, written by whoever can publish there. A nested channel such as `nandi/example` is separate from `nandi`. Without an index, search asks the registry's catalog.
The manifest has `artifactType` `application/vnd.latha.orbit.index.v1` and one JSON layer (`application/vnd.latha.orbit.index.v1+json`):
```json
{"packages":[{"name":"mytool","version":"1.4.0","description":"...","versions":["1.4.0"],"digest":"sha256:..."}]}
```
- `orbit publish` adds the package to the index, and creates the index from the catalog if there is none. `--no-index` skips this.
- `orbit index [--channel <name>]` rebuilds it from the catalog. Use it after deleting a package, or if two publishes ran at once and one entry was lost. On a registry without a catalog, name the packages: `orbit index mytool othertool`.
- `digest` is the manifest digest of `version`. Indexes built before it was added lack it; `orbit index` adds it.
- Installs and version lookups never read the index, so a stale one can't change what is installed.
- Search and `orbit info` keep a copy of each channel's list in `~/.orbit/cache/indexes/` and use it for an hour without touching the network. After that it fetches the list again, or uses the old copy with a warning if the registry can't be reached. `orbit search --refresh` fetches now. Your own `publish`, `index`, `login` and `logout` drop the copies they affect. A channel without an index is cached too, if it has at most 100 repositories.
- The index is built with the publisher's login. On a registry where packages in one namespace can be private while others are public, a public index reveals the private names, descriptions and versions. Gitea sets visibility per owner, so this doesn't apply there.
## Usage
### Global environment
```sh
oras login git.site.latha.org # once, with a Gitea token (needed to publish)
orbit login git.site.latha.org # once, with a Gitea token (needed to publish)
eval "$(orbit env)"
orbit publish examples/hello
orbit install hello
orbit channel add example git.site.latha.org/nandi/example # once
orbit publish examples/hello --channel example
orbit install example::hello
hello # -> hello from orbit
orbit upgrade
orbit rollback hello
orbit remove hello
```
### Project workflow (Pixi-style)
Inside a directory with `orbit.toml` (or pass `--manifest-path <path>`), commands target the project unless you pass `-g` / `--global`:
```sh
orbit new myapp && cd myapp
orbit add example::hello example::greet
orbit run greet
orbit lock --update
orbit install --locked
orbit update
orbit remove hello
```
An `orbit.toml` looks like:
```toml
[project]
name = "myapp"
version = "0.1.0"
channels = ["example", "main"]
[[channels]]
name = "example"
url = "git.site.latha.org/nandi/example"
[dependencies]
hello = { version = "^1.0.0", channel = "example" }
greet = { version = ">=1.0.0, <2.0.0", channel = "example" }
[tasks]
hi = "greet"
```
See [examples/project](examples/project/README.md) for a working example project using `example::hello` and `example::greet`.
Credentials are stored in `~/.orbit/auth.json` (`$ORBIT_ROOT/auth.json`, mode `0600`). Orbit also falls back to `~/.docker/config.json` (`$DOCKER_CONFIG/config.json`) including `credHelpers` and `credsStore`. Use `orbit logout <host>` to remove stored credentials from Orbit.
If a registry rejects the saved login, Orbit reads anonymously without a message, so public packages still work. Publishing always needs a valid login. When an anonymous read is refused or finds nothing, Orbit reports the rejected login instead of moving to the next channel, because the package may be private.
## Channels
Packages come from **channels**, which work like channels in pixi. A channel is a name for a registry namespace. The built-in `main` channel is `git.site.latha.org/nandi`, so no setup is needed.
The packages in `main` are built by [orbit-packages](https://git.site.latha.org/nandi/orbit-packages), whose CI follows their upstreams.
Add your own in `~/.orbit/config.toml` (`$ORBIT_ROOT/config.toml`), highest priority first. [examples/config.toml](examples/config.toml) adds the `example` channel:
```toml
@@ -105,11 +195,34 @@ docker run -d -p 5000:5000 registry:2
orbit channel add local localhost:5000/pkgs --plain-http
```
## Rolling release
Every push to `main` that passes the tests replaces the
[`rolling` release](https://git.site.latha.org/nandi/orbit/releases/tag/rolling)
with a static Linux x86_64 binary. It doesn't need glibc or OpenSSL, only `tar`,
`/bin/sh`, and the system's CA certificates (`ca-certificates` on most distros;
set `SSL_CERT_FILE` if they live somewhere unusual).
```sh
base=https://git.site.latha.org/nandi/orbit/releases/download/rolling
curl -fLO "$base/orbit-linux-x86_64" -fLO "$base/SHA256SUMS" &&
sha256sum -c SHA256SUMS &&
install -Dm755 orbit-linux-x86_64 ~/.local/bin/orbit
```
`just build-musl` makes the same binary locally in `dist/`. It needs `zig`,
`perl`, `make`, and `curl`. [scripts/build-musl.sh](scripts/build-musl.sh) compiles
MoonBit's C output and a pinned OpenSSL with `zig cc -target x86_64-linux-musl`.
`moonbitlang/async` normally loads OpenSSL with `dlopen`, which static binaries
can't do, so [openssl_static.c](scripts/musl/openssl_static.c) supplies the
linked-in functions instead.
## Building
```sh
moon build --target native --release
moon test --target native # semver / manifest unit tests
moon test --target native # unit and mock-registry tests
just prove # proofs of src/kernel (needs an SMT solver: z3, cvc5 or alt-ergo)
# the binary is _build/native/release/build/main/main.exe
```
@@ -119,7 +232,7 @@ isn't already there. Open a new Bash shell or run `source ~/.bashrc` to pick
up the change in your current shell. `~/.local/bin` must already be on `PATH`
to run `orbit` itself by name.
Linux only for now: arguments come from `/proc/self/cmdline`. It needs `oras`, `tar` and `/bin/sh` on `PATH`.
Linux only for now: arguments come from `/proc/self/cmdline`. It needs `tar` and `/bin/sh` on `PATH`.
### Package Orbit with Orbit
@@ -131,10 +244,10 @@ package_dir=$(sh scripts/package-orbit.sh) &&
_build/native/release/build/main/main.exe publish "$package_dir"
```
This publishes to the `main` channel (use `--channel <name>` for another), so log in with `oras login <host>` first if needed. The
This publishes to the `main` channel (use `--channel <name>` for another), so log in with `orbit login <host>` first if needed. The
package contains a native Linux binary for the build machine's architecture.
Use the same architecture on the install machine. `oras` and `tar` are still
system prerequisites; the package does not bundle them.
Use the same architecture on the install machine. `tar` is still a
system prerequisite; the package does not bundle it.
To bootstrap from source, install the published package with the binary you just
built. After adding Orbit's bin directory to `PATH`, use the installed binary
@@ -150,18 +263,38 @@ orbit upgrade orbit
## Layout
`src/kernel/` holds the code whose behaviour is proved rather than tested: number
parsing, version ordering and constraints, sorting, and solver literals. See its
[README](src/kernel/README.md).
```
src/main/
stub.c C glue: system(), popen(), file read/write, getenv, exit
sys.mbt FFI bindings, UTF-8, string helpers, shell quoting
semver.mbt versions, constraints, tag selection (+ tests)
stub.c C glue: time, termios echo toggle, getenv, symlink, stderr, exit
sys.mbt FFI bindings, UTF-8, string helpers, spinner, atomic writes
sha256.mbt streaming FIPS 180-4 SHA-256 (+ tests)
auth.mbt credentials store (~/.orbit/auth.json + Docker config fallback)
oci.mbt OCI Distribution v2 HTTP transport, Bearer/Basic auth, redirects
semver.mbt versions, relational/compound constraints, parsing over src/kernel (+ tests)
model.mbt orbit.json / state.json / config.json (+ tests)
registry.mbt oras wrappers: tags, resolve, fetch-config, pull, push
ops.mbt dependency planner, install/remove/upgrade/rollback/gc
registry.mbt OCI registry ops: tags, resolve, cached manifests, fetch, publish, login
index.mbt channel index: build, publish, read (+ tests)
index_cache.mbt local copies of channel listings for search and info (+ tests)
details.mbt package details shown by install and info (+ tests)
solver.mbt lazy Resolvo-style CDCL SAT solver & UNSAT explainer (+ tests)
ops.mbt SAT-backed global install/upgrade, remove/rollback/gc/search
project.mbt orbit.toml, orbit.lock, .orbit/ environments, project CLI (+ tests)
conflicts.mbt declared conflicts, replacing installed packages (+ tests)
channels.mbt config.toml, channel priority and lookup (+ tests)
main.mbt CLI
registry_wbtest.mbt mock-OCI registry, SAT global, and project workflow tests
```
## Planning
The backlog lives in [`planning/`](planning/), managed with
[means](https://github.com/hmans/means). Browse it with
`means tui --path ./planning`.
## Toolchain notes
Fixes needed for current MoonBit, kept here in case you build with an older compiler:
@@ -173,7 +306,7 @@ Fixes needed for current MoonBit, kept here in case you build with an older comp
## Known limits
- Dependency resolution is greedy (highest satisfying version, first come), not a SAT solver.
- There's no lock file for concurrent runs, and no install hooks, by design.
- `orbit info <name>` reads installed package details without contacting the registry. Use `orbit versions <name>` to check published versions.
- `search` needs the registry's catalog API, which Gitea doesn't expose. Use `orbit versions <name>` if you already know the package name.
- `orbit gc` only preserves global current and rollback builds (run `orbit install` / `orbit sync` in a project to re-populate missing store entries from its `orbit.lock`).
- `orbit info <name>` reads installed package details (the project's, then the global ones) without contacting the registry. A package that isn't installed, or `orbit info [channel::]<name>@<constraint>` for another build, is looked up in the same cached channel listings as `orbit search`: it shows the newest version's description, documentation link, digest, bins, dependencies and conflicts. With the digest from the index and the config blob in the manifest cache, a repeated `info` needs no network; another version, or an index without digests, is resolved in the registry. Use `orbit versions <name>` to list published versions.
- `search` needs a channel index or the registry's catalog API (Gitea has it, also without a login). Otherwise use `orbit versions <name>`.
+1 -2
View File
@@ -1,8 +1,7 @@
# greet
`greet` is an example Orbit package from the `example` channel. It installs a
small greeting command and depends on `hello` from the built-in `main`
channel.
small greeting command and depends on `hello` from the same channel.
- [Installation and usage](files/share/doc/greet/README.md)
- [Package on Gitea](https://git.site.latha.org/nandi/-/packages/container/example%2Fgreet/latest)
@@ -1,8 +1,7 @@
# greet
`greet` is a small Orbit package that demonstrates installing from a custom
channel. It depends on the `hello` package from Orbit's built-in `main`
channel.
channel. It depends on the `hello` package from the same channel.
```sh
# Add the example channel once.
+1
View File
@@ -0,0 +1 @@
.orbit/
+26
View File
@@ -0,0 +1,26 @@
# orbit-demo
An example project whose dependencies (`hello` and `greet`, both from the `example` channel) are declared in [orbit.toml](orbit.toml) and pinned in [orbit.lock](orbit.lock).
## Files
- `orbit.toml` — declares the `example` channel, dependencies (`greet` and `hello`), and `[tasks]`.
- `orbit.lock` — deterministic lockfile generated by `orbit lock`.
- `demo.sh` — script invoked by the `demo` task that calls `hello` and `greet` from `.orbit/bin/`.
- `.gitignore` — ignores the generated `.orbit/` environment directory.
## Usage
From this directory:
```sh
orbit install --locked # sync .orbit/ from orbit.lock
orbit list # show locked project packages
orbit run --locked demo # run demo.sh with .orbit/bin on PATH
orbit run --locked greet # run the greet task
orbit run --locked hello # run the hello task
orbit update # resolve newer versions allowed by orbit.toml
eval "$(orbit env)" # put .orbit/bin on PATH in your current shell
```
Or from the repository root with `--manifest-path examples/project`.
+6
View File
@@ -0,0 +1,6 @@
#!/bin/sh
set -eu
echo "Project: ${ORBIT_PROJECT:-$(pwd)}"
echo " hello -> $(hello)"
echo " greet -> $(greet)"
+30
View File
@@ -0,0 +1,30 @@
# Generated by orbit. Do not edit by hand.
version = 1
[[channels]]
name = "main"
url = "git.site.latha.org/nandi"
[[channels]]
name = "example"
url = "git.site.latha.org/nandi/example"
[[package]]
name = "greet"
version = "1.0.1"
channel = "example"
url = "git.site.latha.org/nandi/example"
digest = "sha256:72f32cfa2800376cf49813e86b5ee99a853c972842e2df72e82447bd825abdb9"
description = "Example package for the example channel"
bin = ["bin/greet"]
depends = { hello = "^1.0.0" }
[[package]]
name = "hello"
version = "1.0.0"
channel = "example"
url = "git.site.latha.org/nandi/example"
digest = "sha256:d4b1df993be52b2f1662bc8ace8a7187b17b713f1da6a17b0cc92abc76dd9b08"
description = "Example orbit package"
bin = ["bin/hello"]
+18
View File
@@ -0,0 +1,18 @@
[project]
name = "orbit-demo"
version = "0.1.0"
description = "Example project with dependencies managed by orbit"
channels = ["main", "example"]
[[channels]]
name = "example"
url = "git.site.latha.org/nandi/example"
[dependencies]
greet = { version = ">=1.0.0, <2.0.0", channel = "example" }
hello = { version = "^1.0.0", channel = "example" }
[tasks]
demo = "sh \"$ORBIT_PROJECT/demo.sh\""
greet = "greet"
hello = ["hello"]
+15
View File
@@ -0,0 +1,15 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64">
<title>orbit</title>
<rect width="64" height="64" fill="#0f172a"/>
<circle cx="32" cy="32" r="21" fill="none" stroke="#a78bfa" stroke-opacity="0.4" stroke-width="2.5"/>
<g transform="rotate(-32 32 32)" fill="none">
<path d="M7 32 A25 10.5 0 0 1 57 32" stroke="#a78bfa" stroke-opacity="0.55" stroke-width="3.2"/>
</g>
<polygon points="32,20.5 42,26.25 42,37.75 32,43.5 22,37.75 22,26.25" fill="#f8fafc"/>
<g transform="rotate(-32 32 32)" fill="none">
<path d="M44.5 41.1 A25 10.5 0 0 1 19.5 41.1" stroke="#0f172a" stroke-width="7.2"/>
<path d="M57 32 A25 10.5 0 0 1 7 32" stroke="#a78bfa" stroke-width="3.2"/>
</g>
<circle cx="18.5" cy="15.9" r="7.5" fill="#0f172a"/>
<circle cx="18.5" cy="15.9" r="4.8" fill="#a78bfa"/>
</svg>

After

Width:  |  Height:  |  Size: 843 B

+21
View File
@@ -6,13 +6,34 @@ default:
build:
moon build --target native --release
# Build a static binary with Zig's musl toolchain (dist/orbit-linux-x86_64).
build-musl:
scripts/build-musl.sh
# Run the unit tests.
test:
moon test --target native
# Prove src/kernel with overflow-checked integers (needs z3, cvc5 or alt-ergo).
prove:
MOON_PROVE_PRELUDE_OVERRIDE="${MOON_HOME:-$HOME/.moon}/lib/prelude_proof_machine_int" moon prove src/kernel
# Install Orbit to ~/.local/bin and set up its package PATH for Bash.
install: build
install -Dm755 _build/native/release/build/main/main.exe "$HOME/.local/bin/orbit"
@just _path
# Build without optimisation (much faster to compile than `build`).
build-debug:
moon build --target native
# Install the unoptimised build to ~/.local/bin, for trying out a change.
install-debug: build-debug
install -Dm755 _build/native/debug/build/main/main.exe "$HOME/.local/bin/orbit"
@just _path
# Add Orbit's package bin directory to PATH in ~/.bashrc, once.
_path:
@line='export PATH="${ORBIT_ROOT:-$HOME/.orbit}/bin:$PATH"'; rc="$HOME/.bashrc"; \
if [ ! -f "$rc" ] || ! grep -Fqx -- "$line" "$rc"; then \
printf '\n%s\n' "$line" >> "$rc"; \
+2 -2
View File
@@ -6,9 +6,9 @@ readme = "README.md"
license = "Apache-2.0"
keywords = [ "package-manager", "oras", "oci" ]
keywords = [ "package-manager", "oci" ]
description = "A small package manager that stores packages as OCI artifacts via ORAS"
description = "A small package manager that stores packages as OCI artifacts"
source = "src"
+1
View File
@@ -0,0 +1 @@
.means/
+20
View File
@@ -0,0 +1,20 @@
---
data:
priority: normal
status: done
tags:
- solver
type: feature
id: 8m9kt
title: Package conflicts
---
Packages such as `moonbit` and `moonbit-nightly` can't be installed together, but only a clash of command names stops it, and the user must remove one by hand first.
Acceptance criteria:
- `orbit.json` takes `"conflicts": { "<name>": "<constraint>" }`, as in Arch. One side declaring it is enough. `*` includes prereleases.
- The solver never selects conflicting packages, in a project or globally, and says why when that leaves no solution.
- A global install that conflicts with installed packages asks before replacing them. Without a terminal it fails unless `--replace` is given. It refuses if another package needs the one to be removed, and downloads first.
- Conflicts are kept in `state.json` and `orbit.lock`; rollback checks them.
Outcome: `src/main/conflicts.mbt` and the solver. Checked end to end against `registry:2`, including the prompt. `moonbit-nightly` declares its conflict in orbit-packages. Arch's `provides` and `replaces` are not included: one package can't satisfy a dependency on another.
+74
View File
@@ -0,0 +1,74 @@
---
title: Orbit planning
description: 'The Orbit backlog: features, bugs, and tasks for Orbit itself.'
schema:
$schema: https://json-schema.org/draft/2020-12/schema
type: object
properties:
type:
type: string
enum: [task, bug, feature]
description: Task for general work, bug for incorrect behavior, or feature for new functionality.
status:
type: string
enum: [todo, in_progress, done, canceled]
description: Todo before work starts, in_progress while working, done once acceptance criteria are met, canceled when intentionally abandoned.
priority:
type: string
enum: [low, normal, high, urgent]
description: Relative importance, ordered urgent, high, normal, then low.
tags:
type: array
items:
type: string
minLength: 1
uniqueItems: true
description: Optional labels for grouping related items.
required: [type, status, priority]
additionalProperties: false
app:
views:
- title: Open work
filter: data.status in ["todo", "in_progress"]
columns: [title, data.type, data.status, data.priority]
---
# Working with Orbit planning
This collection is Orbit's backlog of actionable work. Run commands from the
repository root:
```sh
means list --path ./planning --limit 0 --json
means search --path ./planning --filter status=todo --json
means show <id> --path ./planning --json
means create --path ./planning --input - --json
means update <id> --path ./planning --input - --json
```
Create with:
```json
{
"frontmatter": {
"title": "Add a feature",
"data": { "type": "feature", "status": "todo", "priority": "normal" }
},
"body": "Context and acceptance criteria..."
}
```
Never supply `id`; means generates it. Reference other items by ID.
## Workflow
1. List existing items and read relevant ones before creating new ones. Avoid duplicates.
2. Follow the user's scope and priorities. The tag `deferred` marks ideas that stay
out of scope until the user picks them up.
3. Set `in_progress` when starting agreed work. Set `done` only when acceptance
criteria are met, and record the outcome in the body. Use `canceled` for
abandoned work instead of deleting.
4. Read before each update and supply the returned `hash`. On conflict, read again
and reconcile. Omitting `body` preserves it; supplying it replaces it entirely.
5. Run `means doctor --path ./planning` after writes and fix what it reports.
6. Mention relevant item IDs in commits and when reporting work.
@@ -0,0 +1,20 @@
---
data:
priority: normal
status: done
tags:
- search
type: feature
id: bnbr1
title: Cache channel indexes for fast search
---
`orbit search` reads every channel over the network each time (about 8 s for two channels).
Acceptance criteria:
- A repeated search of the configured channels needs no network, for channels with an index and for small ones listed from the catalog.
- A copy older than an hour is fetched again; if that fails, it is used with a warning.
- `orbit search --refresh` skips the cache. Publishing, indexing, login and logout drop it.
- Installs and version lookups still never read it.
Outcome: copies live in `<root>/cache/indexes/` (`src/main/index_cache.mbt`). A repeated search takes 3 ms instead of about 12 s. Channels with over 100 repositories and no index are not cached.
@@ -0,0 +1,11 @@
---
data:
priority: normal
status: done
type: feature
id: k7q3m
title: Show info for packages that aren't installed
---
`orbit info <name>` only worked for installed packages. It should also describe a package that is in a channel.
Outcome: when the package isn't installed (or `channel::` / `@constraint` asks for a build other than the installed one), `orbit info` finds the package in the same cached channel listings as `orbit search` (`channel_listing`). Index entries now record the `digest` of their version's manifest, so with the config blob in the digest-keyed manifest cache a repeated `info` takes ~8 ms with no network; another version, or an index built before digests, falls back to resolving in the registry. It and prints its description, documentation link, channel, digest, packaged bins, dependencies and conflicts. In a project it still prefers the locked package. `available_details` in `src/main/details.mbt`.
@@ -0,0 +1,11 @@
---
data:
priority: normal
status: done
type: feature
id: y4x2r
title: Show package details on install
---
Installing a package should show its paths and the commands it exposes, and `orbit info` should show the same.
Outcome: `install`, `add`, `sync` and `upgrade` print each new build's description, channel, digest, store path, linked bins, dependencies and conflicts (`src/main/details.mbt`). `orbit info` prints the same, and in a project also covers the locked packages. `orbit run` still syncs silently.
+76
View File
@@ -0,0 +1,76 @@
#!/bin/sh
# Build a fully static Orbit with Zig's musl toolchain:
# dist/orbit-linux-x86_64 and dist/SHA256SUMS
#
# Needs moon, zig, perl, make, and curl. OpenSSL is built once, with zig, into
# _build/musl-deps (set ORBIT_MUSL_DEPS to keep it elsewhere).
set -eu
openssl_version=3.5.9
openssl_sha256=603f5602e2eef00d77fbd429d34dcd5822bb301757a1bc9cdb24c670f1eb859a
cd "$(dirname "$0")/.."
root=$PWD
# Only x86_64: the libbacktrace.a that moon links is prebuilt for the host.
if [ "$(uname -sm)" != "Linux x86_64" ]; then
echo "build-musl.sh only supports Linux x86_64" >&2
exit 1
fi
export ORBIT_MUSL_TARGET=x86_64-linux-musl
deps=${ORBIT_MUSL_DEPS:-$root/_build/musl-deps}
prefix=$deps/openssl-$openssl_version-zig-$(zig version)
if [ ! -f "$prefix/lib/libssl.a" ]; then
echo "Building OpenSSL $openssl_version with zig $(zig version)" >&2
mkdir -p "$deps"
work=$(mktemp -d "$deps/build.XXXXXX")
trap 'rm -rf "$work"' EXIT
curl -fsSL --retry 5 -o "$work/openssl.tar.gz" \
"https://github.com/openssl/openssl/releases/download/openssl-$openssl_version/openssl-$openssl_version.tar.gz"
printf '%s %s\n' "$openssl_sha256" "$work/openssl.tar.gz" | sha256sum -c - >&2
tar -xzf "$work/openssl.tar.gz" -C "$work"
(
cd "$work/openssl-$openssl_version"
# no-autoload-config: the host's openssl.cnf may name modules we can't load.
CC="$root/scripts/musl/cc" AR="$root/scripts/musl/ar" RANLIB="zig ranlib" \
./Configure linux-x86_64 --prefix="$work/out" --libdir=lib --openssldir=/etc/ssl \
no-shared no-module no-dso no-apps no-tests no-docs no-legacy no-autoload-config \
no-ssl3 no-tls1 no-tls1_1 no-dtls no-comp no-afalgeng
make -s -j"$(nproc)" build_libs
make -s install_dev
) > "$work/log" 2>&1 || { tail -n 60 "$work/log" >&2; exit 1; }
rm -rf "$prefix"
mv "$work/out" "$prefix"
fi
if [ ! -d .mooncakes/moonbitlang/async ]; then moon install >&2; fi
obj=$root/_build/musl-shim
mkdir -p "$obj"
sed -nE 's/^ *IMPORT_FUNC(_WITH_ALT_NAMES)?\([^,]+, *([A-Za-z0-9_]+) *,.*/ORBIT_SYMBOL(\2)/p' \
.mooncakes/moonbitlang/async/src/tls/openssl.c > "$obj/openssl_symbols.h"
if [ "$(wc -l < "$obj/openssl_symbols.h")" -lt 20 ]; then
echo "Could not read the OpenSSL imports from moonbitlang/async" >&2
exit 1
fi
scripts/musl/cc -c -O2 -I"$prefix/include" -I"$obj" \
scripts/musl/openssl_static.c -o "$obj/openssl_static.o"
# A separate target directory keeps these objects apart from the usual glibc ones.
# moon doesn't track ORBIT_MUSL_LINK, so relink every time.
rm -f _build/musl/native/release/build/main/main.exe
# async's dir.c uses NAME_MAX without limits.h, which only glibc's dirent.h pulls in.
MOON_CC=$root/scripts/musl/cc MOON_AR=$root/scripts/musl/ar \
ORBIT_MUSL_CFLAGS="-include limits.h" \
ORBIT_MUSL_LINK="$obj/openssl_static.o $prefix/lib/libssl.a $prefix/lib/libcrypto.a" \
moon build --target native --release --target-dir _build/musl >&2
mkdir -p dist
install -m 755 _build/musl/native/release/build/main/main.exe dist/orbit-linux-x86_64
if readelf -lW dist/orbit-linux-x86_64 | grep -q INTERP; then
echo "dist/orbit-linux-x86_64 is not static" >&2
exit 1
fi
(cd dist && sha256sum orbit-linux-x86_64 > SHA256SUMS)
ls -l dist >&2
+2
View File
@@ -0,0 +1,2 @@
#!/bin/sh
exec zig ar "$@"
+11
View File
@@ -0,0 +1,11 @@
#!/bin/sh
# MOON_CC for static musl builds: `zig cc`, plus the static OpenSSL objects when linking.
set -eu
# shellcheck disable=SC2086 # ORBIT_MUSL_* are space-separated lists
for arg in "$@"; do
case $arg in
-c) exec zig cc -target "$ORBIT_MUSL_TARGET" -ffunction-sections -fdata-sections ${ORBIT_MUSL_CFLAGS-} "$@" ;;
esac
done
exec zig cc -target "$ORBIT_MUSL_TARGET" -static -s -Wl,--gc-sections "$@" ${ORBIT_MUSL_LINK-}
+66
View File
@@ -0,0 +1,66 @@
// moonbitlang/async loads OpenSSL with dlopen/dlsym, which a static musl binary
// can't do. These definitions replace musl's stubs (nothing else in Orbit uses
// them) and hand out the statically linked OpenSSL functions instead.
//
// openssl_symbols.h is generated by scripts/build-musl.sh from async's own
// import list, so a function OpenSSL lacks fails the link, not the first request.
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <openssl/crypto.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/objects.h>
#include <openssl/rand.h>
#include <openssl/sha.h>
#include <openssl/ssl.h>
#include <openssl/x509.h>
// SSL_CTX_set_default_verify_paths only checks the OPENSSLDIR chosen at build
// time (/etc/ssl). Also load the CA bundle from where other distros keep it,
// unless the user picked their own with SSL_CERT_FILE or SSL_CERT_DIR.
static int set_default_verify_paths(SSL_CTX *ctx) {
static const char *const bundles[] = {
"/etc/ssl/certs/ca-certificates.crt", // Debian, Arch, Alpine, Nix
"/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem", // Fedora, RHEL
"/etc/pki/tls/certs/ca-bundle.crt", // older Fedora, RHEL
"/etc/ssl/ca-bundle.pem", // openSUSE
"/etc/ssl/cert.pem", // Alpine, Void
};
if (!SSL_CTX_set_default_verify_paths(ctx)) return 0;
if (getenv("SSL_CERT_FILE") || getenv("SSL_CERT_DIR")) return 1;
for (size_t i = 0; i < sizeof(bundles) / sizeof(bundles[0]); ++i) {
if (access(bundles[i], R_OK) == 0 &&
SSL_CTX_load_verify_file(ctx, bundles[i])) {
break;
}
}
return 1;
}
static const struct {
const char *name;
void *address;
} symbols[] = {
{ "OpenSSL_version_num", (void *)OpenSSL_version_num },
#define ORBIT_SYMBOL(name) { #name, (void *)name },
#include "openssl_symbols.h"
#undef ORBIT_SYMBOL
};
void *dlopen(const char *file, int mode) {
(void)mode;
return file && strncmp(file, "libssl.so", 9) == 0 ? (void *)symbols : NULL;
}
void *dlsym(void *handle, const char *name) {
if (handle != (void *)symbols) return NULL;
if (strcmp(name, "SSL_CTX_set_default_verify_paths") == 0) {
return (void *)set_default_verify_paths;
}
for (size_t i = 0; i < sizeof(symbols) / sizeof(symbols[0]); ++i) {
if (strcmp(name, symbols[i].name) == 0) return symbols[i].address;
}
return NULL;
}
+92
View File
@@ -0,0 +1,92 @@
#!/usr/bin/env python3
"""Publish dist/ as the rolling Gitea release. Run by .gitea/workflows/rolling-release.yml."""
import json
import os
from pathlib import Path
import subprocess
import urllib.error
import urllib.parse
import urllib.request
TAG = "rolling"
STAGED = "new-"
ASSETS = ["orbit-linux-x86_64", "SHA256SUMS"]
ROOT = Path(__file__).resolve().parent.parent
DIST = ROOT / "dist"
SERVER = os.environ["GITHUB_SERVER_URL"].rstrip("/")
REPO = os.environ["GITHUB_REPOSITORY"]
COMMIT = os.environ["GITHUB_SHA"]
TOKEN = os.environ["GITEA_TOKEN"]
RELEASES = f"{SERVER}/api/v1/repos/{REPO}/releases"
def call(method, url, data=None, content_type="application/json"):
"""Make a Gitea API call. Returns None when a GET finds nothing."""
if isinstance(data, dict):
data = json.dumps(data).encode()
request = urllib.request.Request(url, data=data, method=method)
request.add_header("Authorization", f"token {TOKEN}")
if data is not None:
request.add_header("Content-Type", content_type)
try:
with urllib.request.urlopen(request, timeout=300) as response:
body = response.read()
except urllib.error.HTTPError as error:
if method == "GET" and error.code == 404:
return None
detail = error.read().decode(errors="replace")
raise SystemExit(f"{method} {url}: HTTP {error.code}: {detail}")
return json.loads(body) if body else None
def replace_assets(release_id):
"""Upload under staging names, then swap, so downloads are only missing for a moment."""
assets_url = f"{RELEASES}/{release_id}/assets"
for asset in call("GET", assets_url):
if asset["name"].startswith(STAGED):
call("DELETE", f"{assets_url}/{asset['id']}")
for name in ASSETS:
query = urllib.parse.urlencode({"name": STAGED + name})
call("POST", f"{assets_url}?{query}", (DIST / name).read_bytes(), "application/octet-stream")
ids = {asset["name"]: asset["id"] for asset in call("GET", assets_url)}
for name in ASSETS:
if name in ids:
call("DELETE", f"{assets_url}/{ids[name]}")
call("PATCH", f"{assets_url}/{ids[STAGED + name]}", {"name": name})
def main():
missing = [name for name in ASSETS if not (DIST / name).is_file()]
if missing:
raise SystemExit(f"missing from dist/: {', '.join(missing)}")
sums = (DIST / "SHA256SUMS").read_text().strip()
download = f"{SERVER}/{REPO}/releases/download/{TAG}"
release = {
"tag_name": TAG,
"target_commitish": COMMIT,
"name": f"Rolling build ({COMMIT[:7]})",
"prerelease": True,
"body": (
f"Automated build of `main` at [`{COMMIT[:7]}`]({SERVER}/{REPO}/commit/{COMMIT}). "
"A static Linux x86_64 binary built with Zig's musl toolchain, with OpenSSL included.\n\n"
f"```sh\ncurl -fLo orbit {download}/orbit-linux-x86_64\nchmod +x orbit\n```\n\n"
f"```\n{sums}\n```\n"
),
}
existing = call("GET", f"{RELEASES}/tags/{TAG}")
if existing is None:
existing = call("POST", RELEASES, {**release, "draft": False})
replace_assets(existing["id"])
subprocess.run(
["git", "push", "--force", "origin", f"{COMMIT}:refs/tags/{TAG}"], cwd=ROOT, check=True
)
call("PATCH", f"{RELEASES}/{existing['id']}", {**release, "draft": False})
print(f"Published {SERVER}/{REPO}/releases/tag/{TAG}")
if __name__ == "__main__":
main()
+24
View File
@@ -0,0 +1,24 @@
# kernel
The proved part of Orbit. `src/main` runs this code, so the proofs replace tests
of it. There are no axioms. Contracts are in `.mbt`, specifications in `.mbtp`.
| File | Proved |
|---|---|
| `nat` | The result is the decimal value, or -1 for an empty string, a non-digit, or 10^18 and up. Nothing overflows. |
| `version` | `compare` is a total order, and each constraint operator accepts exactly its interval. |
| `sort` | `sort_desc` terminates and lists every index once, highest version first and stable. |
| `lit` | Literals round trip to their variable and sign, and a literal and its complement never agree. |
Run `just prove`. It selects the machine-integer prelude. Plain `moon prove`
models integers as unbounded, so it would miss overflow.
Not proved, and still tested in `src/main`: splitting strings, ranking
prereleases (`Key.pre`), and anything that does I/O. The prover treats strings
as opaque. `src/main` is not proof-enabled, so its calls must meet the
`proof_require` clauses by themselves.
**Writing specifications:** `moonc-prove` 0.10.20 drops the parentheses around an
implication, so `(a → b) && (c → d)` is read as `((a → b) && c) → d`. Never put
`→` or a quantifier under `&&` or `||`. Give it its own predicate, or use `==`.
After changing a proof, break the code on purpose and check that it fails.
+80
View File
@@ -0,0 +1,80 @@
///|
#derive(Eq)
pub(all) enum Val {
Unassigned
True
False
}
///|
pub extend Val with Eq::{equal, not_equal}
///|
pub fn pos_lit(
v : Int32,
) -> Int32 where {
proof_require: var_ok(v),
proof_ensure: r => 0 <= r && r / 2 == v && r % 2 == 0,
} {
v * 2
}
///|
pub fn neg_lit(
v : Int32,
) -> Int32 where {
proof_require: var_ok(v),
proof_ensure: r => 0 <= r && r / 2 == v && r % 2 == 1,
} {
v * 2 + 1
}
///|
pub fn lit_var(
l : Int32,
) -> Int32 where {
proof_require: 0 <= l,
proof_ensure: r => 0 <= r && (l == r * 2 || l == r * 2 + 1),
} {
l / 2
}
///|
pub fn lit_is_neg(
l : Int32,
) -> Bool where {
proof_require: 0 <= l,
proof_ensure: r => r == (l % 2 == 1),
} {
l % 2 != 0
}
///|
/// The complement: same variable, opposite sign.
pub fn lit_neg(
l : Int32,
) -> Int32 where {
proof_require: 0 <= l,
proof_ensure: r => 0 <= r && r != l && r / 2 == l / 2 && r % 2 != l % 2,
} {
if l % 2 == 0 {
l + 1
} else {
l - 1
}
}
///|
pub fn lit_val(
v : Val,
l : Int32,
) -> Val where {
proof_require: 0 <= l,
proof_ensure: r => truth_ok(v, l, r),
} {
match v {
Unassigned => Unassigned
True => if lit_is_neg(l) { False } else { True }
False => if lit_is_neg(l) { True } else { False }
}
}
+56
View File
@@ -0,0 +1,56 @@
// Specification of solver literals: variable `v` has the positive literal `2v`
// and the negative literal `2v + 1`.
///|
predicate var_ok(v : Int32) {
0 <= v && v < 1073741823
}
///|
predicate is_true(v : Val) {
match v {
True => true
_ => false
}
}
///|
predicate is_false(v : Val) {
match v {
False => true
_ => false
}
}
///|
predicate lit_true(v : Val, l : Int32) {
(is_true(v) && l % 2 == 0) || (is_false(v) && l % 2 == 1)
}
///|
predicate lit_false(v : Val, l : Int32) {
(is_false(v) && l % 2 == 0) || (is_true(v) && l % 2 == 1)
}
///|
/// `r` is the truth of literal `l` when its variable holds `v`.
predicate truth_ok(v : Val, l : Int32, r : Val) {
is_true(r) == lit_true(v, l) && is_false(r) == lit_false(v, l)
}
///|
predicate opposite(a : Val, b : Val) {
is_true(a) == is_false(b) && is_false(a) == is_true(b)
}
///|
/// Complementary literals never agree.
lemma truth_complement(v : Val, l : Int32, m : Int32, a : Val, b : Val) where {
proof_require: 0 <= l,
proof_require: 0 <= m,
proof_require: l % 2 != m % 2,
proof_require: truth_ok(v, l, a),
proof_require: truth_ok(v, m, b),
proof_ensure: opposite(a, b),
} {
}
+1
View File
@@ -0,0 +1 @@
proof_enabled = true
+33
View File
@@ -0,0 +1,33 @@
///|
/// Value of the decimal code points `s`, or -1 if `s` is empty, has a
/// non-digit, or is 10^18 or more.
pub fn parse_nat(
s : FixedArray[Int64],
) -> Int64 where {
proof_require: s.length() < 2147483647,
proof_ensure: r => parse_post(s, r),
proof_ensure: r => valid_or_rejected(r),
} {
let t = FixedArray::make(s.length() + 1, 0L)
for i in 0..<s.length() {
let n = t[i]
let c = s[i]
t[i + 1] = if n < 0L || n > 99999999999999999L || c < 48L || c > 57L {
-1L
} else {
n * 10L + (c - 48L)
}
} where {
proof_invariant: 0 <= i && i <= s.length(),
proof_invariant: trace(s, t, i, t[i]),
proof_invariant: valid_or_rejected(t[i]),
}
let r = t[s.length()]
proof_assert trace(s, t, s.length(), r)
proof_assert decimal(s, r)
if s.length() == 0 {
-1L
} else {
r
}
}
+52
View File
@@ -0,0 +1,52 @@
// Specification of `parse_nat`.
///|
predicate nat_ok(n : Int64) {
0L <= n && n <= 999999999999999999L
}
///|
/// `p` followed by the digit `c`, or -1 if `p` was already rejected, `c` is not
/// a digit, or the result is 10^18 or more.
fn append(p : Int64, c : Int64) -> Int64 {
if 0L <= p && p <= 99999999999999999L && 48L <= c && c <= 57L {
p * 10L + (c - 48L)
} else {
0L - 1L
}
}
///|
/// `t[i]` is the decimal value of the first `i` code points, for all `i <= n`.
predicate trace_ok(s : FixedArray[Int64], t : FixedArray[Int64], n : Int32) {
∀ i : Int32, (0 <= i && i < n) → t[i + 1] == append(t[i], s[i])
}
///|
predicate trace(
s : FixedArray[Int64],
t : FixedArray[Int64],
n : Int32,
r : Int64,
) {
t.length() == s.length() + 1 &&
t[0] == 0L &&
trace_ok(s, t, n) &&
t[n] == r
}
///|
/// `r` is the decimal value of `s`, or -1 as for `append`.
predicate decimal(s : FixedArray[Int64], r : Int64) {
∃ t : FixedArray[Int64], trace(s, t, s.length(), r)
}
///|
predicate parse_post(s : FixedArray[Int64], r : Int64) {
(s.length() == 0 && r == 0L - 1L) || (s.length() > 0 && decimal(s, r))
}
///|
predicate valid_or_rejected(r : Int64) {
r == 0L - 1L || nat_ok(r)
}
+40
View File
@@ -0,0 +1,40 @@
///|
/// Indices of `keys`, highest version first; equal versions keep their order.
pub fn sort_desc(
keys : FixedArray[Key],
) -> FixedArray[Int32] where {
proof_ensure: r => sort_post(keys, r),
} {
let idx = FixedArray::make(keys.length(), 0)
for i in 0..<keys.length() {
idx[i] = i
sink(keys, idx, i, i)
} where {
proof_invariant: 0 <= i && i <= keys.length(),
proof_invariant: sorted_prefix(keys, idx, i),
}
idx
}
///|
/// Move the entry at `j` left until the first `n + 1` entries are ordered.
fn sink(
keys : FixedArray[Key],
idx : FixedArray[Int32],
j : Int32,
n : Int32,
) -> Unit where {
proof_decrease: j,
proof_require: 0 <= j && j <= n && n < keys.length(),
proof_require: sinking(keys, idx, j, n),
proof_ensure: sorted_prefix(keys, idx, n + 1),
} {
if j > 0 && compare(keys[idx[j]], keys[idx[j - 1]]) > 0 {
let t = idx[j]
idx[j] = idx[j - 1]
idx[j - 1] = t
sink(keys, idx, j - 1, n)
} else {
()
}
}
+87
View File
@@ -0,0 +1,87 @@
// Specification of `sort_desc`: the result lists every index of `keys` once,
// highest version first, ties in their original order.
///|
predicate same_length(keys : FixedArray[Key], idx : FixedArray[Int32]) {
idx.length() == keys.length()
}
///|
/// The first `n` entries are all below `n`.
predicate below(idx : FixedArray[Int32], n : Int32) {
∀ p : Int32, (0 <= p && p < n) → (0 <= idx[p] && idx[p] < n)
}
///|
predicate distinct(idx : FixedArray[Int32], n : Int32) {
∀ p : Int32, ∀ q : Int32, (0 <= p && p < q && q < n) → idx[p] != idx[q]
}
///|
/// Index `i` comes before index `j` in the result.
predicate before(keys : FixedArray[Key], i : Int32, j : Int32) {
key_lt(keys[j], keys[i]) || (key_eq(keys[j], keys[i]) && i < j)
}
///|
predicate ordered(keys : FixedArray[Key], idx : FixedArray[Int32], n : Int32) {
∀ p : Int32, ∀ q : Int32, (0 <= p && p < q && q < n) →
before(keys, idx[p], idx[q])
}
///|
/// Everything in `(j, n]` comes after the entry being inserted at `j`.
predicate after_hole(
keys : FixedArray[Key],
idx : FixedArray[Int32],
j : Int32,
n : Int32,
) {
∀ q : Int32, (j < q && q <= n) → before(keys, idx[j], idx[q])
}
///|
/// The first `n + 1` entries are ordered, ignoring the one at `j`.
predicate ordered_except(
keys : FixedArray[Key],
idx : FixedArray[Int32],
j : Int32,
n : Int32,
) {
∀ p : Int32, ∀ q : Int32, (0 <= p && p < q && q <= n && p != j && q != j) →
before(keys, idx[p], idx[q])
}
///|
predicate sort_post(keys : FixedArray[Key], idx : FixedArray[Int32]) {
sorted_prefix(keys, idx, keys.length())
}
///|
/// The first `n` entries are `0..<n`, reordered.
predicate sorted_prefix(
keys : FixedArray[Key],
idx : FixedArray[Int32],
n : Int32,
) {
same_length(keys, idx) &&
below(idx, n) &&
distinct(idx, n) &&
ordered(keys, idx, n)
}
///|
/// Entry `n` is being inserted and has reached position `j`.
predicate sinking(
keys : FixedArray[Key],
idx : FixedArray[Int32],
j : Int32,
n : Int32,
) {
same_length(keys, idx) &&
below(idx, n + 1) &&
distinct(idx, n + 1) &&
idx[j] == n &&
after_hole(keys, idx, j, n) &&
ordered_except(keys, idx, j, n)
}
+115
View File
@@ -0,0 +1,115 @@
///|
/// A version reduced to integers. `pre` ranks the prerelease: callers must give
/// equal prereleases equal ranks and order the others as they compare.
pub(all) struct Key {
major : Int64
minor : Int64
patch : Int64
pre : Int32
}
///|
#derive(Eq, Debug)
pub(all) enum Op {
Any
Ge
Le
Gt
Lt
Eq
Ne
Caret
Tilde
Prefix
NotPrefix
}
///|
pub extend Op with Eq::{equal, not_equal}
///|
pub extend Op with Debug::{to_repr}
///|
/// -1, 0 or 1 as `a` is below, equal to or above `b`.
pub fn compare(
a : Key,
b : Key,
) -> Int32 where {
proof_ensure: r => compare_post(a, b, r),
} {
if a.major < b.major {
-1
} else if a.major > b.major {
1
} else if a.minor < b.minor {
-1
} else if a.minor > b.minor {
1
} else if a.patch < b.patch {
-1
} else if a.patch > b.patch {
1
} else if a.pre < b.pre {
-1
} else if a.pre > b.pre {
1
} else {
0
}
}
///|
/// Whether `v` satisfies the clause `op b`, where `b` was written with `parts`
/// components.
pub fn matches(
op : Op,
v : Key,
b : Key,
parts : Int32,
) -> Bool where {
proof_require: key_inv(v),
proof_require: key_inv(b),
proof_require: 1 <= parts && parts <= 3,
proof_ensure: r => r == allowed(op, v, b, parts),
} {
match op {
Any => true
Ge => compare(v, b) >= 0
Le => compare(v, b) <= 0
Gt => compare(v, b) > 0
Lt => compare(v, b) < 0
Eq => compare(v, b) == 0
Ne => compare(v, b) != 0
Caret =>
compare(v, b) >= 0 &&
v.major == b.major &&
(b.major != 0L || v.minor == b.minor)
Tilde =>
compare(v, b) >= 0 &&
v.major == b.major &&
(parts == 1 || v.minor == b.minor)
Prefix => same_prefix(v, b, parts)
NotPrefix => !same_prefix(v, b, parts)
}
}
///|
fn same_prefix(
v : Key,
b : Key,
parts : Int32,
) -> Bool where {
proof_require: key_inv(v),
proof_require: key_inv(b),
proof_require: 1 <= parts && parts <= 3,
proof_ensure: r => r == in_prefix(v, b, parts),
} {
if parts == 1 {
v.major == b.major
} else if parts == 2 {
v.major == b.major && v.minor == b.minor
} else {
true
}
}
+140
View File
@@ -0,0 +1,140 @@
// Specification of versions: a key is ordered lexicographically, and every
// constraint operator is an interval of that order.
///|
predicate key_inv(k : Key) {
nat_ok(k.major) && nat_ok(k.minor) && nat_ok(k.patch)
}
///|
predicate core_lt(a : Key, b : Key) {
a.major < b.major ||
(a.major == b.major && a.minor < b.minor) ||
(a.major == b.major && a.minor == b.minor && a.patch < b.patch)
}
///|
predicate core_eq(a : Key, b : Key) {
a.major == b.major && a.minor == b.minor && a.patch == b.patch
}
///|
predicate key_lt(a : Key, b : Key) {
core_lt(a, b) || (core_eq(a, b) && a.pre < b.pre)
}
///|
predicate key_eq(a : Key, b : Key) {
core_eq(a, b) && a.pre == b.pre
}
///|
predicate key_le(a : Key, b : Key) {
key_lt(a, b) || key_eq(a, b)
}
///|
predicate not_lt(a : Key, b : Key) {
!key_lt(a, b)
}
///|
predicate compare_post(a : Key, b : Key, r : Int32) {
(r == 0 || r == 1 || r == -1) &&
((r == -1) == key_lt(a, b)) &&
((r == 0) == key_eq(a, b)) &&
((r == 1) == key_lt(b, a))
}
// Laws of the order: these say `compare` is a total order.
///|
lemma key_lt_irreflexive(a : Key) where {
proof_ensure: not_lt(a, a),
} {
}
///|
lemma key_lt_asymmetric(a : Key, b : Key) where {
proof_require: key_lt(a, b),
proof_ensure: not_lt(b, a),
} {
}
///|
lemma key_lt_transitive(a : Key, b : Key, c : Key) where {
proof_require: key_lt(a, b),
proof_require: key_lt(b, c),
proof_ensure: key_lt(a, c),
} {
}
///|
predicate comparable(a : Key, b : Key) {
key_lt(a, b) || key_eq(a, b) || key_lt(b, a)
}
///|
lemma key_lt_total(a : Key, b : Key) where {
proof_ensure: comparable(a, b),
} {
}
///|
/// `v`'s core is below the first version of the next major.
predicate below_next_major(v : Key, b : Key) {
v.major < b.major + 1L
}
///|
/// `v`'s core is below the first version of the next minor.
predicate below_next_minor(v : Key, b : Key) {
v.major < b.major || (v.major == b.major && v.minor < b.minor + 1L)
}
///|
predicate from_major(v : Key, b : Key) {
b.major <= v.major
}
///|
predicate from_minor(v : Key, b : Key) {
b.major < v.major || (b.major == v.major && b.minor <= v.minor)
}
///|
/// Half-open core interval covered by a one- or two-part prefix.
predicate in_prefix(v : Key, b : Key, parts : Int32) {
(parts == 1 && from_major(v, b) && below_next_major(v, b)) ||
(parts == 2 && from_minor(v, b) && below_next_minor(v, b)) ||
parts == 3
}
///|
predicate in_caret(v : Key, b : Key) {
(b.major != 0L && key_le(b, v) && below_next_major(v, b)) ||
(b.major == 0L && key_le(b, v) && below_next_minor(v, b))
}
///|
predicate in_tilde(v : Key, b : Key, parts : Int32) {
(parts == 1 && key_le(b, v) && below_next_major(v, b)) ||
(parts != 1 && key_le(b, v) && below_next_minor(v, b))
}
///|
predicate allowed(op : Op, v : Key, b : Key, parts : Int32) {
match op {
Any => true
Ge => key_le(b, v)
Le => key_le(v, b)
Gt => key_lt(b, v)
Lt => key_lt(v, b)
Eq => key_eq(v, b)
Ne => !key_eq(v, b)
Caret => in_caret(v, b)
Tilde => in_tilde(v, b, parts)
Prefix => in_prefix(v, b, parts)
NotPrefix => !in_prefix(v, b, parts)
}
}
+448
View File
@@ -0,0 +1,448 @@
// Registry credentials stored in $ORBIT_ROOT/auth.json, with read fallback
// to $DOCKER_CONFIG/config.json (or ~/.docker/config.json).
///|
struct Creds {
username : String
password : String
}
///|
fn strip_url_scheme(s : String) -> String {
if has_prefix(s, "https://") {
drop_chars(s, 8)
} else if has_prefix(s, "http://") {
drop_chars(s, 7)
} else {
s
}
}
///|
fn ascii_lower(s : String) -> String {
let sb = StringBuilder()
for c in s {
if c >= 'A' && c <= 'Z' {
sb.write_char(Int32::unsafe_to_char(c.to_int() + 32))
} else {
sb.write_char(c)
}
}
sb.to_string()
}
///|
fn normalize_host(raw : String) -> String {
let t = trim(raw)
let no_scheme = if has_prefix(ascii_lower(t), "https://") {
drop_chars(t, 8)
} else if has_prefix(ascii_lower(t), "http://") {
drop_chars(t, 7)
} else {
t
}
let (host, _) = split_first(no_scheme, '/')
ascii_lower(trim(host))
}
///|
fn is_docker_hub_host(h : String) -> Bool {
h == "docker.io" || h == "registry-1.docker.io" || h == "index.docker.io"
}
///|
fn host_matches(stored_key : String, host : String) -> Bool {
let a = normalize_host(stored_key)
let b = normalize_host(host)
if a == "" || b == "" {
return false
}
if a == b {
return true
}
is_docker_hub_host(a) && is_docker_hub_host(b)
}
///|
fn auth_file_path(root : String) -> String {
root + "/auth.json"
}
///|
fn docker_config_path() -> String {
let dir = getenv("DOCKER_CONFIG")
if dir != "" {
dir + "/config.json"
} else {
getenv("HOME") + "/.docker/config.json"
}
}
///|
fn encode_basic_auth(creds : Creds) -> String {
let raw = utf8_encode(creds.username + ":" + creds.password)
@base64.encode(raw[:])
}
///|
fn decode_basic_auth(b64 : String) -> Creds? {
let raw = @base64.decode(trim(b64), ignore_whitespace=true) catch {
_ => return None
}
let decoded = utf8_decode(raw)
if !has_char(decoded, ':') {
return None
}
let (username, password) = split_first(decoded, ':')
if username == "" && password == "" {
return None
}
Some(Creds::{ username, password })
}
///|
async fn creds_from_helper(
helper : String,
server_url : String,
) -> Creds? noraise {
if helper == "" || has_char(helper, '/') || has_char(helper, ' ') {
return None
}
let bin = "docker-credential-" + helper
let (code, stdout) = run_with_stdin(bin, ["get"], server_url + "\n") catch {
_ => return None
}
if code != 0 {
return None
}
let obj = parse_object(stdout, "credential helper") catch { _ => return None }
let username = jstr(obj, "Username", "")
let password = jstr(obj, "Secret", "")
if username == "" && password == "" {
None
} else {
Some(Creds::{ username, password })
}
}
///|
async fn load_creds_from_file(path : String, host : String) -> Creds? noraise {
let text = match read_text(path) {
Some(t) => t
None => return None
}
let top = parse_object(text, path) catch { _ => return None }
match top.get("credHelpers") {
Some(Json::Object(helpers)) =>
for k, v in helpers {
if host_matches(k, host) {
match v {
Json::String(helper) =>
if helper != "" {
match creds_from_helper(helper, k) {
Some(c) => return Some(c)
None =>
if k != host {
match creds_from_helper(helper, host) {
Some(c) => return Some(c)
None => ()
}
}
}
}
_ => ()
}
}
}
_ => ()
}
match top.get("auths") {
Some(Json::Object(auths)) =>
for k, v in auths {
if host_matches(k, host) {
match v {
Json::Object(entry) => {
let b64 = jstr(entry, "auth", "")
if b64 != "" {
match decode_basic_auth(b64) {
Some(c) => return Some(c)
None => ()
}
}
let u = jstr(entry, "username", "")
let p = jstr(entry, "password", "")
if u != "" || p != "" {
return Some(Creds::{ username: u, password: p })
}
}
_ => ()
}
}
}
_ => ()
}
let store = jstr(top, "credsStore", "")
if store != "" {
match creds_from_helper(store, host) {
Some(c) => return Some(c)
None =>
if is_docker_hub_host(normalize_host(host)) {
return creds_from_helper(store, "https://index.docker.io/v1/")
}
}
}
None
}
///|
/// The saved login for a host and the file it came from.
async fn load_creds(host : String) -> (Creds, String)? noraise {
let nhost = normalize_host(host)
if nhost == "" {
return None
}
for path in [auth_file_path(orbit_root()), docker_config_path()] {
match load_creds_from_file(path, nhost) {
Some(c) => return Some((c, path))
None => ()
}
}
None
}
///|
async fn save_creds(
root : String,
host : String,
creds : Creds,
) -> Unit raise OrbitError {
let nhost = normalize_host(host)
let path = auth_file_path(root)
let top = match read_text(path) {
Some(t) => parse_object(t, "auth.json")
None => Map([])
}
let auths : Map[String, Json] = match top.get("auths") {
Some(Json::Object(m)) => m
None => Map([])
_ => raise OrbitError("auth.json: expected 'auths' to be an object")
}
let stale : Array[String] = []
for k, _ in auths {
if host_matches(k, nhost) {
stale.push(k)
}
}
for k in stale {
auths.remove(k)
}
let entry : Map[String, Json] = Map([])
entry["auth"] = Json::string(encode_basic_auth(creds))
auths[nhost] = Json::object(entry)
top["auths"] = Json::object(auths)
@fs.mkdir(root, recursive=true, allow_exist=true) catch {
e => raise OrbitError("cannot create \{root}: \{e}")
}
write_secret_atomic(path, Json::object(top).stringify(indent=2) + "\n")
}
///|
async fn remove_creds(root : String, host : String) -> Bool raise OrbitError {
let nhost = normalize_host(host)
let path = auth_file_path(root)
let text = match read_text(path) {
Some(t) => t
None => return false
}
let top = parse_object(text, "auth.json")
let auths : Map[String, Json] = match top.get("auths") {
Some(Json::Object(m)) => m
None => return false
_ => raise OrbitError("auth.json: expected 'auths' to be an object")
}
let matching : Array[String] = []
for k, _ in auths {
if host_matches(k, nhost) {
matching.push(k)
}
}
if matching.length() == 0 {
return false
}
for k in matching {
auths.remove(k)
}
top["auths"] = Json::object(auths)
write_secret_atomic(path, Json::object(top).stringify(indent=2) + "\n")
true
}
///|
fn strip_trailing_cr(s : String) -> String {
let a = chars(s)
let mut end = a.length()
if end > 0 && a[end - 1] == '\r' {
end = end - 1
}
slice(a, 0, end)
}
///|
fn strip_trailing_newlines(s : String) -> String {
let a = chars(s)
let mut end = a.length()
while end > 0 && (a[end - 1] == '\n' || a[end - 1] == '\r') {
end = end - 1
}
slice(a, 0, end)
}
///|
async fn read_stdin_line() -> String raise OrbitError {
let line = @stdio.stdin.read_until("\n") catch {
e => raise OrbitError("cannot read stdin: \{e}")
}
match line {
Some(s) => strip_trailing_cr(s)
None => ""
}
}
///|
async fn read_password_prompt() -> String raise OrbitError {
c_print_err(utf8_encode("Password: "))
let echo_disabled = c_set_echo(0) == 0
defer {
if echo_disabled {
ignore(c_set_echo(1))
c_print_err(utf8_encode("\n"))
}
}
read_stdin_line()
}
///|
async fn resolve_login_plain_http(
raw_host : String,
host : String,
plain_http_flag : Bool,
) -> Bool raise OrbitError {
let lower = ascii_lower(trim(raw_host))
if plain_http_flag || has_prefix(lower, "http://") {
return true
}
if has_prefix(lower, "https://") {
return false
}
let ctx = load_ctx()
for ch in ctx.channels {
let (ch_host, _) = split_first(ch.url, '/')
if host_matches(ch_host, host) && ch.plain_http {
return true
}
}
false
}
///|
async fn cmd_login(
raw_host : String,
username_opt : String?,
password_opt : String?,
password_stdin : Bool,
plain_http_flag : Bool,
) -> Unit raise OrbitError {
if password_opt is Some(_) && password_stdin {
raise OrbitError("use either --password or --password-stdin, not both")
}
let host = normalize_host(raw_host)
if host == "" || has_char(host, ' ') || has_char(host, '\t') {
raise OrbitError("invalid registry host '\{raw_host}'")
}
let plain_http = resolve_login_plain_http(raw_host, host, plain_http_flag)
let username = match username_opt {
Some(u) => u
None => {
c_print_err(utf8_encode("Username: "))
trim(read_stdin_line())
}
}
let password = if password_stdin {
let raw = @stdio.stdin.read_all().text() catch {
e => raise OrbitError("cannot read password from stdin: \{e}")
}
strip_trailing_newlines(raw)
} else {
match password_opt {
Some(p) => p
None => read_password_prompt()
}
}
if username == "" && password == "" {
raise OrbitError("username or password is required")
}
let creds = Creds::{ username, password }
with_spinner("Logging in to \{host}", () => {
verify_login(host, plain_http, creds)
})
save_creds(orbit_root(), host, creds)
drop_cached_indexes(orbit_root())
println("Login succeeded for \{host}")
}
///|
async fn cmd_logout(raw_host : String) -> Unit raise OrbitError {
let host = normalize_host(raw_host)
if host == "" {
raise OrbitError("invalid registry host '\{raw_host}'")
}
drop_cached_indexes(orbit_root())
if remove_creds(orbit_root(), host) {
println("Removed credentials for \{host}")
} else {
println("No stored credentials for \{host}")
}
let docker_path = docker_config_path()
match load_creds_from_file(docker_path, host) {
Some(_) =>
println("note: credentials for \{host} still exist in \{docker_path}")
None => ()
}
}
///|
test "host normalization and matching" {
assert_eq(normalize_host("https://git.site.latha.org/nandi"), "git.site.latha.org")
assert_eq(normalize_host("http://localhost:5000/"), "localhost:5000")
assert_true(host_matches("https://index.docker.io/v1/", "registry-1.docker.io"))
assert_true(host_matches("docker.io", "index.docker.io"))
assert_false(host_matches("ghcr.io", "git.site.latha.org"))
}
///|
test "basic auth encode and decode roundtrip" {
let c = Creds::{ username: "nandi", password: "s:e:c/r+e=t" }
let b64 = encode_basic_auth(c)
let decoded = decode_basic_auth(b64).unwrap()
assert_eq(decoded.username, "nandi")
assert_eq(decoded.password, "s:e:c/r+e=t")
assert_true(decode_basic_auth("not-valid-b64!!!") is None)
assert_true(decode_basic_auth(@base64.encode(b"nocolon"[:])) is None)
}
///|
async test "save and remove credentials in auth.json" {
let root = @fs.tmpdir(prefix="orbit-auth-test-")
defer (@fs.rmdir(root, recursive=true, allow_missing=true) catch { _ => () })
let c = Creds::{ username: "alice", password: "secret" }
save_creds(root, "https://git.site.latha.org", c)
let loaded = load_creds_from_file(auth_file_path(root), "git.site.latha.org")
guard loaded is Some(got) else { fail("expected saved credentials") }
assert_eq(got.username, "alice")
assert_eq(got.password, "secret")
assert_true(remove_creds(root, "git.site.latha.org"))
assert_true(
load_creds_from_file(auth_file_path(root), "git.site.latha.org") is None,
)
assert_false(remove_creds(root, "git.site.latha.org"))
}
+5 -5
View File
@@ -349,9 +349,9 @@ test "channel spec" {
///|
test "only a missing repository falls through to the next channel" {
assert_true(is_missing_repo("Error response from registry: name unknown"))
assert_true(is_missing_repo("GET \"u\": response status code 404: Not Found"))
assert_false(is_missing_repo("dial tcp: lookup x: no such host"))
assert_false(is_missing_repo("connect: connection refused"))
assert_false(is_missing_repo("response status code 401: Unauthorized"))
assert_true(is_missing_status(404))
assert_false(is_missing_status(401))
assert_false(is_missing_status(403))
assert_false(is_missing_status(500))
assert_false(is_missing_status(502))
}
+401
View File
@@ -0,0 +1,401 @@
// Declared package conflicts (`conflicts` in orbit.json), and replacing the
// installed packages that a global install conflicts with.
///|
/// What the solver needs to know about an installed package outside the solve.
struct LockedInfo {
version : String
conflicts : Map[String, String]
}
///|
/// Conflicts apply to versions, so tag names such as "edge" are not allowed.
fn valid_conflict_constraint(c : String) -> Bool {
for piece in split_on(c, ',') {
if !valid_semver_clause(piece) {
return false
}
}
true
}
///|
/// Whether a conflict on `constraint` covers `version`. Unlike a dependency, it
/// covers prereleases without naming one: a conflict with `*` means every build.
fn conflict_covers(constraint : String, version : String) -> Bool {
match parse_ver(version) {
Some(v) => {
for piece in split_on(constraint, ',') {
if !satisfies_clause(v, piece) {
return false
}
}
true
}
None => false
}
}
///|
fn declares_conflict(
conflicts : Map[String, String],
name : String,
version : String,
) -> Bool {
match conflicts.get(name) {
Some(c) => conflict_covers(c, version)
None => false
}
}
///|
/// Either package may declare the conflict.
fn manifests_conflict(a : Manifest, b : Manifest) -> Bool {
declares_conflict(a.conflicts, b.name, b.version) ||
declares_conflict(b.conflicts, a.name, a.version)
}
///|
/// Parse the `conflicts` object of orbit.json.
fn parse_conflicts(
o : Map[String, Json],
self_name : String,
) -> Map[String, String] raise OrbitError {
let out : Map[String, String] = Map([])
match o.get("conflicts") {
None => ()
Some(Json::Object(m)) =>
for name, v in m {
let c = match v {
Json::String(s) => s
_ =>
raise OrbitError(
"orbit.json: conflict '\{name}' must be a version constraint",
)
}
if !valid_name(name) || name == self_name {
raise OrbitError("orbit.json: invalid conflict name '\{name}'")
}
if !valid_conflict_constraint(c) {
raise OrbitError(
"orbit.json: invalid version constraint '\{c}' for conflict '\{name}'",
)
}
out[name] = c
}
Some(_) =>
raise OrbitError(
"orbit.json: conflicts must be an object of names and version constraints",
)
}
out
}
// ---------------------------------------------------------------- global installs
///|
/// Pairs of (installed, planned) packages that conflict, where the installed
/// one is not itself in the plan.
fn plan_conflicts(
ctx : Ctx,
steps : Array[Step],
) -> Array[(Installed, Step)] {
let planned : Map[String, Bool] = Map([])
for st in steps {
planned[st.name] = true
}
let out : Array[(Installed, Step)] = []
for name, inst in ctx.state {
if planned.contains(name) {
continue
}
let m = manifest_of_installed(inst)
for st in steps {
if manifests_conflict(m, st.manifest) {
out.push((inst, st))
}
}
}
out
}
///|
fn conflict_lines(pairs : Array[(Installed, Step)]) -> String {
join(
pairs.map(fn(pair) {
let (inst, st) = pair
" - \{st.name} \{st.version} conflicts with installed \{inst.name} \{inst.version}"
}),
"\n",
)
}
///|
/// Fail if the plan conflicts with an installed package that stays.
fn check_plan_conflicts(
ctx : Ctx,
steps : Array[Step],
leaving : Array[String],
) -> Unit raise OrbitError {
let pairs = plan_conflicts(ctx, steps).filter(fn(pair) {
!leaving.contains(pair.0.name)
})
if pairs.length() > 0 {
raise OrbitError("conflicting packages:\n" + conflict_lines(pairs))
}
}
///|
/// Fail if a package that stays needs one that would be removed.
fn check_replaced_unneeded(
ctx : Ctx,
steps : Array[Step],
removals : Array[String],
) -> Unit raise OrbitError {
let planned : Map[String, Manifest] = Map([])
for st in steps {
planned[st.name] = st.manifest
}
for name, inst in ctx.state {
if removals.contains(name) {
continue
}
let depends = match planned.get(name) {
Some(m) => m.depends
None => inst.depends
}
for dk, _ in depends {
let dep = parse_dep_key(dk).1
if removals.contains(dep) {
raise OrbitError(
"cannot replace \{dep}: \{name} requires it\n" +
conflict_lines(plan_conflicts(ctx, steps)),
)
}
}
}
}
///|
/// Plan an install. If nothing fits beside the installed packages, plan to
/// replace the ones that conflict. Returns the plan and the packages to remove.
async fn plan_install(
ctx : Ctx,
reqs : Array[(String?, String, String, String)],
explicit_new : Map[String, String],
) -> (Array[Step], Array[String]) raise OrbitError {
try plan_global(ctx, reqs, [], explicit_new) catch {
OrbitError(msg) => {
if ctx.state.length() == 0 {
raise OrbitError(msg)
}
// See what the request would choose if nothing were installed.
let free = plan_global(ctx, reqs, [], explicit_new, ignore_installed=true) catch {
_ => raise OrbitError(msg)
}
let removals : Array[String] = []
for pair in plan_conflicts(ctx, free) {
if !removals.contains(pair.0.name) {
removals.push(pair.0.name)
}
}
if removals.length() == 0 {
raise OrbitError(msg)
}
// Solve again without only those packages.
let steps = plan_global(
ctx,
reqs,
[],
explicit_new,
replacing=removals,
)
let conflicting = plan_conflicts(ctx, steps).map(fn(p) { p.0.name })
for name in removals {
if !conflicting.contains(name) {
raise OrbitError(msg)
}
}
check_plan_conflicts(ctx, steps, removals)
check_replaced_unneeded(ctx, steps, removals)
(steps, removals)
}
} noraise {
steps => {
check_plan_conflicts(ctx, steps, [])
(steps, [])
}
}
}
///|
/// Get the user's agreement to remove conflicting packages.
async fn confirm_replace(
ctx : Ctx,
steps : Array[Step],
removals : Array[String],
interactive : Bool,
) -> Unit raise OrbitError {
let lines = conflict_lines(plan_conflicts(ctx, steps))
let names = join(removals, ", ")
if !interactive {
raise OrbitError(
"conflicting packages:\n\{lines}\nuse --replace to remove \{names}",
)
}
c_print_err(utf8_encode("\{lines}\nRemove \{names}? [y/N] "))
let answer = trim(read_stdin_line())
if answer != "y" && answer != "Y" && answer != "yes" {
raise OrbitError("nothing installed; \{names} kept")
}
}
///|
fn stdin_is_interactive() -> Bool {
c_isatty(0) != 0 && c_isatty(2) != 0
}
// ---------------------------------------------------------------- unit tests
///|
test "conflicts parse strictly and cover prereleases" {
let m = parse_manifest(
"{\"name\":\"tool-nightly\",\"version\":\"1.0.0\",\"conflicts\":{\"tool\":\"*\",\"old\":\">=1.0, <2.0\"}}",
)
assert_true(declares_conflict(m.conflicts, "tool", "1.0.0-rc1"))
assert_true(declares_conflict(m.conflicts, "old", "1.5.0-rc1"))
assert_false(declares_conflict(m.conflicts, "old", "2.0.0"))
assert_false(declares_conflict(m.conflicts, "other", "1.0.0"))
for
bad in [
"[\"tool\"]", "{\"tool\":1}", "{\"tool\":\"\"}", "{\"tool\":\"edge\"}", "{\"x\":\"*\"}",
"{\"main::tool\":\"*\"}",
] {
let rejected = try {
parse_manifest(
"{\"name\":\"x\",\"version\":\"1.0.0\",\"conflicts\":\{bad}}",
)
|> ignore
false
} catch {
OrbitError(_) => true
}
assert_true(rejected, msg=bad)
}
}
///|
fn mock_entry(manifest : Manifest) -> MockEntry {
MockEntry::{
channel: "main",
tag: manifest.version,
manifest,
favored: false,
}
}
///|
fn mock_req(name : String) -> SolveReq {
SolveReq::{ name, channel: None, constraint: "*", label: "root" }
}
///|
async test "solver keeps conflicting packages apart" {
let none : Map[String, String] = Map([])
let repo : Map[String, Array[MockEntry]] = Map([
("tool", [mock_entry(mock_manifest("tool", "1.0.0", none))]),
(
"tool-nightly",
[
mock_entry(
mock_manifest(
"tool-nightly",
"2.0.0",
none,
conflicts=Map([("tool", "*")]),
),
),
],
),
(
"app",
[
mock_entry(
mock_manifest("app", "2.0.0", Map([("tool-nightly", "*")])),
),
mock_entry(mock_manifest("app", "1.0.0", none)),
],
),
])
// Both orders fail: the declaring side may be expanded first or second.
for names in [["tool", "tool-nightly"], ["tool-nightly", "tool"]] {
let err = try {
ignore(solve(names.map(mock_req), make_mock_provider(repo)))
""
} catch {
OrbitError(m) => m
}
assert_true(
contains_str(err, "tool-nightly 2.0.0 conflicts with tool 1.0.0"),
msg=err,
)
}
// With a shared binary too, the declared conflict is the one reported.
let shared : Map[String, Array[MockEntry]] = Map([
("a", [mock_entry(mock_manifest("a", "1.0.0", none, bins=["bin/t"]))]),
(
"b",
[
mock_entry(
mock_manifest(
"b",
"1.0.0",
none,
bins=["bin/t"],
conflicts=Map([("a", "*")]),
),
),
],
),
])
let shared_err = try {
ignore(solve([mock_req("a"), mock_req("b")], make_mock_provider(shared)))
""
} catch {
OrbitError(m) => m
}
assert_true(
contains_str(shared_err, "b 1.0.0 conflicts with a 1.0.0"),
msg=shared_err,
)
// A dependency's conflict sends the solver to an older version, in any order.
for names in [["tool", "app"], ["app", "tool"]] {
let m = solved_map(
solve(names.map(mock_req), make_mock_provider(repo)),
)
assert_eq(m.get("app"), Some("1.0.0"))
assert_eq(m.get("tool"), Some("1.0.0"))
assert_false(m.contains("tool-nightly"))
}
// Installed packages outside the solve count too, whichever side declares it.
let locked = make_mock_provider(
repo,
locked=Map([
("tool", LockedInfo::{ version: "1.0.0-rc1", conflicts: none }),
]),
)
assert_eq(solved_map(solve([mock_req("app")], locked)).get("app"), Some("1.0.0"))
let locked2 = make_mock_provider(
repo,
locked=Map([
(
"other",
LockedInfo::{ version: "1.0.0", conflicts: Map([("app", ">=2")]) },
),
]),
)
assert_eq(
solved_map(solve([mock_req("app")], locked2)).get("app"),
Some("1.0.0"),
)
}
+162
View File
@@ -0,0 +1,162 @@
// What install and info print about a package.
///|
/// Label and values. Each value after the first gets its own line.
type Detail = (String, Array[String])
///|
/// Align details in columns, dropping empty ones. Values may come from a
/// registry, so control characters are blanked.
fn detail_lines(details : Array[Detail], indent : String) -> Array[String] {
let lines : Array[String] = []
for detail in details {
let (label, values) = detail
let mut head = label + ":"
for v in values {
if v != "" {
lines.push(indent + pad_right(head, 13) + printable(v))
head = ""
}
}
}
lines
}
///|
fn print_details(details : Array[Detail], indent : String) -> Unit {
for line in detail_lines(details, indent) {
println(line)
}
}
///|
/// The details of a build that install and info share. `bin_dir` is where its
/// commands are linked, `store` where its files are.
fn package_details(
m : Manifest,
channel~ : String,
digest~ : String,
store~ : String,
bin_dir~ : String,
) -> Array[Detail] {
let bins = m.bins.map(b => bin_dir + "/" + basename(b) + " -> " + b)
if bins.is_empty() {
bins.push("(none)")
}
let specs = fn(reqs : Map[String, String]) {
let out : Array[String] = []
for n, c in reqs {
out.push(n + "@" + c)
}
join(out, " ")
}
[
("description", [m.description]),
("channel", [channel]),
("digest", [digest]),
("path", [store]),
("bin", bins),
("depends", [specs(m.depends)]),
("conflicts", [specs(m.conflicts)]),
]
}
///|
/// The details of a build in a channel that isn't installed: it has no paths
/// yet, so bins are shown as they sit in the package.
fn available_details(
m : Manifest,
channel~ : String,
digest~ : String,
) -> Array[Detail] {
let bins = m.bins.copy()
if bins.is_empty() {
bins.push("(none)")
}
let specs = fn(reqs : Map[String, String]) {
let out : Array[String] = []
for n, c in reqs {
out.push(n + "@" + c)
}
join(out, " ")
}
[
("description", [m.description]),
("docs", [m.documentation]),
("channel", [channel]),
("digest", [digest]),
("bin", bins),
("depends", [specs(m.depends)]),
("conflicts", [specs(m.conflicts)]),
]
}
///|
fn installed_details(ctx : Ctx, p : Installed) -> Array[Detail] {
package_details(
manifest_of_installed(p),
channel=p.channel,
digest=p.digest,
store=store_dir(ctx, p.name, p.digest),
bin_dir=bin_dir(ctx),
)
}
///|
fn locked_details(
ctx : Ctx,
project_dir : String,
p : LockedPkg,
) -> Array[Detail] {
package_details(
manifest_of_locked(p),
channel=p.channel,
digest=p.digest,
store=store_dir(ctx, p.name, p.digest),
bin_dir=project_env_dir(project_dir) + "/bin",
)
}
///|
test "package details show paths and every bin" {
let m = parse_manifest(
"{\"name\":\"t\",\"version\":\"1.0.0\",\"description\":\"A\\u001btool\",\"bin\":[\"bin/a\",\"libexec/b\"],\"depends\":{\"x\":\"^1\"},\"conflicts\":{\"y\":\"*\"}}",
)
let details = package_details(
m,
channel="main",
digest="sha256:ab",
store="/o/store/t/ab",
bin_dir="/o/bin",
)
assert_eq(detail_lines(details, " "), [
" description: A tool", " channel: main", " digest: sha256:ab", " path: /o/store/t/ab",
" bin: /o/bin/a -> bin/a", " /o/bin/b -> libexec/b", " depends: x@^1",
" conflicts: y@*",
])
let bare = package_details(
parse_manifest("{\"name\":\"t\",\"version\":\"1.0.0\"}"),
channel="main",
digest="sha256:ab",
store="/o/store/t/ab",
bin_dir="/o/bin",
)
assert_eq(detail_lines(bare, ""), [
"channel: main", "digest: sha256:ab", "path: /o/store/t/ab",
"bin: (none)",
])
}
///|
test "available details show bins as packaged and the docs link" {
let m = parse_manifest(
"{\"name\":\"t\",\"version\":\"1.0.0\",\"description\":\"A tool\",\"documentation\":\"https://x/t\",\"bin\":[\"bin/a\"],\"depends\":{\"x\":\"^1\"}}",
)
assert_eq(
detail_lines(available_details(m, channel="main", digest="sha256:ab"), ""),
[
"description: A tool", "docs: https://x/t", "channel: main", "digest: sha256:ab",
"bin: bin/a", "depends: x@^1",
],
)
}
+373
View File
@@ -0,0 +1,373 @@
// The channel index: one OCI artifact per channel that lists its packages, so
// search needs no catalog API. Installs never use it.
///|
/// Repository name of the index inside a channel. Not usable as a package name.
const INDEX_NAME : String = "orbit-index"
///|
const INDEX_ARTIFACT_TYPE : String = "application/vnd.latha.orbit.index.v1"
///|
const INDEX_MEDIA_TYPE : String = "application/vnd.latha.orbit.index.v1+json"
///|
const EMPTY_MEDIA_TYPE : String = "application/vnd.oci.empty.v1+json"
///|
struct IndexEntry {
name : String
version : String
description : String
versions : Array[String] // newest first
digest : String // of the `version` manifest; "" in older indexes
}
///|
fn index_object(entries : Array[IndexEntry]) -> Map[String, Json] {
let sorted = entries.copy()
sorted.sort_by(fn(a, b) { a.name.lexical_compare(b.name) })
let pkgs : Array[Json] = []
for e in sorted {
let o : Map[String, Json] = Map([])
o["name"] = Json::string(e.name)
o["version"] = Json::string(e.version)
o["description"] = Json::string(e.description)
o["versions"] = strs_json(e.versions)
if e.digest != "" {
o["digest"] = Json::string(e.digest)
}
pkgs.push(Json::object(o))
}
let top : Map[String, Json] = Map([])
top["packages"] = Json::array(pkgs)
top
}
///|
fn index_json(entries : Array[IndexEntry]) -> String {
Json::object(index_object(entries)).stringify() + "\n"
}
///|
fn parse_index(text : String) -> Array[IndexEntry] raise OrbitError {
let top = parse_object(text, "channel index")
let pkgs = match top.get("packages") {
Some(Json::Array(xs)) => xs
_ => raise OrbitError("channel index: expected 'packages' to be an array")
}
let out : Array[IndexEntry] = []
for p in pkgs {
match p {
Json::Object(o) => {
let name = jstr(o, "name", "")
// Skip names that `orbit install` couldn't use.
if valid_name(name) && name != INDEX_NAME {
out.push(IndexEntry::{
name,
version: jstr(o, "version", ""),
description: jstr(o, "description", ""),
versions: jstrs(o, "versions"),
digest: jstr(o, "digest", ""),
})
}
}
_ => ()
}
}
out
}
///|
/// The digest of the index layer, or None if the manifest isn't an index.
fn index_layer_digest(text : String) -> String? raise OrbitError {
let o = parse_object(text, "index manifest")
if jstr(o, "artifactType", "") != INDEX_ARTIFACT_TYPE {
return None
}
match o.get("layers") {
Some(Json::Array([Json::Object(l), ..])) => {
let d = jstr(l, "digest", "")
if has_prefix(d, "sha256:") {
return Some(d)
}
}
_ => ()
}
raise OrbitError("index manifest has no sha256 layer")
}
///|
/// The channel's index, or None if it has none. A 404 here only means "no
/// index", even after a rejected login, so that check is skipped.
async fn load_index(ch : Channel) -> Array[IndexEntry]? raise OrbitError {
with_spinner("Reading index of \{ch.name}", () => {
let repo = channel_repo_path(ch, INDEX_NAME)
let base = channel_base_url(ch) + "/v2/" + repo
let get = async fn(path : String, accept : String) {
oci_request(
Get,
base + path,
Map([("Accept", accept)]),
b"",
repo + ":pull",
check_login=false,
)
}
let (resp, body) = get("/manifests/latest", MANIFEST_ACCEPT)
if is_missing_status(resp.code) {
return None
}
if resp.code < 200 || resp.code >= 300 {
raise OrbitError(format_oci_error(resp.code, resp.reason, body))
}
let digest = match index_layer_digest(utf8_decode(body)) {
Some(d) => d
None => return None
}
let (blob_resp, blob) = get("/blobs/" + digest, "application/json")
if blob_resp.code < 200 || blob_resp.code >= 300 {
raise OrbitError(
format_oci_error(blob_resp.code, blob_resp.reason, blob),
)
}
let actual = sha256_digest(blob)
if actual != digest {
raise OrbitError("index digest mismatch: expected \{digest}, got \{actual}")
}
Some(parse_index(utf8_decode(blob)))
})
}
///|
async fn push_index(
ch : Channel,
entries : Array[IndexEntry],
) -> Unit raise OrbitError {
let base = channel_base_url(ch)
let repo = channel_repo_path(ch, INDEX_NAME)
let config = b"{}"
let data = utf8_encode(index_json(entries))
let descriptor = fn(media_type : String, bytes : Bytes) {
let o : Map[String, Json] = Map([])
o["mediaType"] = Json::string(media_type)
o["digest"] = Json::string(sha256_digest(bytes))
o["size"] = json_int64(bytes.length().to_int64())
Json::object(o)
}
let ann : Map[String, Json] = Map([])
ann["org.opencontainers.image.created"] = Json::string(utc_now())
let manifest : Map[String, Json] = Map([])
manifest["schemaVersion"] = json_int64(2L)
manifest["mediaType"] = Json::string(OCI_MANIFEST_MEDIA_TYPE)
manifest["artifactType"] = Json::string(INDEX_ARTIFACT_TYPE)
manifest["config"] = descriptor(EMPTY_MEDIA_TYPE, config)
manifest["layers"] = Json::array([descriptor(INDEX_MEDIA_TYPE, data)])
manifest["annotations"] = Json::object(ann)
with_spinner("Publishing index of \{ch.name}", () => {
upload_blob_bytes(base, repo, sha256_digest(config), config)
upload_blob_bytes(base, repo, sha256_digest(data), data)
put_manifest(
base,
repo,
"latest",
utf8_encode(Json::object(manifest).stringify() + "\n"),
)
})
}
///|
/// Read one package from the registry. None means it doesn't exist or isn't an
/// Orbit package; failures are errors so that they can't drop a package.
async fn read_index_entry(
ch : Channel,
name : String,
) -> IndexEntry? raise OrbitError {
let tags = match list_tags_quiet(ch, name) {
Some(ts) => ts
None => return None
}
if tags.length() == 0 {
return None
}
let tag = if tags.contains("latest") { "latest" } else { tags[0] }
let raw = fetch_raw_manifest_bytes(ch, name, tag)
match orbit_info(utf8_decode(raw)) {
Some(info) =>
Some(IndexEntry::{
name,
version: info.version,
description: info.description,
versions: sorted_versions(tags),
digest: sha256_digest(raw),
})
None => None
}
}
///|
fn find_entry(entries : Array[IndexEntry], name : String) -> IndexEntry? {
for e in entries {
if e.name == name {
return Some(e)
}
}
None
}
///|
/// Read every named package. Returns those found, and the names that couldn't
/// be read with the reason.
async fn read_entries(
ch : Channel,
names : Array[String],
) -> (Array[IndexEntry], Array[(String, String)]) raise OrbitError {
if names.length() == 0 {
return ([], [])
}
let results : Array[(String, Result[IndexEntry?, String])] = []
with_spinner("Reading \{names.length()} repositories in \{ch.name}", () => {
@async.with_task_group(group => {
let tasks : Array[@async.Task[Result[IndexEntry?, String]]] = []
for n in names {
tasks.push(
group.spawn(() => {
try Ok(read_index_entry(ch, n)) catch {
OrbitError(msg) => Err(msg)
}
}),
)
}
for i, t in tasks {
results.push((names[i], t.wait()))
}
})
})
let out : Array[IndexEntry] = []
let failed : Array[(String, String)] = []
for r in results {
match r {
(_, Ok(Some(e))) => out.push(e)
(_, Ok(None)) => ()
(n, Err(msg)) => failed.push((n, msg))
}
}
(out, failed)
}
///|
/// Read every named package. One that can't be read keeps its old entry.
async fn build_index(
ch : Channel,
names : Array[String],
old : Array[IndexEntry],
) -> Array[IndexEntry] raise OrbitError {
let (out, failed) = read_entries(ch, names)
for f in failed {
let (n, msg) = f
println("warning: cannot read '\{n}': \{msg}")
match find_entry(old, n) {
Some(e) => out.push(e)
None => ()
}
}
out
}
///|
/// Rebuild a channel's index. Without names, the packages come from the
/// registry's catalog; with names, from those names and the existing index.
async fn cmd_index(
ch : Channel,
names : Array[String],
) -> Unit raise OrbitError {
let old = load_index(ch)
rebuild_index(ch, names, old)
}
///|
async fn rebuild_index(
ch : Channel,
names : Array[String],
old : Array[IndexEntry]?,
) -> Unit raise OrbitError {
let old = old.unwrap_or([])
let all : Array[String] = []
let found = if names.length() == 0 { list_repos(ch) } else { names }
for n in found {
if valid_name(n) && n != INDEX_NAME && !all.contains(n) {
all.push(n)
}
}
if names.length() > 0 {
for e in old {
if !all.contains(e.name) {
all.push(e.name)
}
}
}
let entries = build_index(ch, all, old)
push_index(ch, entries)
println("indexed \{entries.length()} package(s) in \{repo_of(ch, INDEX_NAME)}")
}
///|
/// Record a just-published package. A channel without an index gets a full one,
/// because an index with one package would hide the others from search.
/// The package is already published, so failures here are only warnings.
async fn index_published(ch : Channel, name : String) -> Unit noraise {
try {
match load_index(ch) {
None => rebuild_index(ch, [], None)
Some(old) => {
let entries = old.filter(fn(e) { e.name != name })
match read_index_entry(ch, name) {
Some(e) => entries.push(e)
None => ()
}
push_index(ch, entries)
}
}
} catch {
e => {
let msg = match e {
OrbitError(m) => m
}
println("warning: index of channel '\{ch.name}' not updated: \{msg}")
}
}
}
///|
test "index round-trips, sorted, without unusable names" {
let entry = fn(name : String) {
IndexEntry::{
name,
version: "1.0.0",
description: "d",
versions: ["1.0.0"],
digest: "sha256:ab",
}
}
let parsed = parse_index(
index_json([
entry("zed"),
entry("a"),
entry("example/greet"),
entry(INDEX_NAME),
]),
)
assert_eq(parsed.map(fn(e) { e.name }), ["a", "zed"])
assert_eq(parsed[0].versions, ["1.0.0"])
assert_eq(parsed[0].digest, "sha256:ab")
// Indexes written before digests were recorded still parse.
let old = parse_index(
"{\"packages\":[{\"name\":\"a\",\"version\":\"1.0.0\",\"description\":\"d\",\"versions\":[\"1.0.0\"]}]}",
)
assert_eq(old[0].digest, "")
// Only an index artifact is used, and it is not an Orbit package.
assert_true(index_layer_digest("{\"artifactType\":\"x\"}") is None)
assert_true(
orbit_info("{\"artifactType\":\"\{INDEX_ARTIFACT_TYPE}\"}") is None,
)
}
+196
View File
@@ -0,0 +1,196 @@
// Local copies of channel listings, so that a repeated search or info needs no
// network. Installs and version lookups never read them.
///|
/// How long a copy is used before it is fetched again.
const INDEX_TTL_MS : UInt64 = 3_600_000
///|
/// A channel without an index is read whole, so that it can be cached, only up
/// to this many repositories. Beyond that just the matching names are read.
const MAX_LISTED_REPOS : Int32 = 100
///|
fn index_cache_dir(root : String) -> String {
root + "/cache/indexes"
}
///|
/// Copies belong to a URL, not a channel name, which can be repointed.
fn index_cache_path(root : String, ch : Channel) -> String {
let key = channel_scheme(ch) + "://" + ch.url
index_cache_dir(root) +
"/" +
drop_chars(sha256_digest(utf8_encode(key)), 7) +
".json"
}
///|
struct CachedIndex {
entries : Array[IndexEntry]
fetched : UInt64 // milliseconds since the epoch
}
///|
fn is_fresh(c : CachedIndex, now : UInt64) -> Bool {
c.fetched <= now && now - c.fetched < INDEX_TTL_MS
}
///|
/// None if there is no usable copy.
async fn read_cached_index(root : String, ch : Channel) -> CachedIndex? noraise {
let text = match read_text(index_cache_path(root, ch)) {
Some(t) => t
None => return None
}
try {
let top = parse_object(text, "cached index")
let fetched = @string.parse_uint64(jstr(top, "fetched", ""))
Some(CachedIndex::{ entries: parse_index(text), fetched })
} catch {
_ => None
}
}
///|
/// Failing to write a copy only costs speed. It may name private packages, so
/// only the user can read it.
async fn write_cached_index(
root : String,
ch : Channel,
entries : Array[IndexEntry],
now : UInt64,
) -> Unit noraise {
try {
@fs.mkdir(index_cache_dir(root), recursive=true, allow_exist=true)
let top = index_object(entries)
top["fetched"] = Json::string(now.to_string())
write_secret_atomic(
index_cache_path(root, ch),
Json::object(top).stringify() + "\n",
)
} catch {
_ => ()
}
}
///|
/// Forget the copy of a channel that was just published to.
async fn drop_cached_index(root : String, ch : Channel) -> Unit noraise {
@fs.remove(index_cache_path(root, ch)) catch {
_ => ()
}
}
///|
/// Forget every copy, as a login or logout changes what may be listed.
async fn drop_cached_indexes(root : String) -> Unit noraise {
@fs.rmdir(index_cache_dir(root), recursive=true, allow_missing=true) catch {
_ => ()
}
}
///|
/// A channel's packages for search and info, which still have to match `term`
/// (a large channel without an index only lists those that do): a fresh
/// copy, else its index, else the registry's catalog. If the registry fails, an
/// old copy is used. None means the channel couldn't be listed.
async fn channel_listing(
root : String,
ch : Channel,
term : String,
refresh : Bool,
) -> Array[IndexEntry]? noraise {
let now = @env.now()
let cached = read_cached_index(root, ch)
if !refresh && cached is Some(c) && is_fresh(c, now) {
return Some(c.entries)
}
let mut index_failed = false
try {
match load_index(ch) {
Some(entries) => {
write_cached_index(root, ch, entries, now)
return Some(entries)
}
None => ()
}
} catch {
OrbitError(msg) => {
index_failed = true
if cached is Some(c) {
println(
"warning: cannot refresh channel '\{ch.name}', using its saved index: \{msg}",
)
return Some(c.entries)
}
println("warning: cannot read index of channel '\{ch.name}': \{msg}")
}
}
try {
let (entries, complete) = list_catalog(ch, term)
if complete && !index_failed {
write_cached_index(root, ch, entries, now)
}
Some(entries)
} catch {
OrbitError(msg) =>
match cached {
Some(c) => {
println(
"warning: cannot refresh channel '\{ch.name}', using its saved list: \{msg}",
)
Some(c.entries)
}
None => {
println("warning: cannot list channel '\{ch.name}': \{msg}")
None
}
}
}
}
///|
/// Read a channel from the registry's catalog, and whether the result is
/// complete: every package, all of them readable.
async fn list_catalog(
ch : Channel,
term : String,
) -> (Array[IndexEntry], Bool) raise OrbitError {
// A name with "/" is a nested channel namespace (e.g. example/greet under
// main), not a package name that `orbit install` could use.
let all = list_repos(ch).filter(fn(r) { valid_name(r) && r != INDEX_NAME })
if all.length() <= MAX_LISTED_REPOS {
let (entries, failed) = read_entries(ch, all)
for f in failed {
println("warning: cannot read '\{f.0}': \{f.1}")
}
return (entries, failed.length() == 0)
}
let names = all.filter(fn(r) { contains_str(r, term) })
let found = find_orbit_repos(ch, names)
let entries : Array[IndexEntry] = []
for i, name in names {
match found[i] {
Some(info) =>
entries.push(IndexEntry::{
name,
version: info.version,
description: info.description,
versions: [],
digest: "",
})
None => ()
}
}
(entries, false)
}
///|
test "a copy is fresh for an hour, and never from the future" {
let c = CachedIndex::{ entries: [], fetched: 1000 }
assert_true(is_fresh(c, 1000))
assert_true(is_fresh(c, 1000 + INDEX_TTL_MS - 1))
assert_false(is_fresh(c, 1000 + INDEX_TTL_MS))
assert_false(is_fresh(c, 999))
}
+270 -38
View File
@@ -1,32 +1,62 @@
// orbit: a package manager whose repository is any OCI registry, via ORAS.
// orbit: a package manager whose repository is any OCI registry.
///|
/// Orbit's version. A test keeps it equal to the one in moon.mod.
let orbit_version : String = "0.1.0"
///|
let usage : String =
#|orbit - packages as OCI artifacts (via oras)
#|orbit - packages as OCI artifacts
#|
#|usage:
#| orbit init create folders and config.toml
#|usage (project workflow, when orbit.toml is present):
#| orbit new [dir] create a project orbit.toml
#| orbit add [channel::]<name>[@constraint]...
#| solve, pin in orbit.toml, lock & sync
#| orbit install [--locked | --frozen] sync .orbit/ from orbit.toml / orbit.lock
#| orbit sync [--locked | --frozen] same as `orbit install` in a project
#| orbit lock [--update] resolve and write orbit.lock
#| orbit update [name...] upgrade locked packages within constraints
#| orbit remove <name>... remove from orbit.toml, re-lock & sync
#| orbit run [--locked | --frozen] <cmd|task> [args...]
#| run a command or [tasks] entry in .orbit
#| orbit list show locked project packages
#| orbit env print PATH for .orbit/bin + global bin
#|
#|usage (global & registry commands; add -g/--global inside a project):
#| orbit init [--project] create ~/.orbit (or --project for orbit.toml)
#| orbit login <host> [-u <user>] [-p <pass> | --password-stdin] [--plain-http]
#| log in to an OCI registry
#| orbit logout <host> remove stored registry credentials
#| orbit channel list channels, highest priority first
#| orbit channel add <name> <url> [--plain-http]
#| orbit publish <dir> [--channel <name>] [--no-latest]
#| orbit publish <dir> [--channel <name>] [--no-latest] [--no-index]
#| push <dir>/orbit.json + <dir>/files/
#| orbit install [channel::]<name>[@constraint]...
#| install with dependencies
#| orbit remove <name>... [--force] remove, then drop unused dependencies
#| orbit upgrade [name...] upgrade within constraints
#| orbit rollback <name> switch to the previous build
#| orbit list installed packages
#| orbit info [channel::]<name> installed package details (local only)
#| orbit index [--channel <name>] [name...]
#| rebuild the channel's package index
#| orbit install [-g] [channel::]<name>[@constraint]...
#| install globally with SAT dependency solving
#| (--replace: remove conflicting packages
#| without asking)
#| orbit remove [-g] <name>... [--force] remove, then drop unused dependencies
#| orbit upgrade [-g] [name...] jointly upgrade within constraints
#| orbit rollback <name> switch to the previous global build
#| orbit list [-g] installed global packages
#| orbit info [-g] [channel::]<name>[@constraint]
#| details of an installed package, else of
#| the newest matching build in a channel
#| orbit versions <name> published versions
#| orbit search [term] list repositories (needs catalog API)
#| orbit search [--refresh] [term] list packages (cached for an hour)
#| orbit gc delete unused builds from the store
#| orbit env print the PATH line for your shell
#| orbit env [-g] print the PATH line for your shell
#|
#|constraints: 1.2.3 =1.2.3 1.2 ^1.2.0 ~1.2.0 >=1.2 *
#|flags: -g, --global --manifest-path <path> --locked --frozen
#| -h, --help -V, --version
#|constraints: 1.2.3 =1.2.3 ==1.2.3 1.2.* ^1.2.0 ~1.2.0 >=1.2 <2.0 !=1.3.0 *
#| (comma-separated clauses are ANDed, e.g. ">=1.2.0, <2.0.0")
#|config: <orbit root>/config.toml
#|credentials: <orbit root>/auth.json (falls back to ~/.docker/config.json)
#|environment: ORBIT_ROOT (default ~/.orbit); ORBIT_REGISTRY and
#| ORBIT_PLAIN_HTTP=1 override the built-in main channel
#|authentication: run `oras login <registry-host>` once.
///|
/// Create the directories, and a config.toml if there is no config yet.
@@ -59,6 +89,34 @@ fn need(pos : Array[String], n : Int32, what : String) -> Unit raise OrbitError
}
}
///|
async fn resolve_project_or_none(
force_global : Bool,
manifest_path : String?,
) -> String? raise OrbitError {
if force_global {
if manifest_path is Some(_) {
raise OrbitError("--global cannot be used with --manifest-path")
}
None
} else {
find_project_manifest(manifest_path)
}
}
///|
async fn require_project_manifest(
manifest_path : String?,
) -> String raise OrbitError {
match find_project_manifest(manifest_path) {
Some(mf) => mf
None =>
raise OrbitError(
"no orbit.toml found in current or parent directories (run `orbit new` to create one)",
)
}
}
///|
async fn dispatch(args : Array[String]) -> Unit raise OrbitError {
if args.length() == 0 {
@@ -69,31 +127,113 @@ async fn dispatch(args : Array[String]) -> Unit raise OrbitError {
let pos : Array[String] = []
let flags : Array[String] = []
let mut publish_to = MAIN_CHANNEL
let mut username : String? = None
let mut password : String? = None
let mut force_global = false
let mut manifest_path : String? = None
let mut i = 1
while i < args.length() {
if args[i] == "--channel" {
if cmd != "publish" || i + 1 >= args.length() {
raise OrbitError("usage: orbit publish <dir> --channel <name>")
if cmd == "run" && pos.length() > 0 {
// Forward all flags/args after the command/task name verbatim.
pos.push(args[i])
i = i + 1
continue
}
let a = args[i]
if a == "--" {
i = i + 1
while i < args.length() {
pos.push(args[i])
i = i + 1
}
break
} else if a == "-g" || a == "--global" {
force_global = true
} else if a == "--manifest-path" {
if i + 1 >= args.length() {
raise OrbitError("usage: --manifest-path <path>")
}
manifest_path = Some(args[i + 1])
i = i + 1
} else if has_prefix(a, "--manifest-path=") {
manifest_path = Some(drop_chars(a, 16))
} else if a == "--channel" {
if (cmd != "publish" && cmd != "index") || i + 1 >= args.length() {
raise OrbitError("usage: orbit publish <dir> | index --channel <name>")
}
publish_to = args[i + 1]
i = i + 1
} else if has_prefix(args[i], "--") {
flags.push(args[i])
} else if a == "-u" || a == "--username" {
if cmd != "login" || i + 1 >= args.length() {
raise OrbitError(
"usage: orbit login <host> [-u <user>] [-p <pass> | --password-stdin] [--plain-http]",
)
}
username = Some(args[i + 1])
i = i + 1
} else if has_prefix(a, "--username=") {
if cmd != "login" {
raise OrbitError("unknown flag '\{a}'")
}
username = Some(drop_chars(a, 11))
} else if a == "-p" || a == "--password" {
if cmd != "login" || i + 1 >= args.length() {
raise OrbitError(
"usage: orbit login <host> [-u <user>] [-p <pass> | --password-stdin] [--plain-http]",
)
}
password = Some(args[i + 1])
i = i + 1
} else if has_prefix(a, "--password=") {
if cmd != "login" {
raise OrbitError("unknown flag '\{a}'")
}
password = Some(drop_chars(a, 11))
} else if has_prefix(a, "--") {
flags.push(a)
} else {
pos.push(args[i])
pos.push(a)
}
i = i + 1
}
match cmd {
"help" | "-h" | "--help" => println(usage)
"init" => {
"-V" | "--version" => println("orbit \{orbit_version}")
"new" => {
if force_global {
raise OrbitError("--global cannot be used with `orbit new`")
}
cmd_project_init(if pos.length() > 0 { Some(pos[0]) } else { None })
}
"init" =>
if flags.contains("--project") {
cmd_project_init(if pos.length() > 0 { Some(pos[0]) } else { None })
} else {
if pos.length() > 0 {
raise OrbitError(
"init takes no arguments; use `orbit channel add <name> <url>`",
"init takes no arguments; use `orbit channel add <name> <url>` or `orbit new <dir>`",
)
}
cmd_init()
}
"login" => {
need(
pos,
1,
"login <host> [-u <user>] [-p <pass> | --password-stdin] [--plain-http]",
)
cmd_login(
pos[0],
username,
password,
flags.contains("--password-stdin"),
flags.contains("--plain-http"),
)
}
"logout" => {
need(pos, 1, "logout <host>")
cmd_logout(pos[0])
}
"channel" => {
need(pos, 1, "channel list|add")
match pos[0] {
@@ -110,30 +250,126 @@ async fn dispatch(args : Array[String]) -> Unit raise OrbitError {
other => raise OrbitError("unknown channel command '\{other}'")
}
}
"env" => println("export PATH=\"\{orbit_root()}/bin:$PATH\"")
"lock" => {
if force_global {
raise OrbitError("--global cannot be used with `orbit lock`")
}
let mf = require_project_manifest(manifest_path)
cmd_project_lock(load_ctx(), mf, flags.contains("--update"))
}
"sync" => {
if force_global {
raise OrbitError("--global cannot be used with `orbit sync`")
}
let mf = require_project_manifest(manifest_path)
cmd_project_sync(
load_ctx(),
mf,
flags.contains("--locked"),
flags.contains("--frozen"),
)
}
"run" => {
if force_global {
raise OrbitError("--global cannot be used with `orbit run`")
}
let mf = require_project_manifest(manifest_path)
need(pos, 1, "run [--locked|--frozen] <command|task> [args...]")
cmd_project_run(
load_ctx(),
mf,
pos,
flags.contains("--locked"),
flags.contains("--frozen"),
)
}
"env" =>
match resolve_project_or_none(force_global, manifest_path) {
Some(mf) => cmd_project_env(load_ctx(), mf)
None => println("export PATH=\"\{orbit_root()}/bin:$PATH\"")
}
"publish" => {
need(pos, 1, "publish <dir>")
let ch = find_channel(load_ctx(), publish_to)
publish(ch, pos[0], !flags.contains("--no-latest"))
let ctx = load_ctx()
let ch = find_channel(ctx, publish_to)
publish(
ch,
pos[0],
!flags.contains("--no-latest"),
update_index=!flags.contains("--no-index"),
)
drop_cached_index(ctx.root, ch)
}
"index" => {
let ctx = load_ctx()
let ch = find_channel(ctx, publish_to)
cmd_index(ch, pos)
drop_cached_index(ctx.root, ch)
}
"install" =>
match resolve_project_or_none(force_global, manifest_path) {
Some(mf) =>
if pos.length() == 0 {
cmd_project_sync(
load_ctx(),
mf,
flags.contains("--locked"),
flags.contains("--frozen"),
)
} else {
raise OrbitError(
"in a project (found \{mf}), use `orbit add <pkg>...` to add dependencies or `orbit install -g <pkg>...` to install globally",
)
}
None =>
cmd_install(load_ctx(), pos, replace=flags.contains("--replace"))
}
"add" =>
match resolve_project_or_none(force_global, manifest_path) {
Some(mf) => cmd_project_add(load_ctx(), mf, pos)
None =>
cmd_install(load_ctx(), pos, replace=flags.contains("--replace"))
}
"remove" | "rm" =>
match resolve_project_or_none(force_global, manifest_path) {
Some(mf) => cmd_project_remove(load_ctx(), mf, pos)
None => cmd_remove(load_ctx(), pos, flags.contains("--force"))
}
"upgrade" | "up" | "update" =>
match resolve_project_or_none(force_global, manifest_path) {
Some(mf) => cmd_project_update(load_ctx(), mf, pos)
None => cmd_upgrade(load_ctx(), pos)
}
"install" | "add" => cmd_install(load_ctx(), pos)
"remove" | "rm" => cmd_remove(load_ctx(), pos, flags.contains("--force"))
"upgrade" | "up" => cmd_upgrade(load_ctx(), pos)
"rollback" => {
need(pos, 1, "rollback <name>")
cmd_rollback(load_ctx(), pos[0])
}
"list" | "ls" => cmd_list(load_ctx())
"list" | "ls" =>
match resolve_project_or_none(force_global, manifest_path) {
Some(mf) => cmd_project_list(load_ctx(), mf)
None => cmd_list(load_ctx())
}
"info" => {
need(pos, 1, "info [channel::]<name>")
cmd_info(load_ctx(), pos[0])
need(pos, 1, "info [channel::]<name>[@constraint]")
match resolve_project_or_none(force_global, manifest_path) {
Some(mf) => cmd_project_info(load_ctx(), mf, pos[0])
None => cmd_info(load_ctx(), pos[0])
}
}
"versions" => {
need(pos, 1, "versions <name>")
cmd_versions(load_ctx(), pos[0])
}
"search" =>
cmd_search(load_ctx(), if pos.length() > 0 { pos[0] } else { "" })
cmd_search(
load_ctx(),
if pos.length() > 0 {
pos[0]
} else {
""
},
refresh=flags.contains("--refresh"),
)
"gc" => cmd_gc(load_ctx())
_ => raise OrbitError("unknown command '\{cmd}' (try `orbit help`)")
}
@@ -141,10 +377,6 @@ async fn dispatch(args : Array[String]) -> Unit raise OrbitError {
///|
async fn main {
if sh("command -v oras >/dev/null 2>&1") != 0 {
println("orbit: error: `oras` not found on PATH (https://oras.land)")
c_exit(1)
}
dispatch(cli_args()) catch {
OrbitError(msg) => {
println("orbit: error: \{msg}")
+67 -5
View File
@@ -18,6 +18,7 @@ struct Manifest {
description : String
documentation : String
depends : Map[String, String]
conflicts : Map[String, String]
bins : Array[String]
}
@@ -30,6 +31,7 @@ struct Gen {
description : String
bins : Array[String]
depends : Map[String, String]
conflicts : Map[String, String]
}
///|
@@ -43,6 +45,7 @@ struct Installed {
mut constraint : String
mut bins : Array[String]
mut depends : Map[String, String]
mut conflicts : Map[String, String]
history : Array[Gen]
}
@@ -179,15 +182,32 @@ fn valid_rel_path(p : String) -> Bool {
true
}
///|
/// Split a dependency key "[channel::]name" into (channel_pin, package_name).
fn parse_dep_key(key : String) -> (String?, String) {
split_channel(key)
}
///|
fn valid_dep_key(key : String) -> Bool {
let (ch, name) = parse_dep_key(key)
match ch {
Some(c) => valid_name(c) && valid_name(name)
None => valid_name(name)
}
}
///|
fn parse_manifest(text : String) -> Manifest raise OrbitError {
let o = parse_object(text, "orbit.json")
let name = jstr(o, "name", "")
let m = Manifest::{
name: jstr(o, "name", ""),
name,
version: jstr(o, "version", ""),
description: jstr(o, "description", ""),
documentation: jstr(o, "documentation", ""),
depends: jmap(o, "depends"),
conflicts: parse_conflicts(o, name),
bins: jstrs(o, "bin"),
}
if !valid_name(m.name) {
@@ -203,10 +223,15 @@ fn parse_manifest(text : String) -> Manifest raise OrbitError {
raise OrbitError("orbit.json: bin path '\{b}' must be relative")
}
}
for dep, _ in m.depends {
if !valid_name(dep) {
for dep, constraint in m.depends {
if !valid_dep_key(dep) {
raise OrbitError("orbit.json: invalid dependency name '\{dep}'")
}
if !valid_constraint(constraint) {
raise OrbitError(
"orbit.json: invalid version constraint '\{constraint}' for '\{dep}'",
)
}
}
m
}
@@ -222,6 +247,7 @@ fn gen_json(g : Gen) -> Json {
o["description"] = Json::string(g.description)
o["bin"] = strs_json(g.bins)
o["depends"] = map_json(g.depends)
o["conflicts"] = map_json(g.conflicts)
Json::object(o)
}
@@ -236,6 +262,7 @@ fn installed_json(p : Installed) -> Json {
o["constraint"] = Json::string(p.constraint)
o["bin"] = strs_json(p.bins)
o["depends"] = map_json(p.depends)
o["conflicts"] = map_json(p.conflicts)
let h : Array[Json] = []
for g in p.history {
h.push(gen_json(g))
@@ -278,6 +305,7 @@ fn state_from_text(text : String) -> Map[String, Installed] raise OrbitError {
description: jstr(h, "description", ""),
bins: jstrs(h, "bin"),
depends: jmap(h, "depends"),
conflicts: jmap(h, "conflicts"),
})
_ => ()
}
@@ -294,6 +322,7 @@ fn state_from_text(text : String) -> Map[String, Installed] raise OrbitError {
constraint: jstr(o, "constraint", "*"),
bins: jstrs(o, "bin"),
depends: jmap(o, "depends"),
conflicts: jmap(o, "conflicts"),
history,
}
}
@@ -308,12 +337,15 @@ fn state_from_text(text : String) -> Map[String, Installed] raise OrbitError {
///|
test "installed and rollback descriptions round trip with legacy entries" {
let text =
#|{"packages":{"tool":{"description":"Current build","history":[{"description":"Previous build"},{}]}}}
#|{"packages":{"tool":{"description":"Current build","conflicts":{"a":"*"},"history":[{"description":"Previous build","conflicts":{"b":"<2"}},{}]}}}
let state = state_from_text(state_to_text(state_from_text(text)))
guard state.get("tool") is Some(p) else { fail("missing installed package") }
assert_eq(p.description, "Current build")
assert_eq(p.history[0].description, "Previous build")
assert_eq(p.history[1].description, "")
assert_eq(p.conflicts.get("a"), Some("*"))
assert_eq(p.history[0].conflicts.get("b"), Some("<2"))
assert_true(p.history[1].conflicts.is_empty())
}
// ---------------------------------------------------------------- context
@@ -367,15 +399,45 @@ fn bin_dir(ctx : Ctx) -> String {
ctx.root + "/bin"
}
///|
fn cache_dir(root : String) -> String {
root + "/cache/manifests"
}
///|
test "manifest roundtrip" {
let m = parse_manifest(
"{\"name\":\"hello\",\"version\":\"1.0.0\",\"bin\":[\"bin/hello\"],\"depends\":{\"lib\":\"^1\"}}",
"{\"name\":\"hello\",\"version\":\"1.0.0\",\"bin\":[\"bin/hello\"],\"depends\":{\"lib\":\"^1\",\"example::greet\":\">=1.0.0, <2.0.0\"}}",
)
assert_eq(m.name, "hello")
assert_eq(m.bins, ["bin/hello"])
assert_eq(m.depends.get("lib"), Some("^1"))
assert_eq(m.depends.get("example::greet"), Some(">=1.0.0, <2.0.0"))
assert_eq(parse_dep_key("example::greet"), (Some("example"), "greet"))
assert_eq(parse_dep_key("lib"), (None, "lib"))
assert_true(!valid_rel_path("../x"))
assert_true(!valid_rel_path("/bin/sh"))
assert_eq(store_id("sha256:0123456789abcdef0123"), "0123456789abcdef")
let bad_dep = try {
parse_manifest(
"{\"name\":\"hello\",\"version\":\"1.0.0\",\"depends\":{\"BadName\":\"^1\"}}",
)
|> ignore
false
} catch {
OrbitError(_) => true
}
assert_true(bad_dep)
let bad_con = try {
parse_manifest(
"{\"name\":\"hello\",\"version\":\"1.0.0\",\"depends\":{\"lib\":\">=abc\"}}",
)
|> ignore
false
} catch {
OrbitError(_) => true
}
assert_true(bad_con)
}
+12
View File
@@ -1,11 +1,23 @@
import {
"latha/orbit/kernel",
"moonbitlang/core/env",
"moonbitlang/core/json",
"moonbitlang/core/string",
"moonbitlang/core/encoding/base64",
"moonbitlang/core/encoding/hex",
"moonbitlang/core/encoding/percent",
"moonbit-community/toml",
"moonbitlang/async",
"moonbitlang/async/fs",
"moonbitlang/async/http",
"moonbitlang/async/process",
"moonbitlang/async/stdio",
}
import {
"moonbitlang/async/socket",
} for "wbtest"
pkgtype(kind: "executable")
options(
+953
View File
@@ -0,0 +1,953 @@
// OCI Distribution v2 HTTP transport, auth challenges, redirects, and streaming.
///|
const OCI_MANIFEST_MEDIA_TYPE : String = "application/vnd.oci.image.manifest.v1+json"
///|
const MANIFEST_ACCEPT : String = "application/vnd.oci.image.manifest.v1+json, application/vnd.docker.distribution.manifest.v2+json, application/vnd.oci.image.index.v1+json, application/vnd.docker.distribution.manifest.list.v2+json"
///|
struct ParsedUrl {
scheme : String
host : String
path : String
}
///|
enum AuthChallenge {
Bearer(String, String, String)
Basic(String)
Unknown
}
///|
let token_cache : Map[String, String] = Map([])
///|
/// Hosts that rejected the saved login in this run, with the error to report
/// when anonymous access isn't enough.
let rejected_logins : Map[String, String] = Map([])
///|
fn hdr(name : String) -> @http.CaseInsensitiveString {
@http.CaseInsensitiveString(name)
}
///|
fn split_channel_url(url : String) -> (String, String) {
let clean = strip_url_scheme(trim(url))
let (host, ns) = split_first(clean, '/')
(host, trim_slashes(ns))
}
///|
fn trim_slashes(s : String) -> String {
let a = chars(s)
let mut start = 0
let mut end = a.length()
while start < end && a[start] == '/' {
start = start + 1
}
while end > start && a[end - 1] == '/' {
end = end - 1
}
slice(a, start, end)
}
///|
fn channel_scheme(ch : Channel) -> String {
if ch.plain_http {
"http"
} else {
"https"
}
}
///|
fn parse_url(raw : String) -> ParsedUrl raise OrbitError {
let u = trim(raw)
guard u.find("://") is Some(idx) else {
raise OrbitError("invalid URL '\{raw}'")
}
let scheme = ascii_lower(u[:idx].to_owned())
if scheme != "http" && scheme != "https" {
raise OrbitError("unsupported URL scheme '\{scheme}'")
}
let rest = u[idx + 3:].to_owned()
let a = chars(rest)
let mut split_at = a.length()
let mut needs_slash = true
for i = 0; i < a.length(); i = i + 1 {
if a[i] == '/' {
split_at = i
needs_slash = false
break
}
if a[i] == '?' {
split_at = i
needs_slash = true
break
}
}
let host = slice(a, 0, split_at)
if host == "" {
raise OrbitError("URL missing host: '\{raw}'")
}
let path = if split_at == a.length() {
"/"
} else if needs_slash {
"/" + slice(a, split_at, a.length())
} else {
slice(a, split_at, a.length())
}
ParsedUrl::{ scheme, host, path }
}
///|
fn same_origin(a : ParsedUrl, b : ParsedUrl) -> Bool {
ascii_lower(a.scheme) == ascii_lower(b.scheme) &&
ascii_lower(a.host) == ascii_lower(b.host)
}
///|
fn resolve_location(
base : ParsedUrl,
location : String,
) -> ParsedUrl raise OrbitError {
let loc = trim(location)
if loc == "" {
raise OrbitError("empty redirect Location")
}
let lower = ascii_lower(loc)
if has_prefix(lower, "http://") || has_prefix(lower, "https://") {
return parse_url(loc)
}
if has_prefix(loc, "//") {
return parse_url(base.scheme + ":" + loc)
}
if has_prefix(loc, "/") {
return ParsedUrl::{ scheme: base.scheme, host: base.host, path: loc }
}
let (path_only, _) = split_first(base.path, '?')
let a = chars(path_only)
let mut last_slash = -1
for i = 0; i < a.length(); i = i + 1 {
if a[i] == '/' {
last_slash = i
}
}
let dir = if last_slash >= 0 { slice(a, 0, last_slash + 1) } else { "/" }
ParsedUrl::{ scheme: base.scheme, host: base.host, path: dir + loc }
}
///|
fn parse_auth_params(rest : String) -> Map[String, String] {
let out : Map[String, String] = Map([])
let a = chars(rest)
let n = a.length()
let mut i = 0
while i < n {
while i < n && (is_space(a[i]) || a[i] == ',') {
i = i + 1
}
if i >= n {
break
}
let key_start = i
while i < n && a[i] != '=' && a[i] != ',' && !is_space(a[i]) {
i = i + 1
}
let key = ascii_lower(slice(a, key_start, i))
while i < n && is_space(a[i]) {
i = i + 1
}
if i >= n || a[i] != '=' {
while i < n && a[i] != ',' {
i = i + 1
}
continue
}
i = i + 1
while i < n && is_space(a[i]) {
i = i + 1
}
let val = StringBuilder()
if i < n && a[i] == '"' {
i = i + 1
while i < n && a[i] != '"' {
if a[i] == '\\' && i + 1 < n {
val.write_char(a[i + 1])
i = i + 2
} else {
val.write_char(a[i])
i = i + 1
}
}
if i < n && a[i] == '"' {
i = i + 1
}
} else {
while i < n && a[i] != ',' {
val.write_char(a[i])
i = i + 1
}
}
if key != "" {
out[key] = val.to_string()
}
}
out
}
///|
fn parse_www_authenticate(value : String) -> AuthChallenge {
let s = trim(value)
if s == "" {
return Unknown
}
let a = chars(s)
let mut i = 0
while i < a.length() && !is_space(a[i]) {
i = i + 1
}
let scheme = ascii_lower(slice(a, 0, i))
let rest = trim(slice(a, i, a.length()))
if scheme == "bearer" {
let params = parse_auth_params(rest)
let realm = params.get("realm").unwrap_or("")
if realm == "" {
return Unknown
}
let service = params.get("service").unwrap_or("")
let scope = params.get("scope").unwrap_or("")
Bearer(realm, service, scope)
} else if scheme == "basic" {
let params = parse_auth_params(rest)
Basic(params.get("realm").unwrap_or(""))
} else {
Unknown
}
}
///|
fn unquote(s : String) -> String {
let t = trim(s)
let a = chars(t)
if a.length() >= 2 && a[0] == '"' && a[a.length() - 1] == '"' {
slice(a, 1, a.length() - 1)
} else {
t
}
}
///|
fn is_next_rel_param(params : String) -> Bool {
for part in split_on(params, ';') {
let p = trim(part)
if p == "" {
continue
}
let (k, v) = split_first(p, '=')
if ascii_lower(trim(k)) == "rel" {
let rels = unquote(v)
for tok in split_on(rels, ' ') {
if ascii_lower(trim(tok)) == "next" {
return true
}
}
}
}
false
}
///|
fn parse_next_link(value : String) -> String? {
let a = chars(value)
let n = a.length()
let mut i = 0
while i < n {
while i < n && a[i] != '<' {
i = i + 1
}
if i >= n {
break
}
i = i + 1
let url_start = i
while i < n && a[i] != '>' {
i = i + 1
}
if i >= n {
break
}
let target = trim(slice(a, url_start, i))
i = i + 1
let param_start = i
let mut in_quotes = false
while i < n {
if a[i] == '"' {
in_quotes = !in_quotes
} else if a[i] == ',' && !in_quotes {
break
}
i = i + 1
}
let params = slice(a, param_start, i)
if target != "" && is_next_rel_param(params) {
return Some(target)
}
if i < n && a[i] == ',' {
i = i + 1
}
}
None
}
///|
fn extract_digest_header(headers : @http.Headers) -> String? {
match headers.get(hdr("Docker-Content-Digest")) {
Some(v) => {
let t = trim(v)
if t != "" {
return Some(t)
}
}
None => ()
}
match headers.get(hdr("ETag")) {
Some(v) => {
let mut t = trim(v)
if has_prefix(t, "W/") || has_prefix(t, "w/") {
t = trim(drop_chars(t, 2))
}
let d = unquote(t)
if has_prefix(d, "sha256:") || has_prefix(d, "sha512:") {
return Some(d)
}
}
None => ()
}
None
}
///|
fn format_oci_error(code : Int32, reason : String, body : Bytes) -> String {
let text = utf8_decode(body)
let obj : Map[String, Json]? = Some(parse_object(text, "oci error")) catch {
_ => None
}
match obj {
Some(o) =>
match o.get("errors") {
Some(Json::Array(errs)) =>
if errs.length() > 0 {
match errs[0] {
Json::Object(e) => {
let c = jstr(e, "code", "")
let m = jstr(e, "message", "")
if c != "" && m != "" {
return "HTTP \{code}: \{c}: \{m}"
} else if m != "" {
return "HTTP \{code}: \{m}"
} else if c != "" {
return "HTTP \{code}: \{c}"
}
}
_ => ()
}
}
_ => ()
}
None => ()
}
let base = if reason != "" { "HTTP \{code} \{reason}" } else { "HTTP \{code}" }
let snippet = trim(text)
if snippet != "" && chars(snippet).length() < 200 {
base + ": " + snippet
} else {
base
}
}
///|
fn token_cache_key(host : String, scope_key : String) -> String {
ascii_lower(host) + "|" + scope_key
}
///|
fn is_redirect_code(code : Int32) -> Bool {
code == 301 || code == 302 || code == 303 || code == 307 || code == 308
}
///|
fn build_http_headers(
headers : Map[String, String],
auth_header : String?,
content_length : Int64?,
) -> @http.Headers {
let out : @http.Headers = Map([])
for k, v in headers {
out[hdr(k)] = v
}
match auth_header {
Some(a) => out[hdr("Authorization")] = a
None => ()
}
match content_length {
Some(n) => out[hdr("Content-Length")] = n.to_string()
None => ()
}
out
}
///|
async fn connect_http(url : ParsedUrl) -> @http.Client raise OrbitError {
let base_headers : @http.Headers = Map([])
base_headers[hdr("User-Agent")] = "orbit/0.1"
base_headers[hdr("Accept-Encoding")] = "identity"
@http.Client::Client(url.scheme + "://" + url.host, headers=base_headers) catch {
e => raise OrbitError("cannot connect to \{url.host}: \{e}")
}
}
///|
async fn raw_http_bytes(
meth : @http.RequestMethod,
url_str : String,
headers : Map[String, String],
auth_header : String?,
body : Bytes,
) -> (ParsedUrl, @http.Response, Bytes) raise OrbitError {
let mut cur_url = parse_url(url_str)
let mut cur_meth = meth
let mut cur_body = body
let mut cur_auth = auth_header
for hop = 0; hop < 10; hop = hop + 1 {
let clen : Int64? = if cur_body.length() > 0 ||
cur_meth is Post ||
cur_meth is Put {
Some(cur_body.length().to_int64())
} else {
None
}
let extra = build_http_headers(headers, cur_auth, clen)
let client = connect_http(cur_url)
defer client.close()
let resp = try {
client.request(cur_meth, cur_url.path, extra_headers=extra)
if cur_body.length() > 0 {
client.write(cur_body)
}
client.end_request()
} catch {
e => raise OrbitError("HTTP request to \{cur_url.host} failed: \{e}")
}
if is_redirect_code(resp.code) {
match resp.headers.get(hdr("Location")) {
Some(loc) => {
let next_url = resolve_location(cur_url, loc)
if !same_origin(cur_url, next_url) {
cur_auth = None
}
if (resp.code == 301 || resp.code == 302 || resp.code == 303) &&
cur_meth is Post {
cur_meth = Get
cur_body = b""
}
cur_url = next_url
continue
}
None => ()
}
}
let resp_body = if cur_meth is Head {
b""
} else {
client.read_all().binary() catch {
e => raise OrbitError("failed reading response from \{cur_url.host}: \{e}")
}
}
return (cur_url, resp, resp_body)
}
raise OrbitError("too many redirects for \{url_str}")
}
///|
fn bearer_token_url(realm : String, service : String, scope : String) -> String {
let mut token_url = realm
let mut sep = if has_char(realm, '?') { "&" } else { "?" }
if service != "" {
token_url = token_url + sep + "service=" + @percent.encode(service)
sep = "&"
}
if scope != "" {
token_url = token_url + sep + "scope=" + @percent.encode(scope)
}
token_url
}
///|
/// A token, or the HTTP status and message of the token endpoint's refusal.
async fn fetch_bearer_token(
token_url : String,
creds : Creds?,
) -> Result[String, (Int32, String)] raise OrbitError {
let auth_header = creds.map(fn(c) { "Basic " + encode_basic_auth(c) })
let (_, resp, body) = raw_http_bytes(
Get,
token_url,
Map([("Accept", "application/json")]),
auth_header,
b"",
)
if resp.code < 200 || resp.code >= 300 {
return Err((resp.code, format_oci_error(resp.code, resp.reason, body)))
}
let obj = parse_object(utf8_decode(body), "token response")
let tok = jstr(obj, "token", "")
if tok != "" {
return Ok(tok)
}
let access = jstr(obj, "access_token", "")
if access != "" {
return Ok(access)
}
raise OrbitError("token response missing token")
}
///|
/// Get a token, retrying without the saved login if the registry rejects it
/// and the request only reads. `source` is the file the login came from.
async fn bearer_token_or_anonymous(
host : String,
token_url : String,
creds : Creds?,
source : String,
read_only : Bool,
) -> String raise OrbitError {
// Don't offer a login the host has already rejected again for every repo.
let creds = if read_only && source != "" && rejected_logins.contains(host) {
None
} else {
creds
}
let (code, msg) = match fetch_bearer_token(token_url, creds) {
Ok(tok) => return tok
Err(e) => e
}
if creds is None {
check_rejected_login(host, code)
}
if creds is None || source == "" || (code != 401 && code != 403) {
raise OrbitError("authentication failed (\{msg})")
}
let rejected = "\{host} rejected the login saved in \{source} (\{msg}); run `orbit login \{host}`"
if !read_only {
raise OrbitError(rejected)
}
match fetch_bearer_token(token_url, None) {
Ok(tok) => {
// Stay quiet: the login is only reported if the anonymous read isn't enough.
rejected_logins[host] = rejected
tok
}
Err(_) => raise OrbitError(rejected)
}
}
///|
/// After falling back to anonymous access, a refusal may only mean the package
/// is private. Report the rejected login rather than "missing", which would let
/// a lower priority channel supply a package with the same name.
fn check_rejected_login(host : String, code : Int32) -> Unit raise OrbitError {
if code == 401 || code == 403 || code == 404 {
match rejected_logins.get(host) {
Some(msg) => raise OrbitError(msg)
None => ()
}
}
}
///|
async fn resolve_auth_retry(
host : String,
scope_key : String,
used_cached : Bool,
www_auth : String,
creds_override : Creds?,
read_only : Bool,
) -> String? raise OrbitError {
if used_cached && scope_key != "" {
token_cache.remove(token_cache_key(host, scope_key))
}
let (creds, source) = match creds_override {
Some(c) => (Some(c), "")
None =>
match load_creds(host) {
Some((c, path)) => (Some(c), path)
None => (None, "")
}
}
match parse_www_authenticate(www_auth) {
Bearer(realm, service, scope) => {
let tok = bearer_token_or_anonymous(
host,
bearer_token_url(realm, service, scope),
creds,
source,
read_only,
)
if creds_override is None && scope_key != "" {
token_cache[token_cache_key(host, scope_key)] = tok
}
Some("Bearer " + tok)
}
Basic(_) =>
match creds {
Some(c) => Some("Basic " + encode_basic_auth(c))
None => None
}
Unknown => None
}
}
///|
async fn oci_request(
meth : @http.RequestMethod,
url_str : String,
headers : Map[String, String],
body : Bytes,
scope_key : String,
creds_override? : Creds,
check_login? : Bool = true,
) -> (@http.Response, Bytes) raise OrbitError {
let initial_url = parse_url(url_str)
let (initial_auth, used_cached) = if creds_override is None && scope_key != "" {
match token_cache.get(token_cache_key(initial_url.host, scope_key)) {
Some(t) => (Some("Bearer " + t), true)
None => (None, false)
}
} else {
(None, false)
}
let (final_url, resp, resp_body) = raw_http_bytes(
meth, url_str, headers, initial_auth, body,
)
if resp.code != 401 {
if creds_override is None && check_login {
check_rejected_login(final_url.host, resp.code)
}
return (resp, resp_body)
}
let www_auth = match resp.headers.get(hdr("WWW-Authenticate")) {
Some(v) => v
None => return (resp, resp_body)
}
let retry_auth = match
resolve_auth_retry(
final_url.host,
scope_key,
used_cached,
www_auth,
creds_override,
(meth is Get || meth is Head) && !scope_key.has_suffix(":push"),
) {
Some(a) => a
None => return (resp, resp_body)
}
let (_, retry_resp, retry_body) = raw_http_bytes(
meth,
url_str,
headers,
Some(retry_auth),
body,
)
if creds_override is None && check_login {
check_rejected_login(final_url.host, retry_resp.code)
}
(retry_resp, retry_body)
}
///|
async fn try_download_once(
url_str : String,
dest_path : String,
expected_digest : String,
auth_header : String?,
) -> (ParsedUrl, @http.Response, Bytes) raise OrbitError {
let mut cur_url = parse_url(url_str)
let mut cur_auth = auth_header
for hop = 0; hop < 10; hop = hop + 1 {
let extra = build_http_headers(Map([]), cur_auth, None)
let client = connect_http(cur_url)
defer client.close()
let resp = try {
client.request(Get, cur_url.path, extra_headers=extra)
client.end_request()
} catch {
e => raise OrbitError("download from \{cur_url.host} failed: \{e}")
}
if is_redirect_code(resp.code) {
match resp.headers.get(hdr("Location")) {
Some(loc) => {
let next_url = resolve_location(cur_url, loc)
if !same_origin(cur_url, next_url) {
cur_auth = None
}
cur_url = next_url
continue
}
None => ()
}
}
if resp.code < 200 || resp.code >= 300 {
let err_body = client.read_all().binary() catch { _ => b"" }
return (cur_url, resp, err_body)
}
let out = @fs.open(
dest_path,
mode=WriteOnly,
create_mode=CreateOrTruncate,
) catch {
e => raise OrbitError("cannot write \{dest_path}: \{e}")
}
defer out.close()
let hasher = Sha256::new()
let buf = FixedArray::make(32768, b'\x00')
for ;; {
let n = client.read(buf) catch {
e => raise OrbitError("download interrupted from \{cur_url.host}: \{e}")
}
if n == 0 {
break
}
hasher.update_fixed(buf, n)
out.write(buf.unsafe_reinterpret_as_bytes()[:n]) catch {
e => raise OrbitError("cannot write \{dest_path}: \{e}")
}
}
if has_prefix(expected_digest, "sha256:") {
let actual = "sha256:" + hasher.finish_hex()
if actual != expected_digest {
raise OrbitError(
"digest mismatch for \{dest_path}: expected \{expected_digest}, got \{actual}",
)
}
}
return (cur_url, resp, b"")
}
raise OrbitError("too many redirects downloading \{url_str}")
}
///|
async fn oci_download_to_file(
url_str : String,
dest_path : String,
expected_digest : String,
scope_key : String,
) -> Unit raise OrbitError {
let initial_url = parse_url(url_str)
let (initial_auth, used_cached) = if scope_key != "" {
match token_cache.get(token_cache_key(initial_url.host, scope_key)) {
Some(t) => (Some("Bearer " + t), true)
None => (None, false)
}
} else {
(None, false)
}
let (final_url, resp, err_body) = try_download_once(
url_str, dest_path, expected_digest, initial_auth,
)
if resp.code >= 200 && resp.code < 300 {
return
}
if resp.code == 401 {
match resp.headers.get(hdr("WWW-Authenticate")) {
Some(www_auth) =>
match
resolve_auth_retry(
final_url.host,
scope_key,
used_cached,
www_auth,
None,
true,
) {
Some(retry_auth) => {
let (_, retry_resp, retry_err) = try_download_once(
url_str,
dest_path,
expected_digest,
Some(retry_auth),
)
if retry_resp.code >= 200 && retry_resp.code < 300 {
return
}
check_rejected_login(final_url.host, retry_resp.code)
raise OrbitError(
"download failed (\{format_oci_error(retry_resp.code, retry_resp.reason, retry_err)})",
)
}
None => ()
}
None => ()
}
}
check_rejected_login(final_url.host, resp.code)
raise OrbitError(
"download failed (\{format_oci_error(resp.code, resp.reason, err_body)})",
)
}
///|
async fn try_upload_file_once(
url_str : String,
file_path : String,
size : Int64,
content_type : String,
auth_header : String?,
) -> (ParsedUrl, @http.Response, Bytes) raise OrbitError {
let mut cur_url = parse_url(url_str)
let mut cur_auth = auth_header
for hop = 0; hop < 10; hop = hop + 1 {
let extra = build_http_headers(
Map([("Content-Type", content_type)]),
cur_auth,
Some(size),
)
let client = connect_http(cur_url)
defer client.close()
let file = @fs.open(file_path, mode=ReadOnly) catch {
e => raise OrbitError("cannot open \{file_path}: \{e}")
}
defer file.close()
let resp = try {
client.request(Put, cur_url.path, extra_headers=extra)
client.write_reader(file)
client.end_request()
} catch {
e => raise OrbitError("upload to \{cur_url.host} failed: \{e}")
}
if is_redirect_code(resp.code) {
match resp.headers.get(hdr("Location")) {
Some(loc) => {
let next_url = resolve_location(cur_url, loc)
if !same_origin(cur_url, next_url) {
cur_auth = None
}
cur_url = next_url
continue
}
None => ()
}
}
let resp_body = client.read_all().binary() catch {
e => raise OrbitError("failed reading upload response: \{e}")
}
return (cur_url, resp, resp_body)
}
raise OrbitError("too many redirects uploading to \{url_str}")
}
///|
async fn oci_upload_file(
url_str : String,
file_path : String,
size : Int64,
content_type : String,
scope_key : String,
) -> (@http.Response, Bytes) raise OrbitError {
let initial_url = parse_url(url_str)
let (initial_auth, used_cached) = if scope_key != "" {
match token_cache.get(token_cache_key(initial_url.host, scope_key)) {
Some(t) => (Some("Bearer " + t), true)
None => (None, false)
}
} else {
(None, false)
}
let (final_url, resp, resp_body) = try_upload_file_once(
url_str, file_path, size, content_type, initial_auth,
)
if resp.code != 401 {
return (resp, resp_body)
}
let www_auth = match resp.headers.get(hdr("WWW-Authenticate")) {
Some(v) => v
None => return (resp, resp_body)
}
let retry_auth = match
resolve_auth_retry(
final_url.host,
scope_key,
used_cached,
www_auth,
None,
false,
) {
Some(a) => a
None => return (resp, resp_body)
}
let (_, retry_resp, retry_body) = try_upload_file_once(
url_str,
file_path,
size,
content_type,
Some(retry_auth),
)
(retry_resp, retry_body)
}
///|
test "parse_url and resolve_location" {
let base = parse_url("https://git.site.latha.org/v2/nandi/hello/tags/list")
assert_eq(base.scheme, "https")
assert_eq(base.host, "git.site.latha.org")
assert_eq(base.path, "/v2/nandi/hello/tags/list")
let root_rel = resolve_location(base, "/v2/nandi/hello/blobs/uploads/123")
assert_eq(root_rel.host, "git.site.latha.org")
assert_eq(root_rel.path, "/v2/nandi/hello/blobs/uploads/123")
let abs = resolve_location(base, "https://cdn.example.com/blob?sig=1")
assert_eq(abs.host, "cdn.example.com")
assert_eq(abs.path, "/blob?sig=1")
assert_false(same_origin(base, abs))
assert_true(same_origin(base, root_rel))
let rel = resolve_location(base, "next?n=10")
assert_eq(rel.path, "/v2/nandi/hello/tags/next?n=10")
}
///|
test "parse_www_authenticate handles Bearer with commas in scope and Basic" {
match
parse_www_authenticate(
"Bearer realm=\"https://git.site.latha.org/v2/token\",service=\"container_registry\",scope=\"repository:nandi/hello:pull,push\"",
) {
Bearer(realm, service, scope) => {
assert_eq(realm, "https://git.site.latha.org/v2/token")
assert_eq(service, "container_registry")
assert_eq(scope, "repository:nandi/hello:pull,push")
}
_ => fail("expected Bearer challenge")
}
match parse_www_authenticate("Basic realm=\"Registry\"") {
Basic(realm) => assert_eq(realm, "Registry")
_ => fail("expected Basic challenge")
}
}
///|
test "parse_next_link and split_channel_url" {
assert_eq(
parse_next_link("</v2/nandi/hello/tags/list?last=latest>; rel=\"next\""),
Some("/v2/nandi/hello/tags/list?last=latest"),
)
assert_eq(
parse_next_link(
"</v2/_catalog?last=a>; rel=\"prev\", </v2/_catalog?last=b>; rel=\"next\"",
),
Some("/v2/_catalog?last=b"),
)
assert_eq(parse_next_link("</v2/_catalog?last=a>; rel=\"prev\""), None)
assert_eq(split_channel_url("git.site.latha.org/nandi/"), ("git.site.latha.org", "nandi"))
assert_eq(split_channel_url("localhost:5000"), ("localhost:5000", ""))
}
+534 -268
View File
@@ -8,19 +8,11 @@ struct Step {
version : String
digest : String
manifest : Manifest
mut explicit : Bool
mut constraint : String
explicit : Bool
constraint : String
keep : Bool // already installed at this digest; nothing to fetch
}
///|
struct Planner {
ctx : Ctx
steps : Map[String, Step]
order : Array[Step] // dependencies before dependents
upgrade : Array[String] // names allowed to move even if satisfied
}
///|
fn manifest_of_installed(p : Installed) -> Manifest {
Manifest::{
@@ -29,177 +21,241 @@ fn manifest_of_installed(p : Installed) -> Manifest {
description: p.description,
documentation: "",
depends: p.depends,
conflicts: p.conflicts,
bins: p.bins,
}
}
///|
/// Every constraint that currently applies to `name`: the request itself,
/// the user's own constraint if they installed it explicitly, and what each
/// other package requires (using planned manifests for packages being replaced).
fn constraints_for(
p : Planner,
name : String,
requested : String,
) -> Array[String] {
let cons : Array[String] = [requested]
match p.ctx.state.get(name) {
Some(inst) =>
if inst.explicit && inst.constraint != "" && inst.constraint != requested {
cons.push(inst.constraint)
/// "[channel::]name[@constraint]" -> (channel, name, constraint, has_explicit_constraint)
fn parse_spec_full(
spec : String,
) -> (String?, String, String, Bool) raise OrbitError {
let (channel, rest) = split_channel(spec)
match channel {
Some(ch) =>
if !valid_name(ch) {
raise OrbitError("invalid channel name '\{ch}'")
}
None => ()
}
for other, inst in p.ctx.state {
if other == name {
continue
let (name, c) = split_first(rest, '@')
if !valid_name(name) {
raise OrbitError("invalid package name '\{name}'")
}
let deps = match p.steps.get(other) {
Some(st) => st.manifest.depends
None => inst.depends
}
match deps.get(name) {
Some(c) => cons.push(c)
None => ()
}
}
for other, st in p.steps {
if other != name && !p.ctx.state.contains(other) {
match st.manifest.depends.get(name) {
Some(c) => cons.push(c)
None => ()
}
}
}
cons
}
///|
async fn visit(
p : Planner,
name : String,
requested : String,
explicit : Bool,
pin : String?, // channel the user asked for
) -> Unit raise OrbitError {
match p.steps.get(name) {
Some(st) => {
if pin is Some(c) && c != st.channel {
raise OrbitError(
"conflict: \{name} is planned from channel '\{st.channel}' but '\{c}' was requested",
)
}
if !satisfies_all(st.version, [requested]) {
raise OrbitError(
"conflict: \{name} \{st.version} is planned but '\{requested}' is required",
)
}
if explicit {
st.explicit = true
st.constraint = requested
}
return
}
None => ()
}
let cons = constraints_for(p, name, requested)
let upgrading = p.upgrade.contains(name)
match p.ctx.state.get(name) {
Some(inst) => {
let same_channel = match pin {
Some(c) => c == inst.channel
None => true
}
if !upgrading && same_channel && satisfies_all(inst.version, cons) {
let st = Step::{
name,
channel: inst.channel,
version: inst.version,
digest: inst.digest,
manifest: manifest_of_installed(inst),
explicit: explicit || inst.explicit,
constraint: if explicit {
requested
if c == "" {
(channel, name, "*", false)
} else {
inst.constraint
},
keep: true,
if !valid_constraint(c) {
raise OrbitError("invalid version constraint '\{c}' for '\{name}'")
}
p.steps[name] = st
p.order.push(st)
return
(channel, name, c, true)
}
}
None => ()
}
// An installed package stays on its channel unless the user names another.
let wanted = match pin {
Some(c) => Some(c)
None => p.ctx.state.get(name).map(fn(i) { i.channel })
}
let (ch, tags) = locate(p.ctx, name, wanted)
let tag = match pick_tag(tags, cons) {
Some(t) => t
None => {
let avail = sorted_versions(tags)
raise OrbitError(
"no version of \{name} in channel '\{ch.name}' satisfies [\{join(cons, ", ")}]; available: \{join(avail, ", ")}",
)
}
}
let digest = resolve_digest(ch, name, tag)
let prev = p.ctx.state.get(name)
// An unchanged build with a saved description needs no metadata fetch.
let m = match prev {
Some(i) =>
if i.digest == digest && i.description != "" {
manifest_of_installed(i)
} else {
fetch_manifest(ch, name, digest)
}
None => fetch_manifest(ch, name, digest)
}
let st = Step::{
name,
channel: ch.name,
version: m.version,
digest,
manifest: m,
explicit: explicit ||
(match prev {
Some(i) => i.explicit
None => false
}),
constraint: if explicit {
requested
} else {
match prev {
Some(i) => i.constraint
None => "*"
}
},
keep: match prev {
Some(i) => i.digest == digest
None => false
},
}
// Register before recursing so dependency cycles terminate.
p.steps[name] = st
for dep, dc in m.depends {
visit(p, dep, dc, false, None)
}
p.order.push(st)
}
///|
/// "[channel::]name[@constraint]"
fn parse_spec(spec : String) -> (String?, String, String) raise OrbitError {
let (channel, rest) = split_channel(spec)
let (name, c) = split_first(rest, '@')
if !valid_name(name) {
raise OrbitError("invalid package name '\{name}'")
let (channel, name, c, _) = parse_spec_full(spec)
(channel, name, c)
}
(channel, name, if c == "" { "*" } else { c })
///|
/// Build a SAT-solved install/upgrade plan for global state. Packages in
/// `replacing` don't constrain it; with `ignore_installed`, none do.
async fn plan_global(
ctx : Ctx,
req_specs : Array[(String?, String, String, String)],
upgrade : Array[String],
explicit_new : Map[String, String],
replacing? : Array[String] = [],
ignore_installed? : Bool = false,
) -> Array[Step] raise OrbitError {
let ch_by_name : Map[String, Channel] = Map([])
for c in ctx.channels {
ch_by_name[c.name] = c
}
let tags_cache : Map[String, (Channel, Array[String])] = Map([])
let digest_cache : Map[String, String] = Map([])
let manifest_cache : Map[String, Manifest] = Map([])
let locked_bins : Map[String, String] = Map([])
let locked : Map[String, LockedInfo] = Map([])
for name, inst in ctx.state {
if !ignore_installed &&
!upgrade.contains(name) &&
!explicit_new.contains(name) &&
!replacing.contains(name) {
locked[name] = LockedInfo::{
version: inst.version,
conflicts: inst.conflicts,
}
for b in inst.bins {
locked_bins[basename(b)] = name
}
}
}
let provider = SolverProvider::{
candidates: async fn(name, pin) {
let wanted = match pin {
Some(c) => Some(c)
None =>
match ctx.state.get(name) {
Some(inst) => Some(inst.channel)
None => None
}
}
let cache_key = name + "|" + wanted.unwrap_or("")
let (ch, tags) = match tags_cache.get(cache_key) {
Some(pair) => pair
None => {
let pair = locate(ctx, name, wanted)
tags_cache[cache_key] = pair
ch_by_name[pair.0.name] = pair.0
pair
}
}
let favored = if upgrade.contains(name) {
None
} else {
match ctx.state.get(name) {
Some(inst) =>
if inst.channel == ch.name {
Some((inst.channel, inst.version, inst.digest))
} else {
None
}
None => None
}
}
(ch.name, candidates_from_tags(name, ch.name, tags, favored))
},
details: async fn(cand) {
if false {
@async.sleep(0)
}
if cand.favored && cand.digest != "" {
match ctx.state.get(cand.name) {
Some(inst) =>
if inst.digest == cand.digest && inst.channel == cand.channel {
return CandidateDetail::{
digest: cand.digest,
manifest: manifest_of_installed(inst),
}
}
None => ()
}
}
let ch = match ch_by_name.get(cand.channel) {
Some(c) => c
None => find_channel(ctx, cand.channel)
}
let dkey = cand.channel + "::" + cand.name + "@" + cand.tag
let digest = match digest_cache.get(dkey) {
Some(d) => d
None => {
let d = resolve_digest(ch, cand.name, cand.tag)
digest_cache[dkey] = d
d
}
}
let mkey = cand.channel + "::" + cand.name + "@" + digest
let m = match manifest_cache.get(mkey) {
Some(mf) => mf
None => {
let mf = fetch_manifest_cached(ctx.root, ch, cand.name, digest)
manifest_cache[mkey] = mf
mf
}
}
CandidateDetail::{ digest, manifest: m }
},
extra_reqs: fn(pkg_name) {
let reqs : Array[SolveReq] = []
if ignore_installed {
return reqs
}
match ctx.state.get(pkg_name) {
Some(inst) =>
if inst.explicit &&
!explicit_new.contains(pkg_name) &&
!replacing.contains(pkg_name) {
reqs.push(SolveReq::{
name: pkg_name,
channel: Some(inst.channel),
constraint: if inst.constraint == "" {
"*"
} else {
inst.constraint
},
label: "installed \{pkg_name}",
})
}
None => ()
}
for other, oinst in ctx.state {
if other != pkg_name &&
!upgrade.contains(other) &&
!explicit_new.contains(other) &&
!replacing.contains(other) {
for dk, dc in oinst.depends {
let (dch, dname) = parse_dep_key(dk)
if dname == pkg_name {
reqs.push(SolveReq::{
name: pkg_name,
channel: dch,
constraint: dc,
label: "installed \{other} \{oinst.version}",
})
}
}
}
}
reqs
},
locked_bins,
locked,
}
let reqs : Array[SolveReq] = []
for item in req_specs {
let (pin, name, constraint, label) = item
reqs.push(SolveReq::{ name, channel: pin, constraint, label })
}
let solved = solve(reqs, provider)
let steps : Array[Step] = []
for sp in solved {
let prev = ctx.state.get(sp.name)
let explicit = explicit_new.contains(sp.name) ||
(match prev {
Some(i) => i.explicit
None => false
})
let constraint = match explicit_new.get(sp.name) {
Some(c) => c
None =>
match prev {
Some(i) => i.constraint
None => "*"
}
}
let keep = match prev {
Some(i) => i.digest == sp.digest && i.channel == sp.channel
None => false
}
steps.push(Step::{
name: sp.name,
channel: sp.channel,
version: sp.version,
digest: sp.digest,
manifest: sp.manifest,
explicit,
constraint,
keep,
})
}
steps
}
///|
@@ -230,7 +286,7 @@ async fn link_bins(
dir : String,
bins : Array[String],
) -> Unit raise OrbitError {
@fs.mkdir(bin_dir(ctx), recursive=true) catch {
@fs.mkdir(bin_dir(ctx), recursive=true, allow_exist=true) catch {
e => raise OrbitError("cannot create bin dir: " + e.to_string())
}
for b in bins {
@@ -263,8 +319,8 @@ fn check_bin_conflicts(
}
///|
/// Switch `name` to a fetched build, keeping the old one for rollback.
async fn activate(ctx : Ctx, st : Step) -> Unit raise OrbitError {
/// Fetch a step's build into the store and check its contents.
async fn fetch_step(ctx : Ctx, st : Step) -> String raise OrbitError {
let ch = find_channel(ctx, st.channel)
let dir = fetch_into_store(ctx, ch, st.name, st.digest)
for b in st.manifest.bins {
@@ -272,6 +328,13 @@ async fn activate(ctx : Ctx, st : Step) -> Unit raise OrbitError {
raise OrbitError("\{st.name}: bin '\{b}' missing from package contents")
}
}
dir
}
///|
/// Switch `name` to a fetched build, keeping the old one for rollback.
async fn activate(ctx : Ctx, st : Step) -> Unit raise OrbitError {
let dir = fetch_step(ctx, st)
check_bin_conflicts(ctx, st.name, st.manifest.bins)
match ctx.state.get(st.name) {
Some(inst) => {
@@ -283,6 +346,7 @@ async fn activate(ctx : Ctx, st : Step) -> Unit raise OrbitError {
description: inst.description,
bins: inst.bins,
depends: inst.depends,
conflicts: inst.conflicts,
})
while inst.history.length() > 2 {
inst.history.remove(0) |> ignore
@@ -293,6 +357,7 @@ async fn activate(ctx : Ctx, st : Step) -> Unit raise OrbitError {
inst.description = st.manifest.description
inst.bins = st.manifest.bins
inst.depends = st.manifest.depends
inst.conflicts = st.manifest.conflicts
inst.explicit = st.explicit
inst.constraint = st.constraint
println(
@@ -310,6 +375,7 @@ async fn activate(ctx : Ctx, st : Step) -> Unit raise OrbitError {
constraint: st.constraint,
bins: st.manifest.bins,
depends: st.manifest.depends,
conflicts: st.manifest.conflicts,
history: [],
}
println(" \{st.name} \{st.version} installed")
@@ -318,12 +384,30 @@ async fn activate(ctx : Ctx, st : Step) -> Unit raise OrbitError {
link_bins(ctx, dir, st.manifest.bins)
// Persist after each package so a later failure leaves accurate state.
save_state(ctx)
print_details(installed_details(ctx, ctx.state[st.name]), " ")
}
///|
async fn apply_plan(ctx : Ctx, p : Planner) -> Unit raise OrbitError {
async fn apply_plan(
ctx : Ctx,
steps : Array[Step],
removals? : Array[String] = [],
) -> Unit raise OrbitError {
let mut changed = 0
for st in p.order {
if removals.length() > 0 {
// Have the replacements at hand before removing anything.
for st in steps {
if !st.keep {
ignore(fetch_step(ctx, st))
}
}
for name in removals {
remove_one(ctx, name)
changed = changed + 1
}
save_state(ctx)
}
for st in steps {
if st.keep {
match ctx.state.get(st.name) {
Some(inst) => {
@@ -346,58 +430,129 @@ async fn apply_plan(ctx : Ctx, p : Planner) -> Unit raise OrbitError {
}
///|
fn new_planner(ctx : Ctx, upgrade : Array[String]) -> Planner {
Planner::{ ctx, steps: Map([]), order: [], upgrade, }
}
///|
async fn cmd_install(ctx : Ctx, specs : Array[String]) -> Unit raise OrbitError {
async fn cmd_install(
ctx : Ctx,
specs : Array[String],
replace? : Bool = false,
interactive? : Bool = stdin_is_interactive(),
) -> Unit raise OrbitError {
if specs.length() == 0 {
raise OrbitError("usage: orbit install [channel::]<name>[@constraint]...")
raise OrbitError("usage: orbit install [--replace] [channel::]<name>[@constraint]...")
}
let p = new_planner(ctx, [])
let reqs : Array[(String?, String, String, String)] = []
let explicit_new : Map[String, String] = Map([])
for s in specs {
let (channel, name, c) = parse_spec(s)
visit(p, name, c, true, channel)
reqs.push((channel, name, c, "command line"))
explicit_new[name] = c
}
let (steps, removals) = plan_install(ctx, reqs, explicit_new)
if removals.length() > 0 && !replace {
confirm_replace(ctx, steps, removals, interactive)
}
apply_plan(ctx, steps, removals~)
if removals.length() > 0 {
autoremove(ctx)
save_state(ctx)
}
apply_plan(ctx, p)
}
///|
/// Upgrade the named packages (or everything) to the newest versions their
/// constraints allow. Dependencies are moved only when required.
/// Upgrade the named packages (or everything) jointly to the newest versions
/// their constraints allow.
async fn cmd_upgrade(ctx : Ctx, names : Array[String]) -> Unit raise OrbitError {
let targets : Array[String] = []
let reqs : Array[(String?, String, String, String)] = []
if names.length() == 0 {
for name, _ in ctx.state {
if ctx.state.length() == 0 {
println("no packages installed")
return
}
let mut has_explicit = false
for name, inst in ctx.state {
targets.push(name)
if inst.explicit {
has_explicit = true
reqs.push((
Some(inst.channel),
name,
if inst.constraint == "" {
"*"
} else {
inst.constraint
},
"installed \{name}",
))
}
}
if !has_explicit {
for name, inst in ctx.state {
reqs.push((
Some(inst.channel),
name,
if inst.constraint == "" {
"*"
} else {
inst.constraint
},
"installed \{name}",
))
}
}
} else {
for n in names {
if !ctx.state.contains(n) {
raise OrbitError("\{n} is not installed")
let inst = match ctx.state.get(n) {
Some(i) => i
None => raise OrbitError("\{n} is not installed")
}
targets.push(n)
reqs.push((
Some(inst.channel),
n,
if inst.constraint == "" {
"*"
} else {
inst.constraint
},
"installed \{n}",
))
}
}
let p = new_planner(ctx, targets)
for n in targets {
match ctx.state.get(n) {
Some(inst) => visit(p, n, "*", inst.explicit, None)
None => ()
let steps = plan_global(ctx, reqs, targets, Map([]))
// Upgrading everything ends by removing the dependencies nobody needs.
let leaving : Array[String] = []
if names.length() == 0 {
for name, inst in ctx.state {
if !inst.explicit {
leaving.push(name)
}
}
apply_plan(ctx, p)
}
check_plan_conflicts(ctx, steps, leaving)
apply_plan(ctx, steps)
if names.length() == 0 {
autoremove(ctx)
save_state(ctx)
}
}
///|
fn reverse_deps(ctx : Ctx, name : String) -> Array[String] {
let r : Array[String] = []
for other, p in ctx.state {
if other != name && p.depends.contains(name) {
if other != name {
let mut uses = false
for dk, _ in p.depends {
if parse_dep_key(dk).1 == name {
uses = true
break
}
}
if uses {
r.push(other)
}
}
}
r
}
@@ -484,6 +639,18 @@ async fn cmd_rollback(ctx : Ctx, name : String) -> Unit raise OrbitError {
"previous build of \{name} (\{prev.version}) is no longer in the store",
)
}
for other, oinst in ctx.state {
if other != name &&
(
declares_conflict(prev.conflicts, other, oinst.version) ||
declares_conflict(oinst.conflicts, name, prev.version)
) {
raise OrbitError(
"\{name} \{prev.version} conflicts with installed \{other} \{oinst.version}",
)
}
}
check_bin_conflicts(ctx, name, prev.bins)
unlink_bins(ctx, inst.bins)
inst.history.push(Gen::{
channel: inst.channel,
@@ -492,6 +659,7 @@ async fn cmd_rollback(ctx : Ctx, name : String) -> Unit raise OrbitError {
description: inst.description,
bins: inst.bins,
depends: inst.depends,
conflicts: inst.conflicts,
})
inst.channel = prev.channel
let from = inst.version
@@ -500,13 +668,14 @@ async fn cmd_rollback(ctx : Ctx, name : String) -> Unit raise OrbitError {
inst.description = prev.description
inst.bins = prev.bins
inst.depends = prev.depends
check_bin_conflicts(ctx, name, inst.bins)
inst.conflicts = prev.conflicts
link_bins(ctx, dir, inst.bins)
save_state(ctx)
println("\{name}: \{from} -> \{prev.version}")
let missing : Array[String] = []
for dep, c in inst.depends {
match ctx.state.get(dep) {
let (_, dep_name) = parse_dep_key(dep)
match ctx.state.get(dep_name) {
Some(d) =>
if !satisfies_all(d.version, [c]) {
missing.push(dep + "@" + c)
@@ -563,11 +732,19 @@ fn cmd_list(ctx : Ctx) -> Unit {
println("no packages installed")
return
}
let rows : Array[Array[String]] = []
for name, p in ctx.state {
let kind = if p.explicit { "" } else { " (dependency)" }
let from = if p.channel == MAIN_CHANNEL { "" } else { " [\{p.channel}]" }
println("\{name} \{p.version}\{from}\{kind}")
rows.push(
package_row(
name,
p.channel,
p.version,
p.description,
dependency=!p.explicit,
),
)
}
print_packages(rows)
}
///|
@@ -587,35 +764,94 @@ async fn locate_spec(
}
///|
fn cmd_info(ctx : Ctx, spec : String) -> Unit raise OrbitError {
let (pin, name) = split_channel(spec)
let p = match ctx.state.get(name) {
Some(p) => p
None => raise OrbitError("\{spec} is not installed")
/// Find a build for info in the channel listings that search caches: the
/// pinned channel, else the one it is installed from, else by priority. None
/// if no listing has a matching version with a known digest, so the registry
/// has to be asked.
async fn listed_build(
ctx : Ctx,
name : String,
pin : String?,
constraint : String,
) -> (Channel, String, String)? raise OrbitError {
let wanted = match pin {
Some(c) => Some(c)
None => ctx.state.get(name).map(i => i.channel)
}
if pin is Some(channel) && channel != p.channel {
raise OrbitError("\{spec} is not installed (installed from '\{p.channel}')")
let channels = match wanted {
Some(c) => [find_channel(ctx, c)]
None => ctx.channels
}
for ch in channels {
let entries = match channel_listing(ctx.root, ch, name, false) {
Some(es) => es
None => continue
}
match find_entry(entries, name) {
Some(e) =>
if e.digest != "" && satisfies_all(e.version, [constraint]) {
return Some((ch, e.version, e.digest))
} else {
// Another version, or no digest: the registry knows its digest.
return None
}
None => ()
}
}
None
}
///|
/// Details of an installed package, or of the newest matching build in a
/// channel when it isn't installed (or `channel::` / `@constraint` asks for
/// another build).
async fn cmd_info(ctx : Ctx, spec : String) -> Unit raise OrbitError {
let (pin, name, constraint, explicit) = parse_spec_full(spec)
match ctx.state.get(name) {
Some(p) =>
if (pin is None || pin == Some(p.channel)) &&
(!explicit || satisfies_all(p.version, [constraint])) {
println("\{name} \{p.version} (installed)")
if p.description != "" {
println(" description: \{p.description}")
print_details(installed_details(ctx, p), " ")
print_details(
[
("constraint", [p.constraint]),
("needed by", [join(reverse_deps(ctx, name), " ")]),
("rollback", [join(p.history.map(g => g.version), " ")]),
],
" ",
)
return
}
println(" channel: \{p.channel}")
println(" digest: \{p.digest}")
println(" constraint: \{p.constraint}")
println(" bin: \{join(p.bins, " ")}")
let deps : Array[String] = []
for d, c in p.depends {
deps.push(d + "@" + c)
None => ()
}
println(" depends: \{join(deps, " ")}")
let rd = reverse_deps(ctx, name)
println(" needed by: \{join(rd, " ")}")
let hist : Array[String] = []
for g in p.history {
hist.push(g.version)
let (ch, version, digest) = match listed_build(ctx, name, pin, constraint) {
Some(found) => found
None => {
let wanted = match pin {
Some(c) => Some(c)
None => ctx.state.get(name).map(i => i.channel)
}
println(" rollback: \{join(hist, " ")}")
let (ch, tags) = locate(ctx, name, wanted)
let versions = sorted_versions(tags)
let version = match
versions.search_by(v => satisfies_all(v, [constraint])) {
Some(i) => versions[i]
None =>
raise OrbitError(
"no version of \{ch.name}::\{name} matches '\{constraint}'",
)
}
(ch, version, resolve_digest(ch, name, version))
}
}
let m = fetch_manifest_cached(ctx.root, ch, name, digest)
let status = match ctx.state.get(name) {
Some(p) => "not installed; \{p.version} from \{p.channel} is"
None => "not installed"
}
println("\{name} \{version} (\{status})")
print_details(available_details(m, channel=ch.name, digest~), " ")
}
///|
@@ -681,18 +917,16 @@ fn orbit_info(text : String) -> RepoInfo? {
/// Any failure counts as "not an Orbit package", so one broken repo can't hide
/// the others.
async fn orbit_repo_info(ch : Channel, repo : String) -> RepoInfo? noraise {
let tags = lines(capture(oras(ch, "repo tags " + sq(repo_of(ch, repo))))) catch {
_ => return None
let tags = match
(list_tags_quiet(ch, repo) catch { _ => return None }) {
Some(ts) => ts
None => return None
}
if tags.length() == 0 {
return None
}
let tag = if tags.contains("latest") { "latest" } else { tags[0] }
let text = capture(
oras(ch, "manifest fetch " + sq(repo_of(ch, repo) + ":" + tag)),
) catch {
_ => return None
}
let text = fetch_raw_manifest(ch, repo, tag) catch { _ => return None }
orbit_info(text)
}
@@ -783,58 +1017,78 @@ fn print_table(rows : Array[Array[String]]) -> Unit {
}
///|
async fn cmd_search(ctx : Ctx, term : String) -> Unit raise OrbitError {
let rows : Array[Array[String]] = [
["PACKAGE", "CHANNEL", "VERSION", "DESCRIPTION"],
]
let mut listed = 0
for ch in ctx.channels {
let out = capture(
oras(ch, "repo ls " + sq(ch.url)),
progress="Listing packages in \{ch.name}",
) catch {
_ => {
println("warning: channel '\{ch.name}' does not allow listing packages")
continue
/// Registry text for the terminal: control characters become spaces.
fn printable(s : String) -> String {
let sb = StringBuilder()
for c in s {
let n = c.to_int()
sb.write_char(if n < 32 || (n >= 127 && n < 160) { ' ' } else { c })
}
sb.to_string()
}
///|
/// A row of the table that search and list share.
fn package_row(
name : String,
channel : String,
version : String,
description : String,
dependency? : Bool = false,
) -> Array[String] {
let desc = printable(description)
[
name,
channel,
if version == "" {
"-"
} else {
printable(version)
},
match (desc, dependency) {
("", true) => "(dependency)"
("", false) => "-"
(d, true) => d + " (dependency)"
(d, false) => d
},
]
}
///|
fn print_packages(rows : Array[Array[String]]) -> Unit {
let table = [["PACKAGE", "CHANNEL", "VERSION", "DESCRIPTION"]]
table.append(rows)
print_table(table)
}
///|
async fn cmd_search(
ctx : Ctx,
term : String,
refresh? : Bool = false,
) -> Unit raise OrbitError {
let rows : Array[Array[String]] = []
let mut listed = 0
let term_lower = ascii_lower(term)
for ch in ctx.channels {
let entries = match channel_listing(ctx.root, ch, term_lower, refresh) {
Some(es) => es
None => continue
}
listed = listed + 1
let candidates : Array[String] = []
for r in lines(out) {
// A name with "/" is a nested channel namespace (e.g. example/greet under
// main), not a package name that `orbit install` could use.
if valid_name(r) && contains_str(r, term) {
candidates.push(r)
}
}
let found = find_orbit_repos(ch, candidates)
for i, r in candidates {
match found[i] {
Some(info) =>
rows.push([
r,
ch.name,
if info.version == "" {
"-"
} else {
info.version
},
if info.description == "" {
"-"
} else {
info.description
},
])
None => ()
for e in entries {
if contains_str(e.name, term_lower) ||
contains_str(ascii_lower(e.description), term_lower) {
rows.push(package_row(e.name, ch.name, e.version, e.description))
}
}
}
if listed == 0 {
raise OrbitError(
"no channel allows listing packages (catalog API); try `orbit versions <name>`",
"no channel could be listed; if you know the package name, try `orbit versions <name>`",
)
}
if rows.length() == 1 {
if rows.is_empty() {
if term == "" {
println("no packages found")
} else {
@@ -842,7 +1096,7 @@ async fn cmd_search(ctx : Ctx, term : String) -> Unit raise OrbitError {
}
return
}
print_table(rows)
print_packages(rows)
}
///|
@@ -892,3 +1146,15 @@ test "table columns line up" {
assert_eq(pad_right("ab", 4), "ab ")
assert_eq(pad_right("abcd", 2), "abcd")
}
///|
test "list and search rows mark dependencies and blanks" {
assert_eq(package_row("a", "main", "1.0.0", "A tool"), [
"a", "main", "1.0.0", "A tool",
])
assert_eq(package_row("a", "main", "", ""), ["a", "main", "-", "-"])
assert_eq(package_row("a", "main", "1.0.0", "A\u001btool", dependency=true), [
"a", "main", "1.0.0", "A tool (dependency)",
])
assert_eq(package_row("a", "main", "1.0.0", "", dependency=true)[3], "(dependency)")
}
+1750
View File
File diff suppressed because it is too large. Load diff
+694 -80
View File
@@ -1,10 +1,4 @@
// Everything that talks to the registry goes through the `oras` CLI.
// Authentication is whatever `oras login` has stored.
///|
fn oras(ch : Channel, args : String) -> String {
"oras " + args + (if ch.plain_http { " --plain-http" } else { "" })
}
// Native OCI Distribution v2 registry client operations.
///|
fn repo_of(ch : Channel, name : String) -> String {
@@ -12,39 +6,189 @@ fn repo_of(ch : Channel, name : String) -> String {
}
///|
/// Whether oras output says the repository doesn't exist, as opposed to the
/// registry being unreachable or refusing access.
fn is_missing_repo(err : String) -> Bool {
contains_str(err, "name unknown") ||
contains_str(err, "response status code 404")
fn channel_base_url(ch : Channel) -> String {
let (host, _) = split_channel_url(ch.url)
channel_scheme(ch) + "://" + host
}
///|
fn channel_repo_path(ch : Channel, name : String) -> String {
let (_, ns) = split_channel_url(ch.url)
if ns == "" {
name
} else {
ns + "/" + name
}
}
///|
/// Whether an HTTP status says the repository doesn't exist, as opposed to
/// the registry being unreachable or refusing access.
fn is_missing_status(code : Int32) -> Bool {
code == 404
}
///|
async fn verify_login(
host : String,
plain_http : Bool,
creds : Creds,
) -> Unit raise OrbitError {
let scheme = if plain_http { "http" } else { "https" }
let url = scheme + "://" + host + "/v2/"
let (resp, body) = oci_request(
Get,
url,
Map([("Accept", "application/json")]),
b"",
"",
creds_override=creds,
)
if resp.code < 200 || resp.code >= 300 {
raise OrbitError(
"login to \{host} failed (\{format_oci_error(resp.code, resp.reason, body)})",
)
}
}
///|
async fn list_repos(ch : Channel) -> Array[String] raise OrbitError {
with_spinner("Listing packages in \{ch.name}", () => {
let base = channel_base_url(ch)
let (_, ns) = split_channel_url(ch.url)
let ns_prefix = if ns == "" { "" } else { ns + "/" }
let out : Array[String] = []
let seen : Array[String] = []
let mut next_url : String? = Some(base + "/v2/_catalog")
while next_url is Some(url) {
if seen.contains(url) {
break
}
seen.push(url)
let (resp, body) = oci_request(
Get,
url,
Map([("Accept", "application/json")]),
b"",
"catalog",
)
if resp.code < 200 || resp.code >= 300 {
raise OrbitError(
"channel '\{ch.name}' (\{ch.url}): \{format_oci_error(resp.code, resp.reason, body)}",
)
}
let obj = parse_object(utf8_decode(body), "catalog")
let page = jstrs(obj, "repositories")
if page.length() == 0 {
break
}
for r in page {
if ns_prefix == "" {
out.push(r)
} else if has_prefix(r, ns_prefix) {
out.push(drop_chars(r, chars(ns_prefix).length()))
}
}
next_url = match resp.headers.get(hdr("Link")) {
Some(link) =>
match parse_next_link(link) {
Some(target) => {
let resolved = resolve_location(parse_url(url), target)
let full = resolved.scheme + "://" + resolved.host + resolved.path
if seen.contains(full) {
None
} else {
Some(full)
}
}
None => None
}
None => None
}
}
out
})
}
///|
/// The tags of `name` in a channel, or None if the channel doesn't have it.
/// Any other failure is an error: falling through to a lower priority channel
/// could install a different package with the same name.
async fn list_tags(ch : Channel, name : String) -> Array[String]? raise OrbitError {
let errfile = trim(capture("mktemp"))
let cmd = oras(ch, "repo tags " + sq(repo_of(ch, name))) + " 2>" + sq(errfile)
let out = Some(
capture(cmd, progress="Checking versions of \{ch.name}::\{name}"),
) catch {
_ => None
async fn list_tags_inner(
ch : Channel,
name : String,
) -> Array[String]? raise OrbitError {
let base = channel_base_url(ch)
let repo = channel_repo_path(ch, name)
let scope_key = repo + ":pull"
let out : Array[String] = []
let seen : Array[String] = []
let mut next_url : String? = Some(base + "/v2/" + repo + "/tags/list")
let mut first = true
while next_url is Some(url) {
if seen.contains(url) {
break
}
let err = match read_text(errfile) {
Some(t) => trim(t)
None => ""
seen.push(url)
let (resp, body) = oci_request(
Get,
url,
Map([("Accept", "application/json")]),
b"",
scope_key,
)
if first && is_missing_status(resp.code) {
return None
}
sh("rm -f " + sq(errfile)) |> ignore
match out {
Some(o) => Some(lines(o))
None =>
if is_missing_repo(err) {
first = false
if resp.code < 200 || resp.code >= 300 {
raise OrbitError(
"channel '\{ch.name}' (\{ch.url}): \{format_oci_error(resp.code, resp.reason, body)}",
)
}
let obj = parse_object(utf8_decode(body), "tags/list")
let page = jstrs(obj, "tags")
if page.length() == 0 {
break
}
for t in page {
if !out.contains(t) {
out.push(t)
}
}
next_url = match resp.headers.get(hdr("Link")) {
Some(link) =>
match parse_next_link(link) {
Some(target) => {
let resolved = resolve_location(parse_url(url), target)
let full = resolved.scheme + "://" + resolved.host + resolved.path
if seen.contains(full) {
None
} else {
raise OrbitError("channel '\{ch.name}' (\{ch.url}): \{err}")
Some(full)
}
}
None => None
}
None => None
}
}
Some(out)
}
///|
async fn list_tags(ch : Channel, name : String) -> Array[String]? raise OrbitError {
with_spinner("Checking versions of \{ch.name}::\{name}", () => {
list_tags_inner(ch, name)
})
}
///|
async fn list_tags_quiet(
ch : Channel,
name : String,
) -> Array[String]? raise OrbitError {
list_tags_inner(ch, name)
}
///|
@@ -53,38 +197,238 @@ async fn resolve_digest(
name : String,
tag : String,
) -> String raise OrbitError {
let d = trim(
capture(
oras(ch, "resolve " + sq(repo_of(ch, name) + ":" + tag)),
progress="Resolving \{ch.name}::\{name}@\{tag}",
),
with_spinner("Resolving \{ch.name}::\{name}@\{tag}", () => {
let repo = channel_repo_path(ch, name)
let url = channel_base_url(ch) + "/v2/" + repo + "/manifests/" + tag
let scope_key = repo + ":pull"
let req_headers = Map([("Accept", MANIFEST_ACCEPT)])
let (head_resp, head_body) = oci_request(
Head,
url,
req_headers,
b"",
scope_key,
)
if !(has_prefix(d, "sha256:") || has_prefix(d, "sha512:")) {
raise OrbitError("unexpected digest for \{name}:\{tag}: '\{d}'")
let mut digest = if head_resp.code >= 200 && head_resp.code < 300 {
extract_digest_header(head_resp.headers).unwrap_or("")
} else {
""
}
d
if head_resp.code == 405 ||
(head_resp.code >= 200 && head_resp.code < 300 && digest == "") {
let (get_resp, get_body) = oci_request(
Get,
url,
req_headers,
b"",
scope_key,
)
if get_resp.code < 200 || get_resp.code >= 300 {
raise OrbitError(
"cannot resolve \{ch.name}::\{name}@\{tag}: \{format_oci_error(get_resp.code, get_resp.reason, get_body)}",
)
}
digest = match extract_digest_header(get_resp.headers) {
Some(d) => d
None => sha256_digest(get_body)
}
} else if head_resp.code < 200 || head_resp.code >= 300 {
raise OrbitError(
"cannot resolve \{ch.name}::\{name}@\{tag}: \{format_oci_error(head_resp.code, head_resp.reason, head_body)}",
)
}
if !(has_prefix(digest, "sha256:") || has_prefix(digest, "sha512:")) {
raise OrbitError("unexpected digest for \{name}:\{tag}: '\{digest}'")
}
digest
})
}
///|
async fn fetch_raw_manifest_bytes(
ch : Channel,
name : String,
ref_str : String,
) -> Bytes raise OrbitError {
let repo = channel_repo_path(ch, name)
let url = channel_base_url(ch) + "/v2/" + repo + "/manifests/" + ref_str
let (resp, body) = oci_request(
Get,
url,
Map([("Accept", MANIFEST_ACCEPT)]),
b"",
repo + ":pull",
)
if resp.code < 200 || resp.code >= 300 {
raise OrbitError(
"cannot fetch manifest \{ch.name}::\{name}@\{ref_str}: \{format_oci_error(resp.code, resp.reason, body)}",
)
}
if has_prefix(ref_str, "sha256:") {
let actual = sha256_digest(body)
if actual != ref_str {
raise OrbitError(
"manifest digest mismatch for \{name}@\{ref_str}: got \{actual}",
)
}
}
body
}
///|
async fn fetch_raw_manifest(
ch : Channel,
name : String,
ref_str : String,
) -> String raise OrbitError {
utf8_decode(fetch_raw_manifest_bytes(ch, name, ref_str))
}
///|
fn manifest_cache_path(root : String, digest : String) -> String? {
if root == "" || !has_prefix(digest, "sha256:") {
return None
}
let hex = drop_chars(digest, 7)
if hex == "" {
return None
}
for c in hex {
let ok = (c >= '0' && c <= '9') ||
(c >= 'a' && c <= 'f') ||
(c >= 'A' && c <= 'F')
if !ok {
return None
}
}
Some(cache_dir(root) + "/" + ascii_lower(hex) + ".json")
}
///|
/// Fetch only the config blob (orbit.json); no layer download needed to plan.
async fn fetch_manifest(
async fn fetch_manifest_with_raw(
ch : Channel,
name : String,
digest : String,
) -> Manifest raise OrbitError {
let text = capture(
oras(ch, "manifest fetch-config " + sq(repo_of(ch, name) + "@" + digest)),
progress="Reading metadata for \{ch.name}::\{name}",
) -> (Manifest, String) raise OrbitError {
with_spinner("Reading metadata for \{ch.name}::\{name}", () => {
let repo = channel_repo_path(ch, name)
let manifest_text = fetch_raw_manifest(ch, name, digest)
let manifest_obj = parse_object(manifest_text, "manifest")
let cfg_digest = match manifest_obj.get("config") {
Some(Json::Object(c)) => jstr(c, "digest", "")
_ => ""
}
if cfg_digest == "" {
raise OrbitError("\{name}@\{digest} manifest missing config.digest")
}
let blob_url = channel_base_url(ch) + "/v2/" + repo + "/blobs/" + cfg_digest
let (resp, body) = oci_request(
Get,
blob_url,
Map([("Accept", CONFIG_MEDIA_TYPE + ", application/json")]),
b"",
repo + ":pull",
)
let m = parse_manifest(text)
if resp.code < 200 || resp.code >= 300 {
raise OrbitError(
"cannot fetch config for \{name}@\{digest}: \{format_oci_error(resp.code, resp.reason, body)}",
)
}
if has_prefix(cfg_digest, "sha256:") {
let actual = sha256_digest(body)
if actual != cfg_digest {
raise OrbitError(
"config digest mismatch for \{name}@\{digest}: expected \{cfg_digest}, got \{actual}",
)
}
}
let raw = utf8_decode(body)
let m = parse_manifest(raw)
if m.name != name {
raise OrbitError(
"\{name}@\{digest} declares name '\{m.name}'; refusing to install",
)
}
(m, raw)
})
}
///|
/// Fetch config blob (orbit.json) using a digest-keyed local cache under
/// `<root>/cache/manifests/<hex>.json`. Pass `root = ""` to skip caching.
async fn fetch_manifest_cached(
root : String,
ch : Channel,
name : String,
digest : String,
) -> Manifest raise OrbitError {
match manifest_cache_path(root, digest) {
Some(path) =>
match read_text(path) {
Some(raw) => {
let cached : Manifest? = Some(parse_manifest(raw)) catch { _ => None }
match cached {
Some(m) => if m.name == name { return m }
None => ()
}
}
None => ()
}
None => ()
}
let (m, raw) = fetch_manifest_with_raw(ch, name, digest)
match manifest_cache_path(root, digest) {
Some(path) => {
try {
@fs.mkdir(cache_dir(root), recursive=true, allow_exist=true)
write_text_atomic(path, raw)
} catch {
_ => ()
}
}
None => ()
}
m
}
///|
fn find_pkg_layer_digest(manifest_obj : Map[String, Json]) -> String? {
let layers = match manifest_obj.get("layers") {
Some(Json::Array(xs)) => xs
_ => return None
}
for item in layers {
match item {
Json::Object(l) =>
if jstr(l, "mediaType", "") == LAYER_MEDIA_TYPE {
let d = jstr(l, "digest", "")
if d != "" {
return Some(d)
}
}
_ => ()
}
}
for item in layers {
match item {
Json::Object(l) =>
match l.get("annotations") {
Some(Json::Object(ann)) =>
if jstr(ann, "org.opencontainers.image.title", "") == "pkg.tar.gz" {
let d = jstr(l, "digest", "")
if d != "" {
return Some(d)
}
}
_ => ()
}
_ => ()
}
}
None
}
///|
/// Pull a package layer by digest and unpack it into the store.
/// Unpacks into a temp dir first, then renames, so a store dir is either
@@ -99,14 +443,39 @@ async fn fetch_into_store(
if exists(dir) {
return dir
}
let manifest_text = fetch_raw_manifest(ch, name, digest)
let manifest_obj = parse_object(manifest_text, "manifest")
let layer_digest = match find_pkg_layer_digest(manifest_obj) {
Some(d) => d
None => raise OrbitError("\{name}@\{digest} has no pkg.tar.gz layer")
}
let repo = channel_repo_path(ch, name)
let blob_url = channel_base_url(ch) + "/v2/" + repo + "/blobs/" + layer_digest
let tmp = ctx.root + "/tmp/" + name + "-" + store_id(digest)
sh_ok("rm -rf " + sq(tmp) + " && mkdir -p " + sq(tmp + "/root"))
sh_ok(
oras(ch, "pull -o " + sq(tmp) + " " + sq(repo_of(ch, name) + "@" + digest)) +
" >/dev/null",
let dl_res : Result[Unit, Error] = try {
with_spinner("Downloading \{ch.name}::\{name}", () => {
oci_download_to_file(
blob_url,
tmp + "/pkg.tar.gz",
layer_digest,
repo + ":pull",
)
if !exists(tmp + "/pkg.tar.gz") {
raise OrbitError("\{name}@\{digest} has no pkg.tar.gz layer")
})
Ok(())
} catch {
e => Err(e)
}
match dl_res {
Ok(_) => ()
Err(OrbitError(msg)) => {
sh("rm -rf " + sq(tmp)) |> ignore
raise OrbitError(msg)
}
Err(e) => {
sh("rm -rf " + sq(tmp)) |> ignore
raise OrbitError(e.to_string())
}
}
sh_ok(
"tar -xzf " +
@@ -182,18 +551,271 @@ test "package config exposes Gitea labels and preserves Orbit metadata" {
)
}
///|
fn json_int64(n : Int64) -> Json {
Json::number(n.to_double(), repr=n.to_string())
}
///|
fn append_digest_param(upload_url : String, digest : String) -> String {
let sep = if has_char(upload_url, '?') { "&" } else { "?" }
upload_url + sep + "digest=" + @percent.encode(digest)
}
///|
async fn blob_exists(
base : String,
repo : String,
digest : String,
) -> Bool raise OrbitError {
let url = base + "/v2/" + repo + "/blobs/" + digest
let (resp, body) = oci_request(Head, url, Map([]), b"", repo + ":pull")
if resp.code >= 200 && resp.code < 300 {
return true
}
if resp.code == 404 {
return false
}
raise OrbitError(
"blob check failed (\{format_oci_error(resp.code, resp.reason, body)})",
)
}
///|
async fn start_blob_upload(base : String, repo : String) -> String raise OrbitError {
let init_url = base + "/v2/" + repo + "/blobs/uploads/"
let (resp, body) = oci_request(Post, init_url, Map([]), b"", repo + ":push")
if resp.code < 200 || resp.code >= 300 {
raise OrbitError(
"failed to initiate blob upload (\{format_oci_error(resp.code, resp.reason, body)})",
)
}
let loc = match resp.headers.get(hdr("Location")) {
Some(l) => l
None => raise OrbitError("blob upload response missing Location header")
}
let resolved = resolve_location(parse_url(init_url), loc)
resolved.scheme + "://" + resolved.host + resolved.path
}
///|
async fn upload_blob_bytes(
base : String,
repo : String,
digest : String,
data : Bytes,
) -> Unit raise OrbitError {
if blob_exists(base, repo, digest) {
return
}
let upload_url = append_digest_param(start_blob_upload(base, repo), digest)
let (resp, body) = oci_request(
Put,
upload_url,
Map([("Content-Type", "application/octet-stream")]),
data,
repo + ":push",
)
if resp.code < 200 || resp.code >= 300 {
raise OrbitError(
"blob upload failed (\{format_oci_error(resp.code, resp.reason, body)})",
)
}
}
///|
/// Files larger than this are uploaded in pieces of this size. Registries and
/// their proxies limit the length of one request; GHCR accepts 4 MiB per piece.
const UPLOAD_CHUNK : Int32 = 4194304
///|
/// The URL for the next step of an upload. It must stay on the registry's own
/// origin, so that the token and the data don't go to another host.
fn next_upload_url(
url : String,
location : String?,
) -> String raise OrbitError {
match location {
Some(loc) => {
let cur = parse_url(url)
let next = resolve_location(cur, loc)
if !same_origin(cur, next) {
raise OrbitError("unexpected upload location on \{next.host}")
}
next.scheme + "://" + next.host + next.path
}
None => url
}
}
///|
/// Upload a file in pieces. Returns false if the registry refuses the first
/// piece as unsupported, so the caller can send the file in one request.
async fn upload_chunks(
base : String,
repo : String,
digest : String,
path : String,
size : Int64,
chunk : Int32,
) -> Bool raise OrbitError {
let mut url = start_blob_upload(base, repo)
let file = @fs.open(path, mode=ReadOnly) catch {
e => raise OrbitError("cannot open \{path}: \{e}")
}
defer file.close()
let mut sent = 0L
while sent < size {
let left = size - sent
let want = if left < chunk.to_int64() { left.to_int() } else { chunk }
let data = file.read_exactly(want) catch {
e => raise OrbitError("cannot read \{path}: \{e}")
}
let last = sent + want.to_int64() - 1L
let (resp, body) = oci_request(
Patch,
url,
Map([
("Content-Type", "application/octet-stream"),
("Content-Range", "\{sent}-\{last}"),
]),
data,
repo + ":push",
)
if sent == 0L &&
(resp.code == 404 || resp.code == 405 || resp.code == 501) {
return false
}
if resp.code < 200 || resp.code >= 300 {
raise OrbitError(
"layer upload failed (\{format_oci_error(resp.code, resp.reason, body)})",
)
}
url = next_upload_url(url, resp.headers.get(hdr("Location")))
sent = last + 1L
}
let (resp, body) = oci_request(
Put,
append_digest_param(url, digest),
Map([("Content-Type", "application/octet-stream")]),
b"",
repo + ":push",
)
if resp.code < 200 || resp.code >= 300 {
raise OrbitError(
"layer upload failed (\{format_oci_error(resp.code, resp.reason, body)})",
)
}
true
}
///|
async fn upload_blob_file(
base : String,
repo : String,
digest : String,
path : String,
size : Int64,
chunk? : Int32 = UPLOAD_CHUNK,
) -> Unit raise OrbitError {
if blob_exists(base, repo, digest) {
return
}
if size > chunk.to_int64() &&
upload_chunks(base, repo, digest, path, size, chunk) {
return
}
let upload_url = append_digest_param(start_blob_upload(base, repo), digest)
let (resp, body) = oci_upload_file(
upload_url,
path,
size,
"application/octet-stream",
repo + ":push",
)
if resp.code < 200 || resp.code >= 300 {
raise OrbitError(
"layer upload failed (\{format_oci_error(resp.code, resp.reason, body)})",
)
}
}
///|
fn build_oci_manifest_bytes(
m : Manifest,
config_digest : String,
config_size : Int64,
layer_digest : String,
layer_size : Int64,
) -> Bytes {
let cfg : Map[String, Json] = Map([])
cfg["mediaType"] = Json::string(CONFIG_MEDIA_TYPE)
cfg["digest"] = Json::string(config_digest)
cfg["size"] = json_int64(config_size)
let layer_ann : Map[String, Json] = Map([])
layer_ann["org.opencontainers.image.title"] = Json::string("pkg.tar.gz")
let layer : Map[String, Json] = Map([])
layer["mediaType"] = Json::string(LAYER_MEDIA_TYPE)
layer["digest"] = Json::string(layer_digest)
layer["size"] = json_int64(layer_size)
layer["annotations"] = Json::object(layer_ann)
let ann : Map[String, Json] = Map([])
ann["org.opencontainers.image.created"] = Json::string(utc_now())
ann["org.opencontainers.image.version"] = Json::string(m.version)
if m.description != "" {
ann["org.opencontainers.image.description"] = Json::string(m.description)
}
let manifest : Map[String, Json] = Map([])
manifest["schemaVersion"] = json_int64(2L)
manifest["mediaType"] = Json::string(OCI_MANIFEST_MEDIA_TYPE)
manifest["artifactType"] = Json::string(ORBIT_ARTIFACT_TYPE)
manifest["config"] = Json::object(cfg)
manifest["layers"] = Json::array([Json::object(layer)])
manifest["annotations"] = Json::object(ann)
utf8_encode(Json::object(manifest).stringify() + "\n")
}
///|
async fn put_manifest(
base : String,
repo : String,
tag : String,
manifest_bytes : Bytes,
) -> Unit raise OrbitError {
let url = base + "/v2/" + repo + "/manifests/" + tag
let (resp, body) = oci_request(
Put,
url,
Map([("Content-Type", OCI_MANIFEST_MEDIA_TYPE)]),
manifest_bytes,
repo + ":push",
)
if resp.code < 200 || resp.code >= 300 {
raise OrbitError(
"manifest push failed for tag '\{tag}' (\{format_oci_error(resp.code, resp.reason, body)})",
)
}
}
///|
/// Pack `<dir>/files` and push it with the enriched Orbit config blob.
async fn publish(
ch : Channel,
dir : String,
also_latest : Bool,
update_index? : Bool = true,
) -> Unit raise OrbitError {
let text = match read_text(dir + "/orbit.json") {
Some(t) => t
None => raise OrbitError("\{dir}/orbit.json not found")
}
let m = parse_manifest(text)
if m.name == INDEX_NAME {
raise OrbitError("'\{INDEX_NAME}' is reserved for the channel index")
}
let config = package_config(text, m)
let files = dir + "/files"
if !exists(files) {
@@ -204,39 +826,31 @@ async fn publish(
raise OrbitError("bin '\{b}' listed in orbit.json is missing from files/")
}
}
let tmp = trim(capture("mktemp -d"))
sh_ok(
"tar -czf " +
sq(tmp + "/pkg.tar.gz") +
" --owner=0 --group=0 -C " +
sq(files) +
" .",
)
write_text_atomic(tmp + "/orbit.json", config)
let tags = if also_latest { m.version + ",latest" } else { m.version }
let push = oras(
ch,
"push " +
sq(repo_of(ch, m.name) + ":" + tags) +
" --artifact-type " +
sq(ORBIT_ARTIFACT_TYPE) +
" --config " +
sq("orbit.json:" + CONFIG_MEDIA_TYPE) +
" --annotation " +
sq("org.opencontainers.image.version=" + m.version) +
(if m.description != "" {
" --annotation " +
sq("org.opencontainers.image.description=" + m.description)
} else {
""
}) +
" " +
sq("pkg.tar.gz:" + LAYER_MEDIA_TYPE),
)
let rc = sh("cd " + sq(tmp) + " && " + push)
sh("rm -rf " + sq(tmp)) |> ignore
if rc != 0 {
raise OrbitError("oras push failed (exit \{rc})")
let tmp = @fs.tmpdir(prefix="orbit-publish-") catch {
e => raise OrbitError("cannot create temp dir: \{e}")
}
defer (@fs.rmdir(tmp, recursive=true, allow_missing=true) catch { _ => () })
let pkg_path = tmp + "/pkg.tar.gz"
sh_ok("tar -czf " + sq(pkg_path) + " --owner=0 --group=0 -C " + sq(files) + " .")
let config_bytes = utf8_encode(config)
let config_digest = sha256_digest(config_bytes)
let config_size = config_bytes.length().to_int64()
let (layer_digest, layer_size) = sha256_file(pkg_path)
let base = channel_base_url(ch)
let repo = channel_repo_path(ch, m.name)
let manifest_bytes = build_oci_manifest_bytes(
m, config_digest, config_size, layer_digest, layer_size,
)
with_spinner("Publishing \{m.name} \{m.version} to \{ch.name}", () => {
upload_blob_bytes(base, repo, config_digest, config_bytes)
upload_blob_file(base, repo, layer_digest, pkg_path, layer_size)
put_manifest(base, repo, m.version, manifest_bytes)
if also_latest {
put_manifest(base, repo, "latest", manifest_bytes)
}
})
println("published \{m.name} \{m.version} to \{repo_of(ch, m.name)}")
if update_index {
index_published(ch, m.name)
}
}
File diff suppressed because it is too large. Load diff
+261 -133
View File
@@ -1,35 +1,32 @@
// Minimal semantic versions and constraints.
//
// Constraint forms:
// Constraint forms (comma-separated clauses are ANDed together):
// "" | "*" | "latest" any stable version
// "1.2.3" | "=1.2.3" exact
// "1" | "1.2" prefix (1.x.x / 1.2.x)
// "1.2.3" | "=1.2.3" | "==1.2.3" exact
// "1" | "1.2" | "1.*" | "1.2.*" prefix (1.x.x / 1.2.x)
// "^1.2.3" same major (same minor while major is 0), >= base
// "~1.2.3" same major and minor, >= base
// ">=1.2.3" at least base
// "~1.2.3" same major and minor (or major if ~1), >= base
// ">=1.2.3" | "<=1.2.3" | ">1.2.3" | "<1.2.3" relational
// "!=1.2.3" | "!=1.2.*" exclusion
// Prerelease versions (1.0.0-rc1) only match constraints that mention a '-'.
///|
struct Ver {
nums : Array[Int32]
nums : Array[Int64]
parts : Int32
pre : String
}
///|
fn parse_nat(s : String) -> Int32? {
if s == "" {
return None
}
let mut n = 0
for c in s {
if c < '0' || c > '9' {
return None
}
n = n * 10 + (c.to_int() - '0'.to_int())
}
fn parse_nat(s : String) -> Int64? {
let codes = FixedArray::from_array(chars(s).map(c => c.to_int().to_int64()))
let n = @kernel.parse_nat(codes)
if n < 0L {
None
} else {
Some(n)
}
}
///|
fn parse_ver(s0 : String) -> Ver? {
@@ -40,7 +37,7 @@ fn parse_ver(s0 : String) -> Ver? {
if parts.length() == 0 || parts.length() > 3 {
return None
}
let nums = [0, 0, 0]
let nums = [0L, 0L, 0L]
for i = 0; i < parts.length(); i = i + 1 {
match parse_nat(parts[i]) {
Some(n) => nums[i] = n
@@ -59,20 +56,107 @@ fn is_ver(s : String) -> Bool {
}
///|
fn cmp_ver(a : Ver, b : Ver) -> Int32 {
for i = 0; i < 3; i = i + 1 {
if a.nums[i] != b.nums[i] {
return if a.nums[i] < b.nums[i] { -1 } else { 1 }
fn ver_key(v : Ver, pre : Int32) -> @kernel.Key {
{ major: v.nums[0], minor: v.nums[1], patch: v.nums[2], pre, }
}
}
if a.pre == b.pre {
///|
/// Order of prereleases; a release ("") comes after all of them.
fn cmp_pre(a : String, b : String) -> Int32 {
if a == b {
0
} else if a.pre == "" {
} else if a == "" {
1
} else if b.pre == "" {
} else if b == "" {
-1
} else {
a.pre.compare(b.pre)
a.compare(b)
}
}
///|
fn cmp_ver(a : Ver, b : Ver) -> Int32 {
@kernel.compare(ver_key(a, cmp_pre(a.pre, b.pre)), ver_key(b, 0))
}
///|
fn strip_dot_star(s : String) -> (String, Bool) {
let a = chars(s)
let n = a.length()
if n >= 2 && a[n - 2] == '.' && a[n - 1] == '*' {
(slice(a, 0, n - 2), true)
} else {
(s, false)
}
}
///|
/// Split a clause into its operator and the version it applies to; `None` if it
/// is malformed.
fn parse_clause(cl : String) -> (@kernel.Op, Ver)? {
let c = trim(cl)
if c == "*" || c == "latest" {
return Some((Any, Ver::{ nums: [0L, 0L, 0L], parts: 3, pre: "", }))
}
let plain = fn(op : @kernel.Op, rest : String) -> (@kernel.Op, Ver)? {
match parse_ver(trim(rest)) {
Some(b) => Some((op, b))
None => None
}
}
// An exact version, or a prefix when parts are missing or end in ".*".
let exact = fn(
whole : @kernel.Op,
prefix : @kernel.Op,
rest : String,
) -> (@kernel.Op, Ver)? {
let (ver_str, had_wild) = strip_dot_star(trim(rest))
match parse_ver(ver_str) {
Some(b) =>
if b.parts < 3 {
Some((prefix, b))
} else if had_wild {
None
} else {
Some((whole, b))
}
None => None
}
}
if has_prefix(c, ">=") {
plain(Ge, drop_chars(c, 2))
} else if has_prefix(c, "<=") {
plain(Le, drop_chars(c, 2))
} else if has_prefix(c, "!=") {
exact(Ne, NotPrefix, drop_chars(c, 2))
} else if has_prefix(c, "==") {
exact(Eq, Prefix, drop_chars(c, 2))
} else if has_prefix(c, ">") {
plain(Gt, drop_chars(c, 1))
} else if has_prefix(c, "<") {
plain(Lt, drop_chars(c, 1))
} else if has_prefix(c, "^") {
plain(Caret, drop_chars(c, 1))
} else if has_prefix(c, "~") {
plain(Tilde, drop_chars(c, 1))
} else if has_prefix(c, "=") {
exact(Eq, Prefix, drop_chars(c, 1))
} else {
exact(Eq, Prefix, c)
}
}
///|
fn satisfies_clause(v : Ver, cl : String) -> Bool {
match parse_clause(cl) {
Some((op, b)) =>
@kernel.matches(
op,
ver_key(v, cmp_pre(v.pre, b.pre)),
ver_key(b, 0),
b.parts,
)
None => false
}
}
@@ -82,43 +166,54 @@ fn satisfies(v : Ver, c0 : String) -> Bool {
if c == "" || c == "*" || c == "latest" {
return v.pre == ""
}
if v.pre != "" && !(has_char(c, '-')) {
if v.pre != "" && !has_char(c, '-') {
return false
}
let with_base = fn(rest : String, rule : (Ver) -> Bool) -> Bool {
match parse_ver(rest) {
Some(b) => cmp_ver(v, b) >= 0 && rule(b)
None => false
let pieces = split_on(c, ',')
for piece in pieces {
let p = trim(piece)
if p == "" || !satisfies_clause(v, p) {
return false
}
}
if has_prefix(c, ">=") {
with_base(drop_chars(c, 2), fn(_b) { true })
} else if has_prefix(c, "^") {
with_base(drop_chars(c, 1), fn(b) {
v.nums[0] == b.nums[0] && (b.nums[0] != 0 || v.nums[1] == b.nums[1])
})
} else if has_prefix(c, "~") {
with_base(drop_chars(c, 1), fn(b) {
v.nums[0] == b.nums[0] && v.nums[1] == b.nums[1]
})
} else {
let exact = if has_prefix(c, "=") { drop_chars(c, 1) } else { c }
match parse_ver(exact) {
Some(b) =>
if b.parts == 3 {
cmp_ver(v, b) == 0
} else {
let mut ok = true
for i = 0; i < b.parts; i = i + 1 {
if v.nums[i] != b.nums[i] {
ok = false
true
}
///|
fn valid_semver_clause(cl : String) -> Bool {
parse_clause(cl) is Some(_)
}
///|
fn valid_constraint(c0 : String) -> Bool {
let c = trim(c0)
if c == "" || c == "*" || c == "latest" {
return true
}
if !has_char(c, ',') && valid_semver_clause(c) {
return true
}
if has_char(c, ',') {
let pieces = split_on(c, ',')
for piece in pieces {
if !valid_semver_clause(piece) {
return false
}
}
ok
}
None => false
return true
}
// Allow non-semver literal tag pins (e.g. "edge") when they aren't malformed
// version numbers or operator expressions.
let a = chars(c)
let looks_like_ver = a.length() > 0 &&
(
(a[0] >= '0' && a[0] <= '9') ||
(a.length() > 1 && a[0] == 'v' && a[1] >= '0' && a[1] <= '9')
)
if looks_like_ver {
return false
}
valid_name(c)
}
///|
@@ -126,7 +221,7 @@ fn satisfies_all(version : String, cons : Array[String]) -> Bool {
match parse_ver(version) {
Some(v) => {
for c in cons {
if !(satisfies(v, c)) {
if !satisfies(v, c) {
return false
}
}
@@ -136,7 +231,11 @@ fn satisfies_all(version : String, cons : Array[String]) -> Bool {
None => {
for c in cons {
let t = trim(c)
if t != "" && t != "*" && t != version {
if t != "" &&
t != "*" &&
t != version &&
t != "=" + version &&
t != "==" + version {
return false
}
}
@@ -145,97 +244,126 @@ fn satisfies_all(version : String, cons : Array[String]) -> Bool {
}
}
///|
/// Pick the highest tag that satisfies every constraint. Falls back to a
/// literal non-semver tag when a constraint names one exactly.
fn pick_tag(tags : Array[String], cons : Array[String]) -> String? {
let mut best : (String, Ver)? = None
for t in tags {
match parse_ver(t) {
Some(v) =>
if satisfies_all(t, cons) {
match best {
None => best = Some((t, v))
Some((_, bv)) => if cmp_ver(v, bv) > 0 { best = Some((t, v)) }
}
}
None => ()
}
}
match best {
Some((t, _)) => Some(t)
None => {
for c in cons {
let t = trim(c)
if t != "" && t != "*" && !(is_ver(t)) && tags.contains(t) {
return Some(t)
}
}
None
}
}
}
///|
/// Semver tags, highest first.
fn sorted_versions(tags : Array[String]) -> Array[String] {
let out : Array[(String, Ver)] = []
let names : Array[String] = []
let vers : Array[Ver] = []
for t in tags {
match parse_ver(t) {
Some(v) => out.push((t, v))
Some(v) => {
names.push(t)
vers.push(v)
}
None => ()
}
}
// insertion sort, descending
for i = 1; i < out.length(); i = i + 1 {
let mut j = i
while j > 0 && cmp_ver(out[j].1, out[j - 1].1) > 0 {
let tmp = out[j]
out[j] = out[j - 1]
out[j - 1] = tmp
j = j - 1
}
}
let r : Array[String] = []
for p in out {
r.push(p.0)
}
r
let order = @kernel.sort_desc(FixedArray::from_array(ver_keys(vers)))
Array::makei(order.length(), fn(i) { names[order[i]] })
}
///|
test "parse and compare" {
let a = parse_ver("1.2.3").unwrap()
let b = parse_ver("v1.10.0").unwrap()
assert_true(cmp_ver(a, b) < 0)
assert_true(
cmp_ver(parse_ver("1.0.0-rc1").unwrap(), parse_ver("1.0.0").unwrap()) < 0,
/// Keys that order `vers`: the prerelease rank is how many prereleases among
/// `vers` come before it.
fn ver_keys(vers : Array[Ver]) -> Array[@kernel.Key] {
vers.map(fn(v) {
let mut rank = 0
for other in vers {
if cmp_pre(other.pre, v.pre) < 0 {
rank = rank + 1
}
}
ver_key(v, rank)
})
}
// Number parsing, ordering, interval and sorting laws are proved in
// src/kernel. The tests below cover what the prover cannot see: splitting
// strings into versions and clauses, and ranking prereleases.
///|
test "versions parse into numbers and a prerelease" {
let a = parse_ver("v1.10-rc1+build").unwrap()
assert_eq(a.nums, [1L, 10L, 0L])
assert_eq(a.parts, 2)
assert_eq(a.pre, "rc1")
assert_eq(parse_ver("1.0.20261130123000").unwrap().nums, [
1L, 0L, 20261130123000L,
])
for bad in ["", "1.x", "1.", "1.2.3.4", "1.-2", "1.0.1000000000000000000"] {
assert_true(parse_ver(bad) is None)
}
}
///|
test "prereleases rank below their release and by name" {
assert_eq(
sorted_versions([
"1.0.0-rc1", "edge", "2.0.0", "1.0.0", "1.0.0-rc2", "2.1.0-rc1",
]),
["2.1.0-rc1", "2.0.0", "1.0.0", "1.0.0-rc2", "1.0.0-rc1"],
)
assert_true(parse_ver("1.x") is None)
let rc1 = parse_ver("1.0.0-rc1").unwrap()
assert_true(cmp_ver(rc1, parse_ver("1.0.0").unwrap()) < 0)
assert_true(cmp_ver(rc1, parse_ver("1.0.0-rc2").unwrap()) < 0)
assert_eq(cmp_ver(rc1, rc1), 0)
}
///|
test "constraints" {
test "clauses parse into an operator and a version" {
let table : Array[(String, (@kernel.Op, Array[Int64], Int32)?)] = [
("*", Some((Any, [0L, 0L, 0L], 3))),
("latest", Some((Any, [0L, 0L, 0L], 3))),
(">=1.2", Some((Ge, [1L, 2L, 0L], 2))),
("<= 1.2.3", Some((Le, [1L, 2L, 3L], 3))),
(">1", Some((Gt, [1L, 0L, 0L], 1))),
("<2.0.0", Some((Lt, [2L, 0L, 0L], 3))),
("^1.2.0", Some((Caret, [1L, 2L, 0L], 3))),
("~1", Some((Tilde, [1L, 0L, 0L], 1))),
("1.4.2", Some((Eq, [1L, 4L, 2L], 3))),
("=1.4.2", Some((Eq, [1L, 4L, 2L], 3))),
("==1.4.2", Some((Eq, [1L, 4L, 2L], 3))),
("1.4", Some((Prefix, [1L, 4L, 0L], 2))),
("==1.4.*", Some((Prefix, [1L, 4L, 0L], 2))),
("1.*", Some((Prefix, [1L, 0L, 0L], 1))),
("!=1.4.2", Some((Ne, [1L, 4L, 2L], 3))),
("!=1.2.*", Some((NotPrefix, [1L, 2L, 0L], 2))),
("", None),
("<=", None),
(">=abc", None),
("^^1.0", None),
("~>1.0", None),
("1.2.3.*", None),
("1.2.3.4", None),
]
for row in table {
let (text, want) = row
let got = match parse_clause(text) {
Some((op, b)) => Some((op, b.nums, b.parts))
None => None
}
assert_eq(got, want, msg=text)
}
}
///|
test "constraints join clauses and gate prereleases" {
let v = parse_ver("1.4.2").unwrap()
assert_true(satisfies(v, "^1.2.0"))
assert_true(!(satisfies(v, "^2.0.0")))
assert_true(satisfies(v, "~1.4.0"))
assert_true(!(satisfies(v, "~1.3.0")))
assert_true(satisfies(v, ">=1.0"))
assert_true(satisfies(v, "1"))
assert_true(satisfies(v, "1.4"))
assert_true(!(satisfies(v, "1.5")))
let rc = parse_ver("1.2.0-rc1").unwrap()
assert_true(satisfies(v, ">=1.0, !=1.4.1, <2.0"))
assert_false(satisfies(v, ">=1.0, !=1.4.2, <2.0"))
assert_true(satisfies(v, "*"))
assert_true(!(satisfies(parse_ver("0.3.1").unwrap(), "^0.2.0")))
}
assert_false(satisfies(rc, "*"))
assert_true(satisfies(rc, ">=1.0.0-rc1, <2.0.0"))
assert_false(satisfies(rc, ">=1.0.0, <2.0.0"))
///|
test "pick" {
let tags = ["1.0.0", "1.2.0", "2.0.0", "2.1.0-rc1", "latest"]
assert_eq(pick_tag(tags, ["*"]), Some("2.0.0"))
assert_eq(pick_tag(tags, ["^1.0.0"]), Some("1.2.0"))
assert_eq(pick_tag(tags, ["^1.0.0", "~1.0.0"]), Some("1.0.0"))
assert_eq(pick_tag(tags, ["latest"]), Some("2.0.0"))
assert_eq(pick_tag(tags, ["^3"]), None)
assert_eq(sorted_versions(tags), ["2.1.0-rc1", "2.0.0", "1.2.0", "1.0.0"])
assert_true(satisfies_all("1.4.2", ["^1.0.0", "~1.4.0"]))
assert_false(satisfies_all("1.4.2", ["^1.0.0", "~1.3.0"]))
assert_true(satisfies_all("edge", ["edge", "=edge", "==edge", "*"]))
assert_false(satisfies_all("edge", [">=1.0"]))
assert_true(valid_constraint(">=1.2.0, <2.0.0"))
assert_true(valid_constraint("edge"))
assert_false(valid_constraint(">=1,"))
assert_false(valid_constraint("1.2.3.4"))
}
+226
View File
@@ -0,0 +1,226 @@
// Pure MoonBit streaming SHA-256 (FIPS 180-4).
///|
let sha256_k : FixedArray[UInt32] = [
0x428a2f98U, 0x71374491U, 0xb5c0fbcfU, 0xe9b5dba5U, 0x3956c25bU, 0x59f111f1U,
0x923f82a4U, 0xab1c5ed5U, 0xd807aa98U, 0x12835b01U, 0x243185beU, 0x550c7dc3U,
0x72be5d74U, 0x80deb1feU, 0x9bdc06a7U, 0xc19bf174U, 0xe49b69c1U, 0xefbe4786U,
0x0fc19dc6U, 0x240ca1ccU, 0x2de92c6fU, 0x4a7484aaU, 0x5cb0a9dcU, 0x76f988daU,
0x983e5152U, 0xa831c66dU, 0xb00327c8U, 0xbf597fc7U, 0xc6e00bf3U, 0xd5a79147U,
0x06ca6351U, 0x14292967U, 0x27b70a85U, 0x2e1b2138U, 0x4d2c6dfcU, 0x53380d13U,
0x650a7354U, 0x766a0abbU, 0x81c2c92eU, 0x92722c85U, 0xa2bfe8a1U, 0xa81a664bU,
0xc24b8b70U, 0xc76c51a3U, 0xd192e819U, 0xd6990624U, 0xf40e3585U, 0x106aa070U,
0x19a4c116U, 0x1e376c08U, 0x2748774cU, 0x34b0bcb5U, 0x391c0cb3U, 0x4ed8aa4aU,
0x5b9cca4fU, 0x682e6ff3U, 0x748f82eeU, 0x78a5636fU, 0x84c87814U, 0x8cc70208U,
0x90befffaU, 0xa4506cebU, 0xbef9a3f7U, 0xc67178f2U,
]
///|
struct Sha256 {
state : FixedArray[UInt32]
block : FixedArray[Byte]
mut buf_len : Int32
mut total_len : UInt64
}
///|
fn rotr(x : UInt32, n : Int32) -> UInt32 {
(x >> n) | (x << (32 - n))
}
///|
fn Sha256::new() -> Sha256 {
{
state: [
0x6a09e667U, 0xbb67ae85U, 0x3c6ef372U, 0xa54ff53aU, 0x510e527fU, 0x9b05688cU,
0x1f83d9abU, 0x5be0cd19U,
],
block: FixedArray::make(64, b'\x00'),
buf_len: 0,
total_len: 0UL,
}
}
///|
fn Sha256::compress(self : Sha256) -> Unit {
let w = FixedArray::make(64, 0U)
for i = 0; i < 16; i = i + 1 {
let j = i * 4
w[i] = (self.block[j].to_uint() << 24) |
(self.block[j + 1].to_uint() << 16) |
(self.block[j + 2].to_uint() << 8) |
self.block[j + 3].to_uint()
}
for i = 16; i < 64; i = i + 1 {
let x = w[i - 15]
let y = w[i - 2]
let s0 = rotr(x, 7) ^ rotr(x, 18) ^ (x >> 3)
let s1 = rotr(y, 17) ^ rotr(y, 19) ^ (y >> 10)
w[i] = w[i - 16] + s0 + w[i - 7] + s1
}
let mut a = self.state[0]
let mut b = self.state[1]
let mut c = self.state[2]
let mut d = self.state[3]
let mut e = self.state[4]
let mut f = self.state[5]
let mut g = self.state[6]
let mut h = self.state[7]
for i = 0; i < 64; i = i + 1 {
let s1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)
let ch = (e & f) ^ ((e ^ 0xFFFFFFFFU) & g)
let temp1 = h + s1 + ch + sha256_k[i] + w[i]
let s0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)
let maj = (a & b) ^ (a & c) ^ (b & c)
let temp2 = s0 + maj
h = g
g = f
f = e
e = d + temp1
d = c
c = b
b = a
a = temp1 + temp2
}
self.state[0] = self.state[0] + a
self.state[1] = self.state[1] + b
self.state[2] = self.state[2] + c
self.state[3] = self.state[3] + d
self.state[4] = self.state[4] + e
self.state[5] = self.state[5] + f
self.state[6] = self.state[6] + g
self.state[7] = self.state[7] + h
}
///|
fn Sha256::push_byte(self : Sha256, byte : Byte) -> Unit {
self.block[self.buf_len] = byte
self.buf_len = self.buf_len + 1
self.total_len = self.total_len + 1UL
if self.buf_len == 64 {
self.compress()
self.buf_len = 0
}
}
///|
fn Sha256::update_bytes(self : Sha256, data : Bytes) -> Unit {
for i = 0; i < data.length(); i = i + 1 {
self.push_byte(data[i])
}
}
///|
fn Sha256::update_fixed(
self : Sha256,
data : FixedArray[Byte],
len : Int32,
) -> Unit {
for i = 0; i < len; i = i + 1 {
self.push_byte(data[i])
}
}
///|
fn Sha256::finish_hex(self : Sha256) -> String {
let bit_len = self.total_len * 8UL
self.block[self.buf_len] = b'\x80'
self.buf_len = self.buf_len + 1
if self.buf_len > 56 {
while self.buf_len < 64 {
self.block[self.buf_len] = b'\x00'
self.buf_len = self.buf_len + 1
}
self.compress()
self.buf_len = 0
}
while self.buf_len < 56 {
self.block[self.buf_len] = b'\x00'
self.buf_len = self.buf_len + 1
}
let len_bytes = bit_len.to_be_bytes()
for i = 0; i < 8; i = i + 1 {
self.block[56 + i] = len_bytes[i]
}
self.compress()
self.buf_len = 0
let digest = FixedArray::make(32, b'\x00')
for i = 0; i < 8; i = i + 1 {
let w = self.state[i]
let j = i * 4
digest[j] = (w >> 24).to_byte()
digest[j + 1] = (w >> 16).to_byte()
digest[j + 2] = (w >> 8).to_byte()
digest[j + 3] = w.to_byte()
}
@hex.encode(Bytes::makei(32, fn(i) { digest[i] })[:])
}
///|
fn sha256_digest(data : Bytes) -> String {
let h = Sha256::new()
h.update_bytes(data)
"sha256:" + h.finish_hex()
}
///|
async fn sha256_file(path : String) -> (String, Int64) raise OrbitError {
let file = @fs.open(path, mode=ReadOnly) catch {
e => raise OrbitError("cannot read \{path}: \{e}")
}
defer file.close()
let h = Sha256::new()
let buf = FixedArray::make(32768, b'\x00')
let mut total = 0L
for ;; {
let n = file.read(buf) catch {
e => raise OrbitError("cannot read \{path}: \{e}")
}
if n == 0 {
break
}
h.update_fixed(buf, n)
total = total + n.to_int64()
}
("sha256:" + h.finish_hex(), total)
}
///|
test "sha256 FIPS 180-4 vectors" {
assert_eq(
sha256_digest(b""),
"sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
)
assert_eq(
sha256_digest(b"abc"),
"sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
)
let msg56 = b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"
assert_eq(
sha256_digest(msg56),
"sha256:248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1",
)
}
///|
test "sha256 chunked updates match single-shot across block boundaries" {
let payload = FixedArray::make(135, b'\x00')
for i = 0; i < payload.length(); i = i + 1 {
payload[i] = ((i * 31 + 7) & 0xFF).to_byte()
}
let full = Bytes::makei(payload.length(), fn(i) { payload[i] })
let expected = sha256_digest(full)
let h = Sha256::new()
let mut offset = 0
let chunk_sizes = [1, 7, 47, 1, 8, 64, 7]
for sz in chunk_sizes {
let part = FixedArray::make(sz, b'\x00')
for i = 0; i < sz; i = i + 1 {
part[i] = payload[offset + i]
}
h.update_fixed(part, sz)
offset = offset + sz
}
assert_eq(offset, payload.length())
assert_eq("sha256:" + h.finish_hex(), expected)
}
+1608
View File
File diff suppressed because it is too large. Load diff
+25
View File
@@ -3,6 +3,8 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <termios.h>
#include "moonbit.h"
static char *to_cstr(moonbit_bytes_t b) {
@@ -49,3 +51,26 @@ void orbit_print_err(moonbit_bytes_t msg) {
fflush(stderr);
free(m);
}
moonbit_bytes_t orbit_utc_now(void) {
time_t t = time(NULL);
struct tm tm_utc;
if (!gmtime_r(&t, &tm_utc)) {
return from_buf("1970-01-01T00:00:00Z", 20);
}
char buf[32];
size_t n = strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%SZ", &tm_utc);
return from_buf(buf, n);
}
int32_t orbit_set_echo(int32_t enable) {
if (!isatty(0)) return -1;
struct termios t;
if (tcgetattr(0, &t) != 0) return -1;
if (enable) {
t.c_lflag |= (tcflag_t)ECHO;
} else {
t.c_lflag &= ~(tcflag_t)ECHO;
}
return tcsetattr(0, TCSANOW, &t);
}
+83 -54
View File
@@ -23,6 +23,12 @@ extern "C" fn c_print_err(msg : Bytes) -> Unit = "orbit_print_err"
#borrow(target, linkpath)
extern "C" fn c_symlink(target : Bytes, linkpath : Bytes) -> Int32 = "orbit_symlink"
///|
extern "C" fn c_utc_now() -> Bytes = "orbit_utc_now"
///|
extern "C" fn c_set_echo(enable : Int32) -> Int32 = "orbit_set_echo"
// ---------------------------------------------------------------- UTF-8
///|
@@ -209,19 +215,6 @@ fn trim(s : String) -> String {
slice(a, start, end)
}
///|
/// Non-empty, trimmed lines.
fn lines(s : String) -> Array[String] {
let out : Array[String] = []
for l in split_on(s, '\n') {
let t = trim(l)
if t != "" {
out.push(t)
}
}
out
}
///|
fn join(xs : Array[String], sep : String) -> String {
let sb = StringBuilder()
@@ -287,47 +280,6 @@ async fn spin(label : String) -> Unit noraise {
}
}
///|
/// Return stdout; stderr goes to the terminal unless captured. A label shows a
/// braille spinner on a terminal while the command runs. The spinner is a child
/// task that is cancelled as soon as the command finishes, so nothing keeps the
/// group alive.
async fn capture(cmd : String, progress~ : String = "") -> String raise OrbitError {
let is_tty = c_isatty(2) != 0 && getenv("TERM") != "dumb"
let spinning = is_tty && progress != ""
let res : Result[String, Error] = try {
let out = @async.with_task_group(group => {
let spinner = if spinning {
Some(group.spawn(() => {
ignore(@async.handle_cancellation(() => spin(progress)))
}))
} else {
None
}
let (code, stdout, _) = @process.collect_output("sh", ["-c", cmd])
match spinner {
Some(task) => task.cancel()
None => ()
}
if spinning {
c_print_err(utf8_encode("\r\u001B[2K"))
}
if code != 0 {
raise OrbitError("command failed (exit \{code}): \{cmd}")
}
stdout.text()
})
Ok(out)
} catch {
e => Err(e)
}
match res {
Ok(s) => s
Err(OrbitError(msg)) => raise OrbitError(msg)
Err(e) => raise OrbitError(e.to_string())
}
}
///|
async fn exists(path : String) -> Bool noraise {
try {
@@ -364,6 +316,83 @@ fn getenv(name : String) -> String {
utf8_decode(c_getenv(utf8_encode(name)))
}
///|
fn utc_now() -> String {
utf8_decode(c_utc_now())
}
///|
async fn[T] with_spinner(
label : String,
f : async () -> T,
) -> T raise OrbitError {
let is_tty = c_isatty(2) != 0 && getenv("TERM") != "dumb"
if !is_tty || label == "" {
try f() catch {
OrbitError(msg) => raise OrbitError(msg)
e => raise OrbitError(e.to_string())
}
} else {
let res : Result[T, Error] = try {
let out = @async.with_task_group(group => {
let spinner = group.spawn(() => {
ignore(@async.handle_cancellation(() => spin(label)))
})
defer {
spinner.cancel()
c_print_err(utf8_encode("\r\u001B[2K"))
}
f()
})
Ok(out)
} catch {
e => Err(e)
}
match res {
Ok(v) => v
Err(OrbitError(msg)) => raise OrbitError(msg)
Err(e) => raise OrbitError(e.to_string())
}
}
}
///|
async fn write_secret_atomic(
path : String,
text : String,
) -> Unit raise OrbitError {
let tmp = path + ".tmp"
try {
@fs.write_file(tmp, text, create_mode=CreateOrTruncate, permission=0o600)
@fs.chmod(tmp, 0o600)
@fs.rename(tmp, path)
} catch {
e => raise OrbitError("cannot write " + path + ": " + e.to_string())
}
}
///|
async fn run_with_stdin(
cmd : String,
args : Array[String],
stdin_text : String,
) -> (Int32, String) raise OrbitError {
try {
@async.with_task_group(group => {
let (stdin, writer) = @process.write_to_process()
let runner = group.spawn(() => @process.collect_output(cmd, args, stdin~))
group.spawn_bg(allow_failure=true, () => {
defer writer.close()
writer.write(utf8_encode(stdin_text))
})
let (code, stdout, _) = runner.wait()
(code, stdout.text())
})
} catch {
e => raise OrbitError(e.to_string())
}
}
///|
/// Command-line arguments without the program name (Linux: /proc/self/cmdline).
async fn cli_args() -> Array[String] noraise {