Compare commits

...

47 Commits

Author SHA1 Message Date
665164464d chore: add dependencies 2023-03-19 01:09:46 +01:00
7e6853ed63 feat: with base 2023-03-19 01:03:56 +01:00
0f816b5e29 chore(WIP): working on fixing macos cross compile 2023-03-19 01:03:56 +01:00
46208d5681 fix: setup with colima instead 2023-03-19 01:03:56 +01:00
1570e01ff9 fix: longer docker timemout 2023-03-19 01:03:56 +01:00
7d3fc5e3e2 fix: setup docker 2023-03-19 01:03:56 +01:00
c56370182f fix: with target 2023-03-19 01:03:56 +01:00
6858ee74cd fix: with proper '' 2023-03-19 01:03:55 +01:00
84bcf10809 fix: permissions for macos 2023-03-19 01:03:55 +01:00
59b42fc273 feat: fix macos 2023-03-19 01:03:55 +01:00
1e10149522 feat: reorder tasks 2023-03-19 01:03:55 +01:00
cb66d99088 feat: with docker buildx 2023-03-19 01:03:55 +01:00
2d171249d9 feat: test other way around 2023-03-19 01:03:55 +01:00
8ad390f813 fix: with proper disable of windows 2023-03-19 01:03:55 +01:00
6dd6a47131 fix: without windows support for now
'see #47'
2023-03-19 01:03:55 +01:00
e194a01893 fix: native-tls-vendored 2023-03-19 01:03:54 +01:00
9599e6f484 feat: with multi platform ci 2023-03-19 01:03:54 +01:00
11d20935c6 feat: extract client (#48)
This extracts the client (strategy pattern), this is so that it is will be possible to test the actual querier, without hitting / requiring the dagger-engine running.
2023-03-19 00:01:24 +00:00
384294b390 feat: rename projects to point to github/kjuulh/dagger-sdk 2023-03-18 15:33:14 +01:00
79d931e908 feat: with loggers 2023-03-14 23:21:14 +01:00
756a080533 fix: stable input fields and args 2023-03-14 22:21:35 +01:00
ea27fa8168 chore: fmt 2023-03-14 22:21:35 +01:00
71f98d0293 fix: stable enum entries 2023-03-14 22:21:35 +01:00
6ef4bdf587 refactor: add basic cargo make gen command 2023-03-14 22:01:20 +01:00
b55bcc159f refactor: move dagger-rs and adopt workspace.deps 2023-03-14 22:01:20 +01:00
76fab3f466 Release dagger-sdk v0.2.19 2023-03-14 15:00:47 +01:00
6629d2db4f chore: fix release version 2023-03-14 15:00:43 +01:00
8fd6bb983e fix: serialization of enum args for graphql (#34) 2023-03-14 13:56:49 +00:00
1b31331765 feat: update readme 2023-03-13 23:57:32 +01:00
a8e6dde615 Release dagger-sdk v0.2.17 2023-03-13 21:09:18 +01:00
1bfd084cd2 fix: make sure tests have a command to execute 2023-03-13 21:07:14 +01:00
5593fce2e1 fix: remove unused imports 2023-03-13 21:07:14 +01:00
2cc0231c5f refactor: remove export and instead use exitcode 2023-03-13 21:07:14 +01:00
9ba01396cb refactor: move issues to actual tests and refactor 2023-03-13 21:07:14 +01:00
c025d17424 fix: add support for String as well 2023-03-13 21:07:14 +01:00
e9e35edb1c refactor: move issues to another folder 2023-03-13 21:07:14 +01:00
d7317e5cf3 fix: add public tuple field and into func 2023-03-13 21:07:14 +01:00
f67928155f replication(issue-30): initial issue 2023-03-13 21:07:14 +01:00
Renovate Bot
44fa0240f8 fix(deps): update rust crate futures to 0.3.27 2023-03-11 18:21:37 +01:00
62de24153a docs: add basic contributing 2023-03-10 23:49:26 +01:00
9513bb5653 docs: add architecture 2023-03-10 23:46:12 +01:00
6b43d5bc36 fix: proper readme 2023-03-10 23:44:36 +01:00
f390eac29f Release dagger-core v0.2.8, dagger-sdk v0.2.16 2023-03-10 23:40:02 +01:00
e642778d90 chore: fix tasks 2023-03-10 23:39:23 +01:00
7133bfae95 feat: with dagger-engine v.0.4.0 2023-03-10 23:27:15 +01:00
41b20b6268 feat: bump version 2023-03-10 23:27:15 +01:00
13b7805e7e docs(sdk): fix missing await in connect 2023-02-25 02:42:34 +01:00
69 changed files with 32102 additions and 566 deletions

121
.github/workflows/ci-multiplatform.yml vendored Normal file
View File

@@ -0,0 +1,121 @@
name: ci-multi-platform
on:
pull_request:
push:
branches:
- main
schedule:
- cron: '00 01 * * *'
jobs:
test:
name: test
env:
# For some builds, we use cross to test on 32-bit and big-endian
# systems.
CARGO: cargo
# When CARGO is set to CROSS, this is set to `--target matrix.target`.
TARGET_FLAGS: ""
# When CARGO is set to CROSS, TARGET_DIR includes matrix.target.
TARGET_DIR: ./target
# Emit backtraces on panics.
RUST_BACKTRACE: 1
runs-on: ${{ matrix.os }}
strategy:
matrix:
build:
- pinned
- stable
- beta
- nightly
#- nightly-musl
#- nightly-32
#- nightly-mips
#- nightly-arm
#- macos
# - win-msvc
#- win-gnu
include:
- build: pinned
os: ubuntu-22.04
rust: 1.65.0
- build: stable
os: ubuntu-22.04
rust: stable
- build: beta
os: ubuntu-22.04
rust: beta
- build: nightly
os: ubuntu-22.04
rust: nightly
#- build: nightly-musl
# os: ubuntu-22.04
# rust: nightly
# target: x86_64-unknown-linux-musl
#- build: nightly-32
# os: ubuntu-22.04
# rust: nightly
# target: i686-unknown-linux-gnu
#- build: nightly-mips
# os: ubuntu-22.04
# rust: nightly
# target: mips64-unknown-linux-gnuabi64
#- build: nightly-arm
# os: ubuntu-22.04
# rust: nightly
# target: arm-unknown-linux-gnueabihf
#- build: macos
# os: macos-12
# rust: nightly
#- build: win-msvc
# os: windows-2022
# rust: nightly
#- build: win-gnu
# os: windows-2022
# rust: nightly-x86_64-gnu
steps:
- name: Checkout repository
uses: actions/checkout@v3
#- name: Install packages (Ubuntu)
# if: matrix.os == 'ubuntu-22.04'
# run: |
# ci/ubuntu-install-packages
- name: Install packages (macOS)
if: matrix.os == 'macos-12'
run: |
ci/scripts/macos-install-packages
- name: Set up QEMU
uses: docker/setup-qemu-action@v2
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2.0.0
- uses: actions-rs/toolchain@v1
if: matrix.target == ''
with:
toolchain: ${{ matrix.rust }}
- uses: actions-rs/toolchain@v1
if: matrix.target != ''
with:
toolchain: ${{ matrix.rust }}
target: ${{ matrix.target }}
use-cross: true
- uses: actions-rs/cargo@v1
if: matrix.target != ''
with:
use-cross: true
command: build
args: --workspace --verbose --target ${{ matrix.target }}
- uses: actions-rs/cargo@v1
if: matrix.target == ''
with:
command: build
args: --workspace --verbose
- uses: actions-rs/cargo@v1
if: matrix.target != ''
with:
use-cross: true
command: test
args: --all --verbose --target ${{ matrix.target }}
- uses: actions-rs/cargo@v1
if: matrix.target == ''
with:
command: test
args: --all --verbose

12
ARCHITECTURE.md Normal file
View File

@@ -0,0 +1,12 @@
# Architecture
- `.` Root project mainly used for generating the CLI, which in turn is used to
bootstrap the code generation from `dagger`
- `crates/dagger-core` Contains all base types used during actual usage. This is
where the primary logic lives in which the user interacts (\*disclaimer: most
stuff haven't moved in here yet.)
- `crates/dagger-sdk` Contains the actual sdk in which the user interacts,
`dagger-core` is reexported through this API as well.
- `crates/dagger-codegen` This is the bulk of the work, it takes the input
graphql and spits out the API in which the user interacts, this is heavily
inspired by other `dagger-sdk's`. It primarily turns graphql into rust code.

11
CONTRIBUTING.md Normal file
View File

@@ -0,0 +1,11 @@
# Contributing
The sdk is still quite young, so feel free to either:
- Refactor
- Document
- Improve the code
Feel free to ping me on discord @Hermansen#4325, or just create an issue if
there is a missing feature, or you'd like some mentorship in getting into the
code

542
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,42 +1,25 @@
[package]
name = "dagger-rs"
version = "0.2.10"
edition = "2021"
readme = "README.md"
license-file = "LICENSE.MIT"
description = "A dagger sdk for rust, written in rust"
repository = "https://github.com/kjuulh/dagger-rs"
publish = true
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[workspace]
members = [
"crates/dagger-codegen",
"crates/dagger-sdk",
"crates/dagger-core",
"crates/dagger-bootstrap",
"ci",
]
[dependencies]
[workspace.dependencies]
dagger-codegen = { path = "crates/dagger-codegen", version = "^0.2.5" }
dagger-core = { path = "crates/dagger-core", version = "^0.2.7" }
dagger-core = { path = "crates/dagger-core", version = "^0.2.8" }
dagger-bootstrap = { path = "crates/dagger-bootstrap", version = "^0.2.10" }
dagger-sdk = { path = "crates/dagger-sdk", version = "^0.2.19" }
clap = "4.1.6"
dirs = "4.0.0"
eyre = "0.6.8"
flate2 = { version = "1.0.25", features = ["zlib"] }
genco = "0.17.3"
graphql-introspection-query = "0.2.0"
graphql_client = { version = "0.12.0", features = ["reqwest"] }
hex = "0.4.3"
hex-literal = "0.3.4"
platform-info = "1.0.2"
reqwest = { version = "0.11.14", features = ["stream", "deflate"] }
color-eyre = "0.6.2"
serde = { version = "1.0.152", features = ["derive"] }
serde_json = "1.0.93"
sha2 = "0.10.6"
tar = "0.4.38"
tempfile = "3.3.0"
color-eyre = "0.6.2"
tokio = { version = "1.25.0", features = ["full"] }
tracing = { version = "0.1.37", features = ["log"] }
tracing-subscriber = { version = "0.3.16", features = [
"tracing-log",
"tracing",
] }

60
Makefile.toml Normal file
View File

@@ -0,0 +1,60 @@
[tasks.codegen]
command = "cargo"
args = ["run", "-p", "ci", "--", "codegen"]
workspace = false
[tasks.local_codegen]
command = "cargo"
args = [
"run",
"-p",
"dagger-bootstrap",
"--",
"generate",
"--output",
"crates/dagger-sdk/src/gen.rs",
]
workspace = false
[tasks.build]
command = "cargo"
args = ["run", "-p", "ci", "--", "ci"]
dependencies = ["codegen"]
workspace = false
[tasks.fmt]
command = "cargo"
args = ["fmt", "--all"]
workspace = false
[tasks.fix]
command = "cargo"
args = ["fix", "--workspace", "--allow-dirty"]
dependencies = ["fmt"]
workspace = false
[tasks.gen]
dependencies = ["local_codegen", "fmt", "fix"]
workspace = false
[tasks.release_crate]
command = "cargo"
args = [
"smart-release",
"--allow-fully-generated-changelogs",
"--update-crates-index",
"dagger-sdk",
]
dependencies = ["codegen", "fix"]
workspace = false
[tasks.release_crate_commit]
command = "cargo"
args = [
"smart-release",
"-e",
"--allow-fully-generated-changelogs",
"--update-crates-index",
"dagger-sdk",
]
workspace = false

View File

@@ -1,40 +1,55 @@
# dagger-rs
# dagger-sdk
A dagger sdk written in rust for rust.
# Usage
## Examples
See [dagger-sdk](./crates/dagger-sdk/README.md)
See [examples](./crates/dagger-sdk/examples/)
### Status
Run them like so
- [x] dagger cli downloader
- [x] dagger network session
- [x] graphql rust codegen (User API)
- [x] Scalars
- [x] Enums
- [x] Input
- [x] Objects
- [x] Implement context and querier
- [x] Marshaller
- [x] Querier
- [x] Context
- [x] Deserializer for nested response (bind)
- [x] Add codegen to hook into querier
- [x] fix build / release cycle
- [x] general api stabilisation
- [x] document usage
- [x] make async variant
```bash
cargo run --example first-pipeline
```
## Architecture
The examples match the folder name in each directory in examples
- `.` Root project mainly used for generating the CLI, which in turn is used to
bootstrap the code generation from `dagger`
- `crates/dagger-core` Contains all base types used during actual usage. This is
where the primary logic lives in which the user interacts (\*disclaimer: most
stuff haven't moved in here yet.)
- `crates/dagger-sdk` Contains the actual sdk in which the user interacts,
`dagger-core` is reexported through this API as well.
- `crates/dagger-codegen` This is the bulk of the work, it takes the input
graphql and spits out the API in which the user interacts, this is heavily
inspired by other `dagger-sdk's`. It primarily turns graphql into rust code.
## Install
Simply install like:
```bash
cargo add dagger-sdk
```
### Usage
```rust
#[tokio::main]
async fn main() -> eyre::Result<()> {
let client = dagger_sdk::connect().await?;
let version = client
.container()
.from("golang:1.19")
.with_exec(vec!["go", "version"])
.stdout()
.await?;
println!("Hello from Dagger and {}", version.trim());
Ok(())
}
```
And run it like a normal application:
```bash
cargo run
```
### Contributing
See [CONTRIBUTING](./CONTRIBUTING.md)
or just cargo make codegen

View File

@@ -8,6 +8,6 @@ edition = "2021"
[dependencies]
clap = "4.1.6"
color-eyre = "0.6.2"
dagger-sdk = { path = "../crates/dagger-sdk/", version = "^0.2.15" }
dagger-sdk = { path = "../crates/dagger-sdk/", version = "^0.2.19" }
eyre = "0.6.8"
tokio = { version = "1.25.0", features = ["full"] }

View File

@@ -0,0 +1,4 @@
#!/bin/sh
brew install docker
colima start

View File

@@ -1,5 +1,6 @@
use std::sync::Arc;
use clap::ArgMatches;
use dagger_sdk::{Container, HostDirectoryOpts, Query};
#[tokio::main]
@@ -10,6 +11,7 @@ async fn main() -> eyre::Result<()> {
.subcommand_required(true)
.subcommand(clap::Command::new("pr"))
.subcommand(clap::Command::new("release"))
.subcommand(clap::Command::new("codegen"))
.get_matches();
let client = dagger_sdk::connect().await?;
@@ -20,6 +22,7 @@ async fn main() -> eyre::Result<()> {
return validate_pr(client, base).await;
}
Some(("release", subm)) => return release(client, subm).await,
Some(("codegen", subm)) => return run_codegen(client, subm).await,
Some(_) => {
panic!("invalid subcommand selected!")
}
@@ -29,6 +32,42 @@ async fn main() -> eyre::Result<()> {
}
}
async fn run_codegen(client: Arc<Query>, _subm: &ArgMatches) -> eyre::Result<()> {
let docker_cli = client
.container()
.from("docker:cli")
.file("/usr/local/bin/docker");
let socket = client.host().unix_socket("/var/run/docker.sock");
let container = get_dependencies(client).await?;
let generated_image = container
.with_exec(vec!["mkdir", "-p", "/mnt/output"])
.with_mounted_file("/usr/bin/docker", docker_cli.id().await?)
.with_unix_socket("/var/run/docker.sock", socket.id().await?)
.with_exec(vec![
"cargo",
"run",
"--",
"generate",
"--output",
"crates/dagger-sdk/gen.rs",
])
.with_exec(vec!["cargo", "fmt", "--all"])
.with_exec(vec!["cargo", "fix", "--workspace", "--allow-dirty"])
.with_exec(vec!["cargo", "fmt", "--all"])
.with_exec(vec!["mv", "crates/dagger-sdk/gen.rs", "/mnt/output/gen.rs"]);
let _ = generated_image.exit_code().await?;
generated_image
.file("/mnt/output/gen.rs")
.export("crates/dagger-sdk/src/gen.rs")
.await?;
Ok(())
}
async fn release(client: Arc<Query>, _subm: &clap::ArgMatches) -> Result<(), color_eyre::Report> {
let src_dir = client.host().directory_opts(
".",
@@ -51,7 +90,7 @@ async fn release(client: Arc<Query>, _subm: &clap::ArgMatches) -> Result<(), col
"--execute",
"--allow-fully-generated-changelogs",
"--no-changelog-preview",
"dagger-rs",
"dagger-sdk",
"dagger-sdk",
]);
let exit = container.exit_code().await?;
@@ -87,14 +126,14 @@ async fn get_dependencies(client: Arc<Query>) -> eyre::Result<Container> {
);
let cache_cargo_index_dir = client.cache_volume("cargo_index");
let cache_cargo_deps = client.cache_volume("cargo_deps");
let _cache_cargo_deps = client.cache_volume("cargo_deps");
let cache_cargo_bin = client.cache_volume("cargo_bin_cache");
let minio_url = "https://github.com/mozilla/sccache/releases/download/v0.3.3/sccache-v0.3.3-x86_64-unknown-linux-musl.tar.gz";
let base_image = client
.container()
.from("rust:latest")
.from("rustlang/rust:nightly")
.with_workdir("app")
.with_exec(vec!["apt-get", "update"])
.with_exec(vec!["apt-get", "install", "--yes", "libpq-dev", "wget"])
@@ -110,7 +149,7 @@ async fn get_dependencies(client: Arc<Query>) -> eyre::Result<Container> {
"/usr/local/bin/sccache",
])
.with_exec(vec!["chmod", "+x", "/usr/local/bin/sccache"])
.with_env_variable("RUSTC_WRAPPER", "/usr/local/bin/sccache")
//.with_env_variable("RUSTC_WRAPPER", "/usr/local/bin/sccache")
.with_env_variable(
"AWS_ACCESS_KEY_ID",
std::env::var("AWS_ACCESS_KEY_ID").unwrap_or("".into()),
@@ -152,8 +191,7 @@ async fn get_dependencies(client: Arc<Query>) -> eyre::Result<Container> {
"--recipe-path",
"recipe.json",
])
.with_mounted_cache("/app/", cache_cargo_deps.id().await?)
.with_mounted_directory("/app/", src_dir.id().await?)
.with_directory("/app/", src_dir.id().await?)
.with_exec(vec!["cargo", "build", "--all", "--release"]);
return Ok(builder_start);

View File

@@ -0,0 +1,39 @@
[package]
name = "dagger-bootstrap"
version = "0.2.10"
edition = "2021"
readme = "README.md"
license-file = "LICENSE.MIT"
description = "A dagger sdk for rust, written in rust"
repository = "https://github.com/kjuulh/dagger-sdk"
publish = true
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
dagger-core = { workspace = true }
dagger-codegen = { workspace = true }
eyre = { workspace = true }
color-eyre = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
tokio = { workspace = true }
reqwest = { version = "0.11.14", features = [
"stream",
"rustls",
"hyper-rustls",
"rustls-tls",
] }
clap = "4.1.6"
dirs = "4.0.0"
graphql_client = { version = "0.12.0", features = [
"reqwest-rustls",
], default_features = false }
hex = "0.4.3"
hex-literal = "0.3.4"
platform-info = "1.0.2"
sha2 = "0.10.6"
tar = "0.4.38"
tempfile = "3.3.0"

View File

@@ -5,17 +5,20 @@ edition = "2021"
readme = "README.md"
license-file = "LICENSE.MIT"
description = "dagger sdk codegen library"
repository = "https://github.com/kjuulh/dagger-rs"
repository = "https://github.com/kjuulh/dagger-sdk"
publish = true
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
convert_case = "0.6.0"
dagger-core = { path = "../dagger-core", version = "^0.2.7" }
dagger-core = { workspace = true }
eyre = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
eyre = "0.6.8"
genco = "0.17.3"
convert_case = "0.6.0"
itertools = "0.10.5"
[dev-dependencies]
pretty_assertions = "1.3.0"
serde = { version = "1.0.152", features = ["derive"] }
serde_json = "1.0.93"

View File

@@ -196,6 +196,22 @@ pub fn type_ref_is_scalar(type_ref: &TypeRef) -> bool {
.unwrap_or(false)
}
pub fn type_ref_is_enum(type_ref: &TypeRef) -> bool {
let mut type_ref = type_ref.clone();
if type_ref
.kind
.pipe(|k| *k == __TypeKind::NON_NULL)
.unwrap_or(false)
{
type_ref = *type_ref.of_type.unwrap().clone();
}
type_ref
.kind
.pipe(|k| *k == __TypeKind::ENUM)
.unwrap_or(false)
}
pub fn type_ref_is_object(type_ref: &TypeRef) -> bool {
let mut type_ref = type_ref.clone();
if type_ref

View File

@@ -3,10 +3,11 @@ use dagger_core::introspection::{FullTypeFields, TypeRef};
use genco::prelude::rust;
use genco::quote;
use genco::tokens::quoted;
use itertools::Itertools;
use crate::functions::{
type_field_has_optional, type_ref_is_list, type_ref_is_list_of_objects, type_ref_is_object,
type_ref_is_optional, type_ref_is_scalar, CommonFunctions, Scalar,
type_field_has_optional, type_ref_is_enum, type_ref_is_list, type_ref_is_list_of_objects,
type_ref_is_object, type_ref_is_optional, type_ref_is_scalar, CommonFunctions, Scalar,
};
use crate::utility::OptionExt;
@@ -133,6 +134,12 @@ fn render_required_args(_funcs: &CommonFunctions, field: &FullTypeFields) -> Opt
}
}
if type_ref_is_enum(&s.input_value.type_) {
return Some(quote! {
query = query.arg_enum($(quoted(name)), $(n));
})
}
if type_ref_is_list(&s.input_value.type_) {
let inner = *s
.input_value
@@ -187,6 +194,14 @@ fn render_optional_args(_funcs: &CommonFunctions, field: &FullTypeFields) -> Opt
let n = format_struct_name(&s.input_value.name);
let name = &s.input_value.name;
if type_ref_is_enum(&s.input_value.type_) {
return Some(quote! {
if let Some($(&n)) = opts.$(&n) {
query = query.arg_enum($(quoted(name)), $(n));
}
});
}
Some(quote! {
if let Some($(&n)) = opts.$(&n) {
query = query.arg($(quoted(name)), $(&n));
@@ -232,7 +247,7 @@ fn render_execution(funcs: &CommonFunctions, field: &FullTypeFields) -> rust::To
return $(output_type) {
proc: self.proc.clone(),
selection: query,
conn: self.conn.clone(),
graphql_client: self.graphql_client.clone(),
}
};
}
@@ -258,15 +273,13 @@ fn render_execution(funcs: &CommonFunctions, field: &FullTypeFields) -> rust::To
return vec![$(output_type) {
proc: self.proc.clone(),
selection: query,
conn: self.conn.clone(),
graphql_client: self.graphql_client.clone(),
}]
};
}
let graphql_client = rust::import("crate::client", "graphql_client");
quote! {
query.execute(&$graphql_client(&self.conn)).await
query.execute(self.graphql_client.clone()).await
}
}
@@ -391,6 +404,7 @@ pub fn format_optional_args(
.map(|t| {
t.into_iter()
.filter(|t| type_ref_is_optional(&t.input_value.type_))
.sorted_by_key(|val| &val.input_value.name)
.collect::<Vec<_>>()
})
.pipe(|t| render_optional_field_args(funcs, t))

View File

@@ -1,6 +1,7 @@
use dagger_core::introspection::FullType;
use genco::prelude::rust;
use genco::quote;
use itertools::Itertools;
fn render_enum_values(values: &FullType) -> Option<rust::Tokens> {
let values = values
@@ -10,6 +11,7 @@ fn render_enum_values(values: &FullType) -> Option<rust::Tokens> {
.map(|values| {
values
.into_iter()
.sorted_by_key(|a| &a.name)
.map(|val| quote! { $(val.name.as_ref()), })
})
.flatten()

View File

@@ -1,6 +1,7 @@
use dagger_core::introspection::{FullType, FullTypeInputFields};
use genco::prelude::rust;
use genco::quote;
use itertools::Itertools;
use crate::functions::CommonFunctions;
use crate::rust::functions::{format_name, format_struct_name};
@@ -20,7 +21,10 @@ pub fn render_input_fields(
funcs: &CommonFunctions,
fields: &[FullTypeInputFields],
) -> Option<rust::Tokens> {
let rendered_fields = fields.iter().map(|f| render_input_field(funcs, f));
let rendered_fields = fields
.iter()
.sorted_by_key(|val| &val.input_value.name)
.map(|f| render_input_field(funcs, f));
if rendered_fields.len() == 0 {
None

View File

@@ -12,15 +12,15 @@ use crate::utility::OptionExt;
pub fn render_object(funcs: &CommonFunctions, t: &FullType) -> eyre::Result<rust::Tokens> {
let selection = rust::import("crate::querybuilder", "Selection");
let child = rust::import("tokio::process", "Child");
let conn = rust::import("dagger_core::connect_params", "ConnectParams");
let graphql_client = rust::import("dagger_core::graphql_client", "DynGraphQLClient");
let arc = rust::import("std::sync", "Arc");
Ok(quote! {
#[derive(Debug, Clone)]
#[derive(Clone)]
pub struct $(t.name.pipe(|s| format_name(s))) {
pub proc: $arc<$child>,
pub selection: $selection,
pub conn: $conn,
pub graphql_client: $graphql_client
}
$(t.fields.pipe(|f| render_optional_args(funcs, f)))

View File

@@ -11,6 +11,18 @@ pub fn render_scalar(t: &FullType) -> eyre::Result<rust::Tokens> {
Ok(quote! {
#[derive($serialize, $deserialize, PartialEq, Debug, Clone)]
pub struct $(t.name.pipe(|n|format_name(n)))(String);
pub struct $(t.name.pipe(|n|format_name(n)))(pub String);
impl Into<$(t.name.pipe(|n| format_name(n)))> for &str {
fn into(self) -> $(t.name.pipe(|n| format_name(n))) {
$(t.name.pipe(|n| format_name(n)))(self.to_string())
}
}
impl Into<$(t.name.pipe(|n| format_name(n)))> for String {
fn into(self) -> $(t.name.pipe(|n| format_name(n))) {
$(t.name.pipe(|n| format_name(n)))(self.clone())
}
}
})
}

View File

@@ -5,6 +5,42 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## v0.2.8 (2023-03-10)
### New Features
- <csr-id-41b20b6268db9d8defe333694e4d3ec019d7c923/> bump version
- <csr-id-5f9b3a19c0ab6988bc335b020052074f3f101305/> set internal warnings as errors
- <csr-id-f9e7af931d94fbedacf74f5da9a2f71b1992324b/> introduce tests again
### Bug Fixes
- <csr-id-ecca036bc644fee93fbcb69bf6da9f29169e473e/> fix builder pattern to actually work with default values
In previous versions the builder pattern required all values to be set.
This has not been fixed, so that default values are allowed.
### Commit Statistics
<csr-read-only-do-not-edit/>
- 4 commits contributed to the release over the course of 13 calendar days.
- 13 days passed between releases.
- 4 commits were understood as [conventional](https://www.conventionalcommits.org).
- 0 issues like '(#ID)' were seen in commit messages
### Commit Details
<csr-read-only-do-not-edit/>
<details><summary>view details</summary>
* **Uncategorized**
- bump version ([`41b20b6`](https://github.com/kjuulh/dagger-rs/commit/41b20b6268db9d8defe333694e4d3ec019d7c923))
- set internal warnings as errors ([`5f9b3a1`](https://github.com/kjuulh/dagger-rs/commit/5f9b3a19c0ab6988bc335b020052074f3f101305))
- introduce tests again ([`f9e7af9`](https://github.com/kjuulh/dagger-rs/commit/f9e7af931d94fbedacf74f5da9a2f71b1992324b))
- fix builder pattern to actually work with default values ([`ecca036`](https://github.com/kjuulh/dagger-rs/commit/ecca036bc644fee93fbcb69bf6da9f29169e473e))
</details>
## v0.2.7 (2023-02-24)
### New Features
@@ -15,7 +51,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
<csr-read-only-do-not-edit/>
- 1 commit contributed to the release.
- 2 commits contributed to the release.
- 4 days passed between releases.
- 1 commit was understood as [conventional](https://www.conventionalcommits.org).
- 0 issues like '(#ID)' were seen in commit messages
@@ -27,6 +63,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
<details><summary>view details</summary>
* **Uncategorized**
- Release dagger-core v0.2.7, dagger-sdk v0.2.15 ([`6a9a560`](https://github.com/kjuulh/dagger-rs/commit/6a9a560cdca097abf23371d44599a2f1b726ae7f))
- update to dagger-v0.3.13 ([`3e8ca8d`](https://github.com/kjuulh/dagger-rs/commit/3e8ca8d86eafdc1f9d5e8b69f14fb60509549e0f))
</details>

View File

@@ -1,29 +1,38 @@
[package]
name = "dagger-core"
version = "0.2.7"
version = "0.2.8"
edition = "2021"
readme = "README.md"
license-file = "LICENSE.MIT"
description = "dagger sdk core library"
repository = "https://github.com/kjuulh/dagger-rs"
repository = "https://github.com/kjuulh/dagger-sdk"
publish = true
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
clap = "4.1.6"
eyre = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
tokio = { workspace = true }
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
base64 = "0.21.0"
gql_client = "1.0.7"
dirs = "4.0.0"
eyre = "0.6.8"
flate2 = { version = "1.0.25", features = ["zlib"] }
genco = "0.17.3"
graphql-introspection-query = "0.2.0"
graphql_client = { version = "0.12.0", features = ["reqwest"] }
flate2 = { version = "1.0.25", features = ["rust_backend"] }
graphql_client = { version = "0.12.0", features = [
"reqwest-rustls",
"graphql_query_derive",
], default-features = false }
hex = "0.4.3"
hex-literal = "0.3.4"
platform-info = "1.0.2"
reqwest = { version = "0.11.14", features = ["stream", "deflate"] }
serde = { version = "1.0.152", features = ["derive"] }
serde_json = "1.0.93"
reqwest = { version = "0.11.14", features = [
"stream",
"rustls-tls",
], default-features = false }
sha2 = "0.10.6"
tar = "0.4.38"
tempfile = "3.3.0"
tokio = { version = "1.25.0", features = ["full"] }
async-trait = "0.1.67"

View File

@@ -35,7 +35,7 @@ impl InnerCliSession {
cli_path: &PathBuf,
) -> eyre::Result<(ConnectParams, tokio::process::Child)> {
let proc = self.start(config, cli_path)?;
let params = self.get_conn(proc).await?;
let params = self.get_conn(proc, config).await?;
Ok(params)
}
@@ -69,6 +69,7 @@ impl InnerCliSession {
async fn get_conn(
&self,
mut proc: tokio::process::Child,
config: &Config,
) -> eyre::Result<(ConnectParams, tokio::process::Child)> {
let stdout = proc
.stdout
@@ -82,6 +83,7 @@ impl InnerCliSession {
let (sender, mut receiver) = tokio::sync::mpsc::channel(1);
let logger = config.logger.as_ref().map(|p| p.clone());
tokio::spawn(async move {
let mut stdout_bufr = tokio::io::BufReader::new(stdout).lines();
while let Ok(Some(line)) = stdout_bufr.next_line().await {
@@ -89,14 +91,19 @@ impl InnerCliSession {
sender.send(conn).await.unwrap();
}
println!("dagger: {}", line);
if let Some(logger) = &logger {
logger.stdout(&line).unwrap();
}
}
});
let logger = config.logger.as_ref().map(|p| p.clone());
tokio::spawn(async move {
let mut stdout_bufr = tokio::io::BufReader::new(stderr).lines();
while let Ok(Some(line)) = stdout_bufr.next_line().await {
println!("dagger: {}", line);
let mut stderr_bufr = tokio::io::BufReader::new(stderr).lines();
while let Ok(Some(line)) = stderr_bufr.next_line().await {
if let Some(logger) = &logger {
logger.stdout(&line).unwrap();
}
}
});

View File

@@ -1,15 +1,18 @@
use std::path::PathBuf;
use crate::logger::DynLogger;
pub struct Config {
pub workdir_path: Option<PathBuf>,
pub config_path: Option<PathBuf>,
pub timeout_ms: u64,
pub execute_timeout_ms: Option<u64>,
pub logger: Option<DynLogger>,
}
impl Default for Config {
fn default() -> Self {
Self::new(None, None, None, None)
Self::new(None, None, None, None, None)
}
}
@@ -19,12 +22,14 @@ impl Config {
config_path: Option<PathBuf>,
timeout_ms: Option<u64>,
execute_timeout_ms: Option<u64>,
logger: Option<DynLogger>,
) -> Self {
Self {
workdir_path,
config_path,
timeout_ms: timeout_ms.unwrap_or(10 * 1000),
execute_timeout_ms,
logger,
}
}
}

View File

@@ -139,9 +139,10 @@ impl Downloader {
if let Ok(entry) = file {
let path = entry.path();
if path != cli_bin_path {
println!(
"deleting client: path: {:?} vs cli_bin_path: {:?}",
path, cli_bin_path
tracing::debug!(
path = path.display().to_string(),
cli_bin_path = cli_bin_path.display().to_string(),
"deleting existing dagger-engine"
);
std::fs::remove_file(path)?;
}

View File

@@ -1,3 +1,4 @@
use crate::DAGGER_ENGINE_VERSION;
use crate::{
cli_session::CliSession, config::Config, connect_params::ConnectParams, downloader::Downloader,
};
@@ -10,7 +11,9 @@ impl Engine {
}
async fn from_cli(&self, cfg: &Config) -> eyre::Result<(ConnectParams, tokio::process::Child)> {
let cli = Downloader::new("0.3.13".into())?.get_cli().await?;
let cli = Downloader::new(DAGGER_ENGINE_VERSION.into())?
.get_cli()
.await?;
let cli_session = CliSession::new();
@@ -21,6 +24,8 @@ impl Engine {
&self,
cfg: &Config,
) -> eyre::Result<(ConnectParams, tokio::process::Child)> {
tracing::info!("starting dagger-engine");
// TODO: Add from existing session as well
self.from_cli(cfg).await
}

View File

@@ -0,0 +1,375 @@
use reqwest::Error;
use reqwest::{Client, Url};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt::{self, Formatter};
use std::str::FromStr;
#[derive(Clone)]
pub struct GraphQLError {
message: String,
json: Option<Vec<GraphQLErrorMessage>>,
}
// https://spec.graphql.org/June2018/#sec-Errors
#[derive(Deserialize, Debug, Clone)]
#[allow(dead_code)]
pub struct GraphQLErrorMessage {
message: String,
locations: Option<Vec<GraphQLErrorLocation>>,
extensions: Option<HashMap<String, String>>,
path: Option<Vec<GraphQLErrorPathParam>>,
}
#[derive(Deserialize, Debug, Clone)]
#[allow(dead_code)]
pub struct GraphQLErrorLocation {
line: u32,
column: u32,
}
#[derive(Deserialize, Debug, Clone)]
#[serde(untagged)]
pub enum GraphQLErrorPathParam {
String(String),
Number(u32),
}
impl GraphQLError {
pub fn with_text(message: impl AsRef<str>) -> Self {
Self {
message: message.as_ref().to_string(),
json: None,
}
}
pub fn with_message_and_json(message: impl AsRef<str>, json: Vec<GraphQLErrorMessage>) -> Self {
Self {
message: message.as_ref().to_string(),
json: Some(json),
}
}
pub fn with_json(json: Vec<GraphQLErrorMessage>) -> Self {
Self::with_message_and_json("Look at json field for more details", json)
}
pub fn message(&self) -> &str {
&self.message
}
pub fn json(&self) -> Option<Vec<GraphQLErrorMessage>> {
self.json.clone()
}
}
fn format(err: &GraphQLError, f: &mut Formatter<'_>) -> fmt::Result {
// Print the main error message
writeln!(f, "\nGQLClient Error: {}", err.message)?;
// Check if query errors have been received
if err.json.is_none() {
return Ok(());
}
let errors = err.json.as_ref();
for err in errors.unwrap() {
writeln!(f, "Message: {}", err.message)?;
}
Ok(())
}
impl fmt::Display for GraphQLError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
format(self, f)
}
}
impl fmt::Debug for GraphQLError {
#[allow(clippy::needless_borrow)]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
format(&self, f)
}
}
impl From<Error> for GraphQLError {
fn from(error: Error) -> Self {
Self {
message: error.to_string(),
json: None,
}
}
}
/// GQL client config
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct ClientConfig {
/// the endpoint about graphql server
pub endpoint: String,
/// gql query timeout, unit: seconds
pub timeout: Option<u64>,
/// additional request header
pub headers: Option<HashMap<String, String>>,
/// request proxy
pub proxy: Option<GQLProxy>,
}
/// proxy type
#[derive(Clone, Debug, Deserialize, Serialize)]
pub enum ProxyType {
Http,
Https,
All,
}
/// proxy auth, basic_auth
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct ProxyAuth {
pub username: String,
pub password: String,
}
/// request proxy
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct GQLProxy {
/// schema, proxy url
pub schema: String,
/// proxy type
pub type_: ProxyType,
/// auth
pub auth: Option<ProxyAuth>,
}
#[cfg(not(target_arch = "wasm32"))]
impl TryFrom<GQLProxy> for reqwest::Proxy {
type Error = GraphQLError;
fn try_from(gql_proxy: GQLProxy) -> Result<Self, Self::Error> {
let proxy = match gql_proxy.type_ {
ProxyType::Http => reqwest::Proxy::http(gql_proxy.schema),
ProxyType::Https => reqwest::Proxy::https(gql_proxy.schema),
ProxyType::All => reqwest::Proxy::all(gql_proxy.schema),
}
.map_err(|e| Self::Error::with_text(format!("{:?}", e)))?;
Ok(proxy)
}
}
#[derive(Clone, Debug)]
pub struct GQLClient {
config: ClientConfig,
}
#[derive(Serialize)]
struct RequestBody<T: Serialize> {
query: String,
variables: T,
}
#[derive(Deserialize, Debug)]
struct GraphQLResponse<T> {
data: Option<T>,
errors: Option<Vec<GraphQLErrorMessage>>,
}
impl GQLClient {
fn client(&self) -> Result<Client, GraphQLError> {
let mut builder = Client::builder().timeout(std::time::Duration::from_secs(
self.config.timeout.unwrap_or(5),
));
if let Some(proxy) = &self.config.proxy {
builder = builder.proxy(proxy.clone().try_into()?);
}
builder
.build()
.map_err(|e| GraphQLError::with_text(format!("Can not create client: {:?}", e)))
}
}
impl GQLClient {
pub fn new(endpoint: impl AsRef<str>) -> Self {
Self {
config: ClientConfig {
endpoint: endpoint.as_ref().to_string(),
timeout: None,
headers: Default::default(),
proxy: None,
},
}
}
pub fn new_with_headers(
endpoint: impl AsRef<str>,
headers: HashMap<impl ToString, impl ToString>,
) -> Self {
let _headers: HashMap<String, String> = headers
.iter()
.map(|(name, value)| (name.to_string(), value.to_string()))
.into_iter()
.collect();
Self {
config: ClientConfig {
endpoint: endpoint.as_ref().to_string(),
timeout: None,
headers: Some(_headers),
proxy: None,
},
}
}
pub fn new_with_config(config: ClientConfig) -> Self {
Self { config }
}
}
impl GQLClient {
pub async fn query<K>(&self, query: &str) -> Result<Option<K>, GraphQLError>
where
K: for<'de> Deserialize<'de>,
{
self.query_with_vars::<K, ()>(query, ()).await
}
pub async fn query_unwrap<K>(&self, query: &str) -> Result<K, GraphQLError>
where
K: for<'de> Deserialize<'de>,
{
self.query_with_vars_unwrap::<K, ()>(query, ()).await
}
pub async fn query_with_vars_unwrap<K, T: Serialize>(
&self,
query: &str,
variables: T,
) -> Result<K, GraphQLError>
where
K: for<'de> Deserialize<'de>,
{
match self.query_with_vars(query, variables).await? {
Some(v) => Ok(v),
None => Err(GraphQLError::with_text(format!(
"No data from graphql server({}) for this query",
self.config.endpoint
))),
}
}
pub async fn query_with_vars<K, T: Serialize>(
&self,
query: &str,
variables: T,
) -> Result<Option<K>, GraphQLError>
where
K: for<'de> Deserialize<'de>,
{
self.query_with_vars_by_endpoint(&self.config.endpoint, query, variables)
.await
}
async fn query_with_vars_by_endpoint<K, T: Serialize>(
&self,
endpoint: impl AsRef<str>,
query: &str,
variables: T,
) -> Result<Option<K>, GraphQLError>
where
K: for<'de> Deserialize<'de>,
{
let mut times = 1;
let mut endpoint = endpoint.as_ref().to_string();
let endpoint_url = Url::from_str(&endpoint).map_err(|e| {
GraphQLError::with_text(format!("Wrong endpoint: {}. {:?}", endpoint, e))
})?;
let schema = endpoint_url.scheme();
let host = endpoint_url
.host()
.ok_or_else(|| GraphQLError::with_text(format!("Wrong endpoint: {}", endpoint)))?;
let client: Client = self.client()?;
let body = RequestBody {
query: query.to_string(),
variables,
};
loop {
if times > 10 {
return Err(GraphQLError::with_text(format!(
"Many redirect location: {}",
endpoint
)));
}
let mut request = client.post(&endpoint).json(&body);
if let Some(headers) = &self.config.headers {
if !headers.is_empty() {
for (name, value) in headers {
request = request.header(name, value);
}
}
}
let raw_response = request.send().await?;
if let Some(location) = raw_response.headers().get(reqwest::header::LOCATION) {
let redirect_url = location.to_str().map_err(|e| {
GraphQLError::with_text(format!(
"Failed to parse response header: Location. {:?}",
e
))
})?;
// if the response location start with http:// or https://
if redirect_url.starts_with("http://") || redirect_url.starts_with("https://") {
times += 1;
endpoint = redirect_url.to_string();
continue;
}
// without schema
endpoint = if redirect_url.starts_with('/') {
format!("{}://{}{}", schema, host, redirect_url)
} else {
format!("{}://{}/{}", schema, host, redirect_url)
};
times += 1;
continue;
}
let status = raw_response.status();
let response_body_text = raw_response
.text()
.await
.map_err(|e| GraphQLError::with_text(format!("Can not get response: {:?}", e)))?;
let json: GraphQLResponse<K> =
serde_json::from_str(&response_body_text).map_err(|e| {
GraphQLError::with_text(format!(
"Failed to parse response: {:?}. The response body is: {}",
e, response_body_text
))
})?;
if !status.is_success() {
return Err(GraphQLError::with_message_and_json(
format!("The response is [{}]", status.as_u16()),
json.errors.unwrap_or_default(),
));
}
// Check if error messages have been received
if json.errors.is_some() {
return Err(GraphQLError::with_json(json.errors.unwrap_or_default()));
}
if json.data.is_none() {
tracing::warn!(
target = "gql-client",
response_text = response_body_text,
"The deserialized data is none, the response",
);
}
return Ok(json.data);
}
}
}

View File

@@ -0,0 +1,52 @@
use std::collections::HashMap;
use std::sync::Arc;
use async_trait::async_trait;
use base64::engine::general_purpose;
use base64::Engine;
use gql_client::ClientConfig;
use crate::connect_params::ConnectParams;
#[async_trait]
pub trait GraphQLClient {
async fn query(&self, query: &str) -> eyre::Result<Option<serde_json::Value>>;
}
pub type DynGraphQLClient = Arc<dyn GraphQLClient + Send + Sync>;
#[derive(Debug)]
pub struct DefaultGraphQLClient {
client: gql_client::Client,
}
impl DefaultGraphQLClient {
pub fn new(conn: &ConnectParams) -> Self {
let token = general_purpose::URL_SAFE.encode(format!("{}:", conn.session_token));
let mut headers = HashMap::new();
headers.insert("Authorization".to_string(), format!("Basic {}", token));
Self {
client: gql_client::Client::new_with_config(ClientConfig {
endpoint: conn.url(),
timeout: Some(1000),
headers: Some(headers),
proxy: None,
}),
}
}
}
#[async_trait]
impl GraphQLClient for DefaultGraphQLClient {
async fn query(&self, query: &str) -> eyre::Result<Option<serde_json::Value>> {
let res: Option<serde_json::Value> = self
.client
.query(&query)
.await
.map_err(|r| eyre::anyhow!(r.to_string()))?;
return Ok(res);
}
}

View File

@@ -1,11 +1,15 @@
#![deny(warnings)]
pub const DAGGER_ENGINE_VERSION: &'static str = "0.4.0";
pub mod cli_session;
pub mod config;
pub mod connect_params;
pub mod downloader;
pub mod engine;
pub mod graphql_client;
pub mod introspection;
pub mod logger;
pub mod schema;
pub mod session;

View File

@@ -0,0 +1,8 @@
use std::sync::Arc;
pub trait Logger {
fn stdout(&self, output: &str) -> eyre::Result<()>;
fn stderr(&self, output: &str) -> eyre::Result<()>;
}
pub type DynLogger = Arc<dyn Logger + Send + Sync>;

View File

@@ -2,7 +2,7 @@ use crate::introspection::IntrospectionResponse;
use crate::{config::Config, engine::Engine, session::Session};
pub async fn get_schema() -> eyre::Result<IntrospectionResponse> {
let cfg = Config::new(None, None, None, None);
let cfg = Config::default();
//TODO: Implement context for proc
let (conn, _proc) = Engine::new().start(&cfg).await?;

View File

@@ -6,6 +6,138 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to
[Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## v0.2.19 (2023-03-14)
### Chore
- <csr-id-6629d2db4fbc7cdba9b2e4a241e4b0a2592cf384/> fix release version
### Bug Fixes
- <csr-id-8fd6bb983ef00b1aa2cf1ba3088028329033c38f/> serialization of enum args for graphql
### Commit Statistics
<csr-read-only-do-not-edit/>
- 2 commits contributed to the release.
- 2 commits were understood as [conventional](https://www.conventionalcommits.org).
- 1 unique issue was worked on: [#34](https://github.com/kjuulh/dagger-rs/issues/34)
### Commit Details
<csr-read-only-do-not-edit/>
<details><summary>view details</summary>
* **[#34](https://github.com/kjuulh/dagger-rs/issues/34)**
- serialization of enum args for graphql ([`8fd6bb9`](https://github.com/kjuulh/dagger-rs/commit/8fd6bb983ef00b1aa2cf1ba3088028329033c38f))
* **Uncategorized**
- fix release version ([`6629d2d`](https://github.com/kjuulh/dagger-rs/commit/6629d2db4fbc7cdba9b2e4a241e4b0a2592cf384))
</details>
## v0.2.17 (2023-03-13)
<csr-id-f67928155f02076cbb41abd4010523879ff3caf1/>
<csr-id-2cc0231c5f29993081f0f7e15e44cac95a7d6086/>
<csr-id-9ba01396cb44ee02cf7a16008e3f0bdae9f78754/>
<csr-id-e9e35edb1cb67eee8cc033212aba3b1888def78f/>
### Bug Fixes
- <csr-id-1bfd084cd28e2b984c61de7f3f9a065cc41be007/> make sure tests have a command to execute
- <csr-id-5593fce2e16e0aa97a2e6843f15d3bb1121048f5/> remove unused imports
- <csr-id-c025d1742482d701946c292dcf104421d3cade8e/> add support for String as well
- <csr-id-d7317e5cf34ee84a7b092357f5fbb15cd2bae2e3/> add public tuple field and into func
- <csr-id-44fa0240f8197f49fdf942b5c3d89079b59195d1/> update rust crate futures to 0.3.27
### Other
- <csr-id-f67928155f02076cbb41abd4010523879ff3caf1/> initial issue
### Refactor
- <csr-id-2cc0231c5f29993081f0f7e15e44cac95a7d6086/> remove export and instead use exitcode
- <csr-id-9ba01396cb44ee02cf7a16008e3f0bdae9f78754/> move issues to actual tests and refactor
- <csr-id-e9e35edb1cb67eee8cc033212aba3b1888def78f/> move issues to another folder
### Commit Statistics
<csr-read-only-do-not-edit/>
- 10 commits contributed to the release over the course of 2 calendar days.
- 2 days passed between releases.
- 9 commits were understood as [conventional](https://www.conventionalcommits.org).
- 0 issues like '(#ID)' were seen in commit messages
### Commit Details
<csr-read-only-do-not-edit/>
<details><summary>view details</summary>
* **Uncategorized**
- Release dagger-sdk v0.2.17 ([`a8e6dde`](https://github.com/kjuulh/dagger-rs/commit/a8e6dde615029d9a94d159ed84b5373121cd201f))
- make sure tests have a command to execute ([`1bfd084`](https://github.com/kjuulh/dagger-rs/commit/1bfd084cd28e2b984c61de7f3f9a065cc41be007))
- remove unused imports ([`5593fce`](https://github.com/kjuulh/dagger-rs/commit/5593fce2e16e0aa97a2e6843f15d3bb1121048f5))
- remove export and instead use exitcode ([`2cc0231`](https://github.com/kjuulh/dagger-rs/commit/2cc0231c5f29993081f0f7e15e44cac95a7d6086))
- move issues to actual tests and refactor ([`9ba0139`](https://github.com/kjuulh/dagger-rs/commit/9ba01396cb44ee02cf7a16008e3f0bdae9f78754))
- add support for String as well ([`c025d17`](https://github.com/kjuulh/dagger-rs/commit/c025d1742482d701946c292dcf104421d3cade8e))
- move issues to another folder ([`e9e35ed`](https://github.com/kjuulh/dagger-rs/commit/e9e35edb1cb67eee8cc033212aba3b1888def78f))
- add public tuple field and into func ([`d7317e5`](https://github.com/kjuulh/dagger-rs/commit/d7317e5cf34ee84a7b092357f5fbb15cd2bae2e3))
- initial issue ([`f679281`](https://github.com/kjuulh/dagger-rs/commit/f67928155f02076cbb41abd4010523879ff3caf1))
- update rust crate futures to 0.3.27 ([`44fa024`](https://github.com/kjuulh/dagger-rs/commit/44fa0240f8197f49fdf942b5c3d89079b59195d1))
</details>
## v0.2.16 (2023-03-10)
<csr-id-e642778d9028726dfb07217814e15ad1dd3b83f2/>
### Chore
- <csr-id-e642778d9028726dfb07217814e15ad1dd3b83f2/> fix tasks
### Documentation
- <csr-id-13b7805e7e6fcf47e0a1318adcc25b4ab773a3c9/> fix missing await in connect
### New Features
- <csr-id-7133bfae9508bc5977548e373c49342a1248d6e4/> with dagger-engine v.0.4.0
- <csr-id-4381af029521c2cbac9325278d261db79a994657/> add tests to sdk
- <csr-id-5f9b3a19c0ab6988bc335b020052074f3f101305/> set internal warnings as errors
### Bug Fixes
- <csr-id-ecca036bc644fee93fbcb69bf6da9f29169e473e/> fix builder pattern to actually work with default values
In previous versions the builder pattern required all values to be set.
This has not been fixed, so that default values are allowed.
### Commit Statistics
<csr-read-only-do-not-edit/>
- 7 commits contributed to the release over the course of 13 calendar days.
- 13 days passed between releases.
- 6 commits were understood as [conventional](https://www.conventionalcommits.org).
- 0 issues like '(#ID)' were seen in commit messages
### Commit Details
<csr-read-only-do-not-edit/>
<details><summary>view details</summary>
* **Uncategorized**
- Release dagger-core v0.2.8, dagger-sdk v0.2.16 ([`f390eac`](https://github.com/kjuulh/dagger-rs/commit/f390eac29f1d041d18d2207a5aa0a8d993aab68c))
- fix tasks ([`e642778`](https://github.com/kjuulh/dagger-rs/commit/e642778d9028726dfb07217814e15ad1dd3b83f2))
- with dagger-engine v.0.4.0 ([`7133bfa`](https://github.com/kjuulh/dagger-rs/commit/7133bfae9508bc5977548e373c49342a1248d6e4))
- fix missing await in connect ([`13b7805`](https://github.com/kjuulh/dagger-rs/commit/13b7805e7e6fcf47e0a1318adcc25b4ab773a3c9))
- add tests to sdk ([`4381af0`](https://github.com/kjuulh/dagger-rs/commit/4381af029521c2cbac9325278d261db79a994657))
- set internal warnings as errors ([`5f9b3a1`](https://github.com/kjuulh/dagger-rs/commit/5f9b3a19c0ab6988bc335b020052074f3f101305))
- fix builder pattern to actually work with default values ([`ecca036`](https://github.com/kjuulh/dagger-rs/commit/ecca036bc644fee93fbcb69bf6da9f29169e473e))
</details>
## v0.2.15 (2023-02-24)
### New Features
@@ -20,7 +152,7 @@ and this project adheres to
<csr-read-only-do-not-edit/>
- 2 commits contributed to the release.
- 3 commits contributed to the release.
- 2 days passed between releases.
- 2 commits were understood as [conventional](https://www.conventionalcommits.org).
- 0 issues like '(#ID)' were seen in commit messages
@@ -32,6 +164,7 @@ and this project adheres to
<details><summary>view details</summary>
* **Uncategorized**
- Release dagger-core v0.2.7, dagger-sdk v0.2.15 ([`6a9a560`](https://github.com/kjuulh/dagger-rs/commit/6a9a560cdca097abf23371d44599a2f1b726ae7f))
- set deserialize on enums as well ([`e578b0e`](https://github.com/kjuulh/dagger-rs/commit/e578b0e371e13bc30ada793b7cd6ebe75ba83a07))
- update to dagger-v0.3.13 ([`3e8ca8d`](https://github.com/kjuulh/dagger-rs/commit/3e8ca8d86eafdc1f9d5e8b69f14fb60509549e0f))
</details>

View File

@@ -1,28 +1,30 @@
[package]
name = "dagger-sdk"
version = "0.2.15"
version = "0.2.19"
edition = "2021"
readme = "README.md"
license-file = "LICENSE.MIT"
description = "A dagger sdk for rust, written in rust"
repository = "https://github.com/kjuulh/dagger-rs"
repository = "https://github.com/kjuulh/dagger-sdk"
publish = true
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
dagger-core = { path = "../dagger-core", version = "^0.2.7" }
dagger-core = { workspace = true }
base64 = "0.21.0"
eyre = "0.6.8"
futures = "0.3.26"
gql_client = "1.0.7"
serde = { version = "1.0.152", features = ["derive"] }
serde_json = "1.0.93"
tokio = { version = "1.25.0", features = ["full"] }
eyre = { workspace = true }
tokio = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
tracing.workspace = true
tracing-subscriber.workspace = true
futures = "0.3.27"
derive_builder = "0.12.0"
[dev-dependencies]
pretty_assertions = "1.3.0"
rand = "0.8.5"
genco = "0.17.3"
tracing-test = "0.2.4"

View File

@@ -27,7 +27,7 @@ cargo add dagger-sdk
```rust
#[tokio::main]
async fn main() -> eyre::Result<()> {
let client = dagger_sdk::connect()?;
let client = dagger_sdk::connect().await?;
let version = client
.container()
@@ -46,9 +46,3 @@ And run it like a normal application:
```bash
cargo run
```
### Disclaimer
You are free to use something else than `tokio`, I haven't tested it with
anything else, but it should work with any other runtime. We don't rely on it
specifically. That might change in the future though.

View File

@@ -35,7 +35,7 @@ async fn main() -> eyre::Result<()> {
.container()
.from("nginx")
.with_directory("/usr/share/nginx/html", build_dir.id().await?)
.publish(format!("ttl.sh/hello-dagger-rs-{}:1h", rng.gen::<u64>()))
.publish(format!("ttl.sh/hello-dagger-sdk-{}:1h", rng.gen::<u64>()))
.await?;
println!("published image to: {}", ref_);

View File

@@ -13,7 +13,7 @@ async fn main() -> eyre::Result<()> {
let ref_ = client
.container()
.build(context_dir.id().await?)
.publish(format!("ttl.sh/hello-dagger-rs-{}:1h", rng.gen::<u64>()))
.publish(format!("ttl.sh/hello-dagger-sdk-{}:1h", rng.gen::<u64>()))
.await?;
println!("published image to: {}", ref_);

View File

@@ -0,0 +1,25 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*
build-*

View File

@@ -0,0 +1,17 @@
# React Build
This is based on the [Getting Started guide for Nodejs](https://docs.dagger.io/sdk/nodejs/783645/get-started#step-5-test-against-multiple-nodejs-versions)
A simple react app is created with `create-react-app` which is built and tested by `build.js` or `build.ts`.
Run:
`npm install`
and then:
`node --loader ts-node/esm ./build.ts`
or
`node ./build.js`

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,48 @@
{
"name": "react-build",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"@types/jest": "^27.5.2",
"@types/node": "^16.18.6",
"@types/react": "^18.0.26",
"@types/react-dom": "^18.0.9",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"ts-node": "^10.9.1",
"typescript": "^4.9.3",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"type": "module",
"devDependencies": {
"@dagger.io/dagger": "^0.3.2"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

View File

@@ -0,0 +1,43 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

View File

@@ -0,0 +1,25 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

View File

@@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:

View File

@@ -0,0 +1,38 @@
.App {
text-align: center;
}
.App-logo {
height: 40vmin;
pointer-events: none;
}
@media (prefers-reduced-motion: no-preference) {
.App-logo {
animation: App-logo-spin infinite 20s linear;
}
}
.App-header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}
.App-link {
color: #61dafb;
}
@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}

View File

@@ -0,0 +1,9 @@
import React from 'react';
import { render, screen } from '@testing-library/react';
import App from './App';
test('renders learn react link', () => {
render(<App />);
const linkElement = screen.getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();
});

View File

@@ -0,0 +1,26 @@
import React from 'react';
import logo from './logo.svg';
import './App.css';
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.tsx</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
export default App;

View File

@@ -0,0 +1,13 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}

View File

@@ -0,0 +1,19 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 841.9 595.3"><g fill="#61DAFB"><path d="M666.3 296.5c0-32.5-40.7-63.3-103.1-82.4 14.4-63.6 8-114.2-20.2-130.4-6.5-3.8-14.1-5.6-22.4-5.6v22.3c4.6 0 8.3.9 11.4 2.6 13.6 7.8 19.5 37.5 14.9 75.7-1.1 9.4-2.9 19.3-5.1 29.4-19.6-4.8-41-8.5-63.5-10.9-13.5-18.5-27.5-35.3-41.6-50 32.6-30.3 63.2-46.9 84-46.9V78c-27.5 0-63.5 19.6-99.9 53.6-36.4-33.8-72.4-53.2-99.9-53.2v22.3c20.7 0 51.4 16.5 84 46.6-14 14.7-28 31.4-41.3 49.9-22.6 2.4-44 6.1-63.6 11-2.3-10-4-19.7-5.2-29-4.7-38.2 1.1-67.9 14.6-75.8 3-1.8 6.9-2.6 11.5-2.6V78.5c-8.4 0-16 1.8-22.6 5.6-28.1 16.2-34.4 66.7-19.9 130.1-62.2 19.2-102.7 49.9-102.7 82.3 0 32.5 40.7 63.3 103.1 82.4-14.4 63.6-8 114.2 20.2 130.4 6.5 3.8 14.1 5.6 22.5 5.6 27.5 0 63.5-19.6 99.9-53.6 36.4 33.8 72.4 53.2 99.9 53.2 8.4 0 16-1.8 22.6-5.6 28.1-16.2 34.4-66.7 19.9-130.1 62-19.1 102.5-49.9 102.5-82.3zm-130.2-66.7c-3.7 12.9-8.3 26.2-13.5 39.5-4.1-8-8.4-16-13.1-24-4.6-8-9.5-15.8-14.4-23.4 14.2 2.1 27.9 4.7 41 7.9zm-45.8 106.5c-7.8 13.5-15.8 26.3-24.1 38.2-14.9 1.3-30 2-45.2 2-15.1 0-30.2-.7-45-1.9-8.3-11.9-16.4-24.6-24.2-38-7.6-13.1-14.5-26.4-20.8-39.8 6.2-13.4 13.2-26.8 20.7-39.9 7.8-13.5 15.8-26.3 24.1-38.2 14.9-1.3 30-2 45.2-2 15.1 0 30.2.7 45 1.9 8.3 11.9 16.4 24.6 24.2 38 7.6 13.1 14.5 26.4 20.8 39.8-6.3 13.4-13.2 26.8-20.7 39.9zm32.3-13c5.4 13.4 10 26.8 13.8 39.8-13.1 3.2-26.9 5.9-41.2 8 4.9-7.7 9.8-15.6 14.4-23.7 4.6-8 8.9-16.1 13-24.1zM421.2 430c-9.3-9.6-18.6-20.3-27.8-32 9 .4 18.2.7 27.5.7 9.4 0 18.7-.2 27.8-.7-9 11.7-18.3 22.4-27.5 32zm-74.4-58.9c-14.2-2.1-27.9-4.7-41-7.9 3.7-12.9 8.3-26.2 13.5-39.5 4.1 8 8.4 16 13.1 24 4.7 8 9.5 15.8 14.4 23.4zM420.7 163c9.3 9.6 18.6 20.3 27.8 32-9-.4-18.2-.7-27.5-.7-9.4 0-18.7.2-27.8.7 9-11.7 18.3-22.4 27.5-32zm-74 58.9c-4.9 7.7-9.8 15.6-14.4 23.7-4.6 8-8.9 16-13 24-5.4-13.4-10-26.8-13.8-39.8 13.1-3.1 26.9-5.8 41.2-7.9zm-90.5 125.2c-35.4-15.1-58.3-34.9-58.3-50.6 0-15.7 22.9-35.6 58.3-50.6 8.6-3.7 18-7 27.7-10.1 5.7 19.6 13.2 40 22.5 60.9-9.2 20.8-16.6 41.1-22.2 60.6-9.9-3.1-19.3-6.5-28-10.2zM310 490c-13.6-7.8-19.5-37.5-14.9-75.7 1.1-9.4 2.9-19.3 5.1-29.4 19.6 4.8 41 8.5 63.5 10.9 13.5 18.5 27.5 35.3 41.6 50-32.6 30.3-63.2 46.9-84 46.9-4.5-.1-8.3-1-11.3-2.7zm237.2-76.2c4.7 38.2-1.1 67.9-14.6 75.8-3 1.8-6.9 2.6-11.5 2.6-20.7 0-51.4-16.5-84-46.6 14-14.7 28-31.4 41.3-49.9 22.6-2.4 44-6.1 63.6-11 2.3 10.1 4.1 19.8 5.2 29.1zm38.5-66.7c-8.6 3.7-18 7-27.7 10.1-5.7-19.6-13.2-40-22.5-60.9 9.2-20.8 16.6-41.1 22.2-60.6 9.9 3.1 19.3 6.5 28.1 10.2 35.4 15.1 58.3 34.9 58.3 50.6-.1 15.7-23 35.6-58.4 50.6zM320.8 78.4z"/><circle cx="420.9" cy="296.5" r="45.7"/><path d="M520.5 78.1z"/></g></svg>

After

Width:  |  Height:  |  Size: 2.6 KiB

View File

@@ -0,0 +1 @@
/// <reference types="react-scripts" />

View File

@@ -0,0 +1,15 @@
import { ReportHandler } from 'web-vitals';
const reportWebVitals = (onPerfEntry?: ReportHandler) => {
if (onPerfEntry && onPerfEntry instanceof Function) {
import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
getCLS(onPerfEntry);
getFID(onPerfEntry);
getFCP(onPerfEntry);
getLCP(onPerfEntry);
getTTFB(onPerfEntry);
});
}
};
export default reportWebVitals;

View File

@@ -0,0 +1,5 @@
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';

View File

@@ -0,0 +1,26 @@
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": [
"src"
]
}

View File

@@ -0,0 +1,49 @@
use std::sync::Arc;
use dagger_sdk::logging::TracingLogger;
use dagger_sdk::HostDirectoryOpts;
#[tokio::main]
async fn main() -> eyre::Result<()> {
dagger_sdk::logging::default_logging()?;
let client = dagger_sdk::connect_opts(dagger_sdk::Config {
workdir_path: None,
config_path: None,
timeout_ms: 1000,
execute_timeout_ms: None,
logger: Some(Arc::new(TracingLogger::default())),
})
.await?;
let host_source_dir = client.host().directory_opts(
"examples/build-the-application/app",
HostDirectoryOpts {
exclude: Some(vec!["node_modules".into(), "ci/".into()]),
include: None,
},
);
let source = client
.container()
.from("node:16")
.with_mounted_directory("/src", host_source_dir.id().await?);
let runner = source
.with_workdir("/src")
.with_exec(vec!["npm", "install"]);
let test = runner.with_exec(vec!["npm", "test", "--", "--watchAll=false"]);
let build_dir = test
.with_exec(vec!["npm", "run", "build"])
.directory("./build");
let _ = build_dir.export("./build");
let entries = build_dir.entries().await;
println!("build dir contents: \n {:?}", entries);
Ok(())
}

View File

@@ -34,7 +34,7 @@ async fn main() -> eyre::Result<()> {
.container()
.from("nginx")
.with_directory("/usr/share/nginx/html", build_dir.id().await?)
.publish(format!("ttl.sh/hello-dagger-rs-{}:1h", rng.gen::<u64>()))
.publish(format!("ttl.sh/hello-dagger-sdk-{}:1h", rng.gen::<u64>()))
.await?;
println!("published image to: {}", ref_);

View File

@@ -39,7 +39,7 @@ async fn main() -> eyre::Result<()> {
"/usr/share/nginx/html",
client.host().directory(output).id().await?,
)
.publish(format!("ttl.sh/hello-dagger-rs-{}:1h", rng.gen::<u64>()))
.publish(format!("ttl.sh/hello-dagger-sdk-{}:1h", rng.gen::<u64>()))
.await?;
println!("published image to: {}", ref_);

View File

@@ -1,43 +1,32 @@
use std::collections::HashMap;
use std::sync::Arc;
use base64::engine::general_purpose;
use base64::Engine;
use dagger_core::graphql_client::DefaultGraphQLClient;
use dagger_core::config::Config;
use dagger_core::connect_params::ConnectParams;
use dagger_core::engine::Engine as DaggerEngine;
use gql_client::ClientConfig;
use crate::gen::Query;
use crate::logging::StdLogger;
use crate::querybuilder::query;
pub type DaggerConn = Arc<Query>;
pub async fn connect() -> eyre::Result<DaggerConn> {
let cfg = Config::default();
let cfg = Config::new(None, None, None, None, Some(Arc::new(StdLogger::default())));
connect_opts(cfg).await
}
pub async fn connect_opts(cfg: Config) -> eyre::Result<DaggerConn> {
let (conn, proc) = DaggerEngine::new().start(&cfg).await?;
Ok(Arc::new(Query {
conn,
proc: Arc::new(proc),
selection: query(),
graphql_client: Arc::new(DefaultGraphQLClient::new(&conn)),
}))
}
pub fn graphql_client(conn: &ConnectParams) -> gql_client::Client {
let token = general_purpose::URL_SAFE.encode(format!("{}:", conn.session_token));
let mut headers = HashMap::new();
headers.insert("Authorization".to_string(), format!("Basic {}", token));
gql_client::Client::new_with_config(ClientConfig {
endpoint: conn.url(),
timeout: Some(1000),
headers: Some(headers),
proxy: None,
})
}
// Conn will automatically close on drop of proc
#[cfg(test)]

File diff suppressed because it is too large Load Diff

View File

@@ -2,7 +2,9 @@
mod client;
mod gen;
pub mod logging;
mod querybuilder;
pub use client::*;
pub use dagger_core::config::Config;
pub use gen::*;

View File

@@ -0,0 +1,81 @@
use dagger_core::logger::{DynLogger, Logger};
use tracing::Level;
pub fn default_logging() -> eyre::Result<()> {
tracing_subscriber::fmt().with_max_level(Level::INFO).init();
Ok(())
}
pub struct StdLogger {}
impl Default for StdLogger {
fn default() -> Self {
Self {}
}
}
impl Logger for StdLogger {
fn stdout(&self, output: &str) -> eyre::Result<()> {
println!("{}", output);
Ok(())
}
fn stderr(&self, output: &str) -> eyre::Result<()> {
eprintln!("{}", output);
Ok(())
}
}
pub struct TracingLogger {}
impl Default for TracingLogger {
fn default() -> Self {
Self {}
}
}
impl Logger for TracingLogger {
fn stdout(&self, output: &str) -> eyre::Result<()> {
tracing::info!(output = output, "dagger-sdk");
Ok(())
}
fn stderr(&self, output: &str) -> eyre::Result<()> {
tracing::warn!(output = output, "dagger-sdk");
Ok(())
}
}
pub struct AggregateLogger {
pub loggers: Vec<DynLogger>,
}
impl Default for AggregateLogger {
fn default() -> Self {
Self {
loggers: Vec::new(),
}
}
}
impl Logger for AggregateLogger {
fn stdout(&self, output: &str) -> eyre::Result<()> {
for logger in &self.loggers {
logger.stdout(output).unwrap()
}
Ok(())
}
fn stderr(&self, output: &str) -> eyre::Result<()> {
for logger in &self.loggers {
logger.stderr(output).unwrap()
}
Ok(())
}
}

View File

@@ -1,5 +1,6 @@
use std::{collections::HashMap, ops::Add, sync::Arc};
use dagger_core::graphql_client::DynGraphQLClient;
use eyre::Context;
use serde::{Deserialize, Serialize};
@@ -68,6 +69,29 @@ impl Selection {
s
}
pub fn arg_enum<S>(&self, name: &str, value: S) -> Selection
where
S: Serialize,
{
let mut s = self.clone();
let val = serde_json::to_string(&value).unwrap();
let val = val[1..val.len() - 1].to_string();
match s.args.as_mut() {
Some(args) => {
let _ = args.insert(name.to_string(), val);
}
None => {
let mut hm = HashMap::new();
let _ = hm.insert(name.to_string(), val);
s.args = Some(hm);
}
}
s
}
pub fn build(&self) -> eyre::Result<String> {
let mut fields = vec!["query".to_string()];
@@ -76,7 +100,7 @@ impl Selection {
if let Some(args) = sel.args {
let actualargs = args
.iter()
.map(|(name, arg)| format!("{name}:{arg}"))
.map(|(name, arg)| format!("{name}:{}", arg.as_str()))
.collect::<Vec<_>>();
query = query.add(&format!("({})", actualargs.join(", ")));
@@ -93,12 +117,14 @@ impl Selection {
Ok(fields.join("{") + &"}".repeat(fields.len() - 1))
}
pub async fn execute<D>(&self, gql_client: &gql_client::Client) -> eyre::Result<D>
pub async fn execute<D>(&self, gql_client: DynGraphQLClient) -> eyre::Result<D>
where
D: for<'de> Deserialize<'de>,
{
let query = self.build()?;
tracing::trace!(query = query.as_str(), "dagger-query");
let resp: Option<serde_json::Value> = match gql_client.query(&query).await {
Ok(r) => r,
Err(e) => eyre::bail!(e),

View File

@@ -0,0 +1,47 @@
use dagger_sdk::{QueryContainerOpts, QueryContainerOptsBuilder};
static PLATFORMS: [&str; 2] = ["linux/arm64", "linux/x86_64"];
#[tokio::test]
async fn test_issue_30_alt() -> eyre::Result<()> {
let client = dagger_sdk::connect().await?;
for platform in PLATFORMS {
let ref_ = client
.container_opts(QueryContainerOpts {
id: None,
platform: Some(platform.to_string().into()),
})
.from("alpine")
.with_exec(vec!["echo", "'hello'"])
.exit_code()
.await?;
println!("published image to: {:#?}", ref_);
}
Ok(())
}
#[tokio::test]
async fn test_issue_30() -> eyre::Result<()> {
let client = dagger_sdk::connect().await?;
for platform in PLATFORMS {
let ref_ = client
.container_opts(
QueryContainerOptsBuilder::default()
.platform(platform)
.build()
.unwrap(),
)
.from("alpine")
.with_exec(vec!["echo", "'hello'"])
.exit_code()
.await?;
println!("published image to: {:#?}", ref_);
}
Ok(())
}

View File

@@ -0,0 +1,29 @@
use dagger_sdk::{ContainerWithExposedPortOpts, NetworkProtocol};
#[tokio::test]
async fn test_issue_30_alt() -> eyre::Result<()> {
let client = dagger_sdk::connect().await?;
client
.container()
.from("denoland/deno:debian-1.30.3")
.with_exposed_port_opts(
53,
ContainerWithExposedPortOpts {
protocol: Some(NetworkProtocol::TCP),
description: None,
},
)
.with_exposed_port_opts(
53,
ContainerWithExposedPortOpts {
protocol: Some(NetworkProtocol::UDP),
description: None,
},
)
.with_exec(vec!["echo", "hello"])
.exit_code()
.await?;
Ok(())
}

View File

@@ -0,0 +1,2 @@
mod iss_30;
mod iss_33;

View File

@@ -1,4 +1,6 @@
use dagger_sdk::{connect, ContainerExecOpts, ContainerExecOptsBuilder};
mod issues;
use dagger_sdk::{connect, ContainerExecOptsBuilder};
use pretty_assertions::assert_eq;
#[tokio::test]