From a946ba81f7a6089713337644053b00b825824a98 Mon Sep 17 00:00:00 2001 From: Elvis Claros Castro Date: Sat, 26 Sep 2026 19:00:45 -0300 Subject: drae: the RAE Spanish dictionary in the terminal --- .gitignore | 1 + Cargo.lock | 1054 ++++++++++++++++++++++++++++++++++++++++++ Cargo.toml | 33 ++ LICENSE | 21 + README.es.md | 129 ++++++ README.md | 131 ++++++ src/cache.rs | 244 ++++++++++ src/cli.rs | 141 ++++++ src/client.rs | 85 ++++ src/commands.rs | 311 +++++++++++++ src/config.rs | 134 ++++++ src/dle.rs | 309 +++++++++++++ src/html.rs | 235 ++++++++++ src/main.rs | 96 ++++ src/model.rs | 150 ++++++ src/output.rs | 404 ++++++++++++++++ src/raeapi.rs | 441 ++++++++++++++++++ src/suggest.rs | 221 +++++++++ src/wiktionary.rs | 270 +++++++++++ tests/cli.rs | 62 +++ tests/fixtures/dle-casa.html | 24 + 21 files changed, 4496 insertions(+) create mode 100644 .gitignore create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 LICENSE create mode 100644 README.es.md create mode 100644 README.md create mode 100644 src/cache.rs create mode 100644 src/cli.rs create mode 100644 src/client.rs create mode 100644 src/commands.rs create mode 100644 src/config.rs create mode 100644 src/dle.rs create mode 100644 src/html.rs create mode 100644 src/main.rs create mode 100644 src/model.rs create mode 100644 src/output.rs create mode 100644 src/raeapi.rs create mode 100644 src/suggest.rs create mode 100644 src/wiktionary.rs create mode 100644 tests/cli.rs create mode 100644 tests/fixtures/dle-casa.html diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/target diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..8705b4f --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,1054 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "assert_cmd" +version = "2.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2aa3a22042e45de04255c7bf3626e239f450200fd0493c1e382263544b20aea6" +dependencies = [ + "anstyle", + "bstr", + "libc", + "predicates", + "predicates-core", + "predicates-tree", + "wait-timeout", +] + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bitflags" +version = "2.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da" + +[[package]] +name = "bstr" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6bb31b46c14244e20ee9984b11bf5c992b91fb6939fea616e3512c8baecdbe5f" +dependencies = [ + "memchr", + "regex-automata", + "serde_core", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cc" +version = "1.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "005ec2760ca554fae18df7a11195552ec576cd665632a881bc011d5bb2fd4d80" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "clap" +version = "4.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "473c7e07f409a8d772161724aa8db6a765a2532a70f9667eeb7b49d3d02fbdca" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b48fea5a88e9ae728a2dcbedbfc0e730f7d60da42e1cb049a83c9fb8b789889" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d012d2b9d65aca7f18f4d9878a045bc17899bba951561ba5ec3c2ba1eed9a061" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "clap_lex" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "crc32fast" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8498c871161e1742aaa9d52551b2d6ebdd4c3d45a3be423e3728f33b955be550" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "difflib" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6184e33543162437515c2e2b48714794e37845ec9851711914eec9d308f6ebe8" + +[[package]] +name = "drae-cli" +version = "0.1.0" +dependencies = [ + "anyhow", + "assert_cmd", + "clap", + "predicates", + "rusqlite", + "serde", + "serde_json", + "terminal_size", + "toml", + "ureq", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" + +[[package]] +name = "find-msvc-tools" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e0f1c7c3a72c66fd80abe965175f7523475c0489a87d3ff9d6e8c87d87a9d2d" + +[[package]] +name = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "crc32fast", + "miniz_oxide", + "zlib-rs", +] + +[[package]] +name = "float-cmp" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b09cf3155332e944990140d967ff5eceb70df778b34f77d8075db46e4704e6d8" +dependencies = [ + "num-traits", +] + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hashlink" +version = "0.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a596f1b20ed2cc5ecac41a164aaebc7258057060f06c0cf7a2ba3991ee7990fb" +dependencies = [ + "hashbrown 0.17.1", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.105" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce57d20d1ea864ce2ac172ab472d409214f4fd359f0b2a2775abdf522e2af99e" +dependencies = [ + "cfg-if", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "libsqlite3-sys" +version = "0.38.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1d20bef17f513b9b3004532233187769cd072d790971f4e4da0e346eb6401e8" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "normalize-line-endings" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61807f77802ff30975e01f4f071c8ba10c022052f98b3294119f3e615d13e5be" + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "predicates" +version = "3.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ada8f2932f28a27ee7b70dd6c1c39ea0675c55a36879ab92f3a715eaa1e63cfe" +dependencies = [ + "anstyle", + "difflib", + "float-cmp", + "normalize-line-endings", + "predicates-core", + "regex", +] + +[[package]] +name = "predicates-core" +version = "1.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cad38746f3166b4031b1a0d39ad9f954dd291e7854fcc0eed52ee41a0b50d144" + +[[package]] +name = "predicates-tree" +version = "1.0.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0de1b847b39c8131db0467e9df1ff60e6d0562ab8e9a16e568ad0fdb372e2f2" +dependencies = [ + "predicates-core", + "termtree", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rsqlite-vfs" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c51c9ae4df8a7fba42103df5c621fa3c37eccf3a3c650879e90fc48b11cc192c" +dependencies = [ + "hashbrown 0.16.1", + "thiserror", +] + +[[package]] +name = "rusqlite" +version = "0.40.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f2a97da3e3873c73cb2a2e71b35c40ff95e0b1eefa8d72d8499a6928c3b5b3" +dependencies = [ + "bitflags", + "fallible-iterator", + "fallible-streaming-iterator", + "hashlink", + "libsqlite3-sys", + "smallvec", + "sqlite-wasm-rs", +] + +[[package]] +name = "rustix" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6725596c3f2c3a0aef021139e145d4eafe314a6623e4680ca83852b2c67ab2ba" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_spanned" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" +dependencies = [ + "serde", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "smallvec" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9be42f50aa861c555654aa3a37f52f4b1074bacf4e48fe0ef7fa584e80f1f0f" + +[[package]] +name = "sqlite-wasm-rs" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc3efc0da82635d7e1ced0053bbbfa8c7ab9645d0bf36ceb4f7127bb85315d75" +dependencies = [ + "cc", + "js-sys", + "rsqlite-vfs", + "wasm-bindgen", +] + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "3.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12df2e0110f65b775f769bb17ef989067a1d931b2eb822bd4346631eeada89f9" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "terminal_size" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "230a1b821ccbd75b185820a1f1ff7b14d21da1e442e22c0863ea5f08771a8874" +dependencies = [ + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "termtree" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f50febec83f5ee1df3015341d8bd429f2d1cc62bcba7ea2076759d315084683" + +[[package]] +name = "thiserror" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "toml" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" +dependencies = [ + "serde", + "serde_spanned", + "toml_datetime", + "toml_edit", +] + +[[package]] +name = "toml_datetime" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_edit" +version = "0.22.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" +dependencies = [ + "indexmap", + "serde", + "serde_spanned", + "toml_datetime", + "toml_write", + "winnow", +] + +[[package]] +name = "toml_write" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "ureq" +version = "3.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af5546be8f5378d5414f83733f5c9a2526f4645829edbc1c41790aeef1b38e8b" +dependencies = [ + "base64", + "flate2", + "log", + "percent-encoding", + "rustls", + "rustls-pki-types", + "ureq-proto", + "utf8-zero", + "webpki-roots", +] + +[[package]] +name = "ureq-proto" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fabc3e92916c89c95b20eef7b06b00b066bc217ef9ea3a4ac9bf1a7e35261e10" +dependencies = [ + "base64", + "http", + "httparse", + "log", +] + +[[package]] +name = "utf8-zero" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "wait-timeout" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11" +dependencies = [ + "libc", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aecb87a33d3b0c5e3b7aa46336eaf486cffafbd281b195e4c8b80d50df2351bf" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a690d511e3c1a8b3a55e33511e3c2c00c78415cd23650f32b808627f5696b9ed" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "411e4887f0071ef2d2164a9d5fdf2d20efbef78fccd3a78b0c10a1dc5295e48a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81941cd78d0c92026c33e5e01312845a4cb1e9af3407f9134b100dd03144103e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "webpki-roots" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" +dependencies = [ + "memchr", +] + +[[package]] +name = "zeroize" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" + +[[package]] +name = "zlib-rs" +version = "0.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34b31d188d9d685a4f9c7b46d6e36631b07058d2cfe190267adce54dc230bf12" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..c8cb4ff --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,33 @@ +[package] +name = "drae-cli" +version = "0.1.0" +edition = "2021" +description = "The RAE Spanish dictionary in the terminal: definitions, etymology, synonyms and conjugation" +repository = "https://git.all.ar/pub/drae-cli" +license = "MIT" +readme = "README.md" +keywords = ["diccionario", "espanol", "rae", "dictionary", "cli"] +categories = ["command-line-utilities"] +default-run = "drae" + +[[bin]] +name = "drae" +path = "src/main.rs" + +[dependencies] +anyhow = "1" +clap = { version = "4", features = ["derive"] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +toml = "0.8" +ureq = "3" +rusqlite = { version = "0.40", features = ["bundled"] } +terminal_size = "0.4" + +[dev-dependencies] +assert_cmd = "2" +predicates = "3" + +[profile.release] +strip = true +lto = true diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..acdf183 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Elvis Claros Castro + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.es.md b/README.es.md new file mode 100644 index 0000000..d7f44b3 --- /dev/null +++ b/README.es.md @@ -0,0 +1,129 @@ +# drae + +[English](README.md) + +Diccionario de la lengua española en la terminal. + +```console +$ drae casa +casa +Del lat. casa 'choza'. + +1. f. Edificio para habitar. + Una casa de ocho plantas. + Sin.: vivienda, inmueble, domicilio, hogar, residencia, piso, apartamento… + +2. f. Edificio de una o pocas plantas destinado a vivienda unifamiliar, en + oposición a piso. + Quieren vender el piso y comprarse una casa. + Sin.: chalé, chalet +``` + +Lo consultado queda en una caché local, así que la segunda vez responde sin +red y al instante. + +## Instalación + +```sh +git clone https://git.all.ar/pub/drae-cli.git +cd drae-cli +cargo install --path . +``` + +Deja el binario `drae` en `~/.cargo/bin`. + +## Uso + +| Orden | Qué hace | +| --- | --- | +| `drae casa` | Define una palabra | +| `drae definir sin` | Define una palabra que choca con el nombre de una orden | +| `drae sin casa` | Sinónimos y antónimos, acepción por acepción | +| `drae conjugar hablar` | Conjugación completa, con voseo | +| `drae conjugar ser --modo subjuntivo` | Un solo modo verbal | +| `drae dia` | La palabra del día de la RAE | +| `drae azar` | Una palabra al azar | +| `drae buscar edificio` | Busca dentro de las definiciones ya guardadas | +| `drae cache info \| listar \| limpiar` | Gestiona la caché | + +Opciones generales: + +| Opción | Qué hace | +| --- | --- | +| `--json` | Imprime JSON en lugar del texto formateado | +| `-a`, `--abreviaturas` | Despliega las marcas: `f. = nombre femenino` | +| `-A`, `--actualizar` | Ignora la caché y vuelve a descargar | +| `--sin-cache` | No lee ni escribe la caché | +| `--ancho N` | Ancho de salida en columnas | +| `--color auto\|always\|never` | Cuándo colorear | +| `--fuente auto\|dle\|rae-api` | De dónde leer | + +El color se apaga solo cuando la salida va a una tubería o cuando está +definida `NO_COLOR`. + +### Si la palabra no está + +Se buscan las más parecidas en el diccionario de hunspell del sistema, sin +tocar la red, ignorando las tildes: + +```console +$ drae arbol +drae: «arbol» no está en el Diccionario + ¿quiso decir árbol? +``` + +## De dónde salen los datos + +| Qué | Fuente | +| --- | --- | +| Definiciones, etimología, sinónimos | [rae-api.com](https://rae-api.com), que sirve el contenido del *Diccionario de la lengua española* en JSON | +| Conjugación | [Wikcionario en español](https://es.wiktionary.org) (CC BY-SA) | +| Sugerencias | `/usr/share/hunspell/es_*.dic`, local | + +`dle.rae.es` queda como fuente opcional (`--fuente dle`). El sitio responde +con un desafío de Cloudflare a todo cliente que no sea un navegador, así que +casi nunca contesta desde la terminal; el lector de su HTML se mantiene +—verificado contra un fixture— por si en tu red sí pasa. + +La conjugación viene del Wikcionario y no de la RAE por el mismo motivo, con +una ventaja: incluye el voseo, que las tablas de la RAE no traen. + +```console +$ drae conjugar ser --modo subjuntivo +Modo subjuntivo + Presente + que yo sea · que tú seas · que vos seas, seás · que él/ella/ud. sea · + que nosotros seamos · que vosotros seáis · que uds./ellos sean +``` + +rae-api.com admite 10 peticiones por minuto. Con la caché no se nota, pero si +vas a consultar muchas palabras de corrido, tenlo en cuenta. + +## Configuración + +Opcional, en `~/.config/drae/config.toml`. Todo tiene un valor por defecto y +las opciones de la línea de órdenes siempre mandan sobre el archivo. + +```toml +fuente = "auto" # auto | dle | rae-api +timeout = 15 # segundos por petición +ancho = 80 # por defecto, el de la terminal +# cache = "~/.cache/drae/entries.db" +# diccionario = "/usr/share/hunspell/es_AR.dic" +``` + +## Desarrollo + +```sh +cargo test # 70 tests, ninguno toca la red +cargo build --release +``` + +El lector del DLE se prueba contra `tests/fixtures/dle-casa.html`, una página +real recortada, para que siga verificado aunque el camino en vivo esté +bloqueado. + +## Licencia + +MIT. El contenido del diccionario pertenece a la Real Academia Española; las +tablas de conjugación son del Wikcionario, bajo CC BY-SA. diff --git a/README.md b/README.md new file mode 100644 index 0000000..dc9f816 --- /dev/null +++ b/README.md @@ -0,0 +1,131 @@ +# drae + +[Español](README.es.md) + +The Spanish dictionary of the Real Academia Española (RAE) in your terminal: +definitions, etymology, synonyms and antonyms, and full verb conjugation. + +```console +$ drae casa +casa +Del lat. casa 'choza'. + +1. f. Edificio para habitar. + Una casa de ocho plantas. + Sin.: vivienda, inmueble, domicilio, hogar, residencia, piso, apartamento… + +2. f. Edificio de una o pocas plantas destinado a vivienda unifamiliar, en + oposición a piso. + Quieren vender el piso y comprarse una casa. + Sin.: chalé, chalet +``` + +Every lookup is stored in a local cache, so the second time it answers +instantly and offline. + +The tool is meant for Spanish speakers, so its commands, flags and messages +are in Spanish; the code is in English. + +## Install + +```sh +git clone https://git.all.ar/pub/drae-cli.git +cd drae-cli +cargo install --path . +``` + +This puts the `drae` binary in `~/.cargo/bin`. + +## Usage + +| Command | What it does | +| --- | --- | +| `drae casa` | Defines a word | +| `drae definir sin` | Defines a word that clashes with a command name | +| `drae sin casa` | Synonyms and antonyms, sense by sense | +| `drae conjugar hablar` | Full conjugation, including voseo | +| `drae conjugar ser --modo subjuntivo` | A single mood | +| `drae dia` | The RAE word of the day | +| `drae azar` | A random word | +| `drae buscar edificio` | Searches inside the definitions already cached | +| `drae cache info \| listar \| limpiar` | Manages the cache | + +Global options: + +| Option | What it does | +| --- | --- | +| `--json` | Prints JSON instead of formatted text | +| `-a`, `--abreviaturas` | Expands the marks: `f. = nombre femenino` | +| `-A`, `--actualizar` | Ignores the cache and downloads again | +| `--sin-cache` | Neither reads nor writes the cache | +| `--ancho N` | Output width in columns | +| `--color auto\|always\|never` | When to use color | +| `--fuente auto\|dle\|rae-api` | Where to read from | + +Color turns itself off when the output goes to a pipe or when `NO_COLOR` is set. + +### When the word does not exist + +The closest words are looked up in the system hunspell dictionary, offline and +ignoring accents: + +```console +$ drae arbol +drae: «arbol» no está en el Diccionario + ¿quiso decir árbol? +``` + +## Where the data comes from + +| What | Source | +| --- | --- | +| Definitions, etymology, synonyms | [rae-api.com](https://rae-api.com), which serves the content of the *Diccionario de la lengua española* as JSON | +| Conjugation | [Spanish Wiktionary](https://es.wiktionary.org) (CC BY-SA) | +| Suggestions | `/usr/share/hunspell/es_*.dic`, local | + +`dle.rae.es` is an optional source (`--fuente dle`). The site answers every +non-browser client with a Cloudflare challenge, so it almost never responds +from a terminal; its HTML reader is kept, and tested against a fixture, in +case it gets through on your network. + +Conjugation comes from Wiktionary rather than the RAE for the same reason, +with a bonus: it includes voseo («vos hablás»), which the RAE tables leave out. + +```console +$ drae conjugar ser --modo subjuntivo +Modo subjuntivo + Presente + que yo sea · que tú seas · que vos seas, seás · que él/ella/ud. sea · + que nosotros seamos · que vosotros seáis · que uds./ellos sean +``` + +rae-api.com allows 10 requests per minute. The cache hides that, but keep it +in mind if you look up many words in a row. + +## Configuration + +Optional, in `~/.config/drae/config.toml`. Everything has a default and +command-line options always win over the file. + +```toml +fuente = "auto" # auto | dle | rae-api +timeout = 15 # seconds per request +ancho = 80 # defaults to the terminal width +# cache = "~/.cache/drae/entries.db" +# diccionario = "/usr/share/hunspell/es_AR.dic" +``` + +## Development + +```sh +cargo test # 70 tests, none of them touch the network +cargo build --release +``` + +The DLE reader is tested against `tests/fixtures/dle-casa.html`, a real page +trimmed down, so it stays verified even while the live path is blocked. + +## License + +MIT. The dictionary content belongs to the Real Academia Española; the +conjugation tables come from Wiktionary, under CC BY-SA. diff --git a/src/cache.rs b/src/cache.rs new file mode 100644 index 0000000..45d66a4 --- /dev/null +++ b/src/cache.rs @@ -0,0 +1,244 @@ +//! Local SQLite cache: anything looked up once is read back without network. +//! +//! Lives in `~/.cache/drae/entries.db` (or `$XDG_CACHE_HOME`). It stores the +//! already-normalized entry as JSON, so it survives changes to the DLE markup +//! and lets the user search inside definitions already downloaded. + +use std::path::{Path, PathBuf}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use anyhow::{Context, Result}; +use rusqlite::{params, Connection, OptionalExtension}; + +use crate::model::Entry; + +pub struct Cache { + conn: Connection, +} + +impl Cache { + pub fn open(path: &Path) -> Result { + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir) + .with_context(|| format!("no se pudo crear {}", dir.display()))?; + } + let conn = Connection::open(path) + .with_context(|| format!("no se pudo abrir la caché en {}", path.display()))?; + conn.execute_batch( + "PRAGMA journal_mode = WAL; + CREATE TABLE IF NOT EXISTS entries ( + key TEXT PRIMARY KEY, + word TEXT NOT NULL, + json TEXT NOT NULL, + source TEXT NOT NULL, + fetched_at INTEGER NOT NULL + );", + ) + .context("no se pudo preparar la caché")?; + Ok(Cache { conn }) + } + + /// Default path: `$XDG_CACHE_HOME/drae/entries.db`. + pub fn default_path() -> PathBuf { + let base = std::env::var_os("XDG_CACHE_HOME") + .map(PathBuf::from) + .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".cache"))) + .unwrap_or_else(|| PathBuf::from(".cache")); + base.join("drae").join("entries.db") + } + + pub fn get(&self, word: &str) -> Result> { + let json: Option = self + .conn + .query_row( + "SELECT json FROM entries WHERE key = ?1", + params![key(word)], + |r| r.get(0), + ) + .optional()?; + // An entry written by an older version of the model is silently + // ignored and downloaded again. + Ok(json.and_then(|j| serde_json::from_str(&j).ok())) + } + + pub fn put(&self, word: &str, entry: &Entry) -> Result<()> { + self.conn.execute( + "INSERT INTO entries (key, word, json, source, fetched_at) + VALUES (?1, ?2, ?3, ?4, ?5) + ON CONFLICT(key) DO UPDATE SET + json = excluded.json, + source = excluded.source, + fetched_at = excluded.fetched_at", + params![ + key(word), + entry.word, + serde_json::to_string(entry)?, + entry.source, + now(), + ], + )?; + Ok(()) + } + + /// Stored words, most recent first. + pub fn list(&self, limit: usize) -> Result> { + let mut stmt = self.conn.prepare( + "SELECT word, source, fetched_at FROM entries + ORDER BY fetched_at DESC LIMIT ?1", + )?; + let rows = stmt + .query_map(params![limit as i64], |r| { + Ok((r.get(0)?, r.get(1)?, r.get(2)?)) + })? + .collect::>>()?; + Ok(rows) + } + + /// Searches for a text inside the definitions already downloaded. + pub fn search(&self, needle: &str, limit: usize) -> Result> { + let mut stmt = self.conn.prepare( + "SELECT word, json FROM entries + WHERE json LIKE ?1 ESCAPE '\\' + ORDER BY word LIMIT ?2", + )?; + let pattern = format!("%{}%", escape_like(needle)); + let rows = stmt + .query_map(params![pattern, limit as i64], |r| { + Ok((r.get(0)?, r.get(1)?)) + })? + .collect::>>()?; + Ok(rows) + } + + pub fn count(&self) -> Result { + Ok(self + .conn + .query_row("SELECT COUNT(*) FROM entries", [], |r| r.get(0))?) + } + + pub fn clear(&self) -> Result { + let n = self.conn.execute("DELETE FROM entries", [])?; + self.conn.execute_batch("VACUUM;")?; + Ok(n) + } +} + +/// Lookup key: lowercase, so «Casa» and «casa» share an entry. +fn key(word: &str) -> String { + word.trim().to_lowercase() +} + +fn escape_like(s: &str) -> String { + s.replace('\\', "\\\\") + .replace('%', "\\%") + .replace('_', "\\_") +} + +/// Formats a Unix timestamp as `YYYY-MM-DD` without a date library, using +/// Howard Hinnant's civil-from-days algorithm. +pub fn format_date(ts: i64) -> String { + let days = ts.div_euclid(86_400); + let z = days + 719_468; + let era = z.div_euclid(146_097); + let doe = z.rem_euclid(146_097); + let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; + let y = yoe + era * 400; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let m = if mp < 10 { mp + 3 } else { mp - 9 }; + let y = if m <= 2 { y + 1 } else { y }; + format!("{y:04}-{m:02}-{d:02}") +} + +fn now() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs() as i64) + .unwrap_or(0) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::Sense; + + fn entry(word: &str, text: &str) -> Entry { + Entry { + word: word.into(), + etymology: None, + senses: vec![Sense { + text: text.into(), + ..Default::default() + }], + locutions: vec![], + conjugation: None, + source: "dle".into(), + } + } + + fn cache() -> Cache { + Cache::open(Path::new(":memory:")).unwrap() + } + + #[test] + fn stores_and_reads_back_an_entry() { + let c = cache(); + c.put("casa", &entry("casa", "Edificio para habitar.")) + .unwrap(); + let got = c.get("casa").unwrap().expect("should be in the cache"); + assert_eq!(got.word, "casa"); + assert_eq!(c.count().unwrap(), 1); + } + + #[test] + fn lookup_is_case_insensitive() { + let c = cache(); + c.put("Casa", &entry("casa", "Edificio.")).unwrap(); + assert!(c.get("casa").unwrap().is_some()); + assert!(c.get("CASA").unwrap().is_some()); + } + + #[test] + fn writing_the_same_word_twice_replaces_it() { + let c = cache(); + c.put("casa", &entry("casa", "vieja")).unwrap(); + c.put("casa", &entry("casa", "nueva")).unwrap(); + assert_eq!(c.count().unwrap(), 1); + assert_eq!(c.get("casa").unwrap().unwrap().senses[0].text, "nueva"); + } + + #[test] + fn searches_inside_stored_definitions() { + let c = cache(); + c.put("casa", &entry("casa", "Edificio para habitar.")) + .unwrap(); + c.put("perro", &entry("perro", "Mamífero doméstico.")) + .unwrap(); + let hits = c.search("Edificio", 10).unwrap(); + assert_eq!(hits.len(), 1); + assert_eq!(hits[0].0, "casa"); + } + + #[test] + fn like_wildcards_in_the_query_are_literal() { + let c = cache(); + c.put("casa", &entry("casa", "Edificio.")).unwrap(); + // Unescaped, "%" would match everything. + assert!(c.search("%", 10).unwrap().is_empty()); + } + + #[test] + fn formats_a_unix_timestamp_as_a_date() { + assert_eq!(format_date(0), "1970-01-01"); + assert_eq!(format_date(1_757_000_000), "2025-09-04"); + } + + #[test] + fn clear_empties_the_cache() { + let c = cache(); + c.put("casa", &entry("casa", "Edificio.")).unwrap(); + c.clear().unwrap(); + assert_eq!(c.count().unwrap(), 0); + } +} diff --git a/src/cli.rs b/src/cli.rs new file mode 100644 index 0000000..9f23838 --- /dev/null +++ b/src/cli.rs @@ -0,0 +1,141 @@ +//! Command-line definition. +//! +//! The tool is a Spanish dictionary for Spanish speakers, so every command, +//! flag and help text the user sees is in Spanish. Rust names are in English +//! and mapped explicitly (`name = "..."`, `long = "..."`). + +use std::path::PathBuf; + +use clap::{Parser, Subcommand, ValueEnum}; + +#[derive(Parser)] +#[command( + name = "drae", + version, + about = "Diccionario de la lengua española en la terminal", + long_about = "drae — consulta el Diccionario de la lengua española (RAE) sin salir de la terminal.\n\ + Sin orden, define la palabra que se le pase: `drae casa`.\n\ + Lo consultado queda en caché, así que la segunda vez responde sin red.", + args_conflicts_with_subcommands = true +)] +pub struct Cli { + /// La palabra a definir (equivale a `drae definir `) + #[arg(value_name = "PALABRA")] + pub word: Option, + + #[command(subcommand)] + pub cmd: Option, + + /// Archivo de configuración (por defecto ~/.config/drae/config.toml) + #[arg(long, global = true, value_name = "ARCHIVO")] + pub config: Option, + + /// Imprime JSON en lugar del texto formateado + #[arg(long, global = true)] + pub json: bool, + + /// Cuándo colorear la salida + #[arg(long, global = true, value_enum, default_value_t = Color::Auto)] + pub color: Color, + + /// Ancho de salida en columnas (por defecto, el de la terminal) + #[arg(long = "ancho", global = true, value_name = "N")] + pub width: Option, + + /// Despliega el significado de las abreviaturas (f. = nombre femenino) + #[arg(long = "abreviaturas", short = 'a', global = true)] + pub expand_abbr: bool, + + /// Ignora la caché y vuelve a descargar + #[arg(long = "actualizar", short = 'A', global = true)] + pub refresh: bool, + + /// No leer ni escribir la caché + #[arg(long = "sin-cache", global = true)] + pub no_cache: bool, + + /// De dónde leer: auto (rae-api con respaldo), dle o rae-api + #[arg(long = "fuente", global = true, value_enum)] + pub source: Option, +} + +#[derive(Clone, Copy, PartialEq, Eq, ValueEnum)] +pub enum Color { + Auto, + Always, + Never, +} + +#[derive(Clone, Copy, PartialEq, Eq, ValueEnum)] +pub enum Source { + Auto, + Dle, + #[value(name = "rae-api")] + RaeApi, +} + +#[derive(Subcommand)] +pub enum Cmd { + /// Define una palabra. Úsalo cuando la palabra coincida con el nombre de + /// una orden: `drae definir sin` + #[command(name = "definir", alias = "def")] + Define { + #[arg(value_name = "PALABRA")] + word: String, + }, + + /// Sinónimos y antónimos de una palabra + #[command(name = "sinonimos", alias = "sin")] + Synonyms { + #[arg(value_name = "PALABRA")] + word: String, + }, + + /// Conjugación completa de un verbo + #[command(name = "conjugar", alias = "conj")] + Conjugate { + #[arg(value_name = "VERBO")] + verb: String, + /// Solo este modo: indicativo, subjuntivo, imperativo… + #[arg(long = "modo", value_name = "MODO")] + mood: Option, + }, + + /// La palabra del día que publica la RAE + #[command(name = "dia")] + WordOfTheDay, + + /// Una palabra al azar del diccionario + #[command(name = "azar")] + Random, + + /// Busca un texto dentro de las definiciones ya guardadas en caché + #[command(name = "buscar")] + Search { + #[arg(value_name = "TEXTO")] + text: String, + #[arg(long, default_value_t = 20)] + max: usize, + }, + + /// Gestiona la caché local + Cache { + #[command(subcommand)] + action: CacheCmd, + }, +} + +#[derive(Subcommand)] +pub enum CacheCmd { + /// Cuántas entradas hay y dónde viven + Info, + /// Las últimas palabras consultadas + #[command(name = "listar")] + List { + #[arg(long, default_value_t = 30)] + max: usize, + }, + /// Borra todo lo guardado + #[command(name = "limpiar")] + Clear, +} diff --git a/src/client.rs b/src/client.rs new file mode 100644 index 0000000..37205bf --- /dev/null +++ b/src/client.rs @@ -0,0 +1,85 @@ +//! HTTP client. +//! +//! dle.rae.es answers 403 to short or missing user agents, so requests to it +//! identify as a desktop browser. + +use std::time::Duration; + +use anyhow::{Context, Result}; +use ureq::Agent; + +/// Browser user agent, for dle.rae.es, which rejects clients that do not +/// identify as one. +pub const BROWSER_UA: &str = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 \ + (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"; + +/// Honest identification for APIs that want to know who is calling, as the +/// Wikimedia policy asks. +pub const CLIENT_UA: &str = concat!( + "drae-cli/", + env!("CARGO_PKG_VERSION"), + " (terminal dictionary)" +); + +pub struct Http { + agent: Agent, +} + +impl Http { + pub fn new(timeout_secs: u64) -> Self { + let config = Agent::config_builder() + .timeout_global(Some(Duration::from_secs(timeout_secs))) + // A 404 is an answer we want to read, not a network error. + .http_status_as_error(false) + .build(); + Http { + agent: config.new_agent(), + } + } + + /// Returns the status code and the body. + pub fn get(&self, url: &str, user_agent: &str) -> Result<(u16, String)> { + let mut res = self + .agent + .get(url) + .header("User-Agent", user_agent) + .header("Accept-Language", "es-ES,es;q=0.9") + .header("Accept", "text/html,application/json;q=0.9,*/*;q=0.8") + .call() + .with_context(|| format!("no se pudo conectar con {url}"))?; + let status = res.status().as_u16(); + let body = res + .body_mut() + .read_to_string() + .with_context(|| format!("respuesta ilegible de {url}"))?; + Ok((status, body)) + } +} + +/// Encodes a word for a URL path. The RAE needs `%C3%B1` for ñ; other safe +/// characters pass through unchanged. +pub fn percent_encode(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + for b in s.as_bytes() { + match b { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => { + out.push(*b as char) + } + _ => out.push_str(&format!("%{b:02X}")), + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn encodes_spanish_characters() { + assert_eq!(percent_encode("año"), "a%C3%B1o"); + assert_eq!(percent_encode("café"), "caf%C3%A9"); + assert_eq!(percent_encode("perro"), "perro"); + assert_eq!(percent_encode("dar de sí"), "dar%20de%20s%C3%AD"); + } +} diff --git a/src/commands.rs b/src/commands.rs new file mode 100644 index 0000000..d82970e --- /dev/null +++ b/src/commands.rs @@ -0,0 +1,311 @@ +//! The commands, and the path a lookup follows: +//! cache → rae-api.com → dle.rae.es → offline suggestions. + +use anyhow::{bail, Context, Result}; + +use crate::cache::Cache; +use crate::cli::Source; +use crate::client::{percent_encode, Http, BROWSER_UA}; +use crate::config::Config; +use crate::model::Entry; +use crate::output::{self, Style}; +use crate::{dle, raeapi, suggest, wiktionary}; + +const DLE_BASE: &str = "https://dle.rae.es"; + +pub struct Ctx { + pub cfg: Config, + pub http: Http, + pub cache: Option, + pub style: Style, + pub json: bool, + pub expand_abbr: bool, + pub refresh: bool, + pub source: Source, +} + +impl Ctx { + /// Looks a word up. If it does not exist, returns a ready-to-print error + /// with the closest suggestions from the local dictionary. + pub fn lookup(&self, word: &str) -> Result { + let word = word.trim(); + if word.is_empty() { + bail!("hay que indicar una palabra"); + } + + if !self.refresh { + if let Some(c) = &self.cache { + if let Some(hit) = c.get(word)? { + return Ok(hit); + } + } + } + + let entry = self.fetch(word)?; + match entry { + Some(e) => { + if let Some(c) = &self.cache { + // A failed write must not stop the word from being shown. + let _ = c.put(word, &e); + } + Ok(e) + } + None => bail!("{}", self.not_found_message(word)), + } + } + + /// Downloads the entry from the chosen source. `Ok(None)` = no such word. + /// + /// The default order is rae-api first: it serves the DLE content as JSON + /// and accepts automated clients. dle.rae.es is the fallback because it + /// answers with a Cloudflare challenge to anything but a browser, so most + /// of the time it does not respond. + fn fetch(&self, word: &str) -> Result> { + match self.source { + Source::Dle => self.fetch_dle(word), + Source::RaeApi => raeapi::lookup(&self.http, word), + Source::Auto => match raeapi::lookup(&self.http, word) { + Ok(Some(e)) => Ok(Some(e)), + Ok(None) => Ok(None), + // The API failed: try the site, in case this client gets through. + Err(first) => self.fetch_dle(word).map_err(|_| first), + }, + } + } + + fn fetch_dle(&self, word: &str) -> Result> { + let url = format!("{DLE_BASE}/{}", percent_encode(word)); + let (status, body) = self.http.get(&url, BROWSER_UA)?; + if status == 403 { + bail!( + "dle.rae.es rechazó la petición con un desafío de Cloudflare, \ + que solo resuelve un navegador" + ); + } + if status != 200 { + bail!("dle.rae.es respondió {status}"); + } + if dle::is_not_found(&body) { + return Ok(None); + } + match dle::parse(&body) { + Some(e) if !e.senses.is_empty() => Ok(Some(e)), + // A valid page we cannot read: let the caller decide. + _ => bail!("no se pudo interpretar la página del DLE para «{word}»"), + } + } + + fn not_found_message(&self, word: &str) -> String { + let mut msg = format!("«{word}» no está en el Diccionario"); + for s in self.suggestions(word) { + msg.push_str(&format!("\n ¿quiso decir {}?", self.style.cyan(&s))); + } + msg + } + + /// Similar words, from the system hunspell dictionary. + fn suggestions(&self, word: &str) -> Vec { + let path = self + .cfg + .dictionary + .clone() + .or_else(suggest::find_dictionary); + let Some(path) = path else { + return vec![]; + }; + let Ok(words) = suggest::load_words(&path) else { + return vec![]; + }; + suggest::closest(word, &words, 4) + } + + fn print_json(&self, v: &T) -> Result<()> { + println!("{}", serde_json::to_string_pretty(v)?); + Ok(()) + } +} + +pub fn define(ctx: &Ctx, word: &str) -> Result<()> { + let e = ctx.lookup(word)?; + if ctx.json { + return ctx.print_json(&e); + } + print!("{}", output::entry(&e, &ctx.style, ctx.expand_abbr)); + Ok(()) +} + +pub fn synonyms(ctx: &Ctx, word: &str) -> Result<()> { + let e = ctx.lookup(word)?; + if ctx.json { + #[derive(serde::Serialize)] + struct Out<'a> { + word: &'a str, + synonyms: Vec, + antonyms: Vec, + } + return ctx.print_json(&Out { + word: &e.word, + synonyms: e.all_synonyms(), + antonyms: e.all_antonyms(), + }); + } + + if !e.has_synonyms() && !e.has_antonyms() { + println!( + "{}", + ctx.style + .dim(&format!("«{}» no tiene sinónimos registrados", e.word)) + ); + return Ok(()); + } + + println!("{}\n", ctx.style.heading(&e.word)); + // Shown per sense: the synonyms of «casa» are not the same for + // «building» as for «lineage». + for s in &e.senses { + if s.synonyms.is_empty() && s.antonyms.is_empty() { + continue; + } + let num = s.number.clone().unwrap_or_default(); + let head = format!( + "{}. {}", + num, + output::truncate(&s.text, ctx.style.width - 6) + ); + println!("{}", ctx.style.dim(&head)); + if !s.synonyms.is_empty() { + let joined = output::superscript_homographs(&s.synonyms.join(", ")); + let line = format!("{} {joined}", ctx.style.green("Sin.:")); + println!( + "{}", + output::wrap(&line, ctx.style.width, " ", " ") + ); + } + if !s.antonyms.is_empty() { + let joined = output::superscript_homographs(&s.antonyms.join(", ")); + let line = format!("{} {joined}", ctx.style.red("Ant.:")); + println!( + "{}", + output::wrap(&line, ctx.style.width, " ", " ") + ); + } + println!(); + } + Ok(()) +} + +pub fn conjugate(ctx: &Ctx, verb: &str, mood: Option<&str>) -> Result<()> { + let Some(mut c) = wiktionary::conjugation(&ctx.http, verb)? else { + bail!("«{verb}» no tiene tabla de conjugación (¿no es un verbo?)"); + }; + + if let Some(m) = mood { + let needle = suggest::fold(m); + c.groups + .retain(|g| suggest::fold(&g.title).contains(&needle)); + if c.groups.is_empty() { + bail!("no hay ningún modo que se parezca a «{m}»"); + } + } + + if ctx.json { + return ctx.print_json(&c); + } + print!("{}", output::conjugation(&c, &ctx.style)); + Ok(()) +} + +/// The word of the day and the random word come from the rae-api index and +/// are then defined through the normal path. +pub fn featured(ctx: &Ctx, daily: bool) -> Result<()> { + let word = if daily { + raeapi::word_of_the_day(&ctx.http).context("no se pudo obtener la palabra del día")? + } else { + raeapi::random_word(&ctx.http).context("no se pudo obtener una palabra al azar")? + }; + define(ctx, &word) +} + +pub fn search(ctx: &Ctx, text: &str, max: usize) -> Result<()> { + let Some(cache) = &ctx.cache else { + bail!("`buscar` mira dentro de la caché, y está desactivada con --sin-cache"); + }; + let hits = cac