diff --git a/.dagger/modules/dev/dagger.json b/.dagger/modules/dev/dagger.json new file mode 100644 index 0000000..fc0a202 --- /dev/null +++ b/.dagger/modules/dev/dagger.json @@ -0,0 +1,14 @@ +{ + "name": "dev", + "engineVersion": "v1.0.0-0", + "sdk": { + "source": "dang" + }, + "dependencies": [ + { + "name": "polyfill", + "source": "github.com/dagger/polyfill@main", + "pin": "ec3ea84a2351b4beb06ecece951f2e5ef66509ff" + } + ] +} diff --git a/.dagger/modules/dev/main.dang b/.dagger/modules/dev/main.dang new file mode 100644 index 0000000..f51dc1a --- /dev/null +++ b/.dagger/modules/dev/main.dang @@ -0,0 +1,137 @@ +pub description = "Develop the Dagger Elixir SDK" + +""" +Dev tooling for this repository: lint and test the Elixir client library and its +codegen project, and keep the pinned Elixir image in step across the Dang modules +that reference it. + +Module scaffolding, code generation for user modules, and the module runtime are +not here — they live in the root module (`elixir-sdk.dang`, `mod.dang`) and +`runtime/main.dang`. +""" +type Dev { + """ + Elixir image the checks run on. `syncImage` propagates this to the Dang modules + that pin the same image. + """ + pub baseImage: String! = "elixir:1.19.5-otp-28-alpine@sha256:1747b3595b6742d2273d18608203457d5b925000cd38aca40c76e23c64d44def" + + """ + Path of the Elixir client library within this repository. + """ + pub sourcePath: String! = "sdk" + + """ + The workspace this module belongs to. + """ + let ws: Workspace! + + """ + The Elixir client library source. + """ + pub source: Directory! { + ws.directory("/", include: [sourcePath + "/**"]).directory(sourcePath) + } + + """ + Lint the client library: formatting plus credo. + """ + pub lint: Void @check { + devContainer + .withExec(["mix", "format", "--check-formatted"]) + .withExec(["mix", "credo"]) + .sync + + null + } + + """ + Run the client library's hermetic test suite. + + Tests tagged :integration need a live engine and are excluded by default; see + sdk/test/test_helper.exs. + """ + pub sdkTest: Void @check { + devContainer + .withExec(["mix", "test"]) + .sync + + null + } + + """ + Run the dagger_codegen test suite. + """ + pub codegenTest: Void @check { + withCodegen(devContainer) + .withEnvVariable("CI", "true") + .withExec(["mix", "test"]) + .sync + + null + } + + """ + Update dagger_codegen's Mneme snapshots in place. + """ + pub updateCodegenTests: Changeset! { + let before = ws.directory("/", include: [sourcePath + "/dagger_codegen/**"]) + + let updated = withCodegen(devContainer) + .withEnvVariable("MNEME_ACCEPT", "1") + .withExec(["mix", "test"]) + .directory("/src/dagger_codegen") + .withoutDirectory("_build") + .withoutDirectory("deps") + + before + .withDirectory(sourcePath + "/dagger_codegen", updated) + .changes(before) + } + + """ + Pin the same Elixir image everywhere it appears. + + The image is declared in three places that must agree: this module, the module + runtime, and the codegen container used by `dagger generate`. Set `baseImage` + and run this to propagate it. + """ + pub syncImage: Changeset! { + let paths = ["runtime/main.dang", "mod.dang"] + let before = ws.directory("/", include: paths) + + paths + .reduce(before) { acc, path => + let updated = before.file(path).contents.replaceMatches( + `let elixirImage = ".*"`, + with: "let elixirImage = \"" + baseImage + "\"", + ) + acc.withNewFile(path, updated) + } + .changes(before) + } + + """ + Container with the client library mounted and its dependencies fetched. + """ + let devContainer: Container! { + container + .from(baseImage) + .withExec(["apk", "add", "--no-cache", "git"]) + .withExec(["mix", "local.hex", "--force"]) + .withExec(["mix", "local.rebar", "--force"]) + .withMountedCache("/root/.hex", cacheVolume("elixir-sdk-hex")) + .withWorkdir("/src") + .withDirectory("/src", source) + .withExec(["mix", "deps.get"]) + } + + """ + Move a container into the dagger_codegen project and fetch its dependencies. + """ + let withCodegen(ctr: Container!): Container! { + ctr + .withWorkdir("/src/dagger_codegen") + .withExec(["mix", "deps.get"]) + } +} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0d16148 --- /dev/null +++ b/.gitignore @@ -0,0 +1,21 @@ +# Elixir build artifacts +_build/ +cover/ +deps/ +doc/ +.fetch +erl_crash.dump +*.ez +*.tar +tmp/ + +# Go helper build output +/helpers/*/render-template + +# LSP +.elixir_ls +.lexical +.elixir-tools + +# Local env +.env diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..03c3c7c --- /dev/null +++ b/LICENSE @@ -0,0 +1,191 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2023 Dagger, Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md index b50f9ca..b8b1e7a 100644 --- a/README.md +++ b/README.md @@ -1 +1,118 @@ # elixir-sdk + +A Dagger module for managing Dagger modules that use the Elixir SDK, plus the Elixir client +library itself. + +SDK-specific module authoring (scaffolding new modules, language build config, codegen) +lives in modules like this one. Under the CLI 1.0 init contract the engine drives the SDK: +this module exposes `initModule` and `targetRuntime`, and the engine merges the SDK-owned +files with its own workspace bookkeeping. Shared, language-agnostic operations — editing a +module's dependencies or its required engine version — are owned by the core CLI +(`dagger module deps`, `dagger module engine`) and are not part of this module's surface. + +Backed by [`github.com/dagger/polyfill`](https://github.com/dagger/polyfill). + +## What's in here + +| Path | What it is | +| --- | --- | +| `elixir-sdk.dang`, `mod.dang`, `template.dang` | The SDK contract module — `initModule`, `targetRuntime`, and the `@generate` hook | +| `runtime/` | The module runtime new Elixir modules reference. Build-only; see [its README](./runtime/README.md) | +| `sdk/` | The Elixir client library (`dagger` on Hex) and its codegen project | +| `templates/` | Starter templates for `dagger module init elixir` | +| `helpers/render-template/` | Go helper that renders a template for a given module name | +| `.dagger/modules/dev/` | Lint and test tooling for `sdk/` | + +## Install + +From your workspace root: + +```sh +dagger sdk install github.com/dagger/elixir-sdk +``` + +After install, the module is available in `dagger call` as `elixir-sdk`. + +Calls that return a `Changeset` will print the diff and prompt you to confirm before writing +anything to your workspace. + +## Create a new module + +```sh +dagger module init elixir my-module +dagger generate +``` + +`initModule` only seeds the SDK-owned template files; the engine writes the module config +and workspace entries. **Run `generate` afterwards** — a fresh module's `mix.exs` depends on +`./dagger_sdk`, which generation writes, so it does not compile until then. + +Pick a starter with `--template`: + +```sh +dagger module init elixir my-module --template empty +``` + +`default` (the default) gives you a working module with two example functions; `empty` gives +you a bare object module. + +You can also call the function directly for testing. `path` is required (the engine supplies +it in the dispatched path): + +```sh +dagger call elixir-sdk init-module --name my-module --path .dagger/modules/my-module +``` + +## Generate SDK files + +For a single module: + +```sh +dagger call elixir-sdk mod --path my-module generate +``` + +For every Elixir SDK module visible from your current directory: + +```sh +dagger generate +``` + +Generation vendors the Elixir SDK, together with the API bindings generated from your +engine's schema, into `/dagger_sdk/`. **Commit it** — the runtime builds from the +committed sources and never regenerates them. + +To exclude a directory tree from bulk generation, drop an empty +`.dagger-elixir-sdk-skip-generate` file at or above the module root: + +```sh +touch some/fixture/.dagger-elixir-sdk-skip-generate +``` + +## Manage dependencies and the engine version + +Editing a module's dependencies or its required engine version is identical across SDKs, so +the core CLI owns it: + +```sh +dagger module deps add github.com/some/module +dagger module engine require-latest +``` + +## Develop this repository + +```sh +dagger call -m .dagger/modules/dev lint +dagger call -m .dagger/modules/dev sdk-test +dagger call -m .dagger/modules/dev codegen-test +``` + +Check the SDK against the shared contract suite: + +```sh +dagger -m github.com/dagger/sdk-sdk -W . check +``` + +`sdk/`'s test suite is hermetic by default; tests that need a live engine are tagged +`:integration` and run with `mix test --include integration`. + +See [`elixir-sdk.dang`](./elixir-sdk.dang) for the full type surface. diff --git a/dagger.json b/dagger.json new file mode 100644 index 0000000..fcd95b6 --- /dev/null +++ b/dagger.json @@ -0,0 +1,14 @@ +{ + "name": "elixir-sdk", + "engineVersion": "v1.0.0-0", + "sdk": { + "source": "dang" + }, + "dependencies": [ + { + "name": "polyfill", + "source": "github.com/dagger/polyfill@main", + "pin": "ec3ea84a2351b4beb06ecece951f2e5ef66509ff" + } + ] +} diff --git a/dagger.lock b/dagger.lock new file mode 100644 index 0000000..f5407a3 --- /dev/null +++ b/dagger.lock @@ -0,0 +1,3 @@ +[["version","1"]] +["","git.head",["https://github.com/dagger/sdk-sdk"],"e1747f4b6221fa24da080701e027243e0cc5fa33","float"] +["","git.ref",["https://github.com/dagger/polyfill","main"],"ec3ea84a2351b4beb06ecece951f2e5ef66509ff","float"] diff --git a/dagger.toml b/dagger.toml new file mode 100644 index 0000000..4ad20a5 --- /dev/null +++ b/dagger.toml @@ -0,0 +1,15 @@ +# Dagger workspace configuration +# Install modules with: dagger install + +[modules.elixir-sdk] +source = "." +check.skip = ["*"] + +[modules.elixir-sdk.as-sdk] +name = "elixir" + +[modules.dev] +source = ".dagger/modules/dev" + +[modules.sdk-sdk] +source = "github.com/dagger/sdk-sdk" diff --git a/elixir-sdk.dang b/elixir-sdk.dang new file mode 100644 index 0000000..81a26c3 --- /dev/null +++ b/elixir-sdk.dang @@ -0,0 +1,219 @@ +""" +Manage Dagger modules that use the Elixir SDK. +""" +type ElixirSdk { + # Matches `"sdk": { "source": "elixir" }` in a legacy dagger.json. + let legacyConfigPattern = "\"sdk\"\\s*:\\s*\\{[^}]*\"source\"\\s*:\\s*\"elixir\"" + + # Matches a `[runtime]` table whose source names this SDK's runtime in a CLI + # 1.0 dagger-module.toml. Accepts the bare `elixir` name as well as the remote + # runtime ref, with or without a version suffix. + let tomlConfigPattern = "\\[runtime\\][^\\[]*source\\s*=\\s*\"(elixir|github\\.com/dagger/elixir-sdk/runtime[^\"]*)\"" + + """ + Config filenames that mark a Dagger module root: the CLI 1.0 + `dagger-module.toml` (workspace-managed modules) and the legacy `dagger.json`. + A managed module is discovered by whichever it uses. + """ + let moduleConfigFilenames: [String!]! = ["dagger-module.toml", "dagger.json"] + + """ + Marker filename that skips generate when found at or above an Elixir SDK module root. + """ + pub skipGenerateFilename: String! = ".dagger-elixir-sdk-skip-generate" + + """ + Runtime source to write into modules created by this SDK. + + Elixir has no built-in engine runtime, so new modules point at this + repository's build-only runtime module. + """ + pub targetRuntime: String! { "github.com/dagger/elixir-sdk/runtime" } + + """ + Return init templates tracked by this module. + + Templates live under templates/ and are materialized into the new + module before generation. Passing an empty template to init uses the module + default. + """ + pub templates: [Template!]! { + if (currentModule.source.exists("templates")) { + let root = currentModule.source.directory("templates") + root.entries.map { name => + Template( + name: name.trimSuffix("/"), + source: root.directory(name), + ) + } + } else { + directory.entries.map { name => + Template( + name: name, + source: directory, + ) + } + } + } + + """ + Return every managed Elixir SDK module visible from the client's cwd: the + nearest enclosing module plus modules at or below the cwd. Discovery uses the + shared polyfill and intersects its results with the SDK list on the passed + workspace. + """ + pub modules(ws: Workspace!): [Mod!]! { + let managed = currentModule.asSDK(workspace: ws).modules.{{path}} + let cwd = normalizePath(ws.cwd) + polyfill.workspace(ws) + .findConfigDirs(moduleConfigFilenames, exclude: ["**/_build/**", "**/deps/**"]) + .map { dir => workspacePath(cwd, dir) } + .uniq + .filter { path => managed.filter { m => normalizePath(m.path) == path }.length > 0 } + .map { path => Mod(rootPath: path, ws: ws, skipGenerateFilename: skipGenerateFilename) } + } + + """ + Return the Elixir SDK module at or above a workspace path. + + When `findUp` is true, `path` may point inside the module. + """ + pub mod(ws: Workspace!, path: String! = ".", findUp: Boolean! = true): Mod! { + let modPath = if (findUp) { + let foundToml = ws.findUp("dagger-module.toml", path) + let foundJson = ws.findUp("dagger.json", path) + let tomlBase = if (foundToml == null) { null } else { configDir(foundToml, "dagger-module.toml") } + let jsonBase = if (foundJson == null) { null } else { configDir(foundJson, "dagger.json") } + + if (tomlBase == null and jsonBase == null) { + raise "no Dagger module found containing path: " + path + } else if (tomlBase != null and pathDepth(tomlBase) > pathDepth(jsonBase)) { + validateConfig(ws, tomlBase, "dagger-module.toml", tomlConfigPattern, path) + } else if (jsonBase != null) { + validateConfig(ws, jsonBase, "dagger.json", legacyConfigPattern, path) + } else { + raise "no Dagger module found containing path: " + path + } + } else { + normalizePath(path) + } + + Mod( + rootPath: modPath, + ws: ws, + skipGenerateFilename: skipGenerateFilename, + ) + } + + """ + Initialize Elixir-owned files for a new Dagger module. + + Returns a Changeset with only the SDK-owned template files layered onto the + new module's `path`. Engine-owned files (dagger-module.toml, workspace config + updates) are produced by the engine and merged with this changeset. + + Pass `template` to pick a starter under templates/