├── .github ├── actions │ └── install-rust │ │ ├── README.md │ │ ├── action.yml │ │ └── main.js └── workflows │ └── main.yml ├── .gitignore ├── .rustfmt.toml ├── CODE_OF_CONDUCT.md ├── COPYRIGHT ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-Apache-2.0_WITH_LLVM-exception ├── LICENSE-MIT ├── ORG_CODE_OF_CONDUCT.md ├── README.md ├── SECURITY.md ├── build.rs ├── examples ├── basic.rs ├── cat.rs ├── clap.rs ├── copy.rs ├── copy_with_defaults.rs ├── grep.rs ├── kommand.rs ├── repl-client.rs ├── repl.rs ├── sleep.rs ├── text-cat.rs └── text-grep.rs ├── kommand ├── COPYRIGHT ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-Apache-2.0_WITH_LLVM-exception ├── LICENSE-MIT ├── README.md ├── examples │ └── add.rs └── src │ └── lib.rs ├── reaktor ├── COPYRIGHT ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-Apache-2.0_WITH_LLVM-exception ├── LICENSE-MIT ├── README.md └── src │ └── lib.rs └── src ├── input_byte_stream.rs ├── input_text_stream.rs ├── interactive_byte_stream.rs ├── interactive_text_stream.rs ├── lazy_output.rs ├── lib.rs ├── media_type.rs ├── open_input.rs ├── open_interactive.rs ├── open_output.rs ├── output_byte_stream.rs ├── output_text_stream.rs ├── path_to_name.rs ├── pseudonym.rs └── summon_bat.rs /.github/actions/install-rust/README.md: -------------------------------------------------------------------------------- 1 | # install-rust 2 | 3 | A small github action to install `rustup` and a Rust toolchain. This is 4 | generally expressed inline, but it was repeated enough in this repository it 5 | seemed worthwhile to extract. 6 | 7 | Some gotchas: 8 | 9 | * Can't `--self-update` on Windows due to permission errors (a bug in Github 10 | Actions) 11 | * `rustup` isn't installed on macOS (a bug in Github Actions) 12 | 13 | When the above are fixed we should delete this action and just use this inline: 14 | 15 | ```yml 16 | - run: rustup update $toolchain && rustup default $toolchain 17 | shell: bash 18 | ``` 19 | -------------------------------------------------------------------------------- /.github/actions/install-rust/action.yml: -------------------------------------------------------------------------------- 1 | name: 'Install Rust toolchain' 2 | description: 'Install both `rustup` and a Rust toolchain' 3 | 4 | inputs: 5 | toolchain: 6 | description: 'Default toolchan to install' 7 | required: false 8 | default: 'stable' 9 | 10 | runs: 11 | using: node20 12 | main: 'main.js' 13 | -------------------------------------------------------------------------------- /.github/actions/install-rust/main.js: -------------------------------------------------------------------------------- 1 | const child_process = require('child_process'); 2 | const toolchain = process.env.INPUT_TOOLCHAIN; 3 | const fs = require('fs'); 4 | 5 | function set_env(name, val) { 6 | fs.appendFileSync(process.env['GITHUB_ENV'], `${name}=${val}\n`) 7 | } 8 | 9 | // Needed for now to get 1.24.2 which fixes a bug in 1.24.1 that causes issues 10 | // on Windows. 11 | if (process.platform === 'win32') { 12 | child_process.execFileSync('rustup', ['self', 'update']); 13 | } 14 | 15 | child_process.execFileSync('rustup', ['set', 'profile', 'minimal']); 16 | child_process.execFileSync('rustup', ['update', toolchain, '--no-self-update']); 17 | child_process.execFileSync('rustup', ['default', toolchain]); 18 | 19 | // Deny warnings on CI to keep our code warning-free as it lands in-tree. Don't 20 | // do this on nightly though since there's a fair amount of warning churn there. 21 | if (!toolchain.startsWith('nightly')) { 22 | set_env("RUSTFLAGS", "-D warnings"); 23 | } 24 | 25 | // Save disk space by avoiding incremental compilation, and also we don't use 26 | // any caching so incremental wouldn't help anyway. 27 | set_env("CARGO_INCREMENTAL", "0"); 28 | 29 | // Turn down debuginfo from 2 to 1 to help save disk space 30 | set_env("CARGO_PROFILE_DEV_DEBUG", "1"); 31 | set_env("CARGO_PROFILE_TEST_DEBUG", "1"); 32 | 33 | if (process.platform === 'darwin') { 34 | set_env("CARGO_PROFILE_DEV_SPLIT_DEBUGINFO", "unpacked"); 35 | set_env("CARGO_PROFILE_TEST_SPLIT_DEBUGINFO", "unpacked"); 36 | } 37 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | 9 | jobs: 10 | rustfmt: 11 | name: Rustfmt 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v4 15 | with: 16 | submodules: true 17 | - uses: ./.github/actions/install-rust 18 | with: 19 | toolchain: stable 20 | - run: cargo fmt --all -- --check 21 | 22 | test: 23 | name: Test 24 | runs-on: ${{ matrix.os }} 25 | strategy: 26 | matrix: 27 | build: [stable, windows] 28 | include: 29 | - build: stable 30 | os: ubuntu-latest 31 | rust: stable 32 | - build: windows 33 | os: windows-latest 34 | rust: stable 35 | 36 | steps: 37 | - uses: actions/checkout@v4 38 | with: 39 | submodules: true 40 | - uses: ./.github/actions/install-rust 41 | with: 42 | toolchain: ${{ matrix.rust }} 43 | - run: cargo test --workspace 44 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /.rustfmt.toml: -------------------------------------------------------------------------------- 1 | # This file tells tools we use rustfmt. We use the default settings. 2 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | *Note*: this Code of Conduct pertains to individuals' behavior. Please also see the [Organizational Code of Conduct][OCoC]. 4 | 5 | ## Our Pledge 6 | 7 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. 8 | 9 | ## Our Standards 10 | 11 | Examples of behavior that contributes to creating a positive environment include: 12 | 13 | * Using welcoming and inclusive language 14 | * Being respectful of differing viewpoints and experiences 15 | * Gracefully accepting constructive criticism 16 | * Focusing on what is best for the community 17 | * Showing empathy towards other community members 18 | 19 | Examples of unacceptable behavior by participants include: 20 | 21 | * The use of sexualized language or imagery and unwelcome sexual attention or advances 22 | * Trolling, insulting/derogatory comments, and personal or political attacks 23 | * Public or private harassment 24 | * Publishing others' private information, such as a physical or electronic address, without explicit permission 25 | * Other conduct which could reasonably be considered inappropriate in a professional setting 26 | 27 | ## Our Responsibilities 28 | 29 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 30 | 31 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 32 | 33 | ## Scope 34 | 35 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 36 | 37 | ## Enforcement 38 | 39 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the Bytecode Alliance CoC team at [report@bytecodealliance.org](mailto:report@bytecodealliance.org). The CoC team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The CoC team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 40 | 41 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the Bytecode Alliance's leadership. 42 | 43 | ## Attribution 44 | 45 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] 46 | 47 | [OCoC]: https://github.com/bytecodealliance/nameless/blob/main/ORG_CODE_OF_CONDUCT.md 48 | [homepage]: https://www.contributor-covenant.org 49 | [version]: https://www.contributor-covenant.org/version/1/4/ 50 | -------------------------------------------------------------------------------- /COPYRIGHT: -------------------------------------------------------------------------------- 1 | Short version for non-lawyers: 2 | 3 | `nameless` is triple-licensed under Apache 2.0 with the LLVM Exception, 4 | Apache 2.0, and MIT terms. 5 | 6 | 7 | Longer version: 8 | 9 | Copyrights in the `nameless` project are retained by their contributors. 10 | No copyright assignment is required to contribute to the `nameless` 11 | project. 12 | 13 | Some files include code derived from Rust's `libstd`; see the comments in 14 | the code for details. 15 | 16 | Except as otherwise noted (below and/or in individual files), `nameless` 17 | is licensed under: 18 | 19 | - the Apache License, Version 2.0, with the LLVM Exception 20 | or 21 | 22 | - the Apache License, Version 2.0 23 | or 24 | , 25 | - or the MIT license 26 | or 27 | , 28 | 29 | at your option. 30 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "nameless" 3 | version = "0.15.2" 4 | description = "Portable everything-is-a-URL" 5 | authors = ["Dan Gohman "] 6 | edition = "2021" 7 | license = "Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT" 8 | keywords = ["cli", "file", "network"] 9 | categories = ["command-line-interface", "filesystem", "network-programming"] 10 | repository = "https://github.com/sunfishcode/nameless" 11 | exclude = ["/.github"] 12 | 13 | [dependencies] 14 | anyhow = "1.0.35" 15 | char-device = "0.16.0" 16 | clap = { version = "3.0.0-beta.2.2", package = "nameless-clap" } 17 | data-url = "0.3.0" 18 | duplex = "0.16.0" 19 | flate2 = "1.0.19" 20 | layered-io = { version = "0.23.0", features = ["terminal-io"] } 21 | io-streams = { version = "0.16.0", features = ["layered-io", "terminal-io", "use_char_device", "use_socketpair"] } 22 | io-arrays = "0.14.1" 23 | mime = "0.3.16" 24 | mime_guess = "2.0.3" 25 | percent-encoding = "2.1.0" 26 | basic-text = { version = "0.19.0", features = ["terminal-io"] } 27 | io-extras = "0.18.0" 28 | ureq = { version = "2.0.0", default-features = false, features = ["tls", "charset"] } 29 | url = "2.2.0" 30 | terminal-io = "0.19.0" 31 | ssh2 = { version = "0.9.0", optional = true } 32 | system-interface = { version = "0.27.0", features = ["ssh2"] } 33 | utf8-io = { version = "0.19.0", features = ["layered-io", "terminal-io"] } 34 | whoami = "1.1.0" 35 | 36 | [target.'cfg(not(windows))'.dependencies] 37 | rustix = { version = "0.38.0", features = ["stdio", "process"] } 38 | shell-words = "1.0.0" 39 | 40 | [target.'cfg(windows)'.dependencies] 41 | libc = "0.2.99" 42 | 43 | [dev-dependencies] 44 | humantime = "2.0.1" 45 | kommand = { path = "kommand" } 46 | reaktor = { path = "reaktor" } 47 | regex = "1.4.2" 48 | itertools = "0.12.0" 49 | clap_derive = { version = "3.0.0-beta.2.2", package = "nameless-clap_derive" } 50 | 51 | [workspace] 52 | members = [ 53 | "kommand", 54 | "reaktor", 55 | ] 56 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-Apache-2.0_WITH_LLVM-exception: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | 204 | 205 | --- LLVM Exceptions to the Apache 2.0 License ---- 206 | 207 | As an exception, if, as a result of your compiling your source code, portions 208 | of this Software are embedded into an Object form of such source code, you 209 | may redistribute such embedded portions in such Object form without complying 210 | with the conditions of Sections 4(a), 4(b) and 4(d) of the License. 211 | 212 | In addition, if you combine or link compiled forms of this Software with 213 | software that is licensed under the GPLv2 ("Combined Software") and if a 214 | court of competent jurisdiction determines that the patent provision (Section 215 | 3), the indemnity provision (Section 9) or other Section of the License 216 | conflicts with the conditions of the GPLv2, you may retroactively and 217 | prospectively choose to deem waived or otherwise exclude such Section(s) of 218 | the License, but only in their entirety and only with respect to the Combined 219 | Software. 220 | 221 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Permission is hereby granted, free of charge, to any 2 | person obtaining a copy of this software and associated 3 | documentation files (the "Software"), to deal in the 4 | Software without restriction, including without 5 | limitation the rights to use, copy, modify, merge, 6 | publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software 8 | is furnished to do so, subject to the following 9 | conditions: 10 | 11 | The above copyright notice and this permission notice 12 | shall be included in all copies or substantial portions 13 | of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 16 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 17 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 18 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 19 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 20 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 22 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 23 | DEALINGS IN THE SOFTWARE. 24 | -------------------------------------------------------------------------------- /ORG_CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Bytecode Alliance Organizational Code of Conduct (OCoC) 2 | 3 | *Note*: this Code of Conduct pertains to organizations' behavior. Please also see the [Individual Code of Conduct](CODE_OF_CONDUCT.md). 4 | 5 | ## Preamble 6 | 7 | The Bytecode Alliance (BA) welcomes involvement from organizations, 8 | including commercial organizations. This document is an 9 | *organizational* code of conduct, intended particularly to provide 10 | guidance to commercial organizations. It is distinct from the 11 | [Individual Code of Conduct (ICoC)](CODE_OF_CONDUCT.md), and does not 12 | replace the ICoC. This OCoC applies to any group of people acting in 13 | concert as a BA member or as a participant in BA activities, whether 14 | or not that group is formally incorporated in some jurisdiction. 15 | 16 | The code of conduct described below is not a set of rigid rules, and 17 | we did not write it to encompass every conceivable scenario that might 18 | arise. For example, it is theoretically possible there would be times 19 | when asserting patents is in the best interest of the BA community as 20 | a whole. In such instances, consult with the BA, strive for 21 | consensus, and interpret these rules with an intent that is generous 22 | to the community the BA serves. 23 | 24 | While we may revise these guidelines from time to time based on 25 | real-world experience, overall they are based on a simple principle: 26 | 27 | *Bytecode Alliance members should observe the distinction between 28 | public community functions and private functions — especially 29 | commercial ones — and should ensure that the latter support, or at 30 | least do not harm, the former.* 31 | 32 | ## Guidelines 33 | 34 | * **Do not cause confusion about Wasm standards or interoperability.** 35 | 36 | Having an interoperable WebAssembly core is a high priority for 37 | the BA, and members should strive to preserve that core. It is fine 38 | to develop additional non-standard features or APIs, but they 39 | should always be clearly distinguished from the core interoperable 40 | Wasm. 41 | 42 | Treat the WebAssembly name and any BA-associated names with 43 | respect, and follow BA trademark and branding guidelines. If you 44 | distribute a customized version of software originally produced by 45 | the BA, or if you build a product or service using BA-derived 46 | software, use names that clearly distinguish your work from the 47 | original. (You should still provide proper attribution to the 48 | original, of course, wherever such attribution would normally be 49 | given.) 50 | 51 | Further, do not use the WebAssembly name or BA-associated names in 52 | other public namespaces in ways that could cause confusion, e.g., 53 | in company names, names of commercial service offerings, domain 54 | names, publicly-visible social media accounts or online service 55 | accounts, etc. It may sometimes be reasonable, however, to 56 | register such a name in a new namespace and then immediately donate 57 | control of that account to the BA, because that would help the project 58 | maintain its identity. 59 | 60 | For further guidance, see the BA Trademark and Branding Policy 61 | [TODO: create policy, then insert link]. 62 | 63 | * **Do not restrict contributors.** If your company requires 64 | employees or contractors to sign non-compete agreements, those 65 | agreements must not prevent people from participating in the BA or 66 | contributing to related projects. 67 | 68 | This does not mean that all non-compete agreements are incompatible 69 | with this code of conduct. For example, a company may restrict an 70 | employee's ability to solicit the company's customers. However, an 71 | agreement must not block any form of technical or social 72 | participation in BA activities, including but not limited to the 73 | implementation of particular features. 74 | 75 | The accumulation of experience and expertise in individual persons, 76 | who are ultimately free to direct their energy and attention as 77 | they decide, is one of the most important drivers of progress in 78 | open source projects. A company that limits this freedom may hinder 79 | the success of the BA's efforts. 80 | 81 | * **Do not use patents as offensive weapons.** If any BA participant 82 | prevents the adoption or development of BA technologies by 83 | asserting its patents, that undermines the purpose of the 84 | coalition. The collaboration fostered by the BA cannot include 85 | members who act to undermine its work. 86 | 87 | * **Practice responsible disclosure** for security vulnerabilities. 88 | Use designated, non-public reporting channels to disclose technical 89 | vulnerabilities, and give the project a reasonable period to 90 | respond, remediate, and patch. [TODO: optionally include the 91 | security vulnerability reporting URL here.] 92 | 93 | Vulnerability reporters may patch their company's own offerings, as 94 | long as that patching does not significantly delay the reporting of 95 | the vulnerability. Vulnerability information should never be used 96 | for unilateral commercial advantage. Vendors may legitimately 97 | compete on the speed and reliability with which they deploy 98 | security fixes, but withholding vulnerability information damages 99 | everyone in the long run by risking harm to the BA project's 100 | reputation and to the security of all users. 101 | 102 | * **Respect the letter and spirit of open source practice.** While 103 | there is not space to list here all possible aspects of standard 104 | open source practice, some examples will help show what we mean: 105 | 106 | * Abide by all applicable open source license terms. Do not engage 107 | in copyright violation or misattribution of any kind. 108 | 109 | * Do not claim others' ideas or designs as your own. 110 | 111 | * When others engage in publicly visible work (e.g., an upcoming 112 | demo that is coordinated in a public issue tracker), do not 113 | unilaterally announce early releases or early demonstrations of 114 | that work ahead of their schedule in order to secure private 115 | advantage (such as marketplace advantage) for yourself. 116 | 117 | The BA reserves the right to determine what constitutes good open 118 | source practices and to take action as it deems appropriate to 119 | encourage, and if necessary enforce, such practices. 120 | 121 | ## Enforcement 122 | 123 | Instances of organizational behavior in violation of the OCoC may 124 | be reported by contacting the Bytecode Alliance CoC team at 125 | [report@bytecodealliance.org](mailto:report@bytecodealliance.org). The 126 | CoC team will review and investigate all complaints, and will respond 127 | in a way that it deems appropriate to the circumstances. The CoC team 128 | is obligated to maintain confidentiality with regard to the reporter of 129 | an incident. Further details of specific enforcement policies may be 130 | posted separately. 131 | 132 | When the BA deems an organization in violation of this OCoC, the BA 133 | will, at its sole discretion, determine what action to take. The BA 134 | will decide what type, degree, and duration of corrective action is 135 | needed, if any, before a violating organization can be considered for 136 | membership (if it was not already a member) or can have its membership 137 | reinstated (if it was a member and the BA canceled its membership due 138 | to the violation). 139 | 140 | In practice, the BA's first approach will be to start a conversation, 141 | with punitive enforcement used only as a last resort. Violations 142 | often turn out to be unintentional and swiftly correctable with all 143 | parties acting in good faith. 144 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 |

nameless

3 | 4 |

5 | Full-service command-line parsing 6 |

7 | 8 |

9 | Github Actions CI Status 10 | crates.io page 11 | docs.rs docs 12 | zulip chat 13 |

14 |
15 | 16 | *This is currently an experimental project, and the API and command-line 17 | argument syntax are not currently stable.* 18 | 19 | Nameless provides full-service command-line parsing. This means you just write 20 | a `main` function with arguments with the types you want, add a [conventional] 21 | documentation comment, and it takes care of the rest: 22 | 23 | Rust code: 24 | ```rust 25 | use nameless::{InputByteStream, OutputByteStream}; 26 | use std::io::{self, Read, Write}; 27 | 28 | /// A simple program with input and output 29 | /// 30 | /// # Arguments 31 | /// 32 | /// * `input` - Input source 33 | /// * `output` - Output sink 34 | #[kommand::main] 35 | fn main(mut input: InputByteStream, mut output: OutputByteStream) -> io::Result<()> { 36 | let mut s = String::new(); 37 | input.read_to_string(&mut s)?; 38 | output.write_all(s.as_bytes()) 39 | } 40 | ``` 41 | 42 | Cargo.toml: 43 | ```toml 44 | [dependencies] 45 | kommand = "0" 46 | nameless = "0" 47 | ``` 48 | 49 | Nameless completely handles "string to stream" translation. And in doing so, it 50 | doesn't just support files, but also gzipped files (`*.gz`), 51 | stdin/stdout (`-`), child processes (`$(...)`) (not yet on Windows tho), and 52 | URLs, including `http:`, `https:`, `scp:` (enable the "ssh2" feature), `file:`, 53 | and `data:`. And on output, nameless automatically takes care of piping data 54 | through [`bat`](https://crates.io/crates/bat) for syntax highlighting and 55 | paging. So while your code is busy doing one thing and doing it well, nameless 56 | takes care of streaming the data in and out. 57 | 58 | "Everything is a URL, and more", on Linux, macOS, Windows, and more. 59 | 60 | `kommand::main` parses the documentation comment to extract the program 61 | description and the arguments. The command-line usage for the example above 62 | looks like this: 63 | 64 | ``` 65 | $ cargo run -- --help 66 | simple-filter 0.0.0 67 | A simple program with input and output 68 | 69 | USAGE: 70 | simple-filter 71 | 72 | FLAGS: 73 | -h, --help Prints help information 74 | -V, --version Prints version information 75 | 76 | ARGS: 77 | Input source 78 | Output sink 79 | ``` 80 | 81 | ## More features 82 | 83 | `kommand` is a wrapper around `clap_derive`, and supports the same attributes. 84 | 85 | To add a flag, for example, `#[kommand(short = 'n', long)] number: u32` means 86 | an argument with type `i32` which can be specified with `-n` or `--number` on 87 | the command line. The [grep example] and [basic example] show examples of this. 88 | 89 | The [clap-v3 documentation] for the full list of available features. 90 | 91 | ## What's inside 92 | 93 | This library provides: 94 | 95 | - New stream types, [`InputByteStream`], [`OutputByteStream`], and 96 | [`InteractiveByteStream`] for working with byte streams, and 97 | [`InputTextStream`], [`OutputTextStream`], and [`InteractiveTextStream`] 98 | for working with text streams. These implement [`Read`] and [`Write`] in 99 | the usual way, so they interoperate with existing Rust code. 100 | 101 | You can use all these types in type-aware command-line parsing packages 102 | such as [`nameless-clap_derive`] or this library's own [`kommand`]. 103 | (`nameless-clap_derive` is a temporary fork of [`clap_derive`]; we are 104 | in the process of upstreaming our patches). 105 | 106 | - A new command-line parsing package, [`kommand`], which is similar to 107 | to [`paw`], but uses function argument syntax instead of having an options 108 | struct. Command-line arguments can use any type which implements the standard 109 | `FromStr` trait, including builtin types like `i32` or `bool` or library 110 | types like [`Regex`] or [`Duration`]. See [the examples directory] for 111 | more examples. 112 | 113 | ## Why "nameless"? 114 | 115 | The name "nameless" refers to how, from the program's perspective, the string 116 | names of the inputs and outputs are hidden by the library. 117 | 118 | Of course, sometimes you do want to know the name of an input, such as to 119 | display it in an error message. Nameless's [`pseudonym`] mechanism provides 120 | names for [`InputByteStream`] and other stream types, which allow the name 121 | to be displayed without exposing it to the application. 122 | 123 | And sometimes you want to know an input file's extension, to determine what 124 | type of input it is. [`InputByteStream`] and other stream types have a 125 | [`media_type`] function which returns the [media type] (aka MIME type). If the 126 | input is a file, the type is inferred from the extension; if it's an HTTP 127 | stream, the type is inferred from the `Content-Type` header, and so on. 128 | 129 | Why is it important to hide the name? On a theoretical level, most 130 | computations shouldn't care about where data is coming from or where it's 131 | going. This helps separate the concerns of what the program primarily does 132 | and how the program interacts with the local organization of resources. 133 | On a practical level, this is what makes it possible for nameless to 134 | transparently support URLs, child processes, and other things. And, it will 135 | support applications which are useful on conventional platforms, but which 136 | also work on platforms that lack filesystems, such as embedded systems or 137 | systems with new kinds of storage abstractions. 138 | 139 | Hiding the names also helps programs avoid accidentally having behavior that 140 | depends on the names of files it accesses, which is a common source of trouble 141 | in deterministic-build environments. 142 | 143 | ## Data URLs 144 | 145 | [`data:` URLs] aren't as widely known, but are cool and deserve special 146 | mention. They carry a payload string in the URL itself which produced as the 147 | input stream. For example, opening `data:,Hello%2C%20World!` produces an 148 | input stream that reads the string "Hello, World!". Payloads can also be 149 | base64 encoded, like this: `data:text/plain;base64,SGVsbG8sIFdvcmxkIQ==`. 150 | So you can pass a literal string directly into a program's input stream 151 | instead of creating a temporary file. 152 | 153 | ## Looking forward 154 | 155 | Nameless is actively evolving! Watch this space for much more to come, and 156 | [chat with us in Zulip], if you're interested in where we're going. 157 | 158 | ## Literary reference 159 | 160 | > ‘This must be the wood,’ she said thoughtfully to herself, ‘where things 161 | > have no names.’ 162 | 163 | — "Through the Looking Glass", by Lewis Carroll 164 | 165 | [conventional]: https://doc.rust-lang.org/stable/rust-by-example/meta/doc.html 166 | [basic example]: https://github.com/sunfishcode/nameless/blob/main/examples/basic.rs 167 | [grep example]: https://github.com/sunfishcode/nameless/blob/main/examples/grep.rs 168 | [clap-v3 documentation]: https://docs.rs/clap-v3/latest/clap_v3/ 169 | [`nameless-clap_derive`]: https://crates.io/crates/nameless-clap_derive 170 | [`clap_derive`]: https://crates.io/crates/clap_derive 171 | [`paw`]: https://crates.io/crates/paw 172 | [`kommand`]: https://crates.io/crates/kommand 173 | [`Read`]: https://doc.rust-lang.org/std/io/trait.Read.html 174 | [`Write`]: https://doc.rust-lang.org/std/io/trait.Write.html 175 | [`InputByteStream`]: https://docs.rs/nameless/latest/nameless/struct.InputByteStream.html 176 | [`OutputByteStream`]: https://docs.rs/nameless/latest/nameless/struct.OutputByteStream.html 177 | [`InteractiveByteStream`]: https://docs.rs/nameless/latest/nameless/struct.InteractiveByteStream.html 178 | [`InputTextStream`]: https://docs.rs/nameless/latest/nameless/struct.InputTextStream.html 179 | [`OutputTextStream`]: https://docs.rs/nameless/latest/nameless/struct.OutputTextStream.html 180 | [`InteractiveTextStream`]: https://docs.rs/nameless/latest/nameless/struct.InteractiveTextStream.html 181 | [`Regex`]: https://docs.rs/regex/latest/regex/struct.Regex.html 182 | [`Duration`]: https://docs.rs/humantime/latest/humantime/struct.Duration.html 183 | [the examples directory]: examples 184 | [`data:` URLs]: https://fetch.spec.whatwg.org/#data-urls 185 | [`pseudonym`]: https://docs.rs/nameless/latest/nameless/struct.InputByteStream.html#method.pseudonym 186 | [media type]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types 187 | [`media_type`]: https://docs.rs/nameless/latest/nameless/struct.InputByteStream.html#method.media_type 188 | [chat with us in Zulip]: https://bytecodealliance.zulipchat.com/#narrow/stream/219900-wasi 189 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | Building secure foundations for software development is at the core of what we do in the Bytecode Alliance. Contributions of external security researchers are a vital part of that. 4 | 5 | ## Scope 6 | 7 | If you believe you've found a security issue in any website, service, or software owned or operated by the Bytecode Alliance, we encourage you to notify us. 8 | 9 | ## How to Submit a Report 10 | 11 | To submit a vulnerability report to the Bytecode Alliance, please contact us at [security@bytecodealliance.org](mailto:security@bytecodealliance.org). Your submission will be reviewed and validated by a member of our security team. 12 | 13 | ## Safe Harbor 14 | 15 | The Bytecode Alliance supports safe harbor for security researchers who: 16 | 17 | * Make a good faith effort to avoid privacy violations, destruction of data, and interruption or degradation of our services. 18 | * Only interact with accounts you own or with explicit permission of the account holder. If you do encounter Personally Identifiable Information (PII) contact us immediately, do not proceed with access, and immediately purge any local information. 19 | * Provide us with a reasonable amount of time to resolve vulnerabilities prior to any disclosure to the public or a third-party. 20 | 21 | We will consider activities conducted consistent with this policy to constitute "authorized" conduct and will not pursue civil action or initiate a complaint to law enforcement. We will help to the extent we can if legal action is initiated by a third party against you. 22 | 23 | Please submit a report to us before engaging in conduct that may be inconsistent with or unaddressed by this policy. 24 | 25 | ## Preferences 26 | 27 | * Please provide detailed reports with reproducible steps and a clearly defined impact. 28 | * Submit one vulnerability per report. 29 | * Social engineering (e.g. phishing, vishing, smishing) is prohibited. 30 | -------------------------------------------------------------------------------- /build.rs: -------------------------------------------------------------------------------- 1 | use std::env::var; 2 | use std::io::Write; 3 | 4 | fn main() { 5 | use_feature_or_nothing("can_vector"); // https://github.com/rust-lang/rust/issues/69941 6 | use_feature_or_nothing("clamp"); // https://github.com/rust-lang/rust/issues/44095 7 | use_feature_or_nothing("extend_one"); // https://github.com/rust-lang/rust/issues/72631 8 | use_feature_or_nothing("io_error_more"); // https://github.com/rust-lang/rust/issues/86442 9 | use_feature_or_nothing("pattern"); // https://github.com/rust-lang/rust/issues/27721 10 | use_feature_or_nothing("seek_stream_len"); // https://github.com/rust-lang/rust/issues/59359 11 | use_feature_or_nothing("shrink_to"); // https://github.com/rust-lang/rust/issues/56431 12 | use_feature_or_nothing("toowned_clone_into"); // https://github.com/rust-lang/rust/issues/41263 13 | use_feature_or_nothing("try_reserve"); // https://github.com/rust-lang/rust/issues/56431 14 | use_feature_or_nothing("unix_socket_peek"); // https://github.com/rust-lang/rust/issues/76923 15 | use_feature_or_nothing("windows_by_handle"); // https://github.com/rust-lang/rust/issues/63010 16 | use_feature_or_nothing("write_all_vectored"); // https://github.com/rust-lang/rust/issues/70436 17 | // https://doc.rust-lang.org/unstable-book/library-features/windows-file-type-ext.html 18 | use_feature_or_nothing("windows_file_type_ext"); 19 | 20 | // Don't rerun this on changes other than build.rs, as we only depend on 21 | // the rustc version. 22 | println!("cargo:rerun-if-changed=build.rs"); 23 | } 24 | 25 | fn use_feature_or_nothing(feature: &str) { 26 | if has_feature(feature) { 27 | use_feature(feature); 28 | } 29 | } 30 | 31 | fn use_feature(feature: &str) { 32 | println!("cargo:rustc-cfg={}", feature); 33 | } 34 | 35 | /// Test whether the rustc at `var("RUSTC")` supports the given feature. 36 | fn has_feature(feature: &str) -> bool { 37 | can_compile(format!( 38 | "#![allow(stable_features)]\n#![feature({})]", 39 | feature 40 | )) 41 | } 42 | 43 | /// Test whether the rustc at `var("RUSTC")` can compile the given code. 44 | fn can_compile>(test: T) -> bool { 45 | use std::process::Stdio; 46 | 47 | let out_dir = var("OUT_DIR").unwrap(); 48 | let rustc = var("RUSTC").unwrap(); 49 | let target = var("TARGET").unwrap(); 50 | 51 | // Use `RUSTC_WRAPPER` if it's set, unless it's set to an empty string, as 52 | // documented [here]. 53 | // [here]: https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-reads 54 | let wrapper = var("RUSTC_WRAPPER") 55 | .ok() 56 | .and_then(|w| if w.is_empty() { None } else { Some(w) }); 57 | 58 | let mut cmd = if let Some(wrapper) = wrapper { 59 | let mut cmd = std::process::Command::new(wrapper); 60 | // The wrapper's first argument is supposed to be the path to rustc. 61 | cmd.arg(rustc); 62 | cmd 63 | } else { 64 | std::process::Command::new(rustc) 65 | }; 66 | 67 | cmd.arg("--crate-type=rlib") // Don't require `main`. 68 | .arg("--emit=metadata") // Do as little as possible but still parse. 69 | .arg("--target") 70 | .arg(target) 71 | .arg("--out-dir") 72 | .arg(out_dir); // Put the output somewhere inconsequential. 73 | 74 | // If Cargo wants to set RUSTFLAGS, use that. 75 | if let Ok(rustflags) = var("CARGO_ENCODED_RUSTFLAGS") { 76 | if !rustflags.is_empty() { 77 | for arg in rustflags.split('\x1f') { 78 | cmd.arg(arg); 79 | } 80 | } 81 | } 82 | 83 | let mut child = cmd 84 | .arg("-") // Read from stdin. 85 | .stdin(Stdio::piped()) // Stdin is a pipe. 86 | .stderr(Stdio::null()) // Errors from feature detection aren't interesting and can be confusing. 87 | .spawn() 88 | .unwrap(); 89 | 90 | writeln!(child.stdin.take().unwrap(), "{}", test.as_ref()).unwrap(); 91 | 92 | child.wait().unwrap().success() 93 | } 94 | -------------------------------------------------------------------------------- /examples/basic.rs: -------------------------------------------------------------------------------- 1 | //! This is a port of `clap_derive`'s [basic.rs example] to use `kommand`. 2 | //! 3 | //! Note the use of `InputByteStream` and `OutputByteStream` instead of 4 | //! `PathBuf` for inputs and outputs. "files" is renamed to "inputs", as the 5 | //! inputs need not actually be files 😊. 6 | //! 7 | //! [basic.rs example]: https://github.com/clap-rs/clap/blob/master/clap_derive/examples/basic.rs 8 | 9 | use nameless::{InputByteStream, OutputByteStream}; 10 | 11 | /// A basic example 12 | /// 13 | /// # Arguments 14 | /// 15 | /// * `debug` - Activate debug mode 16 | /// * `verbose` - Verbose mode (-v, -vv, -vvv, etc.) 17 | /// * `speed` - Set speed 18 | /// * `output` - Output sink 19 | /// * `nb_cars` - Number of cars 20 | /// * `level` - admin_level to consider 21 | /// * `inputs` - inputs to process 22 | #[kommand::main] 23 | fn main( 24 | // A flag, true if used in the command line. The name of the argument will be, 25 | // by default, based on the name of the field. 26 | #[kommand(short, long)] debug: bool, 27 | // The number of occurrences of the `v/verbose` flag 28 | #[kommand(short, long, parse(from_occurrences))] verbose: u8, 29 | #[kommand(short, long, default_value = "42")] speed: f64, 30 | #[kommand(short, long)] output: OutputByteStream, 31 | // the long option will be translated by default to kebab case, i.e. `--nb-cars`. 32 | #[kommand(short = 'c', long)] nb_cars: Option, 33 | #[kommand(short, long)] level: Vec, 34 | #[kommand(name = "INPUT")] inputs: Vec, 35 | ) { 36 | dbg!(debug, verbose, speed, output, nb_cars, level, inputs); 37 | } 38 | -------------------------------------------------------------------------------- /examples/cat.rs: -------------------------------------------------------------------------------- 1 | //! A simple cat-like program using `kommand` and `InputTextStream`. 2 | //! Unlike regular cat, this cat supports URLs and gzip. Meow! 3 | 4 | use clap::{ambient_authority, TryFromOsArg}; 5 | use nameless::{InputTextStream, OutputTextStream}; 6 | use std::io::copy; 7 | 8 | /// # Arguments 9 | /// 10 | /// * `inputs` - Input sources, stdin if none 11 | #[kommand::main] 12 | fn main(inputs: Vec) -> anyhow::Result<()> { 13 | let mut output = OutputTextStream::try_from_os_str_arg("-".as_ref(), ambient_authority())?; 14 | 15 | for mut input in inputs { 16 | copy(&mut input, &mut output)?; 17 | } 18 | 19 | Ok(()) 20 | } 21 | -------------------------------------------------------------------------------- /examples/clap.rs: -------------------------------------------------------------------------------- 1 | //! A simple example of using `clap_derive` with `InputByteStream` and 2 | //! `OutputByteStream`. Compared to [`structopt`'s example], it's 3 | //! simpler and requires less boilerplate. 4 | //! 5 | //! [`structopt`'s example]: https://docs.rs/structopt/latest/structopt/#how-to-derivestructopt 6 | 7 | use clap::Clap; 8 | use nameless::{InputByteStream, OutputByteStream}; 9 | 10 | #[derive(Debug, Clap)] 11 | #[clap(name = "example", about = "An example of StructOpt usage.")] 12 | struct Opt { 13 | /// Activate debug mode 14 | // short and long flags (-d, --debug) will be deduced from the field's name 15 | #[clap(short, long)] 16 | debug: bool, 17 | 18 | /// Set speed 19 | // we don't want to name it "speed", need to look smart 20 | #[clap(short = 'v', long = "velocity", default_value = "42")] 21 | speed: f64, 22 | 23 | /// Input source 24 | input: InputByteStream, 25 | 26 | /// Output sink, stdout if not present 27 | output: Option, 28 | } 29 | 30 | fn main() { 31 | let opt = Opt::parse(); 32 | println!("{:?}", opt); 33 | } 34 | -------------------------------------------------------------------------------- /examples/copy.rs: -------------------------------------------------------------------------------- 1 | //! A simple program using `kommand` that copies from an 2 | //! `InputByteStream` into an `OutputByteStream`. 3 | 4 | use nameless::{InputByteStream, OutputByteStream}; 5 | use std::io::copy; 6 | 7 | /// # Arguments 8 | /// 9 | /// * `input` - Input source 10 | /// * `output` - Output sink 11 | #[kommand::main] 12 | fn main(mut input: InputByteStream, mut output: OutputByteStream) -> anyhow::Result<()> { 13 | copy(&mut input, &mut output)?; 14 | 15 | Ok(()) 16 | } 17 | -------------------------------------------------------------------------------- /examples/copy_with_defaults.rs: -------------------------------------------------------------------------------- 1 | //! A simple program using `kommand` that copies from an 2 | //! `InputByteStream` into an `OutputByteStream`. 3 | 4 | use clap::{ambient_authority, TryFromOsArg}; 5 | use nameless::{InputByteStream, OutputByteStream}; 6 | use std::io::copy; 7 | 8 | /// # Arguments 9 | /// 10 | /// * `input` - Input source, stdin if not present 11 | /// * `output` - Output sink, stdout if not present 12 | #[kommand::main] 13 | fn main(input: Option, output: Option) -> anyhow::Result<()> { 14 | let mut input = if let Some(input) = input { 15 | input 16 | } else { 17 | InputByteStream::try_from_os_str_arg("-".as_ref(), ambient_authority())? 18 | }; 19 | let mut output = if let Some(output) = output { 20 | output 21 | } else { 22 | OutputByteStream::try_from_os_str_arg("-".as_ref(), ambient_authority())? 23 | }; 24 | 25 | copy(&mut input, &mut output)?; 26 | 27 | Ok(()) 28 | } 29 | -------------------------------------------------------------------------------- /examples/grep.rs: -------------------------------------------------------------------------------- 1 | //! A simple grep-like program using `kommand` and `InputTextStream`. 2 | //! Unlike regular grep, this grep supports URLs and gzip. Perg! 3 | 4 | use nameless::{InputTextStream, LazyOutput, MediaType, OutputTextStream}; 5 | use regex::Regex; 6 | use std::io::{BufRead, BufReader, Write}; 7 | 8 | /// # Arguments 9 | /// 10 | /// * `pattern` - The regex to search for 11 | /// * `output` - Output sink 12 | /// * `inputs` - Input sources 13 | /// * `inputs_with_matches` - Print only the names of the inputs containing matches 14 | #[kommand::main] 15 | fn main( 16 | pattern: Regex, 17 | output: LazyOutput, 18 | inputs: Vec, 19 | #[kommand(short = 'l', long)] inputs_with_matches: bool, 20 | ) -> anyhow::Result<()> { 21 | let mut output = output.materialize(MediaType::text())?; 22 | 23 | let print_inputs = inputs.len() > 1; 24 | 25 | 'next_input: for input in inputs { 26 | let pseudonym = input.pseudonym(); 27 | for line in BufReader::new(input).lines() { 28 | let line = line?; 29 | if pattern.is_match(&line) { 30 | if inputs_with_matches { 31 | output.write_pseudonym(&pseudonym)?; 32 | writeln!(output, "")?; 33 | continue 'next_input; 34 | } 35 | if print_inputs { 36 | output.write_pseudonym(&pseudonym)?; 37 | write!(output, ":")?; 38 | } 39 | writeln!(output, "{}", line)?; 40 | } 41 | } 42 | } 43 | 44 | Ok(()) 45 | } 46 | -------------------------------------------------------------------------------- /examples/kommand.rs: -------------------------------------------------------------------------------- 1 | //! Copy from an input byte stream to an output byte stream. 2 | //! This uses `nameless` types for the streams so it accepts 3 | //! any regular file name, gzipped file name, any http, file, 4 | //! or data URL, or "-" for stdin or stdout. 5 | 6 | use nameless::{InputByteStream, OutputByteStream}; 7 | use std::io::copy; 8 | 9 | /// A minimal example showing how `kommand`, `InputByteStream`, 10 | /// and `OutputByteStream` all work together. 11 | /// 12 | /// # Arguments 13 | /// 14 | /// * `input` - Input source 15 | /// * `output` - Output sink 16 | #[kommand::main] 17 | fn main(mut input: InputByteStream, mut output: OutputByteStream) -> anyhow::Result<()> { 18 | copy(&mut input, &mut output)?; 19 | 20 | Ok(()) 21 | } 22 | -------------------------------------------------------------------------------- /examples/repl-client.rs: -------------------------------------------------------------------------------- 1 | //! An example client program for the `repl` example. See the `repl` example 2 | //! for details. 3 | 4 | use io_streams::BufReaderLineWriter; 5 | use nameless::InteractiveTextStream; 6 | use std::io::{BufRead, Read, Write}; 7 | use std::str; 8 | 9 | const PROMPT: &str = "prompt> \u{34f}"; 10 | 11 | #[kommand::main] 12 | fn main(io: InteractiveTextStream) -> anyhow::Result<()> { 13 | let mut io = BufReaderLineWriter::new(io); 14 | let mut v = [0_u8; PROMPT.len()]; 15 | let mut s = String::new(); 16 | 17 | // Read the "prompt> ". 18 | io.read_exact(&mut v)?; 19 | if str::from_utf8(&v).unwrap() != PROMPT { 20 | panic!("missed prompt"); 21 | } 22 | 23 | // Write "hello". 24 | writeln!(io, "hello")?; 25 | 26 | io.read_line(&mut s)?; 27 | if s != "[received \"hello\"]\n" { 28 | panic!("missed response: '{}'", s); 29 | } 30 | 31 | // Read another "prompt> ". 32 | io.read_exact(&mut v)?; 33 | if str::from_utf8(&v).unwrap() != PROMPT { 34 | panic!("missed second prompt: {:?}", String::from_utf8_lossy(&v)); 35 | } 36 | 37 | // Write "world". 38 | writeln!(io, "world")?; 39 | 40 | s.clear(); 41 | io.read_line(&mut s)?; 42 | if s != "[received \"world\"]\n" { 43 | panic!("missed response: '{}'", s); 44 | } 45 | 46 | // Read one more "prompt> ". 47 | io.read_exact(&mut v)?; 48 | if str::from_utf8(&v).unwrap() != PROMPT { 49 | panic!("missed last prompt"); 50 | } 51 | 52 | // Walk away! `repl` is cool with this. 53 | drop(io); 54 | Ok(()) 55 | } 56 | -------------------------------------------------------------------------------- /examples/repl.rs: -------------------------------------------------------------------------------- 1 | //! A simple REPL program using `kommand` and `InteractiveTextStream`. 2 | //! 3 | //! Run it interactively with the process' (stdin, stdout): 4 | //! ``` 5 | //! $ cargo run --quiet --example repl - 6 | //! prompt> hello 7 | //! [entered "hello"] 8 | //! prompt> world 9 | //! [entered "world"] 10 | //! ``` 11 | //! 12 | //! Run it interactively with the process' tty. This works the same way, but 13 | //! doesn't detect terminal colors, because we need the "TERM" environment 14 | //! variable to do that. 15 | //! ``` 16 | //! $ cargo run --quiet --example repl /dev/tty 17 | //! prompt> hello 18 | //! [entered "hello"] 19 | //! prompt> world 20 | //! [entered "world"] 21 | //! ``` 22 | //! 23 | //! Run it piped to a client process: 24 | //! ``` 25 | //! $ cargo run --quiet --example repl '$(cargo run --quiet --example repl-client -)' 26 | //! [entered "hello"] 27 | //! [entered "world"] 28 | //! ``` 29 | //! 30 | //! Run it connected to the same program but use a socket instead of a 31 | //! pipe -- note that this opens a network port! 32 | //! 33 | //! ``` 34 | //! $ cargo run --quiet --example repl accept://localhost:9999 & 35 | //! ... 36 | //! $ cargo run --quiet --example repl-client connect://localhost:9999 37 | //! [entered "hello"] 38 | //! [entered "world"] 39 | //! ``` 40 | 41 | use io_streams::BufReaderLineWriter; 42 | use layered_io::Bufferable; 43 | use nameless::InteractiveTextStream; 44 | use std::io::{self, BufRead, Write}; 45 | use terminal_io::{TerminalColorSupport, WriteTerminal}; 46 | 47 | #[kommand::main] 48 | fn main(io: InteractiveTextStream) -> anyhow::Result<()> { 49 | let io = BufReaderLineWriter::new(io); 50 | let color = 51 | io.color_support() != TerminalColorSupport::Monochrome && std::env::var("NOCOLOR").is_err(); 52 | 53 | match repl(io, color) { 54 | Ok(()) => Ok(()), 55 | Err(e) => match e.kind() { 56 | io::ErrorKind::BrokenPipe => Ok(()), 57 | _ => Err(e.into()), 58 | }, 59 | } 60 | } 61 | 62 | fn repl(mut io: BufReaderLineWriter, color: bool) -> io::Result<()> { 63 | let mut s = String::new(); 64 | 65 | loop { 66 | if color { 67 | write!(io, "\u{1b}[01;36mprompt>\u{1b}[0m \u{34f}")?; 68 | } else { 69 | write!(io, "prompt> \u{34f}")?; 70 | } 71 | 72 | if io.read_line(&mut s)? == 0 { 73 | // End of stream. 74 | io.abandon(); 75 | return Ok(()); 76 | } 77 | 78 | if s.trim() == "exit" { 79 | io.abandon(); 80 | return Ok(()); 81 | } 82 | 83 | eprintln!("[logging \"{}\"]", s.trim().escape_default()); 84 | writeln!(io, "[received \"{}\"]", s.trim().escape_default())?; 85 | 86 | s.clear(); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /examples/sleep.rs: -------------------------------------------------------------------------------- 1 | //! A simple program using `kommand` that sleeps for a given duration, which 2 | //! may be given in any format recognized by [`humantime::parse_duration`]. 3 | //! 4 | //! [`humantime::parse_duration`]: https://docs.rs/humantime/latest/humantime/fn.parse_duration.html 5 | 6 | use humantime::Duration; 7 | 8 | /// # Arguments 9 | /// 10 | /// * `duration` - Time to sleep 11 | #[kommand::main] 12 | fn main(duration: Duration) { 13 | std::thread::sleep(duration.into()); 14 | } 15 | -------------------------------------------------------------------------------- /examples/text-cat.rs: -------------------------------------------------------------------------------- 1 | //! A simple cat-like program using `kommand` and `InputTextStream`. 2 | //! Unlike regular cat, this cat supports URLs and gzip. Meow! 3 | 4 | use basic_text::copy_text; 5 | use itertools::Itertools; 6 | use nameless::{InputTextStream, LazyOutput, MediaType, OutputTextStream}; 7 | 8 | /// # Arguments 9 | /// 10 | /// * `inputs` - Input sources, stdin if none 11 | #[kommand::main] 12 | fn main(output: LazyOutput, inputs: Vec) -> anyhow::Result<()> { 13 | let media_type = match inputs.iter().next() { 14 | Some(first) if inputs.iter().map(InputTextStream::media_type).all_equal() => { 15 | first.media_type().clone() 16 | } 17 | _ => MediaType::text(), 18 | }; 19 | 20 | let mut output = output.materialize(media_type)?; 21 | 22 | for mut input in inputs { 23 | copy_text(&mut input, &mut output)?; 24 | } 25 | 26 | Ok(()) 27 | } 28 | -------------------------------------------------------------------------------- /examples/text-grep.rs: -------------------------------------------------------------------------------- 1 | //! A simple grep-like program using `kommand` and `InputTextStream`. 2 | //! Unlike regular grep, this grep supports URLs and gzip. Perg! 3 | 4 | use clap::{ambient_authority, TryFromOsArg}; 5 | use nameless::{InputTextStream, OutputTextStream}; 6 | use regex::Regex; 7 | use std::io::{self, BufRead, BufReader, Write}; 8 | 9 | /// # Arguments 10 | /// 11 | /// * `pattern` - The regex to search for 12 | /// * `inputs` - Input sources, stdin if none 13 | #[kommand::main] 14 | fn main(pattern: Regex, mut inputs: Vec) -> anyhow::Result<()> { 15 | let mut output = OutputTextStream::try_from_os_str_arg("-".as_ref(), ambient_authority())?; 16 | 17 | if inputs.is_empty() { 18 | inputs.push(InputTextStream::try_from_os_str_arg( 19 | "-".as_ref(), 20 | ambient_authority(), 21 | )?); 22 | } 23 | 24 | let print_inputs = inputs.len() > 1; 25 | 26 | 'inputs: for input in inputs { 27 | let pseudonym = input.pseudonym(); 28 | let reader = BufReader::new(input); 29 | for line in reader.lines() { 30 | let line = line?; 31 | if pattern.is_match(&line) { 32 | if let Err(e) = (|| -> io::Result<()> { 33 | if print_inputs { 34 | output.write_pseudonym(&pseudonym)?; 35 | write!(output, ":")?; 36 | } 37 | writeln!(output, "{}", line) 38 | })() { 39 | match e.kind() { 40 | io::ErrorKind::BrokenPipe => break 'inputs, 41 | _ => return Err(e.into()), 42 | } 43 | } 44 | } 45 | } 46 | } 47 | 48 | Ok(()) 49 | } 50 | -------------------------------------------------------------------------------- /kommand/COPYRIGHT: -------------------------------------------------------------------------------- 1 | Short version for non-lawyers: 2 | 3 | `nameless` is triple-licensed under Apache 2.0 with the LLVM Exception, 4 | Apache 2.0, and MIT terms. 5 | 6 | 7 | Longer version: 8 | 9 | Copyrights in the `nameless` project are retained by their contributors. 10 | No copyright assignment is required to contribute to the `nameless` 11 | project. 12 | 13 | Some files include code derived from Rust's `libstd`; see the comments in 14 | the code for details. 15 | 16 | Except as otherwise noted (below and/or in individual files), `nameless` 17 | is licensed under: 18 | 19 | - the Apache License, Version 2.0, with the LLVM Exception 20 | or 21 | 22 | - the Apache License, Version 2.0 23 | or 24 | , 25 | - or the MIT license 26 | or 27 | , 28 | 29 | at your option. 30 | -------------------------------------------------------------------------------- /kommand/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "kommand" 3 | version = "0.15.2" 4 | description = "Command-line arguments via function arguments" 5 | authors = ["Dan Gohman "] 6 | edition = "2021" 7 | license = "Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT" 8 | keywords = ["cli", "macro", "main", "parser"] 9 | categories = ["command-line-interface", "command-line-utilities", "parsing", "rust-patterns"] 10 | repository = "https://github.com/sunfishcode/nameless" 11 | 12 | [lib] 13 | proc-macro = true 14 | 15 | [dependencies] 16 | heck = "0.4.0" 17 | syn = { version = "1.0.54", features = ["full", "extra-traits", "visit-mut"] } 18 | proc-macro2 = { version = "1.0.2", features = ["nightly"] } 19 | quote = "1.0.2" 20 | pulldown-cmark = "0.9.0" 21 | 22 | [dev-dependencies] 23 | clap = { version = "3.0.0-beta.2", package = "nameless-clap" } 24 | clap_derive = { version = "3.0.0-beta.2", package = "nameless-clap_derive" } 25 | nameless = { path = ".." } 26 | -------------------------------------------------------------------------------- /kommand/LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /kommand/LICENSE-Apache-2.0_WITH_LLVM-exception: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | 204 | 205 | --- LLVM Exceptions to the Apache 2.0 License ---- 206 | 207 | As an exception, if, as a result of your compiling your source code, portions 208 | of this Software are embedded into an Object form of such source code, you 209 | may redistribute such embedded portions in such Object form without complying 210 | with the conditions of Sections 4(a), 4(b) and 4(d) of the License. 211 | 212 | In addition, if you combine or link compiled forms of this Software with 213 | software that is licensed under the GPLv2 ("Combined Software") and if a 214 | court of competent jurisdiction determines that the patent provision (Section 215 | 3), the indemnity provision (Section 9) or other Section of the License 216 | conflicts with the conditions of the GPLv2, you may retroactively and 217 | prospectively choose to deem waived or otherwise exclude such Section(s) of 218 | the License, but only in their entirety and only with respect to the Combined 219 | Software. 220 | 221 | -------------------------------------------------------------------------------- /kommand/LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Permission is hereby granted, free of charge, to any 2 | person obtaining a copy of this software and associated 3 | documentation files (the "Software"), to deal in the 4 | Software without restriction, including without 5 | limitation the rights to use, copy, modify, merge, 6 | publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software 8 | is furnished to do so, subject to the following 9 | conditions: 10 | 11 | The above copyright notice and this permission notice 12 | shall be included in all copies or substantial portions 13 | of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 16 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 17 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 18 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 19 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 20 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 22 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 23 | DEALINGS IN THE SOFTWARE. 24 | -------------------------------------------------------------------------------- /kommand/README.md: -------------------------------------------------------------------------------- 1 |
2 |

kommand

3 | 4 |

5 | Command-line arguments via function arguments 6 |

7 | 8 |

9 | Github Actions CI Status 10 | crates.io page 11 | docs.rs docs 12 |

13 |
14 | 15 | This is a command-line parser similar to [`paw`] but which allows 16 | arguments to be given as function arguments rather than as struct 17 | fields. 18 | 19 | See [`nameless`] for examples. 20 | 21 | [`nameless`]: https://github.com/sunfishcode/nameless 22 | -------------------------------------------------------------------------------- /kommand/examples/add.rs: -------------------------------------------------------------------------------- 1 | /// Simple example program that adds numbers given on the command-line and 2 | /// in environment variables. 3 | /// 4 | /// # Arguments 5 | /// 6 | /// * `x` - x marks the spot 7 | /// * `y` - why ask y 8 | /// 9 | /// # Environment Variables 10 | /// 11 | /// * `z` - z for zest 12 | /// * `w` - it's not any trouble, you know it's a w 13 | #[kommand::main] 14 | fn main(x: i32, y: i32) { 15 | #[env_or_default] 16 | let z: i32 = 0; 17 | #[env_or_default] 18 | let w: i32 = 0; 19 | 20 | println!("{}", x + y + z + w); 21 | } 22 | -------------------------------------------------------------------------------- /reaktor/COPYRIGHT: -------------------------------------------------------------------------------- 1 | Short version for non-lawyers: 2 | 3 | `nameless` is triple-licensed under Apache 2.0 with the LLVM Exception, 4 | Apache 2.0, and MIT terms. 5 | 6 | 7 | Longer version: 8 | 9 | Copyrights in the `nameless` project are retained by their contributors. 10 | No copyright assignment is required to contribute to the `nameless` 11 | project. 12 | 13 | Some files include code derived from Rust's `libstd`; see the comments in 14 | the code for details. 15 | 16 | Except as otherwise noted (below and/or in individual files), `nameless` 17 | is licensed under: 18 | 19 | - the Apache License, Version 2.0, with the LLVM Exception 20 | or 21 | 22 | - the Apache License, Version 2.0 23 | or 24 | , 25 | - or the MIT license 26 | or 27 | , 28 | 29 | at your option. 30 | -------------------------------------------------------------------------------- /reaktor/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "reaktor" 3 | version = "0.15.2" 4 | description = "Reaktor" 5 | authors = ["Dan Gohman "] 6 | edition = "2021" 7 | license = "Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT" 8 | keywords = ["cli", "macro", "main", "parser"] 9 | categories = ["command-line-interface", "command-line-utilities", "parsing", "rust-patterns"] 10 | repository = "https://github.com/sunfishcode/nameless" 11 | 12 | [lib] 13 | proc-macro = true 14 | 15 | [dependencies] 16 | syn = { version = "1.0.54", features = ["full", "extra-traits"] } 17 | proc-macro2 = { version = "1.0.2", features = ["nightly"] } 18 | quote = "1.0.2" 19 | 20 | [dev-dependencies] 21 | clap = { version = "3.0.0-beta.2.2", package = "nameless-clap" } 22 | clap_derive = { version = "3.0.0-beta.2.2", package = "nameless-clap_derive" } 23 | -------------------------------------------------------------------------------- /reaktor/LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /reaktor/LICENSE-Apache-2.0_WITH_LLVM-exception: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | 204 | 205 | --- LLVM Exceptions to the Apache 2.0 License ---- 206 | 207 | As an exception, if, as a result of your compiling your source code, portions 208 | of this Software are embedded into an Object form of such source code, you 209 | may redistribute such embedded portions in such Object form without complying 210 | with the conditions of Sections 4(a), 4(b) and 4(d) of the License. 211 | 212 | In addition, if you combine or link compiled forms of this Software with 213 | software that is licensed under the GPLv2 ("Combined Software") and if a 214 | court of competent jurisdiction determines that the patent provision (Section 215 | 3), the indemnity provision (Section 9) or other Section of the License 216 | conflicts with the conditions of the GPLv2, you may retroactively and 217 | prospectively choose to deem waived or otherwise exclude such Section(s) of 218 | the License, but only in their entirety and only with respect to the Combined 219 | Software. 220 | 221 | -------------------------------------------------------------------------------- /reaktor/LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Permission is hereby granted, free of charge, to any 2 | person obtaining a copy of this software and associated 3 | documentation files (the "Software"), to deal in the 4 | Software without restriction, including without 5 | limitation the rights to use, copy, modify, merge, 6 | publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software 8 | is furnished to do so, subject to the following 9 | conditions: 10 | 11 | The above copyright notice and this permission notice 12 | shall be included in all copies or substantial portions 13 | of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 16 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 17 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 18 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 19 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 20 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 22 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 23 | DEALINGS IN THE SOFTWARE. 24 | -------------------------------------------------------------------------------- /reaktor/README.md: -------------------------------------------------------------------------------- 1 |
2 |

reaktor

3 | 4 |

5 | Reaktor 6 |

7 | 8 |

9 | Github Actions CI Status 10 | crates.io page 11 | docs.rs docs 12 |

13 |
14 | 15 | Watch this space... 16 | -------------------------------------------------------------------------------- /reaktor/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![forbid(unsafe_code)] 2 | 3 | use proc_macro::TokenStream; 4 | 5 | #[proc_macro_attribute] 6 | pub fn initialize(_attr: TokenStream, item: TokenStream) -> TokenStream { 7 | // Placeholder 8 | item 9 | } 10 | -------------------------------------------------------------------------------- /src/input_byte_stream.rs: -------------------------------------------------------------------------------- 1 | use crate::open_input::{open_input, Input}; 2 | use crate::{MediaType, Pseudonym}; 3 | use clap::{AmbientAuthority, TryFromOsArg}; 4 | use io_streams::StreamReader; 5 | use layered_io::{Bufferable, LayeredReader, ReadLayered, Status}; 6 | use std::ffi::OsStr; 7 | use std::fmt::{self, Debug, Formatter}; 8 | use std::io::{self, IoSliceMut, Read}; 9 | use terminal_io::NeverTerminalReader; 10 | 11 | /// An input stream for binary input. 12 | /// 13 | /// An `InputByteStream` implements `Read` so it supports `read`, 14 | /// `read_to_end`, `read_to_str`, etc. and can be used anywhere a 15 | /// `Read`-implementing object is needed. 16 | /// 17 | /// `InputByteStream` is unbuffered (even when it is stdin), so wrapping 18 | /// it in a [`std::io::BufReader`] is recommended for performance and 19 | /// ease of use. 20 | /// 21 | /// The primary way to construct an `InputByteStream` is to use it as 22 | /// a type in a `kommand` argument or `clap_derive` struct. Command-line 23 | /// arguments will then be automatically converted into input streams. 24 | /// Currently supported syntaxes include: 25 | /// - Names starting with `https:` or `http:`, which are interpreted as URLs 26 | /// to open. 27 | /// - Names starting with `data:` are interpreted as data URLs proving the 28 | /// data in their payload. 29 | /// - Names starting with `file:` are interpreted as local filesystem URLs 30 | /// providing paths to files to open. 31 | /// - "-" is interpreted as standard input. 32 | /// - "(...)" runs a command with a pipe from the child process' stdout, on 33 | /// platforms whch support it. 34 | /// - Names which don't parse as URLs are interpreted as plain local 35 | /// filesystem paths. To force a string to be interpreted as a plain local 36 | /// path, arrange for it to begin with `./` or `/`. 37 | pub struct InputByteStream { 38 | name: String, 39 | reader: LayeredReader>, 40 | media_type: MediaType, 41 | initial_size: Option, 42 | } 43 | 44 | impl InputByteStream { 45 | /// If the input stream metadata implies a particular media type, also 46 | /// known as MIME type, return it. Many input streams know their type, 47 | /// though some do not. This is strictly based on available metadata, and 48 | /// not on examining any of the contents of the stream, and there's no 49 | /// guarantee the contents are valid. 50 | #[inline] 51 | pub fn media_type(&self) -> &MediaType { 52 | &self.media_type 53 | } 54 | 55 | /// Return the initial size of the stream, in bytes. This is strictly based 56 | /// on available metadata, and not on examining any of the contents of the 57 | /// stream, and the stream could end up being shorter or longer if the 58 | /// source is concurrently modified. 59 | #[inline] 60 | pub fn initial_size(&self) -> Option { 61 | self.initial_size 62 | } 63 | 64 | /// Return a `Pseudonym` which encapsulates this stream's name (typically 65 | /// its filesystem path or its URL). This allows it to be written to an 66 | /// `OutputByteStream` while otherwise remaining entirely opaque. 67 | #[inline] 68 | pub fn pseudonym(&self) -> Pseudonym { 69 | Pseudonym::new(self.name.clone()) 70 | } 71 | 72 | fn from_input(input: Input) -> Self { 73 | let reader = NeverTerminalReader::new(input.reader); 74 | let reader = LayeredReader::new(reader); 75 | Self { 76 | name: input.name, 77 | reader, 78 | media_type: input.media_type, 79 | initial_size: input.initial_size, 80 | } 81 | } 82 | } 83 | 84 | /// Implement `TryFromOsArg` so that `clap_derive` can parse InputByteStream` 85 | /// arguments automatically. 86 | /// 87 | /// This is hidden from the documentation as it opens resources from 88 | /// strings using ambient authorities. 89 | #[doc(hidden)] 90 | impl TryFromOsArg for InputByteStream { 91 | type Error = anyhow::Error; 92 | 93 | #[inline] 94 | fn try_from_os_str_arg( 95 | os: &OsStr, 96 | ambient_authority: AmbientAuthority, 97 | ) -> anyhow::Result { 98 | open_input(os, ambient_authority).map(Self::from_input) 99 | } 100 | } 101 | 102 | impl ReadLayered for InputByteStream { 103 | #[inline] 104 | fn read_with_status(&mut self, buf: &mut [u8]) -> io::Result<(usize, Status)> { 105 | self.reader.read_with_status(buf) 106 | } 107 | 108 | #[inline] 109 | fn read_vectored_with_status( 110 | &mut self, 111 | bufs: &mut [IoSliceMut<'_>], 112 | ) -> io::Result<(usize, Status)> { 113 | self.reader.read_vectored_with_status(bufs) 114 | } 115 | } 116 | 117 | impl Read for InputByteStream { 118 | #[inline] 119 | fn read(&mut self, buf: &mut [u8]) -> io::Result { 120 | self.reader.read(buf) 121 | } 122 | 123 | #[inline] 124 | fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result { 125 | self.reader.read_vectored(bufs) 126 | } 127 | 128 | #[cfg(can_vector)] 129 | #[inline] 130 | fn is_read_vectored(&self) -> bool { 131 | self.reader.is_read_vectored() 132 | } 133 | 134 | #[inline] 135 | fn read_to_end(&mut self, buf: &mut Vec) -> io::Result { 136 | self.reader.read_to_end(buf) 137 | } 138 | 139 | #[inline] 140 | fn read_to_string(&mut self, buf: &mut String) -> io::Result { 141 | self.reader.read_to_string(buf) 142 | } 143 | 144 | #[inline] 145 | fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> { 146 | self.reader.read_exact(buf) 147 | } 148 | } 149 | 150 | impl Bufferable for InputByteStream { 151 | #[inline] 152 | fn abandon(&mut self) { 153 | self.reader.abandon() 154 | } 155 | } 156 | 157 | impl Debug for InputByteStream { 158 | fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { 159 | // Don't print the name here, as that's an implementation detail. 160 | let mut b = f.debug_struct("InputByteStream"); 161 | b.field("media_type", &self.media_type); 162 | b.field("initial_size", &self.initial_size); 163 | b.finish() 164 | } 165 | } 166 | 167 | #[test] 168 | fn data_url_plain() { 169 | let mut s = String::new(); 170 | InputByteStream::try_from_os_str_arg( 171 | "data:,Hello%2C%20World!".as_ref(), 172 | clap::ambient_authority(), 173 | ) 174 | .unwrap() 175 | .read_to_string(&mut s) 176 | .unwrap(); 177 | assert_eq!(s, "Hello, World!"); 178 | } 179 | 180 | #[test] 181 | fn data_url_base64() { 182 | let mut s = String::new(); 183 | InputByteStream::try_from_os_str_arg( 184 | "data:text/plain;base64,SGVsbG8sIFdvcmxkIQ==".as_ref(), 185 | clap::ambient_authority(), 186 | ) 187 | .unwrap() 188 | .read_to_string(&mut s) 189 | .unwrap(); 190 | assert_eq!(s, "Hello, World!"); 191 | } 192 | -------------------------------------------------------------------------------- /src/input_text_stream.rs: -------------------------------------------------------------------------------- 1 | use crate::open_input::{open_input, Input}; 2 | use crate::{MediaType, Pseudonym}; 3 | use basic_text::{ReadText, ReadTextLayered, TextReader, TextSubstr}; 4 | use clap::{AmbientAuthority, TryFromOsArg}; 5 | use io_streams::StreamReader; 6 | use layered_io::{Bufferable, LayeredReader, ReadLayered, Status}; 7 | use std::ffi::OsStr; 8 | use std::fmt::{self, Debug, Formatter}; 9 | use std::io::{self, IoSliceMut, Read}; 10 | use terminal_io::TerminalReader; 11 | use utf8_io::{ReadStr, ReadStrLayered, Utf8Reader}; 12 | 13 | /// In input stream for plain text input. 14 | /// 15 | /// An `InputTextStream` implements `Read` so it supports `read`, 16 | /// `read_to_end`, `read_to_str`, etc. and can be used anywhere a 17 | /// `Read`-implementing object is needed. 18 | /// 19 | /// `InputTextStream` is unbuffered (even when it is stdin), so wrapping 20 | /// it in a [`std::io::BufReader`] is recommended for performance and 21 | /// ease of use. 22 | /// 23 | /// The primary way to construct an `InputTextStream` is to use it as 24 | /// a type in a `kommand` argument or `clap_derive` struct. Command-line 25 | /// arguments will then be automatically converted into input streams. 26 | /// Currently supported syntaxes include: 27 | /// - Names starting with `https:` or `http:`, which are interpreted as URLs 28 | /// to open. 29 | /// - Names starting with `data:` are interpreted as data URLs proving the 30 | /// data in their payload. 31 | /// - Names starting with `file:` are interpreted as local filesystem URLs 32 | /// providing paths to files to open. 33 | /// - "-" is interpreted as standard input. 34 | /// - "(...)" runs a command with a pipe from the child process' stdout, on 35 | /// platforms whch support it. 36 | /// - Names which don't parse as URLs are interpreted as plain local 37 | /// filesystem paths. To force a string to be interpreted as a plain local 38 | /// path, arrange for it to begin with `./` or `/`. 39 | pub struct InputTextStream { 40 | name: String, 41 | reader: TextReader>>>, 42 | media_type: MediaType, 43 | initial_size: Option, 44 | } 45 | 46 | impl InputTextStream { 47 | /// If the input stream metadata implies a particular media type, also 48 | /// known as MIME type, return it. Many input streams know their type, 49 | /// though some do not. This is strictly based on available metadata, and 50 | /// not on examining any of the contents of the stream, and there's no 51 | /// guarantee the contents are valid. 52 | pub fn media_type(&self) -> &MediaType { 53 | &self.media_type 54 | } 55 | 56 | /// Return the initial size of the stream, in bytes. This is strictly based 57 | /// on available metadata, and not on examining any of the contents of the 58 | /// stream, and the stream could end up being shorter or longer if the 59 | /// source is concurrently modified or it produces content which must be 60 | /// adapted to meet the "plain text" requirements. 61 | pub fn initial_size(&self) -> Option { 62 | self.initial_size 63 | } 64 | 65 | /// Return a `Pseudonym` which encapsulates this stream's name (typically 66 | /// its filesystem path or its URL). This allows it to be written to an 67 | /// `OutputByteStream` while otherwise remaining entirely opaque. 68 | pub fn pseudonym(&self) -> Pseudonym { 69 | Pseudonym::new(self.name.clone()) 70 | } 71 | 72 | fn from_input(input: Input) -> Self { 73 | let reader = TerminalReader::with_handle(input.reader); 74 | let reader = TextReader::new(reader); 75 | let media_type = input.media_type.union(MediaType::text()); 76 | Self { 77 | name: input.name, 78 | reader, 79 | media_type, 80 | initial_size: input.initial_size, 81 | } 82 | } 83 | } 84 | 85 | /// Implement `TryFromOsArg` so that `clap_derive` can parse `InputTextStream` 86 | /// arguments automatically. 87 | /// 88 | /// This is hidden from the documentation as it opens resources from 89 | /// strings using ambient authorities. 90 | #[doc(hidden)] 91 | impl TryFromOsArg for InputTextStream { 92 | type Error = anyhow::Error; 93 | 94 | #[inline] 95 | fn try_from_os_str_arg( 96 | os: &OsStr, 97 | ambient_authority: AmbientAuthority, 98 | ) -> anyhow::Result { 99 | open_input(os, ambient_authority).map(Self::from_input) 100 | } 101 | } 102 | 103 | impl ReadLayered for InputTextStream { 104 | #[inline] 105 | fn read_with_status(&mut self, buf: &mut [u8]) -> io::Result<(usize, Status)> { 106 | self.reader.read_with_status(buf) 107 | } 108 | 109 | #[inline] 110 | fn read_vectored_with_status( 111 | &mut self, 112 | bufs: &mut [IoSliceMut<'_>], 113 | ) -> io::Result<(usize, Status)> { 114 | self.reader.read_vectored_with_status(bufs) 115 | } 116 | } 117 | 118 | impl Read for InputTextStream { 119 | #[inline] 120 | fn read(&mut self, buf: &mut [u8]) -> io::Result { 121 | self.reader.read(buf) 122 | } 123 | 124 | #[inline] 125 | fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result { 126 | self.reader.read_vectored(bufs) 127 | } 128 | 129 | #[cfg(can_vector)] 130 | #[inline] 131 | fn is_read_vectored(&self) -> bool { 132 | self.reader.is_read_vectored() 133 | } 134 | 135 | #[inline] 136 | fn read_to_end(&mut self, buf: &mut Vec) -> io::Result { 137 | self.reader.read_to_end(buf) 138 | } 139 | 140 | #[inline] 141 | fn read_to_string(&mut self, buf: &mut String) -> io::Result { 142 | self.reader.read_to_string(buf) 143 | } 144 | 145 | #[inline] 146 | fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> { 147 | self.reader.read_exact(buf) 148 | } 149 | } 150 | 151 | impl Bufferable for InputTextStream { 152 | #[inline] 153 | fn abandon(&mut self) { 154 | self.reader.abandon() 155 | } 156 | } 157 | 158 | impl ReadStr for InputTextStream { 159 | #[inline] 160 | fn read_str(&mut self, buf: &mut str) -> io::Result { 161 | self.reader.read_str(buf) 162 | } 163 | } 164 | 165 | impl ReadStrLayered for InputTextStream { 166 | #[inline] 167 | fn read_str_with_status(&mut self, buf: &mut str) -> io::Result<(usize, Status)> { 168 | self.reader.read_str_with_status(buf) 169 | } 170 | } 171 | 172 | impl ReadText for InputTextStream { 173 | #[inline] 174 | fn read_text_substr(&mut self, buf: &mut TextSubstr) -> io::Result { 175 | self.reader.read_text_substr(buf) 176 | } 177 | 178 | #[inline] 179 | fn read_exact_text_substr(&mut self, buf: &mut TextSubstr) -> io::Result<()> { 180 | self.reader.read_exact_text_substr(buf) 181 | } 182 | } 183 | 184 | impl ReadTextLayered for InputTextStream { 185 | #[inline] 186 | fn read_text_substr_with_status( 187 | &mut self, 188 | buf: &mut TextSubstr, 189 | ) -> io::Result<(usize, Status)> { 190 | self.reader.read_text_substr_with_status(buf) 191 | } 192 | 193 | #[inline] 194 | fn read_exact_text_substr_using_status(&mut self, buf: &mut TextSubstr) -> io::Result { 195 | self.reader.read_exact_text_substr_using_status(buf) 196 | } 197 | } 198 | 199 | impl Debug for InputTextStream { 200 | fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { 201 | // Don't print the name here, as that's an implementation detail. 202 | let mut b = f.debug_struct("InputTextStream"); 203 | b.field("media_type", &self.media_type); 204 | b.field("initial_size", &self.initial_size); 205 | b.finish() 206 | } 207 | } 208 | 209 | #[test] 210 | fn data_url_plain() { 211 | let mut s = String::new(); 212 | InputTextStream::try_from_os_str_arg( 213 | "data:,Hello%2C%20World!".as_ref(), 214 | clap::ambient_authority(), 215 | ) 216 | .unwrap() 217 | .read_to_string(&mut s) 218 | .unwrap(); 219 | assert_eq!(s, "Hello, World!\n"); 220 | } 221 | 222 | #[test] 223 | fn data_url_base64() { 224 | let mut s = String::new(); 225 | InputTextStream::try_from_os_str_arg( 226 | "data:text/plain;base64,SGVsbG8sIFdvcmxkIQ==".as_ref(), 227 | clap::ambient_authority(), 228 | ) 229 | .unwrap() 230 | .read_to_string(&mut s) 231 | .unwrap(); 232 | assert_eq!(s, "Hello, World!\n"); 233 | } 234 | -------------------------------------------------------------------------------- /src/interactive_byte_stream.rs: -------------------------------------------------------------------------------- 1 | use crate::open_interactive::{open_interactive, Interactive}; 2 | use crate::Pseudonym; 3 | use clap::{AmbientAuthority, TryFromOsArg}; 4 | use duplex::Duplex; 5 | use io_streams::StreamDuplexer; 6 | use layered_io::{ 7 | default_read, default_read_to_end, default_read_to_string, default_read_vectored, Bufferable, 8 | LayeredDuplexer, ReadLayered, Status, WriteLayered, 9 | }; 10 | use std::ffi::OsStr; 11 | use std::fmt::{self, Arguments, Debug, Formatter}; 12 | use std::io::{self, IoSlice, IoSliceMut, Read, Write}; 13 | use terminal_io::{ 14 | DuplexTerminal, NeverTerminalDuplexer, ReadTerminal, Terminal, TerminalColorSupport, 15 | WriteTerminal, 16 | }; 17 | 18 | /// An `InteractiveByteStream` implements `Read` and `Write` as is meant 19 | /// to be used with interactive streams. 20 | /// 21 | /// The primary way to construct an `InteractiveByteStream` is to use it as 22 | /// a type in a `kommand` argument or `clap_derive` struct. Command-line 23 | /// arguments will then be automatically converted into input streams. 24 | /// Currently supported syntaxes include: 25 | /// - Names starting with `connect:` or `accept:`, which are interpreted as 26 | /// socket addresses to connect to or accept from. Socket addresses may 27 | /// contain host:port pairs or, on platforms which support it, filesystem 28 | /// paths to Unix-domain sockets. 29 | /// - "-" is interpreted as the pair (stdin, stdout). 30 | /// - "(...)" runs a command with pipes to and from the child process' (stdin, 31 | /// stdout), on platforms whch support it. 32 | pub struct InteractiveByteStream { 33 | name: String, 34 | duplexer: LayeredDuplexer>, 35 | } 36 | 37 | impl InteractiveByteStream { 38 | /// Return a `Pseudonym` which encapsulates this stream's name (typically 39 | /// its filesystem path or its URL). This allows it to be written to an 40 | /// `InteractiveByteStream` while otherwise remaining entirely opaque. 41 | pub fn pseudonym(&self) -> Pseudonym { 42 | Pseudonym::new(self.name.clone()) 43 | } 44 | 45 | fn from_interactive(interactive: Interactive) -> Self { 46 | let duplexer = NeverTerminalDuplexer::new(interactive.duplexer); 47 | let duplexer = LayeredDuplexer::new(duplexer); 48 | Self { 49 | name: interactive.name, 50 | duplexer, 51 | } 52 | } 53 | } 54 | 55 | /// Implement `TryFromOsArg` so that `clap_derive` can parse 56 | /// `InteractiveByteStream` arguments automatically. 57 | /// 58 | /// This is hidden from the documentation as it opens resources from 59 | /// strings using ambient authorities. 60 | #[doc(hidden)] 61 | impl TryFromOsArg for InteractiveByteStream { 62 | type Error = anyhow::Error; 63 | 64 | #[inline] 65 | fn try_from_os_str_arg( 66 | os: &OsStr, 67 | ambient_authority: AmbientAuthority, 68 | ) -> anyhow::Result { 69 | open_interactive(os, ambient_authority).map(Self::from_interactive) 70 | } 71 | } 72 | 73 | impl ReadLayered for InteractiveByteStream { 74 | #[inline] 75 | fn read_with_status(&mut self, buf: &mut [u8]) -> io::Result<(usize, Status)> { 76 | self.duplexer.read_with_status(buf) 77 | } 78 | 79 | #[inline] 80 | fn read_vectored_with_status( 81 | &mut self, 82 | bufs: &mut [IoSliceMut<'_>], 83 | ) -> io::Result<(usize, Status)> { 84 | self.duplexer.read_vectored_with_status(bufs) 85 | } 86 | } 87 | 88 | impl Read for InteractiveByteStream { 89 | #[inline] 90 | fn read(&mut self, buf: &mut [u8]) -> io::Result { 91 | default_read(self, buf) 92 | } 93 | 94 | #[inline] 95 | fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result { 96 | default_read_vectored(self, bufs) 97 | } 98 | 99 | #[cfg(can_vector)] 100 | #[inline] 101 | fn is_read_vectored(&self) -> bool { 102 | self.duplexer.is_read_vectored() 103 | } 104 | 105 | #[inline] 106 | fn read_to_end(&mut self, buf: &mut Vec) -> io::Result { 107 | default_read_to_end(self, buf) 108 | } 109 | 110 | #[inline] 111 | fn read_to_string(&mut self, buf: &mut String) -> io::Result { 112 | default_read_to_string(self, buf) 113 | } 114 | } 115 | 116 | impl WriteLayered for InteractiveByteStream { 117 | #[inline] 118 | fn close(&mut self) -> io::Result<()> { 119 | self.duplexer.close() 120 | } 121 | } 122 | 123 | impl Write for InteractiveByteStream { 124 | #[inline] 125 | fn write(&mut self, buf: &[u8]) -> io::Result { 126 | self.duplexer.write(buf) 127 | } 128 | 129 | #[inline] 130 | fn flush(&mut self) -> io::Result<()> { 131 | self.duplexer.flush() 132 | } 133 | 134 | #[inline] 135 | fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result { 136 | self.duplexer.write_vectored(bufs) 137 | } 138 | 139 | #[cfg(can_vector)] 140 | #[inline] 141 | fn is_write_vectored(&self) -> bool { 142 | self.duplexer.is_write_vectored() 143 | } 144 | 145 | #[inline] 146 | fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { 147 | self.duplexer.write_all(buf) 148 | } 149 | 150 | #[cfg(write_all_vectored)] 151 | #[inline] 152 | fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> { 153 | self.duplexer.write_all_vectored(bufs) 154 | } 155 | 156 | #[inline] 157 | fn write_fmt(&mut self, fmt: Arguments<'_>) -> io::Result<()> { 158 | self.duplexer.write_fmt(fmt) 159 | } 160 | } 161 | 162 | impl Bufferable for InteractiveByteStream { 163 | #[inline] 164 | fn abandon(&mut self) { 165 | self.duplexer.abandon() 166 | } 167 | } 168 | 169 | impl Terminal for InteractiveByteStream {} 170 | 171 | impl ReadTerminal for InteractiveByteStream { 172 | #[inline] 173 | fn is_line_by_line(&self) -> bool { 174 | self.duplexer.is_line_by_line() 175 | } 176 | 177 | #[inline] 178 | fn is_input_terminal(&self) -> bool { 179 | self.duplexer.is_input_terminal() 180 | } 181 | } 182 | 183 | impl WriteTerminal for InteractiveByteStream { 184 | #[inline] 185 | fn color_support(&self) -> TerminalColorSupport { 186 | self.duplexer.color_support() 187 | } 188 | 189 | #[inline] 190 | fn color_preference(&self) -> bool { 191 | self.duplexer.color_preference() 192 | } 193 | 194 | #[inline] 195 | fn is_output_terminal(&self) -> bool { 196 | self.duplexer.is_output_terminal() 197 | } 198 | } 199 | 200 | impl DuplexTerminal for InteractiveByteStream {} 201 | 202 | impl Duplex for InteractiveByteStream {} 203 | 204 | impl Debug for InteractiveByteStream { 205 | fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { 206 | // Don't print the name here, as that's an implementation detail. 207 | let mut b = f.debug_struct("InteractiveByteStream"); 208 | b.finish() 209 | } 210 | } 211 | -------------------------------------------------------------------------------- /src/interactive_text_stream.rs: -------------------------------------------------------------------------------- 1 | use crate::open_interactive::{open_interactive, Interactive}; 2 | use crate::Pseudonym; 3 | use basic_text::TextDuplexer; 4 | use clap::{AmbientAuthority, TryFromOsArg}; 5 | use duplex::Duplex; 6 | use io_streams::StreamDuplexer; 7 | use layered_io::{Bufferable, LayeredDuplexer, ReadLayered, Status, WriteLayered}; 8 | use std::ffi::OsStr; 9 | use std::fmt::{self, Arguments, Debug, Formatter}; 10 | use std::io::{self, IoSlice, IoSliceMut, Read, Write}; 11 | use terminal_io::{ 12 | DuplexTerminal, ReadTerminal, Terminal, TerminalColorSupport, TerminalDuplexer, WriteTerminal, 13 | }; 14 | use utf8_io::{ReadStr, ReadStrLayered, Utf8Duplexer, WriteStr}; 15 | 16 | /// An `InteractiveTextStream` implements `Read` and `Write` as is meant 17 | /// to be used with interactive streams. 18 | /// 19 | /// The primary way to construct an `InteractiveTextStream` is to use it as 20 | /// a type in a `kommand` argument or `clap_derive` struct. Command-line 21 | /// arguments will then be automatically converted into input streams. 22 | /// Currently supported syntaxes include: 23 | /// - Names starting with `connect:` or `accept:`, which are interpreted as 24 | /// socket addresses to connect to or accept from. Socket addresses may 25 | /// contain host:port pairs or, on platforms which support it, filesystem 26 | /// paths to Unix-domain sockets. 27 | /// - "-" is interpreted as the pair (stdin, stdout). 28 | /// - "(...)" runs a command with pipes to and from the child process' (stdin, 29 | /// stdout), on platforms whch support it. 30 | pub struct InteractiveTextStream { 31 | name: String, 32 | duplexer: TextDuplexer>>>, 33 | } 34 | 35 | impl InteractiveTextStream { 36 | /// Write the given `Pseudonym` to the output stream. 37 | #[inline] 38 | pub fn write_pseudonym(&mut self, pseudonym: &Pseudonym) -> io::Result<()> { 39 | Write::write_all(self, pseudonym.name.as_bytes()) 40 | } 41 | 42 | /// Return a `Pseudonym` which encapsulates this stream's name (typically 43 | /// its filesystem path or its URL). This allows it to be written to an 44 | /// `OutputByteStream` while otherwise remaining entirely opaque. 45 | #[inline] 46 | pub fn pseudonym(&self) -> Pseudonym { 47 | Pseudonym::new(self.name.clone()) 48 | } 49 | 50 | fn from_interactive(interactive: Interactive) -> Self { 51 | let duplexer = TerminalDuplexer::with_handle(interactive.duplexer); 52 | let duplexer = TextDuplexer::new(duplexer); 53 | Self { 54 | name: interactive.name, 55 | duplexer, 56 | } 57 | } 58 | } 59 | 60 | /// Implement `FromStr` so that `clap_derive` can parse `InteractiveTextStream` 61 | /// arguments automatically. 62 | /// 63 | /// This is hidden from the documentation as it opens resources from 64 | /// strings using ambient authorities. 65 | #[doc(hidden)] 66 | impl TryFromOsArg for InteractiveTextStream { 67 | type Error = anyhow::Error; 68 | 69 | #[inline] 70 | fn try_from_os_str_arg( 71 | os: &OsStr, 72 | ambient_authority: AmbientAuthority, 73 | ) -> anyhow::Result { 74 | open_interactive(os, ambient_authority).map(Self::from_interactive) 75 | } 76 | } 77 | 78 | impl ReadLayered for InteractiveTextStream { 79 | #[inline] 80 | fn read_with_status(&mut self, buf: &mut [u8]) -> io::Result<(usize, Status)> { 81 | self.duplexer.read_with_status(buf) 82 | } 83 | 84 | #[inline] 85 | fn read_vectored_with_status( 86 | &mut self, 87 | bufs: &mut [IoSliceMut<'_>], 88 | ) -> io::Result<(usize, Status)> { 89 | self.duplexer.read_vectored_with_status(bufs) 90 | } 91 | } 92 | 93 | impl Read for InteractiveTextStream { 94 | #[inline] 95 | fn read(&mut self, buf: &mut [u8]) -> io::Result { 96 | self.duplexer.read(buf) 97 | } 98 | 99 | #[inline] 100 | fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result { 101 | self.duplexer.read_vectored(bufs) 102 | } 103 | 104 | #[cfg(can_vector)] 105 | #[inline] 106 | fn is_read_vectored(&self) -> bool { 107 | self.duplexer.is_read_vectored() 108 | } 109 | 110 | #[inline] 111 | fn read_to_end(&mut self, buf: &mut Vec) -> io::Result { 112 | self.duplexer.read_to_end(buf) 113 | } 114 | 115 | #[inline] 116 | fn read_to_string(&mut self, buf: &mut String) -> io::Result { 117 | self.duplexer.read_to_string(buf) 118 | } 119 | 120 | #[inline] 121 | fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> { 122 | self.duplexer.read_exact(buf) 123 | } 124 | } 125 | 126 | impl WriteLayered for InteractiveTextStream { 127 | #[inline] 128 | fn close(&mut self) -> io::Result<()> { 129 | self.duplexer.close() 130 | } 131 | } 132 | 133 | impl WriteStr for InteractiveTextStream { 134 | #[inline] 135 | fn write_str(&mut self, buf: &str) -> io::Result<()> { 136 | self.duplexer.write_str(buf) 137 | } 138 | } 139 | 140 | impl Write for InteractiveTextStream { 141 | #[inline] 142 | fn write(&mut self, buf: &[u8]) -> io::Result { 143 | self.duplexer.write(buf) 144 | } 145 | 146 | #[inline] 147 | fn flush(&mut self) -> io::Result<()> { 148 | self.duplexer.flush() 149 | } 150 | 151 | #[inline] 152 | fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result { 153 | self.duplexer.write_vectored(bufs) 154 | } 155 | 156 | #[cfg(can_vector)] 157 | #[inline] 158 | fn is_write_vectored(&self) -> bool { 159 | self.duplexer.is_write_vectored() 160 | } 161 | 162 | #[inline] 163 | fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { 164 | self.duplexer.write_all(buf) 165 | } 166 | 167 | #[cfg(write_all_vectored)] 168 | #[inline] 169 | fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> { 170 | self.duplexer.write_all_vectored(bufs) 171 | } 172 | 173 | #[inline] 174 | fn write_fmt(&mut self, fmt: Arguments<'_>) -> io::Result<()> { 175 | self.duplexer.write_fmt(fmt) 176 | } 177 | } 178 | 179 | impl Terminal for InteractiveTextStream {} 180 | 181 | impl ReadTerminal for InteractiveTextStream { 182 | #[inline] 183 | fn is_line_by_line(&self) -> bool { 184 | self.duplexer.is_line_by_line() 185 | } 186 | 187 | #[inline] 188 | fn is_input_terminal(&self) -> bool { 189 | self.duplexer.is_input_terminal() 190 | } 191 | } 192 | 193 | impl WriteTerminal for InteractiveTextStream { 194 | #[inline] 195 | fn color_support(&self) -> TerminalColorSupport { 196 | self.duplexer.color_support() 197 | } 198 | 199 | #[inline] 200 | fn color_preference(&self) -> bool { 201 | self.duplexer.color_preference() 202 | } 203 | 204 | #[inline] 205 | fn is_output_terminal(&self) -> bool { 206 | self.duplexer.is_output_terminal() 207 | } 208 | } 209 | 210 | impl DuplexTerminal for InteractiveTextStream {} 211 | 212 | impl Duplex for InteractiveTextStream {} 213 | 214 | impl Bufferable for InteractiveTextStream { 215 | #[inline] 216 | fn abandon(&mut self) { 217 | self.duplexer.abandon() 218 | } 219 | } 220 | 221 | impl ReadStr for InteractiveTextStream { 222 | #[inline] 223 | fn read_str(&mut self, buf: &mut str) -> io::Result { 224 | self.duplexer.read_str(buf) 225 | } 226 | 227 | #[inline] 228 | fn read_exact_str(&mut self, buf: &mut str) -> io::Result<()> { 229 | self.duplexer.read_exact_str(buf) 230 | } 231 | } 232 | 233 | impl ReadStrLayered for InteractiveTextStream { 234 | #[inline] 235 | fn read_str_with_status(&mut self, buf: &mut str) -> io::Result<(usize, Status)> { 236 | self.duplexer.read_str_with_status(buf) 237 | } 238 | 239 | #[inline] 240 | fn read_exact_str_using_status(&mut self, buf: &mut str) -> io::Result { 241 | self.duplexer.read_exact_str_using_status(buf) 242 | } 243 | } 244 | 245 | impl Debug for InteractiveTextStream { 246 | fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { 247 | // Don't print the name here, as that's an implementation detail. 248 | let mut b = f.debug_struct("InteractiveTextStream"); 249 | b.field("duplexer", &self.duplexer); 250 | b.finish() 251 | } 252 | } 253 | -------------------------------------------------------------------------------- /src/lazy_output.rs: -------------------------------------------------------------------------------- 1 | use crate::MediaType; 2 | use clap::{AmbientAuthority, TryFromOsArg}; 3 | use std::error::Error; 4 | use std::ffi::{OsStr, OsString}; 5 | use std::fmt; 6 | use std::marker::PhantomData; 7 | 8 | #[doc(hidden)] 9 | #[derive(Debug)] 10 | pub struct Never {} 11 | 12 | impl Error for Never {} 13 | 14 | impl fmt::Display for Never { 15 | fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result { 16 | panic!() 17 | } 18 | } 19 | 20 | #[doc(hidden)] 21 | pub trait FromLazyOutput { 22 | type Err; 23 | 24 | fn from_lazy_output( 25 | name: OsString, 26 | media_type: MediaType, 27 | ambient_authority: AmbientAuthority, 28 | ) -> Result 29 | where 30 | Self: Sized; 31 | } 32 | 33 | /// A placeholder for an output stream which is created lazily. It is created 34 | /// when `materialize` is called. 35 | pub struct LazyOutput { 36 | name: OsString, 37 | ambient_authority: AmbientAuthority, 38 | _phantom: PhantomData, 39 | } 40 | 41 | impl LazyOutput { 42 | /// Consume `self` and materialize an output stream. 43 | #[inline] 44 | pub fn materialize(self, media_type: MediaType) -> Result { 45 | T::from_lazy_output(self.name, media_type, self.ambient_authority) 46 | } 47 | } 48 | 49 | impl TryFromOsArg for LazyOutput { 50 | type Error = Never; 51 | 52 | #[inline] 53 | fn try_from_os_str_arg(os: &OsStr, ambient_authority: AmbientAuthority) -> Result { 54 | Ok(Self { 55 | name: os.to_owned(), 56 | ambient_authority, 57 | _phantom: PhantomData::default(), 58 | }) 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! This crate provides: 2 | //! 3 | //! - [`InputByteStream`], [`OutputByteStream`], and [`InteractiveByteStream`] 4 | //! for working with byte streams, and [`InputTextStream`], 5 | //! [`OutputTextStream`], and [`InteractiveTextStream`] for working with text 6 | //! streams. These implement [`Read`] and [`Write`] in the usual way, so they 7 | //! interoperate with existing Rust code. 8 | //! 9 | //! You can use all these types in type-aware command-line parsing packages 10 | //! such as [`nameless-clap_derive`] or this library's own [`kommand`]. 11 | //! (`nameless-clap_derive` is a temporary fork of [`clap_derive`]; we are 12 | //! in the process of upstreaming our patches). 13 | //! 14 | //! [`nameless-clap_derive`]: https://crates.io/crates/nameless-clap_derive 15 | //! [`clap_derive`]: https://crates.io/crates/clap_derive 16 | //! [`kommand`]: https://crates.io/crates/kommand 17 | //! [`Read`]: https://doc.rust-lang.org/std/io/trait.Read.html 18 | //! [`Write`]: https://doc.rust-lang.org/std/io/trait.Write.html 19 | //! [`InputByteStream`]: https://docs.rs/nameless/latest/nameless/struct.InputByteStream.html 20 | //! [`OutputByteStream`]: https://docs.rs/nameless/latest/nameless/struct.OutputByteStream.html 21 | //! [`InteractiveByteStream`]: https://docs.rs/nameless/latest/nameless/struct.InteractiveByteStream.html 22 | //! [`InputTextStream`]: https://docs.rs/nameless/latest/nameless/struct.InputTextStream.html 23 | //! [`OutputTextStream`]: https://docs.rs/nameless/latest/nameless/struct.OutputTextStream.html 24 | //! [`InteractiveTextStream`]: https://docs.rs/nameless/latest/nameless/struct.InteractiveTextStream.html 25 | 26 | #![deny(missing_docs)] 27 | #![forbid(unsafe_code)] 28 | #![cfg_attr(read_initializer, feature(read_initializer))] 29 | #![cfg_attr(can_vector, feature(can_vector))] 30 | #![cfg_attr(write_all_vectored, feature(write_all_vectored))] 31 | 32 | // Re-export `clap` for use in the proc macros. 33 | #[doc(hidden)] 34 | pub use clap; 35 | 36 | pub use mime::Mime; 37 | 38 | mod input_byte_stream; 39 | mod input_text_stream; 40 | mod interactive_byte_stream; 41 | mod interactive_text_stream; 42 | mod lazy_output; 43 | mod media_type; 44 | mod open_input; 45 | mod open_interactive; 46 | mod open_output; 47 | mod output_byte_stream; 48 | mod output_text_stream; 49 | mod path_to_name; 50 | mod pseudonym; 51 | #[cfg(unix)] 52 | mod summon_bat; 53 | 54 | pub use input_byte_stream::InputByteStream; 55 | pub use input_text_stream::InputTextStream; 56 | pub use interactive_byte_stream::InteractiveByteStream; 57 | pub use interactive_text_stream::InteractiveTextStream; 58 | pub use lazy_output::LazyOutput; 59 | pub use media_type::MediaType; 60 | pub use output_byte_stream::OutputByteStream; 61 | pub use output_text_stream::OutputTextStream; 62 | pub use pseudonym::Pseudonym; 63 | -------------------------------------------------------------------------------- /src/media_type.rs: -------------------------------------------------------------------------------- 1 | use mime::Mime; 2 | use std::ffi::OsStr; 3 | use std::str::FromStr; 4 | 5 | /// The type of content in a stream. This can be either a Media Type 6 | /// (aka Mime Type) or a filename extension, both, or neither if nothing 7 | /// is known. 8 | #[derive(Clone, Debug, Eq, PartialEq)] 9 | pub struct MediaType { 10 | mime: Mime, 11 | extension: String, 12 | } 13 | 14 | impl MediaType { 15 | /// Construct a type representing completely unknown contents. 16 | pub fn unknown() -> Self { 17 | Self { 18 | mime: mime::STAR_STAR, 19 | extension: String::new(), 20 | } 21 | } 22 | 23 | /// Construct a type representing plain text (UTF-8) contents. 24 | pub fn text() -> Self { 25 | Self { 26 | mime: mime::TEXT_PLAIN_UTF_8, 27 | extension: String::new(), 28 | } 29 | } 30 | 31 | /// Construct a type representing the given Media Type. 32 | pub fn from_mime(mime: Mime) -> Self { 33 | let extension = match mime_guess::get_mime_extensions(&mime) { 34 | Some(exts) => { 35 | if exts.len() == 1 { 36 | exts[0].to_string() 37 | } else { 38 | String::new() 39 | } 40 | } 41 | None => String::new(), 42 | }; 43 | 44 | Self { mime, extension } 45 | } 46 | 47 | /// Construct a type representing the given filename extension. 48 | pub fn from_extension(extension: Option<&OsStr>) -> Self { 49 | if let Some(ext) = extension { 50 | if let Some(s) = ext.to_str() { 51 | let mut guesses = mime_guess::from_ext(s).iter(); 52 | 53 | if let Some(first) = guesses.next() { 54 | let mut merged = Self { 55 | mime: first, 56 | extension: s.to_string(), 57 | }; 58 | for guess in guesses { 59 | merged = merged.union(Self { 60 | mime: guess, 61 | extension: s.to_string(), 62 | }); 63 | } 64 | merged 65 | } else { 66 | Self::unknown() 67 | } 68 | } else { 69 | Self::unknown() 70 | } 71 | } else { 72 | Self::unknown() 73 | } 74 | } 75 | 76 | /// Return the Media Type, which is "*/*" if unknown. 77 | #[inline] 78 | pub fn mime(&self) -> &Mime { 79 | &self.mime 80 | } 81 | 82 | /// Return the filename extension, which is empty if unknown. 83 | #[inline] 84 | pub fn extension(&self) -> &str { 85 | &self.extension 86 | } 87 | 88 | /// Return a type which is the generalization of `self` and `other`. Falls 89 | /// back to `MediaType::unknown()` if it cannot be determined. 90 | pub fn union(self, other: Self) -> Self { 91 | if self == other { 92 | self 93 | } else if other == MediaType::unknown() { 94 | self 95 | } else if self == MediaType::unknown() { 96 | other 97 | } else if self.mime.type_() == other.mime.type_() 98 | && self.mime.suffix() == other.mime.suffix() 99 | && self.mime.params().eq(other.mime.params()) 100 | { 101 | if other.mime.subtype().as_str() == mime::STAR && other.mime.suffix().is_none() { 102 | self 103 | } else if self.mime.subtype().as_str() == mime::STAR && self.mime.suffix().is_none() { 104 | other 105 | } else { 106 | // Create a new mime value with the subtype replaced by star. 107 | let mut s = format!("{}/{}", self.mime.type_(), mime::STAR); 108 | if let Some(suffix) = self.mime.suffix() { 109 | s += &format!("+{}", suffix); 110 | } 111 | if self.mime.params().next().is_some() { 112 | for param in self.mime.params() { 113 | s += &format!("; {}={}", param.0, param.1); 114 | } 115 | } 116 | MediaType::from_mime(Mime::from_str(&s).unwrap()) 117 | } 118 | } else if other == MediaType::text() { 119 | if self.mime.type_() == other.mime.type_() { 120 | self 121 | } else { 122 | MediaType::unknown() 123 | } 124 | } else if self == MediaType::text() { 125 | if self.mime.type_() == other.mime.type_() { 126 | other 127 | } else { 128 | MediaType::unknown() 129 | } 130 | } else { 131 | MediaType::unknown() 132 | } 133 | } 134 | } 135 | 136 | #[test] 137 | fn mime_from_extension() { 138 | use std::path::Path; 139 | assert_eq!(MediaType::from_extension(None), MediaType::unknown()); 140 | assert_eq!( 141 | MediaType::from_extension(Some(Path::new("jpg").as_ref())).mime(), 142 | &Mime::from_str("image/jpeg").unwrap() 143 | ); 144 | } 145 | 146 | #[test] 147 | fn mime_union() { 148 | assert_eq!( 149 | MediaType::from_mime(Mime::from_str("image/jpeg").unwrap()) 150 | .union(MediaType::from_mime(Mime::from_str("image/png").unwrap())) 151 | .mime(), 152 | &Mime::from_str("image/*").unwrap() 153 | ); 154 | } 155 | -------------------------------------------------------------------------------- /src/open_input.rs: -------------------------------------------------------------------------------- 1 | use crate::path_to_name::path_to_name; 2 | use crate::{MediaType, Mime}; 3 | use anyhow::anyhow; 4 | use clap::AmbientAuthority; 5 | use data_url::DataUrl; 6 | use flate2::read::GzDecoder; 7 | use io_streams::StreamReader; 8 | use std::ffi::OsStr; 9 | use std::fs::File; 10 | use std::path::Path; 11 | use std::str::FromStr; 12 | use url::Url; 13 | #[cfg(feature = "ssh2")] 14 | use {percent_encoding::percent_decode, ssh2::Session, std::net::TcpStream}; 15 | 16 | pub(crate) struct Input { 17 | pub(crate) name: String, 18 | pub(crate) reader: StreamReader, 19 | pub(crate) media_type: MediaType, 20 | pub(crate) initial_size: Option, 21 | } 22 | 23 | pub(crate) fn open_input( 24 | os: &OsStr, 25 | _ambient_authority: AmbientAuthority, 26 | ) -> anyhow::Result { 27 | if let Some(s) = os.to_str() { 28 | // If we can parse it as a URL, treat it as such. 29 | if let Ok(url) = Url::parse(s) { 30 | return open_url(url); 31 | } 32 | 33 | // Special-case "-" to mean stdin. 34 | if s == "-" { 35 | return acquire_stdin(); 36 | } 37 | } 38 | 39 | #[cfg(not(windows))] 40 | { 41 | let lossy = os.to_string_lossy(); 42 | 43 | // Strings beginning with "$(" are commands. 44 | if lossy.starts_with("$(") { 45 | return spawn_child(os, &lossy); 46 | } 47 | } 48 | 49 | // Otherwise try opening it as a path in the filesystem namespace. 50 | open_path(Path::new(os)) 51 | } 52 | 53 | fn acquire_stdin() -> anyhow::Result { 54 | let reader = StreamReader::stdin()?; 55 | Ok(Input { 56 | name: "-".to_owned(), 57 | reader, 58 | media_type: MediaType::unknown(), 59 | initial_size: None, 60 | }) 61 | } 62 | 63 | fn open_url(url: Url) -> anyhow::Result { 64 | match url.scheme() { 65 | "http" | "https" => open_http_url_str(url.as_str()), 66 | "data" => open_data_url_str(url.as_str()), 67 | "file" => { 68 | if !url.username().is_empty() 69 | || url.password().is_some() 70 | || url.has_host() 71 | || url.port().is_some() 72 | || url.query().is_some() 73 | || url.fragment().is_some() 74 | { 75 | return Err(anyhow!("file URL should only contain a path")); 76 | } 77 | // TODO: https://docs.rs/url/latest/url/struct.Url.html#method.to_file_path 78 | // is ambiguous about how it can fail. What is `Path::new_opt`? 79 | open_path( 80 | &url.to_file_path() 81 | .map_err(|_: ()| anyhow!("unknown file URL weirdness"))?, 82 | ) 83 | } 84 | #[cfg(feature = "ssh2")] 85 | "scp" => open_scp_url(&url), 86 | other => Err(anyhow!("unsupported URL scheme \"{}\"", other)), 87 | } 88 | } 89 | 90 | fn open_http_url_str(http_url_str: &str) -> anyhow::Result { 91 | // TODO: Set any headers, like "Accept"? 92 | let response = ureq::get(http_url_str) 93 | .call() 94 | .map_err(|e| anyhow!("HTTP error fetching {}: {}", http_url_str, e))?; 95 | 96 | let initial_size = Some( 97 | response 98 | .header("Content-Length") 99 | .ok_or_else(|| anyhow!("invalid Content-Length header"))? 100 | .parse()?, 101 | ); 102 | let media_type = response.content_type(); 103 | let media_type = MediaType::from_mime(Mime::from_str(media_type)?); 104 | 105 | let reader = response.into_reader(); 106 | let reader = StreamReader::piped_thread(Box::new(reader))?; 107 | Ok(Input { 108 | name: http_url_str.to_owned(), 109 | media_type, 110 | reader, 111 | initial_size, 112 | }) 113 | } 114 | 115 | fn open_data_url_str(data_url_str: &str) -> anyhow::Result { 116 | // TODO: `DataUrl` should really implement `std::error::Error`. 117 | let data_url = 118 | DataUrl::process(data_url_str).map_err(|e| anyhow!("invalid data URL syntax: {:?}", e))?; 119 | // TODO: `DataUrl` should really really implement `std::error::Error`. 120 | let (body, fragment) = data_url 121 | .decode_to_vec() 122 | .map_err(|_| anyhow!("invalid base64 encoding"))?; 123 | 124 | if fragment.is_some() { 125 | return Err(anyhow!("data urls with fragments are unsupported")); 126 | } 127 | 128 | // Awkwardly convert from `data_url::Mime` to `mime::Mime`. 129 | // TODO: Consider submitting patches to `data_url` to streamline this. 130 | let media_type = 131 | MediaType::from_mime(Mime::from_str(&data_url.mime_type().to_string()).unwrap()); 132 | 133 | let reader = StreamReader::bytes(&body)?; 134 | Ok(Input { 135 | name: data_url_str.to_owned(), 136 | reader, 137 | media_type, 138 | initial_size: Some(data_url_str.len().try_into().unwrap()), 139 | }) 140 | } 141 | 142 | // Handle URLs of the form `scp://[user@]host[:port][/path]`. 143 | #[cfg(feature = "ssh2")] 144 | fn open_scp_url(scp_url: &Url) -> anyhow::Result { 145 | if scp_url.query().is_some() || scp_url.fragment().is_some() { 146 | return Err(anyhow!("scp URL should only contain a socket address, optional username, optional password, and optional path")); 147 | } 148 | 149 | let host_str = match scp_url.host_str() { 150 | Some(host_str) => host_str, 151 | None => return Err(anyhow!("ssh URL should have a host")), 152 | }; 153 | let port = match scp_url.port() { 154 | Some(port) => port, 155 | None => 22, // default ssh port 156 | }; 157 | let tcp = TcpStream::connect((host_str, port))?; 158 | let mut sess = Session::new().unwrap(); 159 | sess.set_tcp_stream(tcp); 160 | sess.handshake().unwrap(); 161 | 162 | let username = if scp_url.username().is_empty() { 163 | whoami::username() 164 | } else { 165 | scp_url.username().to_owned() 166 | }; 167 | let username = percent_decode(username.as_bytes()).decode_utf8()?; 168 | 169 | if let Some(password) = scp_url.password() { 170 | let password = percent_decode(password.as_bytes()).decode_utf8()?; 171 | sess.userauth_password(&username, &password)?; 172 | } else { 173 | sess.userauth_agent(&username)?; 174 | } 175 | 176 | assert!(sess.authenticated()); 177 | 178 | let path = Path::new(scp_url.path()); 179 | let (channel, stat) = sess.scp_recv(path)?; 180 | let reader = StreamReader::piped_thread(Box::new(channel))?; 181 | let media_type = MediaType::from_extension(path.extension()); 182 | Ok(Input { 183 | name: scp_url.as_str().to_owned(), 184 | reader, 185 | media_type, 186 | initial_size: Some(stat.size()), 187 | }) 188 | } 189 | 190 | fn open_path(path: &Path) -> anyhow::Result { 191 | let name = path_to_name("file", path)?; 192 | // TODO: Should we have our own error type? 193 | let file = File::open(path).map_err(|err| anyhow!("{}: {}", path.display(), err))?; 194 | if path.extension() == Some(Path::new("gz").as_os_str()) { 195 | // TODO: We shouldn't really need to allocate a `PathBuf` here. 196 | let path = path.with_extension(""); 197 | let media_type = MediaType::from_extension(path.extension()); 198 | let initial_size = None; 199 | let reader = GzDecoder::new(file); 200 | let reader = StreamReader::piped_thread(Box::new(reader))?; 201 | Ok(Input { 202 | name, 203 | reader, 204 | media_type, 205 | initial_size, 206 | }) 207 | } else { 208 | let media_type = MediaType::from_extension(path.extension()); 209 | let initial_size = Some(file.metadata()?.len()); 210 | let reader = StreamReader::file(file); 211 | Ok(Input { 212 | name, 213 | reader, 214 | media_type, 215 | initial_size, 216 | }) 217 | } 218 | } 219 | 220 | #[cfg(not(windows))] 221 | fn spawn_child(os: &OsStr, lossy: &str) -> anyhow::Result { 222 | use std::process::{Command, Stdio}; 223 | assert!(lossy.starts_with("$(")); 224 | if !lossy.ends_with(')') { 225 | return Err(anyhow!("child string must end in ')'")); 226 | } 227 | let s = if let Some(s) = os.to_str() { 228 | s 229 | } else { 230 | return Err(anyhow!("Non-UTF-8 child strings not yet supported")); 231 | }; 232 | let words = shell_words::split(&s[2..s.len() - 1])?; 233 | let (first, rest) = words 234 | .split_first() 235 | .ok_or_else(|| anyhow!("child stream specified with '(...)' must contain a command"))?; 236 | let child = Command::new(first) 237 | .args(rest) 238 | .stdin(Stdio::null()) 239 | .stdout(Stdio::piped()) 240 | .spawn()?; 241 | let reader = StreamReader::child_stdout(child.stdout.unwrap()); 242 | Ok(Input { 243 | name: s.to_owned(), 244 | reader, 245 | media_type: MediaType::unknown(), 246 | initial_size: None, 247 | }) 248 | } 249 | -------------------------------------------------------------------------------- /src/open_interactive.rs: -------------------------------------------------------------------------------- 1 | use crate::path_to_name::path_to_name; 2 | use anyhow::anyhow; 3 | use char_device::CharDevice; 4 | use clap::AmbientAuthority; 5 | use io_streams::StreamDuplexer; 6 | use std::ffi::OsStr; 7 | use std::net::{TcpListener, TcpStream}; 8 | #[cfg(unix)] 9 | use std::os::unix::net::{UnixListener, UnixStream}; 10 | use std::path::Path; 11 | use url::Url; 12 | 13 | pub(crate) struct Interactive { 14 | pub(crate) name: String, 15 | pub(crate) duplexer: StreamDuplexer, 16 | } 17 | 18 | pub(crate) fn open_interactive( 19 | os: &OsStr, 20 | _ambient_authority: AmbientAuthority, 21 | ) -> anyhow::Result { 22 | if let Some(s) = os.to_str() { 23 | // If we can parse it as a URL, treat it as such. 24 | if let Ok(url) = Url::parse(s) { 25 | return open_url(url); 26 | } 27 | 28 | // Special-case "-" to mean (stdin, stdout). 29 | if s == "-" { 30 | return acquire_stdin_stdout(); 31 | } 32 | } 33 | 34 | #[cfg(not(windows))] 35 | { 36 | let lossy = os.to_string_lossy(); 37 | 38 | // Strings beginning with "$(" are commands. 39 | if lossy.starts_with("$(") { 40 | return spawn_child(os, &lossy); 41 | } 42 | } 43 | 44 | // Otherwise try opening it as a path in the filesystem namespace. 45 | open_path(Path::new(os)) 46 | } 47 | 48 | fn acquire_stdin_stdout() -> anyhow::Result { 49 | let duplexer = StreamDuplexer::stdin_stdout()?; 50 | Ok(Interactive { 51 | name: "-".to_owned(), 52 | duplexer, 53 | }) 54 | } 55 | 56 | fn open_url(url: Url) -> anyhow::Result { 57 | match url.scheme() { 58 | "connect" => open_connect_url(url), 59 | "accept" => open_accept_url(url), 60 | scheme @ "http" | scheme @ "https" | scheme @ "file" | scheme @ "data" => { 61 | Err(anyhow!("non-interactive URL scheme \"{}\"", scheme)) 62 | } 63 | other => Err(anyhow!("unsupported URL scheme \"{}\"", other)), 64 | } 65 | } 66 | 67 | fn open_connect_url(url: Url) -> anyhow::Result { 68 | if !url.username().is_empty() 69 | || url.password().is_some() 70 | || url.query().is_some() 71 | || url.fragment().is_some() 72 | { 73 | return Err(anyhow!("connect URL should only contain a socket address")); 74 | } 75 | 76 | if url.path().is_empty() { 77 | let port = match url.port() { 78 | Some(port) => port, 79 | None => return Err(anyhow!("TCP connect URL should have a port")), 80 | }; 81 | let host_str = match url.host_str() { 82 | Some(host_str) => host_str, 83 | None => return Err(anyhow!("TCP connect URL should have a host")), 84 | }; 85 | 86 | let duplexer = TcpStream::connect((host_str, port))?; 87 | let duplexer = StreamDuplexer::tcp_stream(duplexer); 88 | 89 | return Ok(Interactive { 90 | name: url.to_string(), 91 | duplexer, 92 | }); 93 | } 94 | 95 | #[cfg(unix)] 96 | { 97 | if url.port().is_some() || url.host_str().is_some() { 98 | return Err(anyhow!( 99 | "Unix-domain connect URL should only contain a path" 100 | )); 101 | } 102 | 103 | let duplexer = UnixStream::connect(url.path())?; 104 | let duplexer = StreamDuplexer::unix_stream(duplexer); 105 | 106 | Ok(Interactive { 107 | name: url.to_string(), 108 | duplexer, 109 | }) 110 | } 111 | 112 | #[cfg(windows)] 113 | { 114 | Err(anyhow!("Unsupported connect URL: {}", url)) 115 | } 116 | } 117 | 118 | fn open_accept_url(url: Url) -> anyhow::Result { 119 | if !url.username().is_empty() 120 | || url.password().is_some() 121 | || url.query().is_some() 122 | || url.fragment().is_some() 123 | { 124 | return Err(anyhow!("accept URL should only contain a socket address")); 125 | } 126 | 127 | if url.path().is_empty() { 128 | let port = match url.port() { 129 | Some(port) => port, 130 | None => return Err(anyhow!("accept URL should have a port")), 131 | }; 132 | let host_str = match url.host_str() { 133 | Some(host_str) => host_str, 134 | None => return Err(anyhow!("accept URL should have a host")), 135 | }; 136 | 137 | let listener = TcpListener::bind((host_str, port))?; 138 | 139 | let (duplexer, addr) = listener.accept()?; 140 | let duplexer = StreamDuplexer::tcp_stream(duplexer); 141 | 142 | return Ok(Interactive { 143 | name: format!("accept://{}", addr), 144 | duplexer, 145 | }); 146 | } 147 | 148 | #[cfg(unix)] 149 | { 150 | if url.port().is_some() || url.host_str().is_some() { 151 | return Err(anyhow!( 152 | "Unix-domain connect URL should only contain a path" 153 | )); 154 | } 155 | 156 | let listener = UnixListener::bind(url.path())?; 157 | 158 | let (duplexer, addr) = listener.accept()?; 159 | let duplexer = StreamDuplexer::unix_stream(duplexer); 160 | let name = path_to_name("accept", addr.as_pathname().unwrap())?; 161 | 162 | Ok(Interactive { name, duplexer }) 163 | } 164 | 165 | #[cfg(windows)] 166 | { 167 | Err(anyhow!("Unsupported connect URL: {}", url)) 168 | } 169 | } 170 | 171 | fn open_path(path: &Path) -> anyhow::Result { 172 | let name = path_to_name("file", path)?; 173 | let duplexer = CharDevice::open(path)?; 174 | let duplexer = StreamDuplexer::char_device(duplexer); 175 | Ok(Interactive { name, duplexer }) 176 | } 177 | 178 | #[cfg(not(windows))] 179 | fn spawn_child(os: &OsStr, lossy: &str) -> anyhow::Result { 180 | use std::process::Command; 181 | assert!(lossy.starts_with("$(")); 182 | if !lossy.ends_with(')') { 183 | return Err(anyhow!("child string must end in ')'")); 184 | } 185 | let s = if let Some(s) = os.to_str() { 186 | s 187 | } else { 188 | return Err(anyhow!("Non-UTF-8 child strings not yet supported")); 189 | }; 190 | let words = shell_words::split(&s[2..s.len() - 1])?; 191 | let (first, rest) = words 192 | .split_first() 193 | .ok_or_else(|| anyhow!("child stream specified with '(...)' must contain a command"))?; 194 | let mut command = Command::new(first); 195 | command.args(rest); 196 | let duplexer = StreamDuplexer::duplex_with_command(command)?; 197 | Ok(Interactive { 198 | name: lossy.to_owned(), 199 | duplexer, 200 | }) 201 | } 202 | -------------------------------------------------------------------------------- /src/open_output.rs: -------------------------------------------------------------------------------- 1 | use crate::path_to_name::path_to_name; 2 | use crate::MediaType; 3 | use anyhow::anyhow; 4 | use clap::AmbientAuthority; 5 | use flate2::write::GzEncoder; 6 | use flate2::Compression; 7 | use io_streams::StreamWriter; 8 | use std::ffi::OsStr; 9 | use std::fs::File; 10 | use std::path::Path; 11 | use url::Url; 12 | 13 | pub(crate) struct Output { 14 | pub(crate) name: String, 15 | pub(crate) writer: StreamWriter, 16 | pub(crate) media_type: MediaType, 17 | } 18 | 19 | pub(crate) fn open_output( 20 | os: &OsStr, 21 | media_type: MediaType, 22 | _ambient_authority: AmbientAuthority, 23 | ) -> anyhow::Result { 24 | if let Some(s) = os.to_str() { 25 | // If we can parse it as a URL, treat it as such. 26 | if let Ok(url) = Url::parse(s) { 27 | return open_url(url, media_type); 28 | } 29 | 30 | // Special-case "-" to mean stdout. 31 | if s == "-" { 32 | return acquire_stdout(media_type); 33 | } 34 | } 35 | 36 | #[cfg(not(windows))] 37 | { 38 | let lossy = os.to_string_lossy(); 39 | 40 | // Strings beginning with "$(" are commands. 41 | if lossy.starts_with("$(") { 42 | return spawn_child(os, &lossy, media_type); 43 | } 44 | } 45 | 46 | // Otherwise try opening it as a path in the filesystem namespace. 47 | open_path(Path::new(os), media_type) 48 | } 49 | 50 | fn acquire_stdout(media_type: MediaType) -> anyhow::Result { 51 | let stdout = StreamWriter::stdout()?; 52 | 53 | Ok(Output { 54 | name: "-".to_string(), 55 | writer: stdout, 56 | media_type, 57 | }) 58 | } 59 | 60 | fn open_url(url: Url, media_type: MediaType) -> anyhow::Result { 61 | match url.scheme() { 62 | // TODO: POST the data to HTTP? But the `Write` trait makes this 63 | // tricky because there's no hook for closing and finishing the 64 | // stream. `Drop` can't fail. 65 | "http" | "https" => Err(anyhow!("output to HTTP not supported yet")), 66 | "file" => { 67 | if !url.username().is_empty() 68 | || url.password().is_some() 69 | || url.has_host() 70 | || url.port().is_some() 71 | || url.query().is_some() 72 | || url.fragment().is_some() 73 | { 74 | return Err(anyhow!("file URL should only contain a path")); 75 | } 76 | // TODO: https://docs.rs/url/latest/url/struct.Url.html#method.to_file_path 77 | // is ambiguous about how it can fail. What is `Path::new_opt`? 78 | open_path( 79 | &url.to_file_path() 80 | .map_err(|_: ()| anyhow!("unknown file URL weirdness"))?, 81 | media_type, 82 | ) 83 | } 84 | "data" => Err(anyhow!("output to data URL isn't possible")), 85 | other => Err(anyhow!("unsupported URL scheme \"{}\"", other)), 86 | } 87 | } 88 | 89 | fn open_path(path: &Path, media_type: MediaType) -> anyhow::Result { 90 | let name = path_to_name("file", path)?; 91 | let file = File::create(path).map_err(|err| anyhow!("{}: {}", path.display(), err))?; 92 | if path.extension() == Some(Path::new("gz").as_os_str()) { 93 | // TODO: We shouldn't really need to allocate a `PathBuf` here. 94 | let path = path.with_extension(""); 95 | let media_type = MediaType::union(media_type, MediaType::from_extension(path.extension())); 96 | // 6 is the default gzip compression level. 97 | let writer = 98 | StreamWriter::piped_thread(Box::new(GzEncoder::new(file, Compression::new(6))))?; 99 | Ok(Output { 100 | name, 101 | writer, 102 | media_type, 103 | }) 104 | } else { 105 | let media_type = MediaType::union(media_type, MediaType::from_extension(path.extension())); 106 | let writer = StreamWriter::file(file); 107 | Ok(Output { 108 | name, 109 | writer, 110 | media_type, 111 | }) 112 | } 113 | } 114 | 115 | #[cfg(not(windows))] 116 | fn spawn_child(os: &OsStr, lossy: &str, media_type: MediaType) -> anyhow::Result { 117 | use std::process::{Command, Stdio}; 118 | assert!(lossy.starts_with("$(")); 119 | if !lossy.ends_with(')') { 120 | return Err(anyhow!("child string must end in ')'")); 121 | } 122 | let s = if let Some(s) = os.to_str() { 123 | s 124 | } else { 125 | return Err(anyhow!("Non-UTF-8 child strings not yet supported")); 126 | }; 127 | let words = shell_words::split(&s[2..s.len() - 1])?; 128 | let (first, rest) = words 129 | .split_first() 130 | .ok_or_else(|| anyhow!("child stream specified with '(...)' must contain a command"))?; 131 | let child = Command::new(first) 132 | .args(rest) 133 | .stdin(Stdio::piped()) 134 | .stdout(Stdio::null()) 135 | .spawn()?; 136 | let writer = StreamWriter::child_stdin(child.stdin.unwrap()); 137 | Ok(Output { 138 | name: lossy.to_owned(), 139 | writer, 140 | media_type, 141 | }) 142 | } 143 | -------------------------------------------------------------------------------- /src/output_byte_stream.rs: -------------------------------------------------------------------------------- 1 | use crate::lazy_output::FromLazyOutput; 2 | use crate::open_output::{open_output, Output}; 3 | use crate::{MediaType, Pseudonym}; 4 | use anyhow::anyhow; 5 | use clap::{AmbientAuthority, TryFromOsArg}; 6 | use io_streams::StreamWriter; 7 | use layered_io::{Bufferable, LayeredWriter, WriteLayered}; 8 | use std::ffi::{OsStr, OsString}; 9 | use std::fmt::{self, Arguments, Debug, Formatter}; 10 | use std::io::{self, IoSlice, Write}; 11 | use terminal_io::{NeverTerminalWriter, TerminalWriter, WriteTerminal}; 12 | 13 | /// An output stream for binary output. 14 | /// 15 | /// An `OutputByteStream` implements `Write` so it supports `write`, 16 | /// `write_all`, etc. and can be used anywhere a `Write`-implementing 17 | /// object is needed. 18 | /// 19 | /// `OutputByteStream` is unbuffered (even when it is stdout), so wrapping 20 | /// it in a [`std::io::BufWriter`] or [`std::io::LineWriter`] is 21 | /// recommended for performance. 22 | /// 23 | /// The primary way to construct an `OutputByteStream` is to use it as 24 | /// a type in a `kommand` argument or `clap_derive` struct. Command-line 25 | /// arguments will then be automatically converted into output streams. 26 | /// Currently supported syntaxes include: 27 | /// - Names starting with `file:` are interpreted as local filesystem URLs 28 | /// providing paths to files to open. 29 | /// - "-" is interpreted as standard output. 30 | /// - "(...)" runs a command with a pipe to the child process' stdin, on 31 | /// platforms whch support it. 32 | /// - Names which don't parse as URLs are interpreted as plain local 33 | /// filesystem paths. To force a string to be interpreted as a plain local 34 | /// path, arrange for it to begin with `./` or `/`. 35 | /// 36 | /// Programs using `OutputByteStream` as an argument should avoid using 37 | /// `std::io::stdout`, `std::println`, or anything else which uses standard 38 | /// output implicitly. 39 | pub struct OutputByteStream { 40 | name: String, 41 | writer: LayeredWriter>, 42 | media_type: MediaType, 43 | } 44 | 45 | impl OutputByteStream { 46 | /// Write the given `Pseudonym` to the output stream. 47 | #[inline] 48 | pub fn write_pseudonym(&mut self, pseudonym: &Pseudonym) -> io::Result<()> { 49 | Write::write_all(self, pseudonym.name.as_bytes()) 50 | } 51 | 52 | /// Return a `Pseudonym` which encapsulates this stream's name (typically 53 | /// its filesystem path or its URL). This allows it to be written to an 54 | /// `OutputByteStream` while otherwise remaining entirely opaque. 55 | #[inline] 56 | pub fn pseudonym(&self) -> Pseudonym { 57 | Pseudonym::new(self.name.clone()) 58 | } 59 | 60 | /// If the output stream metadata implies a particular media type, also 61 | /// known as MIME type, return it. Some output streams know their type, 62 | /// though many do not. 63 | #[inline] 64 | pub fn media_type(&self) -> &MediaType { 65 | &self.media_type 66 | } 67 | 68 | fn from_output(output: Output) -> anyhow::Result { 69 | let writer = NeverTerminalWriter::new(output.writer); 70 | 71 | let writer = TerminalWriter::with_handle(writer); 72 | if writer.is_output_terminal() { 73 | return Err(anyhow!("attempted to write binary output to a terminal")); 74 | } 75 | 76 | let writer = LayeredWriter::new(writer.into_inner()); 77 | 78 | Ok(Self { 79 | name: output.name, 80 | writer, 81 | media_type: output.media_type, 82 | }) 83 | } 84 | } 85 | 86 | /// Implement `From<&OsStr>` so that `clap_derive` can parse `OutputByteStream` 87 | /// objects automatically. 88 | /// 89 | /// This is hidden from the documentation as it opens resources from 90 | /// strings using ambient authorities. 91 | #[doc(hidden)] 92 | impl TryFromOsArg for OutputByteStream { 93 | type Error = anyhow::Error; 94 | 95 | #[inline] 96 | fn try_from_os_str_arg( 97 | os: &OsStr, 98 | ambient_authority: AmbientAuthority, 99 | ) -> anyhow::Result { 100 | open_output(os, MediaType::unknown(), ambient_authority).and_then(Self::from_output) 101 | } 102 | } 103 | 104 | impl WriteLayered for OutputByteStream { 105 | #[inline] 106 | fn close(&mut self) -> io::Result<()> { 107 | self.writer.close() 108 | } 109 | } 110 | 111 | impl Write for OutputByteStream { 112 | #[inline] 113 | fn write(&mut self, buf: &[u8]) -> io::Result { 114 | self.writer.write(buf) 115 | } 116 | 117 | #[inline] 118 | fn flush(&mut self) -> io::Result<()> { 119 | self.writer.flush() 120 | } 121 | 122 | #[inline] 123 | fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result { 124 | self.writer.write_vectored(bufs) 125 | } 126 | 127 | #[cfg(can_vector)] 128 | #[inline] 129 | fn is_write_vectored(&self) -> bool { 130 | self.writer.is_write_vectored() 131 | } 132 | 133 | #[inline] 134 | fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { 135 | self.writer.write_all(buf) 136 | } 137 | 138 | #[cfg(write_all_vectored)] 139 | #[inline] 140 | fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> { 141 | self.writer.write_all_vectored(bufs) 142 | } 143 | 144 | #[inline] 145 | fn write_fmt(&mut self, fmt: Arguments<'_>) -> io::Result<()> { 146 | self.writer.write_fmt(fmt) 147 | } 148 | } 149 | 150 | impl Bufferable for OutputByteStream { 151 | #[inline] 152 | fn abandon(&mut self) { 153 | self.writer.abandon() 154 | } 155 | } 156 | 157 | impl FromLazyOutput for OutputByteStream { 158 | type Err = anyhow::Error; 159 | 160 | fn from_lazy_output( 161 | name: OsString, 162 | media_type: MediaType, 163 | ambient_authority: AmbientAuthority, 164 | ) -> Result { 165 | open_output(&name, media_type, ambient_authority).and_then(Self::from_output) 166 | } 167 | } 168 | 169 | impl Debug for OutputByteStream { 170 | fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { 171 | // Don't print the name here, as that's an implementation detail. 172 | let mut b = f.debug_struct("OutputByteStream"); 173 | b.field("media_type", &self.media_type); 174 | b.finish() 175 | } 176 | } 177 | -------------------------------------------------------------------------------- /src/output_text_stream.rs: -------------------------------------------------------------------------------- 1 | use crate::lazy_output::FromLazyOutput; 2 | use crate::open_output::{open_output, Output}; 3 | #[cfg(unix)] 4 | use crate::summon_bat::summon_bat; 5 | use crate::{MediaType, Pseudonym}; 6 | use basic_text::{TextStr, TextWriter, WriteText}; 7 | use clap::{AmbientAuthority, TryFromOsArg}; 8 | #[cfg(not(windows))] 9 | use io_extras::os::rustix::AsRawFd; 10 | use io_streams::StreamWriter; 11 | use layered_io::{Bufferable, LayeredWriter, WriteLayered}; 12 | use std::ffi::{OsStr, OsString}; 13 | use std::fmt::{self, Arguments, Debug, Formatter}; 14 | use std::io::{self, IoSlice, Write}; 15 | use std::process::{exit, Child}; 16 | use terminal_io::{Terminal, TerminalColorSupport, TerminalWriter, WriteTerminal}; 17 | use utf8_io::{Utf8Writer, WriteStr}; 18 | 19 | /// An output stream for plain text output. 20 | /// 21 | /// An `OutputTextStream` implements `Write` so it supports `write`, 22 | /// `write_all`, etc. and can be used anywhere a `Write`-implementing 23 | /// object is needed. 24 | /// 25 | /// `OutputTextStream` is unbuffered (even when it is stdout), so wrapping 26 | /// it in a [`std::io::BufWriter`] or [`std::io::LineWriter`] is 27 | /// recommended for performance. 28 | /// 29 | /// The primary way to construct an `OutputTextStream` is to use it as 30 | /// a type in a `kommand` argument or a `clap_derive` struct. Command-line 31 | /// arguments will then be automatically converted into output streams. 32 | /// Currently supported syntaxes include: 33 | /// - Names starting with `file:` are interpreted as local filesystem URLs 34 | /// providing paths to files to open. 35 | /// - "-" is interpreted as standard output. 36 | /// - "(...)" runs a command with a pipe to the child process' stdin, on 37 | /// platforms whch support it. 38 | /// - Names which don't parse as URLs are interpreted as plain local 39 | /// filesystem paths. To force a string to be interpreted as a plain local 40 | /// path, arrange for it to begin with `./` or `/`. 41 | /// 42 | /// Programs using `OutputTextStream` as an argument should avoid using 43 | /// `std::io::stdout`, `std::println`, or anything else which uses standard 44 | /// output implicitly. 45 | pub struct OutputTextStream { 46 | name: String, 47 | writer: TextWriter>>>, 48 | media_type: MediaType, 49 | helper_child: Option<(Child, StreamWriter)>, 50 | } 51 | 52 | impl OutputTextStream { 53 | /// Write the given `Pseudonym` to the output stream. 54 | #[inline] 55 | pub fn write_pseudonym(&mut self, pseudonym: &Pseudonym) -> io::Result<()> { 56 | Write::write_all(self, pseudonym.name.as_bytes()) 57 | } 58 | 59 | /// Return a `Pseudonym` which encapsulates this stream's name (typically 60 | /// its filesystem path or its URL). This allows it to be written to an 61 | /// `OutputByteStream` while otherwise remaining entirely opaque. 62 | #[inline] 63 | pub fn pseudonym(&self) -> Pseudonym { 64 | Pseudonym::new(self.name.clone()) 65 | } 66 | 67 | /// If the output stream metadata implies a particular media type, also 68 | /// known as MIME type, return it. Otherwise default to 69 | /// "text/plain; charset=utf-8". 70 | #[inline] 71 | pub fn media_type(&self) -> &MediaType { 72 | &self.media_type 73 | } 74 | 75 | fn from_output(output: Output) -> Self { 76 | #[cfg(unix)] 77 | let is_stdout = output.writer.as_raw_fd() == rustix::stdio::raw_stdout(); 78 | let terminal = TerminalWriter::with_handle(output.writer); 79 | #[cfg(unix)] 80 | let is_terminal = terminal.is_output_terminal(); 81 | #[cfg(unix)] 82 | let color_support = terminal.color_support(); 83 | #[cfg(unix)] 84 | let color_preference = terminal.color_preference(); 85 | 86 | #[cfg(unix)] 87 | if is_terminal && is_stdout { 88 | let stdout_helper_child = summon_bat(&terminal, &output.media_type); 89 | 90 | if let Some(mut stdout_helper_child) = stdout_helper_child { 91 | let writer = StreamWriter::child_stdin(stdout_helper_child.stdin.take().unwrap()); 92 | let writer = 93 | TerminalWriter::from(writer, is_terminal, color_support, color_preference); 94 | let writer = LayeredWriter::new(writer); 95 | let writer = Utf8Writer::new(writer); 96 | let writer = TextWriter::with_ansi_color_output(writer); 97 | 98 | return Self { 99 | name: output.name, 100 | writer, 101 | media_type: output.media_type, 102 | helper_child: Some((stdout_helper_child, terminal.into_inner())), 103 | }; 104 | } 105 | } 106 | 107 | let writer = LayeredWriter::new(terminal); 108 | let writer = Utf8Writer::new(writer); 109 | let writer = TextWriter::with_ansi_color_output(writer); 110 | let media_type = output.media_type.union(MediaType::text()); 111 | Self { 112 | name: output.name, 113 | writer, 114 | media_type, 115 | helper_child: None, 116 | } 117 | } 118 | } 119 | 120 | /// Implement `From<&OsStr>` so that `clap_derive` can parse `OutputTextStream` 121 | /// objects automatically. 122 | /// 123 | /// This is hidden from the documentation as it opens resources from 124 | /// strings using ambient authorities. 125 | #[doc(hidden)] 126 | impl TryFromOsArg for OutputTextStream { 127 | type Error = anyhow::Error; 128 | 129 | #[inline] 130 | fn try_from_os_str_arg( 131 | os: &OsStr, 132 | ambient_authority: AmbientAuthority, 133 | ) -> anyhow::Result { 134 | open_output(os, MediaType::text(), ambient_authority).map(Self::from_output) 135 | } 136 | } 137 | 138 | impl WriteLayered for OutputTextStream { 139 | #[inline] 140 | fn close(&mut self) -> io::Result<()> { 141 | self.writer.close()?; 142 | 143 | if let Some(mut helper_child) = self.helper_child.take() { 144 | helper_child.0.wait()?; 145 | } 146 | 147 | Ok(()) 148 | } 149 | } 150 | 151 | impl WriteStr for OutputTextStream { 152 | #[inline] 153 | fn write_str(&mut self, buf: &str) -> io::Result<()> { 154 | self.writer.write_str(buf) 155 | } 156 | } 157 | 158 | impl Write for OutputTextStream { 159 | #[inline] 160 | fn write(&mut self, buf: &[u8]) -> io::Result { 161 | self.writer.write(buf) 162 | } 163 | 164 | #[inline] 165 | fn flush(&mut self) -> io::Result<()> { 166 | self.writer.flush() 167 | } 168 | 169 | #[inline] 170 | fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result { 171 | self.writer.write_vectored(bufs) 172 | } 173 | 174 | #[cfg(can_vector)] 175 | #[inline] 176 | fn is_write_vectored(&self) -> bool { 177 | self.writer.is_write_vectored() 178 | } 179 | 180 | #[inline] 181 | fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { 182 | self.writer.write_all(buf) 183 | } 184 | 185 | #[cfg(write_all_vectored)] 186 | #[inline] 187 | fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> { 188 | self.writer.write_all_vectored(bufs) 189 | } 190 | 191 | #[inline] 192 | fn write_fmt(&mut self, fmt: Arguments<'_>) -> io::Result<()> { 193 | self.writer.write_fmt(fmt) 194 | } 195 | } 196 | 197 | impl Bufferable for OutputTextStream { 198 | #[inline] 199 | fn abandon(&mut self) { 200 | self.writer.abandon() 201 | } 202 | } 203 | 204 | impl Terminal for OutputTextStream {} 205 | 206 | impl WriteTerminal for OutputTextStream { 207 | #[inline] 208 | fn color_support(&self) -> TerminalColorSupport { 209 | self.writer.color_support() 210 | } 211 | 212 | #[inline] 213 | fn color_preference(&self) -> bool { 214 | self.writer.color_preference() 215 | } 216 | 217 | #[inline] 218 | fn is_output_terminal(&self) -> bool { 219 | self.writer.is_output_terminal() 220 | } 221 | } 222 | 223 | impl WriteText for OutputTextStream { 224 | #[inline] 225 | fn write_text(&mut self, buf: &TextStr) -> io::Result<()> { 226 | self.writer.write_text(buf) 227 | } 228 | } 229 | 230 | impl Drop for OutputTextStream { 231 | fn drop(&mut self) { 232 | if let Some(mut helper_child) = self.helper_child.take() { 233 | // Wait for the child. We can't return `Err` from a `drop` function, 234 | // so just print a message and exit. Callers should use 235 | // `end()` to declare the end of the stream if they wish to avoid 236 | // these errors. 237 | 238 | // Close standard output, prompting the child process to exit. 239 | if let Err(e) = self.writer.close() { 240 | eprintln!("Output formatting process encountered error: {:?}", e); 241 | #[cfg(not(windows))] 242 | exit(rustix::process::EXIT_FAILURE); 243 | #[cfg(windows)] 244 | exit(libc::EXIT_FAILURE); 245 | } 246 | 247 | match helper_child.0.wait() { 248 | Ok(status) => { 249 | if !status.success() { 250 | eprintln!( 251 | "Output formatting process exited with non-success exit status: {:?}", 252 | status 253 | ); 254 | #[cfg(not(windows))] 255 | exit(rustix::process::EXIT_FAILURE); 256 | #[cfg(windows)] 257 | exit(libc::EXIT_FAILURE); 258 | } 259 | } 260 | 261 | Err(e) => { 262 | eprintln!("Unable to wait for output formatting process: {:?}", e); 263 | #[cfg(not(windows))] 264 | exit(rustix::process::EXIT_FAILURE); 265 | #[cfg(windows)] 266 | exit(libc::EXIT_FAILURE); 267 | } 268 | } 269 | } 270 | } 271 | } 272 | 273 | impl FromLazyOutput for OutputTextStream { 274 | type Err = anyhow::Error; 275 | 276 | fn from_lazy_output( 277 | name: OsString, 278 | media_type: MediaType, 279 | ambient_authority: AmbientAuthority, 280 | ) -> Result { 281 | open_output(&name, media_type, ambient_authority).map(Self::from_output) 282 | } 283 | } 284 | 285 | impl Debug for OutputTextStream { 286 | fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { 287 | // Don't print the name here, as that's an implementation detail. 288 | let mut b = f.debug_struct("OutputTextStream"); 289 | b.field("media_type", &self.media_type); 290 | b.finish() 291 | } 292 | } 293 | -------------------------------------------------------------------------------- /src/path_to_name.rs: -------------------------------------------------------------------------------- 1 | use anyhow::anyhow; 2 | use std::path::Path; 3 | use std::str; 4 | #[cfg(not(windows))] 5 | use { 6 | percent_encoding::{percent_encode, NON_ALPHANUMERIC}, 7 | std::path::Component, 8 | }; 9 | 10 | #[cfg(not(windows))] 11 | pub(crate) fn path_to_name(scheme: &str, path: &Path) -> anyhow::Result { 12 | #[cfg(unix)] 13 | use std::os::unix::ffi::OsStrExt; 14 | if path.is_absolute() { 15 | let mut result = String::new(); 16 | let mut components = path.components(); 17 | assert!(components.next().unwrap() == Component::RootDir); 18 | if let Some(component) = components.next() { 19 | result += "/"; 20 | result += 21 | &percent_encode(component.as_os_str().as_bytes(), NON_ALPHANUMERIC).to_string(); 22 | for component in components { 23 | result += "/"; 24 | result += 25 | &percent_encode(component.as_os_str().as_bytes(), NON_ALPHANUMERIC).to_string(); 26 | } 27 | } else { 28 | result += "/"; 29 | } 30 | if result == path.display().to_string() { 31 | Ok(result) 32 | } else { 33 | Ok(format!("{}://{}", scheme, result)) 34 | } 35 | } else { 36 | let result = str::from_utf8(path.as_os_str().as_bytes()) 37 | .map_err(|_| anyhow!("not supported yet: non-UTF-8 relative paths",))? 38 | .escape_default() 39 | .to_string(); 40 | if result.contains(':') { 41 | return Err(anyhow!("not supported yet: strings contains `:`")); 42 | } 43 | let display = path.display().to_string(); 44 | if result == display { 45 | Ok(result) 46 | } else { 47 | Err(anyhow!( 48 | "not supported yet: \"interesting\" strings: {}", 49 | result 50 | )) 51 | } 52 | } 53 | } 54 | 55 | #[cfg(windows)] 56 | pub(crate) fn path_to_name(_scheme: &str, path: &Path) -> anyhow::Result { 57 | if path.is_absolute() { 58 | Ok(url::Url::from_file_path(path) 59 | .map_err(|_| { 60 | anyhow!( 61 | "not supported yet: \"interesting\" strings: {}", 62 | path.display() 63 | ) 64 | })? 65 | .into()) 66 | } else { 67 | Err(anyhow!("not supported yet: non-UTF-8 relative paths",)) 68 | } 69 | } 70 | 71 | #[test] 72 | #[cfg_attr(windows, ignore)] // TODO: Improve path handling on Windows. 73 | fn test_path_to_name() { 74 | assert_eq!(path_to_name("file", Path::new("/")).unwrap(), "/"); 75 | assert_eq!(path_to_name("file", Path::new("/foo")).unwrap(), "/foo"); 76 | assert_eq!( 77 | path_to_name("file", Path::new("/foo:bar")).unwrap(), 78 | "file:///foo%3Abar" 79 | ); 80 | assert_eq!(path_to_name("file", Path::new("foo")).unwrap(), "foo"); 81 | // TODO: Redo how relative paths are handled. 82 | // assert_eq!(path_to_name("file", Path::new("./foo")).unwrap(), "./foo"); 83 | // assert_eq!( 84 | // path_to_name("file", 85 | // OsStr::from_bytes(b"f\xffoo").as_ref()).unwrap(), "\"./f\\ 86 | // u{fffd}oo\"" 87 | //); 88 | } 89 | -------------------------------------------------------------------------------- /src/pseudonym.rs: -------------------------------------------------------------------------------- 1 | /// This struct encapsulates the name of an entity whose name is being 2 | /// hidden in the `nameless` API. It can be written to an `OutputByteStream` 3 | /// but it's otherwise entirely opaque. 4 | pub struct Pseudonym { 5 | pub(crate) name: String, 6 | } 7 | 8 | impl Pseudonym { 9 | pub(crate) fn new(name: String) -> Self { 10 | Self { name } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/summon_bat.rs: -------------------------------------------------------------------------------- 1 | //! Wrap stdout in a [`bat`]. 2 | //! 3 | //! [`bat`]: https://crates.io/crates/bat 4 | 5 | use crate::MediaType; 6 | use io_extras::grip::AsRawGrip; 7 | use std::process::{Child, Command, Stdio}; 8 | 9 | /// Arrange for stdout to be connected to a pipe to a process which runs 10 | /// bat to do syntax highlighting and paging. 11 | pub(crate) fn summon_bat(stdout: &impl AsRawGrip, media_type: &MediaType) -> Option { 12 | assert_eq!(stdout.as_raw_grip(), std::io::stdout().as_raw_grip()); 13 | 14 | // If the "bat" command is available, use it. 15 | Command::new("bat") 16 | .arg("--file-name") 17 | .arg(media_type.extension()) 18 | .arg("--style") 19 | .arg("plain") 20 | .stdin(Stdio::piped()) 21 | .spawn() 22 | .ok() 23 | } 24 | --------------------------------------------------------------------------------