diff --git a/.github/ISSUE_TEMPLATE/BUG_REPORT.yml b/.github/ISSUE_TEMPLATE/BUG_REPORT.yml new file mode 100644 index 0000000..c8bef07 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/BUG_REPORT.yml @@ -0,0 +1,48 @@ +name: Bug Report +description: Report unexpected behavior or crashes +title: "[BUG] " +labels: ["bug-report", "triage"] +body: + - type: checkboxes + attributes: + label: Pre-submission Checklist + options: + - label: I've checked existing issues and pull requests + required: true + - label: I've read the [Code of Conduct](https://github.com/FlakySL/cruct/blob/main/CODE_OF_CONDUCT.md) + required: true + - label: Are you using the latest version of cruct? + required: true + + - type: dropdown + attributes: + label: Component + options: + - Core library + - Documentation + validations: + required: true + + - type: input + attributes: + label: Rust Version + placeholder: Output of `rustc --version` + validations: + required: true + + - type: textarea + attributes: + label: Reproduction Steps + description: Step-by-step instructions to reproduce the issue + validations: + required: true + + - type: textarea + attributes: + label: Expected vs Actual Behavior + description: What you expected to happen vs what actually happened + + - type: textarea + attributes: + label: Additional Context + description: Logs, screenshots, or code samples diff --git a/.github/ISSUE_TEMPLATE/FEATURE_REQUEST.yml b/.github/ISSUE_TEMPLATE/FEATURE_REQUEST.yml new file mode 100644 index 0000000..38b3963 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/FEATURE_REQUEST.yml @@ -0,0 +1,37 @@ +name: Feature Request +description: Suggest an idea for cruct +title: "[FEATURE] " +labels: ["feature-request", "triage"] +body: + - type: checkboxes + attributes: + label: Pre-submission Checklist + options: + - label: I've checked existing issues and pull requests + required: true + - label: I've read the [Code of Conduct](https://github.com/FlakySL/cruct/blob/main/CODE_OF_CONDUCT.md) + required: true + + - type: textarea + attributes: + label: Problem Description + description: What problem are you trying to solve? + validations: + required: true + + - type: textarea + attributes: + label: Proposed Solution + description: How should cruct address this problem? + validations: + required: true + + - type: textarea + attributes: + label: Alternatives Considered + description: Other ways this could potentially be solved + + - type: textarea + attributes: + label: Additional Context + description: Potential disadvantages, edge cases, or examples diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..168db3d --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,26 @@ +blank_issues_enabled: false + +contact_links: + - name: "šŸ’¬ Community Help (Discord)" + url: https://discord.gg/AJWFyps23a + about: | + For general questions, discussion, or brainstorming: + - Get real-time help from maintainers + - Discuss potential features + - Chat with other contributors + *Please check existing issues first!* + + - name: "āš–ļø Code of Conduct" + url: https://github.com/FlakySL/cruct/blob/main/CODE_OF_CONDUCT.md + about: | + All community interactions must follow the project + code of conduct, which is based on the contributor covenant. + *Required reading before participating* + + - name: "🚨 Moderation Contact" + url: mailto:moderation@flaky.es + about: | + For urgent moderation issues: + - Code of Conduct violations + - Community safety concerns + - Escalation requests diff --git a/.github/cruct_banner.png b/.github/cruct_banner.png new file mode 100644 index 0000000..816340d Binary files /dev/null and b/.github/cruct_banner.png differ diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..53f8242 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,6 @@ +version: 2 +updates: + - package-ecosystem: "cargo" + directory: "/" + schedule: + interval: "weekly" diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..6891ff0 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,14 @@ +## Pre-submission Checklist + +- [ ] I've checked existing issues and pull requests +- [ ] I've read the [Code of Conduct](../CODE_OF_CONDUCT.md) +- [ ] I've [implemented tests](../TESTING.md) for my changes +- [ ] I've listed all my changes in the `Changes` section + +## Changes + +- + +## Linked Issues + +- fixes # diff --git a/.github/workflows/overall-coverage.yml b/.github/workflows/overall-coverage.yml new file mode 100644 index 0000000..67a1dad --- /dev/null +++ b/.github/workflows/overall-coverage.yml @@ -0,0 +1,52 @@ +name: tests + +on: + push: + branches: [main] + pull_request: + branches: + - main + +jobs: + coverage: + name: Collect test coverage + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: + - ubuntu-latest + - windows-latest + # nightly rust might break from time to time + continue-on-error: true + env: + RUSTFLAGS: -D warnings + CARGO_TERM_COLOR: always + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4 + # Nightly Rust is used for cargo llvm-cov --doc below. + - uses: dtolnay/rust-toolchain@nightly + with: + components: llvm-tools-preview + - uses: Swatinem/rust-cache@98c8021b550208e191a6a3145459bfc9fb29c4c0 # v2 + + - name: Install latest nextest release + uses: taiki-e/install-action@d028bcc176afad59ee1e0b7dbba9789b8a1421f8 # v2 + with: + tool: nextest + - name: Install cargo-llvm-cov + uses: taiki-e/install-action@d028bcc176afad59ee1e0b7dbba9789b8a1421f8 # v2 + with: + tool: cargo-llvm-cov + + - name: Collect coverage data + # Generate separate reports for nextest and doctests, and combine them. + run: | + cargo llvm-cov --no-report nextest + cargo llvm-cov --no-report --doc + cargo llvm-cov report --doctests --lcov --output-path lcov.info + - name: Upload coverage data to codecov + uses: codecov/codecov-action@18283e04ce6e62d37312384ff67231eb8fd56d24 # v5 + env: + CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} + with: + files: lcov.info diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml new file mode 100644 index 0000000..e69de29 diff --git a/.gitignore b/.gitignore index a209484..c1756b0 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,3 @@ target/ .bacon-locations -.direnv +.direnv/ diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..873568e --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,76 @@ +# cruct Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, gender identity and expression, level of experience, +education, socio-economic status, nationality, personal appearance, race, +religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or + advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at [`moderation@flaky.es`]. +All complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 1.4, available at [contributor covenant]. + +[homepage]: https://www.contributor-covenant.org +[contributor covenant]: https://www.contributor-covenant.org/version/1/4/code-of-conduct.html + +[`moderation@flaky.es`]: mailto:moderation@flaky.es diff --git a/CONTIRBUTING.md b/CONTIRBUTING.md new file mode 100644 index 0000000..361a4ca --- /dev/null +++ b/CONTIRBUTING.md @@ -0,0 +1,65 @@ +# Contributing to cruct + +In cruct, we welcome contributions from everyone, including bug reports, +pull requests, and feedback. This document serves as guidance if you are +considering submitting any of the above. + +## Submitting Bug Reports and Feature Requests + +To submit a bug report or feature request, you can open an issue in this +repository: [`FlakySL/cruct`]. + +When reporting a bug or requesting help, please include sufficient details +to allow others to reproduce the behavior you're encountering. For guidance on +how to approach this, read about [How to Create a Minimal, Reproducible Example]. + +When making a feature request, please clearly explain: + +1. The problem you want to solve +2. How cruct could help address this problem +3. Any potential alternatives +4. Possible disadvantages of your proposal + +Before submitting, please verify that no existing issue addresses your specific +problem/request. If you want to elaborate on a problem or discuss it further, +you can use our [Discord channel] at Flaky. + +We recommend using the issue templates provided in this repository. + +## Making Pull Requests + +Before adding a feature on your behalf, we'd rather for it to be evaluated +in a issue before, we appreciate the time and effort our contributors have +and we don't want to waste it, so we'd rather talk about your feature before +you working on it. + +When submitting a pull request make sure the code you added is tested and +documented, if it isn't you will be asked to document/test it before merging. + +To add tests please refer to the [testing documentation] in the root folder. + +## Running Tests and Compiling the Project + +This project doesn't have any specific configuration +to it, meaning you can simply use `cargo build` to compile +the project and `cargo test` to test it. + +The makefile in the project is used only in the workflow +runs and provides coverage for `codecov` and other statistics. + +## Code of Conduct + +The Flaky community follows the [Contributor covenant]. +For moderation issues or escalation, please contact Esteve or Luis at +[moderation@flaky.es] rather than the Rust +moderation team. + +[testing documentation]: ./TESTING.md +[Contributor covenant]: ./CODE_OF_CONDUCT.md + +[`FlakySL/cruct`]: https://github.com/FlakySL/cruct + +[Discord channel]: https://discord.gg/AJWFyps23a +[moderation@flaky.es]: mailto:moderation@flaky.es + +[How to Create a Minimal, Reproducible Example]: https://stackoverflow.com/help/minimal-reproducible-example diff --git a/Cargo.lock b/Cargo.lock index d16bbe5..79f96d6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,12 +2,71 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "addr2line" +version = "0.24.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfbe277e56a376000877090da837660b4427aad530e3028d44e0bffe4f89a1c1" +dependencies = [ + "gimli", +] + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + [[package]] name = "arraydeque" version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d902e3d592a523def97af8f317b08ce16b7ab854c1985a0c671e6f15cebc236" +[[package]] +name = "assay" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b6400785ccafeab7f18a4d23d726f9090dd1195386f06026c6e59db36e11938" +dependencies = [ + "assay-proc-macro", + "pretty_assertions", + "rusty-fork", + "tempfile", + "tokio", +] + +[[package]] +name = "assay-proc-macro" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d94121b572ccf1d1b38a1004155e59c64f4c6ff7793070d84a8807e0550881e" +dependencies = [ + "quote", + "syn 1.0.109", +] + +[[package]] +name = "backtrace" +version = "0.3.75" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6806a6321ec58106fea15becdad98371e28d92ccbc7c8f1b3b6dd724fe8f1002" +dependencies = [ + "addr2line", + "cfg-if", + "libc", + "miniz_oxide", + "object", + "rustc-demangle", + "windows-targets", +] + +[[package]] +name = "bitflags" +version = "2.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c8214115b7bf84099f1309324e63141d4c5d7cc26862f97a0a857dbefe165bd" + [[package]] name = "cfg-if" version = "1.0.0" @@ -18,9 +77,10 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" name = "cruct" version = "0.1.0" dependencies = [ + "assay", "cruct_proc", "cruct_shared", - "thiserror", + "tempfile", ] [[package]] @@ -30,7 +90,7 @@ dependencies = [ "cruct_shared", "proc-macro2", "quote", - "syn", + "syn 2.0.100", "thiserror", ] @@ -39,11 +99,18 @@ name = "cruct_shared" version = "0.1.0" dependencies = [ "jzon", + "tempfile", "thiserror", "toml_edit", "yaml-rust2", ] +[[package]] +name = "diff" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56254986775e3233ffa9c4d7d3faaf6d36a2c09d30b20687e9f88bc8bafc16c8" + [[package]] name = "encoding_rs" version = "0.8.35" @@ -59,12 +126,52 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" +[[package]] +name = "errno" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "976dd42dc7e85965fe702eb8164f21f450704bdde31faefd6471dba214cb594e" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "fastrand" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + [[package]] name = "foldhash" version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" +[[package]] +name = "getrandom" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73fea8450eea4bac3940448fb7ae50d91f034f941199fcd9d909a5a07aa455f0" +dependencies = [ + "cfg-if", + "libc", + "r-efi", + "wasi", +] + +[[package]] +name = "gimli" +version = "0.31.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07e28edb80900c19c28f1072f2e8aeca7fa06b23cd4169cefe1af5aa3260783f" + [[package]] name = "hashbrown" version = "0.15.2" @@ -99,12 +206,64 @@ version = "0.12.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "17ab85f84ca42c5ec520e6f3c9966ba1fd62909ce260f8837e248857d2560509" +[[package]] +name = "libc" +version = "0.2.172" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d750af042f7ef4f724306de029d18836c26c1765a54a6a3f094cbd23a7267ffa" + +[[package]] +name = "linux-raw-sys" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd945864f07fe9f5371a27ad7b52a172b4b499999f1d97574c9fa68373937e12" + [[package]] name = "memchr" version = "2.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", +] + +[[package]] +name = "object" +version = "0.36.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62948e14d923ea95ea2c7c86c71013138b66525b86bdc08d2dcc262bdb497b87" +dependencies = [ + "memchr", +] + +[[package]] +name = "once_cell" +version = "1.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" + +[[package]] +name = "pin-project-lite" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b" + +[[package]] +name = "pretty_assertions" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ae130e2f271fbc2ac3a40fb1d07180839cdbbe443c7a27e1e3c13c5cac0116d" +dependencies = [ + "diff", + "yansi", +] + [[package]] name = "proc-macro2" version = "1.0.95" @@ -114,6 +273,12 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "quick-error" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" + [[package]] name = "quote" version = "1.0.40" @@ -123,6 +288,54 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "r-efi" +version = "5.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74765f6d916ee2faa39bc8e68e4f3ed8949b48cccdac59983d287a7cb71ce9c5" + +[[package]] +name = "rustc-demangle" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "989e6739f80c4ad5b13e0fd7fe89531180375b18520cc8c82080e4dc4035b84f" + +[[package]] +name = "rustix" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d97817398dd4bb2e6da002002db259209759911da105da92bec29ccb12cf58bf" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "rusty-fork" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb3dcc6e454c328bb824492db107ab7c0ae8fcffe4ad210136ef014458c1bc4f" +dependencies = [ + "fnv", + "quick-error", + "tempfile", + "wait-timeout", +] + +[[package]] +name = "syn" +version = "1.0.109" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "syn" version = "2.0.100" @@ -134,6 +347,19 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "tempfile" +version = "3.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8a64e3985349f2441a1a9ef0b853f869006c3855f2cda6862a94d26ebb9d6a1" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix", + "windows-sys", +] + [[package]] name = "thiserror" version = "2.0.12" @@ -151,7 +377,17 @@ checksum = "7f7cf42b4507d8ea322120659672cf1b9dbb93f8f2d4ecfd6e51350ff5b17a1d" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.100", +] + +[[package]] +name = "tokio" +version = "1.45.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75ef51a33ef1da925cea3e4eb122833cb377c61439ca401b770f54902b806779" +dependencies = [ + "backtrace", + "pin-project-lite", ] [[package]] @@ -177,6 +413,97 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512" +[[package]] +name = "wait-timeout" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11" +dependencies = [ + "libc", +] + +[[package]] +name = "wasi" +version = "0.14.2+wasi-0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9683f9a5a998d873c0d21fcbe3c083009670149a8fab228644b8bd36b2c48cb3" +dependencies = [ + "wit-bindgen-rt", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + [[package]] name = "winnow" version = "0.7.6" @@ -186,6 +513,15 @@ dependencies = [ "memchr", ] +[[package]] +name = "wit-bindgen-rt" +version = "0.39.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f42320e61fe2cfd34354ecb597f86f413484a798ba44a8ca1165c58d42da6c1" +dependencies = [ + "bitflags", +] + [[package]] name = "yaml-rust2" version = "0.10.1" @@ -196,3 +532,9 @@ dependencies = [ "encoding_rs", "hashlink", ] + +[[package]] +name = "yansi" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" diff --git a/GPLv3-LICENSE b/GPLv3-LICENSE new file mode 100644 index 0000000..281d399 --- /dev/null +++ b/GPLv3-LICENSE @@ -0,0 +1,619 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..0d012be --- /dev/null +++ b/LICENSE @@ -0,0 +1,28 @@ +This software is dual-licensed: + +1. GNU GENERAL PUBLIC LICENSE Version 3 (GPLv3) + You can redistribute and/or modify this software under the terms + of the GPLv3 as published by the Free Software Foundation. + + You should have received a copy of the GNU General Public License + along with this program (see `GPLv3-LICENSE`). If not, + see . + +2. Commercial License + Closed-source, proprietary, or commercial use of this software + requires a commercial license. + + If you want to use this software in a closed-source or proprietary + project, or if your project is not licensed under the GPLv3, please contact: + + Flaky, Sl. + licensing@flaky.es + + for a custom license for your use case. + +--- + +Copyright (c) 2025-2030 Flaky, Sl. + +This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty +of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..4c8f9c2 --- /dev/null +++ b/README.md @@ -0,0 +1,115 @@ +![cruct-readme](./.github/cruct_banner.png) + +[![Crates.io](https://badges.ws/crates/v/cruct)](https://crates.io/crates/cruct) +[![Docs.rs](https://badges.ws/crates/docs/cruct)](https://docs.rs/cruct) +[![License](https://badges.ws/crates/l/cruct)](https://docs.rs/cruct) +[![Downloads](https://badges.ws/crates/dt/cruct)](https://crates.io/crates/cruct) +[![Codecov](https://img.shields.io/codecov/c/github/FlakySL/cruct)](https://app.codecov.io/gh/FlakySL/cruct) +![tests](https://github.com/FlakySL/cruct/actions/workflows/overall-coverage.yml/badge.svg) +[![Discord](https://badges.ws/discord/online/1344769456731197450)](https://discord.gg/AJWFyps23a) + +--- + +# Cruct + +A procedural macro for loading configuration files into Rust structs with compile‑time validation and type safety. + +## Features + +- **Multi‑format support**: TOML, YAML, JSON (via Cargo feature flags) +- **Merge & override**: CLI args, environment variables, config files, defaults +- **Compile‑time safety**: Missing or mismatched fields become compile or runtime errors +- **Nested structures**: Automatically derive for nested custom types + +## Installation + +Add to your `Cargo.toml`: + +```toml +[dependencies] +cruct = "0.1.0" +```` + +Enable only the formats you need: + +```toml +[dependencies.cruct] +version = "0.1.0" +default-features = false +features = ["toml", "json"] # only TOML and JSON support +``` + +## Basic Usage + +Annotate your config‐struct with `#[cruct]`, pointing at one or more sources: + +```rust +use cruct::cruct; + +#[cruct(load_config(path = "config/settings.toml"))] +struct AppConfig { + #[field(default = 8080)] + http_port: u16, + database_url: String, +} + +fn main() -> Result<(), cruct_shared::ParserError> { + let cfg = AppConfig::loader() + .with_config() + .load()?; + println!("Listening on port {}", cfg.http_port); + Ok(()) +} +``` + +## Use‑Case: Environment‑Variable Override + +Often you want a default in your file, but allow ops to override via env vars. For example, given `tests/fixtures/test_config.toml`: + +```toml +http_port = 8080 +``` + +You can override `http_port` at runtime: + +```rust +use cruct::cruct; + +#[cruct(load_config(path = "tests/fixtures/test_config.toml"))] +#[derive(Debug, PartialEq)] +struct TestEnv { + #[field(env_override = "TEST_HTTP_PORT")] + http_port: u16, +} + +fn main() { + // Simulate setting the env var: + unsafe { std::env::set_var("TEST_HTTP_PORT", "9999"); } + + let config = TestEnv::loader() + .with_config() + .load() + .unwrap(); + + assert_eq!(config.http_port, 9999); + println!("Overridden port: {}", config.http_port); +} +``` + +This pattern is drawn directly from our end‑to‑end tests. + +## Advanced + +* **Multiple files & priority**: Chain `load_config` calls with explicit `priority` +* **Case‑insensitive keys**: Use `#[field(name = "HTTP_PORT", insensitive = true)]` +* **Default values**: Supply literals, expressions, or functions for `default` + +See the full [API docs](https://docs.rs/cruct) for details on all options. + +## License + +This repository is dual licensed, TLDR. If your repository is open source, the library +is free of use, otherwise contact [licensing@flaky.es](mailto:licensing@flaky.es) for a custom license for your +use case. + +For more information read the [license](./LICENSE) file. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..46fc58b --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,19 @@ +# Security Vulnerabilities + +**If you find any security issues, please reach out to any of the maintainers +listed in our [governance.md].** We take all security reports seriously and +will get back to you as soon as possible. + +We also have security measures in place by using automated tools for managing dependencies. +Our project **strongly** relies on [dependabot] to: + +- Check for security vulnerabilities +- Update dependencies when needed +- Maintain all dependencies up to date + +This automated system helps us apply security patches regularly, reducing the +need for manual checks on dependencies and ensuring that we are using the +latest versions of libraries to prevent security issues. + +[dependabot]: https://docs.github.com/en/code-security/dependabot +[governance.md]: GOVERNANCE.md diff --git a/TESTING.md b/TESTING.md new file mode 100644 index 0000000..6c7679f --- /dev/null +++ b/TESTING.md @@ -0,0 +1,4 @@ +# Tests +--- + +I still have to decide how to structure the tests, so this file is a work in progress. diff --git a/codecov.yml b/codecov.yml new file mode 100644 index 0000000..f5885b2 --- /dev/null +++ b/codecov.yml @@ -0,0 +1,10 @@ +coverage: + status: + project: + default: + target: 80% + patch: + default: + target: 80% +ignore: + - ".direnv" diff --git a/cruct/Cargo.toml b/cruct/Cargo.toml index 66a0c46..4911d29 100644 --- a/cruct/Cargo.toml +++ b/cruct/Cargo.toml @@ -3,8 +3,16 @@ name = "cruct" version = "0.1.0" edition = "2024" +[features] +default = ["toml", "yaml", "json"] +toml = ["cruct_proc/toml", "cruct_shared/toml"] +yaml = ["cruct_proc/yaml", "cruct_shared/yaml"] +json = ["cruct_proc/json", "cruct_shared/json"] + [dependencies] cruct_proc = { path = "../cruct_proc" } cruct_shared = { path = "../cruct_shared" } -thiserror = "2.0.12" +[dev-dependencies] +assay = "0.1.1" +tempfile = "3.19.1" diff --git a/cruct/src/lib.rs b/cruct/src/lib.rs index 9987a62..2a84c81 100644 --- a/cruct/src/lib.rs +++ b/cruct/src/lib.rs @@ -4,16 +4,20 @@ //! with compile-time validation and type safety. //! //! # Example -//! ```ignore +//! ``` //! use cruct::cruct; //! -//! #[cruct(path = "config.toml")] +//! #[cruct(load_config(path = "tests/fixtures/test_config.toml"))] //! struct Config { +//! #[field(default = 8080)] //! http_port: u16, //! database_url: String, //! } //! -//! let config = Config::load()?; +//! let cfg = Config::loader() +//! .with_config() +//! .load() +//! .unwrap(); //! ``` pub use cruct_proc::cruct; diff --git a/cruct/tests/e2e/cli_overrides.rs b/cruct/tests/e2e/cli_overrides.rs new file mode 100644 index 0000000..3a25afb --- /dev/null +++ b/cruct/tests/e2e/cli_overrides.rs @@ -0,0 +1,22 @@ +use assay::assay; +use cruct::cruct; + +#[assay( + include = ["tests/fixtures/integration/cli.toml"], +)] +fn cli_override_takes_highest_priority() { + #[cruct(load_config(path = "tests/fixtures/basic.toml"))] + #[derive(Debug)] + struct C { + #[field(default = 1, arg_override = "number")] + n: u32, + } + + let c = C::loader() + .with_config() + .with_cli(0) + .load() + .unwrap(); + + assert_eq!(c.n, 999); +} diff --git a/cruct/tests/e2e/default_values.rs b/cruct/tests/e2e/default_values.rs new file mode 100644 index 0000000..53e6793 --- /dev/null +++ b/cruct/tests/e2e/default_values.rs @@ -0,0 +1,154 @@ +use assay::assay; +use cruct::cruct; + +#[assay( + include = ["tests/fixtures/e2e/basic.toml"], + env = [ + ("MY_ENV", "world"), + ] +)] +fn default_and_env_precedence() { + #[cruct(load_config(path = "tests/fixtures/e2e/basic.toml"))] + #[derive(Debug)] + struct E2E { + #[field(name = "missing", env_override = "MY_ENV", default = "hello".to_string())] + v: String, + } + + let v1 = E2E::loader() + .with_config() + .load() + .unwrap(); + assert_eq!(v1.v, "world"); + + unsafe { + std::env::remove_var("MY_ENV"); + } + + let v2 = E2E::loader() + .with_config() + .load() + .unwrap(); + assert_eq!(v2.v, "hello"); +} + +#[test] +fn test_string_default() { + #[cruct(load_config(path = "tests/fixtures/e2e/defaults/value.toml"))] + #[derive(Debug, PartialEq)] + struct TestStringDefault { + #[field(default = "literal_default".to_string())] + field: String, + } + + let string_config = TestStringDefault::loader() + .with_config() + .load() + .unwrap(); + + assert_eq!(string_config.field, "literal_default"); +} + +#[test] +fn test_fn_default() { + fn get_default_from_fn() -> String { + "function_default".to_string() + } + + #[cruct(load_config(path = "tests/fixtures/e2e/defaults/value.toml"))] + #[derive(Debug, PartialEq)] + struct TestFnDefault { + #[field(default = get_default_from_fn())] + field: String, + } + + let fn_config = TestFnDefault::loader() + .with_config() + .load() + .unwrap(); + assert_eq!(fn_config.field, "function_default"); +} + +#[test] +fn test_expr_default() { + #[cruct(load_config(path = "tests/fixtures/e2e/defaults/value.toml"))] + #[derive(Debug, PartialEq)] + struct TestExprDefault { + #[field(default = format!("{}-{}", "expr", 42))] + field: String, + } + + let expr_config = TestExprDefault::loader() + .with_config() + .load() + .unwrap(); + assert_eq!(expr_config.field, "expr-42"); +} + +#[test] +fn test_numeric_default() { + #[cruct(load_config(path = "tests/fixtures/e2e/defaults/value.toml"))] + #[derive(Debug, PartialEq)] + struct TestNumericDefault { + #[field(default = 9000)] + port: u16, + } + + let numeric_config = TestNumericDefault::loader() + .with_config() + .load() + .unwrap(); + assert_eq!(numeric_config.port, 9000); +} + +#[test] +fn test_float_default() { + #[cruct(load_config(path = "tests/fixtures/e2e/defaults/value.toml"))] + #[derive(Debug, PartialEq)] + struct TestFloat { + #[field(default = std::f64::consts::PI)] + value: f64, + } + + let config = TestFloat::loader() + .with_config() + .load() + .unwrap(); + + assert_eq!(config.value, std::f64::consts::PI); +} + +#[test] +#[allow(clippy::bool_assert_comparison)] +fn test_boolean_default() { + #[cruct(load_config(path = "tests/fixtures/e2e/defaults/value.toml"))] + #[derive(Debug, PartialEq)] + struct TestBoolean { + #[field(default = false)] + value: bool, + } + + let config = TestBoolean::loader() + .with_config() + .load() + .unwrap(); + + assert_eq!(config.value, false); +} + +#[test] +fn test_char_default() { + #[cruct(load_config(path = "tests/fixtures/e2e/defaults/value.toml"))] + #[derive(Debug, PartialEq)] + struct TestChar { + #[field(default = 'a')] + value: char, + } + + let config = TestChar::loader() + .with_config() + .load() + .unwrap(); + + assert_eq!(config.value, 'a'); +} diff --git a/cruct/tests/e2e/env_overrides.rs b/cruct/tests/e2e/env_overrides.rs new file mode 100644 index 0000000..3fb5837 --- /dev/null +++ b/cruct/tests/e2e/env_overrides.rs @@ -0,0 +1,24 @@ +use assay::assay; +use cruct::cruct; + +#[assay( + include = ["tests/fixtures/test_config.toml"], + env = [ + ("TEST_HTTP_PORT", "9999") + ], +)] +fn test_env_override() { + #[cruct(load_config(path = "tests/fixtures/test_config.toml"))] + #[derive(Debug, PartialEq)] + struct TestEnv { + #[field(env_override = "TEST_HTTP_PORT")] + http_port: u16, + } + + let config = TestEnv::loader() + .with_config() + .load() + .unwrap(); + + assert_eq!(config.http_port, 9999); +} diff --git a/cruct/tests/e2e/mod.rs b/cruct/tests/e2e/mod.rs new file mode 100644 index 0000000..71ec11f --- /dev/null +++ b/cruct/tests/e2e/mod.rs @@ -0,0 +1,5 @@ +// TODO: figure out how to run this test +// mod cli_overrides; +mod default_values; +mod env_overrides; +mod nested_structs; diff --git a/cruct/tests/e2e/nested_structs.rs b/cruct/tests/e2e/nested_structs.rs new file mode 100644 index 0000000..f9fad3d --- /dev/null +++ b/cruct/tests/e2e/nested_structs.rs @@ -0,0 +1,36 @@ +use assay::assay; +use cruct::{ConfigValue, FromConfigValue, ParserError, cruct}; + +#[assay( + include = ["tests/fixtures/e2e/nested.toml"], +)] +fn nested_structs_load_correctly() { + #[cruct(load_config(path = "tests/fixtures/e2e/nested.toml"))] + #[derive(Debug)] + struct Outer { + inner: Inner, + } + + #[cruct] + #[derive(Debug)] + struct Inner { + #[field(default = 100)] + value: u32, + } + + impl FromConfigValue for Inner { + fn from_config_value(value: &ConfigValue) -> Result { + Inner::load_from(value) + } + } + + let o = Outer::loader() + .with_config() + .load() + .unwrap(); + assert_eq!( + o.inner + .value, + 42 + ); +} diff --git a/cruct/tests/fixtures/concurrency.toml b/cruct/tests/fixtures/concurrency.toml new file mode 100644 index 0000000..215f050 --- /dev/null +++ b/cruct/tests/fixtures/concurrency.toml @@ -0,0 +1 @@ +value = 123 diff --git a/cruct/tests/fixtures/e2e/basic.toml b/cruct/tests/fixtures/e2e/basic.toml new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/cruct/tests/fixtures/e2e/basic.toml @@ -0,0 +1 @@ + diff --git a/cruct/tests/fixtures/e2e/defaults/value.toml b/cruct/tests/fixtures/e2e/defaults/value.toml new file mode 100644 index 0000000..e69de29 diff --git a/cruct/tests/fixtures/e2e/nested.toml b/cruct/tests/fixtures/e2e/nested.toml new file mode 100644 index 0000000..0ff284d --- /dev/null +++ b/cruct/tests/fixtures/e2e/nested.toml @@ -0,0 +1,2 @@ +[inner] +value = 42 diff --git a/cruct/tests/fixtures/integration/basic.toml b/cruct/tests/fixtures/integration/basic.toml new file mode 100644 index 0000000..ec1e1e8 --- /dev/null +++ b/cruct/tests/fixtures/integration/basic.toml @@ -0,0 +1,2 @@ +name = "from_file" +count = 100 diff --git a/cruct/tests/fixtures/integration/invalid.toml b/cruct/tests/fixtures/integration/invalid.toml new file mode 100644 index 0000000..f6d220f --- /dev/null +++ b/cruct/tests/fixtures/integration/invalid.toml @@ -0,0 +1 @@ +a = diff --git a/cruct/tests/fixtures/integration/nested.toml b/cruct/tests/fixtures/integration/nested.toml new file mode 100644 index 0000000..37bdb36 --- /dev/null +++ b/cruct/tests/fixtures/integration/nested.toml @@ -0,0 +1 @@ +x = 20 diff --git a/cruct/tests/fixtures/test_config.toml b/cruct/tests/fixtures/test_config.toml index 5b9c3c0..a4df18c 100644 --- a/cruct/tests/fixtures/test_config.toml +++ b/cruct/tests/fixtures/test_config.toml @@ -1,3 +1,8 @@ +name = "file_name" +count = 123 + +database_url = "postgres://user:password@localhost/dbname" + else = "toml value" http_port = 8080 diff --git a/cruct/tests/integration/mod.rs b/cruct/tests/integration/mod.rs new file mode 100644 index 0000000..c402c3e --- /dev/null +++ b/cruct/tests/integration/mod.rs @@ -0,0 +1,10 @@ +mod test_arrays; +mod test_case_insensitive; +mod test_concurrency; +mod test_error_cases; +mod test_loader_flow; +mod test_loading; +mod test_macro_api; +mod test_missing_field; +mod test_nested_structures; +// mod test_scalar_types; diff --git a/cruct/tests/integration/test_arrays.rs b/cruct/tests/integration/test_arrays.rs new file mode 100644 index 0000000..86421f3 --- /dev/null +++ b/cruct/tests/integration/test_arrays.rs @@ -0,0 +1,116 @@ +use assay::assay; +use cruct::cruct; + +#[assay( + include = [ "tests/fixtures/test_config.toml" ] +)] +fn test_array_toml() { + #[cruct(load_config(path = "tests/fixtures/test_config.toml"))] + #[derive(Debug, PartialEq)] + struct ArrayToml { + items: Vec, + numbers: Vec, + } + + let config = ArrayToml::loader() + .with_config() + .load() + .unwrap(); + + assert_eq!(config.items, vec!["a", "b", "c"]); + assert_eq!(config.numbers, vec![1, 2, 3]); +} + +#[assay( + include = [ "tests/fixtures/test_config.json" ] +)] +fn test_array_json() { + #[cruct(load_config(path = "tests/fixtures/test_config.json"))] + #[derive(Debug, PartialEq)] + struct ArrayJson { + items: Vec, + numbers: Vec, + } + + let config = ArrayJson::loader() + .with_config() + .load() + .unwrap(); + + assert_eq!(config.items, vec!["x", "y", "z"]); + assert_eq!(config.numbers, vec![10, 20, 30]); +} + +#[assay( + include = [ "tests/fixtures/test_config.yml" ] +)] +fn test_array_yaml() { + #[cruct(load_config(path = "tests/fixtures/test_config.yml"))] + #[derive(Debug, PartialEq)] + struct ArrayYaml { + items: Vec, + numbers: Vec, + } + + let config = ArrayYaml::loader() + .with_config() + .load() + .unwrap(); + + assert_eq!(config.items, vec!["alpha", "beta", "gamma"]); + assert_eq!(config.numbers, vec![100, 200, 300]); +} + +#[assay( + include = [ "tests/fixtures/test_config.toml" ] +)] +fn test_nested_array_toml() { + #[cruct(load_config(path = "tests/fixtures/test_config.toml"))] + #[derive(Debug, PartialEq)] + struct NestedArrayToml { + matrix: Vec>, + } + + let cfg = NestedArrayToml::loader() + .with_config() + .load() + .unwrap(); + + assert_eq!(cfg.matrix, vec![vec![1, 2], vec![3, 4]]); +} + +#[assay( + include = [ "tests/fixtures/test_config.json" ] +)] +fn test_nested_array_json() { + #[cruct(load_config(path = "tests/fixtures/test_config.json", format = "Json"))] + #[derive(Debug, PartialEq)] + struct NestedArrayJson { + matrix: Vec>, + } + + let cfg = NestedArrayJson::loader() + .with_config() + .load() + .unwrap(); + + assert_eq!(cfg.matrix, vec![vec![1, 2], vec![3, 4]]); +} + +#[assay( + include = [ "tests/fixtures/test_config.yml" ] +)] +fn test_nested_array_yaml() { + #[cruct(load_config(path = "tests/fixtures/test_config.yml", format = "Yml"))] + #[derive(Debug, PartialEq)] + struct NestedArrayYaml { + matrix: Vec>, + } + + let cfg = NestedArrayYaml::loader() + .with_config() + .load() + .unwrap(); + + assert_eq!(cfg.matrix, vec![vec![1, 2], vec![3, 4]]); +} diff --git a/cruct/tests/integration/test_case_insensitive.rs b/cruct/tests/integration/test_case_insensitive.rs new file mode 100644 index 0000000..6145f7e --- /dev/null +++ b/cruct/tests/integration/test_case_insensitive.rs @@ -0,0 +1,21 @@ +use assay::assay; +use cruct::cruct; + +#[assay( + include = ["tests/fixtures/test_config.toml"], +)] +fn test_case_insensitive() { + #[cruct(load_config(path = "tests/fixtures/test_config.toml"))] + #[derive(Debug, PartialEq)] + struct TestInsensitive { + #[field(name = "HTTP_PORT", insensitive = true)] + http_port: u16, + } + + let config = TestInsensitive::loader() + .with_config() + .load() + .unwrap(); + + assert_eq!(config.http_port, 8080); +} diff --git a/cruct/tests/integration/test_concurrency.rs b/cruct/tests/integration/test_concurrency.rs new file mode 100644 index 0000000..245dd9f --- /dev/null +++ b/cruct/tests/integration/test_concurrency.rs @@ -0,0 +1,57 @@ +use std::io::Write; +use std::sync::Arc; +use std::thread::spawn; + +use assay::assay; +use cruct::{Parser, cruct}; +use cruct_shared::parser::TomlParser; +use tempfile::NamedTempFile; + +#[assay( + include = ["tests/fixtures/concurrency.toml"], +)] +fn config_loader_thread_safe() { + #[allow(unused)] + #[cruct(load_config(path = "tests/fixtures/concurrency.toml"))] + struct Config { + value: u32, + } + + let loader = Config::loader(); + spawn(move || { + let _ = loader + .with_config() + .load() + .unwrap(); + }) + .join() + .unwrap(); +} + +#[test] +fn parser_thread_safe() { + let parser = Arc::new(TomlParser); + let handles: Vec<_> = (0..10) + .map(|i| { + let parser = parser.clone(); + spawn(move || { + let mut file = NamedTempFile::new().unwrap(); + writeln!(file, "value = {}", i).unwrap(); + let path = file + .path() + .to_str() + .unwrap(); + + parser + .load(path) + .unwrap() + }) + }) + .collect(); + + for handle in handles { + handle + .join() + .unwrap(); + } +} diff --git a/cruct/tests/integration/test_error_cases.rs b/cruct/tests/integration/test_error_cases.rs new file mode 100644 index 0000000..858bbb1 --- /dev/null +++ b/cruct/tests/integration/test_error_cases.rs @@ -0,0 +1,60 @@ +use assay::assay; +use cruct::cruct; + +#[cfg(unix)] +#[test] +fn missing_file_returns_error_unix() { + #[cruct(load_config(path = "tests/fixtures/does_not_exist.toml"))] + #[derive(Debug)] + #[allow(dead_code)] + struct E { + a: String, + } + + let err = E::loader() + .with_config() + .load() + .unwrap_err(); + + assert_eq!(err.to_string(), "No such file or directory (os error 2)"); +} + +#[cfg(windows)] +#[test] +fn missing_file_returns_error_windows() { + #[cruct(load_config(path = "tests/fixtures/does_not_exist.toml"))] + #[derive(Debug)] + #[allow(dead_code)] + struct E { + a: String, + } + + let err = E::loader() + .with_config() + .load() + .unwrap_err(); + + assert_eq!(err.to_string(), "The system cannot find the file specified. (os error 2)"); +} + +#[assay( + include = ["tests/fixtures/integration/invalid.toml"], +)] +fn invalid_toml_syntax_error() { + #[cruct(load_config(path = "tests/fixtures/integration/invalid.toml"))] + #[derive(Debug)] + #[allow(dead_code)] + struct F { + a: String, + } + + let err = F::loader() + .with_config() + .load() + .unwrap_err(); + + assert!( + err.to_string() + .contains("TOML parse error") + ); +} diff --git a/cruct/tests/integration/test_loader_flow.rs b/cruct/tests/integration/test_loader_flow.rs new file mode 100644 index 0000000..e646b72 --- /dev/null +++ b/cruct/tests/integration/test_loader_flow.rs @@ -0,0 +1,67 @@ +use assay::assay; +use cruct::cruct; + +#[assay( + include = ["tests/fixtures/integration/basic.toml"], +)] +fn loads_values_from_toml_and_env() { + #[cruct(load_config(path = "tests/fixtures/integration/basic.toml"))] + #[derive(Debug)] + struct Cfg { + #[field(env_override = "CFG_NAME", default = "fallback".to_string())] + name: String, + #[field(default = 100)] + count: u32, + } + + // Fixture TOML has `name = "from_file"` and no `count` key. + unsafe { + std::env::remove_var("CFG_NAME"); + } + + let cfg = Cfg::loader() + .with_config() + .load() + .unwrap(); + + assert_eq!(cfg.name, "from_file"); + assert_eq!(cfg.count, 100); + + // Now override via env + unsafe { + std::env::set_var("CFG_NAME", "env_name"); + } + + let cfg2 = Cfg::loader() + .with_config() + .load() + .unwrap(); + + assert_eq!(cfg2.name, "env_name"); +} + +#[assay( + include = [ + "tests/fixtures/integration/nested.toml", + "tests/fixtures/integration/basic.toml" + ], +)] +fn loader_respects_priority_order() { + #[cruct( + load_config(path = "tests/fixtures/integration/basic.toml", priority = 5), + load_config(path = "tests/fixtures/integration/nested.toml", priority = 1) + )] + #[derive(Debug)] + struct P { + #[field(default = 10)] + x: u32, + } + + // nested.toml has x=20, basic.toml has x not set => priority 1 applies first + let p = P::loader() + .with_config() + .load() + .unwrap(); + + assert_eq!(p.x, 20); +} diff --git a/cruct/tests/integration/test_loading.rs b/cruct/tests/integration/test_loading.rs new file mode 100644 index 0000000..60e004f --- /dev/null +++ b/cruct/tests/integration/test_loading.rs @@ -0,0 +1,74 @@ +use assay::assay; +use cruct::cruct; + +#[assay( + include = [ + "tests/fixtures/test_config.toml", + "tests/fixtures/test_config.json", + ] +)] +fn test_toml_loading() { + #[cruct( + load_config(path = "tests/fixtures/test_config.toml", format = "Toml", priority = 0), + load_config(path = "tests/fixtures/test_config.json", format = "Json", priority = 1) + )] + #[derive(Debug, PartialEq)] + struct TestToml { + #[field(name = "else")] + something: String, + http_port: u16, + } + let config = TestToml::loader() + .with_config() + .load() + .unwrap(); + + assert_eq!(config.something, "toml value"); + assert_eq!(config.http_port, 8080); +} + +#[assay( + include = [ + "tests/fixtures/test_config.json", + ] +)] +fn test_json_loading() { + #[cruct(load_config(path = "./tests/fixtures/test_config.json", format = "Json"))] + #[derive(Debug, PartialEq)] + struct TestJson { + #[field(name = "else")] + something: String, + http_port: u16, + } + + let config = TestJson::loader() + .with_config() + .load() + .unwrap(); + + assert_eq!(config.something, "json value"); + assert_eq!(config.http_port, 3000); +} + +#[assay( + include = [ + "tests/fixtures/test_config.yml" + ] +)] +fn test_yaml_loading() { + #[cruct(load_config(path = "./tests/fixtures/test_config.yml", format = "Yml"))] + #[derive(Debug, PartialEq)] + struct TestYaml { + #[field(name = "else")] + something: String, + http_port: u16, + } + + let config = TestYaml::loader() + .with_config() + .load() + .unwrap(); + + assert_eq!(config.something, "yaml value"); + assert_eq!(config.http_port, 4000); +} diff --git a/cruct/tests/integration/test_macro_api.rs b/cruct/tests/integration/test_macro_api.rs new file mode 100644 index 0000000..2170996 --- /dev/null +++ b/cruct/tests/integration/test_macro_api.rs @@ -0,0 +1,16 @@ +use assay::assay; +use cruct::cruct; + +#[assay( + include = ["tests/fixtures/integration/basic.toml"], +)] +fn simple_derive_generates_loader() { + #[cruct(load_config(path = "tests/fixtures/integration/basic.toml"))] + #[derive(Debug)] + #[allow(dead_code)] + struct S { + a: String, + } + + let _ = S::loader(); +} diff --git a/cruct/tests/integration/test_missing_field.rs b/cruct/tests/integration/test_missing_field.rs new file mode 100644 index 0000000..b637e95 --- /dev/null +++ b/cruct/tests/integration/test_missing_field.rs @@ -0,0 +1,27 @@ +use assay::assay; +use cruct::{ParserError, cruct}; + +#[assay( + include = ["tests/fixtures/test_config.toml"], +)] +fn missing_field_errors() { + #[cruct(load_config(path = "tests/fixtures/test_config.toml"))] + #[derive(Debug)] + #[allow(dead_code)] + struct MissingField { + present: String, + absent: u8, + } + + let result = MissingField::loader() + .with_cli(0) + .with_config() + .load(); + + assert!(result.is_err()); + if let Err(e) = result { + let field = String::from("present"); + let expected = ParserError::MissingField(field).to_string(); + assert_eq!(e.to_string(), expected); + } +} diff --git a/cruct/tests/integration/test_nested_structures.rs b/cruct/tests/integration/test_nested_structures.rs new file mode 100644 index 0000000..7e6dd77 --- /dev/null +++ b/cruct/tests/integration/test_nested_structures.rs @@ -0,0 +1,42 @@ +use assay::assay; +use cruct::{ConfigValue, FromConfigValue, ParserError, cruct}; + +#[assay( + include = ["tests/fixtures/test_config.toml"], +)] +fn test_nested_struct_toml() { + #[cruct(load_config(path = "tests/fixtures/test_config.toml"))] + #[derive(Debug, PartialEq)] + struct SomeStruct { + items: Vec, + numbers: Vec, + } + + impl FromConfigValue for SomeStruct { + fn from_config_value(value: &ConfigValue) -> Result { + SomeStruct::load_from(value) + } + } + + #[cruct(load_config(path = "tests/fixtures/test_config.toml"))] + #[derive(Debug, PartialEq)] + struct NestedConfig { + http_port: u16, + nested: SomeStruct, + } + + let cfg = NestedConfig::loader() + .with_config() + .load() + .unwrap(); + + assert_eq!(cfg.http_port, 8080); + + assert_eq!( + cfg.nested, + SomeStruct { + items: vec!["foo".into(), "bar".into()], + numbers: vec![42, 99], + } + ); +} diff --git a/cruct/tests/test.rs b/cruct/tests/test.rs index 7f31ac1..b944a92 100644 --- a/cruct/tests/test.rs +++ b/cruct/tests/test.rs @@ -1,311 +1,2 @@ -use cruct::{ConfigValue, FromConfigValue, ParserError, cruct}; - -#[test] -fn test_toml_loading() { - #[cruct(path = "./tests/fixtures/test_config.toml", format = "Toml")] - #[derive(Debug, PartialEq)] - struct TestToml { - #[field(name = "else")] - something: String, - http_port: u16, - } - let config = TestToml::load().unwrap(); - - assert_eq!(config.something, "toml value"); - assert_eq!(config.http_port, 8080); -} - -#[test] -fn test_json_loading() { - #[cruct(path = "./tests/fixtures/test_config.json", format = "Json")] - #[derive(Debug, PartialEq)] - struct TestJson { - #[field(name = "else")] - something: String, - http_port: u16, - } - - let config = TestJson::load().unwrap(); - assert_eq!(config.something, "json value"); - assert_eq!(config.http_port, 3000); -} - -#[test] -fn test_yaml_loading() { - #[cruct(path = "./tests/fixtures/test_config.yml", format = "Yml")] - #[derive(Debug, PartialEq)] - struct TestYaml { - #[field(name = "else")] - something: String, - http_port: u16, - } - - let config = TestYaml::load().unwrap(); - assert_eq!(config.something, "yaml value"); - assert_eq!(config.http_port, 4000); -} - -#[test] -fn test_default_values() { - #[cruct(path = "./tests/fixtures/test_config.toml")] - #[derive(Debug)] - struct TestDefault { - #[field(name = "missing_field", default = "default value".to_string())] - field: String, - } - - let config = TestDefault::load().unwrap(); - assert_eq!(config.field, "default value"); -} - -#[test] -fn test_missing_field() { - #[cruct(path = "./tests/fixtures/test_config.toml")] - #[derive(Debug)] - #[allow(dead_code)] - pub struct TestMissing { - missing_field: String, - } - - let result = TestMissing::load(); - match result { - Err(cruct_shared::parser::ParserError::MissingField(field)) => { - assert_eq!(field, "missing_field"); - }, - Ok(_) => panic!("Expected MissingField error"), - Err(e) => panic!("Unexpected error: {:?}", e), - } -} - -#[test] -fn test_env_override() { - #[cruct(path = "./tests/fixtures/test_config.toml")] - #[derive(Debug, PartialEq)] - struct TestEnv { - #[field(env_override = "TEST_HTTP_PORT")] - http_port: u16, - } - - unsafe { - std::env::set_var("TEST_HTTP_PORT", "9999"); - } - - let config = TestEnv::load().unwrap(); - assert_eq!(config.http_port, 9999); - - unsafe { - std::env::remove_var("TEST_HTTP_PORT"); - } -} - -#[test] -fn test_case_insensitive() { - #[cruct(path = "./tests/fixtures/test_config.toml")] - #[derive(Debug, PartialEq)] - struct TestInsensitive { - #[field(name = "HTTP_PORT", insensitive = true)] - http_port: u16, - } - - let config = TestInsensitive::load().unwrap(); - assert_eq!(config.http_port, 8080); -} - -fn get_default_from_fn() -> String { - "function_default".to_string() -} - -#[test] -fn test_enhanced_defaults() { - #[cruct(path = "./tests/fixtures/test_config.toml")] - #[derive(Debug, PartialEq)] - struct TestStringDefault { - #[field(default = "literal_default".to_string())] - field: String, - } - - #[cruct(path = "./tests/fixtures/test_config.toml")] - #[derive(Debug, PartialEq)] - struct TestFnDefault { - #[field(default = get_default_from_fn())] - field: String, - } - - #[cruct(path = "./tests/fixtures/test_config.toml")] - #[derive(Debug, PartialEq)] - struct TestExprDefault { - #[field(default = format!("{}-{}", "expr", 42))] - field: String, - } - - #[cruct(path = "./tests/fixtures/test_config.toml")] - #[derive(Debug, PartialEq)] - struct TestNumericDefault { - #[field(default = 9000)] - port: u16, - } - - let string_config = TestStringDefault::load().unwrap(); - assert_eq!(string_config.field, "literal_default"); - - let fn_config = TestFnDefault::load().unwrap(); - assert_eq!(fn_config.field, "function_default"); - - let expr_config = TestExprDefault::load().unwrap(); - assert_eq!(expr_config.field, "expr-42"); - - let numeric_config = TestNumericDefault::load().unwrap(); - assert_eq!(numeric_config.port, 9000); -} - -#[test] -fn test_default_with_environment() { - #[cruct(path = "./tests/fixtures/test_config.toml")] - #[derive(Debug, PartialEq)] - struct TestCombined { - #[field( - name = "missing_field", - env_override = "TEST_DEFAULT_ENV", - default = "base_default".to_string() - )] - field: String, - } - - unsafe { std::env::set_var("TEST_DEFAULT_ENV", "env_value") }; - let config = TestCombined::load().unwrap(); - assert_eq!(config.field, "env_value"); - - unsafe { std::env::remove_var("TEST_DEFAULT_ENV") }; - let config = TestCombined::load().unwrap(); - assert_eq!(config.field, "base_default"); -} - -#[test] -fn test_default_with_type_conversion() { - #[cruct(path = "./tests/fixtures/test_config.toml")] - #[derive(Debug, PartialEq)] - struct TestTypeConversion { - #[field(default = std::f64::consts::PI)] - pi: f64, - - #[field(default = true)] - enabled: bool, - } - - let config = TestTypeConversion::load().unwrap(); - assert_eq!(config.pi, std::f64::consts::PI); - assert_eq!(config.enabled, true); -} - -#[test] -fn test_array_toml() { - #[cruct(path = "./tests/fixtures/test_config.toml")] - #[derive(Debug, PartialEq)] - struct ArrayToml { - items: Vec, - numbers: Vec, - } - - let config = ArrayToml::load().unwrap(); - assert_eq!(config.items, vec!["a", "b", "c"]); - assert_eq!(config.numbers, vec![1, 2, 3]); -} - -#[test] -fn test_array_json() { - #[cruct(path = "./tests/fixtures/test_config.json", format = "Json")] - #[derive(Debug, PartialEq)] - struct ArrayJson { - items: Vec, - numbers: Vec, - } - - let config = ArrayJson::load().unwrap(); - assert_eq!(config.items, vec!["x", "y", "z"]); - assert_eq!(config.numbers, vec![10, 20, 30]); -} - -#[test] -fn test_array_yaml() { - #[cruct(path = "./tests/fixtures/test_config.yml", format = "Yml")] - #[derive(Debug, PartialEq)] - struct ArrayYaml { - items: Vec, - numbers: Vec, - } - - let config = ArrayYaml::load().unwrap(); - assert_eq!(config.items, vec!["alpha", "beta", "gamma"]); - assert_eq!(config.numbers, vec![100, 200, 300]); -} - -#[test] -fn test_nested_array_toml() { - #[cruct(path = "./tests/fixtures/test_config.toml")] - #[derive(Debug, PartialEq)] - struct NestedArrayToml { - matrix: Vec>, - } - - let cfg = NestedArrayToml::load().unwrap(); - assert_eq!(cfg.matrix, vec![vec![1, 2], vec![3, 4]]); -} - -#[test] -fn test_nested_array_json() { - #[cruct(path = "./tests/fixtures/test_config.json", format = "Json")] - #[derive(Debug, PartialEq)] - struct NestedArrayJson { - matrix: Vec>, - } - - let cfg = NestedArrayJson::load().unwrap(); - assert_eq!(cfg.matrix, vec![vec![1, 2], vec![3, 4]]); -} - -#[test] -fn test_nested_array_yaml() { - #[cruct(path = "./tests/fixtures/test_config.yml", format = "Yml")] - #[derive(Debug, PartialEq)] - struct NestedArrayYaml { - matrix: Vec>, - } - - let cfg = NestedArrayYaml::load().unwrap(); - assert_eq!(cfg.matrix, vec![vec![1, 2], vec![3, 4]]); -} - -#[cruct(path = "./tests/fixtures/test_config.toml")] -#[derive(Debug, PartialEq)] -struct SomeStruct { - items: Vec, - numbers: Vec, -} - -impl FromConfigValue for SomeStruct { - fn from_config_value(value: &ConfigValue) -> Result { - SomeStruct::load_from(value) - } -} - -#[cruct(path = "./tests/fixtures/test_config.toml")] -#[derive(Debug, PartialEq)] -struct NestedConfig { - http_port: u16, - nested: SomeStruct, -} - -#[test] -fn test_nested_struct_toml() { - let cfg = NestedConfig::load().unwrap(); - - assert_eq!(cfg.http_port, 8080); - - assert_eq!( - cfg.nested, - SomeStruct { - items: vec!["foo".into(), "bar".into()], - numbers: vec![42, 99], - } - ); -} +mod e2e; +mod integration; diff --git a/cruct_proc/Cargo.toml b/cruct_proc/Cargo.toml index 4ebafd2..149c264 100644 --- a/cruct_proc/Cargo.toml +++ b/cruct_proc/Cargo.toml @@ -3,6 +3,12 @@ name = "cruct_proc" version = "0.1.0" edition = "2024" +[features] +default = ["toml"] +toml = ["cruct_shared/toml"] +yaml = ["cruct_shared/yaml"] +json = ["cruct_shared/json"] + [lib] proc-macro = true diff --git a/cruct_proc/src/generate/fields.rs b/cruct_proc/src/generate/fields.rs index cff588e..186be5d 100644 --- a/cruct_proc/src/generate/fields.rs +++ b/cruct_proc/src/generate/fields.rs @@ -4,6 +4,21 @@ use syn::{Ident, Type}; use crate::parse::FieldParams; +/// Generates code to initialize a field based on configuration sources. +/// +/// This function constructs a token stream that initializes a field by checking +/// values from multiple prioritized configuration sources: command line +/// arguments, environment variables, and configuration files. If a value is not +/// found in any of these sources, it either uses a default value (if provided) +/// or throws an error for missing configuration. +/// +/// * `field`: Metadata about the field being initialized, including its +/// override options, default value, and case sensitivity. +/// * `field_ident`: The identifier for the field in the generated code. +/// * `config_key`: The key used to look up the field's value in the +/// configuration sources. +/// * `field_type`: The expected type of the field, which is used for parsing +/// the configuration value. pub fn generate_field_initialization( field: &FieldParams, field_ident: &Ident, @@ -22,6 +37,23 @@ pub fn generate_field_initialization( }) .unwrap_or_else(|| quote! { None }); + let arg_check = field + .arg_override + .as_ref() + .map(|flag| { + quote! { + std::env::args() + .skip(1) + .find_map(|arg| { + let prefix = concat!("--", #flag, "="); + + arg.strip_prefix(prefix) + .map(|v| cruct_shared::parser::ConfigValue::Value(v.to_string())) + }) + } + }) + .unwrap_or_else(|| quote! { None }); + let config_lookup = if field.insensitive { quote! { section.iter() @@ -34,8 +66,10 @@ pub fn generate_field_initialization( } }; + // Priority: CLI arg override → env_override → config file lookup let value_source = quote! { - #env_check + #arg_check + .or_else(|| #env_check) .or_else(|| #config_lookup) }; diff --git a/cruct_proc/src/generate/impl_block.rs b/cruct_proc/src/generate/impl_block.rs index 7f25109..99002a9 100644 --- a/cruct_proc/src/generate/impl_block.rs +++ b/cruct_proc/src/generate/impl_block.rs @@ -1,43 +1,25 @@ use cruct_shared::FileFormat; -use proc_macro2::TokenStream; +use proc_macro2::{Span, TokenStream}; use quote::quote; -use syn::Ident; +use syn::{Ident, LitStr}; use crate::generate::generate_field_initialization; use crate::parse::{FieldParams, MacroParams, StructField}; +/// Generates an implementation block for a given struct to handle configuration +/// loading. +/// +/// # Arguments +/// * `struct_name`: The name of the struct for which the implementation block +/// is being created. +/// * `params`: Macro parameters containing configuration information. +/// * `fields`: A list of fields in the struct, along with their metadata. pub fn generate_impl_block( struct_name: &Ident, params: &MacroParams, fields: &[StructField], ) -> TokenStream { - let path = ¶ms.path; - let format_match = match ¶ms.format { - Some(file_format) => { - let variant = match file_format { - FileFormat::Json => quote! { cruct_shared::FileFormat::Json }, - FileFormat::Toml => quote! { cruct_shared::FileFormat::Toml }, - FileFormat::Yml => quote! { cruct_shared::FileFormat::Yml }, - }; - - quote! { #variant } - }, - None => quote! { /* auto-detect via extension */ - { - use cruct_shared::{get_parser_by_extension, ParserError}; - let ext = std::path::Path::new(#path) - .extension() - .and_then(|s| s.to_str()) - .map(|s| s.to_lowercase()); - let parser = get_parser_by_extension(ext.as_deref().unwrap_or_default()) - .ok_or_else(|| ParserError::InvalidFileFormat( - ext.unwrap_or_else(|| "unknown".into()) - ))?; - - parser.format() - } - }, - }; + let loader_name = Ident::new(&format!("{}Loader", struct_name), struct_name.span()); let field_inits = fields .iter() @@ -53,34 +35,77 @@ pub fn generate_impl_block( .unwrap_or(&field.name); let default_params = FieldParams::default(); - let params_ref: &FieldParams = field + let params_ref = field .params .as_ref() .unwrap_or(&default_params); - generate_field_initialization(params_ref, field_ident, config_key, &field.ty) }); + let config_adds = params + .configs + .iter() + .map(|cfg| { + let path_lit = LitStr::new(&cfg.path, Span::call_site()); + let format_ts = match &cfg.format { + #[cfg(feature = "json")] + Some(FileFormat::Json) => quote! { Some(cruct_shared::FileFormat::Json) }, + + #[cfg(feature = "toml")] + Some(FileFormat::Toml) => quote! { Some(cruct_shared::FileFormat::Toml) }, + + #[cfg(feature = "yaml")] + Some(FileFormat::Yml) => quote! { Some(cruct_shared::FileFormat::Yml) }, + + None => quote! { None }, + }; + quote! { + self.builder = self.builder.add_source( + cruct_shared::ConfigFileSource::new(#path_lit, #format_ts) + ); + } + }); + quote! { + pub struct #loader_name { + builder: cruct_shared::ConfigBuilder, + } + impl #struct_name { - pub fn load() -> Result { - use cruct_shared::{FileFormat, ParserError, get_parser_by_extension}; + pub fn loader() -> #loader_name { + #loader_name { + builder: cruct_shared::ConfigBuilder::new() + } + } + } - let format: FileFormat = #format_match; - let parser = get_parser_by_extension(&format.to_string()) - .ok_or_else(|| ParserError::InvalidFileFormat(format.to_string()))?; - let config = parser.load(#path)?; + impl #loader_name { + pub fn with_cli(mut self, priority: u8) -> Self { + self.builder = self.builder.add_source(cruct_shared::CliSource::new(priority)); + self + } - Self::load_from(&config) + pub fn with_config(mut self) -> Self { + #(#config_adds)* + self } - pub fn load_from(config: &cruct_shared::ConfigValue) -> Result { + pub fn load(self) -> Result<#struct_name, cruct_shared::ParserError> { + let cfg_val = self.builder.load()?; + #struct_name::load_from(&cfg_val) + } + } + + impl #struct_name { + pub fn load_from( + config: &cruct_shared::ConfigValue + ) -> Result { use cruct_shared::{ConfigValue, ParserError}; let ConfigValue::Section(section) = config else { return Err(ParserError::TypeMismatch { field: "root".into(), - expected: "section".into() + expected: "section".into(), }); }; diff --git a/cruct_proc/src/generate/mod.rs b/cruct_proc/src/generate/mod.rs index 57f6de9..ec8a827 100644 --- a/cruct_proc/src/generate/mod.rs +++ b/cruct_proc/src/generate/mod.rs @@ -1,5 +1,8 @@ pub mod fields; pub mod impl_block; +#[cfg(test)] +mod tests; + pub use fields::generate_field_initialization; pub use impl_block::generate_impl_block; diff --git a/cruct_proc/src/generate/tests/mod.rs b/cruct_proc/src/generate/tests/mod.rs new file mode 100644 index 0000000..f05898a --- /dev/null +++ b/cruct_proc/src/generate/tests/mod.rs @@ -0,0 +1 @@ +mod test_fields; diff --git a/cruct_proc/src/generate/tests/test_fields.rs b/cruct_proc/src/generate/tests/test_fields.rs new file mode 100644 index 0000000..095ed85 --- /dev/null +++ b/cruct_proc/src/generate/tests/test_fields.rs @@ -0,0 +1,38 @@ +use syn::{Ident, Type, parse_quote, parse_str}; + +use crate::generate::generate_field_initialization; +use crate::parse::FieldParams; + +#[test] +fn default_value_generates_correct_initialization() { + let params = FieldParams { + env_override: None, + name: None, + insensitive: false, + default: Some(parse_str("42").unwrap()), + arg_override: None, + }; + let ident: Ident = parse_quote! { bar }; + let ty: Type = parse_quote! { u32 }; + let tokens = generate_field_initialization(¶ms, &ident, "bar", &ty).to_string(); + + assert!(tokens.contains("42")); +} + +#[test] +fn arg_override_generates_correct_lookup() { + let params = FieldParams { + env_override: None, + name: None, + insensitive: false, + default: None, + arg_override: Some("foo".into()), + }; + let ident: Ident = parse_quote! { foo }; + let ty: Type = parse_quote! { String }; + let tokens = generate_field_initialization(¶ms, &ident, "foo", &ty).to_string(); + + // Expect to see args().skip(1).find_map for "--flag=" prefix + assert!(tokens.contains("std :: env :: args () . skip (1) . find_map")); + assert!(tokens.contains("\"--\" , \"foo\" , \"=\"")); +} diff --git a/cruct_proc/src/lib.rs b/cruct_proc/src/lib.rs index d787944..c25ca58 100644 --- a/cruct_proc/src/lib.rs +++ b/cruct_proc/src/lib.rs @@ -14,10 +14,12 @@ mod parse; /// Macro to load configuration files into Rust structs. /// /// # Usage -/// ```ignore -/// #[cruct(path = "config.toml", format = "Toml")] +/// ``` +/// use cruct_proc::cruct; +/// +/// #[cruct(load_config(path = "config.toml", format = "Toml"))] /// struct Config { -/// #[field(name = "http_port")] +/// #[field(name = "http_port", default = 8080)] /// port: u16, /// } /// ``` diff --git a/cruct_proc/src/parse/field_params.rs b/cruct_proc/src/parse/field_params.rs index f27df7a..bad7673 100644 --- a/cruct_proc/src/parse/field_params.rs +++ b/cruct_proc/src/parse/field_params.rs @@ -21,6 +21,9 @@ pub struct FieldParams { /// A default value for the field. pub default: Option, + + /// An argument override for the field, used to set the value + pub arg_override: Option, } impl Parse for FieldParams { @@ -31,6 +34,7 @@ impl Parse for FieldParams { let mut default = None; let mut insensitive = None; let mut env_override = None; + let mut arg_override = None; for param in params { let key = param @@ -51,20 +55,31 @@ impl Parse for FieldParams { env_override = Some(value.value()); }, + ("arg_override", Expr::Lit(ExprLit { lit: Lit::Str(value), .. })) => { + arg_override = Some(value.value()); + }, + ("default", value) => { default = Some(value.clone()); }, - (name @ ("name" | "insensitive" | "env_override"), value) => { + (name @ ("name" | "insensitive" | "env_override" | "arg_override"), value) => { Err(SynError::new_spanned( value, format!( "Invalid value type for '{name}' expected '{}'", match name { + // Do not forget to add new parameters here "name" => "&str", "insensitive" => "bool", + "arg_override" => "&str", "env_override" => "&str", - _ => "", + + &_ => panic!( + "Technically, you should not be able to see this error, but \ + if you do, please let us know. The key that caused this \ + error is: '{name}'." + ), } ), ))? @@ -84,6 +99,7 @@ impl Parse for FieldParams { name, insensitive: insensitive.unwrap_or(false), env_override, + arg_override, default, }) } diff --git a/cruct_proc/src/parse/field_struct.rs b/cruct_proc/src/parse/field_struct.rs index 3c3299a..91705f8 100644 --- a/cruct_proc/src/parse/field_struct.rs +++ b/cruct_proc/src/parse/field_struct.rs @@ -1,5 +1,5 @@ use syn::spanned::Spanned; -use syn::{Attribute, Ident, ItemStruct, Result as SynResult, Type}; +use syn::{Attribute, Error as SynError, Ident, ItemStruct, Result as SynResult, Type}; use super::FieldParams; @@ -10,10 +10,13 @@ pub struct StructField { /// Optional parameters associated with the field, used for resolving /// configuration. pub params: Option, + /// The name of the field as a string. pub name: String, + /// The type of the field. pub ty: Type, + /// The identifier of the field. pub ident: Ident, } @@ -37,28 +40,23 @@ impl StructField { let mut fields = Vec::new(); for field in &item.fields { + let ident = field + .ident + .as_ref() + .ok_or_else(|| SynError::new(field.span(), "Unnamed field not supported"))?; + fields.push(Self { + name: ident.to_string(), + ident: ident.clone(), + ty: field + .ty + .clone(), params: field .attrs .iter() .find(|attr| is_field_attr(attr)) .map(|attr| attr.parse_args::()) .transpose()?, - - name: field - .ident - .as_ref() - .unwrap() - .to_string(), - - ty: field - .ty - .clone(), - - ident: field - .ident - .clone() - .ok_or_else(|| syn::Error::new(field.span(), "Unnamed field not supported"))?, }); } @@ -66,10 +64,27 @@ impl StructField { } } -/// Check if the attribute's path is identified as "field" +/// Check if the attribute's path is identified as "env_override", +/// "arg_override", "name", "insensitive", "default" and "description" +/// - "env_override" is used to override the field value from an environment +/// variable +/// - "arg_override" is used to override the field value from a command line +/// - "name" is used to specify the name of the field in the configuration file +/// - insensitive" is used to specify if the field name should be treated as +/// case-insensitive +/// - description" is a metadata attribute that provides a description of the +/// field fn is_field_attr(attr: &Attribute) -> bool { + let allowed_attrs = + ["env_override", "arg_override", "name", "insensitive", "default", "description", "field"]; + attr.path() - .is_ident("field") + .get_ident() + .is_some_and(|ident| { + allowed_attrs + .iter() + .any(|allowed| ident == allowed) + }) } /// Removes field attributes with the identifier "field" from a struct. diff --git a/cruct_proc/src/parse/macro_params.rs b/cruct_proc/src/parse/macro_params.rs index 3cfa8f8..b8807f2 100644 --- a/cruct_proc/src/parse/macro_params.rs +++ b/cruct_proc/src/parse/macro_params.rs @@ -1,11 +1,15 @@ +use std::cmp::Reverse; + use cruct_shared::FileFormat; use quote::ToTokens; use syn::parse::{Parse, ParseStream}; use syn::punctuated::Punctuated; -use syn::{Error as SynError, Expr, ExprLit, Lit, MetaNameValue, Result as SynResult, Token}; +use syn::{Error as SynError, Expr, ExprLit, Lit, Meta, MetaNameValue, Result as SynResult, Token}; -/// This struct represents a parsed version of the `cruct` macro parameters. -pub struct MacroParams { +use super::ParameterError; + +#[derive(Default)] +pub struct LoadConfig { /// A glob of the path that defines where the macro should be looking for /// that configuration file. /// @@ -15,64 +19,144 @@ pub struct MacroParams { /// Which is the file format that should be used to parse the configuration /// file. pub format: Option, + + /// A priority for the configuration file. The lower the number, the + /// higher the priority. + pub priority: Option, +} + +/// This struct represents a parsed version of the `cruct` macro parameters. +pub struct MacroParams { + /// A vector of `LoadConfig` structs, each representing a configuration + /// file to be loaded. + pub configs: Vec, } impl Parse for MacroParams { fn parse(input: ParseStream) -> SynResult { - let params = Punctuated::::parse_terminated(input)?; + let mut configs = Vec::new(); - let mut path = None; - let mut format = None; + // parse zero or more load_config(...) entries, separated by commas + while !input.is_empty() { + // parse one Meta, expecting a list: load_config(...) + let meta = input.parse::()?; + match meta { + Meta::List(list) + if list + .path + .is_ident("load_config") => + { + // parse inner args as name=value pairs + let pairs: Punctuated = + list.parse_args_with(Punctuated::parse_terminated)?; - for param in params { - let key = param - .path - .to_token_stream() - .to_string(); + let mut cfg = LoadConfig::default(); + for name_value in pairs { + let key = name_value + .path + .get_ident() + .unwrap() + .to_string(); - match (key.as_str(), ¶m.value) { - ("path", Expr::Lit(ExprLit { lit: Lit::Str(value), .. })) => { - path = Some(value.value()); - }, + match key.as_str() { + "path" => match &name_value.value { + Expr::Lit(ExprLit { lit: Lit::Str(lit), .. }) => { + cfg.path = lit.value(); + }, + other => { + return Err(SynError::new_spanned( + other, + ParameterError::InvalidType { + name: "path".to_string(), + expected: "String".to_string(), + found: other + .to_token_stream() + .to_string(), + }, + )); + }, + }, + "format" => match &name_value.value { + Expr::Lit(ExprLit { lit: Lit::Str(lit), .. }) => { + cfg.format = Some( + lit.value() + .parse::() + .map_err(|e| { + SynError::new( + lit.span(), + format!("invalid file format: {}", e), + ) + })?, + ); + }, + other => { + return Err(SynError::new_spanned( + other, + ParameterError::InvalidType { + name: "format".to_string(), + expected: "String".to_string(), + found: other + .to_token_stream() + .to_string(), + }, + )); + }, + }, + "priority" => match &name_value.value { + Expr::Lit(ExprLit { lit: Lit::Int(int_lit), .. }) => { + cfg.priority = Some(int_lit.base10_parse()?); + }, + other => { + return Err(SynError::new_spanned( + other, + ParameterError::InvalidType { + name: "priority".to_string(), + expected: "Integer".to_string(), + found: other + .to_token_stream() + .to_string(), + }, + )); + }, + }, + + other => { + return Err(SynError::new_spanned( + name_value.path, + format!("unknown key '{}' in load_config", other), + )); + }, + } + } + + if cfg + .path + .is_empty() + { + return Err(SynError::new_spanned( + list, + ParameterError::MissingRequired { name: "path".to_string() }, + )); + } - ("format", Expr::Lit(ExprLit { lit: Lit::Str(value), .. })) => { - let ident = value.value(); - format = Some(match ident.as_str() { - "Yml" | "Yaml" => FileFormat::Yml, - "Json" => FileFormat::Json, - "Toml" => FileFormat::Toml, - _ => Err(SynError::new_spanned( - value, - "Expected one of: Yml, Yaml, Json, Toml", - ))?, - }); + configs.push(cfg); + + // consume an optional trailing comma + let _ = input.parse::(); }, - (name @ ("path" | "format"), value) => Err(SynError::new_spanned( - value, - format!( - "Invalid value type for '{name}' expected '{}'", - match name { - "path" => "&str", - "format" => "Json | Toml | Yml | Yaml", - _ => "", - } - ), - ))?, - - (name, _) => Err(SynError::new_spanned( - param, - format!( - "Unknown parameter '{name}'. Known parameters include\n- path: &str\n- \ - format: Json | Toml | Yml" - ), - ))?, - }; + other => { + return Err(SynError::new_spanned( + other, + "expected `load_config(path = ..., format = ..., priority = ...)`", + )); + }, + } } - Ok(Self { - path: path.ok_or(SynError::new(input.span(), "Missing parameter path"))?, - format, - }) + // sort by priority (descending) + configs.sort_by_key(|c| Reverse(c.priority)); + + Ok(MacroParams { configs }) } } diff --git a/cruct_proc/src/parse/mod.rs b/cruct_proc/src/parse/mod.rs index a1c4809..3562698 100644 --- a/cruct_proc/src/parse/mod.rs +++ b/cruct_proc/src/parse/mod.rs @@ -4,6 +4,9 @@ mod field_params; mod field_struct; mod macro_params; +#[cfg(test)] +mod tests; + pub use field_params::FieldParams; pub use field_struct::{StructField, remove_field_attrs}; pub use macro_params::MacroParams; @@ -32,11 +35,4 @@ pub enum ParameterError { /// An identifier for the found type. (not enforced) found: String, }, - - /// This error is used when the macro - #[error( - "Couldn't infer the file type, please specify using `type = ` when invoking the \ - macro" - )] - AmbiguousFileType, } diff --git a/cruct_proc/src/parse/tests/mod.rs b/cruct_proc/src/parse/tests/mod.rs new file mode 100644 index 0000000..3c94280 --- /dev/null +++ b/cruct_proc/src/parse/tests/mod.rs @@ -0,0 +1,3 @@ +mod test_field_params; +mod test_macro_params; +mod test_value_mismatch; diff --git a/cruct_proc/src/parse/tests/test_field_params.rs b/cruct_proc/src/parse/tests/test_field_params.rs new file mode 100644 index 0000000..5b93b7d --- /dev/null +++ b/cruct_proc/src/parse/tests/test_field_params.rs @@ -0,0 +1,67 @@ +use syn::{Result, parse_str}; + +use crate::parse::FieldParams; + +#[test] +fn name_invalid_value() { + let src = r#"name = 1"#; + let params: Result = parse_str(src); + + if let Err(e) = params { + assert_eq!(e.to_string(), "Invalid value type for 'name' expected '&str'".to_string()); + } +} + +#[test] +fn insensitive_invalid_value() { + let src = r#"insensitive = "true""#; + let params: Result = parse_str(src); + + if let Err(e) = params { + assert_eq!( + e.to_string(), + "Invalid value type for 'insensitive' expected 'bool'".to_string() + ); + } +} + +#[test] +fn env_override_invalid_value() { + let src = r#"env_override = 1"#; + let params: Result = parse_str(src); + + if let Err(e) = params { + assert_eq!( + e.to_string(), + "Invalid value type for 'env_override' expected '&str'".to_string() + ); + } +} + +#[test] +fn arg_override_invalid_value() { + let src = r#"arg_override = 1"#; + let params: Result = parse_str(src); + + if let Err(e) = params { + assert_eq!( + e.to_string(), + "Invalid value type for 'arg_override' expected '&str'".to_string() + ); + } +} + +#[test] +fn unknown_key() { + let src = r#"unknown = 1"#; + let params: Result = parse_str(src); + + if let Err(e) = params { + assert_eq!( + e.to_string(), + "Unknown parameter 'unknown'. Known parameters include:\n- name: &str\n- insensitive: \ + bool\n- env_override: &str" + .to_string() + ); + } +} diff --git a/cruct_proc/src/parse/tests/test_macro_params.rs b/cruct_proc/src/parse/tests/test_macro_params.rs new file mode 100644 index 0000000..3c1e764 --- /dev/null +++ b/cruct_proc/src/parse/tests/test_macro_params.rs @@ -0,0 +1,114 @@ +use syn::{Result, parse_str}; + +use crate::parse::MacroParams; + +#[test] +fn parse_single_load_config() { + let src = r#"load_config(path = "a.toml", format = "Toml", priority = 5)"#; + let params: MacroParams = parse_str(src).unwrap(); + assert_eq!( + params + .configs + .len(), + 1 + ); + + let cfg = ¶ms.configs[0]; + assert_eq!(cfg.path, "a.toml"); + assert_eq!( + cfg.format + .unwrap() + .to_string(), + "toml" + ); + assert_eq!( + cfg.priority + .unwrap(), + 5 + ); +} + +#[test] +fn load_config_without_required_parameter() { + let src = r#"load_config()"#; + let params: Result = parse_str(src); + + if let Err(e) = params { + assert_eq!(e.to_string(), "Missing required parameter 'path'".to_string()); + } +} + +#[test] +fn load_config_with_unknown_key() { + let src = r#"load_config(unknown_key = "value")"#; + let params: Result = parse_str(src); + + if let Err(e) = params { + assert_eq!(e.to_string(), "unknown key 'unknown_key' in load_config".to_string()); + } +} + +#[test] +fn multiple_load_configs() { + let src = r#" + load_config(path = "a.toml", format = "Toml", priority = 5), + load_config(path = "b.json", format = "Json") + "#; + let params: MacroParams = parse_str(src).unwrap(); + + assert_eq!( + params + .configs + .len(), + 2 + ); + + let cfg1 = ¶ms.configs[0]; + assert_eq!(cfg1.path, "a.toml"); + assert_eq!( + cfg1.format + .unwrap() + .to_string(), + "toml" + ); + assert_eq!( + cfg1.priority + .unwrap(), + 5 + ); + + let cfg2 = ¶ms.configs[1]; + assert_eq!(cfg2.path, "b.json"); + assert_eq!( + cfg2.format + .unwrap() + .to_string(), + "json" + ); +} + +#[test] +fn parse_invalid_macro_params() { + let src = r#"asd"#; + let params: Result = parse_str(src); + + if let Err(e) = params { + assert_eq!( + e.to_string(), + "expected `load_config(path = ..., format = ..., priority = ...)`".to_string() + ); + } +} + +#[test] +fn parse_invalid_file_format() { + let src = r#"load_config(format = "xml")"#; + let params: Result = parse_str(src); + + if let Err(e) = params { + assert_eq!( + e.to_string(), + "invalid file format: 'xml' is not a valid file format".to_string() + ); + } +} diff --git a/cruct_proc/src/parse/tests/test_value_mismatch.rs b/cruct_proc/src/parse/tests/test_value_mismatch.rs new file mode 100644 index 0000000..8ab43d5 --- /dev/null +++ b/cruct_proc/src/parse/tests/test_value_mismatch.rs @@ -0,0 +1,43 @@ +use syn::{Result, parse_str}; + +use crate::parse::MacroParams; + +#[test] +fn path_value_mismatch() { + let src = r#"load_config(path = 123)"#; + let params: Result = parse_str(src); + + if let Err(e) = params { + assert_eq!( + e.to_string(), + "Invalid parameter type for 'path', expected 'String', found '123'".to_string() + ); + } +} + +#[test] +fn format_value_mismatch() { + let src = r#"load_config(format = 123)"#; + let params: Result = parse_str(src); + + if let Err(e) = params { + assert_eq!( + e.to_string(), + "Invalid parameter type for 'format', expected 'String', found '123'".to_string() + ); + } +} + +#[test] +fn priority_value_mismatch() { + let src = r#"load_config(priority = "high")"#; + let params: Result = parse_str(src); + + if let Err(e) = params { + assert_eq!( + e.to_string(), + "Invalid parameter type for 'priority', expected 'Integer', found '\"high\"'" + .to_string() + ); + } +} diff --git a/cruct_shared/Cargo.toml b/cruct_shared/Cargo.toml index 6311e6f..fa52619 100644 --- a/cruct_shared/Cargo.toml +++ b/cruct_shared/Cargo.toml @@ -3,8 +3,19 @@ name = "cruct_shared" version = "0.1.0" edition = "2024" +[features] +default = ["toml"] +yaml = ["dep:jzon"] +toml = ["dep:toml_edit"] +json = ["dep:yaml-rust2"] + [dependencies] thiserror = "2.0.12" -jzon = "0.12.5" -toml_edit = "0.22.24" -yaml-rust2 = "0.10.1" + +# Parsers +jzon = { version = "0.12.5", optional = true } +toml_edit = { version = "0.22.24", optional = true } +yaml-rust2 = { version = "0.10.1", optional = true } + +[dev-dependencies] +tempfile = "3.19.1" diff --git a/cruct_shared/src/lib.rs b/cruct_shared/src/lib.rs index 1debfff..36f8788 100644 --- a/cruct_shared/src/lib.rs +++ b/cruct_shared/src/lib.rs @@ -1,4 +1,5 @@ pub mod parser; +pub mod source; pub use parser::{ ConfigValue, @@ -6,5 +7,7 @@ pub use parser::{ FromConfigValue, Parser, ParserError, - get_parser_by_extension, + YmlParser, + get_parser, }; +pub use source::{CliSource, ConfigBuilder, ConfigFileSource, ConfigSource}; diff --git a/cruct_shared/src/parser/json.rs b/cruct_shared/src/parser/json.rs index ba78bce..877b650 100644 --- a/cruct_shared/src/parser/json.rs +++ b/cruct_shared/src/parser/json.rs @@ -16,10 +16,14 @@ impl Parser for JsonParser { fn load(&self, path: &str) -> Result { let content = read_to_string(path)?; let json = parse(&content)?; + parse_json_value(json) } } +/// Parses a JSON value into a configuration value. +/// +/// * `value`: The `JsonValue` to be parsed. fn parse_json_value(value: JsonValue) -> Result { match value { JsonValue::Object(obj) => { @@ -39,3 +43,76 @@ fn parse_json_value(value: JsonValue) -> Result { _ => Ok(ConfigValue::Value(value.to_string())), } } + +#[cfg(test)] +mod test { + use std::collections::HashMap; + + use jzon::object::Object; + + use super::*; + + #[test] + fn test_parse_json_value_string() { + let value = JsonValue::String("test_string".into()); + let result = parse_json_value(value).unwrap(); + + assert_eq!(result, ConfigValue::Value("test_string".into())); + } + + #[test] + fn test_parse_json_value_integer() { + let value = JsonValue::Number(123.into()); + let result = parse_json_value(value).unwrap(); + + assert_eq!(result, ConfigValue::Value("123".into())); + } + + #[test] + fn test_parse_json_value_float() { + let value = JsonValue::Number(123.45.into()); + let result = parse_json_value(value).unwrap(); + + assert_eq!(result, ConfigValue::Value("123.45".into())); + } + + #[test] + fn test_parse_json_value_boolean() { + let value = JsonValue::Boolean(true); + let result = parse_json_value(value).unwrap(); + + assert_eq!(result, ConfigValue::Value("true".into())); + } + + #[test] + fn test_parse_json_value_object() { + let mut obj = Object::new(); + obj.insert("key", JsonValue::String("value".into())); + + let value = JsonValue::Object(obj); + let result = parse_json_value(value).unwrap(); + + let mut expected_map = HashMap::new(); + expected_map.insert("key".into(), ConfigValue::Value("value".into())); + + assert_eq!(result, ConfigValue::Section(expected_map)); + } + + #[test] + fn test_parse_json_value_array() { + let value = JsonValue::Array(vec![ + JsonValue::String("item1".into()), + JsonValue::String("item2".into()), + ]); + + let result = parse_json_value(value).unwrap(); + + assert_eq!( + result, + ConfigValue::Array(vec![ + ConfigValue::Value("item1".into()), + ConfigValue::Value("item2".into()) + ]) + ); + } +} diff --git a/cruct_shared/src/parser/mod.rs b/cruct_shared/src/parser/mod.rs index c62f275..b3eb47d 100644 --- a/cruct_shared/src/parser/mod.rs +++ b/cruct_shared/src/parser/mod.rs @@ -1,6 +1,7 @@ use std::collections::HashMap; use std::fmt::Display; use std::io::Error as StdError; +use std::str::FromStr; use std::sync::Arc; use jzon::Error as JsonError; @@ -8,33 +9,54 @@ use thiserror::Error as ThisError; use toml_edit::TomlError; use yaml_rust2::ScanError as YmlError; +#[cfg(feature = "json")] mod json; -mod tml; -mod yml; -use json::JsonParser; -use tml::TomlParser; -use yml::YmlParser; +#[cfg(feature = "toml")] +mod toml; -/// Enum representing possible errors during parsing. -/// Utilizes the `thiserror` crate for error handling. +#[cfg(feature = "yaml")] +mod yaml; + +#[cfg(test)] +mod tests; + +#[cfg(feature = "json")] +pub use json::JsonParser; +#[cfg(feature = "toml")] +pub use toml::TomlParser; +#[cfg(feature = "yaml")] +pub use yaml::YmlParser; + +/// Represents various errors that can occur during the parsing process. +/// Leverages the `thiserror` crate for structured and user-friendly error +/// handling. #[derive(Debug, ThisError)] pub enum ParserError { - /// Error indicating that the file format is not supported. + /// Indicates that the provided file format is unsupported. + /// Occurs when trying to parse a file with an invalid or unrecognized + /// extension. #[error("'{0}' is not a valid file format")] InvalidFileFormat(String), - /// Error indicating that the file format is not supported. + /// Triggered when a required field is missing in the configuration file. + /// This happens when an expected field is absent. #[error("Missing required field: {0}")] MissingField(String), - /// Error indicating that the file format is not supported. + /// Occurs when there is a type mismatch in a field within the configuration + /// file. This happens when a field's value type does not match the + /// expected type. #[error("Type mismatch in field '{field}', expected {expected}")] TypeMismatch { field: String, expected: String }, - #[error("Unsupported type: {0}")] - UnsupportedType(String), + /// Raised when a file path lacks an extension. + /// Without an extension, determining the file format becomes impossible. + #[error("This file has no file extension")] + MissingFileExtension, + /// Indicates a nested configuration error in a specific section. + /// Provides details about the section and the root cause of the error. #[error("Nested configuration error in {section}: {source}")] NestedError { section: String, @@ -42,48 +64,85 @@ pub enum ParserError { source: Box, }, - /// Standard IO error. + /// Reflects standard IO errors encountered during file operations. + /// Arises when issues occur while reading or writing files. #[error("{0:#}")] Io(#[from] StdError), - /// TOML parsing error. + /// Represents a failure in parsing a TOML file. + /// Occurs when the parser encounters invalid TOML syntax or structure. #[error("TOML parsing error: {0}")] TomlError(#[from] TomlError), - /// JSON parsing error. + /// Represents a failure in parsing a JSON file. + /// Triggered by invalid JSON syntax or structure during parsing. #[error("JSON parsing error: {0}")] JsonError(#[from] JsonError), - /// YAML parsing error. + /// Represents a failure in parsing a YAML file. + /// Triggered by invalid YAML syntax or structure during parsing. #[error("YAML parsing error: {0}")] YmlError(#[from] YmlError), } -/// This enum represents the available -/// file formats for configuration parsing. +/// Represents the supported file formats for configuration parsing. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum FileFormat { /// YML/YAML file format identifier. + #[cfg(feature = "yaml")] Yml, /// JSON file format identifier. + #[cfg(feature = "json")] Json, /// TOML file format identifier. + #[cfg(feature = "toml")] Toml, } +// Implement `FromStr` trait for `FileFormat` to allow easy conversion from +// string. +impl FromStr for FileFormat { + type Err = ParserError; + + fn from_str(s: &str) -> Result { + match s + .to_lowercase() + .as_str() + { + #[cfg(feature = "yaml")] + "yml" | "yaml" => Ok(FileFormat::Yml), + + #[cfg(feature = "json")] + "json" => Ok(FileFormat::Json), + + #[cfg(feature = "toml")] + "toml" => Ok(FileFormat::Toml), + + _ => Err(ParserError::InvalidFileFormat(s.into())), + } + } +} + /// Implement `Display` trait for `FileFormat` to allow easy conversion to /// string. impl Display for FileFormat { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { + #[cfg(feature = "yaml")] FileFormat::Yml => write!(f, "yaml"), + + #[cfg(feature = "json")] FileFormat::Json => write!(f, "json"), + + #[cfg(feature = "toml")] FileFormat::Toml => write!(f, "toml"), } } } -#[derive(Debug, Clone)] +/// This enum represents the possible values +/// that can be parsed from a configuration file. +#[derive(Debug, Clone, PartialEq)] pub enum ConfigValue { Value(String), Section(HashMap), @@ -100,9 +159,15 @@ pub trait Parser: Send + Sync { /// Returns the file format associated with this parser. fn format(&self) -> FileFormat { match self.extensions()[0] { + #[cfg(feature = "yaml")] "yml" | "yaml" => FileFormat::Yml, + + #[cfg(feature = "json")] "json" => FileFormat::Json, + + #[cfg(feature = "toml")] "toml" => FileFormat::Toml, + _ => panic!("Unsupported file format"), } } @@ -115,48 +180,71 @@ pub trait Parser: Send + Sync { /// Function to get a parser based on file extension. /// Returns an `Option` containing the parser if the extension is supported. -pub fn get_parser_by_extension(ext: &str) -> Option> { +pub fn get_parser(ext: &str) -> Result, ParserError> { match ext { - "yml" | "yaml" => Some(Arc::new(YmlParser)), - "json" => Some(Arc::new(JsonParser)), - "toml" => Some(Arc::new(TomlParser)), - _ => None, + #[cfg(feature = "yaml")] + "yml" | "yaml" => Ok(Arc::new(YmlParser)), + + #[cfg(feature = "json")] + "json" => Ok(Arc::new(JsonParser)), + + #[cfg(feature = "toml")] + "toml" => Ok(Arc::new(TomlParser)), + + _ => Err(ParserError::InvalidFileFormat(ext.into())), } } +/// Function to get the file extension from a path. +pub fn get_file_extension(path: &str) -> Result { + let ext = std::path::Path::new(path) + .extension() + .and_then(|s| s.to_str()) + .ok_or(ParserError::MissingFileExtension)?; + + Ok(ext.into()) +} + +/// Trait to convert a `ConfigValue` to a specific type. pub trait FromConfigValue { fn from_config_value(value: &ConfigValue) -> Result where Self: Sized; } -/// Macro to impl FromConfigValue for specific scalar types. +/// Macro to implement FromConfigValue for scalar types. +/// This macro generates implementations for types that can be parsed from a +/// string. macro_rules! impl_from_config_value { - ($t:ty) => { + ($($t:ty),* $(,)?) => {$( impl FromConfigValue for $t { fn from_config_value(value: &ConfigValue) -> Result { match value { - ConfigValue::Value(s) => s - .parse::<$t>() - .map_err(|_| ParserError::TypeMismatch { - field: "".into(), - expected: stringify!($t).into(), - }), + ConfigValue::Value(s) => parse_value::<$t>(s), _ => Err(ParserError::TypeMismatch { - field: "".into(), + field: "Expected a scalar value".into(), expected: stringify!($t).into(), }), } } } - }; + )*}; +} + +/// Helper function to parse a string into a specific type. +/// Returns a ParserError if parsing fails. +fn parse_value(s: &str) -> Result { + s.parse::() + .map_err(|_| ParserError::TypeMismatch { + field: "Failed to parse value".into(), + expected: stringify!(T).into(), + }) } // Scalar types -impl_from_config_value!(String); -impl_from_config_value!(u16); -impl_from_config_value!(f64); -impl_from_config_value!(bool); +impl_from_config_value!( + String, bool, i8, i16, i32, i64, i128, u8, u16, u32, u64, u128, usize, isize, f32, f64, char +); /// Helper trait to convert a `ConfigValue` to a `Vec`. impl FromConfigValue for Vec diff --git a/cruct_shared/src/parser/tests/mod.rs b/cruct_shared/src/parser/tests/mod.rs new file mode 100644 index 0000000..697247e --- /dev/null +++ b/cruct_shared/src/parser/tests/mod.rs @@ -0,0 +1,3 @@ +mod test_toml; +mod test_yaml; +mod test_json; diff --git a/cruct_shared/src/parser/tests/test_json.rs b/cruct_shared/src/parser/tests/test_json.rs new file mode 100644 index 0000000..b2b5e6c --- /dev/null +++ b/cruct_shared/src/parser/tests/test_json.rs @@ -0,0 +1,27 @@ +use std::io::Write; + +use tempfile::NamedTempFile; + +use crate::{ConfigFileSource, ConfigSource, ConfigValue, FileFormat}; + +#[test] +fn parses_simple_json_map() { + let mut file = NamedTempFile::new().unwrap(); + writeln!(file, "{{\"foo\": \"bar\",\"baz\": 42}}").unwrap(); + let path = file + .path() + .to_str() + .unwrap(); + + let src = ConfigFileSource::new(path, Some(FileFormat::Yml)); + let cfg = src + .load() + .unwrap(); + + if let ConfigValue::Section(map) = cfg { + assert_eq!(map["foo"], ConfigValue::Value("bar".to_string())); + assert_eq!(map["baz"], ConfigValue::Value("42".to_string())); + } else { + panic!("expected section"); + } +} diff --git a/cruct_shared/src/parser/tests/test_toml.rs b/cruct_shared/src/parser/tests/test_toml.rs new file mode 100644 index 0000000..2e6f7e6 --- /dev/null +++ b/cruct_shared/src/parser/tests/test_toml.rs @@ -0,0 +1,27 @@ +use std::io::Write; + +use tempfile::NamedTempFile; + +use crate::{ConfigFileSource, ConfigSource, ConfigValue, FileFormat}; + +#[test] +fn parses_simple_toml_map() { + let mut file = NamedTempFile::new().unwrap(); + writeln!(file, "foo = 'bar'\nbaz = 42").unwrap(); + let path = file + .path() + .to_str() + .unwrap(); + + let src = ConfigFileSource::new(path, Some(FileFormat::Toml)); + let cfg = src + .load() + .unwrap(); + + if let ConfigValue::Section(map) = cfg { + assert_eq!(map["foo"], ConfigValue::Value("bar".to_string())); + assert_eq!(map["baz"], ConfigValue::Value("42".to_string())); + } else { + panic!("expected section"); + } +} diff --git a/cruct_shared/src/parser/tests/test_yaml.rs b/cruct_shared/src/parser/tests/test_yaml.rs new file mode 100644 index 0000000..7d7afec --- /dev/null +++ b/cruct_shared/src/parser/tests/test_yaml.rs @@ -0,0 +1,27 @@ +use std::io::Write; + +use tempfile::NamedTempFile; + +use crate::{ConfigFileSource, ConfigSource, ConfigValue, FileFormat}; + +#[test] +fn parses_simple_yaml_map() { + let mut file = NamedTempFile::new().unwrap(); + writeln!(file, "foo: bar\nbaz: 42").unwrap(); + let path = file + .path() + .to_str() + .unwrap(); + + let src = ConfigFileSource::new(path, Some(FileFormat::Yml)); + let cfg = src + .load() + .unwrap(); + + if let ConfigValue::Section(map) = cfg { + assert_eq!(map["foo"], ConfigValue::Value("bar".to_string())); + assert_eq!(map["baz"], ConfigValue::Value("42".to_string())); + } else { + panic!("expected section"); + } +} diff --git a/cruct_shared/src/parser/tml.rs b/cruct_shared/src/parser/tml.rs deleted file mode 100644 index 7852772..0000000 --- a/cruct_shared/src/parser/tml.rs +++ /dev/null @@ -1,83 +0,0 @@ -use std::collections::HashMap; -use std::fs; - -use toml_edit::{DocumentMut, Item, Table, Value}; - -use super::{ConfigValue, Parser, ParserError}; - -#[derive(Clone)] -pub struct TomlParser; - -impl Parser for TomlParser { - fn extensions(&self) -> &'static [&'static str] { - &["toml"] - } - - fn load(&self, path: &str) -> Result { - let content = fs::read_to_string(path)?; - let value = content.parse::()?; - parse_toml(value.as_item()) - } -} - -fn parse_toml(item: &Item) -> Result { - match item { - Item::None => Ok(ConfigValue::Array(Vec::new())), - Item::Value(value) => parse_toml_value(value), - Item::Table(table) => parse_table(table), - Item::ArrayOfTables(array_of_tables) => { - let mut array = Vec::new(); - for table in array_of_tables { - array.push(parse_table(table)?); - } - Ok(ConfigValue::Array(array)) - }, - } -} - -fn parse_table(table: &Table) -> Result { - let mut map = HashMap::new(); - for (k, v) in table { - map.insert(k.to_string(), parse_toml(v)?); - } - Ok(ConfigValue::Section(map)) -} - -fn parse_toml_value(value: &Value) -> Result { - match value { - Value::InlineTable(table) => { - let mut map = HashMap::new(); - for (k, v) in table { - map.insert(k.to_string(), parse_toml_value(v)?); - } - Ok(ConfigValue::Section(map)) - }, - Value::Array(arr) => { - let items = arr - .into_iter() - .map(parse_toml_value) - .collect::, _>>()?; - Ok(ConfigValue::Array(items)) - }, - Value::String(s) => Ok(ConfigValue::Value( - s.clone() - .into_value(), - )), - Value::Integer(i) => Ok(ConfigValue::Value( - i.value() - .to_string(), - )), - Value::Float(f) => Ok(ConfigValue::Value( - f.value() - .to_string(), - )), - Value::Boolean(b) => Ok(ConfigValue::Value( - b.value() - .to_string(), - )), - Value::Datetime(dt) => Ok(ConfigValue::Value( - dt.value() - .to_string(), - )), - } -} diff --git a/cruct_shared/src/parser/toml.rs b/cruct_shared/src/parser/toml.rs new file mode 100644 index 0000000..8a2a836 --- /dev/null +++ b/cruct_shared/src/parser/toml.rs @@ -0,0 +1,248 @@ +use std::collections::HashMap; +use std::fs; + +use toml_edit::{DocumentMut, Item, Table, Value}; + +use super::{ConfigValue, Parser, ParserError}; + +#[derive(Clone)] +pub struct TomlParser; + +impl Parser for TomlParser { + fn extensions(&self) -> &'static [&'static str] { + &["toml"] + } + + fn load(&self, path: &str) -> Result { + let content = fs::read_to_string(path)?; + let value = content.parse::()?; + + parse_toml(value.as_item()) + } +} + +/// Parses a TOML item into a `ConfigValue`, which is an intermediary +/// representation for configuration data. +/// +/// # Parameters: +/// * `item`: The TOML item to parse, which could be a value, table, or array of +/// tables. +/// +/// # Returns: +/// A `ConfigValue` representing the parsed TOML data. +/// +/// # Errors: +/// Returns a `ParserError` if the TOML item cannot be parsed due to invalid +/// syntax or unsupported structures. +fn parse_toml(item: &Item) -> Result { + Ok(match item { + Item::None => ConfigValue::Array(Vec::new()), + Item::Value(value) => parse_toml_value(value)?, + Item::Table(table) => parse_table(table)?, + Item::ArrayOfTables(array_of_tables) => { + let mut array = Vec::new(); + for table in array_of_tables { + array.push(parse_table(table)?); + } + ConfigValue::Array(array) + }, + }) +} + +/// Parses a TOML table into a `ConfigValue`. +/// +/// * `table`: A reference to the TOML table to be parsed. +fn parse_table(table: &Table) -> Result { + let mut map = HashMap::new(); + for (k, v) in table { + map.insert(k.to_string(), parse_toml(v)?); + } + Ok(ConfigValue::Section(map)) +} + +/// Parses a TOML value into a `ConfigValue`. +/// +/// * `value`: A reference to the TOML value that needs to be parsed. +fn parse_toml_value(value: &Value) -> Result { + Ok(match value { + Value::InlineTable(table) => { + let mut map = HashMap::new(); + for (k, v) in table { + map.insert(k.to_string(), parse_toml_value(v)?); + } + ConfigValue::Section(map) + }, + Value::Array(arr) => { + let items = arr + .into_iter() + .map(parse_toml_value) + .collect::, _>>()?; + ConfigValue::Array(items) + }, + Value::String(s) => ConfigValue::Value( + s.clone() + .into_value(), + ), + Value::Integer(i) => ConfigValue::Value( + i.value() + .to_string(), + ), + Value::Float(f) => ConfigValue::Value( + f.value() + .to_string(), + ), + Value::Boolean(b) => ConfigValue::Value( + b.value() + .to_string(), + ), + Value::Datetime(dt) => ConfigValue::Value( + dt.value() + .to_string(), + ), + }) +} + +#[cfg(test)] +mod test { + use std::collections::HashMap; + + use toml_edit::{Array, ArrayOfTables, Date, Formatted, Item, Table, Value}; + + use super::*; + + #[test] + fn test_parse_toml_value_string() { + let value = Value::String(Formatted::new("test_string".to_string())); + let result = parse_toml_value(&value).unwrap(); + + assert_eq!(result, ConfigValue::Value("test_string".to_string())); + } + + #[test] + fn test_parse_toml_value_integer() { + let value = Value::Integer(Formatted::new(123)); + let result = parse_toml_value(&value).unwrap(); + + assert_eq!(result, ConfigValue::Value("123".to_string())); + } + + #[test] + fn test_parse_toml_value_float() { + let value = Value::Float(Formatted::new(123.45)); + let result = parse_toml_value(&value).unwrap(); + + assert_eq!(result, ConfigValue::Value("123.45".to_string())); + } + + #[test] + fn test_parse_toml_value_boolean() { + let value = Value::Boolean(Formatted::new(true)); + let result = parse_toml_value(&value).unwrap(); + + assert_eq!(result, ConfigValue::Value("true".to_string())); + } + + #[test] + fn test_parse_toml_value_inline_table() { + let mut table = toml_edit::InlineTable::default(); + table.insert("key", Value::String(Formatted::new("value".to_string()))); + + let value = Value::InlineTable(table); + let result = parse_toml_value(&value).unwrap(); + + let mut expected_map = HashMap::new(); + expected_map.insert("key".to_string(), ConfigValue::Value("value".to_string())); + + assert_eq!(result, ConfigValue::Section(expected_map)); + } + + #[test] + fn test_parse_toml_value_datetime() { + let value = Value::Datetime(Formatted::new(Date { year: 2023, month: 10, day: 1 }.into())); + let result = parse_toml_value(&value).unwrap(); + + assert_eq!(result, ConfigValue::Value("2023-10-01".to_string())); + } + + #[test] + fn test_parse_toml_array() { + let value = Value::Array(Array::from_iter(vec![ + Value::String(Formatted::new("item1".into())), + Value::String(Formatted::new("item2".into())), + ])); + + let result = parse_toml_value(&value).unwrap(); + + assert_eq!( + result, + ConfigValue::Array(vec![ + ConfigValue::Value("item1".to_string()), + ConfigValue::Value("item2".to_string()) + ]) + ); + } + + #[test] + fn test_parse_toml_table() { + let mut table = Table::new(); + + table.insert("key1", Item::Value(Value::String(Formatted::new("value1".to_string())))); + table.insert("key2", Item::Value(Value::Integer(Formatted::new(42.into())))); + + let result = parse_table(&table).unwrap(); + let mut expected_map = HashMap::new(); + + expected_map.insert("key1".to_string(), ConfigValue::Value("value1".to_string())); + expected_map.insert("key2".to_string(), ConfigValue::Value("42".to_string())); + + assert_eq!(result, ConfigValue::Section(expected_map)); + } + + #[test] + fn test_parse_toml_item_table() { + let mut table = Table::new(); + table.insert("key", Item::Value(Value::String(Formatted::new("value".to_string())))); + + let item = Item::Table(table); + let result = parse_toml(&item).unwrap(); + + let mut expected_map = HashMap::new(); + expected_map.insert("key".to_string(), ConfigValue::Value("value".to_string())); + + assert_eq!(result, ConfigValue::Section(expected_map)); + } + + #[test] + fn test_parse_toml_item_array_of_tables() { + let mut table1 = Table::new(); + let mut table2 = Table::new(); + + table1.insert("key1", Item::Value(Value::String(Formatted::new("value1".to_string())))); + table2.insert("key2", Item::Value(Value::String(Formatted::new("value2".to_string())))); + + let item = Item::ArrayOfTables(ArrayOfTables::from_iter(vec![table1, table2])); + let result = parse_toml(&item).unwrap(); + + let mut expected_map1 = HashMap::new(); + let mut expected_map2 = HashMap::new(); + + expected_map1.insert("key1".to_string(), ConfigValue::Value("value1".to_string())); + expected_map2.insert("key2".to_string(), ConfigValue::Value("value2".to_string())); + + assert_eq!( + result, + ConfigValue::Array(vec![ + ConfigValue::Section(expected_map1), + ConfigValue::Section(expected_map2) + ]) + ); + } + + #[test] + fn test_parse_toml_item_none() { + let item = Item::None; + let result = parse_toml(&item).unwrap(); + + assert_eq!(result, ConfigValue::Array(Vec::new())); + } +} diff --git a/cruct_shared/src/parser/yaml.rs b/cruct_shared/src/parser/yaml.rs new file mode 100644 index 0000000..a96cfd0 --- /dev/null +++ b/cruct_shared/src/parser/yaml.rs @@ -0,0 +1,199 @@ +use std::collections::HashMap; +use std::fs::read_to_string; + +use yaml_rust2::{Yaml, YamlLoader}; + +use super::{ConfigValue, Parser, ParserError}; + +#[derive(Clone)] +pub struct YmlParser; + +impl Parser for YmlParser { + fn extensions(&self) -> &'static [&'static str] { + &["yml", "yaml"] + } + + fn load(&self, path: &str) -> Result { + let content = read_to_string(path)?; + let docs = YamlLoader::load_from_str(&content)?; + + let doc = docs + .first() + .ok_or(ParserError::TypeMismatch { + field: "document".to_string(), + expected: "non-empty YAML document".to_string(), + })?; + + parse_yaml_value(doc.clone()) + } +} + +/// Parses a YAML value into a corresponding `ConfigValue` type. +/// +/// This function recursively converts YAML structures (e.g., hashes, arrays, +/// strings, etc.) into the application's internal configuration representation +/// (`ConfigValue`). Unsupported YAML types will result in a `ParserError`. +/// +/// # Arguments +/// +/// * `value` - A `Yaml` value representing the YAML element to parse. +/// +/// # Returns +/// +/// * `Result` - On success, returns the parsed +/// `ConfigValue`. On failure, returns a `ParserError` indicating the type +/// mismatch. +fn parse_yaml_value(value: Yaml) -> Result { + match value { + Yaml::Hash(hash) => { + let mut map = HashMap::new(); + for (k, v) in hash { + if let Yaml::String(k_str) = k { + map.insert(k_str, parse_yaml_value(v)?); + } + } + Ok(ConfigValue::Section(map)) + }, + Yaml::Array(arr) => { + let items = arr + .into_iter() + .map(parse_yaml_value) + .collect::, _>>()?; + Ok(ConfigValue::Array(items)) + }, + Yaml::String(s) => Ok(ConfigValue::Value(s)), + Yaml::Integer(i) => Ok(ConfigValue::Value(i.to_string())), + Yaml::Boolean(b) => Ok(ConfigValue::Value(b.to_string())), + Yaml::Real(s) => Ok(ConfigValue::Value(s)), + Yaml::Null => Ok(ConfigValue::Value("null".to_string())), + _ => Err(ParserError::TypeMismatch { + field: "value".to_string(), + expected: "supported YAML type".to_string(), + }), + } +} + +#[cfg(test)] +mod test { + use std::collections::HashMap; + + use yaml_rust2::YamlLoader; + + use super::*; + + #[test] + fn test_parse_yaml_value_string() { + let yaml_str = "test_string"; + let docs = YamlLoader::load_from_str(yaml_str).unwrap(); + let value = docs[0].clone(); + + let result = parse_yaml_value(value).unwrap(); + assert_eq!(result, ConfigValue::Value("test_string".to_string())); + } + + #[test] + fn test_parse_yaml_value_integer() { + let yaml_str = "123"; + let docs = YamlLoader::load_from_str(yaml_str).unwrap(); + let value = docs[0].clone(); + + let result = parse_yaml_value(value).unwrap(); + assert_eq!(result, ConfigValue::Value("123".to_string())); + } + + #[test] + fn test_parse_yaml_value_float() { + let yaml_str = "123.45"; + let docs = YamlLoader::load_from_str(yaml_str).unwrap(); + let value = docs[0].clone(); + + let result = parse_yaml_value(value).unwrap(); + assert_eq!(result, ConfigValue::Value("123.45".to_string())); + } + + #[test] + fn test_parse_yaml_value_boolean() { + let yaml_str = "true"; + let docs = YamlLoader::load_from_str(yaml_str).unwrap(); + let value = docs[0].clone(); + + let result = parse_yaml_value(value).unwrap(); + assert_eq!(result, ConfigValue::Value("true".to_string())); + } + + #[test] + fn test_parse_yaml_value_object() { + let yaml_str = "key: value"; + let docs = YamlLoader::load_from_str(yaml_str).unwrap(); + let value = docs[0].clone(); + + let result = parse_yaml_value(value).unwrap(); + + let mut expected_map = HashMap::new(); + expected_map.insert("key".to_string(), ConfigValue::Value("value".to_string())); + + assert_eq!(result, ConfigValue::Section(expected_map)); + } + + #[test] + fn test_parse_yaml_value_array() { + let yaml_str = "- item1\n- item2"; + let docs = YamlLoader::load_from_str(yaml_str).unwrap(); + let value = docs[0].clone(); + + let result = parse_yaml_value(value).unwrap(); + + assert_eq!( + result, + ConfigValue::Array(vec![ + ConfigValue::Value("item1".to_string()), + ConfigValue::Value("item2".to_string()) + ]) + ); + } + + #[test] + fn test_parse_yaml_value_null() { + let yaml_str = "null"; + let docs = YamlLoader::load_from_str(yaml_str).unwrap(); + let value = docs[0].clone(); + + let result = parse_yaml_value(value).unwrap(); + assert_eq!(result, ConfigValue::Value("null".to_string())); + } + + #[test] + fn test_parse_yaml_value_nested() { + let yaml_str = "outer:\n inner: value"; + let docs = YamlLoader::load_from_str(yaml_str).unwrap(); + let value = docs[0].clone(); + + let result = parse_yaml_value(value).unwrap(); + + let mut expected_map = HashMap::new(); + expected_map.insert( + "outer".to_string(), + ConfigValue::Section({ + let mut inner_map = HashMap::new(); + inner_map.insert("inner".to_string(), ConfigValue::Value("value".to_string())); + inner_map + }), + ); + + assert_eq!(result, ConfigValue::Section(expected_map)); + } + + #[test] + fn test_parse_yaml_value_empty() { + let yaml_str = ""; + let docs = YamlLoader::load_from_str(yaml_str).unwrap(); + assert!(docs.is_empty(), "Expected no documents for empty YAML"); + } + + #[test] + fn test_parse_yaml_value_invalid() { + let yaml_str = "invalid: yaml: syntax"; + let docs = YamlLoader::load_from_str(yaml_str); + assert!(docs.is_err(), "Expected error for invalid YAML syntax"); + } +} diff --git a/cruct_shared/src/parser/yml.rs b/cruct_shared/src/parser/yml.rs deleted file mode 100644 index d652f23..0000000 --- a/cruct_shared/src/parser/yml.rs +++ /dev/null @@ -1,59 +0,0 @@ -use std::collections::HashMap; -use std::fs; - -use yaml_rust2::{Yaml, YamlLoader}; - -use super::{ConfigValue, Parser, ParserError}; - -#[derive(Clone)] -pub struct YmlParser; - -impl Parser for YmlParser { - fn extensions(&self) -> &'static [&'static str] { - &["yml", "yaml"] - } - - fn load(&self, path: &str) -> Result { - let content = fs::read_to_string(path)?; - let docs = YamlLoader::load_from_str(&content)?; - - let doc = docs - .first() - .ok_or(ParserError::TypeMismatch { - field: "document".to_string(), - expected: "non-empty YAML document".to_string(), - })?; - - parse_yaml_value(doc.clone()) - } -} - -fn parse_yaml_value(value: Yaml) -> Result { - match value { - Yaml::Hash(hash) => { - let mut map = HashMap::new(); - for (k, v) in hash { - if let Yaml::String(k_str) = k { - map.insert(k_str, parse_yaml_value(v)?); - } - } - Ok(ConfigValue::Section(map)) - }, - Yaml::Array(arr) => { - let items = arr - .into_iter() - .map(parse_yaml_value) - .collect::, _>>()?; - Ok(ConfigValue::Array(items)) - }, - Yaml::String(s) => Ok(ConfigValue::Value(s)), - Yaml::Integer(i) => Ok(ConfigValue::Value(i.to_string())), - Yaml::Boolean(b) => Ok(ConfigValue::Value(b.to_string())), - Yaml::Real(s) => Ok(ConfigValue::Value(s)), - Yaml::Null => Ok(ConfigValue::Value("null".to_string())), - _ => Err(ParserError::TypeMismatch { - field: "value".to_string(), - expected: "supported YAML type".to_string(), - }), - } -} diff --git a/cruct_shared/src/source/cli.rs b/cruct_shared/src/source/cli.rs new file mode 100644 index 0000000..9b91f06 --- /dev/null +++ b/cruct_shared/src/source/cli.rs @@ -0,0 +1,50 @@ +use std::collections::HashMap; +use std::env; + +use super::ConfigSource; +use crate::{ConfigValue, ParserError}; + +#[derive(Clone)] +pub struct CliSource { + priority: u8, +} + +impl CliSource { + /// Creates a new `CliSource` with the given priority. + /// The default priority is 0. + pub fn new(priority: u8) -> Self { + CliSource { priority } + } + + /// Retrieves the command-line arguments. + fn get_args() -> Vec { + env::args() + .skip(1) + .collect() + } +} + +impl ConfigSource for CliSource { + fn load(&self) -> Result { + let mut map: HashMap = HashMap::new(); + + // Use the get_args function to gather CLI args + let args = Self::get_args(); + + // Parse --key=val flags + for arg in args { + if let Some(stripped) = arg.strip_prefix("--") { + let mut parts = stripped.splitn(2, '='); + if let (Some(key), Some(val)) = (parts.next(), parts.next()) { + map.insert(key.to_owned(), ConfigValue::Value(val.to_owned())); + } + } + } + + Ok(ConfigValue::Section(map)) + } + + fn priority(&self) -> u8 { + self.priority + } +} diff --git a/cruct_shared/src/source/config.rs b/cruct_shared/src/source/config.rs new file mode 100644 index 0000000..017ea75 --- /dev/null +++ b/cruct_shared/src/source/config.rs @@ -0,0 +1,83 @@ +use std::sync::Arc; + +use super::ConfigSource; +use crate::parser::get_file_extension; +use crate::{ConfigValue, FileFormat, Parser, ParserError, get_parser}; + +pub struct ConfigFileSource { + path: String, + format: Option, +} + +impl ConfigFileSource { + /// Creates a new `ConfigFileSource`. + /// + /// * `path`: The path to the configuration file. + /// * `format`: Optional file format. If not provided, the format will be + /// inferred from the file extension. + pub fn new(path: impl Into, format: Option) -> Self { + ConfigFileSource { path: path.into(), format } + } + + /// Retrieves the parser based on the file format or extension. + /// + /// If a format is provided, it uses that; otherwise, it infers the + /// format from the file + fn get_parser(&self) -> Result, ParserError> { + let ext = if let Some(fmt) = &self.format { + fmt.to_string() + } else { + get_file_extension(&self.path)? + }; + + get_parser(&ext) + } +} + +impl ConfigSource for ConfigFileSource { + fn load(&self) -> Result { + let parser = self.get_parser()?; + parser.load(&self.path) + } +} + +#[cfg(test)] +mod test { + use crate::{ConfigFileSource, FileFormat}; + + #[test] + fn test_toml_parser_extensions() { + let src = ConfigFileSource::new("test.toml", Some(FileFormat::Toml)); + let parser = src + .get_parser() + .expect("Failed to get parser"); + + let extensions = parser.extensions(); + + assert!(extensions.contains(&"toml"), "Expected 'toml' extension, found: {:?}", extensions); + } + + #[test] + fn test_json_parser_extensions() { + let src = ConfigFileSource::new("test.json", Some(FileFormat::Json)); + let parser = src + .get_parser() + .expect("Failed to get parser"); + + let extensions = parser.extensions(); + + assert!(extensions.contains(&"json"), "Expected 'json' extension, found: {:?}", extensions); + } + + #[test] + fn test_yaml_parser_extensions() { + let src = ConfigFileSource::new("test.yaml", Some(FileFormat::Yml)); + let parser = src + .get_parser() + .expect("Failed to get parser"); + + let extensions = parser.extensions(); + + assert!(extensions.contains(&"yaml"), "Expected 'yaml' extension, found: {:?}", extensions); + } +} diff --git a/cruct_shared/src/source/mod.rs b/cruct_shared/src/source/mod.rs new file mode 100644 index 0000000..37abb5f --- /dev/null +++ b/cruct_shared/src/source/mod.rs @@ -0,0 +1,121 @@ +use std::cmp::Reverse; +use std::collections::HashMap; + +use crate::{ConfigValue, ParserError}; + +mod cli; +mod config; + +#[cfg(test)] +mod tests; + +pub use cli::CliSource; +pub use config::ConfigFileSource; + +/// Trait defining a configuration source. +/// +/// A `ConfigSource` is an entity capable of yielding a `ConfigValue`, +/// which can represent configuration data from various sources, such as files, +/// environment variables, or CLI arguments. +pub trait ConfigSource { + /// Load configuration from the source. + /// + /// Returns a `Result` containing either the configuration value + /// (`ConfigValue`) or a parsing error (`ParserError`) if loading fails. + fn load(&self) -> Result; + + /// Defines the priority of this configuration source. + /// + /// Sources with higher priority override those with lower priority during + /// merging. + fn priority(&self) -> u8 { + u8::MAX + } +} + +/// Merge two `ConfigValue::Section` maps, where `high` takes precedence. +/// +/// This function recursively merges two `HashMap` instances containing +/// `ConfigValue::Section` entries. If both sections contain nested sections, +/// they are merged recursively. Otherwise, values from `high` override those +/// in `base`. +pub fn merge_sections( + mut base: HashMap, + high: HashMap, +) -> HashMap { + for (k, v_high) in high { + match (base.remove(&k), v_high) { + (Some(ConfigValue::Section(bsub)), ConfigValue::Section(hsub)) => { + base.insert(k, ConfigValue::Section(merge_sections(bsub, hsub))); + }, + (_old, v_high) => { + base.insert(k, v_high); + }, + } + } + base +} + +/// Merge two `ConfigValue` instances. +/// +/// If both values are sections, their internal maps are merged using +/// `merge_sections`. Otherwise, it prioritizes the `high` value and returns it. +/// If both ConfigValue instances are sections, it merges their internal maps +/// using merge_sections. Otherwise, it prioritizes the high ConfigValue, +/// returning it directly. +pub fn merge_configs(base: ConfigValue, high: ConfigValue) -> Result { + match (base, high) { + (ConfigValue::Section(base), ConfigValue::Section(high)) => { + Ok(ConfigValue::Section(merge_sections(base, high))) + }, + (_old, high_val) => Ok(high_val), + } +} + +/// Builder for creating a configuration from multiple sources. +/// +/// `ConfigBuilder` allows users to specify multiple sources for configuration +/// (e.g., CLI, files, environment variables) and merges their data. +#[derive(Default)] +pub struct ConfigBuilder { + /// A list of sources to load configuration from. + sources: Vec>, +} + +impl ConfigBuilder { + /// Create an empty configuration builder with no sources. + pub fn new() -> Self { + ConfigBuilder { sources: Vec::new() } + } + + /// Add a configuration source. + /// + /// Accepts any entity implementing the `ConfigSource` trait and adds it to + /// the list of sources to be loaded. + pub fn add_source(mut self, src: S) -> Self + where + S: ConfigSource + Send + Sync + 'static, + { + self.sources + .push(Box::new(src)); + self + } + + /// Load and merge all configuration sources. + /// + /// Sources are sorted by priority (highest first) and merged sequentially, + /// ensuring that later sources override earlier ones. + pub fn load(self) -> Result { + let mut sources = self.sources; + + sources.sort_by_key(|s| Reverse(s.priority())); + + let mut accumulated = ConfigValue::Section(HashMap::new()); + for src in sources { + let next = src.load()?; + accumulated = merge_configs(accumulated, next)?; + } + + Ok(accumulated) + } +} diff --git a/cruct_shared/src/source/tests/mod.rs b/cruct_shared/src/source/tests/mod.rs new file mode 100644 index 0000000..9566f16 --- /dev/null +++ b/cruct_shared/src/source/tests/mod.rs @@ -0,0 +1 @@ +mod test_merge; diff --git a/cruct_shared/src/source/tests/test_merge.rs b/cruct_shared/src/source/tests/test_merge.rs new file mode 100644 index 0000000..80e1a65 --- /dev/null +++ b/cruct_shared/src/source/tests/test_merge.rs @@ -0,0 +1,116 @@ +use std::collections::HashMap; + +use crate::ConfigValue; +use crate::source::{merge_configs, merge_sections}; + +#[test] +fn overrides_and_merges_nested_sections() { + let mut base = HashMap::new(); + base.insert("a".into(), ConfigValue::Value("one".into())); + base.insert( + "nested".into(), + ConfigValue::Section({ + let mut m = HashMap::new(); + m.insert("x".into(), ConfigValue::Value("10".into())); + m + }), + ); + + let mut high = HashMap::new(); + high.insert("a".into(), ConfigValue::Value("two".into())); + high.insert( + "nested".into(), + ConfigValue::Section({ + let mut m = HashMap::new(); + m.insert("y".into(), ConfigValue::Value("20".into())); + m + }), + ); + + let merged = merge_sections(base, high); + assert_eq!(merged["a"], ConfigValue::Value("two".into())); + let nested = match &merged["nested"] { + ConfigValue::Section(s) => s, + _ => panic!("expected section"), + }; + assert_eq!(nested["x"], ConfigValue::Value("10".into())); + assert_eq!(nested["y"], ConfigValue::Value("20".into())); +} + +#[test] +fn merge_configs_sections() { + let mut base_section = HashMap::new(); + base_section.insert( + "key1".to_string(), + ConfigValue::Section(HashMap::from([( + "subkey1".to_string(), + ConfigValue::Value("high1".to_string()), + )])), + ); + base_section.insert("key2".to_string(), ConfigValue::Value("base2".to_string())); + + let mut high_section = HashMap::new(); + high_section.insert( + "key1".to_string(), + ConfigValue::Section(HashMap::from([ + ("subkey1".to_string(), ConfigValue::Value("high1".to_string())), + ("subkey2".to_string(), ConfigValue::Value("high2".to_string())), + ])), + ); + high_section.insert("key3".to_string(), ConfigValue::Value("high3".to_string())); + + let base = ConfigValue::Section(base_section); + let high = ConfigValue::Section(high_section); + + let result = merge_configs(base, high).unwrap(); + + if let ConfigValue::Section(merged_section) = result { + assert_eq!(merged_section.len(), 3); + + if let ConfigValue::Section(sub_section) = merged_section + .get("key1") + .unwrap() + { + assert_eq!(sub_section.len(), 2); + assert_eq!( + sub_section + .get("subkey1") + .unwrap(), + &ConfigValue::Value("high1".to_string()) + ); + assert_eq!( + sub_section + .get("subkey2") + .unwrap(), + &ConfigValue::Value("high2".to_string()) + ); + } else { + panic!("Expected key1 to be a section"); + } + + assert_eq!( + merged_section + .get("key2") + .unwrap(), + &ConfigValue::Value("base2".to_string()) + ); + assert_eq!( + merged_section + .get("key3") + .unwrap(), + &ConfigValue::Value("high3".to_string()) + ); + } else { + panic!("Expected result to be a section"); + } +} + +#[test] +fn merge_configs_non_sections() { + let base = ConfigValue::Value("base_value".to_string()); + let high = ConfigValue::Value("high_value".to_string()); + + let result = merge_configs(base, high).unwrap(); + + assert_eq!(result, ConfigValue::Value("high_value".to_string())); +} diff --git a/flake.nix b/flake.nix index 04145ef..08501ec 100644 --- a/flake.nix +++ b/flake.nix @@ -1,5 +1,5 @@ { - description = "Flake configuration file for translatable.rs development."; + description = "Flake configuration file for cruct development."; inputs = { nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable"; crane.url = "github:ipetkov/crane"; @@ -20,26 +20,30 @@ pkgs = nixpkgs.legacyPackages.${system}; crane = inputs.crane.mkLib pkgs; + # Determine the Rust toolchain toolchain = with fenix.packages.${system}; combine [ - minimal.rustc - minimal.cargo - complete.rust-analyzer - complete.rust-src + stable.rustc + stable.rust-src + stable.cargo complete.rustfmt - complete.clippy + stable.clippy + stable.rust-analyzer + stable.llvm-tools-preview ]; + # Override the toolchain in crane craneLib = crane.overrideToolchain toolchain; in { devShells.default = craneLib.devShell { packages = with pkgs; [ toolchain - rustfmt - clippy - qemu-user + cargo-llvm-cov + llvmPackages_19.libllvm + grcov + cargo-nextest ]; env = {