From 277ab2c25a1906acb1d2be5d4816d8589cd7bd92 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 23 Aug 2026 05:53:57 +0000 Subject: [PATCH] Rewrite amendable-cli in Rust Move the command-line client into its own crate. The binary is still `amendable` and keeps the same commands, config file, and staging overrides as the Python prototype that lived in amendable-docs. Co-authored-by: fangpen --- .github/workflows/ci.yml | 21 + .gitignore | 6 + AGENTS.md | 33 + Cargo.lock | 1758 ++++++++++++++++++++++++++++++++++++++ Cargo.toml | 37 + LICENSE | 21 + README.md | 53 +- rust-toolchain.toml | 3 + src/cli.rs | 862 +++++++++++++++++++ src/client.rs | 310 +++++++ src/config.rs | 213 +++++ src/error.rs | 108 +++ src/lib.rs | 19 + src/main.rs | 5 + tests/cli.rs | 272 ++++++ tests/common/mod.rs | 374 ++++++++ 16 files changed, 4094 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/ci.yml create mode 100644 .gitignore create mode 100644 AGENTS.md create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 LICENSE create mode 100644 rust-toolchain.toml create mode 100644 src/cli.rs create mode 100644 src/client.rs create mode 100644 src/config.rs create mode 100644 src/error.rs create mode 100644 src/lib.rs create mode 100644 src/main.rs create mode 100644 tests/cli.rs create mode 100644 tests/common/mod.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..1ba8a62 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,21 @@ +name: CI + +on: + push: + branches: [master] + pull_request: + +env: + CARGO_TERM_COLOR: always + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + with: + components: rustfmt, clippy + - run: cargo fmt --check + - run: cargo clippy --all-targets -- -D warnings + - run: cargo test diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ec87040 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +/target +**/*.rs.bk +.idea/ +.vscode/ +*.swp +.DS_Store diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..612771f --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,33 @@ +# Agent notes for amendable-cli + +Rust CLI (`amendable`) for the Amendable API. + +## Product facts (do not invent others) + +- Site + Git HTTPS: `https://amendable.io` +- API: `https://api.amendable.io` header `access-token` +- Clone: `https://amendable.io/r//.git` +- Git password is the access token. There is no SSH. +- Command name is `amendable`. Package name is `amendable-cli`. + +Staging is a config override, not a different command set: + +- `amendable --staging` / `amendable login --staging` +- `AMENDABLE_API_URL=https://stage.api.amendable.io` +- `AMENDABLE_APP_URL=https://stage.amendable.io` + +Config file: `~/.config/amendable/config.toml` (mode `0600`). + +Authoritative API behavior lives in `../amendable-web`. Customer docs live in `../amendable-docs`. If the CLI disagrees with the API, fix the CLI. If the docs disagree with the CLI, fix the docs. + +## Commands + +Keep the public command surface stable. Docs and examples call `amendable`, not `amendable-cli`. + +## Tests + +```bash +cargo test +cargo fmt --check +cargo clippy --all-targets -- -D warnings +``` diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..731a2bd --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,1758 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "amendable-cli" +version = "0.1.0" +dependencies = [ + "assert_cmd", + "clap", + "hostname", + "open", + "predicates", + "reqwest", + "serde", + "serde_json", + "tempfile", + "tiny_http", + "toml", +] + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "ascii" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d92bec98840b8f03a5ff5413de5293bfcd8bf96467cf5452609f939ec6f5de16" + +[[package]] +name = "assert_cmd" +version = "2.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2aa3a22042e45de04255c7bf3626e239f450200fd0493c1e382263544b20aea6" +dependencies = [ + "anstyle", + "bstr", + "libc", + "predicates", + "predicates-core", + "predicates-tree", + "wait-timeout", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "bitflags" +version = "2.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da" + +[[package]] +name = "bstr" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6bb31b46c14244e20ee9984b11bf5c992b91fb6939fea616e3512c8baecdbe5f" +dependencies = [ + "memchr", + "regex-automata", + "serde_core", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cc" +version = "1.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ad534f4357a5264cce5019c989cf66a4f0dc4e0d1b1d15f8aacec0ff7360273" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d524456ba66e72eb8b115ff89e01e497f8e6d11d78b70b1aa13c0fbd97540a81" +dependencies = [ + "cfg-if", + "cpufeatures", + "rand_core", +] + +[[package]] +name = "chunked_transfer" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e4de3bc4ea267985becf712dc6d9eed8b04c953b3fcfb339ebc87acd9804901" + +[[package]] +name = "clap" +version = "4.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "473c7e07f409a8d772161724aa8db6a765a2532a70f9667eeb7b49d3d02fbdca" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b48fea5a88e9ae728a2dcbedbfc0e730f7d60da42e1cb049a83c9fb8b789889" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d012d2b9d65aca7f18f4d9878a045bc17899bba951561ba5ec3c2ba1eed9a061" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "clap_lex" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "cpufeatures" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201" +dependencies = [ + "libc", +] + +[[package]] +name = "difflib" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6184e33543162437515c2e2b48714794e37845ec9851711914eec9d308f6ebe8" + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "find-msvc-tools" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d45db016d36b838f563236e9193d0ee6ce38f3f68b6c94e914b4929c96bbb890" + +[[package]] +name = "float-cmp" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b09cf3155332e944990140d967ff5eceb70df778b34f77d8075db46e4704e6d8" +dependencies = [ + "num-traits", +] + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-io", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi", + "rand_core", + "wasm-bindgen", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hostname" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "617aaa3557aef3810a6369d0a99fac8a080891b68bd9f9812a1eeda0c0730cbd" +dependencies = [ + "cfg-if", + "libc", + "windows-link", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hyper" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d22053281f852e11534f5198498373cbb59295120a20771d90f7ed1897490a72" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", + "webpki-roots", +] + +[[package]] +name = "hyper-util" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" +dependencies = [ + "base64", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "icu_collections" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" + +[[package]] +name = "icu_properties" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" + +[[package]] +name = "icu_provider" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "ipnet" +version = "2.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a756c3fac73139e83f14c2d742155dd2b78d3ee56597b419a0579b7bdd6dd78" + +[[package]] +name = "is-docker" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "928bae27f42bc99b60d9ac7334e3a21d10ad8f1835a4e12ec3ec0464765ed1b3" +dependencies = [ + "once_cell", +] + +[[package]] +name = "is-wsl" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173609498df190136aa7dea1a91db051746d339e18476eed5ca40521f02d7aa5" +dependencies = [ + "is-docker", + "once_cell", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e0c1080212aad755ea003d18543e8768dd432c48819efd73a7bf1e39b7a5a3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "lru-slab" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mio" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30d65c71f1ce40ab09135ce117d742b9f8a19ff91a41a8b57ed50bc2de59c427" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "normalize-line-endings" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61807f77802ff30975e01f4f071c8ba10c022052f98b3294119f3e615d13e5be" + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "open" +version = "5.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9cfef937e9c486488c7e3d949ae31c0f1d06bdacd75b99c086cb35356e30408" +dependencies = [ + "is-wsl", + "libc", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "predicates" +version = "3.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ada8f2932f28a27ee7b70dd6c1c39ea0675c55a36879ab92f3a715eaa1e63cfe" +dependencies = [ + "anstyle", + "difflib", + "float-cmp", + "normalize-line-endings", + "predicates-core", + "regex", +] + +[[package]] +name = "predicates-core" +version = "1.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cad38746f3166b4031b1a0d39ad9f954dd291e7854fcc0eed52ee41a0b50d144" + +[[package]] +name = "predicates-tree" +version = "1.0.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0de1b847b39c8131db0467e9df1ff60e6d0562ab8e9a16e568ad0fdb372e2f2" +dependencies = [ + "predicates-core", + "termtree", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quinn" +version = "0.11.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c1a41e437b6bbd489372cd4971de128e85c855f56c57f283d20ff016cf7c0a8" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04759210543be93709136e28212294a659ef5001836ff4eab4d663e4529bba83" +dependencies = [ + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand", + "rand_pcg", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35a133f956daabe89a61a685c2649f13d82d5aa4bd5d12d1277e1072a21c0694" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_pcg" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +dependencies = [ + "rand_core", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64", + "bytes", + "futures-channel", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "webpki-roots", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustix" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.43" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0283386ce02abc0151e1761d08802dfe86c173b0b494af5cbc086574e453da06" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_spanned" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" +dependencies = [ + "serde", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.15.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "termtree" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f50febec83f5ee1df3015341d8bd429f2d1cc62bcba7ea2076759d315084683" + +[[package]] +name = "thiserror" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "tiny_http" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "389915df6413a2e74fb181895f933386023c71110878cd0825588928e64cdc82" +dependencies = [ + "ascii", + "chunked_transfer", + "httpdate", + "log", +] + +[[package]] +name = "tinystr" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb4ebadaa0af04fab11ae01eb5f9fdb5f9c5b875506e210e71c07873528baa7f" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + +[[package]] +name = "tokio" +version = "1.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "socket2", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "toml" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" +dependencies = [ + "serde", + "serde_spanned", + "toml_datetime", + "toml_edit", +] + +[[package]] +name = "toml_datetime" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_edit" +version = "0.22.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" +dependencies = [ + "indexmap", + "serde", + "serde_spanned", + "toml_datetime", + "toml_write", + "winnow", +] + +[[package]] +name = "toml_write" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "wait-timeout" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11" +dependencies = [ + "libc", +] + +[[package]] +name = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b70935747edd64d89de3efa29d73789b806c15798f8e7dca4d8ac356b50ce70" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.77" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b7777d5cc23d0e91404e53ce2d5e8ec7acae3026b16233dba62cd3246457950" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77775f8f3f7217702089053b94958f8f54061a3f663417df76e19cbdcca29bc1" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e11d33f857dc2fb11b8bc75aee111aa9cbeb12cd9f25efd3d4c2a3dd4e235284" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 2.0.119", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ef64dbcc55df09c7e5a46182d181c2cfa3e925f3da937ea764728b4bbb9dcbf" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-sys" +version = "0.3.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c435338968042f4f59a557f690a253676d47ce13ceb55d70100e7facf6620a30" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[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.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" +dependencies = [ + "memchr", +] + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..617e0b7 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,37 @@ +[package] +name = "amendable-cli" +version = "0.1.0" +edition = "2021" +rust-version = "1.85" +description = "Command line client for Amendable Git storage" +license = "MIT" +authors = ["Launch Platform LLC"] +repository = "https://github.com/LaunchPlatform/amendable-cli" +homepage = "https://amendable.io" +documentation = "https://docs.amendable.io/cli/install/" +keywords = ["amendable", "git", "cli"] +categories = ["command-line-utilities"] +readme = "README.md" + +[lib] +name = "amendable_cli" +path = "src/lib.rs" + +[[bin]] +name = "amendable" +path = "src/main.rs" + +[dependencies] +clap = { version = "4.5", features = ["derive"] } +hostname = "0.4" +open = "5" +reqwest = { version = "0.12", default-features = false, features = ["blocking", "json", "rustls-tls"] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +toml = "0.8" + +[dev-dependencies] +assert_cmd = "2" +predicates = "3" +tempfile = "3" +tiny_http = "0.12" diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..a832f69 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Launch Platform LLC + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index c69960d..f3fb3ec 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,53 @@ # amendable-cli -Command line tool for Amendable.io + +Command line client for [Amendable](https://amendable.io). The command name is `amendable`. + +```bash +cargo install --git https://github.com/LaunchPlatform/amendable-cli --locked +amendable login +amendable repo create hello +amendable repo clone hello +``` + +Defaults are production (`https://api.amendable.io`). For staging: + +```bash +amendable login --staging +# or +export AMENDABLE_API_URL=https://stage.api.amendable.io +export AMENDABLE_APP_URL=https://stage.amendable.io +``` + +## Install from a checkout + +```bash +git clone https://github.com/LaunchPlatform/amendable-cli.git +cd amendable-cli +cargo install --path . --locked +amendable --help +``` + +Requires Rust 1.85+ ([rustup](https://rustup.rs/)). + +## Config + +`~/.config/amendable/config.toml` (created on `login`, mode `0600`): + +```toml +api_url = "https://api.amendable.io" +app_url = "https://amendable.io" +token = "..." +username = "yourname" +``` + +Override with `AMENDABLE_TOKEN`, `AMENDABLE_API_URL`, `AMENDABLE_APP_URL`, `AMENDABLE_USERNAME`, or `AMENDABLE_CONFIG`. + +## Tests + +```bash +cargo test +cargo fmt --check +cargo clippy --all-targets -- -D warnings +``` + +Product docs: https://docs.amendable.io/cli/install/ diff --git a/rust-toolchain.toml b/rust-toolchain.toml new file mode 100644 index 0000000..73cb934 --- /dev/null +++ b/rust-toolchain.toml @@ -0,0 +1,3 @@ +[toolchain] +channel = "stable" +components = ["rustfmt", "clippy"] diff --git a/src/cli.rs b/src/cli.rs new file mode 100644 index 0000000..692243d --- /dev/null +++ b/src/cli.rs @@ -0,0 +1,862 @@ +use std::io; +use std::io::IsTerminal; +use std::io::Read; +use std::io::Write; +use std::thread; +use std::time::Duration; + +use clap::Parser; +use clap::Subcommand; +use serde_json::Value; + +use crate::client::Client; +use crate::config; +use crate::config::Config; +use crate::error::Error; + +#[derive(Parser)] +#[command( + name = "amendable", + about = "Create and use Amendable Git repositories from the command line.", + version, + arg_required_else_help = true +)] +struct Cli { + /// Talk to stage.amendable.io (site, Git, and stage.api.amendable.io). + #[arg(long, global = true)] + staging: bool, + #[command(subcommand)] + command: Commands, +} + +#[derive(Subcommand)] +enum Commands { + /// Open a browser grant and store an access token. + Login { + /// Label shown on the grant page. Defaults to this machine. + #[arg(long)] + hostname: Option, + /// How often to poll for the grant. + #[arg(long, default_value_t = 2.0)] + poll_seconds: f64, + }, + /// Remove the stored access token. + Logout, + /// Show the stored username and current usage. + Whoami { + #[arg(long)] + json: bool, + }, + /// Show repository, storage, and transfer usage. + Usage { + #[arg(long)] + json: bool, + }, + /// Git credential helper. Configure with: + /// git config --global credential.https://amendable.io.helper '!amendable git-credential' + #[command(name = "git-credential")] + GitCredential { + /// Action appended by Git. `get` prints username and password. + action: Option, + }, + /// Exchange an OIDC ID token for a short-lived Amendable access token. + #[command(name = "oidc-exchange")] + OidcExchange { + /// OIDC ID token from GitHub Actions, GitLab, or another issuer. + #[arg(long)] + id_token: String, + #[arg(long)] + json: bool, + }, + /// Create, list, clone, and delete repositories. + #[command(subcommand_required = true, arg_required_else_help = true)] + Repo { + #[command(subcommand)] + command: RepoCommand, + }, + /// Create and list access tokens. + #[command(subcommand_required = true, arg_required_else_help = true)] + Token { + #[command(subcommand)] + command: TokenCommand, + }, + /// Create, ping, and inspect webhooks. + #[command(subcommand_required = true, arg_required_else_help = true)] + Webhook { + #[command(subcommand)] + command: WebhookCommand, + }, +} + +#[derive(Subcommand)] +enum RepoCommand { + /// List repositories the current token can see. + List { + #[arg(long)] + json: bool, + }, + /// Create a repository. Needs the API_REPOS_WRITE grant (or ALL). + Create { + /// Repository name (lowercase, hyphens, underscores). + name: String, + #[arg(short, long)] + description: Option, + /// Verified BYO bucket id. Optional. + #[arg(long)] + storage_bucket_id: Option, + /// Clone into ./NAME after create. + #[arg(long)] + clone: bool, + #[arg(long)] + json: bool, + }, + /// Show one repository. + Get { + /// NAME or owner/NAME. + name: String, + #[arg(long)] + json: bool, + }, + /// Delete a repository. Needs API_REPOS_WRITE (or ALL). + Delete { + /// NAME or owner/NAME. + name: String, + #[arg(short = 'y', long)] + yes: bool, + }, + /// Clone a repository over HTTPS using your stored token. + Clone { + /// NAME or owner/NAME. + name: String, + /// Target directory. + directory: Option, + }, + /// Print the HTTPS clone URL. + Url { + /// NAME or owner/NAME. + name: String, + }, +} + +#[derive(Subcommand)] +enum TokenCommand { + /// List access tokens. Needs ALL + ALL_REPO on the calling token. + List { + #[arg(long)] + json: bool, + }, + /// Create an access token. The secret is printed once. + Create { + #[arg(long)] + name: Option, + /// ALL_REPO or SELECTED_REPO. + #[arg(long, default_value = "ALL_REPO")] + scope: String, + /// Comma-separated grants. Example: GIT_HTTP_READ,GIT_HTTP_WRITE,API_REPOS_WRITE. + #[arg(long, default_value = "ALL")] + grants: String, + /// Comma-separated repo UUIDs for SELECTED_REPO. + #[arg(long)] + repository_ids: Option, + #[arg(long)] + json: bool, + }, + /// Delete an access token. + Delete { token_id: String }, +} + +#[derive(Subcommand)] +enum WebhookCommand { + /// List account webhooks. + List { + #[arg(long)] + json: bool, + }, + /// Create a webhook. The signing secret is printed once. + Create { + url: String, + /// Comma-separated: push,create,delete,ping. + #[arg(long, default_value = "push")] + events: String, + #[arg(long)] + json: bool, + }, + /// Send a ping event so you can verify HMAC and connectivity. + Ping { + webhook_id: String, + #[arg(long)] + json: bool, + }, + /// List recent deliveries. + Deliveries { + webhook_id: String, + #[arg(long)] + include_payload: bool, + #[arg(long)] + json: bool, + }, + /// Delete a webhook. + Delete { webhook_id: String }, +} + +pub fn try_run() -> Result<(), Error> { + let cli = Cli::parse(); + execute(cli) +} + +fn execute(cli: Cli) -> Result<(), Error> { + if cli.staging { + config::apply_staging_env(); + } + match cli.command { + Commands::Login { + hostname, + poll_seconds, + } => login(hostname, poll_seconds, cli.staging), + Commands::Logout => logout(), + Commands::Whoami { json } | Commands::Usage { json } => whoami(json), + Commands::GitCredential { action } => git_credential(action.as_deref()), + Commands::OidcExchange { id_token, json } => oidc_exchange(&id_token, json), + Commands::Repo { command } => match command { + RepoCommand::List { json } => repo_list(json), + RepoCommand::Create { + name, + description, + storage_bucket_id, + clone, + json, + } => repo_create( + &name, + description.as_deref(), + storage_bucket_id.as_deref(), + clone, + json, + ), + RepoCommand::Get { name, json } => repo_get(&name, json), + RepoCommand::Delete { name, yes } => repo_delete(&name, yes), + RepoCommand::Clone { name, directory } => repo_clone(&name, directory.as_deref()), + RepoCommand::Url { name } => repo_url(&name), + }, + Commands::Token { command } => match command { + TokenCommand::List { json } => token_list(json), + TokenCommand::Create { + name, + scope, + grants, + repository_ids, + json, + } => token_create( + name.as_deref(), + &scope, + &grants, + repository_ids.as_deref(), + json, + ), + TokenCommand::Delete { token_id } => token_delete(&token_id), + }, + Commands::Webhook { command } => match command { + WebhookCommand::List { json } => webhook_list(json), + WebhookCommand::Create { url, events, json } => webhook_create(&url, &events, json), + WebhookCommand::Ping { webhook_id, json } => webhook_ping(&webhook_id, json), + WebhookCommand::Deliveries { + webhook_id, + include_payload, + json, + } => webhook_deliveries(&webhook_id, include_payload, json), + WebhookCommand::Delete { webhook_id } => webhook_delete(&webhook_id), + }, + } +} + +fn login(hostname: Option, poll_seconds: f64, staging: bool) -> Result<(), Error> { + let mut cfg = Config::load()?; + if staging { + cfg.use_staging(); + } + let host = match hostname { + Some(value) => value, + None => current_hostname(), + }; + let client = Client::new(&cfg.api_url, cfg.token.as_deref())?; + let session = client.create_auth_session(&host)?; + let auth_url = required_str(&session, "auth_url")?; + let code = required_str(&session, "code")?; + let session_id = required_str(&session, "id")?; + let secret_token = required_str(&session, "secret_token")?; + println!("Compare this code with the page in your browser:"); + println!(" {code}"); + println!("Grant URL: {auth_url}"); + let _ = open::that(&auth_url); + println!("Waiting for you to grant access..."); + let delay = Duration::from_secs_f64(poll_seconds.max(0.0)); + loop { + thread::sleep(delay); + let result = client.poll_auth_session(&session_id, &secret_token)?; + if let Some(token) = result.get("token").and_then(Value::as_str) { + cfg.token = Some(token.to_string()); + if let Some(repos) = result.get("repositories").and_then(Value::as_array) { + if let Some(first) = repos.first().and_then(Value::as_str) { + if let Some((username, _)) = first.split_once('/') { + cfg.username = Some(username.to_string()); + } + } + } + cfg.save()?; + println!( + "Logged in. Token saved to {}", + config::config_path().display() + ); + if let Some(username) = &cfg.username { + println!("Username: {username}"); + } + return Ok(()); + } + } +} + +fn logout() -> Result<(), Error> { + let mut cfg = Config::load()?; + cfg.token = None; + cfg.save()?; + println!( + "Logged out. {} no longer has a token.", + config::config_path().display() + ); + Ok(()) +} + +fn whoami(json: bool) -> Result<(), Error> { + let mut cfg = Config::load()?; + let client = Client::new(&cfg.api_url, Some(cfg.require_token()?))?; + let usage = client.get_usage()?; + let username = infer_username(&mut cfg, &client)?; + let payload = serde_json::json!({ + "username": username, + "usage": usage, + }); + if json { + print_json(&payload)?; + return Ok(()); + } + println!("API: {}", cfg.api_url); + println!( + "Username: {}", + username.unwrap_or_else(|| "(unknown until you create a repository)".to_string()) + ); + print_quota("Repos", &usage["repos"], ""); + print_quota("Storage", &usage["storage_bytes"], " bytes"); + print_quota("Transfer this month", &usage["transfer_bytes"], " bytes"); + Ok(()) +} + +fn git_credential(action: Option<&str>) -> Result<(), Error> { + let cfg = Config::load()?; + if cfg.token.is_none() { + return Err(Error::NotLoggedIn); + } + let action = action.unwrap_or("").trim().to_ascii_lowercase(); + if action != "get" { + // Git also sends "store" and "erase". Ignore them. + return Ok(()); + } + let mut _fields = String::new(); + io::stdin().read_to_string(&mut _fields)?; + let username = cfg.username.as_deref().unwrap_or("amendable"); + let token = cfg.require_token()?; + let mut stdout = io::stdout(); + write!(stdout, "username={username}\npassword={token}\n\n")?; + Ok(()) +} + +fn oidc_exchange(id_token: &str, json: bool) -> Result<(), Error> { + let cfg = Config::load()?; + let client = Client::new(&cfg.api_url, None)?; + let payload = client.exchange_oidc_token(id_token)?; + if json { + print_json(&payload)?; + return Ok(()); + } + println!("{}", required_str(&payload, "token")?); + if let Some(expires) = payload.get("expires_at").and_then(Value::as_str) { + println!("expires_at: {expires}"); + } + Ok(()) +} + +fn repo_list(json: bool) -> Result<(), Error> { + let cfg = Config::load()?; + let client = Client::new(&cfg.api_url, Some(cfg.require_token()?))?; + let payload = client.list_repositories()?; + if json { + print_json(&payload)?; + return Ok(()); + } + let repos = payload + .get("repositories") + .and_then(Value::as_array) + .cloned() + .unwrap_or_default(); + if repos.is_empty() { + println!("No repositories yet. Create one with `amendable repo create`."); + return Ok(()); + } + let mut rows = Vec::new(); + for repo in &repos { + let username = repo.get("username").and_then(Value::as_str).unwrap_or(""); + let name = repo.get("name").and_then(Value::as_str).unwrap_or(""); + let active = if repo.get("active").and_then(Value::as_bool).unwrap_or(false) { + "yes" + } else { + "no" + }; + let source = repo + .get("storage_source") + .and_then(Value::as_str) + .unwrap_or("platform"); + rows.push(vec![ + format!("{username}/{name}"), + active.to_string(), + source.to_string(), + ]); + } + print_table(&["NAME", "ACTIVE", "STORAGE"], &rows); + Ok(()) +} + +fn repo_create( + name: &str, + description: Option<&str>, + storage_bucket_id: Option<&str>, + clone: bool, + json: bool, +) -> Result<(), Error> { + let mut cfg = Config::load()?; + let client = Client::new(&cfg.api_url, Some(cfg.require_token()?))?; + let repo = client.create_repository(name, description, storage_bucket_id)?; + if let Some(username) = repo.get("username").and_then(Value::as_str) { + cfg.username = Some(username.to_string()); + cfg.save()?; + } + if json { + print_json(&repo)?; + } else { + let username = required_str(&repo, "username")?; + let repo_name = required_str(&repo, "name")?; + let url = config::git_clone_url(&cfg.app_url, &username, &repo_name); + println!("Created {username}/{repo_name}"); + println!("Clone: {url}"); + } + if clone { + let username = required_str(&repo, "username")?; + let repo_name = required_str(&repo, "name")?; + clone_repo(&cfg, &username, &repo_name, None)?; + } + Ok(()) +} + +fn repo_get(name: &str, json: bool) -> Result<(), Error> { + let mut cfg = Config::load()?; + let client = Client::new(&cfg.api_url, Some(cfg.require_token()?))?; + let username = infer_username(&mut cfg, &client)?; + let (owner, repo_name) = parse_repo(name, username.as_deref())?; + let repo = client.get_repository(&owner, &repo_name)?; + if json { + print_json(&repo)?; + return Ok(()); + } + let username = required_str(&repo, "username")?; + let repo_name = required_str(&repo, "name")?; + let url = config::git_clone_url(&cfg.app_url, &username, &repo_name); + println!("{username}/{repo_name}"); + println!( + "Active: {}", + repo.get("active") + .map(|v| v.to_string()) + .unwrap_or_else(|| "null".into()) + ); + println!( + "Storage: {}", + repo.get("storage_source") + .and_then(Value::as_str) + .unwrap_or("null") + ); + println!("Clone: {url}"); + Ok(()) +} + +fn repo_delete(name: &str, yes: bool) -> Result<(), Error> { + let mut cfg = Config::load()?; + let client = Client::new(&cfg.api_url, Some(cfg.require_token()?))?; + let username = infer_username(&mut cfg, &client)?; + let (owner, repo_name) = parse_repo(name, username.as_deref())?; + if !yes { + confirm_delete(&owner, &repo_name)?; + } + client.delete_repository(&owner, &repo_name)?; + println!("Deleted {owner}/{repo_name}"); + Ok(()) +} + +fn repo_clone(name: &str, directory: Option<&str>) -> Result<(), Error> { + let mut cfg = Config::load()?; + let client = Client::new(&cfg.api_url, Some(cfg.require_token()?))?; + let username = infer_username(&mut cfg, &client)?; + let (owner, repo_name) = parse_repo(name, username.as_deref())?; + clone_repo(&cfg, &owner, &repo_name, directory) +} + +fn repo_url(name: &str) -> Result<(), Error> { + let mut cfg = Config::load()?; + let client = Client::new(&cfg.api_url, Some(cfg.require_token()?))?; + let username = infer_username(&mut cfg, &client)?; + let (owner, repo_name) = parse_repo(name, username.as_deref())?; + println!( + "{}", + config::git_clone_url(&cfg.app_url, &owner, &repo_name) + ); + Ok(()) +} + +fn token_list(json: bool) -> Result<(), Error> { + let cfg = Config::load()?; + let client = Client::new(&cfg.api_url, Some(cfg.require_token()?))?; + let payload = client.list_access_tokens()?; + if json { + print_json(&payload)?; + return Ok(()); + } + let mut rows = Vec::new(); + if let Some(items) = payload.get("access_tokens").and_then(Value::as_array) { + for item in items { + let grants = match item.get("grants") { + Some(Value::Array(values)) => values + .iter() + .filter_map(Value::as_str) + .collect::>() + .join(", "), + _ => String::new(), + }; + rows.push(vec![ + item.get("id").and_then(Value::as_str).unwrap_or("").into(), + item.get("name") + .and_then(Value::as_str) + .unwrap_or("") + .into(), + item.get("scope") + .and_then(Value::as_str) + .unwrap_or("") + .into(), + grants, + ]); + } + } + print_table(&["ID", "NAME", "SCOPE", "GRANTS"], &rows); + Ok(()) +} + +fn token_create( + name: Option<&str>, + scope: &str, + grants: &str, + repository_ids: Option<&str>, + json: bool, +) -> Result<(), Error> { + let cfg = Config::load()?; + let grant_list = split_csv(grants); + let repo_ids = repository_ids.map(split_csv); + let client = Client::new(&cfg.api_url, Some(cfg.require_token()?))?; + let created = client.create_access_token(name, scope, &grant_list, repo_ids.as_deref())?; + if json { + print_json(&created)?; + return Ok(()); + } + println!("Created token {}", required_str(&created, "id")?); + if let Some(token) = created.get("token").and_then(Value::as_str) { + println!("Secret (shown once):"); + println!("{token}"); + } + Ok(()) +} + +fn token_delete(token_id: &str) -> Result<(), Error> { + let cfg = Config::load()?; + let client = Client::new(&cfg.api_url, Some(cfg.require_token()?))?; + client.delete_access_token(token_id)?; + println!("Deleted {token_id}"); + Ok(()) +} + +fn webhook_list(json: bool) -> Result<(), Error> { + let cfg = Config::load()?; + let client = Client::new(&cfg.api_url, Some(cfg.require_token()?))?; + let payload = client.list_webhooks()?; + if json { + print_json(&payload)?; + return Ok(()); + } + let mut rows = Vec::new(); + if let Some(hooks) = payload.get("webhooks").and_then(Value::as_array) { + for hook in hooks { + let events = match hook.get("events") { + Some(Value::Array(values)) => values + .iter() + .filter_map(Value::as_str) + .collect::>() + .join(", "), + _ => String::new(), + }; + let active = if hook.get("active").and_then(Value::as_bool).unwrap_or(false) { + "yes" + } else { + "no" + }; + rows.push(vec![ + hook.get("id").and_then(Value::as_str).unwrap_or("").into(), + hook.get("url").and_then(Value::as_str).unwrap_or("").into(), + events, + active.into(), + ]); + } + } + print_table(&["ID", "URL", "EVENTS", "ACTIVE"], &rows); + Ok(()) +} + +fn webhook_create(url: &str, events: &str, json: bool) -> Result<(), Error> { + let cfg = Config::load()?; + let event_list = split_csv(events); + let client = Client::new(&cfg.api_url, Some(cfg.require_token()?))?; + let created = client.create_webhook(url, &event_list)?; + if json { + print_json(&created)?; + return Ok(()); + } + println!("Created webhook {}", required_str(&created, "id")?); + if let Some(secret) = created.get("secret").and_then(Value::as_str) { + println!("Signing secret (shown once):"); + println!("{secret}"); + } + Ok(()) +} + +fn webhook_ping(webhook_id: &str, json: bool) -> Result<(), Error> { + let cfg = Config::load()?; + let client = Client::new(&cfg.api_url, Some(cfg.require_token()?))?; + let payload = client.ping_webhook(webhook_id)?; + if json { + print_json(&payload)?; + return Ok(()); + } + println!( + "Ping queued. delivery_id={}", + required_str(&payload, "delivery_id")? + ); + Ok(()) +} + +fn webhook_deliveries(webhook_id: &str, include_payload: bool, json: bool) -> Result<(), Error> { + let cfg = Config::load()?; + let client = Client::new(&cfg.api_url, Some(cfg.require_token()?))?; + let payload = client.list_webhook_deliveries(webhook_id, include_payload)?; + if json { + print_json(&payload)?; + return Ok(()); + } + let mut rows = Vec::new(); + if let Some(deliveries) = payload.get("deliveries").and_then(Value::as_array) { + for row in deliveries { + rows.push(vec![ + row.get("id").and_then(Value::as_str).unwrap_or("").into(), + row.get("event_type") + .and_then(Value::as_str) + .unwrap_or("") + .into(), + row.get("status") + .and_then(Value::as_str) + .unwrap_or("") + .into(), + row.get("response_code") + .map(|v| match v { + Value::Null => String::new(), + other => other.to_string(), + }) + .unwrap_or_default(), + ]); + } + } + print_table(&["ID", "TYPE", "STATUS", "HTTP"], &rows); + Ok(()) +} + +fn webhook_delete(webhook_id: &str) -> Result<(), Error> { + let cfg = Config::load()?; + let client = Client::new(&cfg.api_url, Some(cfg.require_token()?))?; + client.delete_webhook(webhook_id)?; + println!("Deleted {webhook_id}"); + Ok(()) +} + +fn clone_repo( + cfg: &Config, + username: &str, + name: &str, + directory: Option<&str>, +) -> Result<(), Error> { + let url = config::git_clone_url(&cfg.app_url, username, name); + let token = cfg.require_token()?; + let mut parsed = reqwest::Url::parse(&url).map_err(|err| Error::message(err.to_string()))?; + let _ = parsed.set_username(username); + let _ = parsed.set_password(Some(token)); + let mut args = vec!["clone".to_string(), parsed.to_string()]; + if let Some(directory) = directory { + args.push(directory.to_string()); + } + let status = std::process::Command::new("git").args(&args).status()?; + if !status.success() { + return Err(Error::Git(status.code().unwrap_or(1))); + } + let target = directory.unwrap_or(name); + let _ = std::process::Command::new("git") + .args(["-C", target, "remote", "set-url", "origin", &url]) + .status(); + let _ = std::process::Command::new("git") + .args([ + "-C", + target, + "config", + "credential.helper", + "!amendable git-credential", + ]) + .status(); + Ok(()) +} + +fn infer_username(cfg: &mut Config, client: &Client) -> Result, Error> { + if let Some(username) = &cfg.username { + return Ok(Some(username.clone())); + } + let payload = client.list_repositories()?; + let repos = payload + .get("repositories") + .and_then(Value::as_array) + .cloned() + .unwrap_or_default(); + if let Some(username) = repos + .first() + .and_then(|repo| repo.get("username")) + .and_then(Value::as_str) + { + cfg.username = Some(username.to_string()); + cfg.save()?; + return Ok(cfg.username.clone()); + } + Ok(None) +} + +fn parse_repo(value: &str, username: Option<&str>) -> Result<(String, String), Error> { + if let Some((owner, name)) = value.split_once('/') { + return Ok((owner.to_string(), name.to_string())); + } + match username { + Some(username) => Ok((username.to_string(), value.to_string())), + None => Err(Error::message( + "Pass owner/name, or set a username with `amendable login`.", + )), + } +} + +fn confirm_delete(owner: &str, repo_name: &str) -> Result<(), Error> { + if !io::stdin().is_terminal() { + return Err(Error::message(format!( + "Delete {owner}/{repo_name}? Pass --yes to confirm." + ))); + } + eprint!("Delete {owner}/{repo_name}? [y/N] "); + io::stderr().flush()?; + let mut line = String::new(); + io::stdin().read_line(&mut line)?; + match line.trim() { + "y" | "Y" | "yes" | "YES" => Ok(()), + _ => Err(Error::Aborted), + } +} + +fn print_json(payload: &Value) -> Result<(), Error> { + println!("{}", serde_json::to_string_pretty(payload)?); + Ok(()) +} + +fn print_table(headers: &[&str], rows: &[Vec]) { + let mut widths: Vec = headers.iter().map(|header| header.len()).collect(); + for row in rows { + for (i, cell) in row.iter().enumerate() { + if i < widths.len() { + widths[i] = widths[i].max(cell.len()); + } + } + } + let format_row = |cells: &[String]| { + cells + .iter() + .enumerate() + .map(|(i, cell)| { + format!( + "{cell:>() + .join(" ") + }; + let header_cells: Vec = headers.iter().map(|s| (*s).to_string()).collect(); + println!("{}", format_row(&header_cells)); + for row in rows { + println!("{}", format_row(row)); + } +} + +fn print_quota(label: &str, value: &Value, unit: &str) { + let used = value + .get("used") + .map(value_to_display) + .unwrap_or_else(|| "0".into()); + match value.get("quota") { + Some(Value::Null) | None => println!("{label}: {used}{unit}"), + Some(quota) => println!("{label}: {used}{unit} / {}", value_to_display(quota)), + } +} + +fn value_to_display(value: &Value) -> String { + match value { + Value::String(text) => text.clone(), + Value::Number(number) => number.to_string(), + Value::Bool(flag) => flag.to_string(), + Value::Null => "null".into(), + other => other.to_string(), + } +} + +fn required_str(payload: &Value, key: &str) -> Result { + payload + .get(key) + .and_then(Value::as_str) + .map(str::to_string) + .ok_or_else(|| Error::message(format!("missing field {key} in API response"))) +} + +fn split_csv(value: &str) -> Vec { + value + .split(',') + .map(str::trim) + .filter(|part| !part.is_empty()) + .map(str::to_string) + .collect() +} + +fn current_hostname() -> String { + hostname::get() + .ok() + .and_then(|value| value.into_string().ok()) + .filter(|value| !value.is_empty()) + .unwrap_or_else(|| "unknown".to_string()) +} diff --git a/src/client.rs b/src/client.rs new file mode 100644 index 0000000..0c3eb2d --- /dev/null +++ b/src/client.rs @@ -0,0 +1,310 @@ +use serde_json::Value; + +use crate::error::Error; + +const USER_AGENT: &str = concat!("amendable-cli/", env!("CARGO_PKG_VERSION")); + +pub struct Client { + api_url: String, + token: Option, + http: reqwest::blocking::Client, +} + +impl Client { + pub fn new(api_url: &str, token: Option<&str>) -> Result { + let http = reqwest::blocking::Client::builder() + .timeout(std::time::Duration::from_secs(30)) + .user_agent(USER_AGENT) + .build()?; + Ok(Self { + api_url: api_url.trim_end_matches('/').to_string(), + token: token.map(str::to_string), + http, + }) + } + + fn headers(&self, auth: bool) -> Result { + let mut headers = reqwest::header::HeaderMap::new(); + headers.insert( + reqwest::header::ACCEPT, + reqwest::header::HeaderValue::from_static("application/json"), + ); + if auth { + let token = self.token.as_deref().ok_or(Error::NotLoggedIn)?; + headers.insert( + "access-token", + reqwest::header::HeaderValue::from_str(token) + .map_err(|err| Error::message(err.to_string()))?, + ); + } + Ok(headers) + } + + pub fn request( + &self, + method: reqwest::Method, + path: &str, + auth: bool, + json: Option<&Value>, + query: &[(&str, String)], + expected: &[u16], + ) -> Result { + let url = format!("{}{path}", self.api_url); + let mut builder = self.http.request(method, url).headers(self.headers(auth)?); + if !query.is_empty() { + builder = builder.query(query); + } + if let Some(body) = json { + builder = builder.json(body); + } + let response = builder.send()?; + let status = response.status().as_u16(); + if !expected.contains(&status) { + let detail = match response.json::() { + Ok(payload) => detail_from_body(&payload), + Err(_) => "request failed".to_string(), + }; + return Err(Error::api(status, detail)); + } + if status == 204 { + return Ok(Value::Null); + } + let bytes = response.bytes()?; + if bytes.is_empty() { + return Ok(Value::Null); + } + Ok(serde_json::from_slice(&bytes)?) + } + + pub fn create_auth_session(&self, hostname: &str) -> Result { + self.request( + reqwest::Method::POST, + "/v1/auth/sessions", + false, + Some(&serde_json::json!({ "hostname": hostname })), + &[], + &[201], + ) + } + + pub fn poll_auth_session(&self, session_id: &str, secret_token: &str) -> Result { + self.request( + reqwest::Method::GET, + &format!("/v1/auth/sessions/{session_id}/poll"), + false, + None, + &[("secret_token", secret_token.to_string())], + &[200, 202], + ) + } + + pub fn list_repositories(&self) -> Result { + self.request( + reqwest::Method::GET, + "/v1/repositories", + true, + None, + &[], + &[200], + ) + } + + pub fn create_repository( + &self, + name: &str, + description: Option<&str>, + storage_bucket_id: Option<&str>, + ) -> Result { + let mut body = serde_json::Map::new(); + body.insert("name".into(), Value::String(name.to_string())); + if let Some(description) = description.filter(|v| !v.is_empty()) { + body.insert("description".into(), Value::String(description.to_string())); + } + if let Some(storage_bucket_id) = storage_bucket_id.filter(|v| !v.is_empty()) { + body.insert( + "storage_bucket_id".into(), + Value::String(storage_bucket_id.to_string()), + ); + } + self.request( + reqwest::Method::POST, + "/v1/repositories", + true, + Some(&Value::Object(body)), + &[], + &[201], + ) + } + + pub fn get_repository(&self, username: &str, name: &str) -> Result { + self.request( + reqwest::Method::GET, + &format!("/v1/repos/{username}/{name}"), + true, + None, + &[], + &[200], + ) + } + + pub fn delete_repository(&self, username: &str, name: &str) -> Result<(), Error> { + self.request( + reqwest::Method::DELETE, + &format!("/v1/repos/{username}/{name}"), + true, + None, + &[], + &[204], + )?; + Ok(()) + } + + pub fn get_usage(&self) -> Result { + self.request( + reqwest::Method::GET, + "/v1/account/usage", + true, + None, + &[], + &[200], + ) + } + + pub fn list_access_tokens(&self) -> Result { + self.request( + reqwest::Method::GET, + "/v1/access-tokens", + true, + None, + &[], + &[200], + ) + } + + pub fn create_access_token( + &self, + name: Option<&str>, + scope: &str, + grants: &[String], + repository_ids: Option<&[String]>, + ) -> Result { + let mut body = serde_json::json!({ + "name": name, + "scope": scope, + "grants": grants, + }); + if let Some(ids) = repository_ids.filter(|v| !v.is_empty()) { + body["repository_ids"] = serde_json::json!(ids); + } + self.request( + reqwest::Method::POST, + "/v1/access-tokens", + true, + Some(&body), + &[], + &[201], + ) + } + + pub fn delete_access_token(&self, token_id: &str) -> Result<(), Error> { + self.request( + reqwest::Method::DELETE, + &format!("/v1/access-tokens/{token_id}"), + true, + None, + &[], + &[204], + )?; + Ok(()) + } + + pub fn list_webhooks(&self) -> Result { + self.request( + reqwest::Method::GET, + "/v1/webhooks", + true, + None, + &[], + &[200], + ) + } + + pub fn create_webhook(&self, url: &str, events: &[String]) -> Result { + self.request( + reqwest::Method::POST, + "/v1/webhooks", + true, + Some(&serde_json::json!({ + "url": url, + "events": events, + "active": true, + })), + &[], + &[201], + ) + } + + pub fn ping_webhook(&self, webhook_id: &str) -> Result { + self.request( + reqwest::Method::POST, + &format!("/v1/webhooks/{webhook_id}/ping"), + true, + None, + &[], + &[202], + ) + } + + pub fn delete_webhook(&self, webhook_id: &str) -> Result<(), Error> { + self.request( + reqwest::Method::DELETE, + &format!("/v1/webhooks/{webhook_id}"), + true, + None, + &[], + &[204], + )?; + Ok(()) + } + + pub fn list_webhook_deliveries( + &self, + webhook_id: &str, + include_payload: bool, + ) -> Result { + self.request( + reqwest::Method::GET, + &format!("/v1/webhooks/{webhook_id}/deliveries"), + true, + None, + &[( + "include_payload", + if include_payload { + "true".into() + } else { + "false".into() + }, + )], + &[200], + ) + } + + pub fn exchange_oidc_token(&self, id_token: &str) -> Result { + self.request( + reqwest::Method::POST, + "/v1/oidc/token", + false, + Some(&serde_json::json!({ "id_token": id_token })), + &[], + &[200], + ) + } +} + +fn detail_from_body(payload: &Value) -> String { + match payload.get("detail") { + Some(Value::String(text)) => text.clone(), + Some(other) => other.to_string(), + None => payload.to_string(), + } +} diff --git a/src/config.rs b/src/config.rs new file mode 100644 index 0000000..779f785 --- /dev/null +++ b/src/config.rs @@ -0,0 +1,213 @@ +use std::env; +use std::fs; +use std::path::PathBuf; + +#[cfg(unix)] +use std::os::unix::fs::PermissionsExt; + +use serde::Deserialize; +use serde::Serialize; + +use crate::error::Error; + +pub const DEFAULT_API_URL: &str = "https://api.amendable.io"; +pub const DEFAULT_APP_URL: &str = "https://amendable.io"; +pub const STAGING_API_URL: &str = "https://stage.api.amendable.io"; +pub const STAGING_APP_URL: &str = "https://stage.amendable.io"; + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +struct FileConfig { + #[serde(skip_serializing_if = "Option::is_none")] + api_url: Option, + #[serde(skip_serializing_if = "Option::is_none")] + app_url: Option, + #[serde(skip_serializing_if = "Option::is_none")] + token: Option, + #[serde(skip_serializing_if = "Option::is_none")] + username: Option, +} + +#[derive(Debug, Clone)] +pub struct Config { + pub api_url: String, + pub app_url: String, + pub token: Option, + pub username: Option, +} + +impl Config { + pub fn load() -> Result { + let mut data = FileConfig::default(); + let path = config_path(); + if path.is_file() { + let text = fs::read_to_string(&path)?; + data = toml::from_str(&text)?; + } + let api_url = env::var("AMENDABLE_API_URL") + .ok() + .filter(|v| !v.is_empty()) + .or(data.api_url) + .unwrap_or_else(|| DEFAULT_API_URL.to_string()); + let app_url = env::var("AMENDABLE_APP_URL") + .ok() + .filter(|v| !v.is_empty()) + .or(data.app_url) + .unwrap_or_else(|| DEFAULT_APP_URL.to_string()); + let token = env::var("AMENDABLE_TOKEN") + .ok() + .filter(|v| !v.is_empty()) + .or(data.token); + let username = env::var("AMENDABLE_USERNAME") + .ok() + .filter(|v| !v.is_empty()) + .or(data.username); + Ok(Self { + api_url: trim_slash(&api_url), + app_url: trim_slash(&app_url), + token, + username, + }) + } + + pub fn save(&self) -> Result<(), Error> { + let path = config_path(); + if let Some(parent) = path.parent() { + fs::create_dir_all(parent)?; + } + let file = FileConfig { + api_url: Some(self.api_url.clone()), + app_url: Some(self.app_url.clone()), + token: self.token.clone(), + username: self.username.clone(), + }; + let text = toml::to_string(&file)?; + fs::write(&path, text)?; + #[cfg(unix)] + { + fs::set_permissions(&path, fs::Permissions::from_mode(0o600))?; + } + Ok(()) + } + + pub fn require_token(&self) -> Result<&str, Error> { + self.token.as_deref().ok_or(Error::NotLoggedIn) + } + + pub fn use_staging(&mut self) { + self.api_url = STAGING_API_URL.to_string(); + self.app_url = STAGING_APP_URL.to_string(); + } +} + +pub fn config_dir() -> PathBuf { + if let Ok(xdg) = env::var("XDG_CONFIG_HOME") { + if !xdg.is_empty() { + return PathBuf::from(xdg).join("amendable"); + } + } + home_dir() + .unwrap_or_else(|| PathBuf::from(".")) + .join(".config") + .join("amendable") +} + +pub fn config_path() -> PathBuf { + if let Ok(override_path) = env::var("AMENDABLE_CONFIG") { + if !override_path.is_empty() { + return PathBuf::from(override_path); + } + } + config_dir().join("config.toml") +} + +pub fn apply_staging_env() { + env::set_var("AMENDABLE_API_URL", STAGING_API_URL); + env::set_var("AMENDABLE_APP_URL", STAGING_APP_URL); +} + +pub fn git_clone_url(app_url: &str, username: &str, name: &str) -> String { + format!( + "{}/r/{}/{}.git", + app_url.trim_end_matches('/'), + username, + name + ) +} + +fn trim_slash(value: &str) -> String { + value.trim_end_matches('/').to_string() +} + +fn home_dir() -> Option { + env::var_os("HOME") + .or_else(|| env::var_os("USERPROFILE")) + .map(PathBuf::from) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Mutex; + + static ENV_LOCK: Mutex<()> = Mutex::new(()); + + fn unique_config() -> (tempfile::TempDir, PathBuf) { + let dir = tempfile::tempdir().expect("tempdir"); + let path = dir.path().join("config.toml"); + (dir, path) + } + + #[test] + fn default_hosts_are_production() { + let _guard = ENV_LOCK.lock().unwrap(); + let (_dir, path) = unique_config(); + env::set_var("AMENDABLE_CONFIG", &path); + env::remove_var("AMENDABLE_API_URL"); + env::remove_var("AMENDABLE_APP_URL"); + env::remove_var("AMENDABLE_TOKEN"); + env::remove_var("AMENDABLE_USERNAME"); + let cfg = Config::load().unwrap(); + assert_eq!(cfg.api_url, DEFAULT_API_URL); + assert_eq!(cfg.app_url, DEFAULT_APP_URL); + assert_eq!(cfg.api_url, "https://api.amendable.io"); + } + + #[test] + fn use_staging_sets_hosts() { + let _guard = ENV_LOCK.lock().unwrap(); + let (_dir, path) = unique_config(); + env::set_var("AMENDABLE_CONFIG", &path); + env::remove_var("AMENDABLE_API_URL"); + env::remove_var("AMENDABLE_APP_URL"); + env::remove_var("AMENDABLE_TOKEN"); + env::remove_var("AMENDABLE_USERNAME"); + let mut cfg = Config::load().unwrap(); + cfg.use_staging(); + assert_eq!(cfg.api_url, STAGING_API_URL); + assert_eq!(cfg.app_url, STAGING_APP_URL); + cfg.save().unwrap(); + let loaded = Config::load().unwrap(); + assert_eq!(loaded.api_url, STAGING_API_URL); + assert_eq!(loaded.app_url, STAGING_APP_URL); + } + + #[test] + fn apply_staging_env_overrides_file() { + let _guard = ENV_LOCK.lock().unwrap(); + let (_dir, path) = unique_config(); + fs::write( + &path, + "api_url = \"https://api.amendable.io\"\napp_url = \"https://amendable.io\"\n", + ) + .unwrap(); + env::set_var("AMENDABLE_CONFIG", &path); + env::remove_var("AMENDABLE_TOKEN"); + env::remove_var("AMENDABLE_USERNAME"); + apply_staging_env(); + let cfg = Config::load().unwrap(); + assert_eq!(cfg.api_url, STAGING_API_URL); + assert_eq!(cfg.app_url, STAGING_APP_URL); + env::remove_var("AMENDABLE_API_URL"); + env::remove_var("AMENDABLE_APP_URL"); + } +} diff --git a/src/error.rs b/src/error.rs new file mode 100644 index 0000000..4eaece1 --- /dev/null +++ b/src/error.rs @@ -0,0 +1,108 @@ +use std::fmt; +use std::io; +use std::process::ExitCode; + +#[derive(Debug)] +pub enum Error { + Api { status: u16, detail: String }, + NotLoggedIn, + Message(String), + Io(io::Error), + Http(reqwest::Error), + Json(serde_json::Error), + TomlDe(toml::de::Error), + TomlSer(toml::ser::Error), + Git(i32), + Aborted, +} + +impl Error { + pub fn api(status: u16, detail: impl Into) -> Self { + Self::Api { + status, + detail: detail.into(), + } + } + + pub fn message(msg: impl Into) -> Self { + Self::Message(msg.into()) + } + + pub fn exit_code(&self) -> u8 { + match self { + Self::Git(code) => (*code).clamp(1, 255) as u8, + _ => 1, + } + } + + pub fn print(&self) { + match self { + Self::Api { status, detail } => eprintln!("{status} {detail}"), + Self::NotLoggedIn => { + eprintln!("Not logged in. Run `amendable login` or set AMENDABLE_TOKEN."); + } + Self::Aborted => eprintln!("Aborted."), + Self::Git(_) => {} + other => eprintln!("{other}"), + } + } + + pub fn exit(self) -> ExitCode { + self.print(); + ExitCode::from(self.exit_code()) + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Api { status, detail } => write!(f, "{status}: {detail}"), + Self::NotLoggedIn => { + write!( + f, + "Not logged in. Run `amendable login` or set AMENDABLE_TOKEN." + ) + } + Self::Message(msg) => write!(f, "{msg}"), + Self::Io(err) => write!(f, "{err}"), + Self::Http(err) => write!(f, "{err}"), + Self::Json(err) => write!(f, "{err}"), + Self::TomlDe(err) => write!(f, "{err}"), + Self::TomlSer(err) => write!(f, "{err}"), + Self::Git(code) => write!(f, "git exited with status {code}"), + Self::Aborted => write!(f, "Aborted."), + } + } +} + +impl std::error::Error for Error {} + +impl From for Error { + fn from(err: io::Error) -> Self { + Self::Io(err) + } +} + +impl From for Error { + fn from(err: reqwest::Error) -> Self { + Self::Http(err) + } +} + +impl From for Error { + fn from(err: serde_json::Error) -> Self { + Self::Json(err) + } +} + +impl From for Error { + fn from(err: toml::de::Error) -> Self { + Self::TomlDe(err) + } +} + +impl From for Error { + fn from(err: toml::ser::Error) -> Self { + Self::TomlSer(err) + } +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..1e41108 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,19 @@ +//! Command line client for Amendable Git storage. + +pub mod client; +pub mod config; + +mod cli; +mod error; + +use std::process::ExitCode; + +pub use error::Error; + +/// Parse argv and run a command. Process exit happens here. +pub fn run() -> ExitCode { + match cli::try_run() { + Ok(()) => ExitCode::SUCCESS, + Err(err) => err.exit(), + } +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..a2fb872 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,5 @@ +use std::process::ExitCode; + +fn main() -> ExitCode { + amendable_cli::run() +} diff --git a/tests/cli.rs b/tests/cli.rs new file mode 100644 index 0000000..2186cf3 --- /dev/null +++ b/tests/cli.rs @@ -0,0 +1,272 @@ +mod common; + +use std::fs; + +use assert_cmd::Command; +use predicates::prelude::PredicateBooleanExt; +use predicates::str::contains; +use tempfile::TempDir; + +use common::MockApiServer; +use common::SAMPLE_TOKEN; +use common::SAMPLE_USERNAME; +use common::SAMPLE_WEBHOOK_ID; + +struct Harness { + _dir: TempDir, + config: std::path::PathBuf, +} + +impl Harness { + fn logged_in(server: &MockApiServer) -> Self { + let dir = TempDir::new().expect("tempdir"); + let config = dir.path().join("config.toml"); + fs::write( + &config, + format!( + "api_url = \"{}\"\napp_url = \"https://amendable.io\"\ntoken = \"{SAMPLE_TOKEN}\"\nusername = \"{SAMPLE_USERNAME}\"\n", + server.url + ), + ) + .expect("write config"); + Self { _dir: dir, config } + } + + fn empty(server: &MockApiServer) -> Self { + let dir = TempDir::new().expect("tempdir"); + let config = dir.path().join("config.toml"); + fs::write(&config, format!("api_url = \"{}\"\n", server.url)).expect("write config"); + Self { _dir: dir, config } + } + + fn cmd(&self) -> Command { + let mut cmd = Command::cargo_bin("amendable").expect("binary"); + cmd.env("AMENDABLE_CONFIG", &self.config) + .env_remove("AMENDABLE_TOKEN") + .env_remove("AMENDABLE_API_URL") + .env_remove("AMENDABLE_APP_URL") + .env_remove("AMENDABLE_USERNAME"); + cmd + } +} + +#[test] +fn repo_list() { + let server = MockApiServer::start(); + server.grant(); + let harness = Harness::logged_in(&server); + harness + .cmd() + .args(["repo", "list", "--json"]) + .assert() + .success() + .stdout(contains("agent-workspace")); +} + +#[test] +fn repo_create() { + let server = MockApiServer::start(); + server.grant(); + let harness = Harness::logged_in(&server); + harness + .cmd() + .args(["repo", "create", "new-repo", "--json"]) + .assert() + .success() + .stdout(contains("new-repo").and(contains(SAMPLE_USERNAME))); +} + +#[test] +fn repo_get_and_url() { + let server = MockApiServer::start(); + server.grant(); + let harness = Harness::logged_in(&server); + harness + .cmd() + .args(["repo", "get", "agent-workspace", "--json"]) + .assert() + .success() + .stdout(contains("agent-workspace")); + harness + .cmd() + .args(["repo", "url", "demo/agent-workspace"]) + .assert() + .success() + .stdout(contains("https://amendable.io/r/demo/agent-workspace.git")); +} + +#[test] +fn repo_delete() { + let server = MockApiServer::start(); + server.grant(); + let harness = Harness::logged_in(&server); + harness + .cmd() + .args(["repo", "delete", "agent-workspace", "--yes"]) + .assert() + .success(); + harness + .cmd() + .args(["repo", "list", "--json"]) + .assert() + .success() + .stdout(contains("agent-workspace").not()); +} + +#[test] +fn whoami_usage() { + let server = MockApiServer::start(); + server.grant(); + let harness = Harness::logged_in(&server); + harness + .cmd() + .args(["whoami", "--json"]) + .assert() + .success() + .stdout(contains("\"used\": 1")); +} + +#[test] +fn token_create_and_list() { + let server = MockApiServer::start(); + server.grant(); + let harness = Harness::logged_in(&server); + harness + .cmd() + .args([ + "token", + "create", + "--name", + "ci", + "--grants", + "GIT_HTTP_READ,GIT_HTTP_WRITE,API_REPOS_WRITE", + "--json", + ]) + .assert() + .success() + .stdout(contains("NEWTOKENSHOWNONCE")); + harness + .cmd() + .args(["token", "list", "--json"]) + .assert() + .success() + .stdout(contains("GIT_HTTP_WRITE")); +} + +#[test] +fn webhook_create_ping_delete() { + let server = MockApiServer::start(); + server.grant(); + let harness = Harness::logged_in(&server); + harness + .cmd() + .args([ + "webhook", + "create", + "https://example.com/hooks/amendable", + "--events", + "push,ping", + "--json", + ]) + .assert() + .success() + .stdout(contains("webhook-secret-shown-once")); + harness + .cmd() + .args(["webhook", "ping", SAMPLE_WEBHOOK_ID]) + .assert() + .success(); + harness + .cmd() + .args(["webhook", "delete", SAMPLE_WEBHOOK_ID]) + .assert() + .success(); +} + +#[test] +fn login_polls_until_granted() { + let server = MockApiServer::start(); + let dir = TempDir::new().expect("tempdir"); + let config = dir.path().join("config.toml"); + fs::write( + &config, + format!( + "api_url = \"{}\"\napp_url = \"https://amendable.io\"\n", + server.url + ), + ) + .expect("write config"); + server.grant(); + Command::cargo_bin("amendable") + .expect("binary") + .args(["login", "--hostname", "testhost", "--poll-seconds", "0.01"]) + .env("AMENDABLE_CONFIG", &config) + .env_remove("AMENDABLE_TOKEN") + .env_remove("AMENDABLE_API_URL") + .env_remove("AMENDABLE_APP_URL") + .env_remove("AMENDABLE_USERNAME") + .assert() + .success(); + let saved = fs::read_to_string(&config).expect("read config"); + assert!(saved.contains(SAMPLE_TOKEN), "{saved}"); + assert!(saved.contains(SAMPLE_USERNAME), "{saved}"); +} + +#[test] +fn oidc_exchange() { + let server = MockApiServer::start(); + server.grant(); + let harness = Harness::logged_in(&server); + harness + .cmd() + .args([ + "oidc-exchange", + "--id-token", + "header.payload.sig", + "--json", + ]) + .assert() + .success() + .stdout(contains(SAMPLE_TOKEN).and(contains("expires_at"))); +} + +#[test] +fn missing_token_fails() { + let server = MockApiServer::start(); + server.grant(); + let harness = Harness::empty(&server); + harness + .cmd() + .args(["repo", "list"]) + .assert() + .failure() + .stderr(contains("Not logged in")); +} + +#[test] +fn git_credential_get() { + let server = MockApiServer::start(); + server.grant(); + let harness = Harness::logged_in(&server); + harness + .cmd() + .args(["git-credential", "get"]) + .write_stdin("protocol=https\nhost=amendable.io\n\n") + .assert() + .success() + .stdout(contains(format!("username={SAMPLE_USERNAME}"))) + .stdout(contains(format!("password={SAMPLE_TOKEN}"))); +} + +#[test] +fn git_credential_store_is_ignored() { + let server = MockApiServer::start(); + server.grant(); + let harness = Harness::logged_in(&server); + harness + .cmd() + .args(["git-credential", "store"]) + .write_stdin("protocol=https\nhost=amendable.io\n\n") + .assert() + .success(); +} diff --git a/tests/common/mod.rs b/tests/common/mod.rs new file mode 100644 index 0000000..2971e14 --- /dev/null +++ b/tests/common/mod.rs @@ -0,0 +1,374 @@ +use std::io::Cursor; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::Ordering; +use std::sync::Arc; +use std::sync::Mutex; +use std::thread; +use std::thread::JoinHandle; +use std::time::Duration; + +use serde_json::json; +use serde_json::Value; +use tiny_http::Header; +use tiny_http::Method; +use tiny_http::Request; +use tiny_http::Response; +use tiny_http::Server; +use tiny_http::StatusCode; + +pub const SAMPLE_TOKEN: &str = "5Q2exampleAccessTokenForTestsOnly"; +pub const SAMPLE_USERNAME: &str = "demo"; +pub const SAMPLE_REPO: &str = "agent-workspace"; +pub const SAMPLE_WEBHOOK_ID: &str = "22222222-2222-2222-2222-222222222222"; +pub const SAMPLE_WEBHOOK_SECRET: &str = "webhook-secret-shown-once"; +pub const SAMPLE_AUTH_ID: &str = "33333333-3333-3333-3333-333333333333"; +pub const SAMPLE_AUTH_CODE: &str = "AB12-CD34"; +pub const SAMPLE_AUTH_SECRET: &str = "auth-session-secret"; + +pub struct MockState { + pub granted: bool, + pub repositories: Vec, + pub webhooks: Vec, + pub tokens: Vec, + pub usage: Value, +} + +impl Default for MockState { + fn default() -> Self { + Self { + granted: false, + repositories: vec![json!({ + "username": SAMPLE_USERNAME, + "name": SAMPLE_REPO, + "active": true, + "storage_source": "platform", + })], + webhooks: Vec::new(), + tokens: Vec::new(), + usage: json!({ + "repos": {"used": 1, "quota": 5}, + "storage_bytes": {"used": 1024, "quota": 1073741824_i64}, + "transfer_bytes": {"used": 2048, "quota": 5368709120_i64}, + "ingress_bytes": {"used": 512, "quota": null}, + }), + } + } +} + +pub struct MockApiServer { + pub url: String, + state: Arc>, + running: Arc, + thread: Option>, +} + +impl MockApiServer { + pub fn start() -> Self { + let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind mock api"); + let addr = listener.local_addr().expect("local addr"); + let url = format!("http://{addr}"); + let server = Server::from_listener(listener, None).expect("tiny_http server"); + let state = Arc::new(Mutex::new(MockState::default())); + let running = Arc::new(AtomicBool::new(true)); + let thread_state = Arc::clone(&state); + let thread_running = Arc::clone(&running); + let thread = thread::spawn(move || { + while thread_running.load(Ordering::SeqCst) { + match server.recv_timeout(Duration::from_millis(50)) { + Ok(Some(request)) => handle(&thread_state, request), + Ok(None) => {} + Err(_) => break, + } + } + }); + Self { + url, + state, + running, + thread: Some(thread), + } + } + + pub fn grant(&self) { + self.state.lock().expect("state").granted = true; + } +} + +impl Drop for MockApiServer { + fn drop(&mut self) { + self.running.store(false, Ordering::SeqCst); + if let Some(thread) = self.thread.take() { + let _ = thread.join(); + } + } +} + +fn handle(state: &Arc>, mut request: Request) { + let url = request.url().to_string(); + let (path, query) = split_url(&url); + let method = request.method().clone(); + let token = header_value(&request, "access-token"); + let body = read_json(&mut request); + + let response = match method { + Method::Get => do_get(state, &path, &query, token.as_deref()), + Method::Post => do_post(state, &path, token.as_deref(), body), + Method::Delete => do_delete(state, &path, token.as_deref()), + _ => json_response(404, json!({"detail": "Not found"})), + }; + let _ = request.respond(response); +} + +fn do_get( + state: &Arc>, + path: &str, + query: &[(String, String)], + token: Option<&str>, +) -> Response>> { + if path.starts_with("/v1/auth/sessions/") && path.ends_with("/poll") { + let secret = query + .iter() + .find(|(k, _)| k == "secret_token") + .map(|(_, v)| v.as_str()); + if secret != Some(SAMPLE_AUTH_SECRET) { + return json_response(404, json!({"detail": "Auth session not found"})); + } + let granted = state.lock().expect("state").granted; + if !granted { + return json_response( + 202, + json!({"code": "try_again", "message": "still waiting for auth"}), + ); + } + return json_response( + 200, + json!({ + "token": SAMPLE_TOKEN, + "repositories": [format!("{SAMPLE_USERNAME}/{SAMPLE_REPO}")], + }), + ); + } + if !require_token(token) { + return unauthorized(); + } + let state = state.lock().expect("state"); + if path == "/v1/repositories" { + return json_response(200, json!({"repositories": state.repositories})); + } + if path == "/v1/account/usage" { + return json_response(200, state.usage.clone()); + } + if path == "/v1/access-tokens" { + return json_response(200, json!({"access_tokens": state.tokens})); + } + if path == "/v1/webhooks" { + return json_response(200, json!({"webhooks": state.webhooks})); + } + if path.starts_with("/v1/repos/") && path.ends_with("/branches") { + return json_response( + 200, + json!({ + "default_branch": "main", + "branches": [] + }), + ); + } + if path.starts_with("/v1/repos/") { + let parts: Vec<&str> = path.split('/').collect(); + if parts.len() >= 5 { + let username = parts[3]; + let name = parts[4]; + if let Some(repo) = state + .repositories + .iter() + .find(|repo| repo["username"] == username && repo["name"] == name) + { + return json_response(200, repo.clone()); + } + return json_response(404, json!({"detail": "Repo not found"})); + } + } + if path.contains("/deliveries") { + return json_response(200, json!({"deliveries": []})); + } + json_response(404, json!({"detail": "Not found"})) +} + +fn do_post( + state: &Arc>, + path: &str, + token: Option<&str>, + body: Value, +) -> Response>> { + if path == "/v1/auth/sessions" { + let hostname = body + .get("hostname") + .and_then(Value::as_str) + .unwrap_or("unknown"); + return json_response( + 201, + json!({ + "id": SAMPLE_AUTH_ID, + "code": SAMPLE_AUTH_CODE, + "auth_url": format!( + "https://amendable.io/access-tokens/create?auth_session_id={SAMPLE_AUTH_ID}" + ), + "secret_token": SAMPLE_AUTH_SECRET, + "hostname": hostname, + }), + ); + } + if path == "/v1/oidc/token" { + if body.get("id_token").and_then(Value::as_str).is_none() { + return json_response(401, json!({"detail": "Invalid ID token"})); + } + return json_response( + 200, + json!({ + "token": SAMPLE_TOKEN, + "token_type": "access-token", + "expires_at": "2026-08-23T01:30:00+00:00", + }), + ); + } + if !require_token(token) { + return unauthorized(); + } + let mut state = state.lock().expect("state"); + if path == "/v1/repositories" { + let name = body["name"].as_str().unwrap_or("unnamed"); + let repo = json!({ + "username": SAMPLE_USERNAME, + "name": name, + "active": true, + "description": body.get("description"), + "storage_source": "platform", + "storage_bucket_id": body.get("storage_bucket_id"), + }); + state.repositories.push(repo.clone()); + return json_response(201, repo); + } + if path == "/v1/access-tokens" { + let created = json!({ + "id": "44444444-4444-4444-4444-444444444444", + "name": body.get("name"), + "scope": body.get("scope"), + "grants": body.get("grants"), + "token": "NEWTOKENSHOWNONCE", + "repositories": [], + }); + let mut listed = created.clone(); + listed.as_object_mut().expect("object").remove("token"); + state.tokens.push(listed); + return json_response(201, created); + } + if path == "/v1/webhooks" { + let created = json!({ + "id": SAMPLE_WEBHOOK_ID, + "url": body.get("url"), + "events": body.get("events").cloned().unwrap_or_else(|| json!(["push"])), + "active": body.get("active").and_then(Value::as_bool).unwrap_or(true), + "secret": SAMPLE_WEBHOOK_SECRET, + }); + let mut listed = created.clone(); + listed.as_object_mut().expect("object").remove("secret"); + state.webhooks.push(listed); + return json_response(201, created); + } + if path.ends_with("/ping") { + return json_response( + 202, + json!({ + "event_id": "55555555-5555-5555-5555-555555555555", + "delivery_id": "66666666-6666-6666-6666-666666666666", + }), + ); + } + json_response(404, json!({"detail": "Not found"})) +} + +fn do_delete( + state: &Arc>, + path: &str, + token: Option<&str>, +) -> Response>> { + if !require_token(token) { + return unauthorized(); + } + let mut state = state.lock().expect("state"); + if path.starts_with("/v1/repos/") { + let parts: Vec<&str> = path.split('/').collect(); + let username = parts[3]; + let name = parts[4]; + state + .repositories + .retain(|repo| !(repo["username"] == username && repo["name"] == name)); + return empty(204); + } + if path.starts_with("/v1/access-tokens/") { + let token_id = path.rsplit('/').next().unwrap_or(""); + state.tokens.retain(|item| item["id"] != token_id); + return empty(204); + } + if path.starts_with("/v1/webhooks/") { + let webhook_id = path.rsplit('/').next().unwrap_or(""); + state.webhooks.retain(|item| item["id"] != webhook_id); + return empty(204); + } + json_response(404, json!({"detail": "Not found"})) +} + +fn require_token(token: Option<&str>) -> bool { + token == Some(SAMPLE_TOKEN) +} + +fn unauthorized() -> Response>> { + json_response(401, json!({"detail": "Unauthorized"})) +} + +fn json_response(status: u16, payload: Value) -> Response>> { + let body = serde_json::to_vec(&payload).expect("json"); + Response::from_data(body) + .with_status_code(StatusCode(status)) + .with_header(Header::from_bytes(&b"Content-Type"[..], &b"application/json"[..]).unwrap()) +} + +fn empty(status: u16) -> Response>> { + Response::from_data(Vec::new()).with_status_code(StatusCode(status)) +} + +fn split_url(url: &str) -> (String, Vec<(String, String)>) { + match url.split_once('?') { + Some((path, query)) => { + let pairs = query + .split('&') + .filter_map(|pair| { + let (key, value) = pair.split_once('=')?; + Some((key.to_string(), value.to_string())) + }) + .collect(); + (path.to_string(), pairs) + } + None => (url.to_string(), Vec::new()), + } +} + +fn header_value(request: &Request, name: &str) -> Option { + request.headers().iter().find_map(|header| { + if header.field.as_str().as_str().eq_ignore_ascii_case(name) { + Some(header.value.as_str().to_string()) + } else { + None + } + }) +} + +fn read_json(request: &mut Request) -> Value { + let mut buf = String::new(); + let _ = std::io::Read::read_to_string(request.as_reader(), &mut buf); + if buf.trim().is_empty() { + json!({}) + } else { + serde_json::from_str(&buf).unwrap_or_else(|_| json!({})) + } +}