diff --git a/.github/pr-template.md b/.github/pr-template.md new file mode 100644 index 0000000..cd4d9be --- /dev/null +++ b/.github/pr-template.md @@ -0,0 +1,15 @@ +## Summary + + + +## Release line + + + +## Checklist + +- [ ] `just ci` passes +- [ ] Tests cover the change; a new or changed adapter has a `parse` test against a recorded fixture +- [ ] Changed snapshots were stepped through with `just review` +- [ ] Docs are current: `docs/reference/contract.md` for flags or output, an ADR for a decision, ADR 0004 and `docs/synthesis/terms.md` for a new source +- [ ] Re-recorded fixtures are trimmed, carry no key, and have every personal e-mail address replaced diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..ffd96f9 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,186 @@ +# Release builds once release-plz has published a GitHub release: a wheel and +# a binary archive per platform, the archives attached to the release and the +# wheels sent to PyPI. release-plz owns the version, the tag and crates.io +# (docs/reference/release.md). One machine per platform, because these are the +# only jobs that must run on macOS and Windows (ADR 0017). A pull request that +# changes the release build runs the builds without publishing anything. +name: release + +on: + release: + types: [published] + pull_request: + paths: + - .github/workflows/release.yml + - pyproject.toml + +permissions: {} + +jobs: + build: + name: build ${{ matrix.target }} + runs-on: ${{ matrix.runner }} + timeout-minutes: 30 + permissions: + contents: read + strategy: + fail-fast: false + matrix: + include: + - runner: ubuntu-latest + target: x86_64-unknown-linux-gnu + native: true + # ring's ARM assembly needs a GCC that defines __ARM_ARCH, which the + # manylinux2014 cross image's GCC does not. + - runner: ubuntu-latest + target: aarch64-unknown-linux-gnu + manylinux: 2_28 + - runner: macos-latest + target: aarch64-apple-darwin + native: true + - runner: macos-latest + target: x86_64-apple-darwin + - runner: windows-latest + target: x86_64-pc-windows-msvc + native: true + steps: + - name: checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: wheel + uses: PyO3/maturin-action@e83996d129638aa358a18fbd1dfb82f0b0fb5d3b # v1.51.0 + with: + maturin-version: v1.15.0 + target: ${{ matrix.target }} + manylinux: ${{ matrix.manylinux || 'auto' }} + args: --release --locked --out dist + # The binaries the wheel carries, archived under the name cargo binstall + # looks for: dataseek-.tar.gz, or .zip on Windows. + - name: archive + shell: bash + env: + TARGET: ${{ matrix.target }} + NATIVE: ${{ matrix.native }} + run: | + dir="dataseek-$TARGET" + ext="" + [[ $TARGET == *windows* ]] && ext=".exe" + mkdir -p "$dir" archives + cp "target/$TARGET/release/dataseek$ext" "target/$TARGET/release/dsk$ext" README.md LICENSE-MIT LICENSE-APACHE "$dir/" + if [[ $TARGET == *windows* ]]; then + archive="$dir.zip" + 7z a -bd "archives/$archive" "$dir" > /dev/null + else + archive="$dir.tar.gz" + tar czf "archives/$archive" "$dir" + fi + cd archives + if command -v sha256sum > /dev/null; then + sha256sum "$archive" > "$archive.sha256" + else + shasum -a 256 "$archive" > "$archive.sha256" + fi + if [[ $NATIVE == true ]]; then + "../$dir/dataseek$ext" --version + fi + - name: upload wheel + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: wheel-${{ matrix.target }} + path: dist/*.whl + if-no-files-found: error + - name: upload archive + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: archive-${{ matrix.target }} + path: archives/* + if-no-files-found: error + + sdist: + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: read + steps: + - name: checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: build + uses: PyO3/maturin-action@e83996d129638aa358a18fbd1dfb82f0b0fb5d3b # v1.51.0 + with: + maturin-version: v1.15.0 + command: sdist + args: --out dist + - name: upload + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: sdist + path: dist/*.tar.gz + if-no-files-found: error + + assets: + if: github.event_name == 'release' + needs: build + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: write + id-token: write + attestations: write + steps: + - name: harden runner + uses: step-security/harden-runner@e14015d583714f6e62063499dc959a02595150a1 # v2.21.1 + with: + egress-policy: audit + - name: download + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + pattern: archive-* + path: archives + merge-multiple: true + - name: attest + uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2 + with: + subject-path: archives/dataseek-* + - name: attach + env: + GH_TOKEN: ${{ github.token }} + REPO: ${{ github.repository }} + TAG: ${{ github.event.release.tag_name }} + run: gh release upload "$TAG" archives/* --repo "$REPO" --clobber + + # PyPI's trusted publisher names this workflow file and the pypi + # environment; uv exchanges the job's OIDC token, so no PyPI token exists. + pypi: + if: github.event_name == 'release' + needs: [build, sdist] + runs-on: ubuntu-latest + timeout-minutes: 10 + environment: pypi + permissions: + id-token: write + steps: + - name: harden runner + uses: step-security/harden-runner@e14015d583714f6e62063499dc959a02595150a1 # v2.21.1 + with: + egress-policy: audit + - name: download wheels + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + pattern: wheel-* + path: dist + merge-multiple: true + - name: download sdist + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: sdist + path: dist + - name: uv + uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0 + with: + version: 0.12.21 + enable-cache: false + - name: publish + run: uv publish --trusted-publishing always dist/* diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..e9feead --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,50 @@ +# Contributing + +Bug reports, fixes and new sources are welcome. For anything larger than a fix, open an issue first, so the idea is settled before the code is written. Report vulnerabilities privately, as [`docs/SECURITY.md`](docs/SECURITY.md) describes. + +## Setup + +[`docs/reference/setup.md`](docs/reference/setup.md) lists the toolchain and the tools the recipes call. Run `prek install` once, so formatting, clippy, `cargo-shear` and `typos` run on every commit. + +## While you work + +```sh +just check # fmt --check, clippy -D warnings, tests, doctests +just test # a subset of the tests +just review # step through changed help and output snapshots +just ci # everything CI gates on; run it before opening a pull request +``` + +A green `just ci` means a green CI run on your platform. + +## Commits and pull requests + +Write [conventional commits](https://www.conventionalcommits.org). The prefix decides what gets released: `feat:` cuts a minor release, `fix:`, `perf:` and `refactor:` a patch, `doc:`, `build:` and `chore:` only reach the changelog, and `test:` and `ci:` stay out of it. The full table is in [`docs/reference/release.md`](docs/reference/release.md). + +Each subject becomes a line in the changelog, so write it for someone who runs `dsk`, not for a reviewer: "fix: a 403 with a spent quota reads as rate limited, not as rejected credentials" rather than "fix: map 403 to RateLimited". A pull request with several commits is merged with a merge commit, so make each commit stand on its own. + +Leave the version in `Cargo.toml` and `docs/CHANGELOG.md` alone; the release tooling writes both. + +## Tests + +No test touches the network. Each adapter splits its request from a pure `parse`, and each `parse` is tested against a real response recorded in `tests/fixtures/sources/`, with the expected record read off the fixture by hand, never pasted from the code's own output. + +When you record or re-record a fixture, never send a key, trim the arrays to a few rows, and replace any person's e-mail address with `contact@example.org`. The exact steps, and where each kind of test belongs, are in [`docs/reference/development.md`](docs/reference/development.md). Commit any new file proptest writes to `proptest-regressions/`. + +## Code + +The lints in `Cargo.toml` deny `unwrap`, `expect`, `panic!`, indexing, unchecked arithmetic and direct printing outside tests. Write code that satisfies them rather than adding an `allow`. Results go to stdout only through `src/output.rs`, and everything else to stderr through `src/ui.rs`. [`docs/reference/contract.md`](docs/reference/contract.md) defines the flags, streams, errors and exit codes, and a change to any of them is a change to that document. + +## Adding a source + +A source is one row in `SOURCES` in `src/sources.rs` and at most one module under `src/sources/`. Before writing a module, check whether a protocol adapter (CKAN, Dataverse, NADA, Socrata, STAC, SDMX, EBI) already covers it; then the source is only a row ([ADR 0005](docs/adr/0005-one-adapter-per-shared-protocol.md)). + +A source is complete with: + +- a recorded fixture and a `parse` test against it +- its row in the source table of [ADR 0004](docs/adr/0004-every-source-is-searched.md) +- its row in [`docs/synthesis/terms.md`](docs/synthesis/terms.md), quoting the provider's terms that allow a public tool to query it this way + +## Proposing something bigger + +Read [`docs/adr/`](docs/adr/) first: it records why dataseek is built the way it is. [`docs/adr/watchlist.md`](docs/adr/watchlist.md) lists what is parked and the trigger that would bring each item back; if your idea is there, say what has changed. diff --git a/Cargo.toml b/Cargo.toml index 240d41b..ff037ee 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,10 +2,16 @@ name = "dataseek" version = "0.7.0" description = "Search for datasets from the terminal" +license = "MIT OR Apache-2.0" repository = "https://github.com/lmarkmann/dataseek" +readme = "README.md" +keywords = ["dataset", "search", "open-data", "research", "cli"] +categories = ["command-line-utilities", "science"] edition = "2024" rust-version = "1.99" -publish = false +# What `cargo install` needs to build; tests, fixtures, benches and docs stay +# in the repository. +include = ["/src", "/build.rs", "/README.md", "/LICENSE-MIT", "/LICENSE-APACHE"] [lints.rust] unsafe_code = "forbid" @@ -68,8 +74,8 @@ rustls = { version = "0.23", default-features = false, features = ["std"] } ureq = { version = "3", features = ["json", "platform-verifier"] } [features] -# Re-exports for benches/ and the relevance example only; see the internals -# module in src/lib.rs. +# Re-exports for benches/ and the relevance example only; unstable and +# outside semver, see the internals module in src/lib.rs. internals = [] [dev-dependencies] diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 0000000..1b5ec8b --- /dev/null +++ b/LICENSE-APACHE @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 0000000..c98eff7 --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Luis Markmann + +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 c5cacef..54d9947 100644 --- a/README.md +++ b/README.md @@ -1,31 +1,70 @@ -# dataseek +![dataseek: every dataset source it searches, set out as a periodic table](https://raw.githubusercontent.com/lmarkmann/dataseek/main/docs/assets/dataseek-banner.png) + +[![ci](https://github.com/lmarkmann/dataseek/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/lmarkmann/dataseek/actions/workflows/ci.yml) [![latest release](https://img.shields.io/github/v/release/lmarkmann/dataseek)](https://github.com/lmarkmann/dataseek/releases/latest) Search for datasets from the terminal -One query, 76 dataset sources, one deduplicated list: machine-learning hubs (Hugging Face, Kaggle, OpenML), research repositories and DOI registries (DataCite, Zenodo, Dataverse), government portals (data.europa.eu, Data.gov, CKAN and Socrata portals), economics and finance (DBnomics, IMF, OECD, ECB, BIS, Bundesbank, FRED), earth observation (NASA CMR, STAC catalogs, Copernicus), life sciences, neuroscience, physics and social science archives. Google Dataset Search and Mendeley Data answer only when named with `-s` ([ADR 0013](docs/adr/0013-opt-in-sources.md)). `dsk` is the same program under a shorter name. +Datasets are scattered across dozens of archives: Hugging Face and Kaggle, Zenodo and Dataverse, data.gov and data.europa.eu, the IMF and the ECB, NASA and Copernicus. Each has its own search box, its own idea of relevance, and often its own copy of the same dataset. dataseek covers 76 of them, asks them at once and prints one list: a dataset found in three places shows up once with all three named, and results that several sources agree on, and that match more of your query, rank first. + +Most sources need no key and nothing to set up. Results come back in the terminal, as JSON for scripts, or to an AI client over MCP. Google Dataset Search and Mendeley Data are the exception: neither permits automated searches, so dataseek asks them only when you name them with `-s` ([ADR 0013](docs/adr/0013-opt-in-sources.md)). `dsk` is the same program under a shorter name. ## Install ```sh -cargo install --path . # installs dataseek and dsk +cargo install --locked dataseek # builds dataseek and dsk from source +cargo binstall dataseek # a prebuilt binary when the release has one, else builds +uv tool install dataseek # installs dataseek and dsk with uv +``` + +To run it once without installing: + +```sh +crgx --allow-build dataseek search sea surface temperature +uvx dataseek search sea surface temperature ``` +To upgrade, run the install command again, or `uv tool upgrade dataseek` for uv. Building from source needs a recent stable Rust toolchain; from a clone, `cargo install --locked --path .` does the same. + ## Usage ```sh -dsk search sea surface temperature # every default source, merged and ranked -dsk search mnist -s huggingface,kaggle # only these sources -dsk search inflation -c economics,finance # only these categories -dsk search census --json | jq -r '.results[].url' -dsk sources # every source, its protocol, key and docs -dsk inspect https://zenodo.org/records/13135140 # a page's metadata and the files it lists -dsk bench # latency and overlap of every source -dsk cache warm # download the catalogs searched locally +dsk search sea surface temperature # every default source, merged and ranked +dsk search mnist -s huggingface,kaggle # only these sources +dsk search inflation -c economics,finance # only these categories +dsk search census --json | jq -r '.results[].url' # one URL per line, for scripts +dsk sources # every source, its protocol, key and docs +dsk inspect https://zenodo.org/records/13135140 # a page's metadata and the files it lists +dsk bench # latency and overlap of every source +dsk cache warm # download the catalogs searched locally ``` -`dsk` alone shows the commands, `dsk help environment` the variables it reads, `dsk help exit-codes` what it returns. +`dsk search air quality -n 3` on a terminal: + +```text +- searching 71 sources for "air quality"; 3 need a key, see `dsk doctor` +1 Improving Indoor Air Quality for Poor Families: Controlled Experiments 2005-2006 + https://microdata.worldbank.org/catalog/396 + worldbank-microdata, ihsn | Susmita Dasgupta, Mainul Huq, M. Khaliquzzaman and David Wheeler | 2... + Indoor air pollution (IAP) is dangerously high for many poor families in Bangla... + +2 Air quality data in five counties in California + https://b2find.eudat.eu/dataset/f2611e4d-793c-5e55-950c-7a9979c772b8 + b2find, pangaea | PANGAEA | 2026-05-04 | doi:10.1594/pangaea.923005 + Air quality data used to identify time windows of the best air quality in the d... + +3 Historical Air Quality + https://data.calgary.ca/d/uqjm-jxgp + openaire, socrata | City of Calgary Open Data Portal | 2018-07-16 | See Terms of Use + This dataset makes historical air quality data accessible for various parameter... + + ✓ 3 of 359 results; 70 of 71 sources answered; -n 359 shows all +``` + +The first result was listed by both the World Bank and IHSN and appears once. Results go to stdout and the lines around them to stderr, so `dsk search ... > results.txt` keeps only the results. + +`dsk` alone shows the commands, `dsk help environment` the variables it reads, `dsk help exit-codes` what it returns. `cargo install` cannot install a man page or completions: `dsk man > ~/.local/share/man/man1/dsk.1` puts the page where `man dsk` finds it, and `dsk completion fish` (or `bash`, `zsh`) says where its script goes. Most sources need no key. FRED, Roboflow and Data Commons are skipped without their own; keys for Hugging Face, Kaggle, Data.gov, GitHub and NCBI raise limits. See [`docs/reference/keys-and-cache.md`](docs/reference/keys-and-cache.md). @@ -41,24 +80,41 @@ Most sources need no key. FRED, Roboflow and Data Commons are skipped without th } ``` -Each tool returns what its command prints with `--json`; keys are read from the environment the client starts it in, or from `credentials.toml`. [`docs/reference/contract.md`](docs/reference/contract.md#mcp-mode) has the details. +Each tool returns what its command prints with `--json`; keys are read from the environment the client starts it in, or from `credentials.toml`. Google Dataset Search and Mendeley Data stay opt-in here too; the model asks for them by naming them in the search tool's `source` argument. [`docs/reference/contract.md`](docs/reference/contract.md#mcp-mode) has the details. ## Development ```sh -just check # fmt --check + clippy -D warnings + tests -just ci # everything the CI job runs: check, startup bench, typos, Windows and macOS cross-check, shear, msrv, audit -just audit # cargo-deny + zizmor -just run search climate temperature +just check # fmt --check, clippy -D warnings, tests, doctests +just ci # everything CI gates on: check, relevance, startup bench, Windows and macOS cross-check, shear, msrv, audit, typos +just audit # cargo-deny, zizmor +just run search climate temperature # the CLI built from this checkout ``` ## Docs - [`docs/CHANGELOG.md`](docs/CHANGELOG.md): what shipped, written by release-plz. -- [`docs/reference/`](docs/reference/): setup, development, the CLI contract, keys and cache, security, and the release loop. -- [`docs/adr/`](docs/adr/): why it is built this way, including [the full source list](docs/adr/0004-every-source-is-searched.md), plus what was [rejected](docs/adr/rejected.md) and what is [parked](docs/adr/watchlist.md). Read both before proposing an addition. +- [`docs/reference/`](docs/reference/): setup, development, the CLI contract, keys and cache, the supply-chain gates, and the release loop. +- [`docs/adr/`](docs/adr/): why it is built this way, including [the full source list](docs/adr/0004-every-source-is-searched.md), plus what is [parked](docs/adr/watchlist.md). Read it before proposing an addition. ### Project notes - [`docs/bench/`](docs/bench/): measured speed of the search stages and of startup, each with the machine it ran on. - [`docs/synthesis/`](docs/synthesis/): how the sources' search interfaces differ, and the bench that measures them. + +## Data sources + +dataseek prints each result's publisher and link. When you reuse a dataset, cite or acknowledge its source the way that source asks. + +- This product uses the FRED® API but is not endorsed or certified by the Federal Reserve Bank of St. Louis. By using dataseek's `fred` source you agree to the [FRED® API Terms of Use](https://fred.stlouisfed.org/docs/api/terms_of_use.html). +- This product uses the Census Bureau Data API but is not endorsed or certified by the Census Bureau. +- NCBI results come through the E-utilities; NCBI's [disclaimer and copyright notice](https://www.ncbi.nlm.nih.gov/About/disclaimer.html) applies. +- WHO asks that its data be cited as "World Health Organization {YEAR} data.who.int, {ITEM_NAME} [{ITEM_TYPE}]. {URL} (Accessed on {ACCESS DATE})". + +## Contributing + +[`CONTRIBUTING.md`](CONTRIBUTING.md) covers setup, the commit prefixes that decide each release, the test rules and how to add a source. Report vulnerabilities privately, as [`SECURITY.md`](docs/SECURITY.md) describes. + +## License + +Licensed under either of [Apache License, Version 2.0](LICENSE-APACHE) or [MIT license](LICENSE-MIT), at your option. diff --git a/build.rs b/build.rs index 652393a..532c6eb 100644 --- a/build.rs +++ b/build.rs @@ -1,11 +1,24 @@ #![expect(missing_docs, reason = "build scripts are not a public API")] +use std::path::Path; use std::process::Command; +// A crates.io build has no `.git`, and a rerun-if-changed path that does not +// exist reruns the script on every build. A worktree's `.git` is a file, so +// git names the real HEAD and refs. fn main() { - println!("cargo::rerun-if-changed=.git/HEAD"); - println!("cargo::rerun-if-changed=.git/refs"); - println!("cargo::rustc-env=DATASEEK_GIT_SHA={}", built_from()); + let sha = if Path::new(".git").exists() { + for name in ["HEAD", "refs"] { + if let Some(path) = git(&["rev-parse", "--git-path", name]) { + println!("cargo::rerun-if-changed={path}"); + } + } + built_from() + } else { + println!("cargo::rerun-if-changed=build.rs"); + "unknown".to_owned() + }; + println!("cargo::rustc-env=DATASEEK_GIT_SHA={sha}"); } fn built_from() -> String { diff --git a/deny.toml b/deny.toml index 8fa8fad..4a63c97 100644 --- a/deny.toml +++ b/deny.toml @@ -16,9 +16,6 @@ allow = [ ] unused-allowed-license = "allow" -[licenses.private] -ignore = true - [bans] multiple-versions = "warn" wildcards = "deny" diff --git a/docs/SECURITY.md b/docs/SECURITY.md new file mode 100644 index 0000000..ed2c399 --- /dev/null +++ b/docs/SECURITY.md @@ -0,0 +1,25 @@ +# Security policy + +## Reporting a vulnerability + +Report it privately through [GitHub's advisory form](https://github.com/lmarkmann/dataseek/security/advisories/new). If you cannot use GitHub, write to contact@dataseek.dev. Please do not open a public issue for it. + +A useful report names the version (`dsk --version`), the platform, the command you ran, and what happened. When remote content triggers it, add the source id and the response body that does it; a saved file is enough. + +You will hear back within a week. The fix ships as a patch release, and the advisory is published with it, crediting you unless you ask not to be named. + +## Scope + +In scope: + +- The `dataseek` and `dsk` binaries, including the MCP server that `dsk mcp` runs. +- Keys: a key from the environment, `credentials.toml` or Kaggle's token files reaching a URL, an error message, a log line, the cache, or any host other than the source it belongs to ([ADR 0009](adr/0009-keys-and-contact-address.md)). +- The cache directory: remote text reaching a file path, or a cache file another local user can plant or read. +- Remote text driving the terminal: control characters or escape sequences from a source's response, a page `inspect` reads, or a source's own error message reaching stdout or stderr. +- The release pipeline: the workflows, the tags, and the binaries and wheels they publish. + +Out of scope: + +- The sources themselves. A source serving wrong, stale or misleading data, or a flaw in its own API, belongs with that provider. +- A vulnerability in a dependency that dataseek never reaches. Report it upstream; `cargo-deny` fails CI on any published RUSTSEC advisory ([`reference/supply-chain.md`](reference/supply-chain.md)). +- Attacks that start from control of your environment variables or your config directory. diff --git a/docs/adr/0001-release-plz-owns-the-version.md b/docs/adr/0001-release-plz-owns-the-version.md index 09f6baf..08a5b1c 100644 --- a/docs/adr/0001-release-plz-owns-the-version.md +++ b/docs/adr/0001-release-plz-owns-the-version.md @@ -5,7 +5,7 @@ ## Context -The version in `Cargo.toml`, the `vX.Y.Z` tag, the changelog section and the GitHub release have to move together. Done by hand they drift, which is why a hand-written `just release` recipe was rejected (`rejected.md`, 2026-07-27). +The version in `Cargo.toml`, the `vX.Y.Z` tag, the changelog section and the GitHub release have to move together. Done by hand they drift, which is why there is no hand-written `just release` recipe. ## Decision diff --git a/docs/adr/0007-cache-budget-and-failure-handling.md b/docs/adr/0007-cache-budget-and-failure-handling.md index abf8225..9db5a28 100644 --- a/docs/adr/0007-cache-budget-and-failure-handling.md +++ b/docs/adr/0007-cache-budget-and-failure-handling.md @@ -11,7 +11,7 @@ A search that waits for 75 hosts is only as fast as the slowest, and some hosts - **Cache** (`src/cache.rs`): one JSON file per entry under the XDG cache directory, written atomically. Query results live 6 hours, catalogs 7 days. The directory is trimmed to 30 MB and 2,000 files, oldest first, once per search (the entry cap follows yoink's bounded search cache). Kaggle results are never written, per Kaggle's terms. - **Deadline**: `search` prints what has arrived after `--timeout` seconds (default 20; 0 waits for all). Sources still working are reported as still running; their threads are detached. `dataseek cache warm` downloads every catalog with no deadline. -- **Failure isolation** (`src/search.rs`): each source runs on its own thread. A transient connect failure is retried once after 300 ms; a short `Retry-After` is honored once. An outage (unreachable, timeout, challenge page, HTTP 5xx) marks the source for 10 minutes and later searches skip it unless it is named with `--source`. A failed fetch serves the expired cache entry when one exists. A required key that is missing skips the source instead of failing it. +- **Failure isolation** (`src/search.rs`): each source runs on its own thread. A transient connect failure is retried once after 300 ms; a short `Retry-After` is honored once. An outage (unreachable, timeout, challenge page, HTTP 5xx, or a rate limit that outlasts the one honored retry) marks the source for 10 minutes and later searches skip it unless it is named with `--source`. A failed fetch serves the expired cache entry when one exists. A required key that is missing skips the source instead of failing it. - **Exit codes**: 0 when any source answered (even with no results), 1 when every attempted source failed or none could run. ## Consequences diff --git a/docs/adr/0009-keys-and-contact-address.md b/docs/adr/0009-keys-and-contact-address.md index 451dce4..c3e16a5 100644 --- a/docs/adr/0009-keys-and-contact-address.md +++ b/docs/adr/0009-keys-and-contact-address.md @@ -11,7 +11,7 @@ Eight sources take an API key (Hugging Face, Kaggle, data.gov, GitHub, FRED, Rob - A key is read from its environment variable, then from `credentials.toml` in the config directory. Kaggle additionally reads what its own CLI writes, `~/.kaggle/access_token` then the legacy `~/.kaggle/kaggle.json` (honoring `KAGGLE_CONFIG_DIR`), so a user who ran `kaggle auth` needs no setup. Without a token Kaggle is still asked, anonymously, and answers every page. - Secrets are never formatted into output; `sources` and `doctor` report only where a key came from. `doctor` fails a key file other users can read. -- Every request's User-Agent carries the project contact `user@dataseek.dev`, and DataCite and NCBI also receive it as `mailto`/`email`. It is the project's address, the same for every user; no user's address is ever sent. +- Every request's User-Agent is `dataseek/ (+https://github.com/lmarkmann/dataseek; mailto:user@dataseek.dev)`, so a provider can tell releases apart, find the project, and write to the maintainer; DataCite and NCBI also receive the address as `mailto`/`email`. It is the project's address, the same for every user; no user's address is ever sent. ## Consequences diff --git a/docs/adr/0017-release-builds-on-a-platform-matrix.md b/docs/adr/0017-release-builds-on-a-platform-matrix.md new file mode 100644 index 0000000..140eecf --- /dev/null +++ b/docs/adr/0017-release-builds-on-a-platform-matrix.md @@ -0,0 +1,22 @@ +# ADR 0017: Release builds run on a per-platform matrix + +- Status: accepted +- Date: 2026-10-07 + +## Context + +PyPI wheels and `cargo binstall` both need prebuilt binaries for Linux (x86_64, aarch64), macOS (aarch64, x86_64) and Windows (x86_64). ADR 0002 keeps CI to one Linux job, which cross-checks Windows and macOS with clippy but cannot produce their binaries. + +## Decision + +`.github/workflows/release.yml` runs when a GitHub release is published, which release-plz does when its release PR merges. One job per target builds the wheel with maturin, on a machine of the target's OS (Linux aarch64 in maturin's cross container), and archives the same binaries as `dataseek-.tar.gz` (`.zip` on Windows) with a SHA-256 file. The archives are attested and attached to the release; the wheels and an sdist go to PyPI with `uv publish` through trusted publishing. A pull request that changes the release build runs the builds and publishes nothing. CI stays one Linux job. + +## Consequences + +- Each release starts eight machines, two of them macOS. They run once per version, never per push. +- A build that fails fails only this workflow. The tag and GitHub release already exist, so the fix is a rerun or a patch release, never a retag. +- macOS and Windows binaries are built only at release and on pull requests that change the release build; the clippy cross-checks in CI still catch compile errors there. + +## Evidence + +`maturin build --release --locked --target aarch64-apple-darwin` packs both `dataseek` and `dsk` into one `py3-none-macosx_11_0_arm64` wheel, `uvx --from dsk --version` runs it, and the workflow's archive step, run locally on that build, produces `dataseek-aarch64-apple-darwin/{dataseek,dsk}` with its checksum (2026-10-07). diff --git a/docs/adr/README.md b/docs/adr/README.md index fe724eb..a2bf099 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -7,7 +7,6 @@ A decision that constrains future work lives here, once, and is cited from where | the fact | its home | |---|---| | a decision that would be expensive to reverse or tempting to re-litigate | **here**, one numbered file each | -| something considered and left out, with the date | [`rejected.md`](rejected.md) | | something parked as *not yet*, with the trigger that revisits it | [`watchlist.md`](watchlist.md) | | how to run, configure or extend something | [`../reference/`](../reference/) | | what reads across several dataset sources | [`../synthesis/`](../synthesis/) | @@ -39,3 +38,4 @@ A decision that constrains future work lives here, once, and is cited from where | [0014](0014-system-trust-store-on-every-platform.md) | Every platform trusts the system's root certificates | accepted | | [0015](0015-mcp-server-over-stdio.md) | `dsk mcp` is a hand-written stdio server that runs each tool as a child | accepted | | [0016](0016-rank-by-fusion-and-weighted-coverage.md) | Merge by identity, rank by fusion and rarity-weighted coverage | accepted | +| [0017](0017-release-builds-on-a-platform-matrix.md) | Release builds run on a per-platform matrix | accepted | diff --git a/docs/adr/rejected.md b/docs/adr/rejected.md deleted file mode 100644 index f009fb5..0000000 --- a/docs/adr/rejected.md +++ /dev/null @@ -1,311 +0,0 @@ -# Rejected - -Things that were considered and deliberately left out, with the reason and the date of the decision. The point is that a rejection stays rejected: without this file the same plausible-sounding addition gets re-proposed every few months and re-litigated from scratch. - -A rejection is not permanent. If the reason stops being true (an upstream interface stabilizes, a dependency changes behavior), that is a new entry, not a silent reversal. Ideas that were never rejected, only parked as *not yet*, live in [`watchlist.md`](watchlist.md) with the trigger that would revisit them. - -The template rule most of these fall out of: **anything a clone has to delete is worse than nothing**. A starter is judged by what it saves you, and a feature you did not ask for costs you a deletion plus the confidence that deleting it broke nothing. - -## 2026-07-27: Dynamic completions (`clap_complete`'s `CompleteEnv`) - -Needs the `unstable-dynamic` feature. `clap_complete-4.6.7/src/env/mod.rs` warns that the completions work by generating shell code that calls back into the binary, that this interface is unstable, and that a mismatch between the shell code and the binary yields either wrong completions or none. Upstream's own mitigation is to re-source the completions on every shell start rather than write them to a file. - -That is the wrong trade for a template. Clones get created and then not revisited; a completion mechanism that silently degrades on upgrade fails in exactly the situation this template is built for. The static `completion ` subcommand writes a file once and keeps working. - -## 2026-07-27: `human-panic`, `miette`, `bugreport`, and `vergen` commit-hash versions - -Each is a real improvement to *some* CLI, and each is a feature the clone has to delete when it is not that CLI. `human-panic` reframes a panic the lint config now forbids anyway. `miette` is a second error-rendering system next to the `Error:` / `Cause:` / `Try:` printer that already satisfies the contract. `bugreport` presumes an issue tracker and a user base. `vergen` puts a build-time git hash into `--version`, which breaks the single-source-version rule and makes the build depend on git metadata. - -## 2026-07-27: `trycmd` / `snapbox` - -Would replace a working `assert_cmd` + `insta` setup with a second snapshot system, so the template would ship two ways to assert on CLI output and no guidance on which to use. No capability gained. - -## 2026-07-27: A Ctrl-C cursor-restore handler - -Rejected because the bug it would fix does not exist here. The concern was a progress bar hiding the terminal cursor and a Ctrl-C leaving it hidden. Checked against the vendored source: `indicatif-0.18.6/src/` contains no `hide_cursor`, no `show_cursor`, and no `?25` escape anywhere, so it never touches the cursor and there is nothing to restore. - -Worth recording precisely because the reasoning was sound and the premise was still wrong. If a future dependency does start hiding the cursor, this becomes a real requirement. - -## 2026-07-27: Publishing to crates.io, binary release matrix, and Homebrew tap bump - -Inherited from the `celsius` release workflow the release automation was adapted from. Deleted: the crate is `publish = false`, so there is no registry release; a five-target binary matrix and a tap bump publish a template nobody installs. A clone that does want to ship re-adds these deliberately, which is one paragraph in `release.md`, rather than inheriting a workflow that fails or publishes something unintended on its first tag. - -## 2026-07-27: CodSpeed benchmark workflow - -Also inherited from `celsius`. It ran `cargo codspeed build --bench render` against a `benches/` directory this repo does not have, so it could only ever fail. A benchmark harness with nothing to benchmark is not a starting point. - -## 2026-07-27: GitHub releases and `cargo-semver-checks` in release-plz - -`git_release_enable = false`: with no binaries to attach, a GitHub release only duplicates the tag it was cut from. - -**Overturned 2026-09-25 for GitHub releases; `semver_check = false` stands.** The standing rule across the user's repositories is a tag and a GitHub release per version, the release body being that version's changelog section, so a reader of the Releases page gets the notes without opening the file. `git_release_enable = true` and `git_release_type = "auto"` now. - -`semver_check = false`: cargo-semver-checks compares the public API of a library. This crate is a binary and has no public API, so the check has nothing to compare. Turning it off also removed the 15-line custom `pr_body` template, which existed solely to surface the semver marker. - -## 2026-07-27: `release_always = true` (release-plz default) - -The default releases on every commit to `main`. Set to `false` so a tag is cut only when the release PR merges, which is the behavior actually wanted: the version bump is reviewable as a diff before it becomes a tag. - -## 2026-07-27: Hash-pinning GitHub Actions - -zizmor's `unpinned-uses` audit wants full commit SHAs; `.github/zizmor.yml` relaxes this to `ref-pin`. Tags are mutable, so this is a trust decision about the publishers (`actions/`, `dtolnay/`, `Swatinem/`, `EmbarkStudios/`, `release-plz/`, `zizmorcore/`) rather than a guarantee. - -Rejected because hash pins rot: they need Dependabot to refresh the SHAs, and a clone that never enables Dependabot ends up pinned to increasingly stale actions, which is worse than tag-pinning. This is machinery a template should not impose on every clone. - -**Re-checked 2026-09-04, and the entry holds.** The question came back, so it was settled with a count instead of an argument: every `uses:` line in ripgrep, fd, bat, delta, hyperfine, uv, jj, watchexec, zoxide, eza, starship, difftastic, dust and tokei. Four of the fourteen SHA-pin (starship 56/56, jj 54/55, uv 484/517, difftastic 23/30); the other ten tag-pin, ripgrep and bat with a single SHA each. Three of the four SHA-pinners run a bot to keep the hashes alive, which is the dependency this entry named: uv and starship through `.github/renovate.json5`, jj through Dependabot. - -The fourth is the control group. difftastic SHA-pins with no bot config and no version comments, so its workflows are twenty-three opaque hashes that cannot be read or dated. That is the predicted failure mode, observed. - -Worth recording for a clone that does turn Renovate on, because it is not what jj does: uv and starship write the pin as `actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1`, with the trailing tag comment maintained by Renovate's `helpers:pinGitHubActionDigests` preset. SHA-pinning without that comment is the version nobody can review. - -**The count is not the whole case, and the entry should not pretend otherwise.** What ten of fourteen repos do is evidence about practice, not about correctness, and the guidance runs the other way: GitHub's own security-hardening page recommends pinning third-party actions to a full-length commit SHA, OpenSSF Scorecard's `Pinned-Dependencies` check scores tag pins down, and the 2025 `tj-actions/changed-files` compromise is the demonstration, with tags rewritten under thousands of consumers. ripgrep and fd almost certainly tag-pin because they are old repos with read-only CI, not because they weighed this and declined. - -What keeps the decision where it is, for `ci.yml` specifically, is blast radius rather than a head count. That workflow runs with `contents: read`, holds no secrets, and produces nothing that ships: `publish = false`, no binary release, no tap. A compromised action there can poison a build nobody consumes. Set against that, SHA pins in a repo with no bot freeze the actions permanently, and a frozen action eventually fails outright when the runner drops its Node version. - -**Partially overturned 2026-09-04, the same day.** `release-plz.yml` is now hash-pinned, and the watch-list trigger it was parked behind turned out to be the wrong test. That entry said to revisit once the repo held a second secret; the exposure did not need a second secret to arrive, because one token with `contents: write` is already enough to push to `main` and cut releases. Waiting for a second would have been waiting for a number to change rather than for the risk to. - -Pinned with [`pinact`](https://github.com/suzuki-shunsuke/pinact), which writes the trailing `# v7.0.1` comment alongside each SHA. That comment is what keeps the file reviewable and what `just actions-outdated` compares against, and the recipe was taught to read it in the same commit; without that, pinning would have silently removed two actions from the freshness report. `dtolnay/rust-toolchain@stable` stays a branch ref: it names a toolchain rather than a version, and pinact refuses it for that reason. - -The rest of this entry stands, and `ci.yml` stays on tags. It runs read-only, holds no secret and ships nothing, so it buys nothing from pins that a clone has no bot to refresh. - -**Fully overturned 2026-09-25.** The entry's own condition was a bot to keep the hashes alive, and Renovate is that bot: `.github/renovate.json` now extends `helpers:pinGitHubActionDigests`, which writes the SHA with the `# v7.0.1` comment this entry named as the reviewable form, and a seven-day `minimumReleaseAge` holds action updates back for a week. With the bot in place every `uses:` in both workflows is hash-pinned and `.github/zizmor.yml` is gone. - -## 2026-07-27: `persist-credentials: false` on the release-plz checkout - -Applied to every other checkout to clear zizmor's `artipacked` finding. Not applied here: those credentials are what release-plz pushes the release branch and the tag with. `artipacked` is ignored for that one workflow in `.github/zizmor.yml`. - -**Overturned the same day.** The premise was wrong, and checking it took one page of upstream documentation that was never read. `website/docs/github/persist-credentials.md` says release-plz pushes commits, branches and tags **through the GitHub API**, so the checkout credentials are not what does the pushing. It names the only two cases that need them: signed tags, which release-plz detects via `git config --get tag.gpgSign` and which this repo does not configure, and a later step that runs `git push` itself, which this workflow does not have. Upstream's own quickstart sets `persist-credentials: false` on both jobs. - -So the workflow holding the strongest permissions in the repo was persisting a usable token in `.git/config` for no reason, and the `artipacked` ignore was suppressing a finding that was right. Both are gone. The lesson worth keeping is not about credentials: an audit exemption is a claim about behavior, and this one was written from an assumption about how a tool works rather than from its documentation. - -## 2026-07-27: Uploading zizmor findings to the Security tab - -The action's default, and the mode the CI job originally used. It uploads SARIF through `github/codeql-action/upload-sarif`, giving stateful tracking and incremental triage across runs, which is genuinely better than a console dump. - -Rejected as a template default on two counts. It is not portable: the upload needs the repository to be public or to pay for Advanced Security, so a private clone gets a red X on a job that found nothing, which is what happened here on the first push. And in that mode the action deliberately does not fail the job on findings, because GitHub expects a merge-protection ruleset to do the blocking; the job would report green with findings outstanding. A gate that cannot fail is worse than no gate. `advanced-security: false` behaves the same way everywhere and matches what `just zizmor` does locally. A public clone that wants the Security tab can turn it back on. - -## 2026-07-27: `unreachable_pub` and `missing_debug_implementations` lints - -Both are library lints. In a binary, `pub` on an item in a private module is the normal way to expose it across modules, and the crate has no external consumers for whom `pub` means anything. `unreachable_pub` produced 29 warnings on correct code. A lint that fires on the idiomatic form trains people to ignore lint output. - -## 2026-07-27: Dropping `-D warnings` from CI now that lints live in `Cargo.toml` - -The manifest carries a curated list, so it cannot deny a lint nobody listed. `-D warnings` stays in `just check` and CI as the catch-all for everything not named explicitly. The manifest gives editor and `cargo build` parity; the flag is the backstop. They are not redundant. - -**Holds, respelled in CI on 2026-09-25.** `ci.yml` sets `CARGO_BUILD_WARNINGS=deny` (Cargo's `build.warnings`, stable since Rust 1.97) instead of passing `-D warnings`: the same catch-all over local lints, measured failing build, clippy and rustdoc, without invalidating the build cache the way `RUSTFLAGS` does. `just check` keeps the flag. - -## 2026-07-27: Removing `components:` from `ci.yml` to single-source the toolchain - -`rust-toolchain.toml` names the channel and the components, so repeating `components: clippy, rustfmt` in CI looks like duplication worth deleting. It is not: `dtolnay/rust-toolchain` installs the toolchain itself, and rustup only honors a components list when it is the one performing the install. Deleting the CI line risks a runner with a toolchain but no clippy. - -Kept the duplication with a comment at the site saying the two must agree. The alternative that would genuinely single-source it is dropping the toolchain step entirely and letting rustup auto-install from the file on first `cargo` invocation. - -**Resolved 2026-09-25 the way this entry named.** CI no longer uses `dtolnay/rust-toolchain`: `rustup toolchain install` with no argument installs the toolchain and components `rust-toolchain.toml` names, so the file is the only list. - -## 2026-07-27: Freezing a specific rustc version in `rust-toolchain.toml` - -`channel = "stable"` tracks the newest stable instead of pinning a number. A frozen version in a template ages into the default for every clone, and clones are not revisited. The MSRV that actually matters is `rust-version` in `Cargo.toml`, which is a declared floor rather than the compiler everyone is forced onto. - -## 2026-07-27: Tightening dependency requirements past the major version - -Requirements stay major-only (`"1"`, `"4"`). The lockfile pins the actual build, so a narrower requirement in the manifest buys nothing and bakes a stale minimum into every clone. - -## 2026-07-27: Backticking `NO_COLOR` and friends to satisfy `doc_markdown` - -`clippy::doc_markdown` is `allow` in the manifest. The doc comments in `src/cli.rs` are the `--help` text: backticks added to satisfy rustdoc would be printed literally to the terminal. This is the one lint where the correct-looking fix makes user-facing output worse. - -## 2026-07-27: Suppressing `expect_used` in `ui.rs` with `#[expect(...)]` - -Enabling `clippy::expect_used` flagged two `.expect()` calls on progress-bar templates. The cheap fix was a local allow with a reason. - -Rejected in favor of the real fix: the templates now fall back to indicatif's default style, so a malformed template degrades instead of killing the program mid-render, and the existing unit test still catches a typo at test time. The lint was pointing at a genuine design question ("what should happen if this fails?"), and the honest answer was not "panic". - -## 2026-07-27: A hand-written `just release` recipe and a hand-edited `CHANGELOG.md` - -Replaced by release-plz. The old recipe ran `cargo set-version`, committed, tagged, pushed, and published, with a comment telling you to update the changelog first, which is exactly the step a human forgets. Version bumps and changelog entries are now generated from conventional commits and land as a reviewable PR. - -## 2026-07-27: Having `just rename` rewrite `README.md` - -The recipe rewrites the manifest, `src/`, and `tests/`. It leaves the README name alone: most occurrences describe the template itself, and a blind substitution would produce a README claiming the clone is a starter to be cloned. - -The later `just description` recipe is deliberately narrower. It changes only the paragraph between the repository description markers, along with the matching package and GitHub metadata. - -## 2026-07-27: `cargo-audit` alongside `cargo-deny` - -`cargo deny check advisories` reads the same RustSec advisory database that `cargo-audit` does. Running both means cloning that database twice per audit for one signal, and two tools that can disagree only through version skew in their copies of the same data. `cargo-deny` stays because it also covers licenses, banned crates, and the source allowlist, which `cargo-audit` does not. - -## 2026-07-27: A `cargo test --doc` step in CI - -Proposed to sit next to nextest, since nextest deliberately does not run doctests. Checked before writing it: `cargo test --doc` on this crate fails with `error: no library targets found in package cli-template`. It is a binary-only crate, so the step would not run zero tests, it would break the pipeline on the first push. - -Recorded as a note in `development.md` instead: a clone that grows a `src/lib.rs` should add `cargo test --doc --locked` at that point. - -## 2026-07-27: `cargo-machete` in place of `cargo-shear` - -Both find dependencies declared in `Cargo.toml` and never used, and only one belongs in the hook. `cargo-shear` won because it resolves `use` items rather than pattern-matching source text, so it is the one less likely to produce a false positive that teaches you to ignore the hook. No reason to run both. - -## 2026-07-27: `cargo-fuzz` - -Fuzzing pays for itself against a parser or a decoder handling untrusted bytes. This template reads a file and counts lines. It also requires a nightly toolchain, which contradicts the `channel = "stable"` pin every clone inherits, so shipping it would mean shipping a recipe most clones cannot run. - -## 2026-07-27: `cargo-generate` as the rename mechanism - -Would turn the repo into a parameterized template with `{{project-name}}` placeholders. Rejected because it stops the template from being a working crate: you could no longer clone it, run `just check`, and see it pass, which is how you know the starter is not broken. It also conflicts with the documented `gh repo create --template` flow. `just rename NEW` gets the same result while the repo stays buildable at every point. - -## 2026-07-27: `cargo-expand`, `cargo-cache`, `cargo-edit`, and `cargo-binstall` as template content - -All four are useful and none of them are properties of this project. They are tools you install once on a machine and use across every crate you own, so putting them in `setup.md` as project prerequisites would misrepresent what the template actually needs. `cargo-binstall` appears in the install instructions only as the verb that installs the tools that are prerequisites. - -## 2026-07-27: Coverage, mutation testing, and binary-size analysis as CI gates - -`cargo-llvm-cov`, `cargo-mutants`, and `cargo-bsize` are in the `justfile` and deliberately out of `just ci` and out of the workflow. Each answers a question you ask occasionally, and none has a threshold that is meaningful to fail a merge on: a coverage percentage gate rewards tests that execute lines without asserting on them, and mutation testing the whole crate takes long enough that people start skipping the pipeline. `just mutants` uses `--in-diff` for the same reason. - -No Codecov or coverage-upload step either: it needs an account and a token per clone, to display a number nobody is gating on. - -## 2026-07-27: Running `cargo-msrv` in CI - -The MSRV job installs the floor toolchain and runs `cargo check` instead. That is the actual contract being tested, and it needs no extra tool on the runner. `cargo-msrv` stays a local recipe for the different question of *finding* the floor, which involves compiling repeatedly across a version range and does not belong in a per-push pipeline. - -## 2026-07-27: A Dependabot configuration - -Considered for keeping dependencies and action pins current in clones. Rejected for the same reason as hash-pinning actions: it is standing machinery imposed on every clone, generating PRs in repositories nobody is watching. Dependency freshness is available on demand through `just outdated`, and the lockfile plus `cargo-deny` advisories cover the case that actually matters, which is a known vulnerability rather than a stale minor version. - -(The template repo itself runs Renovate to keep the *template's* dependencies current; clones do not inherit it, because the Renovate app is not enabled on them.) - -## 2026-07-27: Limiting `--locked` to CI - -The first sketch put `--locked` only in the workflow, to spare the local loop a failure when the lockfile is momentarily behind the manifest. Rejected because it recreates the exact split this pass set out to close: a flag that changes what "green" means, present in one place and absent in the other. `--locked` is in `just check`, the prek clippy hook, and CI, so a lockfile that drifted from the manifest fails on the machine where it drifted. - -## 2026-07-27: A module-level `#![allow(clippy::print_stderr)]` in `ui.rs` - -`print_stderr` is `deny` crate-wide, and `ui.rs` is the module whose job is writing to stderr, so an allow with a comment looked like the honest exemption. Unnecessary in the end: `ui.rs` imports `anstream::eprintln`, and the lint fires on the std macros, so the deny holds everywhere with no exemption at all. The version that needs no escape hatch is better than the one that documents its escape hatch well. - -## 2026-07-27: cargo-dist - -cargo-dist generates installer scripts, a build matrix, and the release workflow from one `dist-workspace.toml`. A survey of ripgrep, fd, bat, delta, hyperfine, mise, and watchexec found exactly one user: uv, which ships to millions of installs across 18 targets. watchexec adopted cargo-dist and later dropped it for a hand-rolled tag-triggered workflow, which is what ripgrep, fd, bat, and delta all run as well. The step a clone of this template actually needs is that ripgrep-style `release.yml`, one paragraph in `release.md`, not generator machinery every clone would have to delete before its first release. - -## 2026-07-27: tracing (and tracing-subscriber) - -The structured-logging stack pays off in async or long-running processes, which is exactly where its users in the survey live (jj, uv, watchexec). A small synchronous CLI has one thread and one phase per command; the `Verbosity` enum in `output.rs` is the whole state machine it needs. tracing's default format also writes log-level labels (INFO, WARN) to stderr, which the contract's narration style deliberately avoids in normal mode. If a clone grows async work or a daemon mode, this becomes the right answer, and `clap-verbosity-flag` maps the flags to its levels. - -## 2026-07-27: clap-verbosity-flag - -A crate whose entire job is the `-q` / `-v` counting that `cli.rs` and `output.rs` already do in about fifteen lines, with the exact semantics the contract wants (`-v` is never version, quiet conflicts with verbose). Shipping it would be a dependency standing in for code shorter than its own documentation. It becomes the right adopt candidate only alongside tracing, for a clone that needs real leveled logging. - -## 2026-07-27: concolor and supports-color - -Terminal color-detection crates. `anstream` already resolves auto/always/never plus NO_COLOR and TERM=dumb, and it is the implementation clap itself uses, so a second detector could only disagree with the first. concolor specifically is unmaintained (last commit 2023-04), and supports-color, though alive, would be redundant the day it was added. - -## 2026-07-27: jemalloc - -fd's allocator swap is the standard trick for allocation-heavy CLIs, with a platform carve-out for macOS. A starter has no measured allocation problem to fix, and a global allocator is an invisible default a clone should choose deliberately after profiling, not inherit. The prerequisite is a benchmark and `just bloat` output pointing at allocation, not a dependency line. - -## 2026-07-27: `debug = 1` in the release profile - -jj and watchexec keep line tables in their stripped release binaries so user panic reports carry usable stack traces. Here `panic` is denied in production code, so the only traces this buys are for dependency bugs, and the cost is binary size on every release build of every clone. A clone that starts shipping to users who file crash reports can revisit with a real need. - -## 2026-07-27: Rendering the man page at build time into a shipped file - -Generating a man page is cheap; shipping one as a build artifact is not. A `build.rs` writing roff into `OUT_DIR` gives the clone a build dependency and a lookup to understand, and without binary distribution there is no install path for the resulting file to land in. - -The template takes the other route and keeps the feature: `cli-template man` renders the page on demand to stdout, like every other piece of data. It cannot drift from the flags, it needs no build script, and a clone that later adds distribution pipes it into a file at install time. See `docs/contract.md` for the shape. - -## 2026-07-27: Self-update and update notifications - -mise's `self_update` feature and starship-style update notices both presume published releases and a user base to notify. A template has neither, and the mechanism depends on where the clone publishes (crates.io, GitHub releases, a tap), which is the clone's decision to make at that point, not one to inherit silently. - -## 2026-07-27: A markdown linter (rumdl) on the commit hook - -Tempting here specifically, because `docs/` is a large share of what this repo is, and the argument that earned `typos` its place (prose that ships to users deserves a check) reads as though it applies with more force to seven doc files. - -It does not, because the two differ in who owns the prose. The doc comments `typos` guards are `src/cli.rs`'s `--help` text: code, shipped to the clone's users, and inherited verbatim. The markdown is documentation *about the template*, most of which a clone rewrites or deletes. Adding a hook plus a checked-in `.rumdl.toml` would impose the template author's markdown style on every clone's own README, which is the Dependabot objection above in a different costume: standing machinery in repositories nobody is watching. - -Run it by hand on this repo if you like; `.gitignore` already covers its cache. The decision is only that it is not a gate a clone inherits. - -## 2026-07-27: A checked-in CLI spec (usage-lib, mise.usage.kdl) - -mise generates completions, man pages, and docs from one KDL spec instead of clap derive. That trades the derive API the whole ecosystem documents for a second definition of the CLI the clone has to learn, and it makes `src/cli.rs` stop being the source of truth. The template's bet is the opposite: the doc comments in `cli.rs` are the help text, one source, no generation step. - -## 2026-08-25: Restoring the terminal on SIGTERM and SIGHUP - -The TUI template converts `SIGTERM` and `SIGHUP` into a quit request the event loop checks, so a kill while the alternate screen is up still runs the terminal restore. A CLI has no alternate screen and never enters raw mode, so there is nothing to restore: a kill mid-command leaves the terminal exactly as it was, and the progress layer never hides the cursor (checked against the vendored indicatif source). Recorded so the question is settled before it is re-asked. - -## 2026-09-04: `clippy::nursery` as a lint group - -Denying `pedantic` and `nursery` together is the headline of No Boilerplate's 2026 Rust toolkit config. `pedantic` is already on here; `nursery` is not, and running it produced eight findings that between them make the case against it. Six are `missing_const_for_fn` on the `palette.rs` accessors. One is `option_if_let_else` proposing a `map_or_else` chain in `paths.rs` that reads worse than the `if let` it would replace. The last is `literal_string_with_formatting_args` firing on `" {msg} [{bar:30}] {pos}/{len}"` in `ui.rs`, which is an indicatif template rather than a format string and cannot be written any other way. - -That last one is the disqualifier, and it is the `unreachable_pub` objection above in a different costume: a lint that fires on the only correct form trains people to ignore lint output. nursery lints are also still under evaluation upstream by definition, so a clone would inherit churn from a set whose contents move without a major version. - -## 2026-09-04: `clippy::as_conversions` - -From the same config, and the only lint in it that fires on production code here: `checks.len() as u64` in `doctor.rs`, feeding indicatif's `ProgressBar::new`. - -Rejected because `pedantic` already denies the casts that lose data (`cast_possible_truncation`, `cast_possible_wrap`, `cast_sign_loss`, `cast_precision_loss`) and stays quiet on this one deliberately, since `usize` is at most 64 bits on every Rust target and the cast cannot truncate. Satisfying `as_conversions` would mean `u64::try_from(checks.len()).unwrap_or(u64::MAX)`, a fallback branch no input can reach. A lint whose only effect on this codebase is to add unreachable defensive code is the worse trade. - -## 2026-09-04: `clippy::string_slice` - -Also from that config. Its only hit is `stderr[cause..]` in `tests/cli.rs`, sliced at a byte offset `str::find` returned and therefore always on a character boundary. - -Rejected on consistency. `clippy.toml` deliberately reopens `unwrap`, `expect`, `panic`, and now indexing inside tests, because a panic in a test is the assertion. `string_slice` has no `allow-...-in-tests` key, so denying it would impose on test code a rule this repo has decided not to impose, in exchange for no production coverage at all: nothing in `src/` slices a string. - -## 2026-09-04: A nightly toolchain - -The video has been on nightly since 2020 and leads with compile times and the new trait solver. Rejected for the reason `cargo-fuzz` was: `channel = "stable"` in `rust-toolchain.toml` is inherited by every clone, and shipping a default most clones should not be on is not a starting point. - -There is a second reason specific to this template. The lint set *is* the contract, and nightly clippy knows lints stable does not, so `just check` would mean something different depending on who ran it. That is the same disagreement `rust-toolchain.toml` exists to prevent. - -## 2026-09-04: eyre and color-eyre in place of anyhow - -Rejected on the same ground as `miette` above: it is a second error-rendering system standing next to the `Error:` / `Try:` / `Cause:` printer in `main.rs` that already satisfies the contract, and the contract is about the shape of the message rather than its decoration. - -There is also a specific mismatch. What `color-eyre` leads with is a panic and backtrace hook, and `panic` is denied crate-wide, so the headline feature has nothing to hook. `anyhow` stays for the further reason that `thiserror` is already the typed half of the pair, and the two share an author and an idiom. - -## 2026-09-04: bacon or watchexec as a `just watch` recipe - -The video pairs `bacon clippy` with rust-analyzer as the inner loop, and it is a good loop. Rejected as template content for the reason `cargo-expand` and `cargo-edit` were: these are tools you install once per machine and use across every crate you own, so a recipe would put a prerequisite in the `justfile` that `just check` does not need and a fresh clone would not have. Nothing stops running `bacon clippy` in a second pane; it just is not a property of this project. - -## 2026-09-04: The application crates from the same toolkit - -itertools, rayon, criterion, jiff, reqwest, sqlx, utoipa, leptos, and dioxus are each defensible in the project that needs them and each a deletion in the project that does not. `serde` is here because JSON output is a contract point; none of these has a contract point to hang on. Recorded so the list is settled rather than re-litigated: a clone adds what its domain needs, and the template's job is to have not guessed wrong on its behalf. - -Two notes worth keeping. **jiff** has displaced chrono as the answer for a clone that needs time handling. **criterion** is not blocked by the CodSpeed entry above, which was about a workflow pointing at a `benches/` directory that does not exist; a clone that grows a real benchmark adds criterion at that point. - -**devenv**, which the video manages the entire toolchain with, is out for a plainer reason: `rust-toolchain.toml` and the `justfile` already pin what this repo needs, and a Nix-based environment is a machine-level choice a template cannot make on behalf of its clones. - - -## 2026-09-04: `cargo-hack`, `taplo`, and a rustdoc job - -Found by the same fourteen-repo survey as the hash-pinning re-check above, and turned down as the tail of it. - -`cargo-hack` checks the feature powerset. One repo of the fourteen uses it (eza), and this crate has no optional features for it to combine, so it would iterate over a set of one. It becomes worth adding the day the manifest grows a `[features]` table. - -`taplo` formats and lints TOML. Also one of fourteen (starship). The manifest, `deny.toml`, `clippy.toml` and `release-plz.toml` here are hand-maintained and small enough that a formatter would only ever reformat what a human already read. - -A rustdoc job (`RUSTDOCFLAGS="-D warnings" cargo doc --no-deps`) is the closest call of the three: five of fourteen run one, including ripgrep, jj, bat and delta, and `missing_docs` is already `warn` here so doc comments are not decorative. Left out because what it would add over the existing gate is broken intra-doc links, and this is a binary crate whose doc comments are read as `--help` text rather than as rendered rustdoc. A clone that grows a `src/lib.rs` should add it in the same breath as the `cargo test --doc` step noted in `development.md`. - -## 2026-10-06: Sources considered and not built - -Each was weighed in the source research that produced ADR 0004. - -- **Papers with Code**: shut down in July 2025; every URL, the API included, redirects to Hugging Face trending papers. -- **data.world**: search answers 401 without a key and the catalog is commercial; nothing it holds was missing from the open sources. -- **ICPSR, GESIS, UK Data Service, USGS ScienceBase direct**: each served a Cloudflare challenge page to non-browser clients. Their metadata arrives through DataCite and the CESSDA catalogue instead. -- **Dryad direct**: a clean keyless API, but DataCite carries every Dryad DOI; revisit only if file-level details are wanted. -- **Cloud marketplaces** (BigQuery public datasets, Snowflake, Databricks, AWS Data Exchange): listing needs cloud credentials and an account. -- **LDC**: a paywalled membership catalog. -- **Internet Archive**: a `mediatype:data` query returned books; too noisy to merge. -- **Academic Torrents**: asks clients to read its RSS feeds rather than search; small. -- **re3data**: a registry of 3,534 repositories, not of datasets; useful for pointing at repositories, not for search. -- **Materials Project core API**: a per-material database rather than a dataset catalog; its contributed datasets (MPContribs) are searched instead. - -## 2026-10-07: `panic = "abort"` in the release profile - -It would save 864 KiB of the 4.5 MiB shipped at v0.6.0, the second-largest stable lever ([measurement](../bench/2026-10-07-binary-size.md)). Every source runs on its own thread in `search.rs`, and a panic in a dependency unwinds only that thread, so the search reports the source as crashed and still prints the others. Under abort, one malformed response that trips a panic in quick-xml or serde_json ends the whole search with no results. Destructors would also be skipped: a cache write in progress would leave its temp file behind (the target file stays intact, because the rename is atomic) and the progress line would be left half drawn. Tests would not notice, because cargo builds tests with unwinding regardless. Revisit only if adapters stop running on threads that are allowed to fail. - -## 2026-10-07: `opt-level = "z"` or `"s"` for dataseek's own code - -Building the crate itself for size takes the release binary from 3.79 MB to 2.97 MB on aarch64 macOS, and makes every CPU stage of a search 43% to 287% slower ([measurement](../bench/2026-10-07-binary-size.md)). Dependencies are built at `z` instead, because fat LTO inlines their hot paths into this crate's code, which stays at 3. - -## 2026-10-07: Other ways of merging and ranking results - -Measured with the relevance benchmark and left out because none improved the held-out queries beyond the noise ([`../bench/2026-10-07-relevance.md`](../bench/2026-10-07-relevance.md), ADR 0016): a different RRF constant (1 to 200; 40 and up score within 0.006 of 60, smaller ones interleave sources and lose), fusing only each source's top 3 or 5, CombMNZ, list-length-normalized Borda, round robin, per-source weights learned from the judgments, other coverage floors and shapes, title-weighted coverage, a bonus for the whole query in the title, ignoring function words, and treating records with no description and no publisher differently. Source weights deserve the warning: they gained 0.060 on the queries they were fitted on and lost 0.010 on the others, which is what learning the benchmark looks like. A proposal to revisit any of these starts from `just relevance variants`, not from an argument. diff --git a/docs/adr/watchlist.md b/docs/adr/watchlist.md index 3148159..3f13d0f 100644 --- a/docs/adr/watchlist.md +++ b/docs/adr/watchlist.md @@ -1,12 +1,12 @@ # Watch list -Things that are not rejected and not adopted: each one is a clear *not yet*, with the trigger that would make it worth revisiting. This is the companion to [`rejected.md`](rejected.md). A rejected entry needs its reason to stop being true; a watch entry needs its trigger to fire. When one does, the entry leaves this file and becomes either a commit or a dated entry in `rejected.md`. +Things that are not adopted yet: each one is a clear *not yet*, with the trigger that would make it worth revisiting. When the trigger fires, the entry leaves this file and becomes a commit or an ADR. Keep entries small: the item, why it is parked, and the trigger. If you cannot name the trigger, the item does not belong here. ## clap_complete dynamic completions -Completing *values* (branch names, file arguments from the tool's own index) instead of just flags, by having the shell call back into the binary. Parked because the mechanism lives behind clap_complete's `unstable-dynamic` feature and upstream warns that shell code and binary can drift apart (see the full reasoning in [`rejected.md`](rejected.md)). +Completing *values* (branch names, file arguments from the tool's own index) instead of just flags, by having the shell call back into the binary. Parked because the mechanism lives behind clap_complete's `unstable-dynamic` feature and upstream warns that shell code and binary can drift apart. Trigger: the feature drops the `unstable-` prefix in a clap_complete release. Check `cargo info clap_complete` and its CHANGELOG. diff --git a/docs/assets/dataseek-banner.png b/docs/assets/dataseek-banner.png new file mode 100644 index 0000000..358532d Binary files /dev/null and b/docs/assets/dataseek-banner.png differ diff --git a/docs/bench/2026-10-07-binary-size.md b/docs/bench/2026-10-07-binary-size.md index 67500b3..826dd97 100644 --- a/docs/bench/2026-10-07-binary-size.md +++ b/docs/bench/2026-10-07-binary-size.md @@ -108,7 +108,7 @@ Criterion, `just bench --baseline main`, median change against v0.6.0: ## Verdict -The release profile now uses fat LTO and builds every dependency at `opt-level = "z"`, while dataseek's own code stays at 3. The binary is 18% to 23% smaller per target, and no measured stage got slower. With `--jq` dropped, the binary is 44% to 51% smaller than v0.6.0. `panic = "abort"` saved 864 KiB on the v0.6.0 profile, but it would turn one adapter's panic into a failed search, so it is rejected (`docs/adr/rejected.md`). +The release profile now uses fat LTO and builds every dependency at `opt-level = "z"`, while dataseek's own code stays at 3. The binary is 18% to 23% smaller per target, and no measured stage got slower. With `--jq` dropped, the binary is 44% to 51% smaller than v0.6.0. `panic = "abort"` saved 864 KiB on the v0.6.0 profile, but it would turn one adapter's panic into a failed search, so it stays off. ## Caveats diff --git a/docs/reference/README.md b/docs/reference/README.md index 24becd4..fd8ef53 100644 --- a/docs/reference/README.md +++ b/docs/reference/README.md @@ -2,13 +2,13 @@ How the project works and how to operate it, one file per domain. Each file describes the current state; when that state changes, the file changes with it. -What is not here: why a choice was made ([`../adr/`](../adr/)), what was left out ([`../adr/rejected.md`](../adr/rejected.md)), and what shipped ([`../CHANGELOG.md`](../CHANGELOG.md)). +What is not here: why a choice was made ([`../adr/`](../adr/)) and what shipped ([`../CHANGELOG.md`](../CHANGELOG.md)). | file | covers | read when | |---|---|---| | [setup.md](setup.md) | dev tools to install, `just description` | setting up a machine | | [development.md](development.md) | daily recipes, lints, tests, dependencies, MSRV | writing code | | [contract.md](contract.md) | flags, streams, errors, exit codes, color, the lints that enforce them | changing what the CLI prints or accepts | -| [security.md](security.md) | cargo-deny, zizmor, action pins, workflow permissions | touching dependencies or workflows | +| [supply-chain.md](supply-chain.md) | cargo-deny, zizmor, action pins, workflow permissions | touching dependencies or workflows | | [keys-and-cache.md](keys-and-cache.md) | API keys, where they are read from, the contact address, the cache and its commands | setting up a key or wondering why a result is old | | [release.md](release.md) | conventional commits, the release loop, `.github/release-plz.toml`, the App token | merging anything, or when a release did not happen | diff --git a/docs/reference/contract.md b/docs/reference/contract.md index a759ff5..2821f1e 100644 --- a/docs/reference/contract.md +++ b/docs/reference/contract.md @@ -11,7 +11,7 @@ The version lives only in `Cargo.toml`. Clap reads it via `#[command(version)]`, - `-h/--help`, `-V/--version` - Global `-q/--quiet`, `-v/--verbose` (repeatable) - `--json`, `--color=auto|always|never`, `--no-color`, `--plain`, `--no-progress` -- `--cache-dir DIR` and `--connect-timeout SECS`, each with a `DATASEEK_*` variable +- `--cache-dir DIR` and `--connect-timeout SECS`, each with a `DATASEEK_*` variable; the cache size budget has only its variable, `DATASEEK_CACHE_MAX_MB` `search` reads `-x`, `--per-source`, `-n` and `--timeout` from `DATASEEK_EXCLUDE`, `DATASEEK_PER_SOURCE`, `DATASEEK_LIMIT` and `DATASEEK_TIMEOUT` too. A flag beats its variable, which beats the default; `dataseek help environment` lists them all. A source marked `opt-in` in `dataseek sources` runs only when `-s` names it ([ADR 0013](../adr/0013-opt-in-sources.md)). @@ -29,7 +29,7 @@ Secrets never arrive as flags, which leak into shell history and process listing ## Help surfaces -- A bare `dataseek` prints the overview on **stdout** and exits `0`: the name and version, the commands in three small groups (search, upkeep, shell), and a footer pointing at `-h`. It is orientation, so `dsk | head` shows it. `src/help.rs` holds the groups; a unit test fails when a command is missing from them. +- A bare `dataseek` prints the overview on **stdout** and exits `0`: the name and version, the commands in three small groups (Search, Upkeep, Shell), and a footer pointing at `-h` and `--help`. It is orientation, so `dsk | head` shows it. `src/help.rs` holds the groups as names only; each line's description is the command's `about`, the same line `-h` shows. A unit test fails when the overview and `-h` list different commands or list them in a different order. - `dataseek help ` is that command's `--help`. `dataseek help environment` lists the variables that change what it does, `dataseek help exit-codes` every code it returns. - `dataseek help --json` describes the whole surface as data for scripts and agents: commands, flags with their type (`boolean`, `integer`, `string` or `count`), value names, possible values, defaults, the `minimum` and `maximum` of a ranged integer, and variables, and the exit codes, all generated from the clap definition. A bare `dataseek --json` prints the same object. `dataseek help --json` prints that command's entry of it: its own flags, with the global ones listed once, on the root. @@ -46,13 +46,19 @@ Every byte of stdout goes through a handle from `src/output.rs`, including the t So a piped search still announces itself at once and sums up at the end, and no spinner frame can reach a log. What must never happen is a frame on stdout, and that is guaranteed by the layer only ever writing to stderr. `doctor` does not narrate: its checks take milliseconds, so it prints only its report. +`search` opens with the number of sources it will ask. A source missing its required key is skipped before any request, so it is left out of that number and counted after it (`1 needs a key, see dataseek doctor`); when no chosen source can run, there is no opening line, only the error. + `search` prints its summary after the results, so the last line says how many matched, how many sources answered and how to see more. An empty result is a stderr line, never text on stdout. +Each text result is four lines: the rank and title, the URL, a muted line of facts, and the description. The facts are the sources that found it, then publisher, date, size, license and DOI, whichever are known, separated by ` | `. + +Other text output fits the terminal by wrapping, never by cutting: on a terminal a long value continues under its own column, and in a pipe it stays on one line so a script can read it. `inspect` wraps its fields that way, its description within 40 to 80 columns like a search result's, and `doctor` each check's detail. `sources` sizes each column to its longest value and wraps the notes under its table, and `help environment` wraps what each variable does under its column. On a terminal its file list opens with the count and total size and gives each file two lines, name, size and format, then the link and checksum indented under them; when name, size and format do not fit side by side, size and format get a line of their own. In a pipe each file stays one line. + This is why `Cargo.toml` denies `print_stdout` and `print_stderr`: a stray `println!` is a contract violation, not a style preference. ## JSON -Every `--json` output is one object with a `schema` tag naming its shape and version (`dataseek-search/1`, `dataseek-sources/1`, `dataseek-doctor/1`, ...). A key that changes meaning or disappears bumps the tag; a new key does not. On a terminal the JSON is indented, in a pipe it is one line. To pick fields, pipe it into `jq`. A failed run prints its error event on stderr and nothing on stdout, and `jq` exits 0 on empty input, so a script runs the pipeline under `set -o pipefail` (bash, zsh) or checks `$pipestatus[1]` (fish) to see the failure. `--jq` was removed; passing it is a usage error that says so. `completion` and `man` print their script and page whatever the flag. `tests/snapshots/` freezes the search, sources, doctor, cache info, inspect, exit-codes and error-event shapes. +Every `--json` output is one object with a `schema` tag naming its shape and version (`dataseek-search/1`, `dataseek-sources/1`, `dataseek-doctor/1`, ...). A key that changes meaning or disappears bumps the tag; a new key does not. On a terminal the JSON is indented, in a pipe it is one line. To pick fields, pipe it into `jq`. A failed run prints its error event on stderr and nothing on stdout, and `jq` exits 0 on empty input, so a script runs the pipeline under `set -o pipefail` (bash, zsh) or checks `$pipestatus[1]` (fish) to see the failure. `completion` and `man` print their script and page whatever the flag when stdout is not a terminal. `tests/snapshots/` freezes the search, sources, doctor, cache info, inspect, exit-codes and error-event shapes. `inspect --json` (`dataseek-inspect/1`) prints `dataset`, the page's own JSON-LD node as the page wrote it, and beside it `files`, dataseek's reading of the file list, so a `files` key on the page is never overwritten. Every string of the page's metadata, keys included, has its control characters (C0 other than newline and tab, DEL, and C1) replaced by a space before it is printed, as text or as JSON, so a page cannot drive the terminal that shows it. @@ -97,20 +103,21 @@ Expected failures never show a stack trace. `Cargo.toml` denies every route a pa - `2`: usage error (clap) - `130`: interrupted by Ctrl-C (death by SIGINT, which the shell reports as 130) -For `search`, success means at least one source answered, even with no results: an empty answer is a result (ADR 0007). `1` means every attempted source failed, or none could run: each lacks its key, each is resting after an outage in the last ten minutes, or `-s`, `-c` and `-x` left none. When every attempted source was unreachable (no DNS answer, a refused connection, a failed TLS handshake; a timeout does not count), the error says the machine looks offline and points at `--offline`; under `--offline` with nothing cached, it says so instead. A certificate dataseek cannot verify is not an outage: the source is neither retried nor rested. On Linux that happens when the system has no CA bundle or lacks the root a TLS-inspecting proxy signs with; when every attempted source fails this way, the error says so and its `Try:` names the distribution's `ca-certificates` package and `SSL_CERT_FILE`, or, when `SSL_CERT_FILE` or `SSL_CERT_DIR` points at a path that cannot be read, that variable and path. `inspect` gives the same hint. `--offline` and `-s` ask resting sources anyway. A source that fails while others answer is a warning on stderr, never a failure. `cache warm` is the exception that fails partway: any catalog that did not download makes the run exit `1`, after every success is printed and every failure named, on stderr and again in the error, so `-q` still says which. +For `search`, success means at least one source answered, even with no results: an empty answer is a result (ADR 0007). `1` means every attempted source failed, or none could run: each lacks its key, each is resting after an outage in the last ten minutes, or `-s`, `-c` and `-x` left none. When every attempted source was unreachable (no DNS answer, a refused connection, a failed TLS handshake; a timeout does not count), the error says the machine looks offline and points at `--offline`; under `--offline` with nothing cached, it says so instead. A certificate dataseek cannot verify is not an outage: the source is neither retried nor rested. On Linux that happens when the system has no CA bundle or lacks the root a TLS-inspecting proxy signs with; when every attempted source fails this way, the error says so and its `Try:` names the distribution's `ca-certificates` package and `SSL_CERT_FILE`, or, when `SSL_CERT_FILE` or `SSL_CERT_DIR` points at a path that cannot be read, that variable and path. `inspect` gives the same hint. `--offline` and `-s` ask resting sources anyway. A source that fails while others answer is a warning on stderr, never a failure. Whatever part of a failure's reason came from the source (a malformed tag name, a transport error's text) has its control characters replaced before it is kept, so a source cannot drive the terminal through its own error. `cache warm` is the exception that fails partway: any catalog that did not download makes the run exit `1`, after every success is printed and every failure named, on stderr and again in the error, so `-q` still says which. `src/help.rs` holds the list `help exit-codes` prints, and `tests/cli.rs` asserts every code on it. ## Completion and the man page -`dataseek completion fish` (or `bash`, `zsh`, ...) prints a completion script to stdout. `dataseek man` prints the man page, in roff, to the same place: +`dataseek completion fish` (or `bash`, `zsh`, ...) prints a completion script to stdout. On a terminal, where a script would scroll past unread, it prints no script and says on stderr where to save it so the shell loads it (`dsk completion fish > ~/.config/fish/completions/dsk.fish`), for the name it was run as. `dataseek man` prints the man page, in roff, to the same place when stdout is not a terminal; on a terminal it shows the page through `man`, by way of a temporary file because BSD and macOS `man` cannot read stdin, and prints the roff if `man` is missing. `cargo install` cannot install a man page, so `man dsk` finds nothing until it is saved where `man` looks: ```sh -dataseek man | man -l - -dataseek man > ~/.local/share/man/man1/dataseek.1 +dsk man > ~/.local/share/man/man1/dsk.1 # then: man dsk ``` -Both are data, so both go to stdout, and both are derived from the clap definition rather than maintained by hand. The man page is rendered on demand by `clap_mangen` instead of at build time by a build script, so it cannot drift from the flags. The tests assert the page carries the manifest version, renders without errors and names every command, and that fish parses the completion script. +`man` is a hidden command: the overview, `-h` and `--help` leave it out, `dataseek help --json` still lists it, as it lists every command that runs. + +Both are data, so both go to stdout, and both are derived from the clap definition rather than maintained by hand. The man page is rendered on demand by `clap_mangen` instead of at build time by a build script, so it cannot drift from the flags. `help::man_page` adds two things clap_mangen does not: a flag hidden from `-h` still gets its description, and the examples, exit codes (from `EXIT_CODES`, like `help exit-codes`) and bug address become EXAMPLES, EXIT STATUS and REPORTING BUGS sections. The tests assert the page carries the manifest version, renders without errors, names every command, describes every option and has those three sections, and that fish parses the completion script. ## Color @@ -126,7 +133,7 @@ const MUTED: Color = ansi(AnsiColor::BrightBlack); // secondary detail Roles are semantic (`accent`, `success`, `danger`), not literal, so swapping a color is one edit. Use a named ANSI color for portability, or 24-bit truecolor with `rgb(0x7a, 0xa2, 0xf7)`. -The same roles drive clap help styling, stdout text, and the stderr progress accent. `anstream` strips escapes whenever the stream is not a terminal, so call sites style unconditionally and never branch on color. On a color terminal, result URLs are OSC 8 hyperlinks and long titles and descriptions are cut to the width (`COLUMNS` wins) with an ellipsis; in a pipe every line stays whole. +The same roles drive clap help styling, stdout text, and the stderr progress accent. `anstream` strips escapes whenever the stream is not a terminal, so call sites style unconditionally and never branch on color. On a color terminal, result URLs are OSC 8 hyperlinks. When stdout is a terminal, color or not, a result's title and facts line are cut to the terminal width (`COLUMNS` wins) with an ellipsis, and its description to that width held between 40 and 80 columns, so it reads as prose on a wide terminal; URLs are never cut. In a pipe, and with `--plain`, every line stays whole. indicatif parses its color token with `console::Style::from_dotted_str`, which understands named colors, `#rrggbb` truecolor, and a bare 256-color index, so `palette::accent_token()` renders whichever shape the accent takes exactly. Spinners and bars match help and stdout rather than approximating them. @@ -140,6 +147,8 @@ indicatif parses its color token with `console::Style::from_dotted_str`, which u ## Extending the CLI -Add a subcommand by adding a variant to `Command` in `src/cli.rs`, a match arm in `run()` in `src/lib.rs`, its name in `COMMANDS` and a line in `GROUPS` in `src/help.rs`. Keep one domain per tool; prefer support subcommands (`doctor`, `cache`) over piling flags onto the root. Add a test in `tests/cli.rs` for every behavior you add, and give a command that takes arguments people get wrong at most three examples, and add its `-h` to the list `every_example_in_help_and_readme_parses` reads. +Add a subcommand by adding a variant to `Command` in `src/cli.rs`, a match arm in `run()` in `src/lib.rs`, its name in `COMMANDS` and, unless it is hidden like `man`, a line in `GROUPS` in `src/help.rs`. Keep one domain per tool; prefer support subcommands (`doctor`, `cache`) over piling flags onto the root. Add a test in `tests/cli.rs` for every behavior you add, and give a command that takes arguments people get wrong at most three examples, and add its `-h` to the list `every_example_in_help_and_readme_parses` reads. + +A flag that takes one of a fixed set of values names them in its own help, as `Colorize output (auto, always, or never)` does, because `-h` does not list them. Build the command through `cli::command()`, never `Cli::command()` directly: it hides clap's `[possible values: ...]` list from `-h` and moves each value's meaning, taken from the `ValueEnum` doc comments, into the long help `--help` shows. The man page alone builds from the plain definition, so roff draws its own list of values. The unit test at the bottom of `src/cli.rs` calls clap's `debug_assert()` on the built command, which catches a malformed definition that still compiles: a short flag used twice, a `default_value` outside the possible values, an arg that conflicts with itself. Those otherwise panic the first time a user reaches them, inside clap, where the `panic = "deny"` lint cannot see them. A proptest beside it feeds arbitrary argv to the parser for the same reason. diff --git a/docs/reference/development.md b/docs/reference/development.md index 55170c7..8e26a23 100644 --- a/docs/reference/development.md +++ b/docs/reference/development.md @@ -40,7 +40,7 @@ Every adapter splits its request (`search` or `list`) from a pure `parse`, and e `inspect` reads whole pages, and `tests/fixtures/inspect/` keeps real responses: `zenodo.html` is a record page with its `` and a `` cut down to its `application/ld+json` script, and the other fixtures are the JSON documents Dataverse and Hugging Face serve. The MCP session test in `tests/cli.rs` serves `zenodo.html` through a helper on `127.0.0.1` that acts as the proxy and answers every request with the page, tunnelled through `CONNECT` or not, so `inspect` runs end to end on an `http://` URL without the network. -To re-record a fixture after a source changes, repeat the adapter's request with `xh` and the dataseek User-Agent (`dataseek/ (mailto:user@dataseek.dev)`), never with a key, trim arrays to a few rows with `jq 'walk(if type=="array" then .[:4] else . end)'`, shorten long descriptions to a real prefix, replace any individual's e-mail address with `contact@example.org`, and then re-derive the expected record by reading the new file. Sources that need a key (FRED, Roboflow) use the example response from their API docs, linked above the test. +To re-record a fixture after a source changes, repeat the adapter's request with `xh` and the dataseek User-Agent (`dataseek/ (+https://github.com/lmarkmann/dataseek; mailto:user@dataseek.dev)`), never with a key, trim arrays to a few rows with `jq 'walk(if type=="array" then .[:4] else . end)'`, shorten long descriptions to a real prefix, replace any individual's e-mail address with `contact@example.org`, and then re-derive the expected record by reading the new file. Sources that need a key (FRED, Roboflow) use the example response from their API docs, linked above the test. `inspect` reads its file lists from recorded pages in `tests/fixtures/inspect/`, recorded under the same rules. Its `--json` shape is part of `json_shapes_snapshot` in `tests/cli.rs`, read from a page served on a random local port that a snapshot filter replaces with `[LOCAL_ADDR]`. diff --git a/docs/reference/keys-and-cache.md b/docs/reference/keys-and-cache.md index 8d3f1a1..bf3d8cc 100644 --- a/docs/reference/keys-and-cache.md +++ b/docs/reference/keys-and-cache.md @@ -26,7 +26,7 @@ Kaggle's files are the ones its CLI writes (`kaggle auth login`, or the token fr A data.gov key: sign up at https://api.data.gov/signup/ with a name and an address, and the key arrives by email at once. It gives 1,000 requests an hour; the shared `DEMO_KEY` gives 30 an hour and 50 a day. -Every request carries the contact address `user@dataseek.dev` in its User-Agent (and as `mailto` for DataCite, `email` for NCBI). It is the project's address and the same for every user. +Every request carries the repository URL and the contact address `user@dataseek.dev` in its User-Agent (and the address as `mailto` for DataCite, `email` for NCBI). It is the project's address, read by the maintainer, and the same for every user. ## Cache @@ -36,7 +36,7 @@ Every request carries the contact address `user@dataseek.dev` in its User-Agent | catalogs | 7 days | the full lists of the `local` sources | | outage marks | 10 minutes | sources skipped after an outage unless named with `--source` | -The cache directory is trimmed to 30 MB and 2,000 files after every search, oldest first. `--cache-dir DIR` or `DATASEEK_CACHE_DIR` moves it. +The cache directory is trimmed to 30 MB and 2,000 files after every search, oldest first. `DATASEEK_CACHE_MAX_MB` sets another size budget, in whole megabytes from 1 to 10,000; a larger one keeps more downloaded catalogs between searches, a smaller one fetches them again sooner. A value outside that range is a usage error (exit 2). `--cache-dir DIR` or `DATASEEK_CACHE_DIR` moves the directory. ```sh dataseek cache info # path, size and budget diff --git a/docs/reference/release.md b/docs/reference/release.md index 1b9d9b2..3257288 100644 --- a/docs/reference/release.md +++ b/docs/reference/release.md @@ -21,7 +21,7 @@ Uncategorized is the changelog telling you a subject was not conventional. Add ` ## The loop -On every push to `main`, the `release-pr` job opens or updates a PR that bumps the version and writes the changelog section from the commits since the last tag, then queues it for auto-merge. CI runs on that PR like on any other; once the required `linux` check is green, GitHub squash-merges it and deletes the branch, and the `release` job on that merge commit tags it and cuts the GitHub release, whose body is the changelog section. Nobody clicks anything between a `feat:` landing and its release. +On every push to `main`, the `release-pr` job opens or updates a PR that bumps the version and writes the changelog section from the commits since the last tag, then queues it for auto-merge. CI runs on that PR like on any other; once the required `linux` check is green, GitHub squash-merges it and deletes the branch, and the `release` job on that merge commit tags it and cuts the GitHub release, whose body is the changelog section. Publishing that GitHub release starts `.github/workflows/release.yml`, which builds the wheels and uploads them to PyPI (below). Nobody clicks anything between a `feat:` landing and its release. Nothing earlier than v0.3.0 exists: release-plz diffs against the newest `v*` tag, and that baseline was tagged by hand. @@ -29,7 +29,7 @@ Nothing earlier than v0.3.0 exists: release-plz diffs against the newest `v*` ta `.github/release-plz.toml`, passed through the action's `config` input in both jobs and `--config` locally: -- `git_only = true`, `publish = false`: the previous version comes from git tags, not crates.io, and nothing is published. +- `git_only = true`, `publish = false`: the previous version comes from git tags, not crates.io, and release-plz publishes nothing. Both go once the first crates.io release exists (below). - `git_release_enable = true`, `git_release_type = "auto"`, `git_release_body = "{{ changelog }}"`: every tag gets a GitHub release carrying that version's section. - `release_commits`: release-plz decides whether to release from changed files, not from changelog groups, so without it a `ci:` merge alone opens a release with an empty section. That is how v0.3.1 happened. - `features_always_increment_minor = true`: see ADR 0003. @@ -57,7 +57,19 @@ No release-plz subcommand has a dry-run flag, so the recipe runs the real `relea ## Publishing to crates.io -1. Drop `publish = false` from `Cargo.toml` and add `license`. -2. Drop `publish = false` and `git_only = true` from `.github/release-plz.toml`. -3. Give the `release` job `id-token: write` and register the repo as a crates.io trusted publisher; release-plz does the OIDC exchange, so there is no registry token. The first publish is manual. -4. Turn `semver_check` on if the crate grows a library, and revisit ADR 0003. +`cargo install dataseek` installs `dataseek` and `dsk`. The package holds only what building needs (`cargo package --list`); the `internals` feature is for the benches and unstable. + +crates.io trusts a publisher only for a crate that exists, so the first release goes up by hand: + +1. Merge the release PR; release-plz tags `vX.Y.Z`. +2. `git switch --detach vX.Y.Z && cargo publish --locked`, with a new-crate token in `CARGO_REGISTRY_TOKEN`. +3. Add the trusted publisher on crates.io (`lmarkmann/dataseek`, workflow `release-plz.yml`, environment `crates-io`), then revoke the token. +4. Drop `git_only` and `publish = false` from `.github/release-plz.toml`, and give the `release` job `environment: crates-io` and `id-token: write`. + +## Publishing to PyPI + +`uvx dataseek` runs a wheel holding both binaries, built by maturin with the version from `Cargo.toml`. `release.yml` builds the wheels on each GitHub release and uploads them with `uv publish` through trusted publishing ([ADR 0017](../adr/0017-release-builds-on-a-platform-matrix.md)). The same jobs attach `dataseek-.tar.gz` (`.zip` on Windows) with a `.sha256` to the release, which `cargo binstall dataseek` downloads. + +Before the first release, add a pending publisher at : project `dataseek`, `lmarkmann/dataseek`, workflow `release.yml`, environment `pypi`. + +`dsk` is also an unrelated PyPI project; installing both into one environment makes their scripts collide. diff --git a/docs/reference/security.md b/docs/reference/supply-chain.md similarity index 86% rename from docs/reference/security.md rename to docs/reference/supply-chain.md index 3bb88e7..fc06eef 100644 --- a/docs/reference/security.md +++ b/docs/reference/supply-chain.md @@ -1,4 +1,4 @@ -# Security +# Supply chain dataseek runs two supply-chain gates in CI and locally through `just audit`. @@ -11,15 +11,13 @@ dataseek runs two supply-chain gates in CI and locally through `just audit`. - `bans`: duplicate versions are warned, not failed. Wildcards in dependency requirements are denied. - `sources`: only crates.io is allowed. -The workspace member itself has no `license` field because the crate is `publish = false`; `licenses.private.ignore` tells cargo-deny not to flag it. - Run it with `just deny`. ## zizmor `zizmor` audits the GitHub Actions workflows themselves. There is no `.github/zizmor.yml`: every rule runs at its default. -Every `uses:` in both workflows is pinned to a full commit SHA with its tag in a trailing comment (`actions/checkout@3d3c... # v7.0.1`). The earlier split, tags in `ci.yml` and SHAs only in `release-plz.yml`, rested on hash pins rotting without a bot to refresh them; Renovate's `helpers:pinGitHubActionDigests` is now that bot, with a seven-day `minimumReleaseAge` on action updates so a pin never moves to a release younger than a week. That removes the condition the split was built on ([`rejected.md`](../adr/rejected.md), hash-pinning). The trailing comment is still load-bearing: `just actions-outdated` reads it, and `pinact run --verify --check` fails on a SHA whose comment does not match. Re-pin by hand with: +Every `uses:` in both workflows is pinned to a full commit SHA with its tag in a trailing comment (`actions/checkout@3d3c... # v7.0.1`). The earlier split, tags in `ci.yml` and SHAs only in `release-plz.yml`, rested on hash pins rotting without a bot to refresh them; Renovate's `helpers:pinGitHubActionDigests` is now that bot, with a seven-day `minimumReleaseAge` on action updates so a pin never moves to a release younger than a week. That removes the condition the split was built on. The trailing comment is still load-bearing: `just actions-outdated` reads it, and `pinact run --verify --check` fails on a SHA whose comment does not match. Re-pin by hand with: ```sh just repin diff --git a/docs/synthesis/terms.md b/docs/synthesis/terms.md index eeaaaf9..55766b9 100644 --- a/docs/synthesis/terms.md +++ b/docs/synthesis/terms.md @@ -2,7 +2,7 @@ May a publicly distributed copy of dataseek query each source the way its adapter does? Every row below was checked on 2026-10-06 against the provider's own terms, API pages and `robots.txt`, with the live endpoint, and judged for a public release: thousands of installs sending the adapter's request with one shared User-Agent and contact address. A row rests on a quoted sentence; where the terms are silent the verdict says so, because silence in the terms is never permission. -Verdicts: **keep** (the provider documents or invites this use), **keep with conditions** (the use is allowed or not forbidden, with something to honour or confirm), **opt-in only** (asked only when named, [ADR 0013](../adr/0013-opt-in-sources.md)), **drop** (none). Where the table says `unclear`, no sentence in the terms speaks to a third-party client querying this endpoint. +Verdicts: **keep** (the provider documents or invites this use), **keep with conditions** (the use is allowed or not forbidden, with something to honour), **opt-in only** (asked only when named, [ADR 0013](../adr/0013-opt-in-sources.md)), **drop** (none). Where the table says `unclear`, no sentence in the terms speaks to a third-party client querying this endpoint. ## The 76 rows @@ -28,8 +28,8 @@ Verdicts: **keep** (the provider documents or invites this use), **keep with con | `recherche-data-gouv` | keep | "donne accès ... aux Jeux de données via l'interface de la plateforme Recherche Data Gouv ou par l'intermédiaire d'une API web" [CGU](https://recherche.data.gouv.fr/fr/page/conditions-generales-d-utilisation-de-la-plateforme-de-recherche-data-gouv) | none | 2026-10-06 | | `dataverse-nl` | keep | "DANS will provide community-aligned, standards-based discovery ... and API-based access. DANS allows for harvesting of metadata" [Data Stations Policy J.1](https://dans.knaw.nl/wp-content/uploads/2023/03/DANS-Data-Stations-Policy.pdf) | none | 2026-10-06 | | `dataverse-no` | keep | unclear on the API; metadata: "DataverseNO waives any and all rights it might have with respect to Descriptive Metadata ... pursuant to a CC0 Public Domain Dedication" [site](https://site.uit.no/dataverseno/?p=2020) | none | 2026-10-06 | -| `osf` | keep with conditions | "currently, that trove of metadata is mostly focused on osf.io ... but both are open for anyone to use." [OpenAPI](https://share.osf.io/trove/docs/openapi.json); the `/trove/` throttle is unpublished and 17 requests in 3 minutes drew an hour-long 429 | ask share-support@cos.io for the throttle before release | 2026-10-06 | -| `mendeley` | opt-in only | "Unless you have express prior written permission, you may not use any spider- or bot-like system, software or other device or program (whether automated or otherwise) to extract content, data, information or other material from the Site." (clause 3.5) [terms](https://www.mendeley.com/terms/); `robots.txt` has `Disallow: /api/` and the module requests `/api/research-data/search` | opt-in (ADR 0013); drop if permission is refused | 2026-10-06 | +| `osf` | keep with conditions | "currently, that trove of metadata is mostly focused on osf.io ... but both are open for anyone to use." [OpenAPI](https://share.osf.io/trove/docs/openapi.json); the `/trove/` throttle is unpublished and 17 requests in 3 minutes drew an hour-long 429 | a 429 rests the source for 10 minutes, since the `/trove/` throttle is unpublished | 2026-10-06 | +| `mendeley` | opt-in only | "Unless you have express prior written permission, you may not use any spider- or bot-like system, software or other device or program (whether automated or otherwise) to extract content, data, information or other material from the Site." (clause 3.5) [terms](https://www.mendeley.com/terms/); `robots.txt` has `Disallow: /api/` and the module requests `/api/research-data/search` | opt-in (ADR 0013) | 2026-10-06 | | `europa` | keep | "Search: https://data.europa.eu/api/hub/search/ (Note: Only 'Read-Only' actions are currently supported for this API)" [FAQ](https://data.europa.eu/en/faq) | none | 2026-10-06 | | `datagov` | keep with conditions | "The Data.gov Catalog API provides access to metadata about datasets published by federal, state, local, and tribal governments. You can use it to search for datasets" [Catalog API](https://resources.data.gov/catalog-api/); the keyless host states no rule | heavy users set `DATAGOV_API_KEY` | 2026-10-06 | | `data-gov-uk` | keep | "You do not need an API key to use the API and there are no rate limits." [API guidance](https://guidance.data.gov.uk/get_data/api_documentation/) | none | 2026-10-06 | @@ -39,15 +39,15 @@ Verdicts: **keep** (the provider documents or invites this use), **keep with con | `hdx` | keep | the API is for "analysts and technical audiences who want to discover datasets, build automated workflows, or integrate HDX data into external systems" [docs](https://docs.humdata.org/build/hdx-apis/metadata-endpoints); 60 calls a minute draw a 429 | none | 2026-10-06 | | `socrata` | keep | "Authentication is not required to use this API for read-only access to the corpus of anonymously-viewable (i.e. public, published, approved, and not hidden) assets." [Discovery API](https://dev.socrata.com/apis/discovery.yaml); no standalone API terms; an app token is recommended | none | 2026-10-06 | | `socrata-eu` | keep | same Discovery API on the EU host | none | 2026-10-06 | -| `opendatasoft` | keep with conditions | Art. 3: users must "refrain from accessing, attempting to access, extracting, copying, downloading, reusing, or exploiting all or part of the content published on the solution by automated means (including, without limitation, robots, spiders, crawlers, scrapers, or any other similar process), unless with Huwise's prior written authorization" [terms](https://legal.huwise.com/en/terms-of-use.html); addressed to logged-in users, while the Explore API reference invites anonymous use; 10,000 calls a day shared by all anonymous callers | ask legal@huwise.com for the authorization before release | 2026-10-06 | +| `opendatasoft` | keep with conditions | Art. 3: users must "refrain from accessing, attempting to access, extracting, copying, downloading, reusing, or exploiting all or part of the content published on the solution by automated means (including, without limitation, robots, spiders, crawlers, scrapers, or any other similar process), unless with Huwise's prior written authorization" [terms](https://legal.huwise.com/en/terms-of-use.html); addressed to logged-in users, while the Explore API reference invites anonymous use; 10,000 calls a day shared by all anonymous callers | none | 2026-10-06 | | `arcgis` | keep with conditions | "As a content user, it is your responsibility to abide by the content owner's terms of use." [terms](https://doc.arcgis.com/en/arcgis-online/reference/terms-of-use.htm); public search needs no token | surface each item's license | 2026-10-06 | | `dbnomics` | keep | "It is designed to query focused data, i.e. a subset of the data available on DBnomics, and not to download large datasets." [web API](https://docs.db.nomics.world/web-api/) | none | 2026-10-06 | | `worldbank` | keep with conditions | "You may not use the APIs in a manner that exceeds reasonable request volume or constitutes excessive or abusive usage, as determined by The World Bank Group at its sole discretion." [terms](https://www.worldbank.org/en/about/legal/terms-and-conditions); non-commercial for materials outside the Data Catalog | weekly catalog only; ask data@worldbankgroup.org before any monetised version | 2026-10-06 | -| `worldbank-microdata` | keep with conditions | the same World Bank API clause; the Microdata terms cover the data files, not search calls [terms](https://microdata.worldbank.org/index.php/terms-of-use) | one request per search; ask the Microdata Library before release | 2026-10-06 | +| `worldbank-microdata` | keep with conditions | the same World Bank API clause; the Microdata terms cover the data files, not search calls [terms](https://microdata.worldbank.org/index.php/terms-of-use) | one request per search | 2026-10-06 | | `ihsn` | keep with conditions | unclear: the terms page is a data access agreement and says nothing about API calls | as above | 2026-10-06 | | `fao-microdata` | keep with conditions | unclear: same, a data access agreement | as above | 2026-10-06 | | `unhcr-microdata` | keep with conditions | unclear: same, a data access agreement | as above | 2026-10-06 | -| `imf` | keep with conditions | "The IMF prohibits bulk download of information by automated technology without explicit permission and reserves the right to terminate access to its Sites or Content." [copyright and terms](https://www.imf.org/en/About/copyright-and-terms); the adapter fetches one 445 KB structure list a week and no data | ask datahelp@imf.org for the permission the terms name, before release | 2026-10-06 | +| `imf` | keep with conditions | "The IMF prohibits bulk download of information by automated technology without explicit permission and reserves the right to terminate access to its Sites or Content." [copyright and terms](https://www.imf.org/en/About/copyright-and-terms); the adapter fetches one 445 KB structure list a week and no data | weekly structure list only, no data | 2026-10-06 | | `oecd` | keep | "You may use one or more OECD-developed application programming interfaces ("APIs") to facilitate access to the Data." [terms](https://www.oecd.org/en/about/terms-conditions.html); 60 data downloads an hour per IP | none | 2026-10-06 | | `ecb` | keep | "The ECB SDMX 2.1 RESTful web service offers programmatic access to the statistical data and metadata disseminated via the ECB Data Portal." [API overview](https://data.ecb.europa.eu/help/api/overview) | none | 2026-10-06 | | `eurostat` | keep | "These APIs are free of charge programmatic access to statistical metadata and data. This is the interface to use for the automation of metadata and data queries or downloads." [API introduction](https://ec.europa.eu/eurostat/web/user-guides/data-browser/api-data-access/api-introduction) | none | 2026-10-06 | @@ -56,10 +56,10 @@ Verdicts: **keep** (the provider documents or invites this use), **keep with con | `undata` | keep | "The API is governed by UNdata Terms of Use." [API page](https://data.un.org/Host.aspx?Content=API) | none | 2026-10-06 | | `datacommons` | keep with conditions | "All access to the base Data Commons (datacommons.org) using the REST APIs must be authenticated and authorized with an API key." [REST v2](https://docs.datacommons.org/api/rest/v2/index.html); the trial key is "for general public use ... single requests", not for applications | own key required, trial key removed | 2026-10-06 | | `owid` | keep | "Search API for accessing Our World in Data charts and content pages powered by Algolia." [Search API](https://docs.owid.io/projects/etl/api/search-api/) | none | 2026-10-06 | -| `fred` | keep with conditions | "In order to use the FRED(R) API, you must have register for an API Key." and the application must show "This product uses the FRED(R) API but is not endorsed or certified by the Federal Reserve Bank of St. Louis." with a link to the terms [terms](https://fred.stlouisfed.org/docs/api/terms_of_use.html) | own key required; notice still to be shown (see below) | 2026-10-06 | +| `fred` | keep with conditions | "In order to use the FRED(R) API, you must have register for an API Key." and the application must show "This product uses the FRED(R) API but is not endorsed or certified by the Federal Reserve Bank of St. Louis." with a link to the terms [terms](https://fred.stlouisfed.org/docs/api/terms_of_use.html) | own key required; notice shown in the README and `dataseek sources` | 2026-10-06 | | `bundesbank` | keep | "Die Bundesbank stellt mit dieser API eine technische Schnittstelle bereit, über die statistische Daten automatisiert abgerufen werden können." [API](https://statistiken.bundesbank.de/content/991208) | none | 2026-10-06 | | `fiscal-data` | keep | "The data is offered free, without restriction, and available to copy, adapt, redistribute, or otherwise use for non-commercial or commercial purposes." [API documentation](https://fiscaldata.treasury.gov/api-documentation/); the metadata endpoint itself is not mentioned | none | 2026-10-06 | -| `census` | keep with conditions | "You may use the Census Bureau API to develop a service or service to search, display, analyze, retrieve, view and otherwise "get" information from Census Bureau data." [terms of service](https://www.census.gov/data/developers/about/terms-of-service.html); a notice must be shown | notice still to be shown (see below) | 2026-10-06 | +| `census` | keep with conditions | "You may use the Census Bureau API to develop a service or service to search, display, analyze, retrieve, view and otherwise "get" information from Census Bureau data." [terms of service](https://www.census.gov/data/developers/about/terms-of-service.html); a notice must be shown | notice shown in the README and `dataseek sources` | 2026-10-06 | | `who` | keep with conditions | "You may use our application programming interfaces ("APIs") to facilitate access to the Datasets, whether through a separate web site or through another type of software application." [data.who.int terms](https://data.who.int/about/data/terms-and-conditions); the older website terms allow research and private use only, and it is unclear which governs the GHO API | shows only titles and links, never values | 2026-10-06 | | `cmr` | keep | "NASA's ESDS Program promotes the full and open sharing of all data, metadata, documentation ... and research results, and all source code." [policies](https://www.earthdata.nasa.gov/engage/open-data-services-software-policies) | sends `Client-Id: dataseek` | 2026-10-06 | | `planetary-computer` | keep | "The STAC API is public and can be accessed anonymously." [docs](https://planetarycomputer.microsoft.com/docs) | none | 2026-10-06 | @@ -68,19 +68,19 @@ Verdicts: **keep** (the provider documents or invites this use), **keep with con | `copernicus-cds` | keep with conditions | unclear: the terms only say "Download of Content requires prior registration" and are silent on the catalogue API [terms](https://cds.climate.copernicus.eu/licences/terms-of-use-cds) | none | 2026-10-06 | | `earth-engine` | keep | "using automated means to access content from any of our services in violation of the machine-readable instructions on our web pages" is the barred form [terms](https://policies.google.com/terms); `developers.google.com/robots.txt` allows the page; the 7-day cache of a `no-cache` page is unclear | none | 2026-10-06 | | `ncei` | keep | "The National Centers for Environmental Information (NCEI) Common Access Search Service provides a RESTful application programming interface (API) to discover datasets and data" [API documentation](https://www.ncei.noaa.gov/support/access-search-service-api-user-documentation) | none | 2026-10-06 | -| `pangaea` | keep with conditions | "The offered service of data search via the PANGAEA platform includes the fair use of the access to the open access data portal and its Application Programming Interfaces (APIs)" (5.5) [terms](https://www.pangaea.de/about/terms.php); the endpoint is internal and undocumented, and `robots.txt` has `Disallow: /advanced/` | one request per search; ask PANGAEA for the authorization its terms mention | 2026-10-06 | +| `pangaea` | keep with conditions | "The offered service of data search via the PANGAEA platform includes the fair use of the access to the open access data portal and its Application Programming Interfaces (APIs)" (5.5) [terms](https://www.pangaea.de/about/terms.php); the endpoint is internal and undocumented, and `robots.txt` has `Disallow: /advanced/` | one request per search; move to the official search API when PANGAEA ships it | 2026-10-06 | | `gbif` | keep | barred: DoS and disruption; "If you are integrating the GBIF API into a website or app, we highly recommend you set the HTTP User-Agent to a URL or email address." [API docs](https://techdocs.gbif.org/en/openapi/), [data user terms](https://www.gbif.org/terms/data-user) | none | 2026-10-06 | -| `dataone` | keep with conditions | unclear: no API terms (the site's terms paths answer 401); the design docs say "The underlying SOLR index is also exposed through as an API, so other clients (such as the file system driver) can leverage the search capabilities thus provided." [design](https://dataoneorg.github.io/api-documentation/design/SearchMetadata.html) | ask support@dataone.org for usage terms and a request rate | 2026-10-06 | -| `geo` | keep with conditions | "NCBI recommends that users post no more than three URL requests per second and limit large jobs to either weekends or between 9:00 PM and 5:00 AM Eastern time during weekdays." [usage policy](https://www.ncbi.nlm.nih.gov/books/NBK25497/); `tool` and `email` must be registered, and NCBI's disclaimer and copyright notice "must be evident to users" | register `tool=dataseek`, `email=user@dataseek.dev`; show the notice (see below) | 2026-10-06 | +| `dataone` | keep with conditions | unclear: no API terms (the site's terms paths answer 401); the design docs say "The underlying SOLR index is also exposed through as an API, so other clients (such as the file system driver) can leverage the search capabilities thus provided." [design](https://dataoneorg.github.io/api-documentation/design/SearchMetadata.html) | none | 2026-10-06 | +| `geo` | keep with conditions | "NCBI recommends that users post no more than three URL requests per second and limit large jobs to either weekends or between 9:00 PM and 5:00 AM Eastern time during weekdays." [usage policy](https://www.ncbi.nlm.nih.gov/books/NBK25497/); `tool` and `email` must be registered, and NCBI's disclaimer and copyright notice "must be evident to users" | send `tool=dataseek`, `email=user@dataseek.dev`, registered only if NCBI ever blocks them; show the notice (see below) | 2026-10-06 | | `arrayexpress` | keep | "The RESTful Web Services API offers programmatic access to the EBI Search functionality that can be used in third party projects (Search as a Service)." [EBI Search](https://www.ebi.ac.uk/ebisearch/documentation/rest-api); use that prevents service to others gets blocked [terms](https://www.ebi.ac.uk/about/terms-of-use/) | none | 2026-10-06 | | `biostudies` | keep | the same EBI Search API | none | 2026-10-06 | -| `omicsdi` | keep with conditions | "can be accessed programmatically using a RESTful API allowing for integration with other resources" [API help](https://www.omicsdi.org/help/api); `robots.txt` has `Disallow: /ws` and `Disallow: /ws/dataset/search`, which contradicts the documented API | confirm with omicsdi-support@ebi.ac.uk before release | 2026-10-06 | +| `omicsdi` | keep with conditions | "can be accessed programmatically using a RESTful API allowing for integration with other resources" [API help](https://www.omicsdi.org/help/api); `robots.txt` has `Disallow: /ws` and `Disallow: /ws/dataset/search`, which contradicts the documented API | none | 2026-10-06 | | `cellxgene` | keep | unclear: the terms say nothing on API use; closest text: "You shall not otherwise access or use ... the Site to take any action that could harm us, the Site, or any third party" [terms](https://cellxgene.cziscience.com/tos); the API spec lists them as its `termsOfService` | none | 2026-10-06 | | `synapse` | keep with conditions | "Any use of the API, including use of the API through a third-party product that accesses Synapse, is bound by these Terms and Conditions of Use" (section 5), and 6.s bars scrapers "except and solely to the extent permitted by these Terms and the features of Synapse" [terms](https://s3.amazonaws.com/static.synapse.org/governance/SageBionetworksSynapseTermsandConditionsofUse.pdf); anonymous metadata search is documented ("If not authenticated, only public result will be shown.") | stay anonymous and identified | 2026-10-06 | | `openneuro` | keep | unclear: the docs show programmatic queries but publish no API terms; "all newly published datasets are released under CC0" [FAQ](https://docs.openneuro.org/faq.html) | none | 2026-10-06 | | `dandi` | keep | "Access to DANDI's content is open to all." [terms](https://docs.dandiarchive.org/terms-policies/terms/); "Read operations on public data do not require authentication." | none | 2026-10-06 | | `physionet` | keep with conditions | unclear: no site terms or API page; the code says "Rate limited: 20 requests/hour for anonymous users" while the deployed list answers an anonymous GET [physionet-build](https://github.com/MIT-LCP/physionet-build) | one download a week per install, never a live per-search call | 2026-10-06 | -| `cern` | keep with conditions | unclear: "All metadata and datasets in the CERN Open Data Portal are made available under the terms of the CC0 waiver." The terms never mention the API, `robots.txt` has `Disallow: /api/`, and CERN's own client queries the same API [terms](https://opendata.cern.ch/terms-of-use) | stay under 60 requests a minute; confirm with the portal before release | 2026-10-06 | +| `cern` | keep with conditions | unclear: "All metadata and datasets in the CERN Open Data Portal are made available under the terms of the CC0 waiver." The terms never mention the API, `robots.txt` has `Disallow: /api/`, and CERN's own client queries the same API [terms](https://opendata.cern.ch/terms-of-use) | stay under 60 requests a minute | 2026-10-06 | | `materials-project` | keep | "You may collect large fractions of the database for analysis via the Materials Project API"; "You agree to not scrape the website directly." [terms](https://legacy.materialsproject.org/terms) | none | 2026-10-06 | | `nomad` | keep | the terms bar only "run auto-responders or 'spam' on the site or Service"; "Rate limits are enforced based on your IP address." [terms](https://nomad-lab.eu/nomad-lab/terms.html), [API docs](https://docs.nomad-lab.eu/howto/manage/program/api.html) | none | 2026-10-06 | | `cessda` | keep | "Resource- discovery metadata in a structured format shall be openly available for any third party to harvest." (Data Access Policy, principle 9) [policy](https://www.cessda.eu/CESSDA-Documents/Policies/Data-Acess-Policy/CESSDA-Data-Access-Policy.pdf) | none | 2026-10-06 | @@ -91,14 +91,10 @@ Verdicts: **keep** (the provider documents or invites this use), **keep with con ## What the terms ask the tool to show -None of these is shown at run time yet; each is a decision for the maintainer. +The README's Data sources section carries all of these. `dataseek sources` also prints the FRED and Census notices under its table, because their terms ask for the notice in the application itself. - FRED: the notice "This product uses the FRED(R) API but is not endorsed or certified by the Federal Reserve Bank of St. Louis." and a link to the terms in any application that uses the API. - Census Bureau: "This product uses the Census Bureau Data API but is not endorsed or certified by the Census Bureau." - NCBI: the E-utilities disclaimer and copyright notice must be evident to users; the tool and e-mail pair must be registered with NCBI. - WHO: citation in the form "World Health Organization {YEAR} data.who.int, {ITEM_NAME} [{ITEM_TYPE}]. {URL} (Accessed on {ACCESS DATE})". - OpenAIRE, GBIF, Eurostat, ECB, Bundesbank, OECD, IMF, Data.gov, Materials Project: acknowledgement of the source when the data is reused; dataseek prints each result's publisher and link. - -## Before a public release - -Written confirmation or permission, in the order of the risk it removes: IMF (datahelp@imf.org), Huwise for OpenDataSoft (legal@huwise.com), PANGAEA, OmicsDI (omicsdi-support@ebi.ac.uk), CERN Open Data, Zenodo (the `/api` robots rule), Mendeley (data-queries@mendeley.com, which would lift its opt-in), the World Bank Microdata Library, DataONE (support@dataone.org), OSF (share-support@cos.io, for the trove throttle), NCBI (registration). diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..94847e8 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,21 @@ +# The PyPI package: the Rust binaries in a wheel, no Python API +# (docs/reference/release.md). The version comes from Cargo.toml. +[build-system] +requires = ["maturin>=1.15,<2"] +build-backend = "maturin" + +[project] +name = "dataseek" +description = "Search for datasets from the terminal" +readme = "README.md" +license = "MIT OR Apache-2.0" +license-files = ["LICENSE-MIT", "LICENSE-APACHE"] +keywords = ["dataset", "search", "open-data", "research", "cli"] +dynamic = ["version"] + +[project.urls] +Repository = "https://github.com/lmarkmann/dataseek" +Changelog = "https://github.com/lmarkmann/dataseek/blob/main/docs/CHANGELOG.md" + +[tool.maturin] +bindings = "bin" diff --git a/src/bench.rs b/src/bench.rs index bc7e9db..56ffdc2 100644 --- a/src/bench.rs +++ b/src/bench.rs @@ -67,7 +67,11 @@ pub fn run( .map(|s| (s.id, Row { id: s.id, ..Row::default() })) .collect(); - let total = queries.len().saturating_mul(sources.len()); + let asked = sources + .iter() + .filter(|s| s.missing_key(&services.creds).is_none()) + .count(); + let total = queries.len().saturating_mul(asked); ui::stage(format!( "benchmarking {} sources on {} queries ({total} requests, no cache)", sources.len(), diff --git a/src/cache.rs b/src/cache.rs index da38332..fe5d688 100644 --- a/src/cache.rs +++ b/src/cache.rs @@ -4,13 +4,15 @@ //! One JSON file per entry under the cache directory, written atomically, so //! parallel source threads never share a file or a lock. Fresh entries are //! served without a request; expired ones are kept as a fallback for when the -//! source is down. The whole directory stays under [`BUDGET_BYTES`] and +//! source is down. The whole directory stays under [`budget_bytes`] and //! [`BUDGET_FILES`]: [`Cache::trim`] evicts the least recently written //! entries first and runs once at the end of every search, never per write. //! Everything here is best effort: a cache that cannot be read or written //! degrades to fetching, it never fails a search. +use std::ops::RangeInclusive; use std::path::{Path, PathBuf}; +use std::sync::OnceLock; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use serde::de::DeserializeOwned; @@ -18,8 +20,48 @@ use serde::{Deserialize, Serialize}; use crate::fs::write_atomic; -pub const BUDGET_BYTES: u64 = 30 * 1024 * 1024; +/// The size budget unless [`BUDGET_VAR`] sets another, in decimal megabytes +/// like every size dataseek prints. +pub const BUDGET_BYTES: u64 = 30 * 1000 * 1000; pub const BUDGET_FILES: usize = 2000; +/// Replaces the size budget, in whole megabytes within [`BUDGET_MB`]. +pub const BUDGET_VAR: &str = "DATASEEK_CACHE_MAX_MB"; +pub const BUDGET_MB: RangeInclusive = 1..=10_000; + +static BUDGET: OnceLock = OnceLock::new(); + +/// Read [`BUDGET_VAR`] once, at startup, so a bad value is a usage error +/// before any work starts rather than a cache that quietly ignores it. +pub fn read_budget() -> Result<(), String> { + let Some(raw) = std::env::var_os(BUDGET_VAR) else { return Ok(()) }; + let mb = raw + .to_str() + .and_then(|text| text.trim().parse::().ok()) + .filter(|mb| BUDGET_MB.contains(mb)) + .ok_or_else(|| { + format!( + "invalid value '{}' for {BUDGET_VAR}: whole megabytes from \ + {} to {}\n\ntip: set it to a number such as 100, or unset it \ + for the 30 MB default\n", + raw.to_string_lossy(), + BUDGET_MB.start(), + BUDGET_MB.end() + ) + })?; + let _ = BUDGET.set(mb.saturating_mul(1000 * 1000)); + Ok(()) +} + +/// The size budget in effect: [`BUDGET_VAR`] when set, else +/// [`BUDGET_BYTES`]. +pub fn budget_bytes() -> u64 { + BUDGET.get().copied().unwrap_or(BUDGET_BYTES) +} + +/// Whether [`BUDGET_VAR`] set the budget. +pub fn budget_from_env() -> bool { + BUDGET.get().is_some() +} /// How long a query's results are served without asking the source again. pub const QUERY_TTL: Duration = Duration::from_hours(6); @@ -172,7 +214,7 @@ impl Cache { /// Evict the oldest entries until the directory fits the budget. pub fn trim(&self) -> Usage { - trim_files(self.files(), BUDGET_BYTES, BUDGET_FILES) + trim_files(self.files(), budget_bytes(), BUDGET_FILES) } /// Remove the entries, never the root: `--cache-dir` can point at a diff --git a/src/cache_cmd.rs b/src/cache_cmd.rs index ef52a7d..2a80183 100644 --- a/src/cache_cmd.rs +++ b/src/cache_cmd.rs @@ -4,7 +4,7 @@ use std::io::Write; use anyhow::{Context, Result}; -use crate::cache::{BUDGET_BYTES, BUDGET_FILES, Cache}; +use crate::cache::{self, BUDGET_FILES, Cache}; use crate::cli::CacheAction; use crate::find::human_bytes; use crate::http::SourceError; @@ -15,8 +15,9 @@ use crate::{paths, ui}; #[derive(Debug, thiserror::Error)] pub enum Error { #[error( - "{} of {total} catalogs failed to download: {}\n Try: run `dataseek cache warm` again later; searches still use what did download", + "{} of {} failed to download: {}\n Try: run `dataseek cache warm` again later; searches still use what did download", failed.len(), + crate::ui::count(*total, "catalog"), failed.join(", ") )] Partial { failed: Vec<&'static str>, total: usize }, @@ -106,7 +107,7 @@ fn warm(out: &Out, dry_run: bool) -> Result<()> { return Err(Error::Partial { failed, total: results.len() }.into()); } if !dry_run { - ui::ok(format!("{} catalogs downloaded", results.len())); + ui::ok(format!("{} downloaded", ui::count(results.len(), "catalog"))); } Ok(()) } @@ -126,7 +127,7 @@ fn download<'a>( ) })?; let ctx = services.ctx(true); - ui::stage(format!("downloading {} catalogs", catalogs.len())); + ui::stage(format!("downloading {}", ui::count(catalogs.len(), "catalog"))); let progress = ui::bar(catalogs.len() as u64, "catalogs"); let results = std::thread::scope(|scope| { let workers: Vec<_> = catalogs @@ -167,17 +168,22 @@ fn info(cache: &Cache, out: &Out) -> Result<()> { "files": usage.files, "bytes": usage.bytes, "budget_files": BUDGET_FILES, - "budget_bytes": BUDGET_BYTES, + "budget_bytes": cache::budget_bytes(), })); } let mut w = out.stdout(); writeln!(w, "{}", cache.root().display())?; writeln!( w, - "{} files, {} of {} budget ({} files max)", + "{} files, {} of {} budget{} ({} files max)", usage.files, human_bytes(usage.bytes), - human_bytes(BUDGET_BYTES), + human_bytes(cache::budget_bytes()), + if cache::budget_from_env() { + format!(", set by {}", cache::BUDGET_VAR) + } else { + String::new() + }, BUDGET_FILES )?; Ok(()) diff --git a/src/cli.rs b/src/cli.rs index 94cfbb8..fc96bb5 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -1,8 +1,10 @@ use std::ops::{RangeFrom, RangeInclusive}; use std::path::PathBuf; -use clap::builder::PossibleValuesParser; -use clap::{Args, Parser, Subcommand, ValueEnum}; +use std::fmt::Write; + +use clap::builder::{PossibleValuesParser, StyledStr}; +use clap::{Arg, Args, CommandFactory, Parser, Subcommand, ValueEnum}; use clap_complete::Shell; use crate::palette; @@ -44,6 +46,7 @@ macro_rules! examples { dsk s census --json | jq -r '.results[].url' one field per line" }; } +pub(crate) use examples; #[derive(Parser)] #[command( @@ -79,7 +82,7 @@ pub struct Cli { #[arg(long, global = true)] pub json: bool, - /// When to colorize output: auto, always, or never. + /// Colorize output (auto, always, or never). #[arg(long, value_name = "WHEN", default_value = "auto", global = true)] pub color: ColorChoice, @@ -119,27 +122,10 @@ pub struct Cli { )] pub connect_timeout: u64, - /// Removed; kept hidden so a script that still passes it learns what - /// replaced it instead of reading clap's generic unknown-argument error. - #[arg( - long, - value_name = "EXPR", - global = true, - hide = true, - value_parser = removed_jq - )] - pub jq: Option, - #[command(subcommand)] pub command: Option, } -fn removed_jq(_: &str) -> Result { - Err("--jq was removed; pipe --json into jq instead, as in \ - `dsk search census --json | jq -r '.results[].url'`, under \ - `set -o pipefail` so a failed search still fails the pipeline") -} - /// Which sources to ask, shared by `search` and `bench`. #[derive(Args, Clone, Debug, Default)] pub struct Selection { @@ -167,7 +153,8 @@ pub struct Selection { )] pub exclude: Vec, - /// Only sources in these categories, comma-separated. + /// Only sources in these categories, comma-separated (see `dataseek + /// sources`). #[arg( short = 'c', long = "category", @@ -191,6 +178,47 @@ fn source_ids() -> PossibleValuesParser { PossibleValuesParser::new(crate::sources::SOURCES.iter().map(|s| s.id)) } +/// The command every surface builds from: parsing, help, the man page, +/// completions and `help --json`. A flag with a fixed set of values names +/// them in its own help, so clap's `[possible values: ...]` would repeat +/// them in `-h`; that list is hidden, and what each value means moves into +/// the long help that `--help` and the man page show. +pub fn command() -> clap::Command { + Cli::command() + .mut_args(values_in_long_help) + .mut_subcommands(|sub| sub.mut_args(values_in_long_help)) +} + +fn values_in_long_help(arg: Arg) -> Arg { + let values = arg.get_possible_values(); + if values.is_empty() + || !arg.get_action().takes_values() + || arg.is_hide_possible_values_set() + { + return arg; + } + let described: Vec<_> = values + .iter() + .filter_map(|v| v.get_help().map(|help| (v.get_name(), help))) + .collect(); + let width = described.iter().map(|(name, _)| name.len()).max(); + let (Some(width), Some(help)) = (width, arg.get_help()) else { + return arg.hide_possible_values(true); + }; + let literal = palette::success(); + let mut long = StyledStr::new(); + let _ = write!(long, "{help}\n\nPossible values:"); + for (name, meaning) in &described { + let pad = width.saturating_sub(name.len()); + let _ = write!( + long, + "\n- {literal}{name}{literal:#}: {:pad$}{meaning}", + "" + ); + } + arg.hide_possible_values(true).long_help(long) +} + #[derive(Subcommand)] pub enum Command { /// Search every source at once, merged, deduplicated and ranked. @@ -223,7 +251,7 @@ pub enum Command { )] limit: usize, - /// Order of the results. + /// Order of the results (relevance or newest). #[arg(long, value_name = "ORDER", default_value = "relevance")] sort: Sort, @@ -248,25 +276,6 @@ pub enum Command { /// List every source: what it covers, its protocol, its key, its docs. Sources, - /// Time every source on real queries and measure their overlap. - #[command( - long_about = "Time every source on real queries and measure their \ - overlap.\n\nBench bypasses the cache and asks every chosen source \ - once per query, so it sends queries x sources requests. Without \ - queries it uses a fixed set chosen to touch every category.", - after_help = "Examples: - dsk bench \"air quality\" \"protein structure\" each query is one argument - dsk bench mnist -s huggingface,kaggle,openml only these sources" - )] - Bench { - /// Queries to time; each is one argument (quote multi-word queries). - #[arg(value_name = "QUERY")] - queries: Vec, - - #[command(flatten)] - selection: Selection, - }, - /// Read a dataset page's metadata and the files it lists. #[command( long_about = "Read a dataset page's metadata and the files it \ @@ -300,6 +309,25 @@ pub enum Command { )] Mcp, + /// Time every source on real queries and measure their overlap. + #[command( + long_about = "Time every source on real queries and measure their \ + overlap.\n\nBench bypasses the cache and asks every chosen source \ + once per query, so it sends queries x sources requests. Without \ + queries it uses a fixed set chosen to touch every category.", + after_help = "Examples: + dsk bench \"air quality\" \"protein structure\" each query is one argument + dsk bench mnist -s huggingface,kaggle,openml only these sources" + )] + Bench { + /// Queries to time; each is one argument (quote multi-word queries). + #[arg(value_name = "QUERY")] + queries: Vec, + + #[command(flatten)] + selection: Selection, + }, + /// Show, warm or clear the cache. #[command(subcommand)] Cache(CacheAction), @@ -307,17 +335,19 @@ pub enum Command { /// Check the environment, keys and cache, and report readiness. Doctor, - /// Print a shell completion script to stdout. + /// Print a shell completion script; on a terminal, say where to save it. Completion { - /// Target shell (fish, bash, zsh, ...). + /// Target shell (bash, elvish, fish, powershell, or zsh). shell: Shell, }, - /// Print the man page, in roff, to stdout. + /// Show the man page; in a pipe, print it in roff. #[command( - long_about = "Print the man page, in roff, to stdout.\n\nRead it \ - with `dataseek man | man -l -`, or install it with \ - `dataseek man > ~/.local/share/man/man1/dataseek.1`." + hide = true, + long_about = "Show the man page; in a pipe, print it in roff.\n\n\ + Install it with `dataseek man > \ + ~/.local/share/man/man1/dataseek.1`, then `man dataseek` finds \ + it; save it as dsk.1 for `man dsk`." )] Man, @@ -352,7 +382,7 @@ pub enum CacheAction { #[cfg(test)] mod tests { - use clap::{CommandFactory, Parser}; + use clap::Parser; use proptest::prelude::*; use super::Cli; @@ -361,7 +391,7 @@ mod tests { // are not compile errors. #[test] fn the_definition_is_well_formed() { - Cli::command().debug_assert(); + super::command().debug_assert(); } proptest! { diff --git a/src/doctor.rs b/src/doctor.rs index 6752ce8..3b802bf 100644 --- a/src/doctor.rs +++ b/src/doctor.rs @@ -7,10 +7,10 @@ use anyhow::Result; use clap::builder::styling::Style; use serde::Serialize; -use crate::cache::{BUDGET_BYTES, Cache}; +use crate::cache::{self, Cache}; use crate::credentials::{Credentials, Key}; use crate::find::human_bytes; -use crate::output::Out; +use crate::output::{self, Out}; use crate::sources::SOURCES; use crate::{palette, paths}; @@ -100,9 +100,9 @@ fn gather(out: &Out) -> Result> { "{} files, {} of {}", usage.files, human_bytes(usage.bytes), - human_bytes(BUDGET_BYTES) + human_bytes(cache::budget_bytes()) ), - ok: usage.bytes <= BUDGET_BYTES, + ok: usage.bytes <= cache::budget_bytes(), }); Ok(checks) @@ -174,17 +174,25 @@ fn report(out: &Out, checks: &[Check]) -> Result<()> { )?; writeln!(w)?; let dim = palette::muted(); + // Two spaces, the mark, a space, the label column, a space. + let indent = 29; + let room = output::room(indent); for check in checks { let (mark, style): (&str, Style) = if check.ok { (good, palette::success()) } else { (bad, palette::warning()) }; + let mut detail = output::wrap(&check.detail, room).into_iter(); writeln!( w, " {style}{mark}{style:#} {:<24} {dim}{}{dim:#}", - check.label, check.detail + check.label, + detail.next().unwrap_or_default() )?; + for line in detail { + writeln!(w, "{:indent$}{dim}{line}{dim:#}", "")?; + } } writeln!(w)?; diff --git a/src/find.rs b/src/find.rs index 8d8077a..eb97496 100644 --- a/src/find.rs +++ b/src/find.rs @@ -88,13 +88,31 @@ pub fn run_search(request: &Request<'_>, out: &Out) -> Result<()> { return Err(Error::NoneSelected.into()); } - ui::stage(format!( - "searching {} source{} for \"{query}\"{}", - plan.sources.len(), - if plan.sources.len() == 1 { "" } else { "s" }, - if offline { ", offline" } else { "" } - )); - let progress = ui::bar(plan.sources.len() as u64, "sources"); + // A source without its required key is skipped before any request, so + // the line counts only the sources that will be asked. + let keyless = plan + .sources + .iter() + .filter(|s| s.missing_key(&services.creds).is_some()) + .count(); + let asked = plan.sources.len().saturating_sub(keyless); + if asked > 0 { + let need = if keyless == 1 { "needs" } else { "need" }; + let keys = if keyless > 0 { + format!( + "; {keyless} {need} a key, see `{} doctor`", + crate::invoked_name() + ) + } else { + String::new() + }; + ui::stage(format!( + "searching {} for \"{query}\"{}{keys}", + ui::count(asked, "source"), + if offline { ", offline" } else { "" } + )); + } + let progress = ui::bar(asked as u64, "sources"); let mut outcomes = run( &services, refresh, @@ -197,33 +215,47 @@ fn warn_failures(outcomes: &[Outcome]) { .filter(|o| matches!(o.status, Status::Failed(SourceError::Offline))) .count(); if skipped > 0 { - ui::warn(format!("{skipped} sources had nothing cached (--offline)")); + ui::warn(format!( + "{} had nothing cached (--offline)", + ui::count(skipped, "source") + )); } let catalogs: Vec<&str> = outcomes.iter().filter(downloading).map(|o| o.source.id).collect(); if !catalogs.is_empty() { - ui::warn(format!( - "{} were still downloading their catalogs; `dataseek cache warm` fetches them once", - catalogs.join(", ") - )); + ui::warn(still_downloading(&catalogs)); } } +fn still_downloading(ids: &[&str]) -> String { + let (verb, whose, them) = if ids.len() == 1 { + ("was", "its catalog", "it") + } else { + ("were", "their catalogs", "them") + }; + format!( + "{} {verb} still downloading {whose}; `dataseek cache warm` fetches {them} once", + ids.join(", ") + ) +} + /// The closing lines on stderr, after the results: what failed, then one /// line on how it went and how to see more. fn summarize(query: &str, shown: usize, found: usize, outcomes: &[Outcome]) { warn_failures(outcomes); let answered = outcomes.iter().filter(|o| o.status.answered()).count(); let attempted = outcomes.iter().filter(|o| o.status.attempted()).count(); - let sources = format!("{answered} of {attempted} sources answered"); + let sources = + format!("{answered} of {} answered", ui::count(attempted, "source")); if found == 0 { ui::warn(format!("no datasets matched \"{query}\"; {sources}")); } else if shown < found { ui::ok(format!( - "{shown} of {found} results; {sources}; -n {found} shows all" + "{shown} of {}; {sources}; -n {found} shows all", + ui::count(found, "result") )); } else { - ui::ok(format!("{found} results; {sources}")); + ui::ok(format!("{}; {sources}", ui::count(found, "result"))); } } @@ -308,7 +340,7 @@ fn print( writeln!(w, "{pad}{}", out.link(&d.url))?; writeln!(w, "{pad}{muted}{}{muted:#}", fit(&facts(hit), line))?; if let Some(text) = &d.description { - writeln!(w, "{pad}{}", fit(text, line))?; + writeln!(w, "{pad}{}", fit(text, output::prose_width(line)))?; } writeln!(w)?; } @@ -325,7 +357,7 @@ fn facts(hit: &Hit) -> String { parts.extend(d.size_bytes.map(human_bytes)); parts.extend(d.license.clone()); parts.extend(d.doi.as_ref().map(|doi| format!("doi:{doi}"))); - parts.join(" | ") + parts.join(" | ") } #[expect( @@ -361,6 +393,17 @@ mod tests { assert_eq!(human_bytes(2_559_248_010_229), "2.6 TB"); } + #[test] + fn the_downloading_warning_agrees_with_its_count() { + assert!( + still_downloading(&["openneuro"]) + .starts_with("openneuro was still downloading its catalog;") + ); + assert!(still_downloading(&["openneuro", "physionet"]).starts_with( + "openneuro, physionet were still downloading their catalogs;" + )); + } + fn failed_with(errors: Vec) -> Vec { SOURCES .iter() diff --git a/src/help.rs b/src/help.rs index fddddb7..69883c1 100644 --- a/src/help.rs +++ b/src/help.rs @@ -9,10 +9,10 @@ use std::io::Write; use anyhow::Result; use clap::builder::PossibleValuesParser; use clap::builder::StyledStr; -use clap::{Arg, ArgAction, CommandFactory}; +use clap::{Arg, ArgAction}; use serde_json::{Value, json}; -use crate::cli::{self, Cli}; +use crate::cli; use crate::credentials::Key; use crate::output::Out; use crate::palette; @@ -23,9 +23,9 @@ use crate::palette; const COMMANDS: [&str; 10] = [ "search", "sources", - "bench", "inspect", "mcp", + "bench", "cache", "doctor", "completion", @@ -35,33 +35,12 @@ const COMMANDS: [&str; 10] = [ const TOPICS: [&str; 2] = ["environment", "exit-codes"]; -/// The overview's groups: the name to type and a few words on what it does. -const GROUPS: [(&str, &[(&str, &str)]); 3] = [ - ( - "search", - &[ - ("search, s", "search every source at once"), - ("sources", "list sources and their keys"), - ("inspect", "read a dataset page's metadata and files"), - ("bench", "time and compare sources"), - ("mcp", "serve search, sources and inspect over MCP"), - ], - ), - ( - "upkeep", - &[ - ("cache", "show, warm or clear the cache"), - ("doctor", "check keys, paths and cache"), - ], - ), - ( - "shell", - &[ - ("completion", "print a completion script"), - ("man", "print the man page"), - ("help", "explain a command or topic"), - ], - ), +/// The overview's groups. What each command does comes from its `about`, the +/// line `-h` shows, so the two cannot drift. +const GROUPS: [(&str, &[&str]); 3] = [ + ("Search", &["search", "sources", "inspect", "mcp"]), + ("Upkeep", &["bench", "cache", "doctor"]), + ("Shell", &["completion", "help"]), ]; /// Every code the binary returns. `help exit-codes`, `help --json` and the @@ -95,18 +74,28 @@ pub fn overview(out: &Out) -> Result<()> { env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION") )?; + let cmd = cli::command(); for (group, commands) in GROUPS { writeln!(w)?; - writeln!(w, "{head}{group}{head:#}")?; - for (command, about) in commands { - writeln!(w, " {name}{command:<11}{name:#} {about}")?; + writeln!(w, "{head}{group}:{head:#}")?; + for sub in commands.iter().filter_map(|c| cmd.find_subcommand(c)) { + let typed = std::iter::once(sub.get_name()) + .chain(sub.get_visible_aliases()) + .collect::>() + .join(", "); + let about = sub.get_about().map(ToString::to_string); + writeln!( + w, + " {name}{typed:<11}{name:#} {}", + about.unwrap_or_default() + )?; } } writeln!(w)?; + let bin = crate::invoked_name(); writeln!( w, - "{muted}run {} -h for full usage{muted:#}", - crate::invoked_name() + "{muted}run {bin} -h for a summary, {bin} --help for everything{muted:#}" )?; Ok(()) } @@ -131,8 +120,15 @@ pub fn run(topic: Option<&str>, out: &Out) -> Result<()> { Some("environment") => { let vars = environment(); let width = vars.keys().map(String::len).max().unwrap_or(0); + let indent = width.saturating_add(4); + let room = crate::output::room(indent); for (var, meaning) in &vars { - writeln!(w, " {var: { @@ -153,11 +149,106 @@ pub fn run(topic: Option<&str>, out: &Out) -> Result<()> { /// The command, built so subcommand usage lines carry the invoked name. fn built() -> clap::Command { - let mut cmd = Cli::command().bin_name(crate::invoked_name()); + let mut cmd = cli::command().bin_name(crate::invoked_name()); cmd.build(); cmd } +/// Where `name completion ` should go so the shell loads it, said +/// instead of printing the script to a terminal. +pub fn completion_hint(shell: clap_complete::Shell, name: &str) -> String { + use clap_complete::Shell; + + let save = match shell { + Shell::Bash => { + format!("> ~/.local/share/bash-completion/completions/{name}") + } + Shell::Fish => format!("> ~/.config/fish/completions/{name}.fish"), + Shell::Zsh => format!( + "> ~/.zfunc/_{name} (with ~/.zfunc on $fpath before compinit)" + ), + Shell::Elvish => ">> ~/.config/elvish/rc.elv".to_owned(), + Shell::PowerShell => ">> $PROFILE".to_owned(), + _ => format!("> a file {shell} loads at startup"), + }; + format!( + "the script is for a file, not the terminal; save it with: \ + {name} completion {shell} {save}" + ) +} + +/// Show `page` through `man`, as a reader on a terminal expects. `man` takes a +/// file path everywhere (BSD and macOS `man` have no `-l`), so the page goes +/// through a temporary file: a random name, created only if absent and +/// readable by this user alone, so a link planted in a shared temp directory +/// cannot redirect the write, and gone when the guard drops. False when `man` +/// is missing or fails, so the caller prints the roff instead. +pub fn show_man(page: &[u8]) -> bool { + let Ok(mut file) = + tempfile::Builder::new().prefix("dataseek-").suffix(".1").tempfile() + else { + return false; + }; + file.write_all(page).is_ok() + && file.flush().is_ok() + && std::process::Command::new("man") + .arg(file.path()) + .status() + .is_ok_and(|status| status.success()) +} + +/// The man page, in roff. clap_mangen draws the flags and commands from the +/// plain definition, because roff would run together the value lists that +/// `cli::command()` writes into the long help. Two fixes on top: +/// +/// - A flag hidden from `-h` has no long help of its own, and clap_mangen +/// would print it with no description, so its help becomes its long help. +/// - The examples, exit codes and bug address that `--help` closes with +/// become EXAMPLES, EXIT STATUS and REPORTING BUGS instead of one EXTRA +/// section, from the same examples and from [`EXIT_CODES`]. +pub fn man_page() -> std::io::Result> { + use clap::CommandFactory; + + let cmd = cli::Cli::command() + .after_help(None::<&'static str>) + .after_long_help(None::<&'static str>) + .mut_args(|arg| match arg.get_help().cloned() { + Some(help) + if arg.is_hide_short_help_set() + && arg.get_long_help().is_none() => + { + arg.long_help(help) + } + _ => arg, + }); + let mut rendered = Vec::new(); + clap_mangen::Man::new(cmd).render(&mut rendered)?; + let mut page = String::from_utf8_lossy(&rendered).into_owned(); + let closing = closing_sections(); + match page.find(".SH VERSION") { + Some(at) => page.insert_str(at, &closing), + None => page.push_str(&closing), + } + Ok(page.into_bytes()) +} + +fn closing_sections() -> String { + use std::fmt::Write as _; + + let roff = |text: &str| text.replace('\\', "\\e").replace('-', "\\-"); + let mut page = String::from(".SH EXAMPLES\n.nf\n"); + for line in cli::examples!().lines().skip(1) { + let _ = writeln!(page, "{}", roff(line)); + } + page.push_str(".fi\n.SH \"EXIT STATUS\"\n"); + for (code, meaning) in EXIT_CODES { + let _ = writeln!(page, ".TP\n\\fB{code}\\fR\n{}", roff(meaning)); + } + let issues = concat!(env!("CARGO_PKG_REPOSITORY"), "/issues"); + let _ = writeln!(page, ".SH \"REPORTING BUGS\"\n{}", roff(issues)); + page +} + /// clap's styled help as ANSI text; the stream decides whether it stays. fn ansi(help: &StyledStr) -> String { help.ansi().to_string() @@ -167,7 +258,7 @@ fn ansi(help: &StyledStr) -> String { /// come from the flag definitions, the keys from the key registry. fn environment() -> BTreeMap { let mut vars = BTreeMap::new(); - let mut commands = vec![Cli::command()]; + let mut commands = vec![cli::command()]; while let Some(cmd) = commands.pop() { for arg in cmd.get_arguments() { if let (Some(env), Some(long)) = (arg.get_env(), arg.get_long()) { @@ -186,6 +277,11 @@ fn environment() -> BTreeMap { format!("API key, get one at {}", key.signup()), ); } + vars.insert( + crate::cache::BUDGET_VAR.to_owned(), + "cache size budget in whole megabytes, 1 to 10000; 30 by default" + .to_owned(), + ); for (var, meaning) in [ ("KAGGLE_CONFIG_DIR", "where the Kaggle CLI keeps its token"), ("NO_COLOR", "any non-empty value turns color off"), @@ -244,7 +340,7 @@ fn surface() -> Value { "schema": "dataseek-surface/1", "name": env!("CARGO_PKG_NAME"), "version": env!("CARGO_PKG_VERSION"), - "command": command_json(&Cli::command()), + "command": command_json(&cli::command()), "environment": variables(), "exit_codes": codes(), }) @@ -253,7 +349,7 @@ fn surface() -> Value { /// One command as `help --json` describes it; `mcp` builds its /// tool schemas from the same object. pub fn subcommand_json(name: &str) -> Option { - Cli::command().find_subcommand(name).map(command_json) + cli::command().find_subcommand(name).map(command_json) } fn command_json(cmd: &clap::Command) -> Value { @@ -266,10 +362,7 @@ fn command_json(cmd: &clap::Command) -> Value { .filter(|a| !a.is_hide_set()) .map(arg_json) .collect::>(), - "commands": cmd - .get_subcommands() - .filter(|c| !c.is_hide_set()) - .map(command_json) + "commands": cmd.get_subcommands().map(command_json) .collect::>(), }) } @@ -342,10 +435,12 @@ fn bounds(arg: &Arg) -> (Value, Value) { mod tests { use clap::Parser; + use crate::cli::Cli; + use super::*; fn subcommands() -> Vec { - Cli::command() + cli::command() .get_subcommands() .map(|c| c.get_name().to_owned()) .collect() @@ -358,15 +453,18 @@ mod tests { // A command missing from the overview is a command nobody finds. #[test] - fn the_overview_shows_every_command() { + fn the_overview_shows_every_command_in_help_order() { let shown: Vec<&str> = GROUPS .iter() - .flat_map(|(_, commands)| commands.iter()) - .map(|(name, _)| name.split(',').next().unwrap_or(name)) + .flat_map(|(_, commands)| commands.iter().copied()) .collect(); - for command in subcommands() { - assert!(shown.contains(&command.as_str()), "{command} missing"); - } + let cmd = cli::command(); + let listed: Vec<&str> = cmd + .get_subcommands() + .filter(|c| !c.is_hide_set()) + .map(clap::Command::get_name) + .collect(); + assert_eq!(shown, listed); } #[test] @@ -391,7 +489,7 @@ mod tests { // just past them; one with no bound published takes 0, or 65535. #[test] fn published_bounds_are_the_ones_clap_enforces() { - let root = command_json(&Cli::command()); + let root = command_json(&cli::command()); let leaves = root["commands"] .as_array() .unwrap() diff --git a/src/http.rs b/src/http.rs index 8e7f206..668b2e8 100644 --- a/src/http.rs +++ b/src/http.rs @@ -1,15 +1,16 @@ //! The one blocking HTTP client every source shares, and the failure taxonomy //! the search loop acts on. //! -//! Every request identifies dataseek and its contact address in the -//! User-Agent, which is what DataCite, NCBI and other polite pools key their -//! better rate tier on. Non-2xx statuses come back as values, not errors, so -//! [`SourceError`] can say whether a failure is worth remembering (a dead -//! host) or only this query's problem (a rejected key). A single 429 is -//! retried once when the server asks for a short wait; longer waits are -//! reported instead of slept through, and a failed connect is retried once. -//! Bodies are decoded leniently: a stray invalid byte in a 30 MB catalog -//! should cost one character, not the source. +//! Every request identifies dataseek, its repository and its contact +//! address in the User-Agent, which is what DataCite, NCBI and other polite +//! pools key their better rate tier on. Non-2xx statuses come back as +//! values, not errors, so [`SourceError`] can say whether a failure is worth +//! remembering (a dead or throttling host) or only this query's problem (a +//! rejected key). +//! A single 429 is retried once when the server asks for a short wait; +//! longer waits are reported instead of slept through, and a failed connect +//! is retried once. Bodies are decoded leniently: a stray invalid byte in a +//! 30 MB catalog should cost one character, not the source. use std::ffi::OsStr; use std::path::Path; @@ -79,14 +80,19 @@ pub enum SourceError { } impl SourceError { - /// Failures that say the host is down rather than this query being bad. - /// The search loop skips such a source for a few minutes afterwards. + /// Failures that say the host is down, or wants no more requests for now, + /// rather than this query being bad. The search loop skips such a source + /// for a few minutes afterwards, so a throttled host is not asked again + /// on every search (OSF's `/trove/` answered 17 requests in 3 minutes + /// with an hour of 429s, October 2026). pub fn is_outage(&self) -> bool { match self { - Self::Unreachable(_) | Self::Timeout | Self::Blocked => true, + Self::Unreachable(_) + | Self::Timeout + | Self::Blocked + | Self::RateLimited => true, Self::Status(code) => *code >= 500, - Self::RateLimited - | Self::Certificate(_) + Self::Certificate(_) | Self::Unauthorized(_) | Self::Shape(_) | Self::ConnectLimit(_) @@ -95,10 +101,17 @@ impl SourceError { } pub fn shape(what: impl Into) -> Self { - Self::Shape(what.into()) + Self::Shape(terminal_safe(what.into())) } } +/// Error text that came from upstream, with its control characters +/// replaced: a provider that puts an escape sequence into a tag name or a +/// header must not get to drive the terminal the error is printed on. +fn terminal_safe(upstream: impl std::fmt::Display) -> String { + crate::record::printable(&upstream.to_string()).collect() +} + pub struct Http { agent: ureq::Agent, } @@ -108,8 +121,9 @@ impl Http { let agent = ureq::Agent::config_builder() .http_status_as_error(false) .user_agent(format!( - "dataseek/{} (mailto:{CONTACT})", - env!("CARGO_PKG_VERSION") + "dataseek/{} (+{}; mailto:{CONTACT})", + env!("CARGO_PKG_VERSION"), + env!("CARGO_PKG_REPOSITORY") )) .timeout_global(Some(Duration::from_secs(20))) .timeout_connect(Some(Duration::from_secs( @@ -318,12 +332,14 @@ fn transport(error: &ureq::Error) -> SourceError { } ureq::Error::Timeout(_) => SourceError::Timeout, #[cfg(not(any(windows, target_os = "macos")))] - ureq::Error::Rustls(_) => SourceError::Certificate(error.to_string()), + ureq::Error::Rustls(_) => { + SourceError::Certificate(terminal_safe(error)) + } #[cfg(not(any(windows, target_os = "macos")))] ureq::Error::Io(io) if refused_certificate(io) => { - SourceError::Certificate(error.to_string()) + SourceError::Certificate(terminal_safe(error)) } - other => SourceError::Unreachable(other.to_string()), + other => SourceError::Unreachable(terminal_safe(other)), } } @@ -407,7 +423,7 @@ mod tests { (SourceError::Status(500), true), (SourceError::Status(404), false), (SourceError::Unauthorized(401), false), - (SourceError::RateLimited, false), + (SourceError::RateLimited, true), (SourceError::shape("no hits"), false), ] { assert_eq!(error.is_outage(), outage, "{error:?}"); @@ -631,8 +647,9 @@ mod tests { assert!(head.starts_with("get /search?q=sea"), "{head}"); assert!( head.contains(&format!( - "user-agent: dataseek/{} (mailto:{CONTACT})", - env!("CARGO_PKG_VERSION") + "user-agent: dataseek/{} (+{}; mailto:{CONTACT})", + env!("CARGO_PKG_VERSION"), + env!("CARGO_PKG_REPOSITORY") )), "{head}" ); diff --git a/src/inspect.rs b/src/inspect.rs index 076d3f7..972b02a 100644 --- a/src/inspect.rs +++ b/src/inspect.rs @@ -18,7 +18,7 @@ use serde_json::Value; use crate::find::human_bytes; use crate::http::{Http, SourceError}; -use crate::output::Out; +use crate::output::{self, Out}; use crate::record::{clean, number, scrub_controls, summary, text}; use crate::ui; @@ -373,13 +373,22 @@ fn print(out: &Out, url: &str, page: &Page, files: &[File]) -> Result<()> { "files": files, })); } + let room = output::room(LABEL); let field = |label: &str, value: Option| -> std::io::Result<()> { - match value { - Some(v) if !v.is_empty() => { - writeln!(out.stdout(), "{label:<12} {v}") - } - _ => Ok(()), + let Some(value) = value.filter(|v| !v.is_empty()) else { + return Ok(()); + }; + let width = if label == "description" { + output::prose_width(room) + } else { + room + }; + let mut w = out.stdout(); + for (i, line) in output::wrap(&value, width).iter().enumerate() { + let label = if i == 0 { label } else { "" }; + writeln!(w, "{label:<12} {line}")?; } + Ok(()) }; field("name", page.text("name"))?; field("url", page.text("url").map(|u| out.link(&u)))?; @@ -397,15 +406,97 @@ fn print(out: &Out, url: &str, page: &Page, files: &[File]) -> Result<()> { page.text("description").as_deref().and_then(summary), )?; let mut w = out.stdout(); - for (i, file) in files.iter().enumerate() { + let lines = match output::width() { + Some(width) if !files.is_empty() => { + file_block(files, width, |url| out.link(url)) + } + _ => files.iter().map(|file| listing(out, file)).collect(), + }; + for (i, line) in lines.iter().enumerate() { let label = if i == 0 { "files" } else { "" }; - writeln!(w, "{label:<12} {}", listing(out, file))?; + writeln!(w, "{label:<12} {line}")?; } Ok(()) } -/// One file on one line: name, format, size, checksum and pattern, whichever -/// are known, then the link. +/// Columns the field labels take, the space after them included. +const LABEL: usize = 13; + +/// The file list on a terminal: a count and total size, then per file its +/// name, size and format on one line and its link and checksum indented +/// under it. When the name, size and format columns do not fit beside each +/// other, size and format move to a line of their own. +fn file_block( + files: &[File], + width: usize, + link: impl Fn(&str) -> String, +) -> Vec { + let size = |f: &File| { + f.size_bytes.map(human_bytes).or_else(|| f.size_text.clone()) + }; + let name = |f: &File| f.name.clone().unwrap_or_else(|| "-".to_owned()); + let longest = |text: &dyn Fn(&File) -> String| { + files.iter().map(|f| text(f).chars().count()).max().unwrap_or(0) + }; + let name_w = longest(&name); + let size_w = longest(&|f| size(f).unwrap_or_default()); + let kind_w = longest(&|f| f.format.clone().unwrap_or_default()); + let side_by_side = LABEL + .saturating_add(name_w) + .saturating_add(size_w) + .saturating_add(kind_w) + .saturating_add(4) + <= width; + + let mut lines = vec![total(files)]; + for file in files { + let facts = [ + size(file).map(|s| format!("{s:>size_w$}")), + file.format.clone(), + file.includes.clone(), + ] + .into_iter() + .flatten() + .collect::>() + .join(" "); + if side_by_side { + lines.push( + format!("{:>() + .join(" "); + if !under.is_empty() { + lines.push(format!(" {under}")); + } + } + lines +} + +/// `7 files, 3.5 GB`; when only some files give a size, which ones count. +fn total(files: &[File]) -> String { + let count = ui::count(files.len(), "file"); + let sized: Vec = files.iter().filter_map(|f| f.size_bytes).collect(); + let bytes = sized.iter().fold(0_u64, |sum, b| sum.saturating_add(*b)); + match sized.len() { + 0 => count, + n if n == files.len() => format!("{count}, {}", human_bytes(bytes)), + n => format!("{count}, {} in the {n} with a size", human_bytes(bytes)), + } +} + +/// One file on one line, for a pipe: name, format, size, checksum and +/// pattern, whichever are known, then the link. fn listing(out: &Out, file: &File) -> String { [ file.name.clone(), @@ -677,4 +768,65 @@ mod tests { let file = json!({"sha256": "main", "md5": "z".repeat(32)}); assert_eq!(checksum(&file), None); } + + fn two_files() -> Vec { + vec![ + File { + name: Some("rain.csv".to_owned()), + format: Some("text/csv".to_owned()), + size_bytes: Some(2_000_000), + checksum: Some("md5:00ff".to_owned()), + url: Some("https://example.org/rain.csv".to_owned()), + ..File::default() + }, + File { + name: Some("stations.parquet".to_owned()), + size_bytes: Some(512), + url: Some("https://example.org/stations.parquet".to_owned()), + ..File::default() + }, + ] + } + + #[test] + fn a_wide_terminal_puts_size_and_format_beside_the_name() { + let lines = file_block(&two_files(), 80, str::to_owned); + assert_eq!( + lines, + [ + "2 files, 2.0 MB", + "rain.csv 2.0 MB text/csv", + " https://example.org/rain.csv md5:00ff", + "stations.parquet 512 B", + " https://example.org/stations.parquet", + ] + ); + } + + #[test] + fn a_narrow_terminal_puts_size_and_format_under_the_name() { + let lines = file_block(&two_files(), 40, str::to_owned); + assert_eq!( + lines, + [ + "2 files, 2.0 MB", + "rain.csv", + " 2.0 MB text/csv", + " https://example.org/rain.csv md5:00ff", + "stations.parquet", + " 512 B", + " https://example.org/stations.parquet", + ] + ); + } + + #[test] + fn the_total_says_which_files_it_counts() { + let mut files = two_files(); + assert_eq!(total(&files), "2 files, 2.0 MB"); + files[1].size_bytes = None; + assert_eq!(total(&files), "2 files, 2.0 MB in the 1 with a size"); + files[0].size_bytes = None; + assert_eq!(total(&files), "2 files"); + } } diff --git a/src/lib.rs b/src/lib.rs index 07cfab7..29c7a21 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -43,7 +43,9 @@ mod sources; mod ui; /// What `benches/search.rs` measures and `examples/relevance/` scores. Not -/// an API: it follows the code it points at. +/// an API: it follows the code it points at. The feature is visible to +/// anyone who depends on the crate, but it is unstable, outside semver, and +/// may change or disappear in any release. #[cfg(feature = "internals")] #[doc(hidden)] pub mod internals { @@ -59,7 +61,7 @@ pub mod internals { } use std::ffi::OsString; -use std::io::{self, Write}; +use std::io::{self, IsTerminal, Write}; use std::process::ExitCode; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; @@ -68,7 +70,7 @@ use std::time::Duration; use clap::error::ErrorKind::{ DisplayHelp, DisplayHelpOnMissingArgumentOrSubcommand, DisplayVersion, }; -use clap::{CommandFactory, FromArgMatches, ValueEnum}; +use clap::{FromArgMatches, ValueEnum}; use cli::{Cli, ColorChoice, Command}; use output::Out; @@ -102,7 +104,7 @@ pub fn main() -> ExitCode { let args: Vec = std::env::args_os().collect(); let early = Early::scan(&args); - let parsed = Cli::command() + let parsed = cli::command() .color(early.color) .try_get_matches_from(&args) .and_then(|matches| Cli::from_arg_matches(&matches)); @@ -116,6 +118,11 @@ pub fn main() -> ExitCode { } let out = Out::resolve(&cli); ui::init(&out); + if let Err(message) = cache::read_budget() { + let err = + clap::Error::raw(clap::error::ErrorKind::ValueValidation, message); + return usage(&err, &early); + } paths::relocate_cache(cli.cache_dir.clone()); http::connect_within(Duration::from_secs(cli.connect_timeout)); @@ -272,8 +279,13 @@ fn run(cli: Cli, out: &Out) -> anyhow::Result<()> { Command::Doctor => doctor::run(out)?, // clap_complete::generate panics on a failed write. Generating into a // Vec cannot fail, so the real write goes through the error path. + // A script on a terminal is a wall of text nobody reads; what the + // reader needs there is where to save it. + Command::Completion { shell } if io::stdout().is_terminal() => { + ui::stage(help::completion_hint(shell, invoked_name())); + } Command::Completion { shell } => { - let mut cmd = Cli::command(); + let mut cmd = cli::command(); let mut script = Vec::new(); clap_complete::generate( shell, @@ -285,9 +297,10 @@ fn run(cli: Cli, out: &Out) -> anyhow::Result<()> { } // Rendered on demand so the page cannot drift from the flags. Command::Man => { - let mut page = Vec::new(); - clap_mangen::Man::new(Cli::command()).render(&mut page)?; - out.stdout().write_all(&page)?; + let page = help::man_page()?; + if !(io::stdout().is_terminal() && help::show_man(&page)) { + out.stdout().write_all(&page)?; + } } Command::Help { topic } => help::run(topic.as_deref(), out)?, } diff --git a/src/listing.rs b/src/listing.rs index 6c76262..6841b59 100644 --- a/src/listing.rs +++ b/src/listing.rs @@ -7,7 +7,7 @@ use anyhow::Result; use serde::Serialize; use crate::credentials::Credentials; -use crate::output::Out; +use crate::output::{self, Out}; use crate::palette; use crate::sources::{Need, SOURCES}; @@ -24,6 +24,8 @@ struct Row { docs: &'static str, /// Why the source is asked only when `--source` names it. opt_in: Option<&'static str>, + /// The notice the source's terms ask dataseek to show. + notice: Option<&'static str>, } pub fn run(out: &Out) -> Result<()> { @@ -46,6 +48,7 @@ pub fn run(out: &Out) -> Result<()> { key_env: s.key.map(|(key, _)| key.env_var()), docs: s.docs, opt_in: s.opt_in, + notice: s.notice, }) .collect(); @@ -72,14 +75,37 @@ pub fn run(out: &Out) -> Result<()> { } return Ok(()); } + table(&mut w, &rows)?; + writeln!(w)?; + // A note that wraps continues two columns in, so each note still + // starts at the margin. + let muted = palette::muted(); + let room = output::width().map(|w| w.saturating_sub(2).max(20)); + for note in notes(&rows) { + for (i, line) in output::wrap(¬e, room).iter().enumerate() { + let indent = if i == 0 { "" } else { " " }; + writeln!(w, "{muted}{indent}{line}{muted:#}")?; + } + } + Ok(()) +} + +fn table(w: &mut impl Write, rows: &[Row]) -> Result<()> { let (head, muted, warn) = (palette::accent(), palette::muted(), palette::warning()); + let column = |title: &str, value: &dyn Fn(&Row) -> usize| { + rows.iter().map(value).max().unwrap_or(0).max(title.len()) + }; + let id = column("id", &|r| r.id.len()); + let category = column("category", &|r| r.category.len()); + let protocol = column("protocol", &|r| r.protocol.len()); + let search = column("search", &|r| r.search.len()); writeln!( w, - "{head}{:<22} {:<22} {:<22} {:<6} key{head:#}", + "{head}{: format!("{warn}missing ${var}{warn:#}"), ("optional", Some(var)) => { @@ -91,24 +117,27 @@ pub fn run(out: &Out) -> Result<()> { }; writeln!( w, - "{:<22} {:<22} {:<22} {:<6} {key}", + "{: Vec { + let mut notes = vec![format!( + "{} sources. `local` ones download their catalog once a week and search it on disk.", + rows.len() + )]; + notes.extend(rows.iter().filter_map(|r| { + r.opt_in.map(|reason| { + format!("{} is asked only when named with -s: {reason}.", r.id) + }) + })); + notes.extend( + rows.iter().filter_map(|r| { + r.notice.map(|notice| format!("{}: {notice}", r.id)) + }), + ); + notes +} diff --git a/src/output.rs b/src/output.rs index 953810d..9a85edc 100644 --- a/src/output.rs +++ b/src/output.rs @@ -149,6 +149,13 @@ fn stream(raw: S, color: ColorChoice) -> AutoStream { } } +/// The columns a description may use, given the room left on the line: held +/// between 40 and 80, so a wide terminal still reads as prose and a narrow +/// one still shows a sentence. +pub fn prose_width(room: Option) -> Option { + room.map(|w| w.clamp(40, 80)) +} + /// `text` cut to `width` columns with an ellipsis, counting chars. Wide /// glyphs make a line slightly long, never wrong. pub fn fit(text: &str, width: Option) -> String { @@ -162,9 +169,56 @@ pub fn fit(text: &str, width: Option) -> String { } } +/// `text` broken at spaces into lines of at most `width` columns, counting +/// chars like [`fit`]; a word longer than a line gets one to itself. Without +/// a width, which means stdout is not a terminal, it stays one line. +pub fn wrap(text: &str, width: Option) -> Vec { + let Some(width) = width else { return vec![text.to_owned()] }; + let mut lines = Vec::new(); + let mut line = String::new(); + for word in text.split_whitespace() { + let longer = line + .chars() + .count() + .saturating_add(1) + .saturating_add(word.chars().count()); + if !line.is_empty() && longer > width { + lines.push(std::mem::take(&mut line)); + } + if !line.is_empty() { + line.push(' '); + } + line.push_str(word); + } + if !line.is_empty() || lines.is_empty() { + lines.push(line); + } + lines +} + +/// The room a value has after a column of `indent`, on a terminal. +pub fn room(indent: usize) -> Option { + width().map(|w| w.saturating_sub(indent).max(20)) +} + #[cfg(test)] mod tests { use super::*; + + #[test] + fn wrap_breaks_at_spaces_and_keeps_long_words_whole() { + let text = "seconds a host gets to accept the connection"; + assert_eq!( + wrap(text, Some(16)), + ["seconds a host", "gets to accept", "the connection"] + ); + assert_eq!( + wrap("https://example.org/a/long/path x", Some(8)), + ["https://example.org/a/long/path", "x"] + ); + assert_eq!(wrap(text, None), [text]); + assert_eq!(wrap("", Some(10)), [""]); + } use crate::cli::Command; // Flag resolution is the pure logic; the rest of output needs a real @@ -180,7 +234,6 @@ mod tests { no_progress: false, cache_dir: None, connect_timeout: 10, - jq: None, command: Some(Command::Doctor), }; build(&mut cli); @@ -227,4 +280,12 @@ mod tests { assert_eq!(fit("a long title here", Some(8)), "a long\u{2026}"); assert_eq!(fit("a long title here", None), "a long title here"); } + + #[test] + fn descriptions_stay_between_forty_and_eighty_columns() { + assert_eq!(prose_width(Some(30)), Some(40)); + assert_eq!(prose_width(Some(57)), Some(57)); + assert_eq!(prose_width(Some(117)), Some(80)); + assert_eq!(prose_width(None), None); + } } diff --git a/src/record.rs b/src/record.rs index 6a22ae7..4c84ab3 100644 --- a/src/record.rs +++ b/src/record.rs @@ -358,7 +358,7 @@ pub fn localized(value: Option<&Value>) -> Option { /// Every control character (ESC, CSI, OSC, C1) replaced by a space and /// every [`invisible`] one dropped. -fn printable(text: &str) -> impl Iterator + '_ { +pub fn printable(text: &str) -> impl Iterator + '_ { without_controls(text).filter(|&c| !invisible(c)) } diff --git a/src/search.rs b/src/search.rs index c856811..c8c490f 100644 --- a/src/search.rs +++ b/src/search.rs @@ -96,7 +96,9 @@ pub fn run( ); std::thread::spawn(move || { let outcome = one(&services.ctx(refresh), &plan, source); - progress.inc(1); + if !matches!(outcome.status, Status::NeedsKey(_)) { + progress.inc(1); + } let _ = sender.send((index, outcome)); }); } @@ -256,6 +258,7 @@ mod tests { key: None, persist: true, opt_in: None, + notice: None, adapter: Adapter::Live(run), } } diff --git a/src/sources.rs b/src/sources.rs index 2feb6b1..ecfb0c3 100644 --- a/src/sources.rs +++ b/src/sources.rs @@ -171,6 +171,8 @@ pub struct Source { pub persist: bool, /// Why this source is asked only when `--source` names it. pub opt_in: Option<&'static str>, + /// The notice its terms ask every application that uses it to show. + pub notice: Option<&'static str>, pub adapter: Adapter, } @@ -356,6 +358,7 @@ const fn live( key: None, persist: true, opt_in: None, + notice: None, adapter: Adapter::Live(run), } } @@ -377,6 +380,7 @@ const fn listed( key: None, persist: true, opt_in: None, + notice: None, adapter: Adapter::Catalog(list), } } @@ -391,6 +395,11 @@ const fn opt_in(mut source: Source, reason: &'static str) -> Source { source } +const fn notice(mut source: Source, text: &'static str) -> Source { + source.notice = Some(text); + source +} + const fn via( id: &'static str, name: &'static str, @@ -408,6 +417,7 @@ const fn via( key: None, persist: true, opt_in: None, + notice: None, adapter, } } @@ -850,17 +860,23 @@ pub static SOURCES: &[Source] = &[ "https://docs.owid.io/projects/etl/api/search-api/", owid::search, ), - keyed( - live( - "fred", - "FRED", - Finance, - "FRED API", - "https://fred.stlouisfed.org/docs/api/fred/series_search.html", - fred::search, + notice( + keyed( + live( + "fred", + "FRED", + Finance, + "FRED API", + "https://fred.stlouisfed.org/docs/api/fred/series_search.html", + fred::search, + ), + Key::Fred, + Need::Required, ), - Key::Fred, - Need::Required, + "This product uses the FRED\u{ae} API but is not endorsed or \ + certified by the Federal Reserve Bank of St. Louis. Using it means \ + agreeing to the FRED\u{ae} API Terms of Use: \ + https://fred.stlouisfed.org/docs/api/terms_of_use.html", ), via( "bundesbank", @@ -878,13 +894,17 @@ pub static SOURCES: &[Source] = &[ "https://fiscaldata.treasury.gov/api-documentation/", fiscal::list, ), - listed( - "census", - "U.S. Census Bureau API", - Statistics, - "DCAT data.json, listed", - "https://census.gov/data/developers/updates/new-discovery-tool.html", - census::list, + notice( + listed( + "census", + "U.S. Census Bureau API", + Statistics, + "DCAT data.json, listed", + "https://census.gov/data/developers/updates/new-discovery-tool.html", + census::list, + ), + "This product uses the Census Bureau Data API but is not endorsed or \ + certified by the Census Bureau.", ), listed( "who", diff --git a/src/sources/sdmx.rs b/src/sources/sdmx.rs index 5844487..6b27d06 100644 --- a/src/sources/sdmx.rs +++ b/src/sources/sdmx.rs @@ -350,6 +350,14 @@ mod tests { assert!(flows("").is_err()); } + #[test] + fn an_escape_sequence_in_a_tag_name_never_reaches_the_error() { + let hostile = ""; + let error = flows(hostile).err().unwrap().to_string(); + assert!(error.contains("]52;c;"), "{error}"); + assert!(!error.chars().any(char::is_control), "{error:?}"); + } + #[test] fn dataflows_map_from_a_recorded_list() { let datasets = parse(&ECB, &fixture::text("sdmx.xml")).unwrap(); diff --git a/src/ui.rs b/src/ui.rs index 66683c3..23a5e73 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -125,6 +125,11 @@ pub fn warn(msg: impl Display) { say("warning", " ", &paint(palette::warning(), mark), msg); } +/// `1 source`, `3 sources`: a count with its noun in agreement. +pub fn count(n: usize, noun: &str) -> String { + if n == 1 { format!("1 {noun}") } else { format!("{n} {noun}s") } +} + /// A spinner for work of unknown length. Without a live terminal the message /// becomes a stage line instead, so the wait is still announced. pub fn spinner(msg: impl Into) -> ProgressBar { @@ -223,4 +228,11 @@ mod tests { ProgressStyle::with_template(&bar_template()).unwrap(); } } + + #[test] + fn counts_agree_with_their_noun() { + assert_eq!(count(0, "source"), "0 sources"); + assert_eq!(count(1, "source"), "1 source"); + assert_eq!(count(2, "catalog"), "2 catalogs"); + } } diff --git a/tests/cli.rs b/tests/cli.rs index a47021c..e66d656 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -30,13 +30,14 @@ const KEY_VARS: [&str; 8] = [ "NCBI_API_KEY", ]; -const OWN_VARS: [&str; 6] = [ +const OWN_VARS: [&str; 7] = [ "DATASEEK_EXCLUDE", "DATASEEK_PER_SOURCE", "DATASEEK_LIMIT", "DATASEEK_TIMEOUT", "DATASEEK_CACHE_DIR", "DATASEEK_CONNECT_TIMEOUT", + "DATASEEK_CACHE_MAX_MB", ]; struct Sandbox { @@ -157,10 +158,12 @@ fn naked_invocation_prints_the_overview_on_stdout() { "\u{25c6} dataseek v{}", env!("CARGO_PKG_VERSION") ))); - for group in ["search\n", "upkeep\n", "shell\n"] { + for group in ["\nSearch:\n", "\nUpkeep:\n", "\nShell:\n"] { assert!(text.contains(group), "{group} missing:\n{text}"); } - assert!(text.ends_with("run dataseek -h for full usage\n"), "{text}"); + let footer = + "run dataseek -h for a summary, dataseek --help for everything\n"; + assert!(text.ends_with(footer), "{text}"); assert!(text.lines().count() <= 24, "{text}"); } @@ -169,7 +172,8 @@ fn the_overview_names_the_program_that_ran() { let out = bin_named("dsk").arg("--no-color").output().unwrap(); assert!(out.status.success()); let text = String::from_utf8(out.stdout).unwrap(); - assert!(text.ends_with("run dsk -h for full usage\n"), "{text}"); + let footer = "run dsk -h for a summary, dsk --help for everything\n"; + assert!(text.ends_with(footer), "{text}"); } #[test] @@ -374,19 +378,16 @@ fn errors_under_json_are_events_on_stderr() { assert_eq!(event["causes"], json!(["..."])); } -// A script written for --jq must fail as a usage error that names the -// replacement, never run a search with "--jq" swallowed into the query. +// A script written for the old --jq must fail as a usage error, never run a +// search with "--jq" swallowed into the query. #[test] -fn the_removed_jq_flag_points_at_json_and_jq() { +fn an_unknown_flag_is_never_read_as_query_words() { let out = bin() .args(["search", "census", "--jq", ".results[].url", "--offline"]) .output() .unwrap(); assert_eq!(out.status.code(), Some(2)); assert_eq!(out.stdout, b""); - let stderr = String::from_utf8(out.stderr).unwrap(); - assert!(stderr.contains("pipe --json into jq"), "{stderr}"); - assert!(!stderr.contains("-- --jq"), "{stderr}"); let out = bin() .args(["--json", "sources", "--jq", ".sources"]) @@ -421,6 +422,23 @@ fn sources_without_their_required_key_are_skipped_not_failed() { assert!(stderr.contains("dataseek sources"), "{stderr}"); } +// A source without its key is never asked, so the opening line does not +// count it, and says how many were left out. +#[test] +fn the_searching_line_counts_only_sources_that_will_be_asked() { + let mut cmd = bin(); + seed_rainfall(&cmd.cache()); + let out = cmd + .args(["search", "rainfall", "-s", "roboflow,openml", "--offline"]) + .output() + .unwrap(); + assert!(out.status.success(), "{out:?}"); + let stderr = String::from_utf8_lossy(&out.stderr); + let line = "searching 1 source for \"rainfall\", offline; \ + 1 needs a key, see `dataseek doctor`"; + assert!(stderr.contains(line), "{stderr}"); +} + // --offline never touches the network, so it must never mark a source as // down either: the next online search would skip it for ten minutes. #[test] @@ -574,6 +592,20 @@ fn opt_in_sources_are_marked_in_the_listing_and_doctor() { assert!(doctor.contains("opt-in mendeley"), "{doctor}"); } +#[test] +fn sources_shows_the_notices_fred_and_census_require() { + let text = stdout_text(&["sources"]); + assert!( + text.contains("fred: This product uses the FRED\u{ae} API but"), + "{text}" + ); + assert!(text.contains("stlouisfed.org/docs/api/terms_of_use"), "{text}"); + assert!( + text.contains("census: This product uses the Census Bureau Data API"), + "{text}" + ); +} + #[test] fn piped_json_is_one_line() { let text = stdout_text(&["sources", "--json"]); @@ -641,7 +673,42 @@ fn piped_output_has_no_ansi() { fn cache_info_reports_the_budget() { let info = json_of(&["cache", "info", "--json"]); assert_eq!(info["files"], 0); - assert_eq!(info["budget_bytes"], 30 * 1024 * 1024); + assert_eq!(info["budget_bytes"], 30_000_000); + let text = stdout_text(&["cache", "info"]); + assert!(text.contains("of 30.0 MB budget (2000 files max)"), "{text}"); +} + +#[test] +fn the_cache_budget_comes_from_the_environment() { + let out = bin() + .env("DATASEEK_CACHE_MAX_MB", "120") + .args(["cache", "info", "--json"]) + .output() + .unwrap(); + let info: Value = serde_json::from_slice(&out.stdout).unwrap(); + assert_eq!(info["budget_bytes"], 120_000_000); + let out = bin() + .env("DATASEEK_CACHE_MAX_MB", "120") + .args(["cache", "info"]) + .output() + .unwrap(); + let text = String::from_utf8(out.stdout).unwrap(); + assert!(text.contains("120.0 MB budget, set by DATASEEK_CACHE_MAX_MB")); +} + +#[test] +fn a_bad_cache_budget_is_a_usage_error() { + for value in ["0", "lots", "10001"] { + let out = bin() + .env("DATASEEK_CACHE_MAX_MB", value) + .args(["cache", "info"]) + .output() + .unwrap(); + assert_eq!(out.status.code(), Some(2), "{value}"); + assert!(out.stdout.is_empty(), "a usage error put bytes on stdout"); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(stderr.contains("DATASEEK_CACHE_MAX_MB"), "{stderr}"); + } } #[test] @@ -1166,6 +1233,18 @@ fn cache_dir_moves_the_cache() { assert_eq!(info["path"], dir); } +// `man` is for installing the page, not for daily use: the help leaves it +// out, and it still runs. +#[test] +fn man_is_hidden_from_help_but_still_runs() { + let lists_man = + |text: &str| text.lines().any(|l| l.trim_start().starts_with("man ")); + assert!(!lists_man(&stdout_text(&[])), "overview lists man"); + assert!(!lists_man(&stdout_text(&["-h"])), "-h lists man"); + assert!(!lists_man(&stdout_text(&["--help"])), "--help lists man"); + assert!(stdout_text(&["man"]).starts_with(".ie")); +} + #[test] fn man_renders_roff_with_the_manifest_version() { let out = bin().arg("man").output().unwrap(); @@ -1198,6 +1277,25 @@ fn the_man_page_renders_and_lists_every_command() { } } +// Every option says what it does, the flags `-h` leaves out included, and +// the closing text is split into the sections a man page reader expects. +#[test] +fn the_man_page_describes_every_option_in_named_sections() { + let roff = stdout_text(&["man"]); + let lines: Vec<&str> = roff.lines().collect(); + for pair in lines.windows(2) { + if pair[0].starts_with("\\fB\\-") { + assert!(!pair[1].trim().is_empty(), "no description: {}", pair[0]); + } + } + for section in + [".SH EXAMPLES", ".SH \"EXIT STATUS\"", ".SH \"REPORTING BUGS\""] + { + assert!(roff.contains(section), "{section} missing"); + } + assert!(!roff.contains(".SH EXTRA"), "{roff}"); +} + fn stdout_of(args: &[&str]) -> Vec { bin().arg("sources").args(args).output().unwrap().stdout } @@ -1245,6 +1343,22 @@ fn on_a_terminal(args: &[&str], no_color: bool) -> Vec { cmd.output().unwrap().stdout } +// On a terminal the script would scroll past unread; the reader gets where +// to save it instead. A pipe still gets the script (the other tests). +#[cfg(unix)] +#[test] +fn completion_on_a_terminal_says_where_to_save_the_script() { + let text = String::from_utf8(on_a_terminal(&["completion", "fish"], true)) + .unwrap(); + assert!( + text.contains( + "dataseek completion fish > ~/.config/fish/completions/dataseek.fish" + ), + "{text}" + ); + assert!(!text.contains("complete -c"), "{text}"); +} + // Color is the default on a terminal and every off switch reaches every // writer, clap's own errors included. #[cfg(unix)] diff --git a/tests/snapshots/cli__help_snapshot.snap b/tests/snapshots/cli__help_snapshot.snap index d3203ca..84d88a6 100644 --- a/tests/snapshots/cli__help_snapshot.snap +++ b/tests/snapshots/cli__help_snapshot.snap @@ -11,13 +11,12 @@ Usage: dataseek [OPTIONS] [COMMAND] Commands: search Search every source at once, merged, deduplicated and ranked [alias: s] sources List every source: what it covers, its protocol, its key, its docs - bench Time every source on real queries and measure their overlap inspect Read a dataset page's metadata and the files it lists mcp Serve search, sources and inspect to MCP clients over stdio + bench Time every source on real queries and measure their overlap cache Show, warm or clear the cache doctor Check the environment, keys and cache, and report readiness - completion Print a shell completion script to stdout - man Print the man page, in roff, to stdout + completion Print a shell completion script; on a terminal, say where to save it help Explain a command or a topic: environment, exit-codes Options: @@ -31,8 +30,8 @@ Options: Emit JSON to stdout instead of text --color - When to colorize output: auto, always, or never - + Colorize output (auto, always, or never) + Possible values: - auto: Color when stdout is a terminal and NO_COLOR is unset - always: Always color, even through a pipe (for `| less -R`) diff --git a/tests/snapshots/cli__json_error_event.snap b/tests/snapshots/cli__json_error_event.snap index a38b514..a21cde2 100644 --- a/tests/snapshots/cli__json_error_event.snap +++ b/tests/snapshots/cli__json_error_event.snap @@ -1,6 +1,6 @@ --- source: tests/cli.rs +assertion_line: 338 expression: stderr --- -{"event":"stage","message":"searching 1 source for \"climate\"","schema":"dataseek-events/1"} {"causes":[],"event":"error","message":"none of the chosen sources can run","schema":"dataseek-events/1","try":"`dataseek sources` shows which keys are missing"} diff --git a/tests/snapshots/cli__json_shapes_snapshot.snap b/tests/snapshots/cli__json_shapes_snapshot.snap index dd134c0..71eb47a 100644 --- a/tests/snapshots/cli__json_shapes_snapshot.snap +++ b/tests/snapshots/cli__json_shapes_snapshot.snap @@ -4,7 +4,7 @@ expression: "serde_json::to_string_pretty(&shapes).unwrap()" --- { "cache info": { - "budget_bytes": 31457280, + "budget_bytes": 30000000, "budget_files": 2000, "bytes": 0, "files": 0, @@ -97,7 +97,7 @@ expression: "serde_json::to_string_pretty(&shapes).unwrap()" "ok": true }, { - "detail": "0 files, 0 B of 31.5 MB", + "detail": "0 files, 0 B of 30.0 MB", "label": "cache use", "ok": true } @@ -199,6 +199,7 @@ expression: "serde_json::to_string_pretty(&shapes).unwrap()" "key": "none", "key_env": null, "name": "DataCite", + "notice": null, "opt_in": null, "protocol": "DataCite REST", "search": "live"