├── .github ├── dependabot.yml └── workflows │ └── continuous-integration.yml ├── .gitignore ├── CODE_OF_CONDUCT.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── cli-table-derive ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md └── src │ ├── context.rs │ ├── context │ ├── container.rs │ └── fields.rs │ ├── lib.rs │ ├── table.rs │ └── utils.rs ├── cli-table ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── README.tpl ├── examples │ ├── csv.rs │ ├── nested.rs │ ├── simple.rs │ ├── struct.rs │ └── tuple_struct.rs └── src │ ├── buffers.rs │ ├── cell.rs │ ├── csv.rs │ ├── dimension.rs │ ├── display.rs │ ├── format.rs │ ├── lib.rs │ ├── row.rs │ ├── style.rs │ ├── table.rs │ ├── title.rs │ └── utils.rs └── test-suite ├── Cargo.toml └── tests ├── compiletest.rs └── ui ├── no-enum.rs ├── no-enum.stderr ├── non-display-member.rs ├── non-display-member.stderr ├── title-string-value.rs └── title-string-value.stderr /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: cargo 4 | directory: "/" 5 | schedule: 6 | interval: daily 7 | time: "21:00" 8 | open-pull-requests-limit: 10 9 | -------------------------------------------------------------------------------- /.github/workflows/continuous-integration.yml: -------------------------------------------------------------------------------- 1 | name: Continuous Integration 2 | 3 | on: 4 | pull_request: 5 | branches: 6 | - master 7 | push: 8 | branches: 9 | - master 10 | 11 | jobs: 12 | check: 13 | name: Check 14 | runs-on: ubuntu-latest 15 | steps: 16 | - uses: actions/checkout@v2 17 | - uses: actions-rs/toolchain@v1 18 | with: 19 | profile: minimal 20 | toolchain: stable 21 | override: true 22 | - uses: actions-rs/cargo@v1 23 | with: 24 | command: check 25 | 26 | test: 27 | name: Test Suite 28 | runs-on: ubuntu-latest 29 | steps: 30 | - uses: actions/checkout@v2 31 | - uses: actions-rs/toolchain@v1 32 | with: 33 | profile: minimal 34 | toolchain: stable 35 | override: true 36 | - uses: actions-rs/cargo@v1 37 | with: 38 | command: test 39 | 40 | fmt: 41 | name: Rustfmt 42 | runs-on: ubuntu-latest 43 | steps: 44 | - uses: actions/checkout@v2 45 | - uses: actions-rs/toolchain@v1 46 | with: 47 | profile: minimal 48 | toolchain: stable 49 | override: true 50 | - run: rustup component add rustfmt 51 | - uses: actions-rs/cargo@v1 52 | with: 53 | command: fmt 54 | args: --all -- --check 55 | 56 | clippy: 57 | name: Clippy 58 | runs-on: ubuntu-latest 59 | steps: 60 | - uses: actions/checkout@v2 61 | - uses: actions-rs/toolchain@v1 62 | with: 63 | profile: minimal 64 | toolchain: stable 65 | override: true 66 | - run: rustup component add clippy 67 | - uses: actions-rs/cargo@v1 68 | with: 69 | command: clippy 70 | args: -- -D warnings 71 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | Cargo.lock 4 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at devashishdxt@gmail.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | members = ["cli-table", "cli-table-derive", "test-suite"] 3 | resolver = "3" 4 | -------------------------------------------------------------------------------- /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-MIT: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Devashish Dixit 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ./cli-table/README.md -------------------------------------------------------------------------------- /cli-table-derive/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "cli-table-derive" 3 | version = "0.5.0" 4 | authors = ["Devashish Dixit "] 5 | license = "MIT/Apache-2.0" 6 | description = "A crate for printing tables on command line" 7 | homepage = "https://github.com/devashishdxt/cli-table" 8 | repository = "https://github.com/devashishdxt/cli-table" 9 | categories = ["command-line-interface"] 10 | keywords = ["table", "cli", "format"] 11 | readme = "README.md" 12 | include = ["Cargo.toml", "src/**/*.rs", "README.md", "LICENSE-*"] 13 | edition = "2024" 14 | 15 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 16 | 17 | [features] 18 | default = [] 19 | doc = [] 20 | 21 | [dependencies] 22 | proc-macro2 = "1.0.94" 23 | syn = "2.0.100" 24 | quote = "1.0.40" 25 | 26 | [lib] 27 | proc-macro = true 28 | -------------------------------------------------------------------------------- /cli-table-derive/LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | ../LICENSE-APACHE -------------------------------------------------------------------------------- /cli-table-derive/LICENSE-MIT: -------------------------------------------------------------------------------- 1 | ../LICENSE-MIT -------------------------------------------------------------------------------- /cli-table-derive/README.md: -------------------------------------------------------------------------------- 1 | ../cli-table/README.md -------------------------------------------------------------------------------- /cli-table-derive/src/context.rs: -------------------------------------------------------------------------------- 1 | mod container; 2 | mod fields; 3 | 4 | use syn::{DeriveInput, Result}; 5 | 6 | use self::{container::Container, fields::Fields}; 7 | 8 | pub struct Context<'a> { 9 | pub container: Container<'a>, 10 | pub fields: Fields, 11 | } 12 | 13 | impl<'a> Context<'a> { 14 | pub fn new(input: &'a DeriveInput) -> Result { 15 | let container = Container::new(input)?; 16 | let fields = Fields::new(input)?; 17 | 18 | Ok(Self { container, fields }) 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /cli-table-derive/src/context/container.rs: -------------------------------------------------------------------------------- 1 | use quote::quote; 2 | use syn::{DeriveInput, Error, Ident, Lit, Path, Result}; 3 | 4 | use crate::utils::get_attributes; 5 | 6 | pub struct Container<'a> { 7 | pub crate_name: Path, 8 | pub name: &'a Ident, 9 | } 10 | 11 | impl<'a> Container<'a> { 12 | pub fn new(input: &'a DeriveInput) -> Result { 13 | let container_attributes = get_attributes(&input.attrs)?; 14 | 15 | let mut crate_name = None; 16 | 17 | for (key, value) in container_attributes { 18 | if key.is_ident("crate") { 19 | crate_name = Some(match value { 20 | Lit::Str(lit_str) => lit_str.parse::(), 21 | bad => Err(Error::new_spanned( 22 | bad, 23 | "Invalid value for #[table(crate = \"crate_path\")]", 24 | )), 25 | }?); 26 | } 27 | } 28 | 29 | let mut container_builder = Container::builder(&input.ident); 30 | 31 | if let Some(crate_name) = crate_name { 32 | container_builder.crate_name(crate_name); 33 | } 34 | 35 | Ok(container_builder.build()) 36 | } 37 | 38 | fn builder(name: &'a Ident) -> ContainerBuilder<'a> { 39 | ContainerBuilder::new(name) 40 | } 41 | } 42 | 43 | struct ContainerBuilder<'a> { 44 | crate_name: Option, 45 | name: &'a Ident, 46 | } 47 | 48 | impl<'a> ContainerBuilder<'a> { 49 | pub fn new(name: &'a Ident) -> Self { 50 | Self { 51 | crate_name: None, 52 | name, 53 | } 54 | } 55 | 56 | pub fn crate_name(&mut self, crate_name: Path) -> &mut Self { 57 | self.crate_name = Some(crate_name); 58 | self 59 | } 60 | 61 | pub fn build(self) -> Container<'a> { 62 | Container { 63 | crate_name: self 64 | .crate_name 65 | .unwrap_or_else(|| syn::parse2(quote!(::cli_table)).unwrap()), 66 | name: self.name, 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /cli-table-derive/src/context/fields.rs: -------------------------------------------------------------------------------- 1 | use proc_macro2::{Span, TokenStream}; 2 | use quote::ToTokens; 3 | use syn::{ 4 | Data, DeriveInput, Error, Expr, Field as SynField, Fields as SynFields, Ident, Index, Lit, 5 | LitBool, LitStr, Result, spanned::Spanned, 6 | }; 7 | 8 | use crate::utils::get_attributes; 9 | 10 | pub struct Fields { 11 | fields: Vec, 12 | } 13 | 14 | impl Fields { 15 | pub fn new(input: &DeriveInput) -> Result { 16 | match input.data { 17 | Data::Struct(ref data_struct) => Self::from_fields(&data_struct.fields), 18 | _ => Err(Error::new_spanned( 19 | input, 20 | "`cli_table` derive macros can only be used on structs", 21 | )), 22 | } 23 | } 24 | 25 | pub fn into_iter(self) -> impl Iterator { 26 | self.fields.into_iter() 27 | } 28 | 29 | fn from_fields(syn_fields: &SynFields) -> Result { 30 | let mut fields = Vec::new(); 31 | 32 | for (index, syn_field) in syn_fields.into_iter().enumerate() { 33 | let field = Field::new(syn_field, index)?; 34 | 35 | if let Some(field) = field { 36 | fields.push(field); 37 | } 38 | } 39 | 40 | fields.sort_by(|left, right| left.order.cmp(&right.order)); 41 | 42 | Ok(Fields { fields }) 43 | } 44 | } 45 | 46 | pub struct Field { 47 | pub ident: TokenStream, 48 | pub title: LitStr, 49 | pub justify: Option, 50 | pub align: Option, 51 | pub color: Option, 52 | pub bold: Option, 53 | pub order: usize, 54 | pub display_fn: Option, 55 | pub customize_fn: Option, 56 | pub span: Span, 57 | } 58 | 59 | impl Field { 60 | pub fn new(field: &SynField, index: usize) -> Result> { 61 | let ident = field 62 | .ident 63 | .as_ref() 64 | .map(ToTokens::into_token_stream) 65 | .unwrap_or_else(|| Index::from(index).into_token_stream()); 66 | let span = field.span(); 67 | 68 | let mut title = None; 69 | let mut justify = None; 70 | let mut align = None; 71 | let mut color = None; 72 | let mut bold = None; 73 | let mut order = None; 74 | let mut display_fn = None; 75 | let mut customize_fn = None; 76 | let mut skip = None; 77 | 78 | let field_attributes = get_attributes(&field.attrs)?; 79 | 80 | for (key, value) in field_attributes { 81 | if key.is_ident("name") || key.is_ident("title") { 82 | title = Some(match value { 83 | Lit::Str(lit_str) => Ok(lit_str), 84 | bad => Err(Error::new_spanned( 85 | bad, 86 | "Invalid value for #[table(title = \"field_name\")]", 87 | )), 88 | }?); 89 | } else if key.is_ident("justify") { 90 | justify = Some(match value { 91 | Lit::Str(lit_str) => lit_str.parse::(), 92 | bad => Err(Error::new_spanned( 93 | bad, 94 | "Invalid value for #[table(justify = \"value\")]", 95 | )), 96 | }?); 97 | } else if key.is_ident("align") { 98 | align = Some(match value { 99 | Lit::Str(lit_str) => lit_str.parse::(), 100 | bad => Err(Error::new_spanned( 101 | bad, 102 | "Invalid value for #[table(align = \"value\")]", 103 | )), 104 | }?); 105 | } else if key.is_ident("color") { 106 | color = Some(match value { 107 | Lit::Str(lit_str) => lit_str.parse::(), 108 | bad => Err(Error::new_spanned( 109 | bad, 110 | "Invalid value for #[table(color = \"value\")]", 111 | )), 112 | }?); 113 | } else if key.is_ident("bold") { 114 | bold = Some(match value { 115 | Lit::Bool(lit_bool) => Ok(lit_bool), 116 | bad => Err(Error::new_spanned(bad, "Invalid value for #[table(bold)]")), 117 | }?); 118 | } else if key.is_ident("order") { 119 | order = Some(match value { 120 | Lit::Int(lit_int) => lit_int.base10_parse::(), 121 | bad => Err(Error::new_spanned( 122 | bad, 123 | "Invalid value for #[table(order = )]", 124 | )), 125 | }?); 126 | } else if key.is_ident("display_fn") { 127 | display_fn = Some(match value { 128 | Lit::Str(lit_str) => lit_str.parse::(), 129 | bad => Err(Error::new_spanned( 130 | bad, 131 | "Invalid value for #[table(display_fn = \"value\")]", 132 | )), 133 | }?); 134 | } else if key.is_ident("customize_fn") { 135 | customize_fn = Some(match value { 136 | Lit::Str(lit_str) => lit_str.parse::(), 137 | bad => Err(Error::new_spanned( 138 | bad, 139 | "Invalid value for #[table(display_fn = \"value\")]", 140 | )), 141 | }?); 142 | } else if key.is_ident("skip") { 143 | skip = Some(match value { 144 | Lit::Bool(lit_bool) => Ok(lit_bool), 145 | bad => Err(Error::new_spanned(bad, "Invalid value for #[table(bold)]")), 146 | }?); 147 | } 148 | } 149 | 150 | if let Some(skip) = skip { 151 | if skip.value { 152 | return Ok(None); 153 | } 154 | } 155 | 156 | let mut field_builder = Self::builder(ident, span); 157 | 158 | if let Some(title) = title { 159 | field_builder.title(title); 160 | } 161 | 162 | if let Some(justify) = justify { 163 | field_builder.justify(justify); 164 | } 165 | 166 | if let Some(align) = align { 167 | field_builder.align(align); 168 | } 169 | 170 | if let Some(color) = color { 171 | field_builder.color(color); 172 | } 173 | 174 | if let Some(bold) = bold { 175 | field_builder.bold(bold); 176 | } 177 | 178 | if let Some(order) = order { 179 | field_builder.order(order); 180 | } 181 | 182 | if let Some(display_fn) = display_fn { 183 | field_builder.display_fn(display_fn); 184 | } 185 | 186 | if let Some(customize_fn) = customize_fn { 187 | field_builder.customize_fn(customize_fn); 188 | } 189 | 190 | Ok(Some(field_builder.build())) 191 | } 192 | 193 | fn builder(ident: TokenStream, span: Span) -> FieldBuilder { 194 | FieldBuilder::new(ident, span) 195 | } 196 | } 197 | 198 | struct FieldBuilder { 199 | ident: TokenStream, 200 | title: Option, 201 | justify: Option, 202 | align: Option, 203 | color: Option, 204 | bold: Option, 205 | order: Option, 206 | display_fn: Option, 207 | customize_fn: Option, 208 | span: Span, 209 | } 210 | 211 | impl FieldBuilder { 212 | fn new(ident: TokenStream, span: Span) -> Self { 213 | Self { 214 | ident, 215 | title: None, 216 | justify: None, 217 | align: None, 218 | color: None, 219 | bold: None, 220 | order: None, 221 | display_fn: None, 222 | customize_fn: None, 223 | span, 224 | } 225 | } 226 | 227 | fn title(&mut self, title: LitStr) -> &mut Self { 228 | self.title = Some(title); 229 | self 230 | } 231 | 232 | fn justify(&mut self, justify: Expr) -> &mut Self { 233 | self.justify = Some(justify); 234 | self 235 | } 236 | 237 | fn align(&mut self, align: Expr) -> &mut Self { 238 | self.align = Some(align); 239 | self 240 | } 241 | 242 | fn color(&mut self, color: Expr) -> &mut Self { 243 | self.color = Some(color); 244 | self 245 | } 246 | 247 | fn bold(&mut self, bold: LitBool) -> &mut Self { 248 | self.bold = Some(bold); 249 | self 250 | } 251 | 252 | fn order(&mut self, order: usize) -> &mut Self { 253 | self.order = Some(order); 254 | self 255 | } 256 | 257 | fn display_fn(&mut self, display_fn: Ident) -> &mut Self { 258 | self.display_fn = Some(display_fn); 259 | self 260 | } 261 | 262 | fn customize_fn(&mut self, customize_fn: Ident) -> &mut Self { 263 | self.customize_fn = Some(customize_fn); 264 | self 265 | } 266 | 267 | fn build(self) -> Field { 268 | let ident = self.ident; 269 | let justify = self.justify; 270 | let align = self.align; 271 | let color = self.color; 272 | let bold = self.bold; 273 | let order = self.order.unwrap_or(usize::MAX); 274 | let display_fn = self.display_fn; 275 | let customize_fn = self.customize_fn; 276 | let span = self.span; 277 | 278 | let title = self 279 | .title 280 | .unwrap_or_else(|| LitStr::new(&ident.to_string(), span)); 281 | 282 | Field { 283 | ident, 284 | title, 285 | justify, 286 | align, 287 | color, 288 | bold, 289 | order, 290 | display_fn, 291 | customize_fn, 292 | span, 293 | } 294 | } 295 | } 296 | -------------------------------------------------------------------------------- /cli-table-derive/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![forbid(unsafe_code)] 2 | #![cfg_attr(not(any(docsrs, feature = "doc")), forbid(unstable_features))] 3 | #![deny(missing_docs)] 4 | #![cfg_attr(any(docsrs, feature = "doc"), feature(doc_cfg))] 5 | //! Derive macros for `cli-table` crate. 6 | //! 7 | //! For more details, see [`cli-table`](https://docs.rs/cli-table). 8 | mod context; 9 | mod table; 10 | mod utils; 11 | 12 | use proc_macro::TokenStream; 13 | use syn::{DeriveInput, parse_macro_input}; 14 | 15 | #[proc_macro_derive(Table, attributes(table))] 16 | /// Derive macro to implementing `cli_table` traits 17 | pub fn table(input: TokenStream) -> TokenStream { 18 | // Parse the input tokens into a syntax tree 19 | let input = parse_macro_input!(input as DeriveInput); 20 | 21 | // Prepare and return the output 22 | table::table(input) 23 | .unwrap_or_else(|err| err.to_compile_error()) 24 | .into() 25 | } 26 | -------------------------------------------------------------------------------- /cli-table-derive/src/table.rs: -------------------------------------------------------------------------------- 1 | use proc_macro2::TokenStream; 2 | use quote::{quote, quote_spanned}; 3 | use syn::{DeriveInput, Result}; 4 | 5 | use crate::context::Context; 6 | 7 | pub fn table(input: DeriveInput) -> Result { 8 | // Create context for generating expressions 9 | let context = Context::new(&input)?; 10 | 11 | // Used in the quasi-quotation below as `#name` 12 | let name = context.container.name; 13 | 14 | // Fetch cli_table crate name 15 | let cli_table = &context.container.crate_name; 16 | 17 | // Split a type's generics into the pieces required for implementing a trait for that type 18 | let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); 19 | 20 | let mut field_titles = Vec::new(); 21 | let mut field_rows = Vec::new(); 22 | 23 | for field in context.fields.into_iter() { 24 | field_titles.push(field.title); 25 | 26 | let ident = field.ident; 27 | let justify = field.justify; 28 | let align = field.align; 29 | let color = field.color; 30 | let bold = field.bold; 31 | let display_fn = field.display_fn; 32 | let customize_fn = field.customize_fn; 33 | let span = field.span; 34 | 35 | let cell = match display_fn { 36 | None => quote_spanned! {span=> 37 | &self. #ident 38 | }, 39 | Some(display_fn) => { 40 | let span = display_fn.span(); 41 | quote_spanned! {span=> 42 | #display_fn (&self. #ident) 43 | } 44 | } 45 | }; 46 | 47 | let mut row = quote_spanned! {span=> 48 | #cli_table ::Cell::cell(#cell) 49 | }; 50 | 51 | if let Some(justify) = justify { 52 | row = quote_spanned! {span=> 53 | #row .justify(#justify) 54 | }; 55 | } 56 | 57 | if let Some(align) = align { 58 | row = quote_spanned! {span=> 59 | #row .align(#align) 60 | }; 61 | } 62 | 63 | if let Some(color) = color { 64 | row = quote_spanned! {span=> 65 | #cli_table ::Style::foreground_color(#row, ::core::convert::From::from(#color)) 66 | }; 67 | } 68 | 69 | if let Some(bold) = bold { 70 | row = quote_spanned! {span=> 71 | #cli_table ::Style::bold(#row, #bold) 72 | }; 73 | } 74 | 75 | if let Some(customize_fn) = customize_fn { 76 | row = quote_spanned! {span=> 77 | #customize_fn (#row, &self. #ident) 78 | }; 79 | } 80 | 81 | field_rows.push(row); 82 | } 83 | 84 | // Build the output, possibly using quasi-quotation 85 | Ok(quote! { 86 | #[automatically_derived] 87 | impl #impl_generics #cli_table ::Title for #name #ty_generics # where_clause{ 88 | fn title() -> #cli_table ::RowStruct { 89 | let title: ::std::vec::Vec<#cli_table ::CellStruct> = ::std::vec![ 90 | #(#cli_table ::Style::bold(#cli_table ::Cell::cell(#field_titles), true),)* 91 | ]; 92 | 93 | #cli_table ::Row::row(title) 94 | } 95 | } 96 | 97 | #[automatically_derived] 98 | impl #impl_generics #cli_table ::Row for & #name #ty_generics # where_clause{ 99 | fn row(self) -> #cli_table ::RowStruct { 100 | let row: ::std::vec::Vec<#cli_table ::CellStruct> = ::std::vec![ 101 | #(#field_rows,)* 102 | ]; 103 | 104 | #cli_table ::Row::row(row) 105 | } 106 | } 107 | 108 | #[automatically_derived] 109 | impl #impl_generics #cli_table ::Row for #name #ty_generics # where_clause{ 110 | fn row(self) -> #cli_table ::RowStruct { 111 | #cli_table ::Row::row(&self) 112 | } 113 | } 114 | }) 115 | } 116 | -------------------------------------------------------------------------------- /cli-table-derive/src/utils.rs: -------------------------------------------------------------------------------- 1 | use syn::{Attribute, Error, Lit, LitBool, Path, Result, spanned::Spanned}; 2 | 3 | pub fn get_attributes(attrs: &[Attribute]) -> Result> { 4 | let mut attributes = Vec::new(); 5 | 6 | for attribute in attrs { 7 | if !attribute.path().is_ident("table") { 8 | continue; 9 | } 10 | 11 | if attribute 12 | .parse_nested_meta(|meta| { 13 | let path = meta.path.clone(); 14 | let lit = meta 15 | .value() 16 | .ok() 17 | .map(|v| v.parse()) 18 | .transpose()? 19 | .unwrap_or(Lit::from(LitBool { 20 | value: true, 21 | span: path.span(), 22 | })); 23 | 24 | attributes.push((path, lit)); 25 | 26 | Ok(()) 27 | }) 28 | .is_err() 29 | { 30 | return Err(Error::new_spanned( 31 | attribute, 32 | "Attributes should be of type: #[table(key = \"value\", ..)] or #[table(bool)]", 33 | )); 34 | } 35 | } 36 | 37 | Ok(attributes) 38 | } 39 | -------------------------------------------------------------------------------- /cli-table/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "cli-table" 3 | version = "0.5.0" 4 | authors = ["Devashish Dixit "] 5 | license = "MIT/Apache-2.0" 6 | description = "A crate for printing tables on command line" 7 | homepage = "https://github.com/devashishdxt/cli-table" 8 | repository = "https://github.com/devashishdxt/cli-table" 9 | categories = ["command-line-interface"] 10 | keywords = ["table", "cli", "format"] 11 | readme = "README.md" 12 | include = ["Cargo.toml", "src/**/*.rs", "README.md", "LICENSE-*"] 13 | edition = "2024" 14 | 15 | [lib] 16 | name = "cli_table" 17 | path = "src/lib.rs" 18 | 19 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 20 | 21 | [dependencies] 22 | cli-table-derive = { version = "0.5.0", path = "../cli-table-derive", optional = true } 23 | csv = { version = "1.3.1", optional = true } 24 | termcolor = "1.4.1" 25 | unicode-width = "0.2.0" 26 | 27 | [features] 28 | default = ["csv", "derive"] 29 | derive = ["cli-table-derive", "title"] 30 | doc = [] 31 | title = [] 32 | 33 | [package.metadata.docs.rs] 34 | all-features = true 35 | -------------------------------------------------------------------------------- /cli-table/LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | ../LICENSE-APACHE -------------------------------------------------------------------------------- /cli-table/LICENSE-MIT: -------------------------------------------------------------------------------- 1 | ../LICENSE-MIT -------------------------------------------------------------------------------- /cli-table/README.md: -------------------------------------------------------------------------------- 1 | # cli-table 2 | 3 | [![Continuous Integration](https://github.com/devashishdxt/cli-table/workflows/Continuous%20Integration/badge.svg)](https://github.com/devashishdxt/cli-table/actions?query=workflow%3A%22Continuous+Integration%22) 4 | [![Crates.io](https://img.shields.io/crates/v/cli-table)](https://crates.io/crates/cli-table) 5 | [![Documentation](https://docs.rs/cli-table/badge.svg)](https://docs.rs/cli-table) 6 | [![License](https://img.shields.io/crates/l/cli-table)](https://github.com/devashishdxt/cli-table/blob/master/LICENSE-MIT) 7 | 8 | Rust crate for printing tables on command line. 9 | 10 | ## Usage 11 | 12 | Add `cli-table` in your `Cargo.toml`'s `dependencies` section 13 | 14 | ```toml 15 | [dependencies] 16 | cli-table = "0.5" 17 | ``` 18 | 19 | ### Simple usage 20 | 21 | ```rust 22 | use cli_table::{format::Justify, print_stdout, Cell, Style, Table}; 23 | 24 | let table = vec![ 25 | vec!["Tom".cell(), 10.cell().justify(Justify::Right)], 26 | vec!["Jerry".cell(), 15.cell().justify(Justify::Right)], 27 | vec!["Scooby Doo".cell(), 20.cell().justify(Justify::Right)], 28 | ] 29 | .table() 30 | .title(vec![ 31 | "Name".cell().bold(true), 32 | "Age (in years)".cell().bold(true), 33 | ]) 34 | .bold(true); 35 | 36 | assert!(print_stdout(table).is_ok()); 37 | ``` 38 | 39 | Below is the output of the table we created just now: 40 | 41 | ```markdown 42 | +------------+----------------+ 43 | | Name | Age (in years) | <-- This row and all the borders/separators 44 | +------------+----------------+ will appear in bold 45 | | Tom | 10 | 46 | +------------+----------------+ 47 | | Jerry | 15 | 48 | +------------+----------------+ 49 | | Scooby Doo | 25 | 50 | +------------+----------------+ 51 | ``` 52 | 53 | ### `Display` trait implementation 54 | 55 | To get a `Display` trait implementation of `TableStruct`, use `display()` function on the struct to get an instance 56 | of `TableDisplay` which implements `Display` trait. 57 | 58 | ```rust 59 | use cli_table::{format::Justify, Cell, Style, Table}; 60 | 61 | let table = vec![ 62 | vec!["Tom".cell(), 10.cell().justify(Justify::Right)], 63 | vec!["Jerry".cell(), 15.cell().justify(Justify::Right)], 64 | vec!["Scooby Doo".cell(), 20.cell().justify(Justify::Right)], 65 | ] 66 | .table() 67 | .title(vec![ 68 | "Name".cell().bold(true), 69 | "Age (in years)".cell().bold(true), 70 | ]) 71 | .bold(true); 72 | 73 | let table_display = table.display().unwrap(); 74 | 75 | println!("{}", table_display); 76 | ``` 77 | 78 | Below is the output of the table we created just now: 79 | 80 | ```markdown 81 | +------------+----------------+ 82 | | Name | Age (in years) | <-- This row and all the borders/separators 83 | +------------+----------------+ will appear in bold 84 | | Tom | 10 | 85 | +------------+----------------+ 86 | | Jerry | 15 | 87 | +------------+----------------+ 88 | | Scooby Doo | 25 | 89 | +------------+----------------+ 90 | ``` 91 | 92 | ### Derive macro 93 | 94 | `#[derive(Table)]` can also be used to print a `Vec` or slice of `struct`s as table. 95 | 96 | ```rust 97 | use cli_table::{format::Justify, print_stdout, Table, WithTitle}; 98 | 99 | #[derive(Table)] 100 | struct User { 101 | #[table(title = "ID", justify = "Justify::Right")] 102 | id: u64, 103 | #[table(title = "First Name")] 104 | first_name: &'static str, 105 | #[table(title = "Last Name")] 106 | last_name: &'static str, 107 | } 108 | 109 | let users = vec![ 110 | User { 111 | id: 1, 112 | first_name: "Scooby", 113 | last_name: "Doo", 114 | }, 115 | User { 116 | id: 2, 117 | first_name: "John", 118 | last_name: "Cena", 119 | }, 120 | ]; 121 | 122 | assert!(print_stdout(users.with_title()).is_ok()); 123 | ``` 124 | 125 | Below is the output of the table we created using derive macro: 126 | 127 | ```markdown 128 | +----+------------+-----------+ 129 | | ID | First Name | Last Name | <-- This row will appear in bold 130 | +----+------------+-----------+ 131 | | 1 | Scooby | Doo | 132 | +----+------------+-----------+ 133 | | 2 | John | Cena | 134 | +----+------------+-----------+ 135 | ``` 136 | 137 | #### Field attributes 138 | 139 | - `title` | `name`: Used to specify title of a column. Usage: `#[table(title = "Title")]` 140 | - `justify`: Used to horizontally justify the contents of a column. Usage: `#[table(justify = "Justify::Right")]` 141 | - `align`: Used to vertically align the contents of a column. Usage: `#[table(align = "Align::Top")]` 142 | - `color`: Used to specify color of contents of a column. Usage: `#[table(color = "Color::Red")]` 143 | - `bold`: Used to specify boldness of contents of a column. Usage: `#[table(bold)]` 144 | - `order`: Used to order columns in a table while printing. Usage: `#[table(order = )]`. Here, columns will 145 | be sorted based on their order. For e.g., column with `order = 0` will be displayed on the left followed by 146 | column with `order = 1` and so on. 147 | - `display_fn`: Used to print types which do not implement `Display` trait. Usage `#[table(display_fn = "")]`. 148 | Signature of provided function should be `fn (value: &) -> impl Display`. 149 | - `customize_fn`: Used to customize style of a cell. Usage `#[table(customize_fn = "")]`. Signature of 150 | provided function should be `fn (cell: CellStruct, value: &) -> CellStruct`. This attribute can 151 | be used when you want to change the formatting/style of a cell based on its contents. Note that this will 152 | overwrite all the style settings done by other attributes. 153 | - `skip`: Used to skip a field from table. Usage: `#[table(skip)]` 154 | 155 | For more information on configurations available on derive macro, go to `cli-table/examples/struct.rs`. 156 | 157 | ### CSV 158 | 159 | This crate also integrates with [`csv`](https://crates.io/crates/csv) crate. On enabling `"csv"` feature, you can 160 | use `TryFrom<&mut Reader> for TableStruct` trait implementation to convert `csv::Reader` to `TableStruct`. 161 | 162 | For more information on handling CSV values, go to `cli-table/examples/csv.rs`. 163 | 164 | ## Styling 165 | 166 | Style of a table/cell can be modified by calling functions of [`Style`] trait. It is implementated by both 167 | [`TableStruct`] and [`CellStruct`]. 168 | 169 | For individually formatting each cell of a table, `justify`, `align` and `padding` functions can be used from 170 | `CellStruct`. 171 | 172 | In addition to this, borders and separators of a table can be customized by calling `border` and `separator` 173 | functions in `TableStruct`. For example, to create a borderless table: 174 | 175 | ```rust 176 | use cli_table::{Cell, Table, TableStruct, format::{Justify, Border}, print_stdout}; 177 | 178 | fn get_table() -> TableStruct { 179 | vec![ 180 | vec!["Tom".cell(), 10.cell().justify(Justify::Right)], 181 | vec!["Jerry".cell(), 15.cell().justify(Justify::Right)], 182 | vec!["Scooby Doo".cell(), 20.cell().justify(Justify::Right)], 183 | ] 184 | .table() 185 | } 186 | 187 | let table = get_table().border(Border::builder().build()); // Attaches an empty border to the table 188 | assert!(print_stdout(table).is_ok()); 189 | ``` 190 | 191 | ## Features 192 | 193 | - `derive`: Enables derive macro for creating tables using structs. **Enabled** by default. 194 | - `csv`: Enables support for printing tables using [`csv`](https://crates.io/crates/csv). **Enabled** by default. 195 | 196 | ## License 197 | 198 | Licensed under either of 199 | 200 | - Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE)) 201 | - MIT license ([LICENSE-MIT](LICENSE-MIT)) 202 | 203 | at your option. 204 | 205 | ## Contribution 206 | 207 | Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as 208 | defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. 209 | -------------------------------------------------------------------------------- /cli-table/README.tpl: -------------------------------------------------------------------------------- 1 | # {{crate}} 2 | 3 | [![Continuous Integration](https://github.com/devashishdxt/cli-table/workflows/Continuous%20Integration/badge.svg)](https://github.com/devashishdxt/cli-table/actions?query=workflow%3A%22Continuous+Integration%22) 4 | [![Crates.io](https://img.shields.io/crates/v/cli-table)](https://crates.io/crates/cli-table) 5 | [![Documentation](https://docs.rs/cli-table/badge.svg)](https://docs.rs/cli-table) 6 | [![License](https://img.shields.io/crates/l/cli-table)](https://github.com/devashishdxt/cli-table/blob/master/LICENSE-MIT) 7 | 8 | {{readme}} 9 | 10 | ## License 11 | 12 | Licensed under either of 13 | 14 | - Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE)) 15 | - MIT license ([LICENSE-MIT](LICENSE-MIT)) 16 | 17 | at your option. 18 | 19 | ## Contribution 20 | 21 | Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as 22 | defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. -------------------------------------------------------------------------------- /cli-table/examples/csv.rs: -------------------------------------------------------------------------------- 1 | use std::{convert::TryFrom, io::Result}; 2 | 3 | use cli_table::{TableStruct, print_stdout}; 4 | use csv::ReaderBuilder; 5 | 6 | fn main() -> Result<()> { 7 | let data = "\ 8 | city,country,pop 9 | Boston,United States,4628910 10 | Concord,United States,42695 11 | "; 12 | 13 | let mut reader = ReaderBuilder::new().from_reader(data.as_bytes()); 14 | let table = TableStruct::try_from(&mut reader).unwrap(); 15 | 16 | print_stdout(table) 17 | } 18 | -------------------------------------------------------------------------------- /cli-table/examples/nested.rs: -------------------------------------------------------------------------------- 1 | use std::io::Result; 2 | 3 | use cli_table::{Cell, Style, Table, format::Justify}; 4 | 5 | fn main() -> Result<()> { 6 | let nested_table = vec![vec![20.cell()]].table(); 7 | 8 | let table = vec![ 9 | vec!["Tom".cell(), 10.cell().justify(Justify::Right)], 10 | vec!["Jerry".cell(), 15.cell().justify(Justify::Right)], 11 | vec!["Scooby Doo".cell(), 20.cell().justify(Justify::Right)], 12 | vec![ 13 | "Nested".cell(), 14 | nested_table.display()?.cell().justify(Justify::Right), 15 | ], 16 | ] 17 | .table() 18 | .title(vec![ 19 | "Name".cell().bold(true), 20 | "Age (in years)".cell().bold(true), 21 | ]) 22 | .bold(true); 23 | 24 | println!("{}", table.display()?); 25 | 26 | Ok(()) 27 | } 28 | -------------------------------------------------------------------------------- /cli-table/examples/simple.rs: -------------------------------------------------------------------------------- 1 | use std::io::Result; 2 | 3 | use cli_table::{Cell, Style, Table, format::Justify, print_stdout}; 4 | 5 | fn main() -> Result<()> { 6 | let table = vec![ 7 | vec!["Tom".cell(), 10.cell().justify(Justify::Right)], 8 | vec!["Jerry".cell(), 15.cell().justify(Justify::Right)], 9 | vec!["Scooby Doo".cell(), 20.cell().justify(Justify::Right)], 10 | ] 11 | .table() 12 | .title(vec![ 13 | "Name".cell().bold(true), 14 | "Age (in years)".cell().bold(true), 15 | ]) 16 | .bold(true); 17 | 18 | print_stdout(table) 19 | } 20 | -------------------------------------------------------------------------------- /cli-table/examples/struct.rs: -------------------------------------------------------------------------------- 1 | use std::io::Result; 2 | 3 | use cli_table::{ 4 | Color, Table, WithTitle, 5 | format::{Align, Justify}, 6 | print_stdout, 7 | }; 8 | 9 | #[derive(Debug, Table)] 10 | struct User { 11 | #[table( 12 | title = "ID", 13 | justify = "Justify::Right", 14 | align = "Align::Top", 15 | color = "Color::Green", 16 | bold 17 | )] 18 | id: u64, 19 | #[table(title = "First Name")] 20 | first_name: &'static str, 21 | #[table(title = "Last Name")] 22 | last_name: String, 23 | } 24 | 25 | fn main() -> Result<()> { 26 | let users = vec![ 27 | User { 28 | id: 1, 29 | first_name: "Scooby", 30 | last_name: "Doo".to_string(), 31 | }, 32 | User { 33 | id: 2, 34 | first_name: "John", 35 | last_name: "Cena".to_string(), 36 | }, 37 | ]; 38 | 39 | print_stdout(users.with_title()) 40 | } 41 | -------------------------------------------------------------------------------- /cli-table/examples/tuple_struct.rs: -------------------------------------------------------------------------------- 1 | use std::io::Result; 2 | 3 | use cli_table::{ 4 | Table, WithTitle, 5 | format::{HorizontalLine, Justify::Right, Separator}, 6 | print_stdout, 7 | }; 8 | 9 | #[derive(Debug, Table)] 10 | struct User( 11 | #[table(title = "ID", justify = "Right")] u64, 12 | #[table(title = "First Name")] &'static str, 13 | #[table(title = "Last Name")] &'static str, 14 | ); 15 | 16 | fn main() -> Result<()> { 17 | let users = vec![ 18 | User(1, "Scooby", "Doo"), 19 | User(2, "John", "Cena"), 20 | User(3, "Sherlock", "Holmes"), 21 | ]; 22 | let table = users.with_title().separator( 23 | Separator::builder() 24 | .title(Some(HorizontalLine::new('+', '+', '+', '='))) 25 | .row(Some(Default::default())) 26 | .column(Some(Default::default())) 27 | .build(), 28 | ); 29 | print_stdout(table) 30 | } 31 | -------------------------------------------------------------------------------- /cli-table/src/buffers.rs: -------------------------------------------------------------------------------- 1 | use std::io::{Result, Write}; 2 | 3 | use termcolor::{Buffer, BufferWriter, ColorSpec, WriteColor}; 4 | 5 | pub struct Buffers<'a> { 6 | pub writer: &'a BufferWriter, 7 | buffers: Vec, 8 | current_buffer: Option, 9 | } 10 | 11 | impl<'a> Buffers<'a> { 12 | pub fn new(writer: &'a BufferWriter) -> Self { 13 | Buffers { 14 | writer, 15 | buffers: Vec::new(), 16 | current_buffer: None, 17 | } 18 | } 19 | 20 | pub fn push(&mut self, buffer: Buffer) -> Result<()> { 21 | if let Some(mut current_buffer) = self.current_buffer.take() { 22 | current_buffer.reset()?; 23 | self.buffers.push(current_buffer); 24 | } 25 | 26 | self.buffers.push(buffer); 27 | 28 | Ok(()) 29 | } 30 | 31 | pub fn append(&mut self, other: &mut Vec) -> Result<()> { 32 | if let Some(mut current_buffer) = self.current_buffer.take() { 33 | current_buffer.reset()?; 34 | self.buffers.push(current_buffer); 35 | } 36 | 37 | self.buffers.append(other); 38 | 39 | Ok(()) 40 | } 41 | 42 | pub fn into_vec(self) -> Result> { 43 | let mut buffers = self.buffers; 44 | 45 | if let Some(mut buffer) = self.current_buffer { 46 | buffer.reset()?; 47 | buffers.push(buffer); 48 | } 49 | 50 | Ok(buffers) 51 | } 52 | } 53 | 54 | impl Write for Buffers<'_> { 55 | fn write(&mut self, buf: &[u8]) -> Result { 56 | if let Some(ref mut current_buffer) = self.current_buffer { 57 | current_buffer.write(buf) 58 | } else { 59 | let mut new_buffer = self.writer.buffer(); 60 | let num_bytes = new_buffer.write(buf)?; 61 | self.current_buffer = Some(new_buffer); 62 | 63 | Ok(num_bytes) 64 | } 65 | } 66 | 67 | fn flush(&mut self) -> std::io::Result<()> { 68 | if let Some(ref mut current_buffer) = self.current_buffer { 69 | current_buffer.flush() 70 | } else { 71 | Ok(()) 72 | } 73 | } 74 | } 75 | 76 | impl WriteColor for Buffers<'_> { 77 | fn supports_color(&self) -> bool { 78 | match self.current_buffer { 79 | Some(ref buffer) => buffer.supports_color(), 80 | None => self.writer.buffer().supports_color(), 81 | } 82 | } 83 | 84 | fn set_color(&mut self, color: &ColorSpec) -> Result<()> { 85 | if let Some(ref mut current_buffer) = self.current_buffer { 86 | current_buffer.set_color(color) 87 | } else { 88 | let mut new_buffer = self.writer.buffer(); 89 | new_buffer.set_color(color)?; 90 | self.current_buffer = Some(new_buffer); 91 | 92 | Ok(()) 93 | } 94 | } 95 | 96 | fn reset(&mut self) -> Result<()> { 97 | if let Some(ref mut current_buffer) = self.current_buffer { 98 | current_buffer.reset() 99 | } else { 100 | Ok(()) 101 | } 102 | } 103 | 104 | fn is_synchronous(&self) -> bool { 105 | if let Some(ref buffer) = self.current_buffer { 106 | buffer.is_synchronous() 107 | } else { 108 | self.writer.buffer().is_synchronous() 109 | } 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /cli-table/src/cell.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | fmt::Display, 3 | io::{Result, Write}, 4 | }; 5 | 6 | use termcolor::{Buffer, BufferWriter, Color, ColorSpec, WriteColor}; 7 | 8 | use crate::{ 9 | row::Dimension as RowDimension, 10 | style::{Style, StyleStruct}, 11 | utils::display_width, 12 | }; 13 | 14 | /// Concrete cell of a table 15 | pub struct CellStruct { 16 | data: Vec, 17 | format: CellFormat, 18 | style: StyleStruct, 19 | } 20 | 21 | impl CellStruct { 22 | /// Used to horizontally justify contents of a cell 23 | pub fn justify(mut self, justify: Justify) -> CellStruct { 24 | self.format.justify = justify; 25 | self 26 | } 27 | 28 | /// Used to vertically align the contents of a cell 29 | pub fn align(mut self, align: Align) -> CellStruct { 30 | self.format.align = align; 31 | self 32 | } 33 | 34 | /// Used to add padding to the contents of a cell 35 | pub fn padding(mut self, padding: Padding) -> CellStruct { 36 | self.format.padding = padding; 37 | self 38 | } 39 | 40 | fn color_spec(&self) -> ColorSpec { 41 | self.style.color_spec() 42 | } 43 | 44 | /// Returns the minimum dimensions required by the cell 45 | pub(crate) fn required_dimension(&self) -> Dimension { 46 | let height = self.data.len() + self.format.padding.top + self.format.padding.bottom; 47 | let width = self 48 | .data 49 | .iter() 50 | .map(|x| display_width(x)) 51 | .max() 52 | .unwrap_or_default() 53 | + self.format.padding.left 54 | + self.format.padding.right; 55 | 56 | Dimension { width, height } 57 | } 58 | 59 | pub(crate) fn buffers( 60 | &self, 61 | writer: &BufferWriter, 62 | available_dimension: Dimension, 63 | ) -> Result> { 64 | let required_dimension = self.required_dimension(); 65 | let mut buffers = Vec::with_capacity(available_dimension.height); 66 | 67 | assert!( 68 | available_dimension >= required_dimension, 69 | "Available dimensions for a cell are smaller than required. Please create an issue in https://github.com/devashishdxt/cli-table" 70 | ); 71 | 72 | let top_blank_lines = self.top_blank_lines(available_dimension, required_dimension); 73 | 74 | for _ in 0..top_blank_lines { 75 | buffers.push(self.buffer(writer, available_dimension, required_dimension, "")?); 76 | } 77 | 78 | for line in self.data.clone().iter() { 79 | buffers.push(self.buffer(writer, available_dimension, required_dimension, line)?); 80 | } 81 | 82 | for _ in 0..(available_dimension.height - (self.data.len() + top_blank_lines)) { 83 | buffers.push(self.buffer(writer, available_dimension, required_dimension, "")?); 84 | } 85 | 86 | Ok(buffers) 87 | } 88 | 89 | fn buffer( 90 | &self, 91 | writer: &BufferWriter, 92 | available_dimension: Dimension, 93 | required_dimension: Dimension, 94 | data: &str, 95 | ) -> Result { 96 | let empty_chars = match self.format.justify { 97 | Justify::Left => self.format.padding.left, 98 | Justify::Right => { 99 | (available_dimension.width - required_dimension.width) + self.format.padding.left 100 | } 101 | Justify::Center => { 102 | ((available_dimension.width - required_dimension.width) / 2) 103 | + self.format.padding.left 104 | } 105 | }; 106 | 107 | let mut buffer = writer.buffer(); 108 | buffer.set_color(&self.color_spec())?; 109 | 110 | for _ in 0..empty_chars { 111 | write!(buffer, " ")?; 112 | } 113 | 114 | write!(buffer, "{}", data)?; 115 | 116 | for _ in 0..(available_dimension.width - (display_width(data) + empty_chars)) { 117 | write!(buffer, " ")?; 118 | } 119 | 120 | Ok(buffer) 121 | } 122 | 123 | fn top_blank_lines( 124 | &self, 125 | available_dimension: Dimension, 126 | required_dimension: Dimension, 127 | ) -> usize { 128 | match self.format.align { 129 | Align::Top => self.format.padding.top, 130 | Align::Bottom => { 131 | (available_dimension.height - required_dimension.height) + self.format.padding.top 132 | } 133 | Align::Center => { 134 | ((available_dimension.height - required_dimension.height) / 2) 135 | + self.format.padding.top 136 | } 137 | } 138 | } 139 | } 140 | 141 | /// Trait to convert raw types into cells 142 | pub trait Cell { 143 | /// Converts raw type to cell of a table 144 | fn cell(self) -> CellStruct; 145 | } 146 | 147 | impl Cell for T 148 | where 149 | T: Display, 150 | { 151 | fn cell(self) -> CellStruct { 152 | let data = self.to_string().lines().map(ToString::to_string).collect(); 153 | 154 | CellStruct { 155 | data, 156 | format: Default::default(), 157 | style: Default::default(), 158 | } 159 | } 160 | } 161 | 162 | impl Cell for CellStruct { 163 | fn cell(self) -> CellStruct { 164 | self 165 | } 166 | } 167 | 168 | impl Style for CellStruct { 169 | fn foreground_color(mut self, foreground_color: Option) -> Self { 170 | self.style = self.style.foreground_color(foreground_color); 171 | self 172 | } 173 | 174 | fn background_color(mut self, background_color: Option) -> Self { 175 | self.style = self.style.background_color(background_color); 176 | self 177 | } 178 | 179 | fn bold(mut self, bold: bool) -> Self { 180 | self.style = self.style.bold(bold); 181 | self 182 | } 183 | 184 | fn underline(mut self, underline: bool) -> Self { 185 | self.style = self.style.underline(underline); 186 | self 187 | } 188 | 189 | fn italic(mut self, italic: bool) -> Self { 190 | self.style = self.style.italic(italic); 191 | self 192 | } 193 | 194 | fn intense(mut self, intense: bool) -> Self { 195 | self.style = self.style.intense(intense); 196 | self 197 | } 198 | 199 | fn dimmed(mut self, dimmed: bool) -> Self { 200 | self.style = self.style.dimmed(dimmed); 201 | self 202 | } 203 | } 204 | 205 | /// Struct for configuring a cell's format 206 | #[derive(Debug, Clone, Copy, Default)] 207 | struct CellFormat { 208 | justify: Justify, 209 | align: Align, 210 | padding: Padding, 211 | } 212 | 213 | /// Used to horizontally justify contents of a cell 214 | #[derive(Debug, Clone, Copy)] 215 | pub enum Justify { 216 | /// Justifies contents to left 217 | Left, 218 | /// Justifies contents to right 219 | Right, 220 | /// Justifies contents to center 221 | Center, 222 | } 223 | 224 | impl Default for Justify { 225 | fn default() -> Self { 226 | Self::Left 227 | } 228 | } 229 | 230 | /// Used to vertically align contents of a cell 231 | #[derive(Debug, Clone, Copy)] 232 | pub enum Align { 233 | /// Aligns contents to top 234 | Top, 235 | /// Aligns contents to bottom 236 | Bottom, 237 | /// Aligns contents to center 238 | Center, 239 | } 240 | 241 | impl Default for Align { 242 | fn default() -> Self { 243 | Self::Top 244 | } 245 | } 246 | 247 | /// Used to add padding to the contents of a cell 248 | #[derive(Debug, Clone, Copy, Default)] 249 | pub struct Padding { 250 | /// Left padding 251 | pub(crate) left: usize, 252 | /// Right padding 253 | pub(crate) right: usize, 254 | /// Top padding 255 | pub(crate) top: usize, 256 | /// Bottom padding 257 | pub(crate) bottom: usize, 258 | } 259 | 260 | impl Padding { 261 | /// Creates a new builder for padding 262 | pub fn builder() -> PaddingBuilder { 263 | Default::default() 264 | } 265 | } 266 | 267 | /// Builder for padding 268 | #[derive(Debug, Default)] 269 | pub struct PaddingBuilder(Padding); 270 | 271 | impl PaddingBuilder { 272 | /// Sets left padding of a cell 273 | pub fn left(mut self, left_padding: usize) -> Self { 274 | self.0.left = left_padding; 275 | self 276 | } 277 | 278 | /// Sets right padding of a cell 279 | pub fn right(mut self, right_padding: usize) -> Self { 280 | self.0.right = right_padding; 281 | self 282 | } 283 | 284 | /// Sets top padding of a cell 285 | pub fn top(mut self, top_padding: usize) -> Self { 286 | self.0.top = top_padding; 287 | self 288 | } 289 | 290 | /// Sets bottom padding of a cell 291 | pub fn bottom(mut self, bottom_padding: usize) -> Self { 292 | self.0.bottom = bottom_padding; 293 | self 294 | } 295 | 296 | /// Build padding 297 | pub fn build(self) -> Padding { 298 | self.0 299 | } 300 | } 301 | 302 | /// Dimensions of a cell 303 | #[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq)] 304 | pub(crate) struct Dimension { 305 | /// Width of a cell 306 | pub(crate) width: usize, 307 | /// Height of a cell 308 | pub(crate) height: usize, 309 | } 310 | 311 | impl From for Vec { 312 | fn from(row_dimension: RowDimension) -> Self { 313 | let height = row_dimension.height; 314 | 315 | row_dimension 316 | .widths 317 | .into_iter() 318 | .map(|width| Dimension { width, height }) 319 | .collect() 320 | } 321 | } 322 | 323 | #[cfg(test)] 324 | mod tests { 325 | use super::*; 326 | 327 | #[test] 328 | fn test_into_cell() { 329 | let cell = "Hello".cell(); 330 | assert_eq!(1, cell.data.len()); 331 | assert_eq!("Hello", cell.data[0]); 332 | } 333 | } 334 | -------------------------------------------------------------------------------- /cli-table/src/csv.rs: -------------------------------------------------------------------------------- 1 | use std::{convert::TryFrom, io::Read}; 2 | 3 | use csv::{Error, Reader, StringRecord}; 4 | 5 | use crate::{Cell, RowStruct, Style, Table, TableStruct}; 6 | 7 | impl TryFrom<&mut Reader> for TableStruct { 8 | type Error = Error; 9 | 10 | fn try_from(reader: &mut Reader) -> Result { 11 | let records = reader.records(); 12 | let rows = records 13 | .map(|record| Ok(row(&record?))) 14 | .collect::, Error>>()?; 15 | 16 | let table = if reader.has_headers() { 17 | let headers = reader.headers()?; 18 | let title: RowStruct = title(headers); 19 | 20 | rows.table().title(title) 21 | } else { 22 | rows.table() 23 | }; 24 | 25 | Ok(table) 26 | } 27 | } 28 | 29 | fn row(record: &StringRecord) -> RowStruct { 30 | RowStruct { 31 | cells: record.iter().map(Cell::cell).collect(), 32 | } 33 | } 34 | 35 | fn title(record: &StringRecord) -> RowStruct { 36 | RowStruct { 37 | cells: record.iter().map(|cell| cell.cell().bold(true)).collect(), 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /cli-table/src/dimension.rs: -------------------------------------------------------------------------------- 1 | /// Dimensions of a cell 2 | #[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq)] 3 | pub struct CellDimension { 4 | /// Width of a cell 5 | pub width: usize, 6 | /// Height of a cell 7 | pub height: usize, 8 | } 9 | 10 | /// Dimensions of a row 11 | #[derive(Debug, Default, Clone, Eq, PartialEq)] 12 | pub struct RowDimension { 13 | /// Widths of each cell of row 14 | pub widths: Vec, 15 | /// Height of row 16 | pub height: usize, 17 | } 18 | 19 | /// Dimensions of a table 20 | #[derive(Debug, Clone, Eq, PartialEq, Default)] 21 | pub struct TableDimension { 22 | /// Widths of each column of table 23 | pub widths: Vec, 24 | /// Height of each row of table 25 | pub heights: Vec, 26 | } 27 | 28 | impl From for Vec { 29 | fn from(row_dimension: RowDimension) -> Self { 30 | let height = row_dimension.height; 31 | 32 | row_dimension 33 | .widths 34 | .into_iter() 35 | .map(|width| CellDimension { width, height }) 36 | .collect() 37 | } 38 | } 39 | 40 | impl From for Vec { 41 | fn from(table_dimension: TableDimension) -> Self { 42 | let heights = table_dimension.heights; 43 | let widths = table_dimension.widths; 44 | 45 | heights 46 | .into_iter() 47 | .map(|height| RowDimension { 48 | widths: widths.clone(), 49 | height, 50 | }) 51 | .collect() 52 | } 53 | } 54 | 55 | /// Trait for calculating required dimensions for a type 56 | pub trait RequiredDimension { 57 | /// Type of dimension for given type 58 | type Dimension; 59 | 60 | /// Returns the required dimension 61 | fn required_dimension(&self) -> Option<&Self::Dimension>; 62 | 63 | /// Calculates the required dimension for a type and stores it in the type for future use 64 | fn set_required_dimension(&mut self); 65 | } 66 | 67 | pub trait AvailableDimension: RequiredDimension { 68 | fn available_dimension(&self) -> Option<&::Dimension>; 69 | 70 | fn set_available_dimension( 71 | &mut self, 72 | available_dimension: ::Dimension, 73 | ); 74 | } 75 | -------------------------------------------------------------------------------- /cli-table/src/display.rs: -------------------------------------------------------------------------------- 1 | use std::fmt; 2 | 3 | /// A table which implements the `Display` trait 4 | pub struct TableDisplay { 5 | inner: String, 6 | } 7 | 8 | impl TableDisplay { 9 | pub(crate) fn new(inner: Vec) -> Self { 10 | TableDisplay { 11 | inner: String::from_utf8(inner).expect("valid utf8 string"), 12 | } 13 | } 14 | } 15 | 16 | impl fmt::Display for TableDisplay { 17 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 18 | write!(f, "{}", self.inner.trim()) 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /cli-table/src/format.rs: -------------------------------------------------------------------------------- 1 | //! Utilities for formatting of a table 2 | pub use crate::{ 3 | cell::{Align, Justify, Padding, PaddingBuilder}, 4 | table::{Border, BorderBuilder, HorizontalLine, Separator, SeparatorBuilder, VerticalLine}, 5 | }; 6 | -------------------------------------------------------------------------------- /cli-table/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![forbid(unsafe_code)] 2 | #![cfg_attr(not(feature = "doc"), forbid(unstable_features))] 3 | #![deny(missing_docs)] 4 | #![cfg_attr(feature = "doc", feature(doc_cfg))] 5 | //! Rust crate for printing tables on command line. 6 | //! 7 | //! # Usage 8 | //! 9 | //! Add `cli-table` in your `Cargo.toml`'s `dependencies` section 10 | //! 11 | //! ```toml 12 | //! [dependencies] 13 | //! cli-table = "0.5" 14 | //! ``` 15 | //! 16 | //! ## Simple usage 17 | //! 18 | //! ```rust 19 | //! use cli_table::{format::Justify, print_stdout, Cell, Style, Table}; 20 | //! 21 | //! let table = vec![ 22 | //! vec!["Tom".cell(), 10.cell().justify(Justify::Right)], 23 | //! vec!["Jerry".cell(), 15.cell().justify(Justify::Right)], 24 | //! vec!["Scooby Doo".cell(), 20.cell().justify(Justify::Right)], 25 | //! ] 26 | //! .table() 27 | //! .title(vec![ 28 | //! "Name".cell().bold(true), 29 | //! "Age (in years)".cell().bold(true), 30 | //! ]) 31 | //! .bold(true); 32 | //! 33 | //! assert!(print_stdout(table).is_ok()); 34 | //! ``` 35 | //! 36 | //! Below is the output of the table we created just now: 37 | //! 38 | //! ```markdown 39 | //! +------------+----------------+ 40 | //! | Name | Age (in years) | <-- This row and all the borders/separators 41 | //! +------------+----------------+ will appear in bold 42 | //! | Tom | 10 | 43 | //! +------------+----------------+ 44 | //! | Jerry | 15 | 45 | //! +------------+----------------+ 46 | //! | Scooby Doo | 25 | 47 | //! +------------+----------------+ 48 | //! ``` 49 | //! 50 | //! ## `Display` trait implementation 51 | //! 52 | //! To get a `Display` trait implementation of `TableStruct`, use `display()` function on the struct to get an instance 53 | //! of `TableDisplay` which implements `Display` trait. 54 | //! 55 | //! ```rust 56 | //! use cli_table::{format::Justify, Cell, Style, Table}; 57 | //! 58 | //! let table = vec![ 59 | //! vec!["Tom".cell(), 10.cell().justify(Justify::Right)], 60 | //! vec!["Jerry".cell(), 15.cell().justify(Justify::Right)], 61 | //! vec!["Scooby Doo".cell(), 20.cell().justify(Justify::Right)], 62 | //! ] 63 | //! .table() 64 | //! .title(vec![ 65 | //! "Name".cell().bold(true), 66 | //! "Age (in years)".cell().bold(true), 67 | //! ]) 68 | //! .bold(true); 69 | //! 70 | //! let table_display = table.display().unwrap(); 71 | //! 72 | //! println!("{}", table_display); 73 | //! ``` 74 | //! 75 | //! Below is the output of the table we created just now: 76 | //! 77 | //! ```markdown 78 | //! +------------+----------------+ 79 | //! | Name | Age (in years) | <-- This row and all the borders/separators 80 | //! +------------+----------------+ will appear in bold 81 | //! | Tom | 10 | 82 | //! +------------+----------------+ 83 | //! | Jerry | 15 | 84 | //! +------------+----------------+ 85 | //! | Scooby Doo | 25 | 86 | //! +------------+----------------+ 87 | //! ``` 88 | //! 89 | //! ## Derive macro 90 | //! 91 | //! `#[derive(Table)]` can also be used to print a `Vec` or slice of `struct`s as table. 92 | //! 93 | //! ```rust 94 | //! use cli_table::{format::Justify, print_stdout, Table, WithTitle}; 95 | //! 96 | //! #[derive(Table)] 97 | //! struct User { 98 | //! #[table(title = "ID", justify = "Justify::Right")] 99 | //! id: u64, 100 | //! #[table(title = "First Name")] 101 | //! first_name: &'static str, 102 | //! #[table(title = "Last Name")] 103 | //! last_name: &'static str, 104 | //! } 105 | //! 106 | //! let users = vec![ 107 | //! User { 108 | //! id: 1, 109 | //! first_name: "Scooby", 110 | //! last_name: "Doo", 111 | //! }, 112 | //! User { 113 | //! id: 2, 114 | //! first_name: "John", 115 | //! last_name: "Cena", 116 | //! }, 117 | //! ]; 118 | //! 119 | //! assert!(print_stdout(users.with_title()).is_ok()); 120 | //! ``` 121 | //! 122 | //! Below is the output of the table we created using derive macro: 123 | //! 124 | //! ```markdown 125 | //! +----+------------+-----------+ 126 | //! | ID | First Name | Last Name | <-- This row will appear in bold 127 | //! +----+------------+-----------+ 128 | //! | 1 | Scooby | Doo | 129 | //! +----+------------+-----------+ 130 | //! | 2 | John | Cena | 131 | //! +----+------------+-----------+ 132 | //! ``` 133 | //! 134 | //! ### Field attributes 135 | //! 136 | //! - `title` | `name`: Used to specify title of a column. Usage: `#[table(title = "Title")]` 137 | //! - `justify`: Used to horizontally justify the contents of a column. Usage: `#[table(justify = "Justify::Right")]` 138 | //! - `align`: Used to vertically align the contents of a column. Usage: `#[table(align = "Align::Top")]` 139 | //! - `color`: Used to specify color of contents of a column. Usage: `#[table(color = "Color::Red")]` 140 | //! - `bold`: Used to specify boldness of contents of a column. Usage: `#[table(bold)]` 141 | //! - `order`: Used to order columns in a table while printing. Usage: `#[table(order = )]`. Here, columns will 142 | //! be sorted based on their order. For e.g., column with `order = 0` will be displayed on the left followed by 143 | //! column with `order = 1` and so on. 144 | //! - `display_fn`: Used to print types which do not implement `Display` trait. Usage `#[table(display_fn = "")]`. 145 | //! Signature of provided function should be `fn (value: &) -> impl Display`. 146 | //! - `customize_fn`: Used to customize style of a cell. Usage `#[table(customize_fn = "")]`. Signature of 147 | //! provided function should be `fn (cell: CellStruct, value: &) -> CellStruct`. This attribute can 148 | //! be used when you want to change the formatting/style of a cell based on its contents. Note that this will 149 | //! overwrite all the style settings done by other attributes. 150 | //! - `skip`: Used to skip a field from table. Usage: `#[table(skip)]` 151 | //! 152 | //! For more information on configurations available on derive macro, go to `cli-table/examples/struct.rs`. 153 | //! 154 | //! ## CSV 155 | //! 156 | //! This crate also integrates with [`csv`](https://crates.io/crates/csv) crate. On enabling `"csv"` feature, you can 157 | //! use `TryFrom<&mut Reader> for TableStruct` trait implementation to convert `csv::Reader` to `TableStruct`. 158 | //! 159 | //! For more information on handling CSV values, go to `cli-table/examples/csv.rs`. 160 | //! 161 | //! # Styling 162 | //! 163 | //! Style of a table/cell can be modified by calling functions of [`Style`] trait. It is implementated by both 164 | //! [`TableStruct`] and [`CellStruct`]. 165 | //! 166 | //! For individually formatting each cell of a table, `justify`, `align` and `padding` functions can be used from 167 | //! `CellStruct`. 168 | //! 169 | //! In addition to this, borders and separators of a table can be customized by calling `border` and `separator` 170 | //! functions in `TableStruct`. For example, to create a borderless table: 171 | //! 172 | //! ```rust 173 | //! use cli_table::{Cell, Table, TableStruct, format::{Justify, Border}, print_stdout}; 174 | //! 175 | //! fn get_table() -> TableStruct { 176 | //! vec![ 177 | //! vec!["Tom".cell(), 10.cell().justify(Justify::Right)], 178 | //! vec!["Jerry".cell(), 15.cell().justify(Justify::Right)], 179 | //! vec!["Scooby Doo".cell(), 20.cell().justify(Justify::Right)], 180 | //! ] 181 | //! .table() 182 | //! } 183 | //! 184 | //! let table = get_table().border(Border::builder().build()); // Attaches an empty border to the table 185 | //! assert!(print_stdout(table).is_ok()); 186 | //! ``` 187 | //! 188 | //! # Features 189 | //! 190 | //! - `derive`: Enables derive macro for creating tables using structs. **Enabled** by default. 191 | //! - `csv`: Enables support for printing tables using [`csv`](https://crates.io/crates/csv). **Enabled** by default. 192 | mod buffers; 193 | mod cell; 194 | #[cfg(feature = "csv")] 195 | mod csv; 196 | mod display; 197 | mod row; 198 | mod style; 199 | mod table; 200 | #[cfg(any(feature = "title", feature = "derive"))] 201 | mod title; 202 | mod utils; 203 | 204 | pub mod format; 205 | 206 | pub use termcolor::{Color, ColorChoice}; 207 | 208 | #[cfg(feature = "derive")] 209 | #[cfg_attr(feature = "doc", doc(cfg(feature = "derive")))] 210 | pub use cli_table_derive::Table; 211 | 212 | pub use self::{ 213 | cell::{Cell, CellStruct}, 214 | display::TableDisplay, 215 | row::{Row, RowStruct}, 216 | style::Style, 217 | table::{Table, TableStruct}, 218 | }; 219 | 220 | #[cfg(any(feature = "title", feature = "derive"))] 221 | pub use self::title::{Title, WithTitle}; 222 | 223 | use std::io::Result; 224 | 225 | /// Prints a table to `stdout` 226 | pub fn print_stdout(table: T) -> Result<()> { 227 | table.table().print_stdout() 228 | } 229 | 230 | /// Prints a table to `stderr` 231 | pub fn print_stderr(table: T) -> Result<()> { 232 | table.table().print_stderr() 233 | } 234 | -------------------------------------------------------------------------------- /cli-table/src/row.rs: -------------------------------------------------------------------------------- 1 | use std::io::Result; 2 | 3 | use termcolor::{Buffer, BufferWriter, ColorSpec}; 4 | 5 | use crate::{ 6 | buffers::Buffers, 7 | cell::{Cell, CellStruct, Dimension as CellDimension}, 8 | table::{Dimension as TableDimension, TableFormat}, 9 | utils::{print_char, print_vertical_line, println, transpose}, 10 | }; 11 | 12 | /// Concrete row of a table 13 | pub struct RowStruct { 14 | pub(crate) cells: Vec, 15 | } 16 | 17 | impl RowStruct { 18 | pub(crate) fn required_dimension(&self) -> Dimension { 19 | let mut widths = Vec::with_capacity(self.cells.len()); 20 | let mut height = 0; 21 | 22 | for cell in self.cells.iter() { 23 | let cell_dimension = cell.required_dimension(); 24 | 25 | widths.push(cell_dimension.width); 26 | 27 | height = std::cmp::max(cell_dimension.height, height); 28 | } 29 | 30 | Dimension { widths, height } 31 | } 32 | 33 | pub(crate) fn buffers( 34 | &self, 35 | writer: &BufferWriter, 36 | available_dimension: Dimension, 37 | format: &TableFormat, 38 | color_spec: &ColorSpec, 39 | ) -> Result> { 40 | let available_cell_dimensions: Vec = available_dimension.into(); 41 | 42 | let cell_buffers = self 43 | .cells 44 | .iter() 45 | .zip(available_cell_dimensions.into_iter()) 46 | .map(|(cell, available_dimension)| cell.buffers(writer, available_dimension)) 47 | .collect::>>>()?; 48 | 49 | let cell_buffers = transpose(cell_buffers); 50 | 51 | let mut buffers = Buffers::new(writer); 52 | 53 | for line in cell_buffers { 54 | print_vertical_line(&mut buffers, format.border.left.as_ref(), color_spec)?; 55 | 56 | let mut line_buffers = line.into_iter().peekable(); 57 | 58 | while let Some(line_buffer) = line_buffers.next() { 59 | print_char(&mut buffers, ' ', color_spec)?; 60 | buffers.push(line_buffer)?; 61 | print_char(&mut buffers, ' ', color_spec)?; 62 | 63 | match line_buffers.peek() { 64 | Some(_) => print_vertical_line( 65 | &mut buffers, 66 | format.separator.column.as_ref(), 67 | color_spec, 68 | )?, 69 | None => { 70 | print_vertical_line(&mut buffers, format.border.right.as_ref(), color_spec)? 71 | } 72 | } 73 | } 74 | 75 | println(&mut buffers)?; 76 | } 77 | 78 | buffers.into_vec() 79 | } 80 | } 81 | 82 | /// Trait to convert raw types into rows 83 | pub trait Row { 84 | /// Converts raw type to rows of a table 85 | fn row(self) -> RowStruct; 86 | } 87 | 88 | impl Row for T 89 | where 90 | T: IntoIterator, 91 | C: Cell, 92 | { 93 | fn row(self) -> RowStruct { 94 | let cells = self.into_iter().map(|cell| cell.cell()).collect(); 95 | RowStruct { cells } 96 | } 97 | } 98 | 99 | impl Row for RowStruct { 100 | fn row(self) -> RowStruct { 101 | self 102 | } 103 | } 104 | 105 | /// Dimensions of a row 106 | #[derive(Debug, Default, Clone, Eq, PartialEq)] 107 | pub(crate) struct Dimension { 108 | /// Widths of each cell of row 109 | pub(crate) widths: Vec, 110 | /// Height of row 111 | pub(crate) height: usize, 112 | } 113 | 114 | impl From for Vec { 115 | fn from(table_dimension: TableDimension) -> Self { 116 | let heights = table_dimension.heights; 117 | let widths = table_dimension.widths; 118 | 119 | heights 120 | .into_iter() 121 | .map(|height| Dimension { 122 | widths: widths.clone(), 123 | height, 124 | }) 125 | .collect() 126 | } 127 | } 128 | 129 | #[cfg(test)] 130 | mod tests { 131 | use crate::style::Style; 132 | 133 | use super::*; 134 | 135 | #[test] 136 | fn test_into_row_with_style() { 137 | let row = vec!["Hello".cell().bold(true), "World".cell()].row(); 138 | assert_eq!(2, row.cells.len()); 139 | } 140 | 141 | #[test] 142 | fn test_into_row() { 143 | let row = &["Hello", "World"].row(); 144 | assert_eq!(2, row.cells.len()); 145 | } 146 | } 147 | -------------------------------------------------------------------------------- /cli-table/src/style.rs: -------------------------------------------------------------------------------- 1 | use termcolor::{Color, ColorSpec}; 2 | 3 | /// Trait for modifying style of table and cells 4 | pub trait Style { 5 | /// Used to set foreground color 6 | fn foreground_color(self, foreground_color: Option) -> Self; 7 | /// Used to set background color 8 | fn background_color(self, background_color: Option) -> Self; 9 | /// Used to set contents to be bold 10 | fn bold(self, bold: bool) -> Self; 11 | /// Used to set contents to be underlined 12 | fn underline(self, underline: bool) -> Self; 13 | /// Used to set contents to be italic 14 | fn italic(self, italic: bool) -> Self; 15 | /// Used to set high intensity version of a color specified 16 | fn intense(self, intense: bool) -> Self; 17 | /// Used to set contents to be dimmed 18 | fn dimmed(self, dimmed: bool) -> Self; 19 | } 20 | 21 | #[derive(Debug, Clone, Copy, Default)] 22 | pub(crate) struct StyleStruct { 23 | pub(crate) foreground_color: Option, 24 | pub(crate) background_color: Option, 25 | pub(crate) bold: bool, 26 | pub(crate) underline: bool, 27 | pub(crate) italic: bool, 28 | pub(crate) intense: bool, 29 | pub(crate) dimmed: bool, 30 | } 31 | 32 | impl StyleStruct { 33 | pub(crate) fn color_spec(&self) -> ColorSpec { 34 | let mut color_spec = ColorSpec::new(); 35 | 36 | color_spec.set_fg(self.foreground_color); 37 | color_spec.set_bg(self.background_color); 38 | color_spec.set_bold(self.bold); 39 | color_spec.set_underline(self.underline); 40 | color_spec.set_italic(self.italic); 41 | color_spec.set_intense(self.intense); 42 | color_spec.set_dimmed(self.dimmed); 43 | 44 | color_spec 45 | } 46 | } 47 | 48 | impl Style for StyleStruct { 49 | fn foreground_color(mut self, foreground_color: Option) -> Self { 50 | self.foreground_color = foreground_color; 51 | self 52 | } 53 | 54 | fn background_color(mut self, background_color: Option) -> Self { 55 | self.background_color = background_color; 56 | self 57 | } 58 | 59 | fn bold(mut self, bold: bool) -> Self { 60 | self.bold = bold; 61 | self 62 | } 63 | 64 | fn underline(mut self, underline: bool) -> Self { 65 | self.underline = underline; 66 | self 67 | } 68 | 69 | fn italic(mut self, italic: bool) -> Self { 70 | self.italic = italic; 71 | self 72 | } 73 | 74 | fn intense(mut self, intense: bool) -> Self { 75 | self.intense = intense; 76 | self 77 | } 78 | 79 | fn dimmed(mut self, dimmed: bool) -> Self { 80 | self.dimmed = dimmed; 81 | self 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /cli-table/src/table.rs: -------------------------------------------------------------------------------- 1 | use std::io::Result; 2 | 3 | use termcolor::{Buffer, BufferWriter, Color, ColorChoice, ColorSpec}; 4 | 5 | use crate::{ 6 | buffers::Buffers, 7 | display::TableDisplay, 8 | row::{Dimension as RowDimension, Row, RowStruct}, 9 | style::{Style, StyleStruct}, 10 | utils::*, 11 | }; 12 | 13 | /// Struct for building a table on command line 14 | pub struct TableStruct { 15 | /// Title row of the table 16 | title: Option, 17 | /// Rows in the table 18 | rows: Vec, 19 | /// Format of the table 20 | format: TableFormat, 21 | /// Style of the table 22 | style: StyleStruct, 23 | /// Color preferences for printing the table 24 | color_choice: ColorChoice, 25 | } 26 | 27 | impl TableStruct { 28 | /// Used to add a title row of a table 29 | pub fn title(mut self, title: T) -> Self { 30 | self.title = Some(title.row()); 31 | self 32 | } 33 | 34 | /// Used to set border of a table 35 | pub fn border(mut self, border: Border) -> Self { 36 | self.format.border = border; 37 | self 38 | } 39 | 40 | /// Used to set column/row separators of a table 41 | pub fn separator(mut self, separator: Separator) -> Self { 42 | self.format.separator = separator; 43 | self 44 | } 45 | 46 | /// Used to set the color preferences for printing the table 47 | pub fn color_choice(mut self, color_choice: ColorChoice) -> Self { 48 | self.color_choice = color_choice; 49 | self 50 | } 51 | 52 | /// Returns a struct which implements the `Display` trait 53 | pub fn display(&self) -> Result { 54 | let writer = BufferWriter::stdout(self.color_choice); 55 | let buffers = self.buffers(&writer)?; 56 | 57 | let mut output = Vec::new(); 58 | 59 | for buffer in buffers { 60 | output.append(&mut buffer.into_inner()); 61 | } 62 | 63 | Ok(TableDisplay::new(output)) 64 | } 65 | 66 | /// Prints current table to `stdout` 67 | pub(crate) fn print_stdout(&self) -> Result<()> { 68 | self.print_writer(BufferWriter::stdout(self.color_choice)) 69 | } 70 | 71 | /// Prints current table to `stderr` 72 | pub(crate) fn print_stderr(&self) -> Result<()> { 73 | self.print_writer(BufferWriter::stderr(self.color_choice)) 74 | } 75 | 76 | fn color_spec(&self) -> ColorSpec { 77 | self.style.color_spec() 78 | } 79 | 80 | fn required_dimension(&self) -> Dimension { 81 | let mut heights = Vec::with_capacity(self.rows.len() + 1); 82 | let mut widths = Vec::new(); 83 | 84 | let title_dimension = self.title.as_ref().map(RowStruct::required_dimension); 85 | 86 | if let Some(title_dimension) = title_dimension { 87 | widths = title_dimension.widths; 88 | heights.push(title_dimension.height); 89 | } 90 | 91 | for row in self.rows.iter() { 92 | let row_dimension = row.required_dimension(); 93 | 94 | heights.push(row_dimension.height); 95 | 96 | let new_widths = row_dimension.widths; 97 | 98 | if widths.is_empty() { 99 | widths = new_widths; 100 | } else { 101 | for (width, new_width) in widths.iter_mut().zip(new_widths.into_iter()) { 102 | *width = std::cmp::max(new_width, *width); 103 | } 104 | } 105 | } 106 | 107 | Dimension { widths, heights } 108 | } 109 | 110 | fn buffers(&self, writer: &BufferWriter) -> Result> { 111 | let table_dimension = self.required_dimension(); 112 | let row_dimensions: Vec = table_dimension.clone().into(); 113 | let mut row_dimensions = row_dimensions.into_iter(); 114 | let color_spec = self.color_spec(); 115 | 116 | let mut buffers = Buffers::new(writer); 117 | 118 | print_horizontal_line( 119 | &mut buffers, 120 | self.format.border.top.as_ref(), 121 | &table_dimension, 122 | &self.format, 123 | &color_spec, 124 | )?; 125 | 126 | if let Some(ref title) = self.title { 127 | let title_dimension = row_dimensions.next().unwrap(); 128 | let mut title_buffers = 129 | title.buffers(writer, title_dimension, &self.format, &color_spec)?; 130 | 131 | buffers.append(&mut title_buffers)?; 132 | 133 | if self.format.separator.title.is_some() { 134 | print_horizontal_line( 135 | &mut buffers, 136 | self.format.separator.title.as_ref(), 137 | &table_dimension, 138 | &self.format, 139 | &color_spec, 140 | )? 141 | } else { 142 | print_horizontal_line( 143 | &mut buffers, 144 | self.format.separator.row.as_ref(), 145 | &table_dimension, 146 | &self.format, 147 | &color_spec, 148 | )? 149 | } 150 | } 151 | 152 | let mut rows = self.rows.iter().zip(row_dimensions).peekable(); 153 | 154 | while let Some((row, row_dimension)) = rows.next() { 155 | let mut row_buffers = row.buffers(writer, row_dimension, &self.format, &color_spec)?; 156 | 157 | buffers.append(&mut row_buffers)?; 158 | 159 | match rows.peek() { 160 | Some(_) => print_horizontal_line( 161 | &mut buffers, 162 | self.format.separator.row.as_ref(), 163 | &table_dimension, 164 | &self.format, 165 | &color_spec, 166 | )?, 167 | None => print_horizontal_line( 168 | &mut buffers, 169 | self.format.border.bottom.as_ref(), 170 | &table_dimension, 171 | &self.format, 172 | &color_spec, 173 | )?, 174 | } 175 | } 176 | 177 | buffers.into_vec() 178 | } 179 | 180 | fn print_writer(&self, writer: BufferWriter) -> Result<()> { 181 | let buffers = self.buffers(&writer)?; 182 | 183 | for buffer in buffers.iter() { 184 | writer.print(buffer)?; 185 | } 186 | 187 | Ok(()) 188 | } 189 | } 190 | 191 | /// Trait to convert raw type into table 192 | pub trait Table { 193 | /// Converts raw type to a table 194 | fn table(self) -> TableStruct; 195 | } 196 | 197 | impl Table for T 198 | where 199 | T: IntoIterator, 200 | R: Row, 201 | { 202 | fn table(self) -> TableStruct { 203 | let rows = self.into_iter().map(Row::row).collect(); 204 | 205 | TableStruct { 206 | title: Default::default(), 207 | rows, 208 | format: Default::default(), 209 | style: Default::default(), 210 | color_choice: ColorChoice::Always, 211 | } 212 | } 213 | } 214 | 215 | impl Table for TableStruct { 216 | fn table(self) -> TableStruct { 217 | self 218 | } 219 | } 220 | 221 | impl Style for TableStruct { 222 | fn foreground_color(mut self, foreground_color: Option) -> Self { 223 | self.style = self.style.foreground_color(foreground_color); 224 | self 225 | } 226 | 227 | fn background_color(mut self, background_color: Option) -> Self { 228 | self.style = self.style.background_color(background_color); 229 | self 230 | } 231 | 232 | fn bold(mut self, bold: bool) -> Self { 233 | self.style = self.style.bold(bold); 234 | self 235 | } 236 | 237 | fn underline(mut self, underline: bool) -> Self { 238 | self.style = self.style.underline(underline); 239 | self 240 | } 241 | 242 | fn italic(mut self, italic: bool) -> Self { 243 | self.style = self.style.italic(italic); 244 | self 245 | } 246 | 247 | fn intense(mut self, intense: bool) -> Self { 248 | self.style = self.style.intense(intense); 249 | self 250 | } 251 | 252 | fn dimmed(mut self, dimmed: bool) -> Self { 253 | self.style = self.style.dimmed(dimmed); 254 | self 255 | } 256 | } 257 | 258 | /// A vertical line in a table (border or column separator) 259 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] 260 | pub struct VerticalLine { 261 | pub(crate) filler: char, 262 | } 263 | 264 | impl Default for VerticalLine { 265 | fn default() -> Self { 266 | Self { filler: '|' } 267 | } 268 | } 269 | 270 | impl VerticalLine { 271 | /// Creates a new instance of vertical line 272 | pub fn new(filler: char) -> Self { 273 | Self { filler } 274 | } 275 | } 276 | 277 | /// A horizontal line in a table (border or row separator) 278 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] 279 | pub struct HorizontalLine { 280 | pub(crate) left_end: char, 281 | pub(crate) right_end: char, 282 | pub(crate) junction: char, 283 | pub(crate) filler: char, 284 | } 285 | 286 | impl Default for HorizontalLine { 287 | fn default() -> Self { 288 | Self { 289 | left_end: '+', 290 | right_end: '+', 291 | junction: '+', 292 | filler: '-', 293 | } 294 | } 295 | } 296 | 297 | impl HorizontalLine { 298 | /// Creates a new instance of horizontal line 299 | pub fn new(left_end: char, right_end: char, junction: char, filler: char) -> Self { 300 | Self { 301 | left_end, 302 | right_end, 303 | junction, 304 | filler, 305 | } 306 | } 307 | } 308 | 309 | /// Borders of a table 310 | #[derive(Debug, Copy, Clone, PartialEq, Eq)] 311 | pub struct Border { 312 | pub(crate) top: Option, 313 | pub(crate) bottom: Option, 314 | pub(crate) left: Option, 315 | pub(crate) right: Option, 316 | } 317 | 318 | impl Border { 319 | /// Creates a new builder for border 320 | pub fn builder() -> BorderBuilder { 321 | BorderBuilder(Border { 322 | top: None, 323 | bottom: None, 324 | left: None, 325 | right: None, 326 | }) 327 | } 328 | } 329 | 330 | impl Default for Border { 331 | fn default() -> Self { 332 | Self { 333 | top: Some(Default::default()), 334 | bottom: Some(Default::default()), 335 | left: Some(Default::default()), 336 | right: Some(Default::default()), 337 | } 338 | } 339 | } 340 | 341 | /// Builder for border 342 | #[derive(Debug, Clone, PartialEq, Eq)] 343 | pub struct BorderBuilder(Border); 344 | 345 | impl BorderBuilder { 346 | /// Set top border of a table 347 | pub fn top(mut self, top: HorizontalLine) -> Self { 348 | self.0.top = Some(top); 349 | self 350 | } 351 | 352 | /// Set bottom border of a table 353 | pub fn bottom(mut self, bottom: HorizontalLine) -> Self { 354 | self.0.bottom = Some(bottom); 355 | self 356 | } 357 | 358 | /// Set left border of a table 359 | pub fn left(mut self, left: VerticalLine) -> Self { 360 | self.0.left = Some(left); 361 | self 362 | } 363 | 364 | /// Set right border of a table 365 | pub fn right(mut self, right: VerticalLine) -> Self { 366 | self.0.right = Some(right); 367 | self 368 | } 369 | 370 | /// Build border 371 | pub fn build(self) -> Border { 372 | self.0 373 | } 374 | } 375 | 376 | /// Inner (column/row) separators of a table 377 | #[derive(Debug, Copy, Clone, PartialEq, Eq)] 378 | pub struct Separator { 379 | pub(crate) column: Option, 380 | pub(crate) row: Option, 381 | pub(crate) title: Option, 382 | } 383 | 384 | impl Separator { 385 | /// Creates a new builder for separator 386 | pub fn builder() -> SeparatorBuilder { 387 | SeparatorBuilder(Separator { 388 | column: None, 389 | row: None, 390 | title: None, 391 | }) 392 | } 393 | } 394 | 395 | impl Default for Separator { 396 | fn default() -> Self { 397 | Self { 398 | column: Some(Default::default()), 399 | row: Some(Default::default()), 400 | title: None, 401 | } 402 | } 403 | } 404 | 405 | /// Builder for separator 406 | #[derive(Debug)] 407 | pub struct SeparatorBuilder(Separator); 408 | 409 | impl SeparatorBuilder { 410 | /// Set column separators of a table 411 | pub fn column(mut self, column: Option) -> Self { 412 | self.0.column = column; 413 | self 414 | } 415 | 416 | /// Set column separators of a table 417 | pub fn row(mut self, row: Option) -> Self { 418 | self.0.row = row; 419 | self 420 | } 421 | 422 | /// Set title of a table 423 | /// 424 | /// # None 425 | /// 426 | /// When title separator is not preset (i.e., it is `None`), row separator is displayed in place of title separator. 427 | pub fn title(mut self, title: Option) -> Self { 428 | self.0.title = title; 429 | self 430 | } 431 | 432 | /// Build separator 433 | pub fn build(self) -> Separator { 434 | self.0 435 | } 436 | } 437 | 438 | /// Struct for configuring a table's format 439 | #[derive(Debug, Default, Copy, Clone)] 440 | pub(crate) struct TableFormat { 441 | pub(crate) border: Border, 442 | pub(crate) separator: Separator, 443 | } 444 | 445 | /// Dimensions of a table 446 | #[derive(Debug, Clone, Eq, PartialEq, Default)] 447 | pub(crate) struct Dimension { 448 | /// Widths of each column of table 449 | pub(crate) widths: Vec, 450 | /// Height of each row of table 451 | pub(crate) heights: Vec, 452 | } 453 | 454 | #[cfg(test)] 455 | mod tests { 456 | use super::*; 457 | 458 | #[test] 459 | fn test_row_from_str_arr() { 460 | let table: TableStruct = vec![&["Hello", "World"], &["Scooby", "Doo"]].table(); 461 | assert_eq!(2, table.rows.len()); 462 | assert_eq!(2, table.rows[0].cells.len()); 463 | assert_eq!(2, table.rows[1].cells.len()); 464 | } 465 | } 466 | -------------------------------------------------------------------------------- /cli-table/src/title.rs: -------------------------------------------------------------------------------- 1 | use crate::{Row, RowStruct, Table, TableStruct}; 2 | 3 | /// Trait for getting title row of a struct 4 | #[cfg_attr( 5 | any(docsrs, feature = "doc"), 6 | doc(cfg(any(feature = "title", feature = "derive"))) 7 | )] 8 | pub trait Title { 9 | /// Returns title row of a struct 10 | fn title() -> RowStruct; 11 | } 12 | 13 | /// Trait for creating a table with titles at the top 14 | #[cfg_attr( 15 | any(docsrs, feature = "doc"), 16 | doc(cfg(any(feature = "title", feature = "derive"))) 17 | )] 18 | pub trait WithTitle { 19 | /// Creates a table with title at the top 20 | fn with_title(self) -> TableStruct; 21 | } 22 | 23 | impl<'a, T, R> WithTitle for T 24 | where 25 | T: IntoIterator, 26 | R: Title + 'static, 27 | &'a R: Row, 28 | { 29 | fn with_title(self) -> TableStruct { 30 | let table = self.table(); 31 | let title = R::title(); 32 | table.title(title) 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /cli-table/src/utils.rs: -------------------------------------------------------------------------------- 1 | use std::io::{Result, Write}; 2 | 3 | use termcolor::{ColorSpec, WriteColor}; 4 | 5 | use crate::{ 6 | buffers::Buffers, 7 | table::{Dimension as TableDimension, HorizontalLine, TableFormat, VerticalLine}, 8 | }; 9 | 10 | const ESC: char = '\x1b'; 11 | 12 | /// NOTE: `display_width()` is ported from https://docs.rs/ansi-width/0.1.0/src/ansi_width/lib.rs.html#9-55 13 | /// 14 | /// Return the display width of a unicode string. 15 | /// This functions takes ANSI-escaped color codes into account. 16 | pub(crate) fn display_width(text: &str) -> usize { 17 | let mut width = 0; 18 | let mut chars = text.chars(); 19 | 20 | // This lint is a false positive, because we use the iterator later, leading to 21 | // ownership issues if we follow the lint. 22 | #[allow(clippy::while_let_on_iterator)] 23 | while let Some(c) = chars.next() { 24 | // ESC starts escape sequences, so we need to take characters until the 25 | // end of the escape sequence. 26 | if c == ESC { 27 | let Some(c) = chars.next() else { 28 | break; 29 | }; 30 | match c { 31 | // String terminator character: ends other sequences 32 | // We probably won't encounter this but it's here for completeness. 33 | // Or for if we get passed invalid codes. 34 | '\\' => { 35 | // ignore 36 | } 37 | // Control Sequence Introducer: continue until `\x40-\x7C` 38 | '[' => while !matches!(chars.next(), Some('\x40'..='\x7C') | None) {}, 39 | // Operating System Command: continue until ST 40 | ']' => { 41 | let mut last = c; 42 | while let Some(new) = chars.next() { 43 | if new == '\x07' || (new == '\\' && last == ESC) { 44 | break; 45 | } 46 | last = new; 47 | } 48 | } 49 | // We don't know what character it is, best bet is to fall back to unicode width 50 | // The ESC is assumed to have 0 width in this case. 51 | _ => { 52 | width += unicode_width::UnicodeWidthChar::width(c).unwrap_or(0); 53 | } 54 | } 55 | } else { 56 | // If it's a normal character outside an escape sequence, use the 57 | // unicode width. 58 | width += unicode_width::UnicodeWidthChar::width(c).unwrap_or(0); 59 | } 60 | } 61 | width 62 | } 63 | 64 | pub fn transpose(v: Vec>) -> Vec> { 65 | if v.is_empty() || v[0].is_empty() { 66 | return v; 67 | } 68 | 69 | let columns = v.len(); 70 | let height = v[0].len(); 71 | 72 | let mut optional_v: Vec>> = v 73 | .into_iter() 74 | .map(|cell_v| cell_v.into_iter().map(Some).collect()) 75 | .collect(); 76 | 77 | let mut transpose = Vec::with_capacity(height); 78 | 79 | for i in 0..height { 80 | let mut row_buffer = Vec::with_capacity(columns); 81 | 82 | for inner_v in optional_v.iter_mut().take(columns) { 83 | row_buffer.push(std::mem::take(&mut inner_v[i]).unwrap()); 84 | } 85 | 86 | transpose.push(row_buffer); 87 | } 88 | 89 | transpose 90 | } 91 | 92 | pub(crate) fn print_horizontal_line( 93 | buffers: &mut Buffers<'_>, 94 | line: Option<&HorizontalLine>, 95 | table_dimension: &TableDimension, 96 | table_format: &TableFormat, 97 | color_spec: &ColorSpec, 98 | ) -> Result<()> { 99 | if let Some(line) = line { 100 | if table_format.border.left.is_some() { 101 | print_char(buffers, line.left_end, color_spec)?; 102 | } 103 | 104 | let mut widths = table_dimension.widths.iter().peekable(); 105 | 106 | while let Some(width) = widths.next() { 107 | let s = std::iter::repeat_n(line.filler, width + 2).collect::(); 108 | print_str(buffers, &s, color_spec)?; 109 | 110 | match widths.peek() { 111 | Some(_) => { 112 | if table_format.separator.column.is_some() { 113 | print_char(buffers, line.junction, color_spec)? 114 | } 115 | } 116 | None => { 117 | if table_format.border.right.is_some() { 118 | print_char(buffers, line.right_end, color_spec)?; 119 | } else { 120 | print_str(buffers, "", color_spec)?; 121 | } 122 | } 123 | } 124 | } 125 | 126 | println(buffers)?; 127 | } 128 | 129 | Ok(()) 130 | } 131 | 132 | pub(crate) fn print_vertical_line( 133 | buffers: &mut Buffers<'_>, 134 | line: Option<&VerticalLine>, 135 | color_spec: &ColorSpec, 136 | ) -> Result<()> { 137 | if let Some(line) = line { 138 | print_char(buffers, line.filler, color_spec)?; 139 | } 140 | Ok(()) 141 | } 142 | 143 | pub(crate) fn print_str(buffers: &mut Buffers<'_>, s: &str, color_spec: &ColorSpec) -> Result<()> { 144 | buffers.set_color(color_spec)?; 145 | write!(buffers, "{}", s)?; 146 | buffers.reset() 147 | } 148 | 149 | pub(crate) fn print_char(buffers: &mut Buffers<'_>, c: char, color_spec: &ColorSpec) -> Result<()> { 150 | buffers.set_color(color_spec)?; 151 | write!(buffers, "{}", c)?; 152 | buffers.reset() 153 | } 154 | 155 | pub(crate) fn println(buffers: &mut Buffers<'_>) -> Result<()> { 156 | writeln!(buffers) 157 | } 158 | -------------------------------------------------------------------------------- /test-suite/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "test-suite" 3 | version = "0.1.0" 4 | authors = ["Devashish Dixit "] 5 | edition = "2024" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | cli-table = { path = "../cli-table" } 11 | 12 | [dev-dependencies] 13 | rustversion = "1.0.20" 14 | trybuild = { version = "1.0.104", features = ["diff"] } 15 | -------------------------------------------------------------------------------- /test-suite/tests/compiletest.rs: -------------------------------------------------------------------------------- 1 | #[rustversion::attr(not(nightly), ignore)] 2 | #[test] 3 | fn ui() { 4 | let t = trybuild::TestCases::new(); 5 | t.compile_fail("tests/ui/*.rs"); 6 | } 7 | -------------------------------------------------------------------------------- /test-suite/tests/ui/no-enum.rs: -------------------------------------------------------------------------------- 1 | //! `Table` derive macro is not allowed on enums 2 | use cli_table::Table; 3 | 4 | #[derive(Table)] 5 | enum Test { 6 | Variant1, 7 | Variant2, 8 | } 9 | 10 | fn main () {} 11 | -------------------------------------------------------------------------------- /test-suite/tests/ui/no-enum.stderr: -------------------------------------------------------------------------------- 1 | error: `cli_table` derive macros can only be used on structs 2 | --> $DIR/no-enum.rs:5:1 3 | | 4 | 5 | / enum Test { 5 | 6 | | Variant1, 6 | 7 | | Variant2, 7 | 8 | | } 8 | | |_^ 9 | -------------------------------------------------------------------------------- /test-suite/tests/ui/non-display-member.rs: -------------------------------------------------------------------------------- 1 | //! All the members of a struct should implement `Display` (other option is to use `display_fn`) 2 | use cli_table::Table; 3 | 4 | #[derive(Table)] 5 | struct Test { 6 | #[table(title = "a")] 7 | a: Vec, 8 | } 9 | 10 | fn main() {} 11 | -------------------------------------------------------------------------------- /test-suite/tests/ui/non-display-member.stderr: -------------------------------------------------------------------------------- 1 | error[E0277]: the trait bound `&Vec: cli_table::Cell` is not satisfied 2 | --> tests/ui/non-display-member.rs:6:5 3 | | 4 | 4 | #[derive(Table)] 5 | | ----- required by a bound introduced by this call 6 | 5 | struct Test { 7 | 6 | / #[table(title = "a")] 8 | 7 | | a: Vec, 9 | | |______________^ the trait `std::fmt::Display` is not implemented for `Vec` 10 | | 11 | = help: the trait `cli_table::Cell` is implemented for `CellStruct` 12 | = note: required for `&Vec` to implement `std::fmt::Display` 13 | = note: required for `&Vec` to implement `cli_table::Cell` 14 | -------------------------------------------------------------------------------- /test-suite/tests/ui/title-string-value.rs: -------------------------------------------------------------------------------- 1 | //! `title` only accepts `&str` values 2 | use cli_table::Table; 3 | 4 | #[derive(Table)] 5 | struct Test { 6 | #[table(title = 1)] 7 | a: u8, 8 | } 9 | 10 | fn main() {} 11 | -------------------------------------------------------------------------------- /test-suite/tests/ui/title-string-value.stderr: -------------------------------------------------------------------------------- 1 | error: Invalid value for #[table(title = "field_name")] 2 | --> $DIR/title-string-value.rs:6:21 3 | | 4 | 6 | #[table(title = 1)] 5 | | ^ 6 | --------------------------------------------------------------------------------