From add35ed4c7dfdabd569bb552109398851e869217 Mon Sep 17 00:00:00 2001 From: Valentin Millet Date: Thu, 3 Dec 2026 17:55:16 +0100 Subject: [PATCH] Repository: code formatted at 110 columns, editor settings at the root Co-Authored-By: Claude Opus 5.5 --- .editorconfig | 38 + crates/app/build.rs | 6 +- crates/app/examples/icons.rs | 26 +- crates/app/examples/tours.rs | 17 +- crates/app/src/arguments.rs | 26 +- crates/app/src/desktop.rs | 16 +- crates/app/src/logging.rs | 46 +- crates/app/src/main.rs | 74 +- crates/app/src/renderer.rs | 20 +- crates/app/src/sight.rs | 13 +- crates/app/src/unpainted.rs | 13 +- crates/app/tests/windows_resources.rs | 4 +- crates/drawing/src/edit.rs | 176 +---- crates/drawing/src/edit/tests.rs | 137 +--- crates/drawing/src/geometry.rs | 161 +--- crates/drawing/src/marks.rs | 136 +--- crates/drawing/src/picture.rs | 64 +- crates/drawing/src/picture/tests.rs | 70 +- crates/drawing/src/scene.rs | 81 +- crates/drawing/src/scene/tests.rs | 70 +- crates/drawing/src/text.rs | 9 +- crates/drawing/src/text/tests.rs | 8 +- crates/engine/benches/commands.rs | 92 +-- crates/engine/benches/corpus.rs | 49 +- crates/engine/benches/corpus_size.rs | 10 +- crates/engine/benches/index.rs | 38 +- crates/engine/benches/reference.rs | 47 +- crates/engine/benches/reference_profile.rs | 6 +- crates/engine/build.rs | 18 +- crates/engine/src/attachments.rs | 15 +- crates/engine/src/attachments/files.rs | 55 +- crates/engine/src/attachments/model.rs | 76 +- crates/engine/src/attachments/sealed.rs | 17 +- crates/engine/src/attachments/store.rs | 70 +- crates/engine/src/backup.rs | 6 +- crates/engine/src/backup/copies.rs | 165 +--- crates/engine/src/changelog.rs | 41 +- crates/engine/src/changelog/model.rs | 69 +- crates/engine/src/closed_enum.rs | 10 +- crates/engine/src/db.rs | 54 +- crates/engine/src/db/migration.rs | 8 +- crates/engine/src/db/queue.rs | 10 +- crates/engine/src/docs.rs | 42 +- crates/engine/src/docs/model.rs | 132 +--- crates/engine/src/docs/search.rs | 33 +- crates/engine/src/error.rs | 173 +--- crates/engine/src/folders.rs | 65 +- crates/engine/src/folders/board.rs | 294 ++----- crates/engine/src/folders/model.rs | 111 +-- crates/engine/src/folders/store.rs | 113 +-- crates/engine/src/folders/store/board.rs | 110 +-- crates/engine/src/host.rs | 11 +- crates/engine/src/http.rs | 334 ++------ crates/engine/src/http/codegen.rs | 273 ++----- crates/engine/src/http/codegen/angular.rs | 22 +- crates/engine/src/http/codegen/axios.rs | 10 +- crates/engine/src/http/codegen/csharp.rs | 14 +- crates/engine/src/http/codegen/curl.rs | 25 +- crates/engine/src/http/codegen/dart.rs | 27 +- crates/engine/src/http/codegen/fetch.rs | 6 +- crates/engine/src/http/codegen/go.rs | 28 +- crates/engine/src/http/codegen/guzzle.rs | 26 +- crates/engine/src/http/codegen/httpie.rs | 16 +- crates/engine/src/http/codegen/java.rs | 47 +- crates/engine/src/http/codegen/javascript.rs | 33 +- crates/engine/src/http/codegen/okhttp.rs | 41 +- crates/engine/src/http/codegen/powershell.rs | 20 +- crates/engine/src/http/codegen/python.rs | 24 +- crates/engine/src/http/codegen/req.rs | 16 +- crates/engine/src/http/codegen/reqwest.rs | 29 +- crates/engine/src/http/codegen/ruby.rs | 11 +- crates/engine/src/http/codegen/source.rs | 8 +- crates/engine/src/http/codegen/swift.rs | 27 +- crates/engine/src/http/codegen/wget.rs | 10 +- crates/engine/src/http/collection_run.rs | 23 +- crates/engine/src/http/console.rs | 145 +--- crates/engine/src/http/cookies.rs | 215 ++--- crates/engine/src/http/cookies/store.rs | 99 +-- crates/engine/src/http/environments.rs | 54 +- crates/engine/src/http/environments/store.rs | 45 +- crates/engine/src/http/error.rs | 57 +- crates/engine/src/http/extract.rs | 6 +- crates/engine/src/http/flight.rs | 195 +---- crates/engine/src/http/graphql.rs | 121 +-- crates/engine/src/http/history.rs | 448 +++-------- crates/engine/src/http/history/store.rs | 124 +-- crates/engine/src/http/model.rs | 151 +--- crates/engine/src/http/query.rs | 84 +- crates/engine/src/http/response.rs | 31 +- crates/engine/src/http/runner.rs | 256 ++---- crates/engine/src/http/scripts/around.rs | 262 ++---- crates/engine/src/http/scripts/child.rs | 95 +-- crates/engine/src/http/scripts/engine.rs | 491 +++--------- crates/engine/src/http/scripts/libraries.rs | 11 +- crates/engine/src/http/scripts/model.rs | 242 ++---- crates/engine/src/http/scripts/network.rs | 84 +- crates/engine/src/http/scripts/process.rs | 28 +- crates/engine/src/http/scripts/session.rs | 6 +- crates/engine/src/http/search.rs | 32 +- crates/engine/src/http/send.rs | 743 ++++-------------- crates/engine/src/http/settings.rs | 149 +--- crates/engine/src/http/store.rs | 235 ++---- crates/engine/src/http/transport.rs | 11 +- crates/engine/src/http/variables.rs | 253 ++---- crates/engine/src/http/websocket.rs | 76 +- crates/engine/src/index.rs | 248 ++---- crates/engine/src/index/oracle.rs | 99 +-- crates/engine/src/json/layout.rs | 8 +- crates/engine/src/json/model.rs | 314 ++------ crates/engine/src/json/parse.rs | 54 +- crates/engine/src/json/position.rs | 11 +- crates/engine/src/json/read.rs | 16 +- crates/engine/src/json/toml.rs | 49 +- crates/engine/src/json/xml.rs | 161 +--- crates/engine/src/json/yaml.rs | 137 +--- crates/engine/src/layout.rs | 25 +- crates/engine/src/lib.rs | 7 +- crates/engine/src/libraries.rs | 3 +- crates/engine/src/libraries/registry.rs | 57 +- crates/engine/src/name.rs | 5 +- crates/engine/src/notes.rs | 103 +-- crates/engine/src/notes/calc.rs | 450 ++--------- crates/engine/src/notes/calc/eval.rs | 445 +++-------- crates/engine/src/notes/calc/lexer.rs | 76 +- crates/engine/src/notes/calc/maths.rs | 59 +- crates/engine/src/notes/calc/summary.rs | 40 +- crates/engine/src/notes/calc/units.rs | 357 ++------- crates/engine/src/notes/calc/words.rs | 103 +-- crates/engine/src/notes/checklist.rs | 15 +- crates/engine/src/notes/convert.rs | 96 +-- crates/engine/src/notes/drawing.rs | 50 +- crates/engine/src/notes/duplicate.rs | 52 +- crates/engine/src/notes/kind.rs | 5 +- crates/engine/src/notes/language.rs | 499 +++--------- crates/engine/src/notes/markdown.rs | 116 +-- crates/engine/src/notes/model.rs | 420 ++-------- crates/engine/src/notes/placeholder.rs | 117 +-- crates/engine/src/notes/priority.rs | 9 +- crates/engine/src/notes/revision.rs | 57 +- crates/engine/src/notes/store.rs | 156 +--- crates/engine/src/notes/store/pictures.rs | 80 +- crates/engine/src/notes/store/related.rs | 87 +- crates/engine/src/notes/store/revisions.rs | 17 +- crates/engine/src/notes/store/trash.rs | 26 +- crates/engine/src/notes/trash.rs | 37 +- crates/engine/src/notes/view.rs | 659 +++------------- crates/engine/src/recovery.rs | 27 +- crates/engine/src/spaces/model.rs | 10 +- crates/engine/src/spaces/store.rs | 35 +- crates/engine/src/tools.rs | 8 +- crates/engine/src/tools/bases.rs | 325 ++------ crates/engine/src/tools/check_numbers.rs | 83 +- crates/engine/src/tools/checks.rs | 172 +--- crates/engine/src/tools/cidr.rs | 216 +---- crates/engine/src/tools/cidr/forms.rs | 55 +- crates/engine/src/tools/cidr/masks.rs | 25 +- crates/engine/src/tools/cidr/plan.rs | 120 +-- crates/engine/src/tools/cidr/summary.rs | 55 +- crates/engine/src/tools/colour.rs | 249 ++---- crates/engine/src/tools/convert.rs | 145 +--- crates/engine/src/tools/convert/xml.rs | 58 +- crates/engine/src/tools/cron.rs | 501 +++--------- crates/engine/src/tools/dates.rs | 203 +---- crates/engine/src/tools/diff.rs | 428 ++-------- crates/engine/src/tools/durations.rs | 238 ++---- crates/engine/src/tools/encoding.rs | 43 +- crates/engine/src/tools/files.rs | 17 +- crates/engine/src/tools/generate.rs | 178 +---- crates/engine/src/tools/generate/lorem.rs | 87 +- crates/engine/src/tools/generate/schema.rs | 207 ++--- crates/engine/src/tools/hash.rs | 231 ++---- crates/engine/src/tools/identifiers.rs | 179 +---- crates/engine/src/tools/identity.rs | 467 +++-------- crates/engine/src/tools/identity/data.rs | 69 +- crates/engine/src/tools/identity/numbers.rs | 71 +- crates/engine/src/tools/identity/papers.rs | 192 +---- crates/engine/src/tools/identity/profile.rs | 74 +- crates/engine/src/tools/image.rs | 102 +-- crates/engine/src/tools/jwt.rs | 199 +---- crates/engine/src/tools/numbers.rs | 33 +- crates/engine/src/tools/permissions.rs | 162 +--- crates/engine/src/tools/printed.rs | 5 +- crates/engine/src/tools/qr.rs | 285 ++----- crates/engine/src/tools/random.rs | 59 +- crates/engine/src/tools/sizes.rs | 105 +-- crates/engine/src/tools/stats.rs | 99 +-- crates/engine/src/tools/text.rs | 237 ++---- crates/engine/src/tools/text_diff.rs | 192 +---- crates/engine/src/tools/transfer.rs | 112 +-- crates/engine/src/tools/url_parts.rs | 43 +- crates/engine/src/tools/zones.rs | 196 +---- crates/engine/src/transfer.rs | 6 +- crates/engine/src/transfer/bundle.rs | 54 +- crates/engine/src/transfer/file.rs | 252 ++---- crates/engine/src/transfer/model.rs | 147 +--- crates/engine/src/transfer/protect.rs | 17 +- crates/engine/src/vault.rs | 8 +- crates/engine/src/vault/file.rs | 76 +- crates/engine/src/vault/gate.rs | 19 +- crates/engine/src/vault/key.rs | 40 +- crates/engine/tests/commands/attachments.rs | 85 +- crates/engine/tests/commands/backups.rs | 28 +- crates/engine/tests/commands/concurrency.rs | 73 +- crates/engine/tests/commands/folders.rs | 155 +--- crates/engine/tests/commands/http.rs | 146 +--- crates/engine/tests/commands/http_cookies.rs | 15 +- .../tests/commands/http_environments.rs | 110 +-- crates/engine/tests/commands/http_runner.rs | 141 +--- crates/engine/tests/commands/http_scripts.rs | 154 +--- crates/engine/tests/commands/http_send.rs | 235 ++---- crates/engine/tests/commands/index.rs | 41 +- crates/engine/tests/commands/main.rs | 21 +- crates/engine/tests/commands/notes.rs | 242 ++---- crates/engine/tests/commands/profile.rs | 42 +- crates/engine/tests/commands/recovery.rs | 23 +- crates/engine/tests/commands/spaces.rs | 94 +-- crates/engine/tests/commands/transfer.rs | 87 +- crates/engine/tests/commands/websocket.rs | 121 +-- crates/engine/tests/folders/board.rs | 167 +--- crates/engine/tests/folders/main.rs | 16 +- crates/engine/tests/folders/nesting.rs | 44 +- crates/engine/tests/folders/store.rs | 126 +-- crates/engine/tests/formats.rs | 42 +- crates/engine/tests/http.rs | 372 ++------- crates/engine/tests/http_environments.rs | 66 +- crates/engine/tests/language_corpus.rs | 5 +- crates/engine/tests/notes/batches.rs | 194 +---- crates/engine/tests/notes/checklists.rs | 65 +- crates/engine/tests/notes/exchange.rs | 20 +- crates/engine/tests/notes/fields.rs | 82 +- crates/engine/tests/notes/main.rs | 36 +- crates/engine/tests/notes/queries.rs | 315 ++------ crates/engine/tests/notes/revisions.rs | 60 +- crates/engine/tests/notes/seeding.rs | 67 +- crates/engine/tests/notes/storage.rs | 79 +- crates/engine/tests/notes/tags.rs | 69 +- crates/engine/tests/notes/trash.rs | 47 +- crates/engine/tests/notes/writes.rs | 76 +- crates/engine/tests/scripts.rs | 66 +- crates/engine/tests/spaces.rs | 74 +- crates/engine/tests/transfer.rs | 174 +--- crates/i18n/build.rs | 33 +- crates/i18n/src/format.rs | 131 +-- crates/i18n/src/lib.rs | 84 +- crates/i18n/src/plural.rs | 60 +- crates/i18n/src/time.rs | 71 +- crates/platform/examples/update.rs | 6 +- crates/platform/src/autostart/system.rs | 14 +- crates/platform/src/dialog.rs | 5 +- crates/platform/src/dialog/system.rs | 16 +- crates/platform/src/instance.rs | 57 +- crates/platform/src/links.rs | 9 +- crates/platform/src/notify/system.rs | 10 +- crates/platform/src/paths.rs | 18 +- crates/platform/src/shortcuts.rs | 24 +- crates/platform/src/shortcuts/notation.rs | 10 +- crates/platform/src/shortcuts/system/gnome.rs | 7 +- .../platform/src/shortcuts/system/portal.rs | 56 +- .../platform/src/shortcuts/system/wayland.rs | 11 +- crates/platform/src/tray.rs | 13 +- crates/platform/src/tray/system.rs | 15 +- crates/platform/src/updater/system.rs | 28 +- crates/platform/src/updater/tests.rs | 66 +- crates/platform/src/window.rs | 17 +- crates/richtext/src/edit.rs | 181 +---- crates/richtext/src/edit/tests.rs | 161 +--- crates/richtext/src/escape.rs | 14 +- crates/richtext/src/history.rs | 19 +- crates/richtext/src/html.rs | 146 +--- crates/richtext/src/inlines.rs | 73 +- crates/richtext/src/model.rs | 15 +- crates/richtext/src/picture.rs | 77 +- crates/richtext/src/read.rs | 169 +--- crates/richtext/src/rules.rs | 40 +- crates/richtext/src/rules/tests.rs | 56 +- crates/richtext/src/table.rs | 66 +- crates/richtext/src/tree.rs | 94 +-- crates/richtext/src/write.rs | 169 +--- crates/richtext/tests/golden.rs | 3 +- crates/richtext/tests/past_the_end.rs | 5 +- crates/text/src/buffer.rs | 119 +-- crates/text/src/buffer/tests.rs | 164 +--- crates/text/src/diff.rs | 10 +- crates/text/src/format.rs | 10 +- crates/text/src/format/host.rs | 36 +- crates/text/src/format/tests.rs | 15 +- crates/text/src/highlight.rs | 144 +--- crates/text/src/indent.rs | 78 +- crates/text/src/search.rs | 47 +- crates/text/src/shield.rs | 34 +- crates/text/src/words.rs | 31 +- crates/ui/src/action.rs | 8 +- crates/ui/src/api/attachments.rs | 11 +- crates/ui/src/api/board.rs | 6 +- crates/ui/src/api/folders.rs | 14 +- crates/ui/src/api/http.rs | 63 +- crates/ui/src/api/notes.rs | 68 +- crates/ui/src/api/preferences.rs | 8 +- crates/ui/src/api/tools.rs | 10 +- crates/ui/src/api/transfer.rs | 11 +- crates/ui/src/api/undo.rs | 8 +- crates/ui/src/api/vault.rs | 20 +- crates/ui/src/app.rs | 172 ++-- crates/ui/src/app/about_link_tests.rs | 5 +- crates/ui/src/app/area_switch_tests.rs | 38 +- crates/ui/src/app/captures.rs | 440 +++-------- crates/ui/src/app/docs_tests.rs | 13 +- crates/ui/src/app/gate_update_tests.rs | 15 +- crates/ui/src/app/global_key_tests.rs | 5 +- crates/ui/src/app/library_panel_tests.rs | 11 +- crates/ui/src/app/modal_tests.rs | 27 +- crates/ui/src/app/palette_copy_tests.rs | 8 +- crates/ui/src/app/perf.rs | 100 +-- crates/ui/src/app/preferences_tests.rs | 44 +- crates/ui/src/app/prompt_tests.rs | 6 +- crates/ui/src/app/rail_toggle_tests.rs | 34 +- crates/ui/src/app/screens.rs | 111 +-- crates/ui/src/app/titlebar_tests.rs | 18 +- crates/ui/src/app/update_prompt_tests.rs | 24 +- crates/ui/src/app/window_tests.rs | 51 +- crates/ui/src/backend.rs | 39 +- crates/ui/src/banners/toasts.rs | 52 +- crates/ui/src/banners/update_prompt.rs | 33 +- crates/ui/src/gate/draw.rs | 130 +-- crates/ui/src/gate/mod.rs | 21 +- crates/ui/src/gate/passphrase.rs | 65 +- crates/ui/src/gate/prompt.rs | 99 +-- crates/ui/src/gate/tests.rs | 127 +-- crates/ui/src/http/close.rs | 24 +- crates/ui/src/http/code.rs | 81 +- crates/ui/src/http/code_tests.rs | 86 +- crates/ui/src/http/console.rs | 119 +-- crates/ui/src/http/console/tests.rs | 84 +- crates/ui/src/http/container_settings.rs | 80 +- crates/ui/src/http/cookie_jar.rs | 65 +- crates/ui/src/http/cookie_jar/tests.rs | 10 +- crates/ui/src/http/dialogs_tests.rs | 50 +- crates/ui/src/http/environment_picker.rs | 98 +-- crates/ui/src/http/environments.rs | 157 +--- crates/ui/src/http/environments_tests.rs | 64 +- crates/ui/src/http/extract.rs | 43 +- crates/ui/src/http/history.rs | 187 +---- crates/ui/src/http/history_tests.rs | 77 +- crates/ui/src/http/kept_tests.rs | 61 +- crates/ui/src/http/leave.rs | 47 +- crates/ui/src/http/leave_tests.rs | 37 +- crates/ui/src/http/mod.rs | 56 +- crates/ui/src/http/rail/forms.rs | 78 +- crates/ui/src/http/rail/forms/tests.rs | 5 +- crates/ui/src/http/rail/mod.rs | 209 +---- crates/ui/src/http/rail/row.rs | 92 +-- crates/ui/src/http/request/auth.rs | 72 +- crates/ui/src/http/request/auth/tests.rs | 149 +--- crates/ui/src/http/request/body.rs | 103 +-- crates/ui/src/http/request/chips.rs | 58 +- crates/ui/src/http/request/composer.rs | 55 +- crates/ui/src/http/request/extractions.rs | 17 +- crates/ui/src/http/request/graphql.rs | 107 +-- crates/ui/src/http/request/mod.rs | 290 ++----- crates/ui/src/http/request/parts.rs | 80 +- crates/ui/src/http/request/settings_tests.rs | 88 +-- crates/ui/src/http/request/table.rs | 157 +--- crates/ui/src/http/request/tests.rs | 183 +---- crates/ui/src/http/request/transport.rs | 42 +- crates/ui/src/http/request/url.rs | 13 +- crates/ui/src/http/request/url/tests.rs | 13 +- crates/ui/src/http/response/body.rs | 149 +--- crates/ui/src/http/response/mod.rs | 268 ++----- crates/ui/src/http/response/pane_tests.rs | 28 +- crates/ui/src/http/response/stop.rs | 33 +- crates/ui/src/http/response/tests_view.rs | 78 +- crates/ui/src/http/runner/mod.rs | 100 +-- crates/ui/src/http/runner/order.rs | 105 +-- crates/ui/src/http/runner/results.rs | 214 ++--- crates/ui/src/http/runner_tests.rs | 126 +-- crates/ui/src/http/save_as_note.rs | 47 +- crates/ui/src/http/save_request.rs | 23 +- crates/ui/src/http/save_request/tests.rs | 31 +- crates/ui/src/http/scripts.rs | 111 +-- crates/ui/src/http/scripts_tests.rs | 55 +- crates/ui/src/http/socket_log.rs | 100 +-- crates/ui/src/http/socket_log/tests.rs | 18 +- crates/ui/src/http/socket_tests.rs | 79 +- crates/ui/src/http/tabs.rs | 157 +--- crates/ui/src/http/tests.rs | 491 +++--------- crates/ui/src/http/variables_table.rs | 68 +- crates/ui/src/http/variables_table/tests.rs | 22 +- crates/ui/src/inputs.rs | 10 +- crates/ui/src/keys.rs | 128 +-- crates/ui/src/notes/bench.rs | 146 ++-- crates/ui/src/notes/calc.rs | 310 ++------ crates/ui/src/notes/canvas/board/gesture.rs | 88 +-- crates/ui/src/notes/canvas/board/mod.rs | 263 ++----- crates/ui/src/notes/canvas/board/tests.rs | 230 ++---- crates/ui/src/notes/canvas/board/tidy.rs | 92 +-- crates/ui/src/notes/canvas/board/zone.rs | 247 ++---- crates/ui/src/notes/canvas/card/actions.rs | 153 +--- crates/ui/src/notes/canvas/card/bands.rs | 108 +-- crates/ui/src/notes/canvas/card/body.rs | 168 +--- crates/ui/src/notes/canvas/card/mod.rs | 57 +- crates/ui/src/notes/canvas/card/tests.rs | 161 +--- crates/ui/src/notes/canvas/grid.rs | 26 +- crates/ui/src/notes/canvas/mod.rs | 109 +-- crates/ui/src/notes/canvas/rows.rs | 55 +- crates/ui/src/notes/canvas/shortcuts.rs | 44 +- crates/ui/src/notes/canvas/tests.rs | 151 ++-- crates/ui/src/notes/destinations.rs | 30 +- crates/ui/src/notes/header/facets.rs | 647 +++++---------- crates/ui/src/notes/header/layout.rs | 26 +- crates/ui/src/notes/header/mod.rs | 186 +---- crates/ui/src/notes/header/new_note.rs | 80 +- crates/ui/src/notes/header/selection.rs | 156 +--- crates/ui/src/notes/header/sort.rs | 102 +-- crates/ui/src/notes/header/switchers.rs | 241 ++---- crates/ui/src/notes/header/tests.rs | 158 +--- crates/ui/src/notes/language.rs | 20 +- crates/ui/src/notes/mod.rs | 74 +- .../src/notes/overlays/editor/attachments.rs | 28 +- .../overlays/editor/attachments/tests.rs | 21 +- crates/ui/src/notes/overlays/editor/body.rs | 23 +- crates/ui/src/notes/overlays/editor/calc.rs | 190 +---- .../src/notes/overlays/editor/calc/tests.rs | 84 +- .../ui/src/notes/overlays/editor/checklist.rs | 158 +--- .../notes/overlays/editor/checklist/tests.rs | 158 +--- crates/ui/src/notes/overlays/editor/code.rs | 40 +- .../src/notes/overlays/editor/code/tests.rs | 68 +- .../ui/src/notes/overlays/editor/drawing.rs | 200 +---- .../notes/overlays/editor/drawing/camera.rs | 37 +- .../src/notes/overlays/editor/drawing/look.rs | 19 +- .../notes/overlays/editor/drawing/tests.rs | 61 +- .../ui/src/notes/overlays/editor/expanded.rs | 102 +-- crates/ui/src/notes/overlays/editor/fields.rs | 142 +--- .../src/notes/overlays/editor/fields/tests.rs | 25 +- crates/ui/src/notes/overlays/editor/format.rs | 136 +--- .../src/notes/overlays/editor/format/tests.rs | 130 +-- .../src/notes/overlays/editor/go_to_line.rs | 28 +- crates/ui/src/notes/overlays/editor/header.rs | 129 +-- .../ui/src/notes/overlays/editor/json_view.rs | 115 +-- .../notes/overlays/editor/json_view/tests.rs | 110 +-- crates/ui/src/notes/overlays/editor/mod.rs | 194 +---- .../ui/src/notes/overlays/editor/revisions.rs | 96 +-- .../notes/overlays/editor/revisions/tests.rs | 54 +- crates/ui/src/notes/overlays/editor/rich.rs | 218 ++--- .../src/notes/overlays/editor/rich/images.rs | 29 +- .../src/notes/overlays/editor/rich/search.rs | 39 +- .../notes/overlays/editor/rich/shortcuts.rs | 21 +- .../src/notes/overlays/editor/rich/tests.rs | 227 ++---- .../src/notes/overlays/editor/rich/toolbar.rs | 175 +---- .../src/notes/overlays/editor/search_bar.rs | 100 +-- crates/ui/src/notes/overlays/editor/tests.rs | 156 +--- crates/ui/src/notes/overlays/folder_prompt.rs | 36 +- .../ui/src/notes/overlays/image_lightbox.rs | 13 +- .../ui/src/notes/overlays/placeholder_form.rs | 106 +-- crates/ui/src/notes/overlays/presentation.rs | 97 +-- .../notes/overlays/presentation/mind_map.rs | 66 +- .../src/notes/overlays/presentation/tests.rs | 62 +- crates/ui/src/notes/overlays/tag_manager.rs | 192 +---- crates/ui/src/notes/overlays/trash_panel.rs | 180 +---- crates/ui/src/notes/overlays/undo_bar.rs | 86 +- crates/ui/src/notes/panel.rs | 226 +----- crates/ui/src/notes/parity_tests.rs | 105 +-- crates/ui/src/notes/pointer_tests.rs | 20 +- crates/ui/src/notes/prettier.rs | 53 +- crates/ui/src/notes/sidebar/mod.rs | 148 +--- crates/ui/src/notes/sidebar/row.rs | 47 +- crates/ui/src/notes/sidebar/tests.rs | 210 ++--- crates/ui/src/notes/sidebar/tree.rs | 51 +- crates/ui/src/notes/ui.rs | 55 +- crates/ui/src/palette/list_tests.rs | 74 +- crates/ui/src/palette/mod.rs | 305 ++----- crates/ui/src/palette/options.rs | 113 +-- crates/ui/src/services/autostart.rs | 16 +- crates/ui/src/services/docs_quotes.rs | 37 +- crates/ui/src/services/errors.rs | 65 +- crates/ui/src/services/global_keys.rs | 19 +- crates/ui/src/services/highlight.rs | 6 +- crates/ui/src/services/preferences.rs | 19 +- crates/ui/src/services/samples.rs | 20 +- crates/ui/src/services/settings.rs | 152 +--- crates/ui/src/services/shortcuts.rs | 185 +---- crates/ui/src/services/time.rs | 26 +- crates/ui/src/services/updates.rs | 30 +- crates/ui/src/state/apply_http.rs | 27 +- crates/ui/src/state/apply_notes.rs | 243 ++---- crates/ui/src/state/apply_window.rs | 38 +- crates/ui/src/state/attachments.rs | 62 +- crates/ui/src/state/backups.rs | 12 +- crates/ui/src/state/board.rs | 217 ++--- crates/ui/src/state/drawing_pictures.rs | 34 +- crates/ui/src/state/editor.rs | 159 +--- crates/ui/src/state/explored.rs | 3 +- crates/ui/src/state/folders.rs | 54 +- crates/ui/src/state/formatting.rs | 33 +- crates/ui/src/state/held.rs | 17 +- crates/ui/src/state/http/area_tests.rs | 316 ++------ crates/ui/src/state/http/bodies.rs | 41 +- crates/ui/src/state/http/code.rs | 7 +- crates/ui/src/state/http/containers.rs | 5 +- crates/ui/src/state/http/cookies.rs | 3 +- crates/ui/src/state/http/environments.rs | 74 +- crates/ui/src/state/http/history.rs | 40 +- crates/ui/src/state/http/mod.rs | 181 ++--- crates/ui/src/state/http/moves.rs | 165 +--- crates/ui/src/state/http/runner.rs | 51 +- crates/ui/src/state/http/send.rs | 14 +- crates/ui/src/state/http/sockets.rs | 26 +- crates/ui/src/state/http/tabs.rs | 115 +-- crates/ui/src/state/http/tree.rs | 87 +- crates/ui/src/state/libraries.rs | 26 +- crates/ui/src/state/mod.rs | 129 +-- crates/ui/src/state/note_revisions.rs | 21 +- crates/ui/src/state/notes.rs | 61 +- crates/ui/src/state/notes_query.rs | 74 +- crates/ui/src/state/notes_tests.rs | 174 +--- crates/ui/src/state/palette.rs | 36 +- crates/ui/src/state/placeholder_fill.rs | 24 +- crates/ui/src/state/presentation.rs | 26 +- crates/ui/src/state/query.rs | 13 +- crates/ui/src/state/refused_tests.rs | 146 +--- crates/ui/src/state/security.rs | 30 +- crates/ui/src/state/selection.rs | 3 +- crates/ui/src/state/spaces.rs | 42 +- crates/ui/src/state/tags.rs | 26 +- crates/ui/src/state/tools.rs | 18 +- crates/ui/src/state/transfer.rs | 166 +--- crates/ui/src/state/undo.rs | 30 +- crates/ui/src/state/window_tests.rs | 119 +-- crates/ui/src/testing.rs | 39 +- crates/ui/src/theme/focus.rs | 7 +- crates/ui/src/theme/fonts.rs | 34 +- crates/ui/src/theme/icons.rs | 96 +-- crates/ui/src/theme/literals.rs | 38 +- crates/ui/src/theme/mod.rs | 40 +- crates/ui/src/theme/motion.rs | 49 +- crates/ui/src/theme/tokens.rs | 60 +- crates/ui/src/titlebar/about_menu/card.rs | 52 +- crates/ui/src/titlebar/about_menu/docs/mod.rs | 133 +--- .../ui/src/titlebar/about_menu/docs/page.rs | 117 +-- .../ui/src/titlebar/about_menu/docs/text.rs | 49 +- crates/ui/src/titlebar/about_menu/mod.rs | 64 +- crates/ui/src/titlebar/about_menu/sheet.rs | 39 +- .../ui/src/titlebar/about_menu/whats_new.rs | 31 +- crates/ui/src/titlebar/area_switch.rs | 20 +- crates/ui/src/titlebar/file_menu.rs | 56 +- crates/ui/src/titlebar/libraries.rs | 46 +- crates/ui/src/titlebar/mod.rs | 74 +- crates/ui/src/titlebar/preferences/general.rs | 177 +---- crates/ui/src/titlebar/preferences/mod.rs | 98 +-- .../ui/src/titlebar/preferences/security.rs | 83 +- .../ui/src/titlebar/preferences/shortcuts.rs | 92 +-- .../ui/src/titlebar/preferences/variables.rs | 36 +- crates/ui/src/titlebar/window.rs | 37 +- crates/ui/src/tools/catalogue.rs | 180 +---- .../ui/src/tools/catalogue/answers_tests.rs | 404 ++-------- crates/ui/src/tools/catalogue/ascii.rs | 46 +- crates/ui/src/tools/catalogue/base64.rs | 111 +-- crates/ui/src/tools/catalogue/calc_tests.rs | 140 +--- crates/ui/src/tools/catalogue/case.rs | 29 +- crates/ui/src/tools/catalogue/checks.rs | 155 +--- crates/ui/src/tools/catalogue/cidr.rs | 103 +-- crates/ui/src/tools/catalogue/colour.rs | 47 +- crates/ui/src/tools/catalogue/convert.rs | 24 +- crates/ui/src/tools/catalogue/cron.rs | 151 +--- .../ui/src/tools/catalogue/cron/sentence.rs | 53 +- crates/ui/src/tools/catalogue/data_tests.rs | 96 +-- crates/ui/src/tools/catalogue/dates.rs | 204 ++--- crates/ui/src/tools/catalogue/diff.rs | 78 +- .../ui/src/tools/catalogue/diff/structured.rs | 136 +--- crates/ui/src/tools/catalogue/diff/text.rs | 137 +--- .../ui/src/tools/catalogue/encoding_tests.rs | 56 +- crates/ui/src/tools/catalogue/hash.rs | 121 +-- crates/ui/src/tools/catalogue/http_headers.rs | 27 +- crates/ui/src/tools/catalogue/http_status.rs | 71 +- crates/ui/src/tools/catalogue/identifiers.rs | 108 +-- crates/ui/src/tools/catalogue/identity.rs | 215 +---- .../ui/src/tools/catalogue/json_generator.rs | 38 +- crates/ui/src/tools/catalogue/jwt.rs | 51 +- crates/ui/src/tools/catalogue/line_breaks.rs | 46 +- crates/ui/src/tools/catalogue/lorem.rs | 24 +- .../ui/src/tools/catalogue/markdown_sheet.rs | 15 +- crates/ui/src/tools/catalogue/mime_types.rs | 47 +- .../ui/src/tools/catalogue/mustache_sheet.rs | 11 +- crates/ui/src/tools/catalogue/password.rs | 62 +- crates/ui/src/tools/catalogue/permissions.rs | 74 +- crates/ui/src/tools/catalogue/ports.rs | 16 +- crates/ui/src/tools/catalogue/qr.rs | 95 +-- crates/ui/src/tools/catalogue/reference.rs | 29 +- .../ui/src/tools/catalogue/reference_tests.rs | 21 +- crates/ui/src/tools/catalogue/regex_sheet.rs | 22 +- crates/ui/src/tools/catalogue/signals.rs | 27 +- crates/ui/src/tools/catalogue/sizes.rs | 138 +--- crates/ui/src/tools/catalogue/text_stats.rs | 103 +-- crates/ui/src/tools/catalogue/text_tests.rs | 41 +- crates/ui/src/tools/catalogue/time_tests.rs | 58 +- crates/ui/src/tools/catalogue/url_codec.rs | 54 +- crates/ui/src/tools/catalogue/zones.rs | 108 +-- crates/ui/src/tools/frame.rs | 35 +- crates/ui/src/tools/home.rs | 224 +----- crates/ui/src/tools/home/hits.rs | 23 +- crates/ui/src/tools/live.rs | 11 +- crates/ui/src/tools/mod.rs | 47 +- crates/ui/src/tools/rail.rs | 77 +- crates/ui/src/tools/tests.rs | 17 +- crates/ui/src/tools/ui/copy_value.rs | 69 +- crates/ui/src/tools/ui/mod.rs | 97 +-- crates/ui/src/tools/ui/note_import.rs | 14 +- crates/ui/src/tools/ui/note_picker.rs | 42 +- crates/ui/src/tools/ui/output_row.rs | 26 +- crates/ui/src/tools/ui/reference_table.rs | 96 +-- crates/ui/src/tools/ui/result_row.rs | 82 +- crates/ui/src/tools/ui/tests.rs | 137 ++-- crates/ui/src/tools/ui/text_table.rs | 7 +- crates/ui/src/widgets/badge.rs | 58 +- crates/ui/src/widgets/button.rs | 124 +-- crates/ui/src/widgets/date.rs | 194 ++--- crates/ui/src/widgets/dialog.rs | 116 +-- crates/ui/src/widgets/editor/bubbles.rs | 11 +- crates/ui/src/widgets/editor/bubbles/tests.rs | 81 +- crates/ui/src/widgets/editor/geometry.rs | 46 +- crates/ui/src/widgets/editor/input.rs | 94 +-- crates/ui/src/widgets/editor/mod.rs | 125 +-- crates/ui/src/widgets/editor/tests.rs | 198 ++--- crates/ui/src/widgets/empty.rs | 32 +- crates/ui/src/widgets/field.rs | 99 +-- crates/ui/src/widgets/in_place.rs | 9 +- crates/ui/src/widgets/json_explorer/graph.rs | 274 ++----- crates/ui/src/widgets/json_explorer/mod.rs | 243 ++---- crates/ui/src/widgets/json_explorer/reads.rs | 24 +- crates/ui/src/widgets/json_explorer/tests.rs | 30 +- crates/ui/src/widgets/json_explorer/tree.rs | 51 +- .../src/widgets/json_explorer/view_tests.rs | 202 +---- crates/ui/src/widgets/layout.rs | 117 ++- crates/ui/src/widgets/list.rs | 95 +-- crates/ui/src/widgets/menu.rs | 368 +++------ crates/ui/src/widgets/mod.rs | 63 +- crates/ui/src/widgets/picker.rs | 85 +- crates/ui/src/widgets/release_notes.rs | 6 +- crates/ui/src/widgets/rich.rs | 164 +--- crates/ui/src/widgets/rich/tests.rs | 282 ++----- crates/ui/src/widgets/segmented.rs | 57 +- crates/ui/src/widgets/split.rs | 81 +- crates/ui/src/widgets/tests.rs | 125 +-- docs/architecture.md | 3 +- e2e/examples/footprint.rs | 15 +- e2e/src/lib.rs | 133 +--- e2e/src/server.rs | 33 +- e2e/tests/01_first_launch.rs | 70 +- e2e/tests/02_note_lifecycle.rs | 125 ++- e2e/tests/03_editing_a_note.rs | 335 ++++---- e2e/tests/04_trash_and_undo.rs | 108 ++- e2e/tests/05_spaces.rs | 142 ++-- e2e/tests/06_search_and_filters.rs | 234 ++---- e2e/tests/07_checklists.rs | 83 +- e2e/tests/08_placeholder_fields.rs | 81 +- e2e/tests/09_quick_palette.rs | 71 +- e2e/tests/10_library_transfer.rs | 71 +- e2e/tests/12_preferences.rs | 67 +- e2e/tests/13_multiple_selection.rs | 19 +- e2e/tests/14_tag_manager.rs | 96 +-- e2e/tests/15_preferences_on_disk.rs | 15 +- e2e/tests/16_passphrase_change.rs | 80 +- e2e/tests/17_folders.rs | 343 ++++---- e2e/tests/18_board.rs | 281 +++---- e2e/tests/19_board_gesture.rs | 333 ++++---- e2e/tests/20_folder_descent.rs | 152 ++-- e2e/tests/21_folders_travel.rs | 16 +- e2e/tests/22_note_history.rs | 25 +- e2e/tests/23_backups.rs | 25 +- e2e/tests/24_forgotten_passphrase.rs | 13 +- e2e/tests/25_libraries.rs | 55 +- e2e/tests/26_formatting.rs | 67 +- e2e/tests/27_json_explorer.rs | 101 +-- e2e/tests/28_areas.rs | 118 ++- e2e/tests/29_tools.rs | 58 +- e2e/tests/30_http.rs | 358 ++++----- e2e/tests/31_http_environments.rs | 131 ++- e2e/tests/32_http_code.rs | 8 +- e2e/tests/33_calc.rs | 61 +- e2e/tests/34_http_scripts.rs | 87 +- e2e/tests/35_http_runner.rs | 28 +- e2e/tests/36_recette_libraries.rs | 47 +- e2e/tests/37_recette_socle.rs | 261 +++--- e2e/tests/38_recette_notes.rs | 303 +++---- e2e/tests/39_recette_tools.rs | 165 +--- e2e/tests/40_recette_http.rs | 112 +-- e2e/tests/41_note_fullscreen.rs | 94 +-- e2e/tests/43_close_to_tray.rs | 104 +-- e2e/tests/44_window_controls.rs | 17 +- rustfmt.toml | 3 + 689 files changed, 14605 insertions(+), 49704 deletions(-) create mode 100644 .editorconfig create mode 100644 rustfmt.toml diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 000000000..94341586d --- /dev/null +++ b/.editorconfig @@ -0,0 +1,38 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +indent_style = space +indent_size = 2 +insert_final_newline = true +trim_trailing_whitespace = true + +# As `rustfmt.toml` writes it. +[*.rs] +indent_size = 4 +max_line_length = 110 + +[*.{toml,sql,py}] +indent_size = 4 + +# Two spaces at the end of a line break it. +[*.md] +trim_trailing_whitespace = false + +# Compared byte for byte, or kept as published. +[{golden,crates/engine/tests/corpus,crates/engine/sandbox/dist,crates/text/prettier,docs/recette}/**] +charset = unset +end_of_line = unset +indent_size = unset +indent_style = unset +insert_final_newline = unset +trim_trailing_whitespace = unset + +[.claude/skills/{accessibility,core-web-vitals,frontend-design,rust-guidelines,seo,webapp-testing}/**] +charset = unset +end_of_line = unset +indent_size = unset +indent_style = unset +insert_final_newline = unset +trim_trailing_whitespace = unset diff --git a/crates/app/build.rs b/crates/app/build.rs index 8e6f5a095..3e0e32594 100644 --- a/crates/app/build.rs +++ b/crates/app/build.rs @@ -18,8 +18,7 @@ mod windows { if env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") { return; } - let manifest_dir = - env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set by cargo"); + let manifest_dir = env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set by cargo"); let manifest_dir = Path::new(&manifest_dir); let name = product_name(manifest_dir); let icon = manifest_dir.join("icons/icon.ico"); @@ -34,8 +33,7 @@ mod windows { /// The name the packages give the application, `[package.metadata.packager] product-name`; /// the version is the workspace's, which `winresource` reads from Cargo itself. fn product_name(manifest_dir: &Path) -> String { - let text = - fs::read_to_string(manifest_dir.join("Cargo.toml")).expect("Cargo.toml is readable"); + let text = fs::read_to_string(manifest_dir.join("Cargo.toml")).expect("Cargo.toml is readable"); let manifest: toml::Table = toml::from_str(&text).expect("Cargo.toml is valid TOML"); manifest .get("package") diff --git a/crates/app/examples/icons.rs b/crates/app/examples/icons.rs index 9136547be..814204797 100644 --- a/crates/app/examples/icons.rs +++ b/crates/app/examples/icons.rs @@ -17,11 +17,7 @@ fn main() { let icons = Path::new(env!("CARGO_MANIFEST_DIR")).join("icons"); let master = icons.join("devnotes.svg"); for (name, size) in PNGS { - let source = if HINTED.contains(&size) { - hinted(&icons, size) - } else { - master.clone() - }; + let source = if HINTED.contains(&size) { hinted(&icons, size) } else { master.clone() }; write(&icons.join(name), &render(&source, size)); } let entries: Vec<(u32, Vec)> = HINTED @@ -38,21 +34,13 @@ fn hinted(icons: &Path, size: u32) -> PathBuf { /// The drawing at `size` × `size` px, as a PNG. fn render(source: &Path, size: u32) -> Vec { - let data = - std::fs::read(source).unwrap_or_else(|error| panic!("{}: {error}", source.display())); + let data = std::fs::read(source).unwrap_or_else(|error| panic!("{}: {error}", source.display())); let tree = usvg::Tree::from_data(&data, &usvg::Options::default()) .unwrap_or_else(|error| panic!("{}: {error}", source.display())); let mut pixmap = tiny_skia::Pixmap::new(size, size).expect("a non-empty size"); - #[allow( - clippy::cast_precision_loss, - reason = "an icon is a few hundred pixels wide" - )] + #[allow(clippy::cast_precision_loss, reason = "an icon is a few hundred pixels wide")] let scale = size as f32 / tree.size().width().max(tree.size().height()); - resvg::render( - &tree, - tiny_skia::Transform::from_scale(scale, scale), - &mut pixmap.as_mut(), - ); + resvg::render(&tree, tiny_skia::Transform::from_scale(scale, scale), &mut pixmap.as_mut()); pixmap.encode_png().expect("a PNG of a pixmap") } @@ -70,11 +58,7 @@ fn ico(entries: &[(u32, Vec)]) -> Vec { header.extend_from_slice(&[side, side, 0, 0]); header.extend_from_slice(&1u16.to_le_bytes()); header.extend_from_slice(&32u16.to_le_bytes()); - header.extend_from_slice( - &u32::try_from(data.len()) - .expect("a small PNG") - .to_le_bytes(), - ); + header.extend_from_slice(&u32::try_from(data.len()).expect("a small PNG").to_le_bytes()); header.extend_from_slice(&u32::try_from(offset).expect("a small file").to_le_bytes()); offset += data.len(); } diff --git a/crates/app/examples/tours.rs b/crates/app/examples/tours.rs index 7cd776ca3..e23c5dee0 100644 --- a/crates/app/examples/tours.rs +++ b/crates/app/examples/tours.rs @@ -54,14 +54,7 @@ const TOURS: [(&str, &[&str]); 3] = [ ), ( "http", - &[ - "http-home", - "http-request", - "http-graphql", - "http-websocket", - "http-environments", - "http-code", - ], + &["http-home", "http-request", "http-graphql", "http-websocket", "http-environments", "http-code"], ), ]; @@ -99,14 +92,10 @@ fn write(path: &Path, frames: &[RgbaImage]) { for frame in frames { let mut reduced = frame.clone(); for pixel in reduced.pixels_mut() { - *pixel = *nearest - .entry(*pixel) - .or_insert_with(|| closest(&palette, *pixel)); + *pixel = *nearest.entry(*pixel).or_insert_with(|| closest(&palette, *pixel)); } let delay = Delay::from_saturating_duration(SHOWN); - encoder - .encode_frame(Frame::from_parts(reduced, 0, 0, delay)) - .expect("a frame"); + encoder.encode_frame(Frame::from_parts(reduced, 0, 0, delay)).expect("a frame"); } } diff --git a/crates/app/src/arguments.rs b/crates/app/src/arguments.rs index 3498d80ac..64bf68574 100644 --- a/crates/app/src/arguments.rs +++ b/crates/app/src/arguments.rs @@ -36,10 +36,7 @@ mod tests { #[test] fn a_profile_directory_is_read_after_its_flag() { - assert_eq!( - of(&["--profile", "/tmp/run-1"]).profile, - Some(PathBuf::from("/tmp/run-1")) - ); + assert_eq!(of(&["--profile", "/tmp/run-1"]).profile, Some(PathBuf::from("/tmp/run-1"))); } #[test] @@ -50,32 +47,17 @@ mod tests { #[test] fn an_action_is_read_after_its_flag() { - assert_eq!( - of(&["--action", "palette"]).action, - Some("palette".to_string()) - ); + assert_eq!(of(&["--action", "palette"]).action, Some("palette".to_string())); } #[test] fn an_unknown_argument_is_left_alone() { - assert_eq!( - of(&["--minimized", "--profile", "p"]).profile, - Some(PathBuf::from("p")) - ); + assert_eq!(of(&["--minimized", "--profile", "p"]).profile, Some(PathBuf::from("p"))); } #[test] fn both_are_read_in_any_order_and_the_last_of_each_wins() { - let read = of(&[ - "--action", - "quit", - "--profile", - "a", - "--profile", - "b", - "--action", - "palette", - ]); + let read = of(&["--action", "quit", "--profile", "a", "--profile", "b", "--action", "palette"]); assert_eq!(read.profile, Some(PathBuf::from("b"))); assert_eq!(read.action.as_deref(), Some("palette")); diff --git a/crates/app/src/desktop.rs b/crates/app/src/desktop.rs index 85dc6668c..b06ffc46d 100644 --- a/crates/app/src/desktop.rs +++ b/crates/app/src/desktop.rs @@ -46,19 +46,11 @@ fn start_tray(preferences: &Preferences, inbox: Inbox) -> Box { let Ok(icon) = eframe::icon_data::from_png_bytes(include_bytes!("../icons/32x32.png")) else { return Box::new(NoTray); }; - let picture = Picture { - rgba: icon.rgba, - width: icon.width, - height: icon.height, - }; + let picture = Picture { rgba: icon.rgba, width: icon.width, height: icon.height }; let language = Settings::read(preferences).locale.language(); - platform::tray::system( - picture, - &ui::services::tray::labels(language), - move |asked| { - inbox.post(ui::inputs::Input::Tray(asked)); - }, - ) + platform::tray::system(picture, &ui::services::tray::labels(language), move |asked| { + inbox.post(ui::inputs::Input::Tray(asked)); + }) } /// Named in the language of the launch where a Wayland desktop lists them. diff --git a/crates/app/src/logging.rs b/crates/app/src/logging.rs index 705fd8060..276635cb1 100644 --- a/crates/app/src/logging.rs +++ b/crates/app/src/logging.rs @@ -24,11 +24,7 @@ pub(crate) fn start(directory: &Path) -> Option { logger .log_to_file(file) .append() - .rotate( - Criterion::Size(5_000_000), - Naming::Numbers, - Cleanup::KeepLogFiles(3), - ) + .rotate(Criterion::Size(5_000_000), Naming::Numbers, Cleanup::KeepLogFiles(3)) .duplicate_to_stderr(Duplicate::Error) .start() }) @@ -74,11 +70,7 @@ fn notice(language: i18n::Language, logs: &Path) -> (String, String) { let app = || Value::from(engine::app_info::METADATA.name.to_owned()); let title = i18n::translate(language, keys::crash::TITLE, &[("app", app())]); let folder = Value::from(logs.display().to_string()); - let words = i18n::translate( - language, - keys::crash::BODY, - &[("app", app()), ("folder", folder)], - ); + let words = i18n::translate(language, keys::crash::BODY, &[("app", app()), ("folder", folder)]); (title, words) } @@ -87,12 +79,7 @@ fn report(info: &PanicHookInfo<'_>) -> String { let thread = std::thread::current(); let name = thread.name().unwrap_or("unnamed"); match info.location() { - Some(at) => format!( - "Panicked at {}:{}:{} on thread {name}", - at.file(), - at.line(), - at.column() - ), + Some(at) => format!("Panicked at {}:{}:{} on thread {name}", at.file(), at.line(), at.column()), None => format!("Panicked on thread {name}"), } } @@ -182,9 +169,7 @@ mod tests { logger(); let profile = tempfile::tempdir().unwrap(); let runtime = tokio::runtime::Runtime::new().unwrap(); - let paths = engine::Paths { - profile: profile.path().to_path_buf(), - }; + let paths = engine::Paths { profile: profile.path().to_path_buf() }; let sink = Arc::new(engine::RecordingSink::default()); let closed = engine::Engine::new(paths, sink, runtime.handle().clone()); let patch = NotePatch { @@ -193,9 +178,8 @@ mod tests { ..Default::default() }; - let failed = engine::db::run_here(&closed, |engine| { - engine::notes::update_note(engine, "note-id", &patch) - }); + let failed = + engine::db::run_here(&closed, |engine| engine::notes::update_note(engine, "note-id", &patch)); ui::services::errors::ErrorNotifier::default() .report(i18n::keys::errors::NOTE_GONE, &failed.unwrap_err()); @@ -210,14 +194,10 @@ mod tests { logger(); let profile = tempfile::tempdir().unwrap(); let runtime = tokio::runtime::Runtime::new().unwrap(); - let paths = engine::Paths { - profile: profile.path().to_path_buf(), - }; + let paths = engine::Paths { profile: profile.path().to_path_buf() }; let sink = Arc::new(engine::RecordingSink::default()); let engine = engine::Engine::new(paths, sink, runtime.handle().clone()); - let draft = || engine::spaces::model::SpaceDraft { - name: "Clients Dupont-Aignan".to_owned(), - }; + let draft = || engine::spaces::model::SpaceDraft { name: "Clients Dupont-Aignan".to_owned() }; let duplicate = engine::db::run_here(&engine, |engine| { let phrase = engine::vault::secret("correct horse battery staple".to_owned()); engine::vault::create_vault(engine, phrase)?; @@ -275,10 +255,7 @@ mod tests { assert!(title.contains(engine::app_info::METADATA.name), "{title}"); assert!(words.contains("C:/profil/logs"), "{words}"); assert_ne!(words, english); - assert!( - !words.contains("{{") && !english.contains("{{"), - "{words} {english}" - ); + assert!(!words.contains("{{") && !english.contains("{{"), "{words} {english}"); } /// Where the process that panics for the test below writes its log. @@ -295,10 +272,7 @@ mod tests { let directory = tempfile::tempdir().unwrap(); let ended = std::process::Command::new(std::env::current_exe().unwrap()) - .args([ - "--exact", - "logging::tests::a_panic_ends_the_process_once_its_place_is_in_the_log", - ]) + .args(["--exact", "logging::tests::a_panic_ends_the_process_once_its_place_is_in_the_log"]) .env(PANIC_IN, directory.path()) .output() .unwrap(); diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 782050d68..fa9ddfd81 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -34,10 +34,7 @@ fn main() -> ExitCode { // First, for the script host too: it logs nothing there, and exits the same. logging::install_panic_hook(); // A script host opens no window and writes no log. - if std::env::args_os() - .nth(1) - .is_some_and(|arg| arg == engine::SCRIPT_HOST_ARG) - { + if std::env::args_os().nth(1).is_some_and(|arg| arg == engine::SCRIPT_HOST_ARG) { std::process::exit(engine::serve_scripts()); } @@ -81,9 +78,8 @@ fn main() -> ExitCode { #[cfg(target_os = "linux")] fn missing_library() -> Option<&'static str> { let x11 = std::env::var_os("DISPLAY").is_some(); - (x11 && xkbcommon_dl::x11::xkbcommon_x11_option().is_none()).then_some( - "libxkbcommon-x11 (libxkbcommon-x11-0 on Debian and Ubuntu, libxkbcommon-x11 on Fedora)", - ) + (x11 && xkbcommon_dl::x11::xkbcommon_x11_option().is_none()) + .then_some("libxkbcommon-x11 (libxkbcommon-x11-0 on Debian and Ubuntu, libxkbcommon-x11 on Fedora)") } #[cfg(not(target_os = "linux"))] @@ -98,9 +94,9 @@ fn not_opened(error: &eframe::Error) -> String { use eframe::egui_wgpu::WgpuError; match error { - eframe::Error::Wgpu( - WgpuError::CreateSurfaceError(_) | WgpuError::RequestAdapterError(_), - ) if cfg!(target_os = "linux") => { + eframe::Error::Wgpu(WgpuError::CreateSurfaceError(_) | WgpuError::RequestAdapterError(_)) + if cfg!(target_os = "linux") => + { format!( "The window did not open: no graphics driver answered, neither Vulkan nor OpenGL \ ({error}). Install your graphics card's drivers, or Mesa's: mesa-vulkan-drivers \ @@ -127,23 +123,17 @@ fn hand_over(profile: &Path, action: Option) -> ExitCode { fn run(locations: Locations, instance: Instance) -> eframe::Result { let restored = platform::window::read(&locations.window); let preferences = Preferences::read(&locations.profile.join(engine::layout::PREFERENCES)); - let language = ui::services::settings::Settings::read(&preferences) - .locale - .language(); + let language = ui::services::settings::Settings::read(&preferences).locale.language(); logging::tell_when_stopped(language, &locations.logs); let (inbox, waker, inputs) = ui::inputs::channel(); let heard = inbox.clone(); - if let Err(error) = - instance.serve(move |message| heard.post(ui::inputs::Input::Instance(message))) - { + if let Err(error) = instance.serve(move |message| heard.post(ui::inputs::Input::Instance(message))) { log::warn!("Second launches will not be heard: {error}"); } // ⚠️ Called with the event loop running: macOS makes no tray icon before. let startup = move || ui::Startup { desktop: desktop::start(&preferences, &inbox), - paths: engine::Paths { - profile: locations.profile, - }, + paths: engine::Paths { profile: locations.profile }, window_file: locations.window, geometry: restored, reduced_motion: platform::motion::system_prefers_reduced(), @@ -264,22 +254,14 @@ mod tests { panic!("the profile was taken"); }; let (heard, hearing) = mpsc::channel(); - first - .serve(move |message| heard.send(message).unwrap()) - .unwrap(); + first.serve(move |message| heard.send(message).unwrap()).unwrap(); assert_eq!(hand_over(profile.path(), None), ExitCode::SUCCESS); - assert_eq!( - hand_over(profile.path(), Some("palette".to_string())), - ExitCode::SUCCESS - ); + assert_eq!(hand_over(profile.path(), Some("palette".to_string())), ExitCode::SUCCESS); let wait = Duration::from_secs(10); assert_eq!(hearing.recv_timeout(wait).unwrap(), Message::Reveal); - assert_eq!( - hearing.recv_timeout(wait).unwrap(), - Message::Action("palette".to_string()) - ); + assert_eq!(hearing.recv_timeout(wait).unwrap(), Message::Action("palette".to_string())); } #[test] @@ -297,21 +279,14 @@ mod tests { let said = not_opened(&no_adapter); - assert_eq!( - said.contains("neither Vulkan nor OpenGL"), - cfg!(target_os = "linux") - ); - assert_eq!( - said.contains("mesa-vulkan-drivers"), - cfg!(target_os = "linux") - ); + assert_eq!(said.contains("neither Vulkan nor OpenGL"), cfg!(target_os = "linux")); + assert_eq!(said.contains("mesa-vulkan-drivers"), cfg!(target_os = "linux")); assert!(!said.contains('\n'), "{said}"); } #[test] fn another_renderer_error_is_said_as_it_is() { - let no_format = - eframe::Error::Wgpu(eframe::egui_wgpu::WgpuError::NoSurfaceFormatsAvailable); + let no_format = eframe::Error::Wgpu(eframe::egui_wgpu::WgpuError::NoSurfaceFormatsAvailable); let said = not_opened(&no_format); @@ -324,14 +299,8 @@ mod tests { let options = options(None); assert_eq!(options.viewport.visible, Some(false)); - assert_eq!( - options.viewport.inner_size, - Some(egui::vec2(1_100.0, 720.0)) - ); - assert_eq!( - options.viewport.min_inner_size, - Some(egui::vec2(640.0, 480.0)) - ); + assert_eq!(options.viewport.inner_size, Some(egui::vec2(1_100.0, 720.0))); + assert_eq!(options.viewport.min_inner_size, Some(egui::vec2(640.0, 480.0))); assert!(options.viewport.icon.is_some()); assert!(options.centered); assert!(!options.persist_window); @@ -339,13 +308,8 @@ mod tests { #[test] fn a_later_launch_opens_where_the_window_was() { - let options = options(Some(Geometry { - x: 40.0, - y: 30.0, - width: 900.0, - height: 600.0, - maximized: true, - })); + let options = + options(Some(Geometry { x: 40.0, y: 30.0, width: 900.0, height: 600.0, maximized: true })); assert_eq!(options.viewport.visible, Some(false)); assert_eq!(options.viewport.inner_size, Some(egui::vec2(900.0, 600.0))); diff --git a/crates/app/src/renderer.rs b/crates/app/src/renderer.rs index c2aeb3dc5..ca27ac774 100644 --- a/crates/app/src/renderer.rs +++ b/crates/app/src/renderer.rs @@ -15,9 +15,8 @@ pub(crate) fn options() -> WgpuConfiguration { } let mut setup = WgpuSetupCreateNew::without_display_handle(); setup.native_adapter_selector = Some(std::sync::Arc::new(|adapters, surface| { - let draws_here = |adapter: &&wgpu::Adapter| { - surface.is_none_or(|surface| adapter.is_surface_supported(surface)) - }; + let draws_here = + |adapter: &&wgpu::Adapter| surface.is_none_or(|surface| adapter.is_surface_supported(surface)); adapters .iter() .filter(draws_here) @@ -26,10 +25,7 @@ pub(crate) fn options() -> WgpuConfiguration { .cloned() .ok_or_else(|| "no adapter draws on this window".to_string()) })); - WgpuConfiguration { - wgpu_setup: WgpuSetup::CreateNew(setup), - ..Default::default() - } + WgpuConfiguration { wgpu_setup: WgpuSetup::CreateNew(setup), ..Default::default() } } #[cfg(not(feature = "e2e"))] @@ -40,10 +36,7 @@ pub(crate) fn options() -> WgpuConfiguration { } let device = std::sync::Arc::clone(&setup.device_descriptor); setup.device_descriptor = std::sync::Arc::new(move |adapter| sparing(device(adapter))); - WgpuConfiguration { - wgpu_setup: WgpuSetup::CreateNew(setup), - ..Default::default() - } + WgpuConfiguration { wgpu_setup: WgpuSetup::CreateNew(setup), ..Default::default() } } /// The one API to open, or `None` for eframe's choice: `WGPU_BACKEND` when it is set, and every @@ -109,10 +102,7 @@ mod tests { fn the_device_is_asked_to_reserve_memory_by_small_blocks() { let device = sparing(wgpu::DeviceDescriptor::default()); - assert!(matches!( - device.memory_hints, - wgpu::MemoryHints::MemoryUsage - )); + assert!(matches!(device.memory_hints, wgpu::MemoryHints::MemoryUsage)); } #[test] diff --git a/crates/app/src/sight.rs b/crates/app/src/sight.rs index 2c5e9da36..030dca0ea 100644 --- a/crates/app/src/sight.rs +++ b/crates/app/src/sight.rs @@ -19,12 +19,7 @@ pub(crate) struct Watched { impl Watched { pub(crate) fn new(app: ui::DevNotesApp) -> Self { - Watched { - app, - hidden: false, - put_away: 0, - read: 0, - } + Watched { app, hidden: false, put_away: 0, read: 0 } } fn follow(&mut self, ctx: &Context) { @@ -55,11 +50,7 @@ impl eframe::App for Watched { fn ui(&mut self, ui: &mut Ui, frame: &mut eframe::Frame) { self.app.ui(ui, frame); self.follow(ui.ctx()); - let said = if self.hidden { - "window-hidden" - } else { - "window-shown" - }; + let said = if self.hidden { "window-hidden" } else { "window-shown" }; mark(ui, said, said); mark(ui, "window-put-away", &self.put_away.to_string()); } diff --git a/crates/app/src/unpainted.rs b/crates/app/src/unpainted.rs index 9a1316284..7a1011669 100644 --- a/crates/app/src/unpainted.rs +++ b/crates/app/src/unpainted.rs @@ -32,12 +32,9 @@ impl egui::Plugin for Unpainted { } fn asks_for_capture(output: &FullOutput) -> bool { - output - .viewport_output - .get(&ViewportId::ROOT) - .is_some_and(|root| { - root.commands - .iter() - .any(|command| matches!(command, ViewportCommand::Screenshot(_))) - }) + output.viewport_output.get(&ViewportId::ROOT).is_some_and(|root| { + root.commands + .iter() + .any(|command| matches!(command, ViewportCommand::Screenshot(_))) + }) } diff --git a/crates/app/tests/windows_resources.rs b/crates/app/tests/windows_resources.rs index 5f9d37b22..a91f846f0 100644 --- a/crates/app/tests/windows_resources.rs +++ b/crates/app/tests/windows_resources.rs @@ -42,7 +42,5 @@ fn resource_types(file: &[u8]) -> Vec { let named = u16_at(root + 12); let numbered = u16_at(root + 14); - (named..named + numbered) - .map(|entry| u32_at(root + 16 + 8 * entry)) - .collect() + (named..named + numbered).map(|entry| u32_at(root + 16 + 8 * entry)).collect() } diff --git a/crates/drawing/src/edit.rs b/crates/drawing/src/edit.rs index 18ac5dbca..ef2de9e7a 100644 --- a/crates/drawing/src/edit.rs +++ b/crates/drawing/src/edit.rs @@ -103,10 +103,7 @@ impl Frame { /// A point of the frame's own plane, in the scene's. fn on_scene(&self, x: f64, y: f64) -> Point { let (sin, cos) = self.angle.to_radians().sin_cos(); - Point { - x: self.centre.x + x * cos - y * sin, - y: self.centre.y + x * sin + y * cos, - } + Point { x: self.centre.x + x * cos - y * sin, y: self.centre.y + x * sin + y * cos } } fn on_frame(&self, at: Point) -> (f64, f64) { @@ -117,11 +114,7 @@ impl Frame { pub fn grip(&self, grip: Grip) -> Point { let (x, y) = grip.place(); - let reach = if grip == Grip::Rotate { - self.reach - } else { - 0.0 - }; + let reach = if grip == Grip::Rotate { self.reach } else { 0.0 }; self.on_scene(x * self.width / 2.0, y * self.height / 2.0 - reach) } @@ -136,13 +129,7 @@ impl Frame { } pub fn corners(&self) -> [Point; 4] { - [ - Grip::TopLeft, - Grip::TopRight, - Grip::BottomRight, - Grip::BottomLeft, - ] - .map(|corner| self.grip(corner)) + [Grip::TopLeft, Grip::TopRight, Grip::BottomRight, Grip::BottomLeft].map(|corner| self.grip(corner)) } } @@ -416,10 +403,7 @@ impl Editor { let mut step = 1.0; while step <= steps { let part = step / steps; - let at = Point { - x: from.x + (to.x - from.x) * part, - y: from.y + (to.y - from.y) * part, - }; + let at = Point { x: from.x + (to.x - from.x) * part, y: from.y + (to.y - from.y) * part }; let come_onto = |object: &Object| object.contains(at) && !object.contains(last); let gone: Vec = (0..self.drawing.objects.len()) .filter(|&index| come_onto(&self.drawing.objects[index])) @@ -498,17 +482,13 @@ impl Editor { let reach = GRIP_REACH / self.scale; let near = |end: Point| (end.x - at.x).abs() <= reach && (end.y - at.y).abs() <= reach; let ends = self.arrow_ends()?; - ends.into_iter() - .find(|(_, place)| near(*place)) - .map(|(end, _)| end) + ends.into_iter().find(|(_, place)| near(*place)).map(|(end, _)| end) } /// Asked while the arrow tool is in hand or an end is dragged. pub fn attaching(&self, at: Point) -> Option { let kept = match &self.gesture { - Some(Gesture::MovingEnd { index, end, .. }) => { - end.other_bound(&self.drawing.objects[*index]) - } + Some(Gesture::MovingEnd { index, end, .. }) => end.other_bound(&self.drawing.objects[*index]), Some(Gesture::Arrow { held, .. }) => held.as_ref().map(|hold| hold.id.as_str()), None if self.tool == Tool::Arrow => None, _ => return None, @@ -588,10 +568,7 @@ impl Editor { /// The topmost object under a point. fn object_at(&self, at: Point) -> Option { - self.drawing - .objects - .iter() - .rposition(|object| object.contains(at)) + self.drawing.objects.iter().rposition(|object| object.contains(at)) } /// A pointer pressed. `adding` is Shift: an object joins the selection or leaves it. @@ -634,11 +611,7 @@ impl Editor { && let Some(end) = self.end_at(at) && let [index] = self.selected[..] { - self.gesture = Some(Gesture::MovingEnd { - index, - end, - from: at, - }); + self.gesture = Some(Gesture::MovingEnd { index, end, from: at }); return; } if let Some(grip) = self.grip_at(at).filter(|_| !adding) @@ -646,17 +619,9 @@ impl Editor { { let before = self.selection(); self.gesture = Some(if grip == Grip::Rotate { - Gesture::Rotating { - frame, - from: bearing(frame.centre, at), - before, - } + Gesture::Rotating { frame, from: bearing(frame.centre, at), before } } else { - Gesture::Scaling { - grip, - frame, - before, - } + Gesture::Scaling { grip, frame, before } }); return; } @@ -679,11 +644,7 @@ impl Editor { self.selected = vec![index]; } let before = self.selection(); - self.gesture = Some(Gesture::Moving { - from: at, - before, - reselected, - }); + self.gesture = Some(Gesture::Moving { from: at, before, reselected }); } fn selection(&self) -> Selected { @@ -720,16 +681,8 @@ impl Editor { move_to(self, before, *from, to); } } - Gesture::Scaling { - grip, - frame, - before, - } => scale_to(self, before, *grip, *frame, to), - Gesture::Rotating { - frame, - from, - before, - } => { + Gesture::Scaling { grip, frame, before } => scale_to(self, before, *grip, *frame, to), + Gesture::Rotating { frame, from, before } => { rotate_to(self, before, *frame, bearing(frame.centre, to) - *from); } Gesture::Marquee { to: end, .. } => *end = to, @@ -747,16 +700,7 @@ impl Editor { let least = CLICKED / self.scale; let clicked = dragged.width < least && dragged.height < least; let (width, height) = CLICK_SIZE; - let bounds = if clicked { - Box { - left: from.x, - top: from.y, - width, - height, - } - } else { - dragged - }; + let bounds = if clicked { Box { left: from.x, top: from.y, width, height } } else { dragged }; self.reshape_last(tool, bounds); self.finish(); } @@ -766,9 +710,7 @@ impl Editor { return; }; let kept = held.map(|hold| hold.id); - let hold = self - .hold_at(at) - .filter(|hold| Some(&hold.id) != kept.as_ref()); + let hold = self.hold_at(at).filter(|hold| Some(&hold.id) != kept.as_ref()); End::To.hold(&mut arrow, hold.as_ref()); self.drawing.objects.push(arrow); let last = self.drawing.objects.len() - 1; @@ -780,16 +722,12 @@ impl Editor { Some(Gesture::MovingEnd { from, .. }) if from == at => {} Some(Gesture::MovingEnd { index, end, .. }) => { let kept = end.other_bound(&self.drawing.objects[index]); - let hold = self - .hold_at(at) - .filter(|hold| Some(hold.id.as_str()) != kept); + let hold = self.hold_at(at).filter(|hold| Some(hold.id.as_str()) != kept); self.move_end(index, end, hold.as_ref(), at); self.keep(); } Some(Gesture::Marquee { from, to }) => self.select_within(drag_box(from, to)), - Some(Gesture::Moving { - from, reselected, .. - }) => { + Some(Gesture::Moving { from, reselected, .. }) => { if from != at { self.settle(); } else if reselected { @@ -834,12 +772,7 @@ impl Editor { let Some(index) = self.editing.take() else { return; }; - if self.drawing.objects[index] - .text() - .unwrap_or_default() - .trim() - .is_empty() - { + if self.drawing.objects[index].text().unwrap_or_default().trim().is_empty() { self.drawing.objects.remove(index); self.selected.clear(); } @@ -881,10 +814,7 @@ impl Editor { text.put("fontFamily", TEXT_FONT); text.put_number("strokeWidth", 0.0); text.set_size(TEXT_WIDTH, text_height(1, TEXT_SIZE, text.line_height())); - text.set_centre(Point { - x: at.x + TEXT_WIDTH / 2.0, - y: at.y, - }); + text.set_centre(Point { x: at.x + TEXT_WIDTH / 2.0, y: at.y }); self.drawing.objects.push(text); self.tool = Tool::Select; self.kept.clear(); @@ -918,18 +848,13 @@ impl Editor { } fn select_within(&mut self, marquee: Box) { - let touched = self - .drawing - .objects - .iter() - .enumerate() - .filter(|(_, object)| { - let bounds = object.bounds(); - bounds.left < marquee.left + marquee.width - && marquee.left < bounds.left + bounds.width - && bounds.top < marquee.top + marquee.height - && marquee.top < bounds.top + bounds.height - }); + let touched = self.drawing.objects.iter().enumerate().filter(|(_, object)| { + let bounds = object.bounds(); + bounds.left < marquee.left + marquee.width + && marquee.left < bounds.left + bounds.width + && bounds.top < marquee.top + marquee.height + && marquee.top < bounds.top + bounds.height + }); let touched: Vec = touched.map(|(index, _)| index).collect(); if marquee.width > 0.0 || marquee.height > 0.0 { for index in touched { @@ -945,12 +870,10 @@ impl Editor { /// it: a shape does, under the text or the arrow over it. fn holder_at(&self, at: Point) -> Option<(usize, Option)> { let objects = self.drawing.objects.iter().enumerate().rev(); - objects - .filter(|(_, object)| holds_arrows(object)) - .find_map(|(index, object)| { - let side = self.side_at(object, at); - (side.is_some() || object.contains(at)).then_some((index, side)) - }) + objects.filter(|(_, object)| holds_arrows(object)).find_map(|(index, object)| { + let side = self.side_at(object, at); + (side.is_some() || object.contains(at)).then_some((index, side)) + }) } fn side_at(&self, object: &Object, at: Point) -> Option { @@ -992,10 +915,7 @@ impl Editor { let arrow = &self.drawing.objects[index]; let from = self.held_by(arrow, End::From); let to = self.held_by(arrow, End::To); - set_arrow( - &mut self.drawing.objects[index], - bound_ends(drawn, from.as_ref(), to.as_ref()), - ); + set_arrow(&mut self.drawing.objects[index], bound_ends(drawn, from.as_ref(), to.as_ref())); } /// The arrows bound to anything take their place from it. @@ -1060,10 +980,7 @@ fn move_to(editor: &mut Editor, before: &Selected, from: Point, to: Point) { for (index, object) in before { let centre = object.centre(); let moved = &mut editor.drawing.objects[*index]; - moved.set_centre(Point { - x: centre.x + dx, - y: centre.y + dy, - }); + moved.set_centre(Point { x: centre.x + dx, y: centre.y + dy }); if let Some([x1, y1, x2, y2]) = object.ends() { moved.set_ends([x1 + dx, y1 + dy, x2 + dx, y2 + dy]); } @@ -1077,11 +994,7 @@ fn scale_to(editor: &mut Editor, before: &Selected, grip: Grip, frame: Frame, to // From the handle's opposite, which stays where it is. let anchor = (-place_x * frame.width / 2.0, -place_y * frame.height / 2.0); let along = |place: f64, size: f64, at: f64, from: f64| { - if place == 0.0 { - 1.0 - } else { - ((at - from) * place / size).max(LEAST_SCALE) - } + if place == 0.0 { 1.0 } else { ((at - from) * place / size).max(LEAST_SCALE) } }; let mut scale_x = along(place_x, frame.width, x, anchor.0); let mut scale_y = along(place_y, frame.height, y, anchor.1); @@ -1092,20 +1005,13 @@ fn scale_to(editor: &mut Editor, before: &Selected, grip: Grip, frame: Frame, to } for (index, object) in before { let (cx, cy) = frame.on_frame(object.centre()); - let centre = frame.on_scene( - anchor.0 + (cx - anchor.0) * scale_x, - anchor.1 + (cy - anchor.1) * scale_y, - ); + let centre = + frame.on_scene(anchor.0 + (cx - anchor.0) * scale_x, anchor.1 + (cy - anchor.1) * scale_y); let scaled = &mut editor.drawing.objects[*index]; scaled.set_centre(centre); if object.kind() == Kind::Textbox && place_y == 0.0 { let width = (object.width() * scale_x).max(TEXT_MIN_WIDTH); - let lines = wrap( - object.text().unwrap_or_default(), - width, - object.font_size(), - &editor.fonts, - ); + let lines = wrap(object.text().unwrap_or_default(), width, object.font_size(), &editor.fonts); let height = text_height(lines.len(), object.font_size(), object.line_height()); scaled.set_size(width, height); } else { @@ -1116,14 +1022,8 @@ fn scale_to(editor: &mut Editor, before: &Selected, grip: Grip, frame: Frame, to } fn rotate_to(editor: &mut Editor, before: &Selected, frame: Frame, degrees: f64) { - let turned = Frame { - angle: degrees, - ..frame - }; - let still = Frame { - angle: 0.0, - ..frame - }; + let turned = Frame { angle: degrees, ..frame }; + let still = Frame { angle: 0.0, ..frame }; for (index, object) in before { let (x, y) = still.on_frame(object.centre()); let rotated = &mut editor.drawing.objects[*index]; diff --git a/crates/drawing/src/edit/tests.rs b/crates/drawing/src/edit/tests.rs index 9e00068be..ec51012a6 100644 --- a/crates/drawing/src/edit/tests.rs +++ b/crates/drawing/src/edit/tests.rs @@ -71,11 +71,7 @@ fn a_new_drawing_is_written_as_a_scene_read_back() { let read = Drawing::read(&editor.body()).unwrap(); assert_eq!(read.objects.len(), 1); - assert!( - editor - .body() - .starts_with(r#"{"version":1,"scene":{"version":"7.4.0""#) - ); + assert!(editor.body().starts_with(r#"{"version":1,"scene":{"version":"7.4.0""#)); } #[test] @@ -256,10 +252,7 @@ fn a_text_is_typed_where_clicked_its_left_edge_there() { assert_eq!(editor.tool(), Tool::Select); assert_eq!(text.centre(), at(100.0, 20.0)); - assert_eq!( - (text.text(), text.font_size(), text.stroke_width()), - (Some(""), 18.0, 0.0) - ); + assert_eq!((text.text(), text.font_size(), text.stroke_width()), (Some(""), 18.0, 0.0)); assert_eq!(text.font_family(), "Inter Variable, sans-serif"); assert!(editor.editing().is_some_and(|(index, _)| index == 0)); assert_eq!(editor.frame(), None, "typed into, it has no handles"); @@ -430,10 +423,7 @@ fn a_marquee_is_shown_while_it_is_dragged() { editor.drag(at(50.0, 300.0)); let shown = editor.marquee().unwrap(); - assert_eq!( - (shown.left, shown.top, shown.width, shown.height), - (50.0, 250.0, 70.0, 50.0) - ); + assert_eq!((shown.left, shown.top, shown.width, shown.height), (50.0, 250.0, 70.0, 50.0)); editor.release(at(50.0, 300.0)); assert_eq!(editor.marquee(), None); } @@ -491,11 +481,7 @@ fn a_corner_keeps_the_proportions_from_the_opposite_corner() { let corner = frame.grip(Grip::BottomRight); let anchor = frame.grip(Grip::TopLeft); - drag( - &mut editor, - corner, - at(anchor.x + frame.width * 2.0, anchor.y + frame.height * 2.0), - ); + drag(&mut editor, corner, at(anchor.x + frame.width * 2.0, anchor.y + frame.height * 2.0)); let shape = object(&editor, 0); assert_eq!((shape.scale_x(), shape.scale_y()), (2.0, 2.0)); @@ -587,11 +573,7 @@ fn a_text_is_scaled_by_its_corners() { let frame = editor.frame().unwrap(); let corner = frame.grip(Grip::BottomRight); - drag( - &mut editor, - corner, - at(corner.x + frame.width, corner.y + frame.height), - ); + drag(&mut editor, corner, at(corner.x + frame.width, corner.y + frame.height)); assert_eq!(object(&editor, 0).scale_x(), 2.0); assert_eq!(object(&editor, 0).width(), 180.0); @@ -602,11 +584,7 @@ fn the_rotation_handle_turns_around_the_centre() { let mut editor = with_a_rectangle(); let frame = editor.frame().unwrap(); - drag( - &mut editor, - frame.grip(Grip::Rotate), - at(frame.centre.x + 100.0, frame.centre.y), - ); + drag(&mut editor, frame.grip(Grip::Rotate), at(frame.centre.x + 100.0, frame.centre.y)); assert_eq!(object(&editor, 0).angle(), 90.0); assert_eq!(object(&editor, 0).centre(), frame.centre); @@ -621,11 +599,7 @@ fn several_objects_turn_around_their_frame() { editor.release(at(150.0, 130.0)); let frame = editor.frame().unwrap(); - drag( - &mut editor, - frame.grip(Grip::Rotate), - at(frame.centre.x, frame.centre.y + 100.0), - ); + drag(&mut editor, frame.grip(Grip::Rotate), at(frame.centre.x, frame.centre.y + 100.0)); assert_eq!(object(&editor, 0).angle(), 180.0); assert!(object(&editor, 0).centre().x > object(&editor, 1).centre().x); @@ -734,11 +708,7 @@ fn the_history_keeps_sixty_states() { let mut editor = with_a_rectangle(); for step in 0..70 { let from = object(&editor, 0).centre(); - drag( - &mut editor, - from, - at(from.x + 1.0, from.y + f64::from(step % 2)), - ); + drag(&mut editor, from, at(from.x + 1.0, from.y + f64::from(step % 2))); } let mut back = 0; @@ -772,10 +742,7 @@ fn a_click_leaves_an_arrow_where_it_stands_until_its_shape_moves() { let mut editor = Editor::open(body, Arc::new(fonts())); drag(&mut editor, at(100.0, 100.0), at(100.0, 100.0)); - assert_eq!( - object(&editor, 1).ends(), - Some([300.0, 100.0, 400.0, 100.0]) - ); + assert_eq!(object(&editor, 1).ends(), Some([300.0, 100.0, 400.0, 100.0])); drag(&mut editor, at(100.0, 100.0), at(100.0, 110.0)); assert_ne!(object(&editor, 1).ends().unwrap()[0], 300.0); @@ -994,10 +961,7 @@ fn the_shape_an_end_would_hold_is_told_while_an_arrow_is_drawn_or_an_end_moved() editor.set_tool(Tool::Arrow); assert!(editor.attaching(on_the_second).is_some()); editor.press(at(50.0, 30.0), false); - assert!( - editor.attaching(at(60.0, 30.0)).is_none(), - "not the one it starts on" - ); + assert!(editor.attaching(at(60.0, 30.0)).is_none(), "not the one it starts on"); editor.release(at(200.0, 200.0)); let end = editor.arrow_ends().unwrap()[1].1; @@ -1029,27 +993,15 @@ fn an_arrow_follows_a_shape_resized_and_rotated() { drag(&mut editor, at(350.0, 30.0), at(350.0, 30.0)); // Its left side pulled 50 to the left. drag(&mut editor, at(299.0, 30.0), at(249.0, 30.0)); - assert!( - (ends(&editor)[2] - 249.0).abs() < 1.0, - "{:?}", - ends(&editor) - ); + assert!((ends(&editor)[2] - 249.0).abs() < 1.0, "{:?}", ends(&editor)); let mut editor = joined(); drag(&mut editor, at(350.0, 30.0), at(350.0, 30.0)); let frame = editor.frame().unwrap(); let handle = frame.grip(Grip::Rotate); - drag( - &mut editor, - handle, - at(frame.centre.x + 200.0, frame.centre.y), - ); + drag(&mut editor, handle, at(frame.centre.x + 200.0, frame.centre.y)); // Turned a quarter, it is 62 wide: its left side came closer to its centre. - assert!( - (ends(&editor)[2] - 319.0).abs() < 1.5, - "{:?}", - ends(&editor) - ); + assert!((ends(&editor)[2] - 319.0).abs() < 1.5, "{:?}", ends(&editor)); } #[test] @@ -1057,11 +1009,7 @@ fn an_end_let_go_on_the_middle_of_a_side_stays_on_it() { let mut editor = joined(); drag(&mut editor, at(299.0, 30.0), at(352.0, 64.0)); assert_eq!(object(&editor, 2).to(), object(&editor, 1).id()); - assert_eq!( - ends(&editor)[2..], - [350.0, 61.0], - "the middle of its bottom" - ); + assert_eq!(ends(&editor)[2..], [350.0, 61.0], "the middle of its bottom"); let stored = editor.body(); assert!(stored.contains(r#""toAnchor":"bottom""#), "{stored}"); assert!(!stored.contains("fromAnchor")); @@ -1070,19 +1018,11 @@ fn an_end_let_go_on_the_middle_of_a_side_stays_on_it() { drag(&mut editor, at(380.0, 10.0), at(380.0, 110.0)); assert_eq!(ends(&editor)[2..], [350.0, 161.0]); drag(&mut editor, at(401.0, 130.0), at(501.0, 130.0)); - assert!( - (ends(&editor)[2] - 400.0).abs() < 1.0, - "{:?}", - ends(&editor) - ); + assert!((ends(&editor)[2] - 400.0).abs() < 1.0, "{:?}", ends(&editor)); let mut reopened = Editor::open(&editor.body(), Arc::new(fonts())); drag(&mut reopened, at(480.0, 150.0), at(480.0, 50.0)); - assert_eq!( - ends(&reopened)[3], - 61.0, - "read back, it is on the same point" - ); + assert_eq!(ends(&reopened)[3], 61.0, "read back, it is on the same point"); } #[test] @@ -1162,10 +1102,7 @@ fn a_shape_is_shown_while_it_is_dragged() { let shown = editor.revision(); editor.drag(at(40.0, 20.0)); - assert_eq!( - (object(&editor, 0).width(), object(&editor, 0).height()), - (40.0, 20.0) - ); + assert_eq!((object(&editor, 0).width(), object(&editor, 0).height()), (40.0, 20.0)); assert!(editor.revision() > shown); assert!(!editor.can_undo(), "a step of the history once let go"); } @@ -1191,12 +1128,7 @@ fn a_click_is_told_from_a_drag_on_the_screen() { #[test] fn a_handle_is_taken_from_as_far_on_the_screen_whatever_the_scale() { - for (scale, away, taken) in [ - (1.0, 8.0, true), - (1.0, 8.5, false), - (2.0, 4.0, true), - (2.0, 4.5, false), - ] { + for (scale, away, taken) in [(1.0, 8.0, true), (1.0, 8.5, false), (2.0, 4.0, true), (2.0, 4.5, false)] { let mut editor = with_a_rectangle(); editor.set_scale(scale); let corner = editor.frame().unwrap().grip(Grip::BottomRight); @@ -1208,12 +1140,7 @@ fn a_handle_is_taken_from_as_far_on_the_screen_whatever_the_scale() { #[test] fn an_end_of_an_arrow_is_taken_from_as_far_on_the_screen() { - for (dx, dy, taken) in [ - (8.0, 0.0, true), - (0.0, 8.0, true), - (8.5, 0.0, false), - (0.0, 8.5, false), - ] { + for (dx, dy, taken) in [(8.0, 0.0, true), (0.0, 8.0, true), (8.5, 0.0, false), (0.0, 8.5, false)] { let mut editor = joined(); let end = at(299.0 + dx, 30.0 + dy); editor.press(end, false); @@ -1244,10 +1171,7 @@ fn the_frame_of_a_turned_shape_turns_with_it() { .into_iter() .zip([(181.0, 79.0), (181.0, 181.0), (119.0, 181.0), (119.0, 79.0)]) { - assert!( - (corner.x - x).abs() < 1e-6 && (corner.y - y).abs() < 1e-6, - "{corner:?}" - ); + assert!((corner.x - x).abs() < 1e-6 && (corner.y - y).abs() < 1e-6, "{corner:?}"); } } @@ -1267,15 +1191,8 @@ fn a_turned_shape_is_scaled_along_its_own_sides() { fn where_an_arrow_is_held_is_told_from_as_far_as_its_side_is_reached() { let mut editor = joined(); editor.set_tool(Tool::Arrow); - for (dx, dy, told) in [ - (8.0, 0.0, true), - (8.5, 0.0, false), - (0.0, 8.0, true), - (0.0, 8.5, false), - ] { - let chosen = editor - .attaching(at(401.0 + dx, 30.0 + dy)) - .and_then(|found| found.chosen); + for (dx, dy, told) in [(8.0, 0.0, true), (8.5, 0.0, false), (0.0, 8.0, true), (0.0, 8.5, false)] { + let chosen = editor.attaching(at(401.0 + dx, 30.0 + dy)).and_then(|found| found.chosen); assert_eq!(chosen, told.then_some(at(401.0, 30.0)), "{dx} {dy}"); } } @@ -1298,10 +1215,7 @@ fn an_arrow_bound_to_a_shape_that_is_gone_stays_where_it_is() { let mut editor = Editor::open(body, Arc::new(fonts())); drag(&mut editor, at(100.0, 100.0), at(100.0, 110.0)); - assert_eq!( - object(&editor, 1).ends(), - Some([300.0, 100.0, 400.0, 100.0]) - ); + assert_eq!(object(&editor, 1).ends(), Some([300.0, 100.0, 400.0, 100.0])); } #[test] @@ -1338,9 +1252,6 @@ fn the_eraser_tells_what_it_would_take_by_its_frame() { let editor = with_a_rectangle(); let frame = editor.erasable(at(150.0, 130.0)).unwrap(); - assert_eq!( - (frame.centre, frame.width, frame.height), - (at(150.0, 130.0), 102.0, 62.0) - ); + assert_eq!((frame.centre, frame.width, frame.height), (at(150.0, 130.0), 102.0, 62.0)); assert!(editor.erasable(at(0.0, 0.0)).is_none()); } diff --git a/crates/drawing/src/geometry.rs b/crates/drawing/src/geometry.rs index 78b2588c6..6428831d9 100644 --- a/crates/drawing/src/geometry.rs +++ b/crates/drawing/src/geometry.rs @@ -41,10 +41,7 @@ pub fn arrow_path([x1, y1, x2, y2]: Ends) -> [PathCommand; 6] { let reach = HEAD.min(length); let (foot_x, foot_y) = (x2 - ux * reach, y2 - uy * reach); let half = reach / 2.0; - let at = |x: f64, y: f64| Point { - x: (x * 10.0).round() / 10.0, - y: (y * 10.0).round() / 10.0, - }; + let at = |x: f64, y: f64| Point { x: (x * 10.0).round() / 10.0, y: (y * 10.0).round() / 10.0 }; [ PathCommand::Move(at(x1, y1)), PathCommand::Line(at(foot_x, foot_y)), @@ -65,10 +62,7 @@ pub(crate) fn number(value: f64) -> String { impl Box { pub fn centre(&self) -> Point { - Point { - x: self.left + self.width / 2.0, - y: self.top + self.height / 2.0, - } + Point { x: self.left + self.width / 2.0, y: self.top + self.height / 2.0 } } } @@ -80,17 +74,10 @@ pub fn edge_point(bounds: &Box, toward: Point) -> Point { return centre; } let along = |half: f64, delta: f64| { - if delta == 0.0 { - f64::INFINITY - } else { - half / delta.abs() - } + if delta == 0.0 { f64::INFINITY } else { half / delta.abs() } }; let scale = along(bounds.width / 2.0, dx).min(along(bounds.height / 2.0, dy)); - Point { - x: centre.x + dx * scale, - y: centre.y + dy * scale, - } + Point { x: centre.x + dx * scale, y: centre.y + dy * scale } } /// What an end of an arrow holds on to. @@ -143,22 +130,10 @@ pub fn drag_box(from: Point, to: Point) -> Box { pub fn diamond_points(width: f64, height: f64) -> [Point; 4] { [ - Point { - x: width / 2.0, - y: 0.0, - }, - Point { - x: width, - y: height / 2.0, - }, - Point { - x: width / 2.0, - y: height, - }, - Point { - x: 0.0, - y: height / 2.0, - }, + Point { x: width / 2.0, y: 0.0 }, + Point { x: width, y: height / 2.0 }, + Point { x: width / 2.0, y: height }, + Point { x: 0.0, y: height / 2.0 }, ] } @@ -175,12 +150,7 @@ pub fn scene_box(boxes: &[Box], margin: f64) -> Option { let top = boxes.iter().map(|b| b.top).reduce(f64::min)? - margin; let right = boxes.iter().map(|b| b.left + b.width).reduce(f64::max)? + margin; let bottom = boxes.iter().map(|b| b.top + b.height).reduce(f64::max)? + margin; - Some(Box { - left, - top, - width: right - left, - height: bottom - top, - }) + Some(Box { left, top, width: right - left, height: bottom - top }) } /// What the commands of a path cover, curves to their furthest; `None` for no point at all. @@ -219,10 +189,7 @@ pub fn smooth_path(points: &[Point]) -> Option> { for pair in points.windows(2) { let (control, next) = (pair[0], pair[1]); if control != next { - let middle = Point { - x: f64::midpoint(control.x, next.x), - y: f64::midpoint(control.y, next.y), - }; + let middle = Point { x: f64::midpoint(control.x, next.x), y: f64::midpoint(control.y, next.y) }; path.push(PathCommand::Quad(control, middle)); } } @@ -249,10 +216,8 @@ fn decimated(points: &[Point]) -> Vec { /// Where a curve turns, on each axis it turns on, as a point of the box around it. fn furthest(from: Point, control: Point, to: Point) -> [Option; 2] { - let at = |t: f64| Point { - x: quadratic(from.x, control.x, to.x, t), - y: quadratic(from.y, control.y, to.y, t), - }; + let at = + |t: f64| Point { x: quadratic(from.x, control.x, to.x, t), y: quadratic(from.y, control.y, to.y, t) }; let turn = |from: f64, control: f64, to: f64| { let t = (from - control) / (from - 2.0 * control + to); (t > 0.0 && t < 1.0).then(|| at(t)) @@ -271,12 +236,7 @@ pub fn points_box(points: &[Point]) -> Option { let top = points.iter().map(|point| point.y).reduce(f64::min)?; let right = points.iter().map(|point| point.x).reduce(f64::max)?; let bottom = points.iter().map(|point| point.y).reduce(f64::max)?; - Some(Box { - left, - top, - width: right - left, - height: bottom - top, - }) + Some(Box { left, top, width: right - left, height: bottom - top }) } #[cfg(test)] @@ -284,12 +244,7 @@ pub fn points_box(points: &[Point]) -> Option { mod tests { use super::*; - const BOX: Box = Box { - left: 0.0, - top: 0.0, - width: 100.0, - height: 50.0, - }; + const BOX: Box = Box { left: 0.0, top: 0.0, width: 100.0, height: 50.0 }; fn at(x: f64, y: f64) -> Point { Point { x, y } @@ -327,22 +282,10 @@ mod tests { fn each_bound_end_is_on_its_shape_facing_the_other() { let left = Held::Edge(BOX); let right = Held::Edge(Box { left: 200.0, ..BOX }); - assert_eq!( - bound_ends([0.0; 4], Some(&left), Some(&right)), - [100.0, 25.0, 200.0, 25.0] - ); - assert_eq!( - bound_ends([0.0, 0.0, 50.0, 300.0], Some(&left), None), - [50.0, 50.0, 50.0, 300.0] - ); - assert_eq!( - bound_ends([400.0, 25.0, 0.0, 0.0], None, Some(&right)), - [400.0, 25.0, 300.0, 25.0] - ); - assert_eq!( - bound_ends([1.0, 2.0, 3.0, 4.0], None, None), - [1.0, 2.0, 3.0, 4.0] - ); + assert_eq!(bound_ends([0.0; 4], Some(&left), Some(&right)), [100.0, 25.0, 200.0, 25.0]); + assert_eq!(bound_ends([0.0, 0.0, 50.0, 300.0], Some(&left), None), [50.0, 50.0, 50.0, 300.0]); + assert_eq!(bound_ends([400.0, 25.0, 0.0, 0.0], None, Some(&right)), [400.0, 25.0, 300.0, 25.0]); + assert_eq!(bound_ends([1.0, 2.0, 3.0, 4.0], None, None), [1.0, 2.0, 3.0, 4.0]); } #[test] @@ -356,12 +299,7 @@ mod tests { #[test] fn a_drag_reads_whichever_way_it_went() { - let covered = Box { - left: 10.0, - top: 40.0, - width: 40.0, - height: 20.0, - }; + let covered = Box { left: 10.0, top: 40.0, width: 40.0, height: 20.0 }; for (from, to) in [ (at(50.0, 40.0), at(10.0, 60.0)), (at(10.0, 40.0), at(50.0, 60.0)), @@ -381,53 +319,21 @@ mod tests { #[test] fn a_picture_s_longest_side_is_brought_to_its_size_never_enlarged_too_much() { - for (width, height, scale) in [ - (800.0, 200.0, 0.5), - (200.0, 800.0, 0.5), - (100.0, 50.0, 2.0), - (0.0, 0.0, 2.0), - ] { - let bounds = Box { - width, - height, - ..BOX - }; - assert_eq!( - picture_scale(&bounds, 400.0, 2.0), - scale, - "{width} {height}" - ); + for (width, height, scale) in + [(800.0, 200.0, 0.5), (200.0, 800.0, 0.5), (100.0, 50.0, 2.0), (0.0, 0.0, 2.0)] + { + let bounds = Box { width, height, ..BOX }; + assert_eq!(picture_scale(&bounds, 400.0, 2.0), scale, "{width} {height}"); } - assert_eq!( - picture_scale( - &Box { - width: 0.5, - height: 0.0, - ..BOX - }, - 400.0, - 900.0 - ), - 400.0 - ); + assert_eq!(picture_scale(&Box { width: 0.5, height: 0.0, ..BOX }, 400.0, 900.0), 400.0); } #[test] fn a_scene_is_framed_by_all_that_is_on_it_with_room_around() { - let small = Box { - left: 150.0, - top: -20.0, - width: 10.0, - height: 10.0, - }; + let small = Box { left: 150.0, top: -20.0, width: 10.0, height: 10.0 }; assert_eq!( scene_box(&[BOX, small], 10.0), - Some(Box { - left: -10.0, - top: -30.0, - width: 180.0, - height: 90.0 - }) + Some(Box { left: -10.0, top: -30.0, width: 180.0, height: 90.0 }) ); assert_eq!(scene_box(&[], MARGIN), None); } @@ -436,13 +342,9 @@ mod tests { fn a_path_is_covered_to_where_its_curves_turn() { use PathCommand::{Close, Line, Move, Quad}; - let covered = - |path: &[PathCommand]| path_box(path).map(|b| [b.left, b.top, b.width, b.height]); + let covered = |path: &[PathCommand]| path_box(path).map(|b| [b.left, b.top, b.width, b.height]); - assert_eq!( - covered(&[Move(at(1.0, 2.0)), Line(at(5.0, 9.0)), Close]), - Some([1.0, 2.0, 4.0, 7.0]) - ); + assert_eq!(covered(&[Move(at(1.0, 2.0)), Line(at(5.0, 9.0)), Close]), Some([1.0, 2.0, 4.0, 7.0])); // A curve up to its control and back: it goes half the way. assert_eq!( covered(&[Move(at(0.0, 0.0)), Quad(at(10.0, 20.0), at(20.0, 0.0))]), @@ -462,10 +364,7 @@ mod tests { covered(&[Move(at(0.0, 0.0)), Quad(at(1.0, 5.0), at(10.0, 10.0))]), Some([0.0, 0.0, 10.0, 10.0]) ); - assert_eq!( - covered(&[Quad(at(9.0, 9.0), at(1.0, 1.0))]), - Some([1.0, 1.0, 0.0, 0.0]) - ); + assert_eq!(covered(&[Quad(at(9.0, 9.0), at(1.0, 1.0))]), Some([1.0, 1.0, 0.0, 0.0])); assert_eq!(covered(&[Close]), None); assert_eq!(covered(&[]), None); } diff --git a/crates/drawing/src/marks.rs b/crates/drawing/src/marks.rs index 83e8093ff..0bc1b3aad 100644 --- a/crates/drawing/src/marks.rs +++ b/crates/drawing/src/marks.rs @@ -63,14 +63,7 @@ struct Plane { } impl Plane { - const IDENTITY: Self = Self { - a: 1.0, - b: 0.0, - c: 0.0, - d: 1.0, - e: 0.0, - f: 0.0, - }; + const IDENTITY: Self = Self { a: 1.0, b: 0.0, c: 0.0, d: 1.0, e: 0.0, f: 0.0 }; /// Fabric's order: translate, rotate, scale, skew. fn of(object: &Object) -> Self { @@ -78,10 +71,7 @@ impl Plane { let (sin, cos) = object.angle().to_radians().sin_cos(); let (flip_x, flip_y) = object.flipped(); let mirror = |flipped: bool| if flipped { -1.0 } else { 1.0 }; - let (scale_x, scale_y) = ( - object.scale_x() * mirror(flip_x), - object.scale_y() * mirror(flip_y), - ); + let (scale_x, scale_y) = (object.scale_x() * mirror(flip_x), object.scale_y() * mirror(flip_y)); let (skew_x, skew_y) = object.skew(); let turned = Self { a: cos * scale_x, @@ -92,14 +82,8 @@ impl Plane { f: centre.y, }; turned - .then(Self { - c: skew_x.to_radians().tan(), - ..Self::IDENTITY - }) - .then(Self { - b: skew_y.to_radians().tan(), - ..Self::IDENTITY - }) + .then(Self { c: skew_x.to_radians().tan(), ..Self::IDENTITY }) + .then(Self { b: skew_y.to_radians().tan(), ..Self::IDENTITY }) } /// This plane, with `inner` inside it. @@ -115,10 +99,7 @@ impl Plane { } fn apply(self, at: Point) -> Point { - Point { - x: self.a * at.x + self.c * at.y + self.e, - y: self.b * at.x + self.d * at.y + self.f, - } + Point { x: self.a * at.x + self.c * at.y + self.e, y: self.b * at.x + self.d * at.y + self.f } } fn scale(self) -> f64 { @@ -159,11 +140,7 @@ fn add(marks: &mut Vec, object: &Object, outer: Plane, fonts: &Fonts) { } fn stroke_width(object: &Object, plane: Plane) -> f64 { - if object.stroke_uniform() { - object.stroke_width() - } else { - object.stroke_width() * plane.scale() - } + if object.stroke_uniform() { object.stroke_width() } else { object.stroke_width() * plane.scale() } } /// Round its centre, each corner an arc when it has a radius. @@ -180,10 +157,7 @@ fn rectangle(object: &Object) -> Vec { for (x, y, from) in corners { for step in 0..=CORNER_STEPS { let turned = from + FRAC_PI_2 * f64::from(step) / f64::from(CORNER_STEPS); - outline.push(Point { - x: x + radius * turned.cos(), - y: y + radius * turned.sin(), - }); + outline.push(Point { x: x + radius * turned.cos(), y: y + radius * turned.sin() }); } } outline @@ -194,10 +168,7 @@ fn ellipse(object: &Object) -> Vec { (0..ELLIPSE_STEPS) .map(|step| { let turned = TAU * f64::from(step) / f64::from(ELLIPSE_STEPS); - Point { - x: rx * turned.cos(), - y: ry * turned.sin(), - } + Point { x: rx * turned.cos(), y: ry * turned.sin() } }) .collect() } @@ -207,10 +178,7 @@ fn polygon(object: &Object) -> Vec { let middle = points_box(&points).map_or(Point { x: 0.0, y: 0.0 }, |bounds| bounds.centre()); points .iter() - .map(|point| Point { - x: point.x - middle.x, - y: point.y - middle.y, - }) + .map(|point| Point { x: point.x - middle.x, y: point.y - middle.y }) .collect() } @@ -218,23 +186,14 @@ fn polygon(object: &Object) -> Vec { fn add_path(marks: &mut Vec, object: &Object, plane: Plane) { let commands = object.path(); let middle = path_box(&commands).map_or(Point { x: 0.0, y: 0.0 }, |bounds| bounds.centre()); - let on_plane = |at: Point| { - plane.apply(Point { - x: at.x - middle.x, - y: at.y - middle.y, - }) - }; + let on_plane = |at: Point| plane.apply(Point { x: at.x - middle.x, y: at.y - middle.y }); let arrow = object.ends().is_some(); let mut flush = |points: &mut Vec, closed: bool| { if points.len() > 1 { marks.push(Mark::Line { points: std::mem::take(points), closed, - fill: if closed && arrow { - Fill::Stroke - } else { - Fill::None - }, + fill: if closed && arrow { Fill::Stroke } else { Fill::None }, hue: object.hue(), width: stroke_width(object, plane), }); @@ -269,13 +228,8 @@ fn add_path(marks: &mut Vec, object: &Object, plane: Plane) { fn along_curve(from: Point, control: Point, to: Point, t: f64) -> Point { let rest = 1.0 - t; - let at = |from: f64, control: f64, to: f64| { - rest * rest * from + 2.0 * rest * t * control + t * t * to - }; - Point { - x: at(from.x, control.x, to.x), - y: at(from.y, control.y, to.y), - } + let at = |from: f64, control: f64, to: f64| rest * rest * from + 2.0 * rest * t * control + t * t * to; + Point { x: at(from.x, control.x, to.x), y: at(from.y, control.y, to.y) } } fn add_text(marks: &mut Vec, object: &Object, plane: Plane, fonts: &Fonts) { @@ -287,10 +241,7 @@ fn add_text(marks: &mut Vec, object: &Object, plane: Plane, fonts: &Fonts) for line in wrap(text, object.width(), font_size, fonts) { marks.push(Mark::Words { text: line, - at: plane.apply(Point { - x: left, - y: baseline, - }), + at: plane.apply(Point { x: left, y: baseline }), angle: plane.angle(), size: font_size * plane.scale(), hue: object.hue(), @@ -315,12 +266,7 @@ mod tests { fn line(mark: &Mark) -> (&[Point], bool, Fill) { match mark { - Mark::Line { - points, - closed, - fill, - .. - } => (points, *closed, *fill), + Mark::Line { points, closed, fill, .. } => (points, *closed, *fill), Mark::Words { .. } => panic!("words"), } } @@ -342,11 +288,7 @@ mod tests { let marks = marks_of(r#"{"type":"Rect","width":20,"height":20,"rx":5}"#); let (points, ..) = line(&marks[0]); - assert!( - points - .iter() - .all(|at| at.x.hypot(at.y) < 10.0 * 2f64.sqrt() - 1.0) - ); + assert!(points.iter().all(|at| at.x.hypot(at.y) < 10.0 * 2f64.sqrt() - 1.0)); } #[test] @@ -389,13 +331,9 @@ mod tests { Mark::Words { .. } => panic!("words"), }; + assert!((width(r#"{"type":"Rect","strokeWidth":2,"scaleX":3,"scaleY":3}"#) - 6.0).abs() < 1e-9); assert!( - (width(r#"{"type":"Rect","strokeWidth":2,"scaleX":3,"scaleY":3}"#) - 6.0).abs() < 1e-9 - ); - assert!( - (width(r#"{"type":"Rect","strokeWidth":2,"scaleX":3,"strokeUniform":true}"#) - 2.0) - .abs() - < 1e-9 + (width(r#"{"type":"Rect","strokeWidth":2,"scaleX":3,"strokeUniform":true}"#) - 2.0).abs() < 1e-9 ); } @@ -428,13 +366,11 @@ mod tests { #[test] fn a_flip_and_a_skew_reach_the_plane() { - let flipped = marks_of( - r#"{"type":"Path","flipX":true,"left":0,"top":0,"path":[["M",0,0],["L",10,0]]}"#, - ); + let flipped = + marks_of(r#"{"type":"Path","flipX":true,"left":0,"top":0,"path":[["M",0,0],["L",10,0]]}"#); assert!(near(line(&flipped[0]).0[0], 5.0, 0.0)); - let skewed = - marks_of(r#"{"type":"Polygon","skewX":45,"points":[{"x":0,"y":0},{"x":0,"y":10}]}"#); + let skewed = marks_of(r#"{"type":"Polygon","skewX":45,"points":[{"x":0,"y":0},{"x":0,"y":10}]}"#); assert!(near(line(&skewed[0]).0[1], 5.0, 5.0)); } @@ -442,42 +378,24 @@ mod tests { fn a_path_of_a_lone_point_is_not_drawn_and_each_piece_is_its_own() { let pieces = |path: &str| { let marks = marks_of(&format!(r#"{{"type":"Path","path":[{path}]}}"#)); - marks - .iter() - .map(|mark| line(mark).0.len()) - .collect::>() + marks.iter().map(|mark| line(mark).0.len()).collect::>() }; assert!(pieces(r#"["M",0,0]"#).is_empty()); assert!(pieces(r#"["M",0,0],["Z"]"#).is_empty()); - assert_eq!( - pieces(r#"["M",0,0],["L",1,0],["M",5,5],["M",6,6],["L",7,7],["L",8,8]"#), - [2, 3] - ); - assert_eq!( - pieces(r#"["M",0,0],["L",1,0],["Z"],["L",9,9],["L",8,8]"#), - [2, 2] - ); + assert_eq!(pieces(r#"["M",0,0],["L",1,0],["M",5,5],["M",6,6],["L",7,7],["L",8,8]"#), [2, 3]); + assert_eq!(pieces(r#"["M",0,0],["L",1,0],["Z"],["L",9,9],["L",8,8]"#), [2, 2]); } /// Each curve starts where the one before ended, whatever it was. #[test] fn a_curve_starts_where_the_pen_was() { - for before in [ - r#"["M",10,0]"#, - r#"["M",0,0],["L",10,0]"#, - r#"["M",0,0],["Q",5,0,10,0]"#, - ] { - let marks = marks_of(&format!( - r#"{{"type":"Path","path":[{before},["Q",10,100,10,200]]}}"# - )); + for before in [r#"["M",10,0]"#, r#"["M",0,0],["L",10,0]"#, r#"["M",0,0],["Q",5,0,10,0]"#] { + let marks = marks_of(&format!(r#"{{"type":"Path","path":[{before},["Q",10,100,10,200]]}}"#)); let (points, ..) = line(&marks[0]); let x = points[points.len() - 1].x; let curve = &points[points.len() - usize::try_from(CURVE_STEPS).unwrap()..]; - assert!( - curve.iter().all(|at| (at.x - x).abs() < 1e-9), - "{before}: {curve:?}" - ); + assert!(curve.iter().all(|at| (at.x - x).abs() < 1e-9), "{before}: {curve:?}"); } } diff --git a/crates/drawing/src/picture.rs b/crates/drawing/src/picture.rs index 258bdb8ff..e65c5f835 100644 --- a/crates/drawing/src/picture.rs +++ b/crates/drawing/src/picture.rs @@ -64,24 +64,14 @@ pub fn pictures(drawing: &Drawing, palette: &Palette, fonts: &Fonts) -> Option

Option> { +pub fn export(drawing: &Drawing, palette: &Palette, fonts: &Fonts, format: Format) -> Option> { match format { Format::Png => png(drawing, palette, fonts, PICTURE), Format::Svg => svg(drawing, palette, fonts).map(String::into_bytes), } } -fn png( - drawing: &Drawing, - palette: &Palette, - fonts: &Fonts, - (side, most): (f64, f64), -) -> Option> { +fn png(drawing: &Drawing, palette: &Palette, fonts: &Fonts, (side, most): (f64, f64)) -> Option> { let frame = frame(drawing)?; let options = usvg::Options { font_family: fonts.family.clone(), @@ -95,15 +85,11 @@ fn png( clippy::cast_sign_loss, reason = "positive, and a picture's side at most" )] - let (width, height) = ( - (frame.width * scale).ceil() as u32, - (frame.height * scale).ceil() as u32, - ); + let (width, height) = ((frame.width * scale).ceil() as u32, (frame.height * scale).ceil() as u32); let mut pixmap = Pixmap::new(width, height)?; let drawn = tree.size(); #[expect(clippy::cast_precision_loss, reason = "a picture's side")] - let transform = - Transform::from_scale(width as f32 / drawn.width(), height as f32 / drawn.height()); + let transform = Transform::from_scale(width as f32 / drawn.width(), height as f32 / drawn.height()); resvg::render(&tree, transform, &mut pixmap.as_mut()); pixmap.encode_png().ok() } @@ -144,11 +130,8 @@ pub fn svg(drawing: &Drawing, palette: &Palette, fonts: &Fonts) -> Option return, Kind::Group => { @@ -163,12 +146,8 @@ fn write_object(out: &mut String, object: &Object, palette: &Palette, fonts: &Fo Kind::Rect | Kind::Ellipse | Kind::Polygon | Kind::Path => {} } let shape = shape(object, drawn_at); - let _ = write!( - out, - r#"<{shape} transform="{}" {}/>"#, - transform(object, drawn_at), - paint(object, palette) - ); + let _ = + write!(out, r#"<{shape} transform="{}" {}/>"#, transform(object, drawn_at), paint(object, palette)); } /// The tag and geometry of a shape, around the plane's origin: what `left` and `top` place. @@ -187,11 +166,7 @@ fn shape(object: &Object, (scale_x, scale_y): (f64, f64)) -> String { number(radius * scale_y), ) } - Kind::Ellipse => format!( - r#"ellipse rx="{}" ry="{}""#, - number(width / 2.0), - number(height / 2.0) - ), + Kind::Ellipse => format!(r#"ellipse rx="{}" ry="{}""#, number(width / 2.0), number(height / 2.0)), Kind::Polygon => { let points = object.points(); let middle = points_box(&points).map(|bounds| bounds.centre()); @@ -206,10 +181,7 @@ fn shape(object: &Object, (scale_x, scale_y): (f64, f64)) -> String { .collect(); format!(r#"polygon points="{}""#, points.join(" ")) } - _ => format!( - r#"path d="{}""#, - path_data(&object.path(), (scale_x, scale_y)) - ), + _ => format!(r#"path d="{}""#, path_data(&object.path(), (scale_x, scale_y))), } } @@ -274,12 +246,7 @@ fn paint(object: &Object, palette: &Palette) -> String { fn write_text(out: &mut String, object: &Object, palette: &Palette, fonts: &Fonts) { let font_size = object.font_size(); - let lines = wrap( - object.text().unwrap_or_default(), - object.width(), - font_size, - fonts, - ); + let lines = wrap(object.text().unwrap_or_default(), object.width(), font_size, fonts); let step = line_step(font_size, object.line_height()); let left = -object.width() / 2.0; let top = -object.height() / 2.0 + first_baseline(font_size); @@ -293,13 +260,8 @@ fn write_text(out: &mut String, object: &Object, palette: &Palette, fonts: &Font ); let mut baseline = top; for line in lines { - let _ = write!( - out, - r#"{}"#, - number(left), - number(baseline), - escaped(&line) - ); + let _ = + write!(out, r#"{}"#, number(left), number(baseline), escaped(&line)); baseline += step; } out.push_str(""); diff --git a/crates/drawing/src/picture/tests.rs b/crates/drawing/src/picture/tests.rs index a56ae5e19..7ec7f1533 100644 --- a/crates/drawing/src/picture/tests.rs +++ b/crates/drawing/src/picture/tests.rs @@ -3,20 +3,12 @@ use crate::text::tests::fonts; fn palette() -> Palette { let each = |prefix: &str| Hue::ALL.map(|hue| format!("{prefix}-{}", hue.name())); - Palette { - stroke: each("stroke"), - fill: each("fill"), - paper: "#101010".to_owned(), - } + Palette { stroke: each("stroke"), fill: each("fill"), paper: "#101010".to_owned() } } fn colours() -> Palette { let each = |colour: &str| [colour; 6].map(str::to_owned); - Palette { - stroke: each("#e5e7eb"), - fill: each("rgba(96, 165, 250, 0.14)"), - paper: "#101010".to_owned(), - } + Palette { stroke: each("#e5e7eb"), fill: each("rgba(96, 165, 250, 0.14)"), paper: "#101010".to_owned() } } fn scene(objects: &str) -> Drawing { @@ -59,13 +51,9 @@ fn nothing_drawn_has_no_picture() { #[test] fn the_frame_is_what_is_drawn_with_room_on_its_paper() { - let svg = - svg_of(r#"{"type":"Rect","left":100,"top":50,"width":100,"height":50,"strokeWidth":0}"#); + let svg = svg_of(r#"{"type":"Rect","left":100,"top":50,"width":100,"height":50,"strokeWidth":0}"#); - assert!( - svg.contains(r#"viewBox="26 1 148 98" width="148" height="98""#), - "{svg}" - ); + assert!(svg.contains(r#"viewBox="26 1 148 98" width="148" height="98""#), "{svg}"); assert!(svg.contains(r##""##)); } @@ -77,14 +65,16 @@ fn each_shape_is_drawn_round_its_centre_in_its_hues_colours() { {"type":"Polygon","left":0,"top":0,"width":40,"height":20,"points":[{"x":20,"y":0},{"x":40,"y":10},{"x":20,"y":20},{"x":0,"y":10}]}"#, ); - assert!(svg.contains(r#", objects: &[Object]) { if objects.is_empty() && !fields.contains_key(OBJECTS) { return; } - let objects = objects - .iter() - .map(|object| Value::Object(object.fields())) - .collect(); + let objects = objects.iter().map(|object| Value::Object(object.fields())).collect(); fields.insert(OBJECTS.to_owned(), Value::Array(objects)); } @@ -170,10 +159,7 @@ impl Object { /// A new object of Fabric's `kind`, in `hue`, on nothing yet. pub(crate) fn make(kind: &str, id: String, hue: Hue) -> Self { - let mut object = Self { - fields: Map::new(), - children: Vec::new(), - }; + let mut object = Self { fields: Map::new(), children: Vec::new() }; object.put("type", kind); object.put("version", FABRIC); object.put("originX", "center"); @@ -299,10 +285,7 @@ impl Object { /// ⚠️ Fabric 7 places an object by its centre: `left` and `top` are the box's middle. pub fn centre(&self) -> Point { - Point { - x: self.number("left", 0.0), - y: self.number("top", 0.0), - } + Point { x: self.number("left", 0.0), y: self.number("top", 0.0) } } pub fn width(&self) -> f64 { @@ -391,15 +374,9 @@ impl Object { let stroke = self.stroke_width(); let (scale_x, scale_y) = (self.scale_x().abs(), self.scale_y().abs()); if self.stroke_uniform() { - ( - self.width() * scale_x + stroke, - self.height() * scale_y + stroke, - ) + (self.width() * scale_x + stroke, self.height() * scale_y + stroke) } else { - ( - (self.width() + stroke) * scale_x, - (self.height() + stroke) * scale_y, - ) + ((self.width() + stroke) * scale_x, (self.height() + stroke) * scale_y) } } @@ -410,17 +387,9 @@ impl Object { let (sin, cos) = self.angle().to_radians().sin_cos(); let corners = [(-1.0, -1.0), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)].map(|(x, y)| { let (x, y) = (x * width / 2.0, y * height / 2.0); - Point { - x: centre.x + x * cos - y * sin, - y: centre.y + x * sin + y * cos, - } + Point { x: centre.x + x * cos - y * sin, y: centre.y + x * sin + y * cos } }); - points_box(&corners).unwrap_or(Box { - left: centre.x, - top: centre.y, - width: 0.0, - height: 0.0, - }) + points_box(&corners).unwrap_or(Box { left: centre.x, top: centre.y, width: 0.0, height: 0.0 }) } /// Whether a point falls on it: its whole box, as Fabric finds a target, not its ink. @@ -437,10 +406,7 @@ impl Object { } fn number(&self, name: &str, otherwise: f64) -> f64 { - self.fields - .get(name) - .and_then(Value::as_f64) - .unwrap_or(otherwise) + self.fields.get(name).and_then(Value::as_f64).unwrap_or(otherwise) } fn list(&self, name: &str, read: impl Fn(&Value) -> Option) -> Vec { @@ -459,21 +425,11 @@ fn stored(value: f64) -> Value { } fn point_of(value: &Value) -> Option { - Some(Point { - x: value.get("x")?.as_f64()?, - y: value.get("y")?.as_f64()?, - }) + Some(Point { x: value.get("x")?.as_f64()?, y: value.get("y")?.as_f64()? }) } impl Hue { - pub const ALL: [Self; 6] = [ - Self::Ink, - Self::Blue, - Self::Green, - Self::Amber, - Self::Red, - Self::Purple, - ]; + pub const ALL: [Self; 6] = [Self::Ink, Self::Blue, Self::Green, Self::Amber, Self::Red, Self::Purple]; pub fn name(self) -> &'static str { match self { @@ -488,10 +444,7 @@ impl Hue { /// A name no theme paints is ink, as an object with none. fn named(name: &str) -> Self { - Self::ALL - .into_iter() - .find(|hue| hue.name() == name) - .unwrap_or_default() + Self::ALL.into_iter().find(|hue| hue.name() == name).unwrap_or_default() } } @@ -514,12 +467,8 @@ impl PathCommand { fn read(value: &Value) -> Option { let parts = value.as_array()?; - let at = |index: usize| { - Some(Point { - x: parts.get(index)?.as_f64()?, - y: parts.get(index + 1)?.as_f64()?, - }) - }; + let at = + |index: usize| Some(Point { x: parts.get(index)?.as_f64()?, y: parts.get(index + 1)?.as_f64()? }); match parts.first()?.as_str()? { "M" => Some(Self::Move(at(1)?)), "L" => Some(Self::Line(at(1)?)), diff --git a/crates/drawing/src/scene/tests.rs b/crates/drawing/src/scene/tests.rs index 5143d5f7e..4134c9a04 100644 --- a/crates/drawing/src/scene/tests.rs +++ b/crates/drawing/src/scene/tests.rs @@ -59,11 +59,7 @@ fn a_body_with_no_scene_opens_as_a_new_drawing() { #[test] fn each_object_reads_as_its_kind_and_hue() { let drawing = drawn(); - let read: Vec<_> = drawing - .objects - .iter() - .map(|object| (object.kind(), object.hue())) - .collect(); + let read: Vec<_> = drawing.objects.iter().map(|object| (object.kind(), object.hue())).collect(); assert_eq!( read, @@ -111,19 +107,12 @@ fn an_object_is_placed_by_its_centre_with_fabrics_transform() { #[test] fn a_field_left_out_reads_as_fabrics_default() { let drawing = - Drawing::read(r#"{"scene":{"objects":[{"type":"Textbox","hue":"teal","ends":[1,2]}]}}"#) - .unwrap(); + Drawing::read(r#"{"scene":{"objects":[{"type":"Textbox","hue":"teal","ends":[1,2]}]}}"#).unwrap(); let object = &drawing.objects[0]; assert_eq!(object.centre(), at(0.0, 0.0)); assert_eq!( - [ - object.scale_x(), - object.scale_y(), - object.angle(), - object.stroke_width(), - object.font_size(), - ], + [object.scale_x(), object.scale_y(), object.angle(), object.stroke_width(), object.font_size(),], [1.0, 1.0, 0.0, 1.0, 40.0] ); assert_eq!(object.hue(), Hue::Ink); @@ -139,14 +128,8 @@ fn an_arrow_holds_its_ends_its_shapes_and_its_path() { assert_eq!(arrow.from(), Some("rect-1")); assert_eq!(arrow.to(), Some("ellipse-1")); - assert_eq!( - arrow.ends().map(|ends| ends[0]), - Some(240.000_000_000_000_03) - ); - assert_eq!( - arrow.path().first(), - Some(&PathCommand::Move(at(240.0, 90.1))) - ); + assert_eq!(arrow.ends().map(|ends| ends[0]), Some(240.000_000_000_000_03)); + assert_eq!(arrow.path().first(), Some(&PathCommand::Move(at(240.0, 90.1)))); assert_eq!(arrow.path().last(), Some(&PathCommand::Close)); } @@ -167,8 +150,7 @@ fn a_freehand_line_is_read_with_its_curves() { #[test] fn a_path_command_the_app_never_wrote_is_not_drawn_and_stays_stored() { - let body = - r#"{"scene":{"objects":[{"type":"Path","path":[["M",1,2],["C",1,2,3,4,5,6],["L",3]]}]}}"#; + let body = r#"{"scene":{"objects":[{"type":"Path","path":[["M",1,2],["C",1,2,3,4,5,6],["L",3]]}]}}"#; let drawing = Drawing::read(body).unwrap(); assert_eq!(drawing.objects[0].path(), [PathCommand::Move(at(1.0, 2.0))]); @@ -179,25 +161,10 @@ fn a_path_command_the_app_never_wrote_is_not_drawn_and_stays_stored() { fn a_diamond_keeps_its_corners_a_text_its_words_a_group_its_children() { let drawing = drawn(); - assert_eq!( - drawing.objects[2].points(), - [ - at(60.0, 0.0), - at(120.0, 40.0), - at(60.0, 80.0), - at(0.0, 40.0) - ] - ); - assert_eq!( - drawing.objects[5].text(), - Some("API gateway\nsits in front of « everything »") - ); + assert_eq!(drawing.objects[2].points(), [at(60.0, 0.0), at(120.0, 40.0), at(60.0, 80.0), at(0.0, 40.0)]); + assert_eq!(drawing.objects[5].text(), Some("API gateway\nsits in front of « everything »")); assert_eq!(drawing.objects[5].font_size(), 18.0); - let inside: Vec<_> = drawing.objects[6] - .children - .iter() - .map(Object::kind) - .collect(); + let inside: Vec<_> = drawing.objects[6].children.iter().map(Object::kind).collect(); assert_eq!(inside, [Kind::Rect, Kind::Textbox]); } @@ -215,18 +182,13 @@ fn an_object_taken_away_leaves_the_rest_as_stored() { drawing.objects.remove(0); - assert_eq!( - drawing.write(), - r#"{"version":1,"scene":{"objects":[{"id":"b"}],"background":"x"}}"# - ); + assert_eq!(drawing.write(), r#"{"version":1,"scene":{"objects":[{"id":"b"}],"background":"x"}}"#); } #[test] fn the_first_object_put_on_an_empty_scene_is_stored() { let mut drawing = Drawing::read(r#"{"scene":{}}"#).unwrap(); - drawing.objects = Drawing::read(r#"{"scene":{"objects":[{"id":"a"}]}}"#) - .unwrap() - .objects; + drawing.objects = Drawing::read(r#"{"scene":{"objects":[{"id":"a"}]}}"#).unwrap().objects; assert_eq!(drawing.write(), r#"{"scene":{"objects":[{"id":"a"}]}}"#); } @@ -297,10 +259,7 @@ fn a_drawing_covers_all_that_is_drawn() { fn a_new_drawing_is_empty_and_read_back() { let empty = Drawing::empty(); - assert_eq!( - empty.write(), - r#"{"version":1,"scene":{"version":"7.4.0"}}"# - ); + assert_eq!(empty.write(), r#"{"version":1,"scene":{"version":"7.4.0"}}"#); let read = Drawing::read(&empty.write()).unwrap(); assert_eq!(read.write(), empty.write()); } @@ -310,10 +269,7 @@ fn a_shape_let_go_is_null_and_its_point_goes_with_it() { let mut arrow = Object::make("Path", "a".to_owned(), Hue::Ink); arrow.set_bound("from", Some("b")); arrow.set_anchor("from", Some(Side::Left)); - assert_eq!( - (arrow.from(), arrow.anchor("from")), - (Some("b"), Some(Side::Left)) - ); + assert_eq!((arrow.from(), arrow.anchor("from")), (Some("b"), Some(Side::Left))); arrow.set_bound("from", None); assert_eq!((arrow.from(), arrow.anchor("from")), (None, None)); diff --git a/crates/drawing/src/text.rs b/crates/drawing/src/text.rs index ab1505d93..448cdffe2 100644 --- a/crates/drawing/src/text.rs +++ b/crates/drawing/src/text.rs @@ -36,10 +36,7 @@ impl Fonts { .map_or_else(String::new, |(name, _)| name.clone()); database.set_sans_serif_family(family.clone()); Self { - faces: files - .iter() - .filter_map(|file| FontRef::new(file).ok()) - .collect(), + faces: files.iter().filter_map(|file| FontRef::new(file).ok()).collect(), database: Arc::new(database), family, } @@ -54,9 +51,7 @@ impl Fonts { } fn width(&self, word: &str, font_size: f64) -> f64 { - word.chars() - .map(|character| self.advance(character) * font_size) - .sum() + word.chars().map(|character| self.advance(character) * font_size).sum() } } diff --git a/crates/drawing/src/text/tests.rs b/crates/drawing/src/text/tests.rs index ff243444a..6439e4de2 100644 --- a/crates/drawing/src/text/tests.rs +++ b/crates/drawing/src/text/tests.rs @@ -14,8 +14,7 @@ fn wrapped(text: &str, width: f64) -> Vec { } /// Where Fabric's lines, in a browser, kerned, break elsewhere than these. -const KERNED_ELSEWHERE: [&str; 1] = - ["The quick brown fox jumps over the lazy dog, twice over, then rests"]; +const KERNED_ELSEWHERE: [&str; 1] = ["The quick brown fox jumps over the lazy dog, twice over, then rests"]; #[test] fn the_lines_are_those_fabric_broke_in_a_browser() { @@ -42,10 +41,7 @@ fn the_lines_are_those_fabric_broke_in_a_browser() { #[test] fn a_word_is_never_broken_and_widens_the_box() { - assert_eq!( - wrapped("supercalifragilistic ok", 10.0), - ["supercalifragilistic", "ok"] - ); + assert_eq!(wrapped("supercalifragilistic ok", 10.0), ["supercalifragilistic", "ok"]); } #[test] diff --git a/crates/engine/benches/commands.rs b/crates/engine/benches/commands.rs index 264fd2427..034290ad4 100644 --- a/crates/engine/benches/commands.rs +++ b/crates/engine/benches/commands.rs @@ -77,10 +77,7 @@ fn whole_corpus_read(c: &mut Criterion) { // Narrowed in SQL to the 160 pinned notes: what a filtered query pays for its side tables. group.bench_function("query_notes, pinned only", |b| { - let pinned = NotesQuery { - filter: NoteFilter::Pinned, - ..query("") - }; + let pinned = NotesQuery { filter: NoteFilter::Pinned, ..query("") }; b.iter(|| black_box(run_query(&mut corpus, &pinned))); }); @@ -97,10 +94,7 @@ fn single_write(c: &mut Criterion) { let mut at = 0u32; b.iter(|| { at += 1; - let patch = NotePatch { - title: Some(format!("Retitled {at}")), - ..NotePatch::default() - }; + let patch = NotePatch { title: Some(format!("Retitled {at}")), ..NotePatch::default() }; black_box(store::update(&mut corpus.connection, &id, &patch, now()).expect("a write")); }); }); @@ -122,10 +116,7 @@ fn body_writes(c: &mut Criterion) { // A full history, so every save below also rotates the oldest body out. for kept in 0..=engine::notes::revision::KEEP { - let patch = NotePatch { - content: Some(format!("{body}\n-- {kept}")), - ..NotePatch::default() - }; + let patch = NotePatch { content: Some(format!("{body}\n-- {kept}")), ..NotePatch::default() }; store::update(&mut corpus.connection, &id, &patch, now()).expect("a write"); } @@ -133,10 +124,7 @@ fn body_writes(c: &mut Criterion) { let mut at = 0u32; b.iter(|| { at += 1; - let patch = NotePatch { - content: Some(format!("{body}\n-- saved {at}")), - ..NotePatch::default() - }; + let patch = NotePatch { content: Some(format!("{body}\n-- saved {at}")), ..NotePatch::default() }; black_box(store::update(&mut corpus.connection, &id, &patch, now()).expect("a write")); }); }); @@ -145,10 +133,7 @@ fn body_writes(c: &mut Criterion) { let mut pinned = false; b.iter(|| { pinned = !pinned; - let patch = NotePatch { - pinned: Some(pinned), - ..NotePatch::default() - }; + let patch = NotePatch { pinned: Some(pinned), ..NotePatch::default() }; black_box(store::update(&mut corpus.connection, &id, &patch, now()).expect("a write")); }); }); @@ -164,10 +149,7 @@ fn bulk(c: &mut Criterion) { group.bench_function("tag_notes", |b| { b.iter(|| { - black_box( - store::tag_many(&mut corpus.connection, &ids, &["bulk".to_string()]) - .expect("a batch"), - ); + black_box(store::tag_many(&mut corpus.connection, &ids, &["bulk".to_string()]).expect("a batch")); }); }); @@ -183,9 +165,7 @@ fn bulk(c: &mut Criterion) { group.bench_function("delete_notes then restore_notes", |b| { b.iter(|| { store::trash::trash_many(&mut corpus.connection, &ids, now()).expect("a trashing"); - black_box( - store::trash::restore_many(&mut corpus.connection, &ids).expect("a restoration"), - ); + black_box(store::trash::restore_many(&mut corpus.connection, &ids).expect("a restoration")); }); }); @@ -209,9 +189,7 @@ fn aggregation(c: &mut Criterion) { group.bench_function("list_global_placeholders", |b| { b.iter(|| { - black_box( - store::global_placeholder_values(&mut corpus.connection).expect("the globals"), - ); + black_box(store::global_placeholder_values(&mut corpus.connection).expect("the globals")); }); }); @@ -227,14 +205,9 @@ fn corpus_rewrite(c: &mut Criterion) { let mut at = 0u32; b.iter(|| { at += 1; - let (from, into) = if at.is_multiple_of(2) { - ("ops", "operations") - } else { - ("operations", "ops") - }; - black_box( - store::retag(&mut corpus.connection, &[from.to_string()], into).expect("a retag"), - ); + let (from, into) = + if at.is_multiple_of(2) { ("ops", "operations") } else { ("operations", "ops") }; + black_box(store::retag(&mut corpus.connection, &[from.to_string()], into).expect("a retag")); }); }); @@ -259,14 +232,8 @@ fn disk(c: &mut Criterion) { let notes = store::all(&mut corpus.connection, None).expect("the corpus"); let packed = bundle::collect(&mut corpus.connection, notes).expect("a bundle"); black_box( - file::write( - &target, - &packed, - &attachments, - corpus.connection.vault(), - None, - ) - .expect("a written file"), + file::write(&target, &packed, &attachments, corpus.connection.vault(), None) + .expect("a written file"), ); }); }); @@ -275,8 +242,7 @@ fn disk(c: &mut Criterion) { b.iter(|| { let (incoming, mut payload) = file::read(&target, None).expect("a readable file"); black_box( - bundle::merge(&mut corpus.connection, incoming, &mut payload, &attachments) - .expect("a merge"), + bundle::merge(&mut corpus.connection, incoming, &mut payload, &attachments).expect("a merge"), ); }); }); @@ -304,25 +270,19 @@ fn attachment(c: &mut Criterion) { created_at: now(), }; let (db, vault) = corpus.connection.split(); - sealed::write_sealed( - vault, - &directory.join(screenshot.stored_name()), - &vec![7u8; 256 * 1024], - ) - .expect("a sealed file"); + sealed::write_sealed(vault, &directory.join(screenshot.stored_name()), &vec![7u8; 256 * 1024]) + .expect("a sealed file"); attachments::store::create(db, vault, &screenshot).expect("a record"); group.bench_function("read_attachment, 256 kB", |b| { b.iter(|| { black_box( - attachments::files::read_plain(&mut corpus.connection, "a-screenshot") - .expect("the bytes"), + attachments::files::read_plain(&mut corpus.connection, "a-screenshot").expect("the bytes"), ) }); }); - let profile = - std::env::temp_dir().join(format!("devnotes-bench-profile-{}", uuid::Uuid::new_v4())); + let profile = std::env::temp_dir().join(format!("devnotes-bench-profile-{}", uuid::Uuid::new_v4())); std::fs::create_dir_all(&profile).expect("a writable temporary directory"); libraries::registry::open_directory_in(&profile).expect("a registry"); @@ -348,12 +308,8 @@ fn unlock(c: &mut Criterion) { group.bench_function("Vault::derive at the shipped cost", |b| { b.iter(|| { black_box( - Vault::derive( - black_box("a passphrase"), - b"0123456789abcdef", - Cost::default(), - ) - .expect("a key"), + Vault::derive(black_box("a passphrase"), b"0123456789abcdef", Cost::default()) + .expect("a key"), ) }); }); @@ -367,11 +323,9 @@ fn cookie_jar(c: &mut Criterion) { use engine::http::cookies::{self, Change, JarCookie}; let scratch = tempfile::tempdir().expect("a temporary directory"); - let mut library = engine::db::open( - &scratch.path().join("jar.sqlite3"), - engine::db::test_vault().expect("a key"), - ) - .expect("a library"); + let mut library = + engine::db::open(&scratch.path().join("jar.sqlite3"), engine::db::test_vault().expect("a key")) + .expect("a library"); let changes: Vec = (0..500) .map(|at| { Change::Set(JarCookie { diff --git a/crates/engine/benches/corpus.rs b/crates/engine/benches/corpus.rs index 9d71d0a5a..1e760976b 100644 --- a/crates/engine/benches/corpus.rs +++ b/crates/engine/benches/corpus.rs @@ -29,9 +29,7 @@ pub(crate) const NOTES: usize = 8000; /// Roughly 13 kB of body. const LINES_PER_NOTE: usize = 200; const SPACES: usize = 4; -const TAGS: &[&str] = &[ - "angular", "api", "ci", "db", "docker", "git", "ops", "rust", "sql", "ssh", -]; +const TAGS: &[&str] = &["angular", "api", "ci", "db", "docker", "git", "ops", "rust", "sql", "ssh"]; /// A database file of its own per group, erased with the guard. pub(crate) struct Corpus { @@ -82,23 +80,14 @@ fn draft(seed: usize, space_id: &str) -> NoteDraft { language: Language::Rs, content: if checklist { String::new() } else { body(seed) }, source: "Runbook".to_string(), - tags: vec![ - TAGS[seed % TAGS.len()].to_string(), - TAGS[(seed + 3) % TAGS.len()].to_string(), - ], + tags: vec![TAGS[seed % TAGS.len()].to_string(), TAGS[(seed + 3) % TAGS.len()].to_string()], pinned: seed.is_multiple_of(50), lifecycle: if seed.is_multiple_of(25) { - NoteLifecycle::Expires { - at: now() + TimeDelta::days(3), - } + NoteLifecycle::Expires { at: now() + TimeDelta::days(3) } } else { NoteLifecycle::Permanent }, - kind: if checklist { - NoteKind::Checklist - } else { - NoteKind::Snippet - }, + kind: if checklist { NoteKind::Checklist } else { NoteKind::Snippet }, priority: Priority::None, items: if checklist { (0..5u32) @@ -125,11 +114,7 @@ pub(crate) fn run_query(corpus: &mut Corpus, request: &NotesQuery) -> Vec Corpus { // The corpus is sealed like a real library, so the benchmarks measure what the // commands really pay, encryption included. - let mut connection = db::open( - &directory.join("bench.sqlite3"), - db::test_vault().expect("a key"), - ) - .expect("a fresh database"); + let mut connection = db::open(&directory.join("bench.sqlite3"), db::test_vault().expect("a key")) + .expect("a fresh database"); let space_ids: Vec = (0..SPACES) - .map(|at| { - spaces::create(&mut connection, &format!("Space {at}")) - .expect("a space") - .id - }) + .map(|at| spaces::create(&mut connection, &format!("Space {at}")).expect("a space").id) .collect(); let at = now(); let note_ids: Vec = (0..notes) .map(|seed| { let space_id = &space_ids[seed % SPACES]; - store::create(&mut connection, draft(seed, space_id), at) - .expect("a note") - .id + store::create(&mut connection, draft(seed, space_id), at).expect("a note").id }) .collect(); - Corpus { - connection, - space_ids, - note_ids, - _directory: TempDir(directory), - } + Corpus { connection, space_ids, note_ids, _directory: TempDir(directory) } } diff --git a/crates/engine/benches/corpus_size.rs b/crates/engine/benches/corpus_size.rs index a70f41796..ede273c5a 100644 --- a/crates/engine/benches/corpus_size.rs +++ b/crates/engine/benches/corpus_size.rs @@ -66,13 +66,9 @@ fn query_by_corpus_size(c: &mut Criterion) { // The same query stopped before the view is built: the gap between the two is // what the view costs, and what a LIMIT could not take away. - group.bench_with_input( - BenchmarkId::new(format!("{name}, read only"), size), - &size, - |b, _| { - b.iter(|| black_box(read_only(&mut corpus, &request))); - }, - ); + group.bench_with_input(BenchmarkId::new(format!("{name}, read only"), size), &size, |b, _| { + b.iter(|| black_box(read_only(&mut corpus, &request))); + }); } } diff --git a/crates/engine/benches/index.rs b/crates/engine/benches/index.rs index 8229dabaa..2142503bf 100644 --- a/crates/engine/benches/index.rs +++ b/crates/engine/benches/index.rs @@ -31,27 +31,16 @@ struct Bench { fn bench(size: Size) -> Bench { let mut corpus = build(size); let runtime = tokio::runtime::Runtime::new().unwrap(); - let paths = Paths { - profile: std::env::temp_dir(), - }; - let engine = Arc::new(Engine::new( - paths, - Arc::new(RecordingSink::default()), - runtime.handle().clone(), - )); + let paths = Paths { profile: std::env::temp_dir() }; + let engine = Arc::new(Engine::new(paths, Arc::new(RecordingSink::default()), runtime.handle().clone())); *engine.db().lock().unwrap() = corpus.library.take(); reference::attach(&engine, &corpus.note_ids); - Bench { - engine, - runtime, - corpus, - } + Bench { engine, runtime, corpus } } impl Bench { fn fill(&self) { - self.runtime - .block_on(engine::index::fill(Arc::clone(&self.engine))); + self.runtime.block_on(engine::index::fill(Arc::clone(&self.engine))); } } @@ -103,17 +92,11 @@ fn index_query(c: &mut Criterion) { let engine = &bench.engine; let mut group = c.benchmark_group(format!("index_query/{}", label(size))); group.sample_size(20); - for (name, search) in [ - ("unfiltered", ""), - ("search matching nothing", "zzzzzz"), - ("search folding accents", "etape"), - ] { + for (name, search) in + [("unfiltered", ""), ("search matching nothing", "zzzzzz"), ("search folding accents", "etape")] + { group.bench_function(name, |b| { - b.iter(|| { - black_box(run_here(engine, |e| { - query_notes(e, &query(search)).unwrap() - })) - }); + b.iter(|| black_box(run_here(engine, |e| query_notes(e, &query(search)).unwrap()))); }); } let space = bench.corpus.space_ids[0].clone(); @@ -145,10 +128,7 @@ fn index_refresh(c: &mut Criterion) { let mut n = 0_u32; b.iter(|| { n += 1; - let patch = NotePatch { - title: Some(format!("Retitrée {n}")), - ..NotePatch::default() - }; + let patch = NotePatch { title: Some(format!("Retitrée {n}")), ..NotePatch::default() }; black_box(run_here(engine, |e| update_note(e, &id, &patch).unwrap())) }); }); diff --git a/crates/engine/benches/reference.rs b/crates/engine/benches/reference.rs index d8162d08e..a7a631829 100644 --- a/crates/engine/benches/reference.rs +++ b/crates/engine/benches/reference.rs @@ -88,20 +88,13 @@ fn line(seed: usize) -> &'static str { } fn lines(seed: usize, count: usize) -> String { - (0..count) - .map(|n| line(seed + n)) - .collect::>() - .join("\n") + (0..count).map(|n| line(seed + n)).collect::>().join("\n") } fn markdown(seed: usize) -> String { let mut text = format!("# Procédure {seed}\n\n"); for section in 0..4 { - let _ = write!( - text, - "## Étape {section}\n\n{}\n\n", - lines(seed + section, 4) - ); + let _ = write!(text, "## Étape {section}\n\n{}\n\n", lines(seed + section, 4)); text.push_str("- vérifier\n- **déployer**\n- surveiller\n\n"); text.push_str("| hôte | rôle |\n| --- | --- |\n| db-1 | primaire |\n\n"); let _ = write!(text, "```sql\n{}\n```\n\n", lines(seed, 3)); @@ -169,17 +162,10 @@ fn note(n: usize, size: Size, space_id: &str, folder_id: Option<&str>) -> Note { space_id: space_id.to_string(), folder_id: folder_id.map(str::to_string), title: format!("Note {n} — étape de déploiement"), - language: if kind == NoteKind::Snippet { - LANGUAGES[n % LANGUAGES.len()] - } else { - Language::Txt - }, + language: if kind == NoteKind::Snippet { LANGUAGES[n % LANGUAGES.len()] } else { Language::Txt }, content, source: format!("API Gateway / Auth / {}", n % 50), - tags: vec![ - format!("tag-{}", n % TAGS), - format!("tag-{}", (n * 7) % TAGS), - ], + tags: vec![format!("tag-{}", n % TAGS), format!("tag-{}", (n * 7) % TAGS)], pinned: n.is_multiple_of(97), created_at: at, updated_at: at, @@ -196,30 +182,20 @@ fn uuid(n: usize) -> String { } pub(crate) fn build(size: Size) -> Reference { - let directory = - std::env::temp_dir().join(format!("devnotes-reference-{}", uuid::Uuid::new_v4())); + let directory = std::env::temp_dir().join(format!("devnotes-reference-{}", uuid::Uuid::new_v4())); std::fs::create_dir_all(&directory).unwrap(); let vault = engine::vault::file::create(&directory, "a passphrase", Cost::FOR_TESTS).unwrap(); let mut library = db::open(&directory.join("devnotes.sqlite3"), vault).unwrap(); let (space_ids, note_ids) = seed(&mut library, size); std::fs::create_dir_all(directory.join("attachments")).unwrap(); - Reference { - library: Some(library), - note_ids, - space_ids, - _directory: Directory(directory), - } + Reference { library: Some(library), note_ids, space_ids, _directory: Directory(directory) } } /// Everything but the attachments, into a library already open: the spaces, then the notes. pub(crate) fn seed(library: &mut Library, size: Size) -> (Vec, Vec) { let space_ids: Vec = (0..SPACES) - .map(|n| { - engine::spaces::store::create(library, &format!("Espace {n}")) - .unwrap() - .id - }) + .map(|n| engine::spaces::store::create(library, &format!("Espace {n}")).unwrap().id) .collect(); let folder_ids = folders(library, &space_ids); let note_ids = notes(library, size, &space_ids, &folder_ids); @@ -330,15 +306,10 @@ fn http(library: &mut Library) { }, }; let name = draft.name.clone(); - request_ids.push( - engine::http::store::create_request(library, &draft, &name, now()) - .unwrap() - .id, - ); + request_ids.push(engine::http::store::create_request(library, &draft, &name, now()).unwrap().id); } for n in 0..ENVIRONMENTS { - engine::http::environments::store::create(library, &format!("Environnement {n}"), now()) - .unwrap(); + engine::http::environments::store::create(library, &format!("Environnement {n}"), now()).unwrap(); } for n in 0..HISTORY { let summary = serde_json::from_value(serde_json::json!({ diff --git a/crates/engine/benches/reference_profile.rs b/crates/engine/benches/reference_profile.rs index 1b31eb68b..3bf7f5cef 100644 --- a/crates/engine/benches/reference_profile.rs +++ b/crates/engine/benches/reference_profile.rs @@ -31,11 +31,7 @@ fn main() { std::fs::create_dir_all(&profile).unwrap(); let runtime = tokio::runtime::Runtime::new().unwrap(); let paths = Paths { profile }; - let engine = Arc::new(Engine::new( - paths, - Arc::new(RecordingSink::default()), - runtime.handle().clone(), - )); + let engine = Arc::new(Engine::new(paths, Arc::new(RecordingSink::default()), runtime.handle().clone())); run_here(&engine, |e| create_vault(e, secret(PASSPHRASE.to_owned()))).unwrap(); let (_, note_ids) = run_here(&engine, |e| { let mut library = e.db().lock().unwrap(); diff --git a/crates/engine/build.rs b/crates/engine/build.rs index 9c350d6c4..639443b0e 100644 --- a/crates/engine/build.rs +++ b/crates/engine/build.rs @@ -13,8 +13,8 @@ fn export_metadata() { println!("cargo:rerun-if-changed=Cargo.toml"); let manifest_dir = env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set by cargo"); - let text = fs::read_to_string(Path::new(&manifest_dir).join("Cargo.toml")) - .expect("Cargo.toml is readable"); + let text = + fs::read_to_string(Path::new(&manifest_dir).join("Cargo.toml")).expect("Cargo.toml is readable"); let manifest: toml::Table = toml::from_str(&text).expect("Cargo.toml is valid TOML"); let metadata = manifest @@ -38,10 +38,7 @@ fn export_metadata() { let author = authors.split(';').next().unwrap_or_default(); println!("cargo:rustc-env=DEVNOTES_AUTHOR={author}"); - println!( - "cargo:rustc-env=DEVNOTES_RUST_VERSION={}", - pinned_toolchain(&manifest_dir) - ); + println!("cargo:rustc-env=DEVNOTES_RUST_VERSION={}", pinned_toolchain(&manifest_dir)); } /// Every page of `docs/content`, by language and name, for `docs.rs` to embed: a page added there @@ -59,11 +56,7 @@ fn list_the_documentation() { let path = file.expect("docs/content is readable").path(); if path.extension().is_some_and(|extension| extension == "md") { let id = path.file_stem().and_then(|stem| stem.to_str()); - pages.push(( - language, - id.expect("a page's name is text").to_owned(), - path, - )); + pages.push((language, id.expect("a page's name is text").to_owned(), path)); } } } @@ -72,8 +65,7 @@ fn list_the_documentation() { let mut out = String::from("const SOURCES: &[(&str, &str, &str)] = &[\n"); for (language, id, path) in pages { let path = path.to_str().expect("the repository is at a path of text"); - writeln!(out, " ({language:?}, {id:?}, include_str!({path:?})),") - .expect("a string grows"); + writeln!(out, " ({language:?}, {id:?}, include_str!({path:?})),").expect("a string grows"); } out.push_str("];\n"); let target = Path::new(&env::var("OUT_DIR").expect("cargo sets OUT_DIR")).join("docs.rs"); diff --git a/crates/engine/src/attachments.rs b/crates/engine/src/attachments.rs index bee45db98..b33e99d29 100644 --- a/crates/engine/src/attachments.rs +++ b/crates/engine/src/attachments.rs @@ -34,10 +34,7 @@ pub async fn attach_file( crate::db::run(engine, move |engine| { engine.write(|db| { let answer = store_new(note_id, file_name, &bytes, db)?; - let changed = Changed { - attachments: true, - ..Changed::default() - }; + let changed = Changed { attachments: true, ..Changed::default() }; Ok((answer, changed)) }) }) @@ -97,10 +94,7 @@ pub fn attach_image( let png = model::encode_png(width, height, rgba)?; model::validate_size(png.len() as u64, &model::png_name(file_name))?; let answer = store_new(note_id, model::png_name(file_name), &png, db)?; - let changed = Changed { - attachments: true, - ..Changed::default() - }; + let changed = Changed { attachments: true, ..Changed::default() }; Ok((answer, changed)) }) } @@ -108,10 +102,7 @@ pub fn attach_image( pub fn delete_attachment(engine: &Engine, id: &str) -> Result<(), AppError> { engine.write(|db| { delete(db, id)?; - let changed = Changed { - attachments: true, - ..Changed::default() - }; + let changed = Changed { attachments: true, ..Changed::default() }; Ok(((), changed)) }) } diff --git a/crates/engine/src/attachments/files.rs b/crates/engine/src/attachments/files.rs index 54e14ad23..7d4b1f12a 100644 --- a/crates/engine/src/attachments/files.rs +++ b/crates/engine/src/attachments/files.rs @@ -66,8 +66,8 @@ pub(crate) fn store_new( let destination = directory.join(attachment.stored_name()); let (db, vault) = connection.split(); - let stored = sealed::write_sealed(vault, &destination, bytes) - .and_then(|_| store::create(db, vault, &attachment)); + let stored = + sealed::write_sealed(vault, &destination, bytes).and_then(|_| store::create(db, vault, &attachment)); if stored.is_err() { remove_files(&directory, &[attachment.stored_name()]); } @@ -114,12 +114,9 @@ pub(crate) fn write_plain(path: &str, bytes: &[u8]) -> Result<(), StorageError> std::fs::write(path, bytes).context(path) } -fn locate( - library: &mut Library, - id: &str, -) -> Result<(Attachment, PathBuf, Arc), StorageError> { - let attachment = store::find(library, id)? - .ok_or_else(|| StorageError::AttachmentNotFound(id.to_string()))?; +fn locate(library: &mut Library, id: &str) -> Result<(Attachment, PathBuf, Arc), StorageError> { + let attachment = + store::find(library, id)?.ok_or_else(|| StorageError::AttachmentNotFound(id.to_string()))?; let path = directory(library).join(attachment.stored_name()); Ok((attachment, path, library.shared_vault())) @@ -129,10 +126,7 @@ fn locate( pub fn sweep_orphan_files(db: &Db) -> Result { let (directory, known) = { let mut connection = lock(db)?; - ( - directory(&connection), - store::all_stored_names(&mut connection)?, - ) + (directory(&connection), store::all_stored_names(&mut connection)?) }; let entries = std::fs::read_dir(&directory).context("attachments sweep")?; @@ -192,10 +186,7 @@ pub(crate) mod tests { fn attachments_live_in_the_library_s_own_directory() { let (scratch, db, _) = a_library_with_a_note(); - assert_eq!( - attachments_of(&db), - scratch.path().join(crate::layout::ATTACHMENTS) - ); + assert_eq!(attachments_of(&db), scratch.path().join(crate::layout::ATTACHMENTS)); } /// Sealed like the rows beside it: the plain bytes are nowhere on disk. @@ -208,10 +199,7 @@ pub(crate) mod tests { let on_disk = std::fs::read(attachments_of(&db).join(stored.stored_name())).unwrap(); assert!(!on_disk.windows(bytes.len()).any(|window| window == bytes)); - assert_eq!( - (stored.byte_size, stored.mime_type.as_str()), - (18, "image/png") - ); + assert_eq!((stored.byte_size, stored.mime_type.as_str()), (18, "image/png")); assert_eq!(listed(&db, ¬e_id)[0].id, stored.id); } @@ -220,12 +208,7 @@ pub(crate) mod tests { fn an_attachment_of_a_note_not_there_leaves_no_file() { let (_scratch, db, _) = a_library_with_a_note(); - let refused = store_new( - "missing".to_string(), - "capture.png".to_string(), - b"png", - &db, - ); + let refused = store_new("missing".to_string(), "capture.png".to_string(), b"png", &db); assert!(matches!(refused, Err(StorageError::NoteNotFound(id)) if id == "missing")); assert_eq!(std::fs::read_dir(attachments_of(&db)).unwrap().count(), 0); @@ -239,15 +222,9 @@ pub(crate) mod tests { let (record, bytes) = read_plain(&mut lock(&db).unwrap(), &stored.id).unwrap(); let (_, outside) = read_outside_lock(&db, &stored.id).unwrap(); - assert_eq!( - (record.file_name.as_str(), bytes.as_slice()), - ("notes.txt", &b"plain"[..]) - ); + assert_eq!((record.file_name.as_str(), bytes.as_slice()), ("notes.txt", &b"plain"[..])); assert_eq!(outside, b"plain"); - assert!( - db.try_lock().is_ok(), - "the lock is free once the bytes are in hand" - ); + assert!(db.try_lock().is_ok(), "the lock is free once the bytes are in hand"); } /// Opening a file nothing refers to would read outside what the library knows. @@ -257,10 +234,7 @@ pub(crate) mod tests { std::fs::write(attachments_of(&db).join("stray"), b"stray").unwrap(); for id in ["stray", "missing"] { - assert!(matches!( - read_outside_lock(&db, id), - Err(StorageError::AttachmentNotFound(_)) - )); + assert!(matches!(read_outside_lock(&db, id), Err(StorageError::AttachmentNotFound(_)))); } } @@ -276,10 +250,7 @@ pub(crate) mod tests { assert_eq!(read.len() as u64, model::MAX_BYTES + 1); let missing = scratch.path().join("missing.bin"); - assert!(matches!( - read_within_limit(&missing.to_string_lossy()), - Err(StorageError::File(_)) - )); + assert!(matches!(read_within_limit(&missing.to_string_lossy()), Err(StorageError::File(_)))); } /// Two copies of one name do not overwrite each other. diff --git a/crates/engine/src/attachments/model.rs b/crates/engine/src/attachments/model.rs index cd7a875d3..635af260c 100644 --- a/crates/engine/src/attachments/model.rs +++ b/crates/engine/src/attachments/model.rs @@ -54,21 +54,13 @@ fn copy_name(id: &str, file_name: &str) -> String { } }) .collect(); - let mut name = replaced - .trim_end_matches(['.', ' ']) - .trim_start() - .to_string(); + let mut name = replaced.trim_end_matches(['.', ' ']).trim_start().to_string(); if name.chars().count() > COPY_NAME_CHARS { let extension = extension_of(&name).map(|extension| format!(".{extension}")); let kept = COPY_NAME_CHARS - extension.as_ref().map_or(0, String::len); name = name.chars().take(kept).collect::() + extension.as_deref().unwrap_or(""); } - let stem = name - .split('.') - .next() - .unwrap_or_default() - .trim_end() - .to_ascii_uppercase(); + let stem = name.split('.').next().unwrap_or_default().trim_end().to_ascii_uppercase(); let device = matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL") || ((stem.starts_with("COM") || stem.starts_with("LPT")) && stem.len() == 4 @@ -100,10 +92,7 @@ fn contained(id: &str) -> String { /// Lowercase and alphanumeric: separators, `..` or colons would escape the directory. fn extension_of(file_name: &str) -> Option { let candidate = file_name.rsplit_once('.')?.1; - if candidate.is_empty() - || candidate.len() > 8 - || !candidate.chars().all(|c| c.is_ascii_alphanumeric()) - { + if candidate.is_empty() || candidate.len() > 8 || !candidate.chars().all(|c| c.is_ascii_alphanumeric()) { return None; } @@ -141,12 +130,7 @@ pub fn mime_of(file_name: &str) -> String { /// Stripped of any path: an import must not show `../../secrets/key.pem` as a note's own. pub fn display_name(path: &str) -> Result { - let trimmed = path - .rsplit(['/', '\\']) - .next() - .unwrap_or_default() - .trim() - .to_string(); + let trimmed = path.rsplit(['/', '\\']).next().unwrap_or_default().trim().to_string(); if trimmed.is_empty() || trimmed == "." || trimmed == ".." { return Err(ValidationError::new("fileName", "unreadable file name")); @@ -159,24 +143,14 @@ pub fn display_name(path: &str) -> Result { /// `mime_of` answers `application/octet-stream` and skips the preview. pub fn png_name(base: &str) -> String { let trimmed = base.trim(); - let stem = if trimmed.is_empty() { - "capture" - } else { - trimmed - }; + let stem = if trimmed.is_empty() { "capture" } else { trimmed }; - if stem.to_ascii_lowercase().ends_with(".png") { - stem.to_string() - } else { - format!("{stem}.png") - } + if stem.to_ascii_lowercase().ends_with(".png") { stem.to_string() } else { format!("{stem}.png") } } /// Encodes raw RGBA — what the system clipboard hands over — into PNG. pub fn encode_png(width: u32, height: u32, rgba: &[u8]) -> Result, StorageError> { - let expected = (width as usize) - .saturating_mul(height as usize) - .saturating_mul(4); + let expected = (width as usize).saturating_mul(height as usize).saturating_mul(4); if width == 0 || height == 0 || rgba.len() < expected { return Err(StorageError::File(format!( "clipboard image of {width}×{height} carries {} bytes, {expected} expected", @@ -190,9 +164,7 @@ pub fn encode_png(width: u32, height: u32, rgba: &[u8]) -> Result, Stora encoder.set_color(png::ColorType::Rgba); encoder.set_depth(png::BitDepth::Eight); let mut writer = encoder.write_header().context("png header")?; - writer - .write_image_data(&rgba[..expected]) - .context("png data")?; + writer.write_image_data(&rgba[..expected]).context("png data")?; } Ok(png) @@ -205,10 +177,7 @@ const _: () = assert!(MAX_BYTES == MAX_MEGABYTES as u64 * 1024 * 1024); pub fn validate_size(byte_size: u64, name: &str) -> Result { if byte_size > MAX_BYTES { - return Err(StorageError::TooLarge { - name: name.to_string(), - limit_mb: MAX_MEGABYTES, - }); + return Err(StorageError::TooLarge { name: name.to_string(), limit_mb: MAX_MEGABYTES }); } Ok(saturating_u32(byte_size)) @@ -235,11 +204,7 @@ mod tests { ("a-1", "Capture.PNG", "a-1.png"), ("a-1", "archive.tar.gz", "a-1.gz"), ("a-1", "notes", "a-1"), - ( - "3f2504e0-4f89-41d3-9a0c-0305e82c3301", - "x.png", - "3f2504e0-4f89-41d3-9a0c-0305e82c3301.png", - ), + ("3f2504e0-4f89-41d3-9a0c-0305e82c3301", "x.png", "3f2504e0-4f89-41d3-9a0c-0305e82c3301.png"), ]; for (id, file_name, stored) in cases { @@ -324,11 +289,7 @@ mod tests { assert_eq!(display_name(path), Ok(shown.to_string()), "{path}"); } for unreadable in ["", "folder/", ".", "..", " "] { - assert_eq!( - display_name(unreadable).unwrap_err().field, - "fileName", - "{unreadable:?}" - ); + assert_eq!(display_name(unreadable).unwrap_err().field, "fileName", "{unreadable:?}"); } } @@ -372,10 +333,7 @@ mod tests { #[test] fn a_file_is_attached_up_to_ten_megabytes_and_refused_past_them() { - assert_eq!( - validate_size(MAX_BYTES, "big.bin").unwrap(), - 10 * 1024 * 1024 - ); + assert_eq!(validate_size(MAX_BYTES, "big.bin").unwrap(), 10 * 1024 * 1024); assert!(matches!( validate_size(MAX_BYTES + 1, "big.bin"), Err(StorageError::TooLarge { name, limit_mb: 10 }) if name == "big.bin" @@ -385,14 +343,8 @@ mod tests { /// Two copies of one name must not meet: each sits in a folder of its own. #[test] fn an_opened_copy_sits_in_a_folder_of_its_own_under_its_own_name() { - assert_eq!( - attachment("a-1", "Rapport.pdf").opened_copy(), - PathBuf::from("a-1").join("Rapport.pdf") - ); - assert_eq!( - attachment("../a-1", "x.pdf").opened_copy(), - PathBuf::from("a-1").join("x.pdf") - ); + assert_eq!(attachment("a-1", "Rapport.pdf").opened_copy(), PathBuf::from("a-1").join("Rapport.pdf")); + assert_eq!(attachment("../a-1", "x.pdf").opened_copy(), PathBuf::from("a-1").join("x.pdf")); } /// What Windows forbids is replaced; a device name or nothing left falls back on the diff --git a/crates/engine/src/attachments/sealed.rs b/crates/engine/src/attachments/sealed.rs index b3b149241..bb7619857 100644 --- a/crates/engine/src/attachments/sealed.rs +++ b/crates/engine/src/attachments/sealed.rs @@ -38,10 +38,7 @@ pub fn sweep_plaintext(paths: &Paths) { if let Err(error) = std::fs::remove_dir_all(&directory) && error.kind() != std::io::ErrorKind::NotFound { - log::warn!( - "Decrypted copies not swept from {}: {error}", - directory.display() - ); + log::warn!("Decrypted copies not swept from {}: {error}", directory.display()); } } @@ -58,14 +55,9 @@ mod tests { #[test] fn the_decrypted_copies_live_under_the_profile_and_go_in_one_sweep() { let profile = tempfile::tempdir().unwrap(); - let paths = Paths { - profile: profile.path().to_path_buf(), - }; + let paths = Paths { profile: profile.path().to_path_buf() }; let directory = plaintext_directory(&paths); - assert_eq!( - directory, - profile.path().join(crate::layout::PLAINTEXT_COPIES) - ); + assert_eq!(directory, profile.path().join(crate::layout::PLAINTEXT_COPIES)); sweep_plaintext(&paths); std::fs::create_dir_all(&directory).unwrap(); @@ -121,8 +113,7 @@ mod tests { let target = directory.join("capture.png"); write_sealed(&vault(), &target, b"bytes").unwrap(); - let other = - Vault::derive("another passphrase", b"0123456789abcdef", Cost::FOR_TESTS).unwrap(); + let other = Vault::derive("another passphrase", b"0123456789abcdef", Cost::FOR_TESTS).unwrap(); assert!(read_sealed(&other, &target).is_err()); } diff --git a/crates/engine/src/attachments/store.rs b/crates/engine/src/attachments/store.rs index 5de5a2d49..1ecfee619 100644 --- a/crates/engine/src/attachments/store.rs +++ b/crates/engine/src/attachments/store.rs @@ -26,10 +26,8 @@ struct AttachmentRow { /// `{id}.{extension}`, so the type is already public. Sealing it would be theatre. impl AttachmentRow { fn open(row: Self, vault: &Vault) -> Result { - let created_at = iso8601::parse(&row.created_at).map_err(|_| StorageError::CorruptRow { - id: row.id.clone(), - field: "createdAt", - })?; + let created_at = iso8601::parse(&row.created_at) + .map_err(|_| StorageError::CorruptRow { id: row.id.clone(), field: "createdAt" })?; Ok(Attachment { byte_size: saturating_u32(row.byte_size), @@ -116,10 +114,7 @@ pub fn delete(connection: &mut SqliteConnection, id: &str) -> Result<(), Storage /// The records an export carries. The bytes are not here: the caller reads them from the /// attachments directory by [`model::stored_name`]. -pub fn for_notes( - connection: &mut Library, - note_ids: &[String], -) -> Result, StorageError> { +pub fn for_notes(connection: &mut Library, note_ids: &[String]) -> Result, StorageError> { if note_ids.is_empty() { return Ok(Vec::new()); } @@ -137,10 +132,7 @@ pub fn for_notes( } /// ⚠️ Collected before a purge: the cascade takes the records, never the files. -pub fn stored_names_of( - connection: &mut Library, - note_ids: &[String], -) -> Result, StorageError> { +pub fn stored_names_of(connection: &mut Library, note_ids: &[String]) -> Result, StorageError> { if note_ids.is_empty() { return Ok(Vec::new()); } @@ -211,12 +203,7 @@ mod tests { .id } - fn attachment( - id: &str, - note_id: &str, - file_name: &str, - created_at: DateTime, - ) -> Attachment { + fn attachment(id: &str, note_id: &str, file_name: &str, created_at: DateTime) -> Attachment { Attachment { id: id.to_string(), note_id: note_id.to_string(), @@ -233,10 +220,7 @@ mod tests { } fn ids(attachments: &[Attachment]) -> Vec<&str> { - attachments - .iter() - .map(|attachment| attachment.id.as_str()) - .collect() + attachments.iter().map(|attachment| attachment.id.as_str()).collect() } /// The foreign key would refuse it too, in words the screen cannot translate. @@ -250,10 +234,7 @@ mod tests { for note_id in ["missing", trashed.as_str()] { let refused = create(db, vault, &attachment("a-1", note_id, "x.png", Utc::now())); - assert!( - matches!(refused, Err(StorageError::NoteNotFound(id)) if id == note_id), - "{note_id}" - ); + assert!(matches!(refused, Err(StorageError::NoteNotFound(id)) if id == note_id), "{note_id}"); } } @@ -262,18 +243,9 @@ mod tests { let mut library = open_in_memory().unwrap(); let note = note_in(&mut library); let other = note_in(&mut library); - record( - &mut library, - &attachment("late", ¬e, "b.png", at("2026-07-25T11:00:00.000Z")), - ); - record( - &mut library, - &attachment("early", ¬e, "a.png", at("2026-07-25T10:00:00.000Z")), - ); - record( - &mut library, - &attachment("else", &other, "c.png", at("2026-07-25T10:00:00.000Z")), - ); + record(&mut library, &attachment("late", ¬e, "b.png", at("2026-07-25T11:00:00.000Z"))); + record(&mut library, &attachment("early", ¬e, "a.png", at("2026-07-25T10:00:00.000Z"))); + record(&mut library, &attachment("else", &other, "c.png", at("2026-07-25T10:00:00.000Z"))); assert_eq!(ids(&list(&mut library, ¬e).unwrap()), ["early", "late"]); } @@ -283,12 +255,7 @@ mod tests { fn a_record_s_name_is_sealed_and_read_back_whole() { let mut library = open_in_memory().unwrap(); let note = note_in(&mut library); - let made = attachment( - "a-1", - ¬e, - "secret plan.png", - at("2026-07-25T10:00:00.000Z"), - ); + let made = attachment("a-1", ¬e, "secret plan.png", at("2026-07-25T10:00:00.000Z")); record(&mut library, &made); let (name, mime): (String, String) = attachments::table @@ -344,18 +311,9 @@ mod tests { let first = note_in(&mut library); let second = note_in(&mut library); let left = note_in(&mut library); - record( - &mut library, - &attachment("a-1", &first, "Shot.PNG", at("2026-07-25T10:00:00.000Z")), - ); - record( - &mut library, - &attachment("a-2", &second, "notes", at("2026-07-25T11:00:00.000Z")), - ); - record( - &mut library, - &attachment("a-3", &left, "x.pdf", at("2026-07-25T12:00:00.000Z")), - ); + record(&mut library, &attachment("a-1", &first, "Shot.PNG", at("2026-07-25T10:00:00.000Z"))); + record(&mut library, &attachment("a-2", &second, "notes", at("2026-07-25T11:00:00.000Z"))); + record(&mut library, &attachment("a-3", &left, "x.pdf", at("2026-07-25T12:00:00.000Z"))); let chosen = [first, second]; let records = for_notes(&mut library, &chosen).unwrap(); diff --git a/crates/engine/src/backup.rs b/crates/engine/src/backup.rs index 818950ba5..0ea99f9f1 100644 --- a/crates/engine/src/backup.rs +++ b/crates/engine/src/backup.rs @@ -85,11 +85,7 @@ pub fn take_restored_aside(engine: &Engine) -> Option { fn restore(db: &Db, id: &str, now: DateTime) -> Result { let mut open = db.lock().map_err(|_| StorageError::Unavailable)?; - let directory = open - .as_ref() - .ok_or(StorageError::Locked)? - .directory() - .to_path_buf(); + let directory = open.as_ref().ok_or(StorageError::Locked)?.directory().to_path_buf(); // Dropped before a single file moves, and the lock held for the whole swap. *open = None; diff --git a/crates/engine/src/backup/copies.rs b/crates/engine/src/backup/copies.rs index f4db3eb9b..4283e0729 100644 --- a/crates/engine/src/backup/copies.rs +++ b/crates/engine/src/backup/copies.rs @@ -154,11 +154,7 @@ pub(crate) fn list(library: &Path) -> Vec { /// Moved aside into `replaced/`, never deleted, and `vault.json` with it: the copy brings its /// own, and a database and a key from two wrappings open nothing. `attachments/` goes too, and /// the copy's is linked back: an attachment added since is kept aside, not lost. -pub(crate) fn replace( - library: &Path, - id: &str, - now: DateTime, -) -> Result { +pub(crate) fn replace(library: &Path, id: &str, now: DateTime) -> Result { // ⚠️ Matched against the listing, never joined: the id comes from the front end, and // `../2026-01-01_00-00-00` joins to a path outside `backups/` that still parses as a stamp. let copy = existing(&library.join(BACKUPS)) @@ -213,11 +209,7 @@ fn copy_back(copy: &Path, library: &Path) -> Result<(), String> { fn put_back(moved: &[(PathBuf, PathBuf)], aside: &Path) { for (from, to) in moved { - let _ = if from.is_dir() { - std::fs::remove_dir_all(from) - } else { - std::fs::remove_file(from) - }; + let _ = if from.is_dir() { std::fs::remove_dir_all(from) } else { std::fs::remove_file(from) }; let _ = std::fs::rename(to, from); } let _ = std::fs::remove_dir_all(aside); @@ -250,10 +242,7 @@ pub(crate) fn rewrap(library: &Path, vault: &Vault, passphrase: &str, cost: Cost match crate::vault::file::write_wrapped(&path, vault, passphrase, cost) { Ok(()) => tally.done += 1, Err(error) => { - log::warn!( - "{}: still opens with the old passphrase: {error}", - path.display() - ); + log::warn!("{}: still opens with the old passphrase: {error}", path.display()); tally.left += 1; } } @@ -298,9 +287,7 @@ mod tests { let vault = file::create(directory, PHRASE, Cost::FOR_TESTS).unwrap(); let mut connection = db::open(&directory.join(layout::DATABASE), vault).unwrap(); let space = spaces::create(&mut connection, "Work").unwrap().id; - let note = notes::create(&mut connection, draft(&space, "Kept"), at(0)) - .unwrap() - .id; + let note = notes::create(&mut connection, draft(&space, "Kept"), at(0)).unwrap().id; std::fs::create_dir_all(directory.join(ATTACHMENTS)).unwrap(); std::fs::write(directory.join(ATTACHMENTS).join("a-1.png"), b"png").unwrap(); @@ -315,10 +302,7 @@ mod tests { } fn ids(directory: &Path) -> Vec { - list(directory) - .into_iter() - .map(|backup| backup.id) - .collect() + list(directory).into_iter().map(|backup| backup.id).collect() } /// A copy that cannot be opened is no backup: its key file travels, its attachments too. @@ -327,19 +311,11 @@ mod tests { let scratch = tempfile::tempdir().unwrap(); let (mut connection, _) = library(scratch.path()); - let target = rotate(scratch.path(), &mut connection, at(0)) - .unwrap() - .unwrap(); + let target = rotate(scratch.path(), &mut connection, at(0)).unwrap().unwrap(); - assert_eq!( - target, - scratch.path().join(BACKUPS).join(layout::stamp(at(0))) - ); + assert_eq!(target, scratch.path().join(BACKUPS).join(layout::stamp(at(0)))); assert_eq!(titles_in(&target, PHRASE), ["Kept"]); - assert_eq!( - std::fs::read(target.join(ATTACHMENTS).join("a-1.png")).unwrap(), - b"png" - ); + assert_eq!(std::fs::read(target.join(ATTACHMENTS).join("a-1.png")).unwrap(), b"png"); } /// One file under two names: the copy costs no disk, and a purge in the library only @@ -350,16 +326,11 @@ mod tests { let scratch = tempfile::tempdir().unwrap(); let (mut connection, _) = library(scratch.path()); - let target = rotate(scratch.path(), &mut connection, at(0)) - .unwrap() - .unwrap(); + let target = rotate(scratch.path(), &mut connection, at(0)).unwrap().unwrap(); let live = scratch.path().join(ATTACHMENTS).join("a-1.png"); let copied = target.join(ATTACHMENTS).join("a-1.png"); - let mut through_the_library = std::fs::OpenOptions::new() - .append(true) - .open(&live) - .unwrap(); + let mut through_the_library = std::fs::OpenOptions::new().append(true).open(&live).unwrap(); through_the_library.write_all(b", once").unwrap(); drop(through_the_library); std::fs::remove_file(&live).unwrap(); @@ -374,9 +345,7 @@ mod tests { let (mut connection, _) = library(scratch.path()); std::fs::create_dir_all(scratch.path().join(ATTACHMENTS).join("stray")).unwrap(); - let target = rotate(scratch.path(), &mut connection, at(0)) - .unwrap() - .unwrap(); + let target = rotate(scratch.path(), &mut connection, at(0)).unwrap().unwrap(); assert!(target.join(ATTACHMENTS).join("a-1.png").is_file()); assert!(!target.join(ATTACHMENTS).join("stray").exists()); @@ -415,25 +384,13 @@ mod tests { } std::fs::write(directory.join(KEY_FILE), b"half copied").unwrap(); std::fs::create_dir_all(directory.join(ATTACHMENTS)).unwrap(); - std::fs::write( - directory.join(ATTACHMENTS).join("from-the-copy.png"), - b"half", - ) - .unwrap(); + std::fs::write(directory.join(ATTACHMENTS).join("from-the-copy.png"), b"half").unwrap(); put_back(&moved, &aside); - assert_eq!( - std::fs::read(directory.join(KEY_FILE)).unwrap(), - b"live key" - ); + assert_eq!(std::fs::read(directory.join(KEY_FILE)).unwrap(), b"live key"); assert!(directory.join(ATTACHMENTS).join("a-1.png").is_file()); - assert!( - !directory - .join(ATTACHMENTS) - .join("from-the-copy.png") - .exists() - ); + assert!(!directory.join(ATTACHMENTS).join("from-the-copy.png").exists()); assert!(!aside.exists()); } @@ -450,10 +407,7 @@ mod tests { let retried = rotate(scratch.path(), &mut connection, at(1)).unwrap(); assert!(matches!(failed, Err(StorageError::File(_)))); - assert_eq!( - retried, - Some(scratch.path().join(BACKUPS).join(layout::stamp(at(1)))) - ); + assert_eq!(retried, Some(scratch.path().join(BACKUPS).join(layout::stamp(at(1))))); assert_eq!(list(scratch.path()).len(), 1); } @@ -482,10 +436,7 @@ mod tests { rotate(scratch.path(), &mut connection, at(24 * day)).unwrap(); } - let kept: Vec = [4, 3, 2] - .iter() - .map(|day| layout::stamp(at(24 * day))) - .collect(); + let kept: Vec = [4, 3, 2].iter().map(|day| layout::stamp(at(24 * day))).collect(); assert_eq!(ids(scratch.path()), kept); } @@ -495,30 +446,19 @@ mod tests { fn a_copy_is_listed_with_its_size_and_whether_it_opens() { let scratch = tempfile::tempdir().unwrap(); let (mut connection, _) = library(scratch.path()); - let whole = rotate(scratch.path(), &mut connection, at(0)) - .unwrap() - .unwrap(); - let keyless = rotate(scratch.path(), &mut connection, at(48)) - .unwrap() - .unwrap(); + let whole = rotate(scratch.path(), &mut connection, at(0)).unwrap().unwrap(); + let keyless = rotate(scratch.path(), &mut connection, at(48)).unwrap().unwrap(); std::fs::remove_file(keyless.join(KEY_FILE)).unwrap(); std::fs::create_dir_all(scratch.path().join(BACKUPS).join("not a stamp")).unwrap(); let listed = list(scratch.path()); - let shown: Vec<(&str, bool)> = listed - .iter() - .map(|backup| (backup.id.as_str(), backup.openable)) - .collect(); + let shown: Vec<(&str, bool)> = + listed.iter().map(|backup| (backup.id.as_str(), backup.openable)).collect(); let (whole_id, keyless_id) = (layout::stamp(at(0)), layout::stamp(at(48))); - assert_eq!( - shown, - [(keyless_id.as_str(), false), (whole_id.as_str(), true)] - ); + assert_eq!(shown, [(keyless_id.as_str(), false), (whole_id.as_str(), true)]); assert_eq!(listed[1].taken_at, at(0)); - let size = std::fs::metadata(whole.join(layout::DATABASE)) - .unwrap() - .len(); + let size = std::fs::metadata(whole.join(layout::DATABASE)).unwrap().len(); assert_eq!(listed[1].bytes, size); } @@ -550,9 +490,7 @@ mod tests { fn a_copy_not_there_or_without_its_key_is_not_put_back() { let scratch = tempfile::tempdir().unwrap(); let (mut connection, _) = library(scratch.path()); - let copy = rotate(scratch.path(), &mut connection, at(0)) - .unwrap() - .unwrap(); + let copy = rotate(scratch.path(), &mut connection, at(0)).unwrap().unwrap(); std::fs::remove_file(copy.join(KEY_FILE)).unwrap(); drop(connection); @@ -570,9 +508,7 @@ mod tests { fn a_copy_is_found_by_its_listing_never_by_a_path() { let scratch = tempfile::tempdir().unwrap(); let (mut connection, _) = library(scratch.path()); - let copy = rotate(scratch.path(), &mut connection, at(0)) - .unwrap() - .unwrap(); + let copy = rotate(scratch.path(), &mut connection, at(0)).unwrap().unwrap(); drop(connection); let stamp = layout::stamp(at(0)); let outside = scratch.path().join(&stamp); @@ -600,17 +536,8 @@ mod tests { let failed = replace(scratch.path(), &layout::stamp(at(0)), at(1)); assert!(matches!(failed, Err(StorageError::File(_)))); - assert_eq!( - std::fs::read(scratch.path().join(layout::DATABASE)).unwrap(), - database - ); - assert!( - !scratch - .path() - .join(REPLACED) - .join(layout::stamp(at(1))) - .exists() - ); + assert_eq!(std::fs::read(scratch.path().join(layout::DATABASE)).unwrap(), database); + assert!(!scratch.path().join(REPLACED).join(layout::stamp(at(1))).exists()); } /// ⚠️ What makes a new phrase revoke anything: every retained copy's key file is rewrapped @@ -620,34 +547,16 @@ mod tests { fn a_new_phrase_reaches_every_copy_s_key_file() { let scratch = tempfile::tempdir().unwrap(); let (mut connection, _) = library(scratch.path()); - let first = rotate(scratch.path(), &mut connection, at(0)) - .unwrap() - .unwrap(); - let keyless = rotate(scratch.path(), &mut connection, at(48)) - .unwrap() - .unwrap(); + let first = rotate(scratch.path(), &mut connection, at(0)).unwrap().unwrap(); + let keyless = rotate(scratch.path(), &mut connection, at(48)).unwrap().unwrap(); std::fs::remove_file(keyless.join(KEY_FILE)).unwrap(); let vault = file::unlock(scratch.path(), PHRASE).unwrap(); - file::write_wrapped( - &first.join(KEY_FILE), - &vault, - "an older one", - Cost::FOR_TESTS, - ) - .unwrap(); - - let tally = rewrap( - scratch.path(), - &vault, - "the next passphrase", - Cost::FOR_TESTS, - ); + file::write_wrapped(&first.join(KEY_FILE), &vault, "an older one", Cost::FOR_TESTS).unwrap(); + + let tally = rewrap(scratch.path(), &vault, "the next passphrase", Cost::FOR_TESTS); assert_eq!(tally, Rewrapped { done: 1, left: 0 }); - assert!(matches!( - file::unlock(&first, "an older one"), - Err(StorageError::WrongPassphrase) - )); + assert!(matches!(file::unlock(&first, "an older one"), Err(StorageError::WrongPassphrase))); assert_eq!(titles_in(&first, "the next passphrase"), ["Kept"]); assert!(!keyless.join(KEY_FILE).exists()); } @@ -658,15 +567,9 @@ mod tests { fn a_key_file_that_cannot_be_rewritten_is_counted_as_left() { let scratch = tempfile::tempdir().unwrap(); let (mut connection, _) = library(scratch.path()); - let copy = rotate(scratch.path(), &mut connection, at(0)) - .unwrap() - .unwrap(); + let copy = rotate(scratch.path(), &mut connection, at(0)).unwrap().unwrap(); let vault = file::unlock(scratch.path(), PHRASE).unwrap(); - let refused = Cost { - memory_kib: 0, - passes: 0, - lanes: 0, - }; + let refused = Cost { memory_kib: 0, passes: 0, lanes: 0 }; let tally = rewrap(scratch.path(), &vault, "the next passphrase", refused); diff --git a/crates/engine/src/changelog.rs b/crates/engine/src/changelog.rs index fc10237cc..eb67f7e05 100644 --- a/crates/engine/src/changelog.rs +++ b/crates/engine/src/changelog.rs @@ -33,11 +33,7 @@ mod tests { assert!(!releases.is_empty(), "the file describes no release"); for release in &releases { - assert!( - !release.sections.is_empty(), - "release {} carries no entry", - release.version - ); + assert!(!release.sections.is_empty(), "release {} carries no entry", release.version); for section in &release.sections { assert!( !section.items.is_empty(), @@ -68,36 +64,25 @@ mod tests { spans.iter().any(|span| span.kind == SpanKind::Code), "no entry in the file carries code any more" ); - assert!( - !spans.iter().any(|span| span.text.contains("**")), - "a marker reached the panel as text" - ); + assert!(!spans.iter().any(|span| span.text.contains("**")), "a marker reached the panel as text"); } /// What `release.yml` hands the updater is the newest section of this very file. #[test] fn the_newest_section_reads_the_same_alone_as_in_the_file() { let start = CHANGELOG.find("\n## ").expect("a release heading") + 1; - let body_start = CHANGELOG[start..] - .find('\n') - .map_or(CHANGELOG.len(), |at| start + at + 1); + let body_start = CHANGELOG[start..].find('\n').map_or(CHANGELOG.len(), |at| start + at + 1); let body_end = CHANGELOG[body_start..] .find("\n## ") .map_or(CHANGELOG.len(), |at| body_start + at); - assert_eq!( - release_notes(&CHANGELOG[body_start..body_end]), - app_changelog().remove(0).sections - ); + assert_eq!(release_notes(&CHANGELOG[body_start..body_end]), app_changelog().remove(0).sections); } #[test] fn the_shipped_file_shows_neither_the_site_nor_its_pages() { for heading in model::NOT_IN_THE_APP { - assert!( - CHANGELOG.contains(&format!("### {heading}\n")), - "{heading} is in no release" - ); + assert!(CHANGELOG.contains(&format!("### {heading}\n")), "{heading} is in no release"); } let shown: Vec<_> = app_changelog() .into_iter() @@ -105,27 +90,17 @@ mod tests { .map(|section| section.title) .collect(); - assert!( - !shown - .iter() - .any(|title| model::NOT_IN_THE_APP.contains(&title.as_str())) - ); + assert!(!shown.iter().any(|title| model::NOT_IN_THE_APP.contains(&title.as_str()))); } /// Written by the script, recognised here: a heading renamed on one side alone would reach /// the panel. #[test] fn the_headings_left_out_are_the_ones_the_release_script_writes() { - let script = include_str!(concat!( - env!("CARGO_MANIFEST_DIR"), - "/../../scripts/release-notes.mjs" - )); + let script = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../scripts/release-notes.mjs")); for heading in model::NOT_IN_THE_APP { - assert!( - script.contains(&format!("heading: '{heading}'")), - "{heading}" - ); + assert!(script.contains(&format!("heading: '{heading}'")), "{heading}"); } } diff --git a/crates/engine/src/changelog/model.rs b/crates/engine/src/changelog/model.rs index 06b95c0dc..1d86adbeb 100644 --- a/crates/engine/src/changelog/model.rs +++ b/crates/engine/src/changelog/model.rs @@ -70,11 +70,7 @@ pub fn parse(markdown: &str) -> Vec { release.sections = sections.take(); } let (version, date) = split_heading(heading); - releases.push(ChangelogRelease { - version, - date, - sections: Vec::new(), - }); + releases.push(ChangelogRelease { version, date, sections: Vec::new() }); } else if !releases.is_empty() { // The preamble sits above the first release, with nothing to attach to. sections.read(line); @@ -128,10 +124,8 @@ impl Sections { /// `false` for a line the grammar has no place for. fn read(&mut self, line: &str) -> bool { if let Some(title) = line.strip_prefix("### ") { - self.sections.push(ChangelogSection { - title: title.trim().to_string(), - items: Vec::new(), - }); + self.sections + .push(ChangelogSection { title: title.trim().to_string(), items: Vec::new() }); self.item_open = false; } else if let Some(entry) = bullet(line) { self.current().items.push(spans(entry)); @@ -152,15 +146,10 @@ impl Sections { fn current(&mut self) -> &mut ChangelogSection { if self.sections.is_empty() { - self.sections.push(ChangelogSection { - title: String::new(), - items: Vec::new(), - }); + self.sections.push(ChangelogSection { title: String::new(), items: Vec::new() }); } - self.sections - .last_mut() - .expect("a section was just pushed if there was none") + self.sections.last_mut().expect("a section was just pushed if there was none") } fn take(&mut self) -> Vec { @@ -268,16 +257,9 @@ fn split_heading(heading: &str) -> (String, Option) { }, }; - let date = rest - .trim() - .trim_start_matches(['-', '–', '—']) - .trim() - .to_string(); + let date = rest.trim().trim_start_matches(['-', '–', '—']).trim().to_string(); - ( - version.trim().to_string(), - (!date.is_empty()).then_some(date), - ) + (version.trim().to_string(), (!date.is_empty()).then_some(date)) } #[cfg(test)] @@ -341,10 +323,7 @@ Everything above the first release is preamble. drop_what_is_not_in_the_app(&mut sections); - let titles: Vec<_> = sections - .iter() - .map(|section| section.title.as_str()) - .collect(); + let titles: Vec<_> = sections.iter().map(|section| section.title.as_str()).collect(); assert_eq!(titles, ["✨ Added", "🧰 Under the hood"]); } @@ -379,10 +358,7 @@ Everything above the first release is preamble. #[test] fn keeps_a_dash_inside_a_version_out_of_the_date() { - assert_eq!( - split_heading("1.0.0-rc.1"), - ("1.0.0-rc.1".to_string(), None) - ); + assert_eq!(split_heading("1.0.0-rc.1"), ("1.0.0-rc.1".to_string(), None)); assert_eq!( split_heading("[1.0.0-rc.1] - 2026-01-01"), ("1.0.0-rc.1".to_string(), Some("2026-01-01".to_string())) @@ -410,9 +386,7 @@ Everything above the first release is preamble. use super::*; fn only(markdown: &str) -> ChangelogEntry { - parse(&format!("## 0.1.0\n\n- {markdown}\n")) - .remove(0) - .sections[0] + parse(&format!("## 0.1.0\n\n- {markdown}\n")).remove(0).sections[0] .items .remove(0) } @@ -445,22 +419,14 @@ Everything above the first release is preamble. fn the_pull_request_number_is_dropped() { assert_eq!( only("Let the library rail go down to 160px (#213)"), - vec![ChangelogSpan::plain( - "Let the library rail go down to 160px".to_string() - )] + vec![ChangelogSpan::plain("Let the library rail go down to 160px".to_string())] ); } #[test] fn something_that_only_looks_like_a_number_is_left_alone() { - assert_eq!( - read(&only("Read the guide (#start here)")), - "Read the guide (#start here)" - ); - assert_eq!( - read(&only("Nothing in brackets (#)")), - "Nothing in brackets (#)" - ); + assert_eq!(read(&only("Read the guide (#start here)")), "Read the guide (#start here)"); + assert_eq!(read(&only("Nothing in brackets (#)")), "Nothing in brackets (#)"); } /// Unclosed is text: an entry about `5 * 3` has to stay readable. @@ -468,9 +434,7 @@ Everything above the first release is preamble. fn a_lone_marker_is_text() { assert_eq!( only("5 * 3 and a ** that closes nothing"), - vec![ChangelogSpan::plain( - "5 * 3 and a ** that closes nothing".to_string() - )] + vec![ChangelogSpan::plain("5 * 3 and a ** that closes nothing".to_string())] ); } @@ -499,10 +463,7 @@ Everything above the first release is preamble. use super::*; fn titles(sections: &[ChangelogSection]) -> Vec<&str> { - sections - .iter() - .map(|section| section.title.as_str()) - .collect() + sections.iter().map(|section| section.title.as_str()).collect() } #[test] diff --git a/crates/engine/src/closed_enum.rs b/crates/engine/src/closed_enum.rs index bd700a220..308438846 100644 --- a/crates/engine/src/closed_enum.rs +++ b/crates/engine/src/closed_enum.rs @@ -82,14 +82,8 @@ mod tests { assert_eq!(shade.to_string(), spelling); assert_eq!(Shade::from_str(spelling), Ok(shade)); - assert_eq!( - serde_json::to_string(&shade).unwrap(), - format!("\"{spelling}\"") - ); - assert_eq!( - serde_json::from_str::(&format!("\"{spelling}\"")).unwrap(), - shade - ); + assert_eq!(serde_json::to_string(&shade).unwrap(), format!("\"{spelling}\"")); + assert_eq!(serde_json::from_str::(&format!("\"{spelling}\"")).unwrap(), shade); } } diff --git a/crates/engine/src/db.rs b/crates/engine/src/db.rs index d9a57fc0f..f2e1b15eb 100644 --- a/crates/engine/src/db.rs +++ b/crates/engine/src/db.rs @@ -79,9 +79,7 @@ impl Library { F: FnOnce(&mut SqliteConnection, &Vault) -> Result, { // Destructured so the two disjoint fields borrow separately. - let Self { - connection, vault, .. - } = self; + let Self { connection, vault, .. } = self; connection.transaction(|connection| f(connection, vault)) } } @@ -95,10 +93,7 @@ pub type Db = Mutex>; /// ⚠️ On the db thread alone (`queue`), checked in debug builds; the crate's own unit tests /// lock their in-memory libraries on the test thread. pub(crate) fn lock(db: &Db) -> Result, StorageError> { - debug_assert!( - cfg!(test) || queue::on_db_thread(), - "the library is locked off the db thread" - ); + debug_assert!(cfg!(test) || queue::on_db_thread(), "the library is locked off the db thread"); let guard = db.lock().map_err(|_| StorageError::Unavailable)?; if guard.is_none() { return Err(StorageError::Locked); @@ -120,10 +115,7 @@ where /// [`run`], queued at the call rather than at the first poll: the interface sends from its /// thread and waits elsewhere, and two jobs sent in a row must still run in that order. -pub fn submit( - engine: &Arc, - job: F, -) -> impl Future> + use +pub fn submit(engine: &Arc, job: F) -> impl Future> + use where T: Send + 'static, F: FnOnce(&Engine) -> Result + Send + 'static, @@ -201,21 +193,14 @@ fn is_unreadable(error: &StorageError) -> bool { /// Every failure names the file: this is the error a user meets before any window has /// anything in it, and the database sits in a directory they have never opened. pub fn open(path: &Path, vault: Vault) -> Result { - let named = |error: &dyn std::fmt::Display| { - StorageError::Migration(format!("{}: {error}", path.display())) - }; + let named = + |error: &dyn std::fmt::Display| StorageError::Migration(format!("{}: {error}", path.display())); let mut connection = SqliteConnection::establish(&path.to_string_lossy()).map_err(|error| named(&error))?; - let damaged = - |error: &StorageError| StorageError::Damaged(format!("{}: {error}", path.display())); - configure(&mut connection).map_err(|error| { - if is_unreadable(&error) { - damaged(&error) - } else { - named(&error) - } - })?; + let damaged = |error: &StorageError| StorageError::Damaged(format!("{}: {error}", path.display())); + configure(&mut connection) + .map_err(|error| if is_unreadable(&error) { damaged(&error) } else { named(&error) })?; // ⚠️ Before the migrations, which write: running them over a damaged file is how a // salvageable database becomes an unsalvageable one. @@ -243,8 +228,7 @@ pub fn open_in_memory() -> Result { connection, vault: Arc::new(test_vault()?), // Named, never created: a test writing beside the library fails loudly. - directory: std::env::temp_dir() - .join(format!("devnotes-in-memory-{}", uuid::Uuid::new_v4())), + directory: std::env::temp_dir().join(format!("devnotes-in-memory-{}", uuid::Uuid::new_v4())), number: next_number(), }) } @@ -253,8 +237,7 @@ impl Library { /// Once the index holds every body, nothing reads the file end to end again, and what stays /// mapped stays in the process. Before that, the mapping is what makes the fill fast. pub(crate) fn map_less(&mut self) -> Result<(), StorageError> { - self.connection - .batch_execute("PRAGMA mmap_size = 67108864;")?; + self.connection.batch_execute("PRAGMA mmap_size = 67108864;")?; Ok(()) } } @@ -263,11 +246,7 @@ impl Library { /// what the tests and the benchmarks need. #[doc(hidden)] pub fn test_vault() -> Result { - Vault::derive( - "in-memory", - b"0123456789abcdef", - crate::vault::key::Cost::FOR_TESTS, - ) + Vault::derive("in-memory", b"0123456789abcdef", crate::vault::key::Cost::FOR_TESTS) } fn configure(connection: &mut SqliteConnection) -> Result<(), StorageError> { @@ -395,11 +374,7 @@ mod tests { let scratch = tempfile::tempdir().unwrap(); let mut library = opened(&scratch); - for (name, value) in [ - ("foreign_keys", 1), - ("busy_timeout", 5000), - ("synchronous", 1), - ] { + for (name, value) in [("foreign_keys", 1), ("busy_timeout", 5000), ("synchronous", 1)] { assert_eq!(pragma(&mut library, name), value, "{name}"); } // A build of SQLite whose ceiling is lower answers that ceiling. @@ -531,10 +506,7 @@ mod tests { }) .join(); - assert!(matches!( - lock(&db).map(drop), - Err(StorageError::Unavailable) - )); + assert!(matches!(lock(&db).map(drop), Err(StorageError::Unavailable))); } /// A send writes only into the library it read from. diff --git a/crates/engine/src/db/migration.rs b/crates/engine/src/db/migration.rs index c0335d6cc..e0accd159 100644 --- a/crates/engine/src/db/migration.rs +++ b/crates/engine/src/db/migration.rs @@ -88,11 +88,9 @@ mod tests { #[test] fn a_migration_this_binary_does_not_know_is_refused() { let mut connection = open_in_memory().unwrap(); - diesel::sql_query( - "INSERT INTO __diesel_schema_migrations (version) VALUES ('2099-01-01-000000')", - ) - .execute(connection.db()) - .unwrap(); + diesel::sql_query("INSERT INTO __diesel_schema_migrations (version) VALUES ('2099-01-01-000000')") + .execute(connection.db()) + .unwrap(); let error = run(connection.db()).unwrap_err(); diff --git a/crates/engine/src/db/queue.rs b/crates/engine/src/db/queue.rs index 62e447464..bc92febec 100644 --- a/crates/engine/src/db/queue.rs +++ b/crates/engine/src/db/queue.rs @@ -60,10 +60,7 @@ impl DbQueue { /// Queues `job` now, in the caller's order, and answers a future of its result: what /// keeps two calls made one after the other in that order when the waiting is done /// elsewhere. - pub(crate) fn submit( - &self, - job: F, - ) -> impl Future> + use + pub(crate) fn submit(&self, job: F) -> impl Future> + use where T: Send + 'static, F: FnOnce() -> Result + Send + 'static, @@ -89,10 +86,7 @@ mod tests { use crate::error::ErrorCode; fn block_on(future: impl Future) -> T { - tokio::runtime::Builder::new_current_thread() - .build() - .unwrap() - .block_on(future) + tokio::runtime::Builder::new_current_thread().build().unwrap().block_on(future) } #[test] diff --git a/crates/engine/src/docs.rs b/crates/engine/src/docs.rs index 30b41b527..1a0340186 100644 --- a/crates/engine/src/docs.rs +++ b/crates/engine/src/docs.rs @@ -10,10 +10,7 @@ use model::{Index, Page}; // `SOURCES`: each file of `docs/content/`, by language and page, written by `build.rs`. include!(concat!(env!("OUT_DIR"), "/docs.rs")); -const INDEX: &str = include_str!(concat!( - env!("CARGO_MANIFEST_DIR"), - "/../../docs/content/index.json" -)); +const INDEX: &str = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../docs/content/index.json")); static READ_INDEX: LazyLock = LazyLock::new(|| serde_json::from_str(INDEX).expect("compiled in, and held by a test")); @@ -29,12 +26,8 @@ pub fn docs_index() -> &'static Index { /// A page in a language, by its name in the index. pub fn docs_page(language: &str, id: &str) -> Option<&'static Page> { - let at = SOURCES - .iter() - .position(|source| source.0 == language && source.1 == id)?; - PAGES[at] - .get_or_init(|| model::read(id, SOURCES[at].2).ok()) - .as_ref() + let at = SOURCES.iter().position(|source| source.0 == language && source.1 == id)?; + PAGES[at].get_or_init(|| model::read(id, SOURCES[at].2).ok()).as_ref() } #[cfg(test)] @@ -47,10 +40,7 @@ mod tests { const LANGUAGES: [&str; 2] = ["fr", "en"]; fn ids() -> Vec<&'static str> { - docs_index() - .pages() - .map(|entry| entry.id.as_str()) - .collect() + docs_index().pages().map(|entry| entry.id.as_str()).collect() } fn runs(block: &Block) -> Vec<&Inline> { @@ -124,10 +114,7 @@ mod tests { let mut sections = Vec::new(); for block in &page.body { if let Block::Heading { id: section, .. } = block { - assert!( - !sections.contains(§ion), - "{language}/{id}.md: {section}" - ); + assert!(!sections.contains(§ion), "{language}/{id}.md: {section}"); sections.push(section); } } @@ -137,17 +124,8 @@ mod tests { #[test] fn every_link_leads_to_a_page_and_a_section_that_exist() { for (language, id, _) in SOURCES { - for run in docs_page(language, id) - .expect(id) - .body - .iter() - .flat_map(runs) - { - let Inline::Link { - text, - to: Target::Page { id: to, section }, - } = run - else { + for run in docs_page(language, id).expect(id).body.iter().flat_map(runs) { + let Inline::Link { text, to: Target::Page { id: to, section } } = run else { continue; }; let name = format!("docs/content/{language}/{id}.md: « {text} »"); @@ -170,11 +148,7 @@ mod tests { Block::Pages(pages) => Some(pages.clone()), _ => None, }); - assert_eq!( - listed.unwrap_or_default(), - ids()[1..], - "{language}/overview.md" - ); + assert_eq!(listed.unwrap_or_default(), ids()[1..], "{language}/overview.md"); } } diff --git a/crates/engine/src/docs/model.rs b/crates/engine/src/docs/model.rs index 1d473a19b..2ceda14e4 100644 --- a/crates/engine/src/docs/model.rs +++ b/crates/engine/src/docs/model.rs @@ -163,9 +163,7 @@ pub fn read(id: &str, markdown: &str) -> Reading { let mut reader = Reader { id, markdown, - events: Parser::new_ext(markdown, options) - .into_offset_iter() - .collect(), + events: Parser::new_ext(markdown, options).into_offset_iter().collect(), at: 0, }; reader.page() @@ -181,10 +179,7 @@ struct Reader<'a> { impl<'a> Reader<'a> { fn page(&mut self) -> Reading { let title = match self.next() { - Some(Event::Start(Tag::Heading { - level: HeadingLevel::H1, - .. - })) => self.plain()?, + Some(Event::Start(Tag::Heading { level: HeadingLevel::H1, .. })) => self.plain()?, _ => return self.refuse("a page begins with # and its title"), }; let summary = match self.next() { @@ -196,21 +191,13 @@ impl<'a> Reader<'a> { while self.at < self.events.len() { body.push(self.titled_block()?); } - Ok(Page { - id: self.id.to_owned(), - title, - summary, - body, - }) + Ok(Page { id: self.id.to_owned(), title, summary, body }) } /// A block, and the title of a table or a code block: the bold line just above it. fn titled_block(&mut self) -> Reading { let first = self.block(None)?; - let titled = matches!( - self.peek(), - Some(Event::Start(Tag::Table(_) | Tag::CodeBlock(_))) - ); + let titled = matches!(self.peek(), Some(Event::Start(Tag::Table(_) | Tag::CodeBlock(_)))); match first { Block::Paragraph(text) if titled => match text.as_slice() { [Inline::Strong(title)] => self.block(Some(title)), @@ -248,11 +235,7 @@ impl<'a> Reader<'a> { _ => return self.refuse("a section is ## or ###"), }; let text = self.plain()?; - Ok(Block::Heading { - level, - id: slug(&text), - text, - }) + Ok(Block::Heading { level, id: slug(&text), text }) } fn list(&mut self, ordered: bool) -> Reading { @@ -289,11 +272,7 @@ impl<'a> Reader<'a> { CodeBlockKind::Fenced(language) => language.to_string(), CodeBlockKind::Indented => return self.refuse("a code block is between ```"), }; - Ok(Block::Code { - title: title.to_owned(), - language, - text: text.trim_end_matches('\n').to_owned(), - }) + Ok(Block::Code { title: title.to_owned(), language, text: text.trim_end_matches('\n').to_owned() }) } fn table(&mut self, title: &str) -> Reading { @@ -319,29 +298,21 @@ impl<'a> Reader<'a> { .collect::>(); let title = title.to_owned(); if !SHORTCUTS.contains(&head[0].as_str()) { - return Ok(Block::Table { - title, - head, - rows: rows.collect(), - }); + return Ok(Block::Table { title, head, rows: rows.collect() }); } let mut shortcuts = Vec::new(); for row in rows { match row.as_slice() { [keys, does] => match keys.as_slice() { - [Inline::Keys(keys)] => shortcuts.push(Shortcut { - keys: keys.clone(), - does: text_of(does), - }), + [Inline::Keys(keys)] => { + shortcuts.push(Shortcut { keys: keys.clone(), does: text_of(does) }); + } _ => return self.refuse("a table of shortcuts holds one per row"), }, _ => return self.refuse("a table of shortcuts has two columns"), } } - Ok(Block::Shortcuts { - title, - rows: shortcuts, - }) + Ok(Block::Shortcuts { title, rows: shortcuts }) } /// What an item or a note holds: one paragraph, marked as such or not. @@ -368,10 +339,9 @@ impl<'a> Reader<'a> { Some(Event::Code(code)) => Inline::Code(code.to_string()), Some(Event::Start(Tag::Strong)) => Inline::Strong(self.plain()?), Some(Event::Start(Tag::Emphasis)) => Inline::Label(self.plain()?), - Some(Event::Start(Tag::Link { dest_url, .. })) => Inline::Link { - text: self.plain()?, - to: self.target(&dest_url)?, - }, + Some(Event::Start(Tag::Link { dest_url, .. })) => { + Inline::Link { text: self.plain()?, to: self.target(&dest_url)? } + } Some(Event::InlineHtml(tag)) if &*tag == "" => Inline::Keys(self.keys()?), Some(other) => return self.refuse(format!("{other:?} is not read")), }; @@ -417,10 +387,7 @@ impl<'a> Reader<'a> { None if file.is_empty() && section.is_some() => self.id, _ => return self.refuse(format!("{href} leads nowhere")), }; - Ok(Target::Page { - id: id.to_owned(), - section, - }) + Ok(Target::Page { id: id.to_owned(), section }) } fn peek(&self) -> Option<&Event<'a>> { @@ -435,26 +402,15 @@ impl<'a> Reader<'a> { /// At the event just read. fn refuse(&self, message: impl Into) -> Reading { - let at = self - .events - .get(self.at.saturating_sub(1)) - .map_or(0, |(_, range)| range.start); - Err(Refusal { - line: self.markdown[..at].matches('\n').count() + 1, - message: message.into(), - }) + let at = self.events.get(self.at.saturating_sub(1)).map_or(0, |(_, range)| range.start); + Err(Refusal { line: self.markdown[..at].matches('\n').count() + 1, message: message.into() }) } } /// The page an item leads to, when it is a link to it and nothing more. fn only_page(item: &[Inline]) -> Option { match item { - [ - Inline::Link { - to: Target::Page { id, section: None }, - .. - }, - ] => Some(id.clone()), + [Inline::Link { to: Target::Page { id, section: None }, .. }] => Some(id.clone()), _ => None, } } @@ -499,10 +455,7 @@ mod tests { #[test] fn a_page_opens_on_its_title_and_its_summary() { let page = read("page", HEAD).expect("a page"); - assert_eq!( - (page.title.as_str(), page.summary.as_str()), - ("Titre", "Résumé.") - ); + assert_eq!((page.title.as_str(), page.summary.as_str()), ("Titre", "Résumé.")); assert!(page.body.is_empty()); let refusal = read("page", "Sans titre.\n").expect_err("no title"); @@ -530,10 +483,7 @@ mod tests { text(" ou "), Inline::Link { text: "là".to_owned(), - to: Target::Page { - id: "start".to_owned(), - section: Some("cle-maitre".to_owned()), - }, + to: Target::Page { id: "start".to_owned(), section: Some("cle-maitre".to_owned()) }, }, text("."), ])] @@ -549,13 +499,7 @@ mod tests { }, other => panic!("{other:?}"), }; - assert_eq!( - to("[a](#ici)"), - Target::Page { - id: "page".to_owned(), - section: Some("ici".to_owned()), - } - ); + assert_eq!(to("[a](#ici)"), Target::Page { id: "page".to_owned(), section: Some("ici".to_owned()) }); assert_eq!( to("[a](https://devnotes.fr/telecharger)"), Target::Address("https://devnotes.fr/telecharger".to_owned()) @@ -567,10 +511,7 @@ mod tests { fn a_list_of_nothing_but_pages_is_the_list_of_them() { assert_eq!( body("- [Écrire](writing.md)\n- [Ranger](organising.md)\n"), - [Block::Pages(vec![ - "writing".to_owned(), - "organising".to_owned() - ])] + [Block::Pages(vec!["writing".to_owned(), "organising".to_owned()])] ); assert_eq!( body("1. un\n2. *deux*\n"), @@ -600,10 +541,7 @@ mod tests { [Block::Table { title: "Fichiers".to_owned(), head: vec!["Système".to_owned(), "Fichier".to_owned()], - rows: vec![vec![ - vec![text("Linux")], - vec![Inline::Code("a|b".to_owned())] - ]], + rows: vec![vec![vec![text("Linux")], vec![Inline::Code("a|b".to_owned())]]], }] ); assert_eq!( @@ -621,9 +559,8 @@ mod tests { #[test] fn a_table_headed_by_the_keys_is_one_of_shortcuts() { for head in SHORTCUTS { - let table = format!( - "**Palette**\n\n| {head} | Action |\n| --- | --- |\n| ↑ ↓ | Choisir |\n" - ); + let table = + format!("**Palette**\n\n| {head} | Action |\n| --- | --- |\n| ↑ ↓ | Choisir |\n"); assert_eq!( body(&table), [Block::Shortcuts { @@ -649,9 +586,7 @@ mod tests { "- un\n - dedans\n", "> [!TIP]\n> un\n>\n> deux\n", ] { - assert!( - refused(markdown).starts_with('5') || refused(markdown).starts_with(['6', '8']) - ); + assert!(refused(markdown).starts_with('5') || refused(markdown).starts_with(['6', '8'])); } } @@ -680,23 +615,14 @@ mod tests { ); } for nowhere in ["", "start", "a/start.md", "a.b.md", "ftp://a"] { - assert!( - refused(&format!("[a]({nowhere})")).contains("leads nowhere"), - "{nowhere}" - ); + assert!(refused(&format!("[a]({nowhere})")).contains("leads nowhere"), "{nowhere}"); } } #[test] fn a_name_is_given_in_its_language_or_in_english() { - let names = Names { - fr: "Début".to_owned(), - en: "Start".to_owned(), - }; + let names = Names { fr: "Début".to_owned(), en: "Start".to_owned() }; - assert_eq!( - [names.of("fr"), names.of("en"), names.of("de")], - ["Début", "Start", "Start"] - ); + assert_eq!([names.of("fr"), names.of("en"), names.of("de")], ["Début", "Start", "Start"]); } } diff --git a/crates/engine/src/docs/search.rs b/crates/engine/src/docs/search.rs index 23717f4c4..883b98f7f 100644 --- a/crates/engine/src/docs/search.rs +++ b/crates/engine/src/docs/search.rs @@ -44,15 +44,13 @@ pub fn search_docs(language: &str, query: &str) -> Vec { let mut found: Vec<_> = sections(language) .iter() .filter(|section| { - terms.iter().all(|term| { - section.folded_heading.contains(term) || section.folded_text.contains(term) - }) + terms + .iter() + .all(|term| section.folded_heading.contains(term) || section.folded_text.contains(term)) }) .collect(); found.sort_by_key(|section| { - let named = terms - .iter() - .filter(|term| section.folded_heading.contains(**term)); + let named = terms.iter().filter(|term| section.folded_heading.contains(**term)); std::cmp::Reverse(named.count()) }); found @@ -97,14 +95,7 @@ fn cut(page: &'static Page) -> Vec

{ .into_iter() .map(|(id, heading, words)| { let text = words.join(" "); - Section { - page, - id, - heading, - folded_heading: fold(heading), - folded_text: fold(&text), - text, - } + Section { page, id, heading, folded_heading: fold(heading), folded_text: fold(&text), text } }) .collect() } @@ -116,9 +107,7 @@ fn said(block: &Block) -> String { Block::List { items, .. } => join(items.iter().map(|item| text_of(item))), Block::Code { title, text, .. } => format!("{title} {text}"), Block::Shortcuts { title, rows } => { - let rows = rows - .iter() - .map(|Shortcut { keys, does }| format!("{} {does}", keys.join(" "))); + let rows = rows.iter().map(|Shortcut { keys, does }| format!("{} {does}", keys.join(" "))); format!("{title} {}", join(rows)) } Block::Table { title, rows, .. } => { @@ -159,10 +148,7 @@ mod tests { #[test] fn a_heading_comes_before_a_mention() { let hits = search_docs("en", "palette"); - assert_eq!( - (hits[0].page.id.as_str(), hits[0].heading), - ("paste", "The palette") - ); + assert_eq!((hits[0].page.id.as_str(), hits[0].heading), ("paste", "The palette")); } #[test] @@ -187,10 +173,7 @@ mod tests { #[test] fn an_excerpt_says_where_it_was_cut() { let text = "un deux trois quatre cinq six sept huit neuf dix"; - assert_eq!( - excerpt(text, "huit"), - "…deux trois quatre cinq six sept huit neuf dix" - ); + assert_eq!(excerpt(text, "huit"), "…deux trois quatre cinq six sept huit neuf dix"); assert_eq!(excerpt(text, "absent"), text); } diff --git a/crates/engine/src/error.rs b/crates/engine/src/error.rs index 4542f9f23..d884ede03 100644 --- a/crates/engine/src/error.rs +++ b/crates/engine/src/error.rs @@ -16,10 +16,7 @@ pub struct ValidationError { impl ValidationError { pub fn new(field: &'static str, detail: impl Into) -> Self { - Self { - field, - detail: detail.into(), - } + Self { field, detail: detail.into() } } } @@ -200,11 +197,7 @@ pub struct AppError { impl AppError { pub(crate) fn new(code: ErrorCode, detail: String) -> Self { - Self { - code, - params: BTreeMap::new(), - detail, - } + Self { code, params: BTreeMap::new(), detail } } pub(crate) fn with(code: ErrorCode, detail: String, key: &str, value: &str) -> Self { @@ -249,11 +242,7 @@ impl AppError { | C::HttpScriptSkipped | C::HttpRunData ); - if plain { - format!("{:?}: {}", self.code, self.detail) - } else { - format!("{:?}", self.code) - } + if plain { format!("{:?}: {}", self.code, self.detail) } else { format!("{:?}", self.code) } } pub fn storage_unavailable() -> Self { @@ -266,12 +255,7 @@ impl AppError { impl From for AppError { fn from(error: ValidationError) -> Self { - Self::with( - ErrorCode::InvalidInput, - error.to_string(), - "field", - error.field, - ) + Self::with(ErrorCode::InvalidInput, error.to_string(), "field", error.field) } } @@ -280,27 +264,19 @@ impl From for AppError { let detail = error.to_string(); match error { - StorageError::NoteNotFound(id) => { - Self::with(ErrorCode::NoteNotFound, detail, "id", &id) - } - StorageError::SpaceNotFound(id) => { - Self::with(ErrorCode::SpaceNotFound, detail, "id", &id) - } + StorageError::NoteNotFound(id) => Self::with(ErrorCode::NoteNotFound, detail, "id", &id), + StorageError::SpaceNotFound(id) => Self::with(ErrorCode::SpaceNotFound, detail, "id", &id), StorageError::DuplicateSpaceName(name) => { Self::with(ErrorCode::DuplicateSpaceName, detail, "name", &name) } - StorageError::FolderNotFound(id) => { - Self::with(ErrorCode::FolderNotFound, detail, "id", &id) - } + StorageError::FolderNotFound(id) => Self::with(ErrorCode::FolderNotFound, detail, "id", &id), StorageError::DuplicateFolderName(name) => { Self::with(ErrorCode::DuplicateFolderName, detail, "name", &name) } StorageError::AttachmentNotFound(id) => { Self::with(ErrorCode::AttachmentNotFound, detail, "id", &id) } - StorageError::HttpItemNotFound(id) => { - Self::with(ErrorCode::HttpItemNotFound, detail, "id", &id) - } + StorageError::HttpItemNotFound(id) => Self::with(ErrorCode::HttpItemNotFound, detail, "id", &id), StorageError::HttpEnvironmentNotFound(id) => { Self::with(ErrorCode::HttpEnvironmentNotFound, detail, "id", &id) } @@ -308,23 +284,15 @@ impl From for AppError { Self::with(ErrorCode::DuplicateEnvironmentName, detail, "name", &name) } StorageError::Invalid(error) => error.into(), - StorageError::RevisionNotFound(id) => { - Self::with(ErrorCode::RevisionNotFound, detail, "id", &id) - } - StorageError::LibraryNotFound(id) => { - Self::with(ErrorCode::LibraryNotFound, detail, "id", &id) - } + StorageError::RevisionNotFound(id) => Self::with(ErrorCode::RevisionNotFound, detail, "id", &id), + StorageError::LibraryNotFound(id) => Self::with(ErrorCode::LibraryNotFound, detail, "id", &id), StorageError::LibraryOpen => Self::new(ErrorCode::LibraryOpen, detail), StorageError::LastLibrary => Self::new(ErrorCode::LastLibrary, detail), StorageError::NothingToSetAside(path) => { Self::with(ErrorCode::NothingToSetAside, detail, "path", &path) } - StorageError::BackupNotFound(id) => { - Self::with(ErrorCode::BackupNotFound, detail, "id", &id) - } - StorageError::BackupUnopenable(id) => { - Self::with(ErrorCode::BackupUnopenable, detail, "id", &id) - } + StorageError::BackupNotFound(id) => Self::with(ErrorCode::BackupNotFound, detail, "id", &id), + StorageError::BackupUnopenable(id) => Self::with(ErrorCode::BackupUnopenable, detail, "id", &id), StorageError::Unavailable => Self::new(ErrorCode::StorageUnavailable, detail), StorageError::WrongPassphrase => Self::new(ErrorCode::WrongPassphrase, detail), StorageError::PassphraseRequired => Self::new(ErrorCode::PassphraseRequired, detail), @@ -332,8 +300,7 @@ impl From for AppError { StorageError::Damaged(_) => Self::new(ErrorCode::LibraryDamaged, detail), StorageError::File(_) => Self::new(ErrorCode::FileAccess, detail), StorageError::TooLarge { name, limit_mb } => { - Self::with(ErrorCode::FileTooLarge, detail, "name", &name) - .and("limit", &limit_mb.to_string()) + Self::with(ErrorCode::FileTooLarge, detail, "name", &name).and("limit", &limit_mb.to_string()) } StorageError::ImportFormat(_) => Self::new(ErrorCode::ImportFormat, detail), // Nothing here gives the front anything to do beyond reporting the failure. @@ -363,60 +330,20 @@ mod tests { vec![ (E::NoteNotFound(text("x")), C::NoteNotFound, Some("id")), (E::SpaceNotFound(text("x")), C::SpaceNotFound, Some("id")), - ( - E::DuplicateSpaceName(text("x")), - C::DuplicateSpaceName, - Some("name"), - ), + (E::DuplicateSpaceName(text("x")), C::DuplicateSpaceName, Some("name")), (E::FolderNotFound(text("x")), C::FolderNotFound, Some("id")), - ( - E::DuplicateFolderName(text("x")), - C::DuplicateFolderName, - Some("name"), - ), - ( - E::AttachmentNotFound(text("x")), - C::AttachmentNotFound, - Some("id"), - ), - ( - E::HttpItemNotFound(text("x")), - C::HttpItemNotFound, - Some("id"), - ), - ( - E::HttpEnvironmentNotFound(text("x")), - C::HttpEnvironmentNotFound, - Some("id"), - ), - ( - E::DuplicateEnvironmentName(text("x")), - C::DuplicateEnvironmentName, - Some("name"), - ), - ( - E::RevisionNotFound(text("x")), - C::RevisionNotFound, - Some("id"), - ), - ( - E::LibraryNotFound(text("x")), - C::LibraryNotFound, - Some("id"), - ), + (E::DuplicateFolderName(text("x")), C::DuplicateFolderName, Some("name")), + (E::AttachmentNotFound(text("x")), C::AttachmentNotFound, Some("id")), + (E::HttpItemNotFound(text("x")), C::HttpItemNotFound, Some("id")), + (E::HttpEnvironmentNotFound(text("x")), C::HttpEnvironmentNotFound, Some("id")), + (E::DuplicateEnvironmentName(text("x")), C::DuplicateEnvironmentName, Some("name")), + (E::RevisionNotFound(text("x")), C::RevisionNotFound, Some("id")), + (E::LibraryNotFound(text("x")), C::LibraryNotFound, Some("id")), (E::LibraryOpen, C::LibraryOpen, None), (E::LastLibrary, C::LastLibrary, None), - ( - E::NothingToSetAside(text("x")), - C::NothingToSetAside, - Some("path"), - ), + (E::NothingToSetAside(text("x")), C::NothingToSetAside, Some("path")), (E::BackupNotFound(text("x")), C::BackupNotFound, Some("id")), - ( - E::BackupUnopenable(text("x")), - C::BackupUnopenable, - Some("id"), - ), + (E::BackupUnopenable(text("x")), C::BackupUnopenable, Some("id")), (E::File(text("x")), C::FileAccess, None), (E::ImportFormat(text("x")), C::ImportFormat, None), (E::Damaged(text("x")), C::LibraryDamaged, None), @@ -425,14 +352,7 @@ mod tests { (E::Unavailable, C::StorageUnavailable, None), (E::Locked, C::Locked, None), // Nothing here gives the interface anything to do beyond reporting the failure. - ( - E::CorruptRow { - id: text("x"), - field: "tags", - }, - C::Storage, - None, - ), + (E::CorruptRow { id: text("x"), field: "tags" }, C::Storage, None), (E::SchemaTooRecent(text("x")), C::Storage, None), (E::Migration(text("x")), C::Storage, None), (E::Vault(text("x")), C::Storage, None), @@ -459,29 +379,17 @@ mod tests { #[test] fn a_file_too_large_says_its_name_and_the_limit() { - let answered = AppError::from(StorageError::TooLarge { - name: text("film.mp4"), - limit_mb: 25, - }); + let answered = AppError::from(StorageError::TooLarge { name: text("film.mp4"), limit_mb: 25 }); assert_eq!(answered.code, ErrorCode::FileTooLarge); - assert_eq!( - ( - answered.params["name"].as_str(), - answered.params["limit"].as_str() - ), - ("film.mp4", "25") - ); + assert_eq!((answered.params["name"].as_str(), answered.params["limit"].as_str()), ("film.mp4", "25")); } #[test] fn an_input_refused_names_its_field_wherever_it_was_refused() { let refused = || ValidationError::new("folderId", "a folder cannot move into itself"); - for answered in [ - AppError::from(refused()), - AppError::from(StorageError::from(refused())), - ] { + for answered in [AppError::from(refused()), AppError::from(StorageError::from(refused()))] { assert_eq!( (answered.code, answered.params["field"].as_str()), (ErrorCode::InvalidInput, "folderId") @@ -500,10 +408,7 @@ mod tests { #[test] fn a_storage_unavailable_is_the_same_wherever_it_is_said() { - assert_eq!( - AppError::storage_unavailable().code, - AppError::from(StorageError::Unavailable).code - ); + assert_eq!(AppError::storage_unavailable().code, AppError::from(StorageError::Unavailable).code); assert!(AppError::storage_unavailable().params.is_empty()); } @@ -517,11 +422,7 @@ mod tests { StorageError::DuplicateEnvironmentName(typed()).into(), StorageError::NothingToSetAside(typed()).into(), StorageError::File(typed()).into(), - StorageError::TooLarge { - name: typed(), - limit_mb: 1, - } - .into(), + StorageError::TooLarge { name: typed(), limit_mb: 1 }.into(), StorageError::ImportFormat(typed()).into(), ValidationError::new("title", typed()).into(), SendError::Variable(typed()).into(), @@ -533,10 +434,7 @@ mod tests { SendError::FileTooLarge(typed()).into(), SendError::GraphqlVariables(typed()).into(), SendError::Network(typed()).into(), - SendError::SocketScheme { - twin: Some(typed()), - } - .into(), + SendError::SocketScheme { twin: Some(typed()) }.into(), ]; for error in errors { let line = error.for_log(); @@ -553,20 +451,13 @@ mod tests { StorageError::BackupNotFound(text("2026-07-25_09-05-07")).into(), StorageError::Locked.into(), StorageError::Damaged(text("page 3")).into(), - StorageError::CorruptRow { - id: text("n-1"), - field: "tags", - } - .into(), + StorageError::CorruptRow { id: text("n-1"), field: "tags" }.into(), SendError::Handshake(403).into(), SendError::Fell.into(), DataFault::Empty.into(), ]; for error in errors { - assert_eq!( - error.for_log(), - format!("{:?}: {}", error.code, error.detail) - ); + assert_eq!(error.for_log(), format!("{:?}: {}", error.code, error.detail)); } } } diff --git a/crates/engine/src/folders.rs b/crates/engine/src/folders.rs index 763d0c12d..24ed9d2fc 100644 --- a/crates/engine/src/folders.rs +++ b/crates/engine/src/folders.rs @@ -69,12 +69,7 @@ pub fn save_board_layout( let db = &engine.db; let mut connection = lock(db)?; - Ok(store::board::save_layout( - &mut connection, - root_id.map(std::string::String::as_str), - zones, - cards, - )?) + Ok(store::board::save_layout(&mut connection, root_id.map(std::string::String::as_str), zones, cards)?) } /// `None` = every space, like [`crate::notes::view::NotesQuery::space_id`]. @@ -82,10 +77,7 @@ pub fn list_folders(engine: &Engine, space_id: Option<&String>) -> Result Result { @@ -94,17 +86,9 @@ pub fn create_folder(engine: &Engine, draft: &FolderDraft) -> Result Result Result { +pub fn recolour_folder(engine: &Engine, id: &str, colour: FolderColour) -> Result { engine.write(|db| { let mut connection = lock(db)?; let answer = store::recolour(&mut connection, id, colour)?; - let changed = Changed { - folders: true, - ..Changed::default() - }; + let changed = Changed { folders: true, ..Changed::default() }; Ok((answer, changed)) }) } @@ -152,15 +126,9 @@ pub fn move_folder( engine.write(|db| { let mut connection = lock(db)?; - let answer = store::move_to( - &mut connection, - id, - (space_id, parent_id.map(std::string::String::as_str)), - )?; - let changed = Changed { - folders: true, - ..Changed::notes(answer.notes.clone()) - }; + let answer = + store::move_to(&mut connection, id, (space_id, parent_id.map(std::string::String::as_str)))?; + let changed = Changed { folders: true, ..Changed::notes(answer.notes.clone()) }; Ok((answer, changed)) }) } @@ -171,10 +139,7 @@ pub fn move_folder_back(engine: &Engine, was: &FolderMove) -> Result BoardFrame { #[must_use] pub fn clamp_point(point: BoardPoint) -> BoardPoint { - BoardPoint { - x: point.x.clamp(0, MAX_SIDE), - y: point.y.clamp(0, MAX_SIDE), - } + BoardPoint { x: point.x.clamp(0, MAX_SIDE), y: point.y.clamp(0, MAX_SIDE) } } /// Big enough for the header and one card, or nothing can be dropped in. @@ -360,12 +357,7 @@ pub fn arrange_zones(contents: &[ZoneContents], card: i32) -> Vec { let height = default_zone_height(zone.notes, zone.nested, card); row_height = row_height.max(height); - frames.push(BoardFrame { - x: BOARD_MARGIN + px(column) * (width + GAP), - y: row_top, - width, - height, - }); + frames.push(BoardFrame { x: BOARD_MARGIN + px(column) * (width + GAP), y: row_top, width, height }); } frames @@ -404,12 +396,7 @@ fn overlaps(at: BoardPoint, card: i32, frame: BoardFrame) -> bool { } fn card_frame(at: BoardPoint, card: i32) -> BoardFrame { - BoardFrame { - x: at.x, - y: at.y, - width: CARD_WIDTH, - height: card, - } + BoardFrame { x: at.x, y: at.y, width: CARD_WIDTH, height: card } } /// Below everything already on the board — where a seat goes when the grid has none free. @@ -421,10 +408,7 @@ fn under_everything(taken: &[BoardPoint], zones: &[BoardFrame], card: i32) -> Bo .max() .unwrap_or(BOARD_MARGIN); - BoardPoint { - x: BOARD_MARGIN, - y: bottom + GAP, - } + BoardPoint { x: BOARD_MARGIN, y: bottom + GAP } } /// Where a card that has never been placed goes: the first seat of the flow grid nothing @@ -453,9 +437,7 @@ pub fn free_slot_from( (first..=limit) .map(|index| (index, slot(index, top, card))) .find(|(_, at)| { - !taken - .iter() - .any(|other| overlaps(*at, card, card_frame(*other, card))) + !taken.iter().any(|other| overlaps(*at, card, card_frame(*other, card))) && !zones.iter().any(|frame| overlaps(*at, card, *frame)) }) .unwrap_or_else(|| (first, under_everything(taken, zones, card))) @@ -565,11 +547,7 @@ pub fn build( let hit = criteria.passes(¬e); matched += usize::from(hit); - let entry = BoardNote { - note: model::decorate(note, request.now), - matches: hit, - position: None, - }; + let entry = BoardNote { note: model::decorate(note, request.now), matches: hit, position: None }; match seat { Seat::Zone(id) => by_folder.entry(id).or_default().push(entry), @@ -581,10 +559,7 @@ pub fn build( entry.position = positions.get(&entry.note.id).copied(); } - let by_id: HashMap<&str, &Folder> = folders - .iter() - .map(|folder| (folder.id.as_str(), folder)) - .collect(); + let by_id: HashMap<&str, &Folder> = folders.iter().map(|folder| (folder.id.as_str(), folder)).collect(); let zones: Vec = lineage .children(root) .iter() @@ -601,12 +576,7 @@ pub fn build( height: default_zone_height(notes.len(), !children.is_empty(), card), }); - BoardZone { - folder: (*folder).clone(), - frame, - notes, - children, - } + BoardZone { folder: (*folder).clone(), frame, notes, children } }) .collect(); @@ -696,10 +666,7 @@ pub fn arrange_everything( zones: folder_counts .iter() .zip(frames.iter()) - .map(|((folder_id, _), frame)| ZonePlacement { - folder_id: folder_id.clone(), - frame: *frame, - }) + .map(|((folder_id, _), frame)| ZonePlacement { folder_id: folder_id.clone(), frame: *frame }) .collect(), cards: flowed(loose_ids, loose_top(&frames), card), } @@ -710,20 +677,14 @@ pub fn arrange_everything( /// `zones` comes back empty: nothing placed or sized by hand is touched. #[must_use] pub fn arrange_loose_cards(frames: &[BoardFrame], loose_ids: &[String], card: i32) -> BoardLayout { - BoardLayout { - zones: Vec::new(), - cards: flowed(loose_ids, loose_top(frames), card), - } + BoardLayout { zones: Vec::new(), cards: flowed(loose_ids, loose_top(frames), card) } } fn flowed(loose_ids: &[String], top: i32, card: i32) -> Vec { loose_ids .iter() .zip(arrange_loose(loose_ids.len(), top, card)) - .map(|(note_id, position)| CardPlacement { - note_id: note_id.clone(), - position, - }) + .map(|(note_id, position)| CardPlacement { note_id: note_id.clone(), position }) .collect() } @@ -748,11 +709,7 @@ mod tests { } fn filed(id: &str, folder_id: Option<&str>) -> Note { - Note { - id: id.to_string(), - folder_id: folder_id.map(str::to_string), - ..note() - } + Note { id: id.to_string(), folder_id: folder_id.map(str::to_string), ..note() } } fn request(root: Option<&str>) -> BoardQuery { @@ -780,19 +737,8 @@ mod tests { ] } - fn board( - notes: Vec, - positions: &HashMap, - query: &BoardQuery, - ) -> BoardView { - build( - notes, - &folders(), - &HashMap::new(), - positions, - &Facets::default(), - query, - ) + fn board(notes: Vec, positions: &HashMap, query: &BoardQuery) -> BoardView { + build(notes, &folders(), &HashMap::new(), positions, &Facets::default(), query) } fn ids(notes: &[BoardNote]) -> Vec<&str> { @@ -800,12 +746,7 @@ mod tests { } fn frame(x: i32, y: i32, width: i32, height: i32) -> BoardFrame { - BoardFrame { - x, - y, - width, - height, - } + BoardFrame { x, y, width, height } } fn point(x: i32, y: i32) -> BoardPoint { @@ -814,11 +755,8 @@ mod tests { #[test] fn a_card_is_as_tall_as_the_lines_it_shows() { - let cases = [ - (PreviewLines::Three, 3, 120), - (PreviewLines::Four, 4, 140), - (PreviewLines::Five, 5, 160), - ]; + let cases = + [(PreviewLines::Three, 3, 120), (PreviewLines::Four, 4, 140), (PreviewLines::Five, 5, 160)]; for (lines, count, height) in cases { assert_eq!((lines.count(), lines.card_height()), (count, height)); @@ -859,10 +797,7 @@ mod tests { let space = Occupancy::on(¬es, &lineage, None); let infra = Occupancy::on(¬es, &lineage, Some("infra")); - assert_eq!( - space.per_folder, - HashMap::from([("infra".to_string(), 2), ("docs".to_string(), 1)]) - ); + assert_eq!(space.per_folder, HashMap::from([("infra".to_string(), 2), ("docs".to_string(), 1)])); assert_eq!(space.loose, ["loose"]); assert_eq!(infra.per_folder, HashMap::from([("perf".to_string(), 1)])); assert_eq!(infra.loose, ["in-infra"]); @@ -873,15 +808,9 @@ mod tests { #[test] fn a_frame_is_kept_on_the_board_and_big_enough_to_drop_a_card_into() { let cases = [ - ( - frame(-5, -1, 10, 10), - frame(0, 0, MIN_ZONE_WIDTH, MIN_ZONE_HEIGHT), - ), + (frame(-5, -1, 10, 10), frame(0, 0, MIN_ZONE_WIDTH, MIN_ZONE_HEIGHT)), (frame(40, 60, 600, 400), frame(40, 60, 600, 400)), - ( - frame(0, 0, i32::MAX, i32::MAX), - frame(0, 0, MAX_SIDE, MAX_SIDE), - ), + (frame(0, 0, i32::MAX, i32::MAX), frame(0, 0, MAX_SIDE, MAX_SIDE)), ]; for (asked, kept) in cases { @@ -894,10 +823,8 @@ mod tests { /// belong to the ground. #[test] fn a_point_falls_in_the_topmost_zone_that_holds_it() { - let frames = [ - ("under".to_string(), frame(0, 0, 100, 100)), - ("over".to_string(), frame(50, 50, 100, 100)), - ]; + let frames = + [("under".to_string(), frame(0, 0, 100, 100)), ("over".to_string(), frame(50, 50, 100, 100))]; let cases = [ (point(10, 10), Some("under")), (point(60, 60), Some("over")), @@ -933,8 +860,7 @@ mod tests { #[test] fn a_zone_is_tall_enough_for_its_rows_of_cards_and_never_less_than_one() { - let height = - |notes: usize, columns: i32, nested: bool| zone_height(notes, columns, nested, CARD); + let height = |notes: usize, columns: i32, nested: bool| zone_height(notes, columns, nested, CARD); assert_eq!(height(0, 2, false), height(1, 2, false)); assert_eq!(height(2, 2, false), height(1, 2, false)); @@ -942,19 +868,13 @@ mod tests { assert_eq!(height(2, 0, false), height(2, 1, false)); assert_eq!(height(1, 2, true) - height(1, 2, false), ZONE_SUBFOLDERS); assert_eq!(zone_height(1, 1, false, MIN_CARD_HEIGHT), MIN_ZONE_HEIGHT); - assert_eq!( - default_zone_height(3, true, CARD), - height(3, ZONE_COLUMNS, true) - ); + assert_eq!(default_zone_height(3, true, CARD), height(3, ZONE_COLUMNS, true)); } /// Three across in the order handed over; a row starts under the tallest of the one above. #[test] fn zones_are_laid_out_in_reading_order_three_across() { - let contents = [5, 0, 0, 0].map(|notes| ZoneContents { - notes, - nested: false, - }); + let contents = [5, 0, 0, 0].map(|notes| ZoneContents { notes, nested: false }); let width = default_zone_width(); let frames = arrange_zones(&contents, CARD); @@ -1002,11 +922,7 @@ mod tests { ]; for (taken, zones, seat) in cases { - assert_eq!( - free_slot(100, &taken, &zones, CARD), - seat, - "{taken:?} {zones:?}" - ); + assert_eq!(free_slot(100, &taken, &zones, CARD), seat, "{taken:?} {zones:?}"); } } @@ -1014,10 +930,7 @@ mod tests { fn a_card_with_no_seat_left_goes_under_everything() { let zone = frame(0, 0, 10_000, 5_000); - assert_eq!( - free_slot(100, &[], &[zone], CARD), - point(BOARD_MARGIN, 5_000 + GAP) - ); + assert_eq!(free_slot(100, &[], &[zone], CARD), point(BOARD_MARGIN, 5_000 + GAP)); } /// The run starts each search where the last stopped, and gives the seats one by one would. @@ -1053,23 +966,14 @@ mod tests { position: Some(point(0, 600)), }; - assert_eq!( - surface(&[], &[], CARD), - (960 + BOARD_MARGIN, 540 + BOARD_MARGIN) - ); - assert_eq!( - surface(&[zone], &[card], CARD), - (1_500 + BOARD_MARGIN, 600 + CARD + BOARD_MARGIN) - ); + assert_eq!(surface(&[], &[], CARD), (960 + BOARD_MARGIN, 540 + BOARD_MARGIN)); + assert_eq!(surface(&[zone], &[card], CARD), (1_500 + BOARD_MARGIN, 600 + CARD + BOARD_MARGIN)); } #[test] fn the_space_s_board_draws_its_top_folders_each_gathering_what_is_under_it() { - let notes = vec![ - filed("in-infra", Some("infra")), - filed("in-perf", Some("perf")), - filed("loose", None), - ]; + let notes = + vec![filed("in-infra", Some("infra")), filed("in-perf", Some("perf")), filed("loose", None)]; let view = board(notes, &HashMap::new(), &request(None)); @@ -1078,17 +982,9 @@ mod tests { .iter() .map(|zone| (zone.folder.id.as_str(), ids(&zone.notes))) .collect(); - assert_eq!( - zones, - [("infra", vec!["in-infra", "in-perf"]), ("docs", vec![])] - ); + assert_eq!(zones, [("infra", vec!["in-infra", "in-perf"]), ("docs", vec![])]); assert_eq!(ids(&view.loose), ["loose"]); - assert!( - view.zones[0] - .notes - .iter() - .all(|entry| entry.position.is_none()) - ); + assert!(view.zones[0].notes.iter().all(|entry| entry.position.is_none())); } /// Nothing from outside it: a note of a sibling folder, or loose in the space, is not drawn. @@ -1117,20 +1013,10 @@ mod tests { folder("alpha", Some("infra"), "Alpha"), folder("deep", Some("zeta"), "Deep"), ]; - let notes = vec![ - filed("a", Some("zeta")), - filed("b", Some("deep")), - filed("c", Some("infra")), - ]; + let notes = vec![filed("a", Some("zeta")), filed("b", Some("deep")), filed("c", Some("infra"))]; - let view = build( - notes, - &folders, - &HashMap::new(), - &HashMap::new(), - &Facets::default(), - &request(None), - ); + let view = + build(notes, &folders, &HashMap::new(), &HashMap::new(), &Facets::default(), &request(None)); let children: Vec<(&str, u32)> = view.zones[0] .children @@ -1145,29 +1031,13 @@ mod tests { fn a_zone_never_laid_out_is_sized_for_its_notes_and_its_sub_folders() { let stored = frame(300, 300, 600, 600); let frames = HashMap::from([("docs".to_string(), stored)]); - let notes = vec![ - filed("a", Some("infra")), - filed("b", Some("infra")), - filed("c", Some("infra")), - ]; + let notes = vec![filed("a", Some("infra")), filed("b", Some("infra")), filed("c", Some("infra"))]; - let view = build( - notes, - &folders(), - &frames, - &HashMap::new(), - &Facets::default(), - &request(None), - ); + let view = build(notes, &folders(), &frames, &HashMap::new(), &Facets::default(), &request(None)); assert_eq!( view.zones[0].frame, - frame( - BOARD_MARGIN, - BOARD_MARGIN, - default_zone_width(), - default_zone_height(3, true, CARD) - ) + frame(BOARD_MARGIN, BOARD_MARGIN, default_zone_width(), default_zone_height(3, true, CARD)) ); assert_eq!(view.zones[1].frame, stored); } @@ -1187,26 +1057,15 @@ mod tests { .collect(); assert_eq!(at["placed"], placed); let zones: Vec = view.zones.iter().map(|zone| zone.frame).collect(); - assert_eq!( - at["new"], - free_slot(loose_top(&zones), &[placed], &zones, CARD) - ); + assert_eq!(at["new"], free_slot(loose_top(&zones), &[placed], &zones, CARD)); } /// Spatial memory is what the board has that the list does not: a card is dimmed in place. #[test] fn a_card_that_does_not_match_is_dimmed_not_dropped() { - let notes = vec![ - Note { - title: "Postgres".to_string(), - ..filed("hit", Some("infra")) - }, - filed("miss", None), - ]; - let query = BoardQuery { - search: "postgres".to_string(), - ..request(None) - }; + let notes = + vec![Note { title: "Postgres".to_string(), ..filed("hit", Some("infra")) }, filed("miss", None)]; + let query = BoardQuery { search: "postgres".to_string(), ..request(None) }; let view = board(notes, &HashMap::new(), &query); @@ -1218,22 +1077,11 @@ mod tests { #[test] fn the_quick_filter_alone_counts_as_filtering() { - let cases = [ - (NoteFilter::All, false), - (NoteFilter::Pinned, true), - (NoteFilter::Untriaged, true), - ]; + let cases = [(NoteFilter::All, false), (NoteFilter::Pinned, true), (NoteFilter::Untriaged, true)]; for (filter, filtering) in cases { - let query = BoardQuery { - filter, - ..request(None) - }; - assert_eq!( - board(Vec::new(), &HashMap::new(), &query).is_filtering, - filtering, - "{filter:?}" - ); + let query = BoardQuery { filter, ..request(None) }; + assert_eq!(board(Vec::new(), &HashMap::new(), &query).is_filtering, filtering, "{filter:?}"); } } @@ -1241,10 +1089,7 @@ mod tests { fn a_pinned_card_comes_first_in_its_zone() { let notes = vec![ filed("first", Some("infra")), - Note { - pinned: true, - ..filed("pinned", Some("infra")) - }, + Note { pinned: true, ..filed("pinned", Some("infra")) }, filed("second", Some("infra")), ]; @@ -1257,25 +1102,12 @@ mod tests { #[test] fn the_rails_offer_the_space_s_tags_and_languages() { let facets = Facets { - tags: vec![FacetCount { - value: "sql".to_string(), - count: 2, - }], - languages: vec![FacetCount { - value: Language::Sql, - count: 2, - }], + tags: vec![FacetCount { value: "sql".to_string(), count: 2 }], + languages: vec![FacetCount { value: Language::Sql, count: 2 }], ..Facets::default() }; - let view = build( - Vec::new(), - &folders(), - &HashMap::new(), - &HashMap::new(), - &facets, - &request(None), - ); + let view = build(Vec::new(), &folders(), &HashMap::new(), &HashMap::new(), &facets, &request(None)); assert_eq!(view.available_tags, ["sql"]); assert_eq!(view.available_languages, [Language::Sql]); @@ -1285,10 +1117,7 @@ mod tests { #[test] fn a_card_carries_only_its_preview() { let long = Note { - content: (1..=20) - .map(|line| format!("line {line}")) - .collect::>() - .join("\n"), + content: (1..=20).map(|line| format!("line {line}")).collect::>().join("\n"), ..filed("long", None) }; @@ -1307,11 +1136,7 @@ mod tests { path: vec![id.to_string()], }; let mut view = board( - vec![ - filed("own", Some("infra")), - filed("below", Some("perf")), - filed("loose", None), - ], + vec![filed("own", Some("infra")), filed("below", Some("perf")), filed("loose", None)], &HashMap::new(), &request(None), ); @@ -1333,13 +1158,7 @@ mod tests { #[test] fn tidying_everything_lays_the_zones_out_again_and_flows_the_loose_cards_under_them() { let counts = [ - ( - "infra".to_string(), - ZoneContents { - notes: 3, - nested: true, - }, - ), + ("infra".to_string(), ZoneContents { notes: 3, nested: true }), ("docs".to_string(), ZoneContents::default()), ]; let loose = ["a".to_string(), "b".to_string()]; @@ -1347,11 +1166,8 @@ mod tests { let layout = arrange_everything(&counts, &loose, CARD); let frames = arrange_zones(&[counts[0].1, counts[1].1], CARD); - let placed: Vec<(&str, BoardFrame)> = layout - .zones - .iter() - .map(|zone| (zone.folder_id.as_str(), zone.frame)) - .collect(); + let placed: Vec<(&str, BoardFrame)> = + layout.zones.iter().map(|zone| (zone.folder_id.as_str(), zone.frame)).collect(); assert_eq!(placed, [("infra", frames[0]), ("docs", frames[1])]); let seats = arrange_loose(2, loose_top(&frames), CARD); let cards: Vec = layout.cards.iter().map(|card| card.position).collect(); diff --git a/crates/engine/src/folders/model.rs b/crates/engine/src/folders/model.rs index b54b8167b..02aa06991 100644 --- a/crates/engine/src/folders/model.rs +++ b/crates/engine/src/folders/model.rs @@ -121,25 +121,15 @@ impl Lineage { let mut lineage = Self::default(); for (id, parent) in &links { - let parent = parent - .clone() - .filter(|parent| known.contains(parent.as_str())); - lineage - .children - .entry(parent.clone()) - .or_default() - .push(id.clone()); + let parent = parent.clone().filter(|parent| known.contains(parent.as_str())); + lineage.children.entry(parent.clone()).or_default().push(id.clone()); lineage.parents.insert(id.clone(), parent); } lineage } pub fn of(folders: &[Folder]) -> Self { - Self::new( - folders - .iter() - .map(|folder| (folder.id.clone(), folder.parent_id.clone())), - ) + Self::new(folders.iter().map(|folder| (folder.id.clone(), folder.parent_id.clone()))) } pub fn contains(&self, id: &str) -> bool { @@ -152,9 +142,7 @@ impl Lineage { /// In the order the folders were handed over: creation, for the board's zones. pub fn children(&self, parent: Option<&str>) -> &[String] { - self.children - .get(&parent.map(str::to_string)) - .map_or(&[], Vec::as_slice) + self.children.get(&parent.map(str::to_string)).map_or(&[], Vec::as_slice) } /// The folder and everything under it, the folder first. A cycle a damaged row could make @@ -225,8 +213,7 @@ impl Lineage { None => return Seat::Elsewhere, }, }; - path.get(start) - .map_or(Seat::Elsewhere, |zone| Seat::Zone(zone.clone())) + path.get(start).map_or(Seat::Elsewhere, |zone| Seat::Zone(zone.clone())) } /// A folder made under `parent`: in this space, and not past [`MAX_DEPTH`]. @@ -240,20 +227,13 @@ impl Lineage { if let Some(parent) = parent && self.subtree(id).iter().any(|below| below == parent) { - return Err(ValidationError::new( - "parentId", - "a folder cannot move into itself", - )); + return Err(ValidationError::new("parentId", "a folder cannot move into itself")); } self.check_room(parent, self.height(id).max(1)) } /// A sub-tree `levels` deep arriving from another space under `parent` of this one. - pub fn check_arrival( - &self, - parent: Option<&str>, - levels: usize, - ) -> Result<(), ValidationError> { + pub fn check_arrival(&self, parent: Option<&str>, levels: usize) -> Result<(), ValidationError> { self.check_room(parent, levels) } @@ -262,17 +242,11 @@ impl Lineage { None => 0, Some(parent) if self.contains(parent) => self.depth(parent), Some(_) => { - return Err(ValidationError::new( - "parentId", - "the parent is not a folder of this space", - )); + return Err(ValidationError::new("parentId", "the parent is not a folder of this space")); } }; if above + levels > MAX_DEPTH { - return Err(ValidationError::new( - "parentId", - format!("folders nest at most {MAX_DEPTH} deep"), - )); + return Err(ValidationError::new("parentId", format!("folders nest at most {MAX_DEPTH} deep"))); } Ok(()) } @@ -293,22 +267,12 @@ mod tests { use super::*; fn tree(links: &[(&str, Option<&str>)]) -> Lineage { - Lineage::new( - links - .iter() - .map(|(id, parent)| ((*id).to_string(), parent.map(str::to_string))), - ) + Lineage::new(links.iter().map(|(id, parent)| ((*id).to_string(), parent.map(str::to_string)))) } /// a ─ b ─ c, and a ─ d, made in that order; e alone at the top. fn sample() -> Lineage { - tree(&[ - ("a", None), - ("b", Some("a")), - ("c", Some("b")), - ("d", Some("a")), - ("e", None), - ]) + tree(&[("a", None), ("b", Some("a")), ("c", Some("b")), ("d", Some("a")), ("e", None)]) } /// f1 ─ f2 ─ … ─ f8, as deep as folders nest, beside `others`. @@ -349,19 +313,13 @@ mod tests { ) .unwrap(); - assert_eq!( - (folder.parent_id, folder.colour), - (None, FolderColour::Blue) - ); + assert_eq!((folder.parent_id, folder.colour), (None, FolderColour::Blue)); } #[test] fn a_folder_s_name_is_read_trimmed_and_never_blank() { - let draft = |name: &str| FolderDraft { - space_id: "s".to_string(), - name: name.to_string(), - parent_id: None, - }; + let draft = + |name: &str| FolderDraft { space_id: "s".to_string(), name: name.to_string(), parent_id: None }; assert_eq!(draft(" Perf\t").validated_name(), Ok("Perf".to_string())); assert_eq!(validated_name(" ").unwrap_err().field, "name"); @@ -451,14 +409,8 @@ mod tests { assert_eq!(lineage.check_child(None), Ok(())); assert_eq!(lineage.check_child(Some("f7")), Ok(())); - assert_eq!( - lineage.check_child(Some("f8")).unwrap_err().field, - "parentId" - ); - assert_eq!( - lineage.check_child(Some("elsewhere")).unwrap_err().field, - "parentId" - ); + assert_eq!(lineage.check_child(Some("f8")).unwrap_err().field, "parentId"); + assert_eq!(lineage.check_child(Some("elsewhere")).unwrap_err().field, "parentId"); } #[test] @@ -466,10 +418,7 @@ mod tests { let lineage = sample(); for into in ["a", "b", "c"] { - assert_eq!( - lineage.check_move("a", Some(into)).unwrap_err().field, - "parentId" - ); + assert_eq!(lineage.check_move("a", Some(into)).unwrap_err().field, "parentId"); } assert_eq!(lineage.check_move("b", Some("e")), Ok(())); assert_eq!(lineage.check_move("b", None), Ok(())); @@ -481,19 +430,10 @@ mod tests { let lineage = deepest(&[("g", None), ("h", Some("g"))]); assert_eq!(lineage.check_move("g", Some("f6")), Ok(())); - assert_eq!( - lineage.check_move("g", Some("f7")).unwrap_err().field, - "parentId" - ); + assert_eq!(lineage.check_move("g", Some("f7")).unwrap_err().field, "parentId"); assert_eq!(lineage.check_move("h", Some("f7")), Ok(())); assert_eq!(lineage.check_move("unknown", Some("f7")), Ok(())); - assert_eq!( - lineage - .check_move("g", Some("elsewhere")) - .unwrap_err() - .field, - "parentId" - ); + assert_eq!(lineage.check_move("g", Some("elsewhere")).unwrap_err().field, "parentId"); } #[test] @@ -501,17 +441,8 @@ mod tests { let lineage = deepest(&[]); assert_eq!(lineage.check_arrival(Some("f6"), 2), Ok(())); - assert_eq!( - lineage.check_arrival(Some("f7"), 2).unwrap_err().field, - "parentId" - ); + assert_eq!(lineage.check_arrival(Some("f7"), 2).unwrap_err().field, "parentId"); assert_eq!(lineage.check_arrival(None, MAX_DEPTH), Ok(())); - assert_eq!( - lineage - .check_arrival(Some("elsewhere"), 1) - .unwrap_err() - .field, - "parentId" - ); + assert_eq!(lineage.check_arrival(Some("elsewhere"), 1).unwrap_err().field, "parentId"); } } diff --git a/crates/engine/src/folders/store.rs b/crates/engine/src/folders/store.rs index d86e3e0ec..99ca835b5 100644 --- a/crates/engine/src/folders/store.rs +++ b/crates/engine/src/folders/store.rs @@ -32,10 +32,8 @@ struct FolderRow { impl FolderRow { fn open(self, vault: &Vault) -> Result { Ok(Folder { - created_at: iso8601::parse(&self.created_at).map_err(|_| StorageError::CorruptRow { - id: self.id.clone(), - field: "createdAt", - })?, + created_at: iso8601::parse(&self.created_at) + .map_err(|_| StorageError::CorruptRow { id: self.id.clone(), field: "createdAt" })?, name: vault.open(&self.name)?, // Degrades like `notes.language`: a folder is worth more than its swatch. colour: self.colour.parse().unwrap_or_default(), @@ -122,22 +120,13 @@ pub fn by_id( .collect(); ( folder.id.clone(), - NoteFolder { - id: folder.id.clone(), - name: folder.name.clone(), - colour: folder.colour, - path, - }, + NoteFolder { id: folder.id.clone(), name: folder.name.clone(), colour: folder.colour, path }, ) }) .collect()) } -fn find( - connection: &mut SqliteConnection, - vault: &Vault, - id: &str, -) -> Result { +fn find(connection: &mut SqliteConnection, vault: &Vault, id: &str) -> Result { folders::table .find(id) .select(FolderRow::as_select()) @@ -158,11 +147,7 @@ pub fn exists(connection: &mut SqliteConnection, id: &str) -> Result Result { +pub fn belongs_to(connection: &mut SqliteConnection, id: &str, space_id: &str) -> Result { Ok(folders::table .find(id) .filter(folders::space_id.eq(space_id)) @@ -201,9 +186,7 @@ pub fn create( name: &str, now: DateTime, ) -> Result { - connection.transaction(|connection, vault| { - create_in(connection, vault, space_id, parent_id, name, now) - }) + connection.transaction(|connection, vault| create_in(connection, vault, space_id, parent_id, name, now)) } /// For a caller already inside a transaction — an import creates the folders it needs. @@ -252,31 +235,17 @@ pub(crate) fn create_in( pub fn rename(connection: &mut Library, id: &str, name: &str) -> Result { connection.transaction(|connection, vault| { let folder = find(connection, vault, id)?; - ensure_unique_name( - connection, - vault, - &folder.space_id, - folder.parent_id.as_deref(), - name, - Some(id), - )?; + ensure_unique_name(connection, vault, &folder.space_id, folder.parent_id.as_deref(), name, Some(id))?; diesel::update(folders::table.find(id)) .set(folders::name.eq(vault.seal(name)?)) .execute(connection)?; - Ok(Folder { - name: name.to_string(), - ..folder - }) + Ok(Folder { name: name.to_string(), ..folder }) }) } -pub fn recolour( - connection: &mut Library, - id: &str, - colour: FolderColour, -) -> Result { +pub fn recolour(connection: &mut Library, id: &str, colour: FolderColour) -> Result { connection.transaction(|connection, vault| { diesel::update(folders::table.find(id)) .set(folders::colour.eq(colour.as_str())) @@ -313,14 +282,7 @@ pub fn move_to( } else { lineage(connection, space_id)?.check_arrival(parent_id, from.height(id).max(1))?; } - ensure_unique_name( - connection, - vault, - space_id, - parent_id, - &folder.name, - Some(id), - )?; + ensure_unique_name(connection, vault, space_id, parent_id, &folder.name, Some(id))?; if folder.space_id != space_id { was.notes = cross(connection, &from.subtree(id), space_id)?; } @@ -333,10 +295,7 @@ pub fn move_to( /// The undo of [`move_to`]: back under the parent it left, in its space and in the frame it /// had; `None` when a parent deleted since, or one it now holds, leaves it where it is. The /// notes that went back: every note filed in it, none left in a folder of another space. -pub fn move_back( - connection: &mut Library, - was: &FolderMove, -) -> Result>, StorageError> { +pub fn move_back(connection: &mut Library, was: &FolderMove) -> Result>, StorageError> { connection.transaction(|connection, vault| { let folder = find(connection, vault, &was.folder_id)?; let here = lineage(connection, &folder.space_id)?; @@ -344,17 +303,10 @@ pub fn move_back( let room = if folder.space_id == was.space_id { here.check_move(&folder.id, parent) } else { - lineage(connection, &was.space_id)? - .check_arrival(parent, here.height(&folder.id).max(1)) + lineage(connection, &was.space_id)?.check_arrival(parent, here.height(&folder.id).max(1)) }; - let named = ensure_unique_name( - connection, - vault, - &was.space_id, - parent, - &folder.name, - Some(&folder.id), - ); + let named = + ensure_unique_name(connection, vault, &was.space_id, parent, &folder.name, Some(&folder.id)); if room.is_err() || named.is_err() { return Ok(None); } @@ -414,10 +366,7 @@ fn place( /// What it held goes to its parent — its notes, filed there, and its sub-folders, each to a /// free slot on that board — or loose at the top of the space. `updated_at` is not touched: /// the user aimed at the folder. -pub fn contents( - connection: &mut Library, - id: &str, -) -> Result { +pub fn contents(connection: &mut Library, id: &str) -> Result { let (connection, _vault) = connection.split(); let under = lineage_of(connection, id)?.subtree(id); Ok(super::model::FolderContents { @@ -591,20 +540,13 @@ pub fn move_into( .load::<(String, String, Option)>(connection)? .into_iter() .filter(|(_, _, current)| current.as_deref() != Some(folder_id)) - .map(|(note_id, space_id, folder_id)| NotePlacement { - note_id, - space_id, - folder_id, - }) + .map(|(note_id, space_id, folder_id)| NotePlacement { note_id, space_id, folder_id }) .collect(); let touched: Vec = moved.iter().map(|one| one.note_id.clone()).collect(); board::forget_positions(connection, &touched)?; diesel::update(notes::table.filter(notes::id.eq_any(&touched))) - .set(( - notes::space_id.eq(space_id), - notes::folder_id.eq(Some(folder_id)), - )) + .set((notes::space_id.eq(space_id), notes::folder_id.eq(Some(folder_id)))) .execute(connection)?; let lineage = lineage_of(connection, folder_id)?; @@ -615,10 +557,7 @@ pub fn move_into( } /// How many live notes these folders hold, which is what a zone has to be tall enough for. -fn count_filed( - connection: &mut SqliteConnection, - folder_ids: &[String], -) -> Result { +fn count_filed(connection: &mut SqliteConnection, folder_ids: &[String]) -> Result { let count: i64 = notes::table .filter(notes::folder_id.eq_any(folder_ids)) .filter(notes::deleted_at.is_null()) @@ -640,10 +579,7 @@ pub fn restore_filings( connection.transaction(|connection, _vault| { let mut restored = 0; - let ids: Vec = filings - .iter() - .map(|filing| filing.note_id.clone()) - .collect(); + let ids: Vec = filings.iter().map(|filing| filing.note_id.clone()).collect(); board::forget_positions(connection, &ids)?; for filing in filings { @@ -654,13 +590,10 @@ pub fn restore_filings( continue; } - restored += diesel::update( - notes::table - .find(&filing.note_id) - .filter(notes::deleted_at.is_null()), - ) - .set(notes::folder_id.eq(filing.folder_id.as_deref())) - .execute(connection)?; + restored += + diesel::update(notes::table.find(&filing.note_id).filter(notes::deleted_at.is_null())) + .set(notes::folder_id.eq(filing.folder_id.as_deref())) + .execute(connection)?; } // Undoing puts notes back into zones that may no longer be tall enough for them; a diff --git a/crates/engine/src/folders/store/board.rs b/crates/engine/src/folders/store/board.rs index e6a6cb024..34370fdea 100644 --- a/crates/engine/src/folders/store/board.rs +++ b/crates/engine/src/folders/store/board.rs @@ -10,8 +10,8 @@ use crate::db::Library; use crate::db::schema::{folders, note_positions, notes}; use crate::error::StorageError; use crate::folders::board::{ - self, BoardArrangement, BoardFrame, BoardLayout, BoardPoint, BoardScope, CardPlacement, - Occupancy, ZoneContents, ZonePlacement, + self, BoardArrangement, BoardFrame, BoardLayout, BoardPoint, BoardScope, CardPlacement, Occupancy, + ZoneContents, ZonePlacement, }; /// What a board read resolves before anything can be drawn: where each zone sits, and @@ -23,12 +23,7 @@ type FrameColumns = (Option, Option, Option, Option); /// All four columns move together: a half-laid-out folder is not a state, and a folder /// never laid out answers `None`. fn frame_from((x, y, width, height): FrameColumns) -> Option { - Some(BoardFrame { - x: x?, - y: y?, - width: width?, - height: height?, - }) + Some(BoardFrame { x: x?, y: y?, width: width?, height: height? }) } pub fn frames( @@ -37,10 +32,7 @@ pub fn frames( ) -> Result, StorageError> { let rows = folders::table .filter(folders::space_id.eq(space_id)) - .select(( - folders::id, - (folders::x, folders::y, folders::w, folders::h), - )) + .select((folders::id, (folders::x, folders::y, folders::w, folders::h))) .load::<(String, FrameColumns)>(connection)?; Ok(rows @@ -81,14 +73,7 @@ pub fn grow_to_fit( return Ok(()); } - set_frame( - connection, - folder_id, - board::clamp(BoardFrame { - height: needed, - ..frame - }), - ) + set_frame(connection, folder_id, board::clamp(BoardFrame { height: needed, ..frame })) } pub fn set_frame( @@ -116,23 +101,13 @@ pub fn positions( ) -> Result, StorageError> { let rows = note_positions::table .filter( - note_positions::note_id.eq_any( - notes::table - .select(notes::id) - .filter(notes::space_id.eq(space_id.to_string())), - ), + note_positions::note_id + .eq_any(notes::table.select(notes::id).filter(notes::space_id.eq(space_id.to_string()))), ) - .select(( - note_positions::note_id, - note_positions::x, - note_positions::y, - )) + .select((note_positions::note_id, note_positions::x, note_positions::y)) .load::<(String, i32, i32)>(connection)?; - Ok(rows - .into_iter() - .map(|(note_id, x, y)| (note_id, BoardPoint { x, y })) - .collect()) + Ok(rows.into_iter().map(|(note_id, x, y)| (note_id, BoardPoint { x, y })).collect()) } pub fn set_position( @@ -152,10 +127,7 @@ pub fn set_position( } /// A row exists only for a loose note: filing one drops it, since a filed card flows. -pub fn forget_positions( - connection: &mut SqliteConnection, - note_ids: &[String], -) -> Result<(), StorageError> { +pub fn forget_positions(connection: &mut SqliteConnection, note_ids: &[String]) -> Result<(), StorageError> { if note_ids.is_empty() { return Ok(()); } @@ -183,11 +155,7 @@ pub fn save_layout( if !crate::folders::store::exists(connection, &placement.folder_id)? { return Err(StorageError::FolderNotFound(placement.folder_id.clone())); } - set_frame( - connection, - &placement.folder_id, - board::clamp(placement.frame), - )?; + set_frame(connection, &placement.folder_id, board::clamp(placement.frame))?; } // ⚠️ Only a note filed in the root has a place on its board: one filed elsewhere between @@ -207,11 +175,7 @@ pub fn save_layout( continue; } - set_position( - connection, - &placement.note_id, - board::clamp_point(placement.position), - )?; + set_position(connection, &placement.note_id, board::clamp_point(placement.position))?; } Ok(()) @@ -240,10 +204,8 @@ pub fn geometry( stored_positions.retain(|id, _| loose.contains(id.as_str())); let folder_ids: Vec<&String> = zones.iter().map(|(id, _)| id).collect(); - let missing: Vec<&&String> = folder_ids - .iter() - .filter(|id| !stored_frames.contains_key(**id)) - .collect(); + let missing: Vec<&&String> = + folder_ids.iter().filter(|id| !stored_frames.contains_key(**id)).collect(); if !missing.is_empty() { // Against every zone, so one added later takes its reading-order slot rather @@ -348,11 +310,7 @@ fn loose_ids( }; Ok(query - .order(( - notes::pinned.desc(), - notes::updated_at.desc(), - notes::id.asc(), - )) + .order((notes::pinned.desc(), notes::updated_at.desc(), notes::id.asc())) .select(notes::id) .load::(connection)?) } @@ -387,28 +345,19 @@ pub fn arrange( }; for placement in &next.zones { - set_frame( - connection, - &placement.folder_id, - board::clamp(placement.frame), - )?; + set_frame(connection, &placement.folder_id, board::clamp(placement.frame))?; } for placement in &next.cards { - set_position( - connection, - &placement.note_id, - board::clamp_point(placement.position), - )?; + set_position(connection, &placement.note_id, board::clamp_point(placement.position))?; } let zones: Vec = next .zones .iter() .filter_map(|placement| { - before.get(&placement.folder_id).map(|frame| ZonePlacement { - folder_id: placement.folder_id.clone(), - frame: *frame, - }) + before + .get(&placement.folder_id) + .map(|frame| ZonePlacement { folder_id: placement.folder_id.clone(), frame: *frame }) }) .collect(); let cards: Vec = next @@ -417,34 +366,27 @@ pub fn arrange( .filter_map(|placement| { places .get(&placement.note_id) - .map(|position| CardPlacement { - note_id: placement.note_id.clone(), - position: *position, - }) + .map(|position| CardPlacement { note_id: placement.note_id.clone(), position: *position }) }) .collect(); let moved = zones .iter() .filter(|was| { - next.zones.iter().any(|now| { - now.folder_id == was.folder_id && board::clamp(now.frame) != was.frame - }) + next.zones + .iter() + .any(|now| now.folder_id == was.folder_id && board::clamp(now.frame) != was.frame) }) .count() + cards .iter() .filter(|was| { next.cards.iter().any(|now| { - now.note_id == was.note_id - && board::clamp_point(now.position) != was.position + now.note_id == was.note_id && board::clamp_point(now.position) != was.position }) }) .count(); - Ok(BoardArrangement { - moved: saturating_u32(moved), - previous: BoardLayout { zones, cards }, - }) + Ok(BoardArrangement { moved: saturating_u32(moved), previous: BoardLayout { zones, cards } }) }) } diff --git a/crates/engine/src/host.rs b/crates/engine/src/host.rs index db12d7fee..49044492a 100644 --- a/crates/engine/src/host.rs +++ b/crates/engine/src/host.rs @@ -42,10 +42,7 @@ pub struct RecordingSink(Mutex>); impl RecordingSink { pub fn events(&self) -> Vec { - self.0 - .lock() - .map(|events| events.clone()) - .unwrap_or_default() + self.0.lock().map(|events| events.clone()).unwrap_or_default() } } @@ -65,11 +62,7 @@ mod tests { fn finished(id: &str) -> EngineEvent { EngineEvent::Run(RunEvent { id: id.to_string(), - step: RunStep::Finished { - cancelled: false, - millis: 1, - capped: false, - }, + step: RunStep::Finished { cancelled: false, millis: 1, capped: false }, }) } diff --git a/crates/engine/src/http.rs b/crates/engine/src/http.rs index 818b659ac..927123b36 100644 --- a/crates/engine/src/http.rs +++ b/crates/engine/src/http.rs @@ -48,17 +48,11 @@ pub fn http_tree(engine: &Engine) -> Result { } /// The palette's requests, ranked here: the URL is read from each sealed document. -pub fn search_http_requests( - engine: &Engine, - search: &str, -) -> Result, AppError> { +pub fn search_http_requests(engine: &Engine, search: &str) -> Result, AppError> { let db = &engine.db; let mut connection = lock(db)?; - Ok(search::rank( - store::search_candidates(&mut connection)?, - search, - )) + Ok(search::rank(store::search_candidates(&mut connection)?, search)) } pub fn create_http_collection(engine: &Engine, name: &str) -> Result { @@ -67,11 +61,7 @@ pub fn create_http_collection(engine: &Engine, name: &str) -> Result Result { +pub fn create_http_request(engine: &Engine, draft: &HttpRequestDraft) -> Result { let db = &engine.db; let name = model::validated_name(&draft.name)?; let mut connection = lock(db)?; - Ok(store::create_request( - &mut connection, - draft, - &name, - Utc::now(), - )?) + Ok(store::create_request(&mut connection, draft, &name, Utc::now())?) } /// The first save of a request where nothing holds it yet: what `create` names is created @@ -121,16 +103,8 @@ pub fn create_http_request_in( ) -> Result { let db = &engine.db; let name = model::validated_name(&draft.name)?; - let collection = create - .collection - .as_deref() - .map(model::validated_name) - .transpose()?; - let folder = create - .folder - .as_deref() - .map(model::validated_name) - .transpose()?; + let collection = create.collection.as_deref().map(model::validated_name).transpose()?; + let folder = create.folder.as_deref().map(model::validated_name).transpose()?; let mut connection = lock(db)?; @@ -157,21 +131,11 @@ pub fn save_http_request( patch: &HttpRequestPatch, ) -> Result { let db = &engine.db; - let name = patch - .name - .as_deref() - .map(model::validated_name) - .transpose()?; + let name = patch.name.as_deref().map(model::validated_name).transpose()?; let mut connection = lock(db)?; - Ok(store::save_request( - &mut connection, - id, - patch, - name.as_deref(), - Utc::now(), - )?) + Ok(store::save_request(&mut connection, id, patch, name.as_deref(), Utc::now())?) } pub fn rename_http_item(engine: &Engine, item: &HttpItem, name: &str) -> Result<(), AppError> { @@ -199,11 +163,7 @@ pub fn delete_http_item(engine: &Engine, item: &HttpItem) -> Result<(), AppError } /// The copy's name comes from the front: no user-visible word is Rust's. -pub fn duplicate_http_item( - engine: &Engine, - item: &HttpItem, - name: &str, -) -> Result { +pub fn duplicate_http_item(engine: &Engine, item: &HttpItem, name: &str) -> Result { let db = &engine.db; let name = model::validated_name(name)?; @@ -219,10 +179,7 @@ pub fn move_http_item(engine: &Engine, item: &HttpItem, place: &HttpPlace) -> Re Ok(store::move_item(&mut connection, item, place)?) } -pub fn http_settings( - engine: &Engine, - item: &HttpItem, -) -> Result { +pub fn http_settings(engine: &Engine, item: &HttpItem) -> Result { let db = &engine.db; let mut connection = lock(db)?; @@ -252,10 +209,8 @@ pub fn save_http_settings( let mut connection = lock(db)?; // The dialog does not hold the run order: the one the runner left is kept. - let settings = model::ContainerSettings { - run_order: store::settings(&mut connection, item)?.run_order, - ..settings - }; + let settings = + model::ContainerSettings { run_order: store::settings(&mut connection, item)?.run_order, ..settings }; Ok(store::save_settings(&mut connection, item, &settings)?) } @@ -269,11 +224,7 @@ pub fn inherited_http_settings( let db = &engine.db; let mut connection = lock(db)?; - Ok(store::inherited( - &mut connection, - collection_id, - folder_id.map(std::string::String::as_str), - )?) + Ok(store::inherited(&mut connection, collection_id, folder_id.map(std::string::String::as_str))?) } /// What a body implies, whether a JSON one reads, and whether its method seldom carries one: @@ -304,9 +255,7 @@ pub struct BodyAnswer { /// Each header's fault by its rank, or none: the table marks the row and says why. The rule is /// the model's; the table holds none. -pub fn check_http_headers( - rows: &[model::KeyValue], -) -> Result>, AppError> { +pub fn check_http_headers(rows: &[model::KeyValue]) -> Result>, AppError> { Ok(model::header_faults(rows)) } @@ -329,11 +278,7 @@ pub fn implied_http_headers( let inherited = match collection_id { Some(collection_id) => { let mut connection = lock(db)?; - store::inherited( - &mut connection, - &collection_id, - folder_id.map(std::string::String::as_str), - )? + store::inherited(&mut connection, &collection_id, folder_id.map(std::string::String::as_str))? } None => settings::inherit(&[]), }; @@ -388,12 +333,7 @@ fn resolver_for( inherited: &settings::Inherited, environment_id: Option<&str>, ) -> Result { - Ok(variables::Resolver::new(&layers_for( - connection, - own, - inherited, - environment_id, - )?)) + Ok(variables::Resolver::new(&layers_for(connection, own, inherited, environment_id)?)) } fn layers_for( @@ -405,11 +345,8 @@ fn layers_for( use variables::{VariableLayer, VariableScope}; let sets = environments::store::list(connection)?; - let mut layers = vec![VariableLayer { - scope: VariableScope::Request, - from: String::new(), - variables: own.to_vec(), - }]; + let mut layers = + vec![VariableLayer { scope: VariableScope::Request, from: String::new(), variables: own.to_vec() }]; layers.extend(inherited.variables.iter().cloned()); if let Some(environment) = sets .environments @@ -437,31 +374,12 @@ pub fn generate_http_code( request: CodeRequestOf, ) -> Result { let db = &engine.db; - let CodeRequestOf { - target, - options, - kind, - method, - document, - collection_id, - folder_id, - environment_id, - } = request; + let CodeRequestOf { target, options, kind, method, document, collection_id, folder_id, environment_id } = + request; let mut connection = lock(db)?; - let inherited = inherited_of( - &mut connection, - collection_id.as_deref(), - folder_id.as_deref(), - )?; - let layers = layers_for( - &mut connection, - &document.variables, - &inherited, - environment_id.as_deref(), - )?; - Ok(codegen::generate( - target, options, kind, method, &document, &inherited, &layers, - )) + let inherited = inherited_of(&mut connection, collection_id.as_deref(), folder_id.as_deref())?; + let layers = layers_for(&mut connection, &document.variables, &inherited, environment_id.as_deref())?; + Ok(codegen::generate(target, options, kind, method, &document, &inherited, &layers)) } #[derive(Debug, Clone)] @@ -483,25 +401,10 @@ pub fn http_variables( request: VariablesRequest, ) -> Result, AppError> { let db = &engine.db; - let VariablesRequest { - kind, - document, - collection_id, - folder_id, - environment_id, - } = request; + let VariablesRequest { kind, document, collection_id, folder_id, environment_id } = request; let mut connection = lock(db)?; - let inherited = inherited_of( - &mut connection, - collection_id.as_deref(), - folder_id.as_deref(), - )?; - let resolver = resolver_for( - &mut connection, - &document.variables, - &inherited, - environment_id.as_deref(), - )?; + let inherited = inherited_of(&mut connection, collection_id.as_deref(), folder_id.as_deref())?; + let resolver = resolver_for(&mut connection, &document.variables, &inherited, environment_id.as_deref())?; Ok(resolver.used(&variables::texts(kind, &document, &inherited))) } @@ -522,10 +425,7 @@ pub fn http_run_order(engine: &Engine, item: &HttpItem) -> Result Result<(), AppError> { let db = &engine.db; let mut connection = lock(db)?; - let settings = model::ContainerSettings { - run_order: order, - ..store::settings(&mut connection, item)? - }; + let settings = model::ContainerSettings { run_order: order, ..store::settings(&mut connection, item)? }; Ok(store::save_settings(&mut connection, item, &settings)?) } @@ -547,10 +444,7 @@ pub fn save_http_run_order( /// A collection or a folder run, one request after the other, each sent as a send is — its /// scripts, its tests, its extractions — but written in no history. Each step is said as an /// event; answers once the run is over. The lock is held for reads alone, never over a send. -pub async fn run_http_collection( - engine: Arc, - run: runner::RunRequest, -) -> Result<(), AppError> { +pub async fn run_http_collection(engine: Arc, run: runner::RunRequest) -> Result<(), AppError> { let tree = db::run(Arc::clone(&engine), |engine| { let db = &engine.db; let mut connection = lock(db)?; @@ -563,16 +457,9 @@ pub async fn run_http_collection( .iter() .filter_map(|id| placed.iter().find(|known| &known.id == id).cloned()) .collect(); - let rows = run - .data - .as_ref() - .map(|data| data.rows.clone()) - .unwrap_or_default(); - let iterations = if rows.is_empty() { - run.iterations.max(1) - } else { - u32::try_from(rows.len()).unwrap_or(u32::MAX) - }; + let rows = run.data.as_ref().map(|data| data.rows.clone()).unwrap_or_default(); + let iterations = + if rows.is_empty() { run.iterations.max(1) } else { u32::try_from(rows.len()).unwrap_or(u32::MAX) }; let runs = &engine.runs; runs.start(&run.id); let started = std::time::Instant::now(); @@ -589,27 +476,13 @@ pub async fn run_http_collection( } steps += 1; let placed = &order[index]; - let step = RunStep { - run: &run, - iteration, - iterations, - index, - steps, - placed, - row: &row, - }; + let step = RunStep { run: &run, iteration, iterations, index, steps, placed, row: &row }; let Some((result, next)) = run_step(&engine, step, &mut overlay).await else { cancelled = true; break 'run; }; let failed = result.failed(); - say_run( - &engine, - &run.id, - runner::RunStep::Ended { - result: Box::new(result), - }, - ); + say_run(&engine, &run.id, runner::RunStep::Ended { result: Box::new(result) }); if run.stop_on_failure && failed { break 'run; } @@ -630,15 +503,7 @@ pub async fn run_http_collection( } runs.finish(&run.id); let millis = u32::try_from(started.elapsed().as_millis()).unwrap_or(u32::MAX); - say_run( - &engine, - &run.id, - runner::RunStep::Finished { - cancelled, - millis, - capped, - }, - ); + say_run(&engine, &run.id, runner::RunStep::Finished { cancelled, millis, capped }); Ok(()) } @@ -665,11 +530,7 @@ pub fn cancel_http_send(engine: &Engine, id: &str) -> Result { } /// The whole body of the last answer to `id`, not the text shown: `false` when there is none. -pub async fn save_http_response( - engine: Arc, - id: String, - path: String, -) -> Result { +pub async fn save_http_response(engine: Arc, id: String, path: String) -> Result { crate::transfer::model::validate_path(&path)?; off_thread(move || engine.sending.save(&id, Path::new(&path)).context(&path)) .await? @@ -683,10 +544,7 @@ pub fn forget_http_response(engine: &Engine, id: &str) -> Result<(), AppError> { } /// The last answer to `id` as an image to show, when it is one. -pub async fn http_response_image( - engine: Arc, - id: String, -) -> Result, AppError> { +pub async fn http_response_image(engine: Arc, id: String) -> Result, AppError> { off_thread(move || engine.sending.image(&id)).await } @@ -701,17 +559,11 @@ pub async fn http_response_note( } /// What was sent, newest first, a group a local day. -pub fn http_history( - engine: &Engine, - tz_offset_minutes: i32, -) -> Result, AppError> { +pub fn http_history(engine: &Engine, tz_offset_minutes: i32) -> Result, AppError> { let db = &engine.db; let mut connection = lock(db)?; - Ok(history::by_day( - history::store::list(&mut connection)?, - tz_offset_minutes, - )) + Ok(history::by_day(history::store::list(&mut connection)?, tz_offset_minutes)) } pub fn http_history_entry(engine: &Engine, id: &str) -> Result { @@ -737,20 +589,14 @@ pub fn clear_http_history(engine: &Engine) -> Result { } /// One entry gone, answered whole: its undo hands it back to `restore_http_history_entry`. -pub fn delete_http_history_entry( - engine: &Engine, - id: &str, -) -> Result { +pub fn delete_http_history_entry(engine: &Engine, id: &str) -> Result { let db = &engine.db; let mut connection = lock(db)?; Ok(history::store::delete(&mut connection, id)?) } -pub fn restore_http_history_entry( - engine: &Engine, - entry: &history::HistoryEntry, -) -> Result<(), AppError> { +pub fn restore_http_history_entry(engine: &Engine, entry: &history::HistoryEntry) -> Result<(), AppError> { let db = &engine.db; let mut connection = lock(db)?; @@ -775,11 +621,7 @@ pub fn http_history_onto_request( Err(crate::error::StorageError::HttpItemNotFound(_)) => return Ok(None), Err(error) => return Err(error.into()), }; - let above = store::inherited( - &mut connection, - ¤t.collection_id, - current.folder_id.as_deref(), - )?; + let above = store::inherited(&mut connection, ¤t.collection_id, current.folder_id.as_deref())?; Ok(Some(history::onto(&entry, ¤t, &above.headers))) } @@ -788,16 +630,11 @@ pub fn http_history_draft(engine: &Engine, id: &str) -> Result Result { +pub fn describe_graphql(document: &graphql::GraphqlDocument) -> Result { Ok(graphql::describe(document)) } @@ -818,54 +655,26 @@ pub struct WebsocketRequest { /// Its headers and auth composed like a request's, under the lock for what it inherits; the /// handshake waited on without it. Answers once the socket is open. -pub async fn connect_websocket( - engine: Arc, - request: WebsocketRequest, -) -> Result<(), AppError> { - let WebsocketRequest { - id, - mut document, - collection_id, - folder_id, - environment_id, - } = request; +pub async fn connect_websocket(engine: Arc, request: WebsocketRequest) -> Result<(), AppError> { + let WebsocketRequest { id, mut document, collection_id, folder_id, environment_id } = request; document.body = model::RequestBody::None; let outgoing = db::run(Arc::clone(&engine), move |engine| { let db = &engine.db; let mut connection = lock(db)?; - let inherited = inherited_of( - &mut connection, - collection_id.as_deref(), - folder_id.as_deref(), - )?; - let resolver = resolver_for( - &mut connection, - &document.variables, - &inherited, - environment_id.as_deref(), - )?; + let inherited = inherited_of(&mut connection, collection_id.as_deref(), folder_id.as_deref())?; + let resolver = + resolver_for(&mut connection, &document.variables, &inherited, environment_id.as_deref())?; let (mut document, inherited) = variables::resolve(&document, &inherited, &resolver); document.url = websocket::socket_url(&document.url)?; - Ok(send::compose( - model::RequestKind::Http, - model::HttpMethod::Get, - &document, - &inherited, - ) - .map(|outgoing| (outgoing, document.websocket.protocols))?) + Ok(send::compose(model::RequestKind::Http, model::HttpMethod::Get, &document, &inherited) + .map(|outgoing| (outgoing, document.websocket.protocols))?) }) .await?; let (outgoing, protocols) = outgoing; Ok(engine .sockets - .connect( - &engine.runtime, - Arc::clone(&engine.events), - id, - outgoing, - &protocols, - ) + .connect(&engine.runtime, Arc::clone(&engine.events), id, outgoing, &protocols) .await?) } @@ -923,20 +732,13 @@ pub fn http_environments(engine: &Engine) -> Result Result { +pub fn create_http_environment(engine: &Engine, name: &str) -> Result { let db = &engine.db; let name = environments::validated_name(name)?; let mut connection = lock(db)?; - Ok(environments::store::create( - &mut connection, - &name, - Utc::now(), - )?) + Ok(environments::store::create(&mut connection, &name, Utc::now())?) } pub fn save_http_environment( @@ -945,20 +747,11 @@ pub fn save_http_environment( patch: &environments::EnvironmentPatch, ) -> Result { let db = &engine.db; - let name = patch - .name - .as_deref() - .map(environments::validated_name) - .transpose()?; + let name = patch.name.as_deref().map(environments::validated_name).transpose()?; let mut connection = lock(db)?; - Ok(environments::store::save( - &mut connection, - id, - patch, - name.as_deref(), - )?) + Ok(environments::store::save(&mut connection, id, patch, name.as_deref())?) } pub fn save_http_globals( @@ -968,11 +761,7 @@ pub fn save_http_globals( let db = &engine.db; let mut connection = lock(db)?; - Ok(environments::store::save_globals( - &mut connection, - variables, - Utc::now(), - )?) + Ok(environments::store::save_globals(&mut connection, variables, Utc::now())?) } /// The copy's name comes from the front: no user-visible word is Rust's. @@ -986,12 +775,7 @@ pub fn duplicate_http_environment( let mut connection = lock(db)?; - Ok(environments::store::duplicate( - &mut connection, - id, - &name, - Utc::now(), - )?) + Ok(environments::store::duplicate(&mut connection, id, &name, Utc::now())?) } pub fn delete_http_environment(engine: &Engine, id: &str) -> Result<(), AppError> { diff --git a/crates/engine/src/http/codegen.rs b/crates/engine/src/http/codegen.rs index 13ad8efb9..3ed77c8df 100644 --- a/crates/engine/src/http/codegen.rs +++ b/crates/engine/src/http/codegen.rs @@ -167,11 +167,7 @@ impl CodeRequest { /// starting on a variable left unresolved is written as typed: `{{base}}` holds its own scheme. fn with_scheme(url: &str) -> String { let url = url.trim(); - if url.contains("://") || url.starts_with("{{") { - url.to_string() - } else { - format!("http://{url}") - } + if url.contains("://") || url.starts_with("{{") { url.to_string() } else { format!("http://{url}") } } fn append_query(url: &mut String, pairs: &[(&str, &str)]) { @@ -195,11 +191,7 @@ pub fn request_of( ) -> CodeRequest { let mut url = with_scheme(&document.url); let auth = send::auth_of(document, inherited); - if let RequestAuth::ApiKey { - name, - value, - place: KeyPlace::Query, - } = auth + if let RequestAuth::ApiKey { name, value, place: KeyPlace::Query } = auth && !name.trim().is_empty() { append_query(&mut url, &[(name.trim(), value)]); @@ -215,12 +207,7 @@ pub fn request_of( if let Some(variables) = variables { pairs.push(("variables", variables)); } - if let Some(name) = document - .graphql - .operation_name - .as_deref() - .filter(|name| !name.is_empty()) - { + if let Some(name) = document.graphql.operation_name.as_deref().filter(|name| !name.is_empty()) { pairs.push(("operationName", name)); } append_query(&mut url, &pairs); @@ -228,10 +215,7 @@ pub fn request_of( } RequestKind::Graphql => { let variables = graphql::variables(&document.graphql).ok().flatten(); - ( - HttpMethod::Post, - CodeBody::Text(graphql::body(&document.graphql, variables)), - ) + (HttpMethod::Post, CodeBody::Text(graphql::body(&document.graphql, variables))) } RequestKind::Http | RequestKind::Websocket => (method, body_of(&document.body)), }; @@ -248,9 +232,7 @@ pub fn request_of( fn body_of(body: &RequestBody) -> CodeBody { match body { RequestBody::None => CodeBody::None, - RequestBody::Json { text } | RequestBody::Text { text } if text.is_empty() => { - CodeBody::None - } + RequestBody::Json { text } | RequestBody::Text { text } if text.is_empty() => CodeBody::None, RequestBody::Json { text } | RequestBody::Text { text } => CodeBody::Text(text.clone()), RequestBody::Form { fields } => CodeBody::Form( fields @@ -316,22 +298,13 @@ pub fn generate( } } let (document, inherited) = if options.resolve_variables { - let resolver = if options.include_secrets { - everything - } else { - Resolver::new(&without_secrets(layers)) - }; + let resolver = + if options.include_secrets { everything } else { Resolver::new(&without_secrets(layers)) }; variables::resolve(document, inherited, &resolver) } else { (document.clone(), inherited.clone()) }; - let request = request_of( - kind, - method, - &document, - &inherited, - options.follow_redirects, - ); + let request = request_of(kind, method, &document, &inherited, options.follow_redirects); let notice = (!target.sends_multipart() && matches!(request.body, CodeBody::Multipart(_))) .then_some(CodeNotice::MultipartUnsupported); let code = match target { @@ -356,13 +329,7 @@ pub fn generate( CodeTarget::Dart => dart::write(&request), CodeTarget::Elixir => req::write(&request), }; - GeneratedCode { - code, - language: target.language(), - secrets, - unresolved, - notice, - } + GeneratedCode { code, language: target.language(), secrets, unresolved, notice } } /// `'…'` for a POSIX shell: a quote inside closes, escapes and reopens. @@ -388,13 +355,7 @@ pub fn shell_lines(first: &str, arguments: &[String], multiline: bool) -> String lines .iter() .enumerate() - .map(|(at, line)| { - if at == last { - line.clone() - } else { - format!("{line} \\") - } - }) + .map(|(at, line)| if at == last { line.clone() } else { format!("{line} \\") }) .collect::>() .join("\n") } @@ -423,10 +384,7 @@ pub(crate) mod golden { url: "https://api.exemple.fr/customers/cus_42/invoices?page=1&limit=50".to_string(), headers: vec![ ("Accept".to_string(), "application/json".to_string()), - ( - "Authorization".to_string(), - "Bearer {{accessToken}}".to_string(), - ), + ("Authorization".to_string(), "Bearer {{accessToken}}".to_string()), ], basic: None, body: CodeBody::None, @@ -443,10 +401,7 @@ pub(crate) mod golden { let form = CodeRequest { method: HttpMethod::Post, url: "https://auth.exemple.fr/token".to_string(), - headers: vec![( - "Content-Type".to_string(), - "application/x-www-form-urlencoded".to_string(), - )], + headers: vec![("Content-Type".to_string(), "application/x-www-form-urlencoded".to_string())], basic: Some(("billing-web".to_string(), "{{clientSecret}}".to_string())), body: CodeBody::Form(vec![ ("grant_type".to_string(), "client_credentials".to_string()), @@ -460,11 +415,7 @@ pub(crate) mod golden { headers: Vec::new(), basic: None, body: CodeBody::Multipart(vec![ - CodePart { - name: "title".to_string(), - value: "Facture".to_string(), - file: false, - }, + CodePart { name: "title".to_string(), value: "Facture".to_string(), file: false }, CodePart { name: "scan".to_string(), value: "C:/Users/ada/facture.pdf".to_string(), @@ -476,21 +427,12 @@ pub(crate) mod golden { let file = CodeRequest { method: HttpMethod::Post, url: "https://api.exemple.fr/upload".to_string(), - headers: vec![( - "Content-Type".to_string(), - "application/octet-stream".to_string(), - )], + headers: vec![("Content-Type".to_string(), "application/octet-stream".to_string())], basic: None, body: CodeBody::File("/tmp/archive.zip".to_string()), follow_redirects: false, }; - vec![ - ("get", get), - ("json", json), - ("form", form), - ("multipart", multipart), - ("file", file), - ] + vec![("get", get), ("json", json), ("form", form), ("multipart", multipart), ("file", file)] } /// The file under `golden/`, or written there when `GOLDEN_WRITE` is set. @@ -519,55 +461,27 @@ mod tests { use crate::http::variables::VariableScope; fn row(key: &str, value: &str) -> KeyValue { - KeyValue { - key: key.to_string(), - value: value.to_string(), - ..KeyValue::default() - } + KeyValue { key: key.to_string(), value: value.to_string(), ..KeyValue::default() } } fn off(key: &str) -> KeyValue { - KeyValue { - enabled: false, - ..row(key, "x") - } + KeyValue { enabled: false, ..row(key, "x") } } fn part(key: &str, value: &str, file: bool, enabled: bool) -> FormPart { - FormPart { - enabled, - key: key.to_string(), - value: value.to_string(), - file, - ..FormPart::default() - } + FormPart { enabled, key: key.to_string(), value: value.to_string(), file, ..FormPart::default() } } fn http(document: &RequestDocument) -> CodeRequest { - request_of( - RequestKind::Http, - HttpMethod::Post, - document, - &inherit(&[]), - false, - ) + request_of(RequestKind::Http, HttpMethod::Post, document, &inherit(&[]), false) } fn layer(variables: Vec) -> VariableLayer { - VariableLayer { - scope: VariableScope::Environment, - from: "Prod".to_string(), - variables, - } + VariableLayer { scope: VariableScope::Environment, from: "Prod".to_string(), variables } } fn variable(name: &str, value: &str, kind: VariableKind) -> Variable { - Variable { - name: name.to_string(), - value: value.to_string(), - kind, - ..Variable::default() - } + Variable { name: name.to_string(), value: value.to_string(), kind, ..Variable::default() } } /// What a snippet of each target is saved as; the three that build no multipart body say so. @@ -577,10 +491,7 @@ mod tests { assert_eq!(target.as_str().parse::(), Ok(target)); assert_eq!( target.sends_multipart(), - !matches!( - target, - CodeTarget::Wget | CodeTarget::Java | CodeTarget::Swift - ), + !matches!(target, CodeTarget::Wget | CodeTarget::Java | CodeTarget::Swift), "{target:?}" ); } @@ -613,10 +524,7 @@ mod tests { }, ..RequestDocument::default() }; - let variable = RequestDocument { - url: "{{base}}/a".to_string(), - ..RequestDocument::default() - }; + let variable = RequestDocument { url: "{{base}}/a".to_string(), ..RequestDocument::default() }; let unnamed_key = RequestDocument { url: "https://shop.test/".to_string(), auth: RequestAuth::ApiKey { @@ -639,10 +547,7 @@ mod tests { let document = RequestDocument { url: "https://shop.test/".to_string(), headers: vec![row("X-Trace", "1")], - auth: RequestAuth::Basic { - username: "ada".to_string(), - password: "pw".to_string(), - }, + auth: RequestAuth::Basic { username: "ada".to_string(), password: "pw".to_string() }, ..RequestDocument::default() }; @@ -659,22 +564,10 @@ mod tests { fn the_body_is_what_a_send_would_write() { for (body, expected) in [ (RequestBody::None, CodeBody::None), + (RequestBody::Json { text: String::new() }, CodeBody::None), + (RequestBody::Text { text: "t".to_string() }, CodeBody::Text("t".to_string())), ( - RequestBody::Json { - text: String::new(), - }, - CodeBody::None, - ), - ( - RequestBody::Text { - text: "t".to_string(), - }, - CodeBody::Text("t".to_string()), - ), - ( - RequestBody::Form { - fields: vec![row(" a ", "1"), off("b"), row(" ", "x")], - }, + RequestBody::Form { fields: vec![row(" a ", "1"), off("b"), row(" ", "x")] }, CodeBody::Form(vec![("a".to_string(), "1".to_string())]), ), ( @@ -691,23 +584,13 @@ mod tests { file: true, }]), ), + (RequestBody::Binary { path: " ".to_string() }, CodeBody::None), ( - RequestBody::Binary { - path: " ".to_string(), - }, - CodeBody::None, - ), - ( - RequestBody::Binary { - path: " /dump.bin ".to_string(), - }, + RequestBody::Binary { path: " /dump.bin ".to_string() }, CodeBody::File("/dump.bin".to_string()), ), ] { - let document = RequestDocument { - body, - ..RequestDocument::default() - }; + let document = RequestDocument { body, ..RequestDocument::default() }; assert_eq!(http(&document).body, expected); } @@ -717,45 +600,23 @@ mod tests { /// query, whatever method the document holds. #[test] fn a_graphql_request_is_written_as_it_is_sent() { - let mut document = RequestDocument { - url: "https://shop.test/graphql".to_string(), - ..RequestDocument::default() - }; + let mut document = + RequestDocument { url: "https://shop.test/graphql".to_string(), ..RequestDocument::default() }; document.graphql.query = "{ me }".to_string(); document.graphql.variables = "{\"a\":1}".to_string(); document.graphql.operation_name = Some("Me".to_string()); - let posted = request_of( - RequestKind::Graphql, - HttpMethod::Delete, - &document, - &inherit(&[]), - true, - ); + let posted = request_of(RequestKind::Graphql, HttpMethod::Delete, &document, &inherit(&[]), true); document.graphql.as_get = true; - let got = request_of( - RequestKind::Graphql, - HttpMethod::Delete, - &document, - &inherit(&[]), - true, - ); + let got = request_of(RequestKind::Graphql, HttpMethod::Delete, &document, &inherit(&[]), true); document.graphql.operation_name = Some(String::new()); document.graphql.variables = "[not an object]".to_string(); - let bare = request_of( - RequestKind::Graphql, - HttpMethod::Delete, - &document, - &inherit(&[]), - true, - ); + let bare = request_of(RequestKind::Graphql, HttpMethod::Delete, &document, &inherit(&[]), true); assert_eq!(posted.method, HttpMethod::Post); assert_eq!( posted.body, - CodeBody::Text( - r#"{"query":"{ me }","variables":{"a":1},"operationName":"Me"}"#.to_string() - ) + CodeBody::Text(r#"{"query":"{ me }","variables":{"a":1},"operationName":"Me"}"#.to_string()) ); assert!(posted.follow_redirects); assert_eq!((got.method, &got.body), (HttpMethod::Get, &CodeBody::None)); @@ -779,10 +640,7 @@ mod tests { } fn document_using(names: &str) -> RequestDocument { - RequestDocument { - url: format!("https://shop.test/{names}"), - ..RequestDocument::default() - } + RequestDocument { url: format!("https://shop.test/{names}"), ..RequestDocument::default() } } /// A secret stays its `{{name}}` and is named, unless asked for in clear; a name nothing @@ -794,14 +652,8 @@ mod tests { variable("token", "t0k3n", VariableKind::Secret), ])]; let document = document_using("{{host}}/{{token}}/{{nowhere}}"); - let resolve = CodeOptions { - resolve_variables: true, - ..CodeOptions::default() - }; - let in_clear = CodeOptions { - include_secrets: true, - ..resolve - }; + let resolve = CodeOptions { resolve_variables: true, ..CodeOptions::default() }; + let in_clear = CodeOptions { include_secrets: true, ..resolve }; let generate_with = |options| { generate( CodeTarget::Curl, @@ -818,30 +670,14 @@ mod tests { let clear = generate_with(in_clear); let typed = generate_with(CodeOptions::default()); - assert!( - masked - .code - .contains("https://shop.test/h/{{token}}/{{nowhere}}"), - "{}", - masked.code - ); + assert!(masked.code.contains("https://shop.test/h/{{token}}/{{nowhere}}"), "{}", masked.code); assert_eq!( (masked.secrets, masked.unresolved), (vec!["token".to_string()], vec!["nowhere".to_string()]) ); - assert!( - clear.code.contains("https://shop.test/h/t0k3n/{{nowhere}}"), - "{}", - clear.code - ); + assert!(clear.code.contains("https://shop.test/h/t0k3n/{{nowhere}}"), "{}", clear.code); assert!(clear.secrets.is_empty()); - assert!( - typed - .code - .contains("https://shop.test/{{host}}/{{token}}/{{nowhere}}"), - "{}", - typed.code - ); + assert!(typed.code.contains("https://shop.test/{{host}}/{{token}}/{{nowhere}}"), "{}", typed.code); assert_eq!(masked.language, Language::Sh); } @@ -849,9 +685,7 @@ mod tests { #[test] fn a_target_that_cannot_send_a_multipart_body_says_so() { let document = RequestDocument { - body: RequestBody::Multipart { - parts: vec![part("a", "1", false, true)], - }, + body: RequestBody::Multipart { parts: vec![part("a", "1", false, true)] }, ..document_using("") }; let notice = |target| { @@ -900,11 +734,7 @@ mod tests { &[], ); - assert!( - code.code.contains("shop.test/orders"), - "{target:?}: {}", - code.code - ); + assert!(code.code.contains("shop.test/orders"), "{target:?}: {}", code.code); assert_eq!(code.language, target.language()); } } @@ -921,23 +751,14 @@ mod tests { fn arguments_are_written_on_one_line_or_one_a_line() { let arguments = ["-X POST".to_string(), "'https://shop.test/'".to_string()]; - assert_eq!( - shell_lines("curl", &arguments, false), - "curl -X POST 'https://shop.test/'" - ); - assert_eq!( - shell_lines("curl", &arguments, true), - "curl \\\n -X POST \\\n 'https://shop.test/'" - ); + assert_eq!(shell_lines("curl", &arguments, false), "curl -X POST 'https://shop.test/'"); + assert_eq!(shell_lines("curl", &arguments, true), "curl \\\n -X POST \\\n 'https://shop.test/'"); assert_eq!(shell_lines("curl", &[], true), "curl"); } #[test] fn a_form_is_encoded_as_it_is_sent() { - let fields = [ - ("a b".to_string(), "x&y=z".to_string()), - ("c".to_string(), String::new()), - ]; + let fields = [("a b".to_string(), "x&y=z".to_string()), ("c".to_string(), String::new())]; assert_eq!(form_encoded(&fields), "a+b=x%26y%3Dz&c="); } diff --git a/crates/engine/src/http/codegen/angular.rs b/crates/engine/src/http/codegen/angular.rs index f38533ab2..d9c04125d 100644 --- a/crates/engine/src/http/codegen/angular.rs +++ b/crates/engine/src/http/codegen/angular.rs @@ -39,14 +39,9 @@ pub fn write(request: &CodeRequest) -> String { CodeBody::None => None, CodeBody::Text(text) => Some(string(text)), CodeBody::Form(fields) => { - let entries: Vec<(String, String)> = fields - .iter() - .map(|(name, value)| (name.clone(), string(value))) - .collect(); - Some(format!( - "new URLSearchParams({}).toString()", - object(&entries, " ") - )) + let entries: Vec<(String, String)> = + fields.iter().map(|(name, value)| (name.clone(), string(value))).collect(); + Some(format!("new URLSearchParams({}).toString()", object(&entries, " "))) } CodeBody::Multipart(parts) => { for part in parts.iter().filter(|part| part.file) { @@ -54,11 +49,7 @@ pub fn write(request: &CodeRequest) -> String { } lines.push("const form = new FormData();".to_string()); for part in parts { - let value = if part.file { - identifier(&part.name) - } else { - string(&part.value) - }; + let value = if part.file { identifier(&part.name) } else { string(&part.value) }; lines.push(format!("form.append({}, {value});", string(&part.name))); } Some("form".to_string()) @@ -73,10 +64,7 @@ pub fn write(request: &CodeRequest) -> String { } let mut options = Vec::new(); if !headers.is_empty() { - options.push(( - "headers".to_string(), - format!("new HttpHeaders({})", object(&headers, " ")), - )); + options.push(("headers".to_string(), format!("new HttpHeaders({})", object(&headers, " ")))); } if let Some(body) = body { options.push(("body".to_string(), body)); diff --git a/crates/engine/src/http/codegen/axios.rs b/crates/engine/src/http/codegen/axios.rs index ddf05c2dc..3ae8ad991 100644 --- a/crates/engine/src/http/codegen/axios.rs +++ b/crates/engine/src/http/codegen/axios.rs @@ -28,10 +28,7 @@ pub fn write(request: &CodeRequest) -> String { options.push(( "auth".to_string(), object( - &[ - ("username".to_string(), string(user)), - ("password".to_string(), string(password)), - ], + &[("username".to_string(), string(user)), ("password".to_string(), string(password))], " ", ), )); @@ -44,10 +41,7 @@ pub fn write(request: &CodeRequest) -> String { } // An answer of 4xx or 5xx is an answer to print, not an exception to catch. options.push(("validateStatus".to_string(), "() => true".to_string())); - lines.push(format!( - "const response = await axios.request({});", - object(&options, "") - )); + lines.push(format!("const response = await axios.request({});", object(&options, ""))); lines.push("console.log(response.status, response.data);".to_string()); lines.join("\n") } diff --git a/crates/engine/src/http/codegen/csharp.rs b/crates/engine/src/http/codegen/csharp.rs index 74a8504cf..186302af4 100644 --- a/crates/engine/src/http/codegen/csharp.rs +++ b/crates/engine/src/http/codegen/csharp.rs @@ -40,11 +40,7 @@ pub fn write(request: &CodeRequest) -> String { .iter() .filter(|(name, _)| !name.eq_ignore_ascii_case("content-type")) { - lines.push(format!( - "request.Headers.TryAddWithoutValidation({}, {});", - quoted(name), - quoted(value) - )); + lines.push(format!("request.Headers.TryAddWithoutValidation({}, {});", quoted(name), quoted(value))); } if let Some((user, password)) = &request.basic { lines.push(format!( @@ -61,8 +57,7 @@ pub fn write(request: &CodeRequest) -> String { )), CodeBody::Form(fields) => { lines.push( - "request.Content = new FormUrlEncodedContent(new Dictionary" - .to_string(), + "request.Content = new FormUrlEncodedContent(new Dictionary".to_string(), ); lines.push("{".to_string()); for (name, value) in fields { @@ -91,10 +86,7 @@ pub fn write(request: &CodeRequest) -> String { lines.push("request.Content = form;".to_string()); } CodeBody::File(path) => { - lines.push(format!( - "request.Content = new StreamContent(File.OpenRead({}));", - quoted(path) - )); + lines.push(format!("request.Content = new StreamContent(File.OpenRead({}));", quoted(path))); if let Some(content_type) = content_type { lines.push(format!( "request.Content.Headers.ContentType = new MediaTypeHeaderValue({});", diff --git a/crates/engine/src/http/codegen/curl.rs b/crates/engine/src/http/codegen/curl.rs index 71c3454eb..d2635f351 100644 --- a/crates/engine/src/http/codegen/curl.rs +++ b/crates/engine/src/http/codegen/curl.rs @@ -18,26 +18,17 @@ pub fn write(request: &CodeRequest, multiline: bool) -> String { arguments.push("--location".to_string()); } for (name, value) in &request.headers { - arguments.push(format!( - "--header {}", - shell_quoted(&format!("{name}: {value}")) - )); + arguments.push(format!("--header {}", shell_quoted(&format!("{name}: {value}")))); } if let Some((user, password)) = &request.basic { - arguments.push(format!( - "--user {}", - shell_quoted(&format!("{user}:{password}")) - )); + arguments.push(format!("--user {}", shell_quoted(&format!("{user}:{password}")))); } match &request.body { CodeBody::None => {} CodeBody::Text(text) => arguments.push(format!("--data-raw {}", shell_quoted(text))), CodeBody::Form(fields) => { for (name, value) in fields { - arguments.push(format!( - "--data-urlencode {}", - shell_quoted(&format!("{name}={value}")) - )); + arguments.push(format!("--data-urlencode {}", shell_quoted(&format!("{name}={value}")))); } } CodeBody::Multipart(parts) => { @@ -52,10 +43,7 @@ pub fn write(request: &CodeRequest, multiline: bool) -> String { } } CodeBody::File(path) => { - arguments.push(format!( - "--data-binary {}", - shell_quoted(&format!("@{path}")) - )); + arguments.push(format!("--data-binary {}", shell_quoted(&format!("@{path}")))); } } shell_lines(&first, &arguments, multiline) @@ -78,10 +66,7 @@ mod tests { follow_redirects: false, }; - let text = write( - &request(CodeBody::Text("@/etc/hostname".to_string())), - false, - ); + let text = write(&request(CodeBody::Text("@/etc/hostname".to_string())), false); let form = write( &request(CodeBody::Multipart(vec![super::super::CodePart { name: "a".to_string(), diff --git a/crates/engine/src/http/codegen/dart.rs b/crates/engine/src/http/codegen/dart.rs index 59afb2cda..2affd661c 100644 --- a/crates/engine/src/http/codegen/dart.rs +++ b/crates/engine/src/http/codegen/dart.rs @@ -27,19 +27,12 @@ pub fn write(request: &CodeRequest) -> String { lines.push("Future main() async {".to_string()); lines.push(format!( " final request = http.{}({}, Uri.parse({}));", - if multipart { - "MultipartRequest" - } else { - "Request" - }, + if multipart { "MultipartRequest" } else { "Request" }, quoted(request.method.as_str()), quoted(&request.url) )); if !request.headers.is_empty() { - lines.push(format!( - " request.headers.addAll({});", - map(&request.headers) - )); + lines.push(format!(" request.headers.addAll({});", map(&request.headers))); } if let Some((user, password)) = &request.basic { lines.push(format!( @@ -68,18 +61,12 @@ pub fn write(request: &CodeRequest) -> String { } } } - CodeBody::File(path) => lines.push(format!( - " request.bodyBytes = await File({}).readAsBytes();", - quoted(path) - )), + CodeBody::File(path) => { + lines.push(format!(" request.bodyBytes = await File({}).readAsBytes();", quoted(path))); + } } - lines.push(format!( - " request.followRedirects = {};", - request.follow_redirects - )); - lines.push( - " final response = await http.Response.fromStream(await request.send());".to_string(), - ); + lines.push(format!(" request.followRedirects = {};", request.follow_redirects)); + lines.push(" final response = await http.Response.fromStream(await request.send());".to_string()); lines.push(" print('${response.statusCode} ${response.body}');".to_string()); lines.push("}".to_string()); lines.join("\n") diff --git a/crates/engine/src/http/codegen/fetch.rs b/crates/engine/src/http/codegen/fetch.rs index 9fb4e9f09..b3293e71d 100644 --- a/crates/engine/src/http/codegen/fetch.rs +++ b/crates/engine/src/http/codegen/fetch.rs @@ -23,11 +23,7 @@ pub fn write(request: &CodeRequest) -> String { if !request.follow_redirects { options.push(("redirect".to_string(), string("manual"))); } - lines.push(format!( - "const response = await fetch({}, {});", - string(&request.url), - object(&options, "") - )); + lines.push(format!("const response = await fetch({}, {});", string(&request.url), object(&options, ""))); lines.push("console.log(response.status, await response.text());".to_string()); lines.join("\n") } diff --git a/crates/engine/src/http/codegen/go.rs b/crates/engine/src/http/codegen/go.rs index 806b818aa..87a5aaf92 100644 --- a/crates/engine/src/http/codegen/go.rs +++ b/crates/engine/src/http/codegen/go.rs @@ -46,9 +46,8 @@ pub fn write(request: &CodeRequest) -> String { } } body_lines.push("writer.Close()".to_string()); - after_request.push( - "request.Header.Set(\"Content-Type\", writer.FormDataContentType())".to_string(), - ); + after_request + .push("request.Header.Set(\"Content-Type\", writer.FormDataContentType())".to_string()); "&form".to_string() } CodeBody::File(path) => { @@ -68,19 +67,11 @@ pub fn write(request: &CodeRequest) -> String { )); lines.push("if err != nil {\n\t\tpanic(err)\n\t}".to_string()); for (name, value) in &request.headers { - lines.push(format!( - "request.Header.Set({}, {})", - quoted(name), - quoted(value) - )); + lines.push(format!("request.Header.Set({}, {})", quoted(name), quoted(value))); } lines.extend(after_request); if let Some((user, password)) = &request.basic { - lines.push(format!( - "request.SetBasicAuth({}, {})", - quoted(user), - quoted(password) - )); + lines.push(format!("request.SetBasicAuth({}, {})", quoted(user), quoted(password))); } if request.follow_redirects { lines.push("client := &http.Client{}".to_string()); @@ -96,16 +87,9 @@ pub fn write(request: &CodeRequest) -> String { lines.push("answer, _ := io.ReadAll(response.Body)".to_string()); lines.push("fmt.Println(response.StatusCode, string(answer))".to_string()); - let imports: Vec = imports - .into_iter() - .map(|import| format!("\t{}", quoted(import))) - .collect(); + let imports: Vec = imports.into_iter().map(|import| format!("\t{}", quoted(import))).collect(); let body: Vec = lines.into_iter().map(|line| format!("\t{line}")).collect(); - format!( - "package main\n\nimport (\n{}\n)\n\nfunc main() {{\n{}\n}}", - imports.join("\n"), - body.join("\n") - ) + format!("package main\n\nimport (\n{}\n)\n\nfunc main() {{\n{}\n}}", imports.join("\n"), body.join("\n")) } #[cfg(test)] diff --git a/crates/engine/src/http/codegen/guzzle.rs b/crates/engine/src/http/codegen/guzzle.rs index 7c8cd1b7e..49b9d590e 100644 --- a/crates/engine/src/http/codegen/guzzle.rs +++ b/crates/engine/src/http/codegen/guzzle.rs @@ -25,19 +25,14 @@ pub fn write(request: &CodeRequest) -> String { options.push(("headers".to_string(), array(&headers, " "))); } if let Some((user, password)) = &request.basic { - options.push(( - "auth".to_string(), - format!("[{}, {}]", quoted(user), quoted(password)), - )); + options.push(("auth".to_string(), format!("[{}, {}]", quoted(user), quoted(password)))); } match &request.body { CodeBody::None => {} CodeBody::Text(text) => options.push(("body".to_string(), quoted(text))), CodeBody::Form(fields) => { - let fields: Vec<(String, String)> = fields - .iter() - .map(|(name, value)| (name.clone(), quoted(value))) - .collect(); + let fields: Vec<(String, String)> = + fields.iter().map(|(name, value)| (name.clone(), quoted(value))).collect(); options.push(("form_params".to_string(), array(&fields, " "))); } CodeBody::Multipart(parts) => { @@ -49,25 +44,16 @@ pub fn write(request: &CodeRequest) -> String { } else { quoted(&part.value) }; - format!( - " ['name' => {}, 'contents' => {contents}],", - quoted(&part.name) - ) + format!(" ['name' => {}, 'contents' => {contents}],", quoted(&part.name)) }) .collect(); - options.push(( - "multipart".to_string(), - format!("[\n{}\n ]", lines.join("\n")), - )); + options.push(("multipart".to_string(), format!("[\n{}\n ]", lines.join("\n")))); } CodeBody::File(path) => { options.push(("body".to_string(), format!("fopen({}, 'r')", quoted(path)))); } } - options.push(( - "allow_redirects".to_string(), - request.follow_redirects.to_string(), - )); + options.push(("allow_redirects".to_string(), request.follow_redirects.to_string())); options.push(("http_errors".to_string(), "false".to_string())); format!( "request({}, {}, {});\necho $response->getStatusCode(), ' ', $response->getBody();", diff --git a/crates/engine/src/http/codegen/httpie.rs b/crates/engine/src/http/codegen/httpie.rs index ed1a49fa4..173d37c38 100644 --- a/crates/engine/src/http/codegen/httpie.rs +++ b/crates/engine/src/http/codegen/httpie.rs @@ -10,10 +10,7 @@ pub fn write(request: &CodeRequest, multiline: bool) -> String { arguments.push("--follow".to_string()); } if let Some((user, password)) = &request.basic { - arguments.push(format!( - "--auth {}", - shell_quoted(&format!("{user}:{password}")) - )); + arguments.push(format!("--auth {}", shell_quoted(&format!("{user}:{password}")))); } match &request.body { CodeBody::Form(_) => arguments.push("--form".to_string()), @@ -33,20 +30,13 @@ pub fn write(request: &CodeRequest, multiline: bool) -> String { CodeBody::Multipart(parts) => { for part in parts { let separator = if part.file { "@" } else { "=" }; - arguments.push(shell_quoted(&format!( - "{}{separator}{}", - part.name, part.value - ))); + arguments.push(shell_quoted(&format!("{}{separator}{}", part.name, part.value))); } } CodeBody::File(path) => arguments.push(format!("< {}", shell_quoted(path))), CodeBody::None | CodeBody::Text(_) => {} } - let first = format!( - "http {} {}", - request.method.as_str(), - shell_quoted(&request.url) - ); + let first = format!("http {} {}", request.method.as_str(), shell_quoted(&request.url)); shell_lines(&first, &arguments, multiline) } diff --git a/crates/engine/src/http/codegen/java.rs b/crates/engine/src/http/codegen/java.rs index 371f69dc9..1c24edb91 100644 --- a/crates/engine/src/http/codegen/java.rs +++ b/crates/engine/src/http/codegen/java.rs @@ -14,20 +14,14 @@ pub fn write(request: &CodeRequest) -> String { "java.net.http.HttpResponse", ]; let publisher = match &request.body { - CodeBody::None | CodeBody::Multipart(_) => { - "HttpRequest.BodyPublishers.noBody()".to_string() - } + CodeBody::None | CodeBody::Multipart(_) => "HttpRequest.BodyPublishers.noBody()".to_string(), CodeBody::Text(text) => format!("HttpRequest.BodyPublishers.ofString({})", quoted(text)), - CodeBody::Form(fields) => format!( - "HttpRequest.BodyPublishers.ofString({})", - quoted(&form_encoded(fields)) - ), + CodeBody::Form(fields) => { + format!("HttpRequest.BodyPublishers.ofString({})", quoted(&form_encoded(fields))) + } CodeBody::File(path) => { imports.push("java.nio.file.Path"); - format!( - "HttpRequest.BodyPublishers.ofFile(Path.of({}))", - quoted(path) - ) + format!("HttpRequest.BodyPublishers.ofFile(Path.of({}))", quoted(path)) } }; if request.basic.is_some() { @@ -35,34 +29,20 @@ pub fn write(request: &CodeRequest) -> String { } imports.sort_unstable(); - let mut lines: Vec = imports - .iter() - .map(|import| format!("import {import};")) - .collect(); + let mut lines: Vec = imports.iter().map(|import| format!("import {import};")).collect(); lines.push(String::new()); lines.push("public class Main {".to_string()); lines.push(" public static void main(String[] args) throws Exception {".to_string()); lines.push(" HttpClient client = HttpClient.newBuilder()".to_string()); lines.push(format!( " .followRedirects(HttpClient.Redirect.{})", - if request.follow_redirects { - "NORMAL" - } else { - "NEVER" - } + if request.follow_redirects { "NORMAL" } else { "NEVER" } )); lines.push(" .build();".to_string()); lines.push(" HttpRequest request = HttpRequest.newBuilder()".to_string()); - lines.push(format!( - " .uri(URI.create({}))", - quoted(&request.url) - )); + lines.push(format!(" .uri(URI.create({}))", quoted(&request.url))); for (name, value) in &request.headers { - lines.push(format!( - " .header({}, {})", - quoted(name), - quoted(value) - )); + lines.push(format!(" .header({}, {})", quoted(name), quoted(value))); } if let Some((user, password)) = &request.basic { lines.push(format!( @@ -70,18 +50,13 @@ pub fn write(request: &CodeRequest) -> String { quoted(&format!("{user}:{password}")) )); } - lines.push(format!( - " .method({}, {publisher})", - quoted(request.method.as_str()) - )); + lines.push(format!(" .method({}, {publisher})", quoted(request.method.as_str()))); lines.push(" .build();".to_string()); lines.push( " HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString());" .to_string(), ); - lines.push( - " System.out.println(response.statusCode() + \" \" + response.body());".to_string(), - ); + lines.push(" System.out.println(response.statusCode() + \" \" + response.body());".to_string()); lines.push(" }".to_string()); lines.push("}".to_string()); lines.join("\n") diff --git a/crates/engine/src/http/codegen/javascript.rs b/crates/engine/src/http/codegen/javascript.rs index ad1f35633..218f39f2a 100644 --- a/crates/engine/src/http/codegen/javascript.rs +++ b/crates/engine/src/http/codegen/javascript.rs @@ -8,10 +8,7 @@ use super::{CodeBody, CodeRequest}; #[must_use] pub fn string(text: &str) -> String { if text.contains('\n') { - let escaped = text - .replace('\\', "\\\\") - .replace('`', "\\`") - .replace("${", "\\${"); + let escaped = text.replace('\\', "\\\\").replace('`', "\\`").replace("${", "\\${"); return format!("`{escaped}`"); } let escaped = text @@ -30,11 +27,7 @@ pub fn key(name: &str) -> String { .next() .is_some_and(|first| first.is_ascii_alphabetic() || first == '_' || first == '$') && chars.all(|next| next.is_ascii_alphanumeric() || next == '_' || next == '$'); - if identifier { - name.to_string() - } else { - string(name) - } + if identifier { name.to_string() } else { string(name) } } /// `{ a: 'b', 'c-d': e }` laid out a key a line at `indent`, the values already written. @@ -62,10 +55,7 @@ pub fn headers(request: &CodeRequest) -> Vec<(String, String)> { if let Some((user, password)) = &request.basic { headers.push(( "Authorization".to_string(), - format!( - "`Basic ${{btoa({})}}`", - string(&format!("{user}:{password}")) - ), + format!("`Basic ${{btoa({})}}`", string(&format!("{user}:{password}"))), )); } headers @@ -104,11 +94,7 @@ pub fn form_data(body: &CodeBody) -> Vec { string(&file_name(&part.value)) )); } else { - lines.push(format!( - "form.append({}, {});", - string(&part.name), - string(&part.value) - )); + lines.push(format!("form.append({}, {});", string(&part.name), string(&part.value))); } } lines @@ -121,10 +107,8 @@ pub fn body(body: &CodeBody, indent: &str) -> Option { CodeBody::None => None, CodeBody::Text(text) => Some(string(text)), CodeBody::Form(fields) => { - let entries: Vec<(String, String)> = fields - .iter() - .map(|(name, value)| (name.clone(), string(value))) - .collect(); + let entries: Vec<(String, String)> = + fields.iter().map(|(name, value)| (name.clone(), string(value))).collect(); Some(format!("new URLSearchParams({})", object(&entries, indent))) } CodeBody::Multipart(_) => Some("form".to_string()), @@ -140,10 +124,7 @@ mod tests { fn a_string_is_quoted_for_a_line_and_a_template_for_several() { assert_eq!(string("O'Brien"), r"'O\'Brien'"); assert_eq!(string("a\\b"), r"'a\\b'"); - assert_eq!( - string("{\n \"a\": `${x}`\n}"), - "`{\n \"a\": \\`\\${x}\\`\n}`" - ); + assert_eq!(string("{\n \"a\": `${x}`\n}"), "`{\n \"a\": \\`\\${x}\\`\n}`"); } #[test] diff --git a/crates/engine/src/http/codegen/okhttp.rs b/crates/engine/src/http/codegen/okhttp.rs index 15f9757ee..df862b772 100644 --- a/crates/engine/src/http/codegen/okhttp.rs +++ b/crates/engine/src/http/codegen/okhttp.rs @@ -8,16 +8,10 @@ use super::{CodeBody, CodeRequest}; use crate::http::model::HttpMethod; /// The body as `.method` takes it, what builds it written into `prelude`. -fn body_of( - request: &CodeRequest, - imports: &mut BTreeSet<&'static str>, - prelude: &mut Vec, -) -> String { +fn body_of(request: &CodeRequest, imports: &mut BTreeSet<&'static str>, prelude: &mut Vec) -> String { let content_type = request.content_type().unwrap_or("application/octet-stream"); match &request.body { - CodeBody::None if matches!(request.method, HttpMethod::Get | HttpMethod::Head) => { - "null".to_string() - } + CodeBody::None if matches!(request.method, HttpMethod::Get | HttpMethod::Head) => "null".to_string(), CodeBody::None => { imports.insert("okhttp3.RequestBody.Companion.toRequestBody"); "ByteArray(0).toRequestBody()".to_string() @@ -25,11 +19,7 @@ fn body_of( CodeBody::Text(text) => { imports.insert("okhttp3.MediaType.Companion.toMediaType"); imports.insert("okhttp3.RequestBody.Companion.toRequestBody"); - format!( - "{}.toRequestBody({}.toMediaType())", - quoted(text), - quoted(content_type) - ) + format!("{}.toRequestBody({}.toMediaType())", quoted(text), quoted(content_type)) } CodeBody::Form(fields) => { imports.insert("okhttp3.FormBody"); @@ -69,36 +59,24 @@ fn body_of( imports.insert("java.io.File"); imports.insert("okhttp3.MediaType.Companion.toMediaType"); imports.insert("okhttp3.RequestBody.Companion.asRequestBody"); - format!( - "File({}).asRequestBody({}.toMediaType())", - quoted(path), - quoted(content_type) - ) + format!("File({}).asRequestBody({}.toMediaType())", quoted(path), quoted(content_type)) } } } #[must_use] pub fn write(request: &CodeRequest) -> String { - let mut imports: BTreeSet<&str> = ["okhttp3.OkHttpClient", "okhttp3.Request"] - .into_iter() - .collect(); + let mut imports: BTreeSet<&str> = ["okhttp3.OkHttpClient", "okhttp3.Request"].into_iter().collect(); let mut prelude = Vec::new(); let body = body_of(request, &mut imports, &mut prelude); if request.basic.is_some() { imports.insert("okhttp3.Credentials"); } - let mut lines: Vec = imports - .iter() - .map(|import| format!("import {import}")) - .collect(); + let mut lines: Vec = imports.iter().map(|import| format!("import {import}")).collect(); lines.push(String::new()); lines.push("val client = OkHttpClient.Builder()".to_string()); - lines.push(format!( - " .followRedirects({})", - request.follow_redirects - )); + lines.push(format!(" .followRedirects({})", request.follow_redirects)); lines.push(" .build()".to_string()); lines.extend(prelude); lines.push("val request = Request.Builder()".to_string()); @@ -118,10 +96,7 @@ pub fn write(request: &CodeRequest) -> String { quoted(password) )); } - lines.push(format!( - " .method({}, {body})", - quoted(request.method.as_str()) - )); + lines.push(format!(" .method({}, {body})", quoted(request.method.as_str()))); lines.push(" .build()".to_string()); lines.push("client.newCall(request).execute().use { response ->".to_string()); lines.push(" println(\"${response.code} ${response.body?.string()}\")".to_string()); diff --git a/crates/engine/src/http/codegen/powershell.rs b/crates/engine/src/http/codegen/powershell.rs index 588d25f43..706680be0 100644 --- a/crates/engine/src/http/codegen/powershell.rs +++ b/crates/engine/src/http/codegen/powershell.rs @@ -72,10 +72,8 @@ pub fn write(request: &CodeRequest, multiline: bool) -> String { } let mut lines = Vec::new(); - let mut parameters = vec![ - format!("-Uri {}", quoted(&request.url)), - format!("-Method {}", method(request.method)), - ]; + let mut parameters = + vec![format!("-Uri {}", quoted(&request.url)), format!("-Method {}", method(request.method))]; if !headers.is_empty() { lines.push(format!("$headers = {}", hashtable(&headers, multiline))); parameters.push("-Headers $headers".to_string()); @@ -92,10 +90,8 @@ pub fn write(request: &CodeRequest, multiline: bool) -> String { parameters.push("-Body $body".to_string()); } CodeBody::Form(fields) => { - let entries: Vec<(String, String)> = fields - .iter() - .map(|(name, value)| (name.clone(), quoted(value))) - .collect(); + let entries: Vec<(String, String)> = + fields.iter().map(|(name, value)| (name.clone(), quoted(value))).collect(); lines.push(format!("$body = {}", hashtable(&entries, multiline))); parameters.push("-Body $body".to_string()); } @@ -126,13 +122,7 @@ pub fn write(request: &CodeRequest, multiline: bool) -> String { let last = call.len() - 1; call.iter() .enumerate() - .map(|(at, line)| { - if at == last { - line.clone() - } else { - format!("{line} `") - } - }) + .map(|(at, line)| if at == last { line.clone() } else { format!("{line} `") }) .collect::>() .join("\n") } else { diff --git a/crates/engine/src/http/codegen/python.rs b/crates/engine/src/http/codegen/python.rs index 34ff83da2..48bcd2a7d 100644 --- a/crates/engine/src/http/codegen/python.rs +++ b/crates/engine/src/http/codegen/python.rs @@ -44,10 +44,8 @@ fn write(request: &CodeRequest, library: Library) -> String { CodeBody::None => {} CodeBody::Text(text) => arguments.push(format!("{raw}={}", quoted(text))), CodeBody::Form(fields) => { - let fields: Vec<(String, String)> = fields - .iter() - .map(|(name, value)| (name.clone(), quoted(value))) - .collect(); + let fields: Vec<(String, String)> = + fields.iter().map(|(name, value)| (name.clone(), quoted(value))).collect(); arguments.push(format!("data={}", dict(&fields))); } CodeBody::Multipart(parts) => { @@ -59,12 +57,7 @@ fn write(request: &CodeRequest, library: Library) -> String { let files: Vec<(String, String)> = parts .iter() .filter(|part| part.file) - .map(|part| { - ( - part.name.clone(), - format!("open({}, \"rb\")", quoted(&part.value)), - ) - }) + .map(|part| (part.name.clone(), format!("open({}, \"rb\")", quoted(&part.value)))) .collect(); if !texts.is_empty() { arguments.push(format!("data={}", dict(&texts))); @@ -77,19 +70,12 @@ fn write(request: &CodeRequest, library: Library) -> String { arguments.push(format!("{raw}=open({}, \"rb\")", quoted(path))); } } - let follow = if request.follow_redirects { - "True" - } else { - "False" - }; + let follow = if request.follow_redirects { "True" } else { "False" }; arguments.push(match library { Library::Requests => format!("allow_redirects={follow}"), Library::Httpx => format!("follow_redirects={follow}"), }); - let arguments: Vec = arguments - .into_iter() - .map(|argument| format!(" {argument},")) - .collect(); + let arguments: Vec = arguments.into_iter().map(|argument| format!(" {argument},")).collect(); format!( "import {name}\n\nresponse = {name}.request(\n{}\n)\nprint(response.status_code, response.text)", arguments.join("\n") diff --git a/crates/engine/src/http/codegen/req.rs b/crates/engine/src/http/codegen/req.rs index 330ee944d..c263636b8 100644 --- a/crates/engine/src/http/codegen/req.rs +++ b/crates/engine/src/http/codegen/req.rs @@ -28,19 +28,14 @@ pub fn write(request: &CodeRequest) -> String { options.push(format!("headers: {}", pairs(&headers))); } if let Some((user, password)) = &request.basic { - options.push(format!( - "auth: {{:basic, {}}}", - quoted(&format!("{user}:{password}")) - )); + options.push(format!("auth: {{:basic, {}}}", quoted(&format!("{user}:{password}")))); } match &request.body { CodeBody::None => {} CodeBody::Text(text) => options.push(format!("body: {}", quoted(text))), CodeBody::Form(fields) => { - let fields: Vec<(String, String)> = fields - .iter() - .map(|(name, value)| (name.clone(), quoted(value))) - .collect(); + let fields: Vec<(String, String)> = + fields.iter().map(|(name, value)| (name.clone(), quoted(value))).collect(); options.push(format!("form: {}", pairs(&fields))); } CodeBody::Multipart(parts) => { @@ -61,10 +56,7 @@ pub fn write(request: &CodeRequest) -> String { } options.push(format!("redirect: {}", request.follow_redirects)); options.push("retry: false".to_string()); - let options: Vec = options - .into_iter() - .map(|option| format!(" {option}")) - .collect(); + let options: Vec = options.into_iter().map(|option| format!(" {option}")).collect(); format!( "response =\n Req.request!(\n{}\n )\n\nIO.puts(\"#{{response.status}} #{{inspect(response.body)}}\")", options.join(",\n") diff --git a/crates/engine/src/http/codegen/reqwest.rs b/crates/engine/src/http/codegen/reqwest.rs index cfd2e7fcb..32720010f 100644 --- a/crates/engine/src/http/codegen/reqwest.rs +++ b/crates/engine/src/http/codegen/reqwest.rs @@ -40,17 +40,9 @@ pub fn write(request: &CodeRequest) -> String { for (at, part) in parts.iter().enumerate() { let end = if at == last { ";" } else { "" }; if part.file { - lines.push(format!( - " .file({}, {})?{end}", - quoted(&part.name), - quoted(&part.value) - )); + lines.push(format!(" .file({}, {})?{end}", quoted(&part.name), quoted(&part.value))); } else { - lines.push(format!( - " .text({}, {}){end}", - quoted(&part.name), - quoted(&part.value) - )); + lines.push(format!(" .text({}, {}){end}", quoted(&part.name), quoted(&part.value))); } } } @@ -61,18 +53,10 @@ pub fn write(request: &CodeRequest) -> String { quoted(&request.url) )); for (name, value) in &request.headers { - lines.push(format!( - " .header({}, {})", - quoted(name), - quoted(value) - )); + lines.push(format!(" .header({}, {})", quoted(name), quoted(value))); } if let Some((user, password)) = &request.basic { - lines.push(format!( - " .basic_auth({}, Some({}))", - quoted(user), - quoted(password) - )); + lines.push(format!(" .basic_auth({}, Some({}))", quoted(user), quoted(password))); } match &request.body { CodeBody::None => {} @@ -86,10 +70,7 @@ pub fn write(request: &CodeRequest) -> String { } CodeBody::Multipart(_) => lines.push(" .multipart(form)".to_string()), CodeBody::File(path) => { - lines.push(format!( - " .body(std::fs::File::open({})?)", - quoted(path) - )); + lines.push(format!(" .body(std::fs::File::open({})?)", quoted(path))); } } lines.push(" .send()?;".to_string()); diff --git a/crates/engine/src/http/codegen/ruby.rs b/crates/engine/src/http/codegen/ruby.rs index 0fa2cf3fb..7e6ad1ad0 100644 --- a/crates/engine/src/http/codegen/ruby.rs +++ b/crates/engine/src/http/codegen/ruby.rs @@ -30,11 +30,7 @@ pub fn write(request: &CodeRequest) -> String { lines.push(format!("request[{}] = {}", quoted(name), quoted(value))); } if let Some((user, password)) = &request.basic { - lines.push(format!( - "request.basic_auth({}, {})", - quoted(user), - quoted(password) - )); + lines.push(format!("request.basic_auth({}, {})", quoted(user), quoted(password))); } match &request.body { CodeBody::None => {} @@ -58,10 +54,7 @@ pub fn write(request: &CodeRequest) -> String { format!("[{}, {value}]", quoted(&part.name)) }) .collect(); - lines.push(format!( - "request.set_form([{}], 'multipart/form-data')", - pairs.join(", ") - )); + lines.push(format!("request.set_form([{}], 'multipart/form-data')", pairs.join(", "))); } CodeBody::File(path) => { lines.push(format!("request.body = File.binread({})", quoted(path))); diff --git a/crates/engine/src/http/codegen/source.rs b/crates/engine/src/http/codegen/source.rs index 8fbde7652..2e09913ca 100644 --- a/crates/engine/src/http/codegen/source.rs +++ b/crates/engine/src/http/codegen/source.rs @@ -43,13 +43,7 @@ pub fn single_quoted(text: &str) -> String { pub fn dart(text: &str) -> String { let inner = double_quoted(text); let inner = &inner[1..inner.len() - 1]; - format!( - "'{}'", - inner - .replace("\\\"", "\"") - .replace('\'', "\\'") - .replace('$', "\\$") - ) + format!("'{}'", inner.replace("\\\"", "\"").replace('\'', "\\'").replace('$', "\\$")) } /// The last part of a path: what a file part is sent as. diff --git a/crates/engine/src/http/codegen/swift.rs b/crates/engine/src/http/codegen/swift.rs index 897f45a36..4214a1168 100644 --- a/crates/engine/src/http/codegen/swift.rs +++ b/crates/engine/src/http/codegen/swift.rs @@ -10,18 +10,11 @@ pub fn write(request: &CodeRequest) -> String { let mut lines = vec![ "import Foundation".to_string(), String::new(), - format!( - "var request = URLRequest(url: URL(string: {})!)", - quoted(&request.url) - ), + format!("var request = URLRequest(url: URL(string: {})!)", quoted(&request.url)), format!("request.httpMethod = {}", quoted(request.method.as_str())), ]; for (name, value) in &request.headers { - lines.push(format!( - "request.setValue({}, forHTTPHeaderField: {})", - quoted(value), - quoted(name) - )); + lines.push(format!("request.setValue({}, forHTTPHeaderField: {})", quoted(value), quoted(name))); } if let Some((user, password)) = &request.basic { lines.push(format!( @@ -34,19 +27,15 @@ pub fn write(request: &CodeRequest) -> String { CodeBody::Text(text) => { lines.push(format!("request.httpBody = Data({}.utf8)", quoted(text))); } - CodeBody::Form(fields) => lines.push(format!( - "request.httpBody = Data({}.utf8)", - quoted(&form_encoded(fields)) - )), - CodeBody::File(path) => lines.push(format!( - "request.httpBody = try Data(contentsOf: URL(fileURLWithPath: {}))", - quoted(path) - )), + CodeBody::Form(fields) => { + lines.push(format!("request.httpBody = Data({}.utf8)", quoted(&form_encoded(fields)))); + } + CodeBody::File(path) => lines + .push(format!("request.httpBody = try Data(contentsOf: URL(fileURLWithPath: {}))", quoted(path))), } lines.push("let (data, response) = try await URLSession.shared.data(for: request)".to_string()); lines.push( - "print((response as! HTTPURLResponse).statusCode, String(decoding: data, as: UTF8.self))" - .to_string(), + "print((response as! HTTPURLResponse).statusCode, String(decoding: data, as: UTF8.self))".to_string(), ); lines.join("\n") } diff --git a/crates/engine/src/http/codegen/wget.rs b/crates/engine/src/http/codegen/wget.rs index d924bae8c..50a0dec12 100644 --- a/crates/engine/src/http/codegen/wget.rs +++ b/crates/engine/src/http/codegen/wget.rs @@ -11,10 +11,7 @@ pub fn write(request: &CodeRequest, multiline: bool) -> String { arguments.push("--max-redirect 0".to_string()); } for (name, value) in &request.headers { - arguments.push(format!( - "--header {}", - shell_quoted(&format!("{name}: {value}")) - )); + arguments.push(format!("--header {}", shell_quoted(&format!("{name}: {value}")))); } if let Some((user, password)) = &request.basic { // Without it, wget sends its credentials only once a server has asked for them. @@ -25,10 +22,7 @@ pub fn write(request: &CodeRequest, multiline: bool) -> String { match &request.body { CodeBody::Text(text) => arguments.push(format!("--body-data {}", shell_quoted(text))), CodeBody::Form(fields) => { - arguments.push(format!( - "--body-data {}", - shell_quoted(&form_encoded(fields)) - )); + arguments.push(format!("--body-data {}", shell_quoted(&form_encoded(fields)))); } CodeBody::File(path) => arguments.push(format!("--body-file {}", shell_quoted(path))), CodeBody::None | CodeBody::Multipart(_) => {} diff --git a/crates/engine/src/http/collection_run.rs b/crates/engine/src/http/collection_run.rs index 37233a9ae..efa7ab81a 100644 --- a/crates/engine/src/http/collection_run.rs +++ b/crates/engine/src/http/collection_run.rs @@ -28,15 +28,7 @@ pub(super) async fn run_step( step: RunStep<'_>, overlay: &mut Vec, ) -> Option<(runner::RunResult, Option)> { - let RunStep { - run, - iteration, - iterations, - index, - steps, - placed, - row, - } = step; + let RunStep { run, iteration, iterations, index, steps, placed, row } = step; say_run( engine, &run.id, @@ -88,13 +80,7 @@ pub(super) async fn run_step( if matches!(&answer, Err(error) if error.code == crate::error::ErrorCode::HttpCancelled) { return None; } - let result = runner::result_of( - iteration, - &request, - placed.path.clone(), - answer, - run.keep_responses, - ); + let result = runner::result_of(iteration, &request, placed.path.clone(), answer, run.keep_responses); Some((result, next)) } @@ -112,8 +98,5 @@ pub(super) async fn wait(runs: &runner::Runs, id: &str, millis: u32) -> bool { } pub(super) fn say_run(engine: &Engine, id: &str, step: runner::RunStep) { - engine.emit(EngineEvent::Run(runner::RunEvent { - id: id.to_string(), - step, - })); + engine.emit(EngineEvent::Run(runner::RunEvent { id: id.to_string(), step })); } diff --git a/crates/engine/src/http/console.rs b/crates/engine/src/http/console.rs index eef316d7e..dca07a344 100644 --- a/crates/engine/src/http/console.rs +++ b/crates/engine/src/http/console.rs @@ -28,14 +28,8 @@ pub struct ConsoleOrigin { impl ConsoleOrigin { #[must_use] pub fn of(id: Option<&str>, scripts: &[Script]) -> Option { - let script = scripts - .iter() - .find(|script| Some(script.id.as_str()) == id)?; - Some(Self { - kind: script.kind, - level: script.level, - name: script.name.clone(), - }) + let script = scripts.iter().find(|script| Some(script.id.as_str()) == id)?; + Some(Self { kind: script.kind, level: script.level, name: script.name.clone() }) } } @@ -126,18 +120,9 @@ pub fn secret_segments(text: &str) -> Vec<(String, bool)> { /// A request as the console shows it: each secret in force written as its name, an auth or a /// cookie header masked as the history masks it. #[must_use] -pub fn out( - exchange: &Exchange, - secrets: &[(String, String)], - by: Option, -) -> ConsoleLine { +pub fn out(exchange: &Exchange, secrets: &[(String, String)], by: Option) -> ConsoleLine { let shown = history::shown(exchange, secrets); - ConsoleLine::Out { - method: shown.method.to_string(), - url: shown.url, - headers: shown.headers, - by, - } + ConsoleLine::Out { method: shown.method.to_string(), url: shown.url, headers: shown.headers, by } } #[must_use] @@ -153,11 +138,7 @@ pub fn answered(response: &SentResponse, by: Option) -> ConsoleLi #[must_use] pub fn failed(error: AppError, by: Option) -> ConsoleLine { - ConsoleLine::Failed { - code: error.code, - params: error.params, - by, - } + ConsoleLine::Failed { code: error.code, params: error.params, by } } /// What a phase leaves in the console, in the order it happened: its logs and its sends, then @@ -205,12 +186,7 @@ pub fn phase( .map(|test| (now, tested(test, scripts, secrets))), ); if let Some(failure) = &outcome.failure { - lines.push(( - now, - ConsoleLine::Stopped { - stop: ScriptStop::of(failure, scripts), - }, - )); + lines.push((now, ConsoleLine::Stopped { stop: ScriptStop::of(failure, scripts) })); } lines } @@ -234,13 +210,7 @@ mod tests { use crate::http::send::{SendError, SentBody}; fn script(id: &str, kind: ScriptKind, level: ScriptLevel, name: &str) -> Script { - Script { - id: id.to_string(), - kind, - level, - name: name.to_string(), - ..Script::default() - } + Script { id: id.to_string(), kind, level, name: name.to_string(), ..Script::default() } } fn scripts() -> [Script; 2] { @@ -251,28 +221,15 @@ mod tests { } fn origin(script: &Script) -> ConsoleOrigin { - ConsoleOrigin { - kind: script.kind, - level: script.level, - name: script.name.clone(), - } + ConsoleOrigin { kind: script.kind, level: script.level, name: script.name.clone() } } fn header(key: &str, value: &str) -> KeyValue { - KeyValue { - key: key.to_string(), - value: value.to_string(), - ..KeyValue::default() - } + KeyValue { key: key.to_string(), value: value.to_string(), ..KeyValue::default() } } fn exchange(url: &str, headers: Vec) -> Exchange { - Exchange { - method: HttpMethod::Delete, - url: url.to_string(), - headers, - body: SentBody::None, - } + Exchange { method: HttpMethod::Delete, url: url.to_string(), headers, body: SentBody::None } } fn secrets() -> [(String, String); 1] { @@ -312,24 +269,14 @@ mod tests { #[test] fn a_request_leaves_with_its_secrets_written_as_their_names_and_its_auth_masked() { - let headers = vec![ - header("Authorization", "Bearer s3cr3t"), - header("X-Trace", "s3cr3t-1"), - ]; + let headers = vec![header("Authorization", "Bearer s3cr3t"), header("X-Trace", "s3cr3t-1")]; - let line = out( - &exchange("https://shop.test/me?key=s3cr3t", headers), - &secrets(), - None, - ); + let line = out(&exchange("https://shop.test/me?key=s3cr3t", headers), &secrets(), None); let expected = ConsoleLine::Out { method: "DELETE".to_string(), url: "https://shop.test/me?key={{token}}".to_string(), - headers: vec![ - header("Authorization", "Bearer ••••••••"), - header("X-Trace", "{{token}}-1"), - ], + headers: vec![header("Authorization", "Bearer ••••••••"), header("X-Trace", "{{token}}-1")], by: None, }; assert_eq!(line, expected); @@ -353,10 +300,7 @@ mod tests { by: Some(origin(&scripts()[0])), }; assert_eq!(answered(&response, Some(origin(&scripts()[0]))), expected); - assert_eq!( - lines(Vec::new(), vec![sent(Ok(response))], &Outcome::default())[1], - expected - ); + assert_eq!(lines(Vec::new(), vec![sent(Ok(response))], &Outcome::default())[1], expected); } /// The order it happened in: a script's send around what it logged meanwhile. @@ -364,11 +308,7 @@ mod tests { fn a_phase_says_its_logs_and_its_sends_in_the_order_they_came() { let logs = vec![log("s3cr3t between", "s1", 2), log("last", "gone", 4)]; - let said = lines( - logs, - vec![sent(Err(SendError::Refused("down".to_string())))], - &Outcome::default(), - ); + let said = lines(logs, vec![sent(Err(SendError::Refused("down".to_string())))], &Outcome::default()); let by = Some(origin(&scripts()[0])); let expected = [ @@ -378,21 +318,9 @@ mod tests { headers: Vec::new(), by: by.clone(), }, - ConsoleLine::Log { - level: LogLevel::Warn, - text: "{{token}} between".to_string(), - by: by.clone(), - }, - ConsoleLine::Failed { - code: ErrorCode::HttpRefused, - params: BTreeMap::new(), - by, - }, - ConsoleLine::Log { - level: LogLevel::Warn, - text: "last".to_string(), - by: None, - }, + ConsoleLine::Log { level: LogLevel::Warn, text: "{{token}} between".to_string(), by: by.clone() }, + ConsoleLine::Failed { code: ErrorCode::HttpRefused, params: BTreeMap::new(), by }, + ConsoleLine::Log { level: LogLevel::Warn, text: "last".to_string(), by: None }, ]; assert_eq!(said, expected); } @@ -437,14 +365,8 @@ mod tests { }; let outcome = Outcome { tests: vec![ - TestResult { - passed: true, - ..test("passes") - }, - TestResult { - skipped: true, - ..test("later") - }, + TestResult { passed: true, ..test("passes") }, + TestResult { skipped: true, ..test("later") }, failed, ], failure: Some(failure.clone()), @@ -462,12 +384,7 @@ mod tests { }; assert_eq!(said.len(), 3); assert_eq!(said[1], expected); - assert_eq!( - said[2], - ConsoleLine::Stopped { - stop: ScriptStop::of(&failure, &scripts()) - } - ); + assert_eq!(said[2], ConsoleLine::Stopped { stop: ScriptStop::of(&failure, &scripts()) }); } #[test] @@ -476,27 +393,13 @@ mod tests { ("", vec![]), ("plain", vec![("plain", false)]), ("{{token}}", vec![("{{token}}", true)]), - ( - "a {{b}} c {{d}}", - vec![ - ("a ", false), - ("{{b}}", true), - (" c ", false), - ("{{d}}", true), - ], - ), + ("a {{b}} c {{d}}", vec![("a ", false), ("{{b}}", true), (" c ", false), ("{{d}}", true)]), ("open {{b", vec![("open {{b", false)]), ("{{}} x", vec![("{{", false), ("}} x", false)]), - ( - "{{a{{b}}", - vec![("{{", false), ("a", false), ("{{b}}", true)], - ), + ("{{a{{b}}", vec![("{{", false), ("a", false), ("{{b}}", true)]), ] { let cut = secret_segments(text); - let cut: Vec<(&str, bool)> = cut - .iter() - .map(|(part, secret)| (part.as_str(), *secret)) - .collect(); + let cut: Vec<(&str, bool)> = cut.iter().map(|(part, secret)| (part.as_str(), *secret)).collect(); assert_eq!(cut, parts, "{text}"); } } diff --git a/crates/engine/src/http/cookies.rs b/crates/engine/src/http/cookies.rs index 1e1a5072e..ff912c431 100644 --- a/crates/engine/src/http/cookies.rs +++ b/crates/engine/src/http/cookies.rs @@ -59,25 +59,18 @@ fn is_public_suffix(domain: &str) -> bool { /// between —, read token by token: the first time, day, month and year found, a two-digit year /// taken to 1970–2069. `None` for a date that does not read: the cookie lasts the session. fn cookie_date(text: &str) -> Option> { - const MONTHS: [&str; 12] = [ - "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec", - ]; + const MONTHS: [&str; 12] = + ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"]; let delimiter = |character: char| matches!(character, '\t' | ' '..='/' | ';'..='@' | '['..='`' | '{'..='~'); let leading_digits = |token: &str, at_most: usize| -> Option { let digits: String = token.chars().take_while(char::is_ascii_digit).collect(); - (1..=at_most) - .contains(&digits.len()) - .then(|| digits.parse().ok()) - .flatten() + (1..=at_most).contains(&digits.len()).then(|| digits.parse().ok()).flatten() }; let (mut time, mut day, mut month, mut year) = (None, None, None, None); for token in text.split(delimiter).filter(|token| !token.is_empty()) { if time.is_none() { - let parts: Vec> = token - .splitn(3, ':') - .map(|part| leading_digits(part, 2)) - .collect(); + let parts: Vec> = token.splitn(3, ':').map(|part| leading_digits(part, 2)).collect(); if let [Some(hour), Some(minute), Some(second)] = parts[..] { time = Some((hour, minute, second)); continue; @@ -122,16 +115,12 @@ fn cookie_date(text: &str) -> Option> { } fn domain_matches(host: &str, domain: &str) -> bool { - host == domain - || host - .strip_suffix(domain) - .is_some_and(|rest| rest.ends_with('.')) + host == domain || host.strip_suffix(domain).is_some_and(|rest| rest.ends_with('.')) } fn path_matches(path: &str, cookie: &str) -> bool { path == cookie - || (path.starts_with(cookie) - && (cookie.ends_with('/') || path[cookie.len()..].starts_with('/'))) + || (path.starts_with(cookie) && (cookie.ends_with('/') || path[cookie.len()..].starts_with('/'))) } /// The directory of the request's path: `/api/users` → `/api`. @@ -168,9 +157,7 @@ fn parse(line: &str, url: &Url, now: DateTime) -> Option { for attribute in parts { let (key, value) = attribute .split_once('=') - .map_or((attribute.trim(), ""), |(key, value)| { - (key.trim(), value.trim()) - }); + .map_or((attribute.trim(), ""), |(key, value)| (key.trim(), value.trim())); match key.to_ascii_lowercase().as_str() { "domain" if !value.is_empty() => { let domain = value.trim_start_matches('.').to_ascii_lowercase(); @@ -205,11 +192,7 @@ fn parse(line: &str, url: &Url, now: DateTime) -> Option { if let Some(seconds) = max_age { cookie.expires = Some(now + TimeDelta::seconds(seconds.max(0))); } - Some(if cookie.expired(now) { - Change::Remove(cookie) - } else { - Change::Set(cookie) - }) + Some(if cookie.expired(now) { Change::Remove(cookie) } else { Change::Set(cookie) }) } fn is_secure(url: &Url) -> bool { @@ -238,16 +221,10 @@ pub fn received(headers: &[KeyValue], url: &Url, now: DateTime) -> Vec, changes: &[Change]) { for change in changes { let (Change::Set(cookie) | Change::Remove(cookie)) = change; - let replaced = jar - .iter() - .find(|known| known.same_as(cookie)) - .and_then(|known| known.created); + let replaced = jar.iter().find(|known| known.same_as(cookie)).and_then(|known| known.created); jar.retain(|known| !known.same_as(cookie)); if let Change::Set(cookie) = change { - jar.push(JarCookie { - created: replaced.or(cookie.created), - ..cookie.clone() - }); + jar.push(JarCookie { created: replaced.or(cookie.created), ..cookie.clone() }); } } } @@ -259,19 +236,15 @@ pub fn matching<'a>(jar: &'a [JarCookie], url: &Url, now: DateTime) -> Vec< return Vec::new(); }; let secure = is_secure(url); - let mut sent: Vec<&JarCookie> = jar - .iter() - .filter(|cookie| !cookie.expired(now)) - .filter(|cookie| { - if cookie.host_only { - host == cookie.domain - } else { - domain_matches(&host, &cookie.domain) - } - }) - .filter(|cookie| path_matches(url.path(), &cookie.path)) - .filter(|cookie| secure || !cookie.secure) - .collect(); + let mut sent: Vec<&JarCookie> = + jar.iter() + .filter(|cookie| !cookie.expired(now)) + .filter(|cookie| { + if cookie.host_only { host == cookie.domain } else { domain_matches(&host, &cookie.domain) } + }) + .filter(|cookie| path_matches(url.path(), &cookie.path)) + .filter(|cookie| secure || !cookie.secure) + .collect(); sent.sort_by_key(|cookie| (std::cmp::Reverse(cookie.path.len()), cookie.created)); sent } @@ -300,11 +273,7 @@ mod tests { } fn set_cookie(value: &str) -> KeyValue { - KeyValue { - key: "Set-Cookie".to_string(), - value: value.to_string(), - ..KeyValue::default() - } + KeyValue { key: "Set-Cookie".to_string(), value: value.to_string(), ..KeyValue::default() } } /// The one change a `Set-Cookie` line makes, answered by `at`. @@ -347,14 +316,8 @@ mod tests { fn a_cookie_without_attributes_is_the_host_s_for_its_directory() { let cookie = set("sid=\"abc=1\"", "https://API.Shop.test/v1/users?x=1"); - assert_eq!( - (cookie.name.as_str(), cookie.value.as_str()), - ("sid", "abc=1") - ); - assert_eq!( - (cookie.domain.as_str(), cookie.host_only), - ("api.shop.test", true) - ); + assert_eq!((cookie.name.as_str(), cookie.value.as_str()), ("sid", "abc=1")); + assert_eq!((cookie.domain.as_str(), cookie.host_only), ("api.shop.test", true)); assert_eq!((cookie.path.as_str(), cookie.expires), ("/v1", None)); assert_eq!(set("a=1", "https://shop.test/users").path, "/"); assert_eq!(set("a=1", "https://shop.test").path, "/"); @@ -366,15 +329,8 @@ mod tests { fn an_answer_s_cookies_are_read_in_their_order() { let headers = [ set_cookie("first=1; HttpOnly; SameSite=Strict"), - KeyValue { - key: "Content-Type".to_string(), - value: "a=b".to_string(), - ..KeyValue::default() - }, - KeyValue { - key: "set-cookie".to_string(), - ..set_cookie("second=2; SameSite=") - }, + KeyValue { key: "Content-Type".to_string(), value: "a=b".to_string(), ..KeyValue::default() }, + KeyValue { key: "set-cookie".to_string(), ..set_cookie("second=2; SameSite=") }, set_cookie("no equals sign"), set_cookie(" =nameless"), ]; @@ -395,10 +351,7 @@ mod tests { (Some(now()), Some(now() + TimeDelta::microseconds(1))) ); assert!(read[0].http_only && !read[1].http_only); - assert_eq!( - (read[0].same_site.as_deref(), read[1].same_site.as_deref()), - (Some("Strict"), None) - ); + assert_eq!((read[0].same_site.as_deref(), read[1].same_site.as_deref()), (Some("Strict"), None)); } /// A server sets a cookie for itself or a domain above it, never for another, an address, @@ -410,19 +363,10 @@ mod tests { let empty = set("a=1; Domain=", "https://api.shop.test/"); let registered = set("a=1; Domain=exemple.co.uk", "https://api.exemple.co.uk/"); - assert_eq!( - (above.domain.as_str(), above.host_only), - ("shop.test", false) - ); - assert_eq!( - (itself.domain.as_str(), itself.host_only), - ("api.shop.test", true) - ); + assert_eq!((above.domain.as_str(), above.host_only), ("shop.test", false)); + assert_eq!((itself.domain.as_str(), itself.host_only), ("api.shop.test", true)); assert!(empty.host_only); - assert_eq!( - (registered.domain.as_str(), registered.host_only), - ("exemple.co.uk", false) - ); + assert_eq!((registered.domain.as_str(), registered.host_only), ("exemple.co.uk", false)); for (line, at) in [ ("a=1; Domain=other.test", "https://shop.test/"), ("a=1; Domain=api.shop.test", "https://shop.test/"), @@ -461,40 +405,21 @@ mod tests { let in_a_minute = Some(now() + TimeDelta::seconds(60)); assert_eq!( - set( - "a=1; Max-Age=60; Expires=Wed, 21 Oct 2026 07:28:00 GMT", - "https://shop.test/" - ) - .expires, + set("a=1; Max-Age=60; Expires=Wed, 21 Oct 2026 07:28:00 GMT", "https://shop.test/").expires, in_a_minute ); assert_eq!( - set( - "a=1; Expires=Wed, 21 Oct 2026 07:28:00 GMT; Max-Age=60", - "https://shop.test/" - ) - .expires, + set("a=1; Expires=Wed, 21 Oct 2026 07:28:00 GMT; Max-Age=60", "https://shop.test/").expires, in_a_minute ); assert_eq!(set("a=1; Max-Age=soon", "https://shop.test/").expires, None); let october = crate::db::iso8601::parse("2026-10-21T07:28:00.000Z").ok(); assert_eq!( - set( - "a=1; Expires=Wed, 21 Oct 2026 07:28:00 GMT; Expires=garbage", - "https://shop.test/" - ) - .expires, + set("a=1; Expires=Wed, 21 Oct 2026 07:28:00 GMT; Expires=garbage", "https://shop.test/").expires, october ); - for line in [ - "a=1; Max-Age=0", - "a=1; Max-Age=-5", - "a=1; Expires=Thu, 01 Jan 2026 00:00:00 GMT", - ] { - assert!( - matches!(one(line, "https://shop.test/"), Some(Change::Remove(_))), - "{line}" - ); + for line in ["a=1; Max-Age=0", "a=1; Max-Age=-5", "a=1; Expires=Thu, 01 Jan 2026 00:00:00 GMT"] { + assert!(matches!(one(line, "https://shop.test/"), Some(Change::Remove(_))), "{line}"); } } @@ -509,10 +434,7 @@ mod tests { ("Wednesday, 21-Oct-26 07:28:00 GMT", october), ("Wed Oct 21 07:28:00 2026", october), ("21 october 2026 7:28:0", october), - ( - "Sun, 01-Jan-69 00:00:01 GMT", - crate::db::iso8601::parse("2069-01-01T00:00:01.000Z").ok(), - ), + ("Sun, 01-Jan-69 00:00:01 GMT", crate::db::iso8601::parse("2069-01-01T00:00:01.000Z").ok()), ("mér., 21 oct. 2026 07:28:00", october), ("Wed, 21 Oct 2026 25:00:00 GMT", None), ("Wed, 31 Feb 2026 07:28:00 GMT", None), @@ -528,10 +450,7 @@ mod tests { assert_eq!(read.expires, expected, "{date}"); } assert!(matches!( - one( - "a=1; Expires=Thu, 01-Jan-70 00:00:01 GMT", - "https://shop.test/" - ), + one("a=1; Expires=Thu, 01-Jan-70 00:00:01 GMT", "https://shop.test/"), Some(Change::Remove(_)) )); } @@ -540,41 +459,21 @@ mod tests { /// a removal takes it away; another path is another cookie. #[test] fn a_change_replaces_or_removes_the_same_cookie() { - let mut jar = vec![ - cookie("a", "shop.test", "/"), - cookie("a", "shop.test", "/api"), - ]; + let mut jar = vec![cookie("a", "shop.test", "/"), cookie("a", "shop.test", "/api")]; let newer = JarCookie { value: "new".to_string(), created: Some(now() + TimeDelta::hours(1)), ..cookie("a", "shop.test", "/") }; - apply( - &mut jar, - &[ - Change::Set(newer), - Change::Set(cookie("b", "shop.test", "/")), - ], - ); + apply(&mut jar, &[Change::Set(newer), Change::Set(cookie("b", "shop.test", "/"))]); assert_eq!(jar.len(), 3); - let replaced = jar - .iter() - .find(|known| known.path == "/" && known.name == "a") - .unwrap(); - assert_eq!( - (replaced.value.as_str(), replaced.created), - ("new", Some(now())) - ); + let replaced = jar.iter().find(|known| known.path == "/" && known.name == "a").unwrap(); + assert_eq!((replaced.value.as_str(), replaced.created), ("new", Some(now()))); - apply( - &mut jar, - &[Change::Remove(cookie("a", "shop.test", "/api"))], - ); - let left: Vec<(&str, &str)> = jar - .iter() - .map(|known| (known.name.as_str(), known.path.as_str())) - .collect(); + apply(&mut jar, &[Change::Remove(cookie("a", "shop.test", "/api"))]); + let left: Vec<(&str, &str)> = + jar.iter().map(|known| (known.name.as_str(), known.path.as_str())).collect(); assert_eq!(left, [("a", "/"), ("b", "/")]); } @@ -583,10 +482,7 @@ mod tests { #[test] fn a_cookie_is_sent_to_its_host_or_below_its_domain() { let jar = [ - JarCookie { - host_only: true, - ..cookie("host", "shop.test", "/") - }, + JarCookie { host_only: true, ..cookie("host", "shop.test", "/") }, cookie("domain", "shop.test", "/"), ]; @@ -599,10 +495,7 @@ mod tests { /// A path and what lies under it, never a name that merely starts like it. #[test] fn a_cookie_is_sent_under_its_path() { - let jar = [ - cookie("api", "shop.test", "/api"), - cookie("slash", "shop.test", "/v1/"), - ]; + let jar = [cookie("api", "shop.test", "/api"), cookie("slash", "shop.test", "/v1/")]; assert_eq!(sent(&jar, "https://shop.test/api"), ["api"]); assert_eq!(sent(&jar, "https://shop.test/api/users"), ["api"]); @@ -615,18 +508,9 @@ mod tests { #[test] fn an_expired_or_secure_cookie_is_held_back() { let jar = [ - JarCookie { - expires: Some(now()), - ..cookie("expired", "shop.test", "/") - }, - JarCookie { - expires: Some(now() + TimeDelta::seconds(1)), - ..cookie("later", "shop.test", "/") - }, - JarCookie { - secure: true, - ..cookie("secure", "shop.test", "/") - }, + JarCookie { expires: Some(now()), ..cookie("expired", "shop.test", "/") }, + JarCookie { expires: Some(now() + TimeDelta::seconds(1)), ..cookie("later", "shop.test", "/") }, + JarCookie { secure: true, ..cookie("secure", "shop.test", "/") }, ]; assert_eq!(sent(&jar, "http://shop.test/"), ["later"]); @@ -639,10 +523,7 @@ mod tests { #[test] fn the_cookie_header_sends_the_longest_paths_first_then_the_oldest() { let jar = [ - JarCookie { - created: Some(now() + TimeDelta::seconds(2)), - ..cookie("young", "shop.test", "/") - }, + JarCookie { created: Some(now() + TimeDelta::seconds(2)), ..cookie("young", "shop.test", "/") }, cookie("old", "shop.test", "/"), cookie("deep", "shop.test", "/api"), ]; diff --git a/crates/engine/src/http/cookies/store.rs b/crates/engine/src/http/cookies/store.rs index 04cad0e50..3092c38e2 100644 --- a/crates/engine/src/http/cookies/store.rs +++ b/crates/engine/src/http/cookies/store.rs @@ -24,18 +24,12 @@ pub struct CookieDomain { } fn open(vault: &Vault, id: String, sealed: &str) -> Result { - let cookie = - serde_json::from_str(&vault.open(sealed)?).map_err(|_| StorageError::CorruptRow { - id: id.clone(), - field: "cookie", - })?; + let cookie = serde_json::from_str(&vault.open(sealed)?) + .map_err(|_| StorageError::CorruptRow { id: id.clone(), field: "cookie" })?; Ok(StoredCookie { id, cookie }) } -fn read( - connection: &mut SqliteConnection, - vault: &Vault, -) -> Result, StorageError> { +fn read(connection: &mut SqliteConnection, vault: &Vault) -> Result, StorageError> { http_cookies::table .select((http_cookies::id, http_cookies::cookie)) .load::<(String, String)>(connection)? @@ -56,11 +50,7 @@ pub fn jar(connection: &mut Library, now: DateTime) -> Result, -) -> Result<(), StorageError> { +pub fn apply(connection: &mut Library, changes: &[Change], now: DateTime) -> Result<(), StorageError> { if changes.is_empty() { return Ok(()); } @@ -76,10 +66,7 @@ pub fn apply( known.retain(|stored| !stored.cookie.same_as(cookie)); if let Change::Set(cookie) = change { // As the jar held in memory does: a replaced cookie keeps its place. - let cookie = &JarCookie { - created: replaced.or(cookie.created), - ..cookie.clone() - }; + let cookie = &JarCookie { created: replaced.or(cookie.created), ..cookie.clone() }; let id = Uuid::new_v4().to_string(); let json = serde_json::to_string(cookie) .map_err(|error| StorageError::Vault(format!("unwritable cookie: {error}")))?; @@ -90,16 +77,11 @@ pub fn apply( http_cookies::cookie.eq(vault.seal(&json)?), )) .execute(connection)?; - known.push(StoredCookie { - id, - cookie: cookie.clone(), - }); + known.push(StoredCookie { id, cookie: cookie.clone() }); } } - diesel::delete( - http_cookies::table.filter(http_cookies::expires_at.le(iso8601::format(now))), - ) - .execute(connection)?; + diesel::delete(http_cookies::table.filter(http_cookies::expires_at.le(iso8601::format(now)))) + .execute(connection)?; Ok(()) }) } @@ -119,10 +101,7 @@ pub fn by_domain(connection: &mut Library) -> Result, StorageE for stored in cookies { match domains.last_mut() { Some(last) if last.domain == stored.cookie.domain => last.cookies.push(stored), - _ => domains.push(CookieDomain { - domain: stored.cookie.domain.clone(), - cookies: vec![stored], - }), + _ => domains.push(CookieDomain { domain: stored.cookie.domain.clone(), cookies: vec![stored] }), } } Ok(domains) @@ -134,9 +113,7 @@ fn removed(count: usize) -> u32 { pub fn delete(connection: &mut Library, id: &str) -> Result { let (connection, _) = connection.split(); - Ok(removed( - diesel::delete(http_cookies::table.find(id)).execute(connection)?, - )) + Ok(removed(diesel::delete(http_cookies::table.find(id)).execute(connection)?)) } /// A domain's cookies, answering how many went. @@ -147,10 +124,7 @@ pub fn delete_domain(connection: &mut Library, domain: &str) -> Result Result { @@ -161,9 +135,7 @@ pub fn count(connection: &mut Library) -> Result { pub fn clear(connection: &mut Library) -> Result { let (connection, _) = connection.split(); - Ok(removed( - diesel::delete(http_cookies::table).execute(connection)?, - )) + Ok(removed(diesel::delete(http_cookies::table).execute(connection)?)) } #[cfg(test)] @@ -191,10 +163,7 @@ mod tests { } fn lasting(name: &str, seconds: i64) -> JarCookie { - JarCookie { - expires: Some(now() + TimeDelta::seconds(seconds)), - ..cookie(name, "shop.test", "/") - } + JarCookie { expires: Some(now() + TimeDelta::seconds(seconds)), ..cookie(name, "shop.test", "/") } } fn names(jar: &[JarCookie]) -> Vec<&str> { @@ -227,33 +196,20 @@ mod tests { }; let later = now() + TimeDelta::seconds(10); - apply( - &mut library, - &[ - Change::Set(newer), - Change::Remove(cookie("b", "shop.test", "/")), - ], - later, - ) - .unwrap(); + apply(&mut library, &[Change::Set(newer), Change::Remove(cookie("b", "shop.test", "/"))], later) + .unwrap(); let jar = jar(&mut library, now()).unwrap(); assert_eq!(names(&jar), ["a"]); - assert_eq!( - (jar[0].value.as_str(), jar[0].created), - ("new", Some(now())) - ); + assert_eq!((jar[0].value.as_str(), jar[0].created), ("new", Some(now()))); assert_eq!(count(&mut library).unwrap(), 1); } /// What has expired is never sent, even before a write sweeps it. #[test] fn the_jar_read_leaves_out_what_has_expired() { - let mut library = library_with(&[ - lasting("expired", 0), - lasting("later", 1), - cookie("session", "shop.test", "/"), - ]); + let mut library = + library_with(&[lasting("expired", 0), lasting("later", 1), cookie("session", "shop.test", "/")]); let jar = jar(&mut library, now()).unwrap(); @@ -295,10 +251,7 @@ mod tests { .collect(); assert_eq!( shown, - [ - ("a.test", vec![("a", "/"), ("b", "/"), ("b", "/x")]), - ("b.test", vec![("a", "/")]), - ] + [("a.test", vec![("a", "/"), ("b", "/"), ("b", "/x")]), ("b.test", vec![("a", "/")]),] ); } @@ -331,13 +284,7 @@ mod tests { .execute(library.db()) .unwrap(); - assert!(matches!( - jar(&mut library, now()), - Err(StorageError::CorruptRow { - field: "cookie", - .. - }) - )); + assert!(matches!(jar(&mut library, now()), Err(StorageError::CorruptRow { field: "cookie", .. }))); } /// Sealed whole: neither a name nor a value, nor its domain, is in the database in the clear. @@ -345,10 +292,8 @@ mod tests { fn a_cookie_is_sealed_whole() { let mut library = library_with(&[cookie("session_id", "bank.test", "/")]); - let stored: Vec = http_cookies::table - .select(http_cookies::cookie) - .load(library.db()) - .unwrap(); + let stored: Vec = + http_cookies::table.select(http_cookies::cookie).load(library.db()).unwrap(); assert_eq!(stored.len(), 1); for clear in ["session_id", "bank.test"] { diff --git a/crates/engine/src/http/environments.rs b/crates/engine/src/http/environments.rs index c1f3fa143..a3137932c 100644 --- a/crates/engine/src/http/environments.rs +++ b/crates/engine/src/http/environments.rs @@ -191,25 +191,15 @@ mod tests { use super::*; fn variable(name: &str, value: &str) -> Variable { - Variable { - name: name.to_string(), - value: value.to_string(), - ..Variable::default() - } + Variable { name: name.to_string(), value: value.to_string(), ..Variable::default() } } fn number(name: &str, value: &str) -> Variable { - Variable { - kind: VariableKind::Number, - ..variable(name, value) - } + Variable { kind: VariableKind::Number, ..variable(name, value) } } fn secret(name: &str) -> Variable { - Variable { - kind: VariableKind::Secret, - ..variable(name, "s") - } + Variable { kind: VariableKind::Secret, ..variable(name, "s") } } /// What a `{{…}}` can hold: letters, digits, `_` and `-`, as a snippet's field. @@ -242,10 +232,7 @@ mod tests { number("many", "many"), number("endless", "inf"), variable(" host ", "again"), - Variable { - enabled: false, - ..variable("bad name", "x") - }, + Variable { enabled: false, ..variable("bad name", "x") }, variable(" ", "unnamed"), ]; @@ -269,20 +256,9 @@ mod tests { #[test] fn a_set_counts_its_named_variables_and_its_secrets() { - let counts = variable_counts(&[ - variable("a", "1"), - secret("b"), - secret(" "), - variable("", "x"), - ]); + let counts = variable_counts(&[variable("a", "1"), secret("b"), secret(" "), variable("", "x")]); - assert_eq!( - counts, - VariableCounts { - count: 2, - secrets: 1 - } - ); + assert_eq!(counts, VariableCounts { count: 2, secrets: 1 }); } /// What reads without changing anything goes unasked; a socket asks before it opens, @@ -300,10 +276,7 @@ mod tests { !method.changes_nothing(), "{method:?}" ); - assert!( - asks_before_sending(RequestKind::Websocket, method), - "{method:?}" - ); + assert!(asks_before_sending(RequestKind::Websocket, method), "{method:?}"); } } @@ -316,10 +289,7 @@ mod tests { protected: false, variables: vec![variable("host", "staging")], }; - let patch = EnvironmentPatch { - protected: Some(true), - ..EnvironmentPatch::default() - }; + let patch = EnvironmentPatch { protected: Some(true), ..EnvironmentPatch::default() }; let full = EnvironmentPatch { name: Some("ignored".to_string()), colour: Some(FolderColour::Red), @@ -330,13 +300,7 @@ mod tests { let protected = document.clone().patched(&patch, None); let renamed = document.clone().patched(&full, Some("Production")); - assert_eq!( - protected, - EnvironmentDocument { - protected: true, - ..document - } - ); + assert_eq!(protected, EnvironmentDocument { protected: true, ..document }); assert_eq!( renamed, EnvironmentDocument { diff --git a/crates/engine/src/http/environments/store.rs b/crates/engine/src/http/environments/store.rs index cb23f82ea..84cdcc63b 100644 --- a/crates/engine/src/http/environments/store.rs +++ b/crates/engine/src/http/environments/store.rs @@ -26,10 +26,8 @@ struct EnvironmentRow { impl EnvironmentRow { fn document(&self, vault: &Vault) -> Result { - serde_json::from_str(&vault.open(&self.document)?).map_err(|_| StorageError::CorruptRow { - id: self.id.clone(), - field: "document", - }) + serde_json::from_str(&vault.open(&self.document)?) + .map_err(|_| StorageError::CorruptRow { id: self.id.clone(), field: "document" }) } fn open(self, vault: &Vault) -> Result { @@ -58,10 +56,7 @@ fn rows(connection: &mut SqliteConnection) -> Result, Storag .load(connection)?) } -fn environments( - connection: &mut SqliteConnection, - vault: &Vault, -) -> Result, StorageError> { +fn environments(connection: &mut SqliteConnection, vault: &Vault) -> Result, StorageError> { rows(connection)? .into_iter() .filter(|row| row.kind == ENVIRONMENT) @@ -80,11 +75,7 @@ fn find(connection: &mut SqliteConnection, id: &str) -> Result, -) -> Result<(), StorageError> { +fn refuse_taken(held: &[Environment], name: &str, except_id: Option<&str>) -> Result<(), StorageError> { let pairs = held .iter() .map(|environment| (environment.id.as_str(), environment.name.as_str())); @@ -105,10 +96,7 @@ pub fn list(connection: &mut Library) -> Result environments.push(row.open(vault)?); } } - Ok(HttpEnvironments { - globals, - environments, - }) + Ok(HttpEnvironments { globals, environments }) } /// One environment, for the send that resolves from it. @@ -138,11 +126,7 @@ fn insert( } /// Last, in the next of the five colours: two made one after the other differ. -pub fn create( - connection: &mut Library, - name: &str, - now: DateTime, -) -> Result { +pub fn create(connection: &mut Library, name: &str, now: DateTime) -> Result { connection.transaction(|connection, vault| { let held = environments(connection, vault)?; refuse_taken(&held, name, None)?; @@ -189,15 +173,11 @@ pub fn save_globals( connection.transaction(|connection, vault| { let document = seal( vault, - &EnvironmentDocument { - variables: variables.to_vec(), - ..EnvironmentDocument::default() - }, + &EnvironmentDocument { variables: variables.to_vec(), ..EnvironmentDocument::default() }, )?; - let changed = - diesel::update(http_environments::table.filter(http_environments::kind.eq(GLOBALS))) - .set(http_environments::document.eq(&document)) - .execute(connection)?; + let changed = diesel::update(http_environments::table.filter(http_environments::kind.eq(GLOBALS))) + .set(http_environments::document.eq(&document)) + .execute(connection)?; if changed == 0 { diesel::insert_into(http_environments::table) .values(( @@ -224,10 +204,7 @@ pub fn duplicate( connection.transaction(|connection, vault| { let original = find(connection, id)?; refuse_taken(&environments(connection, vault)?, name, None)?; - let document = EnvironmentDocument { - name: name.to_string(), - ..original.document(vault)? - }; + let document = EnvironmentDocument { name: name.to_string(), ..original.document(vault)? }; diesel::update( http_environments::table .filter(http_environments::kind.eq(ENVIRONMENT)) diff --git a/crates/engine/src/http/error.rs b/crates/engine/src/http/error.rs index 0386ec8a4..a1565f128 100644 --- a/crates/engine/src/http/error.rs +++ b/crates/engine/src/http/error.rs @@ -42,31 +42,22 @@ impl From for AppError { .and("unit", unit) .set_by(&limit.set_by) } - SendError::TooManyRedirects(limit) => { - Self::new(ErrorCode::HttpTooManyRedirects, detail) - .and("count", &limit.value.to_string()) - .set_by(&limit.set_by) - } + SendError::TooManyRedirects(limit) => Self::new(ErrorCode::HttpTooManyRedirects, detail) + .and("count", &limit.value.to_string()) + .set_by(&limit.set_by), SendError::FileUnreadable(path) => { Self::with(ErrorCode::HttpFileUnreadable, detail, "path", &path) } - SendError::FileTooLarge(path) => { - Self::with(ErrorCode::HttpFileTooLarge, detail, "path", &path) - .and("limit", &crate::http::send::SENT_FILE_MEGABYTES.to_string()) - } + SendError::FileTooLarge(path) => Self::with(ErrorCode::HttpFileTooLarge, detail, "path", &path) + .and("limit", &crate::http::send::SENT_FILE_MEGABYTES.to_string()), SendError::Cancelled => Self::new(ErrorCode::HttpCancelled, detail), SendError::Fell => Self::new(ErrorCode::HttpFell, detail), SendError::GraphqlVariables(_) => Self::new(ErrorCode::HttpGraphqlVariables, detail), - SendError::Handshake(status) => Self::with( - ErrorCode::HttpWebsocketRefused, - detail, - "status", - &status.to_string(), - ), - // The cause's own words: « Erreur réseau » alone tells nothing. - SendError::Network(cause) => { - Self::with(ErrorCode::HttpNetwork, detail, "cause", &cause) + SendError::Handshake(status) => { + Self::with(ErrorCode::HttpWebsocketRefused, detail, "status", &status.to_string()) } + // The cause's own words: « Erreur réseau » alone tells nothing. + SendError::Network(cause) => Self::with(ErrorCode::HttpNetwork, detail, "cause", &cause), SendError::SocketScheme { twin } => { let refused = Self::new(ErrorCode::HttpWebsocketScheme, detail); match twin { @@ -74,11 +65,7 @@ impl From for AppError { None => refused, } } - SendError::Header { - name, - fault, - set_by, - } => { + SendError::Header { name, fault, set_by } => { let code = match fault { HeaderFault::Name => ErrorCode::HttpHeaderName, HeaderFault::Value => ErrorCode::HttpHeaderValue, @@ -107,12 +94,8 @@ impl From for AppError { match error { ScriptError::Stopped(stop) => { - let mut refused = Self::with( - ErrorCode::HttpScript, - detail, - "failure", - &stop.kind.to_string(), - ); + let mut refused = + Self::with(ErrorCode::HttpScript, detail, "failure", &stop.kind.to_string()); for (key, value) in [ ("level", stop.level.map(|level| level.to_string())), ("name", stop.name), @@ -131,19 +114,11 @@ impl From for AppError { } ScriptError::Skipped => Self::new(ErrorCode::HttpScriptSkipped, detail), ScriptError::File(path) => Self::with(ErrorCode::HttpScriptFile, detail, "path", &path), - ScriptError::Method(method) => { - Self::with(ErrorCode::HttpScriptMethod, detail, "method", &method) + ScriptError::Method(method) => Self::with(ErrorCode::HttpScriptMethod, detail, "method", &method), + ScriptError::Protected { method, environment } => { + Self::with(ErrorCode::HttpScriptProtected, detail, "method", &method.to_string()) + .and("environment", &environment) } - ScriptError::Protected { - method, - environment, - } => Self::with( - ErrorCode::HttpScriptProtected, - detail, - "method", - &method.to_string(), - ) - .and("environment", &environment), } } } diff --git a/crates/engine/src/http/extract.rs b/crates/engine/src/http/extract.rs index f81814295..2031d7f6c 100644 --- a/crates/engine/src/http/extract.rs +++ b/crates/engine/src/http/extract.rs @@ -105,11 +105,7 @@ pub fn variable_name_of(path: &str) -> String { name.push(c); } } - if name.starts_with(|c: char| c.is_ascii_alphabetic()) { - name - } else { - format!("value{name}") - } + if name.starts_with(|c: char| c.is_ascii_alphabetic()) { name } else { format!("value{name}") } } /// What a key reads as when it holds something to keep out of sight. diff --git a/crates/engine/src/http/flight.rs b/crates/engine/src/http/flight.rs index 30e1ef108..0736b22d3 100644 --- a/crates/engine/src/http/flight.rs +++ b/crates/engine/src/http/flight.rs @@ -8,16 +8,15 @@ use chrono::Utc; use super::scripts::around::{self, Around}; use super::scripts::model::{ - Extracted, FailureKind, Job, LayerScope, LogEntry, Outcome, Phase, RequestFault, Script, - ScriptError, ScriptFailure, ScriptInfo, ScriptLayer, ScriptRequest, ScriptStop, VariableWrite, - WriteScope, + Extracted, FailureKind, Job, LayerScope, LogEntry, Outcome, Phase, RequestFault, Script, ScriptError, + ScriptFailure, ScriptInfo, ScriptLayer, ScriptRequest, ScriptStop, VariableWrite, WriteScope, }; use super::scripts::network::{self, Network}; use super::scripts::process::ScriptProcess; use super::scripts::session::Session; use super::{ - console, cookies, environments, extract, history, inherited_of, layers_for, model, runner, - send, settings, store, transport, variables, + console, cookies, environments, extract, history, inherited_of, layers_for, model, runner, send, + settings, store, transport, variables, }; use crate::db::{self, lock, lock_library}; use crate::error::AppError; @@ -93,10 +92,7 @@ impl Flight { confirmed: false, files: Vec::new(), collection_id: None, - info: ScriptInfo { - iteration_count: 1, - ..ScriptInfo::default() - }, + info: ScriptInfo { iteration_count: 1, ..ScriptInfo::default() }, by: environments::FilledBy::default(), heard: (Vec::new(), Vec::new()), record: true, @@ -110,10 +106,7 @@ impl Flight { } } - pub(super) async fn send( - &mut self, - request: send::SendRequest, - ) -> Result { + pub(super) async fn send(&mut self, request: send::SendRequest) -> Result { let send::SendRequest { id, kind, @@ -127,20 +120,8 @@ impl Flight { confirmed, files, } = request; - let Prepared { - inherited, - mut layers, - environment, - jar, - library, - } = prepare( - &self.engine, - &document, - collection_id.clone(), - folder_id, - environment_id, - ) - .await?; + let Prepared { inherited, mut layers, environment, jar, library } = + prepare(&self.engine, &document, collection_id.clone(), folder_id, environment_id).await?; let around = Around::of(&document.scripts, &name, &inherited); self.jar = jar; self.library = library; @@ -153,12 +134,7 @@ impl Flight { self.layered(&mut layers); // What the request reads as the user wrote it: a file the scripts add waits for a yes. let own = (!around.before.is_empty()).then(|| files_read(&document, &inherited, &layers)); - let mut going = Going { - kind, - method, - document, - layers, - }; + let mut going = Going { kind, method, document, layers }; if !around.before.is_empty() { self.before(&around.before, &mut going).await?; } @@ -215,10 +191,8 @@ impl Flight { fn named(&mut self, name: &str, request_id: Option<&str>) { self.info.request_name = name.to_string(); self.info.request_id = request_id.map(str::to_string); - self.by = environments::FilledBy { - request_id: request_id.map(str::to_string), - name: name.to_string(), - }; + self.by = + environments::FilledBy { request_id: request_id.map(str::to_string), name: name.to_string() }; } /// What a run lays over the levels read: what its scripts wrote, kept for it alone, and @@ -231,12 +205,10 @@ impl Flight { } fn sent_environment(&self) -> Option { - self.environment - .as_ref() - .map(|environment| history::SentEnvironment { - name: environment.name.clone(), - colour: environment.colour, - }) + self.environment.as_ref().map(|environment| history::SentEnvironment { + name: environment.name.clone(), + colour: environment.colour, + }) } /// The request sent, the lock free; `Err` alone when « Annuler » stopped it, a failure to @@ -246,11 +218,7 @@ impl Flight { id: &str, outgoing: send::Outgoing, ) -> Result, AppError> { - let (answer, cookies_set) = self - .engine - .sending - .run(&self.engine.runtime, id, outgoing) - .await; + let (answer, cookies_set) = self.engine.sending.run(&self.engine.runtime, id, outgoing).await; if matches!(answer, Err(send::SendError::Cancelled)) { return Err(send::SendError::Cancelled.into()); } @@ -260,11 +228,9 @@ impl Flight { Utc::now(), match &answer { Ok(response) => console::answered(response, None), - Err(error) => console::ConsoleLine::Failed { - code: error.code, - params: error.params.clone(), - by: None, - }, + Err(error) => { + console::ConsoleLine::Failed { code: error.code, params: error.params.clone(), by: None } + } }, ); Ok(answer) @@ -287,18 +253,11 @@ impl Flight { let finished = outcome.is_some(); if let Some(outcome) = outcome { let extractions = std::mem::take(&mut going.document.extractions); - response.scripts.extracted = self - .extract(&extractions, response, &mut going.layers) - .await; + response.scripts.extracted = self.extract(&extractions, response, &mut going.layers).await; // Said once the extractions ran: a value one makes a secret is hidden in the logs. self.report(&answered, &outcome, &going.layers); self.follow(&outcome); - for missed in response - .scripts - .extracted - .iter() - .filter(|extracted| !extracted.found) - { + for missed in response.scripts.extracted.iter().filter(|extracted| !extracted.found) { self.say( Utc::now(), console::ConsoleLine::Missed { @@ -323,10 +282,7 @@ impl Flight { request: ScriptRequest::of(going.kind, going.method, &going.document), response: None, layers: self.script_layers(going), - environment: self - .environment - .as_ref() - .map(|environment| environment.name.clone()), + environment: self.environment.as_ref().map(|environment| environment.name.clone()), cookies: network::cookies_for(self.jar().as_deref(), url), info: self.info.clone(), } @@ -337,11 +293,7 @@ impl Flight { if !self.data.is_empty() { layers.insert( 0, - ScriptLayer { - scope: LayerScope::Data, - from: String::new(), - values: self.data.clone(), - }, + ScriptLayer { scope: LayerScope::Data, from: String::new(), values: self.data.clone() }, ); } layers @@ -355,10 +307,7 @@ impl Flight { self.write(&outcome.writes, &mut going.layers).await; self.report(scripts, &outcome, &going.layers); self.follow(&outcome); - let refused = self - .session - .as_mut() - .and_then(|session| session.network.refused_file.take()); + let refused = self.session.as_mut().and_then(|session| session.network.refused_file.take()); if let Some(path) = refused { return Err(ScriptError::File(path).into()); } @@ -386,9 +335,7 @@ impl Flight { .into()); } if !outcome.locals.is_empty() { - going - .layers - .insert(0, around::locals_layer(&outcome.locals)); + going.layers.insert(0, around::locals_layer(&outcome.locals)); } Ok(()) } @@ -408,10 +355,7 @@ impl Flight { let outcome = self.run(job).await.ok()?; self.write(&outcome.writes, &mut going.layers).await; response.scripts.tests.clone_from(&outcome.tests); - response.scripts.failure = outcome - .failure - .as_ref() - .map(|failure| ScriptStop::of(failure, scripts)); + response.scripts.failure = outcome.failure.as_ref().map(|failure| ScriptStop::of(failure, scripts)); Some(outcome) } @@ -426,10 +370,7 @@ impl Flight { self.transport, self.jar.take(), self.confirmed - || !self - .environment - .as_ref() - .is_some_and(|environment| environment.protected), + || !self.environment.as_ref().is_some_and(|environment| environment.protected), ); network.files.clone_from(&self.files); Session::new(host, network) @@ -451,10 +392,7 @@ impl Flight { let outcome = match ran { Ok((mut session, outcome)) => { self.changes.append(&mut session.network.changes); - self.heard = ( - std::mem::take(&mut session.logs), - std::mem::take(&mut session.network.sent), - ); + self.heard = (std::mem::take(&mut session.logs), std::mem::take(&mut session.network.sent)); self.session = Some(session); outcome } @@ -475,11 +413,7 @@ impl Flight { response: &send::SentResponse, layers: &mut [variables::VariableLayer], ) -> Vec { - let scope = if self.environment.is_some() { - WriteScope::Environment - } else { - WriteScope::Globals - }; + let scope = if self.environment.is_some() { WriteScope::Environment } else { WriteScope::Globals }; let mut writes = Vec::new(); let extracted = extractions .iter() @@ -516,11 +450,7 @@ impl Flight { /// What the send did to the jar, for the scripts after it to read. fn received(&mut self, changes: Vec) { - if let Some(jar) = self - .session - .as_mut() - .and_then(|session| session.network.jar.as_mut()) - { + if let Some(jar) = self.session.as_mut().and_then(|session| session.network.jar.as_mut()) { cookies::apply(jar, &changes); } self.changes.extend(changes); @@ -550,12 +480,7 @@ impl Flight { /// What the last phase logged and sent, the tests that failed and what stopped it, each /// secret in force — those the phase wrote included — written as its name. - fn report( - &mut self, - scripts: &[Script], - outcome: &Outcome, - layers: &[variables::VariableLayer], - ) { + fn report(&mut self, scripts: &[Script], outcome: &Outcome, layers: &[variables::VariableLayer]) { let (logs, sends) = std::mem::take(&mut self.heard); let secrets = variables::Resolver::new(layers).secrets(); for (at, line) in console::phase(logs, sends, outcome, scripts, &secrets) { @@ -574,10 +499,7 @@ impl Flight { return; } let writes = writes.to_vec(); - let environment_id = self - .environment - .as_ref() - .map(|environment| environment.id.clone()); + let environment_id = self.environment.as_ref().map(|environment| environment.id.clone()); let collection_id = self.collection_id.clone(); let by = self.by.clone(); let library = self.library; @@ -607,13 +529,7 @@ impl Flight { /// The history and the jar, written under the lock again, and never at the answer's expense. pub(super) async fn keep(self) { - let Self { - engine, - library, - sent, - changes, - .. - } = self; + let Self { engine, library, sent, changes, .. } = self; if sent.is_none() && changes.is_empty() { return; } @@ -626,23 +542,14 @@ impl Flight { }; if let Some(sent) = &sent { let (summary, record) = history::record_of(sent); - history::store::record( - &mut connection, - sent.request_id.as_deref(), - &summary, - &record, - now, - )?; + history::store::record(&mut connection, sent.request_id.as_deref(), &summary, &record, now)?; } cookies::store::apply(&mut connection, &changes, now)?; Ok(()) }) .await; if let Err(error) = kept { - log::warn!( - "A send's history or cookies were not kept: {}", - error.for_log() - ); + log::warn!("A send's history or cookies were not kept: {}", error.for_log()); engine.emit(EngineEvent::SendNotKept); } } @@ -678,11 +585,7 @@ async fn prepare( db::run(Arc::clone(engine), move |engine| { let db = &engine.db; let mut connection = lock(db)?; - let inherited = inherited_of( - &mut connection, - collection_id.as_deref(), - folder_id.as_deref(), - )?; + let inherited = inherited_of(&mut connection, collection_id.as_deref(), folder_id.as_deref())?; let layers = layers_for(&mut connection, &own, &inherited, environment_id.as_deref())?; let environment = environment_id .as_deref() @@ -695,13 +598,7 @@ async fn prepare( } else { None }; - Ok(Prepared { - inherited, - layers, - environment, - jar, - library: connection.number(), - }) + Ok(Prepared { inherited, layers, environment, jar, library: connection.number() }) }) .await } @@ -734,27 +631,17 @@ fn keep_writes( } if wrote_to(WriteScope::Globals) { let globals = environments::store::list(connection)?.globals; - let globals = around::written( - &globals, - around::writes_to(writes, WriteScope::Globals), - Some(by), - ); + let globals = around::written(&globals, around::writes_to(writes, WriteScope::Globals), Some(by)); environments::store::save_globals(connection, &globals, Utc::now())?; wrote = true; } if let Some(id) = collection_id && wrote_to(WriteScope::Collection) { - let item = model::HttpItem { - kind: model::HttpItemKind::Collection, - id: id.to_string(), - }; + let item = model::HttpItem { kind: model::HttpItemKind::Collection, id: id.to_string() }; let mut held = store::settings(connection, &item)?; - held.variables = around::written( - &held.variables, - around::writes_to(writes, WriteScope::Collection), - Some(by), - ); + held.variables = + around::written(&held.variables, around::writes_to(writes, WriteScope::Collection), Some(by)); store::save_settings(connection, &item, &held)?; wrote = true; } diff --git a/crates/engine/src/http/graphql.rs b/crates/engine/src/http/graphql.rs index 840a66d12..6ab6f41b1 100644 --- a/crates/engine/src/http/graphql.rs +++ b/crates/engine/src/http/graphql.rs @@ -117,8 +117,7 @@ impl Reader<'_> { } fn word(&mut self) -> String { - std::iter::from_fn(|| self.next_if(|next| next.is_ascii_alphanumeric() || next == '_')) - .collect() + std::iter::from_fn(|| self.next_if(|next| next.is_ascii_alphanumeric() || next == '_')).collect() } fn skip_spaces(&mut self) { @@ -164,11 +163,7 @@ impl Reader<'_> { /// One pass over a query, past its strings and comments: its operations with what each /// declares, and the first brace, parenthesis or string that does not pair. fn scan(query: &str) -> Scanned { - let mut reader = Reader { - chars: query.chars().peekable(), - line: 1, - column: 1, - }; + let mut reader = Reader { chars: query.chars().peekable(), line: 1, column: 1 }; let mut scanned = Scanned::default(); // What is open, and where it was opened. let mut open: Vec<(char, u32, u32)> = Vec::new(); @@ -177,11 +172,7 @@ fn scan(query: &str) -> Scanned { // The depth at which the operation being read declares its variables. let mut declaring: Option = None; let fault = |scanned: &mut Scanned, fault, line, column| { - scanned.problem.get_or_insert(QueryProblem { - fault, - line, - column, - }); + scanned.problem.get_or_insert(QueryProblem { fault, line, column }); }; while let Some((read, line, column)) = reader.next() { @@ -209,11 +200,8 @@ fn scan(query: &str) -> Scanned { if open.last().is_some_and(|(opened, ..)| *opened == pair) { open.pop(); } else { - let stray = if read == '}' { - QueryFault::StrayBrace - } else { - QueryFault::StrayParenthesis - }; + let stray = + if read == '}' { QueryFault::StrayBrace } else { QueryFault::StrayParenthesis }; fault(&mut scanned, stray, line, column); } if declaring.is_some_and(|depth| open.len() < depth) { @@ -223,10 +211,7 @@ fn scan(query: &str) -> Scanned { '$' if declaring == Some(open.len()) => { let name = reader.word(); if let (Some(operation), false) = (scanned.operations.last_mut(), name.is_empty()) { - operation.variables.push(Variable { - name, - has_default: false, - }); + operation.variables.push(Variable { name, has_default: false }); } } '=' if declaring == Some(open.len()) => { @@ -259,11 +244,8 @@ fn scan(query: &str) -> Scanned { } // Left open at the end: the innermost, the one nearest to where the typing stopped. if let Some((opened, line, column)) = open.last().copied() { - let unclosed = if opened == '{' { - QueryFault::UnclosedBrace - } else { - QueryFault::UnclosedParenthesis - }; + let unclosed = + if opened == '{' { QueryFault::UnclosedBrace } else { QueryFault::UnclosedParenthesis }; fault(&mut scanned, unclosed, line, column); } scanned @@ -284,11 +266,7 @@ fn sent<'a>(operations: &'a [Operation], document: &GraphqlDocument) -> Option<& .operation_name .as_deref() .filter(|name| !name.is_empty()) - .and_then(|name| { - operations - .iter() - .find(|operation| operation.name.as_deref() == Some(name)) - }) + .and_then(|name| operations.iter().find(|operation| operation.name.as_deref() == Some(name))) .or_else(|| operations.first()) } @@ -306,10 +284,8 @@ fn given(variables: &str) -> Option> { pub fn describe(document: &GraphqlDocument) -> GraphqlAnswer { let scanned = scan(&document.query); let (mut missing, mut unknown) = (Vec::new(), Vec::new()); - if let (Some(operation), Some(given)) = ( - sent(&scanned.operations, document), - given(&document.variables), - ) { + if let (Some(operation), Some(given)) = (sent(&scanned.operations, document), given(&document.variables)) + { missing = operation .variables .iter() @@ -318,20 +294,11 @@ pub fn describe(document: &GraphqlDocument) -> GraphqlAnswer { .collect(); unknown = given .into_iter() - .filter(|key| { - !operation - .variables - .iter() - .any(|variable| &variable.name == key) - }) + .filter(|key| !operation.variables.iter().any(|variable| &variable.name == key)) .collect(); } GraphqlAnswer { - operations: scanned - .operations - .into_iter() - .filter_map(|operation| operation.name) - .collect(), + operations: scanned.operations.into_iter().filter_map(|operation| operation.name).collect(), variables_problem: if document.variables.trim().is_empty() { None } else { @@ -388,11 +355,7 @@ pub(crate) fn body(document: &GraphqlDocument, variables: Option<&str>) -> Strin body.push_str(",\"variables\":"); body.push_str(variables); } - if let Some(name) = document - .operation_name - .as_deref() - .filter(|name| !name.is_empty()) - { + if let Some(name) = document.operation_name.as_deref().filter(|name| !name.is_empty()) { body.push_str(",\"operationName\":"); body.push_str("ed(name)); } @@ -513,23 +476,14 @@ mod tests { fn a_sign_the_query_leaves_unpaired_is_said_where_it_stands() { for (query, expected) in [ ("{ a { b }", Some((QueryFault::UnclosedBrace, 1, 1))), - ( - "query Q {\n a(x: 1 {\n}", - Some((QueryFault::UnclosedParenthesis, 2, 4)), - ), + ("query Q {\n a(x: 1 {\n}", Some((QueryFault::UnclosedParenthesis, 2, 4))), ("{ a(x: \"open) }", Some((QueryFault::UnclosedString, 1, 8))), ("{ a }\n}", Some((QueryFault::StrayBrace, 2, 1))), ("{ a(x: 1}) }", Some((QueryFault::StrayBrace, 1, 9))), ("{ a ) }", Some((QueryFault::StrayParenthesis, 1, 5))), ("{ a(x: \"\"\"one\ntwo \\\"\"\" three\"\"\") }", None), - ( - "{ a(x: \"\"\"never closed) }", - Some((QueryFault::UnclosedString, 1, 8)), - ), - ( - "{ a(x: \"quote \\\" inside\") } # } stray in a comment", - None, - ), + ("{ a(x: \"\"\"never closed) }", Some((QueryFault::UnclosedString, 1, 8))), + ("{ a(x: \"quote \\\" inside\") } # } stray in a comment", None), ("{ a(x: \"\") }", None), ] { assert_eq!(problem(query), expected, "{query:?}"); @@ -540,18 +494,14 @@ mod tests { /// keys given that it does not declare. #[test] fn the_variables_say_what_the_operation_lacks_and_what_it_does_not_take() { - let query = - "query Orders($first: Int = 10, $after: String, $status: Status!) { orders { id } }"; + let query = "query Orders($first: Int = 10, $after: String, $status: Status!) { orders { id } }"; let answer = describe(&document(query, r#"{"status": "PAID", "extra": 1}"#, None)); assert_eq!(answer.operations, ["Orders"]); assert_eq!(answer.missing, ["after"]); assert_eq!(answer.unknown, ["extra"]); - assert_eq!( - (answer.variables_problem, answer.query_problem), - (None, None) - ); + assert_eq!((answer.variables_problem, answer.query_problem), (None, None)); } /// The operation named, or the first as the server takes it; a variable used in a selection @@ -584,10 +534,7 @@ mod tests { assert!(broken.variables_problem.is_some()); assert!(broken.missing.is_empty() && array.missing.is_empty()); assert_eq!(array.variables_problem, None); - assert_eq!( - (empty.variables_problem, empty.missing), - (None, vec!["id".to_string()]) - ); + assert_eq!((empty.variables_problem, empty.missing), (None, vec!["id".to_string()])); } /// A `null` for each value lacking, written at the end of the object as typed — nothing @@ -596,19 +543,12 @@ mod tests { fn the_values_lacking_are_added_as_null_at_the_end_of_the_object() { let query = "query Q($a: Int, $b: String, $c: Int = 1) { x }"; - let typed = with_missing(&document( - query, - "{\n \"big\": 12345678901234567890\n}", - None, - )); + let typed = with_missing(&document(query, "{\n \"big\": 12345678901234567890\n}", None)); let blank = with_missing(&document(query, "", None)); let empty = with_missing(&document(query, " { } ", None)); let whole = with_missing(&document(query, "{\"a\": 1, \"b\": \"x\"}", None)); - assert_eq!( - typed, - "{\n \"big\": 12345678901234567890,\n \"a\": null,\n \"b\": null\n}" - ); + assert_eq!(typed, "{\n \"big\": 12345678901234567890,\n \"a\": null,\n \"b\": null\n}"); assert_eq!(blank, "{\n \"a\": null,\n \"b\": null\n}"); assert_eq!(empty, blank); assert_eq!(whole, "{\"a\": 1, \"b\": \"x\"}"); @@ -618,10 +558,7 @@ mod tests { /// refused. #[test] fn the_variables_sent_are_the_object_as_typed() { - assert_eq!( - variables(&document("", " {\"n\": 1.10} ", None)), - Ok(Some("{\"n\": 1.10}")) - ); + assert_eq!(variables(&document("", " {\"n\": 1.10} ", None)), Ok(Some("{\"n\": 1.10}"))); assert_eq!(variables(&document("", " ", None)), Ok(None)); assert!(variables(&document("", "[1]", None)).is_err()); assert!(variables(&document("", "{\"a\":", None)).is_err()); @@ -656,16 +593,8 @@ mod tests { path: Some("orders[0].total".to_string()), location: Some("3:5".to_string()), }, - GraphqlError { - message: "bare".to_string(), - path: Some("[0]".to_string()), - location: None, - }, - GraphqlError { - message: String::new(), - path: None, - location: None, - }, + GraphqlError { message: "bare".to_string(), path: Some("[0]".to_string()), location: None }, + GraphqlError { message: String::new(), path: None, location: None }, ] ); assert_eq!(null_data.data, None); diff --git a/crates/engine/src/http/history.rs b/crates/engine/src/http/history.rs index b5200029c..962ec7240 100644 --- a/crates/engine/src/http/history.rs +++ b/crates/engine/src/http/history.rs @@ -91,9 +91,7 @@ pub fn url_parts(url: &str) -> (String, String) { let end = rest.find(['/', '?', '#']).unwrap_or(rest.len()); let (authority, tail) = rest.split_at(end); // Its credentials are nothing a list has to show. - let host = authority - .rsplit_once('@') - .map_or(authority, |(_, host)| host); + let host = authority.rsplit_once('@').map_or(authority, |(_, host)| host); (host.to_string(), tail.to_string()) } @@ -129,10 +127,7 @@ pub struct Sent { fn is_secret(name: &str, secrets: &[String]) -> bool { let name = name.trim().to_ascii_lowercase(); - matches!( - name.as_str(), - "authorization" | "proxy-authorization" | "cookie" - ) || secrets.contains(&name) + matches!(name.as_str(), "authorization" | "proxy-authorization" | "cookie") || secrets.contains(&name) } /// `Bearer abc` keeps its scheme: what kind of auth left is worth knowing, the token is not. @@ -210,9 +205,7 @@ pub fn mask(exchange: &Exchange, secrets: &[String]) -> Exchange { /// `session=abc; Path=/; HttpOnly` keeps its name and what it is set for. fn masked_set_cookie(value: &str) -> String { - let (pair, attributes) = value - .split_once(';') - .map_or((value, None), |(pair, rest)| (pair, Some(rest))); + let (pair, attributes) = value.split_once(';').map_or((value, None), |(pair, rest)| (pair, Some(rest))); let name = pair.split_once('=').map_or(pair, |(name, _)| name); match attributes { Some(rest) => format!("{name}={MASK};{rest}"), @@ -249,22 +242,14 @@ fn masked_answer(response: &SentResponse, secrets: &[String]) -> SentResponse { ..header.clone() }) .collect(), - cookies: response - .cookies - .iter() - .map(|cookie| masked_cookie(cookie, secrets)) - .collect(), + cookies: response.cookies.iter().map(|cookie| masked_cookie(cookie, secrets)).collect(), redirects: response .redirects .iter() .map(|hop| Redirect { url: masked_url(&hop.url, secrets), from: masked_url(&hop.from, secrets), - cookies: hop - .cookies - .iter() - .map(|cookie| masked_cookie(cookie, secrets)) - .collect(), + cookies: hop.cookies.iter().map(|cookie| masked_cookie(cookie, secrets)).collect(), ..hop.clone() }) .collect(), @@ -294,10 +279,12 @@ pub fn sent_secrets(exchange: &Exchange, secrets: &[String]) -> Vec { } let name = header.key.trim().to_ascii_lowercase(); if name == "cookie" { - found.extend(header.value.split(';').filter_map(|pair| { - pair.split_once('=') - .map(|(_, value)| value.trim().to_string()) - })); + found.extend( + header + .value + .split(';') + .filter_map(|pair| pair.split_once('=').map(|(_, value)| value.trim().to_string())), + ); } else { if let Some((_, token)) = header.value.split_once(' ') { found.push(token.trim().to_string()); @@ -309,9 +296,7 @@ pub fn sent_secrets(exchange: &Exchange, secrets: &[String]) -> Vec { let query = query.split_once('#').map_or(query, |(query, _)| query); found.extend(query.split('&').filter_map(|pair| { let (key, value) = pair.split_once('=')?; - secrets - .contains(&key.to_ascii_lowercase()) - .then(|| value.to_string()) + secrets.contains(&key.to_ascii_lowercase()).then(|| value.to_string()) })); } // A secret variable is already written as its `{{name}}`, which stays readable. @@ -324,9 +309,8 @@ pub fn sent_secrets(exchange: &Exchange, secrets: &[String]) -> Vec { /// Each value the request sent as a secret, masked wherever the text says it back. #[must_use] pub fn masked_echo(text: &str, sent: &[String]) -> String { - sent.iter().fold(text.to_string(), |text, value| { - text.replace(value.as_str(), MASK) - }) + sent.iter() + .fold(text.to_string(), |text, value| text.replace(value.as_str(), MASK)) } /// A secret variable's value, wherever the answer repeats it — a server echoing a token in its @@ -353,31 +337,21 @@ fn rewritten(response: &SentResponse, hide: impl Fn(&str) -> String) -> SentResp headers: response .headers .iter() - .map(|header| KeyValue { - value: hide(&header.value), - ..header.clone() - }) + .map(|header| KeyValue { value: hide(&header.value), ..header.clone() }) .collect(), body: hide(&response.body), pretty: response.pretty.as_deref().map(&hide), redirects: response .redirects .iter() - .map(|hop| Redirect { - url: hide(&hop.url), - from: hide(&hop.from), - ..hop.clone() - }) + .map(|hop| Redirect { url: hide(&hop.url), from: hide(&hop.from), ..hop.clone() }) .collect(), graphql: response.graphql.as_ref().map(|graphql| GraphqlResult { data: graphql.data.as_deref().map(&hide), errors: graphql .errors .iter() - .map(|error| GraphqlError { - message: hide(&error.message), - ..error.clone() - }) + .map(|error| GraphqlError { message: hide(&error.message), ..error.clone() }) .collect(), }), ..response.clone() @@ -393,10 +367,7 @@ fn hidden_exchange(exchange: &Exchange, secrets: &[(String, String)]) -> Exchang headers: exchange .headers .iter() - .map(|header| KeyValue { - value: hide(&header.value), - ..header.clone() - }) + .map(|header| KeyValue { value: hide(&header.value), ..header.clone() }) .collect(), body: match &exchange.body { SentBody::Text { text } => SentBody::Text { text: hide(text) }, @@ -415,10 +386,7 @@ pub fn shown(exchange: &Exchange, secrets: &[(String, String)]) -> Exchange { /// What is sealed: the request masked, its body and the answer's cut to `BODY_KEPT`. pub fn record_of(sent: &Sent) -> (HistorySummary, HistoryRecord) { - let mut exchange = mask( - &hidden_exchange(&sent.exchange, &sent.secret_values), - &sent.secrets, - ); + let mut exchange = mask(&hidden_exchange(&sent.exchange, &sent.secret_values), &sent.secrets); if let SentBody::Text { text } = &exchange.body { exchange.body = SentBody::Text { text: cut(text).0 }; } @@ -427,11 +395,7 @@ pub fn record_of(sent: &Sent) -> (HistorySummary, HistoryRecord) { let response = &echo_masked(&hidden_answer(response, &sent.secret_values), &echoed); let (body, shortened) = cut(&response.body); SentResponse { - pretty: if shortened { - None - } else { - response.pretty.clone() - }, + pretty: if shortened { None } else { response.pretty.clone() }, cut: response.cut || shortened, body, exchange: exchange.clone(), @@ -476,17 +440,9 @@ fn draft_url(url: &str) -> String { Some((head, query)) => { let kept: Vec<&str> = query .split('&') - .filter(|pair| { - !pair - .split_once('=') - .is_some_and(|(_, value)| value.starts_with(MASK)) - }) + .filter(|pair| !pair.split_once('=').is_some_and(|(_, value)| value.starts_with(MASK))) .collect(); - if kept.is_empty() { - head.to_string() - } else { - format!("{head}?{}", kept.join("&")) - } + if kept.is_empty() { head.to_string() } else { format!("{head}?{}", kept.join("&")) } } None => url, } @@ -511,10 +467,7 @@ pub fn draft_of(entry: &HistoryEntry) -> HistoryDraft { && !header.key.eq_ignore_ascii_case("content-type") && !send::is_default(&header.key, &header.value) }) - .map(|header| KeyValue { - enabled: true, - ..header.clone() - }) + .map(|header| KeyValue { enabled: true, ..header.clone() }) .collect(); let body = match &exchange.body { SentBody::Text { text } if typed.as_deref().is_some_and(|kind| kind.contains("json")) => { @@ -528,13 +481,7 @@ pub fn draft_of(entry: &HistoryEntry) -> HistoryDraft { name: entry.item.summary.name.clone(), kind: RequestKind::Http, method: exchange.method, - document: RequestDocument { - url, - params, - headers, - body, - ..RequestDocument::default() - }, + document: RequestDocument { url, params, headers, body, ..RequestDocument::default() }, }; // A GraphQL send back in its two boxes, when it still reads as one. if entry.item.summary.kind == RequestKind::Graphql @@ -579,10 +526,7 @@ fn graphql_of(exchange: &Exchange) -> Option<(GraphqlDocument, String)> { )); } let mut url = Url::parse(&exchange.url).ok()?; - let mut document = GraphqlDocument { - as_get: true, - ..GraphqlDocument::default() - }; + let mut document = GraphqlDocument { as_get: true, ..GraphqlDocument::default() }; let mut kept: Vec<(String, String)> = Vec::new(); for (key, value) in url.query_pairs() { match key.as_ref() { @@ -611,11 +555,7 @@ fn graphql_of(exchange: &Exchange) -> Option<(GraphqlDocument, String)> { /// it has one: never the dots as a value. Set by the auth or handed down, it has no row here, /// and what set it is still there. A header its folder or collection hands down today, with /// the value that was sent, is no change of the request's either. -pub fn onto( - entry: &HistoryEntry, - current: &HttpRequest, - above: &[InheritedHeader], -) -> HistoryDraft { +pub fn onto(entry: &HistoryEntry, current: &HttpRequest, above: &[InheritedHeader]) -> HistoryDraft { let sent = draft_of(entry); let exchange = &entry.record.exchange; let mut document = current.document.clone(); @@ -628,8 +568,7 @@ pub fn onto( }; let handed_down = |header: &KeyValue| { above.iter().any(|known| { - known.header.key.trim().eq_ignore_ascii_case(&header.key) - && known.header.value == header.value + known.header.key.trim().eq_ignore_ascii_case(&header.key) && known.header.value == header.value }) }; document.headers = exchange @@ -645,9 +584,7 @@ pub fn onto( .find(|kept| kept.key == header.key && !handed_down(kept)) // Its description is the request's, which the record never held. .map(|kept| KeyValue { - description: own(&kept.key) - .map(|row| row.description.clone()) - .unwrap_or_default(), + description: own(&kept.key).map(|row| row.description.clone()).unwrap_or_default(), ..kept.clone() }) }) @@ -672,18 +609,13 @@ pub fn onto( } } } - HistoryDraft { - name: current.name.clone(), - kind: current.kind, - method, - document, - } + HistoryDraft { name: current.name.clone(), kind: current.kind, method, document } } /// Retention holds even when the history is never opened. Never fatal. pub fn sweep_at_startup(db: &crate::db::Db) { - let purged = crate::db::lock(db) - .and_then(|mut connection| store::purge_expired(&mut connection, Utc::now())); + let purged = + crate::db::lock(db).and_then(|mut connection| store::purge_expired(&mut connection, Utc::now())); if let Err(error) = purged { log::warn!("Expired HTTP history not purged: {error}"); } @@ -694,17 +626,10 @@ pub fn by_day(items: Vec, tz_offset_minutes: i32) -> Vec = Vec::new(); for item in items { - let day = item - .sent_at - .with_timezone(&offset) - .format("%Y-%m-%d") - .to_string(); + let day = item.sent_at.with_timezone(&offset).format("%Y-%m-%d").to_string(); match days.last_mut() { Some(last) if last.day == day => last.items.push(item), - _ => days.push(HistoryDay { - day, - items: vec![item], - }), + _ => days.push(HistoryDay { day, items: vec![item] }), } } days @@ -718,26 +643,15 @@ mod tests { use crate::notes::language::Language; fn header(key: &str, value: &str) -> KeyValue { - KeyValue { - key: key.to_string(), - value: value.to_string(), - ..KeyValue::default() - } + KeyValue { key: key.to_string(), value: value.to_string(), ..KeyValue::default() } } fn text(body: &str) -> SentBody { - SentBody::Text { - text: body.to_string(), - } + SentBody::Text { text: body.to_string() } } fn exchange(url: &str, headers: Vec, body: SentBody) -> Exchange { - Exchange { - method: HttpMethod::Post, - url: url.to_string(), - headers, - body, - } + Exchange { method: HttpMethod::Post, url: url.to_string(), headers, body } } fn response(body: &str) -> SentResponse { @@ -802,19 +716,12 @@ mod tests { url_head: String::new(), url_tail: String::new(), }, - record: HistoryRecord { - exchange, - response: None, - }, + record: HistoryRecord { exchange, response: None }, } } fn value_of<'a>(headers: &'a [KeyValue], key: &str) -> &'a str { - &headers - .iter() - .find(|header| header.key == key) - .unwrap() - .value + &headers.iter().find(|header| header.key == key).unwrap().value } /// What repeats is the host, what tells sends apart follows it; its credentials are not @@ -822,14 +729,8 @@ mod tests { #[test] fn a_url_is_listed_as_its_host_and_what_follows() { for (url, parts) in [ - ( - "https://shop.test/orders?page=2", - ("shop.test", "/orders?page=2"), - ), - ( - "https://ada:pw@shop.test:8443#top", - ("shop.test:8443", "#top"), - ), + ("https://shop.test/orders?page=2", ("shop.test", "/orders?page=2")), + ("https://ada:pw@shop.test:8443#top", ("shop.test:8443", "#top")), ("https://shop.test", ("shop.test", "")), ("{{base}}/orders", ("", "{{base}}/orders")), ] { @@ -858,33 +759,12 @@ mod tests { let kept = mask(&leaving, &["x-api-key".to_string(), "api_key".to_string()]); - assert_eq!( - kept.url, - format!("https://ada:{MASK}@shop.test/a?api_key={MASK}&page=2#top") - ); - let values: Vec<&str> = kept - .headers - .iter() - .map(|header| header.value.as_str()) - .collect(); - assert_eq!( - values, - [ - format!("Bearer {MASK}").as_str(), - MASK, - MASK, - MASK, - MASK, - "application/json" - ] - ); + assert_eq!(kept.url, format!("https://ada:{MASK}@shop.test/a?api_key={MASK}&page=2#top")); + let values: Vec<&str> = kept.headers.iter().map(|header| header.value.as_str()).collect(); + assert_eq!(values, [format!("Bearer {MASK}").as_str(), MASK, MASK, MASK, MASK, "application/json"]); assert_eq!(kept.body, text("{}")); assert_eq!( - mask( - &exchange("https://shop.test/a", Vec::new(), SentBody::None), - &[] - ) - .url, + mask(&exchange("https://shop.test/a", Vec::new(), SentBody::None), &[]).url, "https://shop.test/a" ); } @@ -895,10 +775,7 @@ mod tests { fn a_request_is_shown_with_its_secrets_as_their_names() { let leaving = exchange( "https://shop.test/?t=t0k3n", - vec![ - header("X-Token", "t0k3n"), - header("Authorization", "Bearer t0k3n"), - ], + vec![header("X-Token", "t0k3n"), header("Authorization", "Bearer t0k3n")], text("{\"token\":\"t0k3n\"}"), ); @@ -906,10 +783,7 @@ mod tests { assert_eq!(shown.url, "https://shop.test/?t={{token}}"); assert_eq!(value_of(&shown.headers, "X-Token"), "{{token}}"); - assert_eq!( - value_of(&shown.headers, "Authorization"), - format!("Bearer {MASK}") - ); + assert_eq!(value_of(&shown.headers, "Authorization"), format!("Bearer {MASK}")); assert_eq!(shown.body, text("{\"token\":\"{{token}}\"}")); } @@ -932,20 +806,8 @@ mod tests { let found = sent_secrets(&leaving, &["x-api-key".to_string(), "api_key".to_string()]); - assert_eq!( - found, - [ - "k3y-in-header", - "Bearer t0k3n", - "k3y-in-url", - "s1d-value", - "t0k3n" - ] - ); - assert_eq!( - masked_echo("echo t0k3n and s1d-value", &found), - format!("echo {MASK} and {MASK}") - ); + assert_eq!(found, ["k3y-in-header", "Bearer t0k3n", "k3y-in-url", "s1d-value", "t0k3n"]); + assert_eq!(masked_echo("echo t0k3n and s1d-value", &found), format!("echo {MASK} and {MASK}")); } /// ⚠️ What an answer sets is what the next request sends: a `Set-Cookie` keeps its name and @@ -974,10 +836,7 @@ mod tests { from: "https://shop.test/login?api_key=k3y".to_string(), cookies: vec![set], }]; - let mut leaving = sent( - exchange("https://shop.test/login", Vec::new(), SentBody::None), - Ok(answer), - ); + let mut leaving = sent(exchange("https://shop.test/login", Vec::new(), SentBody::None), Ok(answer)); leaving.secrets = vec!["api_key".to_string()]; let (_, record) = record_of(&leaving); @@ -985,23 +844,11 @@ mod tests { let kept = record.response.unwrap(); let masked = format!("api_key={MASK}"); assert!(kept.url.ends_with(&masked)); - assert_eq!( - value_of(&kept.headers, "Set-Cookie"), - format!("sid={MASK}; Path=/; HttpOnly") - ); - assert_eq!( - value_of(&kept.headers, "set-cookie"), - format!("bare={MASK}") - ); + assert_eq!(value_of(&kept.headers, "Set-Cookie"), format!("sid={MASK}; Path=/; HttpOnly")); + assert_eq!(value_of(&kept.headers, "set-cookie"), format!("bare={MASK}")); assert!(value_of(&kept.headers, "Location").ends_with(&masked)); assert_eq!(value_of(&kept.headers, "Server"), "test"); - assert_eq!( - ( - kept.cookies[0].name.as_str(), - kept.cookies[0].value.as_str() - ), - ("sid", MASK) - ); + assert_eq!((kept.cookies[0].name.as_str(), kept.cookies[0].value.as_str()), ("sid", MASK)); assert!(kept.cookies[0].from.as_deref().unwrap().ends_with(&masked)); let hop = &kept.redirects[0]; assert!(hop.url.ends_with(&masked) && hop.from.ends_with(&masked)); @@ -1024,18 +871,10 @@ mod tests { }]; answer.graphql = Some(GraphqlResult { data: Some("{\"me\":\"abc-123\"}".to_string()), - errors: vec![GraphqlError { - message: "bad token t0k3n".to_string(), - path: None, - location: None, - }], + errors: vec![GraphqlError { message: "bad token t0k3n".to_string(), path: None, location: None }], }); let mut leaving = sent( - exchange( - "https://shop.test/", - vec![header("Authorization", "Bearer abc-123")], - SentBody::None, - ), + exchange("https://shop.test/", vec![header("Authorization", "Bearer abc-123")], SentBody::None), Ok(answer), ); leaving.secret_values = vec![("token".to_string(), "t0k3n".to_string())]; @@ -1043,31 +882,16 @@ mod tests { let (_, record) = record_of(&leaving); let kept = record.response.unwrap(); - assert_eq!( - kept.body, - format!("{{\"token\":\"{{{{token}}}}\",\"auth\":\"{MASK}\"}}") - ); - assert_eq!( - kept.pretty.as_deref(), - Some(format!("{{{{token}}}} {MASK}").as_str()) - ); + assert_eq!(kept.body, format!("{{\"token\":\"{{{{token}}}}\",\"auth\":\"{MASK}\"}}")); + assert_eq!(kept.pretty.as_deref(), Some(format!("{{{{token}}}} {MASK}").as_str())); assert_eq!(value_of(&kept.headers, "X-Echo"), MASK); assert_eq!(kept.url, "https://shop.test/?t={{token}}"); assert_eq!( - ( - kept.redirects[0].url.as_str(), - kept.redirects[0].from.as_str() - ), - ( - format!("https://shop.test/{MASK}").as_str(), - "https://shop.test/{{token}}" - ) + (kept.redirects[0].url.as_str(), kept.redirects[0].from.as_str()), + (format!("https://shop.test/{MASK}").as_str(), "https://shop.test/{{token}}") ); let graphql = kept.graphql.unwrap(); - assert_eq!( - graphql.data.as_deref(), - Some(format!("{{\"me\":\"{MASK}\"}}").as_str()) - ); + assert_eq!(graphql.data.as_deref(), Some(format!("{{\"me\":\"{MASK}\"}}").as_str())); assert_eq!(graphql.errors[0].message, "bad token {{token}}"); } @@ -1092,10 +916,7 @@ mod tests { let (summary, record) = record_of(&leaving); assert_eq!(record.exchange.url, "https://shop.test/?q={{token}}"); - assert_eq!( - value_of(&record.exchange.headers, "Authorization"), - format!("Bearer {MASK}") - ); + assert_eq!(value_of(&record.exchange.headers, "Authorization"), format!("Bearer {MASK}")); assert_eq!(record.exchange.body, text(&"a".repeat(BODY_KEPT - 1))); let kept = record.response.unwrap(); assert_eq!(kept.body.len(), BODY_KEPT - 1); @@ -1109,14 +930,10 @@ mod tests { /// code and what its sentence states, and no answer. #[test] fn a_send_s_summary_says_how_it_went() { - let environment = SentEnvironment { - name: "Prod".to_string(), - colour: crate::folders::model::FolderColour::Red, - }; - let mut answered = sent( - exchange("https://shop.test/", Vec::new(), SentBody::None), - Ok(response("ok")), - ); + let environment = + SentEnvironment { name: "Prod".to_string(), colour: crate::folders::model::FolderColour::Red }; + let mut answered = + sent(exchange("https://shop.test/", Vec::new(), SentBody::None), Ok(response("ok"))); answered.kind = RequestKind::Graphql; answered.environment = Some(environment.clone()); let params = BTreeMap::from([("delay".to_string(), "30 s".to_string())]); @@ -1213,12 +1030,7 @@ mod tests { .collect(); assert_eq!(params, [("page", "2")]); assert_eq!(draft.document.headers, [header("X-Trace", "1")]); - assert_eq!( - draft.document.body, - RequestBody::Json { - text: "{\"a\":1}".to_string() - } - ); + assert_eq!(draft.document.body, RequestBody::Json { text: "{\"a\":1}".to_string() }); } /// A text without a JSON type is text; a file or a multipart was not kept; a query of @@ -1235,31 +1047,12 @@ mod tests { let plain = body(text("hello"), vec![header("Content-Type", "text/plain")]); - assert_eq!( - plain.body, - RequestBody::Text { - text: "hello".to_string() - } - ); + assert_eq!(plain.body, RequestBody::Text { text: "hello".to_string() }); assert_eq!(plain.url, "https://shop.test/"); + assert_eq!(body(text("{}"), Vec::new()).body, RequestBody::Text { text: "{}".to_string() }); + assert_eq!(body(SentBody::Bytes { size: 3 }, Vec::new()).body, RequestBody::None); assert_eq!( - body(text("{}"), Vec::new()).body, - RequestBody::Text { - text: "{}".to_string() - } - ); - assert_eq!( - body(SentBody::Bytes { size: 3 }, Vec::new()).body, - RequestBody::None - ); - assert_eq!( - body( - SentBody::Multipart { - fields: vec!["a".to_string()] - }, - Vec::new() - ) - .body, + body(SentBody::Multipart { fields: vec!["a".to_string()] }, Vec::new()).body, RequestBody::None ); } @@ -1290,16 +1083,10 @@ mod tests { assert_eq!(from_post.kind, RequestKind::Graphql); assert_eq!(from_post.document.graphql.query, "{ me { id } }"); assert_eq!(from_post.document.graphql.variables, "{\n \"id\": 7\n}"); - assert_eq!( - from_post.document.graphql.operation_name.as_deref(), - Some("Me") - ); + assert_eq!(from_post.document.graphql.operation_name.as_deref(), Some("Me")); assert!(!from_post.document.graphql.as_get && from_post.document.body == RequestBody::None); assert_eq!( - ( - from_get.document.graphql.query.as_str(), - from_get.document.graphql.as_get - ), + (from_get.document.graphql.query.as_str(), from_get.document.graphql.as_get), ("{ me }", true) ); assert_eq!(from_get.document.graphql.variables, "{\n \"a\": 1\n}"); @@ -1344,21 +1131,11 @@ mod tests { let mine = RequestDocument { url: "https://shop.test/a".to_string(), headers: vec![ - KeyValue { - description: "the key".to_string(), - ..header("x-api-key", "{{key}}") - }, - KeyValue { - description: "which trace".to_string(), - ..header("X-Trace", "1") - }, + KeyValue { description: "the key".to_string(), ..header("x-api-key", "{{key}}") }, + KeyValue { description: "which trace".to_string(), ..header("X-Trace", "1") }, ], - body: RequestBody::Binary { - path: "/dump.bin".to_string(), - }, - auth: RequestAuth::Bearer { - token: "{{token}}".to_string(), - }, + body: RequestBody::Binary { path: "/dump.bin".to_string() }, + auth: RequestAuth::Bearer { token: "{{token}}".to_string() }, ..RequestDocument::default() }; let above = [InheritedHeader { @@ -1370,11 +1147,8 @@ mod tests { }, }]; - let put_back = onto( - &entry(RequestKind::Http, recorded), - ¤t(RequestKind::Http, mine.clone()), - &above, - ); + let put_back = + onto(&entry(RequestKind::Http, recorded), ¤t(RequestKind::Http, mine.clone()), &above); assert_eq!( (put_back.name.as_str(), put_back.kind, put_back.method), @@ -1386,16 +1160,10 @@ mod tests { put_back.document.headers, [ mine.headers[0].clone(), - KeyValue { - description: "which trace".to_string(), - ..header("X-Trace", "2") - }, + KeyValue { description: "which trace".to_string(), ..header("X-Trace", "2") }, ] ); - assert_eq!( - (&put_back.document.body, &put_back.document.auth), - (&mine.body, &mine.auth) - ); + assert_eq!((&put_back.document.body, &put_back.document.auth), (&mine.body, &mine.auth)); } /// A text body or none goes over the request's; a GraphQL request takes its query back and @@ -1403,39 +1171,18 @@ mod tests { #[test] fn a_send_put_back_takes_its_body_or_its_graphql() { let mine = RequestDocument { - body: RequestBody::Json { - text: "{\"old\":1}".to_string(), - }, + body: RequestBody::Json { text: "{\"old\":1}".to_string() }, ..RequestDocument::default() }; let texted = exchange("https://shop.test/", Vec::new(), text("new")); - let posted = exchange( - "https://shop.test/graphql?x=1", - Vec::new(), - text(r#"{"query":"{ me }"}"#), - ); + let posted = exchange("https://shop.test/graphql?x=1", Vec::new(), text(r#"{"query":"{ me }"}"#)); - let http = onto( - &entry(RequestKind::Http, texted), - ¤t(RequestKind::Http, mine.clone()), - &[], - ); - let graphql = onto( - &entry(RequestKind::Graphql, posted), - ¤t(RequestKind::Graphql, mine.clone()), - &[], - ); + let http = onto(&entry(RequestKind::Http, texted), ¤t(RequestKind::Http, mine.clone()), &[]); + let graphql = + onto(&entry(RequestKind::Graphql, posted), ¤t(RequestKind::Graphql, mine.clone()), &[]); - assert_eq!( - http.document.body, - RequestBody::Text { - text: "new".to_string() - } - ); - assert_eq!( - (graphql.method, graphql.document.graphql.query.as_str()), - (HttpMethod::Get, "{ me }") - ); + assert_eq!(http.document.body, RequestBody::Text { text: "new".to_string() }); + assert_eq!((graphql.method, graphql.document.graphql.query.as_str()), (HttpMethod::Get, "{ me }")); assert_eq!(graphql.document.url, "https://shop.test/graphql?x=1"); assert_eq!(graphql.document.body, mine.body); } @@ -1447,11 +1194,7 @@ mod tests { let item = |id: &str, at: &str| HistoryItem { id: id.to_string(), sent_at: crate::db::iso8601::parse(at).unwrap(), - ..entry( - RequestKind::Http, - exchange("https://shop.test/", Vec::new(), SentBody::None), - ) - .item + ..entry(RequestKind::Http, exchange("https://shop.test/", Vec::new(), SentBody::None)).item }; let items = vec![ item("late", "2026-07-25T23:30:00.000Z"), @@ -1464,27 +1207,16 @@ mod tests { let grouped = |days: &[HistoryDay]| -> Vec<(String, Vec)> { days.iter() - .map(|day| { - ( - day.day.clone(), - day.items.iter().map(|item| item.id.clone()).collect(), - ) - }) + .map(|day| (day.day.clone(), day.items.iter().map(|item| item.id.clone()).collect())) .collect() }; assert_eq!( grouped(&utc), [ - ( - "2026-07-25".to_string(), - vec!["late".to_string(), "evening".to_string()] - ), + ("2026-07-25".to_string(), vec!["late".to_string(), "evening".to_string()]), ("2026-07-24".to_string(), vec!["before".to_string()]) ] ); - assert_eq!( - grouped(&east)[0], - ("2026-07-26".to_string(), vec!["late".to_string()]) - ); + assert_eq!(grouped(&east)[0], ("2026-07-26".to_string(), vec!["late".to_string()])); } } diff --git a/crates/engine/src/http/history/store.rs b/crates/engine/src/http/history/store.rs index e6e07f33d..fcd90c03c 100644 --- a/crates/engine/src/http/history/store.rs +++ b/crates/engine/src/http/history/store.rs @@ -5,8 +5,7 @@ use diesel::prelude::*; use uuid::Uuid; use super::{ - HistoryEntry, HistoryItem, HistoryRecord, HistorySummary, KEPT_AT_MOST, RETENTION_DAYS, - url_parts, + HistoryEntry, HistoryItem, HistoryRecord, HistorySummary, KEPT_AT_MOST, RETENTION_DAYS, url_parts, }; use crate::db::schema::http_history; use crate::db::{Library, iso8601}; @@ -23,10 +22,7 @@ struct Row { } fn corrupt(id: &str, field: &'static str) -> StorageError { - StorageError::CorruptRow { - id: id.to_string(), - field, - } + StorageError::CorruptRow { id: id.to_string(), field } } fn open_json( @@ -62,10 +58,7 @@ impl Row { } /// A request deleted since it was sent is history without its link. -fn still_there<'a>( - connection: &mut SqliteConnection, - request_id: Option<&'a str>, -) -> Option<&'a str> { +fn still_there<'a>(connection: &mut SqliteConnection, request_id: Option<&'a str>) -> Option<&'a str> { request_id.filter(|id| { crate::db::schema::http_requests::table .find(*id) @@ -130,15 +123,15 @@ pub fn restore(connection: &mut Library, entry: &HistoryEntry) -> Result<(), Sto /// Older than the retention, or past the count from the newest. fn purge(connection: &mut SqliteConnection, now: DateTime) -> Result { let horizon = iso8601::format(now - TimeDelta::days(RETENTION_DAYS)); - let aged = diesel::delete(http_history::table.filter(http_history::sent_at.lt(horizon))) - .execute(connection)?; + let aged = + diesel::delete(http_history::table.filter(http_history::sent_at.lt(horizon))).execute(connection)?; let kept: Vec = http_history::table .select(http_history::id) .order((http_history::sent_at.desc(), http_history::id.desc())) .limit(KEPT_AT_MOST) .load(connection)?; - let counted = diesel::delete(http_history::table.filter(http_history::id.ne_all(kept))) - .execute(connection)?; + let counted = + diesel::delete(http_history::table.filter(http_history::id.ne_all(kept))).execute(connection)?; Ok(aged + counted) } @@ -168,10 +161,7 @@ pub fn entry(connection: &mut Library, id: &str) -> Result Result { @@ -224,21 +214,12 @@ mod tests { } } - fn write( - library: &mut Library, - name: &str, - request_id: Option<&str>, - at: DateTime, - ) -> String { + fn write(library: &mut Library, name: &str, request_id: Option<&str>, at: DateTime) -> String { super::record(library, request_id, &summary(name), &record(), at).unwrap() } fn names(library: &mut Library) -> Vec { - list(library) - .unwrap() - .into_iter() - .map(|item| item.summary.name) - .collect() + list(library).unwrap().into_iter().map(|item| item.summary.name).collect() } fn a_request(library: &mut Library) -> String { @@ -251,9 +232,7 @@ mod tests { method: HttpMethod::Get, document: crate::http::model::RequestDocument::default(), }; - crate::http::store::create_request(library, &draft, "Orders", now()) - .unwrap() - .id + crate::http::store::create_request(library, &draft, "Orders", now()).unwrap().id } /// Newest first; of one instant, the one written last; read back with what a list shows, @@ -267,20 +246,11 @@ mod tests { let items = list(&mut library).unwrap(); - let shown: Vec<&str> = items - .iter() - .map(|item| item.summary.name.as_str()) - .collect(); + let shown: Vec<&str> = items.iter().map(|item| item.summary.name.as_str()).collect(); assert_eq!(shown, ["second", "first", "earlier"]); let item = &items[0]; - assert_eq!( - (item.sent_at, item.method, item.status), - (now(), HttpMethod::Delete, Some(401)) - ); - assert_eq!( - (item.url_head.as_str(), item.url_tail.as_str()), - ("api.shop.test", "/orders/42") - ); + assert_eq!((item.sent_at, item.method, item.status), (now(), HttpMethod::Delete, Some(401))); + assert_eq!((item.url_head.as_str(), item.url_tail.as_str()), ("api.shop.test", "/orders/42")); } /// A request deleted since it was sent is history without its link. @@ -291,11 +261,8 @@ mod tests { write(&mut library, "linked", Some(&request), now()); write(&mut library, "gone", Some("deleted-since"), now()); - let links: Vec> = list(&mut library) - .unwrap() - .into_iter() - .map(|item| item.request_id) - .collect(); + let links: Vec> = + list(&mut library).unwrap().into_iter().map(|item| item.request_id).collect(); assert_eq!(links, [None, Some(request)]); } @@ -310,12 +277,7 @@ mod tests { None, now() - TimeDelta::days(RETENTION_DAYS) - TimeDelta::seconds(1), ); - write( - &mut library, - "at the edge", - None, - now() - TimeDelta::days(RETENTION_DAYS), - ); + write(&mut library, "at the edge", None, now() - TimeDelta::days(RETENTION_DAYS)); write(&mut library, "today", None, now()); @@ -340,12 +302,7 @@ mod tests { #[test] fn the_retention_is_swept_at_launch_without_a_write() { let mut library = crate::db::open_in_memory().unwrap(); - write( - &mut library, - "old", - None, - Utc::now() - TimeDelta::days(RETENTION_DAYS + 1), - ); + write(&mut library, "old", None, Utc::now() - TimeDelta::days(RETENTION_DAYS + 1)); write(&mut library, "kept", None, Utc::now()); let db: crate::db::Db = std::sync::Mutex::new(Some(library)); @@ -381,10 +338,8 @@ mod tests { let request = a_request(&mut library); let id = write(&mut library, "linked", Some(&request), now()); let removed = delete(&mut library, &id).unwrap(); - let gone = crate::http::model::HttpItem { - kind: crate::http::model::HttpItemKind::Request, - id: request, - }; + let gone = + crate::http::model::HttpItem { kind: crate::http::model::HttpItemKind::Request, id: request }; crate::http::store::delete(&mut library, &gone).unwrap(); restore(&mut library, &removed).unwrap(); @@ -401,10 +356,7 @@ mod tests { assert!( matches!(entry(&mut library, "missing"), Err(StorageError::HttpItemNotFound(id)) if id == "missing") ); - assert!(matches!( - delete(&mut library, "missing"), - Err(StorageError::HttpItemNotFound(_)) - )); + assert!(matches!(delete(&mut library, "missing"), Err(StorageError::HttpItemNotFound(_)))); assert_eq!(clear(&mut library).unwrap(), 2); assert_eq!(count(&mut library).unwrap(), 0); } @@ -422,10 +374,7 @@ mod tests { .unwrap(); for clear in ["DELETE", "Delete", "401", "api.shop.test", "orders"] { - assert!( - !summary.contains(clear) && !sealed.contains(clear), - "{clear} in the clear" - ); + assert!(!summary.contains(clear) && !sealed.contains(clear), "{clear} in the clear"); } } @@ -440,38 +389,17 @@ mod tests { .set(http_history::record.eq(&garbage)) .execute(library.db()) .unwrap(); - assert!(matches!( - entry(&mut library, &id), - Err(StorageError::CorruptRow { - field: "record", - .. - }) - )); + assert!(matches!(entry(&mut library, &id), Err(StorageError::CorruptRow { field: "record", .. }))); diesel::update(http_history::table.find(&id)) .set(http_history::summary.eq(&garbage)) .execute(library.db()) .unwrap(); - assert!(matches!( - list(&mut library), - Err(StorageError::CorruptRow { - field: "summary", - .. - }) - )); + assert!(matches!(list(&mut library), Err(StorageError::CorruptRow { field: "summary", .. }))); let readable = seal_json(library.vault(), &summary("a")).unwrap(); diesel::update(http_history::table.find(&id)) - .set(( - http_history::summary.eq(readable), - http_history::sent_at.eq("not a date"), - )) + .set((http_history::summary.eq(readable), http_history::sent_at.eq("not a date"))) .execute(library.db()) .unwrap(); - assert!(matches!( - list(&mut library), - Err(StorageError::CorruptRow { - field: "sentAt", - .. - }) - )); + assert!(matches!(list(&mut library), Err(StorageError::CorruptRow { field: "sentAt", .. }))); } } diff --git a/crates/engine/src/http/model.rs b/crates/engine/src/http/model.rs index 449145959..70dffa320 100644 --- a/crates/engine/src/http/model.rs +++ b/crates/engine/src/http/model.rs @@ -114,11 +114,7 @@ pub struct RequestScripts { /// What a request sends as its body. A file is a path, read by Rust when the request is sent: /// its bytes never enter the library. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -#[serde( - tag = "kind", - rename_all = "camelCase", - rename_all_fields = "camelCase" -)] +#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")] pub enum RequestBody { #[default] None, @@ -162,12 +158,8 @@ impl RequestBody { match self { Self::None => false, Self::Json { text } | Self::Text { text } => !text.is_empty(), - Self::Form { fields } => fields - .iter() - .any(|row| row.enabled && !row.key.trim().is_empty()), - Self::Multipart { parts } => parts - .iter() - .any(|part| part.enabled && !part.key.trim().is_empty()), + Self::Form { fields } => fields.iter().any(|row| row.enabled && !row.key.trim().is_empty()), + Self::Multipart { parts } => parts.iter().any(|part| part.enabled && !part.key.trim().is_empty()), Self::Binary { path } => !path.trim().is_empty(), } } @@ -213,11 +205,7 @@ pub enum KeyPlace { /// `Inherit` takes the auth of the nearest folder, then the collection, that sets one. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -#[serde( - tag = "kind", - rename_all = "camelCase", - rename_all_fields = "camelCase" -)] +#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")] pub enum RequestAuth { #[default] Inherit, @@ -274,12 +262,7 @@ pub struct KeyValue { /// Enabled: a row is typed to be sent. impl Default for KeyValue { fn default() -> Self { - Self { - enabled: true, - key: String::new(), - value: String::new(), - description: String::new(), - } + Self { enabled: true, key: String::new(), value: String::new(), description: String::new() } } } @@ -414,13 +397,8 @@ pub struct HttpRequestPatch { #[derive(Debug, Clone, PartialEq, Eq)] pub enum HttpNode { - Folder { - folder: HttpFolder, - children: Vec, - }, - Request { - request: HttpRequestSummary, - }, + Folder { folder: HttpFolder, children: Vec }, + Request { request: HttpRequestSummary }, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -453,9 +431,7 @@ pub struct HttpPlace { /// The type a multipart file part is sent with, read off its name: what an attachment knows, /// and the web's own files besides; `application/octet-stream` for the rest. pub fn part_type(file_name: &str) -> String { - let extension = file_name - .rsplit_once('.') - .map(|(_, extension)| extension.to_ascii_lowercase()); + let extension = file_name.rsplit_once('.').map(|(_, extension)| extension.to_ascii_lowercase()); let web = match extension.as_deref() { Some("html" | "htm") => "text/html", Some("xml") => "application/xml", @@ -484,27 +460,15 @@ mod tests { use super::*; fn row(key: &str, value: &str) -> KeyValue { - KeyValue { - key: key.to_string(), - value: value.to_string(), - ..KeyValue::default() - } + KeyValue { key: key.to_string(), value: value.to_string(), ..KeyValue::default() } } fn part(key: &str, value: &str, file: bool, enabled: bool) -> FormPart { - FormPart { - enabled, - key: key.to_string(), - value: value.to_string(), - file, - ..FormPart::default() - } + FormPart { enabled, key: key.to_string(), value: value.to_string(), file, ..FormPart::default() } } fn json(text: &str) -> RequestBody { - RequestBody::Json { - text: text.to_string(), - } + RequestBody::Json { text: text.to_string() } } /// Stored as written: a method or a kind reads back from its spelling. @@ -548,9 +512,7 @@ mod tests { part("name", "Ada", false, true), ], }; - let binary = RequestBody::Binary { - path: "/dump.bin".to_string(), - }; + let binary = RequestBody::Binary { path: "/dump.bin".to_string() }; assert_eq!(multipart.files(), ["/a.png"]); assert_eq!(binary.files(), ["/dump.bin"]); @@ -561,54 +523,19 @@ mod tests { #[test] fn a_body_carries_something_only_once_filled() { let named = || vec![row("q", "1")]; - let off = || { - vec![KeyValue { - enabled: false, - ..row("q", "1") - }] - }; + let off = || vec![KeyValue { enabled: false, ..row("q", "1") }]; for (body, carries) in [ (RequestBody::None, false), (json(""), false), (json("{}"), true), - ( - RequestBody::Text { - text: "t".to_string(), - }, - true, - ), + (RequestBody::Text { text: "t".to_string() }, true), (RequestBody::Form { fields: named() }, true), (RequestBody::Form { fields: off() }, false), - ( - RequestBody::Form { - fields: vec![row(" ", "1")], - }, - false, - ), - ( - RequestBody::Multipart { - parts: vec![part("a", "", false, true)], - }, - true, - ), - ( - RequestBody::Multipart { - parts: vec![part("a", "", false, false)], - }, - false, - ), - ( - RequestBody::Binary { - path: " ".to_string(), - }, - false, - ), - ( - RequestBody::Binary { - path: "/f".to_string(), - }, - true, - ), + (RequestBody::Form { fields: vec![row(" ", "1")] }, false), + (RequestBody::Multipart { parts: vec![part("a", "", false, true)] }, true), + (RequestBody::Multipart { parts: vec![part("a", "", false, false)] }, false), + (RequestBody::Binary { path: " ".to_string() }, false), + (RequestBody::Binary { path: "/f".to_string() }, true), ] { assert_eq!(body.carries_something(), carries, "{body:?}"); } @@ -650,30 +577,14 @@ mod tests { fn the_rule_agrees_with_what_the_client_builds() { use reqwest::header::{HeaderName, HeaderValue}; - for name in [ - "X-Recette", - "X Recette", - "X:1", - "Clé", - "a(b)", - "x_y", - "a`b", - "", - ] { + for name in ["X-Recette", "X Recette", "X:1", "Clé", "a(b)", "x_y", "a`b", ""] { assert_eq!( header_fault(name, "").is_none(), HeaderName::from_bytes(name.as_bytes()).is_ok(), "{name}" ); } - for value in [ - "plain", - "tab\there", - "Équipe", - "line\nbreak", - "nul\u{0}", - "del\u{7f}", - ] { + for value in ["plain", "tab\there", "Équipe", "line\nbreak", "nul\u{0}", "del\u{7f}"] { assert_eq!( header_fault("X-A", value).is_none(), HeaderValue::from_str(value).is_ok(), @@ -686,8 +597,7 @@ mod tests { /// older version still opens. #[test] fn a_document_written_before_a_field_existed_still_opens() { - let document: RequestDocument = - serde_json::from_str(r#"{"url":"https://exemple.fr"}"#).unwrap(); + let document: RequestDocument = serde_json::from_str(r#"{"url":"https://exemple.fr"}"#).unwrap(); assert_eq!(document.url, "https://exemple.fr"); assert_eq!(document.description, ""); @@ -700,14 +610,7 @@ mod tests { /// Not sent, not judged. #[test] fn a_header_switched_off_or_unnamed_is_not_judged() { - let rows = [ - row("X Id", "x"), - KeyValue { - enabled: false, - ..row("X Id", "x") - }, - row(" ", "a\nb"), - ]; + let rows = [row("X Id", "x"), KeyValue { enabled: false, ..row("X Id", "x") }, row(" ", "a\nb")]; assert_eq!(header_faults(&rows), [Some(HeaderFault::Name), None, None]); } @@ -720,13 +623,7 @@ mod tests { "Accept: application/json\n Referer : https://shop.test/a \nno colon\n:authority: shop.test\n", ); - assert_eq!( - rows, - [ - row("Accept", "application/json"), - row("Referer", "https://shop.test/a"), - ] - ); + assert_eq!(rows, [row("Accept", "application/json"), row("Referer", "https://shop.test/a"),]); } /// The web's own files by their extension, whatever its case; what an attachment knows diff --git a/crates/engine/src/http/query.rs b/crates/engine/src/http/query.rs index f728fdca2..86300e996 100644 --- a/crates/engine/src/http/query.rs +++ b/crates/engine/src/http/query.rs @@ -18,14 +18,8 @@ pub struct SyncedQuery { /// The side that was edited wins; the other is rewritten from it. pub fn sync(url: &str, params: &[KeyValue], edited: QuerySide) -> SyncedQuery { match edited { - QuerySide::Url => SyncedQuery { - url: url.to_string(), - params: params_from_url(url, params), - }, - QuerySide::Params => SyncedQuery { - url: url_with_params(url, params), - params: params.to_vec(), - }, + QuerySide::Url => SyncedQuery { url: url.to_string(), params: params_from_url(url, params) }, + QuerySide::Params => SyncedQuery { url: url_with_params(url, params), params: params.to_vec() }, } } @@ -42,39 +36,21 @@ fn parts(url: &str) -> (&str, Option<&str>, &str) { /// and stays where it was, and a description follows its key. fn params_from_url(url: &str, previous: &[KeyValue]) -> Vec { let (_, query, _) = parts(url); - let mut typed = query - .unwrap_or("") - .split('&') - .filter(|pair| !pair.is_empty()) - .map(|pair| { - let (key, value) = pair.split_once('=').unwrap_or((pair, "")); - (key.to_string(), value.to_string()) - }); + let mut typed = query.unwrap_or("").split('&').filter(|pair| !pair.is_empty()).map(|pair| { + let (key, value) = pair.split_once('=').unwrap_or((pair, "")); + (key.to_string(), value.to_string()) + }); let mut rows = Vec::with_capacity(previous.len()); for row in previous { if !row.enabled { rows.push(row.clone()); } else if let Some((key, value)) = typed.next() { - let description = if key == row.key { - row.description.clone() - } else { - String::new() - }; - rows.push(KeyValue { - enabled: true, - key, - value, - description, - }); + let description = if key == row.key { row.description.clone() } else { String::new() }; + rows.push(KeyValue { enabled: true, key, value, description }); } } - rows.extend(typed.map(|(key, value)| KeyValue { - enabled: true, - key, - value, - description: String::new(), - })); + rows.extend(typed.map(|(key, value)| KeyValue { enabled: true, key, value, description: String::new() })); rows } @@ -98,25 +74,15 @@ mod tests { use super::*; fn row(key: &str, value: &str) -> KeyValue { - KeyValue { - key: key.to_string(), - value: value.to_string(), - ..KeyValue::default() - } + KeyValue { key: key.to_string(), value: value.to_string(), ..KeyValue::default() } } fn described(key: &str, value: &str, description: &str) -> KeyValue { - KeyValue { - description: description.to_string(), - ..row(key, value) - } + KeyValue { description: description.to_string(), ..row(key, value) } } fn off(key: &str, value: &str) -> KeyValue { - KeyValue { - enabled: false, - ..row(key, value) - } + KeyValue { enabled: false, ..row(key, value) } } fn from_url(url: &str, params: &[KeyValue]) -> Vec { @@ -135,15 +101,9 @@ mod tests { /// value, an empty pair is none, and the fragment ends the query. #[test] fn the_url_s_pairs_become_rows_as_typed() { - let rows = from_url( - "https://shop.test/a?q=a%20b&&page={{page}}&flag#top?x=1", - &[], - ); + let rows = from_url("https://shop.test/a?q=a%20b&&page={{page}}&flag#top?x=1", &[]); - assert_eq!( - rows, - [row("q", "a%20b"), row("page", "{{page}}"), row("flag", "")] - ); + assert_eq!(rows, [row("q", "a%20b"), row("page", "{{page}}"), row("flag", "")]); } /// The pairs take the enabled rows' places in order; a row switched off is not in the URL @@ -159,26 +119,14 @@ mod tests { let rows = from_url("https://shop.test/a?q=new&sort=asc", &table); - assert_eq!( - rows, - [ - described("q", "new", "the search"), - off("debug", "1"), - row("sort", "asc"), - ] - ); + assert_eq!(rows, [described("q", "new", "the search"), off("debug", "1"), row("sort", "asc"),]); assert_eq!(from_url("https://shop.test/a", &table), [off("debug", "1")]); } /// The enabled rows with a key, in order; none, no `?`; the fragment stays at the end. #[test] fn the_rows_rewrite_the_url_s_query() { - let table = [ - row("q", "{{term}}"), - off("debug", "1"), - row("", "lost"), - row("page", "2"), - ]; + let table = [row("q", "{{term}}"), off("debug", "1"), row("", "lost"), row("page", "2")]; assert_eq!( from_params("https://shop.test/a?old=1#top", &table), diff --git a/crates/engine/src/http/response.rs b/crates/engine/src/http/response.rs index ff54832ac..dcf5607d5 100644 --- a/crates/engine/src/http/response.rs +++ b/crates/engine/src/http/response.rs @@ -88,9 +88,7 @@ fn cookie(line: &str) -> Option { for attribute in parts { let (key, value) = attribute .split_once('=') - .map_or((attribute.trim(), ""), |(key, value)| { - (key.trim(), value.trim()) - }); + .map_or((attribute.trim(), ""), |(key, value)| (key.trim(), value.trim())); match key.to_ascii_lowercase().as_str() { "domain" => cookie.domain = Some(value.to_string()), "path" => cookie.path = Some(value.to_string()), @@ -171,11 +169,7 @@ mod tests { use super::*; fn header(key: &str, value: &str) -> KeyValue { - KeyValue { - key: key.to_string(), - value: value.to_string(), - ..KeyValue::default() - } + KeyValue { key: key.to_string(), value: value.to_string(), ..KeyValue::default() } } /// Read off its type, whatever its case and parameters; with none, a body that parses as @@ -211,10 +205,7 @@ mod tests { let headers = [ header("Content-Type", "text/plain"), header("X-Not-A-Cookie", "a=b"), - header( - "set-cookie", - "sid=\"abc=1\"; Domain=shop.test; Path=/; HttpOnly; Secure; SameSite=Lax", - ), + header("set-cookie", "sid=\"abc=1\"; Domain=shop.test; Path=/; HttpOnly; Secure; SameSite=Lax"), header("Set-Cookie", "theme=dark"), header("Set-Cookie", "no equals sign"), header("Set-Cookie", " =nameless"), @@ -235,11 +226,7 @@ mod tests { same_site: Some("Lax".to_string()), ..Cookie::default() }, - Cookie { - name: "theme".to_string(), - value: "dark".to_string(), - ..Cookie::default() - }, + Cookie { name: "theme".to_string(), value: "dark".to_string(), ..Cookie::default() }, ] ); } @@ -255,14 +242,8 @@ mod tests { assert_eq!(read[0].expires.as_deref(), Some("Max-Age=60"), "{line}"); } - let expires = cookies(&[header( - "Set-Cookie", - "a=1; expires=Wed, 21 Oct 2026 07:28:00 GMT", - )]); - assert_eq!( - expires[0].expires.as_deref(), - Some("Wed, 21 Oct 2026 07:28:00 GMT") - ); + let expires = cookies(&[header("Set-Cookie", "a=1; expires=Wed, 21 Oct 2026 07:28:00 GMT")]); + assert_eq!(expires[0].expires.as_deref(), Some("Wed, 21 Oct 2026 07:28:00 GMT")); } /// Two spaces a level; an empty object or array stays on its line; what a string holds is diff --git a/crates/engine/src/http/runner.rs b/crates/engine/src/http/runner.rs index 61e386afb..7228663e9 100644 --- a/crates/engine/src/http/runner.rs +++ b/crates/engine/src/http/runner.rs @@ -45,11 +45,7 @@ pub fn read_file(path: &str) -> Result { /// A CSV with its header, or a JSON array of objects: what the file's text reads as. pub fn read_data(text: &str) -> Result { let text = text.trim_start_matches('\u{feff}'); - let data = if text.trim_start().starts_with('[') { - from_json(text)? - } else { - from_csv(text)? - }; + let data = if text.trim_start().starts_with('[') { from_json(text)? } else { from_csv(text)? }; if data.rows.is_empty() { return Err(DataFault::Empty); } @@ -225,12 +221,7 @@ impl RunSummary { #[must_use] pub fn of(results: &[RunResult]) -> Self { let count = |held: usize| u32::try_from(held).unwrap_or(u32::MAX); - let ran = || { - results - .iter() - .flat_map(|result| &result.tests) - .filter(|test| !test.skipped) - }; + let ran = || results.iter().flat_map(|result| &result.tests).filter(|test| !test.skipped); Self { failures: count(results.iter().filter(|result| result.failed()).count()), requests: count(results.len()), @@ -344,10 +335,7 @@ pub fn run_order(saved: &[RunEntry], placed: &[Placed]) -> Vec { } for request in placed { if !order.iter().any(|kept| kept.id == request.id) { - order.push(RunEntry { - id: request.id.clone(), - enabled: true, - }); + order.push(RunEntry { id: request.id.clone(), enabled: true }); } } order @@ -389,10 +377,7 @@ pub fn result_of( } Err(error) if error.code == ErrorCode::HttpScriptSkipped => result.skipped = true, Err(error) => { - result.error = Some(RunError { - code: error.code, - params: error.params, - }); + result.error = Some(RunError { code: error.code, params: error.params }); } } result @@ -412,10 +397,7 @@ pub fn gone(iteration: u32, placed: &Placed, error: AppError) -> RunResult { reason: String::new(), millis: 0, tests: Vec::new(), - error: Some(RunError { - code: error.code, - params: error.params, - }), + error: Some(RunError { code: error.code, params: error.params }), stop: None, skipped: false, response: None, @@ -463,9 +445,7 @@ impl Runs { pub fn cancel_all(&self) { if let Ok(mut running) = self.running.lock() { - running - .values_mut() - .for_each(|(cancelled, _)| *cancelled = true); + running.values_mut().for_each(|(cancelled, _)| *cancelled = true); } } @@ -517,18 +497,13 @@ mod tests { /// as JSON; a byte-order mark before it is no reason to refuse it. #[test] fn a_json_array_of_objects_is_read_a_row_an_object() { - let data = read_data( - "\u{feff} [{\"user\":\"ada\",\"age\":36},{\"admin\":true,\"user\":\"bob\"}]", - ) - .unwrap(); + let data = + read_data("\u{feff} [{\"user\":\"ada\",\"age\":36},{\"admin\":true,\"user\":\"bob\"}]").unwrap(); assert_eq!(columns(&data), ["user", "age", "admin"]); assert_eq!( data.rows, - [ - row(&[("user", "ada"), ("age", "36")]), - row(&[("admin", "true"), ("user", "bob")]) - ] + [row(&[("user", "ada"), ("age", "36")]), row(&[("admin", "true"), ("user", "bob")])] ); } @@ -537,18 +512,13 @@ mod tests { #[test] fn a_csv_with_its_header_is_read_a_row_a_line() { let data = - read_data("user , note,,age\r\nada,\"a, \"\"quoted\"\"\nnote\",x,36\r\n\r\nbob\n") - .unwrap(); + read_data("user , note,,age\r\nada,\"a, \"\"quoted\"\"\nnote\",x,36\r\n\r\nbob\n").unwrap(); assert_eq!(columns(&data), ["user", "note", "", "age"]); assert_eq!( data.rows, [ - row(&[ - ("user", "ada"), - ("note", "a, \"quoted\"\nnote"), - ("age", "36") - ]), + row(&[("user", "ada"), ("note", "a, \"quoted\"\nnote"), ("age", "36")]), row(&[("user", "bob"), ("note", ""), ("age", "")]), ] ); @@ -585,10 +555,7 @@ mod tests { let data = read_file(path.to_str().unwrap()).unwrap(); assert_eq!(data.rows, [row(&[("user", "ada")])]); - assert_eq!( - read_file(missing.to_str().unwrap()).unwrap_err().code, - ErrorCode::FileAccess - ); + assert_eq!(read_file(missing.to_str().unwrap()).unwrap_err().code, ErrorCode::FileAccess); } /// A data file past the cap is refused before it is read whole (a defect once met). @@ -648,11 +615,7 @@ mod tests { "c-1", vec![ request("a"), - folder( - "f-1", - "Auth", - vec![request("b"), folder("f-2", "Deep", vec![request("c")])], - ), + folder("f-1", "Auth", vec![request("b"), folder("f-2", "Deep", vec![request("c")])]), request("d"), ], ), @@ -662,16 +625,10 @@ mod tests { } fn placed(item: HttpItemKind, id: &str) -> Vec<(String, Vec)> { - placed_under( - &tree(), - &HttpItem { - kind: item, - id: id.to_string(), - }, - ) - .into_iter() - .map(|placed| (placed.id, placed.path)) - .collect() + placed_under(&tree(), &HttpItem { kind: item, id: id.to_string() }) + .into_iter() + .map(|placed| (placed.id, placed.path)) + .collect() } /// Each request under a collection or a folder, in the tree's order, with the folders @@ -689,50 +646,26 @@ mod tests { ("d".to_string(), path(&[])), ] ); - assert_eq!( - placed(HttpItemKind::Folder, "f-2"), - [("c".to_string(), path(&[]))] - ); + assert_eq!(placed(HttpItemKind::Folder, "f-2"), [("c".to_string(), path(&[]))]); assert!(placed(HttpItemKind::Folder, "missing").is_empty()); assert!(placed(HttpItemKind::Request, "a").is_empty()); } fn entry(id: &str, enabled: bool) -> RunEntry { - RunEntry { - id: id.to_string(), - enabled, - } + RunEntry { id: id.to_string(), enabled } } /// The order last arranged, less what went since and once each, then what was added since /// in the tree's order, switched on. #[test] fn a_run_takes_the_order_last_arranged_and_what_came_since() { - let here: Vec = placed_under( - &tree(), - &HttpItem { - kind: HttpItemKind::Collection, - id: "c-1".to_string(), - }, - ); - let saved = [ - entry("d", false), - entry("gone", true), - entry("b", true), - entry("d", true), - ]; + let here: Vec = + placed_under(&tree(), &HttpItem { kind: HttpItemKind::Collection, id: "c-1".to_string() }); + let saved = [entry("d", false), entry("gone", true), entry("b", true), entry("d", true)]; let order = run_order(&saved, &here); - assert_eq!( - order, - [ - entry("d", false), - entry("b", true), - entry("a", true), - entry("c", true) - ] - ); + assert_eq!(order, [entry("d", false), entry("b", true), entry("a", true), entry("c", true)]); } /// `run:#.` belongs to its run; any other send to none. @@ -781,31 +714,19 @@ mod tests { body: crate::http::send::SentBody::None, }, graphql: None, - scripts: ScriptsAnswer { - failure, - tests, - ..ScriptsAnswer::default() - }, + scripts: ScriptsAnswer { failure, tests, ..ScriptsAnswer::default() }, } } fn test(name: &str, passed: bool, skipped: bool) -> TestResult { - TestResult { - name: name.to_string(), - passed, - skipped, - ..TestResult::default() - } + TestResult { name: name.to_string(), passed, skipped, ..TestResult::default() } } /// An answer's status, time, tests and stop, its body kept only when asked; a skip is not a /// failure; another error is kept as its code and what it states. #[test] fn a_request_of_a_run_ends_as_its_answer_says() { - let stop = ScriptStop { - message: "boom".to_string(), - ..ScriptStop::default() - }; + let stop = ScriptStop { message: "boom".to_string(), ..ScriptStop::default() }; let answered = result_of( 2, &held("Login"), @@ -813,13 +734,7 @@ mod tests { Ok(answer(vec![test("ok", true, false)], Some(stop.clone()))), false, ); - let kept = result_of( - 1, - &held("Login"), - Vec::new(), - Ok(answer(Vec::new(), None)), - true, - ); + let kept = result_of(1, &held("Login"), Vec::new(), Ok(answer(Vec::new(), None)), true); let skipped = result_of( 1, &held("Login"), @@ -831,39 +746,20 @@ mod tests { 1, &held("Login"), Vec::new(), - Err(AppError::with( - ErrorCode::HttpTimeout, - String::new(), - "delay", - "30 s", - )), + Err(AppError::with(ErrorCode::HttpTimeout, String::new(), "delay", "30 s")), true, ); assert_eq!( - ( - answered.iteration, - answered.request_id.as_str(), - answered.name.as_str() - ), + (answered.iteration, answered.request_id.as_str(), answered.name.as_str()), (2, "login", "Login") ); assert_eq!( (answered.kind, answered.method, answered.path.as_slice()), - ( - RequestKind::Graphql, - HttpMethod::Post, - ["Auth".to_string()].as_slice() - ) - ); - assert_eq!( - (answered.status, answered.reason.as_str(), answered.millis), - (Some(201), "Created", 42) - ); - assert_eq!( - (answered.tests.len(), answered.stop, answered.response), - (1, Some(stop), None) + (RequestKind::Graphql, HttpMethod::Post, ["Auth".to_string()].as_slice()) ); + assert_eq!((answered.status, answered.reason.as_str(), answered.millis), (Some(201), "Created", 42)); + assert_eq!((answered.tests.len(), answered.stop, answered.response), (1, Some(stop), None)); assert!(kept.response.is_some()); assert!(skipped.skipped && skipped.error.is_none() && !skipped.failed()); assert_eq!( @@ -883,31 +779,16 @@ mod tests { 1, &held("A"), Vec::new(), - Ok(answer( - vec![test("ok", true, false), test("later", false, true)], - None, - )), + Ok(answer(vec![test("ok", true, false), test("later", false, true)], None)), false, ); - let failing_test = RunResult { - tests: vec![test("bad", false, false)], - ..base.clone() - }; - let stopped = RunResult { - stop: Some(ScriptStop::default()), - ..base.clone() - }; + let failing_test = RunResult { tests: vec![test("bad", false, false)], ..base.clone() }; + let stopped = RunResult { stop: Some(ScriptStop::default()), ..base.clone() }; let errored = RunResult { - error: Some(RunError { - code: ErrorCode::HttpTimeout, - params: BTreeMap::new(), - }), + error: Some(RunError { code: ErrorCode::HttpTimeout, params: BTreeMap::new() }), ..base.clone() }; - let skipped = RunResult { - skipped: true, - ..failing_test.clone() - }; + let skipped = RunResult { skipped: true, ..failing_test.clone() }; assert!(!base.failed()); assert!(failing_test.failed() && stopped.failed() && errored.failed()); @@ -921,58 +802,27 @@ mod tests { 1, &held("A"), Vec::new(), - Ok(answer( - vec![ - test("a", true, false), - test("b", false, false), - test("c", false, true), - ], - None, - )), + Ok(answer(vec![test("a", true, false), test("b", false, false), test("c", false, true)], None)), false, ); - let clean = RunResult { - tests: vec![test("d", true, false)], - ..base.clone() - }; + let clean = RunResult { tests: vec![test("d", true, false)], ..base.clone() }; let summary = RunSummary::of(&[base, clean]); - assert_eq!( - summary, - RunSummary { - failures: 1, - requests: 2, - passed: 2, - tests: 3 - } - ); + assert_eq!(summary, RunSummary { failures: 1, requests: 2, passed: 2, tests: 3 }); assert_eq!(RunSummary::of(&[]), RunSummary::default()); } /// A request gone when its turn comes ends as the error that says so, under its place. #[test] fn a_request_gone_since_ends_as_its_error() { - let placed = Placed { - id: "r-9".to_string(), - name: "Gone".to_string(), - path: vec!["Auth".to_string()], - }; + let placed = + Placed { id: "r-9".to_string(), name: "Gone".to_string(), path: vec!["Auth".to_string()] }; - let result = gone( - 3, - &placed, - AppError::with(ErrorCode::HttpItemNotFound, String::new(), "id", "r-9"), - ); + let result = + gone(3, &placed, AppError::with(ErrorCode::HttpItemNotFound, String::new(), "id", "r-9")); - assert_eq!( - ( - result.iteration, - result.request_id.as_str(), - result.name.as_str() - ), - (3, "r-9", "Gone") - ); + assert_eq!((result.iteration, result.request_id.as_str(), result.name.as_str()), (3, "r-9", "Gone")); assert_eq!(result.path, ["Auth"]); assert_eq!(result.error.unwrap().code, ErrorCode::HttpItemNotFound); assert_eq!(result.status, None); @@ -984,23 +834,13 @@ mod tests { fn a_run_goes_on_to_the_next_request_or_where_a_script_points() { let order: Vec = ["a", "b", "c"] .iter() - .map(|name| Placed { - id: (*name).to_string(), - name: name.to_uppercase(), - path: Vec::new(), - }) + .map(|name| Placed { id: (*name).to_string(), name: name.to_uppercase(), path: Vec::new() }) .collect(); assert_eq!(next_index(&order, 0, None), Some(1)); assert_eq!(next_index(&order, 2, None), None); - assert_eq!( - next_index(&order, 2, Some(&Next::To("A".to_string()))), - Some(0) - ); - assert_eq!( - next_index(&order, 0, Some(&Next::To("missing".to_string()))), - None - ); + assert_eq!(next_index(&order, 2, Some(&Next::To("A".to_string()))), Some(0)); + assert_eq!(next_index(&order, 0, Some(&Next::To("missing".to_string()))), None); assert_eq!(next_index(&order, 0, Some(&Next::End)), None); } diff --git a/crates/engine/src/http/scripts/around.rs b/crates/engine/src/http/scripts/around.rs index aab49d16a..adefb7d63 100644 --- a/crates/engine/src/http/scripts/around.rs +++ b/crates/engine/src/http/scripts/around.rs @@ -60,17 +60,9 @@ impl Around { scripts: &above.scripts, }) .collect(); - levels.push(Holder { - level: ScriptLevel::Request, - owner: None, - name: request, - scripts: own, - }); + levels.push(Holder { level: ScriptLevel::Request, owner: None, name: request, scripts: own }); Self { - before: levels - .iter() - .filter_map(|level| level.script(ScriptKind::Before)) - .collect(), + before: levels.iter().filter_map(|level| level.script(ScriptKind::Before)).collect(), after: levels .iter() .rev() @@ -112,23 +104,13 @@ pub fn layers_of(layers: &[VariableLayer]) -> Vec { VariableScope::Dynamic => return None, }; let mut values = std::collections::BTreeMap::new(); - for (variable, fault) in layer - .variables - .iter() - .zip(variable_faults(&layer.variables)) - { + for (variable, fault) in layer.variables.iter().zip(variable_faults(&layer.variables)) { let name = variable.name.trim(); if variable.enabled && !name.is_empty() && fault.is_none() { - values - .entry(name.to_string()) - .or_insert_with(|| variable.value.clone()); + values.entry(name.to_string()).or_insert_with(|| variable.value.clone()); } } - Some(ScriptLayer { - scope, - from: layer.from.clone(), - values, - }) + Some(ScriptLayer { scope, from: layer.from.clone(), values }) }) .collect() } @@ -149,10 +131,7 @@ pub fn written<'a>( table.retain(|variable| variable.name.trim() != name); continue; }; - match table - .iter_mut() - .find(|variable| variable.name.trim() == name) - { + match table.iter_mut().find(|variable| variable.name.trim() == name) { Some(variable) => { variable.value.clone_from(value); if write.secret { @@ -166,11 +145,7 @@ pub fn written<'a>( enabled: true, name: name.to_string(), value: value.clone(), - kind: if write.secret { - VariableKind::Secret - } else { - VariableKind::Text - }, + kind: if write.secret { VariableKind::Secret } else { VariableKind::Text }, filled_by: by.cloned(), }), } @@ -179,10 +154,7 @@ pub fn written<'a>( } /// The writes a phase made to one table. -pub fn writes_to( - writes: &[VariableWrite], - scope: WriteScope, -) -> impl Iterator { +pub fn writes_to(writes: &[VariableWrite], scope: WriteScope) -> impl Iterator { writes.iter().filter(move |write| write.scope == scope) } @@ -249,11 +221,7 @@ mod tests { use crate::http::settings::{self, HttpOrigin}; fn scripts(before: &str, after: &str, tests: &str) -> RequestScripts { - RequestScripts { - before: before.to_string(), - after: after.to_string(), - tests: tests.to_string(), - } + RequestScripts { before: before.to_string(), after: after.to_string(), tests: tests.to_string() } } fn above( @@ -262,18 +230,8 @@ mod tests { name: &str, held: RequestScripts, ) -> (HttpOrigin, ContainerSettings) { - let origin = HttpOrigin { - kind, - id: id.to_string(), - name: name.to_string(), - }; - ( - origin, - ContainerSettings { - scripts: held, - ..ContainerSettings::default() - }, - ) + let origin = HttpOrigin { kind, id: id.to_string(), name: name.to_string() }; + (origin, ContainerSettings { scripts: held, ..ContainerSettings::default() }) } /// The collection `API` over the folder `Invoices`, each with its scripts, and the request's. @@ -297,11 +255,7 @@ mod tests { assert_eq!( ids(&around.before), - [ - "collection:c1:before", - "folder:f1:before", - "request:request:before" - ] + ["collection:c1:before", "folder:f1:before", "request:request:before"] ); } @@ -326,11 +280,7 @@ mod tests { #[test] fn a_blank_script_is_not_run() { - let around = around( - scripts(" \n", "", ""), - scripts("a()", "\t", ""), - &scripts("", "b()", " "), - ); + let around = around(scripts(" \n", "", ""), scripts("a()", "\t", ""), &scripts("", "b()", " ")); assert_eq!(ids(&around.before), ["folder:f1:before"]); assert_eq!(ids(&around.answered()), ["request:request:after"]); @@ -339,36 +289,20 @@ mod tests { #[test] fn a_request_with_a_script_of_any_kind_is_not_without_one() { - for own in [ - scripts("a()", "", ""), - scripts("", "a()", ""), - scripts("", "", "a()"), - ] { - assert!( - !Around::of(&own, "Pay", &settings::inherit(&[])).is_empty(), - "{own:?}" - ); + for own in [scripts("a()", "", ""), scripts("", "a()", ""), scripts("", "", "a()")] { + assert!(!Around::of(&own, "Pay", &settings::inherit(&[])).is_empty(), "{own:?}"); } } #[test] fn a_script_says_who_holds_it() { - let around = around( - scripts("c()", "", ""), - scripts("f()", "", ""), - &scripts("r()", "", ""), - ); + let around = around(scripts("c()", "", ""), scripts("f()", "", ""), &scripts("r()", "", "")); let held: Vec<_> = around .before .iter() .map(|script| { - ( - script.level, - script.name.as_str(), - script.owner.as_deref(), - script.source.as_str(), - ) + (script.level, script.name.as_str(), script.owner.as_deref(), script.source.as_str()) }) .collect(); assert_eq!( @@ -379,35 +313,19 @@ mod tests { (ScriptLevel::Request, "Pay", None, "r()"), ] ); - assert!( - around - .before - .iter() - .all(|script| script.kind == ScriptKind::Before) - ); + assert!(around.before.iter().all(|script| script.kind == ScriptKind::Before)); } fn variable(name: &str, value: &str) -> Variable { - Variable { - name: name.to_string(), - value: value.to_string(), - ..Variable::default() - } + Variable { name: name.to_string(), value: value.to_string(), ..Variable::default() } } fn secret(name: &str, value: &str) -> Variable { - Variable { - kind: VariableKind::Secret, - ..variable(name, value) - } + Variable { kind: VariableKind::Secret, ..variable(name, value) } } fn level(scope: VariableScope, variables: Vec) -> VariableLayer { - VariableLayer { - scope, - from: "Staging".to_string(), - variables, - } + VariableLayer { scope, from: "Staging".to_string(), variables } } #[test] @@ -434,23 +352,14 @@ mod tests { LayerScope::Globals ] ); - assert!( - read.iter() - .all(|layer| layer.from == "Staging" && layer.values["a"] == "1") - ); + assert!(read.iter().all(|layer| layer.from == "Staging" && layer.values["a"] == "1")); } /// As the send resolves them. #[test] fn a_row_switched_off_unnamed_or_at_fault_is_no_value_a_script_reads() { - let off = Variable { - enabled: false, - ..variable("off", "x") - }; - let number = Variable { - kind: VariableKind::Number, - ..variable("count", "many") - }; + let off = Variable { enabled: false, ..variable("off", "x") }; + let number = Variable { kind: VariableKind::Number, ..variable("count", "many") }; let rows = vec![ variable(" token ", "first"), variable("token", "second"), @@ -462,34 +371,19 @@ mod tests { let read = layers_of(&[level(VariableScope::Environment, rows)]); - assert_eq!( - read[0].values, - [("token".to_string(), "first".to_string())].into() - ); + assert_eq!(read[0].values, [("token".to_string(), "first".to_string())].into()); } fn set(scope: WriteScope, name: &str, value: &str) -> VariableWrite { - VariableWrite { - scope, - name: name.to_string(), - value: Some(value.to_string()), - secret: false, - } + VariableWrite { scope, name: name.to_string(), value: Some(value.to_string()), secret: false } } fn unset(name: &str) -> VariableWrite { - VariableWrite { - scope: WriteScope::Environment, - name: name.to_string(), - ..VariableWrite::default() - } + VariableWrite { scope: WriteScope::Environment, name: name.to_string(), ..VariableWrite::default() } } fn set_secret(name: &str, value: &str) -> VariableWrite { - VariableWrite { - secret: true, - ..set(WriteScope::Environment, name, value) - } + VariableWrite { secret: true, ..set(WriteScope::Environment, name, value) } } fn rows(table: &[Variable]) -> Vec<(&str, &str, VariableKind)> { @@ -502,28 +396,19 @@ mod tests { #[test] fn a_value_set_changes_its_row_and_a_secret_stays_one() { let table = [secret(" token ", "old"), variable("page", "1")]; - let writes = [ - set(WriteScope::Environment, "token", "new"), - set_secret("page", "2"), - ]; + let writes = [set(WriteScope::Environment, "token", "new"), set_secret("page", "2")]; let after = written(&table, &writes, None); assert_eq!( rows(&after), - [ - (" token ", "new", VariableKind::Secret), - ("page", "2", VariableKind::Secret) - ] + [(" token ", "new", VariableKind::Secret), ("page", "2", VariableKind::Secret)] ); } #[test] fn a_value_set_under_a_new_name_is_a_row_at_the_end() { - let writes = [ - set(WriteScope::Environment, " page ", "2"), - set_secret("key", "k"), - ]; + let writes = [set(WriteScope::Environment, " page ", "2"), set_secret("key", "k")]; let after = written(&[variable("first", "1")], &writes, None); @@ -540,53 +425,24 @@ mod tests { #[test] fn a_value_unset_takes_every_row_of_its_name_and_the_writes_go_in_order() { - let table = [ - variable("gone", "1"), - variable("kept", "2"), - variable(" gone ", "3"), - ]; + let table = [variable("gone", "1"), variable("kept", "2"), variable(" gone ", "3")]; - let after = written( - &table, - &[unset("gone"), set(WriteScope::Environment, "gone", "4")], - None, - ); + let after = written(&table, &[unset("gone"), set(WriteScope::Environment, "gone", "4")], None); - assert_eq!( - rows(&after), - [ - ("kept", "2", VariableKind::Text), - ("gone", "4", VariableKind::Text) - ] - ); + assert_eq!(rows(&after), [("kept", "2", VariableKind::Text), ("gone", "4", VariableKind::Text)]); } #[test] fn a_row_set_says_which_request_filled_it_and_another_keeps_who_did() { - let login = FilledBy { - request_id: Some("r1".to_string()), - name: "Login".to_string(), - }; - let earlier = FilledBy { - request_id: None, - name: "Earlier".to_string(), - }; - let held = |name: &str| Variable { - filled_by: Some(earlier.clone()), - ..variable(name, "1") - }; - let writes = [ - set(WriteScope::Environment, "set", "2"), - set(WriteScope::Environment, "new", "3"), - ]; + let login = FilledBy { request_id: Some("r1".to_string()), name: "Login".to_string() }; + let earlier = FilledBy { request_id: None, name: "Earlier".to_string() }; + let held = |name: &str| Variable { filled_by: Some(earlier.clone()), ..variable(name, "1") }; + let writes = [set(WriteScope::Environment, "set", "2"), set(WriteScope::Environment, "new", "3")]; let named = written(&[held("set"), held("left")], &writes, Some(&login)); let unnamed = written(&[held("set")], &writes[..1], None); - let by: Vec<_> = named - .iter() - .map(|row| row.filled_by.as_ref().unwrap().name.as_str()) - .collect(); + let by: Vec<_> = named.iter().map(|row| row.filled_by.as_ref().unwrap().name.as_str()).collect(); assert_eq!(by, ["Login", "Earlier", "Login"]); assert_eq!(unnamed[0].filled_by, Some(earlier)); } @@ -609,14 +465,8 @@ mod tests { ); let resolver = variables::Resolver::new(&layers); - assert_eq!( - resolver.fill("{{token}}/{{tenant}}/{{page}}"), - "t0k3n/acme/2" - ); - assert_eq!( - resolver.secrets(), - [("token".to_string(), "t0k3n".to_string())] - ); + assert_eq!(resolver.fill("{{token}}/{{tenant}}/{{page}}"), "t0k3n/acme/2"); + assert_eq!(resolver.secrets(), [("token".to_string(), "t0k3n".to_string())]); } /// With « Aucun », there is no environment to write to: the rest is still applied. @@ -624,28 +474,17 @@ mod tests { fn a_write_to_a_level_the_send_has_not_changes_nothing_else() { let mut layers = [level(VariableScope::Globals, vec![variable("kept", "1")])]; - apply( - &mut layers, - &[ - set(WriteScope::Collection, "nowhere", "1"), - set(WriteScope::Data, "row", "1"), - ], - ); + apply(&mut layers, &[set(WriteScope::Collection, "nowhere", "1"), set(WriteScope::Data, "row", "1")]); - assert_eq!( - rows(&layers[0].variables), - [("kept", "1", VariableKind::Text)] - ); + assert_eq!(rows(&layers[0].variables), [("kept", "1", VariableKind::Text)]); } #[test] fn local_variables_are_nearer_than_the_request_s_own() { let locals = locals_layer(&[("path".to_string(), "orders".to_string())].into()); - let resolver = variables::Resolver::new(&[ - locals, - level(VariableScope::Request, vec![variable("path", "own")]), - ]); + let resolver = + variables::Resolver::new(&[locals, level(VariableScope::Request, vec![variable("path", "own")])]); assert_eq!(resolver.fill("/{{path}}"), "/orders"); } @@ -670,11 +509,7 @@ mod tests { ..TestResult::default() }; - let shown = shown_tests( - vec![test], - &[script], - &[("token".to_string(), "t0k3n".to_string())], - ); + let shown = shown_tests(vec![test], &[script], &[("token".to_string(), "t0k3n".to_string())]); let test = &shown[0]; assert_eq!(test.name, "holds {{token}}"); @@ -682,9 +517,6 @@ mod tests { assert_eq!(test.expected.as_deref(), Some("expected {{token}}")); assert_eq!(test.actual.as_deref(), Some("actual {{token}}")); assert_eq!(test.code.as_deref(), Some("expect('{{token}}').toBe(a);")); - assert_eq!( - (test.kind, test.holder.as_deref()), - (Some(ScriptKind::Tests), Some("Pay")) - ); + assert_eq!((test.kind, test.holder.as_deref()), (Some(ScriptKind::Tests), Some("Pay"))); } } diff --git a/crates/engine/src/http/scripts/child.rs b/crates/engine/src/http/scripts/child.rs index 6029e40cb..7764791f1 100644 --- a/crates/engine/src/http/scripts/child.rs +++ b/crates/engine/src/http/scripts/child.rs @@ -21,11 +21,7 @@ const STACK: usize = 16 * 1024 * 1024; /// What the application writes to the host. #[derive(Debug, Serialize, Deserialize)] -#[serde( - tag = "type", - rename_all = "camelCase", - rename_all_fields = "camelCase" -)] +#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")] pub enum ToHost { Run { job: Box, millis: u64 }, Reply { id: u64, answer: String }, @@ -33,29 +29,14 @@ pub enum ToHost { /// What the host writes back. #[derive(Debug, Serialize, Deserialize)] -#[serde( - tag = "type", - rename_all = "camelCase", - rename_all_fields = "camelCase" -)] +#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")] pub enum FromHost { - Call { - id: u64, - kind: String, - payload: String, - }, - Log { - entry: LogEntry, - }, - Done { - outcome: Box, - }, + Call { id: u64, kind: String, payload: String }, + Log { entry: LogEntry }, + Done { outcome: Box }, } -pub(crate) fn write_line( - output: &mut W, - message: &T, -) -> std::io::Result<()> { +pub(crate) fn write_line(output: &mut W, message: &T) -> std::io::Result<()> { serde_json::to_writer(&mut *output, message)?; output.write_all(b"\n")?; output.flush() @@ -92,20 +73,13 @@ impl Host for Stdio { let mut channel = self.0.borrow_mut(); channel.last += 1; let id = channel.last; - let asked = FromHost::Call { - id, - kind: kind.to_string(), - payload: payload.to_string(), - }; + let asked = FromHost::Call { id, kind: kind.to_string(), payload: payload.to_string() }; if write_line(&mut channel.output, &asked).is_err() { return refusal("The application stopped answering"); } loop { match read_line(&mut channel.input) { - Some(ToHost::Reply { - id: answered, - answer, - }) if answered == id => return answer, + Some(ToHost::Reply { id: answered, answer }) if answered == id => return answer, Some(_) => {} None => return refusal("The application stopped answering"), } @@ -119,11 +93,7 @@ impl Host for Stdio { /// Serves until the application closes the input: `0`, or `1` when it could not answer. pub fn serve_on(input: R, output: W) -> i32 { - let channel = Rc::new(RefCell::new(Channel { - input, - output, - last: 0, - })); + let channel = Rc::new(RefCell::new(Channel { input, output, last: 0 })); let engine = Engine::new(Box::new(Stdio(Rc::clone(&channel)))); loop { let message = read_line(&mut channel.borrow_mut().input); @@ -140,9 +110,7 @@ pub fn serve_on(input: R, output: W) - ..ScriptFailure::default() }), }; - let done = FromHost::Done { - outcome: Box::new(outcome), - }; + let done = FromHost::Done { outcome: Box::new(outcome) }; if write_line(&mut channel.borrow_mut().output, &done).is_err() { return 1; } @@ -204,11 +172,7 @@ mod tests { }], ..Job::default() }; - serde_json::to_string(&ToHost::Run { - job: Box::new(job), - millis: 2000, - }) - .unwrap() + serde_json::to_string(&ToHost::Run { job: Box::new(job), millis: 2000 }).unwrap() } fn reply(id: u64) -> String { @@ -219,10 +183,7 @@ mod tests { /// What the host wrote for these lines, and the code it ended with. fn served(lines: &[String]) -> (Vec, i32) { let output = Shared::default(); - let code = serve_on( - Cursor::new(format!("{}\n", lines.join("\n"))), - output.clone(), - ); + let code = serve_on(Cursor::new(format!("{}\n", lines.join("\n"))), output.clone()); let bytes = output.0.lock().unwrap().clone(); let messages = String::from_utf8(bytes) .unwrap() @@ -239,34 +200,23 @@ mod tests { } } - const JAR: &str = - "pm.cookies.jar().getAll('https://x.y', (e, all) => env.set('n', all.length));"; + const JAR: &str = "pm.cookies.jar().getAll('https://x.y', (e, all) => env.set('n', all.length));"; #[test] fn a_job_is_answered_with_its_logs_its_calls_and_its_outcome_then_the_host_ends() { - let (messages, code) = - served(&[run_message(&format!("console.log('hi'); {JAR}")), reply(1)]); + let (messages, code) = served(&[run_message(&format!("console.log('hi'); {JAR}")), reply(1)]); assert_eq!((messages.len(), code), (3, 0)); assert!(matches!(&messages[0], FromHost::Log { entry } if entry.text == "hi")); assert!(matches!(&messages[1], FromHost::Call { id: 1, kind, .. } if kind == "jarAll")); let outcome = outcome(&messages[2]); - assert_eq!( - (&outcome.failure, outcome.writes[0].value.as_deref()), - (&None, Some("0")) - ); + assert_eq!((&outcome.failure, outcome.writes[0].value.as_deref()), (&None, Some("0"))); } #[test] fn a_line_that_does_not_read_and_an_answer_to_another_call_are_passed_over() { - let lines = [ - "not json".to_string(), - reply(9), - run_message(JAR), - "{}".to_string(), - reply(7), - reply(1), - ]; + let lines = + ["not json".to_string(), reply(9), run_message(JAR), "{}".to_string(), reply(7), reply(1)]; let (messages, code) = served(&lines); @@ -283,10 +233,7 @@ mod tests { let (messages, _) = served(&[first, second]); assert_eq!(messages.len(), 2); - assert_eq!( - outcome(&messages[1]).writes[0].value.as_deref(), - Some("yes") - ); + assert_eq!(outcome(&messages[1]).writes[0].value.as_deref(), Some("yes")); } #[test] @@ -294,11 +241,7 @@ mod tests { let (messages, _) = served(&[run_message("await pm.sendRequest('https://x.y');")]); let failure = outcome(messages.last().unwrap()).failure.clone().unwrap(); - assert!( - failure.message.contains("stopped answering"), - "{}", - failure.message - ); + assert!(failure.message.contains("stopped answering"), "{}", failure.message); } #[test] diff --git a/crates/engine/src/http/scripts/engine.rs b/crates/engine/src/http/scripts/engine.rs index 2a54f2bbb..9be8e6197 100644 --- a/crates/engine/src/http/scripts/engine.rs +++ b/crates/engine/src/http/scripts/engine.rs @@ -88,8 +88,7 @@ fn install<'js>(ctx: &Ctx<'js>, host: &Rc>>) -> rquickjs:: return Ok(None); }; let wrapped = format!("(function (module, exports, require) {{{source}\n}})"); - ctx.eval_with_options(wrapped, options(&format!("library:{name}"))) - .map(Some) + ctx.eval_with_options(wrapped, options(&format!("library:{name}"))).map(Some) }, )?, )?; @@ -116,11 +115,7 @@ fn place_in(stack: &str) -> Option<(usize, u32)> { /// What the engine threw, as a failure: the message, and the script and line it came from. fn caught(ctx: &Ctx<'_>, error: &rquickjs::Error, job: &Job, kind: FailureKind) -> ScriptFailure { - let mut failure = ScriptFailure { - kind, - message: error.to_string(), - ..ScriptFailure::default() - }; + let mut failure = ScriptFailure { kind, message: error.to_string(), ..ScriptFailure::default() }; if !matches!(error, rquickjs::Error::Exception) { return failure; } @@ -193,8 +188,7 @@ struct Loop<'js> { } fn drive(ctx: &Ctx<'_>, job: &Job, deadline: Instant, time: Duration) -> Outcome { - let failed = - |error: &rquickjs::Error| Outcome::failed(caught(ctx, error, job, FailureKind::Error)); + let failed = |error: &rquickjs::Error| Outcome::failed(caught(ctx, error, job, FailureKind::Error)); let functions = match compile(ctx, job) { Ok(functions) => functions, Err(failure) => return Outcome::failed(failure), @@ -221,13 +215,12 @@ fn drive(ctx: &Ctx<'_>, job: &Job, deadline: Instant, time: Duration) -> Outcome PromiseState::Resolved => { return match promise.result::() { Some(Ok(answer)) => { - let mut outcome: Outcome = - serde_json::from_str(&answer).unwrap_or_else(|error| { - Outcome::failed(ScriptFailure { - message: error.to_string(), - ..ScriptFailure::default() - }) - }); + let mut outcome: Outcome = serde_json::from_str(&answer).unwrap_or_else(|error| { + Outcome::failed(ScriptFailure { + message: error.to_string(), + ..ScriptFailure::default() + }) + }); if let Some(failure) = outcome.failure.as_mut() { classify(failure); } @@ -378,19 +371,11 @@ mod tests { .iter() .map(|(key, value)| ((*key).to_string(), (*value).to_string())) .collect(); - ScriptLayer { - scope, - from: String::new(), - values, - } + ScriptLayer { scope, from: String::new(), values } } fn row(key: &str, value: &str) -> ScriptRow { - ScriptRow { - key: key.to_string(), - value: value.to_string(), - ..ScriptRow::default() - } + ScriptRow { key: key.to_string(), value: value.to_string(), ..ScriptRow::default() } } /// A phase before the send: a `POST` of `{{baseUrl}}/pay?page=1`, on Staging. @@ -422,11 +407,7 @@ mod tests { } fn cookie(name: &str, value: &str) -> ScriptCookie { - ScriptCookie { - name: name.to_string(), - value: value.to_string(), - ..ScriptCookie::default() - } + ScriptCookie { name: name.to_string(), value: value.to_string(), ..ScriptCookie::default() } } /// A phase after the answer: a `402` whose body is `{"currency":"usd","items":[{"id":7}]}`. @@ -437,11 +418,7 @@ mod tests { response: Some(ScriptResponse { code: 402, reason: "Payment Required".to_string(), - headers: vec![ - row("Content-Type", "application/json"), - row("Vary", "a"), - row("vary", "b"), - ], + headers: vec![row("Content-Type", "application/json"), row("Vary", "a"), row("vary", "b")], body: r#"{"currency":"usd","items":[{"id":7}]}"#.to_string(), millis: 203, size: 37, @@ -466,9 +443,7 @@ mod tests { hosted(move || { let lines: Vec = cases .iter() - .map(|(expression, _)| { - format!("console.log(String(JSON.stringify({expression})));") - }) + .map(|(expression, _)| format!("console.log(String(JSON.stringify({expression})));")) .collect(); let (engine, seen) = engine(); let outcome = engine.run( @@ -528,16 +503,9 @@ mod tests { (request.method.as_str(), request.url.as_str()), ("PUT", "{{baseUrl}}/pay?page=1&retry=1") ); - let headers = [ - row("Accept", "application/json"), - row("X-Signature", "abc"), - row("X-Trace", "1"), - ]; + let headers = [row("Accept", "application/json"), row("X-Signature", "abc"), row("X-Trace", "1")]; assert_eq!(request.headers, headers); - assert_eq!( - (request.body.mode.as_str(), request.body.raw.as_str()), - ("raw", "{\"amount\":2}") - ); + assert_eq!((request.body.mode.as_str(), request.body.raw.as_str()), ("raw", "{\"amount\":2}")); }); } @@ -568,20 +536,11 @@ mod tests { fn a_form_s_file_part_stays_a_file_through_a_script() { hosted(|| { let mut job = before("pm.request.body.formdata.add({ key: 'note', value: 'x' });"); - let scan = ScriptRow { - part: Some("file".to_string()), - ..row("scan", "/tmp/scan.png") - }; - job.request.body = ScriptBody { - mode: "formdata".to_string(), - formdata: vec![scan], - ..ScriptBody::default() - }; + let scan = ScriptRow { part: Some("file".to_string()), ..row("scan", "/tmp/scan.png") }; + job.request.body = + ScriptBody { mode: "formdata".to_string(), formdata: vec![scan], ..ScriptBody::default() }; let parts = run(&job).request.unwrap().body.formdata; - let parts: Vec<_> = parts - .iter() - .map(|part| (part.key.as_str(), part.part.as_deref())) - .collect(); + let parts: Vec<_> = parts.iter().map(|part| (part.key.as_str(), part.part.as_deref())).collect(); assert_eq!(parts, [("scan", Some("file")), ("note", Some("text"))]); }); } @@ -596,20 +555,11 @@ mod tests { hold( before, &[ - ( - "[req.method, req.url, req.body]", - r#"["POST","{{baseUrl}}/pay?page=1",""]"#, - ), + ("[req.method, req.url, req.body]", r#"["POST","{{baseUrl}}/pay?page=1",""]"#), ("req.headers.get('accept')", r#""application/json""#), ("request.headers", r#"{"Accept":"application/json"}"#), - ( - "[request.method, request.url]", - r#"["POST","{{baseUrl}}/pay?page=1"]"#, - ), - ( - "pm.request.getHeaders({ ignoreCase: true })", - r#"{"accept":"application/json"}"#, - ), + ("[request.method, request.url]", r#"["POST","{{baseUrl}}/pay?page=1"]"#), + ("pm.request.getHeaders({ ignoreCase: true })", r#"{"accept":"application/json"}"#), ( "(pm.request.addHeader({ key: 'A', value: 'b', disabled: true }), pm.request.getHeaders({ enabled: true }))", r#"{"Accept":"application/json"}"#, @@ -728,10 +678,7 @@ mod tests { "(pm.request.headers.remove('z'), pm.request.headers.remove({ key: 'y' }), pm.request.headers.remove((row) => row.value === '3'), pm.request.headers.delete('A'), pm.request.headers.repopulate([{ key: 'last' }]), pm.request.headers)", r#"[{"key":"last","value":"","disabled":false}]"#, ), - ( - "(pm.request.headers.set('last'), pm.request.headers.get('last'))", - r#""""#, - ), + ("(pm.request.headers.set('last'), pm.request.headers.get('last'))", r#""""#), ], ); } @@ -743,14 +690,9 @@ mod tests { let asking = |header: &str| { format!("await pm.sendRequest({{ url: 'https://a.test', header: {header} }});") }; - let source = [ - "[{ key: 'A', value: '1' }]", - "{ A: 1 }", - "'A: 1\\r\\nnot a header'", - "null", - ] - .map(asking) - .join("\n"); + let source = ["[{ key: 'A', value: '1' }]", "{ A: 1 }", "'A: 1\\r\\nnot a header'", "null"] + .map(asking) + .join("\n"); assert_eq!(engine.run(&before(&source), SECONDS).failure, None); let sent: Vec<_> = seen .borrow() @@ -770,15 +712,9 @@ mod tests { hold( after, &[ - ( - "[res.status, res.statusText, res.time, res.size]", - r#"[402,"Payment Required",203,37]"#, - ), + ("[res.status, res.statusText, res.time, res.size]", r#"[402,"Payment Required",203,37]"#), // Two headers of one name are one, as a browser joins them. - ( - "res.headers", - r#"{"content-type":"application/json","vary":"a, b"}"#, - ), + ("res.headers", r#"{"content-type":"application/json","vary":"a, b"}"#), ( "[res.body === res.text(), res.json().currency, res.cookies]", r#"[true,"usd",{"sid":"42"}]"#, @@ -801,10 +737,7 @@ mod tests { "[pm.response.json().items[0].id, pm.response.stream.length, pm.response.headers.get('VARY')]", r#"[7,37,"a"]"#, ), - ( - "Object.keys(pm.response.toJSON())", - r#"["code","status","headers","body"]"#, - ), + ("Object.keys(pm.response.toJSON())", r#"["code","status","headers","body"]"#), ], ); } @@ -836,10 +769,7 @@ mod tests { hold( before, &[ - ( - "[typeof res, pm.response, typeof responseBody]", - r#"["undefined",null,"undefined"]"#, - ), + ("[typeof res, pm.response, typeof responseBody]", r#"["undefined",null,"undefined"]"#), ( "[postman.getResponseHeader('a') === undefined, postman.getResponseCookie('a') === undefined]", "[true,true]", @@ -855,9 +785,7 @@ mod tests { job.response.as_mut().unwrap().body = "".to_string(); let failure = run(&job).failure.unwrap(); assert!( - failure - .message - .starts_with("SyntaxError: The response is not JSON: "), + failure.message.starts_with("SyntaxError: The response is not JSON: "), "{}", failure.message ); @@ -942,14 +870,8 @@ mod tests { "(pm.variables.set('tenant', 'local'), [env.get('tenant'), pm.variables.toObject().tenant, env.replaceIn('{{tenant}}')])", r#"["local","local","local"]"#, ), - ( - "(pm.variables.unset('tenant'), env.get('tenant'))", - r#""near""#, - ), - ( - "(pm.variables.set('a', 1), pm.variables.clear(), env.has('a'))", - "false", - ), + ("(pm.variables.unset('tenant'), env.get('tenant'))", r#""near""#), + ("(pm.variables.set('a', 1), pm.variables.clear(), env.has('a'))", "false"), ], ); } @@ -962,38 +884,15 @@ mod tests { "for (const value of ['a', 42, true, null, undefined, { a: 1 }, [1, 2]]) pm.globals.set('v', value); const loop = {}; loop.self = loop; pm.globals.set('v', loop);", )); - let values: Vec<_> = outcome - .writes - .iter() - .map(|write| write.value.as_deref().unwrap()) - .collect(); - assert_eq!( - values, - [ - "a", - "42", - "true", - "", - "", - "{\"a\":1}", - "[1,2]", - "[object Object]" - ] - ); + let values: Vec<_> = outcome.writes.iter().map(|write| write.value.as_deref().unwrap()).collect(); + assert_eq!(values, ["a", "42", "true", "", "", "{\"a\":1}", "[1,2]", "[object Object]"]); }); } fn writes(outcome: &Outcome) -> Vec<(WriteScope, &str, Option<&str>, bool)> { let writes = outcome.writes.iter(); writes - .map(|write| { - ( - write.scope, - write.name.as_str(), - write.value.as_deref(), - write.secret, - ) - }) + .map(|write| (write.scope, write.name.as_str(), write.value.as_deref(), write.secret)) .collect() } @@ -1027,12 +926,7 @@ mod tests { let mut job = before("env.set('a', 1); pm.environment.set('b', 2);"); job.environment = None; let outcome = run(&job); - assert!( - outcome - .writes - .iter() - .all(|write| write.scope == WriteScope::Globals) - ); + assert!(outcome.writes.iter().all(|write| write.scope == WriteScope::Globals)); assert_eq!(outcome.writes.len(), 2); }); } @@ -1086,16 +980,10 @@ mod tests { hosted(|| { let (engine, _) = engine(); let outcome = engine.run(&before("pm.variables.set('started', 'yes');"), SECONDS); - assert_eq!( - outcome.locals, - [("started".to_string(), "yes".to_string())].into() - ); + assert_eq!(outcome.locals, [("started".to_string(), "yes".to_string())].into()); assert!(outcome.writes.is_empty()); - let outcome = engine.run( - &after("env.set('kept', pm.variables.get('started'));"), - SECONDS, - ); + let outcome = engine.run(&after("env.set('kept', pm.variables.get('started'));"), SECONDS); assert_eq!(outcome.writes[0].value.as_deref(), Some("yes")); }); } @@ -1135,23 +1023,15 @@ mod tests { (failed.expected.as_deref(), failed.actual.as_deref()), (Some("\"eur\""), Some("\"usd\"")) ); - assert_eq!( - (failed.script.as_deref(), failed.line), - (Some("request:tests"), Some(3)) - ); + assert_eq!((failed.script.as_deref(), failed.line), (Some("request:tests"), Some(3))); assert!(failed.message.as_deref().unwrap().contains("eur")); } #[test] fn a_test_skipped_neither_passes_nor_fails() { - let tests = - tested("test.skip('later'); pm.test.skip('never', () => { throw new Error('ran'); });"); + let tests = tested("test.skip('later'); pm.test.skip('never', () => { throw new Error('ran'); });"); assert_eq!(tests.len(), 2); - assert!( - tests - .iter() - .all(|test| test.skipped && !test.passed && test.message.is_none()) - ); + assert!(tests.iter().all(|test| test.skipped && !test.passed && test.message.is_none())); } #[test] @@ -1163,10 +1043,7 @@ mod tests { test('no body');", ); let messages: Vec<_> = tests.iter().map(|test| test.message.as_deref()).collect(); - assert_eq!( - messages, - [Some("no"), Some("plain"), Some("undefined"), None] - ); + assert_eq!(messages, [Some("no"), Some("plain"), Some("undefined"), None]); assert!(tests[0].expected.is_none() && tests[0].actual.is_none()); assert!(tests[3].passed); } @@ -1191,10 +1068,7 @@ mod tests { .iter() .map(|test| (test.name.as_str(), test.passed, test.message.as_deref())) .collect(); - assert_eq!( - read, - [("holds", true, None), ("fails", false, Some("false"))] - ); + assert_eq!(read, [("holds", true, None), ("fails", false, Some("false"))]); } /// As the prelude writes a value: a text quoted, the rest as JSON, a long one cut. @@ -1207,11 +1081,7 @@ mod tests { test('loop', () => { const e = new Error('m'); e.actual = loop; throw e; }); test('long', () => { const e = new Error('m'); e.actual = [...'x'.repeat(3000)]; throw e; });", ); - let shown: Vec<_> = tests - .iter() - .take(12) - .map(|test| test.actual.as_deref().unwrap()) - .collect(); + let shown: Vec<_> = tests.iter().take(12).map(|test| test.actual.as_deref().unwrap()).collect(); assert_eq!( shown, [ @@ -1228,18 +1098,10 @@ mod tests { "\"xxxxxxxxxx\"", "[object Object]" ] - .map(|shown| if shown == "[Function value]" { - "[Function]" - } else { - shown - }) + .map(|shown| if shown == "[Function value]" { "[Function]" } else { shown }) ); let long = tests[12].actual.as_deref().unwrap(); - assert!( - long.ends_with('…') && long.chars().count() == 2001, - "{}", - long.len() - ); + assert!(long.ends_with('…') && long.chars().count() == 2001, "{}", long.len()); } #[test] @@ -1248,10 +1110,7 @@ mod tests { ("expect(1).toBe(1)", true), ("expect(NaN).toBe(NaN)", true), ("expect({}).toBe({})", false), - ( - "expect({ a: { b: [1, 2] } }).toEqual({ a: { b: [1, 2] } })", - true, - ), + ("expect({ a: { b: [1, 2] } }).toEqual({ a: { b: [1, 2] } })", true), ("expect({ a: 1 }).toEqual({ a: 2 })", false), ("expect([1]).toStrictEqual([1])", true), ("expect([1]).toStrictEqual([2])", false), @@ -1263,10 +1122,7 @@ mod tests { ("expect([{ a: 1 }]).toContainEqual({ a: 2 })", false), ("expect('DevNotes').toMatch(/notes/i)", true), ("expect('DevNotes').toMatch('notes')", false), - ( - "expect({ a: 1, b: { c: 2, d: 3 } }).toMatchObject({ b: { c: 2 } })", - true, - ), + ("expect({ a: 1, b: { c: 2, d: 3 } }).toMatchObject({ b: { c: 2 } })", true), ("expect({ a: [1, 2] }).toMatchObject({ a: [1] })", false), ("expect({ a: 1 }).toMatchObject({ b: undefined })", false), ("expect('a').toMatchObject({ a: 1 })", false), @@ -1279,20 +1135,11 @@ mod tests { ("expect(0.1 + 0.2).toBeCloseTo(0.3)", true), ("expect(0.31).toBeCloseTo(0.3)", false), ("expect(0.31).toBeCloseTo(0.3, 1)", true), - ( - "expect(res.headers).toHaveProperty('content-type', 'application/json')", - true, - ), + ("expect(res.headers).toHaveProperty('content-type', 'application/json')", true), ("expect(res.json()).toHaveProperty('items[0].id', 7)", true), - ( - "expect(res.json()).toHaveProperty(['items', 0, 'id'])", - true, - ), + ("expect(res.json()).toHaveProperty(['items', 0, 'id'])", true), ("expect(res.json()).toHaveProperty('items[1].id')", false), - ( - "expect(res.json()).toHaveProperty('currency', 'eur')", - false, - ), + ("expect(res.json()).toHaveProperty('currency', 'eur')", false), ("expect(null).toHaveProperty('a')", false), ("expect([1, 2, 3]).toHaveLength(3)", true), ("expect('abc').toHaveLength(2)", false), @@ -1309,26 +1156,11 @@ mod tests { ("expect('NaN').toBeNaN()", false), ("expect(new TypeError('x')).toBeInstanceOf(Error)", true), ("expect({}).toBeInstanceOf(Error)", false), - ( - "expect(() => { throw new TypeError('no'); }).toThrow()", - true, - ), - ( - "expect(() => { throw new TypeError('no'); }).toThrow(TypeError)", - true, - ), - ( - "expect(() => { throw new TypeError('no'); }).toThrow(RangeError)", - false, - ), - ( - "expect(() => { throw new TypeError('no way'); }).toThrow('way')", - true, - ), - ( - "expect(() => { throw new TypeError('no way'); }).toThrow(/^way/)", - false, - ), + ("expect(() => { throw new TypeError('no'); }).toThrow()", true), + ("expect(() => { throw new TypeError('no'); }).toThrow(TypeError)", true), + ("expect(() => { throw new TypeError('no'); }).toThrow(RangeError)", false), + ("expect(() => { throw new TypeError('no way'); }).toThrow('way')", true), + ("expect(() => { throw new TypeError('no way'); }).toThrow(/^way/)", false), ("expect(() => { throw 'plain'; }).toThrow('plain')", true), ("expect(() => {}).toThrow()", false), ("expect(() => {}).not.toThrow()", true), @@ -1359,33 +1191,21 @@ mod tests { ("pm.response.to.be.notFound", false), ("pm.response.to.not.be.rateLimited", true), ("pm.response.to.have.header('content-type')", true), - ( - "pm.response.to.have.header('Content-Type', 'application/json')", - true, - ), - ( - "pm.response.to.have.header('Content-Type', 'text/html')", - false, - ), + ("pm.response.to.have.header('Content-Type', 'application/json')", true), + ("pm.response.to.have.header('Content-Type', 'text/html')", false), ("pm.response.to.have.header('X-Gone')", false), ("pm.response.to.have.body()", true), ("pm.response.to.have.body(responseBody)", true), ("pm.response.to.have.body('other')", false), ("pm.response.to.have.body(/usd/)", true), - ( - "pm.response.to.have.body({ currency: 'usd', items: [{ id: 7 }] })", - true, - ), + ("pm.response.to.have.body({ currency: 'usd', items: [{ id: 7 }] })", true), ("pm.response.to.have.body({ currency: 'eur' })", false), ("pm.response.to.have.jsonBody()", true), ("pm.response.to.have.jsonBody('items[0].id')", true), ("pm.response.to.have.jsonBody('items[0].id', 7)", true), ("pm.response.to.have.jsonBody('items[0].id', 8)", false), ("pm.response.to.have.jsonBody('gone')", false), - ( - "pm.response.to.have.jsonBody({ currency: 'usd', items: [{ id: 7 }] })", - true, - ), + ("pm.response.to.have.jsonBody({ currency: 'usd', items: [{ id: 7 }] })", true), ("pm.response.to.be.json", true), ("pm.response.to.be.withBody", true), ("pm.expect(pm.response).to.have.responseTime(203)", true), @@ -1419,26 +1239,17 @@ mod tests { #[test] fn an_error_names_its_script_and_line_and_stops_the_phase() { hosted(|| { - let mut job = - before("env.set('first', 1);\nconst b = 2;\ntokn.read();\nenv.set('never', 1);"); - job.scripts - .push(script("collection:before", "env.set('later', 1);")); + let mut job = before("env.set('first', 1);\nconst b = 2;\ntokn.read();\nenv.set('never', 1);"); + job.scripts.push(script("collection:before", "env.set('later', 1);")); let outcome = run(&job); let failure = outcome.failure.clone().unwrap(); assert_eq!( (failure.kind, failure.script.as_deref(), failure.line), (FailureKind::Error, Some("request:before"), Some(3)) ); - assert!( - failure.message.starts_with("ReferenceError: "), - "{}", - failure.message - ); + assert!(failure.message.starts_with("ReferenceError: "), "{}", failure.message); // What it did before it stopped is kept. - assert_eq!( - writes(&outcome), - [(WriteScope::Environment, "first", Some("1"), false)] - ); + assert_eq!(writes(&outcome), [(WriteScope::Environment, "first", Some("1"), false)]); }); } @@ -1446,13 +1257,9 @@ mod tests { fn an_error_of_a_later_script_names_that_one() { hosted(|| { let mut job = before("const a = 1;"); - job.scripts - .push(script("collection:before", "\nthrow new Error('x');")); + job.scripts.push(script("collection:before", "\nthrow new Error('x');")); let failure = run(&job).failure.unwrap(); - assert_eq!( - (failure.script.as_deref(), failure.line), - (Some("collection:before"), Some(2)) - ); + assert_eq!((failure.script.as_deref(), failure.line), (Some("collection:before"), Some(2))); }); } @@ -1463,14 +1270,8 @@ mod tests { ("throw 'plain';", "plain"), ("throw null;", "null"), ("throw { message: 'object' };", "Error: object"), - ( - "await Promise.reject(new TypeError('late'));", - "TypeError: late", - ), - ( - "test('t', () => {}); throw new RangeError('after');", - "RangeError: after", - ), + ("await Promise.reject(new TypeError('late'));", "TypeError: late"), + ("test('t', () => {}); throw new RangeError('after');", "RangeError: after"), ] { let failure = failure(source); assert_eq!( @@ -1487,8 +1288,7 @@ mod tests { fn a_script_that_does_not_read_is_a_syntax_failure_on_its_line_and_nothing_runs() { hosted(|| { let mut job = before("env.set('ran', 1);"); - job.scripts - .push(script("folder:before", "const ok = 1;\nif (ok {\n}")); + job.scripts.push(script("folder:before", "const ok = 1;\nif (ok {\n}")); let outcome = run(&job); let failure = outcome.failure.unwrap(); assert_eq!( @@ -1531,8 +1331,7 @@ mod tests { #[test] fn a_script_that_takes_all_memory_ends_as_a_memory_failure() { hosted(|| { - let failure = - failure("const kept = []; while (true) kept.push(new Array(1e6).fill(1));"); + let failure = failure("const kept = []; while (true) kept.push(new Array(1e6).fill(1));"); assert_eq!(failure.kind, FailureKind::Memory); }); } @@ -1542,11 +1341,7 @@ mod tests { hosted(|| { let failure = failure("await new Promise(() => {});"); assert_eq!(failure.kind, FailureKind::Timeout); - assert!( - failure.message.contains("nothing settles"), - "{}", - failure.message - ); + assert!(failure.message.contains("nothing settles"), "{}", failure.message); }); } @@ -1555,10 +1350,7 @@ mod tests { fn a_stack_names_the_script_and_the_line() { for (stack, place) in [ (" at f (script-2:12:5)\n", Some((2, 12))), - ( - " at prelude:40\n at (script-0:3)\n", - Some((0, 3)), - ), + (" at prelude:40\n at (script-0:3)\n", Some((0, 3))), (" at script-x:1\n at script-1:7\n", Some((1, 7))), (" at script-4\n", None), (" at prelude:40\n", None), @@ -1587,20 +1379,14 @@ mod tests { await new Promise((resolve) => setTimeout(resolve, 1));", )); assert_eq!(outcome.failure, None); - assert_eq!( - outcome.writes[0].value.as_deref(), - Some("tick0,now,tick,soon,late") - ); + assert_eq!(outcome.writes[0].value.as_deref(), Some("tick0,now,tick,soon,late")); }); } #[test] fn a_timer_that_throws_or_is_given_no_function_stops_the_script() { hosted(|| { - assert_eq!( - failure("setTimeout(() => { throw new Error('late'); }, 1);").message, - "Error: late" - ); + assert_eq!(failure("setTimeout(() => { throw new Error('late'); }, 1);").message, "Error: late"); assert_eq!( failure("setTimeout('code', 1);").message, "TypeError: The callback must be a function" @@ -1629,18 +1415,12 @@ mod tests { hold( before, &[ - ( - "[require('lodash').chunk([1, 2, 3], 2).length, _.chunk([1, 2, 3], 2).length]", - "[2,2]", - ), + ("[require('lodash').chunk([1, 2, 3], 2).length, _.chunk([1, 2, 3], 2).length]", "[2,2]"), ( "[require('moment')('2026-10-19').format('DD/MM/YYYY'), typeof moment]", r#"["19/10/2026","function"]"#, ), - ( - "require('chai').expect(1).to.equal(1) !== undefined", - "true", - ), + ("require('chai').expect(1).to.equal(1) !== undefined", "true"), ( "CryptoJS.SHA256('abc').toString() === require('crypto-js').SHA256('abc').toString()", "true", @@ -1650,10 +1430,7 @@ mod tests { r#""ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad""#, ), ("/^[0-9a-f-]{36}$/.test(require('uuid').v4())", "true"), - ( - "new (require('ajv'))().validate({ type: 'object', required: ['id'] }, { id: 1 })", - "true", - ), + ("new (require('ajv'))().validate({ type: 'object', required: ['id'] }, { id: 1 })", "true"), ( "[tv4.validate({ id: 1 }, { type: 'object' }), tv4.validate(1, { type: 'object' })]", "[true,false]", @@ -1666,14 +1443,8 @@ mod tests { "[require('cheerio').load('

Bonjour

')('.x').text(), typeof cheerio.load]", r#"["Bonjour","function"]"#, ), - ( - "require('csv-parse/lib/sync')('a,b\\n1,2', { columns: true })", - r#"[{"a":"1","b":"2"}]"#, - ), - ( - "require('csv-parse/sync').parse('a,b\\n1,2')", - r#"[["a","b"],["1","2"]]"#, - ), + ("require('csv-parse/lib/sync')('a,b\\n1,2', { columns: true })", r#"[{"a":"1","b":"2"}]"#), + ("require('csv-parse/sync').parse('a,b\\n1,2')", r#"[["a","b"],["1","2"]]"#), ( "[Buffer.from('DevNotes').toString('base64'), require('node:buffer').Buffer === Buffer]", r#"["RGV2Tm90ZXM=",true]"#, @@ -1686,35 +1457,17 @@ mod tests { "[require('path').join('/a', 'b', '../c'), require('path-browserify') === require('path/')]", r#"["/a/c",true]"#, ), - ( - "require('querystring').stringify({ a: 1, b: 'x y' })", - r#""a=1&b=x%20y""#, - ), - ( - "require('url').parse('https://example.com:8080/p?q=1').port", - r#""8080""#, - ), + ("require('querystring').stringify({ a: 1, b: 'x y' })", r#""a=1&b=x%20y""#), + ("require('url').parse('https://example.com:8080/p?q=1').port", r#""8080""#), ("require('util').format('%s=%d', 'a', 1)", r#""a=1""#), - ( - "require('assert').deepStrictEqual({ a: [1] }, { a: [1] })", - "undefined", - ), - ( - "require('punycode').toASCII('mañana.com')", - r#""xn--maana-pta.com""#, - ), - ( - "new (require('string_decoder').StringDecoder)('utf8').write(Buffer.from('é'))", - r#""é""#, - ), + ("require('assert').deepStrictEqual({ a: [1] }, { a: [1] })", "undefined"), + ("require('punycode').toASCII('mañana.com')", r#""xn--maana-pta.com""#), + ("new (require('string_decoder').StringDecoder)('utf8').write(Buffer.from('é'))", r#""é""#), ( "[typeof require('stream').Readable, typeof require('timers').setTimeout]", r#"["function","function"]"#, ), - ( - "[require('atob')('YQ=='), require('btoa')('a')]", - r#"["a","YQ=="]"#, - ), + ("[require('atob')('YQ=='), require('btoa')('a')]", r#"["a","YQ=="]"#), ], ); } @@ -1734,9 +1487,7 @@ mod tests { format!("require('{library}') === {global}"), format!("{global} === require('{library}')"), ] { - let outcome = run(&before(&format!( - "if (!({same})) throw new Error('not the same');" - ))); + let outcome = run(&before(&format!("if (!({same})) throw new Error('not the same');"))); assert_eq!(outcome.failure, None, "{same}"); } } @@ -1810,13 +1561,7 @@ mod tests { ); assert_eq!(outcome.failure, None); assert_eq!(outcome.writes[0].value.as_deref(), Some("undefined")); - assert!( - outcome.writes[1] - .value - .as_deref() - .unwrap() - .contains("not available here") - ); + assert!(outcome.writes[1].value.as_deref().unwrap().contains("not available here")); assert!(seen.borrow().logs[0].text.contains("not supported")); }); } @@ -1835,12 +1580,7 @@ mod tests { ), SECONDS, ); - let said: Vec<_> = seen - .borrow() - .logs - .iter() - .map(|log| (log.level, log.text.clone())) - .collect(); + let said: Vec<_> = seen.borrow().logs.iter().map(|log| (log.level, log.text.clone())).collect(); let expected = [ (LogLevel::Log, "signé {\"a\":1} 2"), (LogLevel::Error, "TypeError: x"), @@ -1852,10 +1592,7 @@ mod tests { (LogLevel::Log, "{\"a\":1}"), (LogLevel::Error, "Assertion failed not held"), ]; - assert_eq!( - said, - expected.map(|(level, text)| (level, text.to_string())) - ); + assert_eq!(said, expected.map(|(level, text)| (level, text.to_string()))); assert!( seen.borrow() .logs @@ -1887,11 +1624,7 @@ mod tests { SECONDS, ); assert_eq!(outcome.failure, None); - let values: Vec<_> = outcome - .writes - .iter() - .map(|write| write.value.as_deref()) - .collect(); + let values: Vec<_> = outcome.writes.iter().map(|write| write.value.as_deref()).collect(); assert_eq!(values, [Some("https://example.com/a"), Some("200")]); let calls = &seen.borrow().calls; assert_eq!( @@ -1911,15 +1644,8 @@ mod tests { pm.sendRequest(asked, (error, response) => env.set('callback', error.code + ' ' + response)); try { await pm.sendRequest(asked); } catch (error) { env.set('promise', error.message); }", )); - let values: Vec<_> = outcome - .writes - .iter() - .map(|write| write.value.as_deref()) - .collect(); - assert_eq!( - values, - [Some("httpScriptProtected undefined"), Some("refused")] - ); + let values: Vec<_> = outcome.writes.iter().map(|write| write.value.as_deref()).collect(); + assert_eq!(values, [Some("httpScriptProtected undefined"), Some("refused")]); }); } @@ -1941,17 +1667,8 @@ mod tests { ); let calls = &seen.borrow().calls; let kinds: Vec<_> = calls.iter().map(|(kind, _)| kind.as_str()).collect(); - assert_eq!( - kinds, - [ - "jarGet", "jarAll", "jarSet", "jarSet", "jarUnset", "jarClear" - ] - ); - assert!( - calls - .iter() - .all(|(_, payload)| payload["url"] == "https://a.test") - ); + assert_eq!(kinds, ["jarGet", "jarAll", "jarSet", "jarSet", "jarUnset", "jarClear"]); + assert!(calls.iter().all(|(_, payload)| payload["url"] == "https://a.test")); assert_eq!(calls[2].1["cookie"], json!({ "name": "two", "value": "2" })); assert_eq!( calls[3].1["cookie"], @@ -1967,11 +1684,7 @@ mod tests { assert!(run(&before("pm.execution.skipRequest();")).skip); assert!(!run(&before("")).skip); let failure = run(&after("pm.execution.skipRequest();")).failure.unwrap(); - assert!( - failure.message.contains("only before the request is sent"), - "{}", - failure.message - ); + assert!(failure.message.contains("only before the request is sent"), "{}", failure.message); }); } @@ -1983,10 +1696,7 @@ mod tests { (next.set, next.name) }; assert_eq!(next(""), (false, None)); - assert_eq!( - next("pm.execution.setNextRequest('Reçu');"), - (true, Some("Reçu".to_string())) - ); + assert_eq!(next("pm.execution.setNextRequest('Reçu');"), (true, Some("Reçu".to_string()))); assert_eq!(next("pm.execution.setNextRequest(null);"), (true, None)); }); } @@ -1999,10 +1709,7 @@ mod tests { engine.run(&before("env.set('a', 1); test('t', () => {}); pm.execution.skipRequest(); pm.execution.setNextRequest('x');"), SECONDS); let outcome = engine.run(&before(""), SECONDS); assert!( - outcome.writes.is_empty() - && outcome.tests.is_empty() - && !outcome.skip - && !outcome.next.set + outcome.writes.is_empty() && outcome.tests.is_empty() && !outcome.skip && !outcome.next.set ); }); } diff --git a/crates/engine/src/http/scripts/libraries.rs b/crates/engine/src/http/scripts/libraries.rs index 3ee862c1d..9db2a9fac 100644 --- a/crates/engine/src/http/scripts/libraries.rs +++ b/crates/engine/src/http/scripts/libraries.rs @@ -37,10 +37,7 @@ bundled! { /// The module's source, `None` for a name nothing provides. pub(crate) fn source(name: &str) -> Option<&'static str> { - LIBRARIES - .iter() - .find(|(known, _)| *known == name) - .map(|(_, source)| *source) + LIBRARIES.iter().find(|(known, _)| *known == name).map(|(_, source)| *source) } #[cfg(test)] @@ -63,11 +60,7 @@ mod tests { .unwrap(); assert_eq!(manifest.len(), LIBRARIES.len()); for module in manifest { - assert!( - source(&module.name).is_some(), - "{} is not compiled in", - module.name - ); + assert!(source(&module.name).is_some(), "{} is not compiled in", module.name); } } } diff --git a/crates/engine/src/http/scripts/model.rs b/crates/engine/src/http/scripts/model.rs index d3f415ffa..5632991bf 100644 --- a/crates/engine/src/http/scripts/model.rs +++ b/crates/engine/src/http/scripts/model.rs @@ -6,9 +6,7 @@ use std::collections::BTreeMap; use serde::{Deserialize, Serialize}; use crate::closed_enum::closed_enum; -use crate::http::model::{ - FormPart, HttpMethod, KeyValue, RequestBody, RequestDocument, RequestKind, -}; +use crate::http::model::{FormPart, HttpMethod, KeyValue, RequestBody, RequestDocument, RequestKind}; use crate::http::response::Cookie; closed_enum! { @@ -110,18 +108,11 @@ pub enum RequestFault { } fn row(key: &str, value: &str, enabled: bool) -> ScriptRow { - ScriptRow { - key: key.to_string(), - value: value.to_string(), - disabled: !enabled, - part: None, - } + ScriptRow { key: key.to_string(), value: value.to_string(), disabled: !enabled, part: None } } fn rows_of(rows: &[KeyValue]) -> Vec { - rows.iter() - .map(|kv| row(&kv.key, &kv.value, kv.enabled)) - .collect() + rows.iter().map(|kv| row(&kv.key, &kv.value, kv.enabled)).collect() } /// The script's rows back as the request's, each keeping the description of the row of its name. @@ -142,11 +133,7 @@ fn key_values(rows: &[ScriptRow], before: &[KeyValue]) -> Vec { impl ScriptBody { fn of(kind: RequestKind, document: &RequestDocument) -> Self { - let mut body = Self { - mode: "none".to_string(), - language: "text".to_string(), - ..Self::default() - }; + let mut body = Self { mode: "none".to_string(), language: "text".to_string(), ..Self::default() }; if kind == RequestKind::Graphql { body.mode = "graphql".to_string(); body.graphql = ScriptGraphql { @@ -192,20 +179,16 @@ impl ScriptBody { fn onto(&self, before: &RequestBody) -> RequestBody { match self.mode.as_str() { "none" => RequestBody::None, - "raw" if self.language.eq_ignore_ascii_case("json") => RequestBody::Json { - text: self.raw.clone(), - }, - "raw" => RequestBody::Text { - text: self.raw.clone(), - }, + "raw" if self.language.eq_ignore_ascii_case("json") => { + RequestBody::Json { text: self.raw.clone() } + } + "raw" => RequestBody::Text { text: self.raw.clone() }, "urlencoded" => { let fields = match before { RequestBody::Form { fields } => fields.as_slice(), _ => &[], }; - RequestBody::Form { - fields: key_values(&self.urlencoded, fields), - } + RequestBody::Form { fields: key_values(&self.urlencoded, fields) } } "formdata" => RequestBody::Multipart { parts: self @@ -220,9 +203,7 @@ impl ScriptBody { }) .collect(), }, - "file" => RequestBody::Binary { - path: self.file.src.clone(), - }, + "file" => RequestBody::Binary { path: self.file.src.clone() }, _ => before.clone(), } } @@ -257,10 +238,7 @@ impl ScriptRequest { if kind == RequestKind::Graphql { if self.body.mode == "graphql" { document.graphql.query.clone_from(&self.body.graphql.query); - document - .graphql - .variables - .clone_from(&self.body.graphql.variables); + document.graphql.variables.clone_from(&self.body.graphql.variables); } } else { document.body = self.body.onto(&document.body); @@ -271,10 +249,7 @@ impl ScriptRequest { /// A request a script sends by itself, its body by Postman's modes. #[must_use] pub fn document(&self) -> RequestDocument { - let mut document = RequestDocument { - url: self.url.clone(), - ..RequestDocument::default() - }; + let mut document = RequestDocument { url: self.url.clone(), ..RequestDocument::default() }; document.headers = key_values(&self.headers, &[]); document.body = self.body.onto(&RequestBody::None); document @@ -424,11 +399,7 @@ impl TestResult { }; let code = self.line.and_then(|line| { let index = usize::try_from(line).ok()?.checked_sub(1)?; - script - .source - .lines() - .nth(index) - .map(|code| code.trim().to_string()) + script.source.lines().nth(index).map(|code| code.trim().to_string()) }); Self { kind: Some(script.kind), @@ -491,10 +462,7 @@ pub struct Outcome { impl Outcome { #[must_use] pub fn failed(failure: ScriptFailure) -> Self { - Self { - failure: Some(failure), - ..Self::default() - } + Self { failure: Some(failure), ..Self::default() } } } @@ -588,10 +556,7 @@ pub enum ScriptError { #[error("A script set the method {0}, which no request is sent with")] Method(String), #[error("The scripts made the request a {method} on {environment}, which is protected")] - Protected { - method: HttpMethod, - environment: String, - }, + Protected { method: HttpMethod, environment: String }, } #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] @@ -645,10 +610,7 @@ mod tests { ("test('a', () => {});", 1), ("pm.test('a', f);\ntest ('b', f);", 2), ("test.skip('c');", 0), - ( - "const latest = 1; env.test('x'); attest(1); _test(1); my9test(1);", - 0, - ), + ("const latest = 1; env.test('x'); attest(1); _test(1); my9test(1);", 0), ("test", 0), ] { assert_eq!(tests_declared(source), count, "{source}"); @@ -691,14 +653,8 @@ mod tests { fn a_stop_read_from_an_error_that_says_little_says_as_little() { let stop = ScriptStop::of_params(¶ms(&[("failure", "unheard of"), ("line", "many")])); - assert_eq!( - (stop.kind, stop.level, stop.line), - (FailureKind::Error, None, None) - ); - assert_eq!( - (stop.name, stop.owner, stop.message.as_str()), - (None, None, "") - ); + assert_eq!((stop.kind, stop.level, stop.line), (FailureKind::Error, None, None)); + assert_eq!((stop.name, stop.owner, stop.message.as_str()), (None, None, "")); } fn script(id: &str, name: &str) -> Script { @@ -723,33 +679,19 @@ mod tests { #[test] fn a_stop_names_the_script_its_failure_names() { - let stop = ScriptStop::of( - &failure(Some("s2")), - &[script("s1", "First"), script("s2", "Second")], - ); + let stop = ScriptStop::of(&failure(Some("s2")), &[script("s1", "First"), script("s2", "Second")]); - assert_eq!( - (stop.kind, stop.line, stop.message.as_str()), - (FailureKind::Memory, Some(2), "boom") - ); - assert_eq!( - (stop.level, stop.script), - (Some(ScriptLevel::Folder), Some(ScriptKind::Tests)) - ); - assert_eq!( - (stop.name.as_deref(), stop.owner.as_deref()), - (Some("Second"), Some("f1")) - ); + assert_eq!((stop.kind, stop.line, stop.message.as_str()), (FailureKind::Memory, Some(2), "boom")); + assert_eq!((stop.level, stop.script), (Some(ScriptLevel::Folder), Some(ScriptKind::Tests))); + assert_eq!((stop.name.as_deref(), stop.owner.as_deref()), (Some("Second"), Some("f1"))); } /// A timeout names no script: with one alone to blame it is that one, with several none. #[test] fn a_stop_of_no_named_script_is_the_only_one_there_is() { let one = ScriptStop::of(&failure(None), &[script("s1", "First")]); - let several = ScriptStop::of( - &failure(Some("gone")), - &[script("s1", "First"), script("s2", "Second")], - ); + let several = + ScriptStop::of(&failure(Some("gone")), &[script("s1", "First"), script("s2", "Second")]); assert_eq!(one.name.as_deref(), Some("First")); assert_eq!((several.name, several.level), (None, None)); @@ -757,22 +699,12 @@ mod tests { #[test] fn a_test_is_placed_in_the_script_that_wrote_it_with_its_line_of_code() { - let test = TestResult { - script: Some("s1".to_string()), - line: Some(2), - ..TestResult::default() - }; + let test = TestResult { script: Some("s1".to_string()), line: Some(2), ..TestResult::default() }; let placed = test.placed(&[script("s0", "Other"), script("s1", "Auth")]); - assert_eq!( - (placed.kind, placed.level), - (Some(ScriptKind::Tests), Some(ScriptLevel::Folder)) - ); - assert_eq!( - (placed.holder.as_deref(), placed.owner.as_deref()), - (Some("Auth"), Some("f1")) - ); + assert_eq!((placed.kind, placed.level), (Some(ScriptKind::Tests), Some(ScriptLevel::Folder))); + assert_eq!((placed.holder.as_deref(), placed.owner.as_deref()), (Some("Auth"), Some("f1"))); assert_eq!(placed.code.as_deref(), Some("expect(a).toBe(2);")); } @@ -787,17 +719,10 @@ mod tests { for line in [None, Some(0), Some(9)] { let placed = on("s1", line).placed(&scripts); - assert_eq!( - (placed.holder.as_deref(), placed.code), - (Some("Auth"), None), - "{line:?}" - ); + assert_eq!((placed.holder.as_deref(), placed.code), (Some("Auth"), None), "{line:?}"); } assert_eq!(on("gone", Some(2)).placed(&scripts), on("gone", Some(2))); - assert_eq!( - TestResult::default().placed(&scripts), - TestResult::default() - ); + assert_eq!(TestResult::default().placed(&scripts), TestResult::default()); } fn header(key: &str, value: &str) -> KeyValue { @@ -815,10 +740,8 @@ mod tests { #[test] fn what_a_script_changed_is_what_the_request_sends() { - let mut document = RequestDocument { - url: "{{baseUrl}}/pay".to_string(), - ..RequestDocument::default() - }; + let mut document = + RequestDocument { url: "{{baseUrl}}/pay".to_string(), ..RequestDocument::default() }; let mut request = handed(&document); request.method = " put ".to_string(); request.url.push_str("?retry=1"); @@ -827,10 +750,7 @@ mod tests { let method = request.onto(RequestKind::Http, &mut document).unwrap(); - assert_eq!( - (method, document.url.as_str()), - (HttpMethod::Put, "{{baseUrl}}/pay?retry=1") - ); + assert_eq!((method, document.url.as_str()), (HttpMethod::Put, "{{baseUrl}}/pay?retry=1")); let sent: Vec<_> = document .headers .iter() @@ -844,9 +764,7 @@ mod tests { fn a_row_a_script_hands_back_keeps_its_description() { let mut document = RequestDocument { headers: vec![header("Accept", "application/json")], - body: RequestBody::Form { - fields: vec![header("q", "1")], - }, + body: RequestBody::Form { fields: vec![header("q", "1")] }, ..RequestDocument::default() }; let mut request = handed(&document); @@ -856,25 +774,18 @@ mod tests { request.onto(RequestKind::Http, &mut document).unwrap(); assert_eq!( - ( - document.headers[0].value.as_str(), - document.headers[0].description.as_str() - ), + (document.headers[0].value.as_str(), document.headers[0].description.as_str()), ("text/csv", "about Accept") ); - let RequestBody::Form { fields } = &document.body else { - panic!("no form") - }; + let RequestBody::Form { fields } = &document.body else { panic!("no form") }; let described: Vec<_> = fields.iter().map(|row| row.description.as_str()).collect(); assert_eq!(described, ["about q", ""]); } #[test] fn a_method_rust_does_not_send_is_refused_by_its_name_and_changes_nothing() { - let mut document = RequestDocument { - url: "https://shop.test".to_string(), - ..RequestDocument::default() - }; + let mut document = + RequestDocument { url: "https://shop.test".to_string(), ..RequestDocument::default() }; let mut request = handed(&document); request.method = "PURGE".to_string(); request.url = "https://other.test".to_string(); @@ -897,45 +808,19 @@ mod tests { }; for (body, mode, language) in [ (RequestBody::None, "none", "text"), - ( - RequestBody::Text { - text: text("hello"), - }, - "raw", - "text", - ), + (RequestBody::Text { text: text("hello") }, "raw", "text"), (RequestBody::Json { text: text("{}") }, "raw", "json"), + (RequestBody::Form { fields: vec![header("q", "1")] }, "urlencoded", "text"), ( - RequestBody::Form { - fields: vec![header("q", "1")], - }, - "urlencoded", - "text", - ), - ( - RequestBody::Multipart { - parts: vec![part("file", true), part("text", false)], - }, + RequestBody::Multipart { parts: vec![part("file", true), part("text", false)] }, "formdata", "text", ), - ( - RequestBody::Binary { - path: text("/tmp/a.bin"), - }, - "file", - "text", - ), + (RequestBody::Binary { path: text("/tmp/a.bin") }, "file", "text"), ] { - let mut document = RequestDocument { - body: body.clone(), - ..RequestDocument::default() - }; + let mut document = RequestDocument { body: body.clone(), ..RequestDocument::default() }; let request = handed(&document); - assert_eq!( - (request.body.mode.as_str(), request.body.language.as_str()), - (mode, language) - ); + assert_eq!((request.body.mode.as_str(), request.body.language.as_str()), (mode, language)); request.onto(RequestKind::Http, &mut document).unwrap(); @@ -946,9 +831,7 @@ mod tests { #[test] fn a_body_of_a_mode_rust_has_no_kind_for_stays_the_one_it_was() { let mut document = RequestDocument { - body: RequestBody::Text { - text: "kept".to_string(), - }, + body: RequestBody::Text { text: "kept".to_string() }, ..RequestDocument::default() }; let mut request = handed(&document); @@ -956,12 +839,7 @@ mod tests { request.onto(RequestKind::Http, &mut document).unwrap(); - assert_eq!( - document.body, - RequestBody::Text { - text: "kept".to_string() - } - ); + assert_eq!(document.body, RequestBody::Text { text: "kept".to_string() }); } fn graphql() -> RequestDocument { @@ -981,20 +859,14 @@ mod tests { let mut request = ScriptRequest::of(RequestKind::Graphql, HttpMethod::Post, &document); assert_eq!(request.body.mode, "graphql"); let handed = &request.body.graphql; - assert_eq!( - (handed.query.as_str(), handed.variables.as_str()), - ("{ me { id } }", "{}") - ); + assert_eq!((handed.query.as_str(), handed.variables.as_str()), ("{ me { id } }", "{}")); request.body.graphql.query = "{ me { name } }".to_string(); request.body.graphql.variables = "{\"a\":1}".to_string(); request.onto(RequestKind::Graphql, &mut document).unwrap(); assert_eq!( - ( - document.graphql.query.as_str(), - document.graphql.variables.as_str() - ), + (document.graphql.query.as_str(), document.graphql.variables.as_str()), ("{ me { name } }", "{\"a\":1}") ); } @@ -1029,19 +901,8 @@ mod tests { let document = request.document(); assert_eq!(document.url, "https://auth.test/login"); - assert_eq!( - ( - document.headers[0].key.as_str(), - document.headers[0].value.as_str() - ), - ("X-Trace", "1") - ); - assert_eq!( - document.body, - RequestBody::Json { - text: "{}".to_string() - } - ); + assert_eq!((document.headers[0].key.as_str(), document.headers[0].value.as_str()), ("X-Trace", "1")); + assert_eq!(document.body, RequestBody::Json { text: "{}".to_string() }); } #[test] @@ -1063,9 +924,6 @@ mod tests { (read.name, read.value, read.domain, read.path), (cookie.name, cookie.value, cookie.domain, cookie.path) ); - assert_eq!( - (read.expires, read.http_only, read.secure), - (cookie.expires, true, true) - ); + assert_eq!((read.expires, read.http_only, read.secure), (cookie.expires, true, true)); } } diff --git a/crates/engine/src/http/scripts/network.rs b/crates/engine/src/http/scripts/network.rs index 4236cd897..93293c57c 100644 --- a/crates/engine/src/http/scripts/network.rs +++ b/crates/engine/src/http/scripts/network.rs @@ -81,20 +81,12 @@ impl Network { } let Asked { request, script } = serde_json::from_str(payload).map_err(|error| Refusal::new(error.to_string(), None))?; - let method = request - .method - .trim() - .to_ascii_uppercase() - .parse::() - .map_err(|()| { - Refusal::new( - format!( - "The method {} is not one a request is sent with", - request.method - ), - Some("httpScriptMethod"), - ) - })?; + let method = request.method.trim().to_ascii_uppercase().parse::().map_err(|()| { + Refusal::new( + format!("The method {} is not one a request is sent with", request.method), + Some("httpScriptMethod"), + ) + })?; if !self.may_change && !method.changes_nothing() { return Err(Refusal::new( format!( @@ -116,13 +108,8 @@ impl Network { Some(FILE), )); } - let mut outgoing = send::compose( - RequestKind::Http, - method, - &document, - &settings::inherit(&[]), - ) - .map_err(|error| Refusal::new(error.to_string(), Some("httpScriptSend")))?; + let mut outgoing = send::compose(RequestKind::Http, method, &document, &settings::inherit(&[])) + .map_err(|error| Refusal::new(error.to_string(), Some("httpScriptSend")))?; outgoing.transport = self.transport; outgoing.jar = self.jar.clone().filter(|_| self.transport.use_cookies); let exchange = send::exchange(&outgoing); @@ -132,17 +119,10 @@ impl Network { cookies::apply(jar, &changes); } self.changes.extend(changes); - self.sent.push(ScriptSend { - script, - exchange, - started, - ended: Utc::now(), - answer: answer.clone(), - }); - let response = - answer.map_err(|error| Refusal::new(error.to_string(), Some("httpScriptSend")))?; - serde_json::to_value(response_of(&response)) - .map_err(|error| Refusal::new(error.to_string(), None)) + self.sent + .push(ScriptSend { script, exchange, started, ended: Utc::now(), answer: answer.clone() }); + let response = answer.map_err(|error| Refusal::new(error.to_string(), Some("httpScriptSend")))?; + serde_json::to_value(response_of(&response)).map_err(|error| Refusal::new(error.to_string(), None)) } fn jar(&mut self, kind: &str, payload: &str) -> Result { @@ -156,8 +136,8 @@ impl Network { } let asked: Asked = serde_json::from_str(payload).map_err(|error| Refusal::new(error.to_string(), None))?; - let url = Url::parse(&asked.url) - .map_err(|_| Refusal::new(format!("{} is not a URL", asked.url), None))?; + let url = + Url::parse(&asked.url).map_err(|_| Refusal::new(format!("{} is not a URL", asked.url), None))?; let Some(jar) = self.jar.as_mut() else { return Err(Refusal::new( "This request sends no cookie: its jar is switched off", @@ -174,21 +154,15 @@ impl Network { }; let changes: Vec = match kind { "jarGet" => { - let value = found(Some(&asked.name)) - .first() - .map(|cookie| cookie.value.clone()); + let value = found(Some(&asked.name)).first().map(|cookie| cookie.value.clone()); return Ok(serde_json::json!(value)); } "jarAll" => { let all: Vec = found(None).iter().map(cookie_of).collect(); - return serde_json::to_value(all) - .map_err(|error| Refusal::new(error.to_string(), None)); + return serde_json::to_value(all).map_err(|error| Refusal::new(error.to_string(), None)); } "jarSet" => cookies::received(&[set_cookie(&asked.cookie)], &url, now), - "jarUnset" => found(Some(&asked.name)) - .into_iter() - .map(Change::Remove) - .collect(), + "jarUnset" => found(Some(&asked.name)).into_iter().map(Change::Remove).collect(), "jarClear" => found(None).into_iter().map(Change::Remove).collect(), _ => return Err(Refusal::new(format!("Nothing answers {kind}"), None)), }; @@ -201,11 +175,9 @@ impl Network { /// A cookie a script sets, as the line a server would have written for it. fn set_cookie(cookie: &ScriptCookie) -> KeyValue { let mut line = format!("{}={}", cookie.name, cookie.value); - for (attribute, value) in [ - ("Path", &cookie.path), - ("Domain", &cookie.domain), - ("Expires", &cookie.expires), - ] { + for (attribute, value) in + [("Path", &cookie.path), ("Domain", &cookie.domain), ("Expires", &cookie.expires)] + { if let Some(value) = value { let _ = write!(line, "; {attribute}={value}"); } @@ -216,11 +188,7 @@ fn set_cookie(cookie: &ScriptCookie) -> KeyValue { if cookie.http_only { line.push_str("; HttpOnly"); } - KeyValue { - key: "Set-Cookie".to_string(), - value: line, - ..KeyValue::default() - } + KeyValue { key: "Set-Cookie".to_string(), value: line, ..KeyValue::default() } } fn cookie_of(cookie: &JarCookie) -> ScriptCookie { @@ -241,10 +209,7 @@ pub fn cookies_for(jar: Option<&[JarCookie]>, url: &str) -> Vec { let (Some(jar), Ok(url)) = (jar, Url::parse(url)) else { return Vec::new(); }; - cookies::matching(jar, &url, Utc::now()) - .into_iter() - .map(cookie_of) - .collect() + cookies::matching(jar, &url, Utc::now()).into_iter().map(cookie_of).collect() } /// An answer as a script reads it. @@ -279,9 +244,6 @@ impl Services for Network { } fn log(&mut self, entry: LogEntry) { - self.logs.push(LogEntry { - at: Some(Utc::now()), - ..entry - }); + self.logs.push(LogEntry { at: Some(Utc::now()), ..entry }); } } diff --git a/crates/engine/src/http/scripts/process.rs b/crates/engine/src/http/scripts/process.rs index a9451df91..ddc9f2348 100644 --- a/crates/engine/src/http/scripts/process.rs +++ b/crates/engine/src/http/scripts/process.rs @@ -41,10 +41,7 @@ pub struct Refusal { impl Refusal { #[must_use] pub fn new(message: impl Into, code: Option<&str>) -> Self { - Self { - message: message.into(), - code: code.map(str::to_string), - } + Self { message: message.into(), code: code.map(str::to_string) } } } @@ -122,20 +119,12 @@ impl ScriptProcess { let missing = || std::io::Error::other("the script host has no standard streams"); let input = child.stdin.take().ok_or_else(missing)?; let output = BufReader::new(child.stdout.take().ok_or_else(missing)?); - Ok(Self { - child: Arc::new(Mutex::new(child)), - input: Some(input), - output, - killed: Arc::default(), - }) + Ok(Self { child: Arc::new(Mutex::new(child)), input: Some(input), output, killed: Arc::default() }) } #[must_use] pub fn killer(&self) -> Killer { - Killer { - child: Arc::clone(&self.child), - killed: Arc::clone(&self.killed), - } + Killer { child: Arc::clone(&self.child), killed: Arc::clone(&self.killed) } } /// One phase, within `time`, its calls answered by `services`. @@ -169,15 +158,8 @@ impl ScriptProcess { serde_json::json!({ "error": refusal.message, "code": refusal.code }) } }; - let reply = child::ToHost::Reply { - id, - answer: answer.to_string(), - }; - if self - .input - .as_mut() - .is_none_or(|input| write_line(input, &reply).is_err()) - { + let reply = child::ToHost::Reply { id, answer: answer.to_string() }; + if self.input.as_mut().is_none_or(|input| write_line(input, &reply).is_err()) { break host_failure("The script host cannot be reached"); } } diff --git a/crates/engine/src/http/scripts/session.rs b/crates/engine/src/http/scripts/session.rs index c8a97e886..d356066a7 100644 --- a/crates/engine/src/http/scripts/session.rs +++ b/crates/engine/src/http/scripts/session.rs @@ -15,11 +15,7 @@ pub struct Session { impl Session { #[must_use] pub fn new(host: ScriptProcess, network: Network) -> Self { - Self { - host, - network, - logs: Vec::new(), - } + Self { host, network, logs: Vec::new() } } #[must_use] diff --git a/crates/engine/src/http/search.rs b/crates/engine/src/http/search.rs index 0fc1c8d39..3f494948c 100644 --- a/crates/engine/src/http/search.rs +++ b/crates/engine/src/http/search.rs @@ -56,24 +56,12 @@ pub fn rank(candidates: Vec, search: &str) -> Vec { let mut scored: Vec<(u8, DateTime, RequestHit)> = candidates .into_iter() .filter_map(|candidate| { - let score = if needle.is_empty() { - Some(0) - } else { - score(&candidate.hit, &needle) - }; + let score = if needle.is_empty() { Some(0) } else { score(&candidate.hit, &needle) }; score.map(|score| (score, candidate.updated_at, candidate.hit)) }) .collect(); - scored.sort_by(|a, b| { - a.0.cmp(&b.0) - .then(b.1.cmp(&a.1)) - .then_with(|| a.2.name.cmp(&b.2.name)) - }); - scored - .into_iter() - .take(MAX_HITS) - .map(|(_, _, hit)| hit) - .collect() + scored.sort_by(|a, b| a.0.cmp(&b.0).then(b.1.cmp(&a.1)).then_with(|| a.2.name.cmp(&b.2.name))); + scored.into_iter().take(MAX_HITS).map(|(_, _, hit)| hit).collect() } #[cfg(test)] @@ -81,8 +69,7 @@ mod tests { use super::*; fn at(hours: i64) -> DateTime { - crate::db::iso8601::parse("2026-07-25T09:00:00.000Z").unwrap() - + chrono::TimeDelta::hours(hours) + crate::db::iso8601::parse("2026-07-25T09:00:00.000Z").unwrap() + chrono::TimeDelta::hours(hours) } fn candidate(name: &str, url: &str, place: &[&str], edited: i64) -> Candidate { @@ -118,16 +105,7 @@ mod tests { let hits = rank(candidates, " ÓRDER "); - assert_eq!( - names(&hits), - [ - "Ordered items", - "Shop orders", - "Reorder", - "List all", - "Health" - ] - ); + assert_eq!(names(&hits), ["Ordered items", "Shop orders", "Reorder", "List all", "Health"]); } /// A tie goes to the one edited last, then to its name. diff --git a/crates/engine/src/http/send.rs b/crates/engine/src/http/send.rs index 2bc864d0f..88ac9161f 100644 --- a/crates/engine/src/http/send.rs +++ b/crates/engine/src/http/send.rs @@ -17,8 +17,8 @@ use url::Url; use super::cookies::{self, Change, JarCookie}; use super::graphql::{self, GraphqlDocument, GraphqlResult}; use super::model::{ - HeaderFault, HttpMethod, KeyPlace, KeyValue, RequestAuth, RequestBody, RequestDocument, - RequestKind, header_fault, + HeaderFault, HttpMethod, KeyPlace, KeyValue, RequestAuth, RequestBody, RequestDocument, RequestKind, + header_fault, }; use super::response::{self, Cookie}; use super::scripts::model::ScriptsAnswer; @@ -126,11 +126,7 @@ pub struct Exchange { } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde( - tag = "kind", - rename_all = "camelCase", - rename_all_fields = "camelCase" -)] +#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")] pub enum SentBody { None, /// Up to `SHOWN_LIMIT`. @@ -188,11 +184,7 @@ pub enum SendError { SocketScheme { twin: Option }, /// A header that cannot be built: named, with who wrote it, rather than blamed on the URL. #[error("The header {name} cannot be sent: its {fault:?} is not valid")] - Header { - name: String, - fault: HeaderFault, - set_by: SetBy, - }, + Header { name: String, fault: HeaderFault, set_by: SetBy }, } /// Who put a header on a request that no row of its own wrote. @@ -254,17 +246,11 @@ pub struct Outgoing { impl Outgoing { pub fn timeout(&self) -> Limit { - Limit { - value: self.transport.timeout_ms, - set_by: self.limits.timeout.clone(), - } + Limit { value: self.transport.timeout_ms, set_by: self.limits.timeout.clone() } } pub fn redirects(&self) -> Limit { - Limit { - value: self.transport.max_redirects, - set_by: self.limits.redirects.clone(), - } + Limit { value: self.transport.max_redirects, set_by: self.limits.redirects.clone() } } } @@ -283,8 +269,7 @@ pub enum Part { } fn sent(rows: &[KeyValue]) -> impl Iterator { - rows.iter() - .filter(|row| row.enabled && !row.key.trim().is_empty()) + rows.iter().filter(|row| row.enabled && !row.key.trim().is_empty()) } /// Its size is checked before it is read, and the read stops past it: the file may grow. @@ -296,9 +281,7 @@ fn read(path: &str) -> Result, SendError> { return Err(SendError::FileTooLarge(path.to_string())); } let mut bytes = Vec::new(); - file.take(limit + 1) - .read_to_end(&mut bytes) - .map_err(unreadable)?; + file.take(limit + 1).read_to_end(&mut bytes).map_err(unreadable)?; if bytes.len() as u64 > limit { return Err(SendError::FileTooLarge(path.to_string())); } @@ -306,11 +289,7 @@ fn read(path: &str) -> Result, SendError> { } /// The first `{{variable}}` left in what will be sent, in reading order: one no level sets. -fn first_variable( - kind: RequestKind, - document: &RequestDocument, - inherited: &Inherited, -) -> Option { +fn first_variable(kind: RequestKind, document: &RequestDocument, inherited: &Inherited) -> Option { variables::texts(kind, document, inherited) .into_iter() .find_map(|text| variables::names_in(text).into_iter().next()) @@ -319,19 +298,12 @@ fn first_variable( /// `api.example.com/users` is sent as `http://api.example.com/users`, as a browser would. fn parse_url(typed: &str) -> Result { let typed = typed.trim(); - let url = if typed.contains("://") { - Url::parse(typed) - } else { - Url::parse(&format!("http://{typed}")) - }; + let url = if typed.contains("://") { Url::parse(typed) } else { Url::parse(&format!("http://{typed}")) }; let url = url.map_err(|error| SendError::InvalidUrl(error.to_string()))?; // ⚠️ Why, never the URL itself: a detail is shown and logged, and a URL carries a key in // its query or a password before its host. if !matches!(url.scheme(), "http" | "https") { - return Err(SendError::InvalidUrl(format!( - "the scheme {}", - url.scheme() - ))); + return Err(SendError::InvalidUrl(format!("the scheme {}", url.scheme()))); } if url.host_str().is_none_or(str::is_empty) { return Err(SendError::InvalidUrl("no host".to_string())); @@ -350,61 +322,35 @@ fn content_type(kind: RequestKind, document: &RequestDocument) -> Option<&'stati /// Every header of a request and who wrote it: the inherited ones, its own over them by name, /// then, each only where no row sets it, the auth's, the body's type and the application's own. -fn written( - document: &RequestDocument, - inherited: &Inherited, - content_type: Option<&str>, -) -> Vec { +fn written(document: &RequestDocument, inherited: &Inherited, content_type: Option<&str>) -> Vec { let mut headers: Vec = Vec::new(); let mut set = |name: &str, value: &str, by: Wrote| { headers.retain(|known| !known.name.eq_ignore_ascii_case(name)); - headers.push(Written { - name: name.to_string(), - value: value.to_string(), - by, - }); + headers.push(Written { name: name.to_string(), value: value.to_string(), by }); }; for known in &inherited.headers { - set( - known.header.key.trim(), - &known.header.value, - Wrote::Above(known.from.clone()), - ); + set(known.header.key.trim(), &known.header.value, Wrote::Above(known.from.clone())); } for row in sent(&document.headers) { set(row.key.trim(), &row.value, Wrote::Request); } let mut unless_set = |name: &str, value: String, by: Wrote| { - if !headers - .iter() - .any(|known| known.name.eq_ignore_ascii_case(name)) - { - headers.push(Written { - name: name.to_string(), - value, - by, - }); + if !headers.iter().any(|known| known.name.eq_ignore_ascii_case(name)) { + headers.push(Written { name: name.to_string(), value, by }); } }; match auth_of(document, inherited) { RequestAuth::Basic { username, password } => { - let pair = - base64::engine::general_purpose::STANDARD.encode(format!("{username}:{password}")); + let pair = base64::engine::general_purpose::STANDARD.encode(format!("{username}:{password}")); unless_set("Authorization", format!("Basic {pair}"), Wrote::Auth); } RequestAuth::Bearer { token } => { - unless_set( - "Authorization", - format!("Bearer {}", token.trim()), - Wrote::Auth, - ); + unless_set("Authorization", format!("Bearer {}", token.trim()), Wrote::Auth); + } + RequestAuth::ApiKey { name, value, place: KeyPlace::Header } if !name.trim().is_empty() => { + unless_set(name.trim(), value.clone(), Wrote::Auth); } - RequestAuth::ApiKey { - name, - value, - place: KeyPlace::Header, - } if !name.trim().is_empty() => unless_set(name.trim(), value.clone(), Wrote::Auth), _ => {} } if let Some(content_type) = content_type { @@ -428,8 +374,7 @@ pub fn written_for_code( inherited: &Inherited, ) -> Vec<(String, String)> { let basic = matches!(auth_of(document, inherited), RequestAuth::Basic { .. }); - let multipart = - kind == RequestKind::Http && matches!(document.body, RequestBody::Multipart { .. }); + let multipart = kind == RequestKind::Http && matches!(document.body, RequestBody::Multipart { .. }); written(document, inherited, content_type(kind, document)) .into_iter() .filter(|header| header.by != Wrote::Default) @@ -453,23 +398,14 @@ fn host_of(url: &Url) -> Option { if !variables::names_in(host).is_empty() { return None; } - Some( - url.port() - .map_or_else(|| host.to_string(), |port| format!("{host}:{port}")), - ) + Some(url.port().map_or_else(|| host.to_string(), |port| format!("{host}:{port}"))) } /// What a request sends without a row of its own, read from what `compose` writes: the two /// cannot disagree. Nothing is refused here: a URL that does not read yet has no `Host`. -pub fn implied( - kind: RequestKind, - document: &RequestDocument, - inherited: &Inherited, -) -> Vec { +pub fn implied(kind: RequestKind, document: &RequestDocument, inherited: &Inherited) -> Vec { let headers = written(document, inherited, content_type(kind, document)); - let typed_host = headers - .iter() - .any(|known| known.name.eq_ignore_ascii_case("host")); + let typed_host = headers.iter().any(|known| known.name.eq_ignore_ascii_case("host")); let mut listed: Vec = headers .into_iter() .filter_map(|header| { @@ -479,12 +415,7 @@ pub fn implied( Wrote::Body => (ImpliedSource::Body, None), Wrote::Default => (ImpliedSource::Default, None), }; - Some(ImpliedHeader { - name: header.name, - value: header.value, - source, - from, - }) + Some(ImpliedHeader { name: header.name, value: header.value, source, from }) }) .collect(); let url = match kind { @@ -523,11 +454,7 @@ pub fn compose( }; let auth = auth_of(document, inherited); - if let RequestAuth::ApiKey { - name, - value, - place: KeyPlace::Query, - } = auth + if let RequestAuth::ApiKey { name, value, place: KeyPlace::Query } = auth && !name.trim().is_empty() { url.query_pairs_mut().append_pair(name.trim(), value); @@ -538,8 +465,7 @@ pub fn compose( None => body_of(&document.body)?, }; // A multipart type carries its boundary, which reqwest alone knows. - let implied = - content_type(kind, document).filter(|_| !matches!(body, OutgoingBody::Multipart(_))); + let implied = content_type(kind, document).filter(|_| !matches!(body, OutgoingBody::Multipart(_))); let headers = written(document, inherited, implied); // ⚠️ Before the client builds it: its builder says « invalid URL » for a header it refuses. if let Some((header, fault)) = headers @@ -555,10 +481,7 @@ pub fn compose( }, }); } - let headers = headers - .into_iter() - .map(|header| (header.name, header.value)) - .collect(); + let headers = headers.into_iter().map(|header| (header.name, header.value)).collect(); let secrets = match auth { RequestAuth::ApiKey { name, .. } if !name.trim().is_empty() => { @@ -582,14 +505,8 @@ pub fn compose( jar: None, transport: inherited.transport.over(&document.transport), limits: Limits { - timeout: set_by( - document.transport.timeout_ms.is_some(), - &inherited.limits.timeout, - ), - redirects: set_by( - document.transport.max_redirects.is_some(), - &inherited.limits.redirects, - ), + timeout: set_by(document.transport.timeout_ms.is_some(), &inherited.limits.timeout), + redirects: set_by(document.transport.max_redirects.is_some(), &inherited.limits.redirects), }, }) } @@ -606,11 +523,7 @@ fn graphql_body(graphql: &GraphqlDocument, url: &mut Url) -> Result Result { } RequestBody::Multipart { parts } => { let mut fields = Vec::new(); - for part in parts - .iter() - .filter(|part| part.enabled && !part.key.trim().is_empty()) - { + for part in parts.iter().filter(|part| part.enabled && !part.key.trim().is_empty()) { let value = if part.file { Part::File { name: Path::new(&part.value) @@ -659,16 +569,9 @@ fn is_text(content_type: Option<&str>, bytes: &[u8]) -> bool { }; let essence = kind.split(';').next().unwrap_or_default().trim(); if essence.starts_with("text/") - || [ - "json", - "xml", - "javascript", - "x-www-form-urlencoded", - "graphql", - "yaml", - ] - .iter() - .any(|word| essence.contains(word)) + || ["json", "xml", "javascript", "x-www-form-urlencoded", "graphql", "yaml"] + .iter() + .any(|word| essence.contains(word)) { return true; } @@ -730,10 +633,7 @@ pub(crate) fn cause_of( } } let text = current.to_string().to_ascii_lowercase(); - if text.contains("dns error") - || text.contains("failed to lookup") - || text.contains("no such host") - { + if text.contains("dns error") || text.contains("failed to lookup") || text.contains("no such host") { return Some(SendError::Unresolved(current.to_string())); } if text.contains("certificate") || text.contains("invalid peer") { @@ -813,16 +713,12 @@ pub fn exchange(outgoing: &Outgoing) -> Exchange { let body = match &outgoing.body { OutgoingBody::None => SentBody::None, OutgoingBody::Bytes(bytes) => match std::str::from_utf8(bytes) { - Ok(text) => SentBody::Text { - text: hide(&text.chars().take(SHOWN_LIMIT).collect::()), - }, - Err(_) => SentBody::Bytes { - size: u32::try_from(bytes.len()).unwrap_or(u32::MAX), - }, - }, - OutgoingBody::Multipart(parts) => SentBody::Multipart { - fields: parts.iter().map(|(key, _)| key.clone()).collect(), + Ok(text) => SentBody::Text { text: hide(&text.chars().take(SHOWN_LIMIT).collect::()) }, + Err(_) => SentBody::Bytes { size: u32::try_from(bytes.len()).unwrap_or(u32::MAX) }, }, + OutgoingBody::Multipart(parts) => { + SentBody::Multipart { fields: parts.iter().map(|(key, _)| key.clone()).collect() } + } }; Exchange { method: outgoing.method, @@ -830,11 +726,7 @@ pub fn exchange(outgoing: &Outgoing) -> Exchange { headers: outgoing .headers .iter() - .map(|(key, value)| KeyValue { - key: key.clone(), - value: hide(value), - ..KeyValue::default() - }) + .map(|(key, value)| KeyValue { key: key.clone(), value: hide(value), ..KeyValue::default() }) .collect(), body, } @@ -850,20 +742,10 @@ struct Hop { } /// What a redirect to another host does not carry over, as a browser drops them. -const NOT_ACROSS_HOSTS: [&str; 5] = [ - "authorization", - "cookie", - "cookie2", - "proxy-authorization", - "www-authenticate", -]; +const NOT_ACROSS_HOSTS: [&str; 5] = + ["authorization", "cookie", "cookie2", "proxy-authorization", "www-authenticate"]; /// What describes a body a 301, 302 or 303 leaves behind. -const OF_THE_BODY: [&str; 4] = [ - "content-type", - "content-length", - "content-encoding", - "transfer-encoding", -]; +const OF_THE_BODY: [&str; 4] = ["content-type", "content-length", "content-encoding", "transfer-encoding"]; fn without(headers: &mut Vec<(String, String)>, names: &[&str]) { headers.retain(|(name, _)| !names.iter().any(|gone| name.eq_ignore_ascii_case(gone))); @@ -893,19 +775,13 @@ impl Hop { 307 | 308 => true, _ => return None, }; - let location = headers - .iter() - .find(|header| header.key.eq_ignore_ascii_case("location"))?; + let location = headers.iter().find(|header| header.key.eq_ignore_ascii_case("location"))?; let url = self.url.join(location.value.trim()).ok()?; if !matches!(url.scheme(), "http" | "https") { return None; } - let mut next = Self { - method: self.method.clone(), - url, - headers: self.headers.clone(), - body: self.body.clone(), - }; + let mut next = + Self { method: self.method.clone(), url, headers: self.headers.clone(), body: self.body.clone() }; if !keeps_body { next.body = OutgoingBody::None; without(&mut next.headers, &OF_THE_BODY); @@ -928,11 +804,7 @@ impl Hop { /// The jar's `Cookie` for this hop's URL, unless one is typed: what is typed wins, as for /// `Authorization`. fn cookie(&self, jar: Option<&[JarCookie]>) -> Option { - if self - .headers - .iter() - .any(|(name, _)| name.eq_ignore_ascii_case("cookie")) - { + if self.headers.iter().any(|(name, _)| name.eq_ignore_ascii_case("cookie")) { return None; } cookies::header_for(jar?, &self.url, Utc::now()) @@ -968,9 +840,7 @@ fn request(client: &reqwest::Client, hop: &Hop, cookie: Option<&str>) -> reqwest fn file_part(name: &str, bytes: &[u8]) -> reqwest::multipart::Part { let part = || reqwest::multipart::Part::bytes(bytes.to_vec()).file_name(name.to_string()); // Every type of the table parses; a refusal would only leave reqwest's own default. - part() - .mime_str(&super::model::part_type(name)) - .unwrap_or_else(|_| part()) + part().mime_str(&super::model::part_type(name)).unwrap_or_else(|_| part()) } /// A client per send, for its TLS. It follows no redirect: `send` does, a hop at a time. @@ -1046,22 +916,14 @@ impl Chain { } let status = response.status().as_u16(); let Some(next) = self.follows.then(|| hop.after(status, &headers)).flatten() else { - return Ok(Arrival { - response, - headers, - redirects, - cookies, - }); + return Ok(Arrival { response, headers, redirects, cookies }); }; if redirects.len() >= usize::try_from(self.most.value).unwrap_or(usize::MAX) { return Err(SendError::TooManyRedirects(self.most)); } let set: Vec = response::cookies(&headers) .into_iter() - .map(|cookie| Cookie { - from: Some(hop.url.to_string()), - ..cookie - }) + .map(|cookie| Cookie { from: Some(hop.url.to_string()), ..cookie }) .collect(); redirects.push(Redirect { status, @@ -1075,10 +937,7 @@ impl Chain { } } -async fn send( - mut outgoing: Outgoing, - changes: Arc>>, -) -> Result { +async fn send(mut outgoing: Outgoing, changes: Arc>>) -> Result { install_crypto(); let jar = outgoing.jar.take(); let mut exchange = exchange(&outgoing); @@ -1105,12 +964,7 @@ async fn send( let echoed = super::history::sent_secrets(&exchange, &outgoing.secrets); let secret_values = outgoing.secret_values.clone(); - let Arrival { - mut response, - headers, - redirects, - cookies: set_on_the_way, - } = chain.follow(hop).await?; + let Arrival { mut response, headers, redirects, cookies: set_on_the_way } = chain.follow(hop).await?; let failure = |error: reqwest::Error| failure(&error, &timeout); let status = response.status(); let url = response.url().to_string(); @@ -1145,9 +999,7 @@ async fn send( let pretty = (language == Language::Json && !cut) .then(|| response::pretty_json(&shown)) .flatten(); - let graphql = (is_graphql && !cut) - .then(|| graphql::result(&shown)) - .flatten(); + let graphql = (is_graphql && !cut).then(|| graphql::result(&shown)).flatten(); Ok(Received { response: SentResponse { @@ -1156,10 +1008,7 @@ async fn send( millis, size: u32::try_from(bytes.len()).unwrap_or(u32::MAX), url, - cookies: set_on_the_way - .into_iter() - .chain(response::cookies(&headers)) - .collect(), + cookies: set_on_the_way.into_iter().chain(response::cookies(&headers)).collect(), headers, cut, body: shown, @@ -1172,22 +1021,15 @@ async fn send( graphql, scripts: ScriptsAnswer::default(), }, - kept: Kept { - content_type, - bytes, - secret_values, - echoed, - }, + kept: Kept { content_type, bytes, secret_values, echoed }, }) } fn with_cookie(exchange: &mut Exchange, line: Option) { if let Some(line) = line { - exchange.headers.push(KeyValue { - key: "Cookie".to_string(), - value: line, - ..KeyValue::default() - }); + exchange + .headers + .push(KeyValue { key: "Cookie".to_string(), value: line, ..KeyValue::default() }); } } @@ -1195,13 +1037,8 @@ fn with_cookie(exchange: &mut Exchange, line: Option) { /// hops did to the jar. pub(crate) async fn alone(outgoing: Outgoing) -> (Result, Vec) { let changes: Arc>> = Arc::default(); - let answer = send(outgoing, Arc::clone(&changes)) - .await - .map(|received| received.response); - let changes = changes - .lock() - .map(|mut set| std::mem::take(&mut *set)) - .unwrap_or_default(); + let answer = send(outgoing, Arc::clone(&changes)).await.map(|received| received.response); + let changes = changes.lock().map(|mut set| std::mem::take(&mut *set)).unwrap_or_default(); (answer, changes) } @@ -1219,11 +1056,7 @@ pub struct Sending { /// A task aborted was cancelled; one that panicked fell, which a cancel must not hide. fn ended(error: &tokio::task::JoinError) -> SendError { - if error.is_panic() { - SendError::Fell - } else { - SendError::Cancelled - } + if error.is_panic() { SendError::Fell } else { SendError::Cancelled } } impl Sending { @@ -1240,32 +1073,23 @@ impl Sending { let task = runtime.spawn(send(outgoing, Arc::clone(&changes))); let number = self.started.fetch_add(1, Ordering::Relaxed); if let Ok(mut running) = self.running.lock() - && let Some((_, previous)) = - running.insert(id.to_string(), (number, task.abort_handle())) + && let Some((_, previous)) = running.insert(id.to_string(), (number, task.abort_handle())) { previous.abort(); } let answer = task.await; if let Ok(mut running) = self.running.lock() - && running - .get(id) - .is_some_and(|(current, _)| *current == number) + && running.get(id).is_some_and(|(current, _)| *current == number) { running.remove(id); } - let answer = answer - .map_err(|error| ended(&error)) - .flatten() - .map(|received| { - if let Ok(mut bodies) = self.bodies.lock() { - bodies.insert(id.to_string(), Arc::new(received.kept)); - } - received.response - }); - let changes = changes - .lock() - .map(|mut set| std::mem::take(&mut *set)) - .unwrap_or_default(); + let answer = answer.map_err(|error| ended(&error)).flatten().map(|received| { + if let Ok(mut bodies) = self.bodies.lock() { + bodies.insert(id.to_string(), Arc::new(received.kept)); + } + received.response + }); + let changes = changes.lock().map(|mut set| std::mem::take(&mut *set)).unwrap_or_default(); (answer, changes) } @@ -1320,12 +1144,10 @@ impl Sending { pub fn image(&self, id: &str) -> Option { let kept = self.kept(id)?; let kind = kept.content_type.as_deref()?.split(';').next()?.trim(); - (kind.to_ascii_lowercase().starts_with("image/") && kept.bytes.len() <= IMAGE_LIMIT).then( - || { - let encoded = base64::engine::general_purpose::STANDARD.encode(&kept.bytes); - format!("data:{kind};base64,{encoded}") - }, - ) + (kind.to_ascii_lowercase().starts_with("image/") && kept.bytes.len() <= IMAGE_LIMIT).then(|| { + let encoded = base64::engine::general_purpose::STANDARD.encode(&kept.bytes); + format!("data:{kind};base64,{encoded}") + }) } /// The text of an answer made a note: what the request sent as a secret masked wherever it @@ -1340,10 +1162,7 @@ impl Sending { echoed.sort_by_key(|value| std::cmp::Reverse(value.len())); } let masked = super::history::masked_echo(&hidden, &echoed); - NoteText { - masked: masked != text, - text: masked, - } + NoteText { masked: masked != text, text: masked } } fn kept(&self, id: &str) -> Option> { @@ -1365,33 +1184,19 @@ mod tests { use crate::http::transport::TransportSettings; fn row(key: &str, value: &str) -> KeyValue { - KeyValue { - key: key.to_string(), - value: value.to_string(), - ..KeyValue::default() - } + KeyValue { key: key.to_string(), value: value.to_string(), ..KeyValue::default() } } fn off(key: &str) -> KeyValue { - KeyValue { - enabled: false, - ..row(key, "x") - } + KeyValue { enabled: false, ..row(key, "x") } } fn document(url: &str) -> RequestDocument { - RequestDocument { - url: url.to_string(), - ..RequestDocument::default() - } + RequestDocument { url: url.to_string(), ..RequestDocument::default() } } fn origin(name: &str) -> HttpOrigin { - HttpOrigin { - kind: HttpItemKind::Collection, - id: name.to_lowercase(), - name: name.to_string(), - } + HttpOrigin { kind: HttpItemKind::Collection, id: name.to_lowercase(), name: name.to_string() } } fn above(settings: ContainerSettings) -> Inherited { @@ -1399,10 +1204,7 @@ mod tests { } fn headers_above(rows: Vec) -> Inherited { - above(ContainerSettings { - headers: rows, - ..ContainerSettings::default() - }) + above(ContainerSettings { headers: rows, ..ContainerSettings::default() }) } fn post(document: &RequestDocument, inherited: &Inherited) -> Result { @@ -1434,10 +1236,9 @@ mod tests { "not a url with spaces://", ] { match post(&document(url), &inherit(&[])) { - Err(SendError::InvalidUrl(reason)) => assert!( - !reason.contains("s3cret") && !reason.contains("hosts"), - "{url}: {reason}" - ), + Err(SendError::InvalidUrl(reason)) => { + assert!(!reason.contains("s3cret") && !reason.contains("hosts"), "{url}: {reason}"); + } other => panic!("{url}: {other:?}"), } } @@ -1452,10 +1253,8 @@ mod tests { let in_url = post(&held, &inherit(&[])); held.url = "https://shop.test/".to_string(); let in_header = post(&held, &inherit(&[])); - let above = post( - &document("https://shop.test/"), - &headers_above(vec![row("X-Tenant", "{{tenant}}")]), - ); + let above = + post(&document("https://shop.test/"), &headers_above(vec![row("X-Tenant", "{{tenant}}")])); assert_eq!(in_url, Err(SendError::Variable("path".to_string()))); assert_eq!(in_header, Err(SendError::Variable("token".to_string()))); @@ -1467,18 +1266,10 @@ mod tests { #[test] fn its_own_headers_go_over_the_inherited_ones_by_name() { let mut held = document("https://shop.test/"); - held.headers = vec![ - row("x-tenant", "mine"), - off("X-Debug"), - row(" ", "unnamed"), - row(" X-Own ", "1"), - ]; - - let sent = post( - &held, - &headers_above(vec![row("X-Tenant", "theirs"), row("X-Debug", "1")]), - ) - .unwrap(); + held.headers = + vec![row("x-tenant", "mine"), off("X-Debug"), row(" ", "unnamed"), row(" X-Own ", "1")]; + + let sent = post(&held, &headers_above(vec![row("X-Tenant", "theirs"), row("X-Debug", "1")])).unwrap(); assert_eq!(value(&sent, "X-Tenant"), Some("mine")); assert_eq!(value(&sent, "X-Debug"), Some("1")); @@ -1490,25 +1281,14 @@ mod tests { /// own already writes it — and an API key's name is what the history masks. #[test] fn the_auth_becomes_a_header_or_a_query_pair_unless_a_row_writes_it() { - let with = |auth: RequestAuth| RequestDocument { - auth, - ..document("https://shop.test/a?x=1") - }; + let with = |auth: RequestAuth| RequestDocument { auth, ..document("https://shop.test/a?x=1") }; let basic = post( - &with(RequestAuth::Basic { - username: "ada".to_string(), - password: "pw".to_string(), - }), - &inherit(&[]), - ) - .unwrap(); - let bearer = post( - &with(RequestAuth::Bearer { - token: " t0k3n ".to_string(), - }), + &with(RequestAuth::Basic { username: "ada".to_string(), password: "pw".to_string() }), &inherit(&[]), ) .unwrap(); + let bearer = + post(&with(RequestAuth::Bearer { token: " t0k3n ".to_string() }), &inherit(&[])).unwrap(); let header_key = post( &with(RequestAuth::ApiKey { name: " X-Api-Key ".to_string(), @@ -1539,37 +1319,24 @@ mod tests { let inherited = post( &document("https://shop.test/"), &above(ContainerSettings { - auth: RequestAuth::Bearer { - token: "above".to_string(), - }, + auth: RequestAuth::Bearer { token: "above".to_string() }, ..ContainerSettings::default() }), ) .unwrap(); - let mut typed = with(RequestAuth::Bearer { - token: "t".to_string(), - }); + let mut typed = with(RequestAuth::Bearer { token: "t".to_string() }); typed.headers = vec![row("authorization", "Custom x")]; let typed = post(&typed, &inherit(&[])).unwrap(); assert_eq!(value(&basic, "Authorization"), Some("Basic YWRhOnB3")); assert_eq!(value(&bearer, "Authorization"), Some("Bearer t0k3n")); assert_eq!( - ( - value(&header_key, "X-Api-Key"), - header_key.secrets.as_slice() - ), + (value(&header_key, "X-Api-Key"), header_key.secrets.as_slice()), (Some("k"), ["x-api-key".to_string()].as_slice()) ); - assert_eq!( - query_key.url.as_str(), - "https://shop.test/a?x=1&api+key=k%261" - ); + assert_eq!(query_key.url.as_str(), "https://shop.test/a?x=1&api+key=k%261"); assert_eq!(query_key.secrets, ["api key"]); - assert_eq!( - (unnamed_key.url.as_str(), unnamed_key.secrets.len()), - ("https://shop.test/a?x=1", 0) - ); + assert_eq!((unnamed_key.url.as_str(), unnamed_key.secrets.len()), ("https://shop.test/a?x=1", 0)); assert_eq!(value(&inherited, "Authorization"), Some("Bearer above")); assert_eq!(value(&typed, "Authorization"), Some("Custom x")); } @@ -1588,27 +1355,18 @@ mod tests { let sent = post(&unnamed, &inherit(&[])).unwrap(); let names: Vec<&str> = sent.headers.iter().map(|(name, _)| name.as_str()).collect(); - assert_eq!( - (names, sent.secrets.len()), - (vec!["User-Agent", "Accept"], 0) - ); + assert_eq!((names, sent.secrets.len()), (vec!["User-Agent", "Accept"], 0)); } /// Its tool alone knows the boundary. #[test] fn a_program_is_not_handed_a_multipart_form_s_type() { - let with = |body: RequestBody| RequestDocument { - body, - ..document("https://shop.test/") - }; - let written = - |body: RequestBody| written_for_code(RequestKind::Http, &with(body), &inherit(&[])); + let with = |body: RequestBody| RequestDocument { body, ..document("https://shop.test/") }; + let written = |body: RequestBody| written_for_code(RequestKind::Http, &with(body), &inherit(&[])); assert!(written(RequestBody::Multipart { parts: Vec::new() }).is_empty()); assert_eq!( - written(RequestBody::Json { - text: String::new() - }), + written(RequestBody::Json { text: String::new() }), [("Content-Type".to_string(), "application/json".to_string())] ); } @@ -1619,24 +1377,15 @@ mod tests { fn the_application_names_itself_unless_a_row_says_otherwise() { let plain = post(&document("https://shop.test/"), &inherit(&[])).unwrap(); let mut own = document("https://shop.test/"); - own.headers = vec![ - row("User-Agent", "curl/8"), - row("accept", "application/json"), - ]; + own.headers = vec![row("User-Agent", "curl/8"), row("accept", "application/json")]; let own = post(&own, &inherit(&[])).unwrap(); let mut silenced = document("https://shop.test/"); silenced.headers = vec![off("user-agent")]; let silenced = post(&silenced, &inherit(&[])).unwrap(); - let silenced_above = post( - &document("https://shop.test/"), - &headers_above(vec![off("User-Agent")]), - ) - .unwrap(); + let silenced_above = + post(&document("https://shop.test/"), &headers_above(vec![off("User-Agent")])).unwrap(); - assert_eq!( - (value(&plain, "User-Agent"), value(&plain, "Accept")), - (Some(USER_AGENT), Some("*/*")) - ); + assert_eq!((value(&plain, "User-Agent"), value(&plain, "Accept")), (Some(USER_AGENT), Some("*/*"))); assert_eq!( (value(&own, "User-Agent"), value(&own, "Accept")), (Some("curl/8"), Some("application/json")) @@ -1665,10 +1414,7 @@ mod tests { own.headers = vec![row("X Bad", "1")]; let mine = post(&own, &inherit(&[])); - let theirs = post( - &document("https://shop.test/"), - &headers_above(vec![row("X-Id", "a\nb")]), - ); + let theirs = post(&document("https://shop.test/"), &headers_above(vec![row("X-Id", "a\nb")])); assert_eq!( mine, @@ -1692,50 +1438,28 @@ mod tests { /// text as typed. #[test] fn a_body_carries_its_type_unless_one_is_typed() { - let with = |body: RequestBody| RequestDocument { - body, - ..document("https://shop.test/") - }; - let json = post( - &with(RequestBody::Json { - text: "{\"a\":1}".to_string(), - }), - &inherit(&[]), - ) - .unwrap(); + let with = |body: RequestBody| RequestDocument { body, ..document("https://shop.test/") }; + let json = post(&with(RequestBody::Json { text: "{\"a\":1}".to_string() }), &inherit(&[])).unwrap(); let form = post( - &with(RequestBody::Form { - fields: vec![row(" a b ", "x&y"), off("c"), row("", "z")], - }), + &with(RequestBody::Form { fields: vec![row(" a b ", "x&y"), off("c"), row("", "z")] }), &inherit(&[]), ) .unwrap(); - let mut typed = with(RequestBody::Text { - text: "t".to_string(), - }); + let mut typed = with(RequestBody::Text { text: "t".to_string() }); typed.headers = vec![row("content-type", "text/csv")]; let typed = post(&typed, &inherit(&[])).unwrap(); let none = post(&with(RequestBody::None), &inherit(&[])).unwrap(); assert_eq!( (value(&json, "Content-Type"), &json.body), - ( - Some("application/json"), - &OutgoingBody::Bytes(b"{\"a\":1}".to_vec()) - ) + (Some("application/json"), &OutgoingBody::Bytes(b"{\"a\":1}".to_vec())) ); assert_eq!( (value(&form, "Content-Type"), &form.body), - ( - Some("application/x-www-form-urlencoded"), - &OutgoingBody::Bytes(b"a+b=x%26y".to_vec()) - ) + (Some("application/x-www-form-urlencoded"), &OutgoingBody::Bytes(b"a+b=x%26y".to_vec())) ); assert_eq!(value(&typed, "Content-Type"), Some("text/csv")); - assert_eq!( - (value(&none, "Content-Type"), &none.body), - (None, &OutgoingBody::None) - ); + assert_eq!((value(&none, "Content-Type"), &none.body), (None, &OutgoingBody::None)); } /// A file is read when it is sent: a part keeps its file's name, a missing one is named, one @@ -1759,10 +1483,7 @@ mod tests { file, ..FormPart::default() }; - let with = |body: RequestBody| RequestDocument { - body, - ..document("https://shop.test/") - }; + let with = |body: RequestBody| RequestDocument { body, ..document("https://shop.test/") }; let multipart = post( &with(RequestBody::Multipart { @@ -1776,50 +1497,25 @@ mod tests { &inherit(&[]), ) .unwrap(); - let binary = post( - &with(RequestBody::Binary { path: path.clone() }), - &inherit(&[]), - ) - .unwrap(); - let missing = scratch - .path() - .join("missing.bin") - .to_str() - .unwrap() - .to_string(); + let binary = post(&with(RequestBody::Binary { path: path.clone() }), &inherit(&[])).unwrap(); + let missing = scratch.path().join("missing.bin").to_str().unwrap().to_string(); assert_eq!( multipart.body, OutgoingBody::Multipart(vec![ ("title".to_string(), Part::Text("Facture".to_string())), - ( - "scan".to_string(), - Part::File { - name: "scan.pdf".to_string(), - bytes: b"%PDF".to_vec() - } - ) + ("scan".to_string(), Part::File { name: "scan.pdf".to_string(), bytes: b"%PDF".to_vec() }) ]) ); assert_eq!(value(&multipart, "Content-Type"), None); assert_eq!(binary.body, OutgoingBody::Bytes(b"%PDF".to_vec())); assert_eq!( - post( - &with(RequestBody::Binary { - path: missing.clone() - }), - &inherit(&[]) - ), + post(&with(RequestBody::Binary { path: missing.clone() }), &inherit(&[])), Err(SendError::FileUnreadable(missing)) ); let heavy = heavy.to_str().unwrap().to_string(); assert_eq!( - post( - &with(RequestBody::Binary { - path: heavy.clone() - }), - &inherit(&[]) - ), + post(&with(RequestBody::Binary { path: heavy.clone() }), &inherit(&[])), Err(SendError::FileTooLarge(heavy)) ); } @@ -1833,42 +1529,19 @@ mod tests { held.graphql.variables = "{\"a\":1}".to_string(); held.graphql.operation_name = Some("Me".to_string()); - let posted = compose( - RequestKind::Graphql, - HttpMethod::Delete, - &held, - &inherit(&[]), - ) - .unwrap(); + let posted = compose(RequestKind::Graphql, HttpMethod::Delete, &held, &inherit(&[])).unwrap(); held.graphql.as_get = true; - let got = compose( - RequestKind::Graphql, - HttpMethod::Delete, - &held, - &inherit(&[]), - ) - .unwrap(); + let got = compose(RequestKind::Graphql, HttpMethod::Delete, &held, &inherit(&[])).unwrap(); held.graphql.variables = "[1]".to_string(); - let refused = compose( - RequestKind::Graphql, - HttpMethod::Delete, - &held, - &inherit(&[]), - ); + let refused = compose(RequestKind::Graphql, HttpMethod::Delete, &held, &inherit(&[])); assert_eq!( - ( - posted.method, - value(&posted, "Content-Type"), - posted.graphql - ), + (posted.method, value(&posted, "Content-Type"), posted.graphql), (HttpMethod::Post, Some("application/json"), true) ); assert_eq!( posted.body, - OutgoingBody::Bytes( - br#"{"query":"{ me }","variables":{"a":1},"operationName":"Me"}"#.to_vec() - ) + OutgoingBody::Bytes(br#"{"query":"{ me }","variables":{"a":1},"operationName":"Me"}"#.to_vec()) ); assert_eq!( (got.method, value(&got, "Content-Type"), &got.body), @@ -1890,10 +1563,7 @@ mod tests { let sent = compose(RequestKind::Graphql, HttpMethod::Get, &held, &inherit(&[])).unwrap(); - assert_eq!( - sent.url.as_str(), - "https://shop.test/graphql?query=%7Bme%7D" - ); + assert_eq!(sent.url.as_str(), "https://shop.test/graphql?query=%7Bme%7D"); } /// Its own transport over what it inherits, and who set the delay and the redirects a send @@ -1913,24 +1583,9 @@ mod tests { let sent = post(&own, &inherited).unwrap(); - assert_eq!( - sent.timeout(), - Limit { - value: 1_000, - set_by: SetBy::Request - } - ); - assert_eq!( - sent.redirects(), - Limit { - value: 3, - set_by: SetBy::Above(origin("Shop")) - } - ); - assert_eq!( - (sent.jar.is_none(), sent.secret_values.is_empty()), - (true, true) - ); + assert_eq!(sent.timeout(), Limit { value: 1_000, set_by: SetBy::Request }); + assert_eq!(sent.redirects(), Limit { value: 3, set_by: SetBy::Above(origin("Shop")) }); + assert_eq!((sent.jar.is_none(), sent.secret_values.is_empty()), (true, true)); } fn implied_names( @@ -1949,24 +1604,14 @@ mod tests { #[test] fn what_leaves_without_a_row_is_listed_with_who_put_it_there() { let mut held = document("https://shop.test:8443/a"); - held.body = RequestBody::Json { - text: "{}".to_string(), - }; + held.body = RequestBody::Json { text: "{}".to_string() }; held.headers = vec![row("X-Own", "1")]; - held.auth = RequestAuth::Bearer { - token: "t".to_string(), - }; + held.auth = RequestAuth::Bearer { token: "t".to_string() }; - let listed = implied( - RequestKind::Http, - &held, - &headers_above(vec![row("X-Tenant", "acme")]), - ); + let listed = implied(RequestKind::Http, &held, &headers_above(vec![row("X-Tenant", "acme")])); - let shown: Vec<(&str, ImpliedSource)> = listed - .iter() - .map(|header| (header.name.as_str(), header.source)) - .collect(); + let shown: Vec<(&str, ImpliedSource)> = + listed.iter().map(|header| (header.name.as_str(), header.source)).collect(); assert_eq!( shown, [ @@ -2002,23 +1647,16 @@ mod tests { Some("shop.test".to_string()) ); assert_eq!(host(RequestKind::Http, &document("")), None); - assert_eq!( - host(RequestKind::Http, &document("https://{{base}}/a")), - None - ); + assert_eq!(host(RequestKind::Http, &document("https://{{base}}/a")), None); assert_eq!(host(RequestKind::Http, &typed), None); assert_eq!( host(RequestKind::Websocket, &document("wss://live.test:9000/")), Some("live.test:9000".to_string()) ); assert!( - !implied_names( - RequestKind::Websocket, - &document("wss://live.test/"), - &inherit(&[]) - ) - .iter() - .any(|(name, ..)| name == "Content-Type") + !implied_names(RequestKind::Websocket, &document("wss://live.test/"), &inherit(&[])) + .iter() + .any(|(name, ..)| name == "Content-Type") ); assert!( !implied_names(RequestKind::Graphql, &graphql_get, &inherit(&[])) @@ -2034,36 +1672,24 @@ mod tests { let mut outgoing = post(&document("https://shop.test/?t=t0k3n"), &inherit(&[])).unwrap(); outgoing.headers = vec![("X-Token".to_string(), "t0k3n".to_string())]; outgoing.secret_values = vec![("token".to_string(), "t0k3n".to_string())]; - outgoing.body = - OutgoingBody::Bytes(format!("{}{}", "t0k3n ", "a".repeat(SHOWN_LIMIT)).into_bytes()); + outgoing.body = OutgoingBody::Bytes(format!("{}{}", "t0k3n ", "a".repeat(SHOWN_LIMIT)).into_bytes()); let text = exchange(&outgoing); outgoing.body = OutgoingBody::Bytes(vec![0xff, 0xfe, 0x00]); let bytes = exchange(&outgoing); - outgoing.body = - OutgoingBody::Multipart(vec![("title".to_string(), Part::Text("x".to_string()))]); + outgoing.body = OutgoingBody::Multipart(vec![("title".to_string(), Part::Text("x".to_string()))]); let form = exchange(&outgoing); assert_eq!(text.url, "https://shop.test/?t={{token}}"); assert_eq!(text.headers[0].value, "{{token}}"); - let SentBody::Text { text: shown } = &text.body else { - panic!("no text") - }; + let SentBody::Text { text: shown } = &text.body else { panic!("no text") }; assert!(shown.starts_with("{{token}} ") && shown.chars().count() < SHOWN_LIMIT + 10); assert_eq!(bytes.body, SentBody::Bytes { size: 3 }); - assert_eq!( - form.body, - SentBody::Multipart { - fields: vec!["title".to_string()] - } - ); + assert_eq!(form.body, SentBody::Multipart { fields: vec!["title".to_string()] }); } #[derive(Debug)] - struct Wrapped( - &'static str, - Option>, - ); + struct Wrapped(&'static str, Option>); impl std::fmt::Display for Wrapped { fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { @@ -2073,9 +1699,7 @@ mod tests { impl std::error::Error for Wrapped { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - self.1 - .as_deref() - .map(|inner| inner as &(dyn std::error::Error + 'static)) + self.1.as_deref().map(|inner| inner as &(dyn std::error::Error + 'static)) } } @@ -2085,13 +1709,9 @@ mod tests { #[test] fn a_failure_is_read_off_the_chain_of_its_causes() { use std::io::{Error, ErrorKind}; - let limit = Limit { - value: 5_000, - set_by: SetBy::Request, - }; - let wrap = |inner: Box| { - Wrapped("error sending request", Some(inner)) - }; + let limit = Limit { value: 5_000, set_by: SetBy::Request }; + let wrap = + |inner: Box| Wrapped("error sending request", Some(inner)); let kind_of = |error: &(dyn std::error::Error + 'static), limit: Option<&Limit>| { cause_of(error, limit).map(|found| std::mem::discriminant(&found)) }; @@ -2101,10 +1721,7 @@ mod tests { let tls = SendError::Tls(String::new()); assert_eq!( - kind_of( - &wrap(Box::new(Error::from(ErrorKind::ConnectionRefused))), - None - ), + kind_of(&wrap(Box::new(Error::from(ErrorKind::ConnectionRefused))), None), Some(std::mem::discriminant(&refused)) ); assert_eq!( @@ -2124,24 +1741,15 @@ mod tests { ); } assert_eq!( - kind_of( - &Error::other(Wrapped("invalid peer certificate: UnknownIssuer", None)), - None - ), + kind_of(&Error::other(Wrapped("invalid peer certificate: UnknownIssuer", None)), None), Some(std::mem::discriminant(&tls)) ); assert_eq!( - kind_of( - &Error::other(rustls::Error::General("handshake".to_string())), - None - ), + kind_of(&Error::other(rustls::Error::General("handshake".to_string())), None), Some(std::mem::discriminant(&tls)) ); assert_eq!(kind_of(&Wrapped("something else", None), None), None); - assert_eq!( - innermost(&wrap(Box::new(Wrapped("the root", None)))), - "the root" - ); + assert_eq!(innermost(&wrap(Box::new(Wrapped("the root", None)))), "the root"); } /// Windows words its errors in the system's language: the code names the failure. @@ -2150,10 +1758,7 @@ mod tests { fn a_name_that_does_not_resolve_is_read_by_its_code_on_windows() { for code in [11001, 11002, 11003, 11004] { let error = std::io::Error::from_raw_os_error(code); - assert!( - matches!(cause_of(&error, None), Some(SendError::Unresolved(_))), - "{code}" - ); + assert!(matches!(cause_of(&error, None), Some(SendError::Unresolved(_))), "{code}"); } for code in [11000, 11005, 10054] { let error = std::io::Error::from_raw_os_error(code); @@ -2217,11 +1822,7 @@ mod tests { assert_eq!( (moved.method.clone(), moved.url.as_str(), &moved.body), - ( - reqwest::Method::GET, - "https://shop.test/c?x=1", - &OutgoingBody::None - ) + (reqwest::Method::GET, "https://shop.test/c?x=1", &OutgoingBody::None) ); assert_eq!(names(&moved), ["X-Keep", "Referer"]); assert_eq!( @@ -2261,21 +1862,10 @@ mod tests { let same = first.after(302, &location("/b")).unwrap(); let other_host = first.after(302, &location("https://cdn.test/b")).unwrap(); - let other_port = first - .after(302, &location("https://shop.test:8443/b")) - .unwrap(); + let other_port = first.after(302, &location("https://shop.test:8443/b")).unwrap(); let plain = first.after(302, &location("http://shop.test/b")).unwrap(); - assert_eq!( - names(&same), - [ - "Authorization", - "Cookie", - "Proxy-Authorization", - "X-Keep", - "Referer" - ] - ); + assert_eq!(names(&same), ["Authorization", "Cookie", "Proxy-Authorization", "X-Keep", "Referer"]); assert_eq!(same.headers.last().unwrap().1, "https://shop.test/a"); assert_eq!(names(&other_host), ["X-Keep", "Referer"]); assert_eq!(names(&other_port), ["X-Keep", "Referer"]); @@ -2304,23 +1894,12 @@ mod tests { .as_deref(), Some("sid=1") ); + assert_eq!(hop(reqwest::Method::GET, "https://other.test/", &[]).cookie(Some(&jar)), None); assert_eq!( - hop(reqwest::Method::GET, "https://other.test/", &[]).cookie(Some(&jar)), - None - ); - assert_eq!( - hop( - reqwest::Method::GET, - "https://shop.test/", - &[("cookie", "typed=1")] - ) - .cookie(Some(&jar)), - None - ); - assert_eq!( - hop(reqwest::Method::GET, "https://shop.test/", &[]).cookie(None), + hop(reqwest::Method::GET, "https://shop.test/", &[("cookie", "typed=1")]).cookie(Some(&jar)), None ); + assert_eq!(hop(reqwest::Method::GET, "https://shop.test/", &[]).cookie(None), None); } /// Text by its type, or failing one by its bytes reading as UTF-8. Private: an answer's body diff --git a/crates/engine/src/http/settings.rs b/crates/engine/src/http/settings.rs index 15345555a..2a176ce07 100644 --- a/crates/engine/src/http/settings.rs +++ b/crates/engine/src/http/settings.rs @@ -2,9 +2,7 @@ use super::transport::{self, Limits, SetBy, Transport, TransportSettings}; -use super::model::{ - ContainerSettings, HttpItemKind, KeyValue, RequestAuth, RequestBody, RequestScripts, -}; +use super::model::{ContainerSettings, HttpItemKind, KeyValue, RequestAuth, RequestBody, RequestScripts}; use super::variables::{VariableLayer, VariableScope}; /// Where an inherited value was set: what the request says it comes from. @@ -67,10 +65,7 @@ pub fn inherit(levels: &[(HttpOrigin, ContainerSettings)]) -> Inherited { .iter() .filter(|header| header.enabled && !header.key.trim().is_empty()) { - let inherited = InheritedHeader { - header: header.clone(), - from: origin.clone(), - }; + let inherited = InheritedHeader { header: header.clone(), from: origin.clone() }; match headers .iter_mut() .find(|known| known.header.key.eq_ignore_ascii_case(&header.key)) @@ -98,9 +93,7 @@ pub fn inherit(levels: &[(HttpOrigin, ContainerSettings)]) -> Inherited { timeout: set_by(|transport| transport.timeout_ms.is_some()), redirects: set_by(|transport| transport.max_redirects.is_some()), }, - user_agent_off: levels - .iter() - .any(|(_, settings)| switches_off(&settings.headers, "user-agent")), + user_agent_off: levels.iter().any(|(_, settings)| switches_off(&settings.headers, "user-agent")), variables: levels .iter() .rev() @@ -125,8 +118,7 @@ pub fn inherit(levels: &[(HttpOrigin, ContainerSettings)]) -> Inherited { /// Whether a row of that name is written and switched off. pub fn switches_off(rows: &[KeyValue], name: &str) -> bool { - rows.iter() - .any(|row| !row.enabled && row.key.trim().eq_ignore_ascii_case(name)) + rows.iter().any(|row| !row.enabled && row.key.trim().eq_ignore_ascii_case(name)) } /// The `Content-Type` a body implies, sent unless the request sets one by hand. A multipart one @@ -148,11 +140,7 @@ mod tests { use crate::http::environments::Variable; fn origin(kind: HttpItemKind, name: &str) -> HttpOrigin { - HttpOrigin { - kind, - id: name.to_lowercase(), - name: name.to_string(), - } + HttpOrigin { kind, id: name.to_lowercase(), name: name.to_string() } } fn collection() -> HttpOrigin { @@ -164,44 +152,27 @@ mod tests { } fn row(key: &str, value: &str) -> KeyValue { - KeyValue { - key: key.to_string(), - value: value.to_string(), - ..KeyValue::default() - } + KeyValue { key: key.to_string(), value: value.to_string(), ..KeyValue::default() } } fn off(key: &str) -> KeyValue { - KeyValue { - enabled: false, - ..row(key, "") - } + KeyValue { enabled: false, ..row(key, "") } } fn bearer(token: &str) -> RequestAuth { - RequestAuth::Bearer { - token: token.to_string(), - } + RequestAuth::Bearer { token: token.to_string() } } fn with_auth(auth: RequestAuth) -> ContainerSettings { - ContainerSettings { - auth, - ..ContainerSettings::default() - } + ContainerSettings { auth, ..ContainerSettings::default() } } /// The nearest level that sets one wins, and is named; `Inherit` all the way up is none. #[test] fn the_nearest_auth_set_is_inherited_and_named() { - let both = inherit(&[ - (collection(), with_auth(bearer("c"))), - (folder(), with_auth(bearer("f"))), - ]); - let up = inherit(&[ - (collection(), with_auth(bearer("c"))), - (folder(), with_auth(RequestAuth::Inherit)), - ]); + let both = inherit(&[(collection(), with_auth(bearer("c"))), (folder(), with_auth(bearer("f")))]); + let up = + inherit(&[(collection(), with_auth(bearer("c"))), (folder(), with_auth(RequestAuth::Inherit))]); let nothing = inherit(&[(collection(), with_auth(RequestAuth::Inherit))]); assert_eq!((both.auth, both.auth_from), (bearer("f"), Some(folder()))); @@ -214,12 +185,7 @@ mod tests { #[test] fn a_folder_s_header_overrides_its_collection_s_of_the_same_name() { let above = ContainerSettings { - headers: vec![ - row("Accept", "text/plain"), - row("X-Shop", "1"), - off("X-Off"), - row(" ", "unnamed"), - ], + headers: vec![row("Accept", "text/plain"), row("X-Shop", "1"), off("X-Off"), row(" ", "unnamed")], ..ContainerSettings::default() }; let near = ContainerSettings { @@ -232,21 +198,11 @@ mod tests { let shown: Vec<(&str, &str, &str)> = inherited .headers .iter() - .map(|known| { - ( - known.header.key.as_str(), - known.header.value.as_str(), - known.from.name.as_str(), - ) - }) + .map(|known| (known.header.key.as_str(), known.header.value.as_str(), known.from.name.as_str())) .collect(); assert_eq!( shown, - [ - ("accept", "application/json", "Orders"), - ("X-Shop", "1", "Shop"), - ("X-Orders", "2", "Orders"), - ] + [("accept", "application/json", "Orders"), ("X-Shop", "1", "Shop"), ("X-Orders", "2", "Orders"),] ); } @@ -274,13 +230,7 @@ mod tests { let inherited = inherit(&[(collection(), above), (folder(), near)]); let bare = inherit(&[(collection(), ContainerSettings::default())]); - assert_eq!( - ( - inherited.transport.timeout_ms, - inherited.transport.max_redirects - ), - (2_000, 3) - ); + assert_eq!((inherited.transport.timeout_ms, inherited.transport.max_redirects), (2_000, 3)); assert!(!inherited.transport.verify_tls); assert_eq!(inherited.limits.timeout, SetBy::Above(folder())); assert_eq!(inherited.limits.redirects, SetBy::Above(collection())); @@ -290,18 +240,9 @@ mod tests { /// A level holding a `User-Agent` row switched off: the application's own is not sent. #[test] fn a_user_agent_switched_off_above_keeps_the_application_s_off() { - let above = ContainerSettings { - headers: vec![off(" user-agent ")], - ..ContainerSettings::default() - }; + let above = ContainerSettings { headers: vec![off(" user-agent ")], ..ContainerSettings::default() }; - assert!( - inherit(&[ - (collection(), above), - (folder(), ContainerSettings::default()) - ]) - .user_agent_off - ); + assert!(inherit(&[(collection(), above), (folder(), ContainerSettings::default())]).user_agent_off); assert!(!inherit(&[(collection(), ContainerSettings::default())]).user_agent_off); } @@ -310,14 +251,8 @@ mod tests { #[test] fn variables_come_nearest_first_and_scripts_from_the_collection_down() { let settings = |name: &str| ContainerSettings { - variables: vec![Variable { - name: name.to_string(), - ..Variable::default() - }], - scripts: RequestScripts { - before: name.to_string(), - ..RequestScripts::default() - }, + variables: vec![Variable { name: name.to_string(), ..Variable::default() }], + scripts: RequestScripts { before: name.to_string(), ..RequestScripts::default() }, ..ContainerSettings::default() }; @@ -326,20 +261,11 @@ mod tests { let layers: Vec<(VariableScope, &str, &str)> = inherited .variables .iter() - .map(|layer| { - ( - layer.scope, - layer.from.as_str(), - layer.variables[0].name.as_str(), - ) - }) + .map(|layer| (layer.scope, layer.from.as_str(), layer.variables[0].name.as_str())) .collect(); assert_eq!( layers, - [ - (VariableScope::Folder, "Orders", "f"), - (VariableScope::Collection, "Shop", "c") - ] + [(VariableScope::Folder, "Orders", "f"), (VariableScope::Collection, "Shop", "c")] ); let scripts: Vec<(&str, &str)> = inherited .scripts @@ -354,32 +280,11 @@ mod tests { fn a_body_implies_its_content_type() { for (body, implied) in [ (RequestBody::None, None), - ( - RequestBody::Json { - text: String::new(), - }, - Some("application/json"), - ), - ( - RequestBody::Text { - text: String::new(), - }, - Some("text/plain"), - ), - ( - RequestBody::Form { fields: Vec::new() }, - Some("application/x-www-form-urlencoded"), - ), - ( - RequestBody::Multipart { parts: Vec::new() }, - Some("multipart/form-data"), - ), - ( - RequestBody::Binary { - path: String::new(), - }, - Some("application/octet-stream"), - ), + (RequestBody::Json { text: String::new() }, Some("application/json")), + (RequestBody::Text { text: String::new() }, Some("text/plain")), + (RequestBody::Form { fields: Vec::new() }, Some("application/x-www-form-urlencoded")), + (RequestBody::Multipart { parts: Vec::new() }, Some("multipart/form-data")), + (RequestBody::Binary { path: String::new() }, Some("application/octet-stream")), ] { assert_eq!(implied_content_type(&body), implied, "{body:?}"); } diff --git a/crates/engine/src/http/store.rs b/crates/engine/src/http/store.rs index 03cba6e5a..ee7e04baf 100644 --- a/crates/engine/src/http/store.rs +++ b/crates/engine/src/http/store.rs @@ -9,9 +9,9 @@ use diesel::prelude::*; use uuid::Uuid; use super::model::{ - ContainerSettings, HttpCollection, HttpCollectionNode, HttpContents, HttpFolder, HttpItem, - HttpItemKind, HttpNode, HttpPlace, HttpRequest, HttpRequestDraft, HttpRequestPatch, - HttpRequestSummary, HttpTree, RequestDocument, + ContainerSettings, HttpCollection, HttpCollectionNode, HttpContents, HttpFolder, HttpItem, HttpItemKind, + HttpNode, HttpPlace, HttpRequest, HttpRequestDraft, HttpRequestPatch, HttpRequestSummary, HttpTree, + RequestDocument, }; use super::search::{Candidate, RequestHit}; use super::settings::{HttpOrigin, Inherited}; @@ -61,10 +61,7 @@ fn rank(position: i32) -> u32 { } fn instant(id: &str, field: &'static str, text: &str) -> Result, StorageError> { - iso8601::parse(text).map_err(|_| StorageError::CorruptRow { - id: id.to_string(), - field, - }) + iso8601::parse(text).map_err(|_| StorageError::CorruptRow { id: id.to_string(), field }) } impl CollectionRow { @@ -107,12 +104,8 @@ impl RequestRow { fn open(self, vault: &Vault) -> Result { let summary = self.summary(vault)?; - let document = serde_json::from_str(&vault.open(&self.document)?).map_err(|_| { - StorageError::CorruptRow { - id: self.id.clone(), - field: "document", - } - })?; + let document = serde_json::from_str(&vault.open(&self.document)?) + .map_err(|_| StorageError::CorruptRow { id: self.id.clone(), field: "document" })?; Ok(HttpRequest { created_at: instant(&self.id, "createdAt", &self.created_at)?, updated_at: instant(&self.id, "updatedAt", &self.updated_at)?, @@ -137,10 +130,7 @@ fn seal_json(vault: &Vault, value: &T) -> Result Result { +fn find_collection(connection: &mut SqliteConnection, id: &str) -> Result { http_collections::table .find(id) .select(CollectionRow::as_select()) @@ -178,9 +168,7 @@ fn folder_of_collection( if let Some(folder_id) = folder_id && find_folder(connection, folder_id)?.collection_id != collection_id { - return Err( - ValidationError::new("folderId", "the folder belongs to another collection").into(), - ); + return Err(ValidationError::new("folderId", "the folder belongs to another collection").into()); } Ok(()) } @@ -192,12 +180,8 @@ pub fn tree(connection: &mut Library) -> Result { .select(CollectionRow::as_select()) .order((http_collections::position.asc(), http_collections::id.asc())) .load(connection)?; - let folders = http_folders::table - .select(FolderRow::as_select()) - .load(connection)?; - let requests = http_requests::table - .select(RequestRow::as_select()) - .load(connection)?; + let folders = http_folders::table.select(FolderRow::as_select()).load(connection)?; + let requests = http_requests::table.select(RequestRow::as_select()).load(connection)?; let mut nodes: Branches = HashMap::new(); for row in folders { @@ -205,24 +189,14 @@ pub fn tree(connection: &mut Library) -> Result { nodes .entry((folder.collection_id.clone(), folder.parent_id.clone())) .or_default() - .push(( - folder.position, - 0, - folder.id.clone(), - Branch::Folder(folder), - )); + .push((folder.position, 0, folder.id.clone(), Branch::Folder(folder))); } for row in &requests { let request = row.summary(vault)?; nodes .entry((request.collection_id.clone(), request.folder_id.clone())) .or_default() - .push(( - request.position, - 1, - request.id.clone(), - Branch::Request(request), - )); + .push((request.position, 1, request.id.clone(), Branch::Request(request))); } for siblings in nodes.values_mut() { siblings.sort_by(|a, b| (a.0, a.1, &a.2).cmp(&(b.0, b.1, &b.2))); @@ -233,10 +207,7 @@ pub fn tree(connection: &mut Library) -> Result { .map(|row| { let collection = row.open(vault)?; let children = grow(&mut nodes, &collection.id, None); - Ok(HttpCollectionNode { - collection, - children, - }) + Ok(HttpCollectionNode { collection, children }) }) .collect::>()?; @@ -263,9 +234,7 @@ pub fn search_candidates(connection: &mut Library) -> Result, Sto Ok((folder.id.clone(), (folder.parent_id, folder.name))) }) .collect::, StorageError>>()?; - let requests = http_requests::table - .select(RequestRow::as_select()) - .load(connection)?; + let requests = http_requests::table.select(RequestRow::as_select()).load(connection)?; requests .iter() @@ -289,10 +258,7 @@ pub fn search_candidates(connection: &mut Library) -> Result, Sto folder.clone_from(parent); } let collection = collections.get(&summary.collection_id).cloned(); - let place = collection - .into_iter() - .chain(chain.into_iter().rev()) - .collect(); + let place = collection.into_iter().chain(chain.into_iter().rev()).collect(); Ok(Candidate { updated_at: instant(&row.id, "updatedAt", &row.updated_at)?, @@ -324,10 +290,9 @@ fn grow(nodes: &mut Branches, collection_id: &str, folder_id: Option<&str>) -> V siblings .into_iter() .map(|(_, _, id, branch)| match branch { - Branch::Folder(folder) => HttpNode::Folder { - children: grow(nodes, collection_id, Some(&id)), - folder, - }, + Branch::Folder(folder) => { + HttpNode::Folder { children: grow(nodes, collection_id, Some(&id)), folder } + } Branch::Request(request) => HttpNode::Request { request }, }) .collect() @@ -371,11 +336,7 @@ fn siblings( Ok(ranked .into_iter() .map(|(_, kind, id)| HttpItem { - kind: if kind == 0 { - HttpItemKind::Folder - } else { - HttpItemKind::Request - }, + kind: if kind == 0 { HttpItemKind::Folder } else { HttpItemKind::Request }, id, }) .collect()) @@ -424,10 +385,7 @@ fn collections_in_order(connection: &mut SqliteConnection) -> Result(connection)? .into_iter() - .map(|id| HttpItem { - kind: HttpItemKind::Collection, - id, - }) + .map(|id| HttpItem { kind: HttpItemKind::Collection, id }) .collect()) } @@ -487,10 +445,7 @@ fn insert_folder( insert_at( connection, others, - HttpItem { - kind: HttpItemKind::Folder, - id: folder.id.clone(), - }, + HttpItem { kind: HttpItemKind::Folder, id: folder.id.clone() }, usize::MAX, )?; Ok(folder) @@ -521,15 +476,7 @@ fn insert_request( http_requests::updated_at.eq(iso8601::format(now)), )) .execute(connection)?; - insert_at( - connection, - others, - HttpItem { - kind: HttpItemKind::Request, - id: id.clone(), - }, - usize::MAX, - )?; + insert_at(connection, others, HttpItem { kind: HttpItemKind::Request, id: id.clone() }, usize::MAX)?; find_request(connection, &id)?.open(vault) } @@ -581,14 +528,7 @@ pub fn create_request_in( } if let Some(folder) = folder { let parent = placed.folder_id.as_deref(); - let created = insert_folder( - connection, - vault, - &placed.collection_id, - parent, - folder, - now, - )?; + let created = insert_folder(connection, vault, &placed.collection_id, parent, folder, now)?; placed.folder_id = Some(created.id); } insert_request(connection, vault, &placed, name, now) @@ -659,12 +599,8 @@ pub fn delete(connection: &mut Library, item: &HttpItem) -> Result<(), StorageEr HttpItemKind::Collection => { diesel::delete(http_collections::table.find(&item.id)).execute(connection)? } - HttpItemKind::Folder => { - diesel::delete(http_folders::table.find(&item.id)).execute(connection)? - } - HttpItemKind::Request => { - diesel::delete(http_requests::table.find(&item.id)).execute(connection)? - } + HttpItemKind::Folder => diesel::delete(http_folders::table.find(&item.id)).execute(connection)?, + HttpItemKind::Request => diesel::delete(http_requests::table.find(&item.id)).execute(connection)?, }; if deleted == 0 { return Err(not_found(&item.id)); @@ -673,10 +609,7 @@ pub fn delete(connection: &mut Library, item: &HttpItem) -> Result<(), StorageEr } /// Every folder below `folder_id`, at any depth, not counting it. -fn descendants( - connection: &mut SqliteConnection, - folder_id: &str, -) -> Result, StorageError> { +fn descendants(connection: &mut SqliteConnection, folder_id: &str) -> Result, StorageError> { let mut found: Vec = Vec::new(); let mut frontier = vec![folder_id.to_string()]; while !frontier.is_empty() { @@ -685,10 +618,7 @@ fn descendants( .select(http_folders::id) .load(connection)?; // A damaged library may name a folder its own ancestor: what was met is not walked again. - frontier = next - .into_iter() - .filter(|id| id != folder_id && !found.contains(id)) - .collect(); + frontier = next.into_iter().filter(|id| id != folder_id && !found.contains(id)).collect(); found.extend(frontier.iter().cloned()); } Ok(found) @@ -711,10 +641,7 @@ pub fn contents(connection: &mut Library, item: &HttpItem) -> Result { find_folder(connection, &item.id)?; @@ -739,11 +666,7 @@ pub fn contents(connection: &mut Library, item: &HttpItem) -> Result Result<(), StorageError> { +pub fn move_item(connection: &mut Library, item: &HttpItem, place: &HttpPlace) -> Result<(), StorageError> { connection.transaction(|connection, _| { let target_folder = place.folder_id.as_deref(); folder_of_collection(connection, &place.collection_id, target_folder)?; @@ -751,9 +674,7 @@ pub fn move_item( let (from_collection, from_folder) = match item.kind { HttpItemKind::Collection => { - return Err( - ValidationError::new("kind", "a collection is reordered, not moved").into(), - ); + return Err(ValidationError::new("kind", "a collection is reordered, not moved").into()); } HttpItemKind::Folder => { let folder = find_folder(connection, &item.id)?; @@ -761,11 +682,7 @@ pub fn move_item( if target_folder .is_some_and(|target| target == item.id || below.iter().any(|id| id == target)) { - return Err(ValidationError::new( - "folderId", - "a folder cannot move into itself", - ) - .into()); + return Err(ValidationError::new("folderId", "a folder cannot move into itself").into()); } if folder.collection_id != place.collection_id { let mut subtree = below; @@ -773,11 +690,9 @@ pub fn move_item( diesel::update(http_folders::table.filter(http_folders::id.eq_any(&subtree))) .set(http_folders::collection_id.eq(&place.collection_id)) .execute(connection)?; - diesel::update( - http_requests::table.filter(http_requests::folder_id.eq_any(&subtree)), - ) - .set(http_requests::collection_id.eq(&place.collection_id)) - .execute(connection)?; + diesel::update(http_requests::table.filter(http_requests::folder_id.eq_any(&subtree))) + .set(http_requests::collection_id.eq(&place.collection_id)) + .execute(connection)?; } diesel::update(http_folders::table.find(&item.id)) .set(http_folders::parent_id.eq(target_folder)) @@ -803,21 +718,14 @@ pub fn move_item( }) } -pub fn reorder_collection( - connection: &mut Library, - id: &str, - index: u32, -) -> Result<(), StorageError> { +pub fn reorder_collection(connection: &mut Library, id: &str, index: u32) -> Result<(), StorageError> { connection.transaction(|connection, _| { find_collection(connection, id)?; let order = collections_in_order(connection)?; insert_at( connection, order, - HttpItem { - kind: HttpItemKind::Collection, - id: id.to_string(), - }, + HttpItem { kind: HttpItemKind::Collection, id: id.to_string() }, usize::try_from(index).unwrap_or(usize::MAX), ) }) @@ -847,20 +755,14 @@ pub fn duplicate( )) .execute(connection)?; copy_children(connection, &item.id, None, &id, None, now)?; - let copy = HttpItem { - kind: HttpItemKind::Collection, - id, - }; + let copy = HttpItem { kind: HttpItemKind::Collection, id }; let order = collections_in_order(connection)?; place_after(connection, order, item, copy.clone())?; copy } HttpItemKind::Folder => { let source = find_folder(connection, &item.id)?; - let renamed = FolderRow { - name: sealed, - ..source.clone() - }; + let renamed = FolderRow { name: sealed, ..source.clone() }; let id = copy_folder( connection, &renamed, @@ -868,24 +770,14 @@ pub fn duplicate( source.parent_id.as_deref(), now, )?; - let copy = HttpItem { - kind: HttpItemKind::Folder, - id, - }; - let others = siblings( - connection, - &source.collection_id, - source.parent_id.as_deref(), - )?; + let copy = HttpItem { kind: HttpItemKind::Folder, id }; + let others = siblings(connection, &source.collection_id, source.parent_id.as_deref())?; place_after(connection, others, item, copy.clone())?; copy } HttpItemKind::Request => { let source = find_request(connection, &item.id)?; - let renamed = RequestRow { - name: sealed, - ..source.clone() - }; + let renamed = RequestRow { name: sealed, ..source.clone() }; let id = copy_request( connection, &renamed, @@ -893,15 +785,8 @@ pub fn duplicate( source.folder_id.as_deref(), now, )?; - let copy = HttpItem { - kind: HttpItemKind::Request, - id, - }; - let others = siblings( - connection, - &source.collection_id, - source.folder_id.as_deref(), - )?; + let copy = HttpItem { kind: HttpItemKind::Request, id }; + let others = siblings(connection, &source.collection_id, source.folder_id.as_deref())?; place_after(connection, others, item, copy.clone())?; copy } @@ -970,14 +855,7 @@ fn copy_folder( http_folders::created_at.eq(iso8601::format(now)), )) .execute(connection)?; - copy_children( - connection, - &source.collection_id, - Some(&source.id), - collection_id, - Some(&id), - now, - )?; + copy_children(connection, &source.collection_id, Some(&source.id), collection_id, Some(&id), now)?; Ok(id) } @@ -1014,25 +892,18 @@ fn copy_children( } fn open_settings(vault: &Vault, id: &str, sealed: &str) -> Result { - serde_json::from_str(&vault.open(sealed)?).map_err(|_| StorageError::CorruptRow { - id: id.to_string(), - field: "settings", - }) + serde_json::from_str(&vault.open(sealed)?) + .map_err(|_| StorageError::CorruptRow { id: id.to_string(), field: "settings" }) } /// A collection's or a folder's own settings, what its requests inherit. -pub fn settings( - connection: &mut Library, - item: &HttpItem, -) -> Result { +pub fn settings(connection: &mut Library, item: &HttpItem) -> Result { let (connection, vault) = connection.split(); let sealed = match item.kind { HttpItemKind::Collection => find_collection(connection, &item.id)?.settings, HttpItemKind::Folder => find_folder(connection, &item.id)?.settings, HttpItemKind::Request => { - return Err( - ValidationError::new("kind", "a request has no settings of its own").into(), - ); + return Err(ValidationError::new("kind", "a request has no settings of its own").into()); } }; open_settings(vault, &item.id, &sealed) @@ -1053,9 +924,7 @@ pub fn save_settings( .set(http_folders::settings.eq(sealed)) .execute(connection)?, HttpItemKind::Request => { - return Err( - ValidationError::new("kind", "a request has no settings of its own").into(), - ); + return Err(ValidationError::new("kind", "a request has no settings of its own").into()); } }; if changed == 0 { @@ -1095,11 +964,7 @@ pub fn inherited( )]; for folder in folders.into_iter().rev() { levels.push(( - HttpOrigin { - kind: HttpItemKind::Folder, - id: folder.id.clone(), - name: vault.open(&folder.name)?, - }, + HttpOrigin { kind: HttpItemKind::Folder, id: folder.id.clone(), name: vault.open(&folder.name)? }, open_settings(vault, &folder.id, &folder.settings)?, )); } diff --git a/crates/engine/src/http/transport.rs b/crates/engine/src/http/transport.rs index d26a3c28b..520b3cd2d 100644 --- a/crates/engine/src/http/transport.rs +++ b/crates/engine/src/http/transport.rs @@ -99,11 +99,7 @@ impl Transport { /// From the collection down: the nearest set wins. pub fn resolve<'a>(levels: impl IntoIterator) -> Transport { - levels - .into_iter() - .fold(Transport::default(), |transport, settings| { - transport.over(settings) - }) + levels.into_iter().fold(Transport::default(), Transport::over) } #[cfg(test)] @@ -160,10 +156,7 @@ mod tests { /// Under a tenth of a second is a slip of the keyboard, not a choice. #[test] fn a_timeout_too_short_to_mean_it_is_raised() { - let settings = TransportSettings { - timeout_ms: Some(5), - ..TransportSettings::default() - }; + let settings = TransportSettings { timeout_ms: Some(5), ..TransportSettings::default() }; assert_eq!(resolve([&settings]).timeout_ms, 100); } diff --git a/crates/engine/src/http/variables.rs b/crates/engine/src/http/variables.rs index fc930840f..acca364ae 100644 --- a/crates/engine/src/http/variables.rs +++ b/crates/engine/src/http/variables.rs @@ -61,13 +61,7 @@ const NESTING: usize = 8; /// Postman's names for a value made when the request leaves, a new one each time it is written: /// `{{$guid}}`. No level can set one, `$` being no letter of a name. -const DYNAMIC: &[&str] = &[ - "$guid", - "$randomUUID", - "$timestamp", - "$isoTimestamp", - "$randomInt", -]; +const DYNAMIC: &[&str] = &["$guid", "$randomUUID", "$timestamp", "$isoTimestamp", "$randomInt"]; #[must_use] pub fn is_dynamic(name: &str) -> bool { @@ -351,15 +345,8 @@ pub fn resolve( /// Every text of a request a `{{name}}` can stand in, in the order the editor shows them: what /// is sent from it, and nothing that is not. #[must_use] -pub fn texts<'a>( - kind: RequestKind, - document: &'a RequestDocument, - inherited: &'a Inherited, -) -> Vec<&'a str> { - let sent = |rows: &'a [KeyValue]| { - rows.iter() - .filter(|row| row.enabled && !row.key.trim().is_empty()) - }; +pub fn texts<'a>(kind: RequestKind, document: &'a RequestDocument, inherited: &'a Inherited) -> Vec<&'a str> { + let sent = |rows: &'a [KeyValue]| rows.iter().filter(|row| row.enabled && !row.key.trim().is_empty()); let mut texts: Vec<&str> = vec![&document.url]; for row in inherited .headers @@ -383,10 +370,7 @@ pub fn texts<'a>( } match kind { RequestKind::Graphql => { - texts.extend([ - document.graphql.query.as_str(), - document.graphql.variables.as_str(), - ]); + texts.extend([document.graphql.query.as_str(), document.graphql.variables.as_str()]); } RequestKind::Websocket => {} RequestKind::Http => match &document.body { @@ -415,26 +399,15 @@ mod tests { use crate::http::settings::{HttpOrigin, inherit}; fn variable(name: &str, value: &str) -> Variable { - Variable { - name: name.to_string(), - value: value.to_string(), - ..Variable::default() - } + Variable { name: name.to_string(), value: value.to_string(), ..Variable::default() } } fn secret(name: &str, value: &str) -> Variable { - Variable { - kind: VariableKind::Secret, - ..variable(name, value) - } + Variable { kind: VariableKind::Secret, ..variable(name, value) } } fn layer(scope: VariableScope, from: &str, variables: Vec) -> VariableLayer { - VariableLayer { - scope, - from: from.to_string(), - variables, - } + VariableLayer { scope, from: from.to_string(), variables } } fn resolver(variables: Vec) -> Resolver { @@ -442,51 +415,29 @@ mod tests { } fn row(key: &str, value: &str) -> KeyValue { - KeyValue { - key: key.to_string(), - value: value.to_string(), - ..KeyValue::default() - } + KeyValue { key: key.to_string(), value: value.to_string(), ..KeyValue::default() } } fn off(key: &str, value: &str) -> KeyValue { - KeyValue { - enabled: false, - ..row(key, value) - } + KeyValue { enabled: false, ..row(key, value) } } fn part(key: &str, value: &str, enabled: bool) -> FormPart { - FormPart { - enabled, - key: key.to_string(), - value: value.to_string(), - ..FormPart::default() - } + FormPart { enabled, key: key.to_string(), value: value.to_string(), ..FormPart::default() } } fn origin() -> HttpOrigin { - HttpOrigin { - kind: HttpItemKind::Collection, - id: "c-1".to_string(), - name: "Shop".to_string(), - } + HttpOrigin { kind: HttpItemKind::Collection, id: "c-1".to_string(), name: "Shop".to_string() } } /// What a collection hands down: a header and an auth. fn inherited(header: KeyValue, auth: RequestAuth) -> Inherited { - let settings = ContainerSettings { - auth, - headers: vec![header], - ..ContainerSettings::default() - }; + let settings = ContainerSettings { auth, headers: vec![header], ..ContainerSettings::default() }; inherit(&[(origin(), settings)]) } fn bearer(token: &str) -> RequestAuth { - RequestAuth::Bearer { - token: token.to_string(), - } + RequestAuth::Bearer { token: token.to_string() } } /// Braces around anything but a name are text; a dynamic value is a name too. @@ -519,21 +470,9 @@ mod tests { #[test] fn the_nearest_level_setting_a_name_wins_and_names_what_it_hides() { let layers = [ - layer( - VariableScope::Request, - "", - vec![variable("host", "request")], - ), - layer( - VariableScope::Folder, - "Auth", - vec![variable("host", "folder"), variable("user", "ada")], - ), - layer( - VariableScope::Environment, - "Prod", - vec![variable("host", "prod")], - ), + layer(VariableScope::Request, "", vec![variable("host", "request")]), + layer(VariableScope::Folder, "Auth", vec![variable("host", "folder"), variable("user", "ada")]), + layer(VariableScope::Environment, "Prod", vec![variable("host", "prod")]), layer(VariableScope::Globals, "", vec![variable("region", "eu")]), ]; @@ -544,15 +483,9 @@ mod tests { (host.value.as_str(), host.scope, host.from.as_deref()), ("request", VariableScope::Request, None) ); - assert_eq!( - host.shadows, - [VariableScope::Folder, VariableScope::Environment] - ); + assert_eq!(host.shadows, [VariableScope::Folder, VariableScope::Environment]); let user = resolver.get("user").unwrap(); - assert_eq!( - (user.scope, user.from.as_deref()), - (VariableScope::Folder, Some("Auth")) - ); + assert_eq!((user.scope, user.from.as_deref()), (VariableScope::Folder, Some("Auth"))); assert_eq!(resolver.get("region").unwrap().from, None); assert_eq!(resolver.get("missing"), None); } @@ -562,16 +495,10 @@ mod tests { #[test] fn a_row_switched_off_unnamed_or_faulty_is_left_out() { let near = vec![ - Variable { - enabled: false, - ..variable("off", "near") - }, + Variable { enabled: false, ..variable("off", "near") }, variable(" ", "nameless"), variable("bad name", "near"), - Variable { - kind: VariableKind::Number, - ..variable("count", "many") - }, + Variable { kind: VariableKind::Number, ..variable("count", "many") }, variable("twice", "first"), variable("twice", "second"), ]; @@ -597,10 +524,7 @@ mod tests { layer( VariableScope::Request, "", - vec![ - variable("url", "{{scheme}}://{{host}}"), - variable("me", "{{me}}!"), - ], + vec![variable("url", "{{scheme}}://{{host}}"), variable("me", "{{me}}!")], ), layer( VariableScope::Globals, @@ -614,14 +538,8 @@ mod tests { ]); assert_eq!(resolver.get("url").unwrap().value, "https://api.shop.test"); - assert_eq!( - resolver.get("me").unwrap().value, - format!("{{{{me}}}}{}", "!".repeat(NESTING + 1)) - ); - assert_eq!( - resolver.fill("{{url}}/{{unknown}}"), - "https://api.shop.test/{{unknown}}" - ); + assert_eq!(resolver.get("me").unwrap().value, format!("{{{{me}}}}{}", "!".repeat(NESTING + 1))); + assert_eq!(resolver.fill("{{url}}/{{unknown}}"), "https://api.shop.test/{{unknown}}"); } /// The spelling a scope is written in reads back as that scope. @@ -659,23 +577,12 @@ mod tests { layer( VariableScope::Request, "", - vec![ - secret("token", "{{prefix}}-42"), - secret("empty", ""), - variable("prefix", "tk"), - ], - ), - layer( - VariableScope::Globals, - "", - vec![secret("token", "hidden by the request")], + vec![secret("token", "{{prefix}}-42"), secret("empty", ""), variable("prefix", "tk")], ), + layer(VariableScope::Globals, "", vec![secret("token", "hidden by the request")]), ]); - assert_eq!( - resolver.secrets(), - [("token".to_string(), "tk-42".to_string())] - ); + assert_eq!(resolver.secrets(), [("token".to_string(), "tk-42".to_string())]); } /// What the editor lists under a request: each name once, with what it resolves to. @@ -687,20 +594,11 @@ mod tests { let shown: Vec<(&str, Option)> = used .iter() - .map(|used| { - ( - used.name.as_str(), - used.resolved.as_ref().map(|found| found.scope), - ) - }) + .map(|used| (used.name.as_str(), used.resolved.as_ref().map(|found| found.scope))) .collect(); assert_eq!( shown, - [ - ("host", Some(VariableScope::Request)), - ("id", None), - ("$guid", Some(VariableScope::Dynamic)), - ] + [("host", Some(VariableScope::Request)), ("id", None), ("$guid", Some(VariableScope::Dynamic)),] ); } @@ -729,30 +627,17 @@ mod tests { let resolver = resolver(vec![variable("v", "1")]); let bodies = |v: &str| { [ - RequestBody::Json { - text: v.to_string(), - }, - RequestBody::Text { - text: v.to_string(), - }, - RequestBody::Form { - fields: vec![row(v, v)], - }, - RequestBody::Multipart { - parts: vec![part(v, v, true)], - }, - RequestBody::Binary { - path: v.to_string(), - }, + RequestBody::Json { text: v.to_string() }, + RequestBody::Text { text: v.to_string() }, + RequestBody::Form { fields: vec![row(v, v)] }, + RequestBody::Multipart { parts: vec![part(v, v, true)] }, + RequestBody::Binary { path: v.to_string() }, RequestBody::None, ] }; for (body, expected) in bodies("{{v}}").into_iter().zip(bodies(&ones("{{v}}"))) { - let document = RequestDocument { - body, - ..RequestDocument::default() - }; + let document = RequestDocument { body, ..RequestDocument::default() }; let (sent, _) = resolve(&document, &inherit(&[]), &resolver); @@ -766,25 +651,15 @@ mod tests { let resolver = resolver(vec![variable("v", "1")]); let auths = |v: &str| { [ - RequestAuth::Basic { - username: v.to_string(), - password: v.to_string(), - }, + RequestAuth::Basic { username: v.to_string(), password: v.to_string() }, bearer(v), - RequestAuth::ApiKey { - name: v.to_string(), - value: v.to_string(), - place: KeyPlace::Query, - }, + RequestAuth::ApiKey { name: v.to_string(), value: v.to_string(), place: KeyPlace::Query }, RequestAuth::None, ] }; for (auth, expected) in auths("{{v}}").into_iter().zip(auths("1")) { - let document = RequestDocument { - auth: auth.clone(), - ..RequestDocument::default() - }; + let document = RequestDocument { auth: auth.clone(), ..RequestDocument::default() }; let (sent, handed) = resolve(&document, &inherited(row("H", "h"), auth), &resolver); @@ -810,14 +685,8 @@ mod tests { let (sent, handed) = resolve(&document, &handed, &resolver); assert_eq!(sent.url, "https://1"); - assert_eq!( - (sent.params, sent.headers), - (vec![row("1", "1")], vec![row("1", "1")]) - ); - assert_eq!( - (sent.graphql.query.as_str(), sent.graphql.variables.as_str()), - ("1", "1") - ); + assert_eq!((sent.params, sent.headers), (vec![row("1", "1")], vec![row("1", "1")])); + assert_eq!((sent.graphql.query.as_str(), sent.graphql.variables.as_str()), ("1", "1")); assert_eq!(handed.headers[0].header, row("X-1", "1")); } @@ -828,9 +697,7 @@ mod tests { let mut document = RequestDocument { url: "u".to_string(), headers: vec![row("Own", "o"), off("Off", "x"), row(" ", "unnamed")], - body: RequestBody::Json { - text: "body".to_string(), - }, + body: RequestBody::Json { text: "body".to_string() }, ..RequestDocument::default() }; document.graphql.query = "query".to_string(); @@ -841,10 +708,7 @@ mod tests { let websocket = texts(RequestKind::Websocket, &document, &handed); assert_eq!(http, ["u", "Inh", "i", "Own", "o", "inherited", "body"]); - assert_eq!( - graphql, - ["u", "Inh", "i", "Own", "o", "inherited", "query", "vars"] - ); + assert_eq!(graphql, ["u", "Inh", "i", "Own", "o", "inherited", "query", "vars"]); assert_eq!(websocket, ["u", "Inh", "i", "Own", "o", "inherited"]); } @@ -853,27 +717,14 @@ mod tests { fn each_body_and_auth_gives_the_texts_it_sends() { let none = inherit(&[]); let cases: [(RequestBody, RequestAuth, &[&str]); 6] = [ + (RequestBody::Text { text: "t".to_string() }, RequestAuth::None, &["t"]), ( - RequestBody::Text { - text: "t".to_string(), - }, - RequestAuth::None, - &["t"], - ), - ( - RequestBody::Form { - fields: vec![row("k", "v"), off("x", "y")], - }, - RequestAuth::Basic { - username: "u".to_string(), - password: "p".to_string(), - }, + RequestBody::Form { fields: vec![row("k", "v"), off("x", "y")] }, + RequestAuth::Basic { username: "u".to_string(), password: "p".to_string() }, &["u", "p", "k", "v"], ), ( - RequestBody::Multipart { - parts: vec![part("k", "v", true), part("x", "y", false)], - }, + RequestBody::Multipart { parts: vec![part("k", "v", true), part("x", "y", false)] }, RequestAuth::ApiKey { name: "n".to_string(), value: "a".to_string(), @@ -881,22 +732,12 @@ mod tests { }, &["n", "a", "k", "v"], ), - ( - RequestBody::Binary { - path: "f".to_string(), - }, - bearer("b"), - &["b", "f"], - ), + (RequestBody::Binary { path: "f".to_string() }, bearer("b"), &["b", "f"]), (RequestBody::None, RequestAuth::Inherit, &[]), (RequestBody::None, RequestAuth::None, &[]), ]; for (body, auth, expected) in cases { - let document = RequestDocument { - body, - auth, - ..RequestDocument::default() - }; + let document = RequestDocument { body, auth, ..RequestDocument::default() }; let found = texts(RequestKind::Http, &document, &none); diff --git a/crates/engine/src/http/websocket.rs b/crates/engine/src/http/websocket.rs index c8a03477c..ad65976dc 100644 --- a/crates/engine/src/http/websocket.rs +++ b/crates/engine/src/http/websocket.rs @@ -116,12 +116,8 @@ pub fn socket_url(typed: &str) -> Result { match scheme.to_ascii_lowercase().as_str() { "wss" => Ok(format!("https://{rest}")), "ws" => Ok(format!("http://{rest}")), - "https" => Err(SendError::SocketScheme { - twin: Some(format!("wss://{rest}")), - }), - "http" => Err(SendError::SocketScheme { - twin: Some(format!("ws://{rest}")), - }), + "https" => Err(SendError::SocketScheme { twin: Some(format!("wss://{rest}")) }), + "http" => Err(SendError::SocketScheme { twin: Some(format!("ws://{rest}")) }), _ => Err(SendError::SocketScheme { twin: None }), } } @@ -164,8 +160,7 @@ fn failure(error: &tungstenite::Error, timeout: Option<&Limit>) -> SendError { /// The system's verifier, or with « verify TLS » off any certificate, as a request takes it. fn tls_config(verify: bool) -> Result { if verify { - return ClientConfig::with_platform_verifier() - .map_err(|error| SendError::Tls(error.to_string())); + return ClientConfig::with_platform_verifier().map_err(|error| SendError::Tls(error.to_string())); } let provider = CryptoProvider::get_default() .cloned() @@ -228,11 +223,7 @@ impl ServerCertVerifier for AnyCertificate { } fn emit(events: &dyn EventSink, id: &str, event: SocketEvent) { - events.emit(EngineEvent::Socket(WebsocketEvent { - id: id.to_string(), - at: Utc::now(), - event, - })); + events.emit(EngineEvent::Socket(WebsocketEvent { id: id.to_string(), at: Utc::now(), event })); } impl Sockets { @@ -256,8 +247,8 @@ impl Sockets { for (key, value) in &outgoing.headers { let name = tungstenite::http::HeaderName::from_bytes(key.as_bytes()) .map_err(|error| SendError::Network(error.to_string()))?; - let value = HeaderValue::from_str(value) - .map_err(|error| SendError::Network(error.to_string()))?; + let value = + HeaderValue::from_str(value).map_err(|error| SendError::Network(error.to_string()))?; request.headers_mut().insert(name, value); } let protocols: Vec<&str> = protocols @@ -268,19 +259,12 @@ impl Sockets { if !protocols.is_empty() { let value = HeaderValue::from_str(&protocols.join(", ")) .map_err(|error| SendError::Network(error.to_string()))?; - request - .headers_mut() - .insert("Sec-WebSocket-Protocol", value); + request.headers_mut().insert("Sec-WebSocket-Protocol", value); } let tls = tls_config(outgoing.transport.verify_tls)?; let (stream, response) = tokio::time::timeout( Duration::from_millis(u64::from(timeout.value)), - connect_async_tls_with_config( - request, - None, - false, - Some(Connector::Rustls(Arc::new(tls))), - ), + connect_async_tls_with_config(request, None, false, Some(Connector::Rustls(Arc::new(tls)))), ) .await .map_err(|_| SendError::Timeout(timeout.clone()))? @@ -296,13 +280,7 @@ impl Sockets { let (outbound, inbound) = mpsc::unbounded_channel(); let task = runtime.spawn(run(events, id.clone(), stream, inbound)); if let Ok(mut open) = self.open.lock() - && let Some(previous) = open.insert( - id, - Socket { - outbound, - task: task.abort_handle(), - }, - ) + && let Some(previous) = open.insert(id, Socket { outbound, task: task.abort_handle() }) { previous.task.abort(); } @@ -314,10 +292,7 @@ impl Sockets { self.open .lock() .ok() - .and_then(|open| { - open.get(id) - .map(|socket| socket.outbound.send(Outbound::Text(text)).is_ok()) - }) + .and_then(|open| open.get(id).map(|socket| socket.outbound.send(Outbound::Text(text)).is_ok())) .unwrap_or(false) } @@ -346,8 +321,7 @@ impl Sockets { } } -type Stream = - tokio_tungstenite::WebSocketStream>; +type Stream = tokio_tungstenite::WebSocketStream>; async fn run( events: Arc, @@ -424,9 +398,7 @@ async fn run( fn closed(frame: Option<&CloseFrame>) -> SocketEvent { SocketEvent::Closed { code: frame.map(|frame| u16::from(frame.code)), - reason: frame - .map(|frame| frame.reason.to_string()) - .unwrap_or_default(), + reason: frame.map(|frame| frame.reason.to_string()).unwrap_or_default(), } } @@ -440,28 +412,15 @@ mod tests { #[test] fn a_socket_url_is_checked_as_http_or_refused_with_its_twin() { for (typed, checked) in [ - ( - " wss://echo.test/live?x=1 ", - Ok("https://echo.test/live?x=1".to_string()), - ), + (" wss://echo.test/live?x=1 ", Ok("https://echo.test/live?x=1".to_string())), ("WS://echo.test", Ok("http://echo.test".to_string())), ("echo.test:8080/", Ok("echo.test:8080/".to_string())), ( "https://echo.test/a", - Err(SendError::SocketScheme { - twin: Some("wss://echo.test/a".to_string()), - }), - ), - ( - "Http://echo.test", - Err(SendError::SocketScheme { - twin: Some("ws://echo.test".to_string()), - }), - ), - ( - "ftp://echo.test", - Err(SendError::SocketScheme { twin: None }), + Err(SendError::SocketScheme { twin: Some("wss://echo.test/a".to_string()) }), ), + ("Http://echo.test", Err(SendError::SocketScheme { twin: Some("ws://echo.test".to_string()) })), + ("ftp://echo.test", Err(SendError::SocketScheme { twin: None })), ] { assert_eq!(socket_url(typed), checked, "{typed}"); } @@ -470,8 +429,7 @@ mod tests { /// Stored with the request: a document written before a field existed still opens. #[test] fn a_websocket_document_written_before_its_fields_still_opens() { - let document: WebsocketDocument = - serde_json::from_str(r#"{"protocols":["chat"]}"#).unwrap(); + let document: WebsocketDocument = serde_json::from_str(r#"{"protocols":["chat"]}"#).unwrap(); assert_eq!(document.protocols, ["chat"]); assert!(document.messages.is_empty()); diff --git a/crates/engine/src/index.rs b/crates/engine/src/index.rs index 026ab377f..ae276d578 100644 --- a/crates/engine/src/index.rs +++ b/crates/engine/src/index.rs @@ -43,15 +43,7 @@ impl IndexedNote { impl Drop for IndexedNote { fn drop(&mut self) { - let Note { - title, - content, - source, - tags, - items, - placeholder_values, - .. - } = &mut self.note; + let Note { title, content, source, tags, items, placeholder_values, .. } = &mut self.note; title.zeroize(); content.zeroize(); source.zeroize(); @@ -60,13 +52,7 @@ impl Drop for IndexedNote { item.text.zeroize(); } wipe_values(placeholder_values); - let Folded { - title, - tags, - content, - items, - source, - } = &mut self.folded; + let Folded { title, tags, content, items, source } = &mut self.folded; title.zeroize(); tags.zeroize(); content.zeroize(); @@ -84,10 +70,7 @@ fn wipe_values(values: &mut BTreeMap) { /// What a write touched, for the index to read again (`Engine::write`). #[derive(Debug, Default)] -#[allow( - clippy::struct_excessive_bools, - reason = "one flag a decoration the index keeps, read again whole" -)] +#[allow(clippy::struct_excessive_bools, reason = "one flag a decoration the index keeps, read again whole")] pub struct Changed { /// Notes whose row or side tables changed; one no longer live leaves the index. pub notes: Vec, @@ -100,17 +83,11 @@ pub struct Changed { impl Changed { pub fn notes(ids: impl IntoIterator) -> Self { - Self { - notes: ids.into_iter().collect(), - ..Self::default() - } + Self { notes: ids.into_iter().collect(), ..Self::default() } } pub fn everything() -> Self { - Self { - rebuild: true, - ..Self::default() - } + Self { rebuild: true, ..Self::default() } } } @@ -191,11 +168,7 @@ impl NoteIndex { /// Reads again what `changed` names. An index not started on `library` has nothing to /// keep true: the next read builds it whole. - pub(crate) fn refresh( - &mut self, - library: &mut Library, - changed: &Changed, - ) -> Result<(), StorageError> { + pub(crate) fn refresh(&mut self, library: &mut Library, changed: &Changed) -> Result<(), StorageError> { if self.library != Some(library.number()) { return Ok(()); } @@ -220,8 +193,7 @@ impl NoteIndex { self.notes.remove(id); } for note in fresh { - self.notes - .insert(note.id.clone(), Arc::new(IndexedNote::of(note))); + self.notes.insert(note.id.clone(), Arc::new(IndexedNote::of(note))); } self.counted.get_mut().clear(); } @@ -238,10 +210,7 @@ impl NoteIndex { } let mut fresh = Self::default(); fresh.start(library).map_err(|error| error.to_string())?; - while fresh - .next_slice(library) - .map_err(|error| error.to_string())? - {} + while fresh.next_slice(library).map_err(|error| error.to_string())? {} let mut ids: Vec<&String> = self.notes.keys().collect(); let mut expected: Vec<&String> = fresh.notes.keys().collect(); @@ -299,13 +268,8 @@ impl NoteIndex { .values() .filter(|entry| { let note = &entry.note; - query - .space_id - .as_ref() - .is_none_or(|space| ¬e.space_id == space) - && folders.is_none_or(|ids| { - note.folder_id.as_ref().is_some_and(|id| ids.contains(id)) - }) + query.space_id.as_ref().is_none_or(|space| ¬e.space_id == space) + && folders.is_none_or(|ids| note.folder_id.as_ref().is_some_and(|id| ids.contains(id))) && criteria.passes_rails(note) }) .collect(); @@ -342,9 +306,8 @@ impl NoteIndex { .filter(|note| space_id.is_none_or(|space| note.space_id == space)); for note in notes { for tag in ¬e.tags { - let (spelling, count) = tags - .entry(tag.to_ascii_lowercase()) - .or_insert_with(|| (tag.clone(), 0)); + let (spelling, count) = + tags.entry(tag.to_ascii_lowercase()).or_insert_with(|| (tag.clone(), 0)); if tag < spelling { spelling.clone_from(tag); } @@ -357,10 +320,7 @@ impl NoteIndex { *priorities.entry(note.priority.as_str()).or_default() += 1; } let rows = |counts: HashMap<&str, i64>| -> Vec<(String, i64)> { - counts - .into_iter() - .map(|(value, count)| (value.to_string(), count)) - .collect() + counts.into_iter().map(|(value, count)| (value.to_string(), count)).collect() }; Facets { tags: view::count_tags(tags.into_values().collect()), @@ -410,9 +370,7 @@ pub(crate) fn search(entries: &[&Arc], needle: &str) -> Vec { } entries .par_iter() - .filter_map(|entry| { - view::answers(&entry.note, &entry.folded, needle).map(|hit| card(entry, hit)) - }) + .filter_map(|entry| view::answers(&entry.note, &entry.folded, needle).map(|hit| card(entry, hit))) .collect() } @@ -498,9 +456,7 @@ mod tests { fn shelf() -> Shelf { let mut library = open_in_memory().unwrap(); - let space = crate::spaces::store::create(&mut library, "Work") - .unwrap() - .id; + let space = crate::spaces::store::create(&mut library, "Work").unwrap().id; Shelf { library, space } } @@ -535,9 +491,7 @@ mod tests { } fn written(&mut self, draft: NoteDraft) -> String { - store::create(&mut self.library, draft, minutes(0)) - .unwrap() - .id + store::create(&mut self.library, draft, minutes(0)).unwrap().id } fn full_index(&mut self) -> NoteIndex { @@ -548,11 +502,7 @@ mod tests { } fn titles(index: &NoteIndex) -> Vec { - let mut titles: Vec = index - .notes - .values() - .map(|entry| entry.note.title.clone()) - .collect(); + let mut titles: Vec = index.notes.values().map(|entry| entry.note.title.clone()).collect(); titles.sort(); titles } @@ -576,11 +526,7 @@ mod tests { } } - fn selected( - index: &NoteIndex, - request: &NotesQuery, - folders: Option<&HashSet>, - ) -> Vec { + fn selected(index: &NoteIndex, request: &NotesQuery, folders: Option<&HashSet>) -> Vec { index .select(request, folders) .0 @@ -637,9 +583,7 @@ mod tests { let mut index = NoteIndex::default(); index.start(&mut shelf.library).unwrap(); - let answers: Vec = (0..3) - .map(|_| index.next_slice(&mut shelf.library).unwrap()) - .collect(); + let answers: Vec = (0..3).map(|_| index.next_slice(&mut shelf.library).unwrap()).collect(); assert_eq!(answers, [true, true, false]); assert!(index.is_complete()); @@ -735,10 +679,7 @@ mod tests { let edited = shelf.note("before", 0); let trashed = shelf.note("trashed", 0); let mut index = shelf.full_index(); - let retitle = NotePatch { - title: Some("after".into()), - ..NotePatch::default() - }; + let retitle = NotePatch { title: Some("after".into()), ..NotePatch::default() }; store::update(&mut shelf.library, &edited, &retitle, minutes(1)).unwrap(); store::trash::trash(&mut shelf.library, &trashed, minutes(1)).unwrap(); let created = shelf.note("new", 2); @@ -756,8 +697,7 @@ mod tests { let id = shelf.note("a", 0); let mut index = shelf.full_index(); let space = shelf.space.clone(); - crate::folders::store::create(&mut shelf.library, &space, None, "Infra", minutes(1)) - .unwrap(); + crate::folders::store::create(&mut shelf.library, &space, None, "Infra", minutes(1)).unwrap(); store::replace_global_placeholder_values( &mut shelf.library, &[("host".to_string(), "db".to_string())].into(), @@ -774,12 +714,7 @@ mod tests { let (db, vault) = shelf.library.split(); crate::attachments::store::create(db, vault, &attachment).unwrap(); - let changed = Changed { - attachments: true, - folders: true, - globals: true, - ..Changed::default() - }; + let changed = Changed { attachments: true, folders: true, globals: true, ..Changed::default() }; index.refresh(&mut shelf.library, &changed).unwrap(); let decorations = index.decorations(); @@ -795,9 +730,7 @@ mod tests { shelf.note("a", 0); let mut index = shelf.full_index(); - index - .refresh(&mut shelf.library, &Changed::everything()) - .unwrap(); + index.refresh(&mut shelf.library, &Changed::everything()).unwrap(); assert!(index.is_empty()); assert!(!index.is_complete()); @@ -810,9 +743,7 @@ mod tests { let mut second = shelf(); let mut index = first.full_index(); - index - .refresh(&mut second.library, &Changed::everything()) - .unwrap(); + index.refresh(&mut second.library, &Changed::everything()).unwrap(); assert_eq!(index.len(), 1); } @@ -822,17 +753,11 @@ mod tests { let mut shelf = shelf(); let id = shelf.note("before", 0); let index = shelf.full_index(); - let retitle = NotePatch { - title: Some("after".into()), - ..NotePatch::default() - }; + let retitle = NotePatch { title: Some("after".into()), ..NotePatch::default() }; store::update(&mut shelf.library, &id, &retitle, minutes(1)).unwrap(); let mut other = self::shelf(); - assert_eq!( - index.matches(&mut shelf.library), - Err(format!("note {id} differs")) - ); + assert_eq!(index.matches(&mut shelf.library), Err(format!("note {id} differs"))); assert_eq!(index.matches(&mut other.library), Ok(())); } @@ -843,12 +768,8 @@ mod tests { let space = shelf.space.clone(); let index = shelf.full_index(); - crate::folders::store::create(&mut shelf.library, &space, None, "Infra", minutes(1)) - .unwrap(); - assert_eq!( - index.matches(&mut shelf.library), - Err("folders differ".to_string()) - ); + crate::folders::store::create(&mut shelf.library, &space, None, "Infra", minutes(1)).unwrap(); + assert_eq!(index.matches(&mut shelf.library), Err("folders differ".to_string())); let index = shelf.full_index(); store::replace_global_placeholder_values( @@ -856,10 +777,7 @@ mod tests { &[("host".to_string(), "db".to_string())].into(), ) .unwrap(); - assert_eq!( - index.matches(&mut shelf.library), - Err("global values differ".to_string()) - ); + assert_eq!(index.matches(&mut shelf.library), Err("global values differ".to_string())); let index = shelf.full_index(); let attachment = Attachment { @@ -872,10 +790,7 @@ mod tests { }; let (db, vault) = shelf.library.split(); crate::attachments::store::create(db, vault, &attachment).unwrap(); - assert_eq!( - index.matches(&mut shelf.library), - Err("attachment counts differ".to_string()) - ); + assert_eq!(index.matches(&mut shelf.library), Err("attachment counts differ".to_string())); } #[test] @@ -885,12 +800,7 @@ mod tests { let index = shelf.full_index(); shelf.note("b", 1); - assert!( - index - .matches(&mut shelf.library) - .unwrap_err() - .starts_with("notes ") - ); + assert!(index.matches(&mut shelf.library).unwrap_err().starts_with("notes ")); } // --- Reading it. @@ -899,13 +809,8 @@ mod tests { fn a_selection_keeps_the_space_and_runs_from_the_last_edit_then_the_id() { let mut shelf = shelf(); shelf.note("old", 0); - let mut tie = [ - (shelf.note("b-new", 5), "b-new"), - (shelf.note("a-new", 5), "a-new"), - ]; - let elsewhere = crate::spaces::store::create(&mut shelf.library, "Home") - .unwrap() - .id; + let mut tie = [(shelf.note("b-new", 5), "b-new"), (shelf.note("a-new", 5), "a-new")]; + let elsewhere = crate::spaces::store::create(&mut shelf.library, "Home").unwrap().id; shelf.written(draft(&elsewhere, "home")); let index = shelf.full_index(); let space = shelf.space.clone(); @@ -920,26 +825,15 @@ mod tests { fn a_selection_keeps_the_notes_filed_in_the_folders_given_and_the_rails() { let mut shelf = shelf(); let space = shelf.space.clone(); - let folder = - crate::folders::store::create(&mut shelf.library, &space, None, "Infra", minutes(0)) - .unwrap() - .id; - shelf.written(NoteDraft { - folder_id: Some(folder.clone()), - pinned: true, - ..draft(&space, "filed") - }); + let folder = crate::folders::store::create(&mut shelf.library, &space, None, "Infra", minutes(0)) + .unwrap() + .id; + shelf.written(NoteDraft { folder_id: Some(folder.clone()), pinned: true, ..draft(&space, "filed") }); shelf.written(draft(&space, "loose")); let index = shelf.full_index(); - let pinned = NotesQuery { - filter: NoteFilter::Pinned, - ..query(None) - }; + let pinned = NotesQuery { filter: NoteFilter::Pinned, ..query(None) }; - assert_eq!( - selected(&index, &query(None), Some(&[folder].into())), - ["filed"] - ); + assert_eq!(selected(&index, &query(None), Some(&[folder].into())), ["filed"]); assert_eq!(selected(&index, &pinned, None), ["filed"]); } @@ -947,43 +841,22 @@ mod tests { fn facets_count_the_space_s_notes_by_folded_tag_alike_but_for_case_as_one() { let mut shelf = shelf(); let space = shelf.space.clone(); - shelf.written(NoteDraft { - tags: vec!["ops".into()], - ..draft(&space, "a") - }); + shelf.written(NoteDraft { tags: vec!["ops".into()], ..draft(&space, "a") }); shelf.written(NoteDraft { tags: vec!["OPS".into(), "ci".into()], kind: NoteKind::Note, ..draft(&space, "b") }); - let elsewhere = crate::spaces::store::create(&mut shelf.library, "Home") - .unwrap() - .id; - shelf.written(NoteDraft { - tags: vec!["home".into()], - ..draft(&elsewhere, "c") - }); + let elsewhere = crate::spaces::store::create(&mut shelf.library, "Home").unwrap().id; + shelf.written(NoteDraft { tags: vec!["home".into()], ..draft(&elsewhere, "c") }); let index = shelf.full_index(); let facets = index.facets(Some(&space)); - let tags: Vec<_> = facets - .tags - .iter() - .map(|tag| (tag.value.as_str(), tag.count)) - .collect(); + let tags: Vec<_> = facets.tags.iter().map(|tag| (tag.value.as_str(), tag.count)).collect(); assert_eq!(tags, [("ci", 1), ("OPS", 2)]); - assert_eq!( - facets.languages, - view::count_languages(&[("sh".to_string(), 1)]) - ); - assert_eq!( - facets.kinds[1], - view::FacetCount { - value: NoteKind::Note, - count: 1 - } - ); + assert_eq!(facets.languages, view::count_languages(&[("sh".to_string(), 1)])); + assert_eq!(facets.kinds[1], view::FacetCount { value: NoteKind::Note, count: 1 }); assert_eq!(index.facets(None).tags.len(), 3); } @@ -993,15 +866,10 @@ mod tests { let id = shelf.note("a", 0); let mut index = shelf.full_index(); assert!(index.facets(None).tags.is_empty()); - let tag = NotePatch { - tags: Some(vec!["ops".into()]), - ..NotePatch::default() - }; + let tag = NotePatch { tags: Some(vec!["ops".into()]), ..NotePatch::default() }; store::update(&mut shelf.library, &id, &tag, minutes(1)).unwrap(); - index - .refresh(&mut shelf.library, &Changed::notes([id])) - .unwrap(); + index.refresh(&mut shelf.library, &Changed::notes([id])).unwrap(); assert_eq!(index.facets(None).tags[0].value, "ops"); } @@ -1016,10 +884,7 @@ mod tests { store::update( &mut shelf.library, "ed, - &NotePatch { - content: Some("psql -h db".into()), - ..NotePatch::default() - }, + &NotePatch { content: Some("psql -h db".into()), ..NotePatch::default() }, minutes(0), ) .unwrap(); @@ -1043,10 +908,7 @@ mod tests { let id = shelf.note("a", 0); let index = shelf.full_index(); - assert_eq!( - index.get(&id).map(|entry| entry.note.title.as_str()), - Some("a") - ); + assert_eq!(index.get(&id).map(|entry| entry.note.title.as_str()), Some("a")); assert!(index.get("missing").is_none()); } @@ -1087,16 +949,8 @@ mod tests { .map(|step| step.detail) .collect(); - assert!( - plan.iter().any(|step| step.contains("notes_updated_at")), - "{plan:?}" - ); - assert!( - !plan - .iter() - .any(|step| step == "USE TEMP B-TREE FOR ORDER BY"), - "{plan:?}" - ); + assert!(plan.iter().any(|step| step.contains("notes_updated_at")), "{plan:?}"); + assert!(!plan.iter().any(|step| step == "USE TEMP B-TREE FOR ORDER BY"), "{plan:?}"); } /// Nothing of the index reaches the disk, and what it held is wiped when it goes. diff --git a/crates/engine/src/index/oracle.rs b/crates/engine/src/index/oracle.rs index 855c520e0..95d99f449 100644 --- a/crates/engine/src/index/oracle.rs +++ b/crates/engine/src/index/oracle.rs @@ -15,9 +15,7 @@ use crate::notes::kind::NoteKind; use crate::notes::language::Language; use crate::notes::model::{NoteDraft, NoteLifecycle, NotePatch}; use crate::notes::priority::Priority; -use crate::notes::view::{ - Grouping, NoteFilter, NoteOrder, NotesQuery, NotesView, SortDirection, SortKey, -}; +use crate::notes::view::{Grouping, NoteFilter, NoteOrder, NotesQuery, NotesView, SortDirection, SortKey}; use crate::spaces::model::SpaceDraft; use crate::{Engine, Paths, RecordingSink, folders, notes, spaces}; @@ -51,29 +49,15 @@ struct World { impl World { fn new(seed: u64) -> Self { - let runtime = tokio::runtime::Builder::new_current_thread() - .build() - .unwrap(); - let paths = Paths { - profile: std::env::temp_dir(), - }; - let engine = Arc::new(Engine::new( - paths, - Arc::new(RecordingSink::default()), - runtime.handle().clone(), - )); + let runtime = tokio::runtime::Builder::new_current_thread().build().unwrap(); + let paths = Paths { profile: std::env::temp_dir() }; + let engine = + Arc::new(Engine::new(paths, Arc::new(RecordingSink::default()), runtime.handle().clone())); *engine.db.lock().unwrap() = Some(open_in_memory().unwrap()); - let mut world = Self { - _runtime: runtime, - engine, - spaces: Vec::new(), - folders: Vec::new(), - dice: Dice(seed), - }; + let mut world = + Self { _runtime: runtime, engine, spaces: Vec::new(), folders: Vec::new(), dice: Dice(seed) }; for name in ["Perso", "Travail"] { - let draft = SpaceDraft { - name: name.to_string(), - }; + let draft = SpaceDraft { name: name.to_string() }; let id = spaces::create_space(&world.engine, &draft).unwrap().id; world.spaces.push(id); } @@ -87,11 +71,8 @@ impl World { } fn folder(&mut self, name: &str, space: usize) { - let draft = FolderDraft { - space_id: self.spaces[space].clone(), - name: name.to_string(), - parent_id: None, - }; + let draft = + FolderDraft { space_id: self.spaces[space].clone(), name: name.to_string(), parent_id: None }; let id = folders::create_folder(&self.engine, &draft).unwrap().id; self.folders.push(id); } @@ -106,9 +87,7 @@ impl World { space_id: self.dice.pick(&self.spaces).clone(), folder_id: None, title: self.text(), - language: *self - .dice - .pick(&[Language::Txt, Language::Sql, Language::Py]), + language: *self.dice.pick(&[Language::Txt, Language::Sql, Language::Py]), content: if kind == NoteKind::Checklist { String::new() } else { @@ -118,19 +97,14 @@ impl World { tags: vec![(*self.dice.pick(&TAGS)).to_string()], pinned: self.dice.roll(3) == 0, lifecycle: if self.dice.roll(4) == 0 { - NoteLifecycle::Expires { - at: at(NOW) + TimeDelta::days(3), - } + NoteLifecycle::Expires { at: at(NOW) + TimeDelta::days(3) } } else { NoteLifecycle::Permanent }, kind, priority: *self.dice.pick(&Priority::ALL), items: if kind == NoteKind::Checklist { - vec![ChecklistItem { - text: self.text(), - done: false, - }] + vec![ChecklistItem { text: self.text(), done: false }] } else { Vec::new() }, @@ -172,11 +146,7 @@ impl World { 2 => drop(notes::tag_notes(&engine, &one, &[tag])), 3 => drop(notes::remove_tag(&engine, &one, tag)), 4 => drop(notes::set_pinned(&engine, &one, self.dice.roll(2) == 0)), - 5 => drop(notes::set_priority( - &engine, - &one, - *self.dice.pick(&Priority::ALL), - )), + 5 => drop(notes::set_priority(&engine, &one, *self.dice.pick(&Priority::ALL))), 6 => drop(notes::delete_notes(&engine, &one)), 7 => { let space = self.dice.pick(&self.spaces).clone(); @@ -213,29 +183,15 @@ impl World { space_id, folder_id, search: (*self.dice.pick(&NEEDLES)).to_string(), - filter: *self - .dice - .pick(&[NoteFilter::All, NoteFilter::Pinned, NoteFilter::Untriaged]), + filter: *self.dice.pick(&[NoteFilter::All, NoteFilter::Pinned, NoteFilter::Untriaged]), tags: if self.dice.roll(4) == 0 { vec![(*self.dice.pick(&TAGS)).to_string()] } else { Vec::new() }, - languages: if self.dice.roll(6) == 0 { - vec![Language::Sql] - } else { - Vec::new() - }, - kinds: if self.dice.roll(6) == 0 { - vec![NoteKind::Checklist] - } else { - Vec::new() - }, - priorities: if self.dice.roll(6) == 0 { - vec![Priority::High] - } else { - Vec::new() - }, + languages: if self.dice.roll(6) == 0 { vec![Language::Sql] } else { Vec::new() }, + kinds: if self.dice.roll(6) == 0 { vec![NoteKind::Checklist] } else { Vec::new() }, + priorities: if self.dice.roll(6) == 0 { vec![Priority::High] } else { Vec::new() }, order: NoteOrder { key: *self.dice.pick(&[ SortKey::Modified, @@ -244,9 +200,7 @@ impl World { SortKey::Format, SortKey::Title, ]), - direction: *self - .dice - .pick(&[SortDirection::Descending, SortDirection::Ascending]), + direction: *self.dice.pick(&[SortDirection::Descending, SortDirection::Ascending]), }, grouping: *self.dice.pick(&[ Grouping::Date, @@ -269,11 +223,7 @@ fn drawn(view: &NotesView) -> String { .sections .iter() .map(|section| { - let cards: Vec<_> = section - .cards - .iter() - .map(|card| view.display(card)) - .collect(); + let cards: Vec<_> = section.cards.iter().map(|card| view.display(card)).collect(); ( §ion.key, §ion.id, @@ -309,13 +259,8 @@ fn every_query_answers_what_the_database_answers_through_random_writes() { for _ in 0..4 { let query = world.query(); let from_index = notes::query_notes(&world.engine, &query).unwrap(); - let from_database = - notes::query_notes_from_database(&world.engine, &query).unwrap(); - assert_eq!( - drawn(&from_index), - drawn(&from_database), - "seed {seed}, step {step}, {query:?}" - ); + let from_database = notes::query_notes_from_database(&world.engine, &query).unwrap(); + assert_eq!(drawn(&from_index), drawn(&from_database), "seed {seed}, step {step}, {query:?}"); } let tags = notes::list_tags(&world.engine).unwrap(); let mut library = crate::db::lock(&world.engine.db).unwrap(); diff --git a/crates/engine/src/json/layout.rs b/crates/engine/src/json/layout.rs index 211698850..52a70e167 100644 --- a/crates/engine/src/json/layout.rs +++ b/crates/engine/src/json/layout.rs @@ -36,13 +36,7 @@ pub(crate) fn place(nodes: &mut [JsonNode], column_gap: u32, node_gap: u32) -> ( } /// Where the subtree under `index` ends, placed from `top` down. -fn subtree( - nodes: &mut [JsonNode], - children: &[Vec], - index: usize, - top: u32, - gap: u32, -) -> u32 { +fn subtree(nodes: &mut [JsonNode], children: &[Vec], index: usize, top: u32, gap: u32) -> u32 { nodes[index].y = top; let mut bottom = top + nodes[index].height; let mut next = top; diff --git a/crates/engine/src/json/model.rs b/crates/engine/src/json/model.rs index d0c447342..8defc0645 100644 --- a/crates/engine/src/json/model.rs +++ b/crates/engine/src/json/model.rs @@ -166,11 +166,7 @@ pub fn explore(query: &JsonQuery) -> JsonView { graph: graph(&entries, &open, folded), tree, tree_truncated, - matches: hits - .iter() - .take(MAX_MATCHES) - .map(|entry| entry.path.clone()) - .collect(), + matches: hits.iter().take(MAX_MATCHES).map(|entry| entry.path.clone()).collect(), match_count: count(hits.len()), notices, } @@ -180,17 +176,8 @@ impl JsonView { fn invalid(error: JsonError, bytes: u32) -> Self { Self { error: Some(error), - stats: JsonStats { - keys: 0, - depth: 0, - bytes, - }, - graph: JsonGraph { - nodes: Vec::new(), - width: 0, - height: 0, - folded: false, - }, + stats: JsonStats { keys: 0, depth: 0, bytes }, + graph: JsonGraph { nodes: Vec::new(), width: 0, height: 0, folded: false }, tree: Vec::new(), tree_truncated: false, matches: Vec::new(), @@ -221,15 +208,7 @@ struct Entry { impl Entry { fn flatten(root: &Node, needle: &str) -> Vec { let mut entries = Vec::new(); - visit( - root, - None, - "$".to_string(), - "$".to_string(), - false, - &mut entries, - needle, - ); + visit(root, None, "$".to_string(), "$".to_string(), false, &mut entries, needle); entries } @@ -252,8 +231,7 @@ fn visit( let (kind, value, size, searched) = describe(&node.value); let hit = parent.is_some() && !needle.is_empty() - && (fold(&key).contains(needle) - || searched.is_some_and(|text| fold(text).contains(needle))); + && (fold(&key).contains(needle) || searched.is_some_and(|text| fold(text).contains(needle))); entries.push(Entry { parent, @@ -281,15 +259,7 @@ fn visit( Value::Object(members) => { for (name, child) in members { let path = member_path(&entries[index].path, name); - visit( - child, - Some(index), - name.clone(), - path, - false, - entries, - needle, - ); + visit(child, Some(index), name.clone(), path, false, entries, needle); } } Value::Array(items) => { @@ -306,24 +276,9 @@ fn visit( /// The kind, what a row shows, the size, and what the search reads of a scalar. fn describe(value: &Value) -> (JsonKind, String, u32, Option<&str>) { match value { - Value::Object(members) => ( - JsonKind::Object, - "{ … }".to_string(), - count(members.len()), - None, - ), - Value::Array(items) => ( - JsonKind::Array, - format!("[ {} ]", items.len()), - count(items.len()), - None, - ), - Value::String(text) => ( - JsonKind::String, - format!("\"{}\"", cut(text)), - 0, - Some(text), - ), + Value::Object(members) => (JsonKind::Object, "{ … }".to_string(), count(members.len()), None), + Value::Array(items) => (JsonKind::Array, format!("[ {} ]", items.len()), count(items.len()), None), + Value::String(text) => (JsonKind::String, format!("\"{}\"", cut(text)), 0, Some(text)), Value::Number(raw) => (JsonKind::Number, cut(raw), 0, Some(raw)), Value::Bool(true) => (JsonKind::Boolean, "true".to_string(), 0, Some("true")), Value::Bool(false) => (JsonKind::Boolean, "false".to_string(), 0, Some("false")), @@ -340,10 +295,7 @@ fn cut(text: &str) -> String { .take(VALUE_CHARS + 1) .collect(); if line.chars().count() > VALUE_CHARS { - format!( - "{}…", - line.chars().take(VALUE_CHARS - 1).collect::() - ) + format!("{}…", line.chars().take(VALUE_CHARS - 1).collect::()) } else { line } @@ -355,16 +307,11 @@ pub(crate) fn member_path(parent: &str, key: &str) -> String { .chars() .next() .is_some_and(|c| c.is_ascii_alphabetic() || c == '_' || c == '$') - && key - .chars() - .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$'); + && key.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$'); if identifier { format!("{parent}.{key}") } else { - format!( - "{parent}['{}']", - key.replace('\\', "\\\\").replace('\'', "\\'") - ) + format!("{parent}['{}']", key.replace('\\', "\\\\").replace('\'', "\\'")) } } @@ -377,11 +324,7 @@ fn stats(entries: &[Entry], bytes: u32) -> JsonStats { .max() .unwrap_or(0); - JsonStats { - keys: count(keys), - depth, - bytes, - } + JsonStats { keys: count(keys), depth, bytes } } /// Which containers are open, in breadth-first order so a cap keeps the levels nearest the @@ -400,9 +343,7 @@ fn opened(entries: &[Entry], opening: &JsonOpening) -> (BTreeSet, bool) { JsonOpening::Paths { .. } => { index == 0 || revealed.contains(&index) - || asked - .as_ref() - .is_some_and(|asked| asked.contains(entry.path.as_str())) + || asked.as_ref().is_some_and(|asked| asked.contains(entry.path.as_str())) } } }; @@ -443,11 +384,7 @@ fn opened(entries: &[Entry], opening: &JsonOpening) -> (BTreeSet, bool) { /// The containers above the path to reveal, which open whatever the paths say. fn revealed(entries: &[Entry], opening: &JsonOpening) -> BTreeSet { - let JsonOpening::Paths { - reveal: Some(target), - .. - } = opening - else { + let JsonOpening::Paths { reveal: Some(target), .. } = opening else { return BTreeSet::new(); }; let mut above = BTreeSet::new(); @@ -512,12 +449,7 @@ fn graph(entries: &[Entry], open: &BTreeSet, folded: bool) -> JsonGraph { .collect(); let (width, height) = super::layout::place(&mut nodes, COLUMN_GAP, NODE_GAP); - JsonGraph { - nodes, - width, - height, - folded, - } + JsonGraph { nodes, width, height, folded } } /// Wide enough for its widest row, within bounds: the front cuts what still overflows. @@ -527,9 +459,7 @@ fn width(entry: &Entry, rows: &[JsonRow]) -> u32 { let header = entry.key.chars().count() + 12; let widest = rows .iter() - .map(|row| { - row.key.chars().count() + row.value.chars().count() + if row.opens { 8 } else { 5 } - }) + .map(|row| row.key.chars().count() + row.value.chars().count() + if row.opens { 8 } else { 5 }) .max() .unwrap_or(0); @@ -620,10 +550,7 @@ mod tests { } fn paths(paths: &[&str]) -> JsonOpening { - JsonOpening::Paths { - paths: paths.iter().map(|path| (*path).to_string()).collect(), - reveal: None, - } + JsonOpening::Paths { paths: paths.iter().map(|path| (*path).to_string()).collect(), reveal: None } } fn searched(search: &str) -> JsonView { @@ -632,11 +559,7 @@ mod tests { /// The nodes drawn, by path. fn drawn(view: &JsonView) -> Vec<&str> { - view.graph - .nodes - .iter() - .map(|node| node.path.as_str()) - .collect() + view.graph.nodes.iter().map(|node| node.path.as_str()).collect() } fn node<'a>(view: &'a JsonView, path: &str) -> &'a JsonNode { @@ -657,9 +580,7 @@ mod tests { /// `count` arrays of `each` objects, in one object. fn arrays(count: usize, each: usize) -> String { - let arrays: Vec = (0..count) - .map(|i| format!(r#""a{i}": {}"#, objects(each))) - .collect(); + let arrays: Vec = (0..count).map(|i| format!(r#""a{i}": {}"#, objects(each))).collect(); format!("{{{}}}", arrays.join(",")) } @@ -697,27 +618,15 @@ mod tests { assert_eq!(drawn(&view), ["$"]); let data = &node(&view, "$").rows[3]; - assert_eq!( - (data.path.as_str(), data.child, data.size), - ("$.data", None, 1) - ); + assert_eq!((data.path.as_str(), data.child, data.size), ("$.data", None, 1)); } #[test] fn a_path_revealed_opens_everything_above_it() { - let reveal = |path: &str| JsonOpening::Paths { - paths: Vec::new(), - reveal: Some(path.to_string()), - }; + let reveal = |path: &str| JsonOpening::Paths { paths: Vec::new(), reveal: Some(path.to_string()) }; let view = opening(INVOICE, reveal("$.data.object.lines[1].description")); - let expected = [ - "$", - "$.data", - "$.data.object", - "$.data.object.lines", - "$.data.object.lines[1]", - ]; + let expected = ["$", "$.data", "$.data.object", "$.data.object.lines", "$.data.object.lines[1]"]; assert_eq!(drawn(&view), expected); assert_eq!(drawn(&opening(INVOICE, reveal("$.gone"))), ["$"]); } @@ -730,12 +639,7 @@ mod tests { assert!(view.graph.folded); assert_eq!(view.graph.nodes.len(), 21); let first = &view.graph.nodes[1]; - assert!( - first - .rows - .iter() - .all(|row| row.opens && row.child.is_none()) - ); + assert!(first.rows.iter().all(|row| row.opens && row.child.is_none())); } /// The cap keeps the levels nearest the root, and nothing says the arrays were folded. @@ -749,19 +653,9 @@ mod tests { .chain((0..20).map(|i| format!("$.a{i}"))) .collect(); - let view = opening( - &text, - JsonOpening::Paths { - paths: every, - reveal: None, - }, - ); + let view = opening(&text, JsonOpening::Paths { paths: every, reveal: None }); - let arrays = view - .graph - .nodes - .iter() - .filter(|node| node.kind == JsonKind::Array); + let arrays = view.graph.nodes.iter().filter(|node| node.kind == JsonKind::Array); assert_eq!(arrays.count(), 20); assert!(view.graph.nodes.len() <= MAX_NODES); } @@ -789,21 +683,14 @@ mod tests { #[test] fn a_node_lists_its_values_as_rows_of_one_line() { - let text = r#"{"s": "paid", "n": 4900, "t": true, "f": false, "z": null, "o": {"a": 1}, "l": [1, 2, 3]}"#; + let text = + r#"{"s": "paid", "n": 4900, "t": true, "f": false, "z": null, "o": {"a": 1}, "l": [1, 2, 3]}"#; let view = explored(text); let rows: Vec<_> = node(&view, "$") .rows .iter() - .map(|row| { - ( - row.key.as_str(), - row.value.as_str(), - row.kind, - row.size, - row.opens, - ) - }) + .map(|row| (row.key.as_str(), row.value.as_str(), row.kind, row.size, row.opens)) .collect(); assert_eq!( rows, @@ -822,41 +709,27 @@ mod tests { #[test] fn a_node_says_what_it_is_under_and_links_the_rows_it_opened() { let view = explored(INVOICE); - let (root, data, lines) = ( - node(&view, "$"), - node(&view, "$.data"), - node(&view, "$.data.object.lines"), - ); + let (root, data, lines) = + (node(&view, "$"), node(&view, "$.data"), node(&view, "$.data.object.lines")); assert_eq!( (root.label.as_str(), root.kind, root.size, root.parent), ("$", JsonKind::Object, 4, None) ); - assert_eq!( - (data.parent, root.rows[3].child), - (Some(root.id), Some(data.id)) - ); - assert_eq!( - (lines.label.as_str(), lines.kind, lines.size), - ("lines", JsonKind::Array, 2) - ); + assert_eq!((data.parent, root.rows[3].child), (Some(root.id), Some(data.id))); + assert_eq!((lines.label.as_str(), lines.kind, lines.size), ("lines", JsonKind::Array, 2)); assert_eq!(node(&view, "$.data.object.lines[0]").label, "[0]"); assert_eq!(lines.rows[1].key, "[1]"); } #[test] fn a_long_array_shows_its_first_rows_and_counts_the_rest() { - for (count, rows, hidden, height) in [ - (ROWS_PER_NODE, 200, 0, 201), - (ROWS_PER_NODE + 1, 200, 1, 202), - (500, 200, 300, 202), - ] { + for (count, rows, hidden, height) in + [(ROWS_PER_NODE, 200, 0, 201), (ROWS_PER_NODE + 1, 200, 1, 202), (500, 200, 300, 202)] + { let view = explored(&numbers(count)); let root = node(&view, "$"); - assert_eq!( - (root.rows.len(), root.hidden_rows, root.height), - (rows, hidden, height) - ); + assert_eq!((root.rows.len(), root.hidden_rows, root.height), (rows, hidden, height)); } } @@ -865,10 +738,7 @@ mod tests { let view = explored(INVOICE); let row = &node(&view, "$").rows[0]; - assert_eq!( - &INVOICE[row.span.start as usize..row.span.end as usize], - "\"evt_1PqX4c\"" - ); + assert_eq!(&INVOICE[row.span.start as usize..row.span.end as usize], "\"evt_1PqX4c\""); } /// « Copier la valeur » put `"Lyon"` in the clipboard, its quotes with it (COD-23). @@ -876,11 +746,7 @@ mod tests { fn a_string_carries_its_own_text_unquoted_and_nothing_else_does() { let view = explored(r#"{"ville": "Ly\"oné", "n": 4, "o": {"a": 1}}"#); - let texts: Vec<_> = node(&view, "$") - .rows - .iter() - .map(|row| row.text.as_deref()) - .collect(); + let texts: Vec<_> = node(&view, "$").rows.iter().map(|row| row.text.as_deref()).collect(); assert_eq!(texts, [Some("Ly\"oné"), None, None]); let lines: Vec<_> = view.tree.iter().map(|line| line.text.as_deref()).collect(); assert_eq!(lines, [None, Some("Ly\"oné"), None, None, None]); @@ -888,23 +754,13 @@ mod tests { #[test] fn a_value_is_cut_to_one_line_of_what_a_row_holds() { - let shown = |text: &str| { - node(&explored(&format!("[{text}]")), "$").rows[0] - .value - .clone() - }; + let shown = |text: &str| node(&explored(&format!("[{text}]")), "$").rows[0].value.clone(); let long = |count: usize| format!("\"{}\"", "x".repeat(count)); assert_eq!(shown(r#""a\nb\tc""#), "\"a b c\""); assert_eq!(shown(&long(VALUE_CHARS)), long(VALUE_CHARS)); - assert_eq!( - shown(&long(VALUE_CHARS + 1)), - format!("\"{}…\"", "x".repeat(VALUE_CHARS - 1)) - ); - assert_eq!( - shown(&"1".repeat(60)), - format!("{}…", "1".repeat(VALUE_CHARS - 1)) - ); + assert_eq!(shown(&long(VALUE_CHARS + 1)), format!("\"{}…\"", "x".repeat(VALUE_CHARS - 1))); + assert_eq!(shown(&"1".repeat(60)), format!("{}…", "1".repeat(VALUE_CHARS - 1))); } #[test] @@ -913,11 +769,7 @@ mod tests { r#"{"a key": 1, "it's": 2, "b\\s": 3, "1a": 4, "ok_1": 5, "$x": 6, "_": 7, "é": 8, "": 9}"#, ); - let paths: Vec<&str> = node(&view, "$") - .rows - .iter() - .map(|row| row.path.as_str()) - .collect(); + let paths: Vec<&str> = node(&view, "$").rows.iter().map(|row| row.path.as_str()).collect(); assert_eq!( paths, [ @@ -944,15 +796,9 @@ mod tests { let (root, data) = (column("$"), column("$.data")); assert_eq!(root.0, 0); assert_eq!(data.0, root.1 + COLUMN_GAP); - let (customer, lines) = ( - column("$.data.object.customer"), - column("$.data.object.lines"), - ); + let (customer, lines) = (column("$.data.object.customer"), column("$.data.object.lines")); assert_eq!(customer.0, lines.0); - assert_eq!( - column("$.data.object.lines[0]").0, - customer.0 + customer.1.max(lines.1) + COLUMN_GAP - ); + assert_eq!(column("$.data.object.lines[0]").0, customer.0 + customer.1.max(lines.1) + COLUMN_GAP); let period = column("$.data.object.lines[0].period"); assert_eq!(view.graph.width, period.0 + period.1); } @@ -970,12 +816,7 @@ mod tests { assert_eq!(data.y, 1 + 3); assert_eq!(customer.y, node(&view, "$.data.object").y + 1 + 1); assert_eq!(lines.y, customer.y + customer.height + NODE_GAP); - let bottom = view - .graph - .nodes - .iter() - .map(|node| node.y + node.height) - .max(); + let bottom = view.graph.nodes.iter().map(|node| node.y + node.height).max(); assert_eq!(Some(view.graph.height), bottom); } @@ -986,10 +827,7 @@ mod tests { assert_eq!(width(r#"{"a": 1}"#), MIN_WIDTH); assert_eq!(width(r#"{"a key of some length": 1234}"#), 20 + 4 + 5); assert_eq!(width(r#"{"a key of some length": {}}"#), 20 + 5 + 8); - assert_eq!( - width(&format!(r#"{{"key": "{}"}}"#, "x".repeat(200))), - MAX_WIDTH - ); + assert_eq!(width(&format!(r#"{{"key": "{}"}}"#, "x".repeat(200))), MAX_WIDTH); let long = explored(r#"{"a label longer than its rows": {"a": 1}}"#); assert_eq!(long.graph.nodes[1].width, 28 + 12); } @@ -1025,12 +863,8 @@ mod tests { assert!(node(&view, "$.data.object.lines[0].period").hit); assert!(node(&view, "$.data.object.lines[0]").rows[1].hit); assert!(!node(&view, "$.data.object.lines[0]").rows[0].hit); - let marked: Vec<&str> = view - .tree - .iter() - .filter(|line| line.hit) - .map(|line| line.key.as_str()) - .collect(); + let marked: Vec<&str> = + view.tree.iter().filter(|line| line.hit).map(|line| line.key.as_str()).collect(); assert_eq!(marked, ["period"]); } @@ -1039,10 +873,7 @@ mod tests { fn a_search_covers_what_is_not_open_in_the_document_s_order() { let view = explore(&query(INVOICE, "description", paths(&[]))); - let expected = [ - "$.data.object.lines[0].description", - "$.data.object.lines[1].description", - ]; + let expected = ["$.data.object.lines[0].description", "$.data.object.lines[1].description"]; assert_eq!(view.matches, expected); assert_eq!(view.graph.nodes.len(), 1); } @@ -1086,10 +917,7 @@ mod tests { let whole = opening(&numbers(MAX_TREE_LINES - 1), JsonOpening::All); let cut = opening(&numbers(MAX_TREE_LINES), JsonOpening::All); - assert_eq!( - (whole.tree.len(), whole.tree_truncated), - (MAX_TREE_LINES, false) - ); + assert_eq!((whole.tree.len(), whole.tree_truncated), (MAX_TREE_LINES, false)); assert_eq!((cut.tree.len(), cut.tree_truncated), (MAX_TREE_LINES, true)); } @@ -1103,11 +931,7 @@ mod tests { (r#"[{"é": [[1]]}]"#, 1, 3), ] { let stats = explored(text).stats; - assert_eq!( - (stats.keys, stats.depth, stats.bytes as usize), - (keys, depth, text.len()), - "{text}" - ); + assert_eq!((stats.keys, stats.depth, stats.bytes as usize), (keys, depth, text.len()), "{text}"); } } @@ -1118,14 +942,7 @@ mod tests { let error = view.error.unwrap(); assert_eq!((error.line, error.column), (1, 7)); assert!(view.graph.nodes.is_empty() && view.tree.is_empty() && view.matches.is_empty()); - assert_eq!( - view.stats, - JsonStats { - keys: 0, - depth: 0, - bytes: 7 - } - ); + assert_eq!(view.stats, JsonStats { keys: 0, depth: 0, bytes: 7 }); } #[test] @@ -1141,19 +958,10 @@ mod tests { #[test] fn another_format_is_explored_in_the_same_model_under_the_same_caps() { let yaml = |text: &str, opening| { - explore(&JsonQuery { - format: StructureFormat::Yaml, - ..query(text, "", opening) - }) + explore(&JsonQuery { format: StructureFormat::Yaml, ..query(text, "", opening) }) }; - let items = (0..150) - .map(|i| format!(" - i: {i}\n")) - .collect::>() - .concat(); - let lists = (0..20) - .map(|i| format!("a{i}:\n{items}")) - .collect::>() - .concat(); + let items = (0..150).map(|i| format!(" - i: {i}\n")).collect::>().concat(); + let lists = (0..20).map(|i| format!("a{i}:\n{items}")).collect::>().concat(); let capped = yaml(&lists, JsonOpening::All); assert_eq!((capped.graph.folded, capped.graph.nodes.len()), (true, 21)); @@ -1164,10 +972,7 @@ mod tests { assert_eq!(small.notices, [JsonNotice::FirstDocumentOnly]); let broken = yaml("a: [1\n", JsonOpening::Initial); - assert_eq!( - broken.error.map(|error| error.reason), - Some(JsonErrorReason::Malformed) - ); + assert_eq!(broken.error.map(|error| error.reason), Some(JsonErrorReason::Malformed)); } #[test] @@ -1178,9 +983,6 @@ mod tests { }); let row = &node(&view, "$").rows[0]; - assert_eq!( - (row.kind, row.value.as_str(), row.hit), - (JsonKind::Datetime, "1979-05-27", true) - ); + assert_eq!((row.kind, row.value.as_str(), row.hit), (JsonKind::Datetime, "1979-05-27", true)); } } diff --git a/crates/engine/src/json/parse.rs b/crates/engine/src/json/parse.rs index f7275a5fc..e55ecc8df 100644 --- a/crates/engine/src/json/parse.rs +++ b/crates/engine/src/json/parse.rs @@ -56,15 +56,9 @@ pub struct JsonError { pub(crate) const MAX_DEPTH: usize = 256; pub(crate) fn parse(text: &str) -> Result { - let mut parser = Parser { - bytes: text.as_bytes(), - at: 0, - utf16: 0, - }; - - let root = parser - .value(0) - .map_err(|reason| parser.error(text, reason))?; + let mut parser = Parser { bytes: text.as_bytes(), at: 0, utf16: 0 }; + + let root = parser.value(0).map_err(|reason| parser.error(text, reason))?; parser.whitespace(); if parser.at < parser.bytes.len() { return Err(parser.error(text, JsonErrorReason::TrailingCharacters)); @@ -130,13 +124,7 @@ impl Parser<'_> { Some(b'-' | b'0'..=b'9') => Value::Number(self.number()?), Some(_) => return Err(JsonErrorReason::UnexpectedCharacter), }; - Ok(Node { - value, - span: Span { - start, - end: self.utf16, - }, - }) + Ok(Node { value, span: Span { start, end: self.utf16 } }) } fn object(&mut self, depth: usize) -> Parsed { @@ -309,9 +297,7 @@ impl Parser<'_> { for _ in 0..4 { let digit = match self.peek() { None => return Err(JsonErrorReason::UnexpectedEnd), - Some(byte) => char::from(byte) - .to_digit(16) - .ok_or(JsonErrorReason::InvalidEscape)?, + Some(byte) => char::from(byte).to_digit(16).ok_or(JsonErrorReason::InvalidEscape)?, }; self.bump(); code = code * 16 + digit; @@ -393,27 +379,14 @@ mod tests { let keys: Vec<&str> = members.iter().map(|(key, _)| key.as_str()).collect(); assert_eq!(keys, ["b", "a", "b"]); - assert!( - matches!(&members[1].1.value, Value::Array(items) if items[1].value == number("3")) - ); - assert!( - matches!(&members[2].1.value, Value::Object(inner) if inner[0].1.value == number("4")) - ); + assert!(matches!(&members[1].1.value, Value::Array(items) if items[1].value == number("3"))); + assert!(matches!(&members[2].1.value, Value::Object(inner) if inner[0].1.value == number("4"))); } /// `1e3` stays `1e3`, and a number past `f64` loses nothing. #[test] fn a_number_is_kept_as_written() { - for text in [ - "0", - "-0", - "10", - "-1.50", - "1e3", - "1E+3", - "-1.5e-10", - "123456789012345678901234567890", - ] { + for text in ["0", "-0", "10", "-1.50", "1e3", "1E+3", "-1.5e-10", "123456789012345678901234567890"] { assert_eq!(read(text), number(text)); } } @@ -452,10 +425,8 @@ mod tests { let text = r#" ["😀", "é", {"a": 1}] "#; let root = parse(text).unwrap(); - let spans: Vec<(u32, u32)> = items(text) - .iter() - .map(|item| (item.span.start, item.span.end)) - .collect(); + let spans: Vec<(u32, u32)> = + items(text).iter().map(|item| (item.span.start, item.span.end)).collect(); assert_eq!(root.span, Span { start: 1, end: 22 }); assert_eq!(spans, [(2, 6), (8, 11), (13, 21)]); } @@ -532,10 +503,7 @@ mod tests { let objects = |depth: usize| format!("{}1{}", "{\"a\":".repeat(depth), "}".repeat(depth)); assert!(parse(&nested(MAX_DEPTH + 1)).is_ok()); - assert_eq!( - error(&nested(MAX_DEPTH + 2)).reason, - JsonErrorReason::TooDeep - ); + assert_eq!(error(&nested(MAX_DEPTH + 2)).reason, JsonErrorReason::TooDeep); assert_eq!(error(&"[".repeat(10_000)).reason, JsonErrorReason::TooDeep); assert!(parse(&objects(MAX_DEPTH)).is_ok()); let too_deep = error(&objects(MAX_DEPTH + 1)); diff --git a/crates/engine/src/json/position.rs b/crates/engine/src/json/position.rs index 3d2488e41..ad8bea94f 100644 --- a/crates/engine/src/json/position.rs +++ b/crates/engine/src/json/position.rs @@ -50,10 +50,7 @@ impl<'a> Positions<'a> { } pub(crate) fn span(&self, start: usize, end: usize) -> Span { - Span { - start: self.utf16(start), - end: self.utf16(end.max(start)), - } + Span { start: self.utf16(start), end: self.utf16(end.max(start)) } } pub(crate) fn error(&self, reason: JsonErrorReason, byte: usize) -> JsonError { @@ -102,11 +99,7 @@ mod tests { (2, 99, TEXT), (9, 0, TEXT), ] { - assert_eq!( - positions.byte_at(line, column), - before.len(), - "{line}:{column}" - ); + assert_eq!(positions.byte_at(line, column), before.len(), "{line}:{column}"); } } diff --git a/crates/engine/src/json/read.rs b/crates/engine/src/json/read.rs index 6ac639804..d151b0c91 100644 --- a/crates/engine/src/json/read.rs +++ b/crates/engine/src/json/read.rs @@ -28,10 +28,7 @@ pub(crate) struct Read { pub(crate) fn read(text: &str, format: StructureFormat) -> Result { match format { - StructureFormat::Json => parse(text).map(|root| Read { - root, - notices: Vec::new(), - }), + StructureFormat::Json => parse(text).map(|root| Read { root, notices: Vec::new() }), StructureFormat::Yaml => yaml::read(text), StructureFormat::Toml => toml::read(text), StructureFormat::Xml => xml::read(text), @@ -84,16 +81,9 @@ mod tests { let Value::Object(members) = read.root.value else { panic!("{format:?}"); }; - assert_eq!( - (members[0].0.as_str(), &members[0].1.value), - ("a", &Value::String("b".to_string())) - ); + assert_eq!((members[0].0.as_str(), &members[0].1.value), ("a", &Value::String("b".to_string()))); } - for format in [ - StructureFormat::Json, - StructureFormat::Toml, - StructureFormat::Xml, - ] { + for format in [StructureFormat::Json, StructureFormat::Toml, StructureFormat::Xml] { assert!(read("a: b", format).is_err(), "{format:?}"); } } diff --git a/crates/engine/src/json/toml.rs b/crates/engine/src/json/toml.rs index 64c741df4..d400408d3 100644 --- a/crates/engine/src/json/toml.rs +++ b/crates/engine/src/json/toml.rs @@ -17,17 +17,10 @@ pub(crate) fn read(text: &str) -> Result { })?; // The document's own span is empty: the root is the whole text. let root = table(root.get_ref(), &positions, 0, text.len(), 0)?; - Ok(Read { - root, - notices: Vec::new(), - }) + Ok(Read { root, notices: Vec::new() }) } -fn value( - spanned: &Spanned>, - positions: &Positions<'_>, - depth: usize, -) -> Result { +fn value(spanned: &Spanned>, positions: &Positions<'_>, depth: usize) -> Result { let span = spanned.span(); if depth > MAX_DEPTH { return Err(positions.error(JsonErrorReason::TooDeep, span.start)); @@ -46,10 +39,7 @@ fn value( ), DeValue::Table(members) => return table(members, positions, span.start, span.end, depth), }; - Ok(Node { - value, - span: positions.span(span.start, span.end), - }) + Ok(Node { value, span: positions.span(span.start, span.end) }) } /// A table written as `[name]` is placed on its header, an implicit one on its key. @@ -67,17 +57,9 @@ fn table( written.sort_by_key(|(key, _)| key.span().start); let members = written .into_iter() - .map(|(key, child)| { - Ok(( - key.get_ref().to_string(), - value(child, positions, depth + 1)?, - )) - }) + .map(|(key, child)| Ok((key.get_ref().to_string(), value(child, positions, depth + 1)?))) .collect::>()?; - Ok(Node { - value: Value::Object(members), - span: positions.span(start, end), - }) + Ok(Node { value: Value::Object(members), span: positions.span(start, end) }) } #[cfg(test)] @@ -100,10 +82,7 @@ mod tests { fn the_tables_and_keys_keep_the_order_they_were_written_in() { let root = root(CONFIG); - assert_eq!( - keys(&root), - ["title", "when", "site", "server", "a", "products"] - ); + assert_eq!(keys(&root), ["title", "when", "site", "server", "a", "products"]); let products = array(&members(&root)[5].1); assert_eq!(keys(&products[1]), ["inline", "name"]); } @@ -167,11 +146,7 @@ mod tests { fn an_unreadable_document_says_where_it_breaks() { for (text, line) in [("a = 1\nb = \n", 2), ("a = 1\na = 2", 2), ("\n\n[a", 3)] { let error = read(text).expect_err(text); - assert_eq!( - (error.reason, error.line), - (JsonErrorReason::Malformed, line), - "{text}" - ); + assert_eq!((error.reason, error.line), (JsonErrorReason::Malformed, line), "{text}"); } } @@ -186,14 +161,8 @@ mod tests { assert!(read(&nested(79, "1")).is_ok()); let too_deep = nested(39, &format!("{{ {} = 1 }}", path("c"))); - assert_eq!( - read(&too_deep).expect_err("too deep").reason, - JsonErrorReason::TooDeep - ); + assert_eq!(read(&too_deep).expect_err("too deep").reason, JsonErrorReason::TooDeep); let brackets = format!("a = {}1{}", "[".repeat(300), "]".repeat(300)); - assert_eq!( - read(&brackets).expect_err("too deep").reason, - JsonErrorReason::Malformed - ); + assert_eq!(read(&brackets).expect_err("too deep").reason, JsonErrorReason::Malformed); } } diff --git a/crates/engine/src/json/xml.rs b/crates/engine/src/json/xml.rs index b0c17e61c..8d5e54872 100644 --- a/crates/engine/src/json/xml.rs +++ b/crates/engine/src/json/xml.rs @@ -27,12 +27,7 @@ struct Element { } impl Element { - fn open( - tag: &BytesStart<'_>, - start: usize, - end: usize, - positions: &Positions<'_>, - ) -> Result { + fn open(tag: &BytesStart<'_>, start: usize, end: usize, positions: &Positions<'_>) -> Result { let mut element = Self { name: tag.name().as_ref().to_owned(), start, @@ -52,22 +47,14 @@ impl Element { let (from, to) = match &attribute.value { Cow::Borrowed(raw) => { let from = (raw.as_ptr() as usize).wrapping_sub(source.as_ptr() as usize); - if from <= source.len() { - (from, from + raw.len()) - } else { - (start, end) - } + if from <= source.len() { (from, from + raw.len()) } else { (start, end) } } Cow::Owned(_) => (start, end), }; let key = format!("@{}", attribute.key.as_ref()); - element.members.push(( - key, - Node { - value: Value::String(value), - span: positions.span(from, to), - }, - )); + element + .members + .push((key, Node { value: Value::String(value), span: positions.span(from, to) })); } Ok(element) } @@ -93,21 +80,12 @@ impl Element { self.empty = false; match self.members.iter_mut().find(|(key, _)| *key == name) { Some((_, existing)) => { - let span = Span { - start: existing.span.start, - end: node.span.end, - }; + let span = Span { start: existing.span.start, end: node.span.end }; if let Value::Array(items) = &mut existing.value { items.push(node); } else { let first = std::mem::replace(&mut existing.value, Value::Null); - existing.value = Value::Array(vec![ - Node { - value: first, - span: existing.span, - }, - node, - ]); + existing.value = Value::Array(vec![Node { value: first, span: existing.span }, node]); } existing.span = span; } @@ -120,35 +98,19 @@ impl Element { fn close(mut self, end: usize, positions: &Positions<'_>) -> (String, Node) { let text = self.text.trim().to_owned(); let whole = positions.span(self.start, end); - let written = self - .text_at - .map_or(whole, |(from, to)| positions.span(from, to)); + let written = self.text_at.map_or(whole, |(from, to)| positions.span(from, to)); let node = if self.members.is_empty() { if text.is_empty() && self.empty { - Node { - value: Value::Null, - span: whole, - } + Node { value: Value::Null, span: whole } } else { - Node { - value: Value::String(text), - span: written, - } + Node { value: Value::String(text), span: written } } } else { if !text.is_empty() { - self.members.push(( - "#text".to_owned(), - Node { - value: Value::String(text), - span: written, - }, - )); - } - Node { - value: Value::Object(self.members), - span: whole, + self.members + .push(("#text".to_owned(), Node { value: Value::String(text), span: written })); } + Node { value: Value::Object(self.members), span: whole } }; (self.name, node) } @@ -157,11 +119,7 @@ impl Element { /// A character reference, or one of XML's five entities: without a DTD, no other is defined. fn resolve(reference: &BytesRef<'_>) -> Option { if reference.is_char_ref() { - return reference - .resolve_char_ref() - .ok() - .flatten() - .map(String::from); + return reference.resolve_char_ref().ok().flatten().map(String::from); } resolve_predefined_entity(reference).map(str::to_owned) } @@ -174,10 +132,7 @@ pub(crate) struct Refusal { impl Refusal { fn malformed(at: usize) -> Self { - Self { - at, - reason: JsonErrorReason::Malformed, - } + Self { at, reason: JsonErrorReason::Malformed } } } @@ -191,17 +146,12 @@ pub(crate) fn document(text: &str) -> Result { loop { let before = at(&reader); - let event = reader - .read_event() - .map_err(|_| Refusal::malformed(at(&reader)))?; + let event = reader.read_event().map_err(|_| Refusal::malformed(at(&reader)))?; let after = at(&reader); match event { Event::Start(tag) => { if open.len() >= MAX_DEPTH { - return Err(Refusal { - at: before, - reason: JsonErrorReason::TooDeep, - }); + return Err(Refusal { at: before, reason: JsonErrorReason::TooDeep }); } let element = Element::open(&tag, before, after, &positions) .map_err(|()| Refusal::malformed(before))?; @@ -211,14 +161,12 @@ pub(crate) fn document(text: &str) -> Result { let element = Element::open(&tag, before, after, &positions) .map_err(|()| Refusal::malformed(before))?; let (name, node) = element.close(after, &positions); - attach(&mut open, &mut root, name, node) - .map_err(|()| Refusal::malformed(before))?; + attach(&mut open, &mut root, name, node).map_err(|()| Refusal::malformed(before))?; } Event::End(_) => { let element = open.pop().ok_or_else(|| Refusal::malformed(before))?; let (name, node) = element.close(after, &positions); - attach(&mut open, &mut root, name, node) - .map_err(|()| Refusal::malformed(before))?; + attach(&mut open, &mut root, name, node).map_err(|()| Refusal::malformed(before))?; } Event::Text(raw) => { let content = raw.xml10_content(); @@ -261,10 +209,7 @@ pub(crate) fn document(text: &str) -> Result { return Err(Refusal::malformed(text.len())); } let (name, node) = root.ok_or_else(|| Refusal::malformed(0))?; - Ok(Node { - value: Value::Object(vec![(name, node)]), - span: positions.span(0, text.len()), - }) + Ok(Node { value: Value::Object(vec![(name, node)]), span: positions.span(0, text.len()) }) } fn attach( @@ -288,10 +233,7 @@ fn attach( pub(crate) fn read(text: &str) -> Result { document(text) - .map(|root| Read { - root, - notices: Vec::new(), - }) + .map(|root| Read { root, notices: Vec::new() }) .map_err(|refusal| Positions::new(text).error(refusal.reason, refusal.at)) } @@ -299,10 +241,7 @@ pub(crate) fn read(text: &str) -> Result { pub(crate) fn to_value(node: &Node) -> serde_json::Value { match &node.value { Value::Object(members) => serde_json::Value::Object( - members - .iter() - .map(|(key, child)| (key.clone(), to_value(child))) - .collect(), + members.iter().map(|(key, child)| (key.clone(), to_value(child))).collect(), ), Value::Array(items) => serde_json::Value::Array(items.iter().map(to_value).collect()), Value::String(text) | Value::Number(text) | Value::Datetime(text) => { @@ -353,19 +292,10 @@ mod tests { ("x", serde_json::json!("x")), (" x y ", serde_json::json!("x y")), ("", serde_json::json!({ "@x": "1" })), - ( - "t", - serde_json::json!({ "@x": "1", "#text": "t" }), - ), + ("t", serde_json::json!({ "@x": "1", "#text": "t" })), ("1", serde_json::json!({ "b": "1" })), - ( - "tu", - serde_json::json!({ "b": null, "#text": "tu" }), - ), - ( - "123", - serde_json::json!({ "b": ["1", "2", "3"], "c": null }), - ), + ("tu", serde_json::json!({ "b": null, "#text": "tu" })), + ("123", serde_json::json!({ "b": ["1", "2", "3"], "c": null })), ("", serde_json::json!({ "b": "" })), ("x ]]>y", serde_json::json!("x y")), ("x", serde_json::json!("x")), @@ -378,10 +308,7 @@ mod tests { fn references_are_resolved_in_a_text_and_in_an_attribute() { let read = json("&<>"'😀A"); - assert_eq!( - read, - serde_json::json!({ "a": { "@k": "1 < 2 é", "#text": "&<>\"'😀A" } }) - ); + assert_eq!(read, serde_json::json!({ "a": { "@k": "1 < 2 é", "#text": "&<>\"'😀A" } })); } #[test] @@ -390,10 +317,7 @@ mod tests { let note = members(&members(&order)[3].1); assert_eq!((note[0].0.as_str(), note[1].0.as_str()), ("b", "#text")); - assert_eq!( - note[1].1.value, - Value::String("payée & livrée".to_string()) - ); + assert_eq!(note[1].1.value, Value::String("payée & livrée".to_string())); } /// A text-only element on its text, an attribute on its value, a list from its first to its @@ -405,17 +329,11 @@ mod tests { let lines = array(&top[2].1); assert_eq!(slice(ORDER, &top[1].1), "42"); - assert_eq!( - slice(ORDER, &lines[0]), - "Pro · mensuel" - ); + assert_eq!(slice(ORDER, &lines[0]), "Pro · mensuel"); assert_eq!(slice(ORDER, &members(&lines[0])[1].1), "Pro · mensuel"); let both = "Pro · mensuel\n Stockage"; assert_eq!(slice(ORDER, &top[2].1), both); - assert_eq!( - slice(ORDER, &members(&top[3].1)[1].1), - "payée & vite livrée" - ); + assert_eq!(slice(ORDER, &members(&top[3].1)[1].1), "payée & vite livrée"); assert_eq!(slice(ORDER, &top[4].1), "a < b"); assert_eq!(slice(ORDER, &top[5].1), ""); } @@ -460,11 +378,7 @@ mod tests { ("", 1), ] { let error = read(text).expect_err(text); - assert_eq!( - (error.reason, error.line), - (JsonErrorReason::Malformed, line), - "{text}" - ); + assert_eq!((error.reason, error.line), (JsonErrorReason::Malformed, line), "{text}"); } } @@ -473,19 +387,13 @@ mod tests { let nested = |depth: usize| format!("{}{}", "".repeat(depth), "".repeat(depth)); assert!(read(&nested(MAX_DEPTH)).is_ok()); - assert_eq!( - read(&nested(MAX_DEPTH + 1)).expect_err("too deep").reason, - JsonErrorReason::TooDeep - ); + assert_eq!(read(&nested(MAX_DEPTH + 1)).expect_err("too deep").reason, JsonErrorReason::TooDeep); } /// A tree of another format goes through the same conversion. #[test] fn a_number_a_date_and_a_boolean_are_handed_as_values() { - let node = |value: Value| Node { - value, - span: Span { start: 0, end: 0 }, - }; + let node = |value: Value| Node { value, span: Span { start: 0, end: 0 } }; let list = Value::Array(vec![ node(Value::Number("1".to_string())), node(Value::Datetime("1979-05-27".to_string())), @@ -493,9 +401,6 @@ mod tests { node(Value::Null), ]); - assert_eq!( - to_value(&node(list)), - serde_json::json!(["1", "1979-05-27", true, null]) - ); + assert_eq!(to_value(&node(list)), serde_json::json!(["1", "1979-05-27", true, null])); } } diff --git a/crates/engine/src/json/yaml.rs b/crates/engine/src/json/yaml.rs index b151f3a87..24f710d6f 100644 --- a/crates/engine/src/json/yaml.rs +++ b/crates/engine/src/json/yaml.rs @@ -17,19 +17,8 @@ use super::read::{JsonNotice, Read}; const MAX_VALUES: usize = 200_000; enum Frame { - Mapping { - start: usize, - anchor: usize, - members: Vec<(String, Node)>, - key: Option, - end: usize, - }, - Sequence { - start: usize, - anchor: usize, - items: Vec, - end: usize, - }, + Mapping { start: usize, anchor: usize, members: Vec<(String, Node)>, key: Option, end: usize }, + Sequence { start: usize, anchor: usize, items: Vec, end: usize }, } struct Reader<'a> { @@ -53,9 +42,7 @@ pub(crate) fn read(text: &str) -> Result { let mut notices = Vec::new(); loop { - let (event, marker) = parser - .next_token() - .map_err(|error| reader.refused(&error))?; + let (event, marker) = parser.next_token().map_err(|error| reader.refused(&error))?; let at = reader.byte(&marker); match event { Event::StreamEnd => break, @@ -66,19 +53,12 @@ pub(crate) fn read(text: &str) -> Result { break; } } - Event::MappingStart(anchor, _) => reader.open(Frame::Mapping { - start: at, - anchor, - members: Vec::new(), - key: None, - end: at, - })?, - Event::SequenceStart(anchor, _) => reader.open(Frame::Sequence { - start: at, - anchor, - items: Vec::new(), - end: at, - })?, + Event::MappingStart(anchor, _) => { + reader.open(Frame::Mapping { start: at, anchor, members: Vec::new(), key: None, end: at })?; + } + Event::SequenceStart(anchor, _) => { + reader.open(Frame::Sequence { start: at, anchor, items: Vec::new(), end: at })?; + } Event::MappingEnd | Event::SequenceEnd => reader.close(at)?, Event::Scalar(raw, style, anchor, tag) => { reader.scalar(raw, style, anchor, tag.as_ref(), at)?; @@ -88,10 +68,9 @@ pub(crate) fn read(text: &str) -> Result { } } - let root = reader.root.unwrap_or(Node { - value: Value::Null, - span: reader.positions.span(0, 0), - }); + let root = reader + .root + .unwrap_or(Node { value: Value::Null, span: reader.positions.span(0, 0) }); Ok(Read { root, notices }) } @@ -129,25 +108,13 @@ impl Reader<'_> { let text = self.positions.text(); let bracket = matches!(text.as_bytes().get(at), Some(b'}' | b']')); let (value, start, anchor, last) = match frame { - Frame::Mapping { - start, - anchor, - members, - end, - .. - } => (Value::Object(members), start, anchor, end), - Frame::Sequence { - start, - anchor, - items, - end, - } => (Value::Array(items), start, anchor, end), + Frame::Mapping { start, anchor, members, end, .. } => { + (Value::Object(members), start, anchor, end) + } + Frame::Sequence { start, anchor, items, end } => (Value::Array(items), start, anchor, end), }; let end = if bracket { at + 1 } else { last }; - let node = Node { - value, - span: self.positions.span(start, end), - }; + let node = Node { value, span: self.positions.span(start, end) }; self.place(node, anchor, None, start, end) } @@ -162,17 +129,12 @@ impl Reader<'_> { let text = self.positions.text(); // A `|` or `>` block is marked on its first line of content: it starts on its indicator. let at = match style { - TScalarStyle::Literal | TScalarStyle::Folded => { - text[..at].rfind(['|', '>']).unwrap_or(at) - } + TScalarStyle::Literal | TScalarStyle::Folded => text[..at].rfind(['|', '>']).unwrap_or(at), _ => at, }; let end = scalar_end(text, at, &raw, style); let value = typed(&raw, style, tag); - let node = Node { - value, - span: self.positions.span(at, end), - }; + let node = Node { value, span: self.positions.span(at, end) }; self.place(node, anchor, Some(raw), at, end) } @@ -203,9 +165,7 @@ impl Reader<'_> { ) -> Result<(), JsonError> { self.values += 1; if self.values > MAX_VALUES { - return Err(self - .positions - .error(JsonErrorReason::TooLarge, end.saturating_sub(1))); + return Err(self.positions.error(JsonErrorReason::TooLarge, end.saturating_sub(1))); } if anchor > 0 { self.anchors.insert(anchor, node.clone()); @@ -213,13 +173,7 @@ impl Reader<'_> { let text = self.positions.text(); match self.stack.last_mut() { None => self.root = Some(node), - Some(Frame::Mapping { - members, - key, - start: first, - end: last, - .. - }) => { + Some(Frame::Mapping { members, key, start: first, end: last, .. }) => { *first = (*first).min(start); *last = (*last).max(end); match key.take() { @@ -227,12 +181,7 @@ impl Reader<'_> { Some(name) => members.push((name, node)), } } - Some(Frame::Sequence { - items, - start: first, - end: last, - .. - }) => { + Some(Frame::Sequence { items, start: first, end: last, .. }) => { *first = (*first).min(start); *last = (*last).max(end); items.push(node); @@ -327,9 +276,7 @@ fn block_end(text: &str, start: usize) -> usize { let mut at = end; while at < text.len() { let next = at + 1; - let line_end = text[next..] - .find('\n') - .map_or(text.len(), |offset| next + offset); + let line_end = text[next..].find('\n').map_or(text.len(), |offset| next + offset); let line = &text[next..line_end]; if !line.trim().is_empty() { if indentation(line) <= indent { @@ -368,10 +315,7 @@ mod tests { assert_eq!(top[0].1.value, Value::String("api".to_string())); assert_eq!(array(&top[1].1)[1].value, Value::Number("443".to_string())); let env = members(&top[2].1); - assert_eq!( - (&env[0].1.value, &env[1].1.value), - (&Value::Bool(true), &Value::Null) - ); + assert_eq!((&env[0].1.value, &env[1].1.value), (&Value::Bool(true), &Value::Null)); } /// The core schema: quoted, or tagged as a string, it stays one. @@ -393,11 +337,7 @@ mod tests { ("\"true\"", string("true")), ("!!str 12", string("12")), ] { - assert_eq!( - members(&root(&format!("a: {text}\n")))[0].1.value, - value, - "{text}" - ); + assert_eq!(members(&root(&format!("a: {text}\n")))[0].1.value, value, "{text}"); } assert_eq!(members(&root("a: |\n 12\n"))[0].1.value, string("12\n")); assert_eq!(members(&root("a:\n"))[0].1.value, Value::Null); @@ -419,11 +359,7 @@ mod tests { "|-\n kept", ] { let text = format!("a: {written} # note\nb: 1\n").replace("\n ", "\n "); - let text = if written.contains('\n') { - format!("a: {written}\nb: 1\n") - } else { - text - }; + let text = if written.contains('\n') { format!("a: {written}\nb: 1\n") } else { text }; let root = root(&text); assert_eq!(slice(&text, &members(&root)[0].1), written, "{text}"); } @@ -434,10 +370,7 @@ mod tests { let text = "a: one\n two\nb: 1\n"; let root = root(text); - assert_eq!( - members(&root)[0].1.value, - Value::String("one two".to_string()) - ); + assert_eq!(members(&root)[0].1.value, Value::String("one two".to_string())); assert_eq!(slice(text, &members(&root)[0].1), "one"); } @@ -467,10 +400,7 @@ mod tests { let top = members(&root); assert_eq!((top[0].1.span.start, top[0].1.span.end), (4, 11)); - assert_eq!( - (top[1].0.as_str(), slice(text, &top[1].1)), - ("é", "[é]".to_string()) - ); + assert_eq!((top[1].0.as_str(), slice(text, &top[1].1)), ("é", "[é]".to_string())); } /// "Show in code" goes to the anchor; a merge key is kept as read. @@ -522,12 +452,7 @@ mod tests { #[test] fn an_unreadable_document_says_where_it_breaks() { - for text in [ - "a: 1\nb: [1, 2\n", - "ok: 1\n🦀: \"open\n", - "a: 1\n b: 2\n", - "a: 1\nb: *nowhere\n", - ] { + for text in ["a: 1\nb: [1, 2\n", "ok: 1\n🦀: \"open\n", "a: 1\n b: 2\n", "a: 1\nb: *nowhere\n"] { let error = read(text).expect_err(text); assert_eq!(error.reason, JsonErrorReason::Malformed, "{text}"); assert!(error.line >= 2 && error.column >= 1, "{text}: {error:?}"); @@ -538,9 +463,7 @@ mod tests { fn a_nesting_deeper_than_can_be_walked_is_refused() { let flow = format!("{}1{}", "[".repeat(300), "]".repeat(300)); let block = |depth: usize| { - let lines: Vec = (0..depth) - .map(|level| format!("{}a:", " ".repeat(level))) - .collect(); + let lines: Vec = (0..depth).map(|level| format!("{}a:", " ".repeat(level))).collect(); lines.join("\n") }; diff --git a/crates/engine/src/layout.rs b/crates/engine/src/layout.rs index fdfae3b9f..70646ecd4 100644 --- a/crates/engine/src/layout.rs +++ b/crates/engine/src/layout.rs @@ -16,8 +16,7 @@ macro_rules! database { pub(crate) const DATABASE: &str = database!(); /// What SQLite keeps beside the database under WAL; they travel with it. -pub(crate) const DATABASE_SIDECARS: [&str; 2] = - [concat!(database!(), "-wal"), concat!(database!(), "-shm")]; +pub(crate) const DATABASE_SIDECARS: [&str; 2] = [concat!(database!(), "-wal"), concat!(database!(), "-shm")]; /// The library's key, wrapped under the passphrase. pub(crate) const KEY_FILE: &str = "vault.json"; @@ -40,16 +39,10 @@ pub(crate) const REPLACED: &str = "replaced"; pub const PREFERENCES: &str = "preferences.json"; /// Every file a library is made of. -pub(crate) const LIBRARY_FILES: [&str; 4] = [ - DATABASE, - DATABASE_SIDECARS[0], - DATABASE_SIDECARS[1], - KEY_FILE, -]; +pub(crate) const LIBRARY_FILES: [&str; 4] = [DATABASE, DATABASE_SIDECARS[0], DATABASE_SIDECARS[1], KEY_FILE]; /// Every directory a library accumulates. -pub(crate) const LIBRARY_DIRECTORIES: [&str; 5] = - [ATTACHMENTS, BACKUPS, DAMAGED, ARCHIVED, REPLACED]; +pub(crate) const LIBRARY_DIRECTORIES: [&str; 5] = [ATTACHMENTS, BACKUPS, DAMAGED, ARCHIVED, REPLACED]; /// The list of libraries, at the profile root and owned by none of them. pub(crate) const REGISTRY: &str = "libraries.json"; @@ -70,9 +63,7 @@ pub(crate) fn stamp(at: DateTime) -> String { } pub(crate) fn parse_stamp(name: &str) -> Option> { - NaiveDateTime::parse_from_str(name, STAMP) - .ok() - .map(|at| at.and_utc()) + NaiveDateTime::parse_from_str(name, STAMP).ok().map(|at| at.and_utc()) } #[cfg(test)] @@ -117,13 +108,7 @@ mod tests { /// A folder that is not a stamp is never taken for a copy. #[test] fn a_name_that_is_not_a_stamp_reads_as_none() { - for name in [ - "notes", - "2026-07-25", - "2026-07-25 09:05:07", - "../2026-07-25_09-05-07", - "", - ] { + for name in ["notes", "2026-07-25", "2026-07-25 09:05:07", "../2026-07-25_09-05-07", ""] { assert_eq!(parse_stamp(name), None, "{name}"); } } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 628cc26cc..b6ed03428 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -69,8 +69,7 @@ impl Engine { /// Whether the next unlock takes the day's copy; it does until told otherwise. pub fn keep_launch_copies(&self, wanted: bool) { - self.launch_copies - .store(wanted, std::sync::atomic::Ordering::Relaxed); + self.launch_copies.store(wanted, std::sync::atomic::Ordering::Relaxed); } /// For the tests, which open a library of their own. @@ -151,9 +150,7 @@ pub(crate) fn sweep(engine: &Engine) { let db = &engine.db; // ⚠️ The copy before the sweeps: it is worth most holding what retention will purge. - let wanted = engine - .launch_copies - .load(std::sync::atomic::Ordering::Relaxed); + let wanted = engine.launch_copies.load(std::sync::atomic::Ordering::Relaxed); backup::take(wanted, db); notes::trash::sweep_at_startup(db); diff --git a/crates/engine/src/libraries.rs b/crates/engine/src/libraries.rs index dded1c581..58207ee07 100644 --- a/crates/engine/src/libraries.rs +++ b/crates/engine/src/libraries.rs @@ -12,8 +12,7 @@ use std::path::PathBuf; use crate::Engine; use crate::error::{AppError, StorageError}; use registry::{ - LibraryEntry, Registry, create_in, delete_in, open_directory_in, point_at, registry_in, - rename_in, + LibraryEntry, Registry, create_in, delete_in, open_directory_in, point_at, registry_in, rename_in, }; /// The directory of the library the registry points at, for what runs while none is open: diff --git a/crates/engine/src/libraries/registry.rs b/crates/engine/src/libraries/registry.rs index a7021c529..63c26ba5c 100644 --- a/crates/engine/src/libraries/registry.rs +++ b/crates/engine/src/libraries/registry.rs @@ -83,10 +83,7 @@ fn read(profile: &Path) -> Option { /// An unreadable registry moved aside, as it was, and the list made again from the folders /// under `libraries/` that hold one. Their names were in the file: they come back unnamed. fn rebuilt(profile: &Path) -> Registry { - let aside = format!( - "{REGISTRY}.unreadable-{}", - Utc::now().format("%Y%m%d-%H%M%S") - ); + let aside = format!("{REGISTRY}.unreadable-{}", Utc::now().format("%Y%m%d-%H%M%S")); if let Err(error) = std::fs::rename(profile.join(REGISTRY), profile.join(&aside)) { log::warn!("The unreadable registry was not set aside: {error}"); } @@ -101,19 +98,11 @@ fn rebuilt(profile: &Path) -> Registry { .metadata() .and_then(|metadata| metadata.created()) .map_or_else(|_| Utc::now(), DateTime::::from); - Some(LibraryEntry { - directory: format!("{LIBRARIES}/{id}"), - id, - name: String::new(), - created_at, - }) + Some(LibraryEntry { directory: format!("{LIBRARIES}/{id}"), id, name: String::new(), created_at }) }) .collect(); libraries.sort_by_key(|entry| entry.created_at); - let registry = Registry { - open: libraries.first().map(|entry| entry.id.clone()), - libraries, - }; + let registry = Registry { open: libraries.first().map(|entry| entry.id.clone()), libraries }; if !registry.libraries.is_empty() { let _ = write(profile, ®istry); } @@ -163,12 +152,7 @@ pub(crate) fn registry_in(profile: &Path) -> Registry { fn fresh(name: String) -> LibraryEntry { let id = uuid::Uuid::new_v4().to_string(); - LibraryEntry { - directory: format!("{LIBRARIES}/{id}"), - id, - name, - created_at: Utc::now(), - } + LibraryEntry { directory: format!("{LIBRARIES}/{id}"), id, name, created_at: Utc::now() } } /// Public for the benchmark that says what an open library saves by not calling it. @@ -253,11 +237,7 @@ mod tests { } fn ids(registry: &Registry) -> Vec<&str> { - registry - .libraries - .iter() - .map(|entry| entry.id.as_str()) - .collect() + registry.libraries.iter().map(|entry| entry.id.as_str()).collect() } /// A first launch: one unnamed library, open, in a folder of its own, written down. @@ -300,10 +280,7 @@ mod tests { assert!(profile.path().join(crate::layout::PREFERENCES).is_file()); std::fs::write(profile.path().join(DATABASE), b"later").unwrap(); registry_in(profile.path()); - assert!( - profile.path().join(DATABASE).is_file(), - "gathered a second time" - ); + assert!(profile.path().join(DATABASE).is_file(), "gathered a second time"); } /// Never taken for an absent file, which a first launch would write over: set aside as it @@ -324,17 +301,9 @@ mod tests { let aside = std::fs::read_dir(profile.path()) .unwrap() .filter_map(Result::ok) - .any(|entry| { - entry - .file_name() - .to_string_lossy() - .starts_with("libraries.json.unreadable-") - }); + .any(|entry| entry.file_name().to_string_lossy().starts_with("libraries.json.unreadable-")); assert!(aside); - assert!( - profile.path().join(&empty.directory).is_dir(), - "a folder is never deleted here" - ); + assert!(profile.path().join(&empty.directory).is_dir(), "a folder is never deleted here"); } /// A registry the system refuses to read is no absent one either. @@ -406,10 +375,7 @@ mod tests { let registry = registry_in(profile.path()); assert_eq!(registry.open.as_deref(), Some(added.id.as_str())); assert_eq!(registry.entry(&added.id).unwrap().name, "Home"); - assert_eq!( - open_directory_in(profile.path()).unwrap(), - profile.path().join(&added.directory) - ); + assert_eq!(open_directory_in(profile.path()).unwrap(), profile.path().join(&added.directory)); } #[test] @@ -447,10 +413,7 @@ mod tests { let profile = profile(); let only = registry_in(profile.path()).libraries[0].clone(); - assert!(matches!( - delete_in(profile.path(), &only.id), - Err(StorageError::LastLibrary) - )); + assert!(matches!(delete_in(profile.path(), &only.id), Err(StorageError::LastLibrary))); assert!(profile.path().join(&only.directory).is_dir()); } } diff --git a/crates/engine/src/name.rs b/crates/engine/src/name.rs index 55fc42051..08b543d39 100644 --- a/crates/engine/src/name.rs +++ b/crates/engine/src/name.rs @@ -7,10 +7,7 @@ use crate::error::ValidationError; pub(crate) fn readable(raw: &str, what: &str) -> Result { let trimmed = raw.trim(); if trimmed.is_empty() { - return Err(ValidationError::new( - "name", - format!("a {what} must have a readable name"), - )); + return Err(ValidationError::new("name", format!("a {what} must have a readable name"))); } Ok(trimmed.to_string()) diff --git a/crates/engine/src/notes.rs b/crates/engine/src/notes.rs index 0c5b5b148..27013e775 100644 --- a/crates/engine/src/notes.rs +++ b/crates/engine/src/notes.rs @@ -57,10 +57,7 @@ pub fn query_notes(engine: &Engine, query: &NotesQuery) -> Result Result { +pub(crate) fn query_notes_from_database(engine: &Engine, query: &NotesQuery) -> Result { let db = &engine.db; let mut connection = lock(db)?; let (notes, facets) = store::fetch(&mut connection, query)?; @@ -104,11 +101,7 @@ pub fn list_drawings(engine: &Engine) -> Result, AppErr Ok(pictures::drawings(connection, vault)?) } -fn picture_of( - engine: &Engine, - id: &str, - which: pictures::Which, -) -> Result, AppError> { +fn picture_of(engine: &Engine, id: &str, which: pictures::Which) -> Result, AppError> { let mut connection = lock(&engine.db)?; let (connection, vault) = connection.split(); Ok(pictures::read(connection, vault, id, which)?) @@ -151,10 +144,7 @@ pub fn duplicate_note(engine: &Engine, id: &str, title: String) -> Result Result { engine.write(|db| { // Read before anything is locked: two PNGs, or the patch is refused. - let drawn = patch - .pictures - .as_ref() - .map(drawing::DrawingPictures::decoded) - .transpose()?; + let drawn = patch.pictures.as_ref().map(drawing::DrawingPictures::decoded).transpose()?; // `Some(None)`: the pictures are taken away, the drawing having been emptied. let mut connection = lock(db)?; - let note = store::update_drawn( - &mut connection, - id, - patch, - drawn.as_ref().map(Option::as_ref), - Utc::now(), - )?; + let note = + store::update_drawn(&mut connection, id, patch, drawn.as_ref().map(Option::as_ref), Utc::now())?; let answer = display(&mut connection, note)?; let changed = Changed::notes([id.to_owned()]); @@ -217,10 +198,7 @@ pub fn convert_note( let mut connection = lock(db)?; let (note, previous) = store::convert(&mut connection, id, into, Utc::now())?; - let answer = convert::NoteConversion { - note: display(&mut connection, note)?, - previous, - }; + let answer = convert::NoteConversion { note: display(&mut connection, note)?, previous }; let changed = Changed::notes([id.to_owned()]); Ok((answer, changed)) }) @@ -239,17 +217,12 @@ pub fn list_revisions(engine: &Engine, id: &str) -> Result, AppErr } /// What going back to a kept body would change, line by line, against the current text. -pub fn revision_diff( - engine: &Engine, - id: &str, - revision_id: String, -) -> Result, AppError> { +pub fn revision_diff(engine: &Engine, id: &str, revision_id: String) -> Result, AppError> { let db = &engine.db; let mut connection = lock(db)?; let (connection, vault) = connection.split(); - let Some((current, version)) = store::revisions::compare(connection, vault, id, &revision_id)? - else { + let Some((current, version)) = store::revisions::compare(connection, vault, id, &revision_id)? else { return Err(StorageError::RevisionNotFound(revision_id).into()); }; @@ -259,11 +232,7 @@ pub fn revision_diff( /// Goes back to a kept body, dropping it and every body kept after it from the history. /// /// Leaves `updated_at` alone: putting something back is not editing it. -pub fn restore_revision( - engine: &Engine, - id: &str, - revision_id: &str, -) -> Result { +pub fn restore_revision(engine: &Engine, id: &str, revision_id: &str) -> Result { engine.write(|db| { let mut connection = lock(db)?; let note = store::restore_revision(&mut connection, id, revision_id)?; @@ -349,10 +318,7 @@ fn trash_matching( pub fn purge_notes(engine: &Engine, ids: &[String]) -> Result { engine.write(|db| { - let changed = Changed { - attachments: true, - ..Changed::notes(ids.to_vec()) - }; + let changed = Changed { attachments: true, ..Changed::notes(ids.to_vec()) }; Ok((count(trash::purge(db, ids)?), changed)) }) } @@ -365,10 +331,7 @@ pub fn empty_trash(engine: &Engine) -> Result { }; let answer = count(trash::purge(db, &ids)?); - let changed = Changed { - attachments: true, - ..Changed::default() - }; + let changed = Changed { attachments: true, ..Changed::default() }; Ok((answer, changed)) }) } @@ -388,10 +351,7 @@ pub fn move_notes( } /// The undo of [`move_notes`]: each note goes back to the space it left. -pub fn move_notes_back( - engine: &Engine, - placements: &[model::NotePlacement], -) -> Result { +pub fn move_notes_back(engine: &Engine, placements: &[model::NotePlacement]) -> Result { engine.write(|db| { let mut connection = lock(db)?; @@ -402,11 +362,7 @@ pub fn move_notes_back( } /// Normalized here as everywhere else, or a typed `#urgent` would not join `urgent`. -pub fn tag_notes( - engine: &Engine, - ids: &[String], - tags: &[String], -) -> Result, AppError> { +pub fn tag_notes(engine: &Engine, ids: &[String], tags: &[String]) -> Result, AppError> { engine.write(|db| { let normalized = model::normalize_tags(tags); @@ -430,11 +386,7 @@ pub fn untag_notes(engine: &Engine, pairs: &[model::NoteTag]) -> Result Result, AppError> { +pub fn remove_tag(engine: &Engine, ids: &[String], tag: String) -> Result, AppError> { engine.write(|db| { let Some(tag) = model::normalize_tags(&[tag]).into_iter().next() else { return Ok((Vec::new(), Changed::default())); @@ -486,10 +438,7 @@ pub fn set_priority( } /// The undo of [`set_priority`]: each note gets back the priority it had. -pub fn restore_priorities( - engine: &Engine, - previous: &[model::NotePriority], -) -> Result { +pub fn restore_priorities(engine: &Engine, previous: &[model::NotePriority]) -> Result { engine.write(|db| { let mut connection = lock(db)?; @@ -506,10 +455,7 @@ pub fn count_notes_tagged(engine: &Engine, tags: &[String]) -> Result Result, AppError> { @@ -521,10 +467,7 @@ pub fn list_tags(engine: &Engine) -> Result, AppError> { .facets(None) .tags .into_iter() - .map(|facet| TagUsage { - tag: facet.value, - note_count: facet.count, - }) + .map(|facet| TagUsage { tag: facet.value, note_count: facet.count }) .collect()) } @@ -585,10 +528,7 @@ pub fn fill_placeholders( let mut connection = lock(db)?; let globals = store::global_placeholder_values(&mut connection)?; - Ok(placeholder::fill( - content, - &placeholder::resolve(&globals, values), - )) + Ok(placeholder::fill(content, &placeholder::resolve(&globals, values))) } pub fn list_global_placeholders(engine: &Engine) -> Result, AppError> { @@ -610,10 +550,7 @@ pub fn set_global_placeholders( store::replace_global_placeholder_values(&mut connection, &retained)?; let answer = retained; - let changed = Changed { - globals: true, - ..Changed::default() - }; + let changed = Changed { globals: true, ..Changed::default() }; Ok((answer, changed)) }) } diff --git a/crates/engine/src/notes/calc.rs b/crates/engine/src/notes/calc.rs index 3abed2c89..a235e832b 100644 --- a/crates/engine/src/notes/calc.rs +++ b/crates/engine/src/notes/calc.rs @@ -32,11 +32,7 @@ pub struct CalcUnit { /// Exact decimals as text: a float would round them before the front decides how to. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde( - tag = "kind", - rename_all = "camelCase", - rename_all_fields = "camelCase" -)] +#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")] pub enum CalcValue { Number { value: String, @@ -86,11 +82,7 @@ pub struct SpanPart { /// Why a line has no result. It stays on its line: the others go on computing. #[derive(Debug, Clone, PartialEq, Eq, Serialize)] -#[serde( - tag = "kind", - rename_all = "camelCase", - rename_all_fields = "camelCase" -)] +#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")] pub enum CalcError { /// In UTF-16 units from the start of the line. Unreadable { @@ -222,17 +214,9 @@ pub const CARD_LINES: usize = 4; /// 16, not 15,999…. Twenty-five figures stay, past what any display shows. fn tidy(decimal: Decimal) -> Decimal { let whole = decimal.trunc().abs(); - let figures = if whole.is_zero() { - 0 - } else { - u32::try_from(whole.to_string().len()).unwrap_or(28) - }; + let figures = if whole.is_zero() { 0 } else { u32::try_from(whole.to_string().len()).unwrap_or(28) }; let places = 25_u32.saturating_sub(figures); - if decimal.scale() > places { - decimal.round_dp(places) - } else { - decimal - } + if decimal.scale() > places { decimal.round_dp(places) } else { decimal } } fn text(decimal: Decimal) -> String { @@ -257,15 +241,8 @@ impl Units { .enumerate() .flat_map(|(index, unit)| unit.symbols.iter().map(move |symbol| (*symbol, index))) .collect(); - let factors = table - .iter() - .map(|unit| (unit.id, (unit.factor, unit.dim))) - .collect(); - Self { - table, - symbols, - factors, - } + let factors = table.iter().map(|unit| (unit.id, (unit.factor, unit.dim))).collect(); + Self { table, symbols, factors } } /// Base units in one, as above over below: a pixel's and an `em`'s size follow the sheet's @@ -300,11 +277,7 @@ impl Units { let amount = quantity.amount.abs(); let unit = [UnitId::Day, UnitId::Hour, UnitId::Minute, UnitId::Second] .into_iter() - .find(|unit| { - self.factors - .get(unit) - .is_some_and(|(factor, _)| amount >= *factor) - }) + .find(|unit| self.factors.get(unit).is_some_and(|(factor, _)| amount >= *factor)) .unwrap_or(UnitId::Millisecond); Some(Shown::One(unit)) } @@ -312,34 +285,22 @@ impl Units { fn show(&self, value: &Value, css: &Css) -> Result { let quantity = match value { Value::Percent { ratio, signed } => { - return Ok(CalcValue::Percent { - value: text(ratio * Decimal::ONE_HUNDRED), - signed: *signed, - }); + return Ok(CalcValue::Percent { value: text(ratio * Decimal::ONE_HUNDRED), signed: *signed }); } Value::Date(date) => return Ok(CalcValue::Date { date: *date }), Value::Quantity(quantity) => quantity, }; if quantity.dim.is_none() { - return Ok(CalcValue::Number { - value: text(quantity.amount), - unit: None, - }); + return Ok(CalcValue::Number { value: text(quantity.amount), unit: None }); } - let fits = |shown: &Shown| { - self.factor(*shown, css) - .is_some_and(|(_, _, dim)| dim == quantity.dim) - }; + let fits = |shown: &Shown| self.factor(*shown, css).is_some_and(|(_, _, dim)| dim == quantity.dim); let shown = quantity .unit .filter(fits) .or_else(|| self.natural(quantity)) .ok_or(CalcError::Unsupported)?; if quantity.dim.has_temperature() { - return Ok(CalcValue::Number { - value: text(quantity.amount), - unit: Some(shown.calc_unit()), - }); + return Ok(CalcValue::Number { value: text(quantity.amount), unit: Some(shown.calc_unit()) }); } let (above, below, _) = self.factor(shown, css).ok_or(CalcError::Unsupported)?; let value = quantity @@ -354,20 +315,11 @@ impl Units { { return Ok(span); } - Ok(CalcValue::Number { - value: text(value), - unit: Some(shown.calc_unit()), - }) + Ok(CalcValue::Number { value: text(value), unit: Some(shown.calc_unit()) }) } /// `45 jours en sem` is `6 sem 3 j`: the whole weeks, and what is left in whole days. - fn span( - &self, - amount: Decimal, - value: Decimal, - factor: Decimal, - unit: UnitId, - ) -> Option { + fn span(&self, amount: Decimal, value: Decimal, factor: Decimal, unit: UnitId) -> Option { let smaller = match unit { UnitId::Week => UnitId::Day, UnitId::Day => UnitId::Hour, @@ -382,16 +334,7 @@ impl Units { let (small, _) = self.factors.get(&smaller)?; let rest = (amount - whole * factor).checked_div(*small)?; rest.fract().is_zero().then(|| CalcValue::Span { - parts: vec![ - SpanPart { - value: text(whole), - unit, - }, - SpanPart { - value: text(rest), - unit: smaller, - }, - ], + parts: vec![SpanPart { value: text(whole), unit }, SpanPart { value: text(rest), unit: smaller }], }) } } @@ -400,32 +343,18 @@ fn spans_of(tokens: &[Token], kinds: &[Option]) -> Vec { tokens .iter() .zip(kinds) - .filter_map(|(token, kind)| { - kind.map(|kind| CalcSpan { - start: token.start, - end: token.end, - kind, - }) - }) + .filter_map(|(token, kind)| kind.map(|kind| CalcSpan { start: token.start, end: token.end, kind })) .collect() } /// The span of a comment written after an expression, from its `//` to the end. fn trailing_comment(line: &str) -> Option { let at = line.find("//")?; - Some(CalcSpan { - start: utf16(&line[..at]), - end: utf16(line), - kind: TokenKind::Comment, - }) + Some(CalcSpan { start: utf16(&line[..at]), end: utf16(line), kind: TokenKind::Comment }) } fn row(line: CalcLine, spans: Vec) -> CalcRow { - CalcRow { - line, - spans, - converting: None, - } + CalcRow { line, spans, converting: None } } /// What the sheet knows so far, line after line. @@ -442,11 +371,7 @@ struct Walk { } /// `255 en hex`, `5300 en sci`: a plain number written as the line asked. -fn notated( - value: &Value, - shown: CalcValue, - notation: Option, -) -> Result { +fn notated(value: &Value, shown: CalcValue, notation: Option) -> Result { let (Some(notation), Value::Quantity(quantity)) = (notation, value) else { return Ok(shown); }; @@ -456,11 +381,7 @@ fn notated( Ok(match notation { Notation::Base(radix) => { let (negative, digits) = maths::digits(quantity.amount, radix)?; - CalcValue::Base { - digits, - radix, - negative, - } + CalcValue::Base { digits, radix, negative } } Notation::Scientific => { let (mantissa, exponent) = maths::scientific(tidy(quantity.amount)); @@ -474,9 +395,7 @@ fn notated( negative, } } - Notation::Multiplier => CalcValue::Multiplier { - value: text(quantity.amount), - }, + Notation::Multiplier => CalcValue::Multiplier { value: text(quantity.amount) }, Notation::Decimal => shown, }) } @@ -486,9 +405,7 @@ fn label_end(tokens: &[Token]) -> Option { if !matches!(tokens.first()?.tok, Tok::Word(_)) { return None; } - let colon = tokens - .iter() - .position(|token| token.tok == Tok::Other(':'))?; + let colon = tokens.iter().position(|token| token.tok == Tok::Other(':'))?; tokens[..colon] .iter() .all(|token| token.tok != Tok::Symbol('=')) @@ -517,52 +434,22 @@ fn head<'t>(tokens: &'t [Token], spans: &mut Vec) -> Result, None => tokens, }; match tokens { - [ - Token { - tok: Tok::Word(word), - start, - end, - .. - }, - Token { - tok: Tok::Symbol('='), - .. - }, - .., - ] => { + [Token { tok: Tok::Word(word), start, end, .. }, Token { tok: Tok::Symbol('='), .. }, ..] => { if words::reserved(word) { - spans.push(CalcSpan { - start: *start, - end: *end, - kind: TokenKind::Error, - }); + spans.push(CalcSpan { start: *start, end: *end, kind: TokenKind::Error }); let error = CalcError::Reserved { word: word.clone() }; return Err(row(CalcLine::Error { error }, std::mem::take(spans))); } - Ok(Head { - tokens, - name: Some(word.clone()), - body: &tokens[2..], - }) + Ok(Head { tokens, name: Some(word.clone()), body: &tokens[2..] }) } - _ => Ok(Head { - tokens, - name: None, - body: tokens, - }), + _ => Ok(Head { tokens, name: None, body: tokens }), } } impl Walk { fn line(&mut self, index: u32, line: &str) -> CalcRow { let trimmed = line.trim(); - let whole = |kind| { - vec![CalcSpan { - start: 0, - end: utf16(line), - kind, - }] - }; + let whole = |kind| vec![CalcSpan { start: 0, end: utf16(line), kind }]; if trimmed.is_empty() { self.block.clear(); return row(CalcLine::Blank, Vec::new()); @@ -602,17 +489,9 @@ impl Walk { spans.push(CalcSpan { start: tokens[0].start, end: tokens[0].end, - kind: if setting.is_some() { - TokenKind::Keyword - } else { - TokenKind::Name - }, - }); - spans.push(CalcSpan { - start: tokens[1].start, - end: tokens[1].end, - kind: TokenKind::Operator, + kind: if setting.is_some() { TokenKind::Keyword } else { TokenKind::Name }, }); + spans.push(CalcSpan { start: tokens[1].start, end: tokens[1].end, kind: TokenKind::Operator }); } spans.extend(spans_of(body, &parser.kinds)); spans.extend(trailing_comment(line)); @@ -644,13 +523,8 @@ impl Walk { Err(error) => { let sentence = name.is_none() && used.is_empty() - && !tokens - .iter() - .any(|token| matches!(token.tok, Tok::Number(_) | Tok::Date(_))) - && matches!( - error, - CalcError::Unreadable { .. } | CalcError::UnknownName { .. } - ); + && !tokens.iter().any(|token| matches!(token.tok, Tok::Number(_) | Tok::Date(_))) + && matches!(error, CalcError::Unreadable { .. } | CalcError::UnknownName { .. }); if sentence { spans.retain(|span| span.kind == TokenKind::Comment); CalcLine::Text @@ -659,11 +533,7 @@ impl Walk { } } }; - CalcRow { - line, - spans, - converting, - } + CalcRow { line, spans, converting } } /// `ppi = 326`, `em = 20 px`: the sheet's setting from this line down. A size in pixels @@ -672,15 +542,11 @@ impl Walk { let (inch, ppi) = self.css.factor(UnitId::Pixel).ok_or(CalcError::Overflow)?; let pixels = match value { Value::Quantity(quantity) if quantity.dim.is_none() => quantity.amount, - Value::Quantity(quantity) - if quantity.dim == Dim::LENGTH && setting != CalcWord::Ppi => - { - quantity - .amount - .checked_mul(ppi) - .and_then(|product| product.checked_div(inch)) - .ok_or(CalcError::Overflow)? - } + Value::Quantity(quantity) if quantity.dim == Dim::LENGTH && setting != CalcWord::Ppi => quantity + .amount + .checked_mul(ppi) + .and_then(|product| product.checked_div(inch)) + .ok_or(CalcError::Overflow)?, other => { return Err(CalcError::Mismatch { expected: Dimension::Number, @@ -727,17 +593,8 @@ impl Walk { ) -> CalcLine { let dimension = value.dimension(); // `ppi = 326` sets the sheet: no name, nothing for `total` or `préc` to read. - if name - .as_deref() - .is_some_and(|name| words::setting(name).is_some()) - { - return CalcLine::Value { - value: shown, - name, - aggregate, - dimension, - places, - }; + if name.as_deref().is_some_and(|name| words::setting(name).is_some()) { + return CalcLine::Value { value: shown, name, aggregate, dimension, places }; } if let Some(name) = &name { self.current.insert(name.clone(), self.definitions.len()); @@ -753,13 +610,7 @@ impl Walk { if !aggregate && let Value::Quantity(quantity) = value { self.block.push(quantity); } - CalcLine::Value { - value: shown, - name, - aggregate, - dimension, - places, - } + CalcLine::Value { value: shown, name, aggregate, dimension, places } } } @@ -785,10 +636,7 @@ pub fn evaluate(sheet: &str, today: NaiveDate) -> CalcSheet { }) .collect(); - CalcSheet { - rows, - variables: walk.definitions, - } + CalcSheet { rows, variables: walk.definitions } } /// The last lines that gave something, the way a card shows the end of a sheet. @@ -799,12 +647,7 @@ pub fn card_lines(sheet: &str, today: NaiveDate) -> Vec { .into_iter() .zip(&lines) .filter_map(|(row, line)| match row.line { - CalcLine::Value { - value, - aggregate, - places, - .. - } => Some(CalcCardLine { + CalcLine::Value { value, aggregate, places, .. } => Some(CalcCardLine { expression: lexer::without_comment(line).trim().to_string(), value, aggregate, @@ -848,10 +691,7 @@ mod tests { fn value_text(value: &CalcValue) -> String { match value { CalcValue::Number { value, unit: None } => value.clone(), - CalcValue::Number { - value, - unit: Some(unit), - } => format!("{value} {}", unit_text(*unit)), + CalcValue::Number { value, unit: Some(unit) } => format!("{value} {}", unit_text(*unit)), CalcValue::Percent { value, signed } => { format!("{}{value} %", if *signed { "change " } else { "" }) } @@ -861,30 +701,19 @@ mod tests { .map(|part| format!("{} {:?}", part.value, part.unit)) .collect::>() .join(" "), - CalcValue::Base { - digits, - radix, - negative, - } => format!("{}{digits} base {radix}", if *negative { "-" } else { "" }), + CalcValue::Base { digits, radix, negative } => { + format!("{}{digits} base {radix}", if *negative { "-" } else { "" }) + } CalcValue::Scientific { mantissa, exponent } => format!("{mantissa}e{exponent}"), - CalcValue::Fraction { - numerator, - denominator, - negative, - } => format!( - "{}{numerator}/{denominator}", - if *negative { "-" } else { "" } - ), + CalcValue::Fraction { numerator, denominator, negative } => { + format!("{}{numerator}/{denominator}", if *negative { "-" } else { "" }) + } CalcValue::Multiplier { value } => format!("×{value}"), } } fn lines(sheet: &str) -> Vec { - evaluate(sheet, today()) - .rows - .iter() - .map(|row| written(&row.line)) - .collect() + evaluate(sheet, today()).rows.iter().map(|row| written(&row.line)).collect() } fn last(sheet: &str) -> String { @@ -930,11 +759,7 @@ mod tests { #[test] fn a_chain_of_powers_is_read_from_the_right() { - check(&[ - ("2 ^ 3 ^ 2", "512"), - ("2 ^ 2 ^ 2 ^ 2", "65536"), - ("2 ^ -1 ^ 2", "2"), - ]); + check(&[("2 ^ 3 ^ 2", "512"), ("2 ^ 2 ^ 2 ^ 2", "65536"), ("2 ^ -1 ^ 2", "2")]); assert_eq!(evaluate(&"2 ^ ".repeat(50_000), today()).rows.len(), 1); } @@ -958,13 +783,7 @@ mod tests { #[test] fn a_base_or_an_exponent_writes_a_number_too() { - check(&[ - ("0xFF", "255"), - ("0b1010", "10"), - ("0o377", "255"), - ("5,3e+3", "5300"), - ("2e-2", "0.02"), - ]); + check(&[("0xFF", "255"), ("0b1010", "10"), ("0o377", "255"), ("5,3e+3", "5300"), ("2e-2", "0.02")]); } // --- Operators. @@ -1018,10 +837,7 @@ mod tests { #[test] fn a_division_by_zero_is_an_error_of_its_own() { - check(&[ - ("1 / 0", "error: DivisionByZero"), - ("5 mod 0", "error: DivisionByZero"), - ]); + check(&[("1 / 0", "error: DivisionByZero"), ("5 mod 0", "error: DivisionByZero")]); } // --- Words around the figures. @@ -1033,10 +849,7 @@ mod tests { #[test] fn words_leading_up_to_a_result_and_quoted_text_are_read_past() { - check(&[ - ("275 € pour le \"Modèle 227\"", "275 Euro"), - ("999 € (pour l'iPhone)", "999 Euro"), - ]); + check(&[("275 € pour le \"Modèle 227\"", "275 Euro"), ("999 € (pour l'iPhone)", "999 Euro")]); } #[test] @@ -1051,10 +864,7 @@ mod tests { #[test] fn a_comment_line_and_a_heading_compute_nothing() { - assert_eq!( - lines("// note\n# Budget\n"), - ["comment", "# Budget", "blank"] - ); + assert_eq!(lines("// note\n# Budget\n"), ["comment", "# Budget", "blank"]); } #[test] @@ -1074,10 +884,7 @@ mod tests { #[test] fn a_name_used_before_it_is_given_is_unknown() { - assert_eq!( - lines("taux * 2\ntaux = 3"), - ["error: UnknownName { name: \"taux\" }", "3"] - ); + assert_eq!(lines("taux * 2\ntaux = 3"), ["error: UnknownName { name: \"taux\" }", "3"]); } #[test] @@ -1087,18 +894,12 @@ mod tests { #[test] fn a_name_defined_above_hides_a_value_word_from_its_line_down() { - assert_eq!( - lines("1\n2\ntotal\ntotal = 7\ntotal + 1"), - ["1", "2", "3", "7", "8"] - ); + assert_eq!(lines("1\n2\ntotal\ntotal = 7\ntotal + 1"), ["1", "2", "3", "7", "8"]); } #[test] fn previous_is_the_last_result_above() { - assert_eq!( - lines("10\nphrase sans chiffre\npréc * 2\nprev + 1"), - ["10", "text", "20", "21"] - ); + assert_eq!(lines("10\nphrase sans chiffre\npréc * 2\nprev + 1"), ["10", "text", "20", "21"]); check(&[("préc", "error: NoPrevious")]); } @@ -1111,10 +912,7 @@ mod tests { .iter() .map(|variable| (variable.name.as_str(), variable.line, variable.uses.clone())) .collect(); - assert_eq!( - found, - [("a", 0, vec![1]), ("b", 1, vec![3]), ("a", 2, vec![3])] - ); + assert_eq!(found, [("a", 0, vec![1]), ("b", 1, vec![3]), ("a", 2, vec![3])]); assert_eq!(value_text(&sheet.variables[1].value), "4"); } @@ -1124,9 +922,7 @@ mod tests { fn total_and_mean_read_the_quantities_above_in_their_block() { assert_eq!( lines("10 €\n20 €\ntotal\nmoyenne\n\n5 €\ntotal"), - [ - "10 Euro", "20 Euro", "30 Euro", "15 Euro", "blank", "5 Euro", "5 Euro" - ] + ["10 Euro", "20 Euro", "30 Euro", "15 Euro", "blank", "5 Euro", "5 Euro"] ); } @@ -1148,15 +944,7 @@ mod tests { let aggregates: Vec<_> = sheet .rows .iter() - .map(|row| { - matches!( - row.line, - CalcLine::Value { - aggregate: true, - .. - } - ) - }) + .map(|row| matches!(row.line, CalcLine::Value { aggregate: true, .. })) .collect(); assert_eq!(aggregates, [false, false, true, true]); assert_eq!(written(&sheet.rows[3].line), "3"); @@ -1176,10 +964,7 @@ mod tests { #[test] fn quantities_written_side_by_side_add_up() { - check(&[ - ("3 h 20 min en min", "200 Minute"), - ("1 m 20 cm", "1.2 Metre"), - ]); + check(&[("3 h 20 min en min", "200 Minute"), ("1 m 20 cm", "1.2 Metre")]); } #[test] @@ -1214,10 +999,7 @@ mod tests { #[test] fn euros_and_dollars_are_never_converted_into_each_other() { - check(&[ - ("100 € en $", "error: Currency"), - ("100 $ en €", "error: Currency"), - ]); + check(&[("100 € en $", "error: Currency"), ("100 $ en €", "error: Currency")]); } #[test] @@ -1262,16 +1044,7 @@ mod tests { lines( "3 in en px\nppi = 326\n1 in en px\n2 em en px\nem = 20 px\n2 em en px\nrem = 18\n1 rem en px" ), - [ - "288 Pixel", - "326", - "326 Pixel", - "32 Pixel", - "20 Pixel", - "40 Pixel", - "18 Pixel", - "18 Pixel" - ] + ["288 Pixel", "326", "326 Pixel", "32 Pixel", "20 Pixel", "40 Pixel", "18 Pixel", "18 Pixel"] ); } @@ -1304,10 +1077,7 @@ mod tests { #[test] fn in_is_an_inch_after_a_number_and_a_conversion_before_a_notation() { - check(&[ - ("2 in en cm", "5.08 Centimetre"), - ("255 in hex", "FF base 16"), - ]); + check(&[("2 in en cm", "5.08 Centimetre"), ("255 in hex", "FF base 16")]); } // --- Functions and constants. @@ -1367,13 +1137,7 @@ mod tests { let sheet = evaluate("1 / 3 à 2 décimales\npréc * 3", today()); assert_eq!(written(&sheet.rows[0].line), "0.33"); - assert!(matches!( - sheet.rows[0].line, - CalcLine::Value { - places: Some(2), - .. - } - )); + assert!(matches!(sheet.rows[0].line, CalcLine::Value { places: Some(2), .. })); assert_eq!(written(&sheet.rows[1].line), "0.99"); } @@ -1461,10 +1225,7 @@ mod tests { #[test] fn a_proportion_solves_for_its_unknown() { - check(&[ - ("6 est à 60 ce que 8 est à combien", "80"), - ("6 is to 60 as 8 is to what", "80"), - ]); + check(&[("6 est à 60 ce que 8 est à combien", "80"), ("6 is to 60 as 8 is to what", "80")]); } // --- Finance. @@ -1486,9 +1247,7 @@ mod tests { ("valeur actuelle de 1 210 € dans 2 ans à 10 %", "1000 Euro"), ]); assert!(last("mensualité de 10 000 € sur 1 an à 12 %").starts_with("888.48")); - assert!( - last("rendement annuel sur 100 € investis 200 € récupérés en 1 an").starts_with("100") - ); + assert!(last("rendement annuel sur 100 € investis 200 € récupérés en 1 an").starts_with("100")); } #[test] @@ -1592,17 +1351,10 @@ mod tests { #[test] fn a_label_and_a_setting_are_coloured_apart_from_names() { let kinds = |line: &str| -> Vec { - evaluate(line, today()).rows[0] - .spans - .iter() - .map(|span| span.kind) - .collect() + evaluate(line, today()).rows[0].spans.iter().map(|span| span.kind).collect() }; - assert_eq!( - kinds("Prix : 3")[..2], - [TokenKind::Comment, TokenKind::Number] - ); + assert_eq!(kinds("Prix : 3")[..2], [TokenKind::Comment, TokenKind::Number]); assert_eq!(kinds("ppi = 300")[0], TokenKind::Keyword); assert_eq!(kinds("Une phrase"), []); assert_eq!(kinds("en = 5")[0], TokenKind::Error); @@ -1656,14 +1408,8 @@ mod tests { fn a_card_line_carries_its_aggregate_and_its_places() { let shown = card_lines("1\n2\ntotal\n1 / 3 à 2 décimales", today()); - let found: Vec<_> = shown - .iter() - .map(|line| (line.aggregate, line.places)) - .collect(); - assert_eq!( - found, - [(false, None), (false, None), (true, None), (false, Some(2))] - ); + let found: Vec<_> = shown.iter().map(|line| (line.aggregate, line.places)).collect(); + assert_eq!(found, [(false, None), (false, None), (true, None), (false, Some(2))]); } #[test] @@ -1752,14 +1498,10 @@ mod tests { #[test] fn a_form_of_several_words_wins_over_a_name_of_one() { assert!( - last("mensualité = 100 €\nmensualité de 10 000 € sur 6 ans à 6 %") - .starts_with("165.72887893") + last("mensualité = 100 €\nmensualité de 10 000 € sur 6 ans à 6 %").starts_with("165.72887893") ); assert_eq!(last("mensualité = 100 €\nmensualité + 1 €"), "101 Euro"); - assert!( - last("total = $2\ntotal cost of $10,000 over 6 years at 6%") - .starts_with("11932.479283") - ); + assert!(last("total = $2\ntotal cost of $10,000 over 6 years at 6%").starts_with("11932.479283")); assert_eq!(last("racine = 5\nracine carrée(16) + racine"), "9"); } @@ -1769,10 +1511,7 @@ mod tests { assert!(last(&format!("{named}capital après durée à taux")).starts_with("1225.04")); assert!(last(&format!("{named}capital pendant durée à taux")).starts_with("1225.04")); - assert!( - last("principal = $1,000\nterm = 3 years\nprincipal after term @ 7%") - .starts_with("1225.04") - ); + assert!(last("principal = $1,000\nterm = 3 years\nprincipal after term @ 7%").starts_with("1225.04")); assert_eq!(last("prix = 275 €\nprix for the \"Model 227\""), "275 Euro"); } @@ -1840,11 +1579,7 @@ mod tests { #[test] fn a_scale_is_read_in_its_case_and_a_scale_word_in_any() { - check(&[ - ("1 Mille milliards", "1000000000000"), - ("5 K", "5 Kelvin"), - ("5 k", "5000"), - ]); + check(&[("1 Mille milliards", "1000000000000"), ("5 K", "5 Kelvin"), ("5 k", "5000")]); } #[test] @@ -1867,18 +1602,12 @@ mod tests { #[test] fn a_remark_in_parentheses_may_hold_punctuation_or_a_quote() { - check(&[ - ("999 € (pour l'iPhone !)", "999 Euro"), - ("999 € (\"iPhone\")", "999 Euro"), - ]); + check(&[("999 € (pour l'iPhone !)", "999 Euro"), ("999 € (\"iPhone\")", "999 Euro")]); } #[test] fn a_percentage_rounds_as_a_percentage_and_a_date_does_not_round() { - check(&[ - ("33,333 % à 1 décimale", "33.3 %"), - ("aujourd'hui arrondi", "error: Unsupported"), - ]); + check(&[("33,333 % à 1 décimale", "33.3 %"), ("aujourd'hui arrondi", "error: Unsupported")]); } #[test] @@ -1886,10 +1615,7 @@ mod tests { check(&[ ("40 to 90 is what x", "×2.25"), ("5 is to 10 as what is to 80", "40"), - ( - "6 est à 60 ce que combien est à combien", - "error: Unreadable { at: 39 }", - ), + ("6 est à 60 ce que combien est à combien", "error: Unreadable { at: 39 }"), ("6 est à 60 8 est à combien", "error: Unreadable { at: 11 }"), ("6 est à 60 ce que 8", "error: Unreadable { at: 19 }"), ]); @@ -1903,10 +1629,7 @@ mod tests { ("255 en base 3", "error: Unsupported"), ("0,25 en %", "25 %"), ("20 % en %", "20 %"), - ( - "3 km en %", - "error: NotConvertible { from: Length, to: None }", - ), + ("3 km en %", "error: NotConvertible { from: Length, to: None }"), ]); } @@ -1934,18 +1657,9 @@ mod tests { #[test] fn a_finance_line_says_what_it_could_not_read() { check(&[ - ( - "1 000 € après 3 ans à 7 % composés bizarrement", - "error: Unreadable { at: 35 }", - ), - ( - "valeur actuelle de 1 000 € 20 ans à 10 %", - "error: Unreadable { at: 27 }", - ), - ( - "rendement annuel sur 100 € investis 200 € récupérés en 0 an", - "error: DivisionByZero", - ), + ("1 000 € après 3 ans à 7 % composés bizarrement", "error: Unreadable { at: 35 }"), + ("valeur actuelle de 1 000 € 20 ans à 10 %", "error: Unreadable { at: 27 }"), + ("rendement annuel sur 100 € investis 200 € récupérés en 0 an", "error: DivisionByZero"), ]); assert!(last("1 000 € après 3 kg à 7 %").starts_with("error: Mismatch { expected: Time")); } diff --git a/crates/engine/src/notes/calc/eval.rs b/crates/engine/src/notes/calc/eval.rs index 44c7ef55c..175d05d8c 100644 --- a/crates/engine/src/notes/calc/eval.rs +++ b/crates/engine/src/notes/calc/eval.rs @@ -25,10 +25,7 @@ impl Shown { pub(super) fn calc_unit(self) -> CalcUnit { match self { Self::One(unit) => CalcUnit { unit, per: None }, - Self::Per(unit, per) => CalcUnit { - unit, - per: Some(per), - }, + Self::Per(unit, per) => CalcUnit { unit, per: Some(per) }, } } } @@ -41,10 +38,7 @@ pub(super) struct Factor { } impl Factor { - const ONE: Self = Self { - above: Decimal::ONE, - below: Decimal::ONE, - }; + const ONE: Self = Self { above: Decimal::ONE, below: Decimal::ONE }; fn apply(self, number: Decimal) -> Result { number @@ -93,12 +87,7 @@ impl Value { } fn number(amount: Decimal) -> Self { - Self::Quantity(Quantity { - amount, - dim: Dim::NONE, - unit: None, - spans: false, - }) + Self::Quantity(Quantity { amount, dim: Dim::NONE, unit: None, spans: false }) } } @@ -275,11 +264,7 @@ impl<'a> Parser<'a> { } fn skip_quoted(&mut self) { - while self - .tokens - .get(self.at) - .is_some_and(|token| token.tok == Tok::Quoted) - { + while self.tokens.get(self.at).is_some_and(|token| token.tok == Tok::Quoted) { self.kinds[self.at] = Some(TokenKind::Comment); self.at += 1; } @@ -290,17 +275,12 @@ impl<'a> Parser<'a> { fn remark_end(&self) -> Option { self.peek_symbol(&['('])?; let inside = self.at + 1; - let close = inside - + self.tokens[inside..] - .iter() - .position(|token| token.tok == Tok::Symbol(')'))?; - let words = self.tokens[inside..close] - .iter() - .all(|token| match &token.tok { - Tok::Word(word) => !self.context.variables.contains_key(word), - Tok::Other(_) | Tok::Quoted => true, - _ => false, - }); + let close = inside + self.tokens[inside..].iter().position(|token| token.tok == Tok::Symbol(')'))?; + let words = self.tokens[inside..close].iter().all(|token| match &token.tok { + Tok::Word(word) => !self.context.variables.contains_key(word), + Tok::Other(_) | Tok::Quoted => true, + _ => false, + }); (close > inside && words).then_some(close + 1) } @@ -374,9 +354,7 @@ impl<'a> Parser<'a> { } fn notation_at(&self, index: usize) -> bool { - self.tokens - .get(index) - .is_some_and(|token| token.tok == Tok::Symbol('%')) + self.tokens.get(index).is_some_and(|token| token.tok == Tok::Symbol('%')) || NOTATIONS .iter() .map(|(word, _)| *word) @@ -388,10 +366,7 @@ impl<'a> Parser<'a> { fn factor_of(&self, unit: &UnitDef) -> Factor { match self.context.css.factor(unit.id) { Some((above, below)) => Factor { above, below }, - None => Factor { - above: unit.factor, - below: Decimal::ONE, - }, + None => Factor { above: unit.factor, below: Decimal::ONE }, } } @@ -405,10 +380,7 @@ impl<'a> Parser<'a> { fn unit_at(&self, index: usize) -> Option<&'a UnitDef> { let text = self.text_at(index)?; - self.context - .symbols - .get(text.as_str()) - .map(|&found| &self.context.units[found]) + self.context.symbols.get(text.as_str()).map(|&found| &self.context.units[found]) } /// A unit, or one over another written without a space: `€/h`, `Mo/s`. Its factor comes @@ -427,11 +399,7 @@ impl<'a> Parser<'a> { self.take(TokenKind::Unit); self.take(TokenKind::Unit); let factor = self.factor_of(first).over(self.factor_of(second))?; - return Some(( - Shown::Per(first.id, second.id), - first.dim.over(second.dim), - factor, - )); + return Some((Shown::Per(first.id, second.id), first.dim.over(second.dim), factor)); } Some((Shown::One(first.id), first.dim, self.factor_of(first))) } @@ -450,8 +418,7 @@ impl<'a> Parser<'a> { value = share_of(value, &whole, share).map_err(|error| self.blame(error))?; } else if self.eat(CalcWord::IsTo) { value = self.proportion(value)?; - } else if self.duration_after(CalcWord::After) || self.duration_after(CalcWord::During) - { + } else if self.duration_after(CalcWord::After) || self.duration_after(CalcWord::During) { value = self.compound(value)?; } else if self.eat(CalcWord::Invested) { // `500 € investis 1 500 € récupérés` is ×3. @@ -505,22 +472,15 @@ impl<'a> Parser<'a> { }; let step = self.nearest()?; if direction.is_some() || step.is_some() { - let (direction, step) = ( - direction.unwrap_or(Rounding::Nearest), - step.unwrap_or(Decimal::ONE), - ); - let rounded = self.in_its_unit(value.clone(), |amount| { - maths::round_to(amount, step, direction) - }); + let (direction, step) = (direction.unwrap_or(Rounding::Nearest), step.unwrap_or(Decimal::ONE)); + let rounded = self.in_its_unit(value.clone(), |amount| maths::round_to(amount, step, direction)); return rounded.map(Some).map_err(|error| self.blame(error)); } let Some(places) = self.places() else { return Ok(None); }; self.places = Some(places); - Ok(Some(self.in_its_unit(value.clone(), |amount| { - Ok(maths::round_places(amount, places)) - })?)) + Ok(Some(self.in_its_unit(value.clone(), |amount| Ok(maths::round_places(amount, places)))?)) } /// `au 10 près`, `au millier près`, `to nearest 10`: the step to round to. @@ -552,8 +512,7 @@ impl<'a> Parser<'a> { let opener = [CalcWord::At, CalcWord::Convert, CalcWord::To] .into_iter() .find_map(|word| self.sees(word))?; - let Some(Tok::Number(places)) = self.tokens.get(self.at + opener).map(|token| &token.tok) - else { + let Some(Tok::Number(places)) = self.tokens.get(self.at + opener).map(|token| &token.tok) else { return None; }; let places = places.to_u32().filter(|_| places.fract().is_zero())?; @@ -571,20 +530,15 @@ impl<'a> Parser<'a> { } /// Rounded in the unit it is shown in: `1,236 km à 2 décimales` is 1,24 km, not 1 236 m. - fn in_its_unit( - &self, - value: Value, - round: impl Fn(Decimal) -> Result, - ) -> Answer { + fn in_its_unit(&self, value: Value, round: impl Fn(Decimal) -> Result) -> Answer { match value { Value::Quantity(quantity) => { let Factor { above, below } = match quantity.unit { _ if quantity.dim.has_temperature() => Factor::ONE, Some(Shown::One(unit)) => self.unit_factor(unit), - Some(Shown::Per(top, bottom)) => self - .unit_factor(top) - .over(self.unit_factor(bottom)) - .ok_or_else(overflow)?, + Some(Shown::Per(top, bottom)) => { + self.unit_factor(top).over(self.unit_factor(bottom)).ok_or_else(overflow)? + } None => Factor::ONE, }; let shown = quantity @@ -600,10 +554,7 @@ impl<'a> Parser<'a> { } Value::Percent { ratio, signed } => { let percent = round(ratio * Decimal::ONE_HUNDRED)?; - Ok(Value::Percent { - ratio: percent / Decimal::ONE_HUNDRED, - signed, - }) + Ok(Value::Percent { ratio: percent / Decimal::ONE_HUNDRED, signed }) } Value::Date(_) => Err(CalcError::Unsupported), } @@ -649,9 +600,7 @@ impl<'a> Parser<'a> { true }); if percent { - return change(from, to) - .map(Some) - .map_err(|error| self.blame(error)); + return change(from, to).map(Some).map_err(|error| self.blame(error)); } if self.eat(CalcWord::WhatTimes) { let times = divide(to.clone(), from.clone()).map_err(|error| self.blame(error))?; @@ -667,19 +616,11 @@ impl<'a> Parser<'a> { if !self.eat(CalcWord::Like) { return Err(self.unreadable()); } - let third = if self.eat(CalcWord::What) { - None - } else { - Some(self.additive()?) - }; + let third = if self.eat(CalcWord::What) { None } else { Some(self.additive()?) }; if !self.eat(CalcWord::IsTo) { return Err(self.unreadable()); } - let fourth = if self.eat(CalcWord::What) { - None - } else { - Some(self.additive()?) - }; + let fourth = if self.eat(CalcWord::What) { None } else { Some(self.additive()?) }; let found = match (third, fourth) { // The ratio first, so the unknown keeps the unit of the value it scales. (Some(third), None) => divide(third, first).and_then(|ratio| multiply(ratio, second)), @@ -693,10 +634,9 @@ impl<'a> Parser<'a> { fn written(&mut self, value: Value, notation: Notation) -> Answer { // `50 % en fraction` is 1/2: a percentage written as the number it is. let value = match (value, notation) { - ( - Value::Percent { ratio, .. }, - Notation::Fraction | Notation::Multiplier | Notation::Decimal, - ) => Value::number(ratio), + (Value::Percent { ratio, .. }, Notation::Fraction | Notation::Multiplier | Notation::Decimal) => { + Value::number(ratio) + } (value, _) => value, }; let amount = plain(&value).map_err(|error| self.blame(error))?; @@ -760,14 +700,10 @@ impl<'a> Parser<'a> { self.take(TokenKind::Unit); return match value { Value::Percent { .. } => Ok(value), - Value::Quantity(quantity) if quantity.dim.is_none() => Ok(Value::Percent { - ratio: quantity.amount, - signed: false, - }), - other => Err(self.blame(CalcError::NotConvertible { - from: other.dimension(), - to: None, - })), + Value::Quantity(quantity) if quantity.dim.is_none() => { + Ok(Value::Percent { ratio: quantity.amount, signed: false }) + } + other => Err(self.blame(CalcError::NotConvertible { from: other.dimension(), to: None })), }; } let Some((shown, dim, _)) = self.read_unit() else { @@ -858,11 +794,7 @@ impl<'a> Parser<'a> { fn product(&mut self) -> Option { if let Some(symbol) = self.peek_symbol(&['×', '*', '/', '÷']) { self.take(TokenKind::Operator); - return Some(if matches!(symbol, '×' | '*') { - Product::Times - } else { - Product::Over - }); + return Some(if matches!(symbol, '×' | '*') { Product::Times } else { Product::Over }); } if self.eat_as(CalcWord::Times, TokenKind::Operator) { Some(Product::Times) @@ -900,12 +832,8 @@ impl<'a> Parser<'a> { return Err(self.unreadable()); } let right = self.power()?; - left = if solving { - solve(ratio, share, right) - } else { - applied(ratio, share, right) - } - .map_err(|error| self.blame(error))?; + left = if solving { solve(ratio, share, right) } else { applied(ratio, share, right) } + .map_err(|error| self.blame(error))?; } else if !self.no_over && self.eat(CalcWord::Over) { let right = self.power()?; left = ratio(&left, &right).map_err(|error| self.blame(error))?; @@ -946,11 +874,7 @@ impl<'a> Parser<'a> { if let Some(symbol) = self.peek_symbol(&['-', '−', '+']) { self.take(TokenKind::Operator); let value = self.unary()?; - return if symbol == '+' { - Ok(value) - } else { - negate(value) - }; + return if symbol == '+' { Ok(value) } else { negate(value) }; } self.primary() } @@ -997,16 +921,11 @@ impl<'a> Parser<'a> { for _ in 0..taken { self.take(TokenKind::Number); } - number = number - .checked_mul(Decimal::from(scale)) - .ok_or_else(overflow)?; + number = number.checked_mul(Decimal::from(scale)).ok_or_else(overflow)?; } if self.peek_symbol(&['%']).is_some() { self.take(TokenKind::Unit); - return Ok(Value::Percent { - ratio: number / Decimal::ONE_HUNDRED, - signed: false, - }); + return Ok(Value::Percent { ratio: number / Decimal::ONE_HUNDRED, signed: false }); } // `255 in hex`, `0,35 in %`: `in` before what a number is written as converts it, inches aside. if self.sees(CalcWord::Convert) == Some(1) && self.notation_at(self.at + 1) { @@ -1015,31 +934,18 @@ impl<'a> Parser<'a> { let Some((shown, dim, factor)) = self.read_unit() else { return Ok(Value::number(number)); }; - let mut amount = if dim.has_temperature() { - number - } else { - factor.apply(number)? - }; + let mut amount = if dim.has_temperature() { number } else { factor.apply(number)? }; while let Some(Tok::Number(next)) = self.peek().cloned() && !dim.has_temperature() - && self - .unit_at(self.at + 1) - .is_some_and(|unit| unit.dim == dim) + && self.unit_at(self.at + 1).is_some_and(|unit| unit.dim == dim) { self.take(TokenKind::Number); let Some((_, _, factor)) = self.read_unit() else { break; }; - amount = amount - .checked_add(factor.apply(next)?) - .ok_or_else(overflow)?; + amount = amount.checked_add(factor.apply(next)?).ok_or_else(overflow)?; } - Ok(Value::Quantity(Quantity { - amount, - dim, - unit: Some(shown), - spans: false, - })) + Ok(Value::Quantity(Quantity { amount, dim, unit: Some(shown), spans: false })) } /// `$1,000`, `€500`: a currency written before its amount, as English does. @@ -1056,9 +962,7 @@ impl<'a> Parser<'a> { for _ in 0..taken { self.take(TokenKind::Number); } - number = number - .checked_mul(Decimal::from(scale)) - .ok_or_else(overflow)?; + number = number.checked_mul(Decimal::from(scale)).ok_or_else(overflow)?; } Ok(Value::Quantity(Quantity { amount: self.factor_of(unit).apply(number)?, @@ -1099,21 +1003,11 @@ impl<'a> Parser<'a> { } let shifted = |days: i64, today: NaiveDate| { let shift = Days::new(days.unsigned_abs()); - if days < 0 { - today.checked_sub_days(shift) - } else { - today.checked_add_days(shift) - } + if days < 0 { today.checked_sub_days(shift) } else { today.checked_add_days(shift) } }; - for (day, days) in [ - (CalcWord::Today, 0), - (CalcWord::Tomorrow, 1), - (CalcWord::Yesterday, -1), - ] { + for (day, days) in [(CalcWord::Today, 0), (CalcWord::Tomorrow, 1), (CalcWord::Yesterday, -1)] { if self.eat(day) { - return shifted(days, self.context.today) - .map(Value::Date) - .ok_or_else(overflow); + return shifted(days, self.context.today).map(Value::Date).ok_or_else(overflow); } } for (block, mean) in [(CalcWord::Total, false), (CalcWord::Mean, true)] { @@ -1122,9 +1016,7 @@ impl<'a> Parser<'a> { return aggregate(self.context.block, mean); } } - let phi = "1.6180339887498948482045868344" - .parse() - .unwrap_or(Decimal::ONE); + let phi = "1.6180339887498948482045868344".parse().unwrap_or(Decimal::ONE); for (constant, value) in [ (CalcWord::Pi, Decimal::PI), (CalcWord::E, Decimal::E), @@ -1161,9 +1053,7 @@ impl<'a> Parser<'a> { if words::reserved(word) { return Err(CalcError::Unreadable { at }); } - Err(CalcError::UnknownName { - name: word.to_string(), - }) + Err(CalcError::UnknownName { name: word.to_string() }) } } @@ -1195,11 +1085,7 @@ fn add(left: Value, right: Value, plus: bool) -> Answer { if a.dim != b.dim { return Err(mismatch(&Value::Quantity(a), &Value::Quantity(b))); } - let right = if a.dim.has_temperature() { - in_degrees_of(&b, &a) - } else { - b.amount - }; + let right = if a.dim.has_temperature() { in_degrees_of(&b, &a) } else { b.amount }; Ok(Value::Quantity(Quantity { amount: a.amount.checked_add(signed(right)).ok_or_else(overflow)?, unit: a.unit.or(b.unit), @@ -1210,15 +1096,11 @@ fn add(left: Value, right: Value, plus: bool) -> Answer { // `250 + 20 %` is 300: a percentage added to a quantity is a share of it. (Value::Quantity(a), Value::Percent { ratio, .. }) => { let factor = Decimal::ONE + signed(ratio); - Ok(Value::Quantity(Quantity { - amount: a.amount.checked_mul(factor).ok_or_else(overflow)?, - ..a - })) + Ok(Value::Quantity(Quantity { amount: a.amount.checked_mul(factor).ok_or_else(overflow)?, ..a })) + } + (Value::Percent { ratio: a, .. }, Value::Percent { ratio: b, .. }) => { + Ok(Value::Percent { ratio: a + signed(b), signed: false }) } - (Value::Percent { ratio: a, .. }, Value::Percent { ratio: b, .. }) => Ok(Value::Percent { - ratio: a + signed(b), - signed: false, - }), (Value::Date(date), Value::Quantity(shift)) if shift.dim == Dim::TIME => { shift_date(date, &shift, plus) } @@ -1252,11 +1134,7 @@ fn shift_date(date: NaiveDate, shift: &Quantity, plus: bool) -> Answer { let moved = match (count, steps >= 0) { (true, ahead) => { let months = Months::new(u32::try_from(size).map_err(|_| overflow())?); - if ahead { - date.checked_add_months(months) - } else { - date.checked_sub_months(months) - } + if ahead { date.checked_add_months(months) } else { date.checked_sub_months(months) } } (false, true) => date.checked_add_days(Days::new(size)), (false, false) => date.checked_sub_days(Days::new(size)), @@ -1316,8 +1194,7 @@ fn shown_for(dim: Dim, among: &[&Quantity]) -> Option { fn multiply(left: Value, right: Value) -> Answer { match (left, right) { (Value::Quantity(a), Value::Quantity(b)) => { - if (a.dim.has_temperature() && !b.dim.is_none()) - || (b.dim.has_temperature() && !a.dim.is_none()) + if (a.dim.has_temperature() && !b.dim.is_none()) || (b.dim.has_temperature() && !a.dim.is_none()) { return Err(CalcError::Unsupported); } @@ -1330,14 +1207,12 @@ fn multiply(left: Value, right: Value) -> Answer { })) } (Value::Quantity(a), Value::Percent { ratio, .. }) - | (Value::Percent { ratio, .. }, Value::Quantity(a)) => Ok(Value::Quantity(Quantity { - amount: a.amount.checked_mul(ratio).ok_or_else(overflow)?, - ..a - })), - (Value::Percent { ratio: a, .. }, Value::Percent { ratio: b, .. }) => Ok(Value::Percent { - ratio: a.checked_mul(b).ok_or_else(overflow)?, - signed: false, - }), + | (Value::Percent { ratio, .. }, Value::Quantity(a)) => { + Ok(Value::Quantity(Quantity { amount: a.amount.checked_mul(ratio).ok_or_else(overflow)?, ..a })) + } + (Value::Percent { ratio: a, .. }, Value::Percent { ratio: b, .. }) => { + Ok(Value::Percent { ratio: a.checked_mul(b).ok_or_else(overflow)?, signed: false }) + } (left, right) => Err(mismatch(&left, &right)), } } @@ -1366,20 +1241,12 @@ fn divide(left: Value, right: Value) -> Answer { } else { shown_for(dim, &[&a, &b]) }; - Ok(Value::Quantity(Quantity { - amount: by(a.amount, b.amount)?, - dim, - unit, - spans: false, - })) + Ok(Value::Quantity(Quantity { amount: by(a.amount, b.amount)?, dim, unit, spans: false })) } - (Value::Quantity(a), Value::Percent { ratio, .. }) => Ok(Value::Quantity(Quantity { - amount: by(a.amount, ratio)?, - ..a - })), - (Value::Percent { ratio: a, .. }, Value::Percent { ratio: b, .. }) => { - Ok(Value::number(by(a, b)?)) + (Value::Quantity(a), Value::Percent { ratio, .. }) => { + Ok(Value::Quantity(Quantity { amount: by(a.amount, ratio)?, ..a })) } + (Value::Percent { ratio: a, .. }, Value::Percent { ratio: b, .. }) => Ok(Value::number(by(a, b)?)), (left, right) => Err(mismatch(&left, &right)), } } @@ -1391,47 +1258,28 @@ impl Parser<'_> { let degree = match self.peek().cloned() { Some(Tok::Number(number)) if matches!(function, Function::Root | Function::Log) - && self - .tokens - .get(self.at + 1) - .is_some_and(|token| token.tok == Tok::Symbol('(')) => + && self.tokens.get(self.at + 1).is_some_and(|token| token.tok == Tok::Symbol('(')) => { self.take(TokenKind::Number); Some(number) } _ => None, }; - let argument = if self.peek_symbol(&['(']).is_some() { - self.primary()? - } else { - self.power()? - }; + let argument = if self.peek_symbol(&['(']).is_some() { self.primary()? } else { self.power()? }; let number = |value: &Value| plain(value); let result = match function { Function::Root => { let degree = degree.unwrap_or(Decimal::TWO); - number(&argument) - .and_then(|x| maths::root_of(x, degree)) - .map(Value::number) + number(&argument).and_then(|x| maths::root_of(x, degree)).map(Value::number) } - Function::Cbrt => number(&argument) - .and_then(|x| maths::root(x, 3)) - .map(Value::number), - Function::Log => number(&argument) - .and_then(|x| maths::log(x, degree)) - .map(Value::number), + Function::Cbrt => number(&argument).and_then(|x| maths::root(x, 3)).map(Value::number), + Function::Log => number(&argument).and_then(|x| maths::log(x, degree)).map(Value::number), Function::Ln => number(&argument).and_then(maths::ln).map(Value::number), Function::Abs => match argument { Value::Quantity(quantity) if !quantity.dim.has_temperature() => { - Ok(Value::Quantity(Quantity { - amount: quantity.amount.abs(), - ..quantity - })) + Ok(Value::Quantity(Quantity { amount: quantity.amount.abs(), ..quantity })) } - Value::Percent { ratio, signed } => Ok(Value::Percent { - ratio: ratio.abs(), - signed, - }), + Value::Percent { ratio, signed } => Ok(Value::Percent { ratio: ratio.abs(), signed }), _ => Err(CalcError::Unsupported), }, Function::Round | Function::Ceil | Function::Floor => { @@ -1440,9 +1288,7 @@ impl Parser<'_> { Function::Floor => Rounding::Down, _ => Rounding::Nearest, }; - self.in_its_unit(argument, |amount| { - maths::round_to(amount, Decimal::ONE, direction) - }) + self.in_its_unit(argument, |amount| maths::round_to(amount, Decimal::ONE, direction)) } Function::Written(notation) => return self.written(argument, notation), }; @@ -1462,22 +1308,14 @@ impl Parser<'_> { let next = self.additive()?; let order = match (&found, &next) { (Value::Quantity(a), Value::Quantity(b)) if a.dim == b.dim => { - let b_amount = if a.dim.has_temperature() { - in_degrees_of(b, a) - } else { - b.amount - }; + let b_amount = if a.dim.has_temperature() { in_degrees_of(b, a) } else { b.amount }; a.amount.cmp(&b_amount) } (Value::Percent { ratio: a, .. }, Value::Percent { ratio: b, .. }) => a.cmp(b), (Value::Date(a), Value::Date(b)) => a.cmp(b), _ => return Err(self.blame(mismatch(&found, &next))), }; - let keep_next = if largest { - order.is_lt() - } else { - order.is_gt() - }; + let keep_next = if largest { order.is_lt() } else { order.is_gt() }; if keep_next { found = next; } @@ -1526,10 +1364,9 @@ impl Parser<'_> { /// `3 ans`, `36 mois`: a duration in years. fn years(&mut self) -> Result { match self.principal()? { - Value::Quantity(quantity) if quantity.dim == Dim::TIME => quantity - .amount - .checked_div(Decimal::from(YEAR_SECONDS)) - .ok_or_else(overflow), + Value::Quantity(quantity) if quantity.dim == Dim::TIME => { + quantity.amount.checked_div(Decimal::from(YEAR_SECONDS)).ok_or_else(overflow) + } other => Err(self.blame(CalcError::Mismatch { expected: Dimension::Time, found: other.dimension(), @@ -1555,12 +1392,9 @@ impl Parser<'_> { if !self.eat(CalcWord::Compounded) { return Ok(Decimal::ONE); } - for (word, count) in [ - (CalcWord::Monthly, 12), - (CalcWord::Quarterly, 4), - (CalcWord::Yearly, 1), - (CalcWord::Daily, 365), - ] { + for (word, count) in + [(CalcWord::Monthly, 12), (CalcWord::Quarterly, 4), (CalcWord::Yearly, 1), (CalcWord::Daily, 365)] + { if self.eat(word) { return Ok(Decimal::from(count)); } @@ -1585,19 +1419,14 @@ impl Parser<'_> { return Err(self.unreadable()); } let grown = self.compound(principal.clone())?; - return add(grown, principal, false) - .map(Some) - .map_err(|error| self.blame(error)); + return add(grown, principal, false).map(Some).map_err(|error| self.blame(error)); } if self.eat(CalcWord::AnnualReturn) { return self.annual_return().map(Some); } if self.eat(CalcWord::PresentValue) { let future = self.principal()?; - if !(self.eat(CalcWord::Within) - || self.eat(CalcWord::After) - || self.eat(CalcWord::During)) - { + if !(self.eat(CalcWord::Within) || self.eat(CalcWord::After) || self.eat(CalcWord::During)) { return Err(self.unreadable()); } let years = self.years()?; @@ -1630,8 +1459,7 @@ impl Parser<'_> { if !self.eat(CalcWord::Returned) { return Err(self.unreadable()); } - if !(self.eat(CalcWord::Convert) || self.eat(CalcWord::After) || self.eat(CalcWord::During)) - { + if !(self.eat(CalcWord::Convert) || self.eat(CalcWord::After) || self.eat(CalcWord::During)) { return Err(self.unreadable()); } let years = self.years()?; @@ -1639,10 +1467,7 @@ impl Parser<'_> { let yearly = times .and_then(|times| maths::yearly(times, years)) .map_err(|error| self.blame(error))?; - Ok(Value::Percent { - ratio: yearly, - signed: false, - }) + Ok(Value::Percent { ratio: yearly, signed: false }) } /// `mensualité de 10 000 € sur 6 ans à 6 %` is 165,73 €; its total, its interest. @@ -1654,8 +1479,7 @@ impl Parser<'_> { let years = self.years()?; let rate = self.rate()?; let months = years * Decimal::from(12); - let payment = - maths::payment(rate / Decimal::from(12), months).map_err(|error| self.blame(error))?; + let payment = maths::payment(rate / Decimal::from(12), months).map_err(|error| self.blame(error))?; let factor = match part { Loan::Monthly => payment, Loan::Total => payment * months, @@ -1711,11 +1535,7 @@ fn modulo(left: Value, right: Value) -> Answer { if !rest.is_zero() && rest.is_sign_negative() != b.amount.is_sign_negative() { rest += b.amount; } - Ok(Value::Quantity(Quantity { - amount: rest, - spans: false, - ..a - })) + Ok(Value::Quantity(Quantity { amount: rest, spans: false, ..a })) } (left, right) => Err(mismatch(&left, &right)), } @@ -1729,10 +1549,7 @@ fn excluding(left: Value, right: Value) -> Answer { if divisor.is_zero() { return Err(CalcError::DivisionByZero); } - Ok(Value::Quantity(Quantity { - amount: a.amount.checked_div(divisor).ok_or_else(overflow)?, - ..a - })) + Ok(Value::Quantity(Quantity { amount: a.amount.checked_div(divisor).ok_or_else(overflow)?, ..a })) } (left, right) => Err(mismatch(&left, &right)), } @@ -1745,15 +1562,9 @@ fn ratio(left: &Value, right: &Value) -> Answer { if b.amount.is_zero() { return Err(CalcError::DivisionByZero); } - let (part, whole) = if a.dim.has_temperature() { - (a.amount, in_degrees_of(b, a)) - } else { - (a.amount, b.amount) - }; - Ok(Value::Percent { - ratio: part.checked_div(whole).ok_or_else(overflow)?, - signed: false, - }) + let (part, whole) = + if a.dim.has_temperature() { (a.amount, in_degrees_of(b, a)) } else { (a.amount, b.amount) }; + Ok(Value::Percent { ratio: part.checked_div(whole).ok_or_else(overflow)?, signed: false }) } _ => Err(mismatch(left, right)), } @@ -1766,13 +1577,8 @@ fn change(from: &Value, to: &Value) -> Answer { if a.amount.is_zero() { return Err(CalcError::DivisionByZero); } - let ratio = (b.amount - a.amount) - .checked_div(a.amount) - .ok_or_else(overflow)?; - Ok(Value::Percent { - ratio, - signed: true, - }) + let ratio = (b.amount - a.amount).checked_div(a.amount).ok_or_else(overflow)?; + Ok(Value::Percent { ratio, signed: true }) } _ => Err(mismatch(from, to)), } @@ -1794,11 +1600,7 @@ fn power(base: Value, exponent: Value) -> Answer { if !base.dim.is_none() { return Err(CalcError::Unsupported); } - let count = exponent - .amount - .to_i64() - .ok_or_else(overflow)? - .unsigned_abs(); + let count = exponent.amount.to_i64().ok_or_else(overflow)?.unsigned_abs(); let mut result = Decimal::ONE; for _ in 0..count { result = result.checked_mul(base.amount).ok_or_else(overflow)?; @@ -1814,14 +1616,8 @@ fn power(base: Value, exponent: Value) -> Answer { fn negate(value: Value) -> Answer { match value { - Value::Quantity(quantity) => Ok(Value::Quantity(Quantity { - amount: -quantity.amount, - ..quantity - })), - Value::Percent { ratio, signed } => Ok(Value::Percent { - ratio: -ratio, - signed, - }), + Value::Quantity(quantity) => Ok(Value::Quantity(Quantity { amount: -quantity.amount, ..quantity })), + Value::Percent { ratio, signed } => Ok(Value::Percent { ratio: -ratio, signed }), Value::Date(_) => Err(CalcError::Unsupported), } } @@ -1829,35 +1625,24 @@ fn negate(value: Value) -> Answer { /// ⚠️ Euros are never turned into dollars: no rate is fetched, the sheet works offline. fn convert(value: Value, shown: Shown, dim: Dim) -> Answer { let Value::Quantity(quantity) = value else { - return Err(CalcError::NotConvertible { - from: value.dimension(), - to: Some(shown.calc_unit()), - }); + return Err(CalcError::NotConvertible { from: value.dimension(), to: Some(shown.calc_unit()) }); }; if quantity.dim != dim { return Err(if quantity.dim.is_currency() && dim.is_currency() { CalcError::Currency } else { - CalcError::NotConvertible { - from: quantity.dim.dimension(), - to: Some(shown.calc_unit()), - } + CalcError::NotConvertible { from: quantity.dim.dimension(), to: Some(shown.calc_unit()) } }); } let amount = match (quantity.dim.has_temperature(), quantity.unit, shown) { - (true, Some(Shown::One(from)), Shown::One(to)) => { - from_celsius(to_celsius(quantity.amount, from), to) - } + (true, Some(Shown::One(from)), Shown::One(to)) => from_celsius(to_celsius(quantity.amount, from), to), _ => quantity.amount, }; Ok(Value::Quantity(Quantity { amount, dim, unit: Some(shown), - spans: matches!( - shown, - Shown::One(UnitId::Week | UnitId::Day | UnitId::Hour | UnitId::Minute) - ), + spans: matches!(shown, Shown::One(UnitId::Week | UnitId::Day | UnitId::Hour | UnitId::Minute)), })) } @@ -1869,28 +1654,12 @@ fn aggregate(block: &[Quantity], mean: bool) -> Answer { let mut sum = Decimal::ZERO; for quantity in block { if quantity.dim != first.dim { - return Err(mismatch( - &Value::Quantity(first.clone()), - &Value::Quantity(quantity.clone()), - )); + return Err(mismatch(&Value::Quantity(first.clone()), &Value::Quantity(quantity.clone()))); } - let amount = if first.dim.has_temperature() { - in_degrees_of(quantity, first) - } else { - quantity.amount - }; + let amount = + if first.dim.has_temperature() { in_degrees_of(quantity, first) } else { quantity.amount }; sum = sum.checked_add(amount).ok_or_else(overflow)?; } - let amount = if mean { - sum.checked_div(Decimal::from(block.len())) - .ok_or_else(overflow)? - } else { - sum - }; - Ok(Value::Quantity(Quantity { - amount, - dim: first.dim, - unit: first.unit, - spans: false, - })) + let amount = if mean { sum.checked_div(Decimal::from(block.len())).ok_or_else(overflow)? } else { sum }; + Ok(Value::Quantity(Quantity { amount, dim: first.dim, unit: first.unit, spans: false })) } diff --git a/crates/engine/src/notes/calc/lexer.rs b/crates/engine/src/notes/calc/lexer.rs index 410d92478..c604bb8a2 100644 --- a/crates/engine/src/notes/calc/lexer.rs +++ b/crates/engine/src/notes/calc/lexer.rs @@ -27,9 +27,8 @@ pub(super) struct Token { pub(super) spaced: bool, } -const SYMBOLS: &[char] = &[ - '+', '-', '−', '×', '*', '/', '÷', '^', '(', ')', '=', '%', '€', '$', '&', '|', '<', '>', '@', -]; +const SYMBOLS: &[char] = + &['+', '-', '−', '×', '*', '/', '÷', '^', '(', ')', '=', '%', '€', '$', '&', '|', '<', '>', '@']; fn is_word_start(character: char) -> bool { character.is_alphabetic() || character == '_' || character == '°' @@ -60,11 +59,7 @@ fn date_at(characters: &[char], at: usize) -> Option<(NaiveDate, usize)> { { let length = 10; if ends(length) { - let date = NaiveDate::from_ymd_opt( - year.parse().ok()?, - month.parse().ok()?, - day.parse().ok()?, - )?; + let date = NaiveDate::from_ymd_opt(year.parse().ok()?, month.parse().ok()?, day.parse().ok()?)?; return Some((date, length)); } } @@ -80,11 +75,7 @@ fn date_at(characters: &[char], at: usize) -> Option<(NaiveDate, usize)> { { let length = day.len() + month.len() + 2 + 4; if ends(length) { - let date = NaiveDate::from_ymd_opt( - year.parse().ok()?, - month.parse().ok()?, - day.parse().ok()?, - )?; + let date = NaiveDate::from_ymd_opt(year.parse().ok()?, month.parse().ok()?, day.parse().ok()?)?; return Some((date, length)); } } @@ -94,14 +85,8 @@ fn date_at(characters: &[char], at: usize) -> Option<(NaiveDate, usize)> { /// Three digits after a space, the next not a digit: `5 300`, and `1 578,13 €` as the front /// writes it, its space a no-break one. fn group_at(characters: &[char], at: usize) -> bool { - characters - .get(at) - .is_some_and(|c| matches!(c, ' ' | '\u{a0}' | '\u{202f}')) - && (1..=3).all(|offset| { - characters - .get(at + offset) - .is_some_and(char::is_ascii_digit) - }) + characters.get(at).is_some_and(|c| matches!(c, ' ' | '\u{a0}' | '\u{202f}')) + && (1..=3).all(|offset| characters.get(at + offset).is_some_and(char::is_ascii_digit)) && !characters.get(at + 4).is_some_and(char::is_ascii_digit) } @@ -116,15 +101,8 @@ fn based_at(characters: &[char], at: usize) -> Option<(Decimal, usize)> { 'o' | 'O' => 8, _ => return None, }; - let digits: String = characters[at + 2..] - .iter() - .take_while(|c| c.is_digit(radix)) - .collect(); - if digits.is_empty() - || characters - .get(at + 2 + digits.len()) - .is_some_and(|c| c.is_alphanumeric()) - { + let digits: String = characters[at + 2..].iter().take_while(|c| c.is_digit(radix)).collect(); + if digits.is_empty() || characters.get(at + 2 + digits.len()).is_some_and(|c| c.is_alphanumeric()) { return None; } let value = i128::from_str_radix(&digits, radix).ok()?; @@ -167,18 +145,14 @@ fn comma_groups(characters: &[char], end: usize, after_currency: bool) -> Option let mut probe = end; let mut groups = 0; while characters.get(probe) == Some(&',') - && (1..=3).all(|offset| { - characters - .get(probe + offset) - .is_some_and(char::is_ascii_digit) - }) + && (1..=3).all(|offset| characters.get(probe + offset).is_some_and(char::is_ascii_digit)) && !characters.get(probe + 4).is_some_and(char::is_ascii_digit) { probe += 4; groups += 1; } - let point = characters.get(probe) == Some(&'.') - && characters.get(probe + 1).is_some_and(char::is_ascii_digit); + let point = + characters.get(probe) == Some(&'.') && characters.get(probe + 1).is_some_and(char::is_ascii_digit); (groups > 0 && (after_currency || groups > 1 || point)).then_some(probe) } @@ -195,11 +169,7 @@ fn number_at(characters: &[char], at: usize, after_currency: bool) -> Option<(De if end == at { return None; } - let english = if end - at <= 3 { - comma_groups(characters, end, after_currency) - } else { - None - }; + let english = if end - at <= 3 { comma_groups(characters, end, after_currency) } else { None }; if let Some(grouped) = english { end = grouped; } else if end - at <= 3 { @@ -207,11 +177,7 @@ fn number_at(characters: &[char], at: usize, after_currency: bool) -> Option<(De end += 4; } } - let marks: &[char] = if english.is_some() { - &['.'] - } else { - &['.', ','] - }; + let marks: &[char] = if english.is_some() { &['.'] } else { &['.', ','] }; if characters.get(end).is_some_and(|mark| marks.contains(mark)) && characters.get(end + 1).is_some_and(char::is_ascii_digit) { @@ -238,9 +204,7 @@ fn word_at(characters: &[char], at: usize) -> usize { let mut end = at + 1; while let Some(&character) = characters.get(end) { let inner_apostrophe = matches!(character, '\'' | '’') - && characters - .get(end + 1) - .is_some_and(|next| next.is_alphabetic()); + && characters.get(end + 1).is_some_and(|next| next.is_alphabetic()); if is_word_part(character) || inner_apostrophe { end += 1; } else { @@ -299,10 +263,7 @@ pub(super) fn tokens(line: &str) -> Vec { (Tok::Number(number), length) } else if is_word_start(character) { let length = word_at(&characters, at); - ( - Tok::Word(characters[at..at + length].iter().collect()), - length, - ) + (Tok::Word(characters[at..at + length].iter().collect()), length) } else if SYMBOLS.contains(&character) { (Tok::Symbol(character), 1) } else if let Some(length) = quoted_at(&characters, at) { @@ -310,12 +271,7 @@ pub(super) fn tokens(line: &str) -> Vec { } else { (Tok::Other(character), 1) }; - tokens.push(Token { - tok, - start: offsets[at], - end: offsets[at + length], - spaced, - }); + tokens.push(Token { tok, start: offsets[at], end: offsets[at + length], spaced }); spaced = false; at += length; } diff --git a/crates/engine/src/notes/calc/maths.rs b/crates/engine/src/notes/calc/maths.rs index 3275ec5f5..af5fc4e25 100644 --- a/crates/engine/src/notes/calc/maths.rs +++ b/crates/engine/src/notes/calc/maths.rs @@ -19,19 +19,13 @@ fn overflow() -> CalcError { } /// To a multiple of `step`: `37 au 10 près` is 40. -pub(super) fn round_to( - amount: Decimal, - step: Decimal, - rounding: Rounding, -) -> Result { +pub(super) fn round_to(amount: Decimal, step: Decimal, rounding: Rounding) -> Result { if step.is_zero() { return Err(CalcError::DivisionByZero); } let steps = amount.checked_div(step.abs()).ok_or_else(overflow)?; let whole = match rounding { - Rounding::Nearest => { - steps.round_dp_with_strategy(0, RoundingStrategy::MidpointAwayFromZero) - } + Rounding::Nearest => steps.round_dp_with_strategy(0, RoundingStrategy::MidpointAwayFromZero), Rounding::Up => steps.ceil(), Rounding::Down => steps.floor(), }; @@ -62,11 +56,7 @@ fn power(base: Decimal, exponent: u32) -> Option { /// sheet writes and short of the last figure an approximation gets wrong. fn exact_root(x: Decimal, approximate: Decimal, degree: u32) -> Decimal { let candidate = approximate.round_dp(12).normalize(); - if power(candidate, degree) == Some(x) { - candidate - } else { - approximate - } + if power(candidate, degree) == Some(x) { candidate } else { approximate } } /// `racine 2 (8)` is the square root of 8: an even root of a negative number is refused. @@ -84,10 +74,7 @@ pub(super) fn root(x: Decimal, degree: u32) -> Result { let mut guess = if degree == 2 { size.sqrt().ok_or_else(overflow)? } else { - let estimate = size - .to_f64() - .ok_or_else(overflow)? - .powf(1.0 / f64::from(degree)); + let estimate = size.to_f64().ok_or_else(overflow)?.powf(1.0 / f64::from(degree)); Decimal::try_from(estimate).map_err(|_| overflow())? }; // Newton's steps take the estimate to every figure a decimal holds. @@ -98,9 +85,7 @@ pub(super) fn root(x: Decimal, degree: u32) -> Result { break; } let quotient = size.checked_div(below).ok_or_else(overflow)?; - guess = ((n - Decimal::ONE) * guess + quotient) - .checked_div(n) - .ok_or_else(overflow)?; + guess = ((n - Decimal::ONE) * guess + quotient).checked_div(n).ok_or_else(overflow)?; } let found = exact_root(size, guess, degree); Ok(if x.is_sign_negative() { -found } else { found }) @@ -121,21 +106,14 @@ pub(super) fn root_of(x: Decimal, degree: Decimal) -> Result if x.is_zero() { return Ok(x); } - let size = power_of( - x.abs(), - Decimal::ONE.checked_div(degree).ok_or_else(overflow)?, - )?; + let size = power_of(x.abs(), Decimal::ONE.checked_div(degree).ok_or_else(overflow)?)?; Ok(if x.is_sign_negative() { -size } else { size }) } /// A whole result a decimal logarithm only comes near: `ln(e)` is 1. fn whole_if_near(value: Decimal) -> Decimal { let whole = value.round(); - if (value - whole).abs() < Decimal::new(1, 20) { - whole - } else { - value - } + if (value - whole).abs() < Decimal::new(1, 20) { whole } else { value } } pub(super) fn ln(x: Decimal) -> Result { @@ -192,12 +170,7 @@ pub(super) enum Bits { pub(super) fn bits(left: Decimal, right: Decimal, operation: Bits) -> Result { let (a, b) = (whole(left)?, whole(right)?); - let shift = || { - u32::try_from(b) - .ok() - .filter(|count| *count < 127) - .ok_or_else(overflow) - }; + let shift = || u32::try_from(b).ok().filter(|count| *count < 127).ok_or_else(overflow); let value = match operation { Bits::And => a & b, Bits::Or => a | b, @@ -304,12 +277,8 @@ pub(super) fn fraction(value: Decimal) -> (bool, u128, u128) { for _ in 0..64 { let whole = rest.trunc(); let Some(step) = whole.to_u128() else { break }; - let numerator = step - .checked_mul(last.0) - .and_then(|product| product.checked_add(before.0)); - let denominator = step - .checked_mul(last.1) - .and_then(|product| product.checked_add(before.1)); + let numerator = step.checked_mul(last.0).and_then(|product| product.checked_add(before.0)); + let denominator = step.checked_mul(last.1).and_then(|product| product.checked_add(before.1)); let (Some(numerator), Some(denominator)) = (numerator, denominator) else { break; }; @@ -330,10 +299,7 @@ pub(super) fn fraction(value: Decimal) -> (bool, u128, u128) { return (negative, numerator, denominator); } let left = rest - whole; - let Some(next) = (!left.is_zero()) - .then(|| Decimal::ONE.checked_div(left)) - .flatten() - else { + let Some(next) = (!left.is_zero()).then(|| Decimal::ONE.checked_div(left)).flatten() else { break; }; rest = next; @@ -348,8 +314,7 @@ pub(super) fn scientific(value: Decimal) -> (String, i32) { return ("0".into(), 0); } let figures = value.mantissa().unsigned_abs().to_string(); - let exponent = - i32::try_from(figures.len()).unwrap_or(0) - 1 - i32::try_from(value.scale()).unwrap_or(0); + let exponent = i32::try_from(figures.len()).unwrap_or(0) - 1 - i32::try_from(value.scale()).unwrap_or(0); let rest = figures[1..].trim_end_matches('0'); let sign = if value.is_sign_negative() { "-" } else { "" }; let mantissa = if rest.is_empty() { diff --git a/crates/engine/src/notes/calc/summary.rs b/crates/engine/src/notes/calc/summary.rs index a63940e87..3afd361ff 100644 --- a/crates/engine/src/notes/calc/summary.rs +++ b/crates/engine/src/notes/calc/summary.rs @@ -27,10 +27,7 @@ pub fn summary(sheet: &CalcSheet, lines: &[u32]) -> CalcSummary { .iter() .filter_map(|line| sheet.rows.get(usize::try_from(*line).ok()?)) .filter_map(|row| match &row.line { - CalcLine::Value { - value: CalcValue::Number { value, unit }, - .. - } => Some((value.as_str(), *unit)), + CalcLine::Value { value: CalcValue::Number { value, unit }, .. } => Some((value.as_str(), *unit)), _ => None, }) .collect(); @@ -76,37 +73,22 @@ mod tests { fn figures(sum: &str, mean: &str, unit: Option) -> CalcSummary { let unit = unit.map(|unit| CalcUnit { unit, per: None }); CalcSummary::Figures { - sum: CalcValue::Number { - value: sum.into(), - unit, - }, - mean: CalcValue::Number { - value: mean.into(), - unit, - }, + sum: CalcValue::Number { value: sum.into(), unit }, + mean: CalcValue::Number { value: mean.into(), unit }, } } #[test] fn the_lines_chosen_add_up_and_average_exactly_in_their_unit() { - assert_eq!( - summed("0,1 €\n0,2 €\n5 €", &[0, 1]), - figures("0.3", "0.15", Some(UnitId::Euro)) - ); - assert_eq!( - summed("1\n2\n4", &[0, 1, 2]), - figures("7", "2.333333333333333333333333", None) - ); + assert_eq!(summed("0,1 €\n0,2 €\n5 €", &[0, 1]), figures("0.3", "0.15", Some(UnitId::Euro))); + assert_eq!(summed("1\n2\n4", &[0, 1, 2]), figures("7", "2.333333333333333333333333", None)); } #[test] fn a_line_that_gave_no_number_is_left_out() { let sheet = "3\ndes mots\n1 / 0\n20 %\naujourd'hui\n\n5"; - assert_eq!( - summed(sheet, &[0, 1, 2, 3, 4, 5, 6, 99]), - figures("8", "4", None) - ); + assert_eq!(summed(sheet, &[0, 1, 2, 3, 4, 5, 6, 99]), figures("8", "4", None)); } #[test] @@ -126,10 +108,7 @@ mod tests { fn a_sum_past_what_a_decimal_holds_overflows() { let huge = "79228162514264337593543950335"; - assert_eq!( - summed(&format!("{huge}\n{huge}"), &[0, 1]), - CalcSummary::Overflow - ); + assert_eq!(summed(&format!("{huge}\n{huge}"), &[0, 1]), CalcSummary::Overflow); } /// The sums and means the front's footer was checked against (`golden/calc-format`). @@ -157,10 +136,7 @@ mod tests { assert_eq!( got, - CalcValue::Number { - value: case["output"].as_str().expect("an output").into(), - unit: None - }, + CalcValue::Number { value: case["output"].as_str().expect("an output").into(), unit: None }, "{footer} of {input:?}" ); checked += 1; diff --git a/crates/engine/src/notes/calc/units.rs b/crates/engine/src/notes/calc/units.rs index c368ff2f8..9d479305e 100644 --- a/crates/engine/src/notes/calc/units.rs +++ b/crates/engine/src/notes/calc/units.rs @@ -218,309 +218,69 @@ use UnitId as U; /// they are the English `to` and a month. const UNITS: &[(UnitId, Dim, Size, &[&str])] = &[ (U::Nanometre, Dim::LENGTH, Exact("0.000000001"), &["nm"]), - ( - U::Micrometre, - Dim::LENGTH, - Exact("0.000001"), - &["µm", "μm", "um"], - ), + (U::Micrometre, Dim::LENGTH, Exact("0.000001"), &["µm", "μm", "um"]), (U::Millimetre, Dim::LENGTH, Exact("0.001"), &["mm"]), (U::Centimetre, Dim::LENGTH, Exact("0.01"), &["cm"]), - ( - U::Metre, - Dim::LENGTH, - Exact("1"), - &["m", "mètre", "mètres", "metre", "metres", "meter", "meters"], - ), + (U::Metre, Dim::LENGTH, Exact("1"), &["m", "mètre", "mètres", "metre", "metres", "meter", "meters"]), (U::Kilometre, Dim::LENGTH, Exact("1000"), &["km"]), - ( - U::Inch, - Dim::LENGTH, - Exact("0.0254"), - &["in", "po", "pouce", "pouces", "inch", "inches"], - ), - ( - U::Foot, - Dim::LENGTH, - Exact("0.3048"), - &["ft", "pied", "pieds", "foot", "feet"], - ), - ( - U::Yard, - Dim::LENGTH, - Exact("0.9144"), - &["yd", "yard", "yards"], - ), - ( - U::Mile, - Dim::LENGTH, - Exact("1609.344"), - &["mi", "mile", "miles"], - ), + (U::Inch, Dim::LENGTH, Exact("0.0254"), &["in", "po", "pouce", "pouces", "inch", "inches"]), + (U::Foot, Dim::LENGTH, Exact("0.3048"), &["ft", "pied", "pieds", "foot", "feet"]), + (U::Yard, Dim::LENGTH, Exact("0.9144"), &["yd", "yard", "yards"]), + (U::Mile, Dim::LENGTH, Exact("1609.344"), &["mi", "mile", "miles"]), (U::Pixel, Dim::LENGTH, Over("0.0254", "96"), &["px"]), (U::Point, Dim::LENGTH, Over("0.0254", "72"), &["pt"]), (U::Em, Dim::LENGTH, Over("0.4064", "96"), &["em"]), (U::Rem, Dim::LENGTH, Over("0.4064", "96"), &["rem"]), (U::Milligram, Dim::MASS, Exact("0.000001"), &["mg"]), - ( - U::Gram, - Dim::MASS, - Exact("0.001"), - &["g", "gramme", "grammes", "gram", "grams"], - ), + (U::Gram, Dim::MASS, Exact("0.001"), &["g", "gramme", "grammes", "gram", "grams"]), (U::Kilogram, Dim::MASS, Exact("1"), &["kg"]), - ( - U::Tonne, - Dim::MASS, - Exact("1000"), - &["t", "tonne", "tonnes"], - ), - ( - U::Pound, - Dim::MASS, - Exact("0.45359237"), - &["lb", "lbs", "livre", "livres", "pound", "pounds"], - ), - ( - U::Ounce, - Dim::MASS, - Exact("0.028349523125"), - &["oz", "once", "onces", "ounce", "ounces"], - ), + (U::Tonne, Dim::MASS, Exact("1000"), &["t", "tonne", "tonnes"]), + (U::Pound, Dim::MASS, Exact("0.45359237"), &["lb", "lbs", "livre", "livres", "pound", "pounds"]), + (U::Ounce, Dim::MASS, Exact("0.028349523125"), &["oz", "once", "onces", "ounce", "ounces"]), (U::Nanosecond, Dim::TIME, Exact("0.000000001"), &["ns"]), - ( - U::Microsecond, - Dim::TIME, - Exact("0.000001"), - &["µs", "μs", "us"], - ), + (U::Microsecond, Dim::TIME, Exact("0.000001"), &["µs", "μs", "us"]), (U::Millisecond, Dim::TIME, Exact("0.001"), &["ms"]), - ( - U::Second, - Dim::TIME, - Exact("1"), - &["s", "sec", "seconde", "secondes", "second", "seconds"], - ), - ( - U::Minute, - Dim::TIME, - Exact("60"), - &["min", "mn", "minute", "minutes"], - ), - ( - U::Hour, - Dim::TIME, - Exact("3600"), - &["h", "heure", "heures", "hour", "hours"], - ), - ( - U::Day, - Dim::TIME, - Exact("86400"), - &["j", "jour", "jours", "d", "day", "days"], - ), - ( - U::Week, - Dim::TIME, - Exact("604800"), - &["sem", "semaine", "semaines", "wk", "week", "weeks"], - ), + (U::Second, Dim::TIME, Exact("1"), &["s", "sec", "seconde", "secondes", "second", "seconds"]), + (U::Minute, Dim::TIME, Exact("60"), &["min", "mn", "minute", "minutes"]), + (U::Hour, Dim::TIME, Exact("3600"), &["h", "heure", "heures", "hour", "hours"]), + (U::Day, Dim::TIME, Exact("86400"), &["j", "jour", "jours", "d", "day", "days"]), + (U::Week, Dim::TIME, Exact("604800"), &["sem", "semaine", "semaines", "wk", "week", "weeks"]), // The mean month and year of the Gregorian calendar; a date moves by calendar months. - ( - U::Month, - Dim::TIME, - Exact("2629746"), - &["mois", "month", "months", "mo"], - ), - ( - U::Year, - Dim::TIME, - Exact("31556952"), - &["an", "ans", "année", "années", "y", "yr", "year", "years"], - ), - ( - U::Bit, - Dim::DATA, - Data(SizeUnit::Bit), - &["b", "bit", "bits"], - ), - ( - U::Kilobit, - Dim::DATA, - Data(SizeUnit::Kilobit), - &["Kb", "kbit", "Kbit"], - ), - ( - U::Megabit, - Dim::DATA, - Data(SizeUnit::Megabit), - &["Mb", "Mbit", "mbit"], - ), - ( - U::Gigabit, - Dim::DATA, - Data(SizeUnit::Gigabit), - &["Gb", "Gbit", "gbit"], - ), - ( - U::Terabit, - Dim::DATA, - Data(SizeUnit::Terabit), - &["Tb", "Tbit", "tbit"], - ), - ( - U::Petabit, - Dim::DATA, - Exact("1000000000000000"), - &["Pb", "Pbit", "pbit"], - ), - ( - U::Byte, - Dim::DATA, - Data(SizeUnit::Byte), - &["o", "B", "octet", "octets", "byte", "bytes"], - ), - ( - U::Kilobyte, - Dim::DATA, - Data(SizeUnit::Kilobyte), - &["Ko", "ko", "kB", "KB"], - ), - ( - U::Megabyte, - Dim::DATA, - Data(SizeUnit::Megabyte), - &["Mo", "MB"], - ), - ( - U::Gigabyte, - Dim::DATA, - Data(SizeUnit::Gigabyte), - &["Go", "go", "GB", "gb"], - ), - ( - U::Terabyte, - Dim::DATA, - Data(SizeUnit::Terabyte), - &["To", "TB", "tb"], - ), - ( - U::Petabyte, - Dim::DATA, - Data(SizeUnit::Petabyte), - &["Po", "PB"], - ), - ( - U::Exabyte, - Dim::DATA, - Exact("8000000000000000000"), - &["Eo", "EB"], - ), - ( - U::Zettabyte, - Dim::DATA, - Exact("8000000000000000000000"), - &["Zo", "ZB"], - ), - ( - U::Yottabyte, - Dim::DATA, - Exact("8000000000000000000000000"), - &["Yo", "YB"], - ), - ( - U::Kibibyte, - Dim::DATA, - Data(SizeUnit::Kibibyte), - &["Kio", "kio", "KiB", "kiB"], - ), - ( - U::Mebibyte, - Dim::DATA, - Data(SizeUnit::Mebibyte), - &["Mio", "mio", "MiB"], - ), - ( - U::Gibibyte, - Dim::DATA, - Data(SizeUnit::Gibibyte), - &["Gio", "gio", "GiB"], - ), - ( - U::Tebibyte, - Dim::DATA, - Data(SizeUnit::Tebibyte), - &["Tio", "tio", "TiB"], - ), - ( - U::Pebibyte, - Dim::DATA, - Data(SizeUnit::Pebibyte), - &["Pio", "pio", "PiB"], - ), - ( - U::Exbibyte, - Dim::DATA, - Exact("9223372036854775808"), - &["Eio", "EiB"], - ), - ( - U::Zebibyte, - Dim::DATA, - Exact("9444732965739290427392"), - &["Zio", "ZiB"], - ), - ( - U::Yobibyte, - Dim::DATA, - Exact("9671406556917033397649408"), - &["Yio", "YiB"], - ), - ( - U::Celsius, - Dim::TEMPERATURE, - Exact("1"), - &["°C", "°c", "celsius"], - ), - ( - U::Fahrenheit, - Dim::TEMPERATURE, - Exact("1"), - &["°F", "°f", "fahrenheit"], - ), - ( - U::Kelvin, - Dim::TEMPERATURE, - Exact("1"), - &["K", "kelvin", "kelvins"], - ), + (U::Month, Dim::TIME, Exact("2629746"), &["mois", "month", "months", "mo"]), + (U::Year, Dim::TIME, Exact("31556952"), &["an", "ans", "année", "années", "y", "yr", "year", "years"]), + (U::Bit, Dim::DATA, Data(SizeUnit::Bit), &["b", "bit", "bits"]), + (U::Kilobit, Dim::DATA, Data(SizeUnit::Kilobit), &["Kb", "kbit", "Kbit"]), + (U::Megabit, Dim::DATA, Data(SizeUnit::Megabit), &["Mb", "Mbit", "mbit"]), + (U::Gigabit, Dim::DATA, Data(SizeUnit::Gigabit), &["Gb", "Gbit", "gbit"]), + (U::Terabit, Dim::DATA, Data(SizeUnit::Terabit), &["Tb", "Tbit", "tbit"]), + (U::Petabit, Dim::DATA, Exact("1000000000000000"), &["Pb", "Pbit", "pbit"]), + (U::Byte, Dim::DATA, Data(SizeUnit::Byte), &["o", "B", "octet", "octets", "byte", "bytes"]), + (U::Kilobyte, Dim::DATA, Data(SizeUnit::Kilobyte), &["Ko", "ko", "kB", "KB"]), + (U::Megabyte, Dim::DATA, Data(SizeUnit::Megabyte), &["Mo", "MB"]), + (U::Gigabyte, Dim::DATA, Data(SizeUnit::Gigabyte), &["Go", "go", "GB", "gb"]), + (U::Terabyte, Dim::DATA, Data(SizeUnit::Terabyte), &["To", "TB", "tb"]), + (U::Petabyte, Dim::DATA, Data(SizeUnit::Petabyte), &["Po", "PB"]), + (U::Exabyte, Dim::DATA, Exact("8000000000000000000"), &["Eo", "EB"]), + (U::Zettabyte, Dim::DATA, Exact("8000000000000000000000"), &["Zo", "ZB"]), + (U::Yottabyte, Dim::DATA, Exact("8000000000000000000000000"), &["Yo", "YB"]), + (U::Kibibyte, Dim::DATA, Data(SizeUnit::Kibibyte), &["Kio", "kio", "KiB", "kiB"]), + (U::Mebibyte, Dim::DATA, Data(SizeUnit::Mebibyte), &["Mio", "mio", "MiB"]), + (U::Gibibyte, Dim::DATA, Data(SizeUnit::Gibibyte), &["Gio", "gio", "GiB"]), + (U::Tebibyte, Dim::DATA, Data(SizeUnit::Tebibyte), &["Tio", "tio", "TiB"]), + (U::Pebibyte, Dim::DATA, Data(SizeUnit::Pebibyte), &["Pio", "pio", "PiB"]), + (U::Exbibyte, Dim::DATA, Exact("9223372036854775808"), &["Eio", "EiB"]), + (U::Zebibyte, Dim::DATA, Exact("9444732965739290427392"), &["Zio", "ZiB"]), + (U::Yobibyte, Dim::DATA, Exact("9671406556917033397649408"), &["Yio", "YiB"]), + (U::Celsius, Dim::TEMPERATURE, Exact("1"), &["°C", "°c", "celsius"]), + (U::Fahrenheit, Dim::TEMPERATURE, Exact("1"), &["°F", "°f", "fahrenheit"]), + (U::Kelvin, Dim::TEMPERATURE, Exact("1"), &["K", "kelvin", "kelvins"]), (U::Hertz, Dim::FREQUENCY, Exact("1"), &["Hz", "hz", "hertz"]), (U::Kilohertz, Dim::FREQUENCY, Exact("1000"), &["kHz", "khz"]), (U::Megahertz, Dim::FREQUENCY, Exact("1000000"), &["MHz"]), - ( - U::Gigahertz, - Dim::FREQUENCY, - Exact("1000000000"), - &["GHz", "ghz"], - ), - ( - U::Terahertz, - Dim::FREQUENCY, - Exact("1000000000000"), - &["THz", "thz"], - ), - ( - U::Euro, - Dim::EURO, - Exact("1"), - &["€", "euro", "euros", "EUR"], - ), - ( - U::Dollar, - Dim::DOLLAR, - Exact("1"), - &["$", "dollar", "dollars", "USD"], - ), + (U::Gigahertz, Dim::FREQUENCY, Exact("1000000000"), &["GHz", "ghz"]), + (U::Terahertz, Dim::FREQUENCY, Exact("1000000000000"), &["THz", "thz"]), + (U::Euro, Dim::EURO, Exact("1"), &["€", "euro", "euros", "EUR"]), + (U::Dollar, Dim::DOLLAR, Exact("1"), &["$", "dollar", "dollars", "USD"]), ]; pub fn table() -> Vec { @@ -553,10 +313,7 @@ pub struct UnitEntry { pub fn catalogue() -> Vec { UNITS .iter() - .map(|&(id, dim, _, _)| UnitEntry { - id, - dimension: dim.dimension(), - }) + .map(|&(id, dim, _, _)| UnitEntry { id, dimension: dim.dimension() }) .collect() } @@ -571,11 +328,7 @@ pub struct Css { impl Default for Css { fn default() -> Self { - Self { - ppi: Decimal::from(96), - em: Decimal::from(16), - rem: Decimal::from(16), - } + Self { ppi: Decimal::from(96), em: Decimal::from(16), rem: Decimal::from(16) } } } @@ -645,19 +398,13 @@ mod tests { #[test] fn the_catalogue_offers_each_unit_once_with_what_it_measures() { let catalogue = catalogue(); - let mut ids: Vec<_> = catalogue - .iter() - .map(|entry| format!("{:?}", entry.id)) - .collect(); + let mut ids: Vec<_> = catalogue.iter().map(|entry| format!("{:?}", entry.id)).collect(); ids.sort(); ids.dedup(); assert_eq!(ids.len(), catalogue.len()); assert_eq!(catalogue.len(), table().len()); - let euro = catalogue - .iter() - .find(|entry| entry.id == UnitId::Euro) - .expect("euros"); + let euro = catalogue.iter().find(|entry| entry.id == UnitId::Euro).expect("euros"); assert_eq!(euro.dimension, Dimension::Euro); } } diff --git a/crates/engine/src/notes/calc/words.rs b/crates/engine/src/notes/calc/words.rs index f274717c6..e3beb9e2e 100644 --- a/crates/engine/src/notes/calc/words.rs +++ b/crates/engine/src/notes/calc/words.rs @@ -133,10 +133,7 @@ pub struct Spellings { } impl CalcWord { - #[allow( - clippy::too_many_lines, - reason = "one line per concept: the table is the point" - )] + #[allow(clippy::too_many_lines, reason = "one line per concept: the table is the point")] pub const fn spellings(self) -> Spellings { use WordClass::{Setting, Syntax, Value}; let (class, fr, en): (WordClass, &[&str], &[&str]) = match self { @@ -149,16 +146,8 @@ impl CalcWord { Self::Excluding => (Syntax, &["hors", "ex"], &["excluding", "excl", "ex"]), Self::Plus => (Syntax, &["plus", "avec"], &["plus", "with"]), Self::And => (Syntax, &["et"], &["and"]), - Self::Minus => ( - Syntax, - &["moins", "sans"], - &["minus", "without", "subtract"], - ), - Self::Times => ( - Syntax, - &["fois", "multiplié par", "mul"], - &["times", "multiplied by", "mul"], - ), + Self::Minus => (Syntax, &["moins", "sans"], &["minus", "without", "subtract"]), + Self::Times => (Syntax, &["fois", "multiplié par", "mul"], &["times", "multiplied by", "mul"]), Self::Divide => (Syntax, &["divisé par"], &["divided by", "divide by"]), Self::Modulo => (Syntax, &["mod", "modulo"], &["mod", "modulo"]), Self::Total => (Value, &["total", "somme"], &["total", "sum"]), @@ -171,22 +160,14 @@ impl CalcWord { Self::Mega => (Value, &["M"], &["M"]), Self::Giga => (Value, &["Md"], &["bn"]), Self::Tera => (Value, &["T"], &["T", "tn"]), - Self::Thousand => ( - Value, - &["mille", "millier", "milliers"], - &["thousand", "thousands"], - ), + Self::Thousand => (Value, &["mille", "millier", "milliers"], &["thousand", "thousands"]), Self::Million => (Value, &["million", "millions"], &["million", "millions"]), Self::Billion => (Value, &["milliard", "milliards"], &["billion", "billions"]), Self::Trillion => (Value, &["mille milliards"], &["trillion", "trillions"]), Self::Ten => (Value, &["dizaine", "dizaines"], &["ten", "tens"]), Self::Hundred => (Value, &["centaine", "centaines"], &["hundred", "hundreds"]), Self::Xor => (Syntax, &["xor"], &["xor"]), - Self::Decimals => ( - Syntax, - &["décimales", "décimale"], - &["dp", "decimals", "decimal"], - ), + Self::Decimals => (Syntax, &["décimales", "décimale"], &["dp", "decimals", "decimal"]), Self::Digits => (Syntax, &["chiffres", "chiffre"], &["digits", "digit"]), Self::Rounded => (Syntax, &["arrondi"], &["rounded"]), Self::RoundedUp => (Syntax, &["arrondi supérieur"], &["rounded up"]), @@ -228,23 +209,13 @@ impl CalcWord { Self::PercentOff => (Syntax, &["de moins sur", "de moins que"], &["off"]), Self::What => (Syntax, &["combien"], &["what"]), Self::Is => (Syntax, &["font", "fait"], &["is"]), - Self::WhatPercent => ( - Syntax, - &["c'est combien de %", "combien de %"], - &["is what %"], - ), - Self::WhatTimes => ( - Syntax, - &["c'est combien de fois", "combien de fois"], - &["is what x", "is what times"], - ), + Self::WhatPercent => (Syntax, &["c'est combien de %", "combien de %"], &["is what %"]), + Self::WhatTimes => { + (Syntax, &["c'est combien de fois", "combien de fois"], &["is what x", "is what times"]) + } // Values, not syntax: `x` and `a` are names a sheet gives often. Self::Fraction => (Value, &["fraction"], &["fraction"]), - Self::Multiple => ( - Value, - &["multiple", "multiplicateur"], - &["multiplier", "multiple", "x"], - ), + Self::Multiple => (Value, &["multiple", "multiplicateur"], &["multiplier", "multiple", "x"]), Self::AsDecimal => (Value, &["décimal"], &["decimal", "dec"]), Self::Article => (Value, &[], &["a"]), Self::IsTo => (Syntax, &["est à"], &["is to"]), @@ -252,20 +223,14 @@ impl CalcWord { Self::After => (Syntax, &["après"], &["after"]), Self::During => (Syntax, &["pendant"], &["for"]), Self::Within => (Syntax, &["dans"], &[]), - Self::Compounded => ( - Syntax, - &["composés", "composé", "composées", "composée"], - &["compounding", "compounded"], - ), + Self::Compounded => { + (Syntax, &["composés", "composé", "composées", "composée"], &["compounding", "compounded"]) + } Self::Monthly => (Syntax, &["mensuellement"], &["monthly"]), Self::Quarterly => (Syntax, &["trimestriellement"], &["quarterly"]), Self::Yearly => (Syntax, &["annuellement"], &["annually", "yearly"]), Self::Daily => (Syntax, &["quotidiennement"], &["daily"]), - Self::InterestOn => ( - Syntax, - &["intérêts sur", "intérêts de"], - &["interest on", "interest of"], - ), + Self::InterestOn => (Syntax, &["intérêts sur", "intérêts de"], &["interest on", "interest of"]), Self::Invested => (Syntax, &["investis", "investi"], &["invested"]), Self::Returned => (Syntax, &["récupérés", "récupéré"], &["returned"]), Self::AnnualReturn => ( @@ -277,12 +242,7 @@ impl CalcWord { Self::Repayment => ( Syntax, &["mensualité de", "mensualité sur"], - &[ - "monthly repayment on", - "monthly repayment of", - "monthly payment on", - "monthly payment of", - ], + &["monthly repayment on", "monthly repayment of", "monthly payment on", "monthly payment of"], ), Self::TotalRepayment => ( Syntax, @@ -404,12 +364,7 @@ pub fn catalogue() -> Vec { .iter() .map(|&word| { let spellings = word.spellings(); - WordEntry { - word, - class: spellings.class, - fr: spellings.fr.to_vec(), - en: spellings.en.to_vec(), - } + WordEntry { word, class: spellings.class, fr: spellings.fr.to_vec(), en: spellings.en.to_vec() } }) .collect() } @@ -427,21 +382,13 @@ mod tests { for word in CalcWord::ALL { for spelling in word.every_spelling() { let line = tokens(spelling); - assert_eq!( - spelled(word, &line, 0), - Some(line.len()), - "{spelling} is not read as {word}" - ); + assert_eq!(spelled(word, &line, 0), Some(line.len()), "{spelling} is not read as {word}"); if word.exact() { continue; } let mut letters = spelling.chars(); - let capital: String = letters - .next() - .into_iter() - .flat_map(char::to_uppercase) - .chain(letters) - .collect(); + let capital: String = + letters.next().into_iter().flat_map(char::to_uppercase).chain(letters).collect(); assert!(spelled(word, &tokens(&capital), 0).is_some()); } } @@ -457,10 +404,8 @@ mod tests { concepts.entry(spelling).or_default().insert(word); } } - let shared: BTreeMap<&str, BTreeSet> = concepts - .into_iter() - .filter(|(_, words)| words.len() > 1) - .collect(); + let shared: BTreeMap<&str, BTreeSet> = + concepts.into_iter().filter(|(_, words)| words.len() > 1).collect(); let declared: BTreeMap<&str, BTreeSet> = SHARED .iter() .map(|(spelling, words)| (*spelling, words.iter().copied().collect())) @@ -482,10 +427,8 @@ mod tests { #[test] fn a_word_that_is_also_a_unit_is_told_apart_by_where_it_stands() { - let symbols: BTreeSet<&str> = units::table() - .iter() - .flat_map(|unit| unit.symbols.iter().copied()) - .collect(); + let symbols: BTreeSet<&str> = + units::table().iter().flat_map(|unit| unit.symbols.iter().copied()).collect(); let both: BTreeSet<&str> = CalcWord::ALL .iter() .flat_map(|word| word.every_spelling()) diff --git a/crates/engine/src/notes/checklist.rs b/crates/engine/src/notes/checklist.rs index cdce44e02..a80697a64 100644 --- a/crates/engine/src/notes/checklist.rs +++ b/crates/engine/src/notes/checklist.rs @@ -16,10 +16,7 @@ pub fn normalize_items(items: &[ChecklistItem]) -> Vec { .iter() .filter_map(|item| { let text = item.text.trim(); - (!text.is_empty()).then(|| ChecklistItem { - text: text.to_string(), - done: item.done, - }) + (!text.is_empty()).then(|| ChecklistItem { text: text.to_string(), done: item.done }) }) .collect() } @@ -38,10 +35,7 @@ mod tests { use super::*; fn item(text: &str, done: bool) -> ChecklistItem { - ChecklistItem { - text: text.into(), - done, - } + ChecklistItem { text: text.into(), done } } #[test] @@ -62,10 +56,7 @@ mod tests { fn two_identical_items_are_two_items_in_their_order() { let items = normalize_items(&[item("b", false), item("a", false), item("b", false)]); - assert_eq!( - items, - [item("b", false), item("a", false), item("b", false)] - ); + assert_eq!(items, [item("b", false), item("a", false), item("b", false)]); } #[test] diff --git a/crates/engine/src/notes/convert.rs b/crates/engine/src/notes/convert.rs index f05ec5553..09aff9be0 100644 --- a/crates/engine/src/notes/convert.rs +++ b/crates/engine/src/notes/convert.rs @@ -36,12 +36,9 @@ pub fn convert(note: &Note, into: NoteKind) -> NoteBody { (_, NoteKind::Checklist | NoteKind::Drawing) => String::new(), (NoteKind::Drawing, _) => drawing::words(¬e.content), (NoteKind::Checklist, NoteKind::Note) => checklist::to_markdown(¬e.items), - (NoteKind::Checklist, _) => note - .items - .iter() - .map(|item| item.text.as_str()) - .collect::>() - .join("\n"), + (NoteKind::Checklist, _) => { + note.items.iter().map(|item| item.text.as_str()).collect::>().join("\n") + } _ => note.content.clone(), }; let items = match (note.kind, into) { @@ -50,18 +47,9 @@ pub fn convert(note: &Note, into: NoteKind) -> NoteBody { (_, NoteKind::Checklist) => items_of(¬e.content), _ => Vec::new(), }; - let language = if into.has_language() { - language::from_content(&content) - } else { - Language::default() - }; + let language = if into.has_language() { language::from_content(&content) } else { Language::default() }; - NoteBody { - kind: into, - language, - content, - items, - } + NoteBody { kind: into, language, content, items } } /// One item per line that is not blank: a list's marker dropped, a task's box read as done. @@ -71,10 +59,7 @@ pub fn items_of(text: &str) -> Vec { .map(|line| { let line = without_marker(line.trim()); let (done, text) = without_box(line); - ChecklistItem { - text: text.to_string(), - done, - } + ChecklistItem { text: text.to_string(), done } }) .collect(); @@ -129,27 +114,15 @@ mod tests { const PYTHON: &str = "#!/usr/bin/env python\nprint(1)"; fn item(text: &str, done: bool) -> ChecklistItem { - ChecklistItem { - text: text.into(), - done, - } + ChecklistItem { text: text.into(), done } } fn note(kind: NoteKind, content: &str) -> Note { - Note { - kind, - content: content.into(), - ..fixtures::note() - } + Note { kind, content: content.into(), ..fixtures::note() } } fn checklist(items: Vec) -> Note { - Note { - kind: NoteKind::Checklist, - content: String::new(), - items, - ..fixtures::note() - } + Note { kind: NoteKind::Checklist, content: String::new(), items, ..fixtures::note() } } fn scene(texts: &[&str]) -> String { @@ -181,38 +154,22 @@ mod tests { (NoteKind::Calc, Language::Txt), (NoteKind::Checklist, Language::Txt), ] { - assert_eq!( - convert(¬e(NoteKind::Note, PYTHON), into).language, - language, - "{into}" - ); + assert_eq!(convert(¬e(NoteKind::Note, PYTHON), into).language, language, "{into}"); } } #[test] fn a_text_becomes_one_item_per_line_that_is_not_blank() { - let body = convert( - ¬e(NoteKind::Note, "- [ ] write\n\n - [x] ship \n plain"), - NoteKind::Checklist, - ); + let body = + convert(¬e(NoteKind::Note, "- [ ] write\n\n - [x] ship \n plain"), NoteKind::Checklist); assert_eq!(body.content, ""); - assert_eq!( - body.items, - [ - item("write", false), - item("ship", true), - item("plain", false) - ] - ); + assert_eq!(body.items, [item("write", false), item("ship", true), item("plain", false)]); } #[test] fn a_todo_list_becomes_a_task_list_in_a_note() { - let body = convert( - &checklist(vec![item("write", true), item("ship", false)]), - NoteKind::Note, - ); + let body = convert(&checklist(vec![item("write", true), item("ship", false)]), NoteKind::Note); assert_eq!(body.content, "- [x] write\n- [ ] ship"); assert!(body.items.is_empty()); @@ -221,10 +178,7 @@ mod tests { #[test] fn a_todo_list_becomes_its_texts_one_a_line_elsewhere() { for into in [NoteKind::Snippet, NoteKind::Calc] { - let body = convert( - &checklist(vec![item("2 + 2", true), item("3 * 3", false)]), - into, - ); + let body = convert(&checklist(vec![item("2 + 2", true), item("3 * 3", false)]), into); assert_eq!(body.content, "2 + 2\n3 * 3", "{into}"); assert!(body.items.is_empty()); @@ -263,10 +217,7 @@ mod tests { #[test] fn nothing_written_becomes_a_drawing() { - let sources = [ - note(NoteKind::Snippet, PYTHON), - checklist(vec![item("a", false)]), - ]; + let sources = [note(NoteKind::Snippet, PYTHON), checklist(vec![item("a", false)])]; for source in sources { let body = convert(&source, NoteKind::Drawing); @@ -303,15 +254,7 @@ mod tests { fn a_task_box_is_read_as_the_item_s_state() { let items = items_of("[ ] a\n[x] b\n[X] c\n- [x] d"); - assert_eq!( - items, - [ - item("a", false), - item("b", true), - item("c", true), - item("d", true) - ] - ); + assert_eq!(items, [item("a", false), item("b", true), item("c", true), item("d", true)]); } #[test] @@ -319,10 +262,7 @@ mod tests { let items = items_of("-a\n2024 report\n1.5 kg\n[x]done\n(1) first"); let texts: Vec<_> = items.iter().map(|item| item.text.as_str()).collect(); - assert_eq!( - texts, - ["-a", "2024 report", "1.5 kg", "[x]done", "(1) first"] - ); + assert_eq!(texts, ["-a", "2024 report", "1.5 kg", "[x]done", "(1) first"]); assert!(items.iter().all(|item| !item.done)); } diff --git a/crates/engine/src/notes/drawing.rs b/crates/engine/src/notes/drawing.rs index 4935ffbc3..fee21e442 100644 --- a/crates/engine/src/notes/drawing.rs +++ b/crates/engine/src/notes/drawing.rs @@ -67,9 +67,7 @@ fn png(field: &'static str, uri: &str) -> Result, ValidationError> { if (payload.len() / 4 * 3).saturating_sub(padding) > PICTURE_MAX_BYTES { return Err(ValidationError::new(field, "too large")); } - let bytes = BASE64 - .decode(payload) - .map_err(|_| ValidationError::new(field, "not base64"))?; + let bytes = BASE64.decode(payload).map_err(|_| ValidationError::new(field, "not base64"))?; if !bytes.starts_with(SIGNATURE) { return Err(ValidationError::new(field, "not a PNG")); } @@ -132,10 +130,7 @@ mod tests { } fn pictures(thumbnail: &str, picture: &str) -> DrawingPictures { - DrawingPictures { - thumbnail: thumbnail.into(), - picture: picture.into(), - } + DrawingPictures { thumbnail: thumbnail.into(), picture: picture.into() } } fn refused_field(pictures: &DrawingPictures) -> &'static str { @@ -143,10 +138,7 @@ mod tests { } fn reference(id: &str, title: &str) -> DrawingRef { - DrawingRef { - id: id.into(), - title: title.into(), - } + DrawingRef { id: id.into(), title: title.into() } } #[test] @@ -156,13 +148,7 @@ mod tests { let decoded = pictures(&uri_of(&small), &uri_of(&large)).decoded(); - assert_eq!( - decoded, - Ok(Some(Pictures { - thumbnail: small, - picture: large - })) - ); + assert_eq!(decoded, Ok(Some(Pictures { thumbnail: small, picture: large }))); } #[test] @@ -189,26 +175,14 @@ mod tests { "data:image/png;base64,***".to_string(), uri_of(b"GIF89a, not a PNG"), ] { - assert_eq!( - refused_field(&pictures(&bad, &good)), - "pictures.thumbnail", - "{bad}" - ); - assert_eq!( - refused_field(&pictures(&good, &bad)), - "pictures.picture", - "{bad}" - ); + assert_eq!(refused_field(&pictures(&bad, &good)), "pictures.thumbnail", "{bad}"); + assert_eq!(refused_field(&pictures(&good, &bad)), "pictures.picture", "{bad}"); } } #[test] fn a_picture_up_to_the_limit_is_kept() { - for size in [ - PICTURE_MAX_BYTES - 2, - PICTURE_MAX_BYTES - 1, - PICTURE_MAX_BYTES, - ] { + for size in [PICTURE_MAX_BYTES - 2, PICTURE_MAX_BYTES - 1, PICTURE_MAX_BYTES] { let largest = png_of(size); let decoded = pictures(&uri_of(&png_of(16)), &uri_of(&largest)).decoded(); @@ -223,10 +197,7 @@ mod tests { let refused = pictures(&uri_of(&png_of(16)), &past).decoded().unwrap_err(); - assert_eq!( - refused, - ValidationError::new("pictures.picture", "too large") - ); + assert_eq!(refused, ValidationError::new("pictures.picture", "too large")); } #[test] @@ -235,10 +206,7 @@ mod tests { let refused = pictures(&past, &uri_of(&png_of(16))).decoded().unwrap_err(); - assert_eq!( - refused, - ValidationError::new("pictures.thumbnail", "too large") - ); + assert_eq!(refused, ValidationError::new("pictures.thumbnail", "too large")); } #[test] diff --git a/crates/engine/src/notes/duplicate.rs b/crates/engine/src/notes/duplicate.rs index f0ec6463c..669b5bb78 100644 --- a/crates/engine/src/notes/duplicate.rs +++ b/crates/engine/src/notes/duplicate.rs @@ -30,11 +30,7 @@ pub(crate) fn duplicate( continue; } - let twin = Attachment { - id: Uuid::new_v4().to_string(), - note_id: copy.id.clone(), - ..attachment - }; + let twin = Attachment { id: Uuid::new_v4().to_string(), note_id: copy.id.clone(), ..attachment }; std::fs::copy(&source, directory.join(twin.stored_name())).context(twin.stored_name())?; carried.push(twin); } @@ -70,12 +66,8 @@ mod tests { /// A pinned note filed with a field value, and a library that writes its files to disk. fn shelf(kind: NoteKind) -> Shelf { let scratch = tempfile::tempdir().unwrap(); - let mut library = open_in_memory() - .unwrap() - .with_directory(scratch.path().to_path_buf()); - let space_id = crate::spaces::store::create(&mut library, "Work") - .unwrap() - .id; + let mut library = open_in_memory().unwrap().with_directory(scratch.path().to_path_buf()); + let space_id = crate::spaces::store::create(&mut library, "Work").unwrap().id; let original = Note { space_id, kind, @@ -85,11 +77,7 @@ mod tests { ..note() }; store::insert_imported(&mut library, &original).unwrap(); - Shelf { - _scratch: scratch, - library, - original, - } + Shelf { _scratch: scratch, library, original } } fn attach(shelf: &mut Shelf, id: &str, with_file: bool) -> Attachment { @@ -134,10 +122,7 @@ mod tests { ..shelf.original.clone() } ); - assert_eq!( - store::get(&mut shelf.library, "n-1").unwrap(), - shelf.original - ); + assert_eq!(store::get(&mut shelf.library, "n-1").unwrap(), shelf.original); } #[test] @@ -152,16 +137,8 @@ mod tests { assert_ne!(carried[0].id, "a-1"); assert_eq!(carried[0].file_name, "a-1.txt"); let directory = attachments::files::directory(&shelf.library); - assert_eq!( - std::fs::read(directory.join(carried[0].stored_name())).unwrap(), - b"a-1" - ); - assert_eq!( - attachments::store::list(&mut shelf.library, "n-1") - .unwrap() - .len(), - 1 - ); + assert_eq!(std::fs::read(directory.join(carried[0].stored_name())).unwrap(), b"a-1"); + assert_eq!(attachments::store::list(&mut shelf.library, "n-1").unwrap().len(), 1); } /// As an export leaves it: the original has no bytes to give either. @@ -181,10 +158,7 @@ mod tests { #[test] fn a_copy_of_a_drawing_carries_its_pictures() { let mut shelf = shelf(NoteKind::Drawing); - let taken = Pictures { - thumbnail: b"small".to_vec(), - picture: b"large".to_vec(), - }; + let taken = Pictures { thumbnail: b"small".to_vec(), picture: b"large".to_vec() }; let (db, vault) = shelf.library.split(); pictures::save(db, vault, "n-1", &taken).unwrap(); @@ -210,10 +184,7 @@ mod tests { #[test] fn a_copy_of_a_todo_list_keeps_its_items() { let mut shelf = shelf(NoteKind::Checklist); - let items = vec![crate::notes::checklist::ChecklistItem { - text: "Publish".into(), - done: true, - }]; + let items = vec![crate::notes::checklist::ChecklistItem { text: "Publish".into(), done: true }]; let patch = crate::notes::model::NotePatch { items: Some(items.clone()), ..crate::notes::model::NotePatch::default() @@ -222,9 +193,6 @@ mod tests { let copy = duplicate(&mut shelf.library, "n-1", "Copy".into(), later()).unwrap(); - assert_eq!( - store::get(&mut shelf.library, ©.id).unwrap().items, - items - ); + assert_eq!(store::get(&mut shelf.library, ©.id).unwrap().items, items); } } diff --git a/crates/engine/src/notes/kind.rs b/crates/engine/src/notes/kind.rs index 39d0bc27e..0706a00c6 100644 --- a/crates/engine/src/notes/kind.rs +++ b/crates/engine/src/notes/kind.rs @@ -45,9 +45,6 @@ mod tests { fn each_kind_keeps_its_stored_spelling_in_the_rail_s_order() { let spellings = NoteKind::ALL.map(NoteKind::as_str); - assert_eq!( - spellings, - ["snippet", "note", "checklist", "calc", "drawing"] - ); + assert_eq!(spellings, ["snippet", "note", "checklist", "calc", "drawing"]); } } diff --git a/crates/engine/src/notes/language.rs b/crates/engine/src/notes/language.rs index 9b4e76819..629436e58 100644 --- a/crates/engine/src/notes/language.rs +++ b/crates/engine/src/notes/language.rs @@ -156,19 +156,13 @@ closed_enum! { /// The front end's choice if it made one, `txt` meaning it made none. pub fn for_draft(draft: &NoteDraft) -> Language { - if draft.language == Language::default() { - from_content(&draft.content) - } else { - draft.language - } + if draft.language == Language::default() { from_content(&draft.content) } else { draft.language } } /// A snippet's first content, when nothing was chosen: creation sees no content if the title /// came first, the paste after. The refusals keep detection from becoming a correction. pub fn after_patch(before: &Note, patch: &NotePatch) -> Option { - if patch.language.is_some() - || before.language != Language::default() - || !before.content.trim().is_empty() + if patch.language.is_some() || before.language != Language::default() || !before.content.trim().is_empty() { return None; } @@ -202,11 +196,7 @@ struct Sample<'a> { impl<'a> Sample<'a> { fn of(content: &'a str) -> Self { let trimmed = content.trim(); - Self { - trimmed, - lower: trimmed.to_lowercase(), - lines: trimmed.lines().map(str::trim).collect(), - } + Self { trimmed, lower: trimmed.to_lowercase(), lines: trimmed.lines().map(str::trim).collect() } } fn has(&self, needle: &str) -> bool { @@ -366,10 +356,7 @@ fn score_json(sample: &Sample<'_>) -> u32 { let wrapped = (content.starts_with('{') && content.ends_with('}')) || (content.starts_with('[') && content.ends_with(']')); - worth( - SIGNATURE, - wrapped && (content.contains('"') || content.starts_with('[')), - ) + worth(SIGNATURE, wrapped && (content.contains('"') || content.starts_with('['))) } /// A signature, which keeps it ahead of the markup score its `<` also earns. @@ -388,9 +375,7 @@ fn score_xml(sample: &Sample<'_>) -> u32 { /// Its tags are a signature: they must outweigh the markup shape XML earns on the same text. fn score_html(sample: &Sample<'_>) -> u32 { - const TAGS: [&str; 8] = [ - "", "", ") -> u32 { ]; worth(STRONG, starts_with_any(&sample.lower, &STATEMENTS)) - + worth( - WEAK, - sample.lower.contains(" from ") || sample.lower.contains(" where "), - ) + + worth(WEAK, sample.lower.contains(" from ") || sample.lower.contains(" where ")) } /// An operation or a fragment is a signature; a schema's `type User {` is TypeScript's shape @@ -424,8 +406,7 @@ fn score_graphql(sample: &Sample<'_>) -> u32 { let operation = sample.has("{") && sample.any_line(|line| { ["query", "mutation", "subscription"].iter().any(|keyword| { - line.strip_prefix(keyword) - .is_some_and(|rest| rest.starts_with([' ', '{', '('])) + line.strip_prefix(keyword).is_some_and(|rest| rest.starts_with([' ', '{', '('])) }) }); let fragment = sample.has("... on ") @@ -437,9 +418,7 @@ fn score_graphql(sample: &Sample<'_>) -> u32 { else { return false; }; - name.ends_with('{') - && !name.contains('=') - && name.chars().next().is_some_and(char::is_uppercase) + name.ends_with('{') && !name.contains('=') && name.chars().next().is_some_and(char::is_uppercase) }); worth(SIGNATURE, operation || fragment) @@ -449,10 +428,7 @@ fn score_graphql(sample: &Sample<'_>) -> u32 { /// A section and an assignment: `[…]` alone could be an array on its own line. fn score_toml(sample: &Sample<'_>) -> u32 { - worth( - SIGNATURE, - sample.any_line(is_toml_section) && sample.any_line(is_assignment), - ) + worth(SIGNATURE, sample.any_line(is_toml_section) && sample.any_line(is_assignment)) } fn is_toml_section(line: &str) -> bool { @@ -478,28 +454,16 @@ fn is_identifier_char(c: char) -> bool { /// `class` needs its trailing colon: without it, this is TypeScript's. fn score_python(sample: &Sample<'_>) -> u32 { worth(SIGNATURE, sample.has("__name__")) - + worth( - STRONG, - sample.line_starts_with_any(&["def ", "async def ", "elif "]), - ) - + worth( - STRONG, - sample.any_line(|line| line.starts_with("class ") && line.ends_with(':')), - ) - + worth( - STRONG, - sample.any_line(|line| line.starts_with("from ") && line.contains(" import ")), - ) + + worth(STRONG, sample.line_starts_with_any(&["def ", "async def ", "elif "])) + + worth(STRONG, sample.any_line(|line| line.starts_with("class ") && line.ends_with(':'))) + + worth(STRONG, sample.any_line(|line| line.starts_with("from ") && line.contains(" import "))) + worth(WEAK, sample.has("self.")) } /// `fmt.Print` and `package main` are Go's alone; `import (` is its grouped form. fn score_go(sample: &Sample<'_>) -> u32 { worth(SIGNATURE, sample.has("fmt.Print")) - + worth( - STRONG, - sample.line_starts_with_any(&["func ", "package main", "import ("]), - ) + + worth(STRONG, sample.line_starts_with_any(&["func ", "package main", "import ("])) + worth(WEAK, sample.has(":=") || sample.has("err != nil")) } @@ -514,10 +478,7 @@ fn score_rust(sample: &Sample<'_>) -> u32 { starts_with_any(line, &["fn ", "async fn ", "impl "]) }), ) - + worth( - STRONG, - sample.any_line(|line| line.starts_with("use ") && line.contains("::")), - ) + + worth(STRONG, sample.any_line(|line| line.starts_with("use ") && line.contains("::"))) + worth( WEAK, sample.any_line(|line| { @@ -525,37 +486,24 @@ fn score_rust(sample: &Sample<'_>) -> u32 { starts_with_any(line, &["struct ", "trait ", "enum "]) }), ) - + worth( - WEAK, - sample.has("&str") || sample.has("Vec<") || sample.has("Option<"), - ) + + worth(WEAK, sample.has("&str") || sample.has("Vec<") || sample.has("Option<")) } /// `public class` is left to neither this nor C#: both write it. fn score_java(sample: &Sample<'_>) -> u32 { - worth( - SIGNATURE, - sample.has("System.out.print") || sample.has("public static void main"), - ) + worth( - STRONG, - sample.any_line(|line| line.starts_with("import java")), - ) + worth(SIGNATURE, sample.has("System.out.print") || sample.has("public static void main")) + + worth(STRONG, sample.any_line(|line| line.starts_with("import java"))) } fn score_csharp(sample: &Sample<'_>) -> u32 { worth(SIGNATURE, sample.has("Console.Write")) - + worth( - STRONG, - sample.line_starts_with_any(&["using System", "namespace "]), - ) + + worth(STRONG, sample.line_starts_with_any(&["using System", "namespace "])) } /// `#include` is the one marker nothing else here writes. fn score_c(sample: &Sample<'_>) -> u32 { - worth( - SIGNATURE, - sample.any_line(|line| line.starts_with("#include")), - ) + worth(STRONG, sample.has("int main(") && sample.has("printf(")) + worth(SIGNATURE, sample.any_line(|line| line.starts_with("#include"))) + + worth(STRONG, sample.has("int main(") && sample.has("printf(")) } /// Its own markers only, never JavaScript's: inheriting them would tie the two on every file. @@ -576,20 +524,10 @@ fn score_typescript(sample: &Sample<'_>) -> u32 { /// `=>` is the greediest marker in this file — C++, Kotlin, Swift, Scala, Dart and anything /// with a lambda write it — so it is worth the least. fn score_javascript(sample: &Sample<'_>) -> u32 { - const KEYWORDS: [&str; 7] = [ - "function ", - "const ", - "let ", - "var ", - "export ", - "import ", - "class ", - ]; + const KEYWORDS: [&str; 7] = ["function ", "const ", "let ", "var ", "export ", "import ", "class "]; - worth( - SIGNATURE, - sample.has("console.log") || sample.has("require("), - ) + worth(WEAK, sample.has("=>")) + worth(SIGNATURE, sample.has("console.log") || sample.has("require(")) + + worth(WEAK, sample.has("=>")) + worth(WEAK, sample.line_starts_with_any(&KEYWORDS)) } @@ -607,9 +545,10 @@ fn score_css(sample: &Sample<'_>) -> u32 { }); let has_selector = sample.any_line(|line| { line.ends_with('{') - && line.chars().next().is_some_and(|c| { - c.is_ascii_alphabetic() || matches!(c, '.' | '#' | '@' | ':' | '*') - }) + && line + .chars() + .next() + .is_some_and(|c| c.is_ascii_alphabetic() || matches!(c, '.' | '#' | '@' | ':' | '*')) }); let stylesheet_only = sample.has("--") || ["px;", "rem;", "%;", "px ", "em;", "vh;", "vw;", "fr;"] @@ -622,14 +561,7 @@ fn score_css(sample: &Sample<'_>) -> u32 { /// Its own markers only, never CSS's, which it earns as well: a stylesheet with no variable, /// mixin or nesting is CSS, whatever file it came from. fn score_scss(sample: &Sample<'_>) -> u32 { - const AT_RULES: [&str; 6] = [ - "@mixin ", - "@include ", - "@use ", - "@forward ", - "@extend ", - "@each ", - ]; + const AT_RULES: [&str; 6] = ["@mixin ", "@include ", "@use ", "@forward ", "@extend ", "@each "]; let variable = sample.any_line(|line| { line.strip_prefix('$').is_some_and(|rest| { @@ -642,10 +574,7 @@ fn score_scss(sample: &Sample<'_>) -> u32 { // tie with CSS's own score would answer `txt`. let nested = sample.line_starts_with_any(&["&:", "&.", "&-", "& "]); - worth( - SIGNATURE, - variable || nested || sample.line_starts_with_any(&AT_RULES), - ) + worth(SIGNATURE, variable || nested || sample.line_starts_with_any(&AT_RULES)) } fn score_yaml(sample: &Sample<'_>) -> u32 { @@ -666,9 +595,7 @@ fn is_mapping(line: &str) -> bool { return false; }; - !key.is_empty() - && key.chars().all(is_identifier_char) - && (value.is_empty() || value.starts_with(' ')) + !key.is_empty() && key.chars().all(is_identifier_char) && (value.is_empty() || value.starts_with(' ')) } fn score_markdown(sample: &Sample<'_>) -> u32 { @@ -681,15 +608,11 @@ fn score_markdown(sample: &Sample<'_>) -> u32 { /// Deliberately thin: a wide list would catch prose. fn score_shell(sample: &Sample<'_>) -> u32 { - const COMMANDS: [&str; 10] = [ - "echo ", "cd ", "ls ", "cat ", "grep ", "sudo ", "npm ", "git ", "docker ", "curl ", - ]; + const COMMANDS: [&str; 10] = + ["echo ", "cd ", "ls ", "cat ", "grep ", "sudo ", "npm ", "git ", "docker ", "curl "]; worth(STRONG, sample.line_starts_with_any(&COMMANDS)) - + worth( - WEAK, - sample.any_line(|line| line.starts_with('$') || line.starts_with("./")), - ) + + worth(WEAK, sample.any_line(|line| line.starts_with('$') || line.starts_with("./"))) + worth(WEAK, sample.has(" | ") || sample.has(" && ")) } @@ -707,58 +630,40 @@ fn score_powershell(sample: &Sample<'_>) -> u32 { ]; worth(STRONG, CMDLETS.iter().any(|cmdlet| sample.has(cmdlet))) - + worth( - WEAK, - sample.any_line(|line| line.starts_with('$') && line.contains(" = ")), - ) + + worth(WEAK, sample.any_line(|line| line.starts_with('$') && line.contains(" = "))) + worth(WEAK, sample.has("@{")) } /// `fun` and `val` begin a line in Kotlin alone: Swift writes `func`, Scala is not offered. fn score_kotlin(sample: &Sample<'_>) -> u32 { worth(SIGNATURE, sample.has("fun main(")) - + worth( - STRONG, - sample.line_starts_with_any(&["fun ", "val ", "data class ", "object "]), - ) + + worth(STRONG, sample.line_starts_with_any(&["fun ", "val ", "data class ", "object "])) + worth(WEAK, sample.has("?.") && sample.has("val ")) } /// A line that is only `end` is Ruby's or Elixir's: worth little, and the same to both. fn score_ruby(sample: &Sample<'_>) -> u32 { - worth( - SIGNATURE, - sample.line_starts_with_any(&["require '", "require \""]), - ) + worth( - STRONG, - sample.line_starts_with_any(&["puts ", "attr_accessor "]), - ) + worth(STRONG, sample.has(" do |")) + worth(SIGNATURE, sample.line_starts_with_any(&["require '", "require \""])) + + worth(STRONG, sample.line_starts_with_any(&["puts ", "attr_accessor "])) + + worth(STRONG, sample.has(" do |")) + worth(WEAK, sample.any_line(|line| line == "end")) } fn score_swift(sample: &Sample<'_>) -> u32 { - worth( - SIGNATURE, - sample.line_starts_with_any(&["import Foundation", "import SwiftUI", "import UIKit"]), - ) + worth(STRONG, sample.has("guard let ") || sample.has("if let ")) + worth(SIGNATURE, sample.line_starts_with_any(&["import Foundation", "import SwiftUI", "import UIKit"])) + + worth(STRONG, sample.has("guard let ") || sample.has("if let ")) + worth(WEAK, sample.has("func ") && sample.has(" -> ")) } fn score_dart(sample: &Sample<'_>) -> u32 { - worth( - SIGNATURE, - sample.line_starts_with_any(&["import 'package:", "import \"package:"]), - ) + worth( - STRONG, - sample.line_starts_with_any(&["Future main(", "void main() {"]), - ) + worth(WEAK, sample.line_starts_with_any(&["final "])) + worth(SIGNATURE, sample.line_starts_with_any(&["import 'package:", "import \"package:"])) + + worth(STRONG, sample.line_starts_with_any(&["Future main(", "void main() {"])) + + worth(WEAK, sample.line_starts_with_any(&["final "])) } fn score_elixir(sample: &Sample<'_>) -> u32 { - worth( - SIGNATURE, - sample.line_starts_with_any(&["defmodule "]) || sample.has("|>"), - ) + worth(STRONG, sample.has("IO.puts") || sample.has("IO.inspect")) + worth(SIGNATURE, sample.line_starts_with_any(&["defmodule "]) || sample.has("|>")) + + worth(STRONG, sample.has("IO.puts") || sample.has("IO.inspect")) + worth(WEAK, sample.any_line(|line| line == "end")) } @@ -780,9 +685,7 @@ fn from_shebang(first_line: &str) -> Language { let mut words = first_line.trim_start_matches("#!").split_whitespace(); let program = words.next().unwrap_or_default(); let program = if program.ends_with("/env") { - words - .find(|word| !word.starts_with('-')) - .unwrap_or_default() + words.find(|word| !word.starts_with('-')).unwrap_or_default() } else { program }; @@ -830,23 +733,14 @@ fn score_cpp(sample: &Sample<'_>) -> u32 { signed( header || MARKERS.iter().any(|marker| sample.has(marker)), worth(STRONG, header) - + worth( - STRONG, - sample.line_starts_with_any(&["public:", "private:", "protected:"]), - ), + + worth(STRONG, sample.line_starts_with_any(&["public:", "private:", "protected:"])), ) } /// Markup in a script, with what React alone writes in it. fn jsx_markup(sample: &Sample<'_>) -> bool { - const ATTRIBUTES: [&str; 6] = [ - "className=", - "onClick={", - "onChange={", - "onSubmit={", - "useState(", - "useEffect(", - ]; + const ATTRIBUTES: [&str; 6] = + ["className=", "onClick={", "onChange={", "onSubmit={", "useState(", "useEffect("]; (sample.has("/>") || sample.has(") -> bool { /// The markup is worth what HTML's tags are, on top: a component outscores the page. fn score_jsx(sample: &Sample<'_>) -> u32 { - signed( - jsx_markup(sample), - STRONG + worth(STRONG, script_keyword(sample)), - ) + signed(jsx_markup(sample), STRONG + worth(STRONG, script_keyword(sample))) } /// JSX plus TypeScript's own score, so a typed component outscores both, and nothing without /// a type. fn score_tsx(sample: &Sample<'_>) -> u32 { let typed = score_typescript(sample); - signed( - jsx_markup(sample) && typed > 0, - STRONG + typed + worth(STRONG, script_keyword(sample)), - ) + signed(jsx_markup(sample) && typed > 0, STRONG + typed + worth(STRONG, script_keyword(sample))) } fn score_vue(sample: &Sample<'_>) -> u32 { - const DIRECTIVES: [&str; 7] = [ - "v-if=", - "v-for=", - "v-model=", - "v-bind:", - "v-on:", - "v-else", - "