clap_complete-4.5.40/.cargo_vcs_info.json0000644000000001530000000000100137340ustar { "git": { "sha1": "cff27dbf5749777b380abb0f3627ef3d3147844a" }, "path_in_vcs": "clap_complete" }clap_complete-4.5.40/Cargo.lock0000644000000556510000000000100117240ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "addr2line" version = "0.22.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e4503c46a5c0c7844e948c9a4d6acd9f50cccb4de1c48eb9e291ea17470c678" dependencies = [ "gimli", ] [[package]] name = "adler" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" [[package]] name = "anstream" version = "0.6.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "418c75fa768af9c03be99d17643f93f79bbba589895012a80e3452a19ddda15b" dependencies = [ "anstyle", "anstyle-parse", "anstyle-query", "anstyle-wincon", "colorchoice", "is_terminal_polyfill", "utf8parse", ] [[package]] name = "anstyle" version = "1.0.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1bec1de6f59aedf83baf9ff929c98f2ad654b97c9510f4e70cf6f661d49fd5b1" [[package]] name = "anstyle-parse" version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c03a11a9034d92058ceb6ee011ce58af4a9bf61491aa7e1e59ecd24bd40d22d4" dependencies = [ "utf8parse", ] [[package]] name = "anstyle-query" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ad186efb764318d35165f1758e7dcef3b10628e26d41a44bc5550652e6804391" dependencies = [ "windows-sys 0.52.0", ] [[package]] name = "anstyle-wincon" version = "3.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "61a38449feb7068f52bb06c12759005cf459ee52bb4adc1d5a7c4322d716fb19" dependencies = [ "anstyle", "windows-sys 0.52.0", ] [[package]] name = "arrayvec" version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "96d30a06541fbafbc7f82ed10c06164cfbd2c401138f6addd8404629c4b16711" [[package]] name = "autocfg" version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c4b4d0bd25bd0b74681c0ad21497610ce1b7c91b1022cd21c80c6fbdd9476b0" [[package]] name = "automod" version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "edf3ee19dbc0a46d740f6f0926bde8c50f02bdbc7b536842da28f6ac56513a8b" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "backtrace" version = "0.3.73" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5cc23269a4f8976d0a4d2e7109211a419fe30e8d88d677cd60b6bc79c5732e0a" dependencies = [ "addr2line", "cc", "cfg-if", "libc", "miniz_oxide", "object", "rustc-demangle", ] [[package]] name = "bitflags" version = "1.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bitflags" version = "2.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de" [[package]] name = "cc" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eaff6f8ce506b9773fa786672d63fc7a191ffea1be33f72bbd4aeacefca9ffc8" [[package]] name = "cfg-if" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "clap" version = "4.5.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "69371e34337c4c984bbe322360c2547210bf632eb2814bbe78a6e87a2935bd2b" dependencies = [ "clap_builder", "clap_derive", ] [[package]] name = "clap_builder" version = "4.5.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e24c1b4099818523236a8ca881d2b45db98dadfb4625cf6608c12069fcbbde1" dependencies = [ "anstyle", "backtrace", "clap_lex", ] [[package]] name = "clap_complete" version = "4.5.40" dependencies = [ "automod", "clap", "clap_lex", "completest", "completest-pty", "is_executable", "shlex", "snapbox", "trycmd", ] [[package]] name = "clap_derive" version = "4.5.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4ac6a0c7b1a9e9a5186361f67dfa1b88213572f427fb9ab038efb2bd8c582dab" dependencies = [ "heck", "proc-macro2", "quote", "syn", ] [[package]] name = "clap_lex" version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4b82cf0babdbd58558212896d1a4272303a57bdb245c2bf1147185fb45640e70" [[package]] name = "colorchoice" version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b6a852b24ab71dffc585bcb46eaf7959d175cb865a7152e35b348d1b2960422" [[package]] name = "completest" version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "410de1ffe61368aa040f599747584e9e3d19235cf4045be6159edb167ef45ddb" [[package]] name = "completest-pty" version = "0.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fbd2f22a999db122bd2861c504aa363bbacaa32ebea29edf6924ee6cfe044313" dependencies = [ "completest", "ptyprocess", "vt100", ] [[package]] name = "content_inspector" version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b7bda66e858c683005a53a9a60c69a4aca7eeaa45d124526e389f7aec8e62f38" dependencies = [ "memchr", ] [[package]] name = "crossbeam-deque" version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "613f8cc01fe9cf1a3eb3d7f488fd2fa8388403e97039e2f73692932e291a770d" dependencies = [ "crossbeam-epoch", "crossbeam-utils", ] [[package]] name = "crossbeam-epoch" version = "0.9.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e" dependencies = [ "crossbeam-utils", ] [[package]] name = "crossbeam-utils" version = "0.8.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "22ec99545bb0ed0ea7bb9b8e1e9122ea386ff8a48c0922e43f36d45ab09e0e80" [[package]] name = "dunce" version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "56ce8c6da7551ec6c462cbaf3bfbc75131ebbfa1c944aeaa9dab51ca1c5f0c3b" [[package]] name = "either" version = "1.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "60b1af1c220855b6ceac025d3f6ecdd2b7c4894bfe9cd9bda4fbb4bc7c0d4cf0" [[package]] name = "equivalent" version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" [[package]] name = "errno" version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "534c5cf6194dfab3db3242765c03bbe257cf92f22b38f6bc0c58d59108a820ba" dependencies = [ "libc", "windows-sys 0.52.0", ] [[package]] name = "escargot" version = "0.5.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "05a3ac187a16b5382fef8c69fd1bad123c67b7cf3932240a2d43dcdd32cded88" dependencies = [ "log", "once_cell", "serde", "serde_json", ] [[package]] name = "fastrand" version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9fc0510504f03c51ada170672ac806f1f105a88aa97a5281117e1ddc3368e51a" [[package]] name = "filetime" version = "0.2.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ee447700ac8aa0b2f2bd7bc4462ad686ba06baa6727ac149a2d6277f0d240fd" dependencies = [ "cfg-if", "libc", "redox_syscall", "windows-sys 0.52.0", ] [[package]] name = "gimli" version = "0.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40ecd4077b5ae9fd2e9e169b102c6c330d0605168eb0e8bf79952b256dbefffd" [[package]] name = "glob" version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" [[package]] name = "hashbrown" version = "0.14.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" [[package]] name = "heck" version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" [[package]] name = "humantime" version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4" [[package]] name = "humantime-serde" version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "57a3db5ea5923d99402c94e9feb261dc5ee9b4efa158b0315f788cf549cc200c" dependencies = [ "humantime", "serde", ] [[package]] name = "indexmap" version = "2.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "168fb715dda47215e360912c096649d23d58bf392ac62f73919e831745e40f26" dependencies = [ "equivalent", "hashbrown", ] [[package]] name = "is_executable" version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fa9acdc6d67b75e626ad644734e8bc6df893d9cd2a834129065d3dd6158ea9c8" dependencies = [ "winapi", ] [[package]] name = "is_terminal_polyfill" version = "1.70.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8478577c03552c21db0e2724ffb8986a5ce7af88107e6be5d2ee6e158c12800" [[package]] name = "itoa" version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b" [[package]] name = "libc" version = "0.2.155" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "97b3888a4aecf77e811145cadf6eef5901f4782c53886191b2f693f24761847c" [[package]] name = "linux-raw-sys" version = "0.4.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89" [[package]] name = "log" version = "0.4.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24" [[package]] name = "memchr" version = "2.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" [[package]] name = "memoffset" version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5de893c32cde5f383baa4c04c5d6dbdd735cfd4a794b0debdb2bb1b421da5ff4" dependencies = [ "autocfg", ] [[package]] name = "miniz_oxide" version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8a240ddb74feaf34a79a7add65a741f3167852fba007066dcac1ca548d89c08" dependencies = [ "adler", ] [[package]] name = "nix" version = "0.26.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "598beaf3cc6fdd9a5dfb1630c2800c7acd31df7aaf0f565796fba2b53ca1af1b" dependencies = [ "bitflags 1.3.2", "cfg-if", "libc", "memoffset", "pin-utils", ] [[package]] name = "normalize-line-endings" version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "61807f77802ff30975e01f4f071c8ba10c022052f98b3294119f3e615d13e5be" [[package]] name = "object" version = "0.36.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "081b846d1d56ddfc18fdf1a922e4f6e07a11768ea1b92dec44e42b72712ccfce" dependencies = [ "memchr", ] [[package]] name = "once_cell" version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92" [[package]] name = "os_pipe" version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29d73ba8daf8fac13b0501d1abeddcfe21ba7401ada61a819144b6c2a4f32209" dependencies = [ "libc", "windows-sys 0.52.0", ] [[package]] name = "pin-utils" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" [[package]] name = "proc-macro2" version = "1.0.86" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5e719e8df665df0d1c8fbfd238015744736151d4445ec0836b8e628aae103b77" dependencies = [ "unicode-ident", ] [[package]] name = "ptyprocess" version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7e05aef7befb11a210468a2d77d978dde2c6381a0381e33beb575e91f57fe8cf" dependencies = [ "nix", ] [[package]] name = "quote" version = "1.0.36" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7" dependencies = [ "proc-macro2", ] [[package]] name = "rayon" version = "1.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b418a60154510ca1a002a752ca9714984e21e4241e804d32555251faf8b78ffa" dependencies = [ "either", "rayon-core", ] [[package]] name = "rayon-core" version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1465873a3dfdaa8ae7cb14b4383657caab0b3e8a0aa9ae8e04b044854c8dfce2" dependencies = [ "crossbeam-deque", "crossbeam-utils", ] [[package]] name = "redox_syscall" version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa" dependencies = [ "bitflags 1.3.2", ] [[package]] name = "rustc-demangle" version = "0.1.24" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "719b953e2095829ee67db738b3bfa9fa368c94900df327b3f07fe6e794d2fe1f" [[package]] name = "rustix" version = "0.38.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "70dc5ec042f7a43c4a73241207cecc9873a06d45debb38b329f8541d85c2730f" dependencies = [ "bitflags 2.6.0", "errno", "libc", "linux-raw-sys", "windows-sys 0.52.0", ] [[package]] name = "ryu" version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f3cb5ba0dc43242ce17de99c180e96db90b235b8a9fdc9543c96d2209116bd9f" [[package]] name = "same-file" version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" dependencies = [ "winapi-util", ] [[package]] name = "serde" version = "1.0.204" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bc76f558e0cbb2a839d37354c575f1dc3fdc6546b5be373ba43d95f231bf7c12" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" version = "1.0.204" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e0cd7e117be63d3c3678776753929474f3b04a43a080c744d6b0ae2a8c28e222" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "serde_json" version = "1.0.120" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e0d21c9a8cae1235ad58a00c11cb40d4b1e5c784f1ef2c537876ed6ffd8b7c5" dependencies = [ "itoa", "ryu", "serde", ] [[package]] name = "serde_spanned" version = "0.6.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "79e674e01f999af37c49f70a6ede167a8a60b2503e56c5599532a65baa5969a0" dependencies = [ "serde", ] [[package]] name = "shlex" version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" [[package]] name = "similar" version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fa42c91313f1d05da9b26f267f931cf178d4aba455b4c4622dd7355eb80c6640" [[package]] name = "snapbox" version = "0.6.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "881f1849454828a68363dd288b7a0a071e55e2a4356d2c38b567db18a9be0d9f" dependencies = [ "anstream", "anstyle", "content_inspector", "dunce", "escargot", "filetime", "libc", "normalize-line-endings", "os_pipe", "similar", "snapbox-macros", "tempfile", "wait-timeout", "walkdir", "windows-sys 0.59.0", ] [[package]] name = "snapbox-macros" version = "0.3.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "16569f53ca23a41bb6f62e0a5084aa1661f4814a67fa33696a79073e03a664af" dependencies = [ "anstream", ] [[package]] name = "syn" version = "2.0.70" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2f0209b68b3613b093e0ec905354eccaedcfe83b8cb37cbdeae64026c3064c16" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "tempfile" version = "3.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "85b77fafb263dd9d05cbeac119526425676db3784113aa9295c88498cbf8bff1" dependencies = [ "cfg-if", "fastrand", "rustix", "windows-sys 0.52.0", ] [[package]] name = "toml_datetime" version = "0.6.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4badfd56924ae69bcc9039335b2e017639ce3f9b001c393c1b2d1ef846ce2cbf" dependencies = [ "serde", ] [[package]] name = "toml_edit" version = "0.22.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d59a3a72298453f564e2b111fa896f8d07fabb36f51f06d7e875fc5e0b5a3ef1" dependencies = [ "indexmap", "serde", "serde_spanned", "toml_datetime", "winnow", ] [[package]] name = "trycmd" version = "0.15.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "656073a28690a4b8dfd578d1df087826cf8fa53c8161dbd90130d092570a21e1" dependencies = [ "anstream", "automod", "glob", "humantime", "humantime-serde", "rayon", "serde", "shlex", "snapbox", "toml_edit", ] [[package]] name = "unicode-ident" version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" [[package]] name = "unicode-width" version = "0.1.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0336d538f7abc86d282a4189614dfaa90810dfc2c6f6427eaf88e16311dd225d" [[package]] name = "utf8parse" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" [[package]] name = "vt100" version = "0.15.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "84cd863bf0db7e392ba3bd04994be3473491b31e66340672af5d11943c6274de" dependencies = [ "itoa", "log", "unicode-width", "vte", ] [[package]] name = "vte" version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f5022b5fbf9407086c180e9557be968742d839e68346af7792b8592489732197" dependencies = [ "arrayvec", "utf8parse", "vte_generate_state_changes", ] [[package]] name = "vte_generate_state_changes" version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2e369bee1b05d510a7b4ed645f5faa90619e05437111783ea5848f28d97d3c2e" dependencies = [ "proc-macro2", "quote", ] [[package]] name = "wait-timeout" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f200f5b12eb75f8c1ed65abd4b2db8a6e1b138a20de009dacee265a2498f3f6" dependencies = [ "libc", ] [[package]] name = "walkdir" version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" dependencies = [ "same-file", "winapi-util", ] [[package]] name = "winapi" version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" dependencies = [ "winapi-i686-pc-windows-gnu", "winapi-x86_64-pc-windows-gnu", ] [[package]] name = "winapi-i686-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" [[package]] name = "winapi-util" version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4d4cc384e1e73b93bafa6fb4f1df8c41695c8a91cf9c4c64358067d15a7b6c6b" dependencies = [ "windows-sys 0.52.0", ] [[package]] name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[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.59.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" dependencies = [ "windows-targets", ] [[package]] name = "windows-targets" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ "windows_aarch64_gnullvm", "windows_aarch64_msvc", "windows_i686_gnu", "windows_i686_gnullvm", "windows_i686_msvc", "windows_x86_64_gnu", "windows_x86_64_gnullvm", "windows_x86_64_msvc", ] [[package]] name = "windows_aarch64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" [[package]] name = "windows_aarch64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" [[package]] name = "windows_i686_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" [[package]] name = "windows_i686_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" [[package]] name = "windows_i686_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" [[package]] name = "windows_x86_64_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" [[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" [[package]] name = "windows_x86_64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] name = "winnow" version = "0.6.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "59b5e5f6c299a3c7890b876a2a587f3115162487e704907d9b6cd29473052ba1" dependencies = [ "memchr", ] clap_complete-4.5.40/Cargo.toml0000644000000127650000000000100117460ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.74" name = "clap_complete" version = "4.5.40" build = false include = [ "build.rs", "src/**/*", "Cargo.toml", "LICENSE*", "README.md", "benches/**/*", "examples/**/*", ] autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = "Generate shell completion scripts for your clap::Command" readme = "README.md" keywords = [ "clap", "cli", "completion", "bash", ] categories = ["command-line-interface"] license = "MIT OR Apache-2.0" repository = "https://github.com/clap-rs/clap" [package.metadata.docs.rs] cargo-args = [ "-Zunstable-options", "-Zrustdoc-scrape-examples", ] features = ["unstable-doc"] rustdoc-args = [ "--cfg", "docsrs", "--generate-link-to-definition", ] [[package.metadata.release.pre-release-replacements]] file = "CHANGELOG.md" min = 1 replace = "{{version}}" search = "Unreleased" [[package.metadata.release.pre-release-replacements]] exactly = 1 file = "CHANGELOG.md" replace = "...{{tag_name}}" search = '\.\.\.HEAD' [[package.metadata.release.pre-release-replacements]] file = "CHANGELOG.md" min = 1 replace = "{{date}}" search = "ReleaseDate" [[package.metadata.release.pre-release-replacements]] exactly = 1 file = "CHANGELOG.md" replace = """ ## [Unreleased] - ReleaseDate """ search = "" [[package.metadata.release.pre-release-replacements]] exactly = 1 file = "CHANGELOG.md" replace = """ [Unreleased]: https://github.com/clap-rs/clap/compare/{{tag_name}}...HEAD""" search = "" [[package.metadata.release.pre-release-replacements]] exactly = 4 file = "README.md" prerelease = true replace = "github.com/clap-rs/clap/blob/{{tag_name}}/" search = "github.com/clap-rs/clap/blob/[^/]+/" [lib] name = "clap_complete" path = "src/lib.rs" bench = false [[example]] name = "completion" path = "examples/completion.rs" [[example]] name = "completion-derive" path = "examples/completion-derive.rs" [[example]] name = "dynamic" path = "examples/dynamic.rs" required-features = ["unstable-dynamic"] [[example]] name = "exhaustive" path = "examples/exhaustive.rs" [dependencies.clap] version = "4.5.20" features = ["std"] default-features = false [dependencies.clap_lex] version = "0.7.0" optional = true [dependencies.completest] version = "0.4.2" optional = true [dependencies.completest-pty] version = "0.5.5" optional = true [dependencies.is_executable] version = "1.0.1" optional = true [dependencies.shlex] version = "1.3.0" optional = true [dev-dependencies.automod] version = "1.0.14" [dev-dependencies.clap] version = "4.5.20" features = [ "std", "derive", "help", ] default-features = false [dev-dependencies.snapbox] version = "0.6.0" features = [ "diff", "dir", "examples", ] [dev-dependencies.trycmd] version = "0.15.1" features = [ "color-auto", "diff", "examples", ] default-features = false [features] debug = ["clap/debug"] default = [] unstable-doc = ["unstable-dynamic"] unstable-dynamic = [ "dep:clap_lex", "dep:shlex", "dep:is_executable", "clap/unstable-ext", ] unstable-shell-tests = [ "dep:completest", "dep:completest-pty", ] [lints.clippy] assigning_clones = "allow" blocks_in_conditions = "allow" bool_assert_comparison = "allow" branches_sharing_code = "allow" checked_conversions = "warn" collapsible_else_if = "allow" create_dir = "warn" dbg_macro = "warn" debug_assert_with_mut_call = "warn" doc_markdown = "warn" empty_enum = "warn" enum_glob_use = "warn" expl_impl_clone_on_copy = "warn" explicit_deref_methods = "warn" explicit_into_iter_loop = "warn" fallible_impl_from = "warn" filter_map_next = "warn" flat_map_option = "warn" float_cmp_const = "warn" fn_params_excessive_bools = "warn" from_iter_instead_of_collect = "warn" if_same_then_else = "allow" implicit_clone = "warn" imprecise_flops = "warn" inconsistent_struct_constructor = "warn" inefficient_to_string = "warn" infinite_loop = "warn" invalid_upcast_comparisons = "warn" large_digit_groups = "warn" large_stack_arrays = "warn" large_types_passed_by_value = "warn" let_and_return = "allow" linkedlist = "warn" lossy_float_literal = "warn" macro_use_imports = "warn" mem_forget = "warn" multiple_bound_locations = "allow" mutex_integer = "warn" needless_continue = "warn" needless_for_each = "warn" negative_feature_names = "warn" path_buf_push_overwrite = "warn" ptr_as_ptr = "warn" rc_mutex = "warn" redundant_feature_names = "warn" ref_option_ref = "warn" rest_pat_in_fully_bound_structs = "warn" same_functions_in_if_condition = "warn" self_named_module_files = "warn" semicolon_if_nothing_returned = "warn" string_add_assign = "warn" string_lit_as_bytes = "warn" todo = "warn" trait_duplication_in_bounds = "warn" uninlined_format_args = "warn" verbose_file_reads = "warn" zero_sized_map_values = "warn" [lints.rust] unreachable_pub = "warn" unsafe_op_in_unsafe_fn = "warn" unused_lifetimes = "warn" unused_macro_rules = "warn" unused_qualifications = "warn" [lints.rust.rust_2018_idioms] level = "warn" priority = -1 clap_complete-4.5.40/Cargo.toml.orig000064400000000000000000000045551046102023000154250ustar 00000000000000[package] name = "clap_complete" version = "4.5.40" description = "Generate shell completion scripts for your clap::Command" categories = ["command-line-interface"] keywords = [ "clap", "cli", "completion", "bash", ] repository.workspace = true license.workspace = true edition.workspace = true rust-version.workspace = true include.workspace = true [package.metadata.docs.rs] features = ["unstable-doc"] rustdoc-args = ["--cfg", "docsrs", "--generate-link-to-definition"] cargo-args = ["-Zunstable-options", "-Zrustdoc-scrape-examples"] [package.metadata.release] pre-release-replacements = [ {file="CHANGELOG.md", search="Unreleased", replace="{{version}}", min=1}, {file="CHANGELOG.md", search="\\.\\.\\.HEAD", replace="...{{tag_name}}", exactly=1}, {file="CHANGELOG.md", search="ReleaseDate", replace="{{date}}", min=1}, {file="CHANGELOG.md", search="", replace="\n## [Unreleased] - ReleaseDate\n", exactly=1}, {file="CHANGELOG.md", search="", replace="\n[Unreleased]: https://github.com/clap-rs/clap/compare/{{tag_name}}...HEAD", exactly=1}, {file="README.md", search="github.com/clap-rs/clap/blob/[^/]+/", replace="github.com/clap-rs/clap/blob/{{tag_name}}/", exactly=4, prerelease = true}, ] [lib] bench = false [dependencies] clap = { path = "../", version = "4.5.20", default-features = false, features = ["std"] } clap_lex = { path = "../clap_lex", version = "0.7.0", optional = true } is_executable = { version = "1.0.1", optional = true } shlex = { version = "1.3.0", optional = true } completest = { version = "0.4.2", optional = true } completest-pty = { version = "0.5.5", optional = true } [dev-dependencies] snapbox = { version = "0.6.0", features = ["diff", "dir", "examples"] } # Cutting out `filesystem` feature trycmd = { version = "0.15.1", default-features = false, features = ["color-auto", "diff", "examples"] } clap = { path = "../", version = "4.5.20", default-features = false, features = ["std", "derive", "help"] } automod = "1.0.14" [[example]] name = "dynamic" required-features = ["unstable-dynamic"] [features] default = [] unstable-doc = ["unstable-dynamic"] # for docs.rs unstable-dynamic = ["dep:clap_lex", "dep:shlex", "dep:is_executable", "clap/unstable-ext"] unstable-shell-tests = ["dep:completest", "dep:completest-pty"] debug = ["clap/debug"] [lints] workspace = true clap_complete-4.5.40/LICENSE-APACHE000064400000000000000000000261351046102023000144600ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. clap_complete-4.5.40/LICENSE-MIT000064400000000000000000000021241046102023000141600ustar 00000000000000The MIT License (MIT) Copyright (c) 2015-2022 Kevin B. Knapp and Clap Contributors 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. clap_complete-4.5.40/README.md000064400000000000000000000024771046102023000140160ustar 00000000000000 # clap_complete > **Shell completion generation for `clap`** [![Crates.io](https://img.shields.io/crates/v/clap_complete?style=flat-square)](https://crates.io/crates/clap_complete) [![Crates.io](https://img.shields.io/crates/d/clap_complete?style=flat-square)](https://crates.io/crates/clap_complete) [![License](https://img.shields.io/badge/license-Apache%202.0-blue?style=flat-square)](https://github.com/clap-rs/clap/blob/clap_complete-v4.5.40/LICENSE-APACHE) [![License](https://img.shields.io/badge/license-MIT-blue?style=flat-square)](https://github.com/clap-rs/clap/blob/clap_complete-v4.5.40/LICENSE-MIT) Dual-licensed under [Apache 2.0](LICENSE-APACHE) or [MIT](LICENSE-MIT). 1. [About](#about) 2. [API Reference](https://docs.rs/clap_complete) 3. [Questions & Discussions](https://github.com/clap-rs/clap/discussions) 4. [CONTRIBUTING](https://github.com/clap-rs/clap/blob/clap_complete-v4.5.40/clap_complete/CONTRIBUTING.md) 5. [Sponsors](https://github.com/clap-rs/clap/blob/clap_complete-v4.5.40/README.md#sponsors) ## About ### Related Projects - [clap_complete_fig](https://crates.io/crates/clap_complete_fig) for [fig](https://fig.io/) shell completion support - [clap_complete_nushell](https://crates.io/crates/clap_complete_nushell) for [nushell](https://www.nushell.sh/) shell completion support clap_complete-4.5.40/examples/completion-derive.rs000064400000000000000000000054051046102023000203420ustar 00000000000000//! How to use value hints and generate shell completions. //! //! Usage with zsh: //! ```console //! $ cargo run --example completion-derive -- --generate=zsh > /usr/local/share/zsh/site-functions/_completion_derive //! $ compinit //! $ ./target/debug/examples/completion_derive -- //! ``` //! fish: //! ```console //! $ cargo run --example completion-derive -- --generate=fish > completion_derive.fish //! $ . ./completion_derive.fish //! $ ./target/debug/examples/completion_derive -- //! ``` use clap::{Args, Command, CommandFactory, Parser, Subcommand, ValueHint}; use clap_complete::{generate, Generator, Shell}; use std::ffi::OsString; use std::io; use std::path::PathBuf; #[derive(Parser, Debug, PartialEq)] #[command(name = "completion-derive")] struct Opt { // If provided, outputs the completion file for given shell #[arg(long = "generate", value_enum)] generator: Option, #[command(subcommand)] command: Option, } #[derive(Subcommand, Debug, PartialEq)] enum Commands { #[command(visible_alias = "hint")] ValueHint(ValueHintOpt), } #[derive(Args, Debug, PartialEq)] struct ValueHintOpt { // Showcasing all possible ValueHints: #[arg(long, value_hint = ValueHint::Unknown)] unknown: Option, #[arg(long, value_hint = ValueHint::Other)] other: Option, #[arg(short, long, value_hint = ValueHint::AnyPath)] path: Option, #[arg(short, long, value_hint = ValueHint::FilePath)] file: Option, #[arg(short, long, value_hint = ValueHint::DirPath)] dir: Option, #[arg(short, long, value_hint = ValueHint::ExecutablePath)] exe: Option, #[arg(long, value_hint = ValueHint::CommandName)] cmd_name: Option, #[arg(short, long, value_hint = ValueHint::CommandString)] cmd: Option, // Command::trailing_var_ar is required to use ValueHint::CommandWithArguments #[arg(trailing_var_arg = true, value_hint = ValueHint::CommandWithArguments)] command_with_args: Vec, #[arg(short, long, value_hint = ValueHint::Username)] user: Option, #[arg(long, value_hint = ValueHint::Hostname)] host: Option, #[arg(long, value_hint = ValueHint::Url)] url: Option, #[arg(long, value_hint = ValueHint::EmailAddress)] email: Option, } fn print_completions(gen: G, cmd: &mut Command) { generate(gen, cmd, cmd.get_name().to_string(), &mut io::stdout()); } fn main() { let opt = Opt::parse(); if let Some(generator) = opt.generator { let mut cmd = Opt::command(); eprintln!("Generating completion file for {generator:?}..."); print_completions(generator, &mut cmd); } else { println!("{opt:#?}"); } } clap_complete-4.5.40/examples/completion.rs000064400000000000000000000063471046102023000170740ustar 00000000000000//! Example to test arguments with different `ValueHint` values. //! //! Usage with zsh: //! ```console //! $ cargo run --example completion -- --generate=zsh > /usr/local/share/zsh/site-functions/_completion$ //! $ compinit //! $ ./target/debug/examples/completion -- //! ``` //! fish: //! ```console //! $ cargo run --example completion -- --generate=fish > completion.fish //! $ . ./completion.fish //! $ ./target/debug/examples/completion -- //! ``` use clap::{value_parser, Arg, Command, ValueHint}; use clap_complete::{generate, Generator, Shell}; use std::io; fn build_cli() -> Command { let value_hint_command = Command::new("value-hint") .visible_alias("hint") .arg( Arg::new("unknown") .long("unknown") .value_hint(ValueHint::Unknown), ) .arg(Arg::new("other").long("other").value_hint(ValueHint::Other)) .arg( Arg::new("path") .long("path") .short('p') .value_hint(ValueHint::AnyPath), ) .arg( Arg::new("file") .long("file") .short('f') .value_hint(ValueHint::FilePath), ) .arg( Arg::new("dir") .long("dir") .short('d') .value_hint(ValueHint::DirPath), ) .arg( Arg::new("exe") .long("exe") .short('e') .value_hint(ValueHint::ExecutablePath), ) .arg( Arg::new("cmd_name") .long("cmd-name") .value_hint(ValueHint::CommandName), ) .arg( Arg::new("cmd") .long("cmd") .short('c') .value_hint(ValueHint::CommandString), ) .arg( Arg::new("command_with_args") .num_args(1..) // AppSettings::TrailingVarArg is required to use ValueHint::CommandWithArguments .trailing_var_arg(true) .value_hint(ValueHint::CommandWithArguments), ) .arg( Arg::new("user") .short('u') .long("user") .value_hint(ValueHint::Username), ) .arg( Arg::new("host") .long("host") .value_hint(ValueHint::Hostname), ) .arg(Arg::new("url").long("url").value_hint(ValueHint::Url)) .arg( Arg::new("email") .long("email") .value_hint(ValueHint::EmailAddress), ); Command::new("completion") .arg( Arg::new("generator") .long("generate") .value_parser(value_parser!(Shell)), ) .subcommand(value_hint_command) } fn print_completions(gen: G, cmd: &mut Command) { generate(gen, cmd, cmd.get_name().to_string(), &mut io::stdout()); } fn main() { let matches = build_cli().get_matches(); if let Some(generator) = matches.get_one::("generator") { let mut cmd = build_cli(); eprintln!("Generating completion file for {generator}..."); print_completions(*generator, &mut cmd); } } clap_complete-4.5.40/examples/dynamic.rs000064400000000000000000000012751046102023000163420ustar 00000000000000fn command() -> clap::Command { clap::Command::new("dynamic") .arg( clap::Arg::new("input") .long("input") .short('i') .value_hint(clap::ValueHint::FilePath), ) .arg( clap::Arg::new("format") .long("format") .short('F') .value_parser(["json", "yaml", "toml"]), ) .args_conflicts_with_subcommands(true) } fn main() { clap_complete::CompleteEnv::with_factory(command).complete(); let cmd = command(); let matches = cmd.get_matches(); println!("{matches:#?}"); } #[test] fn verify_cli() { command().debug_assert(); } clap_complete-4.5.40/examples/exhaustive.rs000064400000000000000000000207101046102023000170760ustar 00000000000000use clap::builder::PossibleValue; use clap_complete::{generate, Generator, Shell}; fn main() { #[cfg(feature = "unstable-dynamic")] clap_complete::CompleteEnv::with_factory(cli) // Avoid tests snapshotting a path into `target/` .completer("exhaustive") .complete(); let matches = cli().get_matches(); if let Some(generator) = matches.get_one::("generate") { let mut cmd = cli(); eprintln!("Generating completion file for {generator}..."); print_completions(*generator, &mut cmd); return; } println!("{matches:?}"); } fn print_completions(gen: G, cmd: &mut clap::Command) { generate(gen, cmd, cmd.get_name().to_string(), &mut std::io::stdout()); } #[allow(clippy::let_and_return)] fn cli() -> clap::Command { clap::Command::new("exhaustive") .version("3.0") .propagate_version(true) .args([ clap::Arg::new("global") .long("global") .global(true) .action(clap::ArgAction::SetTrue) .help("everywhere"), clap::Arg::new("generate") .long("generate") .value_name("SHELL") .value_parser(clap::value_parser!(Shell)) .help("generate"), ]) .subcommands([ clap::Command::new("action").args([ clap::Arg::new("set-true") .long("set-true") .action(clap::ArgAction::SetTrue) .help("bool"), clap::Arg::new("set") .long("set") .action(clap::ArgAction::Set) .help("value"), clap::Arg::new("count") .long("count") .action(clap::ArgAction::Count) .help("number"), clap::Arg::new("choice") .long("choice") .value_parser(["first", "second"]) .help("enum"), ]), clap::Command::new("quote") .args([ clap::Arg::new("single-quotes") .long("single-quotes") .action(clap::ArgAction::SetTrue) .help("Can be 'always', 'auto', or 'never'"), clap::Arg::new("double-quotes") .long("double-quotes") .action(clap::ArgAction::SetTrue) .help("Can be \"always\", \"auto\", or \"never\""), clap::Arg::new("backticks") .long("backticks") .action(clap::ArgAction::SetTrue) .help("For more information see `echo test`"), clap::Arg::new("backslash") .long("backslash") .action(clap::ArgAction::SetTrue) .help("Avoid '\\n'"), clap::Arg::new("brackets") .long("brackets") .action(clap::ArgAction::SetTrue) .help("List packages [filter]"), clap::Arg::new("expansions") .long("expansions") .action(clap::ArgAction::SetTrue) .help("Execute the shell command with $SHELL"), clap::Arg::new("choice") .long("choice") .action(clap::ArgAction::Set) .value_parser(clap::builder::PossibleValuesParser::new([ PossibleValue::new("another shell").help("something with a space"), PossibleValue::new("bash").help("bash (shell)"), PossibleValue::new("fish").help("fish shell"), PossibleValue::new("zsh").help("zsh shell"), ])), ]) .subcommands([ clap::Command::new("cmd-single-quotes") .about("Can be 'always', 'auto', or 'never'"), clap::Command::new("cmd-double-quotes") .about("Can be \"always\", \"auto\", or \"never\""), clap::Command::new("cmd-backticks") .about("For more information see `echo test`"), clap::Command::new("cmd-backslash").about("Avoid '\\n'"), clap::Command::new("cmd-brackets").about("List packages [filter]"), clap::Command::new("cmd-expansions") .about("Execute the shell command with $SHELL"), clap::Command::new("escape-help").about("\\tab\t\"'\nNew Line"), ]), clap::Command::new("value").args([ clap::Arg::new("delim").long("delim").value_delimiter(','), clap::Arg::new("tuple").long("tuple").num_args(2), clap::Arg::new("require-eq") .long("require-eq") .require_equals(true), clap::Arg::new("term").num_args(1..).value_terminator(";"), ]), clap::Command::new("pacman").subcommands([ clap::Command::new("one").long_flag("one").short_flag('o'), clap::Command::new("two").long_flag("two").short_flag('t'), ]), clap::Command::new("last") .args([clap::Arg::new("first"), clap::Arg::new("free").last(true)]), clap::Command::new("alias").args([ clap::Arg::new("flag") .short('f') .visible_short_alias('F') .long("flag") .action(clap::ArgAction::SetTrue) .visible_alias("flg") .help("cmd flag"), clap::Arg::new("option") .short('o') .visible_short_alias('O') .long("option") .visible_alias("opt") .help("cmd option") .action(clap::ArgAction::Set), clap::Arg::new("positional"), ]), clap::Command::new("hint").args([ clap::Arg::new("choice") .long("choice") .action(clap::ArgAction::Set) .value_parser(["bash", "fish", "zsh"]), clap::Arg::new("unknown") .long("unknown") .value_hint(clap::ValueHint::Unknown), clap::Arg::new("other") .long("other") .value_hint(clap::ValueHint::Other), clap::Arg::new("path") .long("path") .short('p') .value_hint(clap::ValueHint::AnyPath), clap::Arg::new("file") .long("file") .short('f') .value_hint(clap::ValueHint::FilePath), clap::Arg::new("dir") .long("dir") .short('d') .value_hint(clap::ValueHint::DirPath), clap::Arg::new("exe") .long("exe") .short('e') .value_hint(clap::ValueHint::ExecutablePath), clap::Arg::new("cmd_name") .long("cmd-name") .value_hint(clap::ValueHint::CommandName), clap::Arg::new("cmd") .long("cmd") .short('c') .value_hint(clap::ValueHint::CommandString), clap::Arg::new("command_with_args") .action(clap::ArgAction::Set) .num_args(1..) .trailing_var_arg(true) .value_hint(clap::ValueHint::CommandWithArguments), clap::Arg::new("user") .short('u') .long("user") .value_hint(clap::ValueHint::Username), clap::Arg::new("host") .short('H') .long("host") .value_hint(clap::ValueHint::Hostname), clap::Arg::new("url") .long("url") .value_hint(clap::ValueHint::Url), clap::Arg::new("email") .long("email") .value_hint(clap::ValueHint::EmailAddress), ]), ]) } clap_complete-4.5.40/src/aot/generator/mod.rs000064400000000000000000000163541046102023000172230ustar 00000000000000//! Shell completion machinery pub mod utils; use std::ffi::OsString; use std::fs::File; use std::io::Error; use std::io::Write; use std::path::PathBuf; use clap::Command; /// Generator trait which can be used to write generators pub trait Generator { /// Returns the file name that is created when this generator is called during compile time. /// /// # Panics /// /// May panic when called outside of the context of [`generate`] or [`generate_to`] /// /// # Examples /// /// ``` /// # use std::io::Write; /// # use clap::Command; /// use clap_complete::Generator; /// /// pub struct Fish; /// /// impl Generator for Fish { /// fn file_name(&self, name: &str) -> String { /// format!("{name}.fish") /// } /// # fn generate(&self, cmd: &Command, buf: &mut dyn Write) {} /// } /// ``` fn file_name(&self, name: &str) -> String; /// Generates output out of [`clap::Command`]. /// /// # Panics /// /// May panic when called outside of the context of [`generate`] or [`generate_to`] /// /// # Examples /// /// The following example generator displays the [`clap::Command`] /// as if it is printed using [`std::println`]. /// /// ``` /// use std::{io::Write, fmt::write}; /// use clap::Command; /// use clap_complete::Generator; /// /// pub struct ClapDebug; /// /// impl Generator for ClapDebug { /// # fn file_name(&self, name: &str) -> String { /// # name.into() /// # } /// fn generate(&self, cmd: &Command, buf: &mut dyn Write) { /// write!(buf, "{cmd}").unwrap(); /// } /// } /// ``` fn generate(&self, cmd: &Command, buf: &mut dyn Write); } /// Generate a completions file for a specified shell at compile-time. /// ///
/// /// **NOTE:** to generate the file at compile time you must use a `build.rs` "Build Script" or a /// [`cargo-xtask`](https://github.com/matklad/cargo-xtask) /// ///
/// /// # Examples /// /// The following example generates a bash completion script via a `build.rs` script. In this /// simple example, we'll demo a very small application with only a single subcommand and two /// args. Real applications could be many multiple levels deep in subcommands, and have tens or /// potentially hundreds of arguments. /// /// First, it helps if we separate out our `Command` definition into a separate file. Whether you /// do this as a function, or bare Command definition is a matter of personal preference. /// /// ``` /// // src/cli.rs /// # use clap::{Command, Arg, ArgAction}; /// pub fn build_cli() -> Command { /// Command::new("compl") /// .about("Tests completions") /// .arg(Arg::new("file") /// .help("some input file")) /// .subcommand(Command::new("test") /// .about("tests things") /// .arg(Arg::new("case") /// .long("case") /// .action(ArgAction::Set) /// .help("the case to test"))) /// } /// ``` /// /// In our regular code, we can simply call this `build_cli()` function, then call /// `get_matches()`, or any of the other normal methods directly after. For example: /// /// ```ignore /// // src/main.rs /// /// mod cli; /// /// fn main() { /// let _m = cli::build_cli().get_matches(); /// /// // normal logic continues... /// } /// ``` /// /// Next, we set up our `Cargo.toml` to use a `build.rs` build script. /// /// ```toml /// # Cargo.toml /// build = "build.rs" /// /// [dependencies] /// clap = "*" /// /// [build-dependencies] /// clap = "*" /// clap_complete = "*" /// ``` /// /// Next, we place a `build.rs` in our project root. /// /// ```ignore /// use clap_complete::{generate_to, shells::Bash}; /// use std::env; /// use std::io::Error; /// /// include!("src/cli.rs"); /// /// fn main() -> Result<(), Error> { /// let outdir = match env::var_os("OUT_DIR") { /// None => return Ok(()), /// Some(outdir) => outdir, /// }; /// /// let mut cmd = build_cli(); /// let path = generate_to( /// Bash, /// &mut cmd, // We need to specify what generator to use /// "myapp", // We need to specify the bin name manually /// outdir, // We need to specify where to write to /// )?; /// /// println!("cargo:warning=completion file is generated: {path:?}"); /// /// Ok(()) /// } /// ``` /// /// Now, once we compile there will be a `{bin_name}.bash` file in the directory. /// Assuming we compiled with debug mode, it would be somewhere similar to /// `/target/debug/build/myapp-/out/myapp.bash`. /// ///
/// /// **NOTE:** Please look at the individual [shells][crate::shells] /// to see the name of the files generated. /// ///
/// /// Using [`ValueEnum::value_variants()`][clap::ValueEnum::value_variants] you can easily loop over /// all the supported shell variants to generate all the completions at once too. /// /// ```ignore /// use clap::ValueEnum; /// use clap_complete::{generate_to, Shell}; /// use std::env; /// use std::io::Error; /// /// include!("src/cli.rs"); /// /// fn main() -> Result<(), Error> { /// let outdir = match env::var_os("OUT_DIR") { /// None => return Ok(()), /// Some(outdir) => outdir, /// }; /// /// let mut cmd = build_cli(); /// for &shell in Shell::value_variants() { /// generate_to(shell, &mut cmd, "myapp", outdir)?; /// } /// /// Ok(()) /// } /// ``` pub fn generate_to( gen: G, cmd: &mut Command, bin_name: S, out_dir: T, ) -> Result where G: Generator, S: Into, T: Into, { cmd.set_bin_name(bin_name); let out_dir = PathBuf::from(out_dir.into()); let file_name = gen.file_name(cmd.get_bin_name().unwrap()); let path = out_dir.join(file_name); let mut file = File::create(&path)?; _generate::(gen, cmd, &mut file); Ok(path) } /// Generate a completions file for a specified shell at runtime. /// /// Until `cargo install` can install extra files like a completion script, this may be /// used e.g. in a command that outputs the contents of the completion script, to be /// redirected into a file by the user. /// /// # Examples /// /// Assuming a separate `cli.rs` like the [`generate_to` example](generate_to()), /// we can let users generate a completion script using a command: /// /// ```ignore /// // src/main.rs /// /// mod cli; /// use std::io; /// use clap_complete::{generate, shells::Bash}; /// /// fn main() { /// let matches = cli::build_cli().get_matches(); /// /// if matches.is_present("generate-bash-completions") { /// generate(Bash, &mut cli::build_cli(), "myapp", &mut io::stdout()); /// } /// /// // normal logic continues... /// } /// /// ``` /// /// Usage: /// /// ```console /// $ myapp generate-bash-completions > /usr/share/bash-completion/completions/myapp.bash /// ``` pub fn generate(gen: G, cmd: &mut Command, bin_name: S, buf: &mut dyn Write) where G: Generator, S: Into, { cmd.set_bin_name(bin_name); _generate::(gen, cmd, buf); } fn _generate(gen: G, cmd: &mut Command, buf: &mut dyn Write) { cmd.build(); gen.generate(cmd, buf); } clap_complete-4.5.40/src/aot/generator/utils.rs000064400000000000000000000220041046102023000175710ustar 00000000000000//! Helpers for writing generators use clap::{Arg, Command}; /// Gets all subcommands including child subcommands in the form of `("name", "bin_name")`. /// /// Subcommand `rustup toolchain install` would be converted to /// `("install", "rustup toolchain install")`. pub fn all_subcommands(cmd: &Command) -> Vec<(String, String)> { let mut subcmds: Vec<_> = subcommands(cmd); for sc_v in cmd.get_subcommands().map(all_subcommands) { subcmds.extend(sc_v); } subcmds } /// Finds the subcommand [`clap::Command`] from the given [`clap::Command`] with the given path. /// ///
/// /// **NOTE:** `path` should not contain the root `bin_name`. /// ///
pub fn find_subcommand_with_path<'cmd>(p: &'cmd Command, path: Vec<&str>) -> &'cmd Command { let mut cmd = p; for sc in path { cmd = cmd.find_subcommand(sc).unwrap(); } cmd } /// Gets subcommands of [`clap::Command`] in the form of `("name", "bin_name")`. /// /// Subcommand `rustup toolchain install` would be converted to /// `("install", "rustup toolchain install")`. pub fn subcommands(p: &Command) -> Vec<(String, String)> { debug!("subcommands: name={}", p.get_name()); debug!("subcommands: Has subcommands...{:?}", p.has_subcommands()); let mut subcmds = vec![]; for sc in p.get_subcommands() { let sc_bin_name = sc.get_bin_name().unwrap(); debug!( "subcommands:iter: name={}, bin_name={}", sc.get_name(), sc_bin_name ); subcmds.push((sc.get_name().to_string(), sc_bin_name.to_string())); for alias in sc.get_visible_aliases() { debug!( "subcommands:iter: alias={}, bin_name={}", alias, sc_bin_name ); subcmds.push((alias.to_string(), sc_bin_name.to_string())); } } subcmds } /// Gets all the short options, their visible aliases and flags of a [`clap::Command`]. /// Includes `h` and `V` depending on the [`clap::Command`] settings. pub fn shorts_and_visible_aliases(p: &Command) -> Vec { debug!("shorts: name={}", p.get_name()); p.get_arguments() .filter_map(|a| { if !a.is_positional() { if a.get_visible_short_aliases().is_some() && a.get_short().is_some() { let mut shorts_and_visible_aliases = a.get_visible_short_aliases().unwrap(); shorts_and_visible_aliases.push(a.get_short().unwrap()); Some(shorts_and_visible_aliases) } else if a.get_visible_short_aliases().is_none() && a.get_short().is_some() { Some(vec![a.get_short().unwrap()]) } else { None } } else { None } }) .flatten() .collect() } /// Gets all the long options, their visible aliases and flags of a [`clap::Command`]. /// Includes `help` and `version` depending on the [`clap::Command`] settings. pub fn longs_and_visible_aliases(p: &Command) -> Vec { debug!("longs: name={}", p.get_name()); p.get_arguments() .filter_map(|a| { if !a.is_positional() { if a.get_visible_aliases().is_some() && a.get_long().is_some() { let mut visible_aliases: Vec<_> = a .get_visible_aliases() .unwrap() .into_iter() .map(|s| s.to_string()) .collect(); visible_aliases.push(a.get_long().unwrap().to_string()); Some(visible_aliases) } else if a.get_visible_aliases().is_none() && a.get_long().is_some() { Some(vec![a.get_long().unwrap().to_string()]) } else { None } } else { None } }) .flatten() .collect() } /// Gets all the flags of a [`clap::Command`]. /// Includes `help` and `version` depending on the [`clap::Command`] settings. pub fn flags(p: &Command) -> Vec { debug!("flags: name={}", p.get_name()); p.get_arguments() .filter(|a| !a.get_num_args().expect("built").takes_values() && !a.is_positional()) .cloned() .collect() } /// Get the possible values for completion pub fn possible_values(a: &Arg) -> Option> { if !a.get_num_args().expect("built").takes_values() { None } else { a.get_value_parser() .possible_values() .map(|pvs| pvs.collect()) } } #[cfg(test)] mod tests { use super::*; use clap::Arg; use clap::ArgAction; fn common_app() -> Command { Command::new("myapp") .subcommand( Command::new("test").subcommand(Command::new("config")).arg( Arg::new("file") .short('f') .short_alias('c') .visible_short_alias('p') .long("file") .action(ArgAction::SetTrue) .visible_alias("path"), ), ) .subcommand(Command::new("hello")) .bin_name("my-cmd") } fn built() -> Command { let mut cmd = common_app(); cmd.build(); cmd } fn built_with_version() -> Command { let mut cmd = common_app().version("3.0"); cmd.build(); cmd } #[test] fn test_subcommands() { let cmd = built_with_version(); assert_eq!( subcommands(&cmd), vec![ ("test".to_string(), "my-cmd test".to_string()), ("hello".to_string(), "my-cmd hello".to_string()), ("help".to_string(), "my-cmd help".to_string()), ] ); } #[test] fn test_all_subcommands() { let cmd = built_with_version(); assert_eq!( all_subcommands(&cmd), vec![ ("test".to_string(), "my-cmd test".to_string()), ("hello".to_string(), "my-cmd hello".to_string()), ("help".to_string(), "my-cmd help".to_string()), ("config".to_string(), "my-cmd test config".to_string()), ("help".to_string(), "my-cmd test help".to_string()), ("config".to_string(), "my-cmd test help config".to_string()), ("help".to_string(), "my-cmd test help help".to_string()), ("test".to_string(), "my-cmd help test".to_string()), ("hello".to_string(), "my-cmd help hello".to_string()), ("help".to_string(), "my-cmd help help".to_string()), ("config".to_string(), "my-cmd help test config".to_string()), ] ); } #[test] fn test_find_subcommand_with_path() { let cmd = built_with_version(); let sc_app = find_subcommand_with_path(&cmd, "test config".split(' ').collect()); assert_eq!(sc_app.get_name(), "config"); } #[test] fn test_flags() { let cmd = built_with_version(); let actual_flags = flags(&cmd); assert_eq!(actual_flags.len(), 2); assert_eq!(actual_flags[0].get_long(), Some("help")); assert_eq!(actual_flags[1].get_long(), Some("version")); let sc_flags = flags(find_subcommand_with_path(&cmd, vec!["test"])); assert_eq!(sc_flags.len(), 2); assert_eq!(sc_flags[0].get_long(), Some("file")); assert_eq!(sc_flags[1].get_long(), Some("help")); } #[test] fn test_flag_subcommand() { let cmd = built(); let actual_flags = flags(&cmd); assert_eq!(actual_flags.len(), 1); assert_eq!(actual_flags[0].get_long(), Some("help")); let sc_flags = flags(find_subcommand_with_path(&cmd, vec!["test"])); assert_eq!(sc_flags.len(), 2); assert_eq!(sc_flags[0].get_long(), Some("file")); assert_eq!(sc_flags[1].get_long(), Some("help")); } #[test] fn test_shorts() { let cmd = built_with_version(); let shorts = shorts_and_visible_aliases(&cmd); assert_eq!(shorts.len(), 2); assert_eq!(shorts[0], 'h'); assert_eq!(shorts[1], 'V'); let sc_shorts = shorts_and_visible_aliases(find_subcommand_with_path(&cmd, vec!["test"])); assert_eq!(sc_shorts.len(), 3); assert_eq!(sc_shorts[0], 'p'); assert_eq!(sc_shorts[1], 'f'); assert_eq!(sc_shorts[2], 'h'); } #[test] fn test_longs() { let cmd = built_with_version(); let longs = longs_and_visible_aliases(&cmd); assert_eq!(longs.len(), 2); assert_eq!(longs[0], "help"); assert_eq!(longs[1], "version"); let sc_longs = longs_and_visible_aliases(find_subcommand_with_path(&cmd, vec!["test"])); assert_eq!(sc_longs.len(), 3); assert_eq!(sc_longs[0], "path"); assert_eq!(sc_longs[1], "file"); assert_eq!(sc_longs[2], "help"); } } clap_complete-4.5.40/src/aot/mod.rs000064400000000000000000000030611046102023000152240ustar 00000000000000//! Prebuilt completions //! //! ## Quick Start //! //! - For generating at compile-time, see [`generate_to`] //! - For generating at runtime, see [`generate`] //! //! [`Shell`] is a convenience `enum` for an argument value type that implements `Generator` //! for each natively-supported shell type. //! //! To customize completions, see //! - [`ValueHint`] //! - [`ValueEnum`][clap::ValueEnum] //! //! ## Example //! //! ```rust,no_run //! use clap::{Command, Arg, ValueHint, value_parser, ArgAction}; //! use clap_complete::{generate, Generator, Shell}; //! use std::io; //! //! fn build_cli() -> Command { //! Command::new("example") //! .arg(Arg::new("file") //! .help("some input file") //! .value_hint(ValueHint::AnyPath), //! ) //! .arg( //! Arg::new("generator") //! .long("generate") //! .action(ArgAction::Set) //! .value_parser(value_parser!(Shell)), //! ) //! } //! //! fn print_completions(gen: G, cmd: &mut Command) { //! generate(gen, cmd, cmd.get_name().to_string(), &mut io::stdout()); //! } //! //! fn main() { //! let matches = build_cli().get_matches(); //! //! if let Some(generator) = matches.get_one::("generator").copied() { //! let mut cmd = build_cli(); //! eprintln!("Generating completion file for {generator}..."); //! print_completions(generator, &mut cmd); //! } //! } //! ``` mod generator; mod shells; pub use clap::ValueHint; pub use generator::*; pub use shells::*; clap_complete-4.5.40/src/aot/shells/bash.rs000064400000000000000000000226731046102023000166660ustar 00000000000000use std::{fmt::Write as _, io::Write}; use clap::{Arg, Command, ValueHint}; use crate::generator::{utils, Generator}; /// Generate bash completion file #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub struct Bash; impl Generator for Bash { fn file_name(&self, name: &str) -> String { format!("{name}.bash") } fn generate(&self, cmd: &Command, buf: &mut dyn Write) { let bin_name = cmd .get_bin_name() .expect("crate::generate should have set the bin_name"); let fn_name = bin_name.replace('-', "__"); write!( buf, "_{name}() {{ local i cur prev opts cmd COMPREPLY=() cur=\"${{COMP_WORDS[COMP_CWORD]}}\" prev=\"${{COMP_WORDS[COMP_CWORD-1]}}\" cmd=\"\" opts=\"\" for i in ${{COMP_WORDS[@]}} do case \"${{cmd}},${{i}}\" in \",$1\") cmd=\"{cmd}\" ;;{subcmds} *) ;; esac done case \"${{cmd}}\" in {cmd}) opts=\"{name_opts}\" if [[ ${{cur}} == -* || ${{COMP_CWORD}} -eq 1 ]] ; then COMPREPLY=( $(compgen -W \"${{opts}}\" -- \"${{cur}}\") ) return 0 fi case \"${{prev}}\" in{name_opts_details} *) COMPREPLY=() ;; esac COMPREPLY=( $(compgen -W \"${{opts}}\" -- \"${{cur}}\") ) return 0 ;;{subcmd_details} esac }} if [[ \"${{BASH_VERSINFO[0]}}\" -eq 4 && \"${{BASH_VERSINFO[1]}}\" -ge 4 || \"${{BASH_VERSINFO[0]}}\" -gt 4 ]]; then complete -F _{name} -o nosort -o bashdefault -o default {name} else complete -F _{name} -o bashdefault -o default {name} fi ", name = bin_name, cmd = fn_name, name_opts = all_options_for_path(cmd, bin_name), name_opts_details = option_details_for_path(cmd, bin_name), subcmds = all_subcommands(cmd, &fn_name), subcmd_details = subcommand_details(cmd) ).expect("failed to write completion file"); } } fn all_subcommands(cmd: &Command, parent_fn_name: &str) -> String { debug!("all_subcommands"); fn add_command( parent_fn_name: &str, cmd: &Command, subcmds: &mut Vec<(String, String, String)>, ) { let fn_name = format!( "{parent_fn_name}__{cmd_name}", parent_fn_name = parent_fn_name, cmd_name = cmd.get_name().to_string().replace('-', "__") ); subcmds.push(( parent_fn_name.to_string(), cmd.get_name().to_string(), fn_name.clone(), )); for alias in cmd.get_visible_aliases() { subcmds.push(( parent_fn_name.to_string(), alias.to_string(), fn_name.clone(), )); } for subcmd in cmd.get_subcommands() { add_command(&fn_name, subcmd, subcmds); } } let mut subcmds = vec![]; for subcmd in cmd.get_subcommands() { add_command(parent_fn_name, subcmd, &mut subcmds); } subcmds.sort(); let mut cases = vec![String::new()]; for (parent_fn_name, name, fn_name) in subcmds { cases.push(format!( "{parent_fn_name},{name}) cmd=\"{fn_name}\" ;;", )); } cases.join("\n ") } fn subcommand_details(cmd: &Command) -> String { debug!("subcommand_details"); let mut subcmd_dets = vec![String::new()]; let mut scs = utils::all_subcommands(cmd) .iter() .map(|x| x.1.replace(' ', "__")) .collect::>(); scs.sort(); scs.dedup(); subcmd_dets.extend(scs.iter().map(|sc| { format!( "{subcmd}) opts=\"{sc_opts}\" if [[ ${{cur}} == -* || ${{COMP_CWORD}} -eq {level} ]] ; then COMPREPLY=( $(compgen -W \"${{opts}}\" -- \"${{cur}}\") ) return 0 fi case \"${{prev}}\" in{opts_details} *) COMPREPLY=() ;; esac COMPREPLY=( $(compgen -W \"${{opts}}\" -- \"${{cur}}\") ) return 0 ;;", subcmd = sc.replace('-', "__"), sc_opts = all_options_for_path(cmd, sc), level = sc.split("__").map(|_| 1).sum::(), opts_details = option_details_for_path(cmd, sc) ) })); subcmd_dets.join("\n ") } fn option_details_for_path(cmd: &Command, path: &str) -> String { debug!("option_details_for_path: path={path}"); let p = utils::find_subcommand_with_path(cmd, path.split("__").skip(1).collect()); let mut opts = vec![String::new()]; for o in p.get_opts() { let compopt = match o.get_value_hint() { ValueHint::FilePath => Some("compopt -o filenames"), ValueHint::DirPath => Some("compopt -o plusdirs"), ValueHint::Other => Some("compopt -o nospace"), _ => None, }; if let Some(longs) = o.get_long_and_visible_aliases() { opts.extend(longs.iter().map(|long| { let mut v = vec![format!("--{})", long)]; if o.get_value_hint() == ValueHint::FilePath { v.extend([ "local oldifs".to_string(), r#"if [ -n "${IFS+x}" ]; then"#.to_string(), r#" oldifs="$IFS""#.to_string(), "fi".to_string(), r#"IFS=$'\n'"#.to_string(), format!("COMPREPLY=({})", vals_for(o)), r#"if [ -n "${oldifs+x}" ]; then"#.to_string(), r#" IFS="$oldifs""#.to_string(), "fi".to_string(), ]); } else { v.push(format!("COMPREPLY=({})", vals_for(o))); } if let Some(copt) = compopt { v.extend([ r#"if [[ "${BASH_VERSINFO[0]}" -ge 4 ]]; then"#.to_string(), format!(" {copt}"), "fi".to_string(), ]); } v.extend(["return 0", ";;"].iter().map(|s| (*s).to_string())); v.join("\n ") })); } if let Some(shorts) = o.get_short_and_visible_aliases() { opts.extend(shorts.iter().map(|short| { let mut v = vec![format!("-{})", short)]; if o.get_value_hint() == ValueHint::FilePath { v.extend([ "local oldifs".to_string(), r#"if [ -n "${IFS+x}" ]; then"#.to_string(), r#" oldifs="$IFS""#.to_string(), "fi".to_string(), r#"IFS=$'\n'"#.to_string(), format!("COMPREPLY=({})", vals_for(o)), r#"if [ -n "${oldifs+x}" ]; then"#.to_string(), r#" IFS="$oldifs""#.to_string(), "fi".to_string(), ]); } else { v.push(format!("COMPREPLY=({})", vals_for(o))); } if let Some(copt) = compopt { v.extend([ r#"if [[ "${BASH_VERSINFO[0]}" -ge 4 ]]; then"#.to_string(), format!(" {copt}"), "fi".to_string(), ]); } v.extend(["return 0", ";;"].iter().map(|s| (*s).to_string())); v.join("\n ") })); } } opts.join("\n ") } fn vals_for(o: &Arg) -> String { debug!("vals_for: o={}", o.get_id()); if let Some(vals) = utils::possible_values(o) { format!( "$(compgen -W \"{}\" -- \"${{cur}}\")", vals.iter() .filter(|pv| !pv.is_hide_set()) .map(|n| n.get_name()) .collect::>() .join(" ") ) } else if o.get_value_hint() == ValueHint::DirPath { String::from("") // should be empty to avoid duplicate candidates } else if o.get_value_hint() == ValueHint::Other { String::from("\"${cur}\"") } else { String::from("$(compgen -f \"${cur}\")") } } fn all_options_for_path(cmd: &Command, path: &str) -> String { debug!("all_options_for_path: path={path}"); let p = utils::find_subcommand_with_path(cmd, path.split("__").skip(1).collect()); let mut opts = String::new(); for short in utils::shorts_and_visible_aliases(p) { write!(&mut opts, "-{short} ").expect("writing to String is infallible"); } for long in utils::longs_and_visible_aliases(p) { write!(&mut opts, "--{long} ").expect("writing to String is infallible"); } for pos in p.get_positionals() { if let Some(vals) = utils::possible_values(pos) { for value in vals { write!(&mut opts, "{} ", value.get_name()) .expect("writing to String is infallible"); } } else { write!(&mut opts, "{pos} ").expect("writing to String is infallible"); } } for (sc, _) in utils::subcommands(p) { write!(&mut opts, "{sc} ").expect("writing to String is infallible"); } opts.pop(); opts } clap_complete-4.5.40/src/aot/shells/elvish.rs000064400000000000000000000103251046102023000172320ustar 00000000000000use std::io::Write; use clap::builder::StyledStr; use clap::Command; use crate::generator::{utils, Generator}; use crate::INTERNAL_ERROR_MSG; /// Generate elvish completion file #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub struct Elvish; impl Generator for Elvish { fn file_name(&self, name: &str) -> String { format!("{name}.elv") } fn generate(&self, cmd: &Command, buf: &mut dyn Write) { let bin_name = cmd .get_bin_name() .expect("crate::generate should have set the bin_name"); let subcommands_cases = generate_inner(cmd, ""); write!( buf, r#" use builtin; use str; set edit:completion:arg-completer[{bin_name}] = {{|@words| fn spaces {{|n| builtin:repeat $n ' ' | str:join '' }} fn cand {{|text desc| edit:complex-candidate $text &display=$text' '(spaces (- 14 (wcswidth $text)))$desc }} var command = '{bin_name}' for word $words[1..-1] {{ if (str:has-prefix $word '-') {{ break }} set command = $command';'$word }} var completions = [{subcommands_cases} ] $completions[$command] }} "#, ) .expect("failed to write completion file"); } } // Escape string inside single quotes fn escape_string(string: &str) -> String { string.replace('\'', "''") } fn escape_help(help: Option<&StyledStr>, data: T) -> String { match help { Some(help) => escape_string(&help.to_string().replace('\n', " ")), _ => data.to_string(), } } fn generate_inner(p: &Command, previous_command_name: &str) -> String { debug!("generate_inner"); let command_names = if previous_command_name.is_empty() { vec![p.get_bin_name().expect(INTERNAL_ERROR_MSG).to_string()] } else { p.get_name_and_visible_aliases() .into_iter() .map(|name| format!("{previous_command_name};{name}")) .collect() }; let mut completions = String::new(); let preamble = String::from("\n cand "); for option in p.get_opts() { if let Some(shorts) = option.get_short_and_visible_aliases() { let tooltip = escape_help(option.get_help(), shorts[0]); for short in shorts { completions.push_str(&preamble); completions.push_str(format!("-{short} '{tooltip}'").as_str()); } } if let Some(longs) = option.get_long_and_visible_aliases() { let tooltip = escape_help(option.get_help(), longs[0]); for long in longs { completions.push_str(&preamble); completions.push_str(format!("--{long} '{tooltip}'").as_str()); } } } for flag in utils::flags(p) { if let Some(shorts) = flag.get_short_and_visible_aliases() { let tooltip = escape_help(flag.get_help(), shorts[0]); for short in shorts { completions.push_str(&preamble); completions.push_str(format!("-{short} '{tooltip}'").as_str()); } } if let Some(longs) = flag.get_long_and_visible_aliases() { let tooltip = escape_help(flag.get_help(), longs[0]); for long in longs { completions.push_str(&preamble); completions.push_str(format!("--{long} '{tooltip}'").as_str()); } } } for subcommand in p.get_subcommands() { for name in subcommand.get_name_and_visible_aliases() { let tooltip = escape_help(subcommand.get_about(), name); completions.push_str(&preamble); completions.push_str(format!("{name} '{tooltip}'").as_str()); } } let mut subcommands_cases = String::new(); for command_name in &command_names { subcommands_cases.push_str(&format!( r" &'{}'= {{{} }}", &command_name, completions )); } for subcommand in p.get_subcommands() { for command_name in &command_names { let subcommand_subcommands_cases = generate_inner(subcommand, command_name); subcommands_cases.push_str(&subcommand_subcommands_cases); } } subcommands_cases } clap_complete-4.5.40/src/aot/shells/fish.rs000064400000000000000000000253451046102023000167010ustar 00000000000000use std::io::Write; use clap::{builder, Arg, Command, ValueHint}; use crate::generator::{utils, Generator}; /// Generate fish completion file /// /// Note: The fish generator currently only supports named options (-o/--option), not positional arguments. #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub struct Fish; impl Generator for Fish { fn file_name(&self, name: &str) -> String { format!("{name}.fish") } fn generate(&self, cmd: &Command, buf: &mut dyn Write) { let bin_name = cmd .get_bin_name() .expect("crate::generate should have set the bin_name"); let name = escape_name(bin_name); let mut needs_fn_name = &format!("__fish_{name}_needs_command")[..]; let mut using_fn_name = &format!("__fish_{name}_using_subcommand")[..]; // Given `git --git-dir somedir status`, using `__fish_seen_subcommand_from` won't help us // find out `status` is the real subcommand, and not `somedir`. However, when there are no subcommands, // there is no need to use our custom stubs. if cmd.has_subcommands() { gen_subcommand_helpers(&name, cmd, buf, needs_fn_name, using_fn_name); } else { needs_fn_name = "__fish_use_subcommand"; using_fn_name = "__fish_seen_subcommand_from"; } let mut buffer = String::new(); gen_fish_inner( bin_name, &[], cmd, &mut buffer, needs_fn_name, using_fn_name, ); write!(buf, "{buffer}").expect("failed to write completion file"); } } // Escape string inside single quotes fn escape_string(string: &str, escape_comma: bool) -> String { let string = string.replace('\\', "\\\\").replace('\'', "\\'"); if escape_comma { string.replace(',', "\\,") } else { string } } fn escape_help(help: &builder::StyledStr) -> String { escape_string(&help.to_string().replace('\n', " "), false) } fn escape_name(name: &str) -> String { name.replace('-', "_") } fn gen_fish_inner( root_command: &str, parent_commands: &[&str], cmd: &Command, buffer: &mut String, needs_fn_name: &str, using_fn_name: &str, ) { debug!("gen_fish_inner"); // example : // // complete // -c {command} // -d "{description}" // -s {short} // -l {long} // -a "{possible_arguments}" // -r # if require parameter // -f # don't use file completion // -n "{needs_fn_name}" # complete for command "myprog" // -n "{using_fn_name} subcmd1" # complete for command "myprog subcmd1" let mut basic_template = format!("complete -c {root_command}"); if parent_commands.is_empty() { if cmd.has_subcommands() { basic_template.push_str(&format!(" -n \"{needs_fn_name}\"")); } } else { let mut out = String::from(using_fn_name); match parent_commands { [] => unreachable!(), [command] => { out.push_str(&format!(" {command}")); if cmd.has_subcommands() { out.push_str("; and not __fish_seen_subcommand_from"); } let subcommands = cmd .get_subcommands() .flat_map(Command::get_name_and_visible_aliases); for name in subcommands { out.push_str(&format!(" {name}")); } } [command, subcommand] => out.push_str(&format!( " {command}; and __fish_seen_subcommand_from {subcommand}" )), // HACK: Assuming subcommands are only nested less than 3 levels as more than that is // unwieldy and takes more effort to support. // For example, `rustup toolchain help install` is the longest valid command line of `rustup` // that uses nested subcommands, and it cannot receive any flags to it. _ => return, } basic_template.push_str(format!(" -n \"{out}\"").as_str()); } debug!("gen_fish_inner: parent_commands={parent_commands:?}"); for option in cmd.get_opts() { let mut template = basic_template.clone(); if let Some(shorts) = option.get_short_and_visible_aliases() { for short in shorts { template.push_str(format!(" -s {short}").as_str()); } } if let Some(longs) = option.get_long_and_visible_aliases() { for long in longs { template.push_str(format!(" -l {}", escape_string(long, false)).as_str()); } } if let Some(data) = option.get_help() { template.push_str(&format!(" -d '{}'", escape_help(data))); } template.push_str(value_completion(option).as_str()); buffer.push_str(template.as_str()); buffer.push('\n'); } for flag in utils::flags(cmd) { let mut template = basic_template.clone(); if let Some(shorts) = flag.get_short_and_visible_aliases() { for short in shorts { template.push_str(format!(" -s {short}").as_str()); } } if let Some(longs) = flag.get_long_and_visible_aliases() { for long in longs { template.push_str(format!(" -l {}", escape_string(long, false)).as_str()); } } if let Some(data) = flag.get_help() { template.push_str(&format!(" -d '{}'", escape_help(data))); } buffer.push_str(template.as_str()); buffer.push('\n'); } let has_positionals = cmd.get_positionals().next().is_some(); if !has_positionals { basic_template.push_str(" -f"); } for subcommand in cmd.get_subcommands() { for subcommand_name in subcommand.get_name_and_visible_aliases() { let mut template = basic_template.clone(); template.push_str(format!(" -a \"{subcommand_name}\"").as_str()); if let Some(data) = subcommand.get_about() { template.push_str(format!(" -d '{}'", escape_help(data)).as_str()); } buffer.push_str(template.as_str()); buffer.push('\n'); } } // generate options of subcommands for subcommand in cmd.get_subcommands() { for subcommand_name in subcommand.get_name_and_visible_aliases() { let mut parent_commands: Vec<_> = parent_commands.into(); parent_commands.push(subcommand_name); gen_fish_inner( root_command, &parent_commands, subcommand, buffer, needs_fn_name, using_fn_name, ); } } } /// Print fish's helpers for easy handling subcommands. fn gen_subcommand_helpers( bin_name: &str, cmd: &Command, buf: &mut dyn Write, needs_fn_name: &str, using_fn_name: &str, ) { let mut optspecs = String::new(); let cmd_opts = cmd.get_arguments().filter(|a| !a.is_positional()); for option in cmd_opts { optspecs.push(' '); let mut has_short = false; if let Some(short) = option.get_short() { has_short = true; optspecs.push(short); } if let Some(long) = option.get_long() { if has_short { optspecs.push('/'); } optspecs.push_str(&escape_string(long, false)); } let is_an_option = option .get_num_args() .map(|r| r.takes_values()) .unwrap_or(true); if is_an_option { optspecs.push('='); } } let optspecs_fn_name = format!("__fish_{bin_name}_global_optspecs"); write!( buf, "\ # Print an optspec for argparse to handle cmd's options that are independent of any subcommand.\n\ function {optspecs_fn_name}\n\ \tstring join \\n{optspecs}\n\ end\n\n\ function {needs_fn_name}\n\ \t# Figure out if the current invocation already has a command.\n\ \tset -l cmd (commandline -opc)\n\ \tset -e cmd[1]\n\ \targparse -s ({optspecs_fn_name}) -- $cmd 2>/dev/null\n\ \tor return\n\ \tif set -q argv[1]\n\ \t\t# Also print the command, so this can be used to figure out what it is.\n\ \t\techo $argv[1]\n\ \t\treturn 1\n\ \tend\n\ \treturn 0\n\ end\n\n\ function {using_fn_name}\n\ \tset -l cmd ({needs_fn_name})\n\ \ttest -z \"$cmd\"\n\ \tand return 1\n\ \tcontains -- $cmd[1] $argv\n\ end\n\n\ ").expect("failed to write completion file"); } fn value_completion(option: &Arg) -> String { if !option.get_num_args().expect("built").takes_values() { return "".to_string(); } if let Some(data) = utils::possible_values(option) { // We return the possible values with their own empty description e.g. {a\t,b\t} // this makes sure that a and b don't get the description of the option or argument format!( " -r -f -a \"{{{}}}\"", data.iter() .filter_map(|value| if value.is_hide_set() { None } else { // The help text after \t is wrapped in '' to make sure that the it is taken literally // and there is no command substitution or variable expansion resulting in unexpected errors Some(format!( "{}\\t'{}'", escape_string(value.get_name(), true).as_str(), escape_help(value.get_help().unwrap_or_default()) )) }) .collect::>() .join(",") ) } else { // NB! If you change this, please also update the table in `ValueHint` documentation. match option.get_value_hint() { ValueHint::Unknown => " -r", // fish has no built-in support to distinguish these ValueHint::AnyPath | ValueHint::FilePath | ValueHint::ExecutablePath => " -r -F", ValueHint::DirPath => " -r -f -a \"(__fish_complete_directories)\"", // It seems fish has no built-in support for completing command + arguments as // single string (CommandString). Complete just the command name. ValueHint::CommandString | ValueHint::CommandName => { " -r -f -a \"(__fish_complete_command)\"" } ValueHint::Username => " -r -f -a \"(__fish_complete_users)\"", ValueHint::Hostname => " -r -f -a \"(__fish_print_hostnames)\"", // Disable completion for others _ => " -r -f", } .to_string() } } clap_complete-4.5.40/src/aot/shells/mod.rs000064400000000000000000000003541046102023000165200ustar 00000000000000//! Shell-specific generators mod bash; mod elvish; mod fish; mod powershell; mod shell; mod zsh; pub use bash::Bash; pub use elvish::Elvish; pub use fish::Fish; pub use powershell::PowerShell; pub use shell::Shell; pub use zsh::Zsh; clap_complete-4.5.40/src/aot/shells/powershell.rs000064400000000000000000000110331046102023000201210ustar 00000000000000use std::io::Write; use clap::builder::StyledStr; use clap::{Arg, Command}; use crate::generator::{utils, Generator}; use crate::INTERNAL_ERROR_MSG; /// Generate powershell completion file #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub struct PowerShell; impl Generator for PowerShell { fn file_name(&self, name: &str) -> String { format!("_{name}.ps1") } fn generate(&self, cmd: &Command, buf: &mut dyn Write) { let bin_name = cmd .get_bin_name() .expect("crate::generate should have set the bin_name"); let subcommands_cases = generate_inner(cmd, ""); write!( buf, r#" using namespace System.Management.Automation using namespace System.Management.Automation.Language Register-ArgumentCompleter -Native -CommandName '{bin_name}' -ScriptBlock {{ param($wordToComplete, $commandAst, $cursorPosition) $commandElements = $commandAst.CommandElements $command = @( '{bin_name}' for ($i = 1; $i -lt $commandElements.Count; $i++) {{ $element = $commandElements[$i] if ($element -isnot [StringConstantExpressionAst] -or $element.StringConstantType -ne [StringConstantType]::BareWord -or $element.Value.StartsWith('-') -or $element.Value -eq $wordToComplete) {{ break }} $element.Value }}) -join ';' $completions = @(switch ($command) {{{subcommands_cases} }}) $completions.Where{{ $_.CompletionText -like "$wordToComplete*" }} | Sort-Object -Property ListItemText }} "# ) .expect("failed to write completion file"); } } // Escape string inside single quotes fn escape_string(string: &str) -> String { string.replace('\'', "''") } fn escape_help(help: Option<&StyledStr>, data: T) -> String { match help { Some(help) => escape_string(&help.to_string().replace('\n', " ")), _ => data.to_string(), } } fn generate_inner(p: &Command, previous_command_name: &str) -> String { debug!("generate_inner"); let command_names = if previous_command_name.is_empty() { vec![p.get_bin_name().expect(INTERNAL_ERROR_MSG).to_string()] } else { p.get_name_and_visible_aliases() .into_iter() .map(|name| format!("{previous_command_name};{name}")) .collect() }; let mut completions = String::new(); let preamble = String::from("\n [CompletionResult]::new("); for option in p.get_opts() { generate_aliases(&mut completions, &preamble, option); } for flag in utils::flags(p) { generate_aliases(&mut completions, &preamble, &flag); } for subcommand in p.get_subcommands() { for name in subcommand.get_name_and_visible_aliases() { let tooltip = escape_help(subcommand.get_about(), name); completions.push_str(&preamble); completions.push_str(&format!( "'{name}', '{name}', [CompletionResultType]::ParameterValue, '{tooltip}')" )); } } let mut subcommands_cases = String::new(); for command_name in &command_names { subcommands_cases.push_str(&format!( r" '{command_name}' {{{completions} break }}" )); } for subcommand in p.get_subcommands() { for command_name in &command_names { let subcommand_subcommands_cases = generate_inner(subcommand, command_name); subcommands_cases.push_str(&subcommand_subcommands_cases); } } subcommands_cases } fn generate_aliases(completions: &mut String, preamble: &String, arg: &Arg) { use std::fmt::Write as _; if let Some(aliases) = arg.get_short_and_visible_aliases() { let tooltip = escape_help(arg.get_help(), aliases[0]); for alias in aliases { let _ = write!( completions, "{preamble}'-{alias}', '-{alias}{}', [CompletionResultType]::ParameterName, '{tooltip}')", // make PowerShell realize there is a difference between `-s` and `-S` if alias.is_uppercase() { " " } else { "" }, ); } } if let Some(aliases) = arg.get_long_and_visible_aliases() { let tooltip = escape_help(arg.get_help(), aliases[0]); for alias in aliases { let _ = write!( completions, "{preamble}'--{alias}', '--{alias}', [CompletionResultType]::ParameterName, '{tooltip}')" ); } } } clap_complete-4.5.40/src/aot/shells/shell.rs000064400000000000000000000112321046102023000170450ustar 00000000000000use std::fmt::Display; use std::path::Path; use std::str::FromStr; use clap::builder::PossibleValue; use clap::ValueEnum; use crate::shells; use crate::Generator; /// Shell with auto-generated completion script available. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] #[non_exhaustive] pub enum Shell { /// Bourne Again `SHell` (bash) Bash, /// Elvish shell Elvish, /// Friendly Interactive `SHell` (fish) Fish, /// `PowerShell` PowerShell, /// Z `SHell` (zsh) Zsh, } impl Display for Shell { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.to_possible_value() .expect("no values are skipped") .get_name() .fmt(f) } } impl FromStr for Shell { type Err = String; fn from_str(s: &str) -> Result { for variant in Self::value_variants() { if variant.to_possible_value().unwrap().matches(s, false) { return Ok(*variant); } } Err(format!("invalid variant: {s}")) } } // Hand-rolled so it can work even when `derive` feature is disabled impl ValueEnum for Shell { fn value_variants<'a>() -> &'a [Self] { &[ Shell::Bash, Shell::Elvish, Shell::Fish, Shell::PowerShell, Shell::Zsh, ] } fn to_possible_value(&self) -> Option { Some(match self { Shell::Bash => PossibleValue::new("bash"), Shell::Elvish => PossibleValue::new("elvish"), Shell::Fish => PossibleValue::new("fish"), Shell::PowerShell => PossibleValue::new("powershell"), Shell::Zsh => PossibleValue::new("zsh"), }) } } impl Generator for Shell { fn file_name(&self, name: &str) -> String { match self { Shell::Bash => shells::Bash.file_name(name), Shell::Elvish => shells::Elvish.file_name(name), Shell::Fish => shells::Fish.file_name(name), Shell::PowerShell => shells::PowerShell.file_name(name), Shell::Zsh => shells::Zsh.file_name(name), } } fn generate(&self, cmd: &clap::Command, buf: &mut dyn std::io::Write) { match self { Shell::Bash => shells::Bash.generate(cmd, buf), Shell::Elvish => shells::Elvish.generate(cmd, buf), Shell::Fish => shells::Fish.generate(cmd, buf), Shell::PowerShell => shells::PowerShell.generate(cmd, buf), Shell::Zsh => shells::Zsh.generate(cmd, buf), } } } impl Shell { /// Parse a shell from a path to the executable for the shell /// /// # Examples /// /// ``` /// use clap_complete::shells::Shell; /// /// assert_eq!(Shell::from_shell_path("/bin/bash"), Some(Shell::Bash)); /// assert_eq!(Shell::from_shell_path("/usr/bin/zsh"), Some(Shell::Zsh)); /// assert_eq!(Shell::from_shell_path("/opt/my_custom_shell"), None); /// ``` pub fn from_shell_path>(path: P) -> Option { parse_shell_from_path(path.as_ref()) } /// Determine the user's current shell from the environment /// /// This will read the SHELL environment variable and try to determine which shell is in use /// from that. /// /// If SHELL is not set, then on windows, it will default to powershell, and on /// other operating systems it will return `None`. /// /// If SHELL is set, but contains a value that doesn't correspond to one of the supported shell /// types, then return `None`. /// /// # Example: /// /// ```no_run /// # use clap::Command; /// use clap_complete::{generate, shells::Shell}; /// # fn build_cli() -> Command { /// # Command::new("compl") /// # } /// let mut cmd = build_cli(); /// generate(Shell::from_env().unwrap_or(Shell::Bash), &mut cmd, "myapp", &mut std::io::stdout()); /// ``` pub fn from_env() -> Option { if let Some(env_shell) = std::env::var_os("SHELL") { Shell::from_shell_path(env_shell) } else if cfg!(windows) { Some(Shell::PowerShell) } else { None } } } // use a separate function to avoid having to monomorphize the entire function due // to from_shell_path being generic fn parse_shell_from_path(path: &Path) -> Option { let name = path.file_stem()?.to_str()?; match name { "bash" => Some(Shell::Bash), "zsh" => Some(Shell::Zsh), "fish" => Some(Shell::Fish), "elvish" => Some(Shell::Elvish), "powershell" | "powershell_ise" => Some(Shell::PowerShell), _ => None, } } clap_complete-4.5.40/src/aot/shells/zsh.rs000064400000000000000000000520501046102023000165450ustar 00000000000000use std::io::Write; use clap::{Arg, ArgAction, Command, ValueHint}; use crate::generator::{utils, Generator}; use crate::INTERNAL_ERROR_MSG; /// Generate zsh completion file #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub struct Zsh; impl Generator for Zsh { fn file_name(&self, name: &str) -> String { format!("_{name}") } fn generate(&self, cmd: &Command, buf: &mut dyn Write) { let bin_name = cmd .get_bin_name() .expect("crate::generate should have set the bin_name"); write!( buf, "#compdef {name} autoload -U is-at-least _{name}() {{ typeset -A opt_args typeset -a _arguments_options local ret=1 if is-at-least 5.2; then _arguments_options=(-s -S -C) else _arguments_options=(-s -C) fi local context curcontext=\"$curcontext\" state line {initial_args}{subcommands} }} {subcommand_details} if [ \"$funcstack[1]\" = \"_{name}\" ]; then _{name} \"$@\" else compdef _{name} {name} fi ", name = bin_name, initial_args = get_args_of(cmd, None), subcommands = get_subcommands_of(cmd), subcommand_details = subcommand_details(cmd) ) .expect("failed to write completion file"); } } // Displays the commands of a subcommand // (( $+functions[_[bin_name_underscore]_commands] )) || // _[bin_name_underscore]_commands() { // local commands; commands=( // '[arg_name]:[arg_help]' // ) // _describe -t commands '[bin_name] commands' commands "$@" // // Where the following variables are present: // [bin_name_underscore]: The full space delineated bin_name, where spaces have been replaced by // underscore characters // [arg_name]: The name of the subcommand // [arg_help]: The help message of the subcommand // [bin_name]: The full space delineated bin_name // // Here's a snippet from rustup: // // (( $+functions[_rustup_commands] )) || // _rustup_commands() { // local commands; commands=( // 'show:Show the active and installed toolchains' // 'update:Update Rust toolchains' // # ... snip for brevity // 'help:Print this message or the help of the given subcommand(s)' // ) // _describe -t commands 'rustup commands' commands "$@" // fn subcommand_details(p: &Command) -> String { debug!("subcommand_details"); let bin_name = p .get_bin_name() .expect("crate::generate should have set the bin_name"); let mut ret = vec![]; // First we do ourself let parent_text = format!( "\ (( $+functions[_{bin_name_underscore}_commands] )) || _{bin_name_underscore}_commands() {{ local commands; commands=({subcommands_and_args}) _describe -t commands '{bin_name} commands' commands \"$@\" }}", bin_name_underscore = bin_name.replace(' ', "__"), bin_name = bin_name, subcommands_and_args = subcommands_of(p) ); ret.push(parent_text); // Next we start looping through all the children, grandchildren, etc. let mut all_subcommand_bins: Vec<_> = utils::all_subcommands(p) .into_iter() .map(|(_sc_name, bin_name)| bin_name) .collect(); all_subcommand_bins.sort(); all_subcommand_bins.dedup(); for bin_name in &all_subcommand_bins { debug!("subcommand_details:iter: bin_name={bin_name}"); ret.push(format!( "\ (( $+functions[_{bin_name_underscore}_commands] )) || _{bin_name_underscore}_commands() {{ local commands; commands=({subcommands_and_args}) _describe -t commands '{bin_name} commands' commands \"$@\" }}", bin_name_underscore = bin_name.replace(' ', "__"), bin_name = bin_name, subcommands_and_args = subcommands_of(parser_of(p, bin_name).expect(INTERNAL_ERROR_MSG)) )); } ret.join("\n") } // Generates subcommand completions in form of // // '[arg_name]:[arg_help]' // // Where: // [arg_name]: the subcommand's name // [arg_help]: the help message of the subcommand // // A snippet from rustup: // 'show:Show the active and installed toolchains' // 'update:Update Rust toolchains' fn subcommands_of(p: &Command) -> String { debug!("subcommands_of"); let mut segments = vec![]; fn add_subcommands(subcommand: &Command, name: &str, ret: &mut Vec) { debug!("add_subcommands"); let text = format!( "'{name}:{help}' \\", name = name, help = escape_help(&subcommand.get_about().unwrap_or_default().to_string()) ); ret.push(text); } // The subcommands for command in p.get_subcommands() { debug!("subcommands_of:iter: subcommand={}", command.get_name()); add_subcommands(command, command.get_name(), &mut segments); for alias in command.get_visible_aliases() { add_subcommands(command, alias, &mut segments); } } // Surround the text with newlines for proper formatting. // We need this to prevent weirdly formatted `command=(\n \n)` sections. // When there are no (sub-)commands. if !segments.is_empty() { segments.insert(0, "".to_string()); segments.push(" ".to_string()); } segments.join("\n") } // Get's the subcommand section of a completion file // This looks roughly like: // // case $state in // ([bin_name]_args) // curcontext=\"${curcontext%:*:*}:[name_hyphen]-command-$words[1]:\" // case $line[1] in // // ([name]) // _arguments -C -s -S \ // [subcommand_args] // && ret=0 // // [RECURSIVE_CALLS] // // ;;", // // [repeat] // // esac // ;; // esac", // // Where the following variables are present: // [name] = The subcommand name in the form of "install" for "rustup toolchain install" // [bin_name] = The full space delineated bin_name such as "rustup toolchain install" // [name_hyphen] = The full space delineated bin_name, but replace spaces with hyphens // [repeat] = From the same recursive calls, but for all subcommands // [subcommand_args] = The same as zsh::get_args_of fn get_subcommands_of(parent: &Command) -> String { debug!( "get_subcommands_of: Has subcommands...{:?}", parent.has_subcommands() ); if !parent.has_subcommands() { return String::new(); } let subcommand_names = utils::subcommands(parent); let mut all_subcommands = vec![]; for (ref name, ref bin_name) in &subcommand_names { debug!( "get_subcommands_of:iter: parent={}, name={name}, bin_name={bin_name}", parent.get_name(), ); let mut segments = vec![format!("({name})")]; let subcommand_args = get_args_of( parser_of(parent, bin_name).expect(INTERNAL_ERROR_MSG), Some(parent), ); if !subcommand_args.is_empty() { segments.push(subcommand_args); } // Get the help text of all child subcommands. let children = get_subcommands_of(parser_of(parent, bin_name).expect(INTERNAL_ERROR_MSG)); if !children.is_empty() { segments.push(children); } segments.push(String::from(";;")); all_subcommands.push(segments.join("\n")); } let parent_bin_name = parent .get_bin_name() .expect("crate::generate should have set the bin_name"); format!( " case $state in ({name}) words=($line[{pos}] \"${{words[@]}}\") (( CURRENT += 1 )) curcontext=\"${{curcontext%:*:*}}:{name_hyphen}-command-$line[{pos}]:\" case $line[{pos}] in {subcommands} esac ;; esac", name = parent.get_name(), name_hyphen = parent_bin_name.replace(' ', "-"), subcommands = all_subcommands.join("\n"), pos = parent.get_positionals().count() + 1 ) } // Get the Command for a given subcommand tree. // // Given the bin_name "a b c" and the Command for "a" this returns the "c" Command. // Given the bin_name "a b c" and the Command for "b" this returns the "c" Command. fn parser_of<'cmd>(parent: &'cmd Command, bin_name: &str) -> Option<&'cmd Command> { debug!("parser_of: p={}, bin_name={}", parent.get_name(), bin_name); if bin_name == parent.get_bin_name().unwrap_or_default() { return Some(parent); } for subcommand in parent.get_subcommands() { if let Some(ret) = parser_of(subcommand, bin_name) { return Some(ret); } } None } // Writes out the args section, which ends up being the flags, opts and positionals, and a jump to // another ZSH function if there are subcommands. // The structure works like this: // ([conflicting_args]) [multiple] arg [takes_value] [[help]] [: :(possible_values)] // ^-- list '-v -h' ^--'*' ^--'+' ^-- list 'one two three' // // An example from the rustup command: // // _arguments -C -s -S \ // '(-h --help --verbose)-v[Enable verbose output]' \ // '(-V -v --version --verbose --help)-h[Print help information]' \ // # ... snip for brevity // ':: :_rustup_commands' \ # <-- displays subcommands // '*::: :->rustup' \ # <-- displays subcommand args and child subcommands // && ret=0 // // The args used for _arguments are as follows: // -C: modify the $context internal variable // -s: Allow stacking of short args (i.e. -a -b -c => -abc) // -S: Do not complete anything after '--' and treat those as argument values fn get_args_of(parent: &Command, p_global: Option<&Command>) -> String { debug!("get_args_of"); let mut segments = vec![String::from("_arguments \"${_arguments_options[@]}\" : \\")]; let opts = write_opts_of(parent, p_global); let flags = write_flags_of(parent, p_global); let positionals = write_positionals_of(parent); if !opts.is_empty() { segments.push(opts); } if !flags.is_empty() { segments.push(flags); } if !positionals.is_empty() { segments.push(positionals); } if parent.has_subcommands() { let parent_bin_name = parent .get_bin_name() .expect("crate::generate should have set the bin_name"); let subcommand_bin_name = format!( "\":: :_{name}_commands\" \\", name = parent_bin_name.replace(' ', "__") ); segments.push(subcommand_bin_name); let subcommand_text = format!("\"*::: :->{name}\" \\", name = parent.get_name()); segments.push(subcommand_text); }; segments.push(String::from("&& ret=0")); segments.join("\n") } // Uses either `possible_vals` or `value_hint` to give hints about possible argument values fn value_completion(arg: &Arg) -> Option { if let Some(values) = utils::possible_values(arg) { if values .iter() .any(|value| !value.is_hide_set() && value.get_help().is_some()) { Some(format!( "(({}))", values .iter() .filter_map(|value| { if value.is_hide_set() { None } else { Some(format!( r#"{name}\:"{tooltip}""#, name = escape_value(value.get_name()), tooltip = escape_help(&value.get_help().unwrap_or_default().to_string()), )) } }) .collect::>() .join("\n") )) } else { Some(format!( "({})", values .iter() .filter(|pv| !pv.is_hide_set()) .map(|n| n.get_name()) .collect::>() .join(" ") )) } } else { // NB! If you change this, please also update the table in `ValueHint` documentation. Some( match arg.get_value_hint() { ValueHint::Unknown => "_default", ValueHint::Other => "", ValueHint::AnyPath => "_files", ValueHint::FilePath => "_files", ValueHint::DirPath => "_files -/", ValueHint::ExecutablePath => "_absolute_command_paths", ValueHint::CommandName => "_command_names -e", ValueHint::CommandString => "_cmdstring", ValueHint::CommandWithArguments => "_cmdambivalent", ValueHint::Username => "_users", ValueHint::Hostname => "_hosts", ValueHint::Url => "_urls", ValueHint::EmailAddress => "_email_addresses", _ => { return None; } } .to_string(), ) } } /// Escape help string inside single quotes and brackets fn escape_help(string: &str) -> String { string .replace('\\', "\\\\") .replace('\'', "'\\''") .replace('[', "\\[") .replace(']', "\\]") .replace(':', "\\:") .replace('$', "\\$") .replace('`', "\\`") .replace('\n', " ") } /// Escape value string inside single quotes and parentheses fn escape_value(string: &str) -> String { string .replace('\\', "\\\\") .replace('\'', "'\\''") .replace('[', "\\[") .replace(']', "\\]") .replace(':', "\\:") .replace('$', "\\$") .replace('`', "\\`") .replace('(', "\\(") .replace(')', "\\)") .replace(' ', "\\ ") } fn write_opts_of(p: &Command, p_global: Option<&Command>) -> String { debug!("write_opts_of"); let mut ret = vec![]; for o in p.get_opts() { debug!("write_opts_of:iter: o={}", o.get_id()); let help = escape_help(&o.get_help().unwrap_or_default().to_string()); let conflicts = arg_conflicts(p, o, p_global); let multiple = if let ArgAction::Count | ArgAction::Append = o.get_action() { "*" } else { "" }; let vn = match o.get_value_names() { None => " ".to_string(), Some(val) => val[0].to_string(), }; let vc = match value_completion(o) { Some(val) => format!(":{vn}:{val}"), None => format!(":{vn}: "), }; let vc = vc.repeat(o.get_num_args().expect("built").min_values()); if let Some(shorts) = o.get_short_and_visible_aliases() { for short in shorts { let s = format!("'{conflicts}{multiple}-{short}+[{help}]{vc}' \\"); debug!("write_opts_of:iter: Wrote...{}", &*s); ret.push(s); } } if let Some(longs) = o.get_long_and_visible_aliases() { for long in longs { let l = format!("'{conflicts}{multiple}--{long}=[{help}]{vc}' \\"); debug!("write_opts_of:iter: Wrote...{}", &*l); ret.push(l); } } } ret.join("\n") } fn arg_conflicts(cmd: &Command, arg: &Arg, app_global: Option<&Command>) -> String { fn push_conflicts(conflicts: &[&Arg], res: &mut Vec) { for conflict in conflicts { if let Some(s) = conflict.get_short() { res.push(format!("-{s}")); } if let Some(l) = conflict.get_long() { res.push(format!("--{l}")); } } } let mut res = vec![]; match (app_global, arg.is_global_set()) { (Some(x), true) => { let conflicts = x.get_arg_conflicts_with(arg); if conflicts.is_empty() { return String::new(); } push_conflicts(&conflicts, &mut res); } (_, _) => { let conflicts = cmd.get_arg_conflicts_with(arg); if conflicts.is_empty() { return String::new(); } push_conflicts(&conflicts, &mut res); } }; format!("({})", res.join(" ")) } fn write_flags_of(p: &Command, p_global: Option<&Command>) -> String { debug!("write_flags_of;"); let mut ret = vec![]; for f in utils::flags(p) { debug!("write_flags_of:iter: f={}", f.get_id()); let help = escape_help(&f.get_help().unwrap_or_default().to_string()); let conflicts = arg_conflicts(p, &f, p_global); let multiple = if let ArgAction::Count | ArgAction::Append = f.get_action() { "*" } else { "" }; if let Some(short) = f.get_short() { let s = format!("'{conflicts}{multiple}-{short}[{help}]' \\"); debug!("write_flags_of:iter: Wrote...{}", &*s); ret.push(s); if let Some(short_aliases) = f.get_visible_short_aliases() { for alias in short_aliases { let s = format!("'{conflicts}{multiple}-{alias}[{help}]' \\",); debug!("write_flags_of:iter: Wrote...{}", &*s); ret.push(s); } } } if let Some(long) = f.get_long() { let l = format!("'{conflicts}{multiple}--{long}[{help}]' \\"); debug!("write_flags_of:iter: Wrote...{}", &*l); ret.push(l); if let Some(aliases) = f.get_visible_aliases() { for alias in aliases { let l = format!("'{conflicts}{multiple}--{alias}[{help}]' \\"); debug!("write_flags_of:iter: Wrote...{}", &*l); ret.push(l); } } } } ret.join("\n") } fn write_positionals_of(p: &Command) -> String { debug!("write_positionals_of;"); let mut ret = vec![]; // Completions for commands that end with two Vec arguments require special care. // - You can have two Vec args separated with a custom value terminator. // - You can have two Vec args with the second one set to last (raw sets last) // which will require a '--' separator to be used before the second argument // on the command-line. // // We use the '-S' _arguments option to disable completion after '--'. Thus, the // completion for the second argument in scenario (B) does not need to be emitted // because it is implicitly handled by the '-S' option. // We only need to emit the first catch-all. // // Have we already emitted a catch-all multi-valued positional argument // without a custom value terminator? let mut catch_all_emitted = false; for arg in p.get_positionals() { debug!("write_positionals_of:iter: arg={}", arg.get_id()); let num_args = arg.get_num_args().expect("built"); let is_multi_valued = num_args.max_values() > 1; if catch_all_emitted && (arg.is_last_set() || is_multi_valued) { // This is the final argument and it also takes multiple arguments. // We've already emitted a catch-all positional argument so we don't need // to emit anything for this argument because it is implicitly handled by // the use of the '-S' _arguments option. continue; } let cardinality_value; // If we have any subcommands, we'll emit a catch-all argument, so we shouldn't // emit one here. let cardinality = if is_multi_valued && !p.has_subcommands() { match arg.get_value_terminator() { Some(terminator) => { cardinality_value = format!("*{}:", escape_value(terminator)); cardinality_value.as_str() } None => { catch_all_emitted = true; "*:" } } } else if !arg.is_required_set() { ":" } else { "" }; let a = format!( "'{cardinality}:{name}{help}:{value_completion}' \\", cardinality = cardinality, name = arg.get_id(), help = arg .get_help() .map(|s| s.to_string()) .map(|v| " -- ".to_owned() + &v) .unwrap_or_else(|| "".to_owned()) .replace('[', "\\[") .replace(']', "\\]") .replace('\'', "'\\''") .replace(':', "\\:"), value_completion = value_completion(arg).unwrap_or_default() ); debug!("write_positionals_of:iter: Wrote...{a}"); ret.push(a); } ret.join("\n") } #[cfg(test)] mod tests { use super::{escape_help, escape_value}; #[test] fn test_escape_value() { let raw_string = "\\ [foo]() `bar https://$PATH"; assert_eq!( escape_value(raw_string), "\\\\\\ \\[foo\\]\\(\\)\\ \\`bar\\ https\\://\\$PATH" ); } #[test] fn test_escape_help() { let raw_string = "\\ [foo]() `bar https://$PATH"; assert_eq!( escape_help(raw_string), "\\\\ \\[foo\\]() \\`bar https\\://\\$PATH" ); } } clap_complete-4.5.40/src/engine/candidate.rs000064400000000000000000000057051046102023000170520ustar 00000000000000use std::ffi::OsStr; use std::ffi::OsString; use clap::builder::StyledStr; /// A shell-agnostic completion candidate #[derive(Default, Debug, PartialEq, Eq, PartialOrd, Ord)] pub struct CompletionCandidate { value: OsString, help: Option, id: Option, tag: Option, display_order: Option, hidden: bool, } impl CompletionCandidate { /// Create a new completion candidate pub fn new(value: impl Into) -> Self { let value = value.into(); Self { value, ..Default::default() } } /// Set the help message of the completion candidate pub fn help(mut self, help: Option) -> Self { self.help = help; self } /// Only first for a given Id is shown /// /// To reduce the risk of conflicts, this should likely contain a namespace. pub fn id(mut self, id: Option) -> Self { self.id = id; self } /// Group candidates by tag /// /// Future: these may become user-visible pub fn tag(mut self, tag: Option) -> Self { self.tag = tag; self } /// Sort weight within a [`CompletionCandidate::tag`] pub fn display_order(mut self, order: Option) -> Self { self.display_order = order; self } /// Set the visibility of the completion candidate /// /// Only shown when there is no visible candidate for completing the current argument. pub fn hide(mut self, hidden: bool) -> Self { self.hidden = hidden; self } /// Add a prefix to the value of completion candidate /// /// This is generally used for post-process by [`complete`][crate::engine::complete()] for /// things like pre-pending flags, merging delimiter-separated values, etc. pub fn add_prefix(mut self, prefix: impl Into) -> Self { let suffix = self.value; let mut value = prefix.into(); value.push(&suffix); self.value = value; self } } /// Reflection API impl CompletionCandidate { /// Get the literal value being proposed for completion pub fn get_value(&self) -> &OsStr { &self.value } /// Get the help message of the completion candidate pub fn get_help(&self) -> Option<&StyledStr> { self.help.as_ref() } /// Get the id used for de-duplicating pub fn get_id(&self) -> Option<&String> { self.id.as_ref() } /// Get the grouping tag pub fn get_tag(&self) -> Option<&StyledStr> { self.tag.as_ref() } /// Get the grouping tag pub fn get_display_order(&self) -> Option { self.display_order } /// Get the visibility of the completion candidate pub fn is_hide_set(&self) -> bool { self.hidden } } impl> From for CompletionCandidate { fn from(s: S) -> Self { CompletionCandidate::new(s.into()) } } clap_complete-4.5.40/src/engine/complete.rs000064400000000000000000000571731046102023000167540ustar 00000000000000use std::ffi::OsStr; use std::ffi::OsString; use clap_lex::OsStrExt as _; use super::custom::complete_path; use super::ArgValueCandidates; use super::ArgValueCompleter; use super::CompletionCandidate; use super::SubcommandCandidates; /// Complete the given command, shell-agnostic pub fn complete( cmd: &mut clap::Command, args: Vec, arg_index: usize, current_dir: Option<&std::path::Path>, ) -> Result, std::io::Error> { debug!("complete: args={args:?}, arg_index={arg_index:?}, current_dir={current_dir:?}"); cmd.build(); let raw_args = clap_lex::RawArgs::new(args); let mut cursor = raw_args.cursor(); let mut target_cursor = raw_args.cursor(); raw_args.seek( &mut target_cursor, clap_lex::SeekFrom::Start(arg_index as u64), ); // As we loop, `cursor` will always be pointing to the next item raw_args.next_os(&mut target_cursor); debug!("complete: target_cursor={target_cursor:?}"); // TODO: Multicall support if !cmd.is_no_binary_name_set() { raw_args.next_os(&mut cursor); } let mut current_cmd = &*cmd; let mut pos_index = 1; let mut is_escaped = false; let mut next_state = ParseState::ValueDone; while let Some(arg) = raw_args.next(&mut cursor) { let current_state = next_state; next_state = ParseState::ValueDone; debug!( "complete::next: arg={:?}, current_state={current_state:?}, cursor={cursor:?}", arg.to_value_os(), ); if cursor == target_cursor { return complete_arg(&arg, current_cmd, current_dir, pos_index, current_state); } if let Ok(value) = arg.to_value() { if let Some(next_cmd) = current_cmd.find_subcommand(value) { current_cmd = next_cmd; pos_index = 1; continue; } } if is_escaped { (next_state, pos_index) = parse_positional(current_cmd, pos_index, is_escaped, current_state); } else if arg.is_escape() { is_escaped = true; } else if opt_allows_hyphen(¤t_state, &arg) { match current_state { ParseState::Opt((opt, count)) => next_state = parse_opt_value(opt, count), _ => unreachable!("else branch is only reachable in Opt state"), } } else if let Some((flag, value)) = arg.to_long() { if let Ok(flag) = flag { let opt = current_cmd.get_arguments().find(|a| { let longs = a.get_long_and_visible_aliases(); let is_find = longs.map(|v| { let mut iter = v.into_iter(); let s = iter.find(|s| *s == flag); s.is_some() }); is_find.unwrap_or(false) }); if let Some(opt) = opt { if opt.get_action().takes_values() && value.is_none() { next_state = ParseState::Opt((opt, 1)); }; } else if pos_allows_hyphen(current_cmd, pos_index) { (next_state, pos_index) = parse_positional(current_cmd, pos_index, is_escaped, current_state); } } } else if let Some(short) = arg.to_short() { let (_, takes_value_opt, mut short) = parse_shortflags(current_cmd, short); if let Some(opt) = takes_value_opt { if short.next_value_os().is_none() { next_state = ParseState::Opt((opt, 1)); } } else if pos_allows_hyphen(current_cmd, pos_index) { (next_state, pos_index) = parse_positional(current_cmd, pos_index, is_escaped, current_state); } } else { match current_state { ParseState::ValueDone | ParseState::Pos(..) => { (next_state, pos_index) = parse_positional(current_cmd, pos_index, is_escaped, current_state); } ParseState::Opt((opt, count)) => next_state = parse_opt_value(opt, count), } } } Err(std::io::Error::new( std::io::ErrorKind::Other, "no completion generated", )) } #[derive(Debug, PartialEq, Eq, Clone)] enum ParseState<'a> { /// Parsing a value done, there is no state to record. ValueDone, /// Parsing a positional argument after `--`. `Pos(pos_index`, `takes_num_args`) Pos((usize, usize)), /// Parsing a optional flag argument Opt((&'a clap::Arg, usize)), } fn complete_arg( arg: &clap_lex::ParsedArg<'_>, cmd: &clap::Command, current_dir: Option<&std::path::Path>, pos_index: usize, state: ParseState<'_>, ) -> Result, std::io::Error> { debug!( "complete_arg: arg={:?}, cmd={:?}, current_dir={:?}, pos_index={:?}, state={:?}", arg, cmd.get_name(), current_dir, pos_index, state ); let mut completions = Vec::::new(); match state { ParseState::ValueDone => { if let Ok(value) = arg.to_value() { completions.extend(complete_subcommand(value, cmd)); } if let Some(positional) = cmd .get_positionals() .find(|p| p.get_index() == Some(pos_index)) { completions.extend(complete_arg_value(arg.to_value(), positional, current_dir)); } if arg.is_empty() { completions.extend(longs_and_visible_aliases(cmd)); completions.extend(hidden_longs_aliases(cmd)); let dash_or_arg = if arg.is_empty() { "-".into() } else { arg.to_value_os().to_string_lossy() }; completions.extend( shorts_and_visible_aliases(cmd) .into_iter() .map(|comp| comp.add_prefix(dash_or_arg.to_string())), ); } else if arg.is_stdio() { // HACK: Assuming knowledge of is_stdio let dash_or_arg = if arg.is_empty() { "-".into() } else { arg.to_value_os().to_string_lossy() }; completions.extend( shorts_and_visible_aliases(cmd) .into_iter() .map(|comp| comp.add_prefix(dash_or_arg.to_string())), ); completions.extend(longs_and_visible_aliases(cmd)); completions.extend(hidden_longs_aliases(cmd)); } else if arg.is_escape() { // HACK: Assuming knowledge of is_escape completions.extend(longs_and_visible_aliases(cmd)); completions.extend(hidden_longs_aliases(cmd)); } else if let Some((flag, value)) = arg.to_long() { if let Ok(flag) = flag { if let Some(value) = value { if let Some(arg) = cmd.get_arguments().find(|a| a.get_long() == Some(flag)) { completions.extend( complete_arg_value(value.to_str().ok_or(value), arg, current_dir) .into_iter() .map(|comp| comp.add_prefix(format!("--{flag}="))), ); } } else { completions.extend(longs_and_visible_aliases(cmd).into_iter().filter( |comp| comp.get_value().starts_with(format!("--{flag}").as_str()), )); completions.extend(hidden_longs_aliases(cmd).into_iter().filter(|comp| { comp.get_value().starts_with(format!("--{flag}").as_str()) })); } } } else if let Some(short) = arg.to_short() { if !short.is_negative_number() { // Find the first takes_values option. let (leading_flags, takes_value_opt, mut short) = parse_shortflags(cmd, short); // Clone `short` to `peek_short` to peek whether the next flag is a `=`. if let Some(opt) = takes_value_opt { let mut peek_short = short.clone(); let has_equal = if let Some(Ok('=')) = peek_short.next_flag() { short.next_flag(); true } else { false }; let value = short.next_value_os().unwrap_or(OsStr::new("")); completions.extend( complete_arg_value(value.to_str().ok_or(value), opt, current_dir) .into_iter() .map(|comp| { let sep = if has_equal { "=" } else { "" }; comp.add_prefix(format!("-{leading_flags}{sep}")) }), ); } else { completions.extend( shorts_and_visible_aliases(cmd) .into_iter() .map(|comp| comp.add_prefix(format!("-{leading_flags}"))), ); } } } } ParseState::Pos(..) => { if let Some(positional) = cmd .get_positionals() .find(|p| p.get_index() == Some(pos_index)) { completions.extend(complete_arg_value(arg.to_value(), positional, current_dir)); } } ParseState::Opt((opt, count)) => { completions.extend(complete_arg_value(arg.to_value(), opt, current_dir)); let min = opt.get_num_args().map(|r| r.min_values()).unwrap_or(0); if count > min { // Also complete this raw_arg as a positional argument, flags, options and subcommand. completions.extend(complete_arg( arg, cmd, current_dir, pos_index, ParseState::ValueDone, )?); } } } if completions.iter().any(|a| !a.is_hide_set()) { completions.retain(|a| !a.is_hide_set()); } let mut seen_ids = std::collections::HashSet::new(); completions.retain(move |a| { if let Some(id) = a.get_id().cloned() { seen_ids.insert(id) } else { true } }); let mut tags = Vec::new(); for candidate in &completions { let tag = candidate.get_tag().cloned(); if !tags.contains(&tag) { tags.push(tag); } } completions.sort_by_key(|c| { ( tags.iter().position(|t| c.get_tag() == t.as_ref()), c.get_display_order(), ) }); Ok(completions) } fn complete_arg_value( value: Result<&str, &OsStr>, arg: &clap::Arg, current_dir: Option<&std::path::Path>, ) -> Vec { let mut values = Vec::new(); debug!("complete_arg_value: arg={arg:?}, value={value:?}"); let (prefix, value) = rsplit_delimiter(value, arg.get_value_delimiter()).unwrap_or((None, value)); let value_os = match value { Ok(value) => OsStr::new(value), Err(value_os) => value_os, }; if let Some(completer) = arg.get::() { values.extend(completer.complete(value_os)); } else if let Some(completer) = arg.get::() { values.extend(complete_custom_arg_value(value_os, completer)); } else if let Some(possible_values) = possible_values(arg) { if let Ok(value) = value { values.extend(possible_values.into_iter().filter_map(|p| { let name = p.get_name(); name.starts_with(value).then(|| { CompletionCandidate::new(OsString::from(name)) .help(p.get_help().cloned()) .hide(p.is_hide_set()) }) })); } } else { match arg.get_value_hint() { clap::ValueHint::Unknown | clap::ValueHint::Other => { // Should not complete } clap::ValueHint::AnyPath => { values.extend(complete_path(value_os, current_dir, &|_| true)); } clap::ValueHint::FilePath => { values.extend(complete_path(value_os, current_dir, &|p| p.is_file())); } clap::ValueHint::DirPath => { values.extend(complete_path(value_os, current_dir, &|p| p.is_dir())); } clap::ValueHint::ExecutablePath => { use is_executable::IsExecutable; values.extend(complete_path(value_os, current_dir, &|p| p.is_executable())); } clap::ValueHint::CommandName | clap::ValueHint::CommandString | clap::ValueHint::CommandWithArguments | clap::ValueHint::Username | clap::ValueHint::Hostname | clap::ValueHint::Url | clap::ValueHint::EmailAddress => { // No completion implementation } _ => { // Safe-ish fallback values.extend(complete_path(value_os, current_dir, &|_| true)); } } values.sort(); } if let Some(prefix) = prefix { values = values .into_iter() .map(|comp| comp.add_prefix(prefix)) .collect(); } values = values .into_iter() .map(|comp| { if comp.get_tag().is_some() { comp } else { comp.tag(Some(arg.to_string().into())) } }) .collect(); values } fn rsplit_delimiter<'s, 'o>( value: Result<&'s str, &'o OsStr>, delimiter: Option, ) -> Option<(Option<&'s str>, Result<&'s str, &'o OsStr>)> { let delimiter = delimiter?; let value = value.ok()?; let pos = value.rfind(delimiter)?; let (prefix, value) = value.split_at(pos + delimiter.len_utf8()); Some((Some(prefix), Ok(value))) } fn complete_custom_arg_value( value: &OsStr, completer: &ArgValueCandidates, ) -> Vec { debug!("complete_custom_arg_value: completer={completer:?}, value={value:?}"); let mut values = completer.candidates(); values.retain(|comp| comp.get_value().starts_with(&value.to_string_lossy())); values } fn complete_subcommand(value: &str, cmd: &clap::Command) -> Vec { debug!( "complete_subcommand: cmd={:?}, value={:?}", cmd.get_name(), value ); let mut scs: Vec = subcommands(cmd) .into_iter() .filter(|x| x.get_value().starts_with(value)) .collect(); if cmd.is_allow_external_subcommands_set() { let external_completer = cmd.get::(); if let Some(completer) = external_completer { scs.extend(complete_external_subcommand(value, completer)); } } scs.sort(); scs.dedup(); scs } fn complete_external_subcommand( value: &str, completer: &SubcommandCandidates, ) -> Vec { debug!("complete_custom_arg_value: completer={completer:?}, value={value:?}"); let mut values = Vec::new(); let custom_arg_values = completer.candidates(); values.extend(custom_arg_values); values.retain(|comp| comp.get_value().starts_with(value)); values } /// Gets all the long options, their visible aliases and flags of a [`clap::Command`] with formatted `--` prefix. /// Includes `help` and `version` depending on the [`clap::Command`] settings. fn longs_and_visible_aliases(p: &clap::Command) -> Vec { debug!("longs: name={}", p.get_name()); p.get_arguments() .filter_map(|a| { a.get_long_and_visible_aliases().map(|longs| { longs .into_iter() .map(|s| populate_arg_candidate(CompletionCandidate::new(format!("--{s}")), a)) }) }) .flatten() .collect() } /// Gets all the long hidden aliases and flags of a [`clap::Command`]. fn hidden_longs_aliases(p: &clap::Command) -> Vec { debug!("longs: name={}", p.get_name()); p.get_arguments() .filter_map(|a| { a.get_aliases().map(|longs| { longs.into_iter().map(|s| { populate_arg_candidate(CompletionCandidate::new(format!("--{s}")), a).hide(true) }) }) }) .flatten() .collect() } /// Gets all the short options, their visible aliases and flags of a [`clap::Command`]. /// Includes `h` and `V` depending on the [`clap::Command`] settings. fn shorts_and_visible_aliases(p: &clap::Command) -> Vec { debug!("shorts: name={}", p.get_name()); p.get_arguments() .filter_map(|a| { a.get_short_and_visible_aliases().map(|shorts| { shorts.into_iter().map(|s| { populate_arg_candidate(CompletionCandidate::new(s.to_string()), a).help( a.get_help() .cloned() .or_else(|| a.get_long().map(|long| format!("--{long}").into())), ) }) }) }) .flatten() .collect() } fn populate_arg_candidate(candidate: CompletionCandidate, arg: &clap::Arg) -> CompletionCandidate { candidate .help(arg.get_help().cloned()) .id(Some(format!("arg::{}", arg.get_id()))) .tag(Some( arg.get_help_heading() .unwrap_or("Options") .to_owned() .into(), )) .display_order(Some(arg.get_display_order())) .hide(arg.is_hide_set()) } /// Get the possible values for completion fn possible_values(a: &clap::Arg) -> Option> { if !a.get_num_args().expect("built").takes_values() { None } else { a.get_value_parser() .possible_values() .map(|pvs| pvs.collect()) } } /// Gets subcommands of [`clap::Command`] in the form of `("name", "bin_name")`. /// /// Subcommand `rustup toolchain install` would be converted to /// `("install", "rustup toolchain install")`. fn subcommands(p: &clap::Command) -> Vec { debug!("subcommands: name={}", p.get_name()); debug!("subcommands: Has subcommands...{:?}", p.has_subcommands()); p.get_subcommands() .flat_map(|sc| { sc.get_name_and_visible_aliases() .into_iter() .map(|s| populate_command_candidate(CompletionCandidate::new(s.to_string()), p, sc)) .chain(sc.get_aliases().map(|s| { populate_command_candidate(CompletionCandidate::new(s.to_string()), p, sc) .hide(true) })) }) .collect() } fn populate_command_candidate( candidate: CompletionCandidate, cmd: &clap::Command, subcommand: &clap::Command, ) -> CompletionCandidate { candidate .help(subcommand.get_about().cloned()) .id(Some(format!("command::{}", subcommand.get_name()))) .tag(Some( cmd.get_subcommand_help_heading() .unwrap_or("Commands") .to_owned() .into(), )) .display_order(Some(subcommand.get_display_order())) .hide(subcommand.is_hide_set()) } /// Parse the short flags and find the first `takes_values` option. fn parse_shortflags<'c, 's>( cmd: &'c clap::Command, mut short: clap_lex::ShortFlags<'s>, ) -> (String, Option<&'c clap::Arg>, clap_lex::ShortFlags<'s>) { let takes_value_opt; let mut leading_flags = String::new(); // Find the first takes_values option. loop { match short.next_flag() { Some(Ok(opt)) => { leading_flags.push(opt); let opt = cmd.get_arguments().find(|a| { let shorts = a.get_short_and_visible_aliases(); let is_find = shorts.map(|v| { let mut iter = v.into_iter(); let c = iter.find(|c| *c == opt); c.is_some() }); is_find.unwrap_or(false) }); if opt.map(|o| o.get_action().takes_values()).unwrap_or(false) { takes_value_opt = opt; break; } } Some(Err(_)) | None => { takes_value_opt = None; break; } } } (leading_flags, takes_value_opt, short) } /// Parse the positional arguments. Return the new state and the new positional index. fn parse_positional<'a>( cmd: &clap::Command, pos_index: usize, is_escaped: bool, state: ParseState<'a>, ) -> (ParseState<'a>, usize) { let pos_arg = cmd .get_positionals() .find(|p| p.get_index() == Some(pos_index)); let num_args = pos_arg .and_then(|a| a.get_num_args().map(|r| r.max_values())) .unwrap_or(1); let update_state_with_new_positional = |pos_index| -> (ParseState<'a>, usize) { if num_args > 1 { (ParseState::Pos((pos_index, 1)), pos_index) } else { if is_escaped { (ParseState::Pos((pos_index, 1)), pos_index + 1) } else { (ParseState::ValueDone, pos_index + 1) } } }; match state { ParseState::ValueDone => { update_state_with_new_positional(pos_index) }, ParseState::Pos((prev_pos_index, num_arg)) => { if prev_pos_index == pos_index { if num_arg + 1 < num_args { (ParseState::Pos((pos_index, num_arg + 1)), pos_index) } else { if is_escaped { (ParseState::Pos((pos_index, 1)), pos_index + 1) } else { (ParseState::ValueDone, pos_index + 1) } } } else { update_state_with_new_positional(pos_index) } } ParseState::Opt(..) => unreachable!( "This branch won't be hit, because ParseState::Opt should not be seen as a positional argument and passed to this function." ), } } /// Parse optional flag argument. Return new state fn parse_opt_value(opt: &clap::Arg, count: usize) -> ParseState<'_> { let range = opt.get_num_args().expect("built"); let max = range.max_values(); if count < max { ParseState::Opt((opt, count + 1)) } else { ParseState::ValueDone } } fn pos_allows_hyphen(cmd: &clap::Command, pos_index: usize) -> bool { cmd.get_positionals() .find(|a| a.get_index() == Some(pos_index)) .map(|p| p.is_allow_hyphen_values_set()) .unwrap_or(false) } fn opt_allows_hyphen(state: &ParseState<'_>, arg: &clap_lex::ParsedArg<'_>) -> bool { let val = arg.to_value_os(); if val.starts_with("-") { if let ParseState::Opt((opt, _)) = state { return opt.is_allow_hyphen_values_set(); } } false } clap_complete-4.5.40/src/engine/custom.rs000064400000000000000000000244061046102023000164470ustar 00000000000000use std::any::type_name; use std::ffi::OsStr; use std::sync::Arc; use clap::builder::ArgExt; use clap::builder::CommandExt; use clap_lex::OsStrExt as _; use super::CompletionCandidate; /// Extend [`Arg`][clap::Arg] with a completer /// /// # Example /// /// ```rust /// use clap::Parser; /// use clap_complete::engine::{ArgValueCompleter, CompletionCandidate}; /// /// fn custom_completer(current: &std::ffi::OsStr) -> Vec { /// let mut completions = vec![]; /// let Some(current) = current.to_str() else { /// return completions; /// }; /// /// if "foo".starts_with(current) { /// completions.push(CompletionCandidate::new("foo")); /// } /// if "bar".starts_with(current) { /// completions.push(CompletionCandidate::new("bar")); /// } /// if "baz".starts_with(current) { /// completions.push(CompletionCandidate::new("baz")); /// } /// completions /// } /// /// #[derive(Debug, Parser)] /// struct Cli { /// #[arg(long, add = ArgValueCompleter::new(custom_completer))] /// custom: Option, /// } /// ``` #[derive(Clone)] pub struct ArgValueCompleter(Arc); impl ArgValueCompleter { /// Create a new `ArgValueCompleter` with a custom completer pub fn new(completer: C) -> Self where C: ValueCompleter + 'static, { Self(Arc::new(completer)) } /// Candidates that match `current` /// /// See [`CompletionCandidate`] for more information. pub fn complete(&self, current: &OsStr) -> Vec { self.0.complete(current) } } impl std::fmt::Debug for ArgValueCompleter { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(type_name::()) } } impl ArgExt for ArgValueCompleter {} /// User-provided completion candidates for an [`Arg`][clap::Arg], see [`ArgValueCompleter`] /// /// This is useful when predefined value hints are not enough. pub trait ValueCompleter: Send + Sync { /// All potential candidates for an argument. /// /// See [`CompletionCandidate`] for more information. fn complete(&self, current: &OsStr) -> Vec; } impl ValueCompleter for F where F: Fn(&OsStr) -> Vec + Send + Sync, { fn complete(&self, current: &OsStr) -> Vec { self(current) } } /// Extend [`Arg`][clap::Arg] with a [`ValueCandidates`] /// /// # Example /// /// ```rust /// use clap::Parser; /// use clap_complete::engine::{ArgValueCandidates, CompletionCandidate}; /// /// #[derive(Debug, Parser)] /// struct Cli { /// #[arg(long, add = ArgValueCandidates::new(|| { vec![ /// CompletionCandidate::new("foo"), /// CompletionCandidate::new("bar"), /// CompletionCandidate::new("baz")] }))] /// custom: Option, /// } /// ``` #[derive(Clone)] pub struct ArgValueCandidates(Arc); impl ArgValueCandidates { /// Create a new `ArgValueCandidates` with a custom completer pub fn new(completer: C) -> Self where C: ValueCandidates + 'static, { Self(Arc::new(completer)) } /// All potential candidates for an argument. /// /// See [`CompletionCandidate`] for more information. pub fn candidates(&self) -> Vec { self.0.candidates() } } impl std::fmt::Debug for ArgValueCandidates { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(type_name::()) } } impl ArgExt for ArgValueCandidates {} /// Extend [`Command`][clap::Command] with a [`ValueCandidates`] /// /// # Example /// ```rust /// use clap::Parser; /// use clap_complete::engine::{SubcommandCandidates, CompletionCandidate}; /// #[derive(Debug, Parser)] /// #[clap(name = "cli", add = SubcommandCandidates::new(|| { vec![ /// CompletionCandidate::new("foo"), /// CompletionCandidate::new("bar"), /// CompletionCandidate::new("baz")] }))] /// struct Cli { /// #[arg(long)] /// input: Option, /// } /// ``` #[derive(Clone)] pub struct SubcommandCandidates(Arc); impl SubcommandCandidates { /// Create a new `SubcommandCandidates` with a custom completer pub fn new(completer: C) -> Self where C: ValueCandidates + 'static, { Self(Arc::new(completer)) } /// All potential candidates for an external subcommand. /// /// See [`CompletionCandidate`] for more information. pub fn candidates(&self) -> Vec { self.0.candidates() } } impl std::fmt::Debug for SubcommandCandidates { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(type_name::()) } } impl CommandExt for SubcommandCandidates {} /// User-provided completion candidates for an [`Arg`][clap::Arg], see [`ArgValueCandidates`] /// /// User-provided completion candidates for an [`Subcommand`][clap::Subcommand], see [`SubcommandCandidates`] /// /// This is useful when predefined value hints are not enough. pub trait ValueCandidates: Send + Sync { /// All potential candidates for an argument. /// /// See [`CompletionCandidate`] for more information. fn candidates(&self) -> Vec; } impl ValueCandidates for F where F: Fn() -> Vec + Send + Sync, { fn candidates(&self) -> Vec { self() } } /// Complete a value as a [`std::path::Path`] /// /// # Example /// /// ```rust /// use clap::Parser; /// use clap_complete::engine::{ArgValueCompleter, PathCompleter}; /// /// #[derive(Debug, Parser)] /// struct Cli { /// #[arg(long, add = ArgValueCompleter::new(PathCompleter::file()))] /// custom: Option, /// } /// ``` pub struct PathCompleter { current_dir: Option, #[allow(clippy::type_complexity)] filter: Option bool + Send + Sync>>, stdio: bool, } impl PathCompleter { /// Any path is allowed pub fn any() -> Self { Self { filter: None, current_dir: None, stdio: false, } } /// Complete only files pub fn file() -> Self { Self::any().filter(|p| p.is_file()) } /// Complete only directories pub fn dir() -> Self { Self::any().filter(|p| p.is_dir()) } /// Include stdio (`-`) pub fn stdio(mut self) -> Self { self.stdio = true; self } /// Select which paths should be completed pub fn filter( mut self, filter: impl Fn(&std::path::Path) -> bool + Send + Sync + 'static, ) -> Self { self.filter = Some(Box::new(filter)); self } /// Override [`std::env::current_dir`] pub fn current_dir(mut self, path: impl Into) -> Self { self.current_dir = Some(path.into()); self } } impl Default for PathCompleter { fn default() -> Self { Self::any() } } impl ValueCompleter for PathCompleter { fn complete(&self, current: &OsStr) -> Vec { let filter = self.filter.as_deref().unwrap_or(&|_| true); let mut current_dir_actual = None; let current_dir = self.current_dir.as_deref().or_else(|| { current_dir_actual = std::env::current_dir().ok(); current_dir_actual.as_deref() }); let mut candidates = complete_path(current, current_dir, filter); if self.stdio && current.is_empty() { candidates.push(CompletionCandidate::new("-").help(Some("stdio".into()))); } candidates } } pub(crate) fn complete_path( value_os: &OsStr, current_dir: Option<&std::path::Path>, is_wanted: &dyn Fn(&std::path::Path) -> bool, ) -> Vec { let mut completions = Vec::new(); let mut potential = Vec::new(); let value_path = std::path::Path::new(value_os); let (prefix, current) = split_file_name(value_path); let current = current.to_string_lossy(); let search_root = if prefix.is_absolute() { prefix.to_owned() } else { let current_dir = match current_dir { Some(current_dir) => current_dir, None => { // Can't complete without a `current_dir` return completions; } }; current_dir.join(prefix) }; debug!("complete_path: search_root={search_root:?}, prefix={prefix:?}"); if value_os.is_empty() && is_wanted(&search_root) { completions.push(".".into()); } for entry in std::fs::read_dir(&search_root) .ok() .into_iter() .flatten() .filter_map(Result::ok) { let raw_file_name = entry.file_name(); if !raw_file_name.starts_with(¤t) { continue; } if entry.metadata().map(|m| m.is_dir()).unwrap_or(false) { let mut suggestion = prefix.join(raw_file_name); suggestion.push(""); // Ensure trailing `/` let candidate = CompletionCandidate::new(suggestion.as_os_str().to_owned()); if is_wanted(&entry.path()) { completions.push(candidate); } else { potential.push(candidate); } } else { if is_wanted(&entry.path()) { let suggestion = prefix.join(raw_file_name); let candidate = CompletionCandidate::new(suggestion.as_os_str().to_owned()); completions.push(candidate); } } } completions.sort(); potential.sort(); completions.extend(potential); completions } fn split_file_name(path: &std::path::Path) -> (&std::path::Path, &OsStr) { // Workaround that `Path::new("name/").file_name()` reports `"name"` if path_has_name(path) { ( path.parent().unwrap_or_else(|| std::path::Path::new("")), path.file_name().expect("not called with `..`"), ) } else { (path, Default::default()) } } fn path_has_name(path: &std::path::Path) -> bool { let path_bytes = path.as_os_str().as_encoded_bytes(); let Some(trailing) = path_bytes.last() else { return false; }; let trailing = *trailing as char; !std::path::is_separator(trailing) && path.file_name().is_some() } clap_complete-4.5.40/src/engine/mod.rs000064400000000000000000000005731046102023000157130ustar 00000000000000//! `clap`-native completion system //! //! See [`complete()`] mod candidate; mod complete; mod custom; pub use candidate::CompletionCandidate; pub use complete::complete; pub use custom::ArgValueCandidates; pub use custom::ArgValueCompleter; pub use custom::PathCompleter; pub use custom::SubcommandCandidates; pub use custom::ValueCandidates; pub use custom::ValueCompleter; clap_complete-4.5.40/src/env/mod.rs000064400000000000000000000273311046102023000152370ustar 00000000000000//! [`COMPLETE=$SHELL `][CompleteEnv] completion integration //! //! See [`CompleteEnv`]: //! ```rust //! # use clap_complete::CompleteEnv; //! fn cli() -> clap::Command { //! // ... //! # clap::Command::new("empty") //! } //! //! fn main() { //! CompleteEnv::with_factory(cli) //! .complete(); //! //! // ... rest of application logic //! } //! ``` //! //! To customize completions, see //! - [`ValueHint`][crate::ValueHint] //! - [`ValueEnum`][clap::ValueEnum] //! - [`ArgValueCandidates`][crate::ArgValueCandidates] //! - [`ArgValueCompleter`][crate::ArgValueCompleter] //! //! To source your completions: //! //!
//! //! **WARNING:** We recommend re-sourcing your completions on upgrade. //! These completions work by generating shell code that calls into `your_program` while completing. //! That interface is unstable and a mismatch between the shell code and `your_program` may result //! in either invalid completions or no completions being generated. //! For this reason, we recommend generating the shell code anew on shell startup so that it is //! "self-correcting" on shell launch, rather than writing the generated completions to a file. //! //!
//! //! Bash //! ```bash //! echo "source <(COMPLETE=bash your_program)" >> ~/.bashrc //! ``` //! //! Elvish //! ```elvish //! echo "eval (E:COMPLETE=elvish your_program | slurp)" >> ~/.elvish/rc.elv //! ``` //! //! Fish //! ```fish //! echo "source (COMPLETE=fish your_program | psub)" >> ~/.config/fish/config.fish //! ``` //! //! Powershell //! ```powershell //! $env:COMPLETE = "powershell" //! echo "your_program | Out-String | Invoke-Expression" >> $PROFILE //! Remove-Item Env:\COMPLETE //! ``` //! //! Zsh //! ```zsh //! echo "source <(COMPLETE=zsh your_program)" >> ~/.zshrc //! ``` mod shells; use std::ffi::OsString; use std::io::Write as _; pub use shells::*; /// Environment-activated completions for your CLI /// /// Benefits over a CLI completion argument or subcommand /// - Performance: we don't need to generate [`clap::Command`] twice or parse arguments /// - Flexibility: there is no concern over it interfering with other CLI logic /// /// **Warning:** `stdout` should not be written to before [`CompleteEnv::complete`] has had a /// chance to run. /// /// # Examples /// /// ```rust /// # use clap_complete::CompleteEnv; /// fn cli() -> clap::Command { /// // ... /// # clap::Command::new("empty") /// } /// /// fn main() { /// CompleteEnv::with_factory(cli) /// .complete() /// /// // ... rest of application logic /// } /// ``` pub struct CompleteEnv<'s, F> { factory: F, var: &'static str, bin: Option, completer: Option, shells: Shells<'s>, } impl<'s, F: Fn() -> clap::Command> CompleteEnv<'s, F> { /// Complete a [`clap::Command`] /// /// # Example /// /// Builder: /// ```rust /// # use clap_complete::CompleteEnv; /// fn cli() -> clap::Command { /// // ... /// # clap::Command::new("empty") /// } /// /// fn main() { /// CompleteEnv::with_factory(cli) /// .complete() /// /// // ... rest of application logic /// } /// ``` /// /// Derive: /// ``` /// # use clap::Parser; /// # use clap_complete::CompleteEnv; /// use clap::CommandFactory as _; /// /// #[derive(Debug, Parser)] /// struct Cli { /// custom: Option, /// } /// /// fn main() { /// CompleteEnv::with_factory(|| Cli::command()) /// .complete() /// /// // ... rest of application logic /// } /// ``` pub fn with_factory(factory: F) -> Self { Self { factory, var: "COMPLETE", bin: None, completer: None, shells: Shells::builtins(), } } /// Override the environment variable used for enabling completions pub fn var(mut self, var: &'static str) -> Self { self.var = var; self } /// Override the name of the binary to complete /// /// Default: `Command::get_bin_name` pub fn bin(mut self, bin: impl Into) -> Self { self.bin = Some(bin.into()); self } /// Override the binary to call to get completions /// /// Default: `args_os()[0]` pub fn completer(mut self, completer: impl Into) -> Self { self.completer = Some(completer.into()); self } /// Override the shells supported for completions pub fn shells(mut self, shells: Shells<'s>) -> Self { self.shells = shells; self } } impl<'s, F: Fn() -> clap::Command> CompleteEnv<'s, F> { /// Process the completion request and exit /// /// **Warning:** `stdout` should not be written to before this has had a /// chance to run. pub fn complete(self) { let args = std::env::args_os(); let current_dir = std::env::current_dir().ok(); if self .try_complete(args, current_dir.as_deref()) .unwrap_or_else(|e| e.exit()) { std::process::exit(0) } } /// Process the completion request /// /// **Warning:** `stdout` should not be written to before or after this has run. /// /// Returns `true` if a command was completed and `false` if this is a regular run of your /// application pub fn try_complete( self, args: impl IntoIterator>, current_dir: Option<&std::path::Path>, ) -> clap::error::Result { self.try_complete_(args.into_iter().map(|a| a.into()).collect(), current_dir) } fn try_complete_( self, mut args: Vec, current_dir: Option<&std::path::Path>, ) -> clap::error::Result { let Some(name) = std::env::var_os(self.var) else { return Ok(false); }; // Ensure any child processes called for custom completers don't activate their own // completion logic. std::env::remove_var(self.var); let shell = self.shell(std::path::Path::new(&name))?; let mut cmd = (self.factory)(); cmd.build(); let completer = args.remove(0); let escape_index = args .iter() .position(|a| *a == "--") .map(|i| i + 1) .unwrap_or(args.len()); args.drain(0..escape_index); if args.is_empty() { let mut buf = Vec::new(); self.write_registration(&cmd, current_dir, shell, completer, &mut buf)?; std::io::stdout().write_all(&buf)?; } else { let mut buf = Vec::new(); shell.write_complete(&mut cmd, args, current_dir, &mut buf)?; std::io::stdout().write_all(&buf)?; } Ok(true) } fn shell(&self, name: &std::path::Path) -> Result<&dyn EnvCompleter, std::io::Error> { // Strip off the parent dir in case `$SHELL` was used let name = name.file_stem().unwrap_or(name.as_os_str()); // lossy won't match but this will delegate to unknown // error let name = name.to_string_lossy(); let shell = self.shells.completer(&name).ok_or_else(|| { let shells = self.shells .names() .enumerate() .fold(String::new(), |mut seed, (i, name)| { use std::fmt::Write as _; let prefix = if i == 0 { "" } else { ", " }; let _ = write!(&mut seed, "{prefix}`{name}`"); seed }); std::io::Error::new( std::io::ErrorKind::Other, format!("unknown shell `{name}`, expected one of {shells}"), ) })?; Ok(shell) } fn write_registration( &self, cmd: &clap::Command, current_dir: Option<&std::path::Path>, shell: &dyn EnvCompleter, completer: OsString, buf: &mut dyn std::io::Write, ) -> Result<(), std::io::Error> { let name = cmd.get_name(); let bin = self .bin .as_deref() .or_else(|| cmd.get_bin_name()) .unwrap_or_else(|| cmd.get_name()); let completer = if let Some(completer) = self.completer.as_deref() { completer.to_owned() } else { let mut completer = std::path::PathBuf::from(completer); if let Some(current_dir) = current_dir { if 1 < completer.components().count() { completer = current_dir.join(completer); } } completer.to_string_lossy().into_owned() }; shell.write_registration(self.var, name, bin, &completer, buf)?; Ok(()) } } /// Collection of shell-specific completers pub struct Shells<'s>(pub &'s [&'s dyn EnvCompleter]); impl<'s> Shells<'s> { /// Select all of the built-in shells pub const fn builtins() -> Self { Self(&[&Bash, &Elvish, &Fish, &Powershell, &Zsh]) } /// Find the specified [`EnvCompleter`] pub fn completer(&self, name: &str) -> Option<&dyn EnvCompleter> { self.0.iter().copied().find(|c| c.is(name)) } /// Collect all [`EnvCompleter::name`]s pub fn names(&self) -> impl Iterator + 's { self.0.iter().map(|c| c.name()) } /// Iterate over [`EnvCompleter`]s pub fn iter(&self) -> impl Iterator { self.0.iter().copied() } } /// Shell-integration for completions /// /// This will generally be called by [`CompleteEnv`]. /// /// This handles adapting between the shell and [`completer`][crate::engine::complete()]. /// A `EnvCompleter` can choose how much of that lives within the registration script or /// lives in [`EnvCompleter::write_complete`]. pub trait EnvCompleter { /// Canonical name for this shell /// /// **Post-conditions:** /// ```rust,ignore /// assert!(completer.is(completer.name())); /// ``` fn name(&self) -> &'static str; /// Whether the name matches this shell /// /// This should match [`EnvCompleter::name`] and any alternative names, particularly used by /// `$SHELL`. fn is(&self, name: &str) -> bool; /// Register for completions /// /// Write the `buf` the logic needed for calling into `= --`, passing needed /// arguments to [`EnvCompleter::write_complete`] through the environment. /// /// - `var`: see [`CompleteEnv::var`] /// - `name`: an identifier to use in the script /// - `bin`: see [`CompleteEnv::bin`] /// - `completer`: see [`CompleteEnv::completer`] /// ///
/// /// **WARNING:** There are no stability guarantees between the call to /// [`EnvCompleter::write_complete`] that this generates and actually calling [`EnvCompleter::write_complete`]. /// Caching the results of this call may result in invalid or no completions to be generated. /// ///
fn write_registration( &self, var: &str, name: &str, bin: &str, completer: &str, buf: &mut dyn std::io::Write, ) -> Result<(), std::io::Error>; /// Complete the given command /// /// Adapt information from arguments and [`EnvCompleter::write_registration`]-defined env /// variables to what is needed for [`completer`][crate::engine::complete()]. /// /// Write out the [`CompletionCandidate`][crate::engine::CompletionCandidate]s in a way the shell will understand. fn write_complete( &self, cmd: &mut clap::Command, args: Vec, current_dir: Option<&std::path::Path>, buf: &mut dyn std::io::Write, ) -> Result<(), std::io::Error>; } clap_complete-4.5.40/src/env/shells.rs000064400000000000000000000313141046102023000157460ustar 00000000000000use std::ffi::OsString; use std::str::FromStr; use super::EnvCompleter; /// Bash completion adapter #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub struct Bash; impl EnvCompleter for Bash { fn name(&self) -> &'static str { "bash" } fn is(&self, name: &str) -> bool { name == "bash" } fn write_registration( &self, var: &str, name: &str, bin: &str, completer: &str, buf: &mut dyn std::io::Write, ) -> Result<(), std::io::Error> { let escaped_name = name.replace('-', "_"); let completer = shlex::try_quote(completer).unwrap_or(std::borrow::Cow::Borrowed(completer)); let script = r#" _clap_complete_NAME() { local IFS=$'\013' local _CLAP_COMPLETE_INDEX=${COMP_CWORD} local _CLAP_COMPLETE_COMP_TYPE=${COMP_TYPE} if compopt +o nospace 2> /dev/null; then local _CLAP_COMPLETE_SPACE=false else local _CLAP_COMPLETE_SPACE=true fi COMPREPLY=( $( \ _CLAP_IFS="$IFS" \ _CLAP_COMPLETE_INDEX="$_CLAP_COMPLETE_INDEX" \ _CLAP_COMPLETE_COMP_TYPE="$_CLAP_COMPLETE_COMP_TYPE" \ VAR="bash" \ "COMPLETER" -- "${COMP_WORDS[@]}" \ ) ) if [[ $? != 0 ]]; then unset COMPREPLY elif [[ $SUPPRESS_SPACE == 1 ]] && [[ "${COMPREPLY-}" =~ [=/:]$ ]]; then compopt -o nospace fi } if [[ "${BASH_VERSINFO[0]}" -eq 4 && "${BASH_VERSINFO[1]}" -ge 4 || "${BASH_VERSINFO[0]}" -gt 4 ]]; then complete -o nospace -o bashdefault -o nosort -F _clap_complete_NAME BIN else complete -o nospace -o bashdefault -F _clap_complete_NAME BIN fi "# .replace("NAME", &escaped_name) .replace("BIN", bin) .replace("COMPLETER", &completer) .replace("VAR", var); writeln!(buf, "{script}")?; Ok(()) } fn write_complete( &self, cmd: &mut clap::Command, args: Vec, current_dir: Option<&std::path::Path>, buf: &mut dyn std::io::Write, ) -> Result<(), std::io::Error> { let index: usize = std::env::var("_CLAP_COMPLETE_INDEX") .ok() .and_then(|i| i.parse().ok()) .unwrap_or_default(); let _comp_type: CompType = std::env::var("_CLAP_COMPLETE_COMP_TYPE") .ok() .and_then(|i| i.parse().ok()) .unwrap_or_default(); let _space: Option = std::env::var("_CLAP_COMPLETE_SPACE") .ok() .and_then(|i| i.parse().ok()); let ifs: Option = std::env::var("_CLAP_IFS").ok().and_then(|i| i.parse().ok()); let completions = crate::engine::complete(cmd, args, index, current_dir)?; for (i, candidate) in completions.iter().enumerate() { if i != 0 { write!(buf, "{}", ifs.as_deref().unwrap_or("\n"))?; } write!(buf, "{}", candidate.get_value().to_string_lossy())?; } Ok(()) } } /// Type of completion attempted that caused a completion function to be called #[derive(Copy, Clone, Debug, PartialEq, Eq)] #[non_exhaustive] enum CompType { /// Normal completion Normal, /// List completions after successive tabs Successive, /// List alternatives on partial word completion Alternatives, /// List completions if the word is not unmodified Unmodified, /// Menu completion Menu, } impl FromStr for CompType { type Err = String; fn from_str(s: &str) -> Result { match s { "9" => Ok(Self::Normal), "63" => Ok(Self::Successive), "33" => Ok(Self::Alternatives), "64" => Ok(Self::Unmodified), "37" => Ok(Self::Menu), _ => Err(format!("unsupported COMP_TYPE `{s}`")), } } } impl Default for CompType { fn default() -> Self { Self::Normal } } /// Elvish completion adapter #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub struct Elvish; impl EnvCompleter for Elvish { fn name(&self) -> &'static str { "elvish" } fn is(&self, name: &str) -> bool { name == "elvish" } fn write_registration( &self, var: &str, _name: &str, bin: &str, completer: &str, buf: &mut dyn std::io::Write, ) -> Result<(), std::io::Error> { let bin = shlex::try_quote(bin).unwrap_or(std::borrow::Cow::Borrowed(bin)); let completer = shlex::try_quote(completer).unwrap_or(std::borrow::Cow::Borrowed(completer)); let script = r#" set edit:completion:arg-completer[BIN] = { |@words| set E:_CLAP_IFS = "\n" var index = (count $words) set index = (- $index 1) set E:_CLAP_COMPLETE_INDEX = (to-string $index) set E:VAR = "elvish" put (COMPLETER -- $@words) | to-lines } "# .replace("COMPLETER", &completer) .replace("BIN", &bin) .replace("VAR", var); writeln!(buf, "{script}")?; Ok(()) } fn write_complete( &self, cmd: &mut clap::Command, args: Vec, current_dir: Option<&std::path::Path>, buf: &mut dyn std::io::Write, ) -> Result<(), std::io::Error> { let index: usize = std::env::var("_CLAP_COMPLETE_INDEX") .ok() .and_then(|i| i.parse().ok()) .unwrap_or_default(); let ifs: Option = std::env::var("_CLAP_IFS").ok().and_then(|i| i.parse().ok()); let completions = crate::engine::complete(cmd, args, index, current_dir)?; for (i, candidate) in completions.iter().enumerate() { if i != 0 { write!(buf, "{}", ifs.as_deref().unwrap_or("\n"))?; } write!(buf, "{}", candidate.get_value().to_string_lossy())?; } Ok(()) } } /// Fish completion adapter #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub struct Fish; impl EnvCompleter for Fish { fn name(&self) -> &'static str { "fish" } fn is(&self, name: &str) -> bool { name == "fish" } fn write_registration( &self, var: &str, _name: &str, bin: &str, completer: &str, buf: &mut dyn std::io::Write, ) -> Result<(), std::io::Error> { let bin = shlex::try_quote(bin).unwrap_or(std::borrow::Cow::Borrowed(bin)); let completer = shlex::try_quote(completer).unwrap_or(std::borrow::Cow::Borrowed(completer)); writeln!( buf, r#"complete --keep-order --exclusive --command {bin} --arguments "({var}=fish "'{completer}'" -- (commandline --current-process --tokenize --cut-at-cursor) (commandline --current-token))""# ) } fn write_complete( &self, cmd: &mut clap::Command, args: Vec, current_dir: Option<&std::path::Path>, buf: &mut dyn std::io::Write, ) -> Result<(), std::io::Error> { let index = args.len() - 1; let completions = crate::engine::complete(cmd, args, index, current_dir)?; for candidate in completions { write!(buf, "{}", candidate.get_value().to_string_lossy())?; if let Some(help) = candidate.get_help() { write!( buf, "\t{}", help.to_string().lines().next().unwrap_or_default() )?; } writeln!(buf)?; } Ok(()) } } /// Powershell completion adapter #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub struct Powershell; impl EnvCompleter for Powershell { fn name(&self) -> &'static str { "powershell" } fn is(&self, name: &str) -> bool { name == "powershell" || name == "powershell_ise" } fn write_registration( &self, var: &str, _name: &str, bin: &str, completer: &str, buf: &mut dyn std::io::Write, ) -> Result<(), std::io::Error> { let bin = shlex::try_quote(bin).unwrap_or(std::borrow::Cow::Borrowed(bin)); let completer = shlex::try_quote(completer).unwrap_or(std::borrow::Cow::Borrowed(completer)); // `completer` may or may not be surrounded by double quotes, enclosing // the expression in a here-string ensures the whole thing is // interpreted as the first argument to the call operator writeln!( buf, r#" Register-ArgumentCompleter -Native -CommandName {bin} -ScriptBlock {{ param($wordToComplete, $commandAst, $cursorPosition) $prev = $env:{var}; $env:{var} = "powershell"; $results = Invoke-Expression @" & {completer} -- $commandAst "@; if ($null -eq $prev) {{ Remove-Item Env:\{var}; }} else {{ $env:{var} = $prev; }} $results | ForEach-Object {{ $split = $_.Split("`t"); $cmd = $split[0]; if ($split.Length -eq 2) {{ $help = $split[1]; }} else {{ $help = $split[0]; }} [System.Management.Automation.CompletionResult]::new($cmd, $cmd, 'ParameterValue', $help) }} }}; "# ) } fn write_complete( &self, cmd: &mut clap::Command, args: Vec, current_dir: Option<&std::path::Path>, buf: &mut dyn std::io::Write, ) -> Result<(), std::io::Error> { let index = args.len() - 1; let completions = crate::engine::complete(cmd, args, index, current_dir)?; for candidate in completions { write!(buf, "{}", candidate.get_value().to_string_lossy())?; if let Some(help) = candidate.get_help() { write!( buf, "\t{}", help.to_string().lines().next().unwrap_or_default() )?; } writeln!(buf)?; } Ok(()) } } /// Zsh completion adapter #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub struct Zsh; impl EnvCompleter for Zsh { fn name(&self) -> &'static str { "zsh" } fn is(&self, name: &str) -> bool { name == "zsh" } fn write_registration( &self, var: &str, name: &str, bin: &str, completer: &str, buf: &mut dyn std::io::Write, ) -> Result<(), std::io::Error> { let escaped_name = name.replace('-', "_"); let bin = shlex::try_quote(bin).unwrap_or(std::borrow::Cow::Borrowed(bin)); let completer = shlex::try_quote(completer).unwrap_or(std::borrow::Cow::Borrowed(completer)); let script = r#"#compdef BIN function _clap_dynamic_completer_NAME() { local _CLAP_COMPLETE_INDEX=$(expr $CURRENT - 1) local _CLAP_IFS=$'\n' local completions=("${(@f)$( \ _CLAP_IFS="$_CLAP_IFS" \ _CLAP_COMPLETE_INDEX="$_CLAP_COMPLETE_INDEX" \ VAR="zsh" \ COMPLETER -- ${words} 2>/dev/null \ )}") if [[ -n $completions ]]; then _describe 'values' completions fi } compdef _clap_dynamic_completer_NAME BIN"# .replace("NAME", &escaped_name) .replace("COMPLETER", &completer) .replace("BIN", &bin) .replace("VAR", var); writeln!(buf, "{script}")?; Ok(()) } fn write_complete( &self, cmd: &mut clap::Command, args: Vec, current_dir: Option<&std::path::Path>, buf: &mut dyn std::io::Write, ) -> Result<(), std::io::Error> { let index: usize = std::env::var("_CLAP_COMPLETE_INDEX") .ok() .and_then(|i| i.parse().ok()) .unwrap_or_default(); let ifs: Option = std::env::var("_CLAP_IFS").ok().and_then(|i| i.parse().ok()); // If the current word is empty, add an empty string to the args let mut args = args.clone(); if args.len() == index { args.push("".into()); } let completions = crate::engine::complete(cmd, args, index, current_dir)?; for (i, candidate) in completions.iter().enumerate() { if i != 0 { write!(buf, "{}", ifs.as_deref().unwrap_or("\n"))?; } write!( buf, "{}", Self::escape_value(&candidate.get_value().to_string_lossy()) )?; if let Some(help) = candidate.get_help() { write!( buf, ":{}", Self::escape_help(help.to_string().lines().next().unwrap_or_default()) )?; } } Ok(()) } } impl Zsh { /// Escape value string fn escape_value(string: &str) -> String { string.replace('\\', "\\\\").replace(':', "\\:") } /// Escape help string fn escape_help(string: &str) -> String { string.replace('\\', "\\\\") } } clap_complete-4.5.40/src/lib.rs000064400000000000000000000064211046102023000144330ustar 00000000000000// Copyright ⓒ 2015-2018 Kevin B. Knapp // // `clap_complete` is distributed under the terms of both the MIT license and the Apache License // (Version 2.0). // See the [LICENSE-APACHE](LICENSE-APACHE) and [LICENSE-MIT](LICENSE-MIT) files in this repository // for more information. //! ## Quick Start //! //! - For generating at compile-time, see [`generate_to`] //! - For generating at runtime, see [`generate`] //! //! [`Shell`] is a convenience `enum` for an argument value type that implements `Generator` //! for each natively-supported shell type. //! //! ## Example //! //! ```rust,no_run //! use clap::{Command, Arg, ValueHint, value_parser, ArgAction}; //! use clap_complete::aot::{generate, Generator, Shell}; //! use std::io; //! //! fn build_cli() -> Command { //! Command::new("example") //! .arg(Arg::new("file") //! .help("some input file") //! .value_hint(ValueHint::AnyPath)) //! .arg(Arg::new("generator") //! .long("generate") //! .action(ArgAction::Set) //! .value_parser(value_parser!(Shell))) //! } //! //! fn print_completions(gen: G, cmd: &mut Command) { //! generate(gen, cmd, cmd.get_name().to_string(), &mut io::stdout()); //! } //! //! fn main() { //! let matches = build_cli().get_matches(); //! //! if let Some(generator) = matches.get_one::("generator").copied() { //! let mut cmd = build_cli(); //! eprintln!("Generating completion file for {generator}..."); //! print_completions(generator, &mut cmd); //! } //! } //! ``` #![doc(html_logo_url = "https://raw.githubusercontent.com/clap-rs/clap/master/assets/clap.png")] #![doc = include_str!("../README.md")] #![cfg_attr(docsrs, feature(doc_auto_cfg))] #![forbid(unsafe_code)] #![warn(missing_docs)] #![allow(clippy::needless_doctest_main)] #![warn(clippy::print_stderr)] #![warn(clippy::print_stdout)] const INTERNAL_ERROR_MSG: &str = "Fatal internal error. Please consider filing a bug \ report at https://github.com/clap-rs/clap/issues"; #[macro_use] #[allow(missing_docs)] mod macros; pub mod aot; #[cfg(feature = "unstable-dynamic")] pub mod engine; #[cfg(feature = "unstable-dynamic")] pub mod env; pub use clap::ValueHint; #[doc(inline)] #[cfg(feature = "unstable-dynamic")] pub use engine::ArgValueCandidates; #[cfg(feature = "unstable-dynamic")] pub use engine::ArgValueCompleter; #[doc(inline)] #[cfg(feature = "unstable-dynamic")] pub use engine::CompletionCandidate; #[cfg(feature = "unstable-dynamic")] pub use engine::PathCompleter; #[cfg(feature = "unstable-dynamic")] pub use env::CompleteEnv; /// Deprecated, see [`aot`] pub mod generator { pub use crate::aot::generate; pub use crate::aot::generate_to; pub use crate::aot::utils; pub use crate::aot::Generator; } /// Deprecated, see [`aot`] pub mod shells { pub use crate::aot::Bash; pub use crate::aot::Elvish; pub use crate::aot::Fish; pub use crate::aot::PowerShell; pub use crate::aot::Shell; pub use crate::aot::Zsh; } /// Deprecated, see [`aot::generate`] pub use aot::generate; /// Deprecated, see [`aot::generate_to`] pub use aot::generate_to; /// Deprecated, see [`aot::Generator`] pub use aot::Generator; /// Deprecated, see [`aot::Shell`] pub use aot::Shell; clap_complete-4.5.40/src/macros.rs000064400000000000000000000003621046102023000151470ustar 00000000000000#[cfg(feature = "debug")] macro_rules! debug { ($($arg:tt)*) => { eprint!("[{:>w$}] \t", module_path!(), w = 28); eprintln!($($arg)*) } } #[cfg(not(feature = "debug"))] macro_rules! debug { ($($arg:tt)*) => {}; }